-
-
Notifications
You must be signed in to change notification settings - Fork 865
Expand file tree
/
Copy pathmain.js
More file actions
508 lines (433 loc) · 14.9 KB
/
Copy pathmain.js
File metadata and controls
508 lines (433 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
const electron = require('electron')
const fs = require('fs')
const path = require('path')
const {
app, // Module to control application life.
protocol, // Module to control protocol handling
BaseWindow, // Module to create native browser window.
BrowserWindow,
webContents,
session,
ipcMain: ipc,
Menu, MenuItem,
crashReporter,
dialog,
nativeTheme,
shell,
net,
WebContentsView,
utilityProcess,
MessageChannelMain
} = electron
crashReporter.start({
submitURL: 'https://minbrowser.org/',
uploadToServer: false,
compress: true
})
if (process.argv.some(arg => arg === '-v' || arg === '--version')) {
console.log('Min: ' + app.getVersion())
console.log('Chromium: ' + process.versions.chrome)
process.exit()
}
let isInstallerRunning = false
const isDevelopmentMode = process.argv.some(arg => arg === '--development-mode')
const isDebuggingEnabled = process.argv.some(arg => arg === '--debug-browser')
function clamp (n, min, max) {
return Math.max(Math.min(n, max), min)
}
if (process.platform === 'win32') {
(async function () {
var squirrelCommand = process.argv[1]
if (squirrelCommand === '--squirrel-install' || squirrelCommand === '--squirrel-updated') {
isInstallerRunning = true
await registryInstaller.install()
}
if (squirrelCommand === '--squirrel-uninstall') {
isInstallerRunning = true
await registryInstaller.uninstall()
}
if (require('electron-squirrel-startup')) {
app.quit()
}
})()
}
if (isDevelopmentMode) {
app.setPath('userData', app.getPath('userData') + '-development')
}
// workaround for flicker when focusing app (https://github.com/electron/electron/issues/17942)
app.commandLine.appendSwitch('disable-backgrounding-occluded-windows', 'true')
var userDataPath = app.getPath('userData')
settings.initialize(userDataPath)
if (settings.get('userSelectedLanguage')) {
app.commandLine.appendSwitch('lang', settings.get('userSelectedLanguage'))
}
const browserPage = 'min://app/index.html'
var mainMenu = null
var secondaryMenu = null
var isFocusMode = false
var appIsReady = false
const isFirstInstance = app.requestSingleInstanceLock()
if (!isFirstInstance) {
app.quit()
return
}
var saveWindowBounds = function () {
if (windows.getCurrent()) {
var bounds = Object.assign(windows.getCurrent().getBounds(), {
maximized: windows.getCurrent().isMaximized()
})
fs.writeFileSync(path.join(userDataPath, 'windowBounds.json'), JSON.stringify(bounds))
}
}
function sendIPCToWindow (window, action, data) {
if (window && window.isDestroyed()) {
console.warn('ignoring message ' + action + ' sent to destroyed window')
return
}
if (window && getWindowWebContents(window).isLoadingMainFrame()) {
// immediately after a did-finish-load event, isLoading can still be true,
// so wait a bit to confirm that the page is really loading
setTimeout(function() {
if (getWindowWebContents(window).isLoadingMainFrame()) {
getWindowWebContents(window).once('did-finish-load', function () {
getWindowWebContents(window).send(action, data || {})
})
} else {
getWindowWebContents(window).send(action, data || {})
}
}, 0)
} else if (window) {
getWindowWebContents(window).send(action, data || {})
} else {
var window = createWindow()
getWindowWebContents(window).once('did-finish-load', function () {
getWindowWebContents(window).send(action, data || {})
})
}
}
function openTabInWindow (url) {
sendIPCToWindow(windows.getCurrent(), 'addTab', {
url: url
})
}
function handleCommandLineArguments (argv) {
// the "ready" event must occur before this function can be used
if (argv) {
argv.forEach(function (arg, idx) {
if (arg && arg.toLowerCase() !== __dirname.toLowerCase()) {
// URL
if (arg.indexOf('://') !== -1) {
sendIPCToWindow(windows.getCurrent(), 'addTab', {
url: arg
})
} else if (idx > 0 && argv[idx - 1] === '-s') {
// search
sendIPCToWindow(windows.getCurrent(), 'addTab', {
url: arg
})
} else if (/\.(m?ht(ml)?|pdf)$/.test(arg) && fs.existsSync(arg)) {
// local files (.html, .mht, mhtml, .pdf)
sendIPCToWindow(windows.getCurrent(), 'addTab', {
url: 'file://' + path.resolve(arg)
})
}
}
})
}
}
function createWindow (customArgs = {}) {
var bounds;
try {
var data = fs.readFileSync(path.join(userDataPath, 'windowBounds.json'), 'utf-8')
bounds = JSON.parse(data)
} catch (e) {}
if (!bounds) { // there was an error, probably because the file doesn't exist
var size = electron.screen.getPrimaryDisplay().workAreaSize
bounds = {
x: 0,
y: 0,
width: size.width,
height: size.height,
maximized: true
}
}
// make the bounds fit inside a currently-active screen
// (since the screen Min was previously open on could have been removed)
// see: https://github.com/minbrowser/min/issues/904
var containingRect = electron.screen.getDisplayMatching(bounds).workArea
bounds = {
x: clamp(bounds.x, containingRect.x, (containingRect.x + containingRect.width) - bounds.width),
y: clamp(bounds.y, containingRect.y, (containingRect.y + containingRect.height) - bounds.height),
width: clamp(bounds.width, 0, containingRect.width),
height: clamp(bounds.height, 0, containingRect.height),
maximized: bounds.maximized
}
return createWindowWithBounds(bounds, customArgs)
}
function createWindowWithBounds (bounds, customArgs) {
const newWin = new BaseWindow({
width: bounds.width,
height: bounds.height,
x: bounds.x,
y: bounds.y,
minWidth: (process.platform === 'win32' ? 400 : 320), // controls take up more horizontal space on Windows
minHeight: 350,
titleBarStyle: settings.get('useSeparateTitlebar') ? 'default' : 'hidden',
trafficLightPosition: { x: 12, y: 10 },
icon: __dirname + '/icons/icon256.png',
frame: settings.get('useSeparateTitlebar'),
alwaysOnTop: settings.get('windowAlwaysOnTop'),
backgroundColor: '#fff', // the value of this is ignored, but setting it seems to work around https://github.com/electron/electron/issues/10559
})
// windows and linux always use a menu button in the upper-left corner instead
// if frame: false is set, this won't have any effect, but it does apply on Linux if "use separate titlebar" is enabled
if (process.platform !== 'darwin') {
newWin.setMenuBarVisibility(false)
}
const mainView = new WebContentsView({
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
nodeIntegrationInWorker: true, // used by ProcessSpawner
additionalArguments: [
'--user-data-path=' + userDataPath,
'--app-version=' + app.getVersion(),
'--app-name=' + app.getName(),
...((isDevelopmentMode ? ['--development-mode'] : [])),
'--window-id=' + windows.nextId,
...((windows.getAll().length === 0 ? ['--initial-window'] : [])),
...(windows.hasEverCreatedWindow ? [] : ['--launch-window']),
...(customArgs.initialTask ? ['--initial-task=' + customArgs.initialTask] : [])
]
}
})
mainView.webContents.loadURL(browserPage)
mainView.setBounds({x: 0, y: 0, width: bounds.width, height: bounds.height})
newWin.contentView.addChildView(mainView)
newWin.on('resize', function() {
const winBounds = newWin.getBounds()
mainView.setBounds({x: 0, y: 0, width: winBounds.width, height: winBounds.height})
})
if (bounds.maximized) {
newWin.maximize()
mainView.webContents.once('did-finish-load', function () {
sendIPCToWindow(newWin, 'maximize')
})
}
newWin.on('close', function () {
// save the window size for the next launch of the app
saveWindowBounds()
})
newWin.on('focus', function () {
if (!windows.getState(newWin).isMinimized) {
sendIPCToWindow(newWin, 'windowFocus')
}
})
newWin.on('minimize', function () {
sendIPCToWindow(newWin, 'minimize')
windows.getState(newWin).isMinimized = true
})
newWin.on('restore', function () {
windows.getState(newWin).isMinimized = false
})
newWin.on('maximize', function () {
sendIPCToWindow(newWin, 'maximize')
})
newWin.on('unmaximize', function () {
sendIPCToWindow(newWin, 'unmaximize')
})
newWin.on('focus', function () {
sendIPCToWindow(newWin, 'focus')
})
newWin.on('blur', function () {
// if the devtools for this window are focused, this check will be false, and we keep the focused class on the window
if (BaseWindow.getFocusedWindow() !== newWin) {
sendIPCToWindow(newWin, 'blur')
}
})
newWin.on('enter-full-screen', function () {
sendIPCToWindow(newWin, 'enter-full-screen')
})
newWin.on('leave-full-screen', function () {
sendIPCToWindow(newWin, 'leave-full-screen')
// https://github.com/minbrowser/min/issues/1093
newWin.setMenuBarVisibility(false)
})
newWin.on('enter-html-full-screen', function () {
sendIPCToWindow(newWin, 'enter-html-full-screen')
})
newWin.on('leave-html-full-screen', function () {
sendIPCToWindow(newWin, 'leave-html-full-screen')
// https://github.com/minbrowser/min/issues/952
newWin.setMenuBarVisibility(false)
})
/*
Handles events from mouse buttons
Unsupported on macOS, and on Linux, there is a default handler already,
so registering a handler causes events to happen twice.
See: https://github.com/electron/electron/issues/18322
*/
if (process.platform === 'win32') {
newWin.on('app-command', function (e, command) {
if (command === 'browser-backward') {
sendIPCToWindow(newWin, 'goBack')
} else if (command === 'browser-forward') {
sendIPCToWindow(newWin, 'goForward')
}
})
}
// prevent remote pages from being loaded using drag-and-drop, since they would have node access
mainView.webContents.on('will-navigate', function (e, url) {
if (url !== browserPage) {
e.preventDefault()
}
})
mainView.webContents.on('before-input-event', function(e, input) {
sendIPCToWindow(newWin, 'before-input-event', input)
})
newWin.setTouchBar(buildTouchBar())
windows.addWindow(newWin)
return newWin
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function () {
settings.set('restartNow', false)
appIsReady = true
/* the installer launches the app to install registry items and shortcuts,
but if that's happening, we shouldn't display anything */
if (isInstallerRunning) {
return
}
registerBundleProtocol(session.defaultSession)
const newWin = createWindow()
getWindowWebContents(newWin).on('did-finish-load', function () {
// if a URL was passed as a command line argument (probably because Min is set as the default browser on Linux), open it.
handleCommandLineArguments(process.argv)
// there is a URL from an "open-url" event (on Mac)
if (global.URLToOpen) {
// if there is a previously set URL to open (probably from opening a link on macOS), open it
sendIPCToWindow(newWin, 'addTab', {
url: global.URLToOpen
})
global.URLToOpen = null
}
})
mainMenu = buildAppMenu()
Menu.setApplicationMenu(mainMenu)
createDockMenu()
})
app.on('open-url', function (e, url) {
if (appIsReady) {
sendIPCToWindow(windows.getCurrent(), 'addTab', {
url: url
})
} else {
global.URLToOpen = url // this will be handled later in the createWindow callback
}
})
// handoff support for macOS
app.on('continue-activity', function(e, type, userInfo, details) {
if (type === 'NSUserActivityTypeBrowsingWeb' && details.webpageURL) {
e.preventDefault()
sendIPCToWindow(windows.getCurrent(), 'addTab', {
url: details.webpageURL
})
}
})
app.on('second-instance', function (e, argv, workingDir) {
if (windows.getCurrent()) {
if (windows.getCurrent().isMinimized()) {
windows.getCurrent().restore()
}
windows.getCurrent().focus()
// add a tab with the new URL
handleCommandLineArguments(argv)
}
})
/**
* Emitted when the application is activated, which usually happens when clicks on the applications's dock icon
* https://github.com/electron/electron/blob/master/docs/api/app.md#event-activate-os-x
*
* Opens a new tab when all tabs are closed, and min is still open by clicking on the application dock icon
*/
app.on('activate', function (/* e, hasVisibleWindows */) {
if (!windows.getCurrent() && appIsReady) { // sometimes, the event will be triggered before the app is ready, and creating new windows will fail
createWindow()
}
})
ipc.on('focusMainWebContents', function () {
getWindowWebContents(windows.getCurrent()).focus()
})
ipc.on('showSecondaryMenu', function (event, data) {
if (!secondaryMenu) {
secondaryMenu = buildAppMenu({ secondary: true })
}
secondaryMenu.popup({
x: data.x,
y: data.y
})
})
ipc.on('handoffUpdate', function(e, data) {
if (app.setUserActivity && data.url && data.url.startsWith('http')) {
app.setUserActivity('NSUserActivityTypeBrowsingWeb', {}, data.url)
} else if (app.invalidateCurrentActivity) {
app.invalidateCurrentActivity()
}
})
ipc.on('quit', function () {
app.quit()
})
ipc.on('tab-state-change', function(e, events) {
const sourceWindowId = windows.windowFromContents(e.sender)?.id
if (!sourceWindowId) {
console.warn('warning: received tab state update from window after destruction, ignoring')
return
}
windows.getAll().forEach(function(window) {
if (getWindowWebContents(window).id !== e.sender.id) {
getWindowWebContents(window).send('tab-state-change-receive', {
sourceWindowId,
events
})
}
})
})
ipc.on('request-tab-state', function(e) {
const otherWindow = windows.getAll().find(w => getWindowWebContents(w).id !== e.sender.id)
if (!otherWindow) {
throw new Error('secondary window doesn\'t exist as source for tab state')
}
ipc.once('return-tab-state', function(e2, data) {
e.returnValue = data
})
getWindowWebContents(otherWindow).send('read-tab-state')
})
/* places service */
const placesPage = 'file://' + __dirname + '/js/places/placesService.html'
let placesWindow = null
app.once('ready', function() {
placesWindow = new BrowserWindow({
width: 300,
height: 300,
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
placesWindow.loadURL(placesPage)
})
ipc.on('places-connect', function (e) {
placesWindow.webContents.postMessage('places-connect', null, e.ports)
})
function getWindowWebContents (win) {
return win.getContentView().children[0].webContents
}
app.on('ready', () => {
// Main process
const llmServiceProcess = utilityProcess.fork(path.join(__dirname, "main/llmService.mjs"))
ipc.on('llm-service-connect', function(e) {
llmServiceProcess.postMessage({message: 'init'}, e.ports)
})
})