This repository has been archived by the owner on Mar 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17.4k
/
atom-environment.js
1439 lines (1221 loc) · 48.5 KB
/
atom-environment.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
const crypto = require('crypto')
const path = require('path')
const {ipcRenderer} = require('electron')
const _ = require('underscore-plus')
const {deprecate} = require('grim')
const {CompositeDisposable, Disposable, Emitter} = require('event-kit')
const fs = require('fs-plus')
const {mapSourcePosition} = require('@atom/source-map-support')
const WindowEventHandler = require('./window-event-handler')
const StateStore = require('./state-store')
const registerDefaultCommands = require('./register-default-commands')
const {updateProcessEnv} = require('./update-process-env')
const ConfigSchema = require('./config-schema')
const DeserializerManager = require('./deserializer-manager')
const ViewRegistry = require('./view-registry')
const NotificationManager = require('./notification-manager')
const Config = require('./config')
const KeymapManager = require('./keymap-extensions')
const TooltipManager = require('./tooltip-manager')
const CommandRegistry = require('./command-registry')
const URIHandlerRegistry = require('./uri-handler-registry')
const GrammarRegistry = require('./grammar-registry')
const {HistoryManager} = require('./history-manager')
const ReopenProjectMenuManager = require('./reopen-project-menu-manager')
const StyleManager = require('./style-manager')
const PackageManager = require('./package-manager')
const ThemeManager = require('./theme-manager')
const MenuManager = require('./menu-manager')
const ContextMenuManager = require('./context-menu-manager')
const CommandInstaller = require('./command-installer')
const CoreURIHandlers = require('./core-uri-handlers')
const ProtocolHandlerInstaller = require('./protocol-handler-installer')
const Project = require('./project')
const TitleBar = require('./title-bar')
const Workspace = require('./workspace')
const PaneContainer = require('./pane-container')
const PaneAxis = require('./pane-axis')
const Pane = require('./pane')
const Dock = require('./dock')
const TextEditor = require('./text-editor')
const TextBuffer = require('text-buffer')
const TextEditorRegistry = require('./text-editor-registry')
const AutoUpdateManager = require('./auto-update-manager')
let nextId = 0
// Essential: Atom global for dealing with packages, themes, menus, and the window.
//
// An instance of this class is always available as the `atom` global.
class AtomEnvironment {
/*
Section: Properties
*/
constructor (params = {}) {
this.id = (params.id != null) ? params.id : nextId++
// Public: A {Clipboard} instance
this.clipboard = params.clipboard
this.updateProcessEnv = params.updateProcessEnv || updateProcessEnv
this.enablePersistence = params.enablePersistence
this.applicationDelegate = params.applicationDelegate
this.nextProxyRequestId = 0
this.unloaded = false
this.loadTime = null
this.emitter = new Emitter()
this.disposables = new CompositeDisposable()
this.pathsWithWaitSessions = new Set()
// Public: A {DeserializerManager} instance
this.deserializers = new DeserializerManager(this)
this.deserializeTimings = {}
// Public: A {ViewRegistry} instance
this.views = new ViewRegistry(this)
// Public: A {NotificationManager} instance
this.notifications = new NotificationManager()
this.stateStore = new StateStore('AtomEnvironments', 1)
// Public: A {Config} instance
this.config = new Config({
saveCallback: settings => {
if (this.enablePersistence) {
this.applicationDelegate.setUserSettings(settings, this.config.getUserConfigPath())
}
}
})
this.config.setSchema(null, {type: 'object', properties: _.clone(ConfigSchema)})
// Public: A {KeymapManager} instance
this.keymaps = new KeymapManager({notificationManager: this.notifications})
// Public: A {TooltipManager} instance
this.tooltips = new TooltipManager({keymapManager: this.keymaps, viewRegistry: this.views})
// Public: A {CommandRegistry} instance
this.commands = new CommandRegistry()
this.uriHandlerRegistry = new URIHandlerRegistry()
// Public: A {GrammarRegistry} instance
this.grammars = new GrammarRegistry({config: this.config})
// Public: A {StyleManager} instance
this.styles = new StyleManager()
// Public: A {PackageManager} instance
this.packages = new PackageManager({
config: this.config,
styleManager: this.styles,
commandRegistry: this.commands,
keymapManager: this.keymaps,
notificationManager: this.notifications,
grammarRegistry: this.grammars,
deserializerManager: this.deserializers,
viewRegistry: this.views,
uriHandlerRegistry: this.uriHandlerRegistry
})
// Public: A {ThemeManager} instance
this.themes = new ThemeManager({
packageManager: this.packages,
config: this.config,
styleManager: this.styles,
notificationManager: this.notifications,
viewRegistry: this.views
})
// Public: A {MenuManager} instance
this.menu = new MenuManager({keymapManager: this.keymaps, packageManager: this.packages})
// Public: A {ContextMenuManager} instance
this.contextMenu = new ContextMenuManager({keymapManager: this.keymaps})
this.packages.setMenuManager(this.menu)
this.packages.setContextMenuManager(this.contextMenu)
this.packages.setThemeManager(this.themes)
// Public: A {Project} instance
this.project = new Project({
notificationManager: this.notifications,
packageManager: this.packages,
grammarRegistry: this.grammars,
config: this.config,
applicationDelegate: this.applicationDelegate
})
this.commandInstaller = new CommandInstaller(this.applicationDelegate)
this.protocolHandlerInstaller = new ProtocolHandlerInstaller()
// Public: A {TextEditorRegistry} instance
this.textEditors = new TextEditorRegistry({
config: this.config,
grammarRegistry: this.grammars,
assert: this.assert.bind(this),
packageManager: this.packages
})
// Public: A {Workspace} instance
this.workspace = new Workspace({
config: this.config,
project: this.project,
packageManager: this.packages,
grammarRegistry: this.grammars,
deserializerManager: this.deserializers,
notificationManager: this.notifications,
applicationDelegate: this.applicationDelegate,
viewRegistry: this.views,
assert: this.assert.bind(this),
textEditorRegistry: this.textEditors,
styleManager: this.styles,
enablePersistence: this.enablePersistence
})
this.themes.workspace = this.workspace
this.autoUpdater = new AutoUpdateManager({applicationDelegate: this.applicationDelegate})
if (this.keymaps.canLoadBundledKeymapsFromMemory()) {
this.keymaps.loadBundledKeymaps()
}
this.registerDefaultCommands()
this.registerDefaultOpeners()
this.registerDefaultDeserializers()
this.windowEventHandler = new WindowEventHandler({atomEnvironment: this, applicationDelegate: this.applicationDelegate})
// Public: A {HistoryManager} instance
this.history = new HistoryManager({project: this.project, commands: this.commands, stateStore: this.stateStore})
// Keep instances of HistoryManager in sync
this.disposables.add(this.history.onDidChangeProjects(event => {
if (!event.reloaded) this.applicationDelegate.didChangeHistoryManager()
}))
}
initialize (params = {}) {
// This will force TextEditorElement to register the custom element, so that
// using `document.createElement('atom-text-editor')` works if it's called
// before opening a buffer.
require('./text-editor-element')
this.window = params.window
this.document = params.document
this.blobStore = params.blobStore
this.configDirPath = params.configDirPath
const {devMode, safeMode, resourcePath, userSettings, projectSpecification} = this.getLoadSettings()
ConfigSchema.projectHome = {
type: 'string',
default: path.join(fs.getHomeDirectory(), 'github'),
description: 'The directory where projects are assumed to be located. Packages created using the Package Generator will be stored here by default.'
}
this.config.initialize({
mainSource: this.enablePersistence && path.join(this.configDirPath, 'config.cson'),
projectHomeSchema: ConfigSchema.projectHome
})
this.config.resetUserSettings(userSettings)
if (projectSpecification != null && projectSpecification.config != null) {
this.project.replace(projectSpecification)
}
this.menu.initialize({resourcePath})
this.contextMenu.initialize({resourcePath, devMode})
this.keymaps.configDirPath = this.configDirPath
this.keymaps.resourcePath = resourcePath
this.keymaps.devMode = devMode
if (!this.keymaps.canLoadBundledKeymapsFromMemory()) {
this.keymaps.loadBundledKeymaps()
}
this.commands.attach(this.window)
this.styles.initialize({configDirPath: this.configDirPath})
this.packages.initialize({devMode, configDirPath: this.configDirPath, resourcePath, safeMode})
this.themes.initialize({configDirPath: this.configDirPath, resourcePath, safeMode, devMode})
this.commandInstaller.initialize(this.getVersion())
this.uriHandlerRegistry.registerHostHandler('core', CoreURIHandlers.create(this))
this.autoUpdater.initialize()
this.protocolHandlerInstaller.initialize(this.config, this.notifications)
this.themes.loadBaseStylesheets()
this.initialStyleElements = this.styles.getSnapshot()
if (params.onlyLoadBaseStyleSheets) this.themes.initialLoadComplete = true
this.setBodyPlatformClass()
this.stylesElement = this.styles.buildStylesElement()
this.document.head.appendChild(this.stylesElement)
this.keymaps.subscribeToFileReadFailure()
this.installUncaughtErrorHandler()
this.attachSaveStateListeners()
this.windowEventHandler.initialize(this.window, this.document)
const didChangeStyles = this.didChangeStyles.bind(this)
this.disposables.add(this.styles.onDidAddStyleElement(didChangeStyles))
this.disposables.add(this.styles.onDidUpdateStyleElement(didChangeStyles))
this.disposables.add(this.styles.onDidRemoveStyleElement(didChangeStyles))
this.observeAutoHideMenuBar()
this.disposables.add(this.applicationDelegate.onDidChangeHistoryManager(() => this.history.loadState()))
}
preloadPackages () {
return this.packages.preloadPackages()
}
attachSaveStateListeners () {
const saveState = _.debounce(() => {
this.window.requestIdleCallback(() => {
if (!this.unloaded) this.saveState({isUnloading: false})
})
}, this.saveStateDebounceInterval)
this.document.addEventListener('mousedown', saveState, true)
this.document.addEventListener('keydown', saveState, true)
this.disposables.add(new Disposable(() => {
this.document.removeEventListener('mousedown', saveState, true)
this.document.removeEventListener('keydown', saveState, true)
}))
}
registerDefaultDeserializers () {
this.deserializers.add(Workspace)
this.deserializers.add(PaneContainer)
this.deserializers.add(PaneAxis)
this.deserializers.add(Pane)
this.deserializers.add(Dock)
this.deserializers.add(Project)
this.deserializers.add(TextEditor)
this.deserializers.add(TextBuffer)
}
registerDefaultCommands () {
registerDefaultCommands({commandRegistry: this.commands, config: this.config, commandInstaller: this.commandInstaller, notificationManager: this.notifications, project: this.project, clipboard: this.clipboard})
}
registerDefaultOpeners () {
this.workspace.addOpener(uri => {
switch (uri) {
case 'atom://.atom/stylesheet':
return this.workspace.openTextFile(this.styles.getUserStyleSheetPath())
case 'atom://.atom/keymap':
return this.workspace.openTextFile(this.keymaps.getUserKeymapPath())
case 'atom://.atom/config':
return this.workspace.openTextFile(this.config.getUserConfigPath())
case 'atom://.atom/init-script':
return this.workspace.openTextFile(this.getUserInitScriptPath())
}
})
}
registerDefaultTargetForKeymaps () {
this.keymaps.defaultTarget = this.workspace.getElement()
}
observeAutoHideMenuBar () {
this.disposables.add(this.config.onDidChange('core.autoHideMenuBar', ({newValue}) => {
this.setAutoHideMenuBar(newValue)
}))
if (this.config.get('core.autoHideMenuBar')) this.setAutoHideMenuBar(true)
}
async reset () {
this.deserializers.clear()
this.registerDefaultDeserializers()
this.config.clear()
this.config.setSchema(null, {type: 'object', properties: _.clone(ConfigSchema)})
this.keymaps.clear()
this.keymaps.loadBundledKeymaps()
this.commands.clear()
this.registerDefaultCommands()
this.styles.restoreSnapshot(this.initialStyleElements)
this.menu.clear()
this.clipboard.reset()
this.notifications.clear()
this.contextMenu.clear()
await this.packages.reset()
this.workspace.reset(this.packages)
this.registerDefaultOpeners()
this.project.reset(this.packages)
this.workspace.subscribeToEvents()
this.grammars.clear()
this.textEditors.clear()
this.views.clear()
this.pathsWithWaitSessions.clear()
}
destroy () {
if (!this.project) return
this.disposables.dispose()
if (this.workspace) this.workspace.destroy()
this.workspace = null
this.themes.workspace = null
if (this.project) this.project.destroy()
this.project = null
this.commands.clear()
if (this.stylesElement) this.stylesElement.remove()
this.autoUpdater.destroy()
this.uriHandlerRegistry.destroy()
this.uninstallWindowEventHandler()
}
/*
Section: Event Subscription
*/
// Extended: Invoke the given callback whenever {::beep} is called.
//
// * `callback` {Function} to be called whenever {::beep} is called.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidBeep (callback) {
return this.emitter.on('did-beep', callback)
}
// Extended: Invoke the given callback when there is an unhandled error, but
// before the devtools pop open
//
// * `callback` {Function} to be called whenever there is an unhandled error
// * `event` {Object}
// * `originalError` {Object} the original error object
// * `message` {String} the original error object
// * `url` {String} Url to the file where the error originated.
// * `line` {Number}
// * `column` {Number}
// * `preventDefault` {Function} call this to avoid popping up the dev tools.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onWillThrowError (callback) {
return this.emitter.on('will-throw-error', callback)
}
// Extended: Invoke the given callback whenever there is an unhandled error.
//
// * `callback` {Function} to be called whenever there is an unhandled error
// * `event` {Object}
// * `originalError` {Object} the original error object
// * `message` {String} the original error object
// * `url` {String} Url to the file where the error originated.
// * `line` {Number}
// * `column` {Number}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidThrowError (callback) {
return this.emitter.on('did-throw-error', callback)
}
// TODO: Make this part of the public API. We should make onDidThrowError
// match the interface by only yielding an exception object to the handler
// and deprecating the old behavior.
onDidFailAssertion (callback) {
return this.emitter.on('did-fail-assertion', callback)
}
// Extended: Invoke the given callback as soon as the shell environment is
// loaded (or immediately if it was already loaded).
//
// * `callback` {Function} to be called whenever there is an unhandled error
whenShellEnvironmentLoaded (callback) {
if (this.shellEnvironmentLoaded) {
callback()
return new Disposable()
} else {
return this.emitter.once('loaded-shell-environment', callback)
}
}
/*
Section: Atom Details
*/
// Public: Returns a {Boolean} that is `true` if the current window is in development mode.
inDevMode () {
if (this.devMode == null) this.devMode = this.getLoadSettings().devMode
return this.devMode
}
// Public: Returns a {Boolean} that is `true` if the current window is in safe mode.
inSafeMode () {
if (this.safeMode == null) this.safeMode = this.getLoadSettings().safeMode
return this.safeMode
}
// Public: Returns a {Boolean} that is `true` if the current window is running specs.
inSpecMode () {
if (this.specMode == null) this.specMode = this.getLoadSettings().isSpec
return this.specMode
}
// Returns a {Boolean} indicating whether this the first time the window's been
// loaded.
isFirstLoad () {
if (this.firstLoad == null) this.firstLoad = this.getLoadSettings().firstLoad
return this.firstLoad
}
// Public: Get the version of the Atom application.
//
// Returns the version text {String}.
getVersion () {
if (this.appVersion == null) this.appVersion = this.getLoadSettings().appVersion
return this.appVersion
}
// Public: Gets the release channel of the Atom application.
//
// Returns the release channel as a {String}. Will return a specific release channel
// name like 'beta' or 'nightly' if one is found in the Atom version or 'stable'
// otherwise.
getReleaseChannel () {
// This matches stable, dev (with or without commit hash) and any other
// release channel following the pattern '1.00.0-channel0'
const match = this.getVersion().match(/\d+\.\d+\.\d+(-([a-z]+)(\d+|-\w{4,})?)?$/)
if (!match) {
return 'unrecognized'
} else if (match[2]) {
return match[2]
}
return 'stable'
}
// Public: Returns a {Boolean} that is `true` if the current version is an official release.
isReleasedVersion () {
return this.getReleaseChannel().match(/stable|beta|nightly/) != null
}
// Public: Get the time taken to completely load the current window.
//
// This time include things like loading and activating packages, creating
// DOM elements for the editor, and reading the config.
//
// Returns the {Number} of milliseconds taken to load the window or null
// if the window hasn't finished loading yet.
getWindowLoadTime () {
return this.loadTime
}
// Public: Get the load settings for the current window.
//
// Returns an {Object} containing all the load setting key/value pairs.
getLoadSettings () {
return this.applicationDelegate.getWindowLoadSettings()
}
/*
Section: Managing The Atom Window
*/
// Essential: Open a new Atom window using the given options.
//
// Calling this method without an options parameter will open a prompt to pick
// a file/folder to open in the new window.
//
// * `params` An {Object} with the following keys:
// * `pathsToOpen` An {Array} of {String} paths to open.
// * `newWindow` A {Boolean}, true to always open a new window instead of
// reusing existing windows depending on the paths to open.
// * `devMode` A {Boolean}, true to open the window in development mode.
// Development mode loads the Atom source from the locally cloned
// repository and also loads all the packages in ~/.atom/dev/packages
// * `safeMode` A {Boolean}, true to open the window in safe mode. Safe
// mode prevents all packages installed to ~/.atom/packages from loading.
open (params) {
return this.applicationDelegate.open(params)
}
// Extended: Prompt the user to select one or more folders.
//
// * `callback` A {Function} to call once the user has confirmed the selection.
// * `paths` An {Array} of {String} paths that the user selected, or `null`
// if the user dismissed the dialog.
pickFolder (callback) {
return this.applicationDelegate.pickFolder(callback)
}
// Essential: Close the current window.
close () {
return this.applicationDelegate.closeWindow()
}
// Essential: Get the size of current window.
//
// Returns an {Object} in the format `{width: 1000, height: 700}`
getSize () {
return this.applicationDelegate.getWindowSize()
}
// Essential: Set the size of current window.
//
// * `width` The {Number} of pixels.
// * `height` The {Number} of pixels.
setSize (width, height) {
return this.applicationDelegate.setWindowSize(width, height)
}
// Essential: Get the position of current window.
//
// Returns an {Object} in the format `{x: 10, y: 20}`
getPosition () {
return this.applicationDelegate.getWindowPosition()
}
// Essential: Set the position of current window.
//
// * `x` The {Number} of pixels.
// * `y` The {Number} of pixels.
setPosition (x, y) {
return this.applicationDelegate.setWindowPosition(x, y)
}
// Extended: Get the current window
getCurrentWindow () {
return this.applicationDelegate.getCurrentWindow()
}
// Extended: Move current window to the center of the screen.
center () {
return this.applicationDelegate.centerWindow()
}
// Extended: Focus the current window.
focus () {
this.applicationDelegate.focusWindow()
return this.window.focus()
}
// Extended: Show the current window.
show () {
return this.applicationDelegate.showWindow()
}
// Extended: Hide the current window.
hide () {
return this.applicationDelegate.hideWindow()
}
// Extended: Reload the current window.
reload () {
return this.applicationDelegate.reloadWindow()
}
// Extended: Relaunch the entire application.
restartApplication () {
return this.applicationDelegate.restartApplication()
}
// Extended: Returns a {Boolean} that is `true` if the current window is maximized.
isMaximized () {
return this.applicationDelegate.isWindowMaximized()
}
maximize () {
return this.applicationDelegate.maximizeWindow()
}
// Extended: Returns a {Boolean} that is `true` if the current window is in full screen mode.
isFullScreen () {
return this.applicationDelegate.isWindowFullScreen()
}
// Extended: Set the full screen state of the current window.
setFullScreen (fullScreen = false) {
return this.applicationDelegate.setWindowFullScreen(fullScreen)
}
// Extended: Toggle the full screen state of the current window.
toggleFullScreen () {
return this.setFullScreen(!this.isFullScreen())
}
// Restore the window to its previous dimensions and show it.
//
// Restores the full screen and maximized state after the window has resized to
// prevent resize glitches.
async displayWindow () {
await this.restoreWindowDimensions()
const steps = [
this.restoreWindowBackground(),
this.show(),
this.focus()
]
if (this.windowDimensions && this.windowDimensions.fullScreen) {
steps.push(this.setFullScreen(true))
}
if (this.windowDimensions && this.windowDimensions.maximized && process.platform !== 'darwin') {
steps.push(this.maximize())
}
await Promise.all(steps)
}
// Get the dimensions of this window.
//
// Returns an {Object} with the following keys:
// * `x` The window's x-position {Number}.
// * `y` The window's y-position {Number}.
// * `width` The window's width {Number}.
// * `height` The window's height {Number}.
getWindowDimensions () {
const browserWindow = this.getCurrentWindow()
const [x, y] = browserWindow.getPosition()
const [width, height] = browserWindow.getSize()
const maximized = browserWindow.isMaximized()
return {x, y, width, height, maximized}
}
// Set the dimensions of the window.
//
// The window will be centered if either the x or y coordinate is not set
// in the dimensions parameter. If x or y are omitted the window will be
// centered. If height or width are omitted only the position will be changed.
//
// * `dimensions` An {Object} with the following keys:
// * `x` The new x coordinate.
// * `y` The new y coordinate.
// * `width` The new width.
// * `height` The new height.
setWindowDimensions ({x, y, width, height}) {
const steps = []
if (width != null && height != null) {
steps.push(this.setSize(width, height))
}
if (x != null && y != null) {
steps.push(this.setPosition(x, y))
} else {
steps.push(this.center())
}
return Promise.all(steps)
}
// Returns true if the dimensions are useable, false if they should be ignored.
// Work around for https://github.com/atom/atom-shell/issues/473
isValidDimensions ({x, y, width, height} = {}) {
return (width > 0) && (height > 0) && ((x + width) > 0) && ((y + height) > 0)
}
storeWindowDimensions () {
this.windowDimensions = this.getWindowDimensions()
if (this.isValidDimensions(this.windowDimensions)) {
localStorage.setItem('defaultWindowDimensions', JSON.stringify(this.windowDimensions))
}
}
getDefaultWindowDimensions () {
const {windowDimensions} = this.getLoadSettings()
if (windowDimensions) return windowDimensions
let dimensions
try {
dimensions = JSON.parse(localStorage.getItem('defaultWindowDimensions'))
} catch (error) {
console.warn('Error parsing default window dimensions', error)
localStorage.removeItem('defaultWindowDimensions')
}
if (dimensions && this.isValidDimensions(dimensions)) {
return dimensions
} else {
const {width, height} = this.applicationDelegate.getPrimaryDisplayWorkAreaSize()
return {x: 0, y: 0, width: Math.min(1024, width), height}
}
}
async restoreWindowDimensions () {
if (!this.windowDimensions || !this.isValidDimensions(this.windowDimensions)) {
this.windowDimensions = this.getDefaultWindowDimensions()
}
await this.setWindowDimensions(this.windowDimensions)
return this.windowDimensions
}
restoreWindowBackground () {
const backgroundColor = window.localStorage.getItem('atom:window-background-color')
if (backgroundColor) {
this.backgroundStylesheet = document.createElement('style')
this.backgroundStylesheet.type = 'text/css'
this.backgroundStylesheet.innerText = `html, body { background: ${backgroundColor} !important; }`
document.head.appendChild(this.backgroundStylesheet)
}
}
storeWindowBackground () {
if (this.inSpecMode()) return
const backgroundColor = this.window.getComputedStyle(this.workspace.getElement())['background-color']
this.window.localStorage.setItem('atom:window-background-color', backgroundColor)
}
// Call this method when establishing a real application window.
async startEditorWindow () {
if (this.getLoadSettings().clearWindowState) {
await this.stateStore.clear()
}
this.unloaded = false
const updateProcessEnvPromise = this.updateProcessEnvAndTriggerHooks()
const loadStatePromise = this.loadState().then(async state => {
this.windowDimensions = state && state.windowDimensions
await this.displayWindow()
this.commandInstaller.installAtomCommand(false, (error) => {
if (error) console.warn(error.message)
})
this.commandInstaller.installApmCommand(false, (error) => {
if (error) console.warn(error.message)
})
this.disposables.add(this.applicationDelegate.onDidChangeUserSettings(settings =>
this.config.resetUserSettings(settings)
))
this.disposables.add(this.applicationDelegate.onDidFailToReadUserSettings(message =>
this.notifications.addError(message)
))
this.disposables.add(this.applicationDelegate.onDidOpenLocations(this.openLocations.bind(this)))
this.disposables.add(this.applicationDelegate.onApplicationMenuCommand(this.dispatchApplicationMenuCommand.bind(this)))
this.disposables.add(this.applicationDelegate.onContextMenuCommand(this.dispatchContextMenuCommand.bind(this)))
this.disposables.add(this.applicationDelegate.onURIMessage(this.dispatchURIMessage.bind(this)))
this.disposables.add(this.applicationDelegate.onDidRequestUnload(async () => {
try {
await this.saveState({isUnloading: true})
} catch (error) {
console.error(error)
}
const closing = !this.workspace || await this.workspace.confirmClose({
windowCloseRequested: true,
projectHasPaths: this.project.getPaths().length > 0
})
if (closing) await this.packages.deactivatePackages()
return closing
}))
this.listenForUpdates()
this.registerDefaultTargetForKeymaps()
this.packages.loadPackages()
const startTime = Date.now()
await this.deserialize(state)
this.deserializeTimings.atom = Date.now() - startTime
if (process.platform === 'darwin' && this.config.get('core.titleBar') === 'custom') {
this.workspace.addHeaderPanel({item: new TitleBar({workspace: this.workspace, themes: this.themes, applicationDelegate: this.applicationDelegate})})
this.document.body.classList.add('custom-title-bar')
}
if (process.platform === 'darwin' && this.config.get('core.titleBar') === 'custom-inset') {
this.workspace.addHeaderPanel({item: new TitleBar({workspace: this.workspace, themes: this.themes, applicationDelegate: this.applicationDelegate})})
this.document.body.classList.add('custom-inset-title-bar')
}
if (process.platform === 'darwin' && this.config.get('core.titleBar') === 'hidden') {
this.document.body.classList.add('hidden-title-bar')
}
this.document.body.appendChild(this.workspace.getElement())
if (this.backgroundStylesheet) this.backgroundStylesheet.remove()
let previousProjectPaths = this.project.getPaths()
this.disposables.add(this.project.onDidChangePaths(newPaths => {
for (let path of previousProjectPaths) {
if (this.pathsWithWaitSessions.has(path) && !newPaths.includes(path)) {
this.applicationDelegate.didClosePathWithWaitSession(path)
}
}
previousProjectPaths = newPaths
this.applicationDelegate.setRepresentedDirectoryPaths(newPaths)
}))
this.disposables.add(this.workspace.onDidDestroyPaneItem(({item}) => {
const path = item.getPath && item.getPath()
if (this.pathsWithWaitSessions.has(path)) {
this.applicationDelegate.didClosePathWithWaitSession(path)
}
}))
this.packages.activate()
this.keymaps.loadUserKeymap()
if (!this.getLoadSettings().safeMode) this.requireUserInitScript()
this.menu.update()
await this.openInitialEmptyEditorIfNecessary()
})
const loadHistoryPromise = this.history.loadState().then(() => {
this.reopenProjectMenuManager = new ReopenProjectMenuManager({
menu: this.menu,
commands: this.commands,
history: this.history,
config: this.config,
open: paths => this.open({pathsToOpen: paths})
})
this.reopenProjectMenuManager.update()
})
return Promise.all([loadStatePromise, loadHistoryPromise, updateProcessEnvPromise])
}
serialize (options) {
return {
version: this.constructor.version,
project: this.project.serialize(options),
workspace: this.workspace.serialize(),
packageStates: this.packages.serialize(),
grammars: this.grammars.serialize(),
fullScreen: this.isFullScreen(),
windowDimensions: this.windowDimensions
}
}
unloadEditorWindow () {
if (!this.project) return
this.storeWindowBackground()
this.saveBlobStoreSync()
this.unloaded = true
}
saveBlobStoreSync () {
if (this.enablePersistence) {
this.blobStore.save()
}
}
openInitialEmptyEditorIfNecessary () {
if (!this.config.get('core.openEmptyEditorOnStart')) return
const {initialPaths} = this.getLoadSettings()
if (initialPaths && initialPaths.length === 0 && this.workspace.getPaneItems().length === 0) {
return this.workspace.open(null)
}
}
installUncaughtErrorHandler () {
this.previousWindowErrorHandler = this.window.onerror
this.window.onerror = (message, url, line, column, originalError) => {
const mapping = mapSourcePosition({source: url, line, column})
line = mapping.line
column = mapping.column
if (url === '<embedded>') url = mapping.source
const eventObject = {message, url, line, column, originalError}
let openDevTools = true
eventObject.preventDefault = () => { openDevTools = false }
this.emitter.emit('will-throw-error', eventObject)
if (openDevTools) {
this.openDevTools().then(() =>
this.executeJavaScriptInDevTools('DevToolsAPI.showPanel("console")')
)
}
this.emitter.emit('did-throw-error', {message, url, line, column, originalError})
}
}
uninstallUncaughtErrorHandler () {
this.window.onerror = this.previousWindowErrorHandler
}
installWindowEventHandler () {
this.windowEventHandler = new WindowEventHandler({atomEnvironment: this, applicationDelegate: this.applicationDelegate})
this.windowEventHandler.initialize(this.window, this.document)
}
uninstallWindowEventHandler () {
if (this.windowEventHandler) {
this.windowEventHandler.unsubscribe()
}
this.windowEventHandler = null
}
didChangeStyles (styleElement) {
TextEditor.didUpdateStyles()
if (styleElement.textContent.indexOf('scrollbar') >= 0) {
TextEditor.didUpdateScrollbarStyles()
}
}
async updateProcessEnvAndTriggerHooks () {
await this.updateProcessEnv(this.getLoadSettings().env)
this.shellEnvironmentLoaded = true
this.emitter.emit('loaded-shell-environment')
this.packages.triggerActivationHook('core:loaded-shell-environment')
}
/*
Section: Messaging the User
*/
// Essential: Visually and audibly trigger a beep.
beep () {
if (this.config.get('core.audioBeep')) this.applicationDelegate.playBeepSound()
this.emitter.emit('did-beep')
}
// Essential: A flexible way to open a dialog akin to an alert dialog.
//
// While both async and sync versions are provided, it is recommended to use the async version
// such that the renderer process is not blocked while the dialog box is open.
//
// The async version accepts the same options as Electron's `dialog.showMessageBox`.
// For convenience, it sets `type` to `'info'` and `normalizeAccessKeys` to `true` by default.
//
// If the dialog is closed (via `Esc` key or `X` in the top corner) without selecting a button
// the first button will be clicked unless a "Cancel" or "No" button is provided.
//
// ## Examples
//
// ```js
// // Async version (recommended)
// atom.confirm({
// message: 'How you feeling?',
// detail: 'Be honest.',