import { ipcMain } from 'electron'; import { exec } from 'child_process'; import { promisify } from 'util'; import { getCachedAdbPath } from '../config.js'; const execAsync = promisify(exec); /** * 发送系统按键事件到设备 * @param {string} ipPort - 设备 ID/IP:Port * @param {string} keyCode - 按键代码(如 "4" 表示返回键,"3" 表示Home键) * @returns {Promise<{success: boolean, error?: string}>} */ export async function sendSystemKey(ipPort, keyCode) { if (!ipPort) { return { success: false, error: '缺少设备 ID' }; } if (typeof keyCode !== 'string') { return { success: false, error: '按键代码必须是字符串' }; } try { const adbPath = getCachedAdbPath(); const command = `${adbPath} -s ${ipPort} shell input keyevent ${keyCode}`; await execAsync(command, { timeout: 5000, maxBuffer: 1024 * 1024 }); return { success: true }; } catch (error) { return { success: false, error: error.message }; } } /** * 返回键 * @param {string} ipPort - 设备 ID/IP:Port * @returns {Promise<{success: boolean, error?: string}>} */ export async function sendBackKey(ipPort) { return sendSystemKey(ipPort, '4'); } /** * Home键 * @param {string} ipPort - 设备 ID/IP:Port * @returns {Promise<{success: boolean, error?: string}>} */ export async function sendHomeKey(ipPort) { return sendSystemKey(ipPort, '3'); } /** * 最近任务键 * @param {string} ipPort - 设备 ID/IP:Port * @returns {Promise<{success: boolean, error?: string}>} */ export async function sendRecentAppsKey(ipPort) { return sendSystemKey(ipPort, '187'); } /** * 注册 IPC 处理器 */ export function registerIpcHandlers() { // IPC 处理程序:发送系统按键 ipcMain.handle('send-system-key', async (event, ipPort, keyCode) => { return await sendSystemKey(ipPort, keyCode); }); // IPC 处理程序:返回键 ipcMain.handle('send-back-key', async (event, ipPort) => { return await sendBackKey(ipPort); }); // IPC 处理程序:Home键 ipcMain.handle('send-home-key', async (event, ipPort) => { return await sendHomeKey(ipPort); }); // IPC 处理程序:最近任务键 ipcMain.handle('send-recent-apps-key', async (event, ipPort) => { return await sendRecentAppsKey(ipPort); }); }