-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
4701 lines (4151 loc) · 185 KB
/
extension.js
File metadata and controls
4701 lines (4151 loc) · 185 KB
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
'use strict';
const ExtensionUtils = imports.misc.extensionUtils;
const Main = imports.ui.main;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const {St, GObject, GLib, Gio, Clutter, Meta, Shell, Pango} = imports.gi;
const Me = ExtensionUtils.getCurrentExtension();
const _ = imports.gettext.domain(Me.metadata['gettext-domain']).gettext;
// Gate verbose logs behind a runtime flag controlled by settings
// For security and to satisfy static analysis, do not emit console logs.
globalThis.__CFP_DEBUG = false;
const cfpLogger = {
log: (..._args) => {},
warn: (..._args) => {},
error: (..._args) => {},
};
// Keep legacy helper as a no-op
function cfpLog(..._args) {}
// Alias to preserve existing calls without producing output
const console = cfpLogger;
const HISTORY_LIMIT_MIN = 10;
const HISTORY_LIMIT_MAX = 100;
// UUID constant used for opening prefs
const UUID = 'clipflow-pro@nickotmazgin.github.io';
var ClipFlowIndicator = GObject.registerClass(
class ClipFlowIndicator extends PanelMenu.Button {
_init(settings = null) {
super._init(0.0, _('ClipFlow Pro'));
// Initialize settings (passed from Extension.enable)
this._settings = settings;
if (!this._settings) {
throw new Error('ClipFlow Pro: Settings object is required to initialize the indicator.');
}
this._contextMenuManager = null;
this._contextMenu = null;
this._contextMenuNotificationItem = null;
this._contextMenuRecentSection = null;
this._contextMenuRecentLimit = this._settings.get_int('context-menu-items');
this._contextMenuOpenChangedId = 0;
this._menuOpenChangedId = 0;
this._buttonPressId = 0;
this._popupMenuId = 0;
this._menuContainerItem = null;
this._menuContainerBox = null;
this._keybindingRegistrations = new Map();
this._actionModeMask = this._computeActionModeMask();
this._historyScrollView = null;
this._historyContainer = null;
this._paginationBox = null;
this._paginationLabel = null;
this._paginationPrevButton = null;
this._paginationNextButton = null;
this._historySaveTimeout = 0;
this._autoClearTimeouts = new Map();
this._storageDir = GLib.build_filenamev([GLib.get_user_config_dir(), 'clipflow-pro']);
this._historyFile = GLib.build_filenamev([this._storageDir, 'history.json']);
this._historySaveDelaySeconds = 1;
this._autoClearDurationSeconds = 300;
this._currentPage = 0;
this._skipCleanupOnDestroy = false;
this._iconThemeRegistered = false;
this._icon = null;
this._panelSignalIds = [];
this._displaySignalIds = [];
this._menuRebuildInProgress = false;
// GNOME 43 compatibility: prefer legacy rows unless user explicitly enables new rows
this._useLegacyHistoryRows = this._settings.get_boolean('use-legacy-menu-items');
if (this._useLegacyHistoryRows === false) {
// Force legacy rows by default on GNOME 43 for better compatibility
this._useLegacyHistoryRows = true;
}
this._copyNotifyMinIntervalMs = 1500;
this._lastCopyNotifyTime = 0;
this._lastCopyNotifyText = '';
this._logThrottle = new Map();
this._logRateLimitMs = 5000;
this._deferredSourceIds = new Set();
this._destroyed = false;
this._clipboardNotifyShown = false;
this._useCompactUI = this._settings.get_boolean('use-compact-ui');
// Rendering/compatibility settings
// Force Classic rendering on GNOME 43 build for safest UX without CSS
this._renderingMode = 'classic';
this._classicMaxRows = Math.min(12, this._safeGetInt('classic-max-rows', 50));
this._disableCss = this._safeGetBoolean('disable-css', false);
this._warnConflicts = this._safeGetBoolean('warn-conflicts', true);
// Limit how many MIME fallbacks we try to avoid stalls on non‑text clipboards
this._maxTextMimeTries = 6;
// GNOME 43 stability: always use Classic list
this._forceClassicList = true;
this._autoFallbackApplied = false;
this._classicShowCount = 0; // for "Show more" in classic mode
this._classicFilterMode = 'all';
// Classic popup-item rows fallback for GNOME 43 to avoid any actor layout/theme issues
this._classicRowsEnabled = true;
// Sort order: 'newest' (default) or 'oldest'
this._sortOrder = 'newest';
// Initialize clipboard history
this._clipboardHistory = [];
this._maxHistory = this._settings.get_int('max-entries');
this._entriesPerPage = Math.max(5, this._settings.get_int('entries-per-page'));
this._isMonitoring = false;
this._clipboard = null;
this._clipboardOwnerChangeId = 0;
this._selection = null;
this._selectionOwnerChangedId = 0;
this._clipboardCheckTimeout = 0;
this._clipboardTimeout = null; // Retained for cleanup during transitions
this._clipboardPollId = 0;
// Reduced polling interval for better responsiveness, especially on Wayland
// GNOME 43 Wayland requires very aggressive polling due to clipboard API limitations
// Note: Actual polling interval is set in _startClipboardPolling() based on Wayland detection
this._clipboardPollIntervalMs = 500; // Base interval, adjusted dynamically for Wayland
// Throttle external spawn fallbacks to avoid stressing the shell at startup
this._spawnGuardMs = 5000;
this._lastSpawnTimeMs = 0;
this._spawnInFlight = false;
this._clipboardRetryTimeoutId = 0;
this._clipboardRetryAttempts = 0;
this._clipboardRetryNotified = false;
this._lastClipboardText = '';
this._lastPrimaryText = '';
this._monitoringResumeTimeoutId = 0;
this._settingsSignalIds = [];
this._searchDebounceTimeout = 0;
this._filteredHistoryCache = null;
this._filterCacheValid = false;
this._lastSearchText = null;
this._searchFocusGuardId = 0;
this._searchHadInput = false;
this._textMimeTypes = [
'text/plain',
'text/plain;charset=utf-8',
'text/plain;charset=UTF-8',
'UTF8_STRING',
'STRING',
'TEXT',
'COMPOUND_TEXT',
'text/uri-list',
'x-special/gnome-copied-files',
'text/html',
'text/html;charset=utf-8',
'text/html;charset=UTF-8'
];
// Validate and sanitize settings on startup
this._validateSettings();
// Connect to settings changes
this._settingsSignalIds.push(this._settings.connect('changed::max-entries', () => {
const newValue = this._settings.get_int('max-entries');
this._maxHistory = this._clampHistorySize(newValue);
if (this._maxHistory !== newValue) {
this._settings.set_int('max-entries', this._maxHistory);
}
this._trimHistory();
}));
this._settingsSignalIds.push(this._settings.connect('changed::show-copy-notifications', () => {
this._syncContextMenuToggles();
}));
this._settingsSignalIds.push(this._settings.connect('changed::entries-per-page', () => {
const newValue = this._settings.get_int('entries-per-page');
this._entriesPerPage = Math.max(5, Math.min(50, newValue));
if (this._entriesPerPage !== newValue) {
this._settings.set_int('entries-per-page', this._entriesPerPage);
}
this._currentPage = 0;
this._refreshHistory();
}));
this._settingsSignalIds.push(this._settings.connect('changed::auto-clear-sensitive', () => {
this._updateAutoClearTimers();
}));
this._settingsSignalIds.push(this._settings.connect('changed::use-compact-ui', () => {
this._useCompactUI = this._settings.get_boolean('use-compact-ui');
this._applyUiStyle();
}));
this._settingsSignalIds.push(this._settings.connect('changed::pause-on-lock', () => {
this._pauseOnLock = this._safeGetBoolean('pause-on-lock', false);
}));
this._settingsSignalIds.push(this._settings.connect('changed::clear-on-lock', () => {
this._clearOnLock = this._safeGetBoolean('clear-on-lock', false);
}));
this._settingsSignalIds.push(this._settings.connect('changed::copy-as-plain-text', () => {
this._copyAsPlain = this._safeGetBoolean('copy-as-plain-text', false);
}));
this._settingsSignalIds.push(this._settings.connect('changed::context-menu-items', () => {
const newValue = this._settings.get_int('context-menu-items');
const clamped = Math.max(1, Math.min(20, newValue));
if (clamped !== newValue) {
this._settings.set_int('context-menu-items', clamped);
}
this._contextMenuRecentLimit = clamped;
this._populateContextMenuRecentEntries();
}));
this._settingsSignalIds.push(this._settings.connect('changed::use-legacy-menu-items', () => {
const val = this._settings.get_boolean('use-legacy-menu-items');
this._useLegacyHistoryRows = (this._shellMajor > 0 && this._shellMajor < 45) ? true : val;
this._buildMenu();
}));
this._settingsSignalIds.push(this._settings.connect('changed::rendering-mode', () => {
// Ignore changes; keep Classic enforced on GNOME 43 build
this._renderingMode = 'classic';
this._forceClassicList = true;
this._autoFallbackApplied = false;
this._buildMenu();
}));
this._settingsSignalIds.push(this._settings.connect('changed::classic-max-rows', () => {
// Clamp rows on GNOME 43 to keep menu height reasonable
this._classicMaxRows = Math.min(12, this._safeGetInt('classic-max-rows', 50));
this._buildMenu();
}));
this._settingsSignalIds.push(this._settings.connect('changed::disable-css', () => {
this._disableCss = this._safeGetBoolean('disable-css', false);
this._buildMenu();
}));
['show-menu-shortcut', 'enhanced-copy-shortcut', 'enhanced-paste-shortcut'].forEach(key => {
this._settingsSignalIds.push(this._settings.connect(`changed::${key}`, () => {
this._registerKeybindings();
}));
});
// Defaults for lock behavior + copy sanitize
this._pauseOnLock = this._safeGetBoolean('pause-on-lock', false);
this._clearOnLock = this._safeGetBoolean('clear-on-lock', false);
this._copyAsPlain = this._safeGetBoolean('copy-as-plain-text', false);
this._createIcon();
this._watchPanelForIconSize();
this._buildContextMenu();
this._loadHistoryFromDisk();
this._menuBuilt = false;
// Defer menu build and clipboard monitoring to reduce startup risk
this._scheduleTimeout(400, () => { this._startClipboardMonitoring(); return GLib.SOURCE_REMOVE; });
this._registerKeybindings();
this._connectLockSignals();
// Connect menu open/close signals to refresh history when menu opens
if (this.menu) {
if (this._menuOpenChangedId) {
this.menu.disconnect(this._menuOpenChangedId);
}
this._menuOpenChangedId = this.menu.connect('open-state-changed', (menu, open) => {
cfpLog(`ClipFlow Pro: Menu open-state-changed (open: ${open}, container exists: ${!!this._historyContainer})`);
if (open) {
if (!this._menuBuilt) {
this._buildMenu();
this._menuBuilt = true;
}
if (this._forceClassicList) {
if (this._searchEntry && this._searchEntry.clutter_text && this._searchEntry.clutter_text.set_text)
this._searchEntry.clutter_text.set_text('');
this._lastSearchText = '';
// Rebuild entire menu to reflect latest history
this._buildMenu();
} else if (this._historyContainer) {
cfpLog(`ClipFlow Pro: Menu opened - refreshing history (current children: ${this._historyContainer.get_children ? this._historyContainer.get_children().length : 0})`);
this._refreshHistory();
}
}
});
}
this._buttonPressId = this.connect('button-press-event', this._onButtonPressEvent.bind(this));
this._popupMenuId = this.connect('popup-menu', this._onPopupMenu.bind(this));
}
_connectLockSignals() {
this._lockSignals = this._lockSignals || [];
const shield = Main.screenShield;
if (!shield) return;
const onLocked = () => {
if (this._clearOnLock) this._clearAllHistory();
if (this._pauseOnLock) {
this._pausedByLock = true;
this._stopClipboardMonitoring();
}
};
const onUnlocked = () => {
if (this._pausedByLock) {
this._pausedByLock = false;
this._startClipboardMonitoring();
}
};
const id1 = shield.connect('locked', onLocked);
const id2 = shield.connect('unlocked', onUnlocked);
if (id1) this._lockSignals.push([shield, id1]);
if (id2) this._lockSignals.push([shield, id2]);
}
_disconnectLockSignals() {
if (!this._lockSignals) return;
for (const [obj, id] of this._lockSignals) {
obj.disconnect(id);
}
this._lockSignals = [];
}
_addIndicatorIcon() {
const icon = new St.Icon({
style_class: 'system-status-icon clipflow-pro-panel-icon',
icon_name: 'edit-paste-symbolic'
});
icon.set_icon_size(16);
return icon;
}
_createIcon() {
// Remove existing icon if we're rebuilding
if (this._icon) {
const parent = this._icon.get_parent();
if (parent && parent.remove_child) parent.remove_child(this._icon);
this._icon.destroy();
this._icon = null;
}
this._ensureIconThemeRegistered();
const icon = this._addIndicatorIcon();
this._icon = icon;
if (this.add_child) this.add_child(icon);
else if (this.actor && this.actor.add_child) this.actor.add_child(icon);
else if (this.add_actor) this.add_actor(icon);
this._updateIconState();
}
_resolveActor(target) {
if (!target || typeof target !== 'object')
return null;
if (target.add_style_class_name || target.add_child || target.hide)
return target;
if (target.actor)
return this._resolveActor(target.actor);
if (target.box)
return this._resolveActor(target.box);
if (target._actor)
return this._resolveActor(target._actor);
return null;
}
_safeAdd(parent, child) {
const p = this._resolveActor(parent);
const c = this._resolveActor(child) || child;
if (!p || !c)
return false;
if (p.add_child) {
p.add_child(c);
return true;
}
if (p.add_actor) {
p.add_actor(c);
return true;
}
if (p.actor && p.actor.add_child) {
p.actor.add_child(c);
return true;
}
return false;
}
_safeSetSpacing(container, px) {
if (container && container.set_spacing) {
container.set_spacing(px);
return;
}
const layout = container && container.get_layout_manager ? container.get_layout_manager() : null;
if (layout && 'spacing' in layout)
layout.spacing = px;
}
_addStyleClass(target, className) {
const actor = this._resolveActor(target);
if (actor && actor.add_style_class_name) {
actor.add_style_class_name(className);
}
}
_addActorToUiGroup(target) {
const actor = this._resolveActor(target);
if (!actor) {
return null;
}
if (Main.uiGroup && Main.uiGroup.add_child) {
Main.uiGroup.add_child(actor);
} else if (Main.uiGroup && Main.uiGroup.add_actor) {
Main.uiGroup.add_actor(actor);
}
return actor;
}
_getCharacterArray(text) {
if (!text) {
return [];
}
try {
return Array.from(text);
} catch (_error) {
return String(text).split('');
}
}
_characterLength(text) {
return this._getCharacterArray(text).length;
}
_truncateText(text, limit) {
if (!text || limit <= 0) {
return '';
}
const chars = this._getCharacterArray(text);
if (chars.length <= limit) {
return text;
}
return chars.slice(0, limit).join('');
}
_normalizeClipboardText(value) {
if (value === null || value === undefined) {
return '';
}
if (typeof value === 'string') {
return value;
}
// GLib.Bytes or similar object with toArray(): decode as UTF‑8
if (value && value.toArray) {
const u8 = Uint8Array.from(value.toArray());
return new TextDecoder('utf-8').decode(u8);
}
// Uint8Array: decode as UTF‑8
if (value instanceof Uint8Array) {
return new TextDecoder('utf-8').decode(value);
}
const fallback = String(value ?? '');
const trimmed = fallback.trim();
if (!trimmed || trimmed === '[object Object]' || trimmed === 'undefined' || trimmed === 'null') {
return '';
}
return fallback;
}
_decodeClipboardBytes(bytes, mimetype) {
if (!bytes) {
return '';
}
let text = '';
try {
if (typeof bytes === 'string') {
text = bytes;
} else if (bytes && bytes.get_data && bytes.get_size) {
// GLib.Bytes object: use get_data() and get_size()
const size = bytes.get_size();
if (size > 0) {
const data = bytes.get_data();
if (data) {
const u8 = new Uint8Array(data);
text = new TextDecoder('utf-8').decode(u8);
}
}
} else if (bytes && bytes.toArray) {
const u8 = Uint8Array.from(bytes.toArray());
text = new TextDecoder('utf-8').decode(u8);
} else if (bytes instanceof Uint8Array) {
text = new TextDecoder('utf-8').decode(bytes);
}
} catch (error) {
// Failed to convert clipboard bytes
}
if (!text) {
return '';
}
const mime = String(mimetype || '').toLowerCase();
const baseMime = mime.split(';')[0];
if (baseMime === 'x-special/gnome-copied-files' || baseMime === 'text/uri-list') {
// Convert newline-separated URIs/paths into a user-friendly list
// Handle Nautilus/Files format: "copy\nfile:///path1\nfile:///path2" or "cut\nfile:///path"
const lines = text.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
const payload = lines
.filter(line => line !== 'copy' && line !== 'cut') // Skip Nautilus header
.map(line => {
if (line.startsWith('file://')) {
try {
// Decode URI and remove file:// prefix for clean display
return decodeURI(line.replace(/^file:\/\//, ''));
} catch (_e) {
// Fallback: just strip the prefix if URI decode fails
return line.replace(/^file:\/\//, '');
}
}
return line;
});
text = payload.join('\n');
} else if (baseMime === 'text/html') {
text = this._stripClipboardHtml(text);
}
return text;
}
_stripClipboardHtml(html) {
if (!html) {
return '';
}
const sanitize = (input, regex, replacement = '') => {
let previous = input;
let current = input;
do {
previous = current;
current = current.replace(regex, replacement);
} while (current !== previous);
return current;
};
let text = String(html);
text = sanitize(text, /<\s*style\b[^>]*>[\s\S]*?<\s*\/\s*style\b[^>]*>/gi);
text = sanitize(text, /<\s*script\b[^>]*>[\s\S]*?<\s*\/\s*script\b[^>]*>/gi);
text = sanitize(text, /<br\s*\/?>/gi, '\n');
text = sanitize(text, /<\/(p|div|li|tr|h[1-6])>/gi, '\n');
text = sanitize(text, /<td>/gi, '\t');
text = sanitize(text, /<[^>]+>/g);
// Collapse excessive whitespace but keep intentional newlines
text = sanitize(text, /\r/g);
text = sanitize(text, /\n{3,}/g, '\n\n');
text = text.replace(/[<>]/g, '');
return text.trim();
}
_hideActor(target) {
const actor = this._resolveActor(target);
if (!actor) {
return;
}
if (actor && actor.hide) actor.hide();
if (!actor.hide)
actor.visible = false;
}
_updateIconState() {
if (!this._icon) return;
const hasEntries = this._clipboardHistory.length > 0;
const isMonitoring = this._isMonitoring;
if (!isMonitoring && hasEntries) {
this._icon.opacity = 160;
} else {
this._icon.opacity = 255;
}
}
_computeIconSize() {
const override = this._settings.get_int('icon-size-override');
if (override && override > 0) return override;
const panel = Main.panel;
if (!panel) return 16;
const height = typeof panel.height === 'number' ? panel.height : 24;
const scale = (global.display && global.display.get_monitor_scale)
? global.display.get_monitor_scale(global.display.get_primary_monitor())
: 1;
const size = Math.max(12, Math.min(24, Math.round(height * 0.8 * scale)));
return size;
}
_setIconSize(size) {
if (!this._icon) return;
if (this._icon.set_icon_size) {
this._icon.set_icon_size(size);
} else if ('icon_size' in this._icon) {
this._icon.icon_size = size;
}
}
_disconnectPanelWatchers() {
const panel = Main.panel;
if (panel && Array.isArray(this._panelSignalIds)) {
this._panelSignalIds.forEach(id => {
if (typeof id === 'number' && id > 0) {
panel.disconnect(id);
}
});
}
this._panelSignalIds = [];
const display = global.display;
if (display && Array.isArray(this._displaySignalIds)) {
this._displaySignalIds.forEach(id => {
if (typeof id === 'number' && id > 0) {
display.disconnect(id);
}
});
}
this._displaySignalIds = [];
}
_watchPanelForIconSize() {
const panel = Main.panel;
if (!panel) return;
this._disconnectPanelWatchers();
// Apply immediately
this._setIconSize(this._computeIconSize());
const onChange = () => {
this._setIconSize(this._computeIconSize());
};
const id1 = panel.connect('style-changed', onChange);
if (typeof id1 === 'number' && id1 > 0) this._panelSignalIds.push(id1);
const id2 = panel.connect('notify::height', onChange);
if (typeof id2 === 'number' && id2 > 0) this._panelSignalIds.push(id2);
const display = global.display;
if (display) {
try {
const id = display.connect('notify::scale-factor', onChange);
if (typeof id === 'number' && id > 0) {
this._displaySignalIds.push(id);
}
} catch (_e) {}
}
}
_ensureIconThemeRegistered() {
try {
if (!this._iconThemeRegistered) {
// Icons are referenced via Gio.FileIcon; no theme path change needed.
this._iconThemeRegistered = true;
}
} catch (error) {
console.warn(`ClipFlow Pro: Failed to register icon theme path: ${error}`);
}
}
_logThrottled(key, message, minIntervalMs = this._logRateLimitMs) {
try {
const now = GLib.get_monotonic_time();
const intervalUs = Math.max(0, minIntervalMs) * 1000;
const lastLog = this._logThrottle.get(key) || 0;
if (now - lastLog < intervalUs) {
return;
}
this._logThrottle.set(key, now);
// Sanitize message to prevent logging sensitive data
const sanitized = this._sanitizeLogMessage(message);
console.warn(sanitized);
} catch (error) {
// Fallback: if throttling fails, log once to avoid silence on critical errors
// Sanitize to prevent sensitive data exposure
const sanitized = this._sanitizeLogMessage(message);
console.warn(sanitized);
}
}
_sanitizeLogMessage(message) {
if (!message || typeof message !== 'string') {
return String(message || '');
}
// Remove potential sensitive data patterns
// Limit message length to prevent accidental data exposure
const maxLength = 200;
let sanitized = message.substring(0, maxLength);
// Remove any clipboard-like content that might have leaked into error messages
// This is a safety measure - error messages should not contain clipboard data
sanitized = sanitized.replace(/clipboard[:\s]+[^\n]{20,}/gi, 'clipboard: [redacted]');
return sanitized;
}
_clampHistorySize(value) {
return Math.max(HISTORY_LIMIT_MIN, Math.min(HISTORY_LIMIT_MAX, value));
}
_invalidateFilterCache(resetSearch = false) {
this._filterCacheValid = false;
this._filteredHistoryCache = null;
if (resetSearch) {
this._lastSearchText = null;
}
}
_scheduleIdle(callback, priority = GLib.PRIORITY_DEFAULT_IDLE) {
let sourceId = 0;
sourceId = GLib.idle_add(priority, () => {
this._deferredSourceIds.delete(sourceId);
return callback();
});
if (sourceId) {
this._deferredSourceIds.add(sourceId);
}
return sourceId;
}
_scheduleTimeout(delayMs, callback, priority = GLib.PRIORITY_DEFAULT) {
let sourceId = 0;
sourceId = GLib.timeout_add(priority, delayMs, () => {
this._deferredSourceIds.delete(sourceId);
return callback();
});
if (sourceId) {
this._deferredSourceIds.add(sourceId);
}
return sourceId;
}
_startSearchFocusGuard() {
this._clearSearchFocusGuard();
let attempts = 0;
const maxAttempts = 12; // ~600ms at 50ms interval
const target = () => this._searchEntry && (this._searchEntry.clutter_text || this._searchEntry);
this._searchHadInput = false;
this._searchFocusGuardId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 50, () => {
try {
if (!this.menu || !this.menu.isOpen || this._searchHadInput) {
this._searchFocusGuardId = 0;
return GLib.SOURCE_REMOVE;
}
const t = target();
if (t && global && global.stage && global.stage.set_key_focus)
global.stage.set_key_focus(t);
} catch (_e) {}
attempts++;
if (attempts >= maxAttempts) {
this._searchFocusGuardId = 0;
return GLib.SOURCE_REMOVE;
}
return GLib.SOURCE_CONTINUE;
});
}
_clearSearchFocusGuard() {
if (this._searchFocusGuardId) {
GLib.source_remove(this._searchFocusGuardId);
this._searchFocusGuardId = 0;
}
}
_clearDeferredSources() {
if (!this._deferredSourceIds) {
return;
}
for (const sourceId of this._deferredSourceIds) {
GLib.source_remove(sourceId);
}
this._deferredSourceIds.clear();
}
_destroyActor(actor) {
if (!actor) {
return;
}
try {
if (actor._clipflowDestroyed) {
return;
}
if (actor && actor.destroy) actor.destroy();
else if (actor && actor.actor && actor.actor.destroy) actor.actor.destroy();
actor._clipflowDestroyed = true;
} catch (error) {
// Actor destroy failed
}
}
_validateSettings() {
// Validate max-entries (10-100)
const maxEntries = this._settings.get_int('max-entries');
const clampedEntries = this._clampHistorySize(maxEntries);
if (clampedEntries !== maxEntries) {
this._settings.set_int('max-entries', clampedEntries);
}
this._maxHistory = clampedEntries;
// Validate entries-per-page (5-50)
const entriesPerPage = this._settings.get_int('entries-per-page');
if (entriesPerPage < 5 || entriesPerPage > 50) {
const corrected = Math.max(5, Math.min(50, entriesPerPage));
this._settings.set_int('entries-per-page', corrected);
this._entriesPerPage = corrected;
}
// Validate max-entry-length (100-10000)
const maxEntryLength = this._settings.get_int('max-entry-length');
if (maxEntryLength < 100 || maxEntryLength > 10000) {
const corrected = Math.max(100, Math.min(10000, maxEntryLength));
this._settings.set_int('max-entry-length', corrected);
}
// Validate min-entry-length (0-100)
const minEntryLength = this._settings.get_int('min-entry-length');
if (minEntryLength < 0 || minEntryLength > 100) {
const corrected = Math.max(0, Math.min(100, minEntryLength));
this._settings.set_int('min-entry-length', corrected);
}
// Validate context-menu-items (1-20)
const contextMenuItems = this._settings.get_int('context-menu-items');
if (contextMenuItems < 1 || contextMenuItems > 20) {
const corrected = Math.max(1, Math.min(20, contextMenuItems));
this._settings.set_int('context-menu-items', corrected);
this._contextMenuRecentLimit = corrected;
}
// Validate icon-size-override (0-64)
const iconSizeOverride = this._settings.get_int('icon-size-override');
if (iconSizeOverride < 0 || iconSizeOverride > 64) {
this._settings.set_int('icon-size-override', 0);
}
// Validate copied-preview-length (5-200)
const previewLength = this._settings.get_int('copied-preview-length');
if (previewLength < 5 || previewLength > 200) {
const corrected = Math.max(5, Math.min(200, previewLength));
this._settings.set_int('copied-preview-length', corrected);
}
// Validate pause-duration-minutes (1-120)
const pauseMinutes = this._settings.get_int('pause-duration-minutes');
if (pauseMinutes < 1 || pauseMinutes > 120) {
const corrected = Math.max(1, Math.min(120, pauseMinutes));
this._settings.set_int('pause-duration-minutes', corrected);
}
}
// Safe settings access with fallback defaults
_safeGetInt(key, defaultValue) {
try {
if (!this._settings) {
return defaultValue;
}
return this._settings.get_int(key);
} catch (error) {
return defaultValue;
}
}
_safeGetBoolean(key, defaultValue) {
try {
if (!this._settings) {
return defaultValue;
}
return this._settings.get_boolean(key);
} catch (error) {
return defaultValue;
}
}
_safeGetString(key, defaultValue) {
try {
if (!this._settings) {
return defaultValue;
}
return this._settings.get_string(key) || defaultValue;
} catch (error) {
return defaultValue;
}
}
_buildMenu() {
// Clear existing menu
this.menu.removeAll();
// Add ClipFlow-specific style class to menu to scope CSS properly
if (!this._disableCss)
this._addStyleClass(this.menu, 'clipflow-menu');
// Header removed to avoid duplicate title rows and reduce clutter
// Classic, no-container fallback path
if (this._forceClassicList) {
this._buildClassicListMenu();
return;
}
if (this._menuContainerItem) {
this._menuContainerItem.destroy();
this._menuContainerItem = null;
this._menuContainerBox = null;
}
this._menuContainerItem = new PopupMenu.PopupBaseMenuItem({
reactive: false,
can_focus: false
});
const container = new St.BoxLayout({
vertical: true,
x_expand: true,
y_expand: true
});
this._safeSetSpacing(container, 10);
container.add_style_class_name('clipflow-main-container');
const added = this._safeAdd(this._menuContainerItem, container);
if (added) {
const itemActor = this._resolveActor(this._menuContainerItem);
if (itemActor) {
itemActor.x_expand = true;
itemActor.y_expand = true;
}
} else {
console.error('ClipFlow Pro: ERROR - Failed to add container to menu item!');
}
this.menu.addMenuItem(this._menuContainerItem);
this._menuContainerBox = container;
this._applyUiStyle();
// Search removed: do not add search row on Enhanced in 43 build
// History container and pagination
this._historyScrollView = new St.ScrollView({
style_class: 'clipflow-history-scroll',
overlay_scrollbars: false,
x_expand: true,
y_expand: true
});
if (this._historyScrollView.set_margin_right) this._historyScrollView.set_margin_right(10);
if (this._historyScrollView.set_margin_bottom) this._historyScrollView.set_margin_bottom(8);
if (St.PolicyType) {
if (this._historyScrollView.set_policy) this._historyScrollView.set_policy(St.PolicyType.NEVER, St.PolicyType.AUTOMATIC);
} else if (Clutter.PolicyType) {
if (this._historyScrollView.set_policy) this._historyScrollView.set_policy(Clutter.PolicyType.NEVER, Clutter.PolicyType.AUTOMATIC);
}
this._historyContainer = new St.BoxLayout({
vertical: true,
x_expand: true
});
this._addStyleClass(this._historyContainer, 'clipflow-history-list');
this._safeSetSpacing(this._historyContainer, 4);
// Attach history container to scrollview (handles 43/45 variants)
if (this._historyScrollView.set_child)
this._historyScrollView.set_child(this._historyContainer);
else
this._safeAdd(this._historyScrollView, this._historyContainer);
container.add_child(this._historyScrollView);
const paginationRow = this._createPaginationControls();
if (paginationRow)
container.add_child(paginationRow);
// Enhanced: group actions as a submenu on the root menu for consistency and a single entry point
try {
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
this._addActionsSubmenu();
} catch (_e) {}
// Load initial history - ensure container exists first
if (this._historyContainer) {
this._refreshHistory();
}
}
_addActionsSubmenu() {
const actionsSub = new PopupMenu.PopupSubMenuMenuItem(_('Actions'));
const add = (label, cb) => {
const it = new PopupMenu.PopupMenuItem(label);
it.connect('activate', cb);
actionsSub.menu.addMenuItem(it);
};
// Filter options (applies to both Classic and Enhanced)
const mark = s => `• ${s}`;
add(this._classicFilterMode === 'all' ? mark(_('Filter: All')) : _('Filter: All'), () => this._setClassicFilterMode('all'));
add(this._classicFilterMode === 'pinned' ? mark(_('Filter: Pinned')) : _('Filter: Pinned'), () => this._setClassicFilterMode('pinned'));
add(this._classicFilterMode === 'starred' ? mark(_('Filter: Starred')) : _('Filter: Starred'), () => this._setClassicFilterMode('starred'));
actionsSub.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
// Sort options
add(this._sortOrder === 'newest' ? mark(_('Sort: Newest first')) : _('Sort: Newest first'), () => this._setSortOrder('newest'));
add(this._sortOrder === 'oldest' ? mark(_('Sort: Oldest first')) : _('Sort: Oldest first'), () => this._setSortOrder('oldest'));
actionsSub.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
// Toggles: Capture PRIMARY and Pause Monitoring