forked from micheleg/dash-to-dock
/
appIcons.js
1760 lines (1479 loc) · 65.6 KB
/
appIcons.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 -*-
const Clutter = imports.gi.Clutter;
const GdkPixbuf = imports.gi.GdkPixbuf
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const Gtk = imports.gi.Gtk;
const Pango = imports.gi.Pango;
const Signals = imports.signals;
const Lang = imports.lang;
const Meta = imports.gi.Meta;
const Shell = imports.gi.Shell;
const St = imports.gi.St;
const Mainloop = imports.mainloop;
const Cairo = imports.cairo;
// Use __ () and N__() for the extension gettext domain, and reuse
// the shell domain with the default _() and N_()
const Gettext = imports.gettext.domain('dashtodock');
const __ = Gettext.gettext;
const N__ = function(e) { return e };
const AppDisplay = imports.ui.appDisplay;
const AppFavorites = imports.ui.appFavorites;
const Dash = imports.ui.dash;
const DND = imports.ui.dnd;
const IconGrid = imports.ui.iconGrid;
const Main = imports.ui.main;
const PopupMenu = imports.ui.popupMenu;
const Tweener = imports.ui.tweener;
const Util = imports.misc.util;
const Workspace = imports.ui.workspace;
const Me = imports.misc.extensionUtils.getCurrentExtension();
const Utils = Me.imports.utils;
const WindowPreview = Me.imports.windowPreview;
let tracker = Shell.WindowTracker.get_default();
let DASH_ITEM_LABEL_SHOW_TIME = Dash.DASH_ITEM_LABEL_SHOW_TIME;
const clickAction = {
SKIP: 0,
MINIMIZE: 1,
LAUNCH: 2,
CYCLE_WINDOWS: 3,
MINIMIZE_OR_OVERVIEW: 4,
PREVIEWS: 5,
QUIT: 6
};
const scrollAction = {
DO_NOTHING: 0,
CYCLE_WINDOWS: 1,
SWITCH_WORKSPACE: 2
};
let recentlyClickedAppLoopId = 0;
let recentlyClickedApp = null;
let recentlyClickedAppWindows = null;
let recentlyClickedAppIndex = 0;
let recentlyClickedAppMonitor = -1;
// We need an icons theme object, this is the only way I managed to get
// pixel buffers that can be used for calculating the backlight color
let themeLoader = null;
// Global icon cache. Used for Unity7 styling.
let iconCacheMap = new Map();
// Max number of items to store
// We don't expect to ever reach this number, but let's put an hard limit to avoid
// even the remote possibility of the cached items to grow indefinitely.
const MAX_CACHED_ITEMS = 1000;
// When the size exceed it, the oldest 'n' ones are deleted
const BATCH_SIZE_TO_DELETE = 50;
// The icon size used to extract the dominant color
const DOMINANT_COLOR_ICON_SIZE = 64;
/**
* Extend AppIcon
*
* - Pass settings to the constructor and bind settings changes
* - Apply a css class based on the number of windows of each application (#N);
* - Draw a dot for each window of the application based on the default "dot" style which is hidden (#N);
* a class of the form "running#N" is applied to the AppWellIcon actor.
* like the original .running one.
* - Add a .focused style to the focused app
* - Customize click actions.
* - Update minimization animation target
* - Update menu if open on windows change
* - Unity7-esk backlit item emulation
*/
var MyAppIcon = new Lang.Class({
Name: 'DashToDock.AppIcon',
Extends: AppDisplay.AppIcon,
// settings are required inside.
_init: function(settings, app, monitorIndex, iconParams) {
// a prefix is required to avoid conflicting with the parent class variable
this._dtdSettings = settings;
this.monitorIndex = monitorIndex;
this._signalsHandler = new Utils.GlobalSignalsHandler();
this._nWindows = 0;
this._remoteEntries = [];
this.parent(app, iconParams);
// Monitor windows-changes instead of app state.
// Keep using the same Id and function callback (that is extended)
if (this._stateChangedId > 0) {
this.app.disconnect(this._stateChangedId);
this._stateChangedId = 0;
}
this._stateChangedId = this.app.connect('windows-changed',
Lang.bind(this,
this.onWindowsChanged));
this._focusAppChangeId = tracker.connect('notify::focus-app',
Lang.bind(this,
this._onFocusAppChanged));
// In Wayland sessions, this signal is needed to track the state of windows dragged
// from one monitor to another. As this is triggered quite often (whenever a new winow
// of any application opened or moved to a different desktop),
// we restrict this signal to the case when 'isolate-monitors' is true,
// and if there are at least 2 monitors.
if (this._dtdSettings.get_boolean('isolate-monitors') &&
Main.layoutManager.monitors.length > 1) {
this._signalsHandler.removeWithLabel('isolate-monitors');
this._signalsHandler.addWithLabel('isolate-monitors', [
global.screen,
'window-entered-monitor',
Lang.bind(this, this._onWindowEntered)
]);
}
this._dots = null;
this._progressOverlayArea = null;
this._progress = 0;
let keys = ['apply-custom-theme',
'custom-theme-running-dots',
'custom-theme-customize-running-dots',
'custom-theme-running-dots-color',
'custom-theme-running-dots-border-color',
'custom-theme-running-dots-border-width',
'unity-backlit-items'];
keys.forEach(function(key) {
this._signalsHandler.add([
this._dtdSettings,
'changed::' + key,
Lang.bind(this, this._toggleAppIndicators)
]);
}, this);
this._toggleAppIndicators();
this._dtdSettings.connect('changed::scroll-action', Lang.bind(this, function() {
this._optionalScrollCycleWindows();
}));
this._optionalScrollCycleWindows();
this._notificationBadge();
this._numberOverlay();
this._previewMenuManager = null;
this._previewMenu = null;
},
_onDestroy: function() {
this.parent();
// This is necessary due to an upstream bug
// https://bugzilla.gnome.org/show_bug.cgi?id=757556
// It can be safely removed once it get solved upstrea.
if (this._menu)
this._menu.close(false);
// Disconect global signals
// stateChangedId is already handled by parent)
if (this._focusAppChangeId > 0) {
tracker.disconnect(this._focusAppChangeId);
this._focusAppChangeId = 0;
}
this._signalsHandler.destroy();
if (this._scrollEventHandler)
this.actor.disconnect(this._scrollEventHandler);
},
_onWindowEntered: function(metaScreen, monitorIndex, metaWin) {
let app = Shell.WindowTracker.get_default().get_window_app(metaWin);
if (app && app.get_id() == this.app.get_id())
this.onWindowsChanged();
},
_optionalScrollCycleWindows: function() {
if (this._scrollEventHandler) {
this.actor.disconnect(this._scrollEventHandler);
this._scrollEventHandler = 0;
}
let isEnabled = this._dtdSettings.get_enum('scroll-action') === scrollAction.CYCLE_WINDOWS;
if (!isEnabled) return;
this._scrollEventHandler = this.actor.connect('scroll-event', Lang.bind(this,
this.onScrollEvent));
},
onScrollEvent: function(actor, event) {
// We only activate windows of running applications, i.e. we never open new windows
// We check if the app is running, and that the # of windows is > 0 in
// case we use workspace isolation,
let appIsRunning = this.app.state == Shell.AppState.RUNNING
&& this.getInterestingWindows().length > 0;
if (!appIsRunning)
return false
if (this._optionalScrollCycleWindowsDeadTimeId > 0)
return false;
else
this._optionalScrollCycleWindowsDeadTimeId = Mainloop.timeout_add(250, Lang.bind(this, function() {
this._optionalScrollCycleWindowsDeadTimeId = 0;
}));
let direction = null;
switch (event.get_scroll_direction()) {
case Clutter.ScrollDirection.UP:
direction = Meta.MotionDirection.UP;
break;
case Clutter.ScrollDirection.DOWN:
direction = Meta.MotionDirection.DOWN;
break;
case Clutter.ScrollDirection.SMOOTH:
let [dx, dy] = event.get_scroll_delta();
if (dy < 0)
direction = Meta.MotionDirection.UP;
else if (dy > 0)
direction = Meta.MotionDirection.DOWN;
break;
}
let focusedApp = tracker.focus_app;
if (!Main.overview._shown) {
let reversed = direction === Meta.MotionDirection.UP;
if (this.app == focusedApp)
this._cycleThroughWindows(reversed);
else {
// Activate the first window
let windows = this.getInterestingWindows();
if (windows.length > 0) {
let w = windows[0];
Main.activateWindow(w);
}
}
}
else
this.app.activate();
return true;
},
onWindowsChanged: function() {
if (this._menu && this._menu.isOpen)
this._menu.update();
this._updateRunningStyle();
this.updateIconGeometry();
},
/**
* Update taraget for minimization animation
*/
updateIconGeometry: function() {
// If (for unknown reason) the actor is not on the stage the reported size
// and position are random values, which might exceeds the integer range
// resulting in an error when assigned to the a rect. This is a more like
// a workaround to prevent flooding the system with errors.
if (this.actor.get_stage() == null)
return;
let rect = new Meta.Rectangle();
[rect.x, rect.y] = this.actor.get_transformed_position();
[rect.width, rect.height] = this.actor.get_transformed_size();
let windows = this.app.get_windows();
if (this._dtdSettings.get_boolean('multi-monitor')){
let monitorIndex = this.monitorIndex;
windows = windows.filter(function(w) {
return w.get_monitor() == monitorIndex;
});
}
windows.forEach(function(w) {
w.set_icon_geometry(rect);
});
},
_toggleAppIndicators: function() {
if (this._dtdSettings.get_boolean('custom-theme-running-dots') || this._dtdSettings.get_boolean('apply-custom-theme'))
this._showDots();
else
this._hideDots();
let applyGlossyBackground = this._dtdSettings.get_boolean('unity-backlit-items') &&
!this._dtdSettings.get_boolean('apply-custom-theme');
if (applyGlossyBackground) {
let path = imports.misc.extensionUtils.getCurrentExtension().path;
let backgroundStyle = 'background-image: url(\'' + path + '/media/glossy.svg\');' +
'background-size: contain;'
this._iconContainer.get_children()[1].set_style(backgroundStyle)
} else {
this._iconContainer.get_children()[1].set_style(null);
}
this._updateRunningStyle();
if (this._dots)
this._dots.queue_repaint()
},
_showDots: function() {
// I use opacity to hide the default dot because the show/hide function
// are used by the parent class.
this._dot.opacity = 0;
// Just update style if dots already exist
if (this._dots) {
this._updateCounterClass();
return;
}
this._dots = new St.DrawingArea({x_expand: true, y_expand: true});
this._dots.connect('repaint', Lang.bind(this, function() {
this._drawCircles(this._dots, Utils.getPosition(this._dtdSettings));
}));
this._iconContainer.add_child(this._dots);
this._updateCounterClass();
},
_hideDots: function() {
this._dot.opacity = 255;
if (this._dots)
this._dots.destroy()
this._dots = null;
},
_updateRunningStyle: function() {
// When using workspace isolation, we need to hide the dots of apps with
// no windows in the current workspace
if (this._dtdSettings.get_boolean('isolate-workspaces') ||
this._dtdSettings.get_boolean('isolate-monitors')) {
if (this.app.state != Shell.AppState.STOPPED
&& this.getInterestingWindows().length != 0)
this._dot.show();
else
this._dot.hide();
}
else
this.parent();
this._onFocusAppChanged();
this._updateCounterClass();
// Enable / Disable the backlight of running apps
if (this.app.state !== Shell.AppState.STOPPED &&
this._dtdSettings.get_boolean('unity-backlit-items') === true &&
this._dtdSettings.get_boolean('apply-custom-theme') === false &&
this.getInterestingWindows().length > 0) {
this._enableBacklight();
// Repaint the dots to make sure they have the correct color
if (this._dots)
this._dots.queue_repaint();
} else {
this._disableBacklight();
}
},
popupMenu: function() {
this._removeMenuTimeout();
this.actor.fake_release();
this._draggable.fakeRelease();
if (!this._menu) {
this._menu = new MyAppIconMenu(this, this._dtdSettings);
this._menu.connect('activate-window', Lang.bind(this, function(menu, window) {
this.activateWindow(window);
}));
this._menu.connect('open-state-changed', Lang.bind(this, function(menu, isPoppedUp) {
if (!isPoppedUp)
this._onMenuPoppedDown();
else {
// Setting the max-height is s useful if part of the menu is
// scrollable so the minimum height is smaller than the natural height.
let monitor_index = Main.layoutManager.findIndexForActor(this.actor);
let workArea = Main.layoutManager.getWorkAreaForMonitor(monitor_index);
let position = Utils.getPosition(this._dtdSettings);
this._isHorizontal = ( position == St.Side.TOP ||
position == St.Side.BOTTOM);
// If horizontal also remove the height of the dash
let additional_margin = this._isHorizontal && !this._dtdSettings.get_boolean('dock-fixed') ? Main.overview._dash.actor.height : 0;
let verticalMargins = this._menu.actor.margin_top + this._menu.actor.margin_bottom;
// Also set a max width to the menu, so long labels (long windows title) get truncated
this._menu.actor.style = ('max-height: ' + Math.round(workArea.height - additional_margin - verticalMargins) + 'px;' +
'max-width: 400px');
}
}));
let id = Main.overview.connect('hiding', Lang.bind(this, function() {
this._menu.close();
}));
this._menu.actor.connect('destroy', function() {
Main.overview.disconnect(id);
});
this._menuManager.addMenu(this._menu);
}
this.emit('menu-state-changed', true);
this.actor.set_hover(true);
this._menu.popup();
this._menuManager.ignoreRelease();
this.emit('sync-tooltip');
return false;
},
_onFocusAppChanged: function() {
// We need to check the number of windows, as the focus might be
// happening on another monitor if using isolation
if (tracker.focus_app == this.app && this.getInterestingWindows().length != 0)
this.actor.add_style_class_name('focused');
else
this.actor.remove_style_class_name('focused');
},
activate: function(button) {
let event = Clutter.get_current_event();
let modifiers = event ? event.get_state() : 0;
let focusedApp = tracker.focus_app;
// Only consider SHIFT and CONTROL as modifiers (exclude SUPER, CAPS-LOCK, etc.)
modifiers = modifiers & (Clutter.ModifierType.SHIFT_MASK | Clutter.ModifierType.CONTROL_MASK);
// We don't change the CTRL-click behaviour: in such case we just chain
// up the parent method and return.
if (modifiers & Clutter.ModifierType.CONTROL_MASK) {
// Keep default behaviour: launch new window
// By calling the parent method I make it compatible
// with other extensions tweaking ctrl + click
this.parent(button);
return;
}
// We check what type of click we have and if the modifier SHIFT is
// being used. We then define what buttonAction should be for this
// event.
let buttonAction = 0;
if (button && button == 2 ) {
if (modifiers & Clutter.ModifierType.SHIFT_MASK)
buttonAction = this._dtdSettings.get_enum('shift-middle-click-action');
else
buttonAction = this._dtdSettings.get_enum('middle-click-action');
}
else if (button && button == 1) {
if (modifiers & Clutter.ModifierType.SHIFT_MASK)
buttonAction = this._dtdSettings.get_enum('shift-click-action');
else
buttonAction = this._dtdSettings.get_enum('click-action');
}
// We check if the app is running, and that the # of windows is > 0 in
// case we use workspace isolation.
let windows = this.getInterestingWindows();
let appIsRunning = this.app.state == Shell.AppState.RUNNING
&& windows.length > 0;
// Some action modes (e.g. MINIMIZE_OR_OVERVIEW) require overview to remain open
// This variable keeps track of this
let shouldHideOverview = true;
// We customize the action only when the application is already running
if (appIsRunning) {
switch (buttonAction) {
case clickAction.MINIMIZE:
// In overview just activate the app, unless the acion is explicitely
// requested with a keyboard modifier
if (!Main.overview._shown || modifiers){
// If we have button=2 or a modifier, allow minimization even if
// the app is not focused
if (this.app == focusedApp || button == 2 || modifiers & Clutter.ModifierType.SHIFT_MASK) {
// minimize all windows on double click and always in the case of primary click without
// additional modifiers
let click_count = 0;
if (Clutter.EventType.CLUTTER_BUTTON_PRESS)
click_count = event.get_click_count();
let all_windows = (button == 1 && ! modifiers) || click_count > 1;
this._minimizeWindow(all_windows);
}
else
this._activateAllWindows();
}
else {
let w = windows[0];
Main.activateWindow(w);
}
break;
case clickAction.MINIMIZE_OR_OVERVIEW:
// When a single window is present, toggle minimization
// If only one windows is present toggle minimization, but only when trigggered with the
// simple click action (no modifiers, no middle click).
if (windows.length == 1 && !modifiers && button == 1) {
let w = windows[0];
if (this.app == focusedApp) {
// Window is raised, minimize it
this._minimizeWindow(w);
} else {
// Window is minimized, raise it
Main.activateWindow(w);
}
// Launch overview when multiple windows are present
// TODO: only show current app windows when gnome shell API will allow it
} else {
shouldHideOverview = false;
Main.overview.toggle();
}
break;
case clickAction.CYCLE_WINDOWS:
if (!Main.overview._shown){
if (this.app == focusedApp)
this._cycleThroughWindows();
else {
// Activate the first window
let w = windows[0];
Main.activateWindow(w);
}
}
else
this.app.activate();
break;
case clickAction.LAUNCH:
this.launchNewWindow();
break;
case clickAction.PREVIEWS:
if (!Main.overview._shown) {
// If only one windows is present just switch to it, but only when trigggered with the
// simple click action (no modifiers, no middle click).
if (windows.length == 1 && !modifiers && button == 1) {
let w = windows[0];
Main.activateWindow(w);
} else
this._windowPreviews();
}
else {
this.app.activate();
}
break;
case clickAction.QUIT:
this.closeAllWindows();
break;
case clickAction.SKIP:
let w = windows[0];
Main.activateWindow(w);
break;
}
}
else {
this.launchNewWindow();
}
// Hide overview except when action mode requires it
if(shouldHideOverview) {
Main.overview.hide();
}
},
shouldShowTooltip: function() {
return this.actor.hover && (!this._menu || !this._menu.isOpen) &&
(!this._previewMenu || !this._previewMenu.isOpen);
},
_windowPreviews: function() {
if (!this._previewMenu) {
this._previewMenuManager = new PopupMenu.PopupMenuManager(this);
this._previewMenu = new WindowPreview.WindowPreviewMenu(this, this._dtdSettings);
this._previewMenuManager.addMenu(this._previewMenu);
this._previewMenu.connect('open-state-changed', Lang.bind(this, function(menu, isPoppedUp) {
if (!isPoppedUp)
this._onMenuPoppedDown();
}));
let id = Main.overview.connect('hiding', Lang.bind(this, function() {
this._previewMenu.close();
}));
this._previewMenu.actor.connect('destroy', function() {
Main.overview.disconnect(id);
});
}
if (this._previewMenu.isOpen)
this._previewMenu.close();
else
this._previewMenu.popup();
return false;
},
// Try to do the right thing when attempting to launch a new window of an app. In
// particular, if the application doens't allow to launch a new window, activate
// the existing window instead.
launchNewWindow: function(p) {
let appInfo = this.app.get_app_info();
let actions = appInfo.list_actions();
if (this.app.can_open_new_window()) {
this.animateLaunch();
// This is used as a workaround for a bug resulting in no new windows being opened
// for certain running applications when calling open_new_window().
//
// https://bugzilla.gnome.org/show_bug.cgi?id=756844
//
// Similar to what done when generating the popupMenu entries, if the application provides
// a "New Window" action, use it instead of directly requesting a new window with
// open_new_window(), which fails for certain application, notably Nautilus.
if (actions.indexOf('new-window') == -1) {
this.app.open_new_window(-1);
}
else {
let i = actions.indexOf('new-window');
if (i !== -1)
this.app.launch_action(actions[i], global.get_current_time(), -1);
}
}
else {
// Try to manually activate the first window. Otherwise, when the app is activated by
// switching to a different workspace, a launch spinning icon is shown and disappers only
// after a timeout.
let windows = this.app.get_windows();
if (windows.length > 0)
Main.activateWindow(windows[0])
else
this.app.activate();
}
},
_updateCounterClass: function() {
let maxN = 4;
this._nWindows = Math.min(this.getInterestingWindows().length, maxN);
for (let i = 1; i <= maxN; i++) {
let className = 'running' + i;
if (i != this._nWindows)
this.actor.remove_style_class_name(className);
else
this.actor.add_style_class_name(className);
}
if (this._dots)
this._dots.queue_repaint();
},
_enableBacklight: function() {
let colorPallete = this._calculateColorPalette();
// Fallback
if (colorPallete === null) {
this._iconContainer.set_style(
'border-radius: 5px;' +
'background-gradient-direction: vertical;' +
'background-gradient-start: #e0e0e0;' +
'background-gradient-end: darkgray;'
);
this._dot.set_style(
'height: 0px;' +
'border: 0px solid white;' +
'background-color: gray;'
);
return;
}
this._iconContainer.set_style(
'border-radius: 5px;' +
'background-gradient-direction: vertical;' +
'background-gradient-start: ' + colorPallete.original + ';' +
'background-gradient-end: ' + colorPallete.darker + ';'
);
this._dot.set_style(
'height: 0px;' +
'border: 0px solid ' + colorPallete.lighter + ';' +
'background-color: ' + colorPallete.darker + ';'
);
},
_disableBacklight: function() {
this._iconContainer.set_style(null);
this._dot.set_style(null);
},
/**
* Try to get the pixel buffer for the current icon, if not fail gracefully
*/
_getIconPixBuf: function() {
let iconTexture = this.app.create_icon_texture(16);
if (themeLoader === null) {
let ifaceSettings = new Gio.Settings({ schema: "org.gnome.desktop.interface" });
themeLoader = new Gtk.IconTheme(),
themeLoader.set_custom_theme(ifaceSettings.get_string('icon-theme')); // Make sure the correct theme is loaded
}
// Unable to load the icon texture, use fallback
if (iconTexture instanceof St.Icon === false) {
return null;
}
iconTexture = iconTexture.get_gicon();
// Unable to load the icon texture, use fallback
if (iconTexture === null) {
return null;
}
if (iconTexture instanceof Gio.FileIcon) {
// Use GdkPixBuf to load the pixel buffer from the provided file path
return GdkPixbuf.Pixbuf.new_from_file(iconTexture.get_file().get_path());
}
// Get the pixel buffer from the icon theme
return themeLoader.load_icon(iconTexture.get_names()[0], DOMINANT_COLOR_ICON_SIZE, 0);
},
/**
* The backlight color choosing algorithm was mostly ported to javascript from the
* Unity7 C++ source of Canonicals:
* http://bazaar.launchpad.net/~unity-team/unity/trunk/view/head:/launcher/LauncherIcon.cpp
* so it more or less works the same way.
*/
_calculateColorPalette: function() {
if (iconCacheMap.get(this.app.get_id())) {
// We already know the answer
return iconCacheMap.get(this.app.get_id());
}
let pixBuf = this._getIconPixBuf();
if (pixBuf == null)
return null;
let pixels = pixBuf.get_pixels(),
offset = 0;
let total = 0,
rTotal = 0,
gTotal = 0,
bTotal = 0;
let resample_y = 1,
resample_x = 1;
// Resampling of large icons
// We resample icons larger than twice the desired size, as the resampling
// to a size s
// DOMINANT_COLOR_ICON_SIZE < s < 2*DOMINANT_COLOR_ICON_SIZE,
// most of the case exactly DOMINANT_COLOR_ICON_SIZE as the icon size is tipycally
// a multiple of it.
let width = pixBuf.get_width();
let height = pixBuf.get_height();
// Resample
if (height >= 2* DOMINANT_COLOR_ICON_SIZE)
resample_y = Math.floor(height/DOMINANT_COLOR_ICON_SIZE);
if (width >= 2* DOMINANT_COLOR_ICON_SIZE)
resample_x = Math.floor(width/DOMINANT_COLOR_ICON_SIZE);
if (resample_x !==1 || resample_y !== 1)
pixels = this._resamplePixels(pixels, resample_x, resample_y);
// computing the limit outside the for (where it would be repeated at each iteration)
// for performance reasons
let limit = pixels.length;
for (let offset = 0; offset < limit; offset+=4) {
let r = pixels[offset],
g = pixels[offset + 1],
b = pixels[offset + 2],
a = pixels[offset + 3];
let saturation = (Math.max(r,g, b) - Math.min(r,g, b));
let relevance = 0.1 * 255 * 255 + 0.9 * a * saturation;
rTotal += r * relevance;
gTotal += g * relevance;
bTotal += b * relevance;
total += relevance;
}
total = total * 255;
let r = rTotal / total,
g = gTotal / total,
b = bTotal / total;
let hsv = Utils.ColorUtils.RGBtoHSV(r * 255, g * 255, b * 255);
if (hsv.s > 0.15)
hsv.s = 0.65;
hsv.v = 0.90;
let rgb = Utils.ColorUtils.HSVtoRGB(hsv.h, hsv.s, hsv.v);
// Cache the result.
let backgroundColor = {
lighter: Utils.ColorUtils.ColorLuminance(rgb.r, rgb.g, rgb.b, 0.2),
original: Utils.ColorUtils.ColorLuminance(rgb.r, rgb.g, rgb.b, 0),
darker: Utils.ColorUtils.ColorLuminance(rgb.r, rgb.g, rgb.b, -0.5)
};
if (iconCacheMap.size >= MAX_CACHED_ITEMS) {
//delete oldest cached values (which are in order of insertions)
let ctr=0;
for (let key of iconCacheMap.keys()) {
if (++ctr > BATCH_SIZE_TO_DELETE)
break;
iconCacheMap.delete(key);
}
}
iconCacheMap.set(this.app.get_id(), backgroundColor);
return backgroundColor;
},
/**
* Downsample large icons before scanning for the backlight color to
* improve performance.
*
* @param pixBuf
* @param pixels
* @param resampleX
* @param resampleY
*
* @return [];
*/
_resamplePixels: function (pixels, resampleX, resampleY) {
let resampledPixels = [];
// computing the limit outside the for (where it would be repeated at each iteration)
// for performance reasons
let limit = pixels.length / (resampleX * resampleY) / 4;
for (let i = 0; i < limit; i++) {
let pixel = i * resampleX * resampleY;
resampledPixels.push(pixels[pixel * 4]);
resampledPixels.push(pixels[pixel * 4 + 1]);
resampledPixels.push(pixels[pixel * 4 + 2]);
resampledPixels.push(pixels[pixel * 4 + 3]);
}
return resampledPixels;
},
_drawCircles: function(area, side) {
let borderColor, borderWidth, bodyColor;
if (!this._dtdSettings.get_boolean('apply-custom-theme')
&& this._dtdSettings.get_boolean('custom-theme-running-dots')
&& this._dtdSettings.get_boolean('custom-theme-customize-running-dots')) {
borderColor = Clutter.color_from_string(this._dtdSettings.get_string('custom-theme-running-dots-border-color'))[1];
borderWidth = this._dtdSettings.get_int('custom-theme-running-dots-border-width');
bodyColor = Clutter.color_from_string(this._dtdSettings.get_string('custom-theme-running-dots-color'))[1];
}
else {
// Re-use the style - background color, and border width and color -
// of the default dot
let themeNode = this._dot.get_theme_node();
borderColor = themeNode.get_border_color(side);
borderWidth = themeNode.get_border_width(side);
bodyColor = themeNode.get_background_color();
}
let [width, height] = area.get_surface_size();
let cr = area.get_context();
// Draw the required numbers of dots
// Define the radius as an arbitrary size, but keep large enough to account
// for the drawing of the border.
let radius = Math.max(width/22, borderWidth/2);
let padding = 0; // distance from the margin
let spacing = radius + borderWidth; // separation between the dots
let n = this._nWindows;
// Lightly adjust the styling in case of unity7 backlit mode
if (this._dtdSettings.get_boolean('unity-backlit-items') === true) {
padding = 1.45;
borderWidth = 2;
}
cr.setLineWidth(borderWidth);
Clutter.cairo_set_source_color(cr, borderColor);
switch (side) {
case St.Side.TOP:
cr.translate((width - (2*n)*radius - (n-1)*spacing)/2, padding);
for (let i = 0; i < n; i++) {
cr.newSubPath();
cr.arc((2*i+1)*radius + i*spacing, radius + borderWidth/2, radius, 0, 2*Math.PI);
}
break;
case St.Side.BOTTOM:
cr.translate((width - (2*n)*radius - (n-1)*spacing)/2, height - padding);
for (let i = 0; i < n; i++) {
cr.newSubPath();
cr.arc((2*i+1)*radius + i*spacing, -radius - borderWidth/2, radius, 0, 2*Math.PI);
}
break;
case St.Side.LEFT:
cr.translate(padding, (height - (2*n)*radius - (n-1)*spacing)/2);
for (let i = 0; i < n; i++) {
cr.newSubPath();
cr.arc(radius + borderWidth/2, (2*i+1)*radius + i*spacing, radius, 0, 2*Math.PI);
}
break;
case St.Side.RIGHT:
cr.translate(width - padding , (height - (2*n)*radius - (n-1)*spacing)/2);
for (let i = 0; i < n; i++) {
cr.newSubPath();
cr.arc(-radius - borderWidth/2, (2*i+1)*radius + i*spacing, radius, 0, 2*Math.PI);
}
break;
}
cr.strokePreserve();
Clutter.cairo_set_source_color(cr, bodyColor);
cr.fill();
cr.$dispose();
},
_notificationBadge: function() {
this._notificationBadgeLabel = new St.Label();
this._notificationBadgeBin = new St.Bin({
child: this._notificationBadgeLabel,
x_align: St.Align.END, y_align: St.Align.START,
x_expand: true, y_expand: true
});
this._notificationBadgeLabel.add_style_class_name('notification-badge');
this._notificationBadgeCount = 0;
this._notificationBadgeBin.hide();
this._iconContainer.add_child(this._notificationBadgeBin);
this._iconContainer.connect('allocation-changed', Lang.bind(this, this.updateNotificationBadge));
},
updateNotificationBadge: function() {
let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
let [minWidth, natWidth] = this._iconContainer.get_preferred_width(-1);
let logicalNatWidth = natWidth / scaleFactor;
let font_size = Math.max(10, Math.round(logicalNatWidth / 5));
let margin_left = Math.round(logicalNatWidth / 4);
this._notificationBadgeLabel.set_style(
'font-size: ' + font_size + 'px;' +
'margin-left: ' + margin_left + 'px;'
);
this._notificationBadgeBin.width = Math.round(logicalNatWidth - margin_left);
this._notificationBadgeLabel.clutter_text.ellipsize = Pango.EllipsizeMode.MIDDLE;
},
_notificationBadgeCountToText: function(count) {
if (count <= 9999) {
return count.toString();
} else if (count < 1e5) {
let thousands = count / 1e3;
return thousands.toFixed(1).toString() + "k";
} else if (count < 1e6) {
let thousands = count / 1e3;
return thousands.toFixed(0).toString() + "k";
} else if (count < 1e8) {