-
Notifications
You must be signed in to change notification settings - Fork 460
/
locations.js
1510 lines (1263 loc) · 48.4 KB
/
locations.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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
import {
Gio,
GLib,
GObject,
Shell,
St,
} from './dependencies/gi.js';
import {ShellMountOperation} from './dependencies/shell/ui.js';
import {
Docking,
Utils,
} from './imports.js';
import {Extension} from './dependencies/shell/extensions/extension.js';
// Use __ () and N__() for the extension gettext domain, and reuse
// the shell domain with the default _() and N_()
const {gettext: __} = Extension;
const {signals: Signals} = imports;
const FALLBACK_REMOVABLE_MEDIA_ICON = 'drive-removable-media';
const FALLBACK_TRASH_ICON = 'user-trash';
const FILE_MANAGER_DESKTOP_APP_ID = 'org.gnome.Nautilus.desktop';
const ATTRIBUTE_METADATA_CUSTOM_ICON = 'metadata::custom-icon';
const TRASH_URI = 'trash://';
const UPDATE_TRASH_DELAY = 1000;
const LAUNCH_HANDLER_MAX_WAIT = 200;
const NautilusFileOperations2Interface = '<node>\
<interface name="org.gnome.Nautilus.FileOperations2">\
<method name="EmptyTrash">\
<arg type="b" name="ask_confirmation" direction="in"/>\
<arg type="a{sv}" name="platform_data" direction="in"/>\
</method>\
</interface>\
</node>';
const NautilusFileOperations2ProxyInterface =
Gio.DBusProxy.makeProxyWrapper(NautilusFileOperations2Interface);
const Labels = Object.freeze({
LOCATION_WINDOWS: Symbol('location-windows'),
WINDOWS_CHANGED: Symbol('windows-changed'),
});
const GJS_SUPPORTS_FILE_IFACE_PROMISES = imports.system.version >= 17101;
if (GJS_SUPPORTS_FILE_IFACE_PROMISES) {
Gio._promisify(Gio.File.prototype, 'query_info_async');
Gio._promisify(Gio.File.prototype, 'query_default_handler_async');
}
/**
*
*/
function makeNautilusFileOperationsProxy() {
const proxy = new NautilusFileOperations2ProxyInterface(
Gio.DBus.session,
'org.gnome.Nautilus',
'/org/gnome/Nautilus/FileOperations2', (_p, error) => {
if (error)
logError(error, 'Error connecting to Nautilus');
}
);
proxy.platformData = params => {
const defaultParams = {
parentHandle: '',
timestamp: global.get_current_time(),
windowPosition: 'center',
};
const {parentHandle, timestamp, windowPosition} = {
...defaultParams,
...params,
};
return {
'parent-handle': new GLib.Variant('s', parentHandle),
'timestamp': new GLib.Variant('u', timestamp),
'window-position': new GLib.Variant('s', windowPosition),
};
};
return proxy;
}
export const LocationAppInfo = GObject.registerClass({
Implements: [Gio.AppInfo],
Properties: {
'location': GObject.ParamSpec.object(
'location', 'location', 'location',
GObject.ParamFlags.READWRITE,
Gio.File.$gtype),
'name': GObject.ParamSpec.string(
'name', 'name', 'name',
GObject.ParamFlags.READWRITE,
null),
'icon': GObject.ParamSpec.object(
'icon', 'icon', 'icon',
GObject.ParamFlags.READWRITE,
Gio.Icon.$gtype),
'cancellable': GObject.ParamSpec.object(
'cancellable', 'cancellable', 'cancellable',
GObject.ParamFlags.READWRITE,
Gio.Cancellable.$gtype),
},
}, class LocationAppInfo extends Gio.DesktopAppInfo {
static get GJS_BINARY_PATH() {
if (!this._gjsBinaryPath)
this._gjsBinaryPath = GLib.find_program_in_path('gjs');
return this._gjsBinaryPath;
}
list_actions() {
return [];
}
get_action_name() {
return null;
}
get_boolean() {
return false;
}
vfunc_dup() {
return new LocationAppInfo({
location: this.location,
name: this.name,
icon: this.icon,
cancellable: this.cancellable,
});
}
vfunc_equal(other) {
if (this.location)
return this.location.equal(other?.location);
return this.name === other.name &&
(this.icon ? this.icon.equal(other?.icon) : !other?.icon);
}
vfunc_get_id() {
return 'location:%s'.format(this.location?.get_uri());
}
vfunc_get_name() {
return this.name;
}
vfunc_get_description() {
return null;
}
vfunc_get_executable() {
return null;
}
vfunc_get_icon() {
return this.icon;
}
vfunc_launch(files, context) {
if (files?.length) {
throw new GLib.Error(Gio.IOErrorEnum,
Gio.IOErrorEnum.NOT_SUPPORTED, 'Launching with files not supported');
}
return this.getHandlerApp().launch_uris([this.location.get_uri()], context);
}
vfunc_supports_uris() {
return false;
}
vfunc_supports_files() {
return false;
}
vfunc_launch_uris(uris, context) {
return this.launch(uris, context);
}
vfunc_should_show() {
return true;
}
vfunc_set_as_default_for_type() {
throw new GLib.Error(Gio.IOErrorEnum,
Gio.IOErrorEnum.NOT_SUPPORTED, 'Not supported');
}
vfunc_set_as_default_for_extension() {
throw new GLib.Error(Gio.IOErrorEnum,
Gio.IOErrorEnum.NOT_SUPPORTED, 'Not supported');
}
vfunc_add_supports_type() {
throw new GLib.Error(Gio.IOErrorEnum,
Gio.IOErrorEnum.NOT_SUPPORTED, 'Not supported');
}
vfunc_can_remove_supports_type() {
return false;
}
vfunc_remove_supports_type() {
return false;
}
vfunc_can_delete() {
return false;
}
vfunc_do_delete() {
return false;
}
vfunc_get_commandline() {
try {
return this.getHandlerApp().get_commandline();
} catch {
return this._getFallbackCommandLine();
}
}
vfunc_get_display_name() {
return this.name;
}
vfunc_set_as_last_used_for_type() {
throw new GLib.Error(Gio.IOErrorEnum,
Gio.IOErrorEnum.NOT_SUPPORTED, 'Not supported');
}
vfunc_get_supported_types() {
return [];
}
_getFallbackCommandLine() {
return `gio open ${this.location?.get_uri()}`;
}
async _queryLocationIcons(params) {
const icons = {standard: null, custom: null};
if (!this.location)
return icons;
const cancellable = params.cancellable ?? this.cancellable;
const iconsQuery = [];
if (params?.standard)
iconsQuery.push(Gio.FILE_ATTRIBUTE_STANDARD_ICON);
if (params?.custom)
iconsQuery.push(ATTRIBUTE_METADATA_CUSTOM_ICON);
if (!iconsQuery.length)
throw new Error('Invalid Query Location Icons parameters');
let info;
try {
if (!GJS_SUPPORTS_FILE_IFACE_PROMISES) {
Gio._promisify(this.location.constructor.prototype,
'query_info_async', 'query_info_finish');
}
info = await this.location.query_info_async(
iconsQuery.join(','),
Gio.FileQueryInfoFlags.NONE,
GLib.PRIORITY_LOW, cancellable);
if (info.has_attribute(Gio.FILE_ATTRIBUTE_STANDARD_ICON))
icons.standard = info.get_icon();
} catch (e) {
if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_FOUND) ||
e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_MOUNTED))
return icons;
throw e;
}
const customIcon = info.get_attribute_string(ATTRIBUTE_METADATA_CUSTOM_ICON);
if (customIcon) {
const customIconFile = GLib.uri_parse_scheme(customIcon)
? Gio.File.new_for_uri(customIcon) : Gio.File.new_for_path(customIcon);
const iconFileInfo = await customIconFile.query_info_async(
Gio.FILE_ATTRIBUTE_STANDARD_TYPE,
Gio.FileQueryInfoFlags.NONE,
GLib.PRIORITY_LOW, cancellable);
if (iconFileInfo.get_file_type() === Gio.FileType.REGULAR)
icons.custom = Gio.FileIcon.new(customIconFile);
}
return icons;
}
async _updateLocationIcon(params = {standard: true, custom: true}) {
const cancellable = new Utils.CancellableChild(this.cancellable);
try {
this._updateIconCancellable?.cancel();
this._updateIconCancellable = cancellable;
const icons = await this._queryLocationIcons({cancellable, ...params});
const icon = icons.custom ?? icons.standard;
if (icon && !icon.equal(this.icon))
this.icon = icon;
} catch (e) {
if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
logError(e, 'Impossible to update icon for %s'.format(this.get_id()));
} finally {
cancellable.cancel();
if (this._updateIconCancellable === cancellable)
delete this._updateIconCancellable;
}
}
async _getHandlerAppAsync(cancellable) {
if (!this.location)
return null;
try {
if (!GJS_SUPPORTS_FILE_IFACE_PROMISES) {
Gio._promisify(this.location.constructor.prototype,
'query_default_handler_async',
'query_default_handler_finish');
}
return await this.location.query_default_handler_async(
GLib.PRIORITY_DEFAULT, cancellable);
} catch (e) {
if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_MOUNTED))
return getFileManagerApp()?.appInfo;
if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
logError(e, 'Impossible to find an URI handler for %s'.format(
this.get_id()));
}
throw e;
}
}
_getHandlerAppFromWorker(cancellable) {
const locationsWorker = GLib.build_filenamev([
Docking.DockManager.extension.path,
'locationsWorker.js',
]);
const locationsWorkerArgs = [LocationAppInfo.GJS_BINARY_PATH, '-m',
locationsWorker, 'handler', this.location.get_uri(),
'--timeout', `${LAUNCH_HANDLER_MAX_WAIT}`];
const subProcess = Gio.Subprocess.new(locationsWorkerArgs,
Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_PIPE);
try {
const [, stdOut, stdErr] = subProcess.communicate(null, cancellable);
subProcess.wait(cancellable);
const errorCode = subProcess.get_exit_status();
const textDecoder = new TextDecoder();
if (errorCode) {
const errorLines = textDecoder.decode(stdErr.toArray()).split('\n');
const error = new GLib.Error(Gio.IOErrorEnum,
errorCode === GLib.MAXUINT8 ? 0 : errorCode, errorLines[0]);
error.stack = `${errorLines.slice(3).join('\n')}${error.stack}`;
throw error;
}
const desktopId = textDecoder.decode(stdOut.toArray()).trim();
const handlerApp = Shell.AppSystem.get_default().lookup_app(desktopId)?.appInfo;
return handlerApp;
} finally {
subProcess.force_exit();
}
}
getHandlerApp() {
if (this._handlerApp)
return this._handlerApp;
if (!this.location)
return null;
const cancellable = new Utils.CancellableChild(this.cancellable);
try {
if (LocationAppInfo.GJS_BINARY_PATH)
this._handlerApp = this._getHandlerAppFromWorker(cancellable);
else
this._handlerApp = this.location.query_default_handler(cancellable);
if (!this._handlerApp) {
throw new GLib.Error(Gio.IOErrorEnum,
Gio.IOErrorEnum.NOT_FOUND, `Handler for ${this.location} not found`);
}
} catch (e) {
if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_MOUNTED))
return getFileManagerApp()?.appInfo;
if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
logError(e, 'Impossible to find an URI handler for %s'.format(
this.get_id()));
}
throw e;
}
return this._handlerApp;
}
destroy() {
this.location = null;
this.icon = null;
this.name = null;
this._handlerApp = null;
this.cancellable?.cancel();
}
});
const MountableVolumeAppInfo = GObject.registerClass({
Implements: [Gio.AppInfo],
Properties: {
'volume': GObject.ParamSpec.object(
'volume', 'volume', 'volume',
GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY,
Gio.Volume.$gtype),
'mount': GObject.ParamSpec.object(
'mount', 'mount', 'mount',
GObject.ParamFlags.READWRITE,
Gio.Mount.$gtype),
'busy': GObject.ParamSpec.boolean(
'busy', 'busy', 'busy',
GObject.ParamFlags.READWRITE,
false),
},
},
class MountableVolumeAppInfo extends LocationAppInfo {
_init(volume, cancellable = null) {
super._init({
volume,
cancellable,
});
this._signalsHandler = new Utils.GlobalSignalsHandler();
const updateAndMonitor = () => {
this._update();
this._monitorChanges();
};
updateAndMonitor();
this._mountChanged = this.connect('notify::mount', updateAndMonitor);
if (!this.mount && this.volume.get_identifier('class') === 'network') {
// For some devices the mount point isn't advertised promptly
// even if it's already existing, and there's no signaling about
this._lazyUpdater = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 2, () => {
this._update();
delete this._lazyUpdater;
return GLib.SOURCE_REMOVE;
});
}
}
get busy() {
return !!this._currentAction;
}
get currentAction() {
return this._currentAction;
}
destroy() {
if (this._lazyUpdater) {
GLib.source_remove(this._lazyUpdater);
delete this._lazyUpdater;
}
this.disconnect(this._mountChanged);
this.mount = null;
this._signalsHandler.destroy();
super.destroy();
}
vfunc_dup() {
return new MountableVolumeAppInfo({
volume: this.volume,
cancellable: this.cancellable,
});
}
vfunc_get_id() {
const uuid = this.mount?.get_uuid() ?? this.volume.get_uuid();
return uuid ? 'mountable-volume:%s'.format(uuid) : super.vfunc_get_id();
}
vfunc_equal(other) {
if (this.volume === other?.volume && this.mount === other?.mount)
return true;
return this.get_id() === other?.get_id();
}
list_actions() {
const actions = [];
const {mount} = this;
if (mount) {
if (this.mount.can_unmount())
actions.push('unmount');
if (this.mount.can_eject())
actions.push('eject');
return actions;
}
if (this.volume.can_mount())
actions.push('mount');
if (this.volume.can_eject())
actions.push('eject');
return actions;
}
get_action_name(action) {
switch (action) {
case 'mount':
return __('Mount');
case 'unmount':
return __('Unmount');
case 'eject':
return __('Eject');
default:
return null;
}
}
vfunc_launch(files, context) {
if (this.mount || files?.length)
return super.vfunc_launch(files, context);
this.mountAndLaunch(files, context);
return true;
}
_update() {
this.mount = this.volume.get_mount();
const removable = this.mount ?? this.volume;
this.name = removable.get_name();
this.icon = removable.get_icon();
this.location = this.mount?.get_default_location() ??
this.volume.get_activation_root();
this._updateLocationIcon({custom: true});
}
_monitorChanges() {
this._signalsHandler.destroy();
const removable = this.mount ?? this.volume;
this._signalsHandler.add(removable, 'changed', () => this._update());
if (this.mount) {
this._signalsHandler.add(this.mount, 'pre-unmount', () => this._update());
this._signalsHandler.add(this.mount, 'unmounted', () => this._update());
}
}
async mountAndLaunch(files, context) {
if (this.mount)
return super.vfunc_launch(files, context);
try {
await this.launchAction('mount');
if (!this.mount) {
throw new Error('No mounted location to open for %s'.format(
this.get_id()));
}
return super.vfunc_launch(files, context);
} catch (e) {
logError(e, 'Mount and launch %s'.format(this.get_id()));
return false;
}
}
_notifyActionError(action, message) {
if (action === 'mount') {
global.notify_error(__('Failed to mount “%s”'.format(
this.get_name())), message);
} else if (action === 'unmount') {
global.notify_error(__('Failed to umount “%s”'.format(
this.get_name())), message);
} else if (action === 'eject') {
global.notify_error(__('Failed to eject “%s”'.format(
this.get_name())), message);
}
}
async launchAction(action) {
if (!this.list_actions().includes(action))
throw new Error('Action %s is not supported by %s', action, this);
if (this._currentAction) {
if (this._currentAction === 'mount') {
this._notifyActionError(action,
__('Mount operation already in progress'));
} else if (this._currentAction === 'unmount') {
this._notifyActionError(action,
__('Umount operation already in progress'));
} else if (this._currentAction === 'eject') {
this._notifyActionError(action,
__('Eject operation already in progress'));
}
throw new Error('Another action %s is being performed in %s'.format(
this._currentAction, this));
}
this._currentAction = action;
this.notify('busy');
const removable = this.mount ?? this.volume;
const operation = new ShellMountOperation.ShellMountOperation(removable);
try {
if (action === 'mount') {
await this.volume.mount(Gio.MountMountFlags.NONE, operation.mountOp,
this.cancellable);
} else if (action === 'unmount') {
await this.mount.unmount_with_operation(Gio.MountUnmountFlags.FORCE,
operation.mountOp, this.cancellable);
} else if (action === 'eject') {
await removable.eject_with_operation(Gio.MountUnmountFlags.FORCE,
operation.mountOp, this.cancellable);
} else {
logError(new Error(), 'No action %s on removable %s'.format(action,
removable.get_name()));
return false;
}
return true;
} catch (e) {
if (action === 'mount' &&
e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.ALREADY_MOUNTED))
return true;
else if (action === 'umount' &&
e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_MOUNTED))
return true;
if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.FAILED))
this._notifyActionError(action, e.message);
if (action === 'mount' && this._isEncryptedMountError(e)) {
delete this._currentAction;
operation.close();
return this.launchAction(action);
}
if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
logError(e, 'Impossible to %s removable %s'.format(action,
removable.get_name()));
}
return false;
} finally {
delete this._currentAction;
this.notify('busy');
this._update();
operation.close();
}
}
_isEncryptedMountError(error) {
// FIXME: we will always get G_IO_ERROR_FAILED from the gvfs udisks
// backend, see https://bugs.freedesktop.org/show_bug.cgi?id=51271
if (!error.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.FAILED))
return false;
// cryptsetup
if (error.message.includes('No key available with this passphrase'))
return true;
// udisks (no password)
if (error.message.includes('No key available to unlock device'))
return true;
// libblockdev wrong password opening LUKS device
if (error.message.includes('Failed to activate device: Incorrect passphrase'))
return true;
// cryptsetup returns EINVAL in many cases, including wrong TCRYPT password/parameters
if (error.message.includes('Failed to load device\'s parameters: Invalid argument') ||
error.message.includes(`Failed to load device's parameters: ${GLib.strerror(22 /* EINVAL */)}`))
return true;
// cryptsetup returns EPERM when the TCRYPT header can't be decrypted
// with the provided password/parameters.
if (error.message.includes('Failed to load device\'s parameters: Operation not permitted') ||
error.message.includes(`Failed to load device's parameters: ${GLib.strerror(1 /* EPERM */)}`))
return true;
return false;
}
});
const TrashAppInfo = GObject.registerClass({
Implements: [Gio.AppInfo],
Properties: {
'empty': GObject.ParamSpec.boolean(
'empty', 'empty', 'empty',
GObject.ParamFlags.READWRITE,
true),
},
},
class TrashAppInfo extends LocationAppInfo {
static initPromises(file) {
if (TrashAppInfo._promisified)
return;
const trashProto = file.constructor.prototype;
Gio._promisify(Gio.FileEnumerator.prototype, 'close_async', 'close_finish');
Gio._promisify(Gio.FileEnumerator.prototype, 'next_files_async', 'next_files_finish');
Gio._promisify(trashProto, 'enumerate_children_async', 'enumerate_children_finish');
Gio._promisify(trashProto, 'query_info_async', 'query_info_finish');
TrashAppInfo._promisified = true;
}
_init(cancellable = null) {
super._init({
location: Gio.file_new_for_uri(TRASH_URI),
name: __('Trash'),
icon: Gio.ThemedIcon.new(FALLBACK_TRASH_ICON),
cancellable,
});
TrashAppInfo.initPromises(this.location);
try {
this._monitor = this.location.monitor_directory(0, this.cancellable);
this._schedUpdateId = 0;
this._monitorChangedId = this._monitor.connect('changed', () =>
this._onTrashChange());
} catch (e) {
if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
return;
logError(e, 'Impossible to monitor trash');
}
this._updateTrash();
this.connect('notify::empty', () => this._updateLocationIcon());
this.notify('empty');
}
destroy() {
if (this._schedUpdateId) {
GLib.source_remove(this._schedUpdateId);
this._schedUpdateId = 0;
}
this._updateTrashCancellable?.cancel();
this._monitor?.disconnect(this._monitorChangedId);
this._monitor = null;
super.destroy();
}
list_actions() {
return this.empty ? [] : ['empty-trash'];
}
get_action_name(action) {
switch (action) {
case 'empty-trash':
return __('Empty Trash');
default:
return null;
}
}
_onTrashChange() {
if (this._schedUpdateId) {
GLib.source_remove(this._schedUpdateId);
this._schedUpdateId = 0;
}
if (this._monitor.is_cancelled())
return;
this._schedUpdateId = GLib.timeout_add(GLib.PRIORITY_LOW,
UPDATE_TRASH_DELAY, () => {
this._schedUpdateId = 0;
this._updateTrash();
return GLib.SOURCE_REMOVE;
});
}
async _updateTrash() {
const priority = GLib.PRIORITY_LOW;
this._updateTrashCancellable?.cancel();
const cancellable = new Utils.CancellableChild(this.cancellable);
this._updateTrashCancellable = cancellable;
try {
const trashInfo = await this.location.query_info_async(
Gio.FILE_ATTRIBUTE_TRASH_ITEM_COUNT,
Gio.FileQueryInfoFlags.NONE,
priority, cancellable);
this.empty = !trashInfo.get_attribute_uint32(
Gio.FILE_ATTRIBUTE_TRASH_ITEM_COUNT);
return;
} catch (e) {
if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
logError(e, 'Impossible to get trash children from infos');
} finally {
cancellable.cancel();
if (this._updateIconCancellable === cancellable)
delete this._updateTrashCancellable;
}
try {
const childrenEnumerator = await this.location.enumerate_children_async(
Gio.FILE_ATTRIBUTE_STANDARD_TYPE, Gio.FileQueryInfoFlags.NONE,
priority, cancellable);
const children = await childrenEnumerator.next_files_async(1,
priority, cancellable);
this.empty = !children.length;
await childrenEnumerator.close_async(priority, null);
} catch (e) {
if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
logError(e, 'Impossible to enumerate trash children');
} finally {
cancellable.cancel();
if (this._updateIconCancellable === cancellable)
delete this._updateTrashCancellable;
}
}
launchAction(action, timestamp) {
if (!this.list_actions().includes(action))
throw new Error('Action %s is not supported by %s', action, this);
const nautilus = makeNautilusFileOperationsProxy();
const askConfirmation = true;
nautilus.EmptyTrashRemote(askConfirmation,
nautilus.platformData({timestamp}), (_p, error) => {
if (error)
logError(error, 'Empty trash failed');
}, this.cancellable);
}
});
/**
* @param shellApp
*/
function wrapWindowsBackedApp(shellApp) {
if (shellApp._dtdData)
throw new Error('%s has been already wrapped'.format(shellApp));
shellApp._dtdData = {
windows: [],
state: undefined,
startingWorkspace: 0,
isFocused: false,
proxyProperties: [],
sources: new Set(),
signalConnections: new Utils.GlobalSignalsHandler(),
methodInjections: new Utils.InjectionsHandler(),
propertyInjections: new Utils.PropertyInjectionsHandler(),
addProxyProperties(parent, proxyProperties) {
Object.entries(proxyProperties).forEach(([p, o]) => {
const publicProp = o.public ? p : `_${p}`;
const get = o.getter && o.value instanceof Function
? () => this[p]() : () => this[p];
Object.defineProperty(parent, publicProp, Object.assign({
get,
set: v => (this[p] = v),
configurable: true,
enumerable: !!o.enumerable,
}, o.readOnly ? {set: undefined} : {}));
if (o.value)
this[p] = o.value;
this.proxyProperties.push(publicProp);
});
},
destroy() {
this.windows = [];
this.proxyProperties = [];
this.sources.forEach(s => GLib.source_remove(s));
this.sources.clear();
this.signalConnections.destroy();
this.methodInjections.destroy();
this.propertyInjections.destroy();
},
};
shellApp._dtdData.addProxyProperties(shellApp, {
windows: {},
state: {},
startingWorkspace: {},
isFocused: {public: true},
signalConnections: {readOnly: true},
sources: {readOnly: true},
checkFocused: {},
setDtdData: {},
});
shellApp._setDtdData = function (data, params = {}) {
for (const [name, value] of Object.entries(data)) {
if (params.readOnly && name in this._dtdData)
throw new Error('Property %s is already defined'.format(name));
const defaultParams = {public: true, readOnly: true};
this._dtdData.addProxyProperties(this, {
[name]: {...defaultParams, ...params, value},
});
}
};
const m = (...args) => shellApp._dtdData.methodInjections.add(shellApp, ...args);
const p = (...args) => shellApp._dtdData.propertyInjections.add(shellApp, ...args);
// mi is Method injector, pi is Property injector
shellApp._setDtdData({mi: m, pi: p}, {public: false});
m('get_state', () => shellApp._state ?? shellApp._getStateByWindows());
p('state', {get: () => shellApp.get_state()});
m('get_windows', () => shellApp._windows);
m('get_n_windows', () => shellApp._windows.length);
m('get_pids', () => shellApp._windows.reduce((pids, w) => {
if (w.get_pid() > 0 && !pids.includes(w.get_pid()))
pids.push(w.get_pid());
return pids;
}, []));
m('is_on_workspace', (_om, workspace) => shellApp._windows.some(w =>
w.get_workspace() === workspace) ||
(shellApp.state === Shell.AppState.STARTING &&
[-1, workspace.index()].includes(shellApp._startingWorkspace)));
m('request_quit', () => shellApp._windows.filter(w =>
w.can_close()).forEach(w => w.delete(global.get_current_time())));
shellApp._setDtdData({
_getStateByWindows() {
return this.get_n_windows() ? Shell.AppState.RUNNING : Shell.AppState.STOPPED;
},
_updateWindows() {
throw new GObject.NotImplementedError(`_updateWindows in ${this.constructor.name}`);
},
_notifyStateChanged() {
Shell.AppSystem.get_default().emit('app-state-changed', this);
this.notify('state');
},
_setState(state) {
const oldState = this.state;
this._state = state;
if (this.state !== oldState)
this._notifyStateChanged();
},
_setWindows(windows) {
const oldState = this.state;
const oldWindows = this._windows.slice();
const result = {windowsChanged: false, stateChanged: false};
this._state = undefined;
if (windows.length !== oldWindows.length ||
windows.some((win, index) => win !== oldWindows[index])) {
this._windows = windows.filter(w => !w.is_override_redirect());
this.emit('windows-changed');
result.windowsChanged = true;
}
if (this.state !== oldState) {
this._notifyStateChanged();
this._checkFocused();
result.stateChanged = true;
}
return result;
},
}, {readOnly: false});
shellApp._sources.add(GLib.idle_add(GLib.DEFAULT_PRIORITY, () => {
shellApp._updateWindows();
shellApp._sources.delete(GLib.main_current_source().source_id);
return GLib.SOURCE_REMOVE;
}));
const windowTracker = Shell.WindowTracker.get_default();
shellApp._checkFocused = function () {
if (this._windows.some(w => w.has_focus())) {