desky-agent 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/electron/icons.js CHANGED
@@ -1,79 +1,79 @@
1
- 'use strict';
2
- // Tray icons: the pixel Desky from the app's favicon, drawn here as PNGs so there are no image files to keep in
3
- // step. One pose per thing worth seeing at a glance in the tray.
4
-
5
- const zlib = require('zlib');
6
-
7
- const ORANGE = [0xd9, 0x77, 0x4b, 255];
8
- // the body in the tray for each colour Desky is printed in (src/core.js COLORS); graphite a shade lighter, to be seen
9
- // on a dark taskbar
10
- const BODY = { orange: ORANGE, white: [0xec, 0xe8, 0xe1, 255], mint: [0x7c, 0xc4, 0xa4, 255], blue: [0x6f, 0xa3, 0xd8, 255],
11
- graphite: [0x6a, 0x67, 0x63, 255] };
12
- const GREY = [0x8a, 0x85, 0x80, 255];
13
- const EYE = [0x22, 0x22, 0x22, 255];
14
-
15
- /** 16x16 grid of the pose: [x, y, w, h, colour] rectangles. */
16
- function pose(kind, body) {
17
- const r = [[2, 3, 12, 9, body], [3, 12, 2, 3, body], [11, 12, 2, 3, body]];
18
- if (kind === 'ask') r.push([0, 0, 2, 6, body], [14, 0, 2, 6, body]); // arms up: a call for you
19
- else r.push([0, 6, 2, 3, body], [14, 6, 2, 3, body]);
20
- if (kind === 'sleep') r.push([5, 7, 2, 1, EYE], [9, 7, 2, 1, EYE]); // eyes shut
21
- else if (kind === 'read') r.push([5, 7, 2, 3, EYE], [9, 7, 2, 3, EYE]); // looking down at the screen
22
- else r.push([5, 5, 2, 3, EYE], [9, 5, 2, 3, EYE]);
23
- return r;
24
- }
25
-
26
- const CRC = new Int32Array(256).map((_, n) => {
27
- let c = n;
28
- for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
29
- return c;
30
- });
31
- function crc32(buf) {
32
- let c = -1;
33
- for (const b of buf) c = CRC[(c ^ b) & 0xff] ^ (c >>> 8);
34
- return (c ^ -1) >>> 0;
35
- }
36
- function chunk(type, data) {
37
- const len = Buffer.alloc(4);
38
- len.writeUInt32BE(data.length);
39
- const td = Buffer.concat([Buffer.from(type, 'ascii'), data]);
40
- const crc = Buffer.alloc(4);
41
- crc.writeUInt32BE(crc32(td));
42
- return Buffer.concat([len, td, crc]);
43
- }
44
-
45
- function png(rects, scale) {
46
- const size = 16 * scale;
47
- const rgba = Buffer.alloc(size * size * 4);
48
- for (const [x, y, w, h, c] of rects) {
49
- for (let yy = y * scale; yy < (y + h) * scale; yy++) {
50
- for (let xx = x * scale; xx < (x + w) * scale; xx++) Buffer.from(c).copy(rgba, (yy * size + xx) * 4);
51
- }
52
- }
53
- const raw = Buffer.alloc(size * (size * 4 + 1));
54
- for (let y = 0; y < size; y++) rgba.copy(raw, y * (size * 4 + 1) + 1, y * size * 4, (y + 1) * size * 4);
55
- const ihdr = Buffer.alloc(13);
56
- ihdr.writeUInt32BE(size, 0);
57
- ihdr.writeUInt32BE(size, 4);
58
- ihdr[8] = 8; // 8 bits per channel
59
- ihdr[9] = 6; // RGBA
60
- return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr),
61
- chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
62
- }
63
-
64
- /** What the tray shows: no board (grey), asleep, reading, a call for you, or plain Desky. */
65
- function trayKind(st) {
66
- if (!st || !st.connected) return 'off';
67
- if (st.state === 'sleep') return 'sleep';
68
- if (st.state === 'read') return 'read';
69
- if (st.state === 'ask') return 'ask';
70
- return 'on';
71
- }
72
-
73
- /** PNG buffers at 1x, 2x and 3x for a tray kind, in Desky's colour. */
74
- function trayPngs(kind, color) {
75
- const rects = pose(kind === 'off' ? 'on' : kind, kind === 'off' ? GREY : BODY[color] || ORANGE);
76
- return [1, 2, 3].map(scale => ({ scale, buffer: png(rects, scale) }));
77
- }
78
-
79
- module.exports = { trayPngs, trayKind, png, pose };
1
+ 'use strict';
2
+ // Tray icons: the pixel Desky from the app's favicon, drawn here as PNGs so there are no image files to keep in
3
+ // step. One pose per thing worth seeing at a glance in the tray.
4
+
5
+ const zlib = require('zlib');
6
+
7
+ const ORANGE = [0xd9, 0x77, 0x4b, 255];
8
+ // the body in the tray for each colour Desky is printed in (src/core.js COLORS); graphite a shade lighter, to be seen
9
+ // on a dark taskbar
10
+ const BODY = { orange: ORANGE, white: [0xec, 0xe8, 0xe1, 255], mint: [0x7c, 0xc4, 0xa4, 255], blue: [0x6f, 0xa3, 0xd8, 255],
11
+ graphite: [0x6a, 0x67, 0x63, 255] };
12
+ const GREY = [0x8a, 0x85, 0x80, 255];
13
+ const EYE = [0x22, 0x22, 0x22, 255];
14
+
15
+ /** 16x16 grid of the pose: [x, y, w, h, colour] rectangles. */
16
+ function pose(kind, body) {
17
+ const r = [[2, 3, 12, 9, body], [3, 12, 2, 3, body], [11, 12, 2, 3, body]];
18
+ if (kind === 'ask') r.push([0, 0, 2, 6, body], [14, 0, 2, 6, body]); // arms up: a call for you
19
+ else r.push([0, 6, 2, 3, body], [14, 6, 2, 3, body]);
20
+ if (kind === 'sleep') r.push([5, 7, 2, 1, EYE], [9, 7, 2, 1, EYE]); // eyes shut
21
+ else if (kind === 'read') r.push([5, 7, 2, 3, EYE], [9, 7, 2, 3, EYE]); // looking down at the screen
22
+ else r.push([5, 5, 2, 3, EYE], [9, 5, 2, 3, EYE]);
23
+ return r;
24
+ }
25
+
26
+ const CRC = new Int32Array(256).map((_, n) => {
27
+ let c = n;
28
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
29
+ return c;
30
+ });
31
+ function crc32(buf) {
32
+ let c = -1;
33
+ for (const b of buf) c = CRC[(c ^ b) & 0xff] ^ (c >>> 8);
34
+ return (c ^ -1) >>> 0;
35
+ }
36
+ function chunk(type, data) {
37
+ const len = Buffer.alloc(4);
38
+ len.writeUInt32BE(data.length);
39
+ const td = Buffer.concat([Buffer.from(type, 'ascii'), data]);
40
+ const crc = Buffer.alloc(4);
41
+ crc.writeUInt32BE(crc32(td));
42
+ return Buffer.concat([len, td, crc]);
43
+ }
44
+
45
+ function png(rects, scale) {
46
+ const size = 16 * scale;
47
+ const rgba = Buffer.alloc(size * size * 4);
48
+ for (const [x, y, w, h, c] of rects) {
49
+ for (let yy = y * scale; yy < (y + h) * scale; yy++) {
50
+ for (let xx = x * scale; xx < (x + w) * scale; xx++) Buffer.from(c).copy(rgba, (yy * size + xx) * 4);
51
+ }
52
+ }
53
+ const raw = Buffer.alloc(size * (size * 4 + 1));
54
+ for (let y = 0; y < size; y++) rgba.copy(raw, y * (size * 4 + 1) + 1, y * size * 4, (y + 1) * size * 4);
55
+ const ihdr = Buffer.alloc(13);
56
+ ihdr.writeUInt32BE(size, 0);
57
+ ihdr.writeUInt32BE(size, 4);
58
+ ihdr[8] = 8; // 8 bits per channel
59
+ ihdr[9] = 6; // RGBA
60
+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr),
61
+ chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
62
+ }
63
+
64
+ /** What the tray shows: no board (grey), asleep, reading, a call for you, or plain Desky. */
65
+ function trayKind(st) {
66
+ if (!st || !st.connected) return 'off';
67
+ if (st.state === 'sleep') return 'sleep';
68
+ if (st.state === 'read') return 'read';
69
+ if (st.state === 'ask') return 'ask';
70
+ return 'on';
71
+ }
72
+
73
+ /** PNG buffers at 1x, 2x and 3x for a tray kind, in Desky's colour. */
74
+ function trayPngs(kind, color) {
75
+ const rects = pose(kind === 'off' ? 'on' : kind, kind === 'off' ? GREY : BODY[color] || ORANGE);
76
+ return [1, 2, 3].map(scale => ({ scale, buffer: png(rects, scale) }));
77
+ }
78
+
79
+ module.exports = { trayPngs, trayKind, png, pose };
package/electron/main.js CHANGED
@@ -1,219 +1,244 @@
1
- 'use strict';
2
- // Desky in the tray: the daemon (port, hooks, the control app's HTTP) lives in this process, the tray icon shows
3
- // what Desky shows, and the control app opens in a window of its own.
4
- //
5
- // Desky open the window (a shortcut, the Applications folder); wakes Desky after "Выйти"
6
- // Desky --background tray only: a hook started it, or "desky-agent start"
7
- // Desky --login tray only, at login; a new login undoes an old "Выйти"
8
- //
9
- // One instance: a second launch hands its wish (open the window) to the first and quits.
10
-
11
- const fs = require('fs');
12
- const http = require('http');
13
- const path = require('path');
14
- const { app, BrowserWindow, Menu, Tray, Notification, nativeImage, shell, dialog } = require('electron');
15
- const paths = require('../src/paths');
16
- const { Daemon, log } = require('../src/daemon');
17
- const autostart = require('../src/autostart');
18
- const { trayPngs, trayKind } = require('./icons');
19
-
20
- const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
21
- error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
22
- const MAC = process.platform === 'darwin';
23
- const quietLaunch = argv => argv.includes('--background') || argv.includes('--login');
24
-
25
- app.setName('Desky');
26
- if (process.platform === 'win32') app.setAppUserModelId('desk.clawd.app');
27
-
28
- let daemon = null;
29
- let tray = null;
30
- let win = null;
31
- let shownKey = '';
32
- let fwShown = '';
33
- let quitting = false;
34
-
35
- if (!app.requestSingleInstanceLock()) {
36
- app.exit(0);
37
- } else {
38
- app.on('second-instance', (_e, argv) => {
39
- if (quietLaunch(argv)) return;
40
- paths.markStopped(false);
41
- openWindow();
42
- });
43
- app.on('window-all-closed', () => { /* stay in the tray */ });
44
- app.whenReady().then(boot).catch(e => {
45
- log('не запустився: ' + (e.stack || e));
46
- dialog.showErrorBox('Desky Agent', 'Desky не запустився: ' + e.message + '\n\nЛог: ' + paths.LOG);
47
- app.exit(1);
48
- });
49
- }
50
-
51
- async function boot() {
52
- if (MAC && app.dock) app.dock.hide();
53
- if (!quietLaunch(process.argv) || process.argv.includes('--login')) paths.markStopped(false);
54
- menu();
55
-
56
- daemon = new Daemon({ onStop: () => quit() });
57
- try {
58
- await daemon.listen();
59
- } catch (e) {
60
- if (e.code !== 'EADDRINUSE') throw e;
61
- // the old Python daemon (agent/) or a stray instance: ask it to go, then take the port
62
- await post('/stop');
63
- await new Promise(r => setTimeout(r, 2500));
64
- daemon.server.removeAllListeners('error');
65
- await daemon.listen().catch(() => {
66
- throw new Error('порт 127.0.0.1:' + paths.port() + ' зайнятий іншою програмою');
67
- });
68
- }
69
- daemon.start();
70
-
71
- tray = new Tray(image('off'));
72
- tray.setToolTip('Desky');
73
- if (!MAC) tray.on('click', () => openWindow()); // Windows, Linux: a click opens; the menu is on right click
74
- refresh();
75
- setInterval(refresh, 1000);
76
-
77
- if (!quietLaunch(process.argv)) openWindow();
78
- }
79
-
80
- function post(p) {
81
- return new Promise(resolve => {
82
- const req = http.request({ host: '127.0.0.1', port: paths.port(), path: p, method: 'POST', timeout: 1500,
83
- headers: { 'Content-Type': 'application/json', 'Content-Length': 2 } }, res => {
84
- res.resume();
85
- res.on('end', resolve);
86
- });
87
- req.on('error', resolve);
88
- req.on('timeout', () => req.destroy());
89
- req.end('{}');
90
- });
91
- }
92
-
93
- function image(kind) {
94
- const img = nativeImage.createEmpty();
95
- const color = daemon && daemon.cfg ? daemon.cfg.color : 'orange';
96
- for (const { scale, buffer } of trayPngs(kind, color)) img.addRepresentation({ scaleFactor: scale, buffer });
97
- return img;
98
- }
99
-
100
- // ---------------------------------------------------------------- the tray
101
- function refresh() {
102
- const st = daemon.status();
103
- const kind = trayKind(st);
104
- const name = NAMES[st.state] || st.state;
105
- const fw = st.firmware_update;
106
- const updating = Boolean(fw && fw.state === 'updating');
107
- const line = updating ? 'Оновлюю прошивку…' : st.connected ? `Desky ${name}` : 'Плату не під\'єднано';
108
- if (fw && fw.text !== fwShown) { // one line when the update starts and one when it ends
109
- fwShown = fw.text;
110
- try {
111
- if (Notification.isSupported()) new Notification({ title: 'Desky Agent', body: fw.text, silent: true }).show();
112
- } catch (e) { /* the tray line and the log still say it */ }
113
- }
114
- const key = [kind, line, st.manual, st.connected, autostart.isEnabledCached(), daemon.cfg.color].join('|');
115
- if (key === shownKey) return;
116
- shownKey = key;
117
- tray.setImage(image(kind));
118
- tray.setToolTip(updating ? 'Desky: ' + fw.text
119
- : st.connected ? `Desky: ${name} · ${st.port}` : 'Desky: плату не під\'єднано');
120
- tray.setContextMenu(Menu.buildFromTemplate([
121
- { label: line, enabled: false },
122
- { label: updating ? 'Не від\'єднуй плату' : st.connected ? `Порт ${st.port}` : 'Під\'єднай кабелем, Desky знайдеться сам',
123
- enabled: false },
124
- { type: 'separator' },
125
- { label: 'Відкрити пульт', click: () => openWindow() },
126
- { label: 'Повернути агенту', visible: st.manual, click: () => daemon.setManual(false) },
127
- { label: 'Перезапустити плату', enabled: st.connected, click: () => daemon.link.reset() },
128
- { type: 'separator' },
129
- { label: 'Запускати під час входу', type: 'checkbox', checked: autostart.isEnabledCached(),
130
- click: item => {
131
- try {
132
- if (item.checked) autostart.enable();
133
- else autostart.disable();
134
- } catch (e) {
135
- dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
136
- }
137
- autostart.forget();
138
- shownKey = '';
139
- refresh();
140
- } },
141
- { label: 'Тека з логом', click: () => shell.openPath(paths.STATE) },
142
- { type: 'separator' },
143
- { label: 'Вийти', click: () => quit() },
144
- ]));
145
- }
146
-
147
- // ---------------------------------------------------------------- the window
148
- function bounds() {
149
- try {
150
- const b = JSON.parse(fs.readFileSync(paths.WINDOW, 'utf8'));
151
- if (b.width > 400 && b.height > 300) return b;
152
- } catch (e) { /* first time */ }
153
- return { width: 1300, height: 960 };
154
- }
155
-
156
- function openWindow() {
157
- if (!daemon) return;
158
- if (win) {
159
- if (win.isMinimized()) win.restore();
160
- win.show();
161
- win.focus();
162
- return;
163
- }
164
- win = new BrowserWindow({
165
- ...bounds(), minWidth: 900, minHeight: 600, title: 'Desky Agent', show: false, backgroundColor: '#161514',
166
- autoHideMenuBar: true, icon: image('on'),
167
- webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false },
168
- });
169
- win.loadURL(`http://127.0.0.1:${daemon.httpPort}/`);
170
- win.once('ready-to-show', () => win.show());
171
- win.webContents.setWindowOpenHandler(({ url }) => {
172
- if (/^https?:/.test(url)) shell.openExternal(url);
173
- return { action: 'deny' };
174
- });
175
- win.webContents.on('will-navigate', (e, url) => {
176
- if (!url.startsWith(`http://127.0.0.1:${daemon.httpPort}/`)) {
177
- e.preventDefault();
178
- shell.openExternal(url);
179
- }
180
- });
181
- win.on('close', () => {
182
- try {
183
- fs.mkdirSync(paths.STATE, { recursive: true });
184
- const b = win.getNormalBounds();
185
- fs.writeFileSync(paths.WINDOW, JSON.stringify(b));
186
- } catch (e) { /* not worth failing for */ }
187
- });
188
- win.on('closed', () => {
189
- win = null;
190
- if (MAC && app.dock) app.dock.hide();
191
- });
192
- if (MAC && app.dock) app.dock.show();
193
- }
194
-
195
- function menu() {
196
- if (!MAC) {
197
- Menu.setApplicationMenu(null);
198
- return;
199
- }
200
- // macOS: Cmd+C / Cmd+V in the app's text fields need an Edit menu
201
- Menu.setApplicationMenu(Menu.buildFromTemplate([
202
- { label: 'Desky Agent', submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'hide' }, { type: 'separator' },
203
- { label: 'Закрити вікно', accelerator: 'Cmd+W', click: () => win && win.close() },
204
- { label: 'Вийти з Desky Agent', accelerator: 'Cmd+Q', click: () => quit() }] },
205
- { role: 'editMenu' },
206
- { role: 'windowMenu' },
207
- ]));
208
- }
209
-
210
- /** Leave the tray and free the port. Hooks do not start Desky again until it is opened or the next login. */
211
- async function quit() {
212
- if (quitting) return;
213
- quitting = true;
214
- paths.markStopped(true);
215
- if (win) win.destroy();
216
- if (tray) tray.destroy();
217
- if (daemon) await daemon.close();
218
- app.exit(0);
219
- }
1
+ 'use strict';
2
+ // Desky in the tray: the daemon (port, hooks, the control app's HTTP) lives in this process, the tray icon shows
3
+ // what Desky shows, and the control app opens in a window of its own.
4
+ //
5
+ // Desky open the window (a shortcut, the Applications folder); wakes Desky after "Выйти"
6
+ // Desky --background tray only: a hook started it, or "desky-agent start"
7
+ // Desky --login tray only, at login; a new login undoes an old "Выйти"
8
+ //
9
+ // One instance: a second launch hands its wish (open the window) to the first and quits.
10
+
11
+ const fs = require('fs');
12
+ const http = require('http');
13
+ const path = require('path');
14
+ const { app, BrowserWindow, Menu, Tray, Notification, nativeImage, shell, dialog } = require('electron');
15
+ const paths = require('../src/paths');
16
+ const { Daemon, log } = require('../src/daemon');
17
+ const autostart = require('../src/autostart');
18
+ const { trayPngs, trayKind } = require('./icons');
19
+
20
+ const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
21
+ error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
22
+ const MAC = process.platform === 'darwin';
23
+ const quietLaunch = argv => argv.includes('--background') || argv.includes('--login');
24
+
25
+ app.setName('Desky');
26
+ if (process.platform === 'win32') app.setAppUserModelId('desk.clawd.app');
27
+
28
+ let daemon = null;
29
+ let tray = null;
30
+ let win = null;
31
+ let shownKey = '';
32
+ let fwShown = '';
33
+ let appShown = '';
34
+ let quitting = false;
35
+
36
+ if (!app.requestSingleInstanceLock()) {
37
+ app.exit(0);
38
+ } else {
39
+ app.on('second-instance', (_e, argv) => {
40
+ if (quietLaunch(argv)) return;
41
+ paths.markStopped(false);
42
+ openWindow();
43
+ });
44
+ app.on('window-all-closed', () => { /* stay in the tray */ });
45
+ app.whenReady().then(boot).catch(e => {
46
+ log('не запустився: ' + (e.stack || e));
47
+ dialog.showErrorBox('Desky Agent', 'Desky не запустився: ' + e.message + '\n\nЛог: ' + paths.LOG);
48
+ app.exit(1);
49
+ });
50
+ }
51
+
52
+ async function boot() {
53
+ if (MAC && app.dock) app.dock.hide();
54
+ if (!quietLaunch(process.argv) || process.argv.includes('--login')) paths.markStopped(false);
55
+ menu();
56
+
57
+ daemon = new Daemon({ onStop: () => quit() });
58
+ try {
59
+ await daemon.listen();
60
+ } catch (e) {
61
+ if (e.code !== 'EADDRINUSE') throw e;
62
+ // the old Python daemon (agent/) or a stray instance: ask it to go, then take the port
63
+ await post('/stop');
64
+ await new Promise(r => setTimeout(r, 2500));
65
+ daemon.server.removeAllListeners('error');
66
+ await daemon.listen().catch(() => {
67
+ throw new Error('порт 127.0.0.1:' + paths.port() + ' зайнятий іншою програмою');
68
+ });
69
+ }
70
+ daemon.start();
71
+
72
+ tray = new Tray(image('off'));
73
+ tray.setToolTip('Desky');
74
+ if (!MAC) tray.on('click', () => openWindow()); // Windows, Linux: a click opens; the menu is on right click
75
+ refresh();
76
+ setInterval(refresh, 1000);
77
+
78
+ if (!quietLaunch(process.argv)) openWindow();
79
+ }
80
+
81
+ function post(p) {
82
+ return new Promise(resolve => {
83
+ const req = http.request({ host: '127.0.0.1', port: paths.port(), path: p, method: 'POST', timeout: 1500,
84
+ headers: { 'Content-Type': 'application/json', 'Content-Length': 2 } }, res => {
85
+ res.resume();
86
+ res.on('end', resolve);
87
+ });
88
+ req.on('error', resolve);
89
+ req.on('timeout', () => req.destroy());
90
+ req.end('{}');
91
+ });
92
+ }
93
+
94
+ function image(kind) {
95
+ const img = nativeImage.createEmpty();
96
+ const color = daemon && daemon.cfg ? daemon.cfg.color : 'orange';
97
+ for (const { scale, buffer } of trayPngs(kind, color)) img.addRepresentation({ scaleFactor: scale, buffer });
98
+ return img;
99
+ }
100
+
101
+ // ---------------------------------------------------------------- the tray
102
+ function refresh() {
103
+ const st = daemon.status();
104
+ const kind = trayKind(st);
105
+ const name = NAMES[st.state] || st.state;
106
+ const fw = st.firmware_update;
107
+ const updating = Boolean(fw && fw.state === 'updating');
108
+ const line = updating ? 'Оновлюю прошивку…' : st.connected ? `Desky ${name}` : 'Плату не під\'єднано';
109
+ if (fw && fw.text !== fwShown) { // one line when the update starts and one when it ends
110
+ fwShown = fw.text;
111
+ notify(fw.text);
112
+ }
113
+ const au = st.app_update || {};
114
+ const appNews = au.text || (au.available ? `Вийшла нова версія Desky: ${au.latest}. Оновити можна в пульті` : '');
115
+ if (appNews && appNews !== appShown) { // a new version once, then the update's start and end
116
+ appShown = appNews;
117
+ notify(appNews, () => openWindow());
118
+ }
119
+ const offer = au.available && au.can && au.state !== 'updating';
120
+ const key = [kind, line, st.manual, st.connected, autostart.isEnabledCached(), daemon.cfg.color,
121
+ offer && au.latest].join('|');
122
+ if (key === shownKey) return;
123
+ shownKey = key;
124
+ tray.setImage(image(kind));
125
+ tray.setToolTip(updating ? 'Desky: ' + fw.text
126
+ : st.connected ? `Desky: ${name} · ${st.port}` : 'Desky: плату не під\'єднано');
127
+ tray.setContextMenu(Menu.buildFromTemplate([
128
+ { label: line, enabled: false },
129
+ { label: updating ? 'Не від\'єднуй плату' : st.connected ? `Порт ${st.port}` : 'Під\'єднай кабелем, Desky знайдеться сам',
130
+ enabled: false },
131
+ { type: 'separator' },
132
+ { label: 'Відкрити пульт', click: () => openWindow() },
133
+ { label: 'Повернути агенту', visible: st.manual, click: () => daemon.setManual(false) },
134
+ { label: 'Перезапустити плату', enabled: st.connected, click: () => daemon.link.reset() },
135
+ { label: `Оновити Desky до ${au.latest}`, visible: Boolean(offer), click: () => {
136
+ try {
137
+ daemon.startAppUpdate();
138
+ } catch (e) {
139
+ dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
140
+ }
141
+ shownKey = '';
142
+ refresh();
143
+ } },
144
+ { type: 'separator' },
145
+ { label: 'Запускати під час входу', type: 'checkbox', checked: autostart.isEnabledCached(),
146
+ click: item => {
147
+ try {
148
+ if (item.checked) autostart.enable();
149
+ else autostart.disable();
150
+ } catch (e) {
151
+ dialog.showErrorBox('Desky Agent', 'Не вдалося: ' + e.message);
152
+ }
153
+ autostart.forget();
154
+ shownKey = '';
155
+ refresh();
156
+ } },
157
+ { label: 'Тека з логом', click: () => shell.openPath(paths.STATE) },
158
+ { type: 'separator' },
159
+ { label: 'Вийти', click: () => quit() },
160
+ ]));
161
+ }
162
+
163
+ function notify(body, onClick) {
164
+ try {
165
+ if (!Notification.isSupported()) return;
166
+ const n = new Notification({ title: 'Desky Agent', body, silent: true });
167
+ if (onClick) n.on('click', onClick);
168
+ n.show();
169
+ } catch (e) { /* the tray, the window and the log still say it */ }
170
+ }
171
+
172
+ // ---------------------------------------------------------------- the window
173
+ function bounds() {
174
+ try {
175
+ const b = JSON.parse(fs.readFileSync(paths.WINDOW, 'utf8'));
176
+ if (b.width > 400 && b.height > 300) return b;
177
+ } catch (e) { /* first time */ }
178
+ return { width: 1300, height: 960 };
179
+ }
180
+
181
+ function openWindow() {
182
+ if (!daemon) return;
183
+ if (win) {
184
+ if (win.isMinimized()) win.restore();
185
+ win.show();
186
+ win.focus();
187
+ return;
188
+ }
189
+ win = new BrowserWindow({
190
+ ...bounds(), minWidth: 900, minHeight: 600, title: 'Desky Agent', show: false, backgroundColor: '#161514',
191
+ autoHideMenuBar: true, icon: image('on'),
192
+ webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false },
193
+ });
194
+ win.loadURL(`http://127.0.0.1:${daemon.httpPort}/`);
195
+ win.once('ready-to-show', () => win.show());
196
+ win.webContents.setWindowOpenHandler(({ url }) => {
197
+ if (/^https?:/.test(url)) shell.openExternal(url);
198
+ return { action: 'deny' };
199
+ });
200
+ win.webContents.on('will-navigate', (e, url) => {
201
+ if (!url.startsWith(`http://127.0.0.1:${daemon.httpPort}/`)) {
202
+ e.preventDefault();
203
+ shell.openExternal(url);
204
+ }
205
+ });
206
+ win.on('close', () => {
207
+ try {
208
+ fs.mkdirSync(paths.STATE, { recursive: true });
209
+ const b = win.getNormalBounds();
210
+ fs.writeFileSync(paths.WINDOW, JSON.stringify(b));
211
+ } catch (e) { /* not worth failing for */ }
212
+ });
213
+ win.on('closed', () => {
214
+ win = null;
215
+ if (MAC && app.dock) app.dock.hide();
216
+ });
217
+ if (MAC && app.dock) app.dock.show();
218
+ }
219
+
220
+ function menu() {
221
+ if (!MAC) {
222
+ Menu.setApplicationMenu(null);
223
+ return;
224
+ }
225
+ // macOS: Cmd+C / Cmd+V in the app's text fields need an Edit menu
226
+ Menu.setApplicationMenu(Menu.buildFromTemplate([
227
+ { label: 'Desky Agent', submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'hide' }, { type: 'separator' },
228
+ { label: 'Закрити вікно', accelerator: 'Cmd+W', click: () => win && win.close() },
229
+ { label: 'Вийти з Desky Agent', accelerator: 'Cmd+Q', click: () => quit() }] },
230
+ { role: 'editMenu' },
231
+ { role: 'windowMenu' },
232
+ ]));
233
+ }
234
+
235
+ /** Leave the tray and free the port. Hooks do not start Desky again until it is opened or the next login. */
236
+ async function quit() {
237
+ if (quitting) return;
238
+ quitting = true;
239
+ paths.markStopped(true);
240
+ if (win) win.destroy();
241
+ if (tray) tray.destroy();
242
+ if (daemon) await daemon.close();
243
+ app.exit(0);
244
+ }
Binary file