-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindicator.js
executable file
·581 lines (464 loc) · 23.4 KB
/
indicator.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
'use strict';
const { GObject, St, Gio, GLib, Clutter, Shell, Meta } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const PopupMenu = imports.ui.popupMenu;
const PanelMenu = imports.ui.panelMenu;
const MoveSession = Me.imports.moveSession;
const RestoreSession = Me.imports.restoreSession;
const FileUtils = Me.imports.utils.fileUtils;
const SessionItem = Me.imports.ui.sessionItem;
const SearchSessionItem = Me.imports.ui.searchSessionItem;
const PopupMenuButtonItems = Me.imports.ui.popupMenuButtonItems;
const IconFinder = Me.imports.utils.iconFinder;
const PrefsUtils = Me.imports.utils.prefsUtils;
const Log = Me.imports.utils.log;
const Signal = Me.imports.utils.signal;
var AwsIndicator = GObject.registerClass(
class AwsIndicator extends PanelMenu.Button {
_init() {
super._init(0.0, "Another Window Session Manager");
this._windowTracker = Shell.WindowTracker.get_default();
this._prefsUtils = new PrefsUtils.PrefsUtils();
this._settings = this._prefsUtils.getSettings();
this._log = new Log.Log();
this._signal = new Signal.Signal();
this._itemIndex = 0;
this._sessions_path = FileUtils.sessions_path;
this.monitors = [];
this._sessionsMenuSection = null;
// TODO backup path
// Add an icon
let icon = new St.Icon({
gicon: IconFinder.find('restore-symbolic.svg'),
style_class: 'popup-menu-icon'
});
this.add_child(icon);
this._createMenu();
this.menu.connect('open-state-changed', this._onOpenStateChanged.bind(this));
// Open menu
// this.menu.open(true);
// Toggle menu
// this.menu.toggle();
// Remove all activate signals on all menu items, so the panel menu can always stay open
// See: PopupMenu#itemActivated() => this.menu._getTopMenu().close
this.menu.itemActivated = function(animate) {};
this._moveSession = new MoveSession.MoveSession();
this._metaWindowConnectIds = [];
this._display = global.display;
this._displayId = this._display.connect('window-created', this._windowCreated.bind(this));
this._isDestroyed = false;
}
// TODO Move this method and related code to a single .js file
async _windowCreated(display, metaWindow, userData) {
if (!Meta.is_wayland_compositor()) {
// We call createEnoughWorkspaceAndMoveWindows() if and only if all conditions checked.
// But we give some windows (such as the OS running in VirtualBox) a chance to connect `first-frame` and `shown` signals.
// The reason I do this is that
// `Shell.AppSystem.get_default().lookup_app('a-VirtualBox-machine-name.desktop')`
// and `Shell.WindowTracker.get_default().get_window_app(metaWindow_of_VirtualBoxMachine)`
// are not the same instance.
// My best guess is:
// Looks like if launch a VirtualBox machine via `/usr/lib64/virtualbox/VirtualBoxVM --comment "test" --startvm "{xxxxxxx-xxxxxxx-xxxxxxx-xxxxxxx-xxxxxxxxxxxxxx}"`,
// it will open two process: the first process open another process, which is running a machine, and then the first process stops to run and the associated Shell.App is also destroyed.
// And
// the two processes all have window, window of the first process will be destroyed before/after the second process open a new window, which is running the virtual OS.
// Install https://extensions.gnome.org/extension/4679/burn-my-windows/ to watch this process.
const shellApp = this._windowTracker.get_window_app(metaWindow);
let shellAppData = RestoreSession.restoringApps.get(shellApp);
if (!shellAppData) {
shellAppData = RestoreSession.restoringApps.get(metaWindow.get_pid());
}
if (shellAppData) {
const saved_window_sessions = shellAppData.saved_window_sessions;
// On X11, we have to create enough workspace and move windows before receive the first-frame signal.
// If not, all windows will be shown in current workspace when stay in Overview, which is not pretty.
let matchedSavedWindowSession = await this._moveSession.createEnoughWorkspaceAndMoveWindows(metaWindow, saved_window_sessions);
if (matchedSavedWindowSession) {
// We try to restore window state here if necessary.
// Below are possible reasons:
// 1) In current implement there is no guarantee that the first-frame and shown signals can be triggered immediately. You have to click a window to trigger them.
// 2) The restored window state could be lost
this._log.debug(`Restoring window state of ${shellApp.get_name()} - ${metaWindow.get_title()} if necessary`);
this._moveSession._restoreWindowState(metaWindow, matchedSavedWindowSession);
// Fix window geometry later on in first-frame signal
// TODO The side-effect is when a window is already in the current workspace there will be two same logs (The window 'Clocks' is already on workspace 0 for Clocks) in the journalctl, which is not pretty.
// TODO Maybe it's better to use another state to indicator whether a window has been restored geometry.
matchedSavedWindowSession.moved = false;
}
}
}
let metaWindowActor = metaWindow.get_compositor_private();
// https://github.com/paperwm/PaperWM/blob/10215f57e8b34a044e10b7407cac8fac4b93bbbc/tiling.js#L2120
// https://gjs-docs.gnome.org/meta8~8_api/meta.windowactor#signal-first-frame
let firstFrameId = metaWindowActor.connect('first-frame', () => {
if (this._isDestroyed) {
metaWindowActor.disconnect(firstFrameId);
return;
}
if (metaWindow._aboutToClose) {
return;
}
const shellApp = this._windowTracker.get_window_app(metaWindow);
if (!shellApp) {
return;
}
// NOTE: The title of a dialog (for example a close warning dialog, like gnome-terminal) attached to a window is ''
this._log.debug(`window-created -> first-frame: ${shellApp.get_name()} -> ${metaWindow.get_title()}`);
let shellAppData = RestoreSession.restoringApps.get(shellApp);
if (!shellAppData) {
shellAppData = RestoreSession.restoringApps.get(metaWindow.get_pid());
}
if (!shellAppData) {
return;
}
const saved_window_sessions = shellAppData.saved_window_sessions;
this._moveSession.moveWindowByMetaWindow(metaWindow, saved_window_sessions);
metaWindowActor.disconnect(firstFrameId);
firstFrameId = 0;
})
let shownId = metaWindow.connect('shown', () => {
if (this._isDestroyed) {
metaWindow.disconnect(shownId);
return;
}
if (metaWindow._aboutToClose) {
return;
}
const shellApp = this._windowTracker.get_window_app(metaWindow);
if (!shellApp) {
return;
}
// NOTE: The title of a dialog (for example a close warning dialog, like gnome-terminal) attached to a window is ''
this._log.debug(`window-created -> shown: ${shellApp.get_name()} -> ${metaWindow.get_title()}`);
let shellAppData = RestoreSession.restoringApps.get(shellApp);
if (!shellAppData) {
shellAppData = RestoreSession.restoringApps.get(metaWindow.get_pid());
}
if (!shellAppData) {
return;
}
const saved_window_sessions = shellAppData.saved_window_sessions;
this._moveSession.moveWindowByMetaWindow(metaWindow, saved_window_sessions);
metaWindow.disconnect(shownId);
shownId = 0;
});
/*
We have to disconnect firstFrameId within the unmanaging signal of metaWindow.
If we do this in `destroy()`, the metaWindowActor instance has been disposed, disconnecting signals from
metaWindowActor gets many errors when disable extension: Object .MetaWindowActorWayland (0x55fae658e3d0), has been already disposed — impossible to access it. This might be caused by the object having been destroyed from C code using something such as destroy(), dispose(), or remove() vfuncs.
I don't know why 😢. TODO
But metaWindow is not disposed in `destroy()`, so we can disconnect signals from it there.
*/
let unmanagingId = metaWindow.connect('unmanaging', () => {
// Fix ../gobject/gsignal.c:2732: instance '0x55629xxxxxx' has no handler with id '11000' when disable this extension right after restore apps
this._signal.disconnectSafely(metaWindowActor, firstFrameId);
});
// The window title might be changing multiple times while the app is starting.
// For some apps, such as Visual Studio Code, when it's starting, the first title is `Visual Studio Code`,
// the second could be `indicator.js - gnome-shell-extension-another-window-session-manager - Visual Studio Code`.
// In the above instance, `notify::title` catches the second.
let titleChangedId = metaWindow.connect('notify::title', () => {
if (this._isDestroyed) {
metaWindow.disconnect(titleChangedId);
return;
}
if (metaWindow._aboutToClose) {
return;
}
const shellApp = this._windowTracker.get_window_app(metaWindow);
if (!shellApp) {
return;
}
// NOTE: The title of a dialog (for example a close warning dialog, like gnome-terminal) attached to a window is ''
this._log.debug(`window-created -> title changed: ${shellApp.get_name()} -> ${metaWindow.get_title()}`);
let shellAppData = RestoreSession.restoringApps.get(shellApp);
if (!shellAppData) {
shellAppData = RestoreSession.restoringApps.get(metaWindow.get_pid());
}
if (!shellAppData) {
return;
}
const saved_window_sessions = shellAppData.saved_window_sessions;
this._moveSession.moveWindowByMetaWindow(metaWindow, saved_window_sessions);
metaWindow.disconnect(titleChangedId);
titleChangedId = 0;
});
this._metaWindowConnectIds.push([metaWindow, shownId]);
this._metaWindowConnectIds.push([metaWindow, unmanagingId]);
this._metaWindowConnectIds.push([metaWindow, titleChangedId]);
}
_onOpenStateChanged(menu, state) {
if (state) {
this._searchSessionItem.reset();
this._searchSessionItem._clearIcon.hide();
this._searchSessionItem._entry.grab_key_focus();
}
super._onOpenStateChanged(menu, state);
}
_createMenu() {
this._addButtonItems();
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem(), this._itemIndex++);
this._searchSessionItem = new SearchSessionItem.SearchSessionItem();
const searchEntryText = this._searchSessionItem._entry.get_clutter_text()
searchEntryText.connect('text-changed', this._onSearch.bind(this));
this._searchSessionItem._filterAutoRestoreSwitch.connect('notify::state', this._onAutoRestoreSwitchChanged.bind(this));
this.menu.addMenuItem(this._searchSessionItem, this._itemIndex++);
this._addScrollableSessionsMenuSection();
this._addSessionItems().catch((error => {
this._log.error(error, 'Error adding session items while creating indicator menu');
}));
this._addSessionFolderMonitor();
this._settings.connect('changed::debugging-mode', () => {
this._addSessionItems().catch((error => {
this._log.error(error, 'Error reloading session items while debugging-mode was changed');
}));
});
}
_addScrollableSessionsMenuSection() {
this._sessionsMenuSection = new PopupMenu.PopupMenuSection();
this._scrollableSessionsMenuSection = new PopupMenu.PopupMenuSection();
let scrollView = new St.ScrollView({
style_class: 'session-menu-section',
overlay_scrollbars: true
});
scrollView.add_actor(this._sessionsMenuSection.actor);
this._scrollableSessionsMenuSection.actor.add_actor(scrollView);
this.menu.addMenuItem(this._scrollableSessionsMenuSection);
}
_addButtonItems() {
this._popupMenuButtonItems = new PopupMenuButtonItems.PopupMenuButtonItems();
const buttonItems = this._popupMenuButtonItems.buttonItems;
buttonItems.forEach(item => {
this.menu.addMenuItem(item, this._itemIndex++);
});
}
async _addSessionItems() {
if (!GLib.file_test(this._sessions_path, GLib.FileTest.EXISTS)) {
// TODO Empty session
this._log.info(`${this._sessions_path} not found! It's harmless, please save some windows in the panel menu to create it automatically.`);
this._sessionsMenuSection.removeAll();
return;
}
this._log.debug('List all sessions to add session items');
let sessionFileInfos = [];
await FileUtils.listAllSessions(null, false, (file, info) => {
// We have an interest in regular and text files
const file_type = info.get_file_type();
if (file_type !== Gio.FileType.REGULAR) {
this._log.debug(`${file.get_path()} (file type is ${file_type}) is not a regular file, skipping`);
return;
}
const content_type = info.get_content_type();
if (content_type !== 'text/plain') {
this._log.debug(`${file.get_path()} (content type is ${content_type}) is not a text file, skipping`);
return;
}
// Skip the `Recently Closed Session` file since it has been added to the session list already.
if (file.equal(FileUtils.recently_closed_session_file)) {
return;
}
this._log.debug(`Processing ${file.get_path()}`);
sessionFileInfos.push({
info: info,
file: file
});
}).catch(e => {
this._log.error(e, 'Error listing all sessions')
});
// Sort by modification time: https://gjs-docs.gnome.org/gio20~2.0/gio.fileenumerator
// The latest on the top, if a file has no modification time put it on the bottom
sessionFileInfos.sort((sessionFileInfo1, sessionFileInfo2) => {
const info1 = sessionFileInfo1.info;
let modification_date_time1 = info1.get_modification_date_time();
const info2 = sessionFileInfo2.info;
let modification_date_time2 = info2.get_modification_date_time();
if (!modification_date_time1 && !modification_date_time2) {
return 0;
}
if (!modification_date_time1 && modification_date_time2) {
return 1;
}
if (modification_date_time1 && !modification_date_time2) {
return -1;
}
// https://gjs-docs.gnome.org/glib20~2.66.1/glib.datetime#function-compare
// -1, 0 or 1 if dt1 is less than, equal to or greater than dt2.
return modification_date_time2.compare(modification_date_time1);
});
this._sessionsMenuSection.removeAll();
let info = null;
try {
info = FileUtils.recently_closed_session_file.query_info(
[Gio.FILE_ATTRIBUTE_STANDARD_NAME,
Gio.FILE_ATTRIBUTE_TIME_MODIFIED].join(','),
Gio.FileQueryInfoFlags.NONE,
null);
} catch (ignored) {}
// Recently Closed Session always on the top
let item = new SessionItem.SessionItem(info, FileUtils.recently_closed_session_file, this);
this._sessionsMenuSection.addMenuItem(item, this._itemIndex++);
for (const sessionFileInfo of sessionFileInfos) {
const info = sessionFileInfo.info;
const file = sessionFileInfo.file;
let item = new SessionItem.SessionItem(info, file, this);
this._sessionsMenuSection.addMenuItem(item, this._itemIndex++);
}
}
/**
* monitor files changes, recreate items when necessary.
*
*/
_addSessionFolderMonitor() {
const sessionPathFile = Gio.File.new_for_path(this._sessions_path);
this._monitor_directory(sessionPathFile);
// Moving a directory on the same filesystem doesn’t move its contents, so we
// monitor each parent directory because I want to receive the `changed` when they are moved
let parent = sessionPathFile.get_parent();
// If parent is null, then it represents the root directory of the file system
while (parent) {
if (parent.get_path() === `${FileUtils.user_config}`) {
break;
}
this._monitor_directory(parent);
parent = parent.get_parent();
}
}
_monitor_directory(directory) {
const monitor = directory.monitor_directory(
Gio.FileMonitorFlags.WATCH_MOUNTS |
Gio.FileMonitorFlags.WATCH_MOVES, null);
monitor.connect('changed', this._sessionChanged.bind(this));
this.monitors.push(monitor);
}
// https://gjs-docs.gnome.org/gio20~2.66p/gio.filemonitor#signal-changed
// Looks like the document is wrong ...
_sessionChanged(monitor, fileMonitored, otherFile, eventType) {
const pathMonitored = fileMonitored.get_path();
const otherFilePath = otherFile?.get_path();
this._log.debug(`Session changed, readd all session items from ${this._sessions_path}. ${pathMonitored} changed. other_file: ${otherFilePath}. Event type: ${eventType}`);
// Ignore CHANGED and CREATED events, since in both cases
// we'll get a CHANGES_DONE_HINT event when done.
if (eventType === Gio.FileMonitorEvent.CHANGED ||
eventType === Gio.FileMonitorEvent.CREATED) {
return;
}
// The eventType is Gio.FileMonitorEvent.RENAMED while modify the content of a text file,
// so otherFile is the correct file we need to read.
// The doc said:
// If using Gio.FileMonitorFlags.WATCH_MOVES on a directory monitor, and
// the information is available (and if supported by the backend),
// event_type may be Gio.FileMonitorEvent.RENAMED,
// Gio.FileMonitorEvent.MOVED_IN or Gio.FileMonitorEvent.MOVED_OUT.
if (eventType === Gio.FileMonitorEvent.RENAMED) {
fileMonitored = otherFile;
}
// Ignore temporary files generated by Gio
if (fileMonitored.get_basename().startsWith('.goutputstream-')) {
return;
}
let info = null;
try {
info = fileMonitored.query_info(
[Gio.FILE_ATTRIBUTE_STANDARD_TYPE,
Gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE].join(','),
Gio.FileQueryInfoFlags.NONE,
null);
} catch (ignored) {}
// Ignore none regular and text files
if (info) {
const file_type = info.get_file_type();
const content_type = info.get_content_type();
if (!(file_type === Gio.FileType.REGULAR &&
content_type === 'text/plain') &&
// Parent folders could be changed
!this._sessions_path.startsWith(pathMonitored)) {
return;
}
}
// It probably is a problem when there are large amount session files,
// say thousands of them, but who creates that much?
//
// Can use Gio.FileMonitorEvent to modify the results
// of this._sessionsMenuSection._getMenuItems() when the performance
// is a problem to be resolved, it's a more complex implement.
this._addSessionItems().catch((error => {
this._log.error(error, 'Error adding session items while session was changed');
}));
}
_onAutoRestoreSwitchChanged() {
this._search();
this._filterAutoRestore();
}
_filterAutoRestore() {
const switchState = this._searchSessionItem._filterAutoRestoreSwitch.state;
if (switchState) {
const menuItems = this._sessionsMenuSection._getMenuItems();
for (const menuItem of menuItems) {
const sessionName = menuItem._filename;
if (menuItem.actor.visible) {
const visible = sessionName == this._settings.get_string(PrefsUtils.SETTINGS_AUTORESTORE_SESSIONS);
menuItem.actor.visible = visible;
}
}
}
}
_onSearch() {
this._search();
this._filterAutoRestore();
}
_search() {
this._searchSessionItem._clearIcon.show();
let searchText = this._searchSessionItem._entry.text;
if (!(searchText && searchText.trim())) {
// when search entry is empty, hide clear button
if (!searchText) {
this._searchSessionItem._clearIcon.hide();
}
const menuItems = this._sessionsMenuSection._getMenuItems();
for (const menuItem of menuItems) {
menuItem.actor.visible = true;
}
} else {
const menuItems = this._sessionsMenuSection._getMenuItems();
searchText = searchText.toLowerCase().trim();
for (const menuItem of menuItems) {
const sessionName = menuItem._filename.toLowerCase();
menuItem.actor.visible = new RegExp(searchText).test(sessionName);
}
}
}
destroy() {
if (this.monitors) {
this.monitors.forEach ((monitor) => {
monitor.cancel();
monitor = null;
});
this.monitors = [];
}
if (this._sessions_path) {
this._sessions_path = null;
}
if (this._prefsUtils) {
this._prefsUtils.destroy();
this._prefsUtils = null;
}
if (this._metaWindowConnectIds) {
for (let [obj, signalId] of this._metaWindowConnectIds) {
// Fix ../gobject/gsignal.c:2732: instance '0x55629xxxxxx' has no handler with id '11000' when disable this extension right after restore apps
this._signal.disconnectSafely(obj, signalId);
}
this._metaWindowConnectIds = null;
}
if (this._displayId) {
this._display.disconnect(this._displayId);
this._displayId = 0;
}
if (this._log) {
this._log.destroy();
this._log = null;
}
super.destroy();
this._isDestroyed = true;
}
});