├── .gitignore ├── Chapter 1 ├── 10-ipc │ ├── index.html │ ├── index2.html │ ├── main.js │ ├── package-lock.json │ ├── package.json │ ├── renderer.js │ └── renderer2.js ├── 12-lazy-load │ ├── index.html │ ├── index.js │ └── package.json ├── 2-content-roadmap.png ├── 3-hello-electron │ ├── index.html │ ├── main.js │ └── package.json ├── 6-electron-setup.md ├── 8-pomodoro-demo │ ├── .tmp │ │ ├── main.js │ │ └── renderer.js │ ├── index.html │ ├── main.js │ ├── package.json │ ├── readme.md │ └── renderer.js └── 8-pomodoro-homework │ ├── index.html │ ├── main.js │ ├── package.json │ ├── readme.md │ └── renderer.js ├── Chapter 2 ├── 10-signal │ ├── index.js │ ├── package-lock.json │ └── package.json ├── 12-remote-control │ ├── app │ │ ├── main │ │ │ ├── index.js │ │ │ ├── ipc.js │ │ │ ├── robot.js │ │ │ ├── signal.js │ │ │ ├── trayAndMenu │ │ │ │ ├── darwin.js │ │ │ │ ├── icon_darwin.png │ │ │ │ ├── icon_darwin@2x.png │ │ │ │ ├── icon_win32.png │ │ │ │ ├── icon_win32@2x.png │ │ │ │ ├── index.js │ │ │ │ └── win32.js │ │ │ └── windows │ │ │ │ ├── about.js │ │ │ │ ├── control.js │ │ │ │ ├── icon.png │ │ │ │ └── main.js │ │ └── renderer │ │ │ ├── pages │ │ │ └── control │ │ │ │ ├── app.js │ │ │ │ ├── index.html │ │ │ │ ├── index.js │ │ │ │ └── peer-control.js │ │ │ └── src │ │ │ └── main │ │ │ ├── .gitignore │ │ │ ├── README.md │ │ │ ├── config-overrides.js │ │ │ ├── package.json │ │ │ ├── public │ │ │ ├── favicon.ico │ │ │ ├── index.html │ │ │ ├── logo192.png │ │ │ ├── logo512.png │ │ │ ├── manifest.json │ │ │ └── robots.txt │ │ │ └── src │ │ │ ├── App.css │ │ │ ├── App.js │ │ │ ├── App.test.js │ │ │ ├── index.css │ │ │ ├── index.js │ │ │ ├── logo.svg │ │ │ ├── peer-puppet.js │ │ │ ├── serviceWorker.js │ │ │ └── setupTests.js │ └── package.json ├── 3-6-remote-control-local-mock │ ├── READMD.md │ ├── app │ │ ├── main │ │ │ ├── index.js │ │ │ ├── ipc.js │ │ │ ├── robot.js │ │ │ └── windows │ │ │ │ ├── control.js │ │ │ │ └── main.js │ │ └── renderer │ │ │ ├── pages │ │ │ └── control │ │ │ │ ├── app.js │ │ │ │ ├── index.html │ │ │ │ ├── index.js │ │ │ │ ├── peer-control.js │ │ │ │ └── robot.js │ │ │ └── src │ │ │ └── main │ │ │ ├── .gitignore │ │ │ ├── README.md │ │ │ ├── config-overrides.js │ │ │ ├── package-lock.json │ │ │ ├── package.json │ │ │ ├── public │ │ │ ├── favicon.ico │ │ │ ├── index.html │ │ │ ├── logo192.png │ │ │ ├── logo512.png │ │ │ ├── manifest.json │ │ │ └── robots.txt │ │ │ └── src │ │ │ ├── App.css │ │ │ ├── App.js │ │ │ ├── App.test.js │ │ │ ├── index.css │ │ │ ├── index.js │ │ │ ├── logo.svg │ │ │ ├── serviceWorker.js │ │ │ └── setupTests.js │ ├── package-lock.json │ └── package.json ├── 4-robot-heart │ ├── READMD.md │ ├── index.html │ ├── main.js │ ├── package-lock.json │ ├── package.json │ └── renderer.js └── 7-11-remote-control │ ├── app │ ├── main │ │ ├── index.js │ │ ├── ipc.js │ │ ├── robot.js │ │ ├── signal.js │ │ └── windows │ │ │ ├── control.js │ │ │ └── main.js │ └── renderer │ │ ├── pages │ │ └── control │ │ │ ├── app.js │ │ │ ├── index.html │ │ │ ├── index.js │ │ │ ├── peer-control.js │ │ │ └── robot.js │ │ └── src │ │ └── main │ │ ├── .gitignore │ │ ├── README.md │ │ ├── config-overrides.js │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── public │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── logo192.png │ │ ├── logo512.png │ │ ├── manifest.json │ │ └── robots.txt │ │ └── src │ │ ├── App.css │ │ ├── App.js │ │ ├── App.test.js │ │ ├── index.css │ │ ├── index.js │ │ ├── logo.svg │ │ ├── peer-puppet.js │ │ ├── serviceWorker.js │ │ └── setupTests.js │ └── package.json ├── Chapter 3 ├── remote-control │ ├── .gitignore │ ├── app │ │ ├── main │ │ │ ├── crash-reporter.js │ │ │ ├── index.js │ │ │ ├── ipc.js │ │ │ ├── robot.js │ │ │ ├── signal.js │ │ │ ├── trayAndMenu │ │ │ │ ├── darwin.js │ │ │ │ ├── icon_darwin.png │ │ │ │ ├── icon_darwin@2x.png │ │ │ │ ├── icon_win32.png │ │ │ │ ├── icon_win32@2x.png │ │ │ │ ├── index.js │ │ │ │ └── win32.js │ │ │ ├── updater.js │ │ │ └── windows │ │ │ │ ├── about.js │ │ │ │ ├── control.js │ │ │ │ ├── icon.png │ │ │ │ └── main.js │ │ └── renderer │ │ │ ├── pages │ │ │ └── control │ │ │ │ ├── app.js │ │ │ │ ├── index.html │ │ │ │ ├── index.js │ │ │ │ ├── peer-control.js │ │ │ │ └── robot.js │ │ │ └── src │ │ │ └── main │ │ │ ├── .gitignore │ │ │ ├── README.md │ │ │ ├── build.js │ │ │ ├── config-overrides.js │ │ │ ├── package.json │ │ │ ├── public │ │ │ ├── favicon.ico │ │ │ ├── index.html │ │ │ ├── logo192.png │ │ │ ├── logo512.png │ │ │ ├── manifest.json │ │ │ └── robots.txt │ │ │ └── src │ │ │ ├── App.css │ │ │ ├── App.js │ │ │ ├── App.test.js │ │ │ ├── index.css │ │ │ ├── index.js │ │ │ ├── logo.svg │ │ │ ├── peer-puppet.js │ │ │ ├── serviceWorker.js │ │ │ └── setupTests.js │ ├── package.json │ └── resources │ │ ├── background.png │ │ ├── background@2x.png │ │ ├── icon.icns │ │ ├── icon.ico │ │ └── icon.png └── updater-server │ ├── index.js │ ├── package.json │ └── public │ ├── Mercurius-1.0.1-full.nupkg │ ├── Mercurius-1.0.1-mac.zip │ └── RELEASES ├── PDF ├── Electron 基础篇.pdf ├── Electron 实战篇 .pdf └── Electron 工程篇.pdf ├── README.md ├── ROADMAP.md └── img ├── icon.ico ├── intro.jpeg └── qrcode.png /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | **/node_modules 3 | **/package-lock.json 4 | **/app/renderer/pages/main/ 5 | -------------------------------------------------------------------------------- /Chapter 1/10-ipc/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Chapter 1/10-ipc/index2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Chapter 1/10-ipc/main.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow, Notification, ipcMain} = require('electron') 2 | 3 | let win 4 | let win2 5 | app.on('ready', () => { 6 | win = new BrowserWindow({ 7 | width: 300, 8 | height: 300, 9 | webPreferences: { 10 | nodeIntegration: true 11 | } 12 | }) 13 | win.loadFile('./index.html') 14 | 15 | win2 = new BrowserWindow({ 16 | width: 300, 17 | height: 300, 18 | webPreferences: { 19 | nodeIntegration: true 20 | } 21 | }) 22 | win2.loadFile('./index2.html') 23 | global.sharedObject = { 24 | win2WebContentsId: win2.webContents.id 25 | } 26 | setTimeout(handleIPC, 500) 27 | }) 28 | 29 | function handleIPC() { 30 | // ipcMain.on('do-some-work', function (e, a, b) { 31 | // // do some work 32 | // console.log('do-some-work', a,b) 33 | // }) 34 | 35 | // win.webContents.send('do-some-render-work') 36 | } 37 | -------------------------------------------------------------------------------- /Chapter 1/10-ipc/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ipc", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "electron": "^7.1.7" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter 1/10-ipc/renderer.js: -------------------------------------------------------------------------------- 1 | const {ipcRenderer, remote} = require('electron') 2 | 3 | // ipcRenderer.send('do-some-work', 1,2) 4 | 5 | // ipcRenderer.on('do-some-render-work', () => { 6 | // alert('do some work') 7 | // }) 8 | let sharedObject = remote.getGlobal('sharedObject') 9 | let win2WebContentsId = sharedObject.win2WebContentsId 10 | 11 | ipcRenderer.sendTo(win2WebContentsId, 'do-some-work', 1) 12 | -------------------------------------------------------------------------------- /Chapter 1/10-ipc/renderer2.js: -------------------------------------------------------------------------------- 1 | const {ipcRenderer} = require('electron') 2 | ipcRenderer.on('do-some-work', (e, a) => { 3 | alert('renderer2 handle some work' + a) 4 | }) 5 | -------------------------------------------------------------------------------- /Chapter 1/12-lazy-load/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |
5 | 35 |
36 |
37 |

抱歉,没有找到符合条件的结果ï 38 | 39 |

40 | 41 | 42 | -------------------------------------------------------------------------------- /Chapter 1/12-lazy-load/index.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow} = require('electron') 2 | 3 | let mainWindow 4 | app.whenReady().then(() => { 5 | mainWindow = new BrowserWindow({ 6 | width: 1000, 7 | heigth: 680, 8 | }) 9 | mainWindow.loadURL('https://mathiasbynens.be/demo/img-loading-lazy') 10 | }) 11 | -------------------------------------------------------------------------------- /Chapter 1/12-lazy-load/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lazy-load", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "electron ." 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "devDependencies": { 14 | "electron": "^7.1.7" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Chapter 1/2-content-roadmap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 1/2-content-roadmap.png -------------------------------------------------------------------------------- /Chapter 1/3-hello-electron/index.html: -------------------------------------------------------------------------------- 1 | 2 | hello 3 | 4 | -------------------------------------------------------------------------------- /Chapter 1/3-hello-electron/main.js: -------------------------------------------------------------------------------- 1 | const { app, BrowserWindow } = require('electron') 2 | let win 3 | app.on('ready', () => { 4 | win = new BrowserWindow() 5 | win.loadFile('index.html') 6 | }) 7 | -------------------------------------------------------------------------------- /Chapter 1/3-hello-electron/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "3-hello-electron", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "main.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "electron ." 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "electron": "^7.1.7" 15 | 16 | } 17 | 18 | } 19 | 20 | -------------------------------------------------------------------------------- /Chapter 1/6-electron-setup.md: -------------------------------------------------------------------------------- 1 | # nvm安装 2 | ``` 3 | Mac/Linux: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash 4 | Windows: https://github.com/coreybutler/nvm-windows/releasesa 5 | 验证nvm: nvm --versiona 6 | ``` 7 | 8 | 9 | # Node.js/NPM 安装 10 | ``` 11 | 安装 Node.js: nvm install 12.14.0 12 | 切换 Node.js 版本:nvm use 12.14.0 13 | 验证 npm -v 14 | 验证 node -v 15 | ``` 16 | 17 | # node安装加速机器 18 | ``` 19 | // mac 在 .bashrc 或者 .zshrc 加入 20 | export NVM_NODEJS_ORG_MIRROR=http://npm.taobao.org/mirrors/node 21 | 22 | // Windows 在 %userprofile%\AppData\Roaming\nvm\setting.txt 加入 23 | node_mirror: https://npm.taobao.org/mirrors/node/ npm_mirror: https://npm.taobao.org/mirrors/npm/ 24 | ``` 25 | 26 | # Electron 安装 27 | ``` 28 | npm install electron --save-dev 29 | npm install --arch=ia32 --platform=win32 electron 30 | 31 | // 验证安装成功: 32 | npx electron -v (npm > 5.2) 33 | ./node_modules/.bin/electron -v 34 | ``` 35 | 36 | # Electron加速技巧 37 | ``` 38 | # 设置ELECTRON_MIRROR 39 | ELECTRON_MIRROR=https://cdn.npm.taobao.org/dist/electron/ npm install electron --save- dev 40 | ``` 41 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-demo/.tmp/main.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow, ipcMain, Notification} = require('electron') 2 | 3 | let win 4 | app.on('ready', () => { 5 | win = new BrowserWindow({ 6 | width: 300, 7 | height: 300, 8 | webPreferences: { 9 | nodeIntegration: true 10 | } 11 | }) 12 | win.loadFile('./index.html') 13 | handleIPC() 14 | }) 15 | 16 | function handleIPC() { 17 | ipcMain.handle('notification', async function () { 18 | let res = await new Promise((resolve, reject) => { 19 | let notification = new Notification({ 20 | actions: [{text: '开始休息', type: 'button'}], 21 | title: '工作结束', 22 | body: '是否要休息', 23 | closeButtonText: '继续工作' 24 | }) 25 | notification.show() 26 | notification.on('action',() => { 27 | resolve('rest') 28 | }) 29 | notification.on('close', () => { 30 | resolve('work') 31 | }) 32 | }) 33 | return res 34 | }) 35 | } 36 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-demo/.tmp/renderer.js: -------------------------------------------------------------------------------- 1 | const {ipcRenderer} = require('electron') 2 | const Timer = require('timer.js') 3 | const timerContainer = document.getElementById('timer-container') 4 | const workTimer = new Timer({ 5 | tick: 1, 6 | ontick: updateTime, 7 | onend: () => { 8 | notification() 9 | } 10 | }) 11 | function startWork() { 12 | workTimer.start(10) 13 | } 14 | 15 | async function notification() { 16 | let res = await ipcRenderer.invoke('notification') 17 | if(res === 'rest') { 18 | setTimeout(() => { 19 | let notificaiton = new Notification('休息结束!开始工作吧') 20 | startWork() 21 | }, 1000) 22 | 23 | } else if(res === 'work') { 24 | startWork() 25 | } 26 | } 27 | 28 | function updateTime(ms) { 29 | let s = (ms / 1000).toFixed(0) 30 | let ss = (s % 60).toFixed(0) 31 | let mm = (s / 60).toFixed(0) 32 | console.log(ms) 33 | timerContainer.innerText = `${mm.toString().padStart(2, '0')}:${ss.toString().padStart(2, '0')}` 34 | } 35 | 36 | 37 | startWork() 38 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-demo/main.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow, Notification, ipcMain} = require('electron') 2 | 3 | let win 4 | app.on('ready', () => { 5 | win = new BrowserWindow({ 6 | width: 300, 7 | height: 300, 8 | webPreferences: { 9 | nodeIntegration: true 10 | } 11 | }) 12 | win.loadFile('./index.html') 13 | handleIPC() 14 | }) 15 | 16 | function handleIPC() { 17 | ipcMain.handle('work-notification', async function () { 18 | let res = await new Promise((resolve, reject) => { 19 | let notification = new Notification({ 20 | title: '任务结束', 21 | body: '是否开始休息', 22 | actions: [{text: '开始休息', type: 'button'}], 23 | closeButtonText: '继续工作' 24 | }) 25 | notification.show() 26 | notification.on('action', () => { 27 | resolve('rest') 28 | }) 29 | notification.on('close', () => { 30 | resolve('work') 31 | }) 32 | }) 33 | return res 34 | }) 35 | } 36 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pomodoro", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "main.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "electron ." 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "devDependencies": { 14 | "electron": "^7.1.7" 15 | }, 16 | "dependencies": { 17 | "timer.js": "^1.0.4" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-demo/readme.md: -------------------------------------------------------------------------------- 1 | # 番茄钟教学极简版 2 | 3 | # 使用 4 | ``` 5 | npm install 6 | npm start 7 | ``` 8 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-demo/renderer.js: -------------------------------------------------------------------------------- 1 | const {ipcRenderer} = require('electron') 2 | const Timer = require('timer.js') 3 | 4 | function startWork() { 5 | let workTimer = new Timer({ 6 | ontick: (ms) => { 7 | updateTime(ms) 8 | }, 9 | onend: () => { 10 | notification() 11 | } 12 | }) 13 | workTimer.start(10) 14 | } 15 | 16 | function updateTime(ms) { 17 | let timerContainer = document.getElementById('timer-container') 18 | let s = (ms / 1000).toFixed(0) 19 | let ss = s % 60 20 | let mm = (s / 60).toFixed(0) 21 | timerContainer.innerText = `${mm.toString().padStart(2, 0)}: ${ss.toString().padStart(2, 0)}` 22 | } 23 | 24 | async function notification() { 25 | let res = await ipcRenderer.invoke('work-notification') 26 | if(res === 'rest') { 27 | setTimeout(() => { 28 | alert('休息') 29 | }, 5 * 1000) 30 | } else if(res === 'work') { 31 | startWork() 32 | } 33 | } 34 | 35 | startWork() 36 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-homework/index.html: -------------------------------------------------------------------------------- 1 | 2 | 26 | 27 |
28 |
29 | 30 |
31 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-homework/main.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow, ipcMain, Notification} = require('electron') 2 | let mainWindow; 3 | function handleIPC() { 4 | ipcMain.handle('notification', async (e, {body, title, actions, closeButtonText}) => { 5 | let res = await new Promise((resolve, reject) => { 6 | console.log({ 7 | title, 8 | body, 9 | actions, 10 | closeButtonText 11 | }) 12 | let notification = new Notification({ 13 | title, 14 | body, 15 | actions, 16 | closeButtonText 17 | }) 18 | notification.show() 19 | notification.on('action', function(event) { 20 | resolve({event: 'action'}) 21 | }) 22 | notification.on('close', function(event) { 23 | resolve({event: 'close'}) 24 | }) 25 | }) 26 | return res 27 | }) 28 | } 29 | 30 | function createMainWindow() { 31 | mainWindow = new BrowserWindow({ 32 | width: 250, 33 | height: 350, 34 | webPreferences: { 35 | nodeIntegration: true 36 | } 37 | }) 38 | mainWindow.loadFile('./index.html') 39 | 40 | return mainWindow 41 | } 42 | 43 | app.whenReady().then(() => { 44 | handleIPC() 45 | createMainWindow() 46 | }) 47 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-homework/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pomodoro", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "main.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "electron ." 9 | }, 10 | "keywords": [], 11 | "author": "dragon", 12 | "license": "ISC", 13 | "devDependencies": { 14 | "electron": "^7.1.7" 15 | }, 16 | "dependencies": { 17 | "progressbar.js": "^1.1.0", 18 | "timer.js": "^1.0.4" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-homework/readme.md: -------------------------------------------------------------------------------- 1 | # 番茄钟完整版 2 | 3 | # 使用 4 | ``` 5 | npm install 6 | npm start 7 | ``` 8 | -------------------------------------------------------------------------------- /Chapter 1/8-pomodoro-homework/renderer.js: -------------------------------------------------------------------------------- 1 | const {ipcRenderer} = require('electron') 2 | const ProgressBar = require('progressbar.js/dist/progressbar.js') 3 | const Timer = require('timer.js') 4 | 5 | let timerContainer = document.getElementById('timer-container') 6 | let switchButton = document.getElementById('switch-button') 7 | let progressBar = new ProgressBar.Circle('#timer-container', { 8 | strokeWidth: 2, 9 | color: '#F44336', 10 | trailColor: '#eee', 11 | trailWidth: 1, 12 | svgStyle: null 13 | }) 14 | let workTime = 1 * 60 // 1分钟工作, 自行设定 15 | let restTime = 10 // 10秒休息 16 | let state = {} 17 | 18 | function render () { 19 | let {remainTime: s, type} = state 20 | let maxTime = type < 2 ? workTime: restTime 21 | let ss = s % 60 22 | let mm = ((s - ss)/ 60).toFixed() 23 | progressBar.set(1- s/maxTime) 24 | progressBar.setText(`${mm.toString().padStart(2, '0')}:${ss.toString().padStart(2, '0')}`) 25 | if(type === 0) { 26 | switchButton.innerText = '开始工作' 27 | } else if(type === 1) { 28 | switchButton.innerText = '停止工作' 29 | } else if (type === 2){ 30 | switchButton.innerText = '开始休息' 31 | } else { 32 | switchButton.innerText = '停止休息' 33 | } 34 | } 35 | 36 | function setState(_state) { 37 | Object.assign(state, _state) 38 | render() 39 | } 40 | 41 | function startWork() { 42 | setState({type: 1, remainTime: workTime }) 43 | workTimer.start(workTime) 44 | } 45 | 46 | function startRest() { 47 | setState({type: 3, remainTime: restTime}) 48 | workTimer.start(restTime) 49 | } 50 | 51 | const workTimer = new Timer({ 52 | ontick: (ms) => { setState({remainTime: (ms/1000).toFixed(0)}) }, // 每秒更新时间 53 | onstop: () => { setState({type: 0, remainTime: 0}) }, // 只要是停止,都会进入到工作状态 54 | onend: function() { 55 | let {type} = state 56 | if(type === 1) { 57 | setState({type: 2, remainTime: 0}) 58 | if(process.platform === 'darwin') { // 在Mac下才能使用notification 59 | notification({ 60 | title: '恭喜你完成任务', 61 | body: '是否开始休息?', 62 | actionText: '休息五分钟', 63 | closeButtonText: '继续工作', 64 | onaction: startRest, 65 | onclose: startWork 66 | }) 67 | } else { // windows直接alert 68 | alert('工作结束') 69 | } 70 | } else if(type === 3) { 71 | setState({type: 0, remainTime: 0}) 72 | if(process.platform === 'darwin') { 73 | notification({ 74 | body: '开始新的工作吧!', 75 | title: '休息结束', 76 | closeButtonText: '继续休息', 77 | actionText: '开始工作', 78 | onaction: startWork, 79 | onclose: startRest 80 | }) 81 | } else { 82 | alert('工作结束') 83 | } 84 | } 85 | } 86 | }); 87 | 88 | switchButton.onclick = function() { 89 | if (this.innerText === '开始工作') { 90 | startWork() 91 | } else if(this.innerText === '开始休息'){ 92 | startRest() 93 | } else { 94 | workTimer.stop() 95 | } 96 | } 97 | 98 | async function notification({title, body, actionText, closeButtonText, onclose, onaction}) { 99 | let res = await ipcRenderer.invoke('notification', { 100 | title, 101 | body, 102 | actions: [{text: actionText, type: 'button'}], 103 | closeButtonText 104 | }) 105 | res.event === 'close' ? onclose() : onaction() 106 | } 107 | 108 | setState({ 109 | remainTime: 0, 110 | type: 0 // 0 开始工作、1 停止工作、2 开始休息、3 停止休息 111 | }) 112 | -------------------------------------------------------------------------------- /Chapter 2/10-signal/index.js: -------------------------------------------------------------------------------- 1 | const WebSocket = require('ws'); 2 | const wss = new WebSocket.Server({ port: 8010 }); 3 | const code2ws = new Map() 4 | 5 | wss.on('connection', function connection(ws, request) { 6 | ws.sendData = (event, data) => { 7 | ws.send(JSON.stringify({event, data})); 8 | }; 9 | ws.sendError = msg => { 10 | ws.sendData('error', {msg}) 11 | }; 12 | 13 | let code = Math.floor(Math.random()*(999999-100000)) + 100000; 14 | let ip = request.connection.remoteAddress.replace('::ffff:', ''); 15 | console.log('ip is connected', ip) 16 | code2ws.set(code, ws) 17 | ws.on('message', function incoming(message) { 18 | console.log('imcoming message') 19 | let parsedMessage = {} 20 | try { 21 | parsedMessage = JSON.parse(message); 22 | } catch (e) { 23 | console.log('parse error', e) 24 | ws.sendError('message not valid') 25 | return 26 | } 27 | let {event, data} = parsedMessage 28 | 29 | if (event === 'login') { 30 | ws.sendData( 'logined', {code}) 31 | } else if(event === 'control'){ 32 | let remote = +data.remote 33 | if (code2ws.has(remote)) { 34 | ws.sendData('controlled', {remote}) 35 | let remoteWS = code2ws.get(remote) 36 | ws.sendRemote = remoteWS.sendData 37 | remoteWS.sendRemote = ws.sendData 38 | ws.sendRemote('be-controlled', {remote: code}) 39 | } else { 40 | ws.sendError('user not found') 41 | } 42 | } else if (event === 'forward'){ 43 | ws.sendRemote(data.event, data.data) 44 | } else { 45 | ws.sendError('message not handle', message) 46 | } 47 | }); 48 | 49 | ws.on('close', () => { 50 | code2ws.delete(code) 51 | delete ws.sendRemote 52 | clearTimeout(ws._closeTimeout); 53 | }) 54 | 55 | ws._closeTimeout = setTimeout(() => { 56 | ws.terminate(); 57 | }, 600000); 58 | }); 59 | -------------------------------------------------------------------------------- /Chapter 2/10-signal/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "signal", 3 | "version": "1.0.0", 4 | "description": "geetime-electron signal example", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "node .", 9 | "online": "pm2 start index.js" 10 | }, 11 | "keywords": [], 12 | "author": "", 13 | "license": "ISC", 14 | "dependencies": { 15 | "ws": "^7.2.1" 16 | }, 17 | "devDependencies": { 18 | "pm2": "^4.2.3" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/index.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow} = require('electron') 2 | const path = require('path') 3 | const handleIPC = require('./ipc') 4 | const {create: createMainWindow, show: showMainWindow, close: closeMainWindow} = require('./windows/main') 5 | // const {create: createControlWindow} = require('./windows/control') 6 | const gotTheLock = app.requestSingleInstanceLock() 7 | if(!gotTheLock) { 8 | app.quit() 9 | } else { 10 | app.on('second-instance', () => { 11 | showMainWindow() 12 | }) 13 | app.on('ready', () => { 14 | // createControlWindow() 15 | createMainWindow() 16 | handleIPC() 17 | require('./trayAndMenu') 18 | require('./robot.js')() 19 | }) 20 | app.on('before-quit', () => { 21 | closeMainWindow() 22 | }) 23 | app.on('activate', () => { 24 | showMainWindow() 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/ipc.js: -------------------------------------------------------------------------------- 1 | const {ipcMain} = require('electron') 2 | const {create: createControlWindow, send: sendControlWindow} = require('./windows/control') 3 | const {send: sendMainWindow} = require('./windows/main') 4 | const signal = require('./signal') 5 | 6 | module.exports = function () { 7 | ipcMain.handle('login', async () => { 8 | let {code} = await signal.invoke('login', null, 'logined') 9 | return code 10 | }) 11 | ipcMain.on('control', async (e, remote) => { 12 | // 这里是跟服务端的交互,成功后我们会唤起面板 13 | signal.send('control', {remote}) 14 | }) 15 | 16 | signal.on('controlled', (data) => { 17 | sendMainWindow('control-state-change', data.remote, 1) 18 | createControlWindow() 19 | }) 20 | 21 | signal.on('be-controlled', (data) => { 22 | sendMainWindow('control-state-change', data.remote, 2) 23 | }) 24 | 25 | // puppet、control共享的信道,就是转发 26 | ipcMain.on('forward', (e, event, data) => { 27 | signal.send('forward', {event, data}) 28 | }) 29 | 30 | // 收到offer,puppet响应 31 | signal.on('offer', (data) => { 32 | sendMainWindow('offer', data) 33 | }) 34 | 35 | // 收到puppet证书,answer响应 36 | signal.on('answer', (data) => { 37 | sendControlWindow('answer', data) 38 | }) 39 | 40 | // 收到control证书,puppet响应 41 | signal.on('puppet-candidate', (data) => { 42 | sendControlWindow('candidate', data) 43 | }) 44 | 45 | // 收到puppet证书,control响应 46 | signal.on('control-candidate', (data) => { 47 | sendMainWindow('candidate', data) 48 | }) 49 | } 50 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/robot.js: -------------------------------------------------------------------------------- 1 | const {ipcMain} = require('electron') 2 | const robot = require('robotjs') 3 | const vkey = require('vkey') 4 | 5 | function handleMouse(data) { 6 | let {clientX, clientY, screen, video} = data 7 | // data {clientX, clientY, screen: {width, height}, video: {width, height}} 8 | let x = clientX * screen.width / video.width 9 | let y = clientY * screen.height / video.height 10 | console.log(x, y) 11 | robot.moveMouse(x, y) 12 | robot.mouseClick() 13 | } 14 | 15 | function handleKey(data) { 16 | // data {keyCode, meta, alt, ctrl, shift} 17 | const modifiers = [] 18 | if(data.meta) modifiers.push('meta') 19 | if(data.shift) modifiers.push('shift') 20 | if(data.alt) modifiers.push('alt') 21 | if(data.ctrl) modifiers.push('ctrl') 22 | let key = vkey[data.keyCode].toLowerCase() 23 | if(key[0] !== '<') { // 24 | robot.keyTap(key, modifiers) 25 | } 26 | } 27 | 28 | module.exports = function() { 29 | ipcMain.on('robot', (e, type, data) => { 30 | console.log('handle', type, data) 31 | if(type === 'mouse') { 32 | handleMouse(data) 33 | } else if(type === 'key') { 34 | handleKey(data) 35 | } 36 | }) 37 | } 38 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/signal.js: -------------------------------------------------------------------------------- 1 | const WebSocket = require('ws'); 2 | const EventEmitter = require('events'); 3 | const signal = new EventEmitter(); 4 | 5 | const ws = new WebSocket('ws://127.0.0.1:8010'); 6 | // const ws = new WebSocket('ws://111.231.59.178:8010'); // 填你自己的地址,这个是我的服务器,不一定可用 7 | 8 | ws.on('open', function open() { 9 | console.log('connect success') 10 | }) 11 | 12 | ws.on('message', function incoming(message) { 13 | let data = JSON.parse(message) 14 | console.log('data', data, message); 15 | signal.emit(data.event, data.data) 16 | }) 17 | 18 | 19 | function send(event, data) { 20 | console.log('sended', JSON.stringify({event, data})) 21 | ws.send(JSON.stringify({event, data})) 22 | } 23 | 24 | function invoke(event, data, answerEvent) { 25 | return new Promise((resolve, reject) => { 26 | send(event, data) 27 | signal.once(answerEvent, resolve) 28 | setTimeout(() => { 29 | reject('timeout') 30 | }, 5000) 31 | }) 32 | } 33 | signal.send = send 34 | signal.invoke = invoke 35 | 36 | module.exports = signal 37 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/trayAndMenu/darwin.js: -------------------------------------------------------------------------------- 1 | const {app, Menu, Tray} = require('electron') 2 | const {show: showMainWindow} = require('../windows/main') 3 | const {create: createAboutWindow} = require('../windows/about') 4 | const path = require('path') 5 | 6 | let tray 7 | function setTray() { 8 | tray = new Tray(path.resolve(__dirname, './icon_darwin.png')) 9 | tray.on('click', () => { 10 | showMainWindow() 11 | }) 12 | tray.on('right-click', () => { 13 | const contextMenu = Menu.buildFromTemplate([ 14 | {label: '显示', click: showMainWindow}, 15 | {label: '退出', click: app.quit} 16 | ]) 17 | tray.popUpContextMenu(contextMenu) 18 | }) 19 | } 20 | 21 | function setAppMenu() { 22 | let appMenu = Menu.buildFromTemplate([ 23 | { 24 | label: app.name, 25 | submenu: [ 26 | { 27 | label: 'About', 28 | click: createAboutWindow 29 | }, 30 | { type: 'separator' }, 31 | { role: 'services' }, 32 | { type: 'separator' }, 33 | { role: 'hide' }, 34 | { role: 'hideothers' }, 35 | { role: 'unhide' }, 36 | { type: 'separator' }, 37 | { role: 'quit' } 38 | ], 39 | 40 | }, 41 | { role: 'fileMenu' }, 42 | { role: 'windowMenu' }, 43 | { role: 'editMenu' } 44 | ]); 45 | app.applicationMenu = appMenu 46 | } 47 | 48 | app.whenReady().then(() => { 49 | setTray() 50 | setAppMenu() 51 | }) 52 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/trayAndMenu/icon_darwin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/12-remote-control/app/main/trayAndMenu/icon_darwin.png -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/trayAndMenu/icon_darwin@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/12-remote-control/app/main/trayAndMenu/icon_darwin@2x.png -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/trayAndMenu/icon_win32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/12-remote-control/app/main/trayAndMenu/icon_win32.png -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/trayAndMenu/icon_win32@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/12-remote-control/app/main/trayAndMenu/icon_win32@2x.png -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/trayAndMenu/index.js: -------------------------------------------------------------------------------- 1 | if(process.platform === 'darwin') { 2 | require('./darwin.js') 3 | } else if (process.platform === 'win32') { 4 | require('./win32.js') 5 | } else { 6 | // 不处理 7 | } 8 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/trayAndMenu/win32.js: -------------------------------------------------------------------------------- 1 | const { app, Menu, Tray } = require('electron') 2 | const path = require('path') 3 | const {show: showMainWindow} = require('../windows/main') 4 | const {create: createAboutWindow}= require('../windows/about') 5 | 6 | let tray; 7 | app.whenReady().then(() => { 8 | tray = new Tray(path.resolve(__dirname, './icon_win32.png')) 9 | const contextMenu = Menu.buildFromTemplate([ 10 | { label: '打开' + app.name, click: showMainWindow}, 11 | { label: '关于' + app.name, click: createAboutWindow}, 12 | { type: 'separator' }, 13 | { label: '退出', click: () => {app.quit()}} 14 | ]) 15 | tray.setContextMenu(contextMenu) 16 | menu = Menu.buildFromTemplate([]) 17 | app.applicationMenu = menu; 18 | }) 19 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/windows/about.js: -------------------------------------------------------------------------------- 1 | const openAboutWindow = require('about-window').default 2 | const path = require('path') 3 | 4 | const create = () => openAboutWindow({ 5 | icon_path: path.join(__dirname, 'icon.png'), 6 | package_json_dir: path.resolve(__dirname, '/../../../'), 7 | cropyright: 'Copyright (c) 2020 dragon', 8 | homepage: 'https://github.com/dengyaolong/geektime-electron', 9 | }) 10 | 11 | module.exports = {create} 12 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/windows/control.js: -------------------------------------------------------------------------------- 1 | const {BrowserWindow} = require('electron') 2 | const path = require('path') 3 | let win 4 | function create() { 5 | win = new BrowserWindow({ 6 | width: 1000, 7 | height: 680, 8 | webPreferences: { 9 | nodeIntegration: true 10 | } 11 | }) 12 | win.loadFile(path.resolve(__dirname, '../../renderer/pages/control/index.html')) 13 | } 14 | 15 | function send(channel, ...args) { 16 | win.webContents.send(channel, ...args) 17 | } 18 | 19 | module.exports = {create, send} 20 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/windows/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/12-remote-control/app/main/windows/icon.png -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/main/windows/main.js: -------------------------------------------------------------------------------- 1 | const {BrowserWindow} = require('electron') 2 | const isDev = require('electron-is-dev') 3 | 4 | 5 | let win 6 | let willQuitApp = false 7 | function create () { 8 | win = new BrowserWindow({ 9 | width: 600, 10 | height: 300, 11 | webPreferences: { 12 | nodeIntegration: true 13 | } 14 | }) 15 | win.on('close', (e) => { 16 | if(willQuitApp) { 17 | win = null 18 | } else { 19 | e.preventDefault() 20 | win.hide() 21 | } 22 | }) 23 | 24 | if (isDev) { 25 | win.loadURL('http://localhost:3000') 26 | } else { 27 | // 第三章用到 28 | win.loadFile(path.resolve(__dirname, '../../renderer/pages/main/index.html')) 29 | } 30 | } 31 | 32 | function send(channel, ...args) { 33 | win.webContents.send(channel, ...args) 34 | } 35 | 36 | function show() { 37 | win.show() 38 | } 39 | 40 | function close() { 41 | willQuitApp = true 42 | win.close() 43 | } 44 | 45 | module.exports = {create, send, show, close} 46 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/pages/control/app.js: -------------------------------------------------------------------------------- 1 | const peer = require('./peer-control') 2 | 3 | peer.on('add-stream', (stream) => { 4 | console.log('play stream') 5 | play(stream) 6 | }) 7 | 8 | let video = document.getElementById('screen-video') 9 | function play(stream) { 10 | video.srcObject = stream 11 | video.onloadedmetadata = function() { 12 | video.play() 13 | } 14 | } 15 | 16 | window.onkeydown = function(e) { 17 | // data {keyCode, meta, alt, ctrl, shift} 18 | let data = { 19 | keyCode: e.keyCode, 20 | shift: e.shiftKey, 21 | meta: e.metaKey, 22 | control: e.ctrlKey, 23 | alt: e.altKey 24 | } 25 | peer.emit('robot', 'key', data) 26 | } 27 | 28 | window.onmouseup = function(e) { 29 | // data {clientX, clientY, screen: {width, height}, video: {width, height}} 30 | let data = {} 31 | data.clientX = e.clientX 32 | data.clientY = e.clientY 33 | data.video = { 34 | width: video.getBoundingClientRect().width, 35 | height: video.getBoundingClientRect().height 36 | } 37 | peer.emit('robot', 'mouse', data) 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/pages/control/index.html: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/pages/control/index.js: -------------------------------------------------------------------------------- 1 | const {desktopCapture} = require('electron') 2 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/pages/control/peer-control.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events') 2 | const peer = new EventEmitter() 3 | const {ipcRenderer, desktopCapturer} = require('electron') 4 | const pc = new window.RTCPeerConnection({}) 5 | let dc = pc.createDataChannel('robotchannel', {reliable: false}); 6 | console.log('before-opened', dc) 7 | dc.onopen = function() { 8 | console.log('opened') 9 | peer.on('robot', (type, data) => { 10 | dc.send(JSON.stringify({type, data})) 11 | }) 12 | } 13 | dc.onmessage = function(event) { 14 | console.log('message', event) 15 | } 16 | dc.onerror = (e) => {console.log(e)} 17 | async function createOffer() { 18 | let offer = await pc.createOffer({ 19 | offerToReceiveAudio: false, 20 | offerToReceiveVideo: true 21 | }) 22 | await pc.setLocalDescription(offer) 23 | console.log('create-offer\n', JSON.stringify(pc.localDescription)) 24 | return pc.localDescription 25 | } 26 | createOffer().then((offer) => { 27 | console.log('forward', 'offer', offer) 28 | ipcRenderer.send('forward', 'offer', {type: offer.type, sdp: offer.sdp}) 29 | }) 30 | 31 | ipcRenderer.on('answer', (e, answer) => { 32 | setRemote(answer) 33 | }) 34 | 35 | ipcRenderer.on('candidate', (e, candidate) => { 36 | addIceCandidate(candidate) 37 | }) 38 | 39 | async function setRemote(answer) { 40 | await pc.setRemoteDescription(answer) 41 | console.log('create-answer', pc) 42 | } 43 | window.setRemote = setRemote 44 | 45 | pc.onicecandidate = (e) => { 46 | console.log('candidate', JSON.stringify(e.candidate)) 47 | ipcRenderer.send('forward', 'control-candidate', e.candidate) 48 | // 告知其他人 49 | } 50 | const candidates = [] 51 | async function addIceCandidate(candidate) { 52 | if(!candidate || !candidate.type) return 53 | candidates.push(candidate) 54 | if(pc.remoteDescription && pc.remoteDescription.type) { 55 | for(let i = 0; i < candidates.length; i ++) { 56 | await pc.addIceCandidate(new RTCIceCandidate(candidates[i])) 57 | } 58 | candidates = [] 59 | } 60 | } 61 | window.addIceCandidate = addIceCandidate 62 | 63 | pc.onaddstream = (e) => { 64 | console.log('addstream', e) 65 | peer.emit('add-stream', e.stream) 66 | 67 | } 68 | 69 | 70 | // 先把robot屏蔽 71 | // peer.on('robot', (type, data) => { 72 | // console.log('robot', type, data) 73 | // if(type === 'mouse') { 74 | // data.screen = { 75 | // width: window.screen.width, 76 | // height: window.screen.height 77 | // } 78 | // } 79 | // setTimeout(() => { 80 | // ipcRenderer.send('robot', type, data) 81 | // }, 2000) 82 | // 83 | // }) 84 | module.exports = peer 85 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `npm run build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/config-overrides.js: -------------------------------------------------------------------------------- 1 | const { override } = require('customize-cra'); 2 | 3 | function addRendererTarget(config) { 4 | config.target = 'electron-renderer' 5 | return config 6 | } 7 | 8 | module.exports = override(addRendererTarget) 9 | 10 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "main", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.4.0", 8 | "@testing-library/user-event": "^7.2.1", 9 | "react": "^16.12.0", 10 | "react-dom": "^16.12.0", 11 | "react-scripts": "3.3.0" 12 | }, 13 | "scripts": { 14 | "start": "BROWSER=none react-app-rewired start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | }, 34 | "devDependencies": { 35 | "customize-cra": "^0.9.1", 36 | "react-app-rewired": "^2.1.5" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/12-remote-control/app/renderer/src/main/public/favicon.ico -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | Mercurius 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/12-remote-control/app/renderer/src/main/public/logo192.png -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/12-remote-control/app/renderer/src/main/public/logo512.png -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/App.js: -------------------------------------------------------------------------------- 1 | import React, {useState, useEffect} from 'react'; 2 | import './App.css'; 3 | import {ipcRenderer, remote} from 'electron' 4 | import './peer-puppet' 5 | const {Menu, MenuItem} = remote 6 | 7 | function App() { 8 | const [remoteCode, setRemoteCode] = useState(''); 9 | const [localCode, setLocalCode] = useState(''); 10 | // 0未连接,1已控制,2被控制 11 | const [controlText, setControlText] = useState(''); 12 | 13 | const startControl = (remoteCode) => { 14 | ipcRenderer.send('control', remoteCode) 15 | } 16 | const login = async () => { 17 | let code = await ipcRenderer.invoke('login') 18 | setLocalCode(code) 19 | } 20 | 21 | const handleControlState = (e, name, type) => { 22 | let text = '' 23 | if(type === 1) { 24 | text = `正在远程控制${name}` 25 | } else if(type === 2) { 26 | text = `被${name}控制中` 27 | } else { 28 | text = '' 29 | } 30 | setControlText(text) 31 | } 32 | 33 | useEffect(() => { 34 | login() 35 | ipcRenderer.on('control-state-change', handleControlState) 36 | return () => { 37 | ipcRenderer.removeListener('control-state-change', handleControlState) 38 | } 39 | }, []) 40 | 41 | const handleContextMenu = (e) => { 42 | e.preventDefault() 43 | const menu = new Menu() 44 | menu.append(new MenuItem({label: '复制', role: 'copy'})) 45 | menu.popup() 46 | } 47 | return ( 48 |
49 | { 50 | controlText === '' ? <> 51 |
你的控制码 handleContextMenu(e)} >{localCode}
52 | setRemoteCode(e.target.value)}/> 53 | 54 | :
{controlText}
55 | } 56 |
57 | ); 58 | } 59 | 60 | export default App; 61 | 62 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/peer-puppet.js: -------------------------------------------------------------------------------- 1 | import EventEmitter from 'events' 2 | import {ipcRenderer, desktopCapturer} from 'electron' 3 | let peer = new EventEmitter() 4 | window.peer = peer // 为了直接模拟过程,信令结束后,会删掉 5 | ipcRenderer.on('offer', (e, offer) => { 6 | console.log('init pc', offer) 7 | const pc = new window.RTCPeerConnection(); 8 | 9 | pc.ondatachannel = (e) => { 10 | console.log('data', e) 11 | e.channel.onmessage = (e) => { 12 | console.log('onmessage', e, JSON.parse(e.data)) 13 | let {type, data} = JSON.parse(e.data) 14 | console.log('robot', type, data) 15 | if(type === 'mouse') { 16 | data.screen = { 17 | width: window.screen.width, 18 | height: window.screen.height 19 | } 20 | } 21 | ipcRenderer.send('robot', type, data) 22 | } 23 | } 24 | 25 | async function getScreenStream() { 26 | const sources = await desktopCapturer.getSources({types: ['screen']}) 27 | return new Promise((resolve, reject) => { 28 | navigator.webkitGetUserMedia({ 29 | audio: false, 30 | video: { 31 | mandatory: { 32 | chromeMediaSource: 'desktop', 33 | chromeMediaSourceId: sources[0].id, 34 | maxWidth: window.screen.width, 35 | maxHeight: window.screen.height 36 | } 37 | } 38 | }, (stream) => { 39 | console.log('add-stream', stream) 40 | resolve(stream) 41 | }, reject) 42 | }) 43 | } 44 | 45 | pc.onicecandidate = (e) => { 46 | // 告知其他人 47 | ipcRenderer.send('forward', 'puppet-candidate', e.candidate) 48 | } 49 | 50 | async function addIceCandidate(candidate) { 51 | if(!candidate || !candidate.type) return 52 | await pc.addIceCandidate(new RTCIceCandidate(candidate)) 53 | } 54 | window.addIceCandidate = addIceCandidate 55 | 56 | async function createAnswer(offer) { 57 | let stream = await getScreenStream() 58 | pc.addStream(stream) 59 | await pc.setRemoteDescription(offer); 60 | await pc.setLocalDescription(await pc.createAnswer()); 61 | console.log('create answer \n', JSON.stringify(pc.localDescription)) 62 | // send answer 63 | return pc.localDescription 64 | } 65 | createAnswer(offer).then((answer) => { 66 | ipcRenderer.send('forward', 'answer', {type: answer.type, sdp: answer.sdp}) 67 | }) 68 | 69 | }) 70 | export default peer 71 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' } 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready.then(registration => { 134 | registration.unregister(); 135 | }); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/app/renderer/src/main/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /Chapter 2/12-remote-control/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Mercurius", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app/main/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "concurrently \"npm run start:render\" \"wait-on http://localhost:3000 && npm run start:main\" ", 9 | "start:main": "electron .", 10 | "start:render": "cd app/renderer/src/main && npm start" 11 | }, 12 | "keywords": [], 13 | "author": "dragon", 14 | "license": "ISC", 15 | "devDependencies": { 16 | "concurrently": "^5.0.2", 17 | "electron": "^7.1.8", 18 | "electron-rebuild": "^1.8.8", 19 | "wait-on": "^3.3.0" 20 | }, 21 | "dependencies": { 22 | "about-window": "^1.13.2", 23 | "electron-about-window": "^1.13.2", 24 | "electron-is-dev": "^1.1.0", 25 | "robotjs": "^0.6.0", 26 | "vkey": "^1.0.1", 27 | "ws": "^7.2.1" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/READMD.md: -------------------------------------------------------------------------------- 1 | # 说明 2 | 这个是前六节的demo,所有操作都是mock的。运行起来后,随便输一个code,之后弹出画面,能看到桌面流即可 3 | 4 | # 运行 5 | * npm install 6 | * cd app/renderer/src/main/ 7 | * npm install 8 | * cd - # 返回到根目录 9 | * npm start 10 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/main/index.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow} = require('electron') 2 | const path = require('path') 3 | const handleIPC = require('./ipc') 4 | const {create: createMainWindow} = require('./windows/main') 5 | const {create: createControlWindow} = require('./windows/control') 6 | 7 | app.on('ready', () => { 8 | // createControlWindow() 9 | createMainWindow() 10 | handleIPC() 11 | require('./robot.js')() 12 | }) 13 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/main/ipc.js: -------------------------------------------------------------------------------- 1 | const {ipcMain} = require('electron') 2 | const {create: createControlWindow} = require('./windows/control') 3 | const {send: sendMainWindow} = require('./windows/main') 4 | 5 | module.exports = function () { 6 | ipcMain.handle('login', async () => { 7 | // 这里是跟服务端的交互,先mock 8 | let code = Math.floor(Math.random()*(999999-100000)) + 100000; 9 | return code 10 | }) 11 | ipcMain.on('control', async (e, remoteCode) => { 12 | // 这里是跟服务端的交互,成功后我们会唤起面板 13 | createControlWindow() 14 | sendMainWindow('control-state-change', remoteCode, 1) 15 | }) 16 | } 17 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/main/robot.js: -------------------------------------------------------------------------------- 1 | const {ipcMain} = require('electron') 2 | const robot = require('robotjs') 3 | const vkey = require('vkey') 4 | 5 | function handleMouse(data) { 6 | let {clientX, clientY, screen, video} = data 7 | // data {clientX, clientY, screen: {width, height}, video: {width, height}} 8 | let x = clientX * screen.width / video.width 9 | let y = clientY * screen.height / video.height 10 | console.log(x, y) 11 | robot.moveMouse(x, y) 12 | robot.mouseClick() 13 | } 14 | 15 | function handleKey(data) { 16 | // data {keyCode, meta, alt, ctrl, shift} 17 | const modifiers = [] 18 | if(data.meta) modifiers.push('meta') 19 | if(data.shift) modifiers.push('shift') 20 | if(data.alt) modifiers.push('alt') 21 | if(data.ctrl) modifiers.push('ctrl') 22 | let key = vkey[data.keyCode].toLowerCase() 23 | if(key[0] !== '<') { // 24 | robot.keyTap(key, modifiers) 25 | } 26 | } 27 | 28 | module.exports = function() { 29 | ipcMain.on('robot', (e, type, data) => { 30 | console.log('handle', type, data) 31 | if(type === 'mouse') { 32 | handleMouse(data) 33 | } else if(type === 'key') { 34 | handleKey(data) 35 | } 36 | }) 37 | } 38 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/main/windows/control.js: -------------------------------------------------------------------------------- 1 | const {BrowserWindow} = require('electron') 2 | const path = require('path') 3 | let win 4 | function create() { 5 | win = new BrowserWindow({ 6 | width: 1000, 7 | height: 680, 8 | webPreferences: { 9 | nodeIntegration: true 10 | } 11 | }) 12 | win.loadFile(path.resolve(__dirname, '../../renderer/pages/control/index.html')) 13 | } 14 | 15 | module.exports = {create} 16 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/main/windows/main.js: -------------------------------------------------------------------------------- 1 | const {BrowserWindow} = require('electron') 2 | const isDev = require('electron-is-dev') 3 | 4 | let win 5 | function create () { 6 | win = new BrowserWindow({ 7 | width: 600, 8 | height: 300, 9 | webPreferences: { 10 | nodeIntegration: true 11 | } 12 | }) 13 | 14 | if (isDev) { 15 | win.loadURL('http://localhost:3000') 16 | } else { 17 | // 第三章用到 18 | win.loadFile(path.resolve(__dirname, '../../renderer/pages/main/index.html')) 19 | } 20 | } 21 | 22 | function send(channel, ...args) { 23 | win.webContents.send(channel, ...args) 24 | } 25 | 26 | module.exports = {create, send} 27 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/pages/control/app.js: -------------------------------------------------------------------------------- 1 | const peer = require('./peer-control') 2 | 3 | peer.on('add-stream', (stream) => { 4 | play(stream) 5 | }) 6 | 7 | let video = document.getElementById('screen-video') 8 | function play(stream) { 9 | video.srcObject = stream 10 | video.onloadedmetadata = function() { 11 | video.play() 12 | } 13 | } 14 | 15 | window.onkeydown = function(e) { 16 | // data {keyCode, meta, alt, ctrl, shift} 17 | let data = { 18 | keyCode: e.keyCode, 19 | shift: e.shiftKey, 20 | meta: e.metaKey, 21 | control: e.ctrlKey, 22 | alt: e.altKey 23 | } 24 | peer.emit('robot', 'key', data) 25 | } 26 | 27 | window.onmouseup = function(e) { 28 | // data {clientX, clientY, screen: {width, height}, video: {width, height}} 29 | let data = {} 30 | data.clientX = e.clientX 31 | data.clientY = e.clientY 32 | data.video = { 33 | width: video.getBoundingClientRect().width, 34 | height: video.getBoundingClientRect().height 35 | } 36 | peer.emit('robot', 'mouse', data) 37 | } 38 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/pages/control/index.html: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/pages/control/index.js: -------------------------------------------------------------------------------- 1 | const {desktopCapture} = require('electron') 2 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/pages/control/peer-control.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events') 2 | const peer = new EventEmitter() 3 | const {ipcRenderer, desktopCapturer} = require('electron') 4 | async function getScreenStream() { 5 | const sources = await desktopCapturer.getSources({types: ['screen']}) 6 | 7 | navigator.webkitGetUserMedia({ 8 | audio: false, 9 | video: { 10 | mandatory: { 11 | chromeMediaSource: 'desktop', 12 | chromeMediaSourceId: sources[0].id, 13 | maxWidth: window.screen.width, 14 | maxHeight: window.screen.height 15 | } 16 | } 17 | }, (stream) => { 18 | peer.emit('add-stream', stream) 19 | }, (err) => { 20 | //handle err 21 | console.error(err) 22 | }) 23 | } 24 | 25 | getScreenStream() 26 | peer.on('robot', (type, data) => { 27 | console.log('robot', type, data) 28 | if(type === 'mouse') { 29 | data.screen = { 30 | width: window.screen.width, 31 | height: window.screen.height 32 | } 33 | } 34 | setTimeout(() => { 35 | ipcRenderer.send('robot', type, data) 36 | }, 2000) 37 | 38 | }) 39 | module.exports = peer 40 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/pages/control/robot.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/3-6-remote-control-local-mock/app/renderer/pages/control/robot.js -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `npm run build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/config-overrides.js: -------------------------------------------------------------------------------- 1 | const { override } = require('customize-cra'); 2 | 3 | function addRendererTarget(config) { 4 | config.target = 'electron-renderer' 5 | return config 6 | } 7 | 8 | module.exports = override(addRendererTarget) 9 | 10 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "main", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.4.0", 8 | "@testing-library/user-event": "^7.2.1", 9 | "react": "^16.12.0", 10 | "react-dom": "^16.12.0", 11 | "react-scripts": "3.3.0" 12 | }, 13 | "scripts": { 14 | "start": "BROWSER=none react-app-rewired start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | }, 34 | "devDependencies": { 35 | "customize-cra": "^0.9.1", 36 | "react-app-rewired": "^2.1.5" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/favicon.ico -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/logo192.png -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/logo512.png -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/src/App.js: -------------------------------------------------------------------------------- 1 | import React, {useState, useEffect} from 'react'; 2 | import './App.css'; 3 | import {ipcRenderer} from 'electron' 4 | 5 | function App() { 6 | const [remoteCode, setRemoteCode] = useState(''); 7 | const [localCode, setLocalCode] = useState(''); 8 | // 0未连接,1已控制,2被控制 9 | const [controlText, setControlText] = useState(''); 10 | 11 | const startControl = (remoteCode) => { 12 | ipcRenderer.send('control', remoteCode) 13 | } 14 | const login = async () => { 15 | let code = await ipcRenderer.invoke('login') 16 | setLocalCode(code) 17 | } 18 | 19 | const handleControlState = (e, name, type) => { 20 | let text = '' 21 | if(type === 1) { 22 | text = `正在远程控制${name}` 23 | } else if(type === 2) { 24 | text = `被${name}控制中` 25 | } else { 26 | text = '' 27 | } 28 | setControlText(text) 29 | } 30 | 31 | useEffect(() => { 32 | login() 33 | ipcRenderer.on('control-state-change', handleControlState) 34 | return () => { 35 | ipcRenderer.removeListener('control-state-change', handleControlState) 36 | } 37 | }, []) 38 | 39 | return ( 40 |
41 | { 42 | controlText === '' ? <> 43 |
你的控制码{localCode}
44 | setRemoteCode(e.target.value)}/> 45 | 46 | :
{controlText}
47 | } 48 |
49 | ); 50 | } 51 | 52 | export default App; 53 | 54 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' } 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready.then(registration => { 134 | registration.unregister(); 135 | }); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/app/renderer/src/main/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /Chapter 2/3-6-remote-control-local-mock/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "remote-control", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app/main/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "concurrently \"npm run start:render\" \"wait-on http://localhost:3000 && npm run start:main\" ", 9 | "start:main": "electron .", 10 | "start:render": "cd app/renderer/src/main && npm start" 11 | }, 12 | "keywords": [], 13 | "author": "", 14 | "license": "ISC", 15 | "devDependencies": { 16 | "concurrently": "^5.0.2", 17 | "customize-cra": "^0.9.1", 18 | "electron": "^7.1.8", 19 | "electron-rebuild": "^1.8.8", 20 | "react-app-rewired": "^2.1.5", 21 | "wait-on": "^3.3.0" 22 | }, 23 | "dependencies": { 24 | "electron-is-dev": "^1.1.0", 25 | "robotjs": "^0.6.0", 26 | "vkey": "^1.0.1" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter 2/4-robot-heart/READMD.md: -------------------------------------------------------------------------------- 1 | npm install 2 | npm run rebuild2 3 | npm start 4 | -------------------------------------------------------------------------------- /Chapter 2/4-robot-heart/index.html: -------------------------------------------------------------------------------- 1 | 2 | hello 3 | 4 | 5 | { 15 | createWindow() 16 | console.log(process.versions.electron, process.versions.node) 17 | ipcMain.on('robot-move', (e, x, y) => { 18 | console.log('move', x, y) 19 | robot.moveMouse(x, y); 20 | robot.mouseClick(); 21 | }) 22 | }) 23 | -------------------------------------------------------------------------------- /Chapter 2/4-robot-heart/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "remote-control", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "main.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "rebuild2": "npm rebuild --runtime=electron --target=5.0.13 --disturl=https://atom.io/download/atom-shell --abi=72", 9 | "start": "electron ." 10 | }, 11 | "keywords": [], 12 | "author": "", 13 | "license": "ISC", 14 | "devDependencies": { 15 | "electron": "^7.1.7", 16 | "electron-rebuild": "^1.8.8" 17 | }, 18 | "dependencies": { 19 | "keycode": "^2.2.0", 20 | "robotjs": "^0.6.0" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter 2/4-robot-heart/renderer.js: -------------------------------------------------------------------------------- 1 | const {ipcRenderer} = require('electron') 2 | setTimeout(() => { 3 | 4 | let n = 120; 5 | let beta = 1/n; 6 | let a = 50 7 | let c = Math.cos(beta) 8 | let s = Math.sin(beta) 9 | let c1 = c*c - s*s 10 | let s1 = 2 * c * s 11 | let x10 = a, x20=a/2, y10=0, y20=0 12 | let x=2*a,y=0 13 | let x1=x,y1=y 14 | // function draw(x, y) {console.log(x,y)} 15 | draw(x1,y1) 16 | for(let i = 0; i <= n * 10; i++) { 17 | let x_10= c * x10 - s * y10 18 | let y_10= c * y10 + s * x10 19 | let x_20 = c1 * x20 - s1 * y20 20 | let y_20 = c1 * y20 + s1 * x20 21 | x10 = x_10 ; y10=y_10; 22 | x20 = x_20; y20 = y_20; 23 | x = x10 + x20 + a/2.0 24 | y = y10 + y20; 25 | x1 = x + 0.5; y1 = y + 0.5; 26 | draw(x1, y1) 27 | } 28 | 29 | function sleep(ms){ 30 | return new Promise(resolve=>{ 31 | setTimeout(resolve,ms) 32 | }) 33 | } 34 | async function draw(x,y ){ 35 | // 把每个点连接起来 36 | await sleep(10) 37 | ipcRenderer.send('robot-move', x + 400,y + 300) 38 | // context.fill(); 39 | } 40 | }, 2000) 41 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/main/index.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow} = require('electron') 2 | const path = require('path') 3 | const handleIPC = require('./ipc') 4 | const {create: createMainWindow} = require('./windows/main') 5 | // const {create: createControlWindow} = require('./windows/control') 6 | 7 | app.on('ready', () => { 8 | // createControlWindow() 9 | createMainWindow() 10 | handleIPC() 11 | require('./robot.js')() 12 | }) 13 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/main/ipc.js: -------------------------------------------------------------------------------- 1 | const {ipcMain} = require('electron') 2 | const {create: createControlWindow, send: sendControlWindow} = require('./windows/control') 3 | const {send: sendMainWindow} = require('./windows/main') 4 | const signal = require('./signal') 5 | 6 | module.exports = function () { 7 | ipcMain.handle('login', async () => { 8 | let {code} = await signal.invoke('login', null, 'logined') 9 | return code 10 | }) 11 | ipcMain.on('control', async (e, remote) => { 12 | // 这里是跟服务端的交互,成功后我们会唤起面板 13 | signal.send('control', {remote}) 14 | }) 15 | 16 | signal.on('controlled', (data) => { 17 | sendMainWindow('control-state-change', data.remote, 1) 18 | createControlWindow() 19 | }) 20 | 21 | signal.on('be-controlled', (data) => { 22 | sendMainWindow('control-state-change', data.remote, 2) 23 | }) 24 | 25 | // puppet、control共享的信道,就是转发 26 | ipcMain.on('forward', (e, event, data) => { 27 | signal.send('forward', {event, data}) 28 | }) 29 | 30 | // 收到offer,puppet响应 31 | signal.on('offer', (data) => { 32 | sendMainWindow('offer', data) 33 | }) 34 | 35 | // 收到puppet证书,answer响应 36 | signal.on('answer', (data) => { 37 | sendControlWindow('answer', data) 38 | }) 39 | 40 | // 收到control证书,puppet响应 41 | signal.on('puppet-candidate', (data) => { 42 | sendControlWindow('candidate', data) 43 | }) 44 | 45 | // 收到puppet证书,control响应 46 | signal.on('control-candidate', (data) => { 47 | sendMainWindow('candidate', data) 48 | }) 49 | } 50 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/main/robot.js: -------------------------------------------------------------------------------- 1 | const {ipcMain} = require('electron') 2 | const robot = require('robotjs') 3 | const vkey = require('vkey') 4 | 5 | function handleMouse(data) { 6 | let {clientX, clientY, screen, video} = data 7 | // data {clientX, clientY, screen: {width, height}, video: {width, height}} 8 | let x = clientX * screen.width / video.width 9 | let y = clientY * screen.height / video.height 10 | console.log(x, y) 11 | robot.moveMouse(x, y) 12 | robot.mouseClick() 13 | } 14 | 15 | function handleKey(data) { 16 | // data {keyCode, meta, alt, ctrl, shift} 17 | const modifiers = [] 18 | if(data.meta) modifiers.push('meta') 19 | if(data.shift) modifiers.push('shift') 20 | if(data.alt) modifiers.push('alt') 21 | if(data.ctrl) modifiers.push('ctrl') 22 | let key = vkey[data.keyCode].toLowerCase() 23 | if(key[0] !== '<') { // 24 | robot.keyTap(key, modifiers) 25 | } 26 | } 27 | 28 | module.exports = function() { 29 | ipcMain.on('robot', (e, type, data) => { 30 | console.log('handle', type, data) 31 | if(type === 'mouse') { 32 | handleMouse(data) 33 | } else if(type === 'key') { 34 | handleKey(data) 35 | } 36 | }) 37 | } 38 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/main/signal.js: -------------------------------------------------------------------------------- 1 | const WebSocket = require('ws'); 2 | const EventEmitter = require('events'); 3 | const signal = new EventEmitter(); 4 | 5 | const ws = new WebSocket('ws://127.0.0.1:8010'); 6 | // const ws = new WebSocket('ws://111.231.59.178:8010'); // 填你自己的地址,这个是我的服务器,不一定可用 7 | 8 | ws.on('open', function open() { 9 | console.log('connect success') 10 | }) 11 | 12 | ws.on('message', function incoming(message) { 13 | let data = JSON.parse(message) 14 | console.log('data', data, message); 15 | signal.emit(data.event, data.data) 16 | }) 17 | 18 | 19 | function send(event, data) { 20 | console.log('sended', JSON.stringify({event, data})) 21 | ws.send(JSON.stringify({event, data})) 22 | } 23 | 24 | function invoke(event, data, answerEvent) { 25 | return new Promise((resolve, reject) => { 26 | send(event, data) 27 | signal.once(answerEvent, resolve) 28 | setTimeout(() => { 29 | reject('timeout') 30 | }, 5000) 31 | }) 32 | } 33 | signal.send = send 34 | signal.invoke = invoke 35 | 36 | module.exports = signal 37 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/main/windows/control.js: -------------------------------------------------------------------------------- 1 | const {BrowserWindow} = require('electron') 2 | const path = require('path') 3 | let win 4 | function create() { 5 | win = new BrowserWindow({ 6 | width: 1000, 7 | height: 680, 8 | webPreferences: { 9 | nodeIntegration: true 10 | } 11 | }) 12 | win.loadFile(path.resolve(__dirname, '../../renderer/pages/control/index.html')) 13 | } 14 | 15 | function send(channel, ...args) { 16 | win.webContents.send(channel, ...args) 17 | } 18 | 19 | module.exports = {create, send} 20 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/main/windows/main.js: -------------------------------------------------------------------------------- 1 | const {BrowserWindow} = require('electron') 2 | const isDev = require('electron-is-dev') 3 | 4 | let win 5 | function create () { 6 | win = new BrowserWindow({ 7 | width: 600, 8 | height: 300, 9 | webPreferences: { 10 | nodeIntegration: true 11 | } 12 | }) 13 | 14 | if (isDev) { 15 | win.loadURL('http://localhost:3000') 16 | } else { 17 | // 第三章用到 18 | win.loadFile(path.resolve(__dirname, '../../renderer/pages/main/index.html')) 19 | } 20 | } 21 | 22 | function send(channel, ...args) { 23 | win.webContents.send(channel, ...args) 24 | } 25 | 26 | module.exports = {create, send} 27 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/pages/control/app.js: -------------------------------------------------------------------------------- 1 | const peer = require('./peer-control') 2 | 3 | peer.on('add-stream', (stream) => { 4 | console.log('play stream') 5 | play(stream) 6 | }) 7 | 8 | let video = document.getElementById('screen-video') 9 | function play(stream) { 10 | video.srcObject = stream 11 | video.onloadedmetadata = function() { 12 | video.play() 13 | } 14 | } 15 | 16 | window.onkeydown = function(e) { 17 | // data {keyCode, meta, alt, ctrl, shift} 18 | let data = { 19 | keyCode: e.keyCode, 20 | shift: e.shiftKey, 21 | meta: e.metaKey, 22 | control: e.ctrlKey, 23 | alt: e.altKey 24 | } 25 | peer.emit('robot', 'key', data) 26 | } 27 | 28 | window.onmouseup = function(e) { 29 | // data {clientX, clientY, screen: {width, height}, video: {width, height}} 30 | let data = {} 31 | data.clientX = e.clientX 32 | data.clientY = e.clientY 33 | data.video = { 34 | width: video.getBoundingClientRect().width, 35 | height: video.getBoundingClientRect().height 36 | } 37 | peer.emit('robot', 'mouse', data) 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/pages/control/index.html: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/pages/control/index.js: -------------------------------------------------------------------------------- 1 | const {desktopCapture} = require('electron') 2 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/pages/control/peer-control.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events') 2 | const peer = new EventEmitter() 3 | const {ipcRenderer, desktopCapturer} = require('electron') 4 | const pc = new window.RTCPeerConnection({}) 5 | let dc = pc.createDataChannel('robotchannel', {reliable: false}); 6 | console.log('before-opened', dc) 7 | dc.onopen = function() { 8 | console.log('opened') 9 | peer.on('robot', (type, data) => { 10 | dc.send(JSON.stringify({type, data})) 11 | }) 12 | } 13 | dc.onmessage = function(event) { 14 | console.log('message', event) 15 | } 16 | dc.onerror = (e) => {console.log(e)} 17 | async function createOffer() { 18 | let offer = await pc.createOffer({ 19 | offerToReceiveAudio: false, 20 | offerToReceiveVideo: true 21 | }) 22 | await pc.setLocalDescription(offer) 23 | console.log('create-offer\n', JSON.stringify(pc.localDescription)) 24 | return pc.localDescription 25 | } 26 | createOffer().then((offer) => { 27 | console.log('forward', 'offer', offer) 28 | ipcRenderer.send('forward', 'offer', {type: offer.type, sdp: offer.sdp}) 29 | }) 30 | 31 | ipcRenderer.on('answer', (e, answer) => { 32 | setRemote(answer) 33 | }) 34 | 35 | ipcRenderer.on('candidate', (e, candidate) => { 36 | addIceCandidate(candidate) 37 | }) 38 | 39 | async function setRemote(answer) { 40 | await pc.setRemoteDescription(answer) 41 | console.log('create-answer', pc) 42 | } 43 | window.setRemote = setRemote 44 | 45 | pc.onicecandidate = (e) => { 46 | console.log('candidate', JSON.stringify(e.candidate)) 47 | ipcRenderer.send('forward', 'control-candidate', e.candidate) 48 | // 告知其他人 49 | } 50 | const candidates = [] 51 | async function addIceCandidate(candidate) { 52 | if(!candidate || !candidate.type) return 53 | candidates.push(candidate) 54 | if(pc.remoteDescription && pc.remoteDescription.type) { 55 | for(let i = 0; i < candidates.length; i ++) { 56 | await pc.addIceCandidate(new RTCIceCandidate(candidates[i])) 57 | } 58 | candidates = [] 59 | } 60 | } 61 | window.addIceCandidate = addIceCandidate 62 | 63 | pc.onaddstream = (e) => { 64 | console.log('addstream', e) 65 | peer.emit('add-stream', e.stream) 66 | 67 | } 68 | 69 | 70 | // 先把robot屏蔽 71 | // peer.on('robot', (type, data) => { 72 | // console.log('robot', type, data) 73 | // if(type === 'mouse') { 74 | // data.screen = { 75 | // width: window.screen.width, 76 | // height: window.screen.height 77 | // } 78 | // } 79 | // setTimeout(() => { 80 | // ipcRenderer.send('robot', type, data) 81 | // }, 2000) 82 | // 83 | // }) 84 | module.exports = peer 85 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/pages/control/robot.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/7-11-remote-control/app/renderer/pages/control/robot.js -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `npm run build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/config-overrides.js: -------------------------------------------------------------------------------- 1 | const { override } = require('customize-cra'); 2 | 3 | function addRendererTarget(config) { 4 | config.target = 'electron-renderer' 5 | return config 6 | } 7 | 8 | module.exports = override(addRendererTarget) 9 | 10 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "main", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.4.0", 8 | "@testing-library/user-event": "^7.2.1", 9 | "react": "^16.12.0", 10 | "react-dom": "^16.12.0", 11 | "react-scripts": "3.3.0" 12 | }, 13 | "scripts": { 14 | "start": "BROWSER=none react-app-rewired start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | }, 34 | "devDependencies": { 35 | "customize-cra": "^0.9.1", 36 | "react-app-rewired": "^2.1.5" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/7-11-remote-control/app/renderer/src/main/public/favicon.ico -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/7-11-remote-control/app/renderer/src/main/public/logo192.png -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 2/7-11-remote-control/app/renderer/src/main/public/logo512.png -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/App.js: -------------------------------------------------------------------------------- 1 | import React, {useState, useEffect} from 'react'; 2 | import './App.css'; 3 | import {ipcRenderer} from 'electron' 4 | import './peer-puppet' 5 | 6 | function App() { 7 | const [remoteCode, setRemoteCode] = useState(''); 8 | const [localCode, setLocalCode] = useState(''); 9 | // 0未连接,1已控制,2被控制 10 | const [controlText, setControlText] = useState(''); 11 | 12 | const startControl = (remoteCode) => { 13 | ipcRenderer.send('control', remoteCode) 14 | } 15 | const login = async () => { 16 | let code = await ipcRenderer.invoke('login') 17 | setLocalCode(code) 18 | } 19 | 20 | const handleControlState = (e, name, type) => { 21 | let text = '' 22 | if(type === 1) { 23 | text = `正在远程控制${name}` 24 | } else if(type === 2) { 25 | text = `被${name}控制中` 26 | } else { 27 | text = '' 28 | } 29 | setControlText(text) 30 | } 31 | 32 | useEffect(() => { 33 | login() 34 | ipcRenderer.on('control-state-change', handleControlState) 35 | return () => { 36 | ipcRenderer.removeListener('control-state-change', handleControlState) 37 | } 38 | }, []) 39 | 40 | return ( 41 |
42 | { 43 | controlText === '' ? <> 44 |
你的控制码{localCode}
45 | setRemoteCode(e.target.value)}/> 46 | 47 | :
{controlText}
48 | } 49 |
50 | ); 51 | } 52 | 53 | export default App; 54 | 55 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/peer-puppet.js: -------------------------------------------------------------------------------- 1 | import EventEmitter from 'events' 2 | import {ipcRenderer, desktopCapturer} from 'electron' 3 | let peer = new EventEmitter() 4 | window.peer = peer // 为了直接模拟过程,信令结束后,会删掉 5 | ipcRenderer.on('offer', (e, offer) => { 6 | console.log('init pc', offer) 7 | const pc = new window.RTCPeerConnection(); 8 | 9 | pc.ondatachannel = (e) => { 10 | console.log('data', e) 11 | e.channel.onmessage = (e) => { 12 | console.log('onmessage', e, JSON.parse(e.data)) 13 | let {type, data} = JSON.parse(e.data) 14 | console.log('robot', type, data) 15 | if(type === 'mouse') { 16 | data.screen = { 17 | width: window.screen.width, 18 | height: window.screen.height 19 | } 20 | } 21 | ipcRenderer.send('robot', type, data) 22 | } 23 | } 24 | 25 | async function getScreenStream() { 26 | const sources = await desktopCapturer.getSources({types: ['screen']}) 27 | return new Promise((resolve, reject) => { 28 | navigator.webkitGetUserMedia({ 29 | audio: false, 30 | video: { 31 | mandatory: { 32 | chromeMediaSource: 'desktop', 33 | chromeMediaSourceId: sources[0].id, 34 | maxWidth: window.screen.width, 35 | maxHeight: window.screen.height 36 | } 37 | } 38 | }, (stream) => { 39 | console.log('add-stream', stream) 40 | resolve(stream) 41 | }, reject) 42 | }) 43 | } 44 | 45 | pc.onicecandidate = (e) => { 46 | // 告知其他人 47 | ipcRenderer.send('forward', 'puppet-candidate', e.candidate) 48 | } 49 | 50 | async function addIceCandidate(candidate) { 51 | if(!candidate || !candidate.type) return 52 | await pc.addIceCandidate(new RTCIceCandidate(candidate)) 53 | } 54 | window.addIceCandidate = addIceCandidate 55 | 56 | async function createAnswer(offer) { 57 | let stream = await getScreenStream() 58 | pc.addStream(stream) 59 | await pc.setRemoteDescription(offer); 60 | await pc.setLocalDescription(await pc.createAnswer()); 61 | console.log('create answer \n', JSON.stringify(pc.localDescription)) 62 | // send answer 63 | return pc.localDescription 64 | } 65 | createAnswer(offer).then((answer) => { 66 | ipcRenderer.send('forward', 'answer', {type: answer.type, sdp: answer.sdp}) 67 | }) 68 | 69 | }) 70 | export default peer 71 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' } 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready.then(registration => { 134 | registration.unregister(); 135 | }); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/app/renderer/src/main/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /Chapter 2/7-11-remote-control/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "remote-control", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app/main/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "concurrently \"npm run start:render\" \"wait-on http://localhost:3000 && npm run start:main\" ", 9 | "start:main": "electron .", 10 | "start:render": "cd app/renderer/src/main && npm start" 11 | }, 12 | "keywords": [], 13 | "author": "", 14 | "license": "ISC", 15 | "devDependencies": { 16 | "concurrently": "^5.0.2", 17 | "electron": "^7.1.8", 18 | "electron-rebuild": "^1.8.8", 19 | "wait-on": "^3.3.0" 20 | }, 21 | "dependencies": { 22 | "electron-is-dev": "^1.1.0", 23 | "robotjs": "^0.6.0", 24 | "vkey": "^1.0.1", 25 | "ws": "^7.2.1" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | release/* 3 | app/renderer/pages/main/ 4 | .DS_Store 5 | **/**/.DS_Store 6 | 7 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/crash-reporter.js: -------------------------------------------------------------------------------- 1 | const {crashReporter} = require('electron') 2 | 3 | function init() { 4 | crashReporter.start({ 5 | productName: 'Mercurius', 6 | companyName: 'geektime', 7 | submitURL: 'http://127.0.0.1:33855/crash', 8 | 9 | }) 10 | } 11 | module.exports = {init} 12 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/index.js: -------------------------------------------------------------------------------- 1 | const {app, BrowserWindow} = require('electron') const path = require('path') 2 | const isDev = require('electron-is-dev') 3 | const handleIPC = require('./ipc') 4 | const {create: createMainWindow, show: showMainWindow, close: closeMainWindow} = require('./windows/main') 5 | // const {create: createControlWindow} = require('./windows/control') 6 | if(require('electron-squirrel-startup')) app.quit() 7 | const gotTheLock = app.requestSingleInstanceLock() 8 | if (!gotTheLock) { 9 | app.quit() 10 | } else { 11 | app.on('second-instance', (event, commandLine, workingDirectory) => { 12 | // 当运行第二个实例时,将会聚焦到myWindow这个窗口 13 | showMainWindow() 14 | }) 15 | app.on('will-finish-launching', () => { 16 | if(!isDev) { 17 | require('./updater.js') 18 | } 19 | require('./crash-reporter').init() 20 | }) 21 | // 创建 myWindow, 加载应用的其余部分, etc... 22 | app.on('ready', () => { 23 | // createControlWindow() 24 | app.fp = require('geektime-fringerprint-example').getFringerprint() 25 | createMainWindow() 26 | handleIPC() 27 | require('./trayAndMenu') 28 | require('./robot.js')() 29 | }) 30 | 31 | app.on('activate', () => { 32 | // process.crash() 33 | showMainWindow() 34 | }) 35 | 36 | app.on('before-quit', () => { 37 | closeMainWindow() 38 | }) 39 | } 40 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/ipc.js: -------------------------------------------------------------------------------- 1 | const {ipcMain, clipboard} = require('electron') 2 | const {create: createControlWindow, send: sendControlWindow} = require('./windows/control') 3 | const {send: sendMainWindow} = require('./windows/main') 4 | const signal = require('./signal') 5 | 6 | module.exports = function () { 7 | ipcMain.handle('login', async () => { 8 | let {code} = await signal.invoke('login', null, 'logined') 9 | return code 10 | }) 11 | ipcMain.on('control', async (e, remote) => { 12 | // 这里是跟服务端的交互,成功后我们会唤起面板 13 | signal.send('control', {remote}) 14 | }) 15 | ipcMain.on('share-to-wechat', async (e, code) => { 16 | if(code) { 17 | clipboard.writeText(code.toString()) 18 | } 19 | require('./dll/activate-window').showWeChat() 20 | }) 21 | 22 | signal.on('controlled', (data) => { 23 | sendMainWindow('control-state-change', data.remote, 1) 24 | createControlWindow() 25 | }) 26 | 27 | signal.on('be-controlled', (data) => { 28 | sendMainWindow('control-state-change', data.remote, 2) 29 | }) 30 | 31 | // puppet、control共享的信道,就是转发 32 | ipcMain.on('forward', (e, event, data) => { 33 | signal.send('forward', {event, data}) 34 | }) 35 | 36 | // 收到offer,puppet响应 37 | signal.on('offer', (data) => { 38 | sendMainWindow('offer', data) 39 | }) 40 | 41 | // 收到puppet证书,answer响应 42 | signal.on('answer', (data) => { 43 | sendControlWindow('answer', data) 44 | }) 45 | 46 | // 收到control证书,puppet响应 47 | signal.on('puppet-candidate', (data) => { 48 | sendControlWindow('candidate', data) 49 | }) 50 | 51 | // 收到puppet证书,control响应 52 | signal.on('control-candidate', (data) => { 53 | sendMainWindow('candidate', data) 54 | }) 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/robot.js: -------------------------------------------------------------------------------- 1 | const {ipcMain} = require('electron') 2 | const robot = require('robotjs') 3 | const vkey = require('vkey') 4 | 5 | function handleMouse(data) { 6 | let {clientX, clientY, screen, video} = data 7 | // data {clientX, clientY, screen: {width, height}, video: {width, height}} 8 | let x = clientX * screen.width / video.width 9 | let y = clientY * screen.height / video.height 10 | console.log(x, y) 11 | robot.moveMouse(x, y) 12 | robot.mouseClick() 13 | } 14 | 15 | function handleKey(data) { 16 | // data {keyCode, meta, alt, ctrl, shift} 17 | const modifiers = [] 18 | if(data.meta) modifiers.push('meta') 19 | if(data.shift) modifiers.push('shift') 20 | if(data.alt) modifiers.push('alt') 21 | if(data.ctrl) modifiers.push('ctrl') 22 | let key = vkey[data.keyCode].toLowerCase() 23 | if(key[0] !== '<') { // 24 | robot.keyTap(key, modifiers) 25 | } 26 | } 27 | 28 | module.exports = function() { 29 | ipcMain.on('robot', (e, type, data) => { 30 | console.log('handle', type, data) 31 | if(type === 'mouse') { 32 | handleMouse(data) 33 | } else if(type === 'key') { 34 | handleKey(data) 35 | } 36 | }) 37 | } 38 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/signal.js: -------------------------------------------------------------------------------- 1 | const WebSocket = require('ws'); 2 | const EventEmitter = require('events'); 3 | const signal = new EventEmitter(); 4 | 5 | const ws = new WebSocket('ws://111.231.59.178:8010'); 6 | ws.on('open', function open() { 7 | console.log('connect success') 8 | }) 9 | 10 | ws.on('message', function incoming(message) { 11 | let data = JSON.parse(message) 12 | console.log('data', data, message); 13 | signal.emit(data.event, data.data) 14 | }) 15 | 16 | 17 | function send(event, data) { 18 | console.log('sended', JSON.stringify({event, data})) 19 | ws.send(JSON.stringify({event, data})) 20 | } 21 | 22 | function invoke(event, data, answerEvent) { 23 | return new Promise((resolve, reject) => { 24 | send(event, data) 25 | signal.once(answerEvent, resolve) 26 | setTimeout(() => { 27 | reject('timeout') 28 | }, 5000) 29 | }) 30 | } 31 | signal.send = send 32 | signal.invoke = invoke 33 | 34 | module.exports = signal 35 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/trayAndMenu/darwin.js: -------------------------------------------------------------------------------- 1 | const { app, Menu, Tray } = require('electron') 2 | const {create: createAboutWindow}= require('../windows/about') 3 | const path = require('path') 4 | const {show: showMainWindow, close: closeMainWindow} = require('../windows/main') 5 | let tray; 6 | 7 | function setTray() { 8 | tray = new Tray(path.resolve(__dirname, './icon_darwin.png')) 9 | tray.on('click', () => { 10 | console.log('click') 11 | showMainWindow() 12 | }) 13 | tray.on('right-click', () => { 14 | const contextMenu = Menu.buildFromTemplate([ 15 | { label: '显示', click: () => {showMainWindow()}}, 16 | { label: '退出', click: () => {app.quit()}} 17 | ]) 18 | tray.popUpContextMenu(contextMenu) 19 | }) 20 | tray.on('drop-files', (e, files) => { 21 | console.log('files', files) 22 | }) 23 | tray.on('drop-text', (e, text) => { 24 | console.log('text', text) 25 | 26 | }) 27 | } 28 | 29 | function setAppMenu() { 30 | let appMenu = Menu.buildFromTemplate([ 31 | { 32 | label: app.name, 33 | submenu: [ 34 | { 35 | label: 'About', 36 | click: createAboutWindow 37 | }, 38 | { type: 'separator' }, 39 | { role: 'services' }, 40 | { type: 'separator' }, 41 | { role: 'hide' }, 42 | { role: 'hideothers' }, 43 | { role: 'unhide' }, 44 | { type: 'separator' }, 45 | { role: 'quit' } 46 | ], 47 | 48 | }, 49 | { role: 'fileMenu' }, 50 | { role: 'windowMenu' }, 51 | { role: 'editMenu' } 52 | ]); 53 | app.applicationMenu = appMenu; 54 | } 55 | app.whenReady().then(() => { 56 | setTray() 57 | setAppMenu() 58 | }) 59 | 60 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/trayAndMenu/icon_darwin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/main/trayAndMenu/icon_darwin.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/trayAndMenu/icon_darwin@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/main/trayAndMenu/icon_darwin@2x.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/trayAndMenu/icon_win32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/main/trayAndMenu/icon_win32.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/trayAndMenu/icon_win32@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/main/trayAndMenu/icon_win32@2x.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/trayAndMenu/index.js: -------------------------------------------------------------------------------- 1 | if(process.platform === 'darwin') { 2 | require('./darwin.js') 3 | } else if(process.platform === 'win32') { 4 | require('./win32.js') 5 | } else { 6 | // 不处理 7 | } 8 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/trayAndMenu/win32.js: -------------------------------------------------------------------------------- 1 | const { app, Menu, Tray } = require('electron') 2 | const path = require('path') 3 | const {show: showMainWindow} = require('../windows/main') 4 | const {create: createAboutWindow}= require('../windows/about') 5 | 6 | let tray; 7 | app.whenReady().then(() => { 8 | tray = new Tray(path.resolve(__dirname, './icon_win32.png')) 9 | const contextMenu = Menu.buildFromTemplate([ 10 | { label: '打开' + app.name, click: showMainWindow}, 11 | { label: '关于' + app.name, click: createAboutWindow}, 12 | { type: 'separator' }, 13 | { label: '退出', click: () => {app.quit()}} 14 | ]) 15 | tray.setContextMenu(contextMenu) 16 | menu = Menu.buildFromTemplate([]) 17 | app.applicationMenu = menu; 18 | }) 19 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/updater.js: -------------------------------------------------------------------------------- 1 | const {autoUpdater, app, dialog} = require('electron') 2 | if(process.platform == 'darwin') { 3 | autoUpdater.setFeedURL('http://127.0.0.1:33855/darwin?version=' + app.getVersion()) 4 | } else { 5 | autoUpdater.setFeedURL('http://127.0.0.1:33855/win32?version=' + app.getVersion()) 6 | } 7 | 8 | autoUpdater.checkForUpdates() // 定时轮训、服务端推送 9 | autoUpdater.on('update-available', () => { 10 | console.log('update-available') 11 | }) 12 | 13 | autoUpdater.on('update-downloaded', (e, notes, version) => { 14 | // 提醒用户更新 15 | app.whenReady().then(() => { 16 | let clickId = dialog.showMessageBoxSync({ 17 | type: 'info', 18 | title: '升级提示', 19 | message: '已为你升级到最新版,是否立即体验', 20 | buttons: ['马上升级', '手动重启'], 21 | cancelId: 1, 22 | }) 23 | if(clickId === 0) { 24 | autoUpdater.quitAndInstall() 25 | app.quit() 26 | } 27 | }) 28 | }) 29 | 30 | autoUpdater.on('error', (err) => { 31 | console.log('error', err) 32 | }) 33 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/windows/about.js: -------------------------------------------------------------------------------- 1 | const openAboutWindow = require('about-window').default; 2 | const path = require('path') 3 | const create = () => openAboutWindow({ 4 | icon_path: path.join(__dirname, 'icon.png'), 5 | package_json_dir: path.resolve(__dirname + '/../../../'), 6 | copyright: 'Copyright (c) 2020 dragon', 7 | homepage: 'https://github.com/dengyaolong/geektime-electron', 8 | bug_report_url: 'https://github.com/dengyaolong/geektime-electron/issues', 9 | }) 10 | module.exports = {create} 11 | 12 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/windows/control.js: -------------------------------------------------------------------------------- 1 | const {BrowserWindow} = require('electron') 2 | const path = require('path') 3 | let win 4 | function create() { 5 | win = new BrowserWindow({ 6 | width: 1000, 7 | height: 680, 8 | webPreferences: { 9 | nodeIntegration: true 10 | } 11 | }) 12 | win.loadFile(path.resolve(__dirname, '../../renderer/pages/control/index.html')) 13 | } 14 | 15 | function send(channel, ...args) { 16 | win.webContents.send(channel, ...args) 17 | } 18 | 19 | module.exports = {create, send} 20 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/windows/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/main/windows/icon.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/main/windows/main.js: -------------------------------------------------------------------------------- 1 | const {BrowserWindow} = require('electron') 2 | const isDev = require('electron-is-dev') 3 | const path = require('path') 4 | 5 | let win 6 | let willQuitApp = false 7 | function create () { 8 | win = new BrowserWindow({ 9 | width: 600, 10 | height: 300, 11 | webPreferences: { 12 | nodeIntegration: true 13 | }, 14 | show: false, 15 | }) 16 | 17 | win.on('close', (e) => { 18 | if (willQuitApp) { 19 | win = null; 20 | } else { 21 | e.preventDefault(); 22 | win.hide(); 23 | } 24 | }) 25 | 26 | win.on('ready-to-show', () => { 27 | win.show() 28 | }) 29 | 30 | if (isDev) { 31 | win.loadURL('http://localhost:3000') 32 | } else { 33 | // 第三章用到 34 | win.loadFile(path.resolve(__dirname, '../../renderer/pages/main/index.html')) 35 | } 36 | 37 | } 38 | 39 | function send(channel, ...args) { 40 | win.webContents.send(channel, ...args) 41 | } 42 | function show() { 43 | if (win.isMinimized()) win.restore() 44 | win.show() 45 | } 46 | 47 | function close() { 48 | willQuitApp = true 49 | win.close() 50 | } 51 | 52 | module.exports = {create, send, show, close} 53 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/pages/control/app.js: -------------------------------------------------------------------------------- 1 | const peer = require('./peer-control') 2 | 3 | peer.on('add-stream', (stream) => { 4 | console.log('play stream') 5 | play(stream) 6 | }) 7 | 8 | let video = document.getElementById('screen-video') 9 | function play(stream) { 10 | video.srcObject = stream 11 | video.onloadedmetadata = function() { 12 | video.play() 13 | } 14 | } 15 | 16 | window.onkeydown = function(e) { 17 | // data {keyCode, meta, alt, ctrl, shift} 18 | let data = { 19 | keyCode: e.keyCode, 20 | shift: e.shiftKey, 21 | meta: e.metaKey, 22 | control: e.ctrlKey, 23 | alt: e.altKey 24 | } 25 | peer.emit('robot', 'key', data) 26 | } 27 | 28 | window.onmouseup = function(e) { 29 | // data {clientX, clientY, screen: {width, height}, video: {width, height}} 30 | let data = {} 31 | data.clientX = e.clientX 32 | data.clientY = e.clientY 33 | data.video = { 34 | width: video.getBoundingClientRect().width, 35 | height: video.getBoundingClientRect().height 36 | } 37 | peer.emit('robot', 'mouse', data) 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/pages/control/index.html: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/pages/control/index.js: -------------------------------------------------------------------------------- 1 | const {desktopCapture} = require('electron') 2 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/pages/control/peer-control.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events') 2 | const peer = new EventEmitter() 3 | const {ipcRenderer, desktopCapturer} = require('electron') 4 | const pc = new window.RTCPeerConnection({}) 5 | let dc = pc.createDataChannel('robotchannel', {reliable: false}); 6 | console.log('before-opened', dc) 7 | dc.onopen = function() { 8 | console.log('opened') 9 | peer.on('robot', (type, data) => { 10 | dc.send(JSON.stringify({type, data})) 11 | }) 12 | } 13 | dc.onmessage = function(event) { 14 | console.log('message', event) 15 | } 16 | dc.onerror = (e) => {console.log(e)} 17 | async function createOffer() { 18 | let offer = await pc.createOffer({ 19 | offerToReceiveAudio: false, 20 | offerToReceiveVideo: true 21 | }) 22 | await pc.setLocalDescription(offer) 23 | console.log('create-offer\n', JSON.stringify(pc.localDescription)) 24 | return pc.localDescription 25 | } 26 | createOffer().then((offer) => { 27 | console.log('forward', 'offer', offer) 28 | ipcRenderer.send('forward', 'offer', {type: offer.type, sdp: offer.sdp}) 29 | }) 30 | 31 | ipcRenderer.on('answer', (e, answer) => { 32 | setRemote(answer) 33 | }) 34 | 35 | ipcRenderer.on('candidate', (e, candidate) => { 36 | addIceCandidate(candidate) 37 | }) 38 | 39 | async function setRemote(answer) { 40 | await pc.setRemoteDescription(answer) 41 | console.log('create-answer', pc) 42 | } 43 | window.setRemote = setRemote 44 | 45 | pc.onicecandidate = (e) => { 46 | console.log('candidate', JSON.stringify(e.candidate)) 47 | ipcRenderer.send('forward', 'control-candidate', e.candidate) 48 | // 告知其他人 49 | } 50 | const candidates = [] 51 | async function addIceCandidate(candidate) { 52 | if(!candidate || !candidate.type) return 53 | candidates.push(candidate) 54 | if(pc.remoteDescription && pc.remoteDescription.type) { 55 | for(let i = 0; i < candidates.length; i ++) { 56 | await pc.addIceCandidate(new RTCIceCandidate(candidates[i])) 57 | } 58 | candidates = [] 59 | } 60 | } 61 | window.addIceCandidate = addIceCandidate 62 | 63 | pc.onaddstream = (e) => { 64 | console.log('addstream', e) 65 | peer.emit('add-stream', e.stream) 66 | 67 | } 68 | 69 | 70 | // 先把robot屏蔽 71 | // peer.on('robot', (type, data) => { 72 | // console.log('robot', type, data) 73 | // if(type === 'mouse') { 74 | // data.screen = { 75 | // width: window.screen.width, 76 | // height: window.screen.height 77 | // } 78 | // } 79 | // setTimeout(() => { 80 | // ipcRenderer.send('robot', type, data) 81 | // }, 2000) 82 | // 83 | // }) 84 | module.exports = peer 85 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/pages/control/robot.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/renderer/pages/control/robot.js -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `npm run build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/build.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs-extra') 2 | const dest = '../../pages/main' 3 | fs.removeSync(dest) 4 | fs.moveSync('./build', '../../pages/main') 5 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/config-overrides.js: -------------------------------------------------------------------------------- 1 | const { override } = require('customize-cra'); 2 | 3 | function addRendererTarget(config) { 4 | config.target = 'electron-renderer' 5 | return config 6 | } 7 | 8 | module.exports = override(addRendererTarget) 9 | 10 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "main", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.4.0", 8 | "@testing-library/user-event": "^7.2.1", 9 | "fs-extra": "^8.1.0", 10 | "react": "^16.12.0", 11 | "react-dom": "^16.12.0", 12 | "react-scripts": "3.3.0" 13 | }, 14 | "scripts": { 15 | "start": "BROWSER=none react-app-rewired start", 16 | "build": "react-app-rewired build", 17 | "postbuild": "node ./build.js", 18 | "test": "react-scripts test", 19 | "eject": "react-scripts eject" 20 | }, 21 | "eslintConfig": { 22 | "extends": "react-app" 23 | }, 24 | "browserslist": { 25 | "production": [ 26 | ">0.2%", 27 | "not dead", 28 | "not op_mini all" 29 | ], 30 | "development": [ 31 | "last 1 chrome version", 32 | "last 1 firefox version", 33 | "last 1 safari version" 34 | ] 35 | }, 36 | "homepage": "./", 37 | "devDependencies": { 38 | "cross-env": "^7.0.0", 39 | "customize-cra": "^0.9.1", 40 | "react-app-rewired": "^2.1.5" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/renderer/src/main/public/favicon.ico -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/renderer/src/main/public/logo192.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/app/renderer/src/main/public/logo512.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/App.js: -------------------------------------------------------------------------------- 1 | import React, {useState, useEffect} from 'react'; 2 | import './App.css'; 3 | import {ipcRenderer, remote} from 'electron' 4 | import './peer-puppet' 5 | 6 | function App() { 7 | const [remoteCode, setRemoteCode] = useState(''); 8 | const [localCode, setLocalCode] = useState(''); 9 | // 0未连接,1已控制,2被控制 10 | const [controlText, setControlText] = useState(''); 11 | 12 | const startControl = (remoteCode) => { 13 | ipcRenderer.send('control', remoteCode) 14 | } 15 | const login = async () => { 16 | let code = await ipcRenderer.invoke('login') 17 | setLocalCode(code) 18 | } 19 | 20 | const handleControlState = (e, name, type) => { 21 | let text = '' 22 | if(type === 1) { 23 | text = `正在远程控制${name}` 24 | } else if(type === 2) { 25 | text = `被${name}控制中` 26 | } else { 27 | text = '' 28 | } 29 | setControlText(text) 30 | } 31 | 32 | useEffect(() => { 33 | login() 34 | ipcRenderer.on('control-state-change', handleControlState) 35 | return () => { 36 | ipcRenderer.removeListener('control-state-change', handleControlState) 37 | } 38 | }, []) 39 | 40 | const handleContextMenu = (e) => { 41 | e.preventDefault() 42 | const { Menu, MenuItem } = remote 43 | const menu = new Menu() 44 | menu.append(new MenuItem({ label: '复制', role: 'copy' })) 45 | menu.append(new MenuItem({ label: '分享到微信', click: (menuItem, win, keyboardEvent)=>{ 46 | ipcRenderer.send('share-to-wechat', localCode) 47 | }})) 48 | menu.popup() 49 | } 50 | 51 | return ( 52 |
53 | { 54 | controlText === '' ? <> 55 |
你的控制码 handleContextMenu(e)}> {localCode}
56 | setRemoteCode(e.target.value)}/> 57 | 58 | :
{controlText}
59 | } 60 |
61 | ); 62 | } 63 | 64 | export default App; 65 | 66 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/peer-puppet.js: -------------------------------------------------------------------------------- 1 | import EventEmitter from 'events' 2 | import {ipcRenderer, desktopCapturer} from 'electron' 3 | let peer = new EventEmitter() 4 | window.peer = peer // 为了直接模拟过程,信令结束后,会删掉 5 | ipcRenderer.on('offer', (e, offer) => { 6 | console.log('init pc', offer) 7 | const pc = new window.RTCPeerConnection(); 8 | 9 | pc.ondatachannel = (e) => { 10 | console.log('data', e) 11 | e.channel.onmessage = (e) => { 12 | console.log('onmessage', e, JSON.parse(e.data)) 13 | let {type, data} = JSON.parse(e.data) 14 | console.log('robot', type, data) 15 | if(type === 'mouse') { 16 | data.screen = { 17 | width: window.screen.width, 18 | height: window.screen.height 19 | } 20 | } 21 | ipcRenderer.send('robot', type, data) 22 | } 23 | } 24 | 25 | async function getScreenStream() { 26 | const sources = await desktopCapturer.getSources({types: ['screen']}) 27 | return new Promise((resolve, reject) => { 28 | navigator.webkitGetUserMedia({ 29 | audio: false, 30 | video: { 31 | mandatory: { 32 | chromeMediaSource: 'desktop', 33 | chromeMediaSourceId: sources[0].id, 34 | maxWidth: window.screen.width, 35 | maxHeight: window.screen.height 36 | } 37 | } 38 | }, (stream) => { 39 | console.log('add-stream', stream) 40 | resolve(stream) 41 | }, reject) 42 | }) 43 | } 44 | 45 | pc.onicecandidate = (e) => { 46 | // 告知其他人 47 | ipcRenderer.send('forward', 'puppet-candidate', e.candidate) 48 | } 49 | 50 | async function addIceCandidate(candidate) { 51 | if(!candidate || !candidate.type) return 52 | await pc.addIceCandidate(new RTCIceCandidate(candidate)) 53 | } 54 | window.addIceCandidate = addIceCandidate 55 | 56 | async function createAnswer(offer) { 57 | let stream = await getScreenStream() 58 | pc.addStream(stream) 59 | await pc.setRemoteDescription(offer); 60 | await pc.setLocalDescription(await pc.createAnswer()); 61 | console.log('create answer \n', JSON.stringify(pc.localDescription)) 62 | // send answer 63 | return pc.localDescription 64 | } 65 | createAnswer(offer).then((answer) => { 66 | ipcRenderer.send('forward', 'answer', {type: answer.type, sdp: answer.sdp}) 67 | }) 68 | 69 | }) 70 | export default peer 71 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' } 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready.then(registration => { 134 | registration.unregister(); 135 | }); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/app/renderer/src/main/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Mercurius", 3 | "version": "1.0.0", 4 | "description": "remote control", 5 | "main": "app/main/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "concurrently \"npm run start:render\" \"wait-on http://localhost:3000 && npm run start:main\" ", 9 | "start:main": "electron .", 10 | "start:render": "cd app/renderer/src/main && npm start", 11 | "build": "cd app/renderer/src/main && npm run build", 12 | "pack:mac": "npm run build && NPM_CONFIG_ELECTRON_MIRROR=http://npm.taobao.org/mirrors/electron/ electron-builder build --mac", 13 | "pack:wi": "npm run build && cross-env NPM_CONFIG_ELECTRON_MIRROR=http://npm.taobao.org/mirrors/electron/ electron-builder build --win --ia32", 14 | "pack:win": " cross-env NPM_CONFIG_ELECTRON_MIRROR=http://npm.taobao.org/mirrors/electron/ electron-builder build --win --ia32", 15 | "postinstall": "electron-builder install-app-deps" 16 | }, 17 | "keywords": [], 18 | "author": "dragon", 19 | "license": "ISC", 20 | "devDependencies": { 21 | "concurrently": "^5.0.2", 22 | "cross-env": "^7.0.0", 23 | "electron": "^7.1.8", 24 | "electron-builder": "^22.3.2", 25 | "electron-builder-squirrel-windows": "^22.3.3", 26 | "wait-on": "^3.3.0" 27 | }, 28 | "dependencies": { 29 | "about-window": "^1.13.2", 30 | "electron-is-dev": "^1.1.0", 31 | "electron-squirrel-startup": "^1.0.0", 32 | "robotjs": "^0.6.0", 33 | "vkey": "^1.0.1", 34 | "ws": "^7.2.1" 35 | }, 36 | "build": { 37 | "appId": "com.geektime.mercurius", 38 | "productName": "Mercurius", 39 | "files": "app", 40 | "asar": false, 41 | "extraFiles": [ 42 | "app/renderer/**/src" 43 | ], 44 | "directories": { 45 | "buildResources": "resource", 46 | "output": "release" 47 | }, 48 | "copyright": "Copyright © 2020 dragon", 49 | "mac": { 50 | "target": [ 51 | "dmg", 52 | "zip" 53 | ], 54 | "icon": "resources/icon.icns" 55 | }, 56 | "dmg": { 57 | "background": "resources/background.png", 58 | "window": { 59 | "width": 540, 60 | "height": 380 61 | }, 62 | "contents": [ 63 | { 64 | "x": 410, 65 | "y": 180, 66 | "type": "link", 67 | "path": "/Applications" 68 | }, 69 | { 70 | "x": 130, 71 | "y": 180, 72 | "type": "file" 73 | } 74 | ], 75 | "iconSize": 128 76 | }, 77 | "win": { 78 | "icon": "resources/icon.ico", 79 | "target": [ 80 | "squirrel", 81 | "nsis" 82 | ] 83 | }, 84 | "nsis": { 85 | "oneClick": false, 86 | "language": "2052", 87 | "perMachine": true, 88 | "allowToChangeInstallationDirectory": true 89 | }, 90 | "squirrelWindows": { 91 | "iconUrl": "https://raw.githubusercontent.com/dengyaolong/geektime-electron/master/img/icon.ico" 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Chapter 3/remote-control/resources/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/resources/background.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/resources/background@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/resources/background@2x.png -------------------------------------------------------------------------------- /Chapter 3/remote-control/resources/icon.icns: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/resources/icon.icns -------------------------------------------------------------------------------- /Chapter 3/remote-control/resources/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/resources/icon.ico -------------------------------------------------------------------------------- /Chapter 3/remote-control/resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/remote-control/resources/icon.png -------------------------------------------------------------------------------- /Chapter 3/updater-server/index.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa') 2 | const app = new Koa() 3 | const Router = require('koa-router') 4 | const serve = require('koa-static-server') 5 | const router = new Router() 6 | const compareVersions = require('compare-versions') 7 | const multer = require('koa-multer') 8 | const uploadCrash = multer({dest: 'crash/'}) 9 | router.post('/crash', uploadCrash.single('upload_file_minidump'), (ctx, next) => { 10 | console.log(ctx.req.body) 11 | // 存DB 12 | }) 13 | function getNewVersion(version) { 14 | if(!version) return null 15 | let maxVersion = { 16 | name: '1.0.1', 17 | pub_date: '2020-02-01T12:26:53+1:00', 18 | notes: '新增功能AAA', 19 | url: `http://127.0.0.1:33855/public/Mercurius-1.0.1-mac.zip` 20 | } 21 | if(compareVersions.compare(maxVersion.name , version, '>')) { 22 | return maxVersion 23 | } 24 | return null 25 | } 26 | router.get('/win32/RELEASES', (ctx, next) => { 27 | let newVersion = getNewVersion(ctx.query.version) 28 | if(newVersion) { 29 | ctx.body='BBC6F98A5CD32C675AAB6737A5F67176248B900C Mercurius-1.0.1-full.nupkg 62177782' 30 | } else { 31 | ctx.status = 204 32 | } 33 | }) 34 | router.get('/win32/*.nupkg', (ctx, next) => { 35 | // redirect s3 静态文件服务 36 | ctx.redirect(`/public/${ctx.params[0]}.nupkg`) 37 | }) 38 | router.get('/darwin', (ctx, next) => { 39 | // 处理Mac更新, ?version=1.0.0&uid=123 40 | let {version} = ctx.query 41 | let newVersion = getNewVersion(version) 42 | if(newVersion) { 43 | ctx.body = newVersion 44 | } else { 45 | ctx.status = 204 46 | } 47 | }) 48 | app.use(serve({rootDir: 'public', rootPath: '/public'})) 49 | app.use(router.routes()) 50 | .use(router.allowedMethods()) 51 | 52 | app.listen(33855) 53 | -------------------------------------------------------------------------------- /Chapter 3/updater-server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "updater-server", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "compare-versions": "^3.5.1", 14 | "koa": "^2.11.0", 15 | "koa-multer": "^1.0.2", 16 | "koa-router": "^8.0.7", 17 | "koa-static-server": "^1.4.0" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter 3/updater-server/public/Mercurius-1.0.1-full.nupkg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/updater-server/public/Mercurius-1.0.1-full.nupkg -------------------------------------------------------------------------------- /Chapter 3/updater-server/public/Mercurius-1.0.1-mac.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/Chapter 3/updater-server/public/Mercurius-1.0.1-mac.zip -------------------------------------------------------------------------------- /Chapter 3/updater-server/public/RELEASES: -------------------------------------------------------------------------------- 1 | BBC6F98A5CD32C675AAB6737A5F67176248B900C Mercurius-1.0.1-full.nupkg 62177782 -------------------------------------------------------------------------------- /PDF/Electron 基础篇.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/PDF/Electron 基础篇.pdf -------------------------------------------------------------------------------- /PDF/Electron 实战篇 .pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/PDF/Electron 实战篇 .pdf -------------------------------------------------------------------------------- /PDF/Electron 工程篇.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/PDF/Electron 工程篇.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # geektime-electron 2 | 极客时间视频课程《Electron开发实战》课件及源码 3 | 4 | 5 | # 快速入口 6 | * [视频教程 📺](https://time.geekbang.org/course/intro/269) 7 | * [课程课件 📚](https://github.com/dengyaolong/geektime-electron/tree/master/PDF) 8 | * [番茄钟 🍅 ](https://github.com/dengyaolong/geektime-electron/tree/master/Chapter%201/8-pomodoro-homework) 9 | * [心形曲线 💝 ](https://github.com/dengyaolong/geektime-electron/tree/master/Chapter%202/4-robot-heart) 10 | 11 | # 课程内容大纲 12 | ![image1](/Chapter%201/2-content-roadmap.png) 13 | 14 | # [学习路线 🛣️](https://github.com/dengyaolong/geektime-electron/tree/master/ROADMAP.md) 15 | ### 基础部分 16 | * quick-start https://electronjs.org/docs/tutorial/first-app 17 | * 基本架构 https://electronjs.org/docs/tutorial/application-architecture#main-and-renderer-processes 18 | * 写得很好的基础介绍 http://jlord.us/essential-electron/ 19 | * 掌握Electron模块。重点包括:app、BrowserWindow、ipcMain、Menu、Tray、ipcRenderer、Notification、clipboard 20 | * 通过api-demos可以快速看到效果 https://github.com/electron/electron-api-demos 21 | * 查看文档 https://electronjs.org/docs 22 | 23 | ### 工程部分 24 | * 选择一个合适的模板 25 | * react https://github.com/electron-react-boilerplate/electron-react-boilerplate 26 | * vue https://github.com/SimulatedGREG/electron-vue 27 | * svelet https://github.com/Rich-Harris/svelte-template-electron 28 | * 纯JS https://github.com/dengyaolong/electron-boilerplate 29 | * 更新 https://electronjs.org/docs/tutorial/updates 30 | * 监控 https://electronjs.org/docs/api/crash-reporter 31 | * 打包 & 分发 https://electronjs.org/docs/tutorial/application-distribution 32 | * 安全 https://electronjs.org/docs/tutorial/security 33 | * 单测 https://electronjs.org/docs/tutorial/automated-testing-with-a-custom-driver 34 | * 持续集成 https://juejin.im/entry/5995599a6fb9a0249f6a131b 35 | 36 | ### 原理深入 37 | * 了解Electron时间循环 https://electronjs.org/blog/electron-internals-node-integration 38 | * 源码结构 https://electronjs.org/docs/development/source-code-directory-structure 39 | * 与原生模块混合开发 https://electronjs.org/docs/tutorial/using-native-node-modules 40 | * 性能调优 https://electronjs.org/docs/tutorial/performance 41 | 42 | 43 | ### 项目参考 44 | * 源码 45 | * Atom (架构清晰) 46 | * WebTorrent (WebTorren就是纯JS写的,个人十分喜欢) 47 | * VSCode (大而全,可能比较难读) 48 | * 实践经验 49 | * 美团 [QConPPT](https://github.com/QConChina/QConBeijing2019/blob/master/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%AE%9E%E8%B7%B5/Electron%20%E5%9C%A8%E4%BC%81%E4%B8%9A%20IM%20%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%AE%9E%E8%B7%B5-%E9%82%93%E8%80%80%E9%BE%99.pdf) 50 | * 携程 51 | * 52 | * 53 | * 54 | 55 | ### 其他资料 56 | 书籍,可以翻一下《Electron in Action》,《跨平台桌面应用开发:基于Electron与NW.js》 57 | 视频,推荐一下自己的课程 https://time.geekbang.org/course/intro/269 58 | -------------------------------------------------------------------------------- /ROADMAP.md: -------------------------------------------------------------------------------- 1 | ### 基础部分 2 | * quick-start https://electronjs.org/docs/tutorial/first-app 3 | * 基本架构 https://electronjs.org/docs/tutorial/application-architecture#main-and-renderer-processes 4 | * 写得很好的基础介绍 http://jlord.us/essential-electron/ 5 | * 掌握Electron模块。重点包括:app、BrowserWindow、ipcMain、Menu、Tray、ipcRenderer、Notification、clipboard 6 | * 通过api-demos可以快速看到效果 https://github.com/electron/electron-api-demos 7 | * 查看文档 https://electronjs.org/docs 8 | 9 | ### 工程部分 10 | * 选择一个合适的模板 11 | * react https://github.com/electron-react-boilerplate/electron-react-boilerplate 12 | * vue https://github.com/SimulatedGREG/electron-vue 13 | * svelet https://github.com/Rich-Harris/svelte-template-electron 14 | * 纯JS https://github.com/dengyaolong/electron-boilerplate 15 | * 更新 https://electronjs.org/docs/tutorial/updates 16 | * 监控 https://electronjs.org/docs/api/crash-reporter 17 | * 打包 & 分发 https://electronjs.org/docs/tutorial/application-distribution 18 | * 安全 https://electronjs.org/docs/tutorial/security 19 | * 单测 https://electronjs.org/docs/tutorial/automated-testing-with-a-custom-driver 20 | * 持续集成 https://juejin.im/entry/5995599a6fb9a0249f6a131b 21 | 22 | ### 原理深入 23 | * 了解Electron时间循环 https://electronjs.org/blog/electron-internals-node-integration 24 | * 源码结构 https://electronjs.org/docs/development/source-code-directory-structure 25 | * 与原生模块混合开发 https://electronjs.org/docs/tutorial/using-native-node-modules 26 | * 性能调优 https://electronjs.org/docs/tutorial/performance 27 | 28 | 29 | ### 项目参考 30 | * 源码 31 | * Atom https://github.com/atom/atom (架构清晰) 32 | * WebTorrent https://github.com/webtorrent/webtorrent (WebTorren就是纯JS写的,个人十分喜欢) 33 | * VSCode https://github.com/microsoft/vscode (大而全,可能比较难读) 34 | * 实践经验 35 | * 美团 https://github.com/QConChina/QConBeijing2019/blob/master/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%AE%9E%E8%B7%B5/Electron%20%E5%9C%A8%E4%BC%81%E4%B8%9A%20IM%20%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%AE%9E%E8%B7%B5-%E9%82%93%E8%80%80%E9%BE%99.pdf 36 | * 携程 https://www.infoq.cn/article/AwVS6Kxt-7LCIFVruF6d 37 | * https://cloud.tencent.com/developer/article/1558453 38 | * https://changkun.us/archives/2017/03/217/ 39 | * https://webfe.kujiale.com/browser-to-client/ 40 | 41 | ### 其他资料 42 | 书籍,可以翻一下《Electron in Action》,《跨平台桌面应用开发:基于Electron与NW.js》 43 | 视频,推荐一下自己的课程 https://time.geekbang.org/course/intro/269 44 | -------------------------------------------------------------------------------- /img/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/img/icon.ico -------------------------------------------------------------------------------- /img/intro.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/img/intro.jpeg -------------------------------------------------------------------------------- /img/qrcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektime-geekbang/geektime-electron/07bdd32677e6b728ad99231384258c29c195755e/img/qrcode.png --------------------------------------------------------------------------------