simpleServices.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  6. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8. 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;
  9. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10. };
  11. var __param = (this && this.__param) || function (paramIndex, decorator) {
  12. return function (target, key) { decorator(target, key, paramIndex); }
  13. };
  14. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  15. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  16. return new (P || (P = Promise))(function (resolve, reject) {
  17. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  18. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  19. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  20. step((generator = generator.apply(thisArg, _arguments || [])).next());
  21. });
  22. };
  23. import * as strings from '../../../base/common/strings.js';
  24. import * as dom from '../../../base/browser/dom.js';
  25. import { StandardKeyboardEvent } from '../../../base/browser/keyboardEvent.js';
  26. import { Emitter, Event } from '../../../base/common/event.js';
  27. import { SimpleKeybinding, createKeybinding } from '../../../base/common/keybindings.js';
  28. import { ImmortalReference, toDisposable, DisposableStore, Disposable } from '../../../base/common/lifecycle.js';
  29. import { OS, isLinux, isMacintosh } from '../../../base/common/platform.js';
  30. import Severity from '../../../base/common/severity.js';
  31. import { URI } from '../../../base/common/uri.js';
  32. import { isCodeEditor } from '../../browser/editorBrowser.js';
  33. import { ResourceTextEdit } from '../../browser/services/bulkEditService.js';
  34. import { isDiffEditorConfigurationKey, isEditorConfigurationKey } from '../../common/config/commonEditorConfig.js';
  35. import { EditOperation } from '../../common/core/editOperation.js';
  36. import { Position as Pos } from '../../common/core/position.js';
  37. import { Range } from '../../common/core/range.js';
  38. import { IModelService } from '../../common/services/modelService.js';
  39. import { CommandsRegistry } from '../../../platform/commands/common/commands.js';
  40. import { IConfigurationService } from '../../../platform/configuration/common/configuration.js';
  41. import { Configuration, ConfigurationModel, DefaultConfigurationModel, ConfigurationChangeEvent } from '../../../platform/configuration/common/configurationModels.js';
  42. import { AbstractKeybindingService } from '../../../platform/keybinding/common/abstractKeybindingService.js';
  43. import { KeybindingResolver } from '../../../platform/keybinding/common/keybindingResolver.js';
  44. import { KeybindingsRegistry } from '../../../platform/keybinding/common/keybindingsRegistry.js';
  45. import { ResolvedKeybindingItem } from '../../../platform/keybinding/common/resolvedKeybindingItem.js';
  46. import { USLayoutResolvedKeybinding } from '../../../platform/keybinding/common/usLayoutResolvedKeybinding.js';
  47. import { NoOpNotification } from '../../../platform/notification/common/notification.js';
  48. import { WorkspaceFolder } from '../../../platform/workspace/common/workspace.js';
  49. import { SimpleServicesNLS } from '../../common/standaloneStrings.js';
  50. export class SimpleModel {
  51. constructor(model) {
  52. this.disposed = false;
  53. this.model = model;
  54. this._onWillDispose = new Emitter();
  55. }
  56. get textEditorModel() {
  57. return this.model;
  58. }
  59. dispose() {
  60. this.disposed = true;
  61. this._onWillDispose.fire();
  62. }
  63. }
  64. function withTypedEditor(widget, codeEditorCallback, diffEditorCallback) {
  65. if (isCodeEditor(widget)) {
  66. // Single Editor
  67. return codeEditorCallback(widget);
  68. }
  69. else {
  70. // Diff Editor
  71. return diffEditorCallback(widget);
  72. }
  73. }
  74. let SimpleEditorModelResolverService = class SimpleEditorModelResolverService {
  75. constructor(modelService) {
  76. this.modelService = modelService;
  77. }
  78. setEditor(editor) {
  79. this.editor = editor;
  80. }
  81. createModelReference(resource) {
  82. let model = null;
  83. if (this.editor) {
  84. model = withTypedEditor(this.editor, (editor) => this.findModel(editor, resource), (diffEditor) => this.findModel(diffEditor.getOriginalEditor(), resource) || this.findModel(diffEditor.getModifiedEditor(), resource));
  85. }
  86. if (!model) {
  87. return Promise.reject(new Error(`Model not found`));
  88. }
  89. return Promise.resolve(new ImmortalReference(new SimpleModel(model)));
  90. }
  91. findModel(editor, resource) {
  92. let model = this.modelService.getModel(resource);
  93. if (model && model.uri.toString() !== resource.toString()) {
  94. return null;
  95. }
  96. return model;
  97. }
  98. };
  99. SimpleEditorModelResolverService = __decorate([
  100. __param(0, IModelService)
  101. ], SimpleEditorModelResolverService);
  102. export { SimpleEditorModelResolverService };
  103. export class SimpleEditorProgressService {
  104. show() {
  105. return SimpleEditorProgressService.NULL_PROGRESS_RUNNER;
  106. }
  107. showWhile(promise, delay) {
  108. return __awaiter(this, void 0, void 0, function* () {
  109. yield promise;
  110. });
  111. }
  112. }
  113. SimpleEditorProgressService.NULL_PROGRESS_RUNNER = {
  114. done: () => { },
  115. total: () => { },
  116. worked: () => { }
  117. };
  118. export class SimpleDialogService {
  119. confirm(confirmation) {
  120. return this.doConfirm(confirmation).then(confirmed => {
  121. return {
  122. confirmed,
  123. checkboxChecked: false // unsupported
  124. };
  125. });
  126. }
  127. doConfirm(confirmation) {
  128. let messageText = confirmation.message;
  129. if (confirmation.detail) {
  130. messageText = messageText + '\n\n' + confirmation.detail;
  131. }
  132. return Promise.resolve(window.confirm(messageText));
  133. }
  134. show(severity, message, buttons, options) {
  135. return Promise.resolve({ choice: 0 });
  136. }
  137. }
  138. export class SimpleNotificationService {
  139. info(message) {
  140. return this.notify({ severity: Severity.Info, message });
  141. }
  142. warn(message) {
  143. return this.notify({ severity: Severity.Warning, message });
  144. }
  145. error(error) {
  146. return this.notify({ severity: Severity.Error, message: error });
  147. }
  148. notify(notification) {
  149. switch (notification.severity) {
  150. case Severity.Error:
  151. console.error(notification.message);
  152. break;
  153. case Severity.Warning:
  154. console.warn(notification.message);
  155. break;
  156. default:
  157. console.log(notification.message);
  158. break;
  159. }
  160. return SimpleNotificationService.NO_OP;
  161. }
  162. status(message, options) {
  163. return Disposable.None;
  164. }
  165. }
  166. SimpleNotificationService.NO_OP = new NoOpNotification();
  167. export class StandaloneCommandService {
  168. constructor(instantiationService) {
  169. this._onWillExecuteCommand = new Emitter();
  170. this._onDidExecuteCommand = new Emitter();
  171. this.onWillExecuteCommand = this._onWillExecuteCommand.event;
  172. this.onDidExecuteCommand = this._onDidExecuteCommand.event;
  173. this._instantiationService = instantiationService;
  174. }
  175. executeCommand(id, ...args) {
  176. const command = CommandsRegistry.getCommand(id);
  177. if (!command) {
  178. return Promise.reject(new Error(`command '${id}' not found`));
  179. }
  180. try {
  181. this._onWillExecuteCommand.fire({ commandId: id, args });
  182. const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler, ...args]);
  183. this._onDidExecuteCommand.fire({ commandId: id, args });
  184. return Promise.resolve(result);
  185. }
  186. catch (err) {
  187. return Promise.reject(err);
  188. }
  189. }
  190. }
  191. export class StandaloneKeybindingService extends AbstractKeybindingService {
  192. constructor(contextKeyService, commandService, telemetryService, notificationService, logService, domNode) {
  193. super(contextKeyService, commandService, telemetryService, notificationService, logService);
  194. this._cachedResolver = null;
  195. this._dynamicKeybindings = [];
  196. // for standard keybindings
  197. this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e) => {
  198. const keyEvent = new StandardKeyboardEvent(e);
  199. const shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
  200. if (shouldPreventDefault) {
  201. keyEvent.preventDefault();
  202. keyEvent.stopPropagation();
  203. }
  204. }));
  205. // for single modifier chord keybindings (e.g. shift shift)
  206. this._register(dom.addDisposableListener(window, dom.EventType.KEY_UP, (e) => {
  207. const keyEvent = new StandardKeyboardEvent(e);
  208. const shouldPreventDefault = this._singleModifierDispatch(keyEvent, keyEvent.target);
  209. if (shouldPreventDefault) {
  210. keyEvent.preventDefault();
  211. }
  212. }));
  213. }
  214. addDynamicKeybinding(commandId, _keybinding, handler, when) {
  215. const keybinding = createKeybinding(_keybinding, OS);
  216. const toDispose = new DisposableStore();
  217. if (keybinding) {
  218. this._dynamicKeybindings.push({
  219. keybinding: keybinding.parts,
  220. command: commandId,
  221. when: when,
  222. weight1: 1000,
  223. weight2: 0,
  224. extensionId: null,
  225. isBuiltinExtension: false
  226. });
  227. toDispose.add(toDisposable(() => {
  228. for (let i = 0; i < this._dynamicKeybindings.length; i++) {
  229. let kb = this._dynamicKeybindings[i];
  230. if (kb.command === commandId) {
  231. this._dynamicKeybindings.splice(i, 1);
  232. this.updateResolver({ source: 1 /* Default */ });
  233. return;
  234. }
  235. }
  236. }));
  237. }
  238. toDispose.add(CommandsRegistry.registerCommand(commandId, handler));
  239. this.updateResolver({ source: 1 /* Default */ });
  240. return toDispose;
  241. }
  242. updateResolver(event) {
  243. this._cachedResolver = null;
  244. this._onDidUpdateKeybindings.fire(event);
  245. }
  246. _getResolver() {
  247. if (!this._cachedResolver) {
  248. const defaults = this._toNormalizedKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true);
  249. const overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false);
  250. this._cachedResolver = new KeybindingResolver(defaults, overrides, (str) => this._log(str));
  251. }
  252. return this._cachedResolver;
  253. }
  254. _documentHasFocus() {
  255. return document.hasFocus();
  256. }
  257. _toNormalizedKeybindingItems(items, isDefault) {
  258. let result = [], resultLen = 0;
  259. for (const item of items) {
  260. const when = item.when || undefined;
  261. const keybinding = item.keybinding;
  262. if (!keybinding) {
  263. // This might be a removal keybinding item in user settings => accept it
  264. result[resultLen++] = new ResolvedKeybindingItem(undefined, item.command, item.commandArgs, when, isDefault, null, false);
  265. }
  266. else {
  267. const resolvedKeybindings = USLayoutResolvedKeybinding.resolveUserBinding(keybinding, OS);
  268. for (const resolvedKeybinding of resolvedKeybindings) {
  269. result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null, false);
  270. }
  271. }
  272. }
  273. return result;
  274. }
  275. resolveKeyboardEvent(keyboardEvent) {
  276. let keybinding = new SimpleKeybinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode).toChord();
  277. return new USLayoutResolvedKeybinding(keybinding, OS);
  278. }
  279. }
  280. function isConfigurationOverrides(thing) {
  281. return thing
  282. && typeof thing === 'object'
  283. && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string')
  284. && (!thing.resource || thing.resource instanceof URI);
  285. }
  286. export class SimpleConfigurationService {
  287. constructor() {
  288. this._onDidChangeConfiguration = new Emitter();
  289. this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
  290. this._configuration = new Configuration(new DefaultConfigurationModel(), new ConfigurationModel());
  291. }
  292. getValue(arg1, arg2) {
  293. const section = typeof arg1 === 'string' ? arg1 : undefined;
  294. const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {};
  295. return this._configuration.getValue(section, overrides, undefined);
  296. }
  297. updateValues(values) {
  298. const previous = { data: this._configuration.toData() };
  299. let changedKeys = [];
  300. for (const entry of values) {
  301. const [key, value] = entry;
  302. if (this.getValue(key) === value) {
  303. continue;
  304. }
  305. this._configuration.updateValue(key, value);
  306. changedKeys.push(key);
  307. }
  308. if (changedKeys.length > 0) {
  309. const configurationChangeEvent = new ConfigurationChangeEvent({ keys: changedKeys, overrides: [] }, previous, this._configuration);
  310. configurationChangeEvent.source = 7 /* MEMORY */;
  311. configurationChangeEvent.sourceConfig = null;
  312. this._onDidChangeConfiguration.fire(configurationChangeEvent);
  313. }
  314. return Promise.resolve();
  315. }
  316. updateValue(key, value, arg3, arg4) {
  317. return this.updateValues([[key, value]]);
  318. }
  319. }
  320. export class SimpleResourceConfigurationService {
  321. constructor(configurationService) {
  322. this.configurationService = configurationService;
  323. this._onDidChangeConfiguration = new Emitter();
  324. this.configurationService.onDidChangeConfiguration((e) => {
  325. this._onDidChangeConfiguration.fire({ affectedKeys: e.affectedKeys, affectsConfiguration: (resource, configuration) => e.affectsConfiguration(configuration) });
  326. });
  327. }
  328. getValue(resource, arg2, arg3) {
  329. const position = Pos.isIPosition(arg2) ? arg2 : null;
  330. const section = position ? (typeof arg3 === 'string' ? arg3 : undefined) : (typeof arg2 === 'string' ? arg2 : undefined);
  331. if (typeof section === 'undefined') {
  332. return this.configurationService.getValue();
  333. }
  334. return this.configurationService.getValue(section);
  335. }
  336. }
  337. let SimpleResourcePropertiesService = class SimpleResourcePropertiesService {
  338. constructor(configurationService) {
  339. this.configurationService = configurationService;
  340. }
  341. getEOL(resource, language) {
  342. const eol = this.configurationService.getValue('files.eol', { overrideIdentifier: language, resource });
  343. if (eol && typeof eol === 'string' && eol !== 'auto') {
  344. return eol;
  345. }
  346. return (isLinux || isMacintosh) ? '\n' : '\r\n';
  347. }
  348. };
  349. SimpleResourcePropertiesService = __decorate([
  350. __param(0, IConfigurationService)
  351. ], SimpleResourcePropertiesService);
  352. export { SimpleResourcePropertiesService };
  353. export class StandaloneTelemetryService {
  354. publicLog(eventName, data) {
  355. return Promise.resolve(undefined);
  356. }
  357. publicLog2(eventName, data) {
  358. return this.publicLog(eventName, data);
  359. }
  360. }
  361. export class SimpleWorkspaceContextService {
  362. constructor() {
  363. const resource = URI.from({ scheme: SimpleWorkspaceContextService.SCHEME, authority: 'model', path: '/' });
  364. this.workspace = { id: '4064f6ec-cb38-4ad0-af64-ee6467e63c82', folders: [new WorkspaceFolder({ uri: resource, name: '', index: 0 })] };
  365. }
  366. getWorkspace() {
  367. return this.workspace;
  368. }
  369. }
  370. SimpleWorkspaceContextService.SCHEME = 'inmemory';
  371. export function updateConfigurationService(configurationService, source, isDiffEditor) {
  372. if (!source) {
  373. return;
  374. }
  375. if (!(configurationService instanceof SimpleConfigurationService)) {
  376. return;
  377. }
  378. let toUpdate = [];
  379. Object.keys(source).forEach((key) => {
  380. if (isEditorConfigurationKey(key)) {
  381. toUpdate.push([`editor.${key}`, source[key]]);
  382. }
  383. if (isDiffEditor && isDiffEditorConfigurationKey(key)) {
  384. toUpdate.push([`diffEditor.${key}`, source[key]]);
  385. }
  386. });
  387. if (toUpdate.length > 0) {
  388. configurationService.updateValues(toUpdate);
  389. }
  390. }
  391. export class SimpleBulkEditService {
  392. constructor(_modelService) {
  393. this._modelService = _modelService;
  394. //
  395. }
  396. hasPreviewHandler() {
  397. return false;
  398. }
  399. apply(edits, _options) {
  400. return __awaiter(this, void 0, void 0, function* () {
  401. const textEdits = new Map();
  402. for (let edit of edits) {
  403. if (!(edit instanceof ResourceTextEdit)) {
  404. throw new Error('bad edit - only text edits are supported');
  405. }
  406. const model = this._modelService.getModel(edit.resource);
  407. if (!model) {
  408. throw new Error('bad edit - model not found');
  409. }
  410. if (typeof edit.versionId === 'number' && model.getVersionId() !== edit.versionId) {
  411. throw new Error('bad state - model changed in the meantime');
  412. }
  413. let array = textEdits.get(model);
  414. if (!array) {
  415. array = [];
  416. textEdits.set(model, array);
  417. }
  418. array.push(EditOperation.replaceMove(Range.lift(edit.textEdit.range), edit.textEdit.text));
  419. }
  420. let totalEdits = 0;
  421. let totalFiles = 0;
  422. for (const [model, edits] of textEdits) {
  423. model.pushStackElement();
  424. model.pushEditOperations([], edits, () => []);
  425. model.pushStackElement();
  426. totalFiles += 1;
  427. totalEdits += edits.length;
  428. }
  429. return {
  430. ariaSummary: strings.format(SimpleServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles)
  431. };
  432. });
  433. }
  434. }
  435. export class SimpleUriLabelService {
  436. getUriLabel(resource, options) {
  437. if (resource.scheme === 'file') {
  438. return resource.fsPath;
  439. }
  440. return resource.path;
  441. }
  442. }
  443. export class SimpleLayoutService {
  444. constructor(_codeEditorService, _container) {
  445. this._codeEditorService = _codeEditorService;
  446. this._container = _container;
  447. this.onDidLayout = Event.None;
  448. }
  449. get dimension() {
  450. if (!this._dimension) {
  451. this._dimension = dom.getClientArea(window.document.body);
  452. }
  453. return this._dimension;
  454. }
  455. get container() {
  456. return this._container;
  457. }
  458. focus() {
  459. var _a;
  460. (_a = this._codeEditorService.getFocusedCodeEditor()) === null || _a === void 0 ? void 0 : _a.focus();
  461. }
  462. }
  463. export class SimpleWorkspaceTrustManagementService {
  464. constructor() {
  465. this._neverEmitter = new Emitter();
  466. this.onDidChangeTrust = this._neverEmitter.event;
  467. }
  468. isWorkspaceTrusted() {
  469. return true;
  470. }
  471. }