-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
483 lines (420 loc) · 11.7 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
const {app, Menu, Tray, BrowserWindow, nativeImage, ipcMain} = require('electron')
const path = require('path')
const fs = require('fs')
const url = require('url')
const child_process = require('child_process')
const _ = require('underscore')
const DEBUG = false
const CWD = process.cwd()
const execOpts = { cwd: CWD, stdio: [0, 1, 2], sync: true } // stdio is only needed for execSync|spawn
const settingsPath = path.join(app.getPath('userData'), 'settings.json')
const assetsDirectory = path.join(__dirname, 'assets')
const defaultTheme = 'light-theme' // or 'dark-theme'
let settings = {}
let currentUser = undefined
let autoSwitchTimeout = undefined
app.dock.hide()
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let tray
// ///////////
// Helpers //
// ///////////
const log = (err, stdout, stderr) => {
if (err) process.stdout.write(`${err}\n`)
if (stderr !== null && stderr !== '') process.stdout.write(`${stderr}\n`)
if (stdout !== null && stdout !== '') process.stdout.write(`${stdout}\n`)
}
const execute = (cmd, opts, callback) => {
if (_(opts).isFunction()) {
callback = opts
opts = {}
}
opts = _(execOpts).extend(opts)
if (opts.sync || !_.isArray(cmd)) {
if (DEBUG) console.log('--', 'Sync command: ', JSON.stringify(cmd), JSON.stringify(opts), callback)
if (_.isArray(cmd)) cmd = cmd.join(' ') // escape(cmd)
child_process.exec(cmd, opts, callback)
} else {
return new Promise((resolve, reject) => {
if (DEBUG) console.log('--', 'Spawn command', JSON.stringify(cmd), cmd.join(' '), JSON.stringify(opts))
const spawned = child_process.spawn(cmd.shift(), cmd, opts)
spawned.on('close', (err) => {
if (err != 0) log(`Process exited with code ${err}`, false, false)
if (err != 0) reject(err, false, false)
// else reject(err)
})
spawned.stdout.on('data', (data) => {
if (callback) callback(false, data, false)
else resolve(data)
})
})
}
}
function getGitInfo() {
return new Promise((resolve, reject) => {
execute('git config --global user.name', (err, username) => {
execute('git config --global user.email', (err, email) => {
if (!_(username).isString() || !_(email).isString()) {
resolve({})
return false
}
username = username.replace('\n', '')
email = email.replace('\n', '')
currentUser = undefined
const ob = {}
for (const key in settings.profiles) {
if (settings.profiles[key].username == username && settings.profiles[key].email == email) {
currentUser = key
ob[key] = settings.profiles[key]
break
}
}
if (!currentUser) {
const id = Date.now()
currentUser = id
ob[id] = {
label: username,
username: username,
email: email
}
}
resolve(ob)
})
})
})
}
function setGitInfo(key) {
return new Promise((resolve, reject) => {
if (!settings.profiles[key]) return reject()
execute(`git config --global user.name \"${settings.profiles[key].username}\"`, (name) => {
execute(`git config --global user.email \"${settings.profiles[key].email}\"`, (email) => {
currentUser = key
getGitInfo()
.then(resolve)
.catch(reject)
})
})
})
}
function checkIfRightUser() {
return new Promise((resolve, reject) => {
if( settings.backToPreviousUser && settings.previousUser){
setPreviousUser()
}
resolve();
})
}
// ///////////
// /// UI ////
// ///////////
const getWindowPosition = () => {
const windowBounds = mainWindow.getBounds()
const trayBounds = tray.getBounds()
// Center window horizontally below the tray icon
const x = Math.round(trayBounds.x + (trayBounds.width / 2) - (windowBounds.width / 2))
// Position window 4 pixels vertically below the tray icon
const y = Math.round(trayBounds.y + trayBounds.height + 4)
return {x: x, y: y}
}
const showWindow = () => {
const position = getWindowPosition()
mainWindow.setPosition(position.x, position.y, false)
mainWindow.show()
mainWindow.focus()
}
const toggleWindow = () => {
if (mainWindow.isVisible()) {
mainWindow.hide()
} else {
showWindow()
}
}
const getTrayMenu = function() {
const minute = 60000
return Menu.buildFromTemplate([
{
label: 'Current profile:',
enabled: false
},
{
label: settings.profiles[currentUser].label,
enabled: false
},
{
type: 'separator'
},
{
label: 'Temporary switch:',
enabled: false
},
{
type: 'radio',
label: 'Disabled',
checked: settings.temporarySwitch === false,
click: () => changeTemporarySwitch(false)
},
{
type: 'radio',
label: '1 min',
checked: settings.temporarySwitch === minute,
click: () => changeTemporarySwitch(minute)
},
{
type: 'radio',
label: '30 min',
checked: settings.temporarySwitch === 30 * minute,
click: () => changeTemporarySwitch(30 * minute)
},
{
type: 'radio',
label: '1 hour',
checked: settings.temporarySwitch === 60 * minute,
click: () => changeTemporarySwitch(60 * minute)
},
{
type: 'radio',
label: '4 hour',
checked: settings.temporarySwitch === 4 * 60 * minute,
click: () => changeTemporarySwitch(4 * 60 * minute)
},
{
type: 'radio',
label: '12 hour',
checked: settings.temporarySwitch === 12 * 60 * minute,
click: () => changeTemporarySwitch(12 * 60 * minute)
},
{
type: 'separator'
},
{
label: 'Select theme:',
enabled: false
},
{
type: 'radio',
label: 'Light theme',
checked: getCurrentTheme() == 'light-theme',
click: changeTheme
},
{
type: 'radio',
label: 'Dark theme',
checked: getCurrentTheme() == 'dark-theme',
click: changeTheme
},
{
type: 'separator'
},
{
type: 'checkbox',
label: 'Start at login',
checked: getAutoStart() == true,
click: toggleAutoStart
},
{
type: 'separator'
},
{
label: 'Quit',
click() { app.quit() }
}
])
}
function createTray() {
tray = new Tray(path.join(assetsDirectory, 'logoTemplate.png'))
tray.on('right-click', () => { tray.popUpContextMenu(getTrayMenu()) })
tray.on('double-click', toggleWindow)
tray.on('click', toggleWindow)
createWindow()
return true
}
function createWindow(state) {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 300,
height: 350,
show: false,
frame: false,
fullscreenable: false,
resizable: false,
transparent: false,
webPreferences: {
nodeIntegration: true,
backgroundThrottling: false,
}
})
mainWindow.custom = {
'currentState': state ? state : 'profile-list',
'theme': getCurrentTheme()
}
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, '/client/public/index.html'),
protocol: 'file:',
slashes: true
}))
// Hide the window when it loses focus
mainWindow.on('blur', () => {
if (!mainWindow.webContents.isDevToolsOpened()) {
mainWindow.hide()
}
})
}
// ///////////
// // APP ////
// ///////////
function readSettings() {
return new Promise((resolve, reject) => {
try {
settings = fs.readFileSync(settingsPath, 'utf-8')
settings = JSON.parse(settings)
if (DEBUG) console.log('Loaded file:' + settingsPath, settings)
resolve(settings)
} catch (err) {
if (DEBUG) console.log('Error reading the file: ' + JSON.stringify(err))
reject(null)
}
})
}
function saveSettings() {
try {
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 4), 'utf-8')
} catch (e) {
alert('Failed to save the file !')
}
}
function insertOrUpdateSetting(ob) {
if (!settings.profiles) { settings.profiles = {} }
_(settings.profiles).extend(ob)
saveSettings()
}
function removeSetting(key) {
if (!settings.profiles || settings.profiles[key] == null) return
delete settings.profiles[key]
saveSettings()
}
function getAllSettings() {
return settings.profiles
}
function activateSetting(key) {
if (!settings.profiles[key]) {
return
}
if (autoSwitchTimeout) {
clearTimeout(autoSwitchTimeout)
}
settings.backToPreviousUser = false
settings.previousUser = currentUser
setGitInfo(key)
if (settings.temporarySwitch) {
settings.backToPreviousUser = Date.now() + settings.temporarySwitch
autoSwitchTimeout = setTimeout(setPreviousUser, settings.temporarySwitch)
saveSettings()
}
}
function getCurrentTheme() {
return settings.theme ? settings.theme : defaultTheme
}
function setPreviousUser() {
setGitInfo(settings.previousUser)
notifyUserChange()
settings.backToPreviousUser = false
settings.previousUser = false
saveSettings()
}
function changeTheme() {
if (getCurrentTheme() == 'light-theme') {
settings.theme = 'dark-theme'
} else {
settings.theme = 'light-theme'
}
mainWindow.webContents.send('changeTheme', settings.theme)
saveSettings()
}
function changeTemporarySwitch(value) {
settings.temporarySwitch = value
saveSettings()
}
function notifyUserChange(){
mainWindow.webContents.send('changeUser', settings.profiles[currentUser].label)
}
function getAutoStart() {
return settings.autostart ? settings.autostart : false
}
function toggleAutoStart() {
settings.autostart = !getAutoStart()
setAutoStart()
}
function setAutoStart() {
app.setLoginItemSettings({
openAtLogin: !! settings.autostart,
})
saveSettings()
}
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
(function() {
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', function() {
// createWindow()
ipcMain.on('callSyncMethod', (event, type, data) => {
if (DEBUG) console.log(type, data)
switch (type) {
case 'getCurrentUser':
// update currentUser
getGitInfo()
event.returnValue = currentUser
break
case 'getSettings':
event.returnValue = getAllSettings()
break
case 'removeSetting':
removeSetting(data)
event.returnValue = true
break
case 'activateSetting':
activateSetting(data)
event.returnValue = true
break
case 'insertOrUpdateSetting':
insertOrUpdateSetting(data)
event.returnValue = true
break
}
})
readSettings()
.then(getGitInfo)
.then(insertOrUpdateSetting)
.then(checkIfRightUser)
.then(createTray)
.then(setAutoStart)
.catch(() => {
if (DEBUG) console.log('First launch probably!')
return getGitInfo()
.then(insertOrUpdateSetting)
.then(createTray)
.then(setAutoStart)
.catch(log)
})
})
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function() {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
createTray()
}
})
})()