-
Notifications
You must be signed in to change notification settings - Fork 6
/
openWindowsTracker.js
648 lines (544 loc) · 24.8 KB
/
openWindowsTracker.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
'use strict';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import Shell from 'gi://Shell';
import Meta from 'gi://Meta';
import * as SystemActions from 'resource:///org/gnome/shell/misc/systemActions.js';
import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';
import * as SaveSession from './saveSession.js';
import * as RestoreSession from './restoreSession.js';
import * as MoveSession from './moveSession.js';
import * as Autoclose from './ui/autoclose.js';
import * as UiHelper from './ui/uiHelper.js';
import * as Log from './utils/log.js';
import {PrefsUtils} from './utils/prefsUtils.js';
import * as FileUtils from './utils/fileUtils.js';
import * as MetaWindowUtils from './utils/metaWindowUtils.js';
import * as Function from './utils/function.js';
import {WindowTilingSupport} from './windowTilingSupport.js';
let _meta_restart = null;
export const OpenWindowsTracker = class {
constructor() {
// TODO Add an (or maybe two: one for save, another for restore) option to Preferences.
// Those apps (its wm_class) in the blacklist will not be saved,
// and will not be restored ether.
// For Guake, too many unnecessary 'Guake saved to xxx' logs
// while it is toggled hidden or shown.
this._blacklist = new Set([
'Guake',
]);
this._windowInterestingSignalsWhileSave = [
'notify::above',
'notify::fullscreen',
'notify::maximized-horizontally',
'notify::maximized-vertically',
'notify::minimized',
'notify::on-all-workspaces',
'notify::title',
'notify::wm-class',
'position-changed',
'size-changed',
'workspace-changed',
];
this._signalsToSaveSummary = [
{
instance: global.display,
signals: ['notify::focus-window']
},
{
instance: global.workspace_manager,
signals: [
'notify::n-workspaces',
'active-workspace-changed'
]
}
];
this._signals = [];
this._windowTracker = Shell.WindowTracker.get_default();
this._defaultAppSystem = Shell.AppSystem.get_default();
this._wm = global.workspace_manager;
this._log = new Log.Log();
this._settings = PrefsUtils.getSettings();
this._saveSession = new SaveSession.SaveSession();
this._moveSession = new MoveSession.MoveSession();
this._restoringSession = false;
this._runningSaveCancelableMap = new Map();
this._windowsAboutToSaveSet = new Set();
this._saveWindowSessionPeriodically();
this._confirmedLogoutId = 0;
this._confirmedRebootId = 0;
this._confirmedShutdownId = 0;
this._closedId = 0;
this._canceledId = 0;
this._busWatchId = Gio.bus_watch_name(
Gio.BusType.SESSION,
'org.gnome.Shell',
Gio.BusNameWatcherFlags.NONE,
this._onNameAppearedGnomeShell.bind(this),
this._onNameVanishedGnomeShell.bind(this)
);
this._display = global.display;
const x11DisplayOpenedId = this._display.connect('x11-display-opened', () => {
this._restoringSession = true;
this._allSavedWindowSessions = [];
// `installed-changed` emits after `shell_app_system_init()` is called
// and all `window-created` emits.
const installedChangedId = this._defaultAppSystem.connect('installed-changed', () => {
// RestoreSession.RestoreSession.restoreFromSummary();
Log.Log.getDefault().info(`Restoring windows states after gnome shell starts`);
this._moveSession.moveApps(this._allSavedWindowSessions);
this._restoringSession = false;
});
this._signals.push([installedChangedId, this._defaultAppSystem]);
});
this._signals.push([x11DisplayOpenedId, this._display]);
const windowCreatedId = this._display.connect('window-created', (display, window, userData) => {
this._onWindowCreatedSaveOrUpdateWindowsMapping(display, window, userData);
this._restoreOrSaveWindowSession(window);
});
this._signals.push([windowCreatedId, this._display]);
this._meta_is_restarting = false;
this._overrideMetaRestart();
this._saveSummaryCancellable = null;
this._summaryAboutToSave = false;
this._connectSignalsToSaveSummary();
this._saveSummary();
this._saveAllWindows();
const settingsChangedToSaveAllWindows = [
'stash-and-restore-states',
'enable-restore-previous-session'
];
settingsChangedToSaveAllWindows.forEach((setting) => {
this._settings.connect(`changed::${setting}`, () => {
if (this._settings.get_boolean(`${setting}`))
this._saveAllWindows();
});
});
const windowTiledId = WindowTilingSupport.connect('window-tiled', (signals, w1, w2) => {
// w2 will be saved in another 'window-tiled'
this._prepareToSaveWindowSession(w1);
});
this._signals.push([windowTiledId, WindowTilingSupport]);
const windowUntiledId = WindowTilingSupport.connect('window-untiled', (signals, w1, w2) => {
this._prepareToSaveWindowSession(w1);
this._prepareToSaveWindowSession(w2);
});
this._signals.push([windowUntiledId, WindowTilingSupport]);
this._overrideSystemActionsPrototypeMap = new Map();
// TODO Users can click the cancel button of EndSessionDialog, and autoclose.js could also call EndSessionDialog.cancel() function,
// I don't know how to distinguish them, therefor set `Autoclose.autocloseObject.sessionClosedByUser` to false in cancelled signal will not work.
// this._overrideSystemActions();
}
/**
* For some apps, like Beyond Compare, if users click the Log Out / Restart / Power Off button,
* they will be closed and their session configs that is used to restore its states at startup
* will also be removed.
*
* We prevent that happening here by overriding some functions to set the flag `Autoclose.autocloseObject.sessionClosedByUser`
* to `true`, just before continuing to operate via DBus provided by gnome-session.
*
* `Autoclose.autocloseObject.sessionClosedByUser` will be set to false while users close or cancel the EndSessionDialog.
*
* see: https://bugzilla.gnome.org/show_bug.cgi?id=782786
*/
_overrideSystemActions() {
// We call SystemActions.SystemActions once, otherwise SystemActions.SystemActions will be undefined.
// A second, SystemActions.SystemActions has value, which is too weird to understand. This issue might be gjs related.
SystemActions.SystemActions;
let overrideFunctions = ['activateLogout', 'activateRestart', 'activatePowerOff'];
overrideFunctions.forEach(funcName => {
const originalFunc = SystemActions.SystemActions.prototype[funcName];
this._overrideSystemActionsPrototypeMap.set(funcName, originalFunc);
SystemActions.SystemActions.prototype[funcName] = function () {
Autoclose.autocloseObject.sessionClosedByUser = true;
Function.callFunc(this, originalFunc);
}
});
}
_overrideMetaRestart() {
const that = this;
_meta_restart = Meta.restart;
Meta.restart = function (message, context) {
that._meta_is_restarting = true;
_meta_restart(message, context);
}
}
_connectSignalsToSaveSummary() {
this._signalsToSaveSummary.forEach(e => {
e.signals.forEach(signal => {
const id = e.instance.connect(signal, () => {
this._summaryAboutToSave = true;
});
this._signals.push([id, e.instance]);
});
});
}
async _saveSummary() {
try {
if (this._restoringSession) return;
if (this._saveSummaryCancellable && !this._saveSummaryCancellable.is_cancelled())
this._saveSummaryCancellable.cancel();
this._saveSummaryCancellable = new Gio.Cancellable();
await this._saveSession.saveSummaryAsync(this._saveSummaryCancellable);
} catch (error) {
Log.Log.getDefault().error(error);
}
}
_saveAllWindows() {
const runningApps = this._defaultAppSystem.get_running();
// runningApps.length is 0 when display opening
// runningApps.length is greater than 0 when this extension enabled
if (runningApps.length) {
for (const app of runningApps) {
const windows = app.get_windows();
for (const window of windows) {
this._prepareToSaveWindowSession(window);
this._connectWindowSignalsToSaveSession(window);
}
}
}
}
async _restoreOrSaveWindowSession(window) {
try {
this._restoreWindowState(window);
this._prepareToSaveWindowSession(window);
this._connectWindowSignalsToSaveSession(window);
} catch (e) {
this._log.error(e);
}
}
_connectWindowSignalsToSaveSession(window) {
this._windowInterestingSignalsWhileSave.forEach(signal => {
const windowSignalId = window.connect(signal, () => {
this._prepareToSaveWindowSession(window);
});
this._signals.push([windowSignalId, window]);
})
}
_restoreWindowState(window) {
if (!this._settings.get_boolean('stash-and-restore-states')) return;
if (!this._restoringSession) return;
const sessionFilePath = `${FileUtils.current_session_path}/${window.get_wm_class()}/${MetaWindowUtils.getStableWindowId(window)}.json`;
// Apps in the `this._blacklist` does not save a session
if (!GLib.file_test(sessionFilePath, GLib.FileTest.EXISTS)) {
if (!this._blacklist.has(window.get_wm_class()))
this._log.warn(`${sessionFilePath} not found while restoring!`);
return;
}
const sessionPathFile = Gio.File.new_for_path(sessionFilePath);
let [success, contents] = sessionPathFile.load_contents(null);
if (!success) {
return;
}
const sessionContent = FileUtils.getJsonObj(contents);
Log.Log.getDefault().debug(`Prepare to restore window session from ${sessionFilePath}`);
this._allSavedWindowSessions.push(sessionContent);
// TODO It's no necessary to put sessions to `RestoreSession.restoreSessionObject.restoringApps` any more, since this job has been done by `MoveSession.moveApps(sessions)`
const app = this._windowTracker.get_app_from_pid(sessionContent.pid);
if (app && app.get_name() == sessionContent.app_name) {
const restoringShellAppData = RestoreSession.restoreSessionObject.restoringApps.get(app);
if (restoringShellAppData) {
restoringShellAppData.saved_window_sessions.push(sessionContent);
} else {
RestoreSession.restoreSessionObject.restoringApps.set(app, {
saved_window_sessions: [sessionContent]
});
}
}
}
async _prepareToSaveWindowSession(window) {
try {
if (!this._settings.get_boolean('stash-and-restore-states')
&& !this._settings.get_boolean('enable-restore-previous-session'))
return;
if (!window) return;
const workspace = window.get_workspace();
// workspace is nullish during gnome shell restarts
if (!workspace) return;
if (this._blacklist.has(window.get_wm_class())) return;
// this._log.debug(`Adding window ${window.get_title()} to queue (current size: ${this._windowsAboutToSaveSet.size}) to prepare to save window session`);
this._windowsAboutToSaveSet.add(window);
} catch (error) {
this._log.error(error);
}
}
_saveWindowSessionPeriodically() {
// TODO Add an option: save session config delay
this._saveSessionByBatchTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 500, () => {
if (this._summaryAboutToSave) {
this._saveSummary().then(() => {
this._summaryAboutToSave = false;
});
}
if (this._windowsAboutToSaveSet.size) {
const windows = [...this._windowsAboutToSaveSet];
windows.forEach(window => {
this._windowsAboutToSaveSet.delete(window);
// Cancel running save operation
this._cancelRunningSave(window);
const cancellable = new Gio.Cancellable();
this._runningSaveCancelableMap.set(window, cancellable);
});
this._saveSession.saveWindowsSessionAsync(
windows,
this._runningSaveCancelableMap
).then(sessionSaved => {
try {
if (sessionSaved) {
for (const [success, metaWindow, baseDir, sessionName] of sessionSaved) {
if (success) {
this._connectSignalsToCleanUpSessionFile(metaWindow, baseDir, sessionName);
}
}
}
} catch (e) {
this._log.error(e);
}
});
}
return GLib.SOURCE_CONTINUE;
});
}
_connectSignalsToCleanUpSessionFile(window, sessionDirectory, sessionName) {
try {
// Clean up while window is closing
let unmanagingId = window.connect('unmanaging', () => {
window.disconnect(unmanagingId);
unmanagingId = 0;
this._cleanUpSessionFileByWindow(window, sessionDirectory, sessionName);
});
this._signals.push([unmanagingId, window]);
// Clean up while the app state becomes STOPPED, just in case the session file cannot be cleanup while the last window is closed.
const app = this._windowTracker.get_window_app(window);
if (app) {
const appName = app.get_name();
let appId = app.connect('notify::state', app => {
if (app.state === Shell.AppState.STOPPED) {
app.disconnect(appId);
appId = 0;
this._cleanUpSessionFileByApp(app, appName, window, sessionDirectory);
}
});
this._signals.push([appId, app]);
}
} catch (e) {
this._log.error(e);
}
}
_cleanUpSessionFileByWindow(window, sessionDirectory, sessionName) {
if (!window || Autoclose.autocloseObject.sessionClosedByUser || this._meta_is_restarting) return;
const sessionFilePath = `${sessionDirectory}/${sessionName}`;
if (!GLib.file_test(sessionFilePath, GLib.FileTest.EXISTS)) return;
const app = this._windowTracker.get_window_app(window);
this._log.debug(`${window.get_title()}(${app?.get_name()}) was closed. Cleaning up its saved session files.`);
FileUtils.removeFile(sessionFilePath);
this._removeOrphanSessionConfigs(app, sessionDirectory);
}
_removeOrphanSessionConfigs(app, sessionDirectory) {
try {
if (!app) return;
if (!GLib.file_test(sessionDirectory, GLib.FileTest.EXISTS)) return;
this._log.debug(`Checking if ${app.get_name()} has orphan session configs`);
const sessionNames = new Set();
const windows = app.get_windows();
for (const metaWindow of windows) {
if (UiHelper.ignoreWindows(metaWindow)) continue;
sessionNames.add(`${MetaWindowUtils.getStableWindowId(metaWindow)}.json`);
}
FileUtils.listAllSessions(sessionDirectory, false, (file, info) => {
const filename = info.get_name();
const path = file.get_path();
if (!sessionNames.has(filename) && path && GLib.file_test(path, GLib.FileTest.EXISTS)) {
FileUtils.removeFile(path);
}
});
} catch (e) {
this._log.error(e);
}
}
_cleanUpSessionFileByApp(app, appName, window, sessionDirectory) {
if (!app || Autoclose.autocloseObject.sessionClosedByUser || this._meta_is_restarting) return;
if (!GLib.file_test(sessionDirectory, GLib.FileTest.EXISTS)) return;
// If this app is window-backed, app.get_name() will cause gnome-shell to bail out, so we get
// the app name outside this function. (See: shell-app.c -> shell_app_get_name -> window_backed_app_get_window: g_assert (app->running_state->windows))
this._log.debug(`${appName} was closed. Cleaning up its saved session files.`);
FileUtils.removeFile(sessionDirectory, true);
const possibleOrphanFolder = `${FileUtils.current_session_path}/${window.get_wm_class_instance()}`;
if (GLib.file_test(possibleOrphanFolder, GLib.FileTest.EXISTS)) {
this._log.debug(`Removing orphan session folder ${possibleOrphanFolder}`)
FileUtils.removeFile(possibleOrphanFolder, true);
}
}
_onNameAppearedGnomeShell() {
const EndSessionDialogIface = new TextDecoder().decode(
FileUtils.current_extension_dir.get_child('dbus-interfaces').get_child('org.gnome.SessionManager.EndSessionDialog.xml').load_contents(null)[1]);
const EndSessionDialogProxy = Gio.DBusProxy.makeProxyWrapper(EndSessionDialogIface);
this._endSessionProxy = new EndSessionDialogProxy(Gio.DBus.session,
'org.gnome.Shell',
'/org/gnome/SessionManager/EndSessionDialog',
(proxy, error) => {
// If `error` is not `null` it will be an Error object indicating the
// failure, and `proxy` will be `null` in this case.
if (error !== null) {
this._log.error(new Error(error), 'Failed to create the EndSessionDialog dbus proxy!');
return;
}
this._confirmedLogoutId = this._endSessionProxy.connectSignal('ConfirmedLogout', this._onConfirmedLogout.bind(this));
this._confirmedRebootId = this._endSessionProxy.connectSignal('ConfirmedReboot', this._onConfirmedReboot.bind(this));
this._confirmedShutdownId = this._endSessionProxy.connectSignal('ConfirmedShutdown', this._onConfirmedShutdown.bind(this));
this._closedId = this._endSessionProxy.connectSignal('Closed', this._onClose.bind(this));
this._canceledId = this._endSessionProxy.connectSignal('Canceled', this._onCancel.bind(this));
},
null,
Gio.DBusProxyFlags.NONE
);
}
_onNameVanishedGnomeShell(connection, name) {
this._log.debug(`Dbus name ${name} vanished`);
}
_onClose() {
this._log.debug(`User closed endSessionDialog`);
}
_onCancel() {
this._log.debug(`User cancel endSessionDialog`);
}
_onConfirmedLogout(proxy, sender) {
try {
this._log.debug(`Resetting windows-mapping before logout.`);
this._settings.set_string('windows-mapping', '{}');
} catch (error) {
this._log.error(error);
}
}
_onConfirmedReboot(proxy, sender) {
this._log.debug(`Resetting windows-mapping before reboot.`);
this._settings.set_string('windows-mapping', '{}');
}
_onConfirmedShutdown(proxy, sender) {
this._log.debug(`Resetting windows-mapping before shutdown.`);
this._settings.set_string('windows-mapping', '{}');
// TODO Move currentSession to recentlyClosed (recent closed session / recent closed app) with three tabs?
}
_onWindowCreatedSaveOrUpdateWindowsMapping(display, metaWindow, userData) {
const shellApp = this._windowTracker.get_window_app(metaWindow);
if (!shellApp) {
return;
}
let key;
const app_info = shellApp.get_app_info();
if (app_info) {
// .desktop file full path
key = app_info.get_filename();
} else {
// window backed app
key = shellApp.get_name();
}
const xid = metaWindow.get_description();
const windowStableSequence = metaWindow.get_stable_sequence();
const savedWindowsMappingJsonStr = this._settings.get_string('windows-mapping');
let savedWindowsMapping;
if (savedWindowsMappingJsonStr === '{}') {
savedWindowsMapping = new Map();
} else {
savedWindowsMapping = new Map(JSON.parse(savedWindowsMappingJsonStr));
}
let xidObj = savedWindowsMapping.get(key);
if (xidObj) {
const windows = shellApp.get_windows();
const removedXids = Object.keys(xidObj).filter(xid =>
!windows.find(w => w.get_description() === xid));
removedXids.forEach(xid => {
delete xidObj[xid];
});
if (!xidObj[xid]) {
xidObj[xid] = {
windowTitle: metaWindow.get_title(),
xid: xid,
windowStableSequence: windowStableSequence
};
}
} else {
if (!xidObj) {
xidObj = {};
}
xidObj[xid] = {
windowTitle: metaWindow.get_title(),
xid: xid,
windowStableSequence: windowStableSequence
};
savedWindowsMapping.set(key, xidObj);
}
const newSavedWindowsMappingJsonStr = JSON.stringify(Array.from(savedWindowsMapping.entries()));
this._settings.set_string('windows-mapping', newSavedWindowsMappingJsonStr);
Gio.Settings.sync();
}
_cancelRunningSave(window) {
if (!this._runningSaveCancelableMap) {
return;
}
const cancellable = this._runningSaveCancelableMap.get(window);
if (cancellable && !cancellable.is_cancelled()) {
cancellable.cancel();
}
}
_cancelAllRunningSave() {
if (!this._runningSaveCancelableMap) {
return;
}
for (const cancellable of this._runningSaveCancelableMap.values()) {
if (!cancellable.is_cancelled())
cancellable.cancel();
}
this._runningSaveCancelableMap.clear();
}
destroy() {
this._cancelAllRunningSave();
if (this._busWatchId) {
Gio.bus_unwatch_name(this._busWatchId);
this._busWatchId = 0;
}
if (this._confirmedLogoutId) {
this._endSessionProxy?.disconnectSignal(this._confirmedLogoutId);
this._confirmedLogoutId = 0;
}
if (this._confirmedRebootId) {
this._endSessionProxy?.disconnectSignal(this._confirmedRebootId);
this._confirmedRebootId = 0;
}
if (this._confirmedShutdownId) {
this._endSessionProxy?.disconnectSignal(this._confirmedShutdownId);
this._confirmedShutdownId = 0;
}
if (this._closedId) {
this._endSessionProxy?.disconnectSignal(this._closedId);
this._closedId = 0;
}
if (this._canceledId) {
this._endSessionProxy?.disconnectSignal(this._canceledId);
this._canceledId = 0;
}
if (this._saveSessionByBatchTimeoutId) {
GLib.Source.remove(this._saveSessionByBatchTimeoutId);
this._saveSessionByBatchTimeoutId = 0;
}
if (_meta_restart) {
Meta.restart = _meta_restart;
_meta_restart = null;
}
if (this._overrideSystemActionsPrototypeMap.size) {
this._overrideSystemActionsPrototypeMap.forEach((originalFunc, funcName) => {
SystemActions.SystemActions.prototype[funcName] = originalFunc;
});
this._overrideSystemActionsPrototypeMap.clear();
this._overrideSystemActionsPrototypeMap = null;
}
if (this._signals && this._signals.length) {
this._signals.forEach(([id, obj]) => {
if (id && obj) {
obj.disconnect(id);
}
});
this._signals = null;
}
}
}