This repository has been archived by the owner on Mar 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.js
497 lines (445 loc) · 13.4 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
/* eslint-disable */
const fs = require('fs');
const electron = require('electron');
const app = electron.app;
const globalShortcut = electron.globalShortcut;
const BrowserWindow = electron.BrowserWindow;
const {
ipcMain
} = require('electron');
const ipc = require('electron').ipcMain;
ipc.on('errorInWindow', function(event, error, url, line){
console.log(url, line, error);
});
const dialog = require('electron').dialog;
const {
Menu
} = require('electron');
const appMenu = require('./scripts/appMenu');
const {
clipboard,
Tray
} = require('electron');
let tray = null;
let globalShot;
/**
* Окно приложения
*/
let appWindow;
const argv = require('minimist')(process.argv);
let gettedDbToken;
let gettedIMToken;
/**
* Опции диалога о новом скриншоте
* @type {{type: string, title: string, message: string, buttons: string[]}}
*/
const newShotDialog = {
type: 'info',
title: 'Create new shot',
message: 'All your progress will be lost. Are you sure?',
buttons: ['Yes', 'No']
};
const signInDialog = {
type: 'info',
title: 'Sign out',
message: `You're authorized user. Would you want to sign out?`,
buttons: ['Yes', 'No']
};
let appFirstStart = true;
const shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
// apply params from console
if (commandLine[1]) {
parseAndDo(commandLine[1]);
return true;
}
// Someone tried to run a second instance, we should focus our window
if (appWindow) {
if (appWindow.isMinimized()) appWindow.restore();
appWindow.focus();
}
return true;
});
if (shouldQuit) {
app.quit();
return;
}
/**
* Создаём окно, когда приложение инициализировано
* И регистрируем необходимые клаиши для обработки истории
*/
app.on('ready', () => {
tray = new Tray(__dirname + '/icon.png');
createWindow();
rigesterGlobalHotkey();
const template = appMenu(app, appWindow, getDropboxToken, getImgurToken);
const menu = Menu.buildFromTemplate(template);
/**
* Содаём меню приложения
*/
Menu.setApplicationMenu(menu);
app.firstStartTray = true;
appWindow.hide();
tray.setToolTip('--shots');
});
app.on('will-quit', () => {
globalShortcut.unregisterAll();
});
/**
* Уничтожаем процесс, когда все окна закрыты
*/
app.on('window-all-closed', function() {
if (process.platform !== 'darwin') {
app.quit();
}
});
/**
* Принимаем сообщения из рендера и отвечаем на них
*/
ipcMain.on('synchronous-message', (event, arg, data) => {
if (arg === 'hide') {
event.returnValue = 'ok';
appWindow.hide();
} else if (arg === 'crop') {
event.returnValue = 'ok';
} else if (arg === 'rect') {
event.returnValue = 'ok';
} else if (arg === 'pen') {
event.returnValue = 'ok';
} else if (arg === 'arrow') {
event.returnValue = 'ok';
} else if (arg === 'optimize') {
let oImg = optimizeShots(data);
event.returnValue = 'data';
} else if (arg === 'version') {
event.returnValue = app.getVersion();
} else if (arg === 'dropbox-token') {
validateDropboxToken(data);
event.returnValue = 'ty';
} else if (arg === 'imgur-token') {
validateImgurToken(data);
event.returnValue = 'ty';
} else if (arg === 'createNew') {
if (data === 'ask') {
dialog.showMessageBox(newShotDialog, function(index) {
// если пользователь подтвердил выбор — далем новый скриншот
if (index === 0) {
appWindow.webContents.send('new');
}
event.returnValue = 'not-ok';
})
} else {
appWindow.webContents.send('new');
event.returnValue = 'ok';
}
// event.returnValue = app.getVersion();
} else{
appWindow.show();
appWindow.setPosition(0,0);
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize;
appWindow.setSize(width, height);
}
});
/**
* Выводим диалог перед новым скриншотом
*/
ipc.on('open-information-dialog', function() {
dialog.showMessageBox(newShotDialog, function(index) {
// если пользователь подтвердил выбор — далем новый скриншот
if (index === 0) {
appWindow.webContents.send( 'new' );
}
})
});
/**
* Выводим диалог перед деавторизацией
*/
ipc.on('open-signin-dialog', function() {
dialog.showMessageBox(signInDialog, function(index) {
// если пользователь подтвердил выбор — далем новый скриншот
if (index === 0) {
appWindow.webContents.send( 'signout' );
}
})
});
ipc.on('open-save-dialog', function(event, data, path) {
let saveDialogOption = {
filters: [{name: 'Images', extensions: ['png']}]
}
if (path !== null) {
saveDialogOption.defaultPath = path;
}
dialog.showSaveDialog(saveDialogOption, function(path) {
if (path !== undefined) {
fs.writeFile(path, data);
appWindow.webContents.send( 'successSave', path );
} else {
appWindow.webContents.send( 'canceledSave');
}
});
});
/**
* Метод создания окна приложения
*/
function createWindow() {
appWindow = new BrowserWindow({
width: 0,
height: 0,
icon: __dirname + '/icon.png'
});
if (process.platform === 'darwin') {
appWindow.loadURL(`file://${__dirname}/index.mac.html`);
} else {
appWindow.loadURL(`file://${__dirname}/index.html`);
}
if (argv.debug) {
appWindow.webContents.openDevTools();
}
appWindow.on('closed', function() {
appWindow = null;
});
let contextMenu = createContextMenu(true, false, false);
tray.setContextMenu(contextMenu);
app.firstStartTray = false;
appWindow.on('minimize', function() {
contextMenu = createContextMenu(false, true, false);
tray.setContextMenu(contextMenu);
});
appWindow.on('hide', function() {
if (app.firstStartTray === true) {
contextMenu = createContextMenu(true, false, false);
tray.setContextMenu(contextMenu);
app.firstStartTray = false;
} else {
contextMenu = createContextMenu(true, true, false);
tray.setContextMenu(contextMenu);
}
});
appWindow.on('show', function() {
contextMenu = createContextMenu(true, false, true);
tray.setContextMenu(contextMenu);
if(app.createShot === true) {
appWindow.webContents.send( 'new' );
app.createShot = false;
}
});
appWindow.setAutoHideMenuBar(false);
let processStartFlags = Object.keys(argv)[1];
if ((processStartFlags) && (processStartFlags !== 'debug')) {
parseAndDo(`-${processStartFlags}`);
if (['h','help','a','about','v','version'].indexOf(processStartFlags) !== -1) {
app.exit(0);
}
}
}
function createContextMenu(newShot, open, tray) {
return (
Menu.buildFromTemplate([{
label: 'New',
enabled: newShot,
click() {
if (appFirstStart) {
app.createShot = true;
appWindow.webContents.send('new');
appWindow.setPosition(0,0);
appWindow.show();
appFirstStart = false;
return;
}
app.createShot = true;
appWindow.webContents.send('saveState');
}
},
{
label: 'Open',
enabled: open,
click() {
appWindow.show();
appWindow.setPosition(0,0);
}
},
{
label: 'Minimize to tray',
enabled: tray,
click() {
appWindow.hide();
}
},
{
label: 'Disable shortcuts',
type: 'checkbox',
click(element) {
if (element.checked === true) {
globalShortcut.unregisterAll();
} else {
rigesterGlobalHotkey();
}
}
},
{
label: 'Quit',
click() {
globalShortcut.unregisterAll();
app.quit()
}
}])
);
}
function parseAndDo(flagName) {
switch (flagName) {
case '--help':
case '-help':
case '-h':
console.log(
`Usage:
shots [option]
Options:
-v, --version | print --shots version
-h, --help | show all commands
-a, --about | about --shots
-n, --new | create screenshot
-c, --capture | capture screenshot and call crop tool
-f, --fast | capture screenshot and save
-s, --save | save current screenshot
Example:
shots -v --> shots ${app.getVersion()}
`);
break;
case '--version':
case '-version':
case '-v':
console.log(`--shots ${app.getVersion()}`);
break;
case '--about':
case '-about':
case '-a':
console.log('--shots is an application for creating screenshots.\n' +
'It was created on web-technologies.\nhttps://github.com/binjospookie/--shots');
break;
case '--capture':
case '-capture':
case '-c':
dialog.showMessageBox(newShotDialog, function(index) {
// если пользователь подтвердил выбор — далем новый скриншот
if (index === 0) {
app.createShot = true;
appWindow.webContents.send('new', 'capture');
appWindow.setPosition(0,0);
appWindow.show();
appFirstStart = false;
}
})
break;
case '--fast':
case '-fast':
case '-f':
dialog.showMessageBox(newShotDialog, function(index) {
// если пользователь подтвердил выбор — далем новый скриншот
if (index === 0) {
app.createShot = true;
appWindow.webContents.send('new', 'fast');
appWindow.setPosition(0,0);
appWindow.show();
appFirstStart = false;
}
})
break;
case '--new':
case '-new':
case '-n':
app.createShot = true;
appWindow.webContents.send('saveState');
break;
case '--save':
case '-save':
case '-s':
if (appFirstStart === true) {
console.log(`Screenshot wasn't create. Try 'shots --new'`);
app.exit(0);
break;
}
appWindow.webContents.send( 'save' );
break;
default:
console.log('Unknown option. Try "shots --help"');
break;
}
}
function optimizeShots(data) {
// console.log('ready')
}
function rigesterGlobalHotkey() {
globalShot = globalShortcut.register('CommandOrControl+Alt+M', () => {
if (appFirstStart) {
app.createShot = true;
appWindow.webContents.send('new');
appWindow.setPosition(0,0);
appWindow.show();
appWindow.focus();
appFirstStart = false;
return;
}
app.createShot = true;
appWindow.webContents.send('saveState');
})
}
// dropbox get token
function getDropboxToken() {
appWindow.webContents.send('isDropbox');
}
function getImgurToken() {
appWindow.webContents.send('isImgur');
}
function validateImgurToken(data) {
let imWindow = new BrowserWindow({
width: 680,
height: 680,
icon: __dirname + '/icon.png'
});
imWindow.loadURL('https://api.imgur.com/oauth2/authorize?client_id=<imgur token>&response_type=token');
imWindow.on('focus', function(){
Menu.setApplicationMenu(null);
})
imWindow.on('blur', function(){
Menu.setApplicationMenu(Menu.buildFromTemplate(appMenu(app, appWindow, getDropboxToken, getImgurToken)));
})
imWindow.on('close', function(event) {
imHistory = imWindow.webContents.history;
console.log(imHistory)
gettedIMToken = imHistory[imHistory.length - 1];
if (!gettedIMToken.includes('access_token=')) {
return;
}
appWindow.webContents.send('freshImgurToken', gettedIMToken);
});
imWindow.on('closed', ()=>{
Menu.setApplicationMenu(Menu.buildFromTemplate(appMenu(app, appWindow, getDropboxToken, getImgurToken)));
dbWindow = null;
});
}
function validateDropboxToken(data) {
// need auth
let dbWindow = new BrowserWindow({
width: 680,
height: 680,
icon: __dirname + '/icon.png'
});
dbWindow.loadURL('https://www.dropbox.com/oauth2/authorize?response_type=token&client_id=TOKEN&redirect_uri=https://theshots.ru/dropbox.html')
dbWindow.on('focus', function(){
Menu.setApplicationMenu(null);
})
dbWindow.on('blur', function(){
Menu.setApplicationMenu(Menu.buildFromTemplate(appMenu(app, appWindow, getDropboxToken, getImgurToken)));
})
dbWindow.on('close', function(event) {
dbHistory = dbWindow.webContents.history;
gettedDbToken = dbHistory[dbHistory.length - 1];
if (!gettedDbToken.includes('access_token=')) {
return;
}
appWindow.webContents.send('freshDropboxToken', gettedDbToken);
});
dbWindow.on('closed', ()=>{
Menu.setApplicationMenu(Menu.buildFromTemplate(appMenu(app, appWindow, getDropboxToken, getImgurToken)));
dbWindow = null;
});
}