/* * Copyright (C) 2017 TypeFox and others. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 */ import { injectable, inject } from "inversify"; import { ResourceResolver, Resource, ResourceProvider, DisposableCollection, Emitter, Event } from "@theia/core"; import URI from "@theia/core/lib/common/uri"; import { FileSystem } from '@theia/filesystem/lib/common'; import { Workspace } from '@theia/languages/lib/browser'; import { CatalogoUri } from "./catalogo-uri"; export class CatalogoResource implements Resource { protected readonly originalUri: string; protected readonly toDispose = new DisposableCollection(); protected readonly onDidChangeContentsEmitter = new Emitter(); constructor( public readonly uri: URI, protected readonly originalResource: Resource, protected readonly workspace: Workspace ) { this.originalUri = this.originalResource.uri.toString(); this.toDispose.push(originalResource); this.toDispose.push(this.onDidChangeContentsEmitter); if (originalResource.onDidChangeContents) { this.toDispose.push(originalResource.onDidChangeContents(() => this.fireDidChangeContents())); } this.toDispose.push(this.workspace.onDidOpenTextDocument(({ uri }) => this.fireDidChangeContents(uri))); this.toDispose.push(this.workspace.onDidChangeTextDocument(({ textDocument }) => this.fireDidChangeContents(textDocument.uri))); this.toDispose.push(this.workspace.onDidCloseTextDocument(({ uri }) => this.fireDidChangeContents(uri))); } dispose(): void { this.toDispose.dispose(); } get onDidChangeContents(): Event { return this.onDidChangeContentsEmitter.event; } protected fireDidChangeContents(affectedUri?: string): void { if (this.shouldFireDidChangeContents(affectedUri)) { this.onDidChangeContentsEmitter.fire(undefined); } } protected shouldFireDidChangeContents(affectedUri?: string): boolean { return !affectedUri || affectedUri === this.originalUri; } async readContents(options?: { encoding?: string | undefined; }): Promise { const document = this.workspace.textDocuments.find(document => document.uri === this.originalUri); if (document) { return this.render(document.getText()); } return this.render(await this.originalResource.readContents(options)); } protected render(text: string): string { return text } } @injectable() export class CatalogoResourceResolver implements ResourceResolver { @inject(FileSystem) protected readonly fileSystem: FileSystem; @inject(CatalogoUri) protected readonly catalogoUri: CatalogoUri; @inject(Workspace) protected readonly workspace: Workspace; @inject(ResourceProvider) protected readonly resourceProvider: ResourceProvider; async resolve(uri: URI): Promise { const resourceUri = this.catalogoUri.validate(uri); const originalResource = await this.resourceProvider(resourceUri); return new CatalogoResource(uri, originalResource, this.workspace); } }