-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1390 lines (1210 loc) · 47.1 KB
/
main.js
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
// Modules to control application life and create native browser window
const prompt = require('electron-prompt');
const sharp = require('sharp');
const ShutdownHandler = require('@paymoapp/electron-shutdown-handler').default;
const fetch = require('electron-fetch').default
const isMac = process.platform === 'darwin'
const isWindows = process.platform === 'win32'
const isLinux = process.platform === 'linux'
/*if ((isMac) || (isLinux)) {
var { app, clipboard, BrowserWindow, Menu, Tray, nativeImage, Notification, dialog, session, shell, powerMonitor, nativeTheme } = require('electron')
}
if (isWindows) {
var { app, clipboard, Menu, Tray, nativeImage, Notification, dialog, session, shell, powerMonitor, nativeTheme } = require('electron')
var { BrowserWindow } = require('electron-acrylic-window') // return BrowserWindows to electron in case of not using electron-acrylic-window
}*/
const { app, clipboard, BrowserWindow, Menu, Tray, nativeImage, Notification, dialog, session, shell, powerMonitor, nativeTheme } = require('electron')
const fs = require("fs");
const { join } = require('path');
const path = require('node:path');
const Store = require('electron-store');
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light'
const gotTheLock = app.requestSingleInstanceLock();
main();
async function main() {
// prevent multiple instances, focus on the existed app instead
if (!gotTheLock) {
app.exit(0);
} else {
app.on('second-instance', (event) => {
if (win) {
//if (win.isMinimized()) win.restore();
win.show();
win.focus();
}
})
try {
const store = new Store();
// to check prompted status for dialogs
let prompted = false
// to check gui_blocked status
//let gui_blocked = false
//let is_notification = false;
// for storing unread counter
let unread = false;
// to store settings menu opened status
let settings_opened = false;
let url = "";
const url_example = 'http://cloud.example.com';
if (!((app.commandLine.getSwitchValue("server_url") == undefined) || (app.commandLine.getSwitchValue("server_url") == ""))) {
// overwrite server_url if arg is given
store.set('server_url',app.commandLine.getSwitchValue("server_url"))
url = app.commandLine.getSwitchValue("server_url");
} else if (!((store.get('server_url') == undefined) || (store.get('server_url') == ""))) {
url = store.get('server_url');
}
// set run at startup
if (store.get('run_at_startup')) {
app.setLoginItemSettings({
openAtLogin: true,
name: app.getName()
})
} else {
app.setLoginItemSettings({
openAtLogin: false,
name: app.getName()
})
}
let iconPath = path.join(__dirname,store.get('app_icon_name')||'iconTemplate.png');
let icon = nativeImage.createFromPath(iconPath); // template with center transparency
let trayIcon = icon
if (isMac) {
var icon_bw = await bw_icon_process(icon);
// as this icon is for macos tray only resize it here
icon_bw = icon_bw.resize({width:16});
}
//icon = icon_bw
const icon_notification = nativeImage.createFromPath(path.join(__dirname,store.get('notification_icon_name')||'notification.png'));
//const icon_red_dot = nativeImage.createFromPath(path.join(__dirname,'red_dot.png'));
//const icon = './icon.png';
var win = null;
//var win_loading = null;
var appIcon = null;
var MainMenu = null;
let mainMenuTemplate = [
{
label: 'Файл',
submenu: [
{
label: 'Открыть Nextcloud',
click: () => {
shell.openExternal(store.get('server_url'));
},
},
{
label: 'Настройки',
click: () => {
openSettings();
},
},
{ type: 'separator' },
{
label: 'Выйти',
accelerator: isMac ? 'Cmd+Q' : 'Alt+X',
click: () => {
store.set('bounds', win.getBounds());
app.exit(0);
},
}
]
},
{
label : "Вид",
submenu : [
//{ label : "Обновить", role : "reload" },
{ label: 'Обновить',
click: () => {
/*if (!gui_blocked) {
block_gui_loading(true);*/
win.reload()
//}
},
accelerator: isMac ? 'Cmd+R' : 'Ctrl+R'
},
{ type: 'separator' },
{ label: 'Свернуть',
click: () => {
if (isMac) app.dock.hide();
win.hide()
},
accelerator: isMac ? 'Cmd+H' : 'Ctrl+H',
role : "hide"
},
{ label: 'На весь экран',
accelerator: isMac ? 'Cmd+M' : 'Ctrl+M',
click: () => {
checkMaximize(true);
if (isMac) { /*app.dock.setIcon(icon); */app.dock.show();};
},
},
]
},
{
label : "?",
submenu : [
{ label : "Помощь",
accelerator: 'F1',
click: () => {
openPopup('https://docs.nextcloud.com/server/latest/user_manual/ru/talk');
//app.exit(0);
}
},
{ label: 'Открыть DevTools',
accelerator: 'F12',
click: () => {
win.webContents.toggleDevTools();
}
},
{ type: 'separator' },
{ label : "О программе",
// for linux compatibility
click: () => {
app.showAboutPanel();
}
}
]
}
];
let appIconMenuTemplate = [
{
label: 'Показать',
click: () => {
/*if (gui_blocked) {
win_loading.show();
}*/
win.show()
if (isMac) { /*app.dock.setIcon(icon);*/ app.dock.show();};
},
},
{
label: 'Свернуть',
click: () => {
if (isMac) app.dock.hide();
win.hide()
//win_loading.hide();
},
role : "hide"
},
{ type: 'separator' },
{
label: 'Открыть Nextcloud',
click: () => {
shell.openExternal(store.get('server_url'));
},
},
{
label: 'Настройки',
click: () => {
openSettings();
},
},
{ type: 'separator' },
{
label: 'Выйти',
click: () => {
store.set('bounds', win.getBounds());
app.exit(0);
},
}
];
function checkMaximize(click) {
if (win.isMaximized()) {
if (click) {
mainMenuTemplate[1].submenu[3].label = "На весь экран";
win.unmaximize()
} else {
mainMenuTemplate[1].submenu[3].label = "Восстановить размер";
}
} else {
if (click) {
mainMenuTemplate[1].submenu[3].label = "Восстановить размер";
win.maximize()
} else {
mainMenuTemplate[1].submenu[3].label = "На весь экран";
}
}
MainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu(MainMenu);
}
function isInternalLink(url) {
return url.startsWith('file')
}
function isExternalLink(url) {
return !isInternalLink(url)
}
function applyContextMenu(win) {
win.webContents.on('context-menu', (event, params) => {
const menuItems = []
let haveContext = false;
// Add context actions for misspelling words and typos
const menuMisspellingItems = [
...params.dictionarySuggestions.map(suggestion => ({
label: suggestion,
click: () => win.webContents.replaceMisspelling(suggestion),
})),
{ type: 'separator' },
{
//label: 'Add to dictionary',
label: 'Добавить в словарь',
click: () => win.webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord),
},
{ type: 'separator' },
]
if (params.misspelledWord) {
menuItems.push(...menuMisspellingItems)
haveContext = true;
}
// Add context actions for handling images
const menuImageItems = [
{
//label: 'Copy image',
label: 'Скопировать картинку',
click: () => win.webContents.copyImageAt(params.x, params.y),
},
{
//label: 'Save image',
label: 'Сохранить картинку',
click: () => win.webContents.downloadURL(params.srcURL),
},
{ type: 'separator' },
]
if (params.hasImageContents) {
menuItems.push(...menuImageItems)
haveContext = true;
}
// Add context actions for handling links
const menuLinkItems = [
{
//label: 'Copy link address',
label: 'Скопировать адрес ссылки',
click: () => clipboard.writeText(params.linkURL),
},
{
//label: 'Copy link text',
label: 'Скопировать текст ссылки',
click: () => clipboard.writeText(params.linkText.trim() || params.linkURL),
},
{ type: 'separator' },
]
if (params.linkURL && isExternalLink(params.linkURL)) {
menuItems.push(...menuLinkItems)
haveContext = true;
}
// Add context actions for clipboard events and text editing
const menuClipboardItems = [
{
role: 'copy',
label: 'Скопировать',
enabled: params.selectionText && params.editFlags.canCopy,
},
{
role: 'cut',
label: 'Вырезать',
enabled: params.selectionText && params.isEditable && params.editFlags.canCut,
visible: params.isEditable,
},
{
role: 'selectAll',
label: 'Выбрать всё',
enabled: params.editFlags.canSelectAll,
},
{
role: 'paste',
label: 'Вставить',
enabled: params.isEditable && params.editFlags.canPaste,
visible: params.isEditable,
},
{ type: 'separator' },
]
if (params.isEditable || params.selectionText.length) {
menuItems.push(...menuClipboardItems)
haveContext = true;
}
// TODO Remove or hide from production DevTools toggle before final release
//menuItems.push({ role: 'toggleDevTools' })
if (haveContext) {
Menu.buildFromTemplate(menuItems).popup()
}
})
}
function getSettings(win) {
//console.log(code);
win.webContents.executeJavaScript(`loadSettings(`+JSON.stringify(store.store)+`);`);
}
function setSettings(message,win) {
try {
if (JSON.parse(message).action == 'save_settings') {
obj = JSON.parse(JSON.parse(message).settings);
for (var key in obj){
store.set(key, obj[key]);
}
//win.close();
app.relaunch();
app.exit(0);
}
}
catch (err) {
//console.log(err);
//dialog.showErrorBox('Ошибка', "Подробнее: "+JSON.stringify(err));
}
}
/*function switchSpinner(state) {
if (state) {
// prevent memory leaking
if (win_loading) {
win_loading.destroy();
}
win_loading = new BrowserWindow({
//modal: !isMac,
frame : false,
movable: false,
focusable: false,
icon:icon,
minWidth: 512, // temporary restrict min window width by 512px,
title: app.getName() + " - " + store.get('server_url') + " - Загрузка...",
resizable:false,
parent: win,
opacity: 0.6, // return in case of not using electron-acrylic-window
//vibrancy: 'fullscreen-ui', // on MacOS
//backgroundMaterial: 'acrylic', // on Windows 11
transparent: true, // on linux, also see css
show: false
})
win_loading.loadFile('loading.html');
// TODO change y position for linux
//win_loading.setEnabled(false);
//win_loading.setOpacity(0.8)
//win.hide();
//if (!store.get('start_hidden')) {
if (isLinux) {
if ((!initialized)) {
// linux first run +29px fix (check non-KDE...)
win_loading.setBounds({x: store.get('bounds').x, y: store.get('bounds').y, width: store.get('bounds').width, height:store.get('bounds').height + 29} );
} else {
win_loading.setBounds({x: store.get('bounds').x, y: store.get('bounds').y - 29, width: store.get('bounds').width, height:store.get('bounds').height + 29} );
}
} else {
win_loading.setBounds(store.get('bounds'));
}
if (win.isVisible()) {
if (isLinux) {
win.setResizable(false)
}
win_loading.show();
}
} else {
win_loading.hide();
if (win.isVisible()) {
win.setResizable(true)
win.focus();
}
}
// show devtools
//win_loading.webContents.openDevTools()
}*/
function openSettings() {
if (!(settings_opened)) {
let win_settings = new BrowserWindow({
modal: !isMac,
icon:icon,
title:'Настройки',
width: 500,
height: 300,
resizable:false,
parent: win
})
win_settings.loadFile('settings.html');
win_settings.setMenu(null);
// save app name title
win_settings.on('page-title-updated', function(e) {
e.preventDefault()
});
win_settings.once('ready-to-show', () => {
if (isMac) {
win.show();
app.dock.show();
}
win_settings.show();
settings_opened = true;
getSettings(win_settings);
win_settings.webContents.on('console-message', (event, level, message, line, sourceId) => {
setSettings(message,win_settings);
});
});
win_settings.on('closed', function(e) {
settings_opened = false;
});
//win_settings.webContents.openDevTools()
}
}
function openPopup(url) {
// check for cloud profile link
let allow_navi = false;
if (url.includes('/settings/user')) {
title = "Настройки пользователя" + " - " + store.get('server_url');
allow_navi = true;
} else if (url.includes('/u/')) {
title = "Профиль" + " - " + store.get('server_url')
} else {
title = "Помощь" + " - " + store.get('server_url')
}
let win_popup = new BrowserWindow({
modal: !isMac,
icon:icon,
title:title,
parent: win
})
var theUrl = url;
win_popup.loadURL(theUrl);
win_popup.setMenu(null);
//block_gui_loading(false);
// save app name title
win_popup.on('page-title-updated', function(e) {
e.preventDefault()
});
// add app styling override for cloud
win_popup.on('ready-to-show', () => {
win_popup.show();
win_popup.webContents.insertCSS('#app-content div.admin.access__section, #app-content div.shared.access__section, #app-content .social-button, #header, div.profile__wrapper div.profile__sidebar div.user-actions,#app-content-vue a[href*="/settings/user"] {display:none!important;}');
win_popup.webContents.insertCSS('#content-vue { margin-top: 0px!important; height: 100% !important;}');
})
win_popup.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
})
// prevent navigation away from help pages
win_popup.webContents.on('will-navigate', (event,redirectUrl) => {
if (!(allow_navi)) {
// check for nextcloud help urls
if (!(redirectUrl.includes('docs.nextcloud.com'))) {
event.preventDefault();
}
}
});
//win_popup.webContents.openDevTools()
}
// function to create badge img buffer 16x16
async function createBadge (unread,purpose) {
//unread = 13
// commented for telegram style non-notificationable unread messages
/*if (purpose == "tray") {
var badge_color = "grey"
var text_color = "wheat"
}*/
if ((purpose == "taskbar")||(purpose == "tray")) {
if (isMac) {
if (theme == 'dark') {
var badge_color = "white"
var text_color = "black"
} else {
var badge_color = "black"
var text_color = "white"
}
} else {
var badge_color = "red"
var text_color = "white"
}
var font_size = "65"
}
if (unread >= 100) {
unread = '∞'
font_size = "90"
}
// colored text
let font_family = !isLinux ? "system-ui, -apple-system, 'Segoe UI', Roboto, Oxygen-Sans, Cantarell, Ubuntu, 'Helvetica Neue', 'Noto Sans', 'Liberation Sans', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'" : "Noto Sans"
var SVGtext = `<text style="fill: `+text_color+`; stroke: `+text_color+`; /*stroke-width:3*/" font-family="`+font_family+`" font-size="`+font_size+`" text-anchor="middle" x="40" y="65" >`+unread+`</text>`
// transparent text
//var SVGtext = `<mask id="clip"><rect width="100%" height="100%" fill="`+text_color+`"/><text font-size="`+font_size+`" font-weight="bold" text-anchor="middle" x="40" y="65">`+unread+`</text></mask>`
// for colored text
var badge = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="82"><circle cx="41" cy="41" r="40.5" fill="`+badge_color+`" />`+SVGtext+`</svg>`;
// for transparent text
//var badge = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="82"><circle cx="41" cy="41" r="40.5" fill="`+text_color+`" /><circle mask="url(#clip)" stroke-width="2" style="stroke:`+badge_color+`;" cx="41" cy="41" r="40.5" fill="`+badge_color+`" />`+SVGtext+`</svg>`
//var badge = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="82"><circle mask="url(#clip)" stroke-width="2" style="stroke:`+text_color+`;" cx="41" cy="41" r="40.5" fill="`+badge_color+`" />`+SVGtext+`</svg>`
convertIcon(badge,unread,purpose)
}
// convert icon to B&W
async function bw_icon_process(icon) {
if (theme == 'dark') {
var linear = 3 // for white color
} else {
var linear = 0 // for black color
}
var newImage = await sharp(icon.toPNG()).greyscale().linear(linear, 0).png({colors:2}).toBuffer();
return nativeImage.createFromBuffer(newImage);
}
async function convertIcon (badge,unread,purpose) {
if (purpose == "tray") {
//let newImage = await sharp(Buffer.from(badge)).toBuffer();
// process icon for macos to black and white colors
if (isMac) {
icon = await bw_icon_process(icon)
}
// var newImage = await sharp(Buffer.from(badge)).toBuffer();
var newImage = await sharp(icon.toPNG()).toBuffer();
newImage = await sharp(newImage).resize(120, 120).toBuffer();
newImage = await sharp(newImage).composite([{ input: Buffer.from(badge), top: 45, left: 45, blend: 'over'}]).toBuffer();
trayIcon = nativeImage.createFromBuffer(newImage);
// set linux taskbar image same as tray
if (isLinux) {
win.setIcon(trayIcon)
}
if (isMac) {
trayIcon = trayIcon.resize({width:16});
}
appIcon.setImage(trayIcon);
// apply theme to the tray icon - don't apply
//trayIcon.setTemplateImage(true);
// tray icon title
appIcon.setToolTip(app.getName()+ " - " + store.get('server_url') + " - Непрочитанных сообщений: " + unread);
win.setTitle(app.getName() + " - " + store.get('server_url') + " - Непрочитанных сообщений: " + unread)
return;
}
if (purpose == "taskbar") {
// windows the icon to display on the bottom right corner of the taskbar icon
let newImage = await sharp(Buffer.from(badge)).toBuffer();
win.setOverlayIcon(nativeImage.createFromBuffer(newImage), 'Непрочитанных сообщений: '+ unread);
return;
}
}
/*function addNotificationToTray () {
console.log("Found unread notification!");
let trayIcon = icon_notification.resize({width:16});
// apply theme to the tray icon
trayIcon.setTemplateImage(true);
// set mac dock icon
if (isMac) {
//app.dock.setIcon(icon_notification);
app.dock.setBadge(' ');
}
appIcon.setImage(trayIcon);
is_notification = true;
if (store.get('show_on_notify')) {
win.show();
if (isMac) app.dock.show();
}
win.flashFrame(true);
win.setOverlayIcon(icon_notification, 'Есть непрочитанные уведомления');
appIcon.setToolTip(app.getName()+" - Есть непрочитанные уведомления");
}*/
async function UnreadTray (unread,removed) {
//console.log("Found " + unread +" messages!");
// create icon with unread counter
if (unread === 0) {
// apply theme to the tray icon - don't apply
//trayIcon.setTemplateImage(true);
// set mac dock icon
if (isMac) {
//app.dock.setIcon(icon);
app.dock.setBadge('');
icon_bw = await bw_icon_process(icon);
trayIcon = icon_bw.resize({width:16});
} else {
trayIcon = icon/*.resize({width:16});*/
}
appIcon.setImage(trayIcon);
//is_notification = false;
win.flashFrame(false);
win.setOverlayIcon(null, '');
// tray icon badge
appIcon.setToolTip(app.getName() + " - " + store.get('server_url'));
} else {
createBadge(unread,"tray");
//let trayIcon = icon_notification.resize({width:16});
createBadge(unread,"taskbar");
// set mac dock icon
if (isMac) {
//app.dock.setIcon(icon_notification);
app.dock.setBadge(unread.toString());
}
//is_notification = true;
if (store.get('show_on_new_message')) {
win.show();
if (isMac) app.dock.show();
}
if ((!removed)&&(!win.isFocused())) {
win.flashFrame(true);
}
}
}
/*function removeNotificationFromTray () {
console.log("Removed notification.");
let trayIcon = icon.resize({width:16});
// apply theme to the tray icon
trayIcon.setTemplateImage(true);
// set mac dock icon
if (isMac) {
//app.dock.setIcon(icon);
app.dock.setBadge('');
}
appIcon.setImage(trayIcon);
is_notification = false;
win.flashFrame(false);
win.setOverlayIcon(null, '');
appIcon.setToolTip(app.getName()+" "+app.getVersion());
}*/
/*function checkWinWidth(win) {
let size = win.getSize();
if ((size[0] < 512) && (store.get('bounds').width >= 512)) {
console.log("Narrow window, reload page to prevent user input block!");
return true;
} else {
return false;
}
}*/
/*function block_gui_loading(state) {
if (state) {
gui_blocked = true
//win.setProgressBar(2, { mode: 'indeterminate' })
win.setEnabled(false);
//win.setOpacity(0.8)
win.setTitle(app.getName() + " - " + store.get('server_url') + ' - Загрузка...');
switchSpinner(true)
} else {
gui_blocked = false
//win.setProgressBar(-1)
win.setEnabled(true);
//win.setOpacity(1);
switchSpinner(false)
//console.log(unread)
if (unread != 0) {
// set linux taskbar image same as tray
if (isLinux) {
win.setIcon(icon)
}
win.setTitle(app.getName() + " - " + store.get('server_url') + " - Непрочитанных сообщений: " + unread);
} else {
// set linux taskbar image same as tray
if (isLinux) {
win.setIcon(icon)
}
win.setTitle(app.getName() + " - " + store.get('server_url'));
}
//if(appIcon === null) {
// appIcon.setToolTip(app.getName() + " - " + store.get('server_url'));
//}
}
}*/
async function createWindow () {
// for SSO setting, allowed domains
if (store.get('allow_domain')) {
session.defaultSession.allowNTLMCredentialsForDomains(store.get('allow_domain'));
}
// Create the browser window.
win = new BrowserWindow({
title: app.getName() + " - " + store.get('server_url'),
center: true,
show: store.get('start_hidden') ? !JSON.parse(store.get('start_hidden')) : true,
resizable: true,
minWidth: 512, // temporary restrict min window width by 512px,
// see issues https://github.com/nextcloud/spreed/issues/12236
// https://github.com/nextcloud/spreed/issues/11454
icon:icon,
useContentSize: true,
webPreferences: {
enableRemoteModule: true,
backgroundThrottling: false,
//preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
}
});
// set always on top
if (store.get('always_on_top') ) {
win.setAlwaysOnTop(true, 'floating', 1);
}
win.setBounds(store.get('bounds'));
// hanlde open external links in system browser
win.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
//customize about
app.setAboutPanelOptions({
applicationName: app.getName(),
applicationVersion: "v."+app.getVersion(),
authors: ["drlight17"],
version: app.getVersion(),
copyright: "Lisense AGPLv3 ©2024",
iconPath: iconPath,
website: "https://github.com/drlight17/talk-electron"
});
// to set app.name instead of electron.app.Electron in Windows notifications
if (!(isMac))
{
app.setAppUserModelId(app.name);
}
win.on("maximize", function () {
checkMaximize();
})
win.on("unmaximize", function () {
checkMaximize();
})
// as linux don't respect win.setEnabled(false) for minimize operations
/*win.on("minimize", function () {
if ((isLinux) && (gui_blocked)) {
win_loading.hide();
}
})
win.on("restore", function () {
if ((isLinux) && (gui_blocked)) {
win_loading.show();
}
})*/
//Do debounce with 500 ms
let debounce;
win.on("resize", function () {
clearTimeout(debounce);
debounce = setTimeout(function() {
// force page refresh to prevent user input text block in narrow (< 512px) window - deprecated and commented.
/*if (checkWinWidth(win)) {
win.reload();
}*/
store.set('bounds', win.getBounds());
// check 0.2.4-alpha BUG pinned/maximized window
//win.focus();
}, 200);
})
// for linux compatibility change "moved" to "move"
win.on("move", function () {
clearTimeout(debounce);
debounce = setTimeout(function() {
/*if (checkWinWidth(win)) {
win.reload();
}*/
//console.log(win.getBounds().y)
store.set('bounds', win.getBounds());
// check 0.2.4-alpha BUG pinned/maximized window
//win.focus();
}, 200);
})
// Prevent window from closing and quitting app
// Instead make close simply hide main window
// Clicking on tray icon will bring back main window
win.on('close', event => {
event.preventDefault();
store.set('bounds', win.getBounds());
if (isMac) app.dock.hide();
win.hide();
})
win.on('hide', event => {
store.set('bounds', win.getBounds());
})
// save app name title
win.on('page-title-updated', function(e) {
e.preventDefault()
});
win.on('show', function () {
win.setBounds(store.get('bounds'));
if (isMac) app.dock.setIcon(icon);
//if (is_notification) {
if (unread != 0) {
createBadge(unread,"taskbar");
//win.setOverlayIcon(icon_notification, 'Есть непрочитанные уведомления');
if (isMac) {
// remove badge prior to set new badge!
app.dock.setBadge('');
//console.log(unread)
app.dock.setBadge(unread.toString());
}
} else {
win.setOverlayIcon(null, '');
if (isMac) app.dock.setBadge('');
}
})
// some things when window is ready
win.on('ready-to-show', () => {
// load icon from server
if (store.get('use_server_icon')) {
//console.log("Let's get server icon")
let icon_url = store.get('server_url')+"/apps/theming/image/logo";
const fetchImage = async url => {
const response = await fetch(url);
const buffer = await response.arrayBuffer();
const nodebuffer = Buffer.from(buffer);
icon = nativeImage.createFromBuffer(nodebuffer)
// apply theme to the tray icon - don't apply
//trayIcon.setTemplateImage(true);
// set mac dock icon
if (isMac) {
icon_bw = await bw_icon_process(icon);
trayIcon = icon_bw.resize({width:16});
app.dock.setIcon(icon);
} else {
trayIcon = icon/*.resize({width:16});*/
}
appIcon.setImage(trayIcon);
win.setIcon(icon);
}
fetchImage(icon_url);
}
// hide dock if win is hidden
if ((!win.isVisible()) && (isMac)) app.dock.hide();
// add app styling override
win.webContents.insertCSS(fs.readFileSync(path.join(__dirname, 'styles.css'), 'utf8'));
})
//block_gui_loading(true);
win.loadURL(url);
preventUnsupportedBrowser(win);
// apply context menus
// BUG since 19.x Talk version double call ready-to-show
applyContextMenu(win)
// no need since we have nextcloud_check observer script below
/*win.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
win.close();
appIcon.destroy();
dialog.showErrorBox('Ошибка','Nextcloud или Talk необходимых версий не найдены!');
setServerUrl (store.get('server_url')||url_example);
})*/
/*win.webContents.on('did-start-loading', () => {
if (!gui_blocked) {
block_gui_loading(true);
}
});*/
// check cloud
win.webContents.on('did-finish-load', function(e) {
/*if (!store.get('start_hidden')) {
win.show()
}*/
preventUnsupportedBrowser(win);
// get notification dot status on webContents change
//win.webContents.executeJavaScript(fs.readFileSync(path.join(__dirname, 'notification_observer.js')), true)