-
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathmain.js
More file actions
1545 lines (1303 loc) · 43.7 KB
/
main.js
File metadata and controls
1545 lines (1303 loc) · 43.7 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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { app, BrowserWindow, ipcMain, BrowserView, Menu, MenuItem, globalShortcut, Tray, shell, net, Notification, clipboard, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const Store = require('electron-store');
const marked = require('marked');
const windowStateKeeper = require('electron-window-state');
// Migrate settings from older app versions if this is a fresh install
// Migration chain: perplexity-ai-app → simplexity-ai-app
(function migrateOldSettings() {
try {
const appDataBase = app.getPath('appData');
const newAppDataDir = app.getPath('userData'); // .../simplexity-ai-app
const newConfigPath = path.join(newAppDataDir, 'config.json');
// Already has config — no migration needed
if (fs.existsSync(newConfigPath)) return;
// Try migrating from simplexity-ai-app first (most recent), then perplexity-ai-app (oldest)
const oldDirs = [
path.join(appDataBase, 'simplexity-ai-app'),
path.join(appDataBase, 'perplexity-ai-app')
];
for (const oldAppDataDir of oldDirs) {
const oldConfigPath = path.join(oldAppDataDir, 'config.json');
if (fs.existsSync(oldConfigPath)) {
// Ensure new directory exists
if (!fs.existsSync(newAppDataDir)) {
fs.mkdirSync(newAppDataDir, { recursive: true });
}
// Copy config.json (settings)
fs.copyFileSync(oldConfigPath, newConfigPath);
console.log(`Migrated settings from ${path.basename(oldAppDataDir)}`);
// Also copy window-state.json if it exists
const oldWindowState = path.join(oldAppDataDir, 'window-state.json');
const newWindowState = path.join(newAppDataDir, 'window-state.json');
if (fs.existsSync(oldWindowState) && !fs.existsSync(newWindowState)) {
fs.copyFileSync(oldWindowState, newWindowState);
console.log(`Migrated window state from ${path.basename(oldAppDataDir)}`);
}
break; // Stop after first successful migration
}
}
} catch (error) {
console.error('Settings migration failed (non-fatal):', error.message);
}
})();
const settings = new Store();
const NotificationManager = require('./notification-manager');
const SearchService = require('./search-service');
const isMac = process.platform === 'darwin';
const isWindows = process.platform === 'win32';
const isLinux = process.platform === 'linux';
if (process.platform === 'win32') {
app.setAppUserModelId("SimplexityAI");
}
let mainWindow;
let currentView;
let views = {};
let findBarOpen = false;
let tray = null;
let settingsWindow = null;
let updateWindow = null;
let notificationManager;
let searchService;
let prefixSearchWindow = null;
let launchedHidden = process.argv.includes('--hidden') || process.argv.includes('--start-minimized');
let layoutCheckInterval;
let autoStartEnabled = settings.get('autoStartEnabled', false);
let originalClipboardContent = '';
let lastUpdateCheck = 0;
let shortcutsRegistered = false;
const UPDATE_CHECK_INTERVAL = 12 * 60 * 60 * 1000; // Check twice per day (every 12 hours)
function configureAutoStart(enable) {
try {
if (isMac) {
// macOS implementation
app.setLoginItemSettings({
openAtLogin: enable,
openAsHidden: true
});
} else if (isWindows) {
// Windows implementation with hidden flag
app.setLoginItemSettings({
openAtLogin: enable,
path: process.execPath,
args: ['--hidden']
});
} else {
// Linux implementation (depends on desktop environment)
app.setLoginItemSettings({
openAtLogin: enable
});
}
// Save the setting
settings.set('autoStartEnabled', enable);
autoStartEnabled = enable;
console.log(`Autostart ${enable ? 'enabled' : 'disabled'} (in tray mode)`);
return true;
} catch (error) {
console.error('Error configuring autostart:', error);
return false;
}
}
// Process command line arguments for searching
function processCommandLineArgs(argv) {
const searchArg = argv.find(arg =>
arg.startsWith('--search-text=') ||
arg.startsWith('--explain=') ||
arg.startsWith('--meaning=')
);
if (searchArg) {
let searchText = '';
let searchPrefix = '';
let argType = '';
if (searchArg.startsWith('--search-text=')) {
argType = '--search-text=';
searchText = searchArg.substring(argType.length);
} else if (searchArg.startsWith('--explain=')) {
argType = '--explain=';
searchText = searchArg.substring(argType.length);
searchPrefix = 'explain ';
} else if (searchArg.startsWith('--meaning=')) {
argType = '--meaning=';
searchText = searchArg.substring(argType.length);
searchPrefix = 'meaning of ';
}
searchText = searchText.trim();
if (searchText.startsWith('"') && searchText.endsWith('"')) {
searchText = searchText.slice(1, -1);
}
try {
searchText = decodeURIComponent(searchText);
} catch (e) {
console.log('Error decoding URI component:', e);
}
console.log('Processed search text:', searchText);
if (searchText) {
return {
formattedText: searchPrefix + searchText.trim(),
searchUrl: `https://www.perplexity.ai/search?q=${encodeURIComponent(searchPrefix + searchText.trim())}`
};
}
}
return null;
}
const defaultShortcuts = isMac
? {
perplexityAI: { key: 'Command+1', enabled: false },
perplexityLabs: { key: 'Command+2', enabled: false },
sendToTray: { key: 'Command+W', enabled: false },
restoreApp: { key: 'Command+Shift+Q', enabled: false },
quickSearch: { key: 'Command+Shift+P', enabled: false },
customPrefixSearch: { key: 'Command+Shift+C', enabled: false }
}
: {
perplexityAI: { key: 'Control+1', enabled: false },
perplexityLabs: { key: 'Control+2', enabled: false },
sendToTray: { key: 'Alt+Shift+W', enabled: false },
restoreApp: { key: 'Alt+Shift+Q', enabled: false },
quickSearch: { key: 'Alt+Shift+X', enabled: false },
customPrefixSearch: { key: 'Alt+Shift+D', enabled: false }
};
let shortcuts = settings.get('shortcuts', defaultShortcuts);
function ensureShortcutsFormat() {
let updated = false;
for (const [key, value] of Object.entries(shortcuts)) {
if (typeof value === 'string') {
shortcuts[key] = {
key: value,
enabled: false
};
updated = true;
}
}
if (updated) {
settings.set('shortcuts', shortcuts);
}
const validShortcutKeys = Object.keys(defaultShortcuts);
let hasRemovedShortcuts = false;
for (const key of Object.keys(shortcuts)) {
if (!validShortcutKeys.includes(key)) {
delete shortcuts[key];
hasRemovedShortcuts = true;
}
}
if (hasRemovedShortcuts) {
settings.set('shortcuts', shortcuts);
}
}
ensureShortcutsFormat();
function registerShortcuts() {
globalShortcut.unregisterAll();
const shortcutActions = {
perplexityAI: () => switchView('https://perplexity.ai'),
perplexityLabs: () => switchView('https://labs.perplexity.ai'),
sendToTray: () => mainWindow.hide(),
restoreApp: () => {
if (mainWindow.isMinimized() || !mainWindow.isVisible()) {
mainWindow.show();
mainWindow.focus();
setTimeout(() => adjustViewBounds(), 100);
}
},
quickSearch: () => {
if (searchService) {
searchService.searchSelectedText();
}
},
customPrefixSearch: () => {
if (searchService) {
showPrefixSearchWindow();
}
}
};
for (const [key, shortcutData] of Object.entries(shortcuts)) {
const shortcutKey = typeof shortcutData === 'object' ? shortcutData.key : shortcutData;
const isEnabled = typeof shortcutData === 'object' ? shortcutData.enabled === true : false;
if (isEnabled && shortcutKey && shortcutActions[key]) {
try {
globalShortcut.register(shortcutKey, shortcutActions[key]);
} catch (error) {
console.error(`Failed to register shortcut for ${key}:`, error);
}
}
}
shortcutsRegistered = true;
}
/**
* Gets selected text directly from X11 selections
* Uses xclip to access both primary (mouse) and clipboard selections
* @returns {Promise<string>} The selected text or empty string if no selection
*/
function getX11SelectionText() {
return new Promise((resolve) => {
const { exec } = require('child_process');
// Try primary selection first (mouse selection)
exec('xclip -o -selection primary 2>/dev/null', { timeout: 1000 }, (primaryError, primaryText) => {
if (!primaryError && primaryText && primaryText.trim()) {
console.log('Got text from primary selection');
resolve(primaryText.trim());
} else {
// Fall back to clipboard selection
exec('xclip -o -selection clipboard 2>/dev/null', { timeout: 1000 }, (clipboardError, clipboardText) => {
if (!clipboardError && clipboardText && clipboardText.trim()) {
console.log('Got text from clipboard selection');
resolve(clipboardText.trim());
} else {
// Last resort: Use the existing clipboard content
const clipboardContent = clipboard.readText().trim();
console.log('Using clipboard content as fallback', clipboardContent ? 'has content' : 'is empty');
resolve(clipboardContent);
}
});
}
});
});
}
function showPrefixSearchWindow() {
originalClipboardContent = clipboard.readText();
if (isLinux) {
getX11SelectionText().then((selectedText) => {
if (!selectedText) {
const notification = new Notification({
title: 'No text selected',
body: 'Please select text before searching or install xclip: sudo pacman -S xclip'
});
notification.show();
clipboard.writeText(originalClipboardContent);
return;
}
createPrefixSearchWindow(selectedText);
});
return;
}
clipboard.writeText('');
searchService.copySelectedText().then(() => {
setTimeout(() => {
const selectedText = clipboard.readText().trim();
if (!selectedText) {
const notification = new Notification({
title: 'No text selected',
body: 'Please select text before searching.'
});
notification.show();
clipboard.writeText(originalClipboardContent);
return;
}
createPrefixSearchWindow(selectedText);
}, 400);
});
}
/**
* Creates and displays the prefix search window with the selected text
* Extracted to a separate function for better code organization
* @param {string} selectedText - The text that was selected by the user
*/
function createPrefixSearchWindow(selectedText) {
if (!prefixSearchWindow || prefixSearchWindow.isDestroyed()) {
const windowPosition = calculatePrefixWindowPosition();
prefixSearchWindow = new BrowserWindow({
width: 560,
height: 420,
x: windowPosition.x,
y: windowPosition.y,
frame: false,
resizable: false,
transparent: false,
alwaysOnTop: true,
show: false,
webPreferences: {
preload: path.join(__dirname, 'src', 'js', 'preload', 'preload_prefix.js'),
contextIsolation: true,
nodeIntegration: false,
backgroundThrottling: false,
devTools: false,
offscreen: false,
disableBlinkFeatures: 'Accelerated2dCanvas,AcceleratedSmil'
}
});
prefixSearchWindow.loadFile('prefix-search.html', { cache: false });
prefixSearchWindow.once('ready-to-show', () => {
prefixSearchWindow.webContents.send('set-selected-text', selectedText);
prefixSearchWindow.show();
prefixSearchWindow.focus();
});
prefixSearchWindow.on('blur', () => {
if (prefixSearchWindow && !prefixSearchWindow.isDestroyed()) {
prefixSearchWindow.close();
setTimeout(() => {
clipboard.writeText(originalClipboardContent);
}, 500);
}
});
prefixSearchWindow.on('closed', () => {
setTimeout(() => {
if (clipboard.readText() !== originalClipboardContent) {
clipboard.writeText(originalClipboardContent);
}
}, 200);
});
} else {
prefixSearchWindow.webContents.send('set-selected-text', selectedText);
prefixSearchWindow.show();
prefixSearchWindow.focus();
}
}
function calculatePrefixWindowPosition() {
const screenBounds = require('electron').screen.getPrimaryDisplay().workAreaSize;
const windowBounds = mainWindow ? mainWindow.getBounds() : { x: 0, y: 0, width: 800, height: 600 };
return {
x: Math.min(Math.max(windowBounds.x + windowBounds.width / 2 - 180, 0), screenBounds.width - 360),
y: Math.min(Math.max(windowBounds.y + windowBounds.height / 2 - 230, 0), screenBounds.height - 460)
};
}
function startLayoutChecks() {
if (layoutCheckInterval) {
clearInterval(layoutCheckInterval);
}
layoutCheckInterval = setInterval(() => {
if (mainWindow && !mainWindow.isMinimized() && mainWindow.isVisible()) {
adjustViewBounds();
}
}, 120000); // Once every 2 minutes instead of every minute for better performance
}
function configureAppForBetterPerformance() {
const disableHardwareAcceleration = settings.get('disableHardwareAcceleration', false);
if (disableHardwareAcceleration) {
app.disableHardwareAcceleration();
}
// Set chromium flags to reduce memory usage
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=256');
app.commandLine.appendSwitch('disable-gpu-compositing');
app.commandLine.appendSwitch('disable-smooth-scrolling');
// Optimize for low GPU memory
app.commandLine.appendSwitch('gpu-rasterization-msaa-sample-count', '0');
app.commandLine.appendSwitch('num-raster-threads', '1');
app.commandLine.appendSwitch('enable-zero-copy');
app.commandLine.appendSwitch('enable-gpu-memory-buffer-compositor-resources');
app.commandLine.appendSwitch('enable-checker-imaging');
app.commandLine.appendSwitch('tile-width', '256');
app.commandLine.appendSwitch('tile-height', '256');
}
function createWindow() {
let mainWindowState = windowStateKeeper({
defaultWidth: 1200,
defaultHeight: 800
});
mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
show: !launchedHidden, // Don't show if launched with --hidden flag
webPreferences: {
preload: path.join(__dirname, 'src', 'js', 'preload', 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
disableBlinkFeatures: 'Accelerated2dCanvas,AcceleratedSmil',
enableBlinkFeatures: 'PaintHolding',
backgroundThrottling: true
},
backgroundColor: '#FFFFFF',
autoHideMenuBar: true
});
mainWindowState.manage(mainWindow);
// Application menu with Find and Zoom accelerators (menu bar hidden, accelerators still work)
const appMenu = Menu.buildFromTemplate([
{
label: 'Edit',
submenu: [
{
label: 'Find',
accelerator: 'CmdOrCtrl+F',
click: () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('toggle-find-bar');
}
}
}
]
},
{
label: 'View',
submenu: [
{
label: 'Zoom In',
accelerator: 'CmdOrCtrl+=',
click: () => {
if (currentView) {
const current = currentView.webContents.getZoomLevel();
currentView.webContents.setZoomLevel(current + 0.5);
}
}
},
{
label: 'Zoom Out',
accelerator: 'CmdOrCtrl+-',
click: () => {
if (currentView) {
const current = currentView.webContents.getZoomLevel();
currentView.webContents.setZoomLevel(current - 0.5);
}
}
},
{ type: 'separator' },
{
label: 'Reset Zoom',
accelerator: 'CmdOrCtrl+0',
click: () => {
if (currentView) {
currentView.webContents.setZoomLevel(0);
}
}
}
]
}
]);
Menu.setApplicationMenu(appMenu);
mainWindow.setMenuBarVisibility(false);
mainWindow.loadFile('index.html').catch(console.error);
mainWindow.webContents.on('did-finish-load', () => {
if (!launchedHidden) {
mainWindow.show();
}
registerShortcuts();
loadDefaultAI();
checkForUpdates();
notificationManager.checkForNotifications();
notificationManager.updateBadge();
configureAutoStart(autoStartEnabled);
});
let resizeTimeout = null;
mainWindow.on('resize', () => {
if (resizeTimeout) clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => adjustViewBounds(), 200);
});
mainWindow.on('focus', () => {
setTimeout(() => adjustViewBounds(), 200);
if (!settingsWindow) {
reattachShortcuts();
}
});
mainWindow.on('restore', () => {
setTimeout(() => adjustViewBounds(), 200);
if (!settingsWindow) {
reattachShortcuts();
}
});
mainWindow.on('show', () => {
setTimeout(() => adjustViewBounds(), 200);
startLayoutChecks();
if (!settingsWindow) {
reattachShortcuts();
}
});
mainWindow.on('blur', () => {
detachAllShortcuts();
});
mainWindow.on('minimize', () => {
detachAllShortcuts();
});
mainWindow.on('hide', () => {
detachAllShortcuts();
});
mainWindow.on('close', (event) => {
if (app.isQuitting) {
return;
}
const closeToTray = settings.get('closeToTray', true);
if (closeToTray) {
event.preventDefault();
mainWindow.hide();
if (!settings.get('hasShownTrayNotification', false)) {
const notification = new Notification({
title: 'SimplexityAI',
body: 'Application is now running in the system tray'
});
notification.show();
settings.set('hasShownTrayNotification', true);
}
} else {
app.isQuitting = true;
}
});
notificationManager = new NotificationManager(mainWindow);
searchService = new SearchService(mainWindow, switchView);
setInterval(() => cleanupUnusedResources(), 300000); // Every 5 minutes
}
app.on('before-quit', () => {
app.isQuitting = true;
if (layoutCheckInterval) {
clearInterval(layoutCheckInterval);
}
});
function loadDefaultAI() {
const defaultAI = settings.get('defaultAI', 'https://perplexity.ai');
switchView(defaultAI);
}
function adjustViewBounds() {
if (currentView && mainWindow) {
const bounds = mainWindow.getContentBounds();
const sidebarWidth = 60;
const findBarHeight = findBarOpen ? 36 : 0;
const viewWidth = Math.max(bounds.width - sidebarWidth, 500);
const viewHeight = Math.max(bounds.height - findBarHeight, 400);
currentView.setBounds({
x: sidebarWidth,
y: findBarHeight,
width: viewWidth,
height: viewHeight,
});
if (process.platform === 'win32' && mainWindow.isVisible() && !mainWindow.isMinimized()) {
mainWindow.webContents.invalidate();
}
}
}
function isCtrlEnterToSendEnabled() {
return settings.get('ctrlEnterToSend', false);
}
function switchView(url) {
if (url === 'refresh' && currentView) {
const currentUrl = currentView.webContents.getURL();
let baseUrl;
if (currentUrl.includes('labs.perplexity.ai')) {
baseUrl = 'https://labs.perplexity.ai';
} else if (currentUrl.includes('perplexity.ai')) {
baseUrl = 'https://perplexity.ai';
} else {
baseUrl = settings.get('defaultAI', 'https://perplexity.ai');
}
console.log(`Refreshing to base URL: ${baseUrl}`);
currentView.webContents.loadURL(baseUrl);
return;
}
if (currentView) {
mainWindow.removeBrowserView(currentView);
}
if (url.startsWith('search:')) {
const searchQuery = url.substring(7).trim();
if (searchQuery) {
url = `https://www.perplexity.ai/search?q=${encodeURIComponent(searchQuery)}`;
} else {
url = 'https://perplexity.ai';
}
}
const maxCachedViews = 2;
const viewUrls = Object.keys(views);
if (viewUrls.length > maxCachedViews && !views[url]) {
const oldestUrl = viewUrls[0];
const oldView = views[oldestUrl];
if (oldView) {
oldView.webContents.destroy();
}
delete views[oldestUrl];
}
if (views[url]) {
currentView = views[url];
} else {
currentView = new BrowserView({
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'src', 'js', 'preload', 'preload_inject.js'),
backgroundThrottling: true,
worldSafeExecuteJavaScript: true,
sandbox: false,
spellcheck: true,
webgl: true,
enableWebSQL: false,
// Memory optimization settings
disableBlinkFeatures: 'Accelerated2dCanvas',
enableBlinkFeatures: 'PaintHolding',
},
});
if (currentView.webContents.setBackgroundThrottling) {
currentView.webContents.setBackgroundThrottling(true);
}
if (currentView.webContents.session && currentView.webContents.session.webRequest) {
currentView.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
callback({cancel: false, requestHeaders: details.requestHeaders});
});
}
currentView.webContents.loadURL(url);
views[url] = currentView;
currentView.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
// Context menu with spell check, copy link, and standard editing
const viewRef = currentView;
viewRef.webContents.on('context-menu', (event, params) => {
const menuItems = [];
// Spell check suggestions first (most actionable)
if (params.dictionarySuggestions && params.dictionarySuggestions.length > 0) {
for (const suggestion of params.dictionarySuggestions) {
menuItems.push({
label: suggestion,
click: () => viewRef.webContents.replaceMisspelling(suggestion)
});
}
menuItems.push({ type: 'separator' });
}
if (params.misspelledWord) {
menuItems.push({
label: 'Add to dictionary',
click: () => viewRef.webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord)
});
menuItems.push({ type: 'separator' });
}
// Only show editing options that are actually available
if (params.editFlags.canCut) {
menuItems.push({ label: 'Cut', role: 'cut' });
}
if (params.selectionText.trim().length > 0) {
menuItems.push({ label: 'Copy', role: 'copy' });
}
if (params.editFlags.canPaste) {
menuItems.push({ label: 'Paste', role: 'paste' });
}
if (params.editFlags.canSelectAll) {
menuItems.push({ label: 'Select All', role: 'selectAll' });
}
// Copy Link (only visible when right-clicking a link)
if (params.linkURL) {
if (menuItems.length > 0) {
menuItems.push({ type: 'separator' });
}
menuItems.push({
label: 'Copy Link',
click: () => clipboard.writeText(params.linkURL)
});
}
if (menuItems.length > 0) {
const menu = Menu.buildFromTemplate(menuItems);
menu.popup(mainWindow);
}
});
// Forward find-in-page results to the main window renderer
viewRef.webContents.on('found-in-page', (event, result) => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('find-result', {
activeMatchOrdinal: result.activeMatchOrdinal,
matches: result.matches
});
}
});
// Intercept keyboard shortcuts at the BrowserView level before the website can handle them
let sendingEnter = false;
viewRef.webContents.on('before-input-event', (event, input) => {
if (input.type !== 'keyDown') return;
const key = input.key.toLowerCase();
// Ctrl+Enter to Send: block plain Enter in textarea, allow Ctrl+Enter
if (key === 'enter' && isCtrlEnterToSendEnabled() && !sendingEnter) {
const mod = process.platform === 'darwin' ? input.meta : input.control;
// Shift+Enter → allow default (newline)
if (input.shift) {
// let it through
}
// Ctrl/Cmd+Enter → submit by sending a clean Enter keypress
else if (mod) {
event.preventDefault();
// Send a raw Enter key without modifiers so Perplexity sees a normal Enter (submit)
sendingEnter = true;
viewRef.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Return' });
viewRef.webContents.sendInputEvent({ type: 'char', keyCode: '\r' });
viewRef.webContents.sendInputEvent({ type: 'keyUp', keyCode: 'Return' });
sendingEnter = false;
}
// Plain Enter → block and insert newline
else {
event.preventDefault();
viewRef.webContents.executeJavaScript(`
(function() {
const ta = document.activeElement;
if (ta && ta.tagName === 'TEXTAREA') {
const start = ta.selectionStart;
const end = ta.selectionEnd;
// Use native input setter to update React state
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLTextAreaElement.prototype, 'value'
).set;
nativeInputValueSetter.call(ta, ta.value.substring(0, start) + '\\n' + ta.value.substring(end));
ta.selectionStart = ta.selectionEnd = start + 1;
ta.dispatchEvent(new Event('input', { bubbles: true }));
}
})();
`).catch(() => {});
}
return;
}
// Escape → close find bar if open
if (key === 'escape' && findBarOpen) {
event.preventDefault();
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('toggle-find-bar');
}
return;
}
const mod = process.platform === 'darwin' ? input.meta : input.control;
if (!mod) return;
// Ctrl/Cmd+F → toggle find bar
if (key === 'f' && !input.alt && !input.shift) {
event.preventDefault();
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('toggle-find-bar');
}
return;
}
// Ctrl/Cmd+= or Ctrl/Cmd+Shift+= → zoom in
if (key === '=' || key === '+') {
event.preventDefault();
const current = viewRef.webContents.getZoomLevel();
viewRef.webContents.setZoomLevel(current + 0.5);
return;
}
// Ctrl/Cmd+- → zoom out
if (key === '-') {
event.preventDefault();
const current = viewRef.webContents.getZoomLevel();
viewRef.webContents.setZoomLevel(current - 0.5);
return;
}
// Ctrl/Cmd+0 → reset zoom
if (key === '0') {
event.preventDefault();
viewRef.webContents.setZoomLevel(0);
return;
}
});
currentView.webContents.on('did-finish-load', () => {
currentView.webContents.executeJavaScript(`
(function removeNagScreens() {
const nagScreenSelectors = [
'div.max-w-\\\\[400px\\\\].rounded-xl',
'div.rounded-lg.p-md.animate-in.fade-in',
'div.flex.items-center.gap-sm',
];
nagScreenSelectors.forEach((selector) => {
document.querySelectorAll(selector).forEach((el) => el.remove());
});
// Add CSS to optimize rendering performance
const style = document.createElement('style');
style.textContent = 'img { will-change: auto !important; } .will-change-transform { will-change: auto !important; }';
document.head.appendChild(style);
})();
`);
});
currentView.webContents.on('did-start-loading', () => {
mainWindow.webContents.send('page-loading', true);
});
currentView.webContents.on('did-stop-loading', () => {
mainWindow.webContents.send('page-loading', false);
});
}
mainWindow.addBrowserView(currentView);
adjustViewBounds();
}
function cleanupUnusedResources() {
if (global.gc) {
global.gc();
}
const currentTime = Date.now();
const viewUrls = Object.keys(views);
for (const url of viewUrls) {
if (views[url] === currentView) continue;
if (!views[url].lastAccessTime || (currentTime - views[url].lastAccessTime > 300000)) {
if (views[url].webContents) {
views[url].webContents.destroy();
}
delete views[url];
}
}
}
function createTray() {
let iconPath;
if (isWindows) {
iconPath = path.join(__dirname, 'assets', 'icons', 'win', 'icon.ico');
} else if (isMac) {
iconPath = path.join(__dirname, 'assets', 'icons', 'mac', 'favicon.icns');
} else {
iconPath = path.join(__dirname, 'assets', 'icons', 'png', 'favicon.png');
}
if (!fs.existsSync(iconPath)) {
console.error(`Tray icon not found at path: ${iconPath}`);
return;
}
try {
tray = new Tray(iconPath);
tray.setToolTip('SimplexityAI');
const contextMenu = Menu.buildFromTemplate([
{
label: 'Quick Search',
click: () => {
if (searchService) {
searchService.searchSelectedText();
}
}
},
{
label: 'Show App',
click: () => {
if (mainWindow) {
mainWindow.show();
mainWindow.focus();
setTimeout(() => adjustViewBounds(), 100);
}
}
},
{ type: 'separator' },
{
label: 'Disable Hardware Acceleration',
type: 'checkbox',
checked: settings.get('disableHardwareAcceleration', false),
click: (menuItem) => {
settings.set('disableHardwareAcceleration', menuItem.checked);
dialog.showMessageBox(mainWindow, {
type: 'info',
title: 'Restart Required',
message: 'Please restart the application for this change to take effect.',
buttons: ['OK']
});
}
},