zm2000 5de57baa2c fix(订单复核): 软键盘弹出又隐藏/遮挡修复 + 称重语音播报 + 语音串行队列
- 键盘: 修复称重/包材弹窗软键盘「弹出又自动隐藏」——登录页遗留窗口级
  ALWAYS_HIDDEN(3),订单页新增 restoreSoftInputMode()(setSoftInputMode 48)
  与 showSoftKeyboard()(showSoftInput SHOW_FORCED) 恢复并强制唤出键盘
- 键盘: 称重弹窗打开后延迟聚焦(weighDialogVisible watcher);包材弹窗焦点
  改为复用「复核设置→包材软键盘」开关,默认不自动聚焦
- 键盘: 称重/包材弹窗固定屏幕上部(weigh-mask--keyboard),避免键盘遮挡输入框
  与底部按钮;回退 adjust-position/cursor-spacing 动态方案(旧 WebView 会失焦)
- 语音: 称重操作新增播报「称重成功:X 克」「称重失败」
- 语音: core/voice.js 改 FIFO 串行队列,连续播报按触发顺序一条播完再下一条,
  消除交叉打断
- 样式: 推荐包材标签与值无间隔修复(老 WebView 不支持 flex gap,改 margin-left)
- 登录页: reLaunch 切回时延迟重注册扫码接收,避免 plus.key 监听被误删
- 调试: electron/main.js 渲染进程 console 转发到主进程终端
2026-10-20 18:16:19 +08:00

365 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { app, BrowserWindow, session, ipcMain, shell, Tray, Menu, nativeImage } = require('electron')
const path = require('path')
const fs = require('fs')
const os = require('os')
const https = require('https')
const http = require('http')
const { startHikvisionLiveServer, stopHikvisionLiveServer } = require('./hikvision-live')
const devServerUrl = process.env.ELECTRON_RENDERER_URL
const rendererEntry = path.join(__dirname, '..', 'dist', 'build', 'h5', 'index.html')
let tray = null
let isQuitting = false
if (devServerUrl) {
app.commandLine.appendSwitch('disable-http-cache')
}
// ---------- 本地静态服务:history 模式路由需要 http 协议(file:// 下 pushState 被禁用) ----------
const STATIC_MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.mp3': 'audio/mpeg',
'.map': 'application/json; charset=utf-8',
}
let staticServer = null
let staticServerPort = 0
function serveFile(filePath, res) {
const ext = path.extname(filePath).toLowerCase()
res.writeHead(200, { 'Content-Type': STATIC_MIME[ext] || 'application/octet-stream' })
fs.createReadStream(filePath).pipe(res)
}
function startStaticServer() {
if (staticServer) {
return Promise.resolve(staticServerPort)
}
const rootDir = path.dirname(rendererEntry)
const server = http.createServer((req, res) => {
let urlPath = '/'
try {
urlPath = decodeURIComponent(String(req.url || '/').split('?')[0])
} catch (e) {
urlPath = '/'
}
if (!urlPath || urlPath === '/') {
serveFile(path.join(rootDir, 'index.html'), res)
return
}
// 防目录穿越
const filePath = path.normalize(path.join(rootDir, urlPath))
if (!filePath.startsWith(rootDir)) {
res.writeHead(403)
res.end('Forbidden')
return
}
fs.stat(filePath, (err, stat) => {
if (!err && stat.isDirectory()) {
serveFile(path.join(filePath, 'index.html'), res)
return
}
if (err || !stat.isFile()) {
// SPA 回退:history 路由统一返回 index.html
serveFile(path.join(rootDir, 'index.html'), res)
return
}
serveFile(filePath, res)
})
})
return new Promise((resolve, reject) => {
server.on('error', reject)
server.listen(0, '127.0.0.1', () => {
staticServer = server
staticServerPort = server.address().port
resolve(staticServerPort)
})
})
}
async function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
// 全站按 1280 设计宽做 rem 缩放(<1280 等比缩、下限 640px 对应 0.5 倍),
// 窗口再窄就会出现横向溢出(页面 min-width 约 614px),故限制最小尺寸
minWidth: 1024,
minHeight: 640,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
})
if (devServerUrl) {
win.webContents.session.clearCache().catch(() => {})
win.loadURL(devServerUrl)
win.webContents.openDevTools({ mode: 'detach' })
} else {
const port = await startStaticServer()
win.loadURL(`http://127.0.0.1:${port}/`)
}
// 渲染进程 console 转发到主进程终端:开发时无需开 DevTools 也能看 [order-scan] 等日志
win.webContents.on('console-message', (event, level, message) => {
const lvl = (event && event.level) || level || 'info'
const msg = (event && event.message) || message || ''
console.log(`[renderer:${lvl}] ${msg}`)
})
// 不显示窗口标题栏下的菜单
win.removeMenu()
// 点关闭按钮时不退出,隐藏到托盘;托盘菜单退出时才真正退出
win.on('close', (event) => {
if (!isQuitting) {
event.preventDefault()
win.hide()
}
})
// 外部链接(更新下载地址等)交给系统浏览器打开
win.webContents.setWindowOpenHandler(({ url }) => {
if (url && url.startsWith('http')) {
require('electron').shell.openExternal(url)
}
return { action: 'deny' }
})
return win
}
function getTrayIconPath() {
const candidates = [
path.join(__dirname, 'icon.png'),
path.join(__dirname, '..', 'src', 'static', 'images', '1.png'),
path.join(__dirname, '..', 'dist', 'build', 'h5', 'static', 'images', '1.png'),
]
return candidates.find((p) => fs.existsSync(p)) || ''
}
function createTray(mainWindow) {
if (tray) {
return tray
}
const iconPath = getTrayIconPath()
let image = nativeImage.createEmpty()
if (iconPath) {
const loaded = nativeImage.createFromPath(iconPath)
if (!loaded.isEmpty()) {
image = loaded.resize({ width: 16, height: 16 })
}
}
tray = new Tray(image)
tray.setToolTip('WMS工作台')
const showWindow = () => {
if (!mainWindow || mainWindow.isDestroyed()) {
return
}
mainWindow.show()
if (mainWindow.isMinimized()) {
mainWindow.restore()
}
mainWindow.focus()
}
tray.on('click', showWindow)
tray.setContextMenu(
Menu.buildFromTemplate([
{ label: '显示主界面', click: showWindow },
{ type: 'separator' },
{
label: '退出',
click: () => {
isQuitting = true
app.quit()
},
},
])
)
return tray
}
function setupCorsHeaders() {
// 允许渲染进程跨域读取发布服务器上的 latest.json 等文件
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Access-Control-Allow-Origin': ['*'],
},
})
})
}
// ---------- 内置更新下载(主进程,支持重定向/重试与进度回传) ----------
function downloadUpdateFile(url, dest, onProgress) {
return new Promise((resolve, reject) => {
const maxAttempts = 3
let attempt = 0
const tryOnce = () => {
attempt++
const start = (target, redirects) => {
if (redirects > 5) {
reject(new Error('重定向次数过多'))
return
}
const request = https.get(
target,
{ headers: { 'User-Agent': 'wms-worker-station-updater' } },
(res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume()
start(new URL(res.headers.location, target).toString(), redirects + 1)
return
}
if (res.statusCode !== 200) {
res.resume()
reject(new Error(`HTTP ${res.statusCode}`))
return
}
const total = Number(res.headers['content-length'] || 0)
let received = 0
const file = fs.createWriteStream(dest)
res.on('data', (chunk) => {
received += chunk.length
onProgress(received, total)
})
res.pipe(file)
file.on('finish', () => {
file.close(() => resolve(dest))
})
file.on('error', (error) => reject(error))
}
)
request.on('error', (error) => {
if (attempt < maxAttempts) {
console.warn(`[updater] 下载失败,重试 ${attempt}/${maxAttempts}: ${error.message}`)
tryOnce()
} else {
reject(error)
}
})
}
start(url, 0)
}
tryOnce()
})
}
ipcMain.handle('download-update', async (event, url) => {
const tmpPath = path.join(os.tmpdir(), `wms-worker-station-${Date.now()}-setup.exe`)
await downloadUpdateFile(url, tmpPath, (received, total) => {
if (!event.sender.isDestroyed()) {
event.sender.send('download-progress', { received, total })
}
})
return tmpPath
})
ipcMain.handle('open-installer', async (_event, filePath) => {
const result = await shell.openPath(filePath)
return result
})
function setupMediaPermissions() {
const ses = session.defaultSession
if (!ses) {
return
}
const mediaPermissions = new Set(['media', 'videoCapture', 'audioCapture', 'camera', 'microphone'])
ses.setPermissionCheckHandler((webContents, permission) => {
if (mediaPermissions.has(permission)) {
return true
}
return false
})
ses.setPermissionRequestHandler((webContents, permission, callback) => {
callback(mediaPermissions.has(permission))
})
if (typeof ses.setDevicePermissionHandler === 'function') {
ses.setDevicePermissionHandler((details) => {
return details.deviceType === 'videoCapture' || details.deviceType === 'audioCapture'
})
}
}
// ---------- 单实例锁:防止同时打开两个应用实例 ----------
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
app.quit()
} else {
// 用户再次启动应用时,唤起已有实例的窗口
app.on('second-instance', () => {
const win = BrowserWindow.getAllWindows()[0]
if (win) {
if (win.isMinimized()) {
win.restore()
}
win.show()
win.focus()
}
})
app.whenReady().then(async () => {
setupMediaPermissions()
setupCorsHeaders()
const win = await createWindow()
createTray(win)
// 内置海康取流服务(127.0.0.1:17320, HTTP 快照模式):端口空闲时自起,与 printServer(17311) 隔离
startHikvisionLiveServer()
.then((r) => console.log('[main] 海康取流服务状态:', JSON.stringify(r)))
.catch((e) => console.error('[main] 海康取流服务启动失败:', e))
app.on('activate', async () => {
const allWindows = BrowserWindow.getAllWindows()
if (allWindows.length === 0) {
try {
await createWindow()
} catch (error) {
console.error('[static-server] 启动失败:', error)
}
} else {
allWindows[0].show()
}
})
})
app.on('before-quit', () => {
isQuitting = true
stopHikvisionLiveServer()
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
}