@theia/workspace 1.45.1 → 1.46.0-next.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +30 -30
  2. package/lib/browser/canonical-uri-service.d.ts +11 -11
  3. package/lib/browser/canonical-uri-service.js +59 -59
  4. package/lib/browser/diff-service.d.ts +10 -10
  5. package/lib/browser/diff-service.js +85 -85
  6. package/lib/browser/index.d.ts +7 -7
  7. package/lib/browser/index.js +34 -34
  8. package/lib/browser/quick-open-workspace.d.ts +25 -25
  9. package/lib/browser/quick-open-workspace.js +137 -137
  10. package/lib/browser/untitled-workspace-exit-dialog.d.ts +19 -19
  11. package/lib/browser/untitled-workspace-exit-dialog.js +74 -74
  12. package/lib/browser/workspace-breadcrumbs-contribution.d.ts +10 -10
  13. package/lib/browser/workspace-breadcrumbs-contribution.js +66 -66
  14. package/lib/browser/workspace-commands.d.ts +117 -117
  15. package/lib/browser/workspace-commands.js +601 -601
  16. package/lib/browser/workspace-commands.spec.d.ts +1 -1
  17. package/lib/browser/workspace-commands.spec.js +127 -127
  18. package/lib/browser/workspace-compare-handler.d.ts +26 -26
  19. package/lib/browser/workspace-compare-handler.js +66 -66
  20. package/lib/browser/workspace-delete-handler.d.ts +75 -75
  21. package/lib/browser/workspace-delete-handler.js +214 -214
  22. package/lib/browser/workspace-duplicate-handler.d.ts +30 -30
  23. package/lib/browser/workspace-duplicate-handler.js +86 -86
  24. package/lib/browser/workspace-frontend-contribution.d.ts +110 -110
  25. package/lib/browser/workspace-frontend-contribution.js +546 -546
  26. package/lib/browser/workspace-frontend-contribution.js.map +1 -1
  27. package/lib/browser/workspace-frontend-module.d.ts +3 -3
  28. package/lib/browser/workspace-frontend-module.js +91 -91
  29. package/lib/browser/workspace-input-dialog.d.ts +19 -19
  30. package/lib/browser/workspace-input-dialog.js +74 -74
  31. package/lib/browser/workspace-preferences.d.ts +11 -11
  32. package/lib/browser/workspace-preferences.js +46 -46
  33. package/lib/browser/workspace-schema-updater.d.ts +34 -34
  34. package/lib/browser/workspace-schema-updater.js +153 -153
  35. package/lib/browser/workspace-service.d.ts +184 -184
  36. package/lib/browser/workspace-service.js +739 -739
  37. package/lib/browser/workspace-storage-service.d.ts +15 -15
  38. package/lib/browser/workspace-storage-service.js +80 -80
  39. package/lib/browser/workspace-trust-preferences.d.ts +21 -21
  40. package/lib/browser/workspace-trust-preferences.js +65 -65
  41. package/lib/browser/workspace-trust-service.d.ts +27 -27
  42. package/lib/browser/workspace-trust-service.js +152 -152
  43. package/lib/browser/workspace-uri-contribution.d.ts +20 -20
  44. package/lib/browser/workspace-uri-contribution.js +113 -113
  45. package/lib/browser/workspace-uri-contribution.spec.d.ts +1 -1
  46. package/lib/browser/workspace-uri-contribution.spec.js +169 -169
  47. package/lib/browser/workspace-user-working-directory-provider.d.ts +12 -12
  48. package/lib/browser/workspace-user-working-directory-provider.js +62 -62
  49. package/lib/browser/workspace-utils.d.ts +15 -15
  50. package/lib/browser/workspace-utils.js +54 -54
  51. package/lib/browser/workspace-variable-contribution.d.ts +23 -23
  52. package/lib/browser/workspace-variable-contribution.js +237 -237
  53. package/lib/browser/workspace-window-title-updater.d.ts +7 -7
  54. package/lib/browser/workspace-window-title-updater.js +57 -57
  55. package/lib/browser-only/browser-only-workspace-server.d.ts +13 -0
  56. package/lib/browser-only/browser-only-workspace-server.d.ts.map +1 -0
  57. package/lib/browser-only/browser-only-workspace-server.js +81 -0
  58. package/lib/browser-only/browser-only-workspace-server.js.map +1 -0
  59. package/lib/browser-only/workspace-frontend-only-module.d.ts +4 -0
  60. package/lib/browser-only/workspace-frontend-only-module.d.ts.map +1 -0
  61. package/lib/browser-only/workspace-frontend-only-module.js +30 -0
  62. package/lib/browser-only/workspace-frontend-only-module.js.map +1 -0
  63. package/lib/common/index.d.ts +3 -3
  64. package/lib/common/index.js +30 -30
  65. package/lib/common/test/mock-workspace-server.d.ts +7 -7
  66. package/lib/common/test/mock-workspace-server.js +35 -35
  67. package/lib/common/untitled-workspace-service.d.ts +8 -8
  68. package/lib/common/untitled-workspace-service.js +60 -60
  69. package/lib/common/workspace-file-service.d.ts +26 -26
  70. package/lib/common/workspace-file-service.js +71 -71
  71. package/lib/common/workspace-protocol.d.ts +26 -26
  72. package/lib/common/workspace-protocol.js +23 -23
  73. package/lib/node/default-workspace-server.d.ts +65 -65
  74. package/lib/node/default-workspace-server.js +248 -248
  75. package/lib/node/default-workspace-server.spec.d.ts +1 -1
  76. package/lib/node/default-workspace-server.spec.js +85 -85
  77. package/lib/node/index.d.ts +2 -2
  78. package/lib/node/index.js +29 -29
  79. package/lib/node/workspace-backend-module.d.ts +3 -3
  80. package/lib/node/workspace-backend-module.js +33 -33
  81. package/package.json +9 -6
  82. package/src/browser/canonical-uri-service.ts +57 -57
  83. package/src/browser/diff-service.ts +62 -62
  84. package/src/browser/index.ts +23 -23
  85. package/src/browser/quick-open-workspace.ts +112 -112
  86. package/src/browser/untitled-workspace-exit-dialog.ts +70 -70
  87. package/src/browser/workspace-breadcrumbs-contribution.ts +56 -56
  88. package/src/browser/workspace-commands.spec.ts +153 -153
  89. package/src/browser/workspace-commands.ts +588 -588
  90. package/src/browser/workspace-compare-handler.ts +56 -56
  91. package/src/browser/workspace-delete-handler.ts +212 -212
  92. package/src/browser/workspace-duplicate-handler.ts +75 -75
  93. package/src/browser/workspace-frontend-contribution.ts +537 -537
  94. package/src/browser/workspace-frontend-module.ts +118 -118
  95. package/src/browser/workspace-input-dialog.ts +61 -61
  96. package/src/browser/workspace-preferences.ts +58 -58
  97. package/src/browser/workspace-schema-updater.ts +150 -150
  98. package/src/browser/workspace-service.ts +780 -780
  99. package/src/browser/workspace-storage-service.ts +67 -67
  100. package/src/browser/workspace-trust-preferences.ts +76 -76
  101. package/src/browser/workspace-trust-service.ts +147 -147
  102. package/src/browser/workspace-uri-contribution.spec.ts +191 -191
  103. package/src/browser/workspace-uri-contribution.ts +97 -97
  104. package/src/browser/workspace-user-working-directory-provider.ts +49 -49
  105. package/src/browser/workspace-utils.ts +45 -45
  106. package/src/browser/workspace-variable-contribution.ts +222 -222
  107. package/src/browser/workspace-window-title-updater.ts +45 -45
  108. package/src/browser-only/browser-only-workspace-server.ts +69 -0
  109. package/src/browser-only/workspace-frontend-only-module.ts +28 -0
  110. package/src/common/index.ts +19 -19
  111. package/src/common/test/mock-workspace-server.ts +29 -29
  112. package/src/common/untitled-workspace-service.ts +50 -50
  113. package/src/common/workspace-file-service.ts +72 -72
  114. package/src/common/workspace-protocol.ts +47 -47
  115. package/src/node/default-workspace-server.spec.ts +100 -100
  116. package/src/node/default-workspace-server.ts +244 -244
  117. package/src/node/index.ts +18 -18
  118. package/src/node/workspace-backend-module.ts +38 -38
@@ -1,740 +1,740 @@
1
- "use strict";
2
- // *****************************************************************************
3
- // Copyright (C) 2017 TypeFox and others.
4
- //
5
- // This program and the accompanying materials are made available under the
6
- // terms of the Eclipse Public License v. 2.0 which is available at
7
- // http://www.eclipse.org/legal/epl-2.0.
8
- //
9
- // This Source Code may also be made available under the following Secondary
10
- // Licenses when the conditions for such availability set forth in the Eclipse
11
- // Public License v. 2.0 are satisfied: GNU General Public License, version 2
12
- // with the GNU Classpath Exception which is available at
13
- // https://www.gnu.org/software/classpath/license.html.
14
- //
15
- // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
16
- // *****************************************************************************
17
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
18
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
20
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
21
- return c > 3 && r && Object.defineProperty(target, key, r), r;
22
- };
23
- var __metadata = (this && this.__metadata) || function (k, v) {
24
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
25
- };
26
- Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.WorkspaceData = exports.WorkspaceService = void 0;
28
- const inversify_1 = require("@theia/core/shared/inversify");
29
- const uri_1 = require("@theia/core/lib/common/uri");
30
- const common_1 = require("../common");
31
- const window_service_1 = require("@theia/core/lib/browser/window/window-service");
32
- const window_1 = require("@theia/core/lib/common/window");
33
- const browser_1 = require("@theia/core/lib/browser");
34
- const promise_util_1 = require("@theia/core/lib/common/promise-util");
35
- const env_variables_1 = require("@theia/core/lib/common/env-variables");
36
- const core_1 = require("@theia/core");
37
- const workspace_preferences_1 = require("./workspace-preferences");
38
- const jsoncparser = require("jsonc-parser");
39
- const Ajv = require("@theia/core/shared/ajv");
40
- const files_1 = require("@theia/filesystem/lib/common/files");
41
- const file_service_1 = require("@theia/filesystem/lib/browser/file-service");
42
- const window_title_service_1 = require("@theia/core/lib/browser/window/window-title-service");
43
- const browser_2 = require("@theia/filesystem/lib/browser");
44
- const workspace_schema_updater_1 = require("./workspace-schema-updater");
45
- const frontend_application_state_1 = require("@theia/core/lib/common/frontend-application-state");
46
- /**
47
- * The workspace service.
48
- */
49
- let WorkspaceService = class WorkspaceService {
50
- constructor() {
51
- this._roots = [];
52
- this.deferredRoots = new promise_util_1.Deferred();
53
- this._ready = new promise_util_1.Deferred();
54
- this.onWorkspaceChangeEmitter = new core_1.Emitter();
55
- this.onWorkspaceLocationChangedEmitter = new core_1.Emitter();
56
- this.toDisposeOnWorkspace = new core_1.DisposableCollection();
57
- this.rootWatchers = new Map();
58
- }
59
- get ready() {
60
- return this._ready.promise;
61
- }
62
- init() {
63
- this.doInit();
64
- }
65
- async doInit() {
66
- const wsUriString = await this.getDefaultWorkspaceUri();
67
- const wsStat = await this.toFileStat(wsUriString);
68
- await this.setWorkspace(wsStat);
69
- this.fileService.onDidFilesChange(event => {
70
- if (this._workspace && this._workspace.isFile && event.contains(this._workspace.resource)) {
71
- this.updateWorkspace();
72
- }
73
- });
74
- this.fsPreferences.onPreferenceChanged(event => {
75
- if (event.preferenceName === 'files.watcherExclude') {
76
- this.refreshRootWatchers();
77
- }
78
- });
79
- this._ready.resolve();
80
- }
81
- /**
82
- * Resolves to the default workspace URI as string.
83
- *
84
- * The default implementation tries to extract the default workspace location
85
- * from the `window.location.hash`, then falls-back to the most recently
86
- * used workspace root from the server.
87
- *
88
- * It is not ensured that the resolved workspace URI is valid, it can point
89
- * to a non-existing location.
90
- */
91
- getDefaultWorkspaceUri() {
92
- return this.doGetDefaultWorkspaceUri();
93
- }
94
- async doGetDefaultWorkspaceUri() {
95
- // If an empty window is explicitly requested do not restore a previous workspace.
96
- // Note: `window.location.hash` includes leading "#" if non-empty.
97
- if (window.location.hash === `#${window_1.DEFAULT_WINDOW_HASH}`) {
98
- window.location.hash = '';
99
- return undefined;
100
- }
101
- // Prefer the workspace path specified as the URL fragment, if present.
102
- if (window.location.hash.length > 1) {
103
- // Remove the leading # and decode the URI.
104
- const wpPath = decodeURI(window.location.hash.substring(1));
105
- const workspaceUri = new uri_1.default().withPath(wpPath).withScheme('file');
106
- let workspaceStat;
107
- try {
108
- workspaceStat = await this.fileService.resolve(workspaceUri);
109
- }
110
- catch { }
111
- if (workspaceStat && !workspaceStat.isDirectory && !this.isWorkspaceFile(workspaceStat)) {
112
- this.messageService.error(`Not a valid workspace file: ${workspaceUri}`);
113
- return undefined;
114
- }
115
- return workspaceUri.toString();
116
- }
117
- else {
118
- // Else, ask the server for its suggested workspace (usually the one
119
- // specified on the CLI, or the most recent).
120
- return this.server.getMostRecentlyUsedWorkspace();
121
- }
122
- }
123
- /**
124
- * Set the URL fragment to the given workspace path.
125
- */
126
- setURLFragment(workspacePath) {
127
- window.location.hash = encodeURI(workspacePath);
128
- }
129
- get roots() {
130
- return this.deferredRoots.promise;
131
- }
132
- tryGetRoots() {
133
- return this._roots;
134
- }
135
- get workspace() {
136
- return this._workspace;
137
- }
138
- get onWorkspaceChanged() {
139
- return this.onWorkspaceChangeEmitter.event;
140
- }
141
- get onWorkspaceLocationChanged() {
142
- return this.onWorkspaceLocationChangedEmitter.event;
143
- }
144
- async setWorkspace(workspaceStat) {
145
- if (this._workspace && workspaceStat &&
146
- this._workspace.resource === workspaceStat.resource &&
147
- this._workspace.mtime === workspaceStat.mtime &&
148
- this._workspace.etag === workspaceStat.etag &&
149
- this._workspace.size === workspaceStat.size) {
150
- return;
151
- }
152
- this.toDisposeOnWorkspace.dispose();
153
- this._workspace = workspaceStat;
154
- if (this._workspace) {
155
- const uri = this._workspace.resource;
156
- if (this._workspace.isFile) {
157
- this.toDisposeOnWorkspace.push(this.fileService.watch(uri));
158
- this.onWorkspaceLocationChangedEmitter.fire(this._workspace);
159
- }
160
- this.setURLFragment(uri.path.toString());
161
- }
162
- else {
163
- this.setURLFragment('');
164
- }
165
- this.updateTitle();
166
- await this.server.setMostRecentlyUsedWorkspace(this._workspace ? this._workspace.resource.toString() : '');
167
- await this.updateWorkspace();
168
- }
169
- async updateWorkspace() {
170
- await this.updateRoots();
171
- this.watchRoots();
172
- }
173
- async updateRoots() {
174
- const newRoots = await this.computeRoots();
175
- let rootsChanged = false;
176
- if (newRoots.length !== this._roots.length || newRoots.length === 0) {
177
- rootsChanged = true;
178
- }
179
- else {
180
- for (const newRoot of newRoots) {
181
- if (!this._roots.some(r => r.resource.toString() === newRoot.resource.toString())) {
182
- rootsChanged = true;
183
- break;
184
- }
185
- }
186
- }
187
- if (rootsChanged) {
188
- this._roots = newRoots;
189
- this.deferredRoots.resolve(this._roots); // in order to resolve first
190
- this.deferredRoots = new promise_util_1.Deferred();
191
- this.deferredRoots.resolve(this._roots);
192
- this.onWorkspaceChangeEmitter.fire(this._roots);
193
- }
194
- }
195
- async computeRoots() {
196
- const roots = [];
197
- if (this._workspace) {
198
- if (this._workspace.isDirectory) {
199
- return [this._workspace];
200
- }
201
- const workspaceData = await this.getWorkspaceDataFromFile();
202
- if (workspaceData) {
203
- for (const { path } of workspaceData.folders) {
204
- const valid = await this.toValidRoot(path);
205
- if (valid) {
206
- roots.push(valid);
207
- }
208
- else {
209
- roots.push(files_1.FileStat.dir(path));
210
- }
211
- }
212
- }
213
- }
214
- return roots;
215
- }
216
- async getWorkspaceDataFromFile() {
217
- if (this._workspace && await this.fileService.exists(this._workspace.resource)) {
218
- if (this._workspace.isDirectory) {
219
- return {
220
- folders: [{ path: this._workspace.resource.toString() }]
221
- };
222
- }
223
- else if (this.isWorkspaceFile(this._workspace)) {
224
- const stat = await this.fileService.read(this._workspace.resource);
225
- const strippedContent = jsoncparser.stripComments(stat.value);
226
- const data = jsoncparser.parse(strippedContent);
227
- if (data && WorkspaceData.is(data)) {
228
- return WorkspaceData.transformToAbsolute(data, stat);
229
- }
230
- this.logger.error(`Unable to retrieve workspace data from the file: '${this.labelProvider.getLongName(this._workspace)}'. Please check if the file is corrupted.`);
231
- }
232
- else {
233
- this.logger.warn(`Not a valid workspace file: ${this.labelProvider.getLongName(this._workspace)}`);
234
- }
235
- }
236
- }
237
- updateTitle() {
238
- let rootName;
239
- let rootPath;
240
- if (this._workspace) {
241
- const displayName = this._workspace.name;
242
- const fullName = this._workspace.resource.path.toString();
243
- if (this.isWorkspaceFile(this._workspace)) {
244
- if (this.isUntitledWorkspace(this._workspace.resource)) {
245
- const untitled = core_1.nls.localizeByDefault('Untitled (Workspace)');
246
- rootName = untitled;
247
- rootPath = untitled;
248
- }
249
- else {
250
- rootName = displayName.slice(0, displayName.lastIndexOf('.'));
251
- rootPath = fullName.slice(0, fullName.lastIndexOf('.'));
252
- }
253
- }
254
- else {
255
- rootName = displayName;
256
- rootPath = fullName;
257
- }
258
- }
259
- this.windowTitleService.update({
260
- rootName,
261
- rootPath
262
- });
263
- }
264
- /**
265
- * on unload, we set our workspace root as the last recently used on the backend.
266
- */
267
- onStop() {
268
- this.server.setMostRecentlyUsedWorkspace(this._workspace ? this._workspace.resource.toString() : '');
269
- }
270
- async recentWorkspaces() {
271
- return this.server.getRecentWorkspaces();
272
- }
273
- async removeRecentWorkspace(uri) {
274
- return this.server.removeRecentWorkspace(uri);
275
- }
276
- /**
277
- * Returns `true` if theia has an opened workspace or folder
278
- * @returns {boolean}
279
- */
280
- get opened() {
281
- return !!this._workspace;
282
- }
283
- /**
284
- * Returns `true` if a multiple-root workspace is currently open.
285
- * @returns {boolean}
286
- */
287
- get isMultiRootWorkspaceOpened() {
288
- return !!this.workspace && !this.workspace.isDirectory;
289
- }
290
- /**
291
- * Opens directory, or recreates a workspace from the file that `uri` points to.
292
- */
293
- open(uri, options) {
294
- this.doOpen(uri, options);
295
- }
296
- async doOpen(uri, options) {
297
- const stat = await this.toFileStat(uri);
298
- if (stat) {
299
- if (!stat.isDirectory && !this.isWorkspaceFile(stat)) {
300
- const message = `Not a valid workspace: ${uri.path.toString()}`;
301
- this.messageService.error(message);
302
- throw new Error(message);
303
- }
304
- // The same window has to be preserved too (instead of opening a new one), if the workspace root is not yet available and we are setting it for the first time.
305
- // Option passed as parameter has the highest priority (for api developers), then the preference, then the default.
306
- await this.roots;
307
- const { preserveWindow } = {
308
- preserveWindow: this.preferences['workspace.preserveWindow'] || !this.opened,
309
- ...options
310
- };
311
- await this.server.setMostRecentlyUsedWorkspace(uri.toString());
312
- if (preserveWindow) {
313
- this._workspace = stat;
314
- }
315
- this.openWindow(stat, Object.assign(options !== null && options !== void 0 ? options : {}, { preserveWindow }));
316
- return;
317
- }
318
- throw new Error('Invalid workspace root URI. Expected an existing directory or workspace file.');
319
- }
320
- /**
321
- * Adds root folder(s) to the workspace
322
- * @param uris URI or URIs of the root folder(s) to add
323
- */
324
- async addRoot(uris) {
325
- const toAdd = Array.isArray(uris) ? uris : [uris];
326
- await this.spliceRoots(this._roots.length, 0, ...toAdd);
327
- }
328
- /**
329
- * Removes root folder(s) from workspace.
330
- */
331
- async removeRoots(uris) {
332
- if (!this.opened) {
333
- throw new Error('Folder cannot be removed as there is no active folder in the current workspace.');
334
- }
335
- if (this._workspace) {
336
- const workspaceData = await this.getWorkspaceDataFromFile();
337
- this._workspace = await this.writeWorkspaceFile(this._workspace, WorkspaceData.buildWorkspaceData(this._roots.filter(root => uris.findIndex(u => u.toString() === root.resource.toString()) < 0), workspaceData));
338
- await this.updateWorkspace();
339
- }
340
- }
341
- async spliceRoots(start, deleteCount, ...rootsToAdd) {
342
- if (!this._workspace || this._workspace.isDirectory) {
343
- const untitledWorkspace = await this.getUntitledWorkspace();
344
- await this.save(untitledWorkspace);
345
- if (!this._workspace) {
346
- throw new Error('Could not create new untitled workspace');
347
- }
348
- }
349
- const dedup = new Set();
350
- const roots = this._roots.map(root => (dedup.add(root.resource.toString()), root.resource.toString()));
351
- const toAdd = [];
352
- for (const root of rootsToAdd) {
353
- const uri = root.toString();
354
- if (!dedup.has(uri)) {
355
- dedup.add(uri);
356
- toAdd.push(uri);
357
- }
358
- }
359
- const toRemove = roots.splice(start, deleteCount || 0, ...toAdd);
360
- if (!toRemove.length && !toAdd.length) {
361
- return [];
362
- }
363
- const currentData = await this.getWorkspaceDataFromFile();
364
- const newData = WorkspaceData.buildWorkspaceData(roots, currentData);
365
- await this.writeWorkspaceFile(this._workspace, newData);
366
- await this.updateWorkspace();
367
- return toRemove.map(root => new uri_1.default(root));
368
- }
369
- async getUntitledWorkspace() {
370
- const configDirURI = new uri_1.default(await this.envVariableServer.getConfigDirUri());
371
- return this.untitledWorkspaceService.getUntitledWorkspaceUri(configDirURI, uri => this.fileService.exists(uri).then(exists => !exists), () => this.messageService.warn(core_1.nls.localize('theia/workspace/untitled-cleanup', 'There appear to be many untitled workspace files. Please check {0} and remove any unused files.', configDirURI.resolve('workspaces').path.fsPath())));
372
- }
373
- async writeWorkspaceFile(workspaceFile, workspaceData) {
374
- if (workspaceFile) {
375
- const data = JSON.stringify(WorkspaceData.transformToRelative(workspaceData, workspaceFile));
376
- const edits = jsoncparser.format(data, undefined, { tabSize: 2, insertSpaces: true, eol: '' });
377
- const result = jsoncparser.applyEdits(data, edits);
378
- await this.fileService.write(workspaceFile.resource, result);
379
- return this.fileService.resolve(workspaceFile.resource);
380
- }
381
- }
382
- /**
383
- * Clears current workspace root.
384
- */
385
- async close() {
386
- if (await this.windowService.isSafeToShutDown(frontend_application_state_1.StopReason.Reload)) {
387
- this.windowService.setSafeToShutDown();
388
- this._workspace = undefined;
389
- this._roots.length = 0;
390
- await this.server.setMostRecentlyUsedWorkspace('');
391
- this.reloadWindow();
392
- }
393
- }
394
- /**
395
- * returns a FileStat if the argument URI points to an existing directory. Otherwise, `undefined`.
396
- */
397
- async toValidRoot(uri) {
398
- const fileStat = await this.toFileStat(uri);
399
- if (fileStat && fileStat.isDirectory) {
400
- return fileStat;
401
- }
402
- return undefined;
403
- }
404
- /**
405
- * returns a FileStat if the argument URI points to a file or directory. Otherwise, `undefined`.
406
- */
407
- async toFileStat(uri) {
408
- if (!uri) {
409
- return undefined;
410
- }
411
- let uriStr = uri.toString();
412
- try {
413
- if (uriStr.endsWith('/')) {
414
- uriStr = uriStr.slice(0, -1);
415
- }
416
- const normalizedUri = new uri_1.default(uriStr).normalizePath();
417
- return await this.fileService.resolve(normalizedUri);
418
- }
419
- catch (error) {
420
- return undefined;
421
- }
422
- }
423
- openWindow(uri, options) {
424
- const workspacePath = uri.resource.path.toString();
425
- if (this.shouldPreserveWindow(options)) {
426
- this.reloadWindow(options);
427
- }
428
- else {
429
- try {
430
- this.openNewWindow(workspacePath, options);
431
- }
432
- catch (error) {
433
- // Fall back to reloading the current window in case the browser has blocked the new window
434
- this._workspace = uri;
435
- this.logger.error(error.toString()).then(() => this.reloadWindow());
436
- }
437
- }
438
- }
439
- reloadWindow(options) {
440
- // Set the new workspace path as the URL fragment.
441
- if (this._workspace !== undefined) {
442
- this.setURLFragment(this._workspace.resource.path.toString());
443
- }
444
- else {
445
- this.setURLFragment('');
446
- }
447
- this.windowService.reload();
448
- }
449
- openNewWindow(workspacePath, options) {
450
- const url = new URL(window.location.href);
451
- url.hash = encodeURI(workspacePath);
452
- this.windowService.openNewWindow(url.toString());
453
- }
454
- shouldPreserveWindow(options) {
455
- return options !== undefined && !!options.preserveWindow;
456
- }
457
- /**
458
- * Return true if one of the paths in paths array is present in the workspace
459
- * NOTE: You should always explicitly use `/` as the separator between the path segments.
460
- */
461
- async containsSome(paths) {
462
- await this.roots;
463
- if (this.opened) {
464
- for (const root of this._roots) {
465
- const uri = root.resource;
466
- for (const path of paths) {
467
- const fileUri = uri.resolve(path);
468
- const exists = await this.fileService.exists(fileUri);
469
- if (exists) {
470
- return exists;
471
- }
472
- }
473
- }
474
- }
475
- return false;
476
- }
477
- /**
478
- * `true` if the current workspace is configured using a configuration file.
479
- *
480
- * `false` if there is no workspace or the workspace is simply a folder.
481
- */
482
- get saved() {
483
- return !!this._workspace && !this._workspace.isDirectory;
484
- }
485
- /**
486
- * Save workspace data into a file
487
- * @param uri URI or FileStat of the workspace file
488
- */
489
- async save(uri) {
490
- var _a;
491
- const resource = uri instanceof uri_1.default ? uri : uri.resource;
492
- if (!await this.fileService.exists(resource)) {
493
- await this.fileService.create(resource);
494
- }
495
- const workspaceData = { folders: [], settings: {} };
496
- if (!this.saved) {
497
- for (const p of Object.keys(this.schemaProvider.getCombinedSchema().properties)) {
498
- if (this.schemaProvider.isValidInScope(p, browser_1.PreferenceScope.Folder)) {
499
- continue;
500
- }
501
- const preferences = this.preferenceImpl.inspect(p);
502
- if (preferences && preferences.workspaceValue) {
503
- workspaceData.settings[p] = preferences.workspaceValue;
504
- }
505
- }
506
- }
507
- let stat = await this.toFileStat(resource);
508
- Object.assign(workspaceData, await this.getWorkspaceDataFromFile());
509
- stat = await this.writeWorkspaceFile(stat, WorkspaceData.buildWorkspaceData(this._roots, workspaceData));
510
- await this.server.setMostRecentlyUsedWorkspace(resource.toString());
511
- // If saving a workspace based on an untitled workspace, delete the old file.
512
- const toDelete = this.isUntitledWorkspace((_a = this.workspace) === null || _a === void 0 ? void 0 : _a.resource) && this.workspace.resource;
513
- await this.setWorkspace(stat);
514
- if (toDelete && stat && !toDelete.isEqual(stat.resource)) {
515
- await this.fileService.delete(toDelete).catch(() => { });
516
- }
517
- this.onWorkspaceLocationChangedEmitter.fire(stat);
518
- }
519
- async watchRoots() {
520
- const rootUris = new Set(this._roots.map(r => r.resource.toString()));
521
- for (const [uri, watcher] of this.rootWatchers.entries()) {
522
- if (!rootUris.has(uri)) {
523
- watcher.dispose();
524
- }
525
- }
526
- for (const root of this._roots) {
527
- this.watchRoot(root);
528
- }
529
- }
530
- async refreshRootWatchers() {
531
- for (const watcher of this.rootWatchers.values()) {
532
- watcher.dispose();
533
- }
534
- await this.watchRoots();
535
- }
536
- async watchRoot(root) {
537
- const uriStr = root.resource.toString();
538
- if (this.rootWatchers.has(uriStr)) {
539
- return;
540
- }
541
- const excludes = this.getExcludes(uriStr);
542
- const watcher = this.fileService.watch(new uri_1.default(uriStr), {
543
- recursive: true,
544
- excludes
545
- });
546
- this.rootWatchers.set(uriStr, new core_1.DisposableCollection(watcher, core_1.Disposable.create(() => this.rootWatchers.delete(uriStr))));
547
- }
548
- getExcludes(uri) {
549
- const patterns = this.fsPreferences.get('files.watcherExclude', undefined, uri);
550
- return Object.keys(patterns).filter(pattern => patterns[pattern]);
551
- }
552
- /**
553
- * Returns the workspace root uri that the given file belongs to.
554
- * In case that the file is found in more than one workspace roots, returns the root that is closest to the file.
555
- * If the file is not from the current workspace, returns `undefined`.
556
- * @param uri URI of the file
557
- */
558
- getWorkspaceRootUri(uri) {
559
- if (!uri) {
560
- const root = this.tryGetRoots()[0];
561
- if (root) {
562
- return root.resource;
563
- }
564
- return undefined;
565
- }
566
- const rootUris = [];
567
- for (const root of this.tryGetRoots()) {
568
- const rootUri = root.resource;
569
- if (rootUri && rootUri.isEqualOrParent(uri)) {
570
- rootUris.push(rootUri);
571
- }
572
- }
573
- return rootUris.sort((r1, r2) => r2.toString().length - r1.toString().length)[0];
574
- }
575
- areWorkspaceRoots(uris) {
576
- if (!uris.length) {
577
- return false;
578
- }
579
- const rootUris = new Set(this.tryGetRoots().map(root => root.resource.toString()));
580
- return uris.every(uri => rootUris.has(uri.toString()));
581
- }
582
- /**
583
- * Check if the file should be considered as a workspace file.
584
- *
585
- * Example: We should not try to read the contents of an .exe file.
586
- */
587
- isWorkspaceFile(candidate) {
588
- return this.workspaceFileService.isWorkspaceFile(candidate);
589
- }
590
- isUntitledWorkspace(candidate) {
591
- return this.untitledWorkspaceService.isUntitledWorkspace(candidate);
592
- }
593
- async isSafeToReload(withURI) {
594
- return !withURI || !this.untitledWorkspaceService.isUntitledWorkspace(withURI) || new uri_1.default(await this.getDefaultWorkspaceUri()).isEqual(withURI);
595
- }
596
- /**
597
- *
598
- * @param key the property key under which to store the schema (e.g. tasks, launch)
599
- * @param schema the schema for the property. If none is supplied, the update is treated as a deletion.
600
- */
601
- async updateSchema(key, schema) {
602
- return this.schemaUpdater.updateSchema({ key, schema });
603
- }
604
- };
605
- __decorate([
606
- (0, inversify_1.inject)(file_service_1.FileService),
607
- __metadata("design:type", file_service_1.FileService)
608
- ], WorkspaceService.prototype, "fileService", void 0);
609
- __decorate([
610
- (0, inversify_1.inject)(common_1.WorkspaceServer),
611
- __metadata("design:type", Object)
612
- ], WorkspaceService.prototype, "server", void 0);
613
- __decorate([
614
- (0, inversify_1.inject)(window_service_1.WindowService),
615
- __metadata("design:type", Object)
616
- ], WorkspaceService.prototype, "windowService", void 0);
617
- __decorate([
618
- (0, inversify_1.inject)(core_1.ILogger),
619
- __metadata("design:type", Object)
620
- ], WorkspaceService.prototype, "logger", void 0);
621
- __decorate([
622
- (0, inversify_1.inject)(workspace_preferences_1.WorkspacePreferences),
623
- __metadata("design:type", Object)
624
- ], WorkspaceService.prototype, "preferences", void 0);
625
- __decorate([
626
- (0, inversify_1.inject)(browser_1.PreferenceServiceImpl),
627
- __metadata("design:type", browser_1.PreferenceServiceImpl)
628
- ], WorkspaceService.prototype, "preferenceImpl", void 0);
629
- __decorate([
630
- (0, inversify_1.inject)(browser_1.PreferenceSchemaProvider),
631
- __metadata("design:type", browser_1.PreferenceSchemaProvider)
632
- ], WorkspaceService.prototype, "schemaProvider", void 0);
633
- __decorate([
634
- (0, inversify_1.inject)(env_variables_1.EnvVariablesServer),
635
- __metadata("design:type", Object)
636
- ], WorkspaceService.prototype, "envVariableServer", void 0);
637
- __decorate([
638
- (0, inversify_1.inject)(core_1.MessageService),
639
- __metadata("design:type", core_1.MessageService)
640
- ], WorkspaceService.prototype, "messageService", void 0);
641
- __decorate([
642
- (0, inversify_1.inject)(browser_1.LabelProvider),
643
- __metadata("design:type", browser_1.LabelProvider)
644
- ], WorkspaceService.prototype, "labelProvider", void 0);
645
- __decorate([
646
- (0, inversify_1.inject)(browser_2.FileSystemPreferences),
647
- __metadata("design:type", Object)
648
- ], WorkspaceService.prototype, "fsPreferences", void 0);
649
- __decorate([
650
- (0, inversify_1.inject)(workspace_schema_updater_1.WorkspaceSchemaUpdater),
651
- __metadata("design:type", workspace_schema_updater_1.WorkspaceSchemaUpdater)
652
- ], WorkspaceService.prototype, "schemaUpdater", void 0);
653
- __decorate([
654
- (0, inversify_1.inject)(common_1.UntitledWorkspaceService),
655
- __metadata("design:type", common_1.UntitledWorkspaceService)
656
- ], WorkspaceService.prototype, "untitledWorkspaceService", void 0);
657
- __decorate([
658
- (0, inversify_1.inject)(common_1.WorkspaceFileService),
659
- __metadata("design:type", common_1.WorkspaceFileService)
660
- ], WorkspaceService.prototype, "workspaceFileService", void 0);
661
- __decorate([
662
- (0, inversify_1.inject)(window_title_service_1.WindowTitleService),
663
- __metadata("design:type", window_title_service_1.WindowTitleService)
664
- ], WorkspaceService.prototype, "windowTitleService", void 0);
665
- __decorate([
666
- (0, inversify_1.postConstruct)(),
667
- __metadata("design:type", Function),
668
- __metadata("design:paramtypes", []),
669
- __metadata("design:returntype", void 0)
670
- ], WorkspaceService.prototype, "init", null);
671
- WorkspaceService = __decorate([
672
- (0, inversify_1.injectable)()
673
- ], WorkspaceService);
674
- exports.WorkspaceService = WorkspaceService;
675
- var WorkspaceData;
676
- (function (WorkspaceData) {
677
- const validateSchema = new Ajv().compile(workspace_schema_updater_1.workspaceSchema);
678
- function is(data) {
679
- return !!validateSchema(data);
680
- }
681
- WorkspaceData.is = is;
682
- function buildWorkspaceData(folders, additionalFields) {
683
- const roots = new Set();
684
- if (folders.length > 0) {
685
- if (typeof folders[0] !== 'string') {
686
- folders.forEach(folder => roots.add(folder.resource.toString()));
687
- }
688
- else {
689
- folders.forEach(folder => roots.add(folder));
690
- }
691
- }
692
- const data = {
693
- folders: Array.from(roots, folder => ({ path: folder }))
694
- };
695
- if (additionalFields) {
696
- delete additionalFields.folders;
697
- Object.assign(data, additionalFields);
698
- }
699
- return data;
700
- }
701
- WorkspaceData.buildWorkspaceData = buildWorkspaceData;
702
- function transformToRelative(data, workspaceFile) {
703
- const folderUris = [];
704
- const workspaceFileUri = new uri_1.default(workspaceFile ? workspaceFile.resource.toString() : '').withScheme('file');
705
- for (const { path } of data.folders) {
706
- const folderUri = new uri_1.default(path).withScheme('file');
707
- const rel = workspaceFileUri.parent.relative(folderUri);
708
- if (rel) {
709
- folderUris.push(rel.toString());
710
- }
711
- else {
712
- folderUris.push(folderUri.toString());
713
- }
714
- }
715
- return buildWorkspaceData(folderUris, data);
716
- }
717
- WorkspaceData.transformToRelative = transformToRelative;
718
- function transformToAbsolute(data, workspaceFile) {
719
- var _a;
720
- if (workspaceFile) {
721
- const folders = [];
722
- for (const folder of data.folders) {
723
- const path = folder.path;
724
- if (path.startsWith('file:///')) {
725
- folders.push(path);
726
- }
727
- else {
728
- const absolutePath = (_a = workspaceFile.resource.withScheme('file').parent.resolveToAbsolute(path)) === null || _a === void 0 ? void 0 : _a.toString();
729
- if (absolutePath) {
730
- folders.push(absolutePath.toString());
731
- }
732
- }
733
- }
734
- return Object.assign(data, buildWorkspaceData(folders, data));
735
- }
736
- return data;
737
- }
738
- WorkspaceData.transformToAbsolute = transformToAbsolute;
739
- })(WorkspaceData = exports.WorkspaceData || (exports.WorkspaceData = {}));
1
+ "use strict";
2
+ // *****************************************************************************
3
+ // Copyright (C) 2017 TypeFox and others.
4
+ //
5
+ // This program and the accompanying materials are made available under the
6
+ // terms of the Eclipse Public License v. 2.0 which is available at
7
+ // http://www.eclipse.org/legal/epl-2.0.
8
+ //
9
+ // This Source Code may also be made available under the following Secondary
10
+ // Licenses when the conditions for such availability set forth in the Eclipse
11
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
12
+ // with the GNU Classpath Exception which is available at
13
+ // https://www.gnu.org/software/classpath/license.html.
14
+ //
15
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
16
+ // *****************************************************************************
17
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
18
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
20
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
21
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
22
+ };
23
+ var __metadata = (this && this.__metadata) || function (k, v) {
24
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.WorkspaceData = exports.WorkspaceService = void 0;
28
+ const inversify_1 = require("@theia/core/shared/inversify");
29
+ const uri_1 = require("@theia/core/lib/common/uri");
30
+ const common_1 = require("../common");
31
+ const window_service_1 = require("@theia/core/lib/browser/window/window-service");
32
+ const window_1 = require("@theia/core/lib/common/window");
33
+ const browser_1 = require("@theia/core/lib/browser");
34
+ const promise_util_1 = require("@theia/core/lib/common/promise-util");
35
+ const env_variables_1 = require("@theia/core/lib/common/env-variables");
36
+ const core_1 = require("@theia/core");
37
+ const workspace_preferences_1 = require("./workspace-preferences");
38
+ const jsoncparser = require("jsonc-parser");
39
+ const Ajv = require("@theia/core/shared/ajv");
40
+ const files_1 = require("@theia/filesystem/lib/common/files");
41
+ const file_service_1 = require("@theia/filesystem/lib/browser/file-service");
42
+ const window_title_service_1 = require("@theia/core/lib/browser/window/window-title-service");
43
+ const browser_2 = require("@theia/filesystem/lib/browser");
44
+ const workspace_schema_updater_1 = require("./workspace-schema-updater");
45
+ const frontend_application_state_1 = require("@theia/core/lib/common/frontend-application-state");
46
+ /**
47
+ * The workspace service.
48
+ */
49
+ let WorkspaceService = class WorkspaceService {
50
+ constructor() {
51
+ this._roots = [];
52
+ this.deferredRoots = new promise_util_1.Deferred();
53
+ this._ready = new promise_util_1.Deferred();
54
+ this.onWorkspaceChangeEmitter = new core_1.Emitter();
55
+ this.onWorkspaceLocationChangedEmitter = new core_1.Emitter();
56
+ this.toDisposeOnWorkspace = new core_1.DisposableCollection();
57
+ this.rootWatchers = new Map();
58
+ }
59
+ get ready() {
60
+ return this._ready.promise;
61
+ }
62
+ init() {
63
+ this.doInit();
64
+ }
65
+ async doInit() {
66
+ const wsUriString = await this.getDefaultWorkspaceUri();
67
+ const wsStat = await this.toFileStat(wsUriString);
68
+ await this.setWorkspace(wsStat);
69
+ this.fileService.onDidFilesChange(event => {
70
+ if (this._workspace && this._workspace.isFile && event.contains(this._workspace.resource)) {
71
+ this.updateWorkspace();
72
+ }
73
+ });
74
+ this.fsPreferences.onPreferenceChanged(event => {
75
+ if (event.preferenceName === 'files.watcherExclude') {
76
+ this.refreshRootWatchers();
77
+ }
78
+ });
79
+ this._ready.resolve();
80
+ }
81
+ /**
82
+ * Resolves to the default workspace URI as string.
83
+ *
84
+ * The default implementation tries to extract the default workspace location
85
+ * from the `window.location.hash`, then falls-back to the most recently
86
+ * used workspace root from the server.
87
+ *
88
+ * It is not ensured that the resolved workspace URI is valid, it can point
89
+ * to a non-existing location.
90
+ */
91
+ getDefaultWorkspaceUri() {
92
+ return this.doGetDefaultWorkspaceUri();
93
+ }
94
+ async doGetDefaultWorkspaceUri() {
95
+ // If an empty window is explicitly requested do not restore a previous workspace.
96
+ // Note: `window.location.hash` includes leading "#" if non-empty.
97
+ if (window.location.hash === `#${window_1.DEFAULT_WINDOW_HASH}`) {
98
+ window.location.hash = '';
99
+ return undefined;
100
+ }
101
+ // Prefer the workspace path specified as the URL fragment, if present.
102
+ if (window.location.hash.length > 1) {
103
+ // Remove the leading # and decode the URI.
104
+ const wpPath = decodeURI(window.location.hash.substring(1));
105
+ const workspaceUri = new uri_1.default().withPath(wpPath).withScheme('file');
106
+ let workspaceStat;
107
+ try {
108
+ workspaceStat = await this.fileService.resolve(workspaceUri);
109
+ }
110
+ catch { }
111
+ if (workspaceStat && !workspaceStat.isDirectory && !this.isWorkspaceFile(workspaceStat)) {
112
+ this.messageService.error(`Not a valid workspace file: ${workspaceUri}`);
113
+ return undefined;
114
+ }
115
+ return workspaceUri.toString();
116
+ }
117
+ else {
118
+ // Else, ask the server for its suggested workspace (usually the one
119
+ // specified on the CLI, or the most recent).
120
+ return this.server.getMostRecentlyUsedWorkspace();
121
+ }
122
+ }
123
+ /**
124
+ * Set the URL fragment to the given workspace path.
125
+ */
126
+ setURLFragment(workspacePath) {
127
+ window.location.hash = encodeURI(workspacePath);
128
+ }
129
+ get roots() {
130
+ return this.deferredRoots.promise;
131
+ }
132
+ tryGetRoots() {
133
+ return this._roots;
134
+ }
135
+ get workspace() {
136
+ return this._workspace;
137
+ }
138
+ get onWorkspaceChanged() {
139
+ return this.onWorkspaceChangeEmitter.event;
140
+ }
141
+ get onWorkspaceLocationChanged() {
142
+ return this.onWorkspaceLocationChangedEmitter.event;
143
+ }
144
+ async setWorkspace(workspaceStat) {
145
+ if (this._workspace && workspaceStat &&
146
+ this._workspace.resource === workspaceStat.resource &&
147
+ this._workspace.mtime === workspaceStat.mtime &&
148
+ this._workspace.etag === workspaceStat.etag &&
149
+ this._workspace.size === workspaceStat.size) {
150
+ return;
151
+ }
152
+ this.toDisposeOnWorkspace.dispose();
153
+ this._workspace = workspaceStat;
154
+ if (this._workspace) {
155
+ const uri = this._workspace.resource;
156
+ if (this._workspace.isFile) {
157
+ this.toDisposeOnWorkspace.push(this.fileService.watch(uri));
158
+ this.onWorkspaceLocationChangedEmitter.fire(this._workspace);
159
+ }
160
+ this.setURLFragment(uri.path.toString());
161
+ }
162
+ else {
163
+ this.setURLFragment('');
164
+ }
165
+ this.updateTitle();
166
+ await this.server.setMostRecentlyUsedWorkspace(this._workspace ? this._workspace.resource.toString() : '');
167
+ await this.updateWorkspace();
168
+ }
169
+ async updateWorkspace() {
170
+ await this.updateRoots();
171
+ this.watchRoots();
172
+ }
173
+ async updateRoots() {
174
+ const newRoots = await this.computeRoots();
175
+ let rootsChanged = false;
176
+ if (newRoots.length !== this._roots.length || newRoots.length === 0) {
177
+ rootsChanged = true;
178
+ }
179
+ else {
180
+ for (const newRoot of newRoots) {
181
+ if (!this._roots.some(r => r.resource.toString() === newRoot.resource.toString())) {
182
+ rootsChanged = true;
183
+ break;
184
+ }
185
+ }
186
+ }
187
+ if (rootsChanged) {
188
+ this._roots = newRoots;
189
+ this.deferredRoots.resolve(this._roots); // in order to resolve first
190
+ this.deferredRoots = new promise_util_1.Deferred();
191
+ this.deferredRoots.resolve(this._roots);
192
+ this.onWorkspaceChangeEmitter.fire(this._roots);
193
+ }
194
+ }
195
+ async computeRoots() {
196
+ const roots = [];
197
+ if (this._workspace) {
198
+ if (this._workspace.isDirectory) {
199
+ return [this._workspace];
200
+ }
201
+ const workspaceData = await this.getWorkspaceDataFromFile();
202
+ if (workspaceData) {
203
+ for (const { path } of workspaceData.folders) {
204
+ const valid = await this.toValidRoot(path);
205
+ if (valid) {
206
+ roots.push(valid);
207
+ }
208
+ else {
209
+ roots.push(files_1.FileStat.dir(path));
210
+ }
211
+ }
212
+ }
213
+ }
214
+ return roots;
215
+ }
216
+ async getWorkspaceDataFromFile() {
217
+ if (this._workspace && await this.fileService.exists(this._workspace.resource)) {
218
+ if (this._workspace.isDirectory) {
219
+ return {
220
+ folders: [{ path: this._workspace.resource.toString() }]
221
+ };
222
+ }
223
+ else if (this.isWorkspaceFile(this._workspace)) {
224
+ const stat = await this.fileService.read(this._workspace.resource);
225
+ const strippedContent = jsoncparser.stripComments(stat.value);
226
+ const data = jsoncparser.parse(strippedContent);
227
+ if (data && WorkspaceData.is(data)) {
228
+ return WorkspaceData.transformToAbsolute(data, stat);
229
+ }
230
+ this.logger.error(`Unable to retrieve workspace data from the file: '${this.labelProvider.getLongName(this._workspace)}'. Please check if the file is corrupted.`);
231
+ }
232
+ else {
233
+ this.logger.warn(`Not a valid workspace file: ${this.labelProvider.getLongName(this._workspace)}`);
234
+ }
235
+ }
236
+ }
237
+ updateTitle() {
238
+ let rootName;
239
+ let rootPath;
240
+ if (this._workspace) {
241
+ const displayName = this._workspace.name;
242
+ const fullName = this._workspace.resource.path.toString();
243
+ if (this.isWorkspaceFile(this._workspace)) {
244
+ if (this.isUntitledWorkspace(this._workspace.resource)) {
245
+ const untitled = core_1.nls.localizeByDefault('Untitled (Workspace)');
246
+ rootName = untitled;
247
+ rootPath = untitled;
248
+ }
249
+ else {
250
+ rootName = displayName.slice(0, displayName.lastIndexOf('.'));
251
+ rootPath = fullName.slice(0, fullName.lastIndexOf('.'));
252
+ }
253
+ }
254
+ else {
255
+ rootName = displayName;
256
+ rootPath = fullName;
257
+ }
258
+ }
259
+ this.windowTitleService.update({
260
+ rootName,
261
+ rootPath
262
+ });
263
+ }
264
+ /**
265
+ * on unload, we set our workspace root as the last recently used on the backend.
266
+ */
267
+ onStop() {
268
+ this.server.setMostRecentlyUsedWorkspace(this._workspace ? this._workspace.resource.toString() : '');
269
+ }
270
+ async recentWorkspaces() {
271
+ return this.server.getRecentWorkspaces();
272
+ }
273
+ async removeRecentWorkspace(uri) {
274
+ return this.server.removeRecentWorkspace(uri);
275
+ }
276
+ /**
277
+ * Returns `true` if theia has an opened workspace or folder
278
+ * @returns {boolean}
279
+ */
280
+ get opened() {
281
+ return !!this._workspace;
282
+ }
283
+ /**
284
+ * Returns `true` if a multiple-root workspace is currently open.
285
+ * @returns {boolean}
286
+ */
287
+ get isMultiRootWorkspaceOpened() {
288
+ return !!this.workspace && !this.workspace.isDirectory;
289
+ }
290
+ /**
291
+ * Opens directory, or recreates a workspace from the file that `uri` points to.
292
+ */
293
+ open(uri, options) {
294
+ this.doOpen(uri, options);
295
+ }
296
+ async doOpen(uri, options) {
297
+ const stat = await this.toFileStat(uri);
298
+ if (stat) {
299
+ if (!stat.isDirectory && !this.isWorkspaceFile(stat)) {
300
+ const message = `Not a valid workspace: ${uri.path.toString()}`;
301
+ this.messageService.error(message);
302
+ throw new Error(message);
303
+ }
304
+ // The same window has to be preserved too (instead of opening a new one), if the workspace root is not yet available and we are setting it for the first time.
305
+ // Option passed as parameter has the highest priority (for api developers), then the preference, then the default.
306
+ await this.roots;
307
+ const { preserveWindow } = {
308
+ preserveWindow: this.preferences['workspace.preserveWindow'] || !this.opened,
309
+ ...options
310
+ };
311
+ await this.server.setMostRecentlyUsedWorkspace(uri.toString());
312
+ if (preserveWindow) {
313
+ this._workspace = stat;
314
+ }
315
+ this.openWindow(stat, Object.assign(options !== null && options !== void 0 ? options : {}, { preserveWindow }));
316
+ return;
317
+ }
318
+ throw new Error('Invalid workspace root URI. Expected an existing directory or workspace file.');
319
+ }
320
+ /**
321
+ * Adds root folder(s) to the workspace
322
+ * @param uris URI or URIs of the root folder(s) to add
323
+ */
324
+ async addRoot(uris) {
325
+ const toAdd = Array.isArray(uris) ? uris : [uris];
326
+ await this.spliceRoots(this._roots.length, 0, ...toAdd);
327
+ }
328
+ /**
329
+ * Removes root folder(s) from workspace.
330
+ */
331
+ async removeRoots(uris) {
332
+ if (!this.opened) {
333
+ throw new Error('Folder cannot be removed as there is no active folder in the current workspace.');
334
+ }
335
+ if (this._workspace) {
336
+ const workspaceData = await this.getWorkspaceDataFromFile();
337
+ this._workspace = await this.writeWorkspaceFile(this._workspace, WorkspaceData.buildWorkspaceData(this._roots.filter(root => uris.findIndex(u => u.toString() === root.resource.toString()) < 0), workspaceData));
338
+ await this.updateWorkspace();
339
+ }
340
+ }
341
+ async spliceRoots(start, deleteCount, ...rootsToAdd) {
342
+ if (!this._workspace || this._workspace.isDirectory) {
343
+ const untitledWorkspace = await this.getUntitledWorkspace();
344
+ await this.save(untitledWorkspace);
345
+ if (!this._workspace) {
346
+ throw new Error('Could not create new untitled workspace');
347
+ }
348
+ }
349
+ const dedup = new Set();
350
+ const roots = this._roots.map(root => (dedup.add(root.resource.toString()), root.resource.toString()));
351
+ const toAdd = [];
352
+ for (const root of rootsToAdd) {
353
+ const uri = root.toString();
354
+ if (!dedup.has(uri)) {
355
+ dedup.add(uri);
356
+ toAdd.push(uri);
357
+ }
358
+ }
359
+ const toRemove = roots.splice(start, deleteCount || 0, ...toAdd);
360
+ if (!toRemove.length && !toAdd.length) {
361
+ return [];
362
+ }
363
+ const currentData = await this.getWorkspaceDataFromFile();
364
+ const newData = WorkspaceData.buildWorkspaceData(roots, currentData);
365
+ await this.writeWorkspaceFile(this._workspace, newData);
366
+ await this.updateWorkspace();
367
+ return toRemove.map(root => new uri_1.default(root));
368
+ }
369
+ async getUntitledWorkspace() {
370
+ const configDirURI = new uri_1.default(await this.envVariableServer.getConfigDirUri());
371
+ return this.untitledWorkspaceService.getUntitledWorkspaceUri(configDirURI, uri => this.fileService.exists(uri).then(exists => !exists), () => this.messageService.warn(core_1.nls.localize('theia/workspace/untitled-cleanup', 'There appear to be many untitled workspace files. Please check {0} and remove any unused files.', configDirURI.resolve('workspaces').path.fsPath())));
372
+ }
373
+ async writeWorkspaceFile(workspaceFile, workspaceData) {
374
+ if (workspaceFile) {
375
+ const data = JSON.stringify(WorkspaceData.transformToRelative(workspaceData, workspaceFile));
376
+ const edits = jsoncparser.format(data, undefined, { tabSize: 2, insertSpaces: true, eol: '' });
377
+ const result = jsoncparser.applyEdits(data, edits);
378
+ await this.fileService.write(workspaceFile.resource, result);
379
+ return this.fileService.resolve(workspaceFile.resource);
380
+ }
381
+ }
382
+ /**
383
+ * Clears current workspace root.
384
+ */
385
+ async close() {
386
+ if (await this.windowService.isSafeToShutDown(frontend_application_state_1.StopReason.Reload)) {
387
+ this.windowService.setSafeToShutDown();
388
+ this._workspace = undefined;
389
+ this._roots.length = 0;
390
+ await this.server.setMostRecentlyUsedWorkspace('');
391
+ this.reloadWindow();
392
+ }
393
+ }
394
+ /**
395
+ * returns a FileStat if the argument URI points to an existing directory. Otherwise, `undefined`.
396
+ */
397
+ async toValidRoot(uri) {
398
+ const fileStat = await this.toFileStat(uri);
399
+ if (fileStat && fileStat.isDirectory) {
400
+ return fileStat;
401
+ }
402
+ return undefined;
403
+ }
404
+ /**
405
+ * returns a FileStat if the argument URI points to a file or directory. Otherwise, `undefined`.
406
+ */
407
+ async toFileStat(uri) {
408
+ if (!uri) {
409
+ return undefined;
410
+ }
411
+ let uriStr = uri.toString();
412
+ try {
413
+ if (uriStr.endsWith('/')) {
414
+ uriStr = uriStr.slice(0, -1);
415
+ }
416
+ const normalizedUri = new uri_1.default(uriStr).normalizePath();
417
+ return await this.fileService.resolve(normalizedUri);
418
+ }
419
+ catch (error) {
420
+ return undefined;
421
+ }
422
+ }
423
+ openWindow(uri, options) {
424
+ const workspacePath = uri.resource.path.toString();
425
+ if (this.shouldPreserveWindow(options)) {
426
+ this.reloadWindow(options);
427
+ }
428
+ else {
429
+ try {
430
+ this.openNewWindow(workspacePath, options);
431
+ }
432
+ catch (error) {
433
+ // Fall back to reloading the current window in case the browser has blocked the new window
434
+ this._workspace = uri;
435
+ this.logger.error(error.toString()).then(() => this.reloadWindow());
436
+ }
437
+ }
438
+ }
439
+ reloadWindow(options) {
440
+ // Set the new workspace path as the URL fragment.
441
+ if (this._workspace !== undefined) {
442
+ this.setURLFragment(this._workspace.resource.path.toString());
443
+ }
444
+ else {
445
+ this.setURLFragment('');
446
+ }
447
+ this.windowService.reload();
448
+ }
449
+ openNewWindow(workspacePath, options) {
450
+ const url = new URL(window.location.href);
451
+ url.hash = encodeURI(workspacePath);
452
+ this.windowService.openNewWindow(url.toString());
453
+ }
454
+ shouldPreserveWindow(options) {
455
+ return options !== undefined && !!options.preserveWindow;
456
+ }
457
+ /**
458
+ * Return true if one of the paths in paths array is present in the workspace
459
+ * NOTE: You should always explicitly use `/` as the separator between the path segments.
460
+ */
461
+ async containsSome(paths) {
462
+ await this.roots;
463
+ if (this.opened) {
464
+ for (const root of this._roots) {
465
+ const uri = root.resource;
466
+ for (const path of paths) {
467
+ const fileUri = uri.resolve(path);
468
+ const exists = await this.fileService.exists(fileUri);
469
+ if (exists) {
470
+ return exists;
471
+ }
472
+ }
473
+ }
474
+ }
475
+ return false;
476
+ }
477
+ /**
478
+ * `true` if the current workspace is configured using a configuration file.
479
+ *
480
+ * `false` if there is no workspace or the workspace is simply a folder.
481
+ */
482
+ get saved() {
483
+ return !!this._workspace && !this._workspace.isDirectory;
484
+ }
485
+ /**
486
+ * Save workspace data into a file
487
+ * @param uri URI or FileStat of the workspace file
488
+ */
489
+ async save(uri) {
490
+ var _a;
491
+ const resource = uri instanceof uri_1.default ? uri : uri.resource;
492
+ if (!await this.fileService.exists(resource)) {
493
+ await this.fileService.create(resource);
494
+ }
495
+ const workspaceData = { folders: [], settings: {} };
496
+ if (!this.saved) {
497
+ for (const p of Object.keys(this.schemaProvider.getCombinedSchema().properties)) {
498
+ if (this.schemaProvider.isValidInScope(p, browser_1.PreferenceScope.Folder)) {
499
+ continue;
500
+ }
501
+ const preferences = this.preferenceImpl.inspect(p);
502
+ if (preferences && preferences.workspaceValue) {
503
+ workspaceData.settings[p] = preferences.workspaceValue;
504
+ }
505
+ }
506
+ }
507
+ let stat = await this.toFileStat(resource);
508
+ Object.assign(workspaceData, await this.getWorkspaceDataFromFile());
509
+ stat = await this.writeWorkspaceFile(stat, WorkspaceData.buildWorkspaceData(this._roots, workspaceData));
510
+ await this.server.setMostRecentlyUsedWorkspace(resource.toString());
511
+ // If saving a workspace based on an untitled workspace, delete the old file.
512
+ const toDelete = this.isUntitledWorkspace((_a = this.workspace) === null || _a === void 0 ? void 0 : _a.resource) && this.workspace.resource;
513
+ await this.setWorkspace(stat);
514
+ if (toDelete && stat && !toDelete.isEqual(stat.resource)) {
515
+ await this.fileService.delete(toDelete).catch(() => { });
516
+ }
517
+ this.onWorkspaceLocationChangedEmitter.fire(stat);
518
+ }
519
+ async watchRoots() {
520
+ const rootUris = new Set(this._roots.map(r => r.resource.toString()));
521
+ for (const [uri, watcher] of this.rootWatchers.entries()) {
522
+ if (!rootUris.has(uri)) {
523
+ watcher.dispose();
524
+ }
525
+ }
526
+ for (const root of this._roots) {
527
+ this.watchRoot(root);
528
+ }
529
+ }
530
+ async refreshRootWatchers() {
531
+ for (const watcher of this.rootWatchers.values()) {
532
+ watcher.dispose();
533
+ }
534
+ await this.watchRoots();
535
+ }
536
+ async watchRoot(root) {
537
+ const uriStr = root.resource.toString();
538
+ if (this.rootWatchers.has(uriStr)) {
539
+ return;
540
+ }
541
+ const excludes = this.getExcludes(uriStr);
542
+ const watcher = this.fileService.watch(new uri_1.default(uriStr), {
543
+ recursive: true,
544
+ excludes
545
+ });
546
+ this.rootWatchers.set(uriStr, new core_1.DisposableCollection(watcher, core_1.Disposable.create(() => this.rootWatchers.delete(uriStr))));
547
+ }
548
+ getExcludes(uri) {
549
+ const patterns = this.fsPreferences.get('files.watcherExclude', undefined, uri);
550
+ return Object.keys(patterns).filter(pattern => patterns[pattern]);
551
+ }
552
+ /**
553
+ * Returns the workspace root uri that the given file belongs to.
554
+ * In case that the file is found in more than one workspace roots, returns the root that is closest to the file.
555
+ * If the file is not from the current workspace, returns `undefined`.
556
+ * @param uri URI of the file
557
+ */
558
+ getWorkspaceRootUri(uri) {
559
+ if (!uri) {
560
+ const root = this.tryGetRoots()[0];
561
+ if (root) {
562
+ return root.resource;
563
+ }
564
+ return undefined;
565
+ }
566
+ const rootUris = [];
567
+ for (const root of this.tryGetRoots()) {
568
+ const rootUri = root.resource;
569
+ if (rootUri && rootUri.isEqualOrParent(uri)) {
570
+ rootUris.push(rootUri);
571
+ }
572
+ }
573
+ return rootUris.sort((r1, r2) => r2.toString().length - r1.toString().length)[0];
574
+ }
575
+ areWorkspaceRoots(uris) {
576
+ if (!uris.length) {
577
+ return false;
578
+ }
579
+ const rootUris = new Set(this.tryGetRoots().map(root => root.resource.toString()));
580
+ return uris.every(uri => rootUris.has(uri.toString()));
581
+ }
582
+ /**
583
+ * Check if the file should be considered as a workspace file.
584
+ *
585
+ * Example: We should not try to read the contents of an .exe file.
586
+ */
587
+ isWorkspaceFile(candidate) {
588
+ return this.workspaceFileService.isWorkspaceFile(candidate);
589
+ }
590
+ isUntitledWorkspace(candidate) {
591
+ return this.untitledWorkspaceService.isUntitledWorkspace(candidate);
592
+ }
593
+ async isSafeToReload(withURI) {
594
+ return !withURI || !this.untitledWorkspaceService.isUntitledWorkspace(withURI) || new uri_1.default(await this.getDefaultWorkspaceUri()).isEqual(withURI);
595
+ }
596
+ /**
597
+ *
598
+ * @param key the property key under which to store the schema (e.g. tasks, launch)
599
+ * @param schema the schema for the property. If none is supplied, the update is treated as a deletion.
600
+ */
601
+ async updateSchema(key, schema) {
602
+ return this.schemaUpdater.updateSchema({ key, schema });
603
+ }
604
+ };
605
+ __decorate([
606
+ (0, inversify_1.inject)(file_service_1.FileService),
607
+ __metadata("design:type", file_service_1.FileService)
608
+ ], WorkspaceService.prototype, "fileService", void 0);
609
+ __decorate([
610
+ (0, inversify_1.inject)(common_1.WorkspaceServer),
611
+ __metadata("design:type", Object)
612
+ ], WorkspaceService.prototype, "server", void 0);
613
+ __decorate([
614
+ (0, inversify_1.inject)(window_service_1.WindowService),
615
+ __metadata("design:type", Object)
616
+ ], WorkspaceService.prototype, "windowService", void 0);
617
+ __decorate([
618
+ (0, inversify_1.inject)(core_1.ILogger),
619
+ __metadata("design:type", Object)
620
+ ], WorkspaceService.prototype, "logger", void 0);
621
+ __decorate([
622
+ (0, inversify_1.inject)(workspace_preferences_1.WorkspacePreferences),
623
+ __metadata("design:type", Object)
624
+ ], WorkspaceService.prototype, "preferences", void 0);
625
+ __decorate([
626
+ (0, inversify_1.inject)(browser_1.PreferenceServiceImpl),
627
+ __metadata("design:type", browser_1.PreferenceServiceImpl)
628
+ ], WorkspaceService.prototype, "preferenceImpl", void 0);
629
+ __decorate([
630
+ (0, inversify_1.inject)(browser_1.PreferenceSchemaProvider),
631
+ __metadata("design:type", browser_1.PreferenceSchemaProvider)
632
+ ], WorkspaceService.prototype, "schemaProvider", void 0);
633
+ __decorate([
634
+ (0, inversify_1.inject)(env_variables_1.EnvVariablesServer),
635
+ __metadata("design:type", Object)
636
+ ], WorkspaceService.prototype, "envVariableServer", void 0);
637
+ __decorate([
638
+ (0, inversify_1.inject)(core_1.MessageService),
639
+ __metadata("design:type", core_1.MessageService)
640
+ ], WorkspaceService.prototype, "messageService", void 0);
641
+ __decorate([
642
+ (0, inversify_1.inject)(browser_1.LabelProvider),
643
+ __metadata("design:type", browser_1.LabelProvider)
644
+ ], WorkspaceService.prototype, "labelProvider", void 0);
645
+ __decorate([
646
+ (0, inversify_1.inject)(browser_2.FileSystemPreferences),
647
+ __metadata("design:type", Object)
648
+ ], WorkspaceService.prototype, "fsPreferences", void 0);
649
+ __decorate([
650
+ (0, inversify_1.inject)(workspace_schema_updater_1.WorkspaceSchemaUpdater),
651
+ __metadata("design:type", workspace_schema_updater_1.WorkspaceSchemaUpdater)
652
+ ], WorkspaceService.prototype, "schemaUpdater", void 0);
653
+ __decorate([
654
+ (0, inversify_1.inject)(common_1.UntitledWorkspaceService),
655
+ __metadata("design:type", common_1.UntitledWorkspaceService)
656
+ ], WorkspaceService.prototype, "untitledWorkspaceService", void 0);
657
+ __decorate([
658
+ (0, inversify_1.inject)(common_1.WorkspaceFileService),
659
+ __metadata("design:type", common_1.WorkspaceFileService)
660
+ ], WorkspaceService.prototype, "workspaceFileService", void 0);
661
+ __decorate([
662
+ (0, inversify_1.inject)(window_title_service_1.WindowTitleService),
663
+ __metadata("design:type", window_title_service_1.WindowTitleService)
664
+ ], WorkspaceService.prototype, "windowTitleService", void 0);
665
+ __decorate([
666
+ (0, inversify_1.postConstruct)(),
667
+ __metadata("design:type", Function),
668
+ __metadata("design:paramtypes", []),
669
+ __metadata("design:returntype", void 0)
670
+ ], WorkspaceService.prototype, "init", null);
671
+ WorkspaceService = __decorate([
672
+ (0, inversify_1.injectable)()
673
+ ], WorkspaceService);
674
+ exports.WorkspaceService = WorkspaceService;
675
+ var WorkspaceData;
676
+ (function (WorkspaceData) {
677
+ const validateSchema = new Ajv().compile(workspace_schema_updater_1.workspaceSchema);
678
+ function is(data) {
679
+ return !!validateSchema(data);
680
+ }
681
+ WorkspaceData.is = is;
682
+ function buildWorkspaceData(folders, additionalFields) {
683
+ const roots = new Set();
684
+ if (folders.length > 0) {
685
+ if (typeof folders[0] !== 'string') {
686
+ folders.forEach(folder => roots.add(folder.resource.toString()));
687
+ }
688
+ else {
689
+ folders.forEach(folder => roots.add(folder));
690
+ }
691
+ }
692
+ const data = {
693
+ folders: Array.from(roots, folder => ({ path: folder }))
694
+ };
695
+ if (additionalFields) {
696
+ delete additionalFields.folders;
697
+ Object.assign(data, additionalFields);
698
+ }
699
+ return data;
700
+ }
701
+ WorkspaceData.buildWorkspaceData = buildWorkspaceData;
702
+ function transformToRelative(data, workspaceFile) {
703
+ const folderUris = [];
704
+ const workspaceFileUri = new uri_1.default(workspaceFile ? workspaceFile.resource.toString() : '').withScheme('file');
705
+ for (const { path } of data.folders) {
706
+ const folderUri = new uri_1.default(path).withScheme('file');
707
+ const rel = workspaceFileUri.parent.relative(folderUri);
708
+ if (rel) {
709
+ folderUris.push(rel.toString());
710
+ }
711
+ else {
712
+ folderUris.push(folderUri.toString());
713
+ }
714
+ }
715
+ return buildWorkspaceData(folderUris, data);
716
+ }
717
+ WorkspaceData.transformToRelative = transformToRelative;
718
+ function transformToAbsolute(data, workspaceFile) {
719
+ var _a;
720
+ if (workspaceFile) {
721
+ const folders = [];
722
+ for (const folder of data.folders) {
723
+ const path = folder.path;
724
+ if (path.startsWith('file:///')) {
725
+ folders.push(path);
726
+ }
727
+ else {
728
+ const absolutePath = (_a = workspaceFile.resource.withScheme('file').parent.resolveToAbsolute(path)) === null || _a === void 0 ? void 0 : _a.toString();
729
+ if (absolutePath) {
730
+ folders.push(absolutePath.toString());
731
+ }
732
+ }
733
+ }
734
+ return Object.assign(data, buildWorkspaceData(folders, data));
735
+ }
736
+ return data;
737
+ }
738
+ WorkspaceData.transformToAbsolute = transformToAbsolute;
739
+ })(WorkspaceData = exports.WorkspaceData || (exports.WorkspaceData = {}));
740
740
  //# sourceMappingURL=workspace-service.js.map