Debian Codegraph @

extensions/places-menu/placeDisplay.js

raw
1 // SPDX-FileCopyrightText: 2012 Giovanni Campagna <[email protected]>
2 // SPDX-FileCopyrightText: 2013 Debarshi Ray <[email protected]>
3 // SPDX-FileCopyrightText: 2015 Florian Müllner <[email protected]>
4 // SPDX-FileCopyrightText: 2016 Rémy Lefevre <[email protected]>
5 // SPDX-FileCopyrightText: 2017 Christian Kellner <[email protected]>
6 //
7 // SPDX-License-Identifier: GPL-2.0-or-later
8
9 import Gio from 'gi://Gio';
10 import GLib from 'gi://GLib';
11 import Shell from 'gi://Shell';
12 import {EventEmitter} from 'resource:///org/gnome/shell/misc/signals.js';
13
14 import {gettext as _} from 'resource:///org/gnome/shell/extensions/extension.js';
15
16 import * as Main from 'resource:///org/gnome/shell/ui/main.js';
17 import * as ShellMountOperation from 'resource:///org/gnome/shell/ui/shellMountOperation.js';
18
19 const N_ = x => x;
20
21 Gio._promisify(Gio.AppInfo, 'launch_default_for_uri_async');
22 Gio._promisify(Gio.File.prototype, 'mount_enclosing_volume');
23
24 const BACKGROUND_SCHEMA = 'org.gnome.desktop.background';
25
26 class PlaceInfo extends EventEmitter {
27 constructor(...params) {
28 super();
29
30 this._init(...params);
31 }
32
33 _init(kind, file, name, icon) {
34 this.kind = kind;
35 this.file = file;
36 this.name = name || this._getFileName();
37 this.icon = icon ? new Gio.ThemedIcon({name: icon}) : this.getIcon();
38 }
39
40 destroy() {
41 }
42
43 isRemovable() {
44 return false;
45 }
46
47 async _ensureMountAndLaunch(context, tryMount) {
48 try {
49 await Gio.AppInfo.launch_default_for_uri_async(this.file.get_uri(), context, null);
50 } catch (err) {
51 if (!err.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_MOUNTED)) {
52 Main.notifyError(_('Failed to launch “%s”').format(this.name), err.message);
53 return;
54 }
55
56 const source = {
57 get_drive: () => null,
58 };
59 const op = new ShellMountOperation.ShellMountOperation(source);
60 try {
61 await this.file.mount_enclosing_volume(0, op.mountOp, null);
62
63 if (tryMount)
64 this._ensureMountAndLaunch(context, false).catch(logError);
65 } catch (e) {
66 if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.FAILED_HANDLED))
67 Main.notifyError(_('Failed to mount volume for “%s”').format(this.name), e.message);
68 } finally {
69 op.close();
70 }
71 }
72 }
73
74 launch(timestamp) {
75 const launchContext = global.create_app_launch_context(timestamp, -1);
76 this._ensureMountAndLaunch(launchContext, true).catch(logError);
77 }
78
79 getIcon() {
80 this.file.query_info_async('standard::symbolic-icon',
81 Gio.FileQueryInfoFlags.NONE,
82 0,
83 null,
84 (file, result) => {
85 try {
86 const info = file.query_info_finish(result);
87 this.icon = info.get_symbolic_icon();
88 this.emit('changed');
89 } catch (e) {
90 if (e instanceof Gio.IOErrorEnum)
91 return;
92 throw e;
93 }
94 });
95
96 // return a generic icon for this kind for now, until we have the
97 // icon from the query info above
98 switch (this.kind) {
99 case 'network':
100 return new Gio.ThemedIcon({name: 'folder-remote-symbolic'});
101 case 'devices':
102 return new Gio.ThemedIcon({name: 'drive-harddisk-symbolic'});
103 case 'special':
104 case 'bookmarks':
105 default:
106 if (!this.file.is_native())
107 return new Gio.ThemedIcon({name: 'folder-remote-symbolic'});
108 else
109 return new Gio.ThemedIcon({name: 'folder-symbolic'});
110 }
111 }
112
113 _getFileName() {
114 try {
115 const info = this.file.query_info('standard::display-name', 0, null);
116 return info.get_display_name();
117 } catch (e) {
118 if (e instanceof Gio.IOErrorEnum)
119 return this.file.get_basename();
120 throw e;
121 }
122 }
123 }
124
125 class NautilusSpecialInfo extends PlaceInfo {
126 constructor(file, name, icon) {
127 super('special', file, name, icon);
128
129 const appSystem = Shell.AppSystem.get_default();
130 this._app = appSystem.lookup_app('org.gnome.Nautilus.desktop');
131 }
132
133 launch(timestamp) {
134 const launchContext = global.create_app_launch_context(timestamp, -1);
135 this._app.appInfo.launch([this.file], launchContext);
136 }
137 }
138
139 class PlaceDeviceInfo extends PlaceInfo {
140 _init(kind, mount) {
141 this._mount = mount;
142 super._init(kind, mount.get_root(), mount.get_name());
143 }
144
145 getIcon() {
146 return this._mount.get_symbolic_icon();
147 }
148
149 isRemovable() {
150 return this._mount.can_eject() || this._mount.can_unmount();
151 }
152
153 eject() {
154 const unmountArgs = [
155 Gio.MountUnmountFlags.NONE,
156 new ShellMountOperation.ShellMountOperation(this._mount).mountOp,
157 null, // Gio.Cancellable
158 ];
159
160 if (this._mount.can_eject()) {
161 this._mount.eject_with_operation(...unmountArgs,
162 this._ejectFinish.bind(this));
163 } else {
164 this._mount.unmount_with_operation(...unmountArgs,
165 this._unmountFinish.bind(this));
166 }
167 }
168
169 _ejectFinish(mount, result) {
170 try {
171 mount.eject_with_operation_finish(result);
172 } catch (e) {
173 this._reportFailure(e);
174 }
175 }
176
177 _unmountFinish(mount, result) {
178 try {
179 mount.unmount_with_operation_finish(result);
180 } catch (e) {
181 this._reportFailure(e);
182 }
183 }
184
185 _reportFailure(exception) {
186 const msg = _('Ejecting drive “%s” failed:').format(this._mount.get_name());
187 Main.notifyError(msg, exception.message);
188 }
189 }
190
191 class PlaceVolumeInfo extends PlaceInfo {
192 _init(kind, volume) {
193 this._volume = volume;
194 super._init(kind, volume.get_activation_root(), volume.get_name());
195 }
196
197 launch(timestamp) {
198 if (this.file) {
199 super.launch(timestamp);
200 return;
201 }
202
203 this._volume.mount(0, null, null, (volume, result) => {
204 volume.mount_finish(result);
205
206 const mount = volume.get_mount();
207 this.file = mount.get_root();
208 super.launch(timestamp);
209 });
210 }
211
212 getIcon() {
213 return this._volume.get_symbolic_icon();
214 }
215 }
216
217 export class PlacesManager extends EventEmitter {
218 constructor() {
219 super();
220
221 this._places = {
222 special: [],
223 devices: [],
224 bookmarks: [],
225 network: [],
226 };
227
228 this._settings = new Gio.Settings({schema_id: BACKGROUND_SCHEMA});
229 this._settings.connectObject('changed::show-desktop-icons',
230 () => this._updateSpecials(), this);
231
232 this._privacySettings = new Gio.Settings({
233 schema_id: 'org.gnome.desktop.privacy',
234 });
235 this._privacySettings.connectObject('changed::remember-recent-files',
236 () => this._updateSpecials(), this);
237 this._updateSpecials();
238
239 /*
240 * Show devices, code more or less ported from nautilus-places-sidebar.c
241 */
242 this._volumeMonitor = Gio.VolumeMonitor.get();
243 this._volumeMonitor.connectObject(
244 'volume-added', () => this._updateMounts(),
245 'volume-removed', () => this._updateMounts(),
246 'volume-changed', () => this._updateMounts(),
247 'mount-added', () => this._updateMounts(),
248 'mount-removed', () => this._updateMounts(),
249 'mount-changed', () => this._updateMounts(),
250 'drive-connected', () => this._updateMounts(),
251 'drive-disconnected', () => this._updateMounts(),
252 'drive-changed', () => this._updateMounts(),
253 this);
254 this._updateMounts();
255
256 this._bookmarksFile = this._findBookmarksFile();
257 this._bookmarkTimeoutId = 0;
258 this._monitor = null;
259
260 if (this._bookmarksFile) {
261 this._monitor = this._bookmarksFile.monitor_file(Gio.FileMonitorFlags.NONE, null);
262 this._monitor.connect('changed', () => {
263 if (this._bookmarkTimeoutId > 0)
264 return;
265 /* Defensive event compression */
266 this._bookmarkTimeoutId = GLib.timeout_add_once(
267 GLib.PRIORITY_DEFAULT, 100, () => {
268 this._bookmarkTimeoutId = 0;
269 this._reloadBookmarks();
270 });
271 });
272
273 this._reloadBookmarks();
274 }
275 }
276
277 destroy() {
278 this._settings?.disconnectObject(this);
279 this._settings = null;
280
281 this._privacySettings.disconnectObject(this);
282 this._privacySettings = null;
283
284 this._volumeMonitor.disconnectObject(this);
285
286 if (this._monitor)
287 this._monitor.cancel();
288 if (this._bookmarkTimeoutId)
289 GLib.source_remove(this._bookmarkTimeoutId);
290 }
291
292 _shouldShowRecent() {
293 const vfs = Gio.Vfs.get_default();
294 const schemes = vfs.get_supported_uri_schemes();
295 return this._privacySettings.get_boolean('remember-recent-files') &&
296 schemes.includes('recent');
297 }
298
299 _updateSpecials() {
300 this._places.special.forEach(p => p.destroy());
301 this._places.special = [];
302
303 const appSystem = Shell.AppSystem.get_default();
304 const nautilusApp = appSystem.lookup_app('org.gnome.Nautilus.desktop');
305 const defaultFm = Gio.AppInfo.get_default_for_type('inode/directory', true);
306 const showNautilusSpecials =
307 nautilusApp && defaultFm && nautilusApp.appInfo.equal(defaultFm);
308
309 const homeFile = Gio.File.new_for_path(GLib.get_home_dir());
310
311 this._places.special.push(new PlaceInfo(
312 'special',
313 homeFile,
314 _('Home')));
315
316 if (this._shouldShowRecent()) {
317 this._places.special.push(new PlaceInfo(
318 'special',
319 Gio.File.new_for_uri('recent:///'),
320 _('Recent')));
321 }
322
323 if (showNautilusSpecials) {
324 this._places.special.push(new NautilusSpecialInfo(
325 Gio.File.new_for_uri('starred:///'),
326 _('Starred'),
327 'starred-symbolic'));
328 }
329
330 if (this._settings.get_boolean('show-desktop-icons')) {
331 const desktopPath = GLib.get_user_special_dir(
332 GLib.UserDirectory.DIRECTORY_DESKTOP);
333 const desktopFile = desktopPath
334 ? Gio.File.new_for_path(desktopPath)
335 : null;
336
337 if (desktopFile && !desktopFile.equal(homeFile)) {
338 this._places.special.push(
339 new PlaceInfo('special', desktopFile));
340 }
341 }
342
343 if (showNautilusSpecials) {
344 this._places.special.push(new NautilusSpecialInfo(
345 Gio.File.new_for_uri('x-network-view:///'),
346 _('Network'),
347 'network-workgroup-symbolic'));
348 }
349
350 this._places.special.push(new PlaceInfo(
351 'special',
352 Gio.File.new_for_uri('trash:///'),
353 _('Trash')));
354
355 this.emit('special-updated');
356 }
357
358 _updateMounts() {
359 const networkMounts = [];
360 const networkVolumes = [];
361
362 this._places.devices.forEach(p => p.destroy());
363 this._places.devices = [];
364 this._places.network.forEach(p => p.destroy());
365 this._places.network = [];
366
367 /* first go through all connected drives */
368 const drives = this._volumeMonitor.get_connected_drives();
369 for (let i = 0; i < drives.length; i++) {
370 const volumes = drives[i].get_volumes();
371
372 for (let j = 0; j < volumes.length; j++) {
373 const identifier = volumes[j].get_identifier('class');
374 if (identifier && identifier.includes('network')) {
375 networkVolumes.push(volumes[j]);
376 } else {
377 const mount = volumes[j].get_mount();
378 if (mount)
379 this._addMount('devices', mount);
380 }
381 }
382 }
383
384 /* add all volumes that is not associated with a drive */
385 const volumes = this._volumeMonitor.get_volumes();
386 for (let i = 0; i < volumes.length; i++) {
387 if (volumes[i].get_drive())
388 continue;
389
390 const identifier = volumes[i].get_identifier('class');
391 if (identifier && identifier.includes('network')) {
392 networkVolumes.push(volumes[i]);
393 } else {
394 const mount = volumes[i].get_mount();
395 if (mount)
396 this._addMount('devices', mount);
397 }
398 }
399
400 /* add mounts that have no volume (/etc/mtab mounts, ftp, sftp,...) */
401 const mounts = this._volumeMonitor.get_mounts();
402 for (let i = 0; i < mounts.length; i++) {
403 if (mounts[i].is_shadowed())
404 continue;
405
406 if (mounts[i].get_volume())
407 continue;
408
409 const root = mounts[i].get_default_location();
410 if (!root.is_native()) {
411 networkMounts.push(mounts[i]);
412 continue;
413 }
414 this._addMount('devices', mounts[i]);
415 }
416
417 for (let i = 0; i < networkVolumes.length; i++) {
418 const mount = networkVolumes[i].get_mount();
419 if (mount) {
420 networkMounts.push(mount);
421 continue;
422 }
423 this._addVolume('network', networkVolumes[i]);
424 }
425
426 for (let i = 0; i < networkMounts.length; i++)
427 this._addMount('network', networkMounts[i]);
428
429
430 this.emit('devices-updated');
431 this.emit('network-updated');
432 }
433
434 _findBookmarksFile() {
435 const paths = [
436 GLib.build_filenamev([GLib.get_user_config_dir(), 'gtk-3.0', 'bookmarks']),
437 GLib.build_filenamev([GLib.get_home_dir(), '.gtk-bookmarks']),
438 ];
439
440 for (let i = 0; i < paths.length; i++) {
441 if (GLib.file_test(paths[i], GLib.FileTest.EXISTS))
442 return Gio.File.new_for_path(paths[i]);
443 }
444
445 return null;
446 }
447
448 _reloadBookmarks() {
449 this._bookmarks = [];
450
451 const content = Shell.get_file_contents_utf8_sync(this._bookmarksFile.get_path());
452 const lines = content.split('\n');
453
454 const bookmarks = [];
455 for (let i = 0; i < lines.length; i++) {
456 const line = lines[i];
457 const components = line.split(' ');
458 const [bookmark] = components;
459
460 if (!bookmark)
461 continue;
462
463 const file = Gio.File.new_for_uri(bookmark);
464 if (file.is_native() && !file.query_exists(null))
465 continue;
466
467 let duplicate = false;
468 for (let j = 0; j < this._places.special.length; j++) {
469 if (file.equal(this._places.special[j].file)) {
470 duplicate = true;
471 break;
472 }
473 }
474 if (duplicate)
475 continue;
476 for (let j = 0; j < bookmarks.length; j++) {
477 if (file.equal(bookmarks[j].file)) {
478 duplicate = true;
479 break;
480 }
481 }
482 if (duplicate)
483 continue;
484
485 let label = null;
486 if (components.length > 1)
487 label = components.slice(1).join(' ');
488
489 bookmarks.push(new PlaceInfo('bookmarks', file, label));
490 }
491
492 this._places.bookmarks = bookmarks;
493
494 this.emit('bookmarks-updated');
495 }
496
497 _addMount(kind, mount) {
498 const devItem = new PlaceDeviceInfo(kind, mount);
499 this._places[kind].push(devItem);
500 }
501
502 _addVolume(kind, volume) {
503 const volItem = new PlaceVolumeInfo(kind, volume);
504 this._places[kind].push(volItem);
505 }
506
507 get(kind) {
508 return this._places[kind];
509 }
510 }