-
Notifications
You must be signed in to change notification settings - Fork 776
/
Copy pathmain.js
1587 lines (1394 loc) · 51.8 KB
/
main.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 -*-
/**
* FILE:main.js
* @short_description: This is the heart of Cinnamon, the mother of everything.
* @placesManager (PlacesManager.PlacesManager): The places manager
* @overview (Overview.Overview): The "scale" overview
* @expo (Expo.Expo): The "expo" overview
* @runDialog (RunDialog.RunDialog): The run dialog
* @lookingGlass (LookingGlass.Melange): The looking glass object
* @wm (WindowManager.WindowManager): The window manager
* @messageTray (MessageTray.MessageTray): The mesesage tray
* @notificationDaemon (NotificationDaemon.NotificationDaemon): The notification daemon
* @windowAttentionHandler (WindowAttentionHandler.WindowAttentionHandler): The window attention handle
* @screenRecorder (ScreenRecorder.ScreenRecorder): The recorder
* @cinnamonDBusService (CinnamonDBus.Cinnamon): The cinnamon dbus object
* @screenshotService (Screenshot.ScreenshotService): Implementation of gnome-shell's screenshot interface.
* @modalCount (int): The number of modals "pushed"
* @modalActorFocusStack (array): Array of pushed modal actors
* @uiGroup (Cinnamon.GenericContainer): The group containing all Cinnamon and
* Muffin actors
*
* @magnifier (Magnifier.Magnifier): The magnifier
* @locatePointer (LocatePointer.LocatePointer): The locate pointer object
* @xdndHandler (XdndHandler.XdndHandler): The X DND handler
* @statusIconDispatcher (StatusIconDispatcher.StatusIconDispatcher): The status icon dispatcher
* @virtualKeyboard (VirtualKeyboard.Keyboard): The keyboard object
* @layoutManager (Layout.LayoutManager): The layout manager.
* @monitorLabeler (MonitorLabeler.MonitorLabeler): Adds labels to each monitor when configuring displays.
* \
* All actors that are part of the Cinnamon UI ar handled by the layout
* manager, which will determine when to show and hide the actors etc.
*
* @panelManager (Panel.PanelManager): The panel manager.
* \
* This is responsible for handling events relating to panels, eg. showing all
* panels.
*
* @themeManager (ThemeManager.ThemeManager): The theme manager
* @soundManager (SoundManager.SoundManager): The sound manager
* @settingsManager (Settings.SettingsManager): The manager of the xlet Settings API
*
* @backgroundManager (BackgroundManager.BackgroundManager): The background
* manager.
* \
* This listens to changes in the GNOME background settings and mirrors them to
* the Cinnamon settings, since many applications have a "Set background"
* button that modifies the GNOME background settings.
*
* @slideshowManager (SlideshowManager.SlideshowManager): The slideshow manager.
* \
* This is responsible for managing the background slideshow, since the
* background "slideshow" is created by cinnamon changing the active background
* gsetting every x minutes.
*
* @keybindingManager (KeybindingManager.KeybindingManager): The keybinding manager
* @systrayManager (Systray.SystrayManager): The systray manager
* @gesturesManager (GesturesManager.GesturesManager): Gesture support from ToucheEgg.
*
* @osdWindow (OsdWindow.OsdWindow): Osd window that pops up when you use media
* keys.
* @tracker (Cinnamon.WindowTracker): The window tracker
* @workspace_names (array): Names of workspace
* @deskletContainer (DeskletManager.DeskletContainer): The desklet container.
* \
* This is a container that contains all the desklets as childs. Its actor is
* put between @global.bottom_window_group and @global.uiGroup.
* @software_rendering (boolean): Whether software rendering is used
* @animations_enabled (boolean): Whether any effects or animations should be used.
* @popup_rendering_actor (Clutter.Actor): The popup actor that is in the process of rendering
* @xlet_startup_error (boolean): Whether there was at least one xlet that did
* not manage to load
*
* The main file is responsible for launching Cinnamon as well as creating its
* components. The C part of cinnamon calls the @start() function, which then
* initializes all of cinnamon. Most components of Cinnamon can be accessed
* through main.
*/
const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const Gtk = imports.gi.Gtk;
const Mainloop = imports.mainloop;
const Meta = imports.gi.Meta;
const Cinnamon = imports.gi.Cinnamon;
const St = imports.gi.St;
const GObject = imports.gi.GObject;
const XApp = imports.gi.XApp;
const PointerTracker = imports.misc.pointerTracker;
const AudioDeviceSelection = imports.ui.audioDeviceSelection;
const SoundManager = imports.ui.soundManager;
const BackgroundManager = imports.ui.backgroundManager;
const Config = imports.misc.config;
const SlideshowManager = imports.ui.slideshowManager;
var AppletManager = imports.ui.appletManager;
const SearchProviderManager = imports.ui.searchProviderManager;
const DeskletManager = imports.ui.deskletManager;
const ExtensionSystem = imports.ui.extensionSystem;
const VirtualKeyboard = imports.ui.virtualKeyboard;
const MessageTray = imports.ui.messageTray;
const OsdWindow = imports.ui.osdWindow;
const Overview = imports.ui.overview;
const Expo = imports.ui.expo;
const Panel = imports.ui.panel;
const PlacesManager = imports.ui.placesManager;
const PolkitAuthenticationAgent = imports.ui.polkitAuthenticationAgent;
const KeyringPrompt = imports.ui.keyringPrompt;
const RunDialog = imports.ui.runDialog;
const Layout = imports.ui.layout;
const LookingGlass = imports.ui.lookingGlass;
const NetworkAgent = imports.ui.networkAgent;
const NotificationDaemon = imports.ui.notificationDaemon;
const WindowAttentionHandler = imports.ui.windowAttentionHandler;
const CinnamonDBus = imports.ui.cinnamonDBus;
const Screenshot = imports.ui.screenshot;
const ThemeManager = imports.ui.themeManager;
const Magnifier = imports.ui.magnifier;
const LocatePointer = imports.ui.locatePointer;
const XdndHandler = imports.ui.xdndHandler;
const StatusIconDispatcher = imports.ui.statusIconDispatcher;
const Util = imports.misc.util;
const Keybindings = imports.ui.keybindings;
const Settings = imports.ui.settings;
const Systray = imports.ui.systray;
const Accessibility = imports.ui.accessibility;
const ModalDialog = imports.ui.modalDialog;
const InputMethod = imports.misc.inputMethod;
const ScreenRecorder = imports.ui.screenRecorder;
const {GesturesManager} = imports.ui.gestures.gesturesManager;
const {MonitorLabeler} = imports.ui.monitorLabeler;
const {CinnamonPortalHandler} = imports.misc.portalHandlers;
var LAYOUT_TRADITIONAL = "traditional";
var LAYOUT_FLIPPED = "flipped";
var LAYOUT_CLASSIC = "classic";
var DEFAULT_BACKGROUND_COLOR = Clutter.Color.from_pixel(0x000000ff);
var panel = null;
var soundManager = null;
var backgroundManager = null;
var slideshowManager = null;
var placesManager = null;
var panelManager = null;
var osdWindowManager = null;
var overview = null;
var expo = null;
var runDialog = null;
var lookingGlass = null;
var lookingGlassUpdateID = 0;
var wm = null;
var a11yHandler = null;
var messageTray = null;
var notificationDaemon = null;
var windowAttentionHandler = null;
var screenRecorder = null;
var cinnamonAudioSelectionDBusService = null;
var cinnamonDBusService = null;
var screenshotService = null;
var modalCount = 0;
var modalActorFocusStack = [];
var uiGroup = null;
var magnifier = null;
var locatePointer = null;
var xdndHandler = null;
var statusIconDispatcher = null;
var virtualKeyboard = null;
var layoutManager = null;
var networkAgent = null;
var monitorLabeler = null;
var themeManager = null;
var keybindingManager = null;
var _errorLogStack = [];
var _startDate;
var _defaultCssStylesheet = null;
var _cssStylesheet = null;
var dynamicWorkspaces = null;
var tracker = null;
var settingsManager = null;
var systrayManager = null;
var wmSettings = null;
var pointerSwitcher = null;
var gesturesManager = null;
var workspace_names = [];
var applet_side = St.Side.TOP; // Kept to maintain compatibility. Doesn't seem to be used anywhere
var deskletContainer = null;
var software_rendering = false;
var animations_enabled = false;
var popup_rendering_actor = null;
var xlet_startup_error = false;
var gpuOffloadHelper = null;
var gpu_offload_supported = false;
var RunState = {
INIT : 0,
STARTUP : 1,
RUNNING : 2
}
var runState = RunState.INIT;
// Override Gettext localization
const Gettext = imports.gettext;
Gettext.bindtextdomain('cinnamon', '/usr/share/locale');
Gettext.textdomain('cinnamon');
const _ = Gettext.gettext;
function setRunState(state) {
let oldState = runState;
if (state != oldState) {
runState = state;
cinnamonDBusService.EmitRunStateChanged();
}
}
function _addXletDirectoriesToSearchPath() {
imports.searchPath.unshift(global.datadir);
imports.searchPath.unshift(global.userdatadir);
// Including the system data directory also includes unnecessary system utilities,
// so we are making sure they are removed.
let types = ['applets', 'desklets', 'extensions', 'search_providers'];
let importsCache = {};
for (let i = 0; i < types.length; i++) {
// Cache our existing xlet GJS importer objects
importsCache[types[i]] = imports[types[i]];
}
// Remove the two paths we added to the beginning of the array.
imports.searchPath.splice(0, 2);
for (let i = 0; i < types.length; i++) {
// Re-add cached xlet objects
imports[types[i]] = importsCache[types[i]];
importsCache[types[i]] = undefined;
}
}
function _initUserSession() {
global.workspace_manager.override_workspace_layout(Meta.DisplayCorner.TOPLEFT, false, 1, -1);
systrayManager = new Systray.SystrayManager();
Meta.keybindings_set_custom_handler('panel-run-dialog', function() {
getRunDialog().open();
});
}
function do_shutdown_sequence() {
panelManager.panels.forEach(function (panel) {
panel.actor.hide();
});
}
function _reparentActor(actor, newParent) {
let parent = actor.get_parent();
if (parent)
parent.remove_actor(actor);
if(newParent)
newParent.add_actor(actor);
}
/**
* start:
*
* Starts cinnamon. Should not be called in JavaScript code
*/
function start() {
global.reparentActor = _reparentActor;
// Monkey patch utility functions into the global proxy;
// This is easier and faster than indirecting down into global
// if we want to call back up into JS.
global.logTrace = _logTrace;
global.logWarning = _logWarning;
global.logError = _logError;
global.log = _logInfo;
let cinnamonStartTime = new Date().getTime();
log(`About to start Cinnamon (${Meta.is_wayland_compositor() ? "Wayland" : "X11"} backend)`);
let backend = Meta.get_backend();
// Only cinnamon2d launcher will set CINNAMON_2D - this is deliberate by the user.
let cinnamon_2d = GLib.getenv("CINNAMON_2D") === true;
let live = false;
if (!backend.is_rendering_hardware_accelerated() || cinnamon_2d) {
global.logError("Cinnamon Software Rendering mode enabled");
software_rendering = true;
// We only warn if software_rendering is not of the user's volition.
if (!cinnamon_2d && GLib.file_test("/proc/cmdline", GLib.FileTest.EXISTS)) {
let content = Cinnamon.get_file_contents_utf8_sync("/proc/cmdline");
if (content.match("boot=casper") || content.match("boot=live")) {
// If we're in a live session, pretend we're using hardware rendering,
// so all animations end up being enabled.
software_rendering = false;
live = true;
}
}
}
// Chain up async errors reported from C
global.connect('notify-error', function (global, msg, detail) { notifyError(msg, detail); });
Gio.DesktopAppInfo.set_desktop_env('X-Cinnamon');
Clutter.get_default_backend().set_input_method(new InputMethod.InputMethod());
new CinnamonPortalHandler();
cinnamonAudioSelectionDBusService = new AudioDeviceSelection.AudioDeviceSelectionDBus();
cinnamonDBusService = new CinnamonDBus.CinnamonDBus();
setRunState(RunState.STARTUP);
screenshotService = new Screenshot.ScreenshotService();
// Ensure CinnamonWindowTracker and CinnamonAppUsage are initialized; this will
// also initialize CinnamonAppSystem first. CinnamonAppSystem
// needs to load all the .desktop files, and CinnamonWindowTracker
// will use those to associate with windows. Right now
// the Monitor doesn't listen for installed app changes
// and recalculate application associations, so to avoid
// races for now we initialize it here. It's better to
// be predictable anyways.
tracker = Cinnamon.WindowTracker.get_default();
let startTime = new Date().getTime();
Cinnamon.AppSystem.get_default();
global.log('Cinnamon.AppSystem.get_default() started in %d ms'.format(new Date().getTime() - startTime));
// The stage is always covered so Clutter doesn't need to clear it; however
// the color is used as the default contents for the Muffin root background
// actor so set it anyways.
global.stage.background_color = DEFAULT_BACKGROUND_COLOR;
global.stage.no_clear_hint = true;
Gtk.IconTheme.get_default().append_search_path("/usr/share/cinnamon/icons/");
_defaultCssStylesheet = global.datadir + '/theme/cinnamon.css';
soundManager = new SoundManager.SoundManager();
/* note: This call will initialize St.TextureCache */
themeManager = new ThemeManager.ThemeManager();
settingsManager = new Settings.SettingsManager();
backgroundManager = new BackgroundManager.BackgroundManager();
backgroundManager.hideBackground();
slideshowManager = new SlideshowManager.SlideshowManager();
keybindingManager = new Keybindings.KeybindingManager();
deskletContainer = new DeskletManager.DeskletContainer();
gesturesManager = new GesturesManager();
uiGroup = new Layout.UiActor({ name: 'uiGroup' });
uiGroup.set_flags(Clutter.ActorFlags.NO_LAYOUT);
global.reparentActor(global.window_group, uiGroup);
global.reparentActor(global.overlay_group, uiGroup);
let stage_bg = new Clutter.Actor();
let constraint = new Clutter.BindConstraint({ source: global.stage, coordinate: Clutter.BindCoordinate.ALL, offset: 0 })
stage_bg.add_constraint(constraint);
stage_bg.set_background_color(new Clutter.Color({red: 0, green: 0, blue: 0, alpha: 255}));
stage_bg.set_size(global.screen_width, global.screen_height);
global.stage.add_actor(stage_bg);
stage_bg.add_actor(uiGroup);
global.reparentActor(global.top_window_group, global.stage);
global.menuStackLength = 0;
layoutManager = new Layout.LayoutManager();
Panel.checkPanelUpgrade();
panelManager = new Panel.PanelManager();
let startupAnimationEnabled = global.settings.get_boolean("startup-animation");
let do_startup_animation = !global.session_running &&
startupAnimationEnabled &&
!software_rendering;
if (do_startup_animation) {
backgroundManager.showBackground();
layoutManager._prepareStartupAnimation();
}
let pointerTracker = new PointerTracker.PointerTracker();
pointerTracker.setPosition(layoutManager.primaryMonitor.x + layoutManager.primaryMonitor.width/2,
layoutManager.primaryMonitor.y + layoutManager.primaryMonitor.height/2);
pointerSwitcher = new PointerTracker.PointerSwitcher();
if (Meta.is_wayland_compositor()) {
monitorLabeler = new MonitorLabeler();
} else {
monitorLabeler = null;
}
xdndHandler = new XdndHandler.XdndHandler();
osdWindowManager = new OsdWindow.OsdWindowManager();
// This overview object is just a stub for non-user sessions
overview = new Overview.Overview();
expo = new Expo.Expo();
statusIconDispatcher = new StatusIconDispatcher.StatusIconDispatcher();
layoutManager._updateBoxes();
wm = new imports.ui.windowManager.WindowManager();
messageTray = new MessageTray.MessageTray();
virtualKeyboard = new VirtualKeyboard.Keyboard();
notificationDaemon = new NotificationDaemon.NotificationDaemon();
windowAttentionHandler = new WindowAttentionHandler.WindowAttentionHandler();
placesManager = new PlacesManager.PlacesManager();
if (Config.HAVE_NETWORKMANAGER)
networkAgent = new NetworkAgent.NetworkAgent();
magnifier = new Magnifier.Magnifier();
locatePointer = new LocatePointer.locatePointer();
layoutManager.init();
virtualKeyboard.init();
overview.init();
expo.init();
_addXletDirectoriesToSearchPath();
_initUserSession();
screenRecorder = new ScreenRecorder.ScreenRecorder();
if (Meta.is_wayland_compositor()) {
PolkitAuthenticationAgent.init();
}
KeyringPrompt.init();
_startDate = new Date();
global.display.connect('restart', () => {
global.real_restart();
return true;
});
global.stage.connect('captured-event', _stageEventHandler);
global.log('loaded at ' + _startDate);
log('Cinnamon started at ' + _startDate);
wmSettings = new Gio.Settings({schema_id: "org.cinnamon.desktop.wm.preferences"})
workspace_names = wmSettings.get_strv("workspace-names");
wmSettings.connect("changed::workspace-names", function (settings, pspec) {
workspace_names = wmSettings.get_strv("workspace-names");
});
global.display.connect('gl-video-memory-purged', loadTheme);
gpuOffloadHelper = XApp.GpuOffloadHelper.get();
gpuOffloadHelper.connect("ready", (helper, success) => {
gpu_offload_supported = success && gpuOffloadHelper.is_offload_supported();
global.log(`GPU offload supported: ${gpu_offload_supported}`);
});
// We're ready for the session manager to move to the next phase
GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
Meta.register_with_session();
return GLib.SOURCE_REMOVE;
});
Promise.all([
AppletManager.init(),
ExtensionSystem.init(),
DeskletManager.init(),
SearchProviderManager.init()
]).then(function() {
createLookingGlass();
a11yHandler = new Accessibility.A11yHandler();
// We only warn if software_rendering is not of the user's volition.
if (software_rendering && !cinnamon_2d && !live) {
notifyCinnamon2d();
}
if (xlet_startup_error)
Mainloop.timeout_add_seconds(3, notifyXletStartupError);
let sound_settings = new Gio.Settings( {schema_id: "org.cinnamon.sounds"} );
let do_login_sound = sound_settings.get_boolean("login-enabled");
// We're mostly prepared for the startup animation
// now, but since a lot is going on asynchronously
// during startup, let's defer the startup animation
// until the event loop is uncontended and idle.
// This helps to prevent us from running the animation
// when the system is bogged down
if (do_startup_animation) {
let id = GLib.idle_add(GLib.PRIORITY_LOW, () => {
layoutManager._doStartupAnimation();
return GLib.SOURCE_REMOVE;
});
} else {
backgroundManager.showBackground();
setRunState(RunState.RUNNING);
}
if (do_login_sound && !global.session_running)
soundManager.play('login');
// Disable panel edit mode when Cinnamon starts
if (global.settings.get_boolean("panel-edit-mode")) {
global.settings.set_boolean("panel-edit-mode", false);
}
global.connect('shutdown', do_shutdown_sequence);
global.log('Cinnamon took %d ms to start'.format(new Date().getTime() - cinnamonStartTime));
});
}
function updateAnimationsEnabled() {
animations_enabled = !(software_rendering) && global.settings.get_boolean("desktop-effects-workspace");
cinnamonDBusService.notifyAnimationsEnabled();
}
function notifyCinnamon2d() {
let icon = new St.Icon({ icon_name: 'driver-manager',
icon_type: St.IconType.FULLCOLOR,
icon_size: 36 });
let notification =
criticalNotify(_("Check your video drivers"),
_("Your system is currently running without video hardware acceleration.") +
"\n\n" +
_("You may experience poor performance and high CPU usage."),
icon);
if (GLib.file_test("/usr/bin/cinnamon-driver-manager", GLib.FileTest.EXISTS)) {
notification.addButton("driver-manager", _("Launch Driver Manager"));
notification.connect("action-invoked", this.launchDriverManager);
}
}
function notifyXletStartupError() {
let icon = new St.Icon({ icon_name: 'dialog-warning',
icon_type: St.IconType.FULLCOLOR,
icon_size: 36 });
warningNotify(_("Problems during Cinnamon startup"),
_("Cinnamon started successfully, but one or more applets, desklets or extensions failed to load.\n\n") +
_("Check your system log and the Cinnamon LookingGlass log for any issues. ") +
_("You can disable the offending extension(s) in Cinnamon Settings to prevent this message from recurring. ") +
_("Please contact the developer."), icon);
}
/* Provided by panelManager now, but kept here for xlet compatibility */
function enablePanels() {
panelManager.enablePanels();
}
function disablePanels() {
panelManager.disablePanels();
}
function getPanels() {
return panelManager.getPanels();
}
let _workspaces = [];
let _checkWorkspacesId = 0;
/*
* When the last window closed on a workspace is a dialog or splash
* screen, we assume that it might be an initial window shown before
* the main window of an application, and give the app a grace period
* where it can map another window before we remove the workspace.
*/
const LAST_WINDOW_GRACE_TIME = 1000;
function _fillWorkspaceNames(index) {
// ensure that we have workspace names up to index
for (let i = index - workspace_names.length; i > 0; --i) {
workspace_names.push('');
}
}
function _shouldTrimWorkspace(i) {
return i >= 0 && (i >= global.workspace_manager.n_workspaces || !workspace_names[i].length);
}
function _trimWorkspaceNames() {
// trim empty or out-of-bounds names from the end.
let i = workspace_names.length - 1;
while (_shouldTrimWorkspace(i)) {
workspace_names.pop();
i--;
}
}
function _makeDefaultWorkspaceName(index) {
return _("Workspace") + " " + (index + 1).toString();
}
/**
* setWorkspaceName:
* @index (int): index of workspace
* @name (string): name of workspace
*
* Sets the name of the workspace @index to @name
*/
function setWorkspaceName(index, name) {
name.trim();
if (name != getWorkspaceName(index)) {
_fillWorkspaceNames(index);
workspace_names[index] = (name == _makeDefaultWorkspaceName(index) ?
"" :
name);
_trimWorkspaceNames();
wmSettings.set_strv("workspace-names", workspace_names);
}
}
/**
* getWorkspaceName:
* @index (int): index of workspace
*
* Retrieves the name of the workspace @index
*
* Returns (string): name of workspace
*/
function getWorkspaceName(index) {
let wsName = index < workspace_names.length ?
workspace_names[index] :
"";
wsName.trim();
return wsName.length > 0 ?
wsName :
_makeDefaultWorkspaceName(index);
}
/**
* hasDefaultWorkspaceName:
* @index (int): index of workspace
*
* Whether the workspace uses the default name
*
* Returns (boolean): whether the workspace uses the default name
*/
function hasDefaultWorkspaceName(index) {
return getWorkspaceName(index) == _makeDefaultWorkspaceName(index);
}
function _addWorkspace() {
global.workspace_manager.append_new_workspace(false, global.get_current_time());
return true;
}
function _removeWorkspace(workspace) {
if (global.workspace_manager.n_workspaces == 1)
return false;
let index = workspace.index();
if (index < workspace_names.length) {
workspace_names.splice (index, 1);
}
_trimWorkspaceNames();
wmSettings.set_strv("workspace-names", workspace_names);
global.workspace_manager.remove_workspace(workspace, global.get_current_time());
return true;
}
/**
* moveWindowToNewWorkspace:
* @metaWindow (Meta.Window): the window to be moved
* @switchToNewWorkspace (boolean): whether or not to switch to the
* new created workspace
*
* Moves the window to a new workspace.
*
* If @switchToNewWorkspace is true, it will switch to the new workspace
* after moving the window
*/
function moveWindowToNewWorkspace(metaWindow, switchToNewWorkspace) {
if (switchToNewWorkspace) {
let targetCount = global.workspace_manager.n_workspaces + 1;
let nnwId = global.workspace_manager.connect('notify::n-workspaces', function() {
global.workspace_manager.disconnect(nnwId);
if (global.workspace_manager.n_workspaces === targetCount) {
let newWs = global.workspace_manager.get_workspace_by_index(global.workspace_manager.n_workspaces - 1);
newWs.activate(global.get_current_time());
}
});
}
metaWindow.change_workspace_by_index(global.workspace_manager.n_workspaces, true, global.get_current_time());
}
/**
* getThemeStylesheet:
*
* Get the theme CSS file that Cinnamon will load
*
* Returns (string): A file path that contains the theme CSS,
* null if using the default
*/
function getThemeStylesheet()
{
return _cssStylesheet;
}
/**
* setThemeStylesheet:
* @cssStylesheet (string): A file path that contains the theme CSS,
* set it to null to use the default
*
* Set the theme CSS file that Cinnamon will load
*/
function setThemeStylesheet(cssStylesheet)
{
_cssStylesheet = cssStylesheet;
}
/**
* loadTheme:
*
* Reloads the theme CSS file
*/
function loadTheme() {
let themeContext = St.ThemeContext.get_for_stage (global.stage);
let theme = new St.Theme ({ fallback_stylesheet: _defaultCssStylesheet });
let stylesheetLoaded = false;
if (_cssStylesheet != null) {
stylesheetLoaded = theme.load_stylesheet(_cssStylesheet);
}
if (!stylesheetLoaded) {
theme.load_stylesheet(_defaultCssStylesheet);
if (_cssStylesheet != null) {
global.logError("There was some problem parsing the theme: " + _cssStylesheet + ". Falling back to the default theme.");
}
}
themeContext.set_theme (theme);
}
/**
* notify:
* @msg (string): A message
* @details (string): Additional information to be
*
* Sends a notification
*/
function notify(msg, details) {
let source = new MessageTray.SystemNotificationSource();
messageTray.add(source);
let notification = new MessageTray.Notification(source, msg, details);
notification.setTransient(true);
source.notify(notification);
}
/**
* criticalNotify:
* @msg: A critical message
* @details: Additional information
*/
function criticalNotify(msg, details, icon) {
let source = new MessageTray.SystemNotificationSource();
messageTray.add(source);
let notification = new MessageTray.Notification(source, msg, details, { icon: icon });
notification.setTransient(false);
notification.setUrgency(MessageTray.Urgency.CRITICAL);
source.notify(notification);
return notification;
}
function launchDriverManager() {
Util.spawnCommandLineAsync("cinnamon-driver-manager", null, null);
}
/**
* warningNotify:
* @msg: A warning message
* @details: Additional information
*/
function warningNotify(msg, details, icon) {
let source = new MessageTray.SystemNotificationSource();
messageTray.add(source);
let notification = new MessageTray.Notification(source, msg, details, { icon: icon });
notification.setTransient(false);
notification.setUrgency(MessageTray.Urgency.HIGH);
source.notify(notification);
}
/**
* notifyError:
* @msg (string): An error message
* @details (string): Additional information
*
* See cinnamon_global_notify_problem().
*/
function notifyError(msg, details) {
// Also print to stderr so it's logged somewhere
if (details)
log('error: ' + msg + ': ' + details);
else
log('error: ' + msg);
notify(msg, details);
}
/**
* formatLogArgument:
* @arg (any): A single argument.
* @recursion (int): Keeps track of the number of recursions.
* @depth (int): Controls how deeply to inspect object structures.
*
* Used by _log to handle each argument type and its formatting.
*/
function formatLogArgument(arg = '', recursion = 0, depth = 6) {
// Make sure falsey values are clearly indicated.
if (arg === null) {
arg = 'null';
} else if (arg === undefined) {
arg = 'undefined';
// Ensure strings are distinguishable.
} else if (typeof arg === 'string' && recursion > 0) {
arg = '\'' + arg + '\'';
}
// Check if we reached the depth threshold
if (recursion + 1 > depth) {
try {
arg = JSON.stringify(arg);
} catch (e) {
arg = arg.toString();
}
return arg;
}
let isGObject = arg instanceof GObject.Object;
let space = '';
for (let i = 0; i < recursion + 1; i++) {
space += ' ';
}
if (typeof arg === 'object') {
let isArray = Array.isArray(arg);
let brackets = isArray ? ['[', ']'] : ['{', '}'];
if (isGObject) {
arg = Util.getGObjectPropertyValues(arg);
if (Object.keys(arg).length === 0) {
return arg.toString();
}
}
let array = isArray ? arg : Object.keys(arg);
// Add beginning bracket with indentation
let string = brackets[0] + (recursion + 1 > depth ? '' : '\n');
for (let j = 0, len = array.length; j < len; j++) {
if (isArray) {
string += space + formatLogArgument(arg[j], recursion + 1, depth) + ',\n';
} else {
string += space + array[j] + ': ' + formatLogArgument(arg[array[j]], recursion + 1, depth) + ',\n';
}
}
// Remove one level of indentation and add the closing bracket.
space = space.substr(4, space.length);
arg = string + space + brackets[1];
// Functions, numbers, etc.
} else if (typeof arg === 'function') {
let array = arg.toString().split('\n');
for (let i = 0; i < array.length; i++) {
if (i === 0) continue;
array[i] = space + array[i];
}
arg = array.join('\n');
} else if (typeof arg !== 'string' || isGObject) {
arg = arg.toString();
}
return arg;
}
/**
* _log:
* @category (string): string message type ('info', 'error')
* @msg (string): A message string
* @...: Any further arguments are converted into JSON notation,
* and appended to the log message, separated by spaces.
*
* Log a message into the LookingGlass error
* stream. This is primarily intended for use by the
* extension system as well as debugging.
*/
function _log(category = 'info', msg = '') {
// Convert arguments into an array so it can be iterated.
let args = Array.prototype.slice.call(arguments);
// Remove category from the list of loggable arguments
args.shift();
let text = '';
for (let i = 0, len = args.length; i < len; i++) {
args[i] = formatLogArgument(args[i]);
}
if (args.length === 2) {
text = args[0] + ': ' + args[1];
} else {
text = args.join(' ');
}
let out = {
timestamp: new Date().getTime().toString(),
category: category,
message: text
};
_errorLogStack.push(out);
// If the melange window is open/exists, excessive dbus traffic caused by gesture debug
// logging can leave the desktop unstable. We end up with lots of:
//
// Attempting to call back into JSAPI during the sweeping phase of GC...
//
// This is a hack, and how we handle logging and melange probably needs looked at.
if (lookingGlass && !gesturesManager.gesture_active()) {
if (lookingGlassUpdateID > 0) {
GLib.source_remove (lookingGlassUpdateID);
}
lookingGlassUpdateID = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => {
lookingGlass.emitLogUpdate();
lookingGlassUpdateID = 0;
});
}
log(`[LookingGlass/${category}] ${text}`);
}
/**
* isError:
* @obj (Object): the object to be tested
*
* Tests whether @obj is an error object
*
* Returns (boolean): whether @obj is an error object
*/
function isError(obj) {
if (obj == undefined) return false;
let isErr = false;
if (typeof(obj) == 'object' && 'message' in obj && 'stack' in obj) {
isErr = true;
} else if (obj instanceof GLib.Error) {
// Make existing logging functionality work as expected when passed
// a GLib.Error which doesn't normally have a stack trace attached.
let stack = new Error().stack;
// This is reached the first time isError is called by a _log function,
// so strip off this function call and the _log function that called us.
let strPos = stack.indexOf('\n', stack.indexOf('\n') + 1) + 1;
stack = stack.substr(strPos);
obj.stack = stack;
isErr = true;
}
return isErr;
}
/**
* _LogTraceFormatted:
* @stack (string): the stack trace
*
* Prints the stack trace to the LookingGlass
* error stream in a predefined format
*/
function _LogTraceFormatted(stack) {
_log('trace', '\n<----------------\n' + stack + '---------------->');
}
/**
* _logTrace:
* @msg (Error): An error object
*
* Prints a stack trace of the given object.
*
* If msg is an error, its stack-trace will be
* printed. Otherwise, a stack-trace of the call
* will be generated
*
* If you want to print the message of an Error
* as well, use the other log functions instead.
*/
function _logTrace(msg) {
if(isError(msg)) {
_LogTraceFormatted(msg.stack);
} else {
try {
throw new Error();