Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update "Open With..." command UX #13573

Merged
merged 3 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/core/src/browser/frontend-application-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ import { HoverService } from './hover-service';
import { AdditionalViewsMenuWidget, AdditionalViewsMenuWidgetFactory } from './shell/additional-views-menu-widget';
import { LanguageIconLabelProvider } from './language-icon-provider';
import { bindTreePreferences } from './tree';
import { OpenWithService } from './open-with-service';

export { bindResourceProvider, bindMessageService, bindPreferenceService };

Expand Down Expand Up @@ -224,6 +225,8 @@ export const frontendApplicationModule = new ContainerModule((bind, _unbind, _is
bind(CommandOpenHandler).toSelf().inSingletonScope();
bind(OpenHandler).toService(CommandOpenHandler);

bind(OpenWithService).toSelf().inSingletonScope();

bind(TooltipServiceImpl).toSelf().inSingletonScope();
bind(TooltipService).toService(TooltipServiceImpl);

Expand Down
1 change: 1 addition & 0 deletions packages/core/src/browser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export * from './frontend-application';
export * from './frontend-application-contribution';
export * from './keyboard';
export * from './opener-service';
export * from './open-with-service';
export * from './browser';
export * from './context-menu-renderer';
export * from './widgets';
Expand Down
93 changes: 93 additions & 0 deletions packages/core/src/browser/open-with-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// *****************************************************************************
// Copyright (C) 2024 TypeFox and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************

import { inject, injectable } from 'inversify';
import { Disposable } from '../common/disposable';
import { nls } from '../common/nls';
import { MaybePromise } from '../common/types';
import { URI } from '../common/uri';
import { QuickInputService } from './quick-input';

export interface OpenWithHandler {
/**
* A unique id of this handler.
*/
readonly id: string;
/**
* A human-readable name of this handler.
*/
readonly label?: string;
/**
* A human-readable provider name of this handler.
*/
readonly providerName?: string;
/**
* A css icon class of this handler.
*/
readonly iconClass?: string;
/**
* Test whether this handler can open the given URI for given options.
* Return a nonzero number if this handler can open; otherwise it cannot.
* Never reject.
*
* A returned value indicating a priority of this handler.
*/
canHandle(uri: URI): number;
/**
* Open a widget for the given URI and options.
* Resolve to an opened widget or undefined, e.g. if a page is opened.
* Never reject if `canHandle` return a positive number; otherwise should reject.
*/
open(uri: URI): MaybePromise<object | undefined>;
}

@injectable()
export class OpenWithService {

@inject(QuickInputService)
protected readonly quickInputService: QuickInputService;

protected readonly handlers: OpenWithHandler[] = [];

registerHandler(handler: OpenWithHandler): Disposable {
this.handlers.push(handler);
return Disposable.create(() => {
const index = this.handlers.indexOf(handler);
if (index !== -1) {
this.handlers.splice(index, 1);
}
});
}

async openWith(uri: URI): Promise<object | undefined> {
const handlers = this.getHandlers(uri);
const result = await this.quickInputService.pick(handlers.map(handler => ({
handler: handler,
label: handler.label ?? handler.id,
detail: handler.providerName
})), {
placeHolder: nls.localizeByDefault("Select editor for '{0}'", uri.path.base)
});
if (result) {
return result.handler.open(uri);
}
}

getHandlers(uri: URI): OpenWithHandler[] {
const map = new Map<OpenWithHandler, number>(this.handlers.map(handler => [handler, handler.canHandle(uri)]));
return this.handlers.filter(handler => map.get(handler)! > 0).sort((a, b) => map.get(b)! - map.get(a)!);
}
}
16 changes: 13 additions & 3 deletions packages/editor/src/browser/editor-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

import { injectable, postConstruct, inject } from '@theia/core/shared/inversify';
import URI from '@theia/core/lib/common/uri';
import { RecursivePartial, Emitter, Event, MaybePromise, CommandService } from '@theia/core/lib/common';
import { WidgetOpenerOptions, NavigatableWidgetOpenHandler, NavigatableWidgetOptions, Widget, PreferenceService, CommonCommands } from '@theia/core/lib/browser';
import { RecursivePartial, Emitter, Event, MaybePromise, CommandService, nls } from '@theia/core/lib/common';
import { WidgetOpenerOptions, NavigatableWidgetOpenHandler, NavigatableWidgetOptions, Widget, PreferenceService, CommonCommands, OpenWithService } from '@theia/core/lib/browser';
import { EditorWidget } from './editor-widget';
import { Range, Position, Location, TextEditor } from './editor';
import { EditorWidgetFactory } from './editor-widget-factory';
Expand All @@ -38,7 +38,7 @@ export class EditorManager extends NavigatableWidgetOpenHandler<EditorWidget> {

readonly id = EditorWidgetFactory.ID;

readonly label = 'Code Editor';
readonly label = nls.localizeByDefault('Text Editor');

protected readonly editorCounters = new Map<string, number>();

Expand All @@ -56,6 +56,7 @@ export class EditorManager extends NavigatableWidgetOpenHandler<EditorWidget> {

@inject(CommandService) protected readonly commands: CommandService;
@inject(PreferenceService) protected readonly preferenceService: PreferenceService;
@inject(OpenWithService) protected readonly openWithService: OpenWithService;

@postConstruct()
protected override init(): void {
Expand Down Expand Up @@ -84,6 +85,15 @@ export class EditorManager extends NavigatableWidgetOpenHandler<EditorWidget> {
this.addRecentlyVisible(widget);
}
}
this.openWithService.registerHandler({
id: this.id,
label: this.label,
providerName: nls.localizeByDefault('Built-in'),
// Higher priority than any other handler
// so that the text editor always appears first in the quick pick
canHandle: uri => this.canHandle(uri) * 100,
open: uri => this.open(uri)
});
this.updateCurrentEditor();
}

Expand Down
9 changes: 5 additions & 4 deletions packages/navigator/src/browser/file-navigator-commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,12 @@ export namespace FileNavigatorCommands {
category: CommonCommands.FILE_CATEGORY,
label: 'Focus on Files Explorer'
});
export const OPEN = Command.toDefaultLocalizedCommand({
export const OPEN: Command = {
msujew marked this conversation as resolved.
Show resolved Hide resolved
id: 'navigator.open',
category: CommonCommands.FILE_CATEGORY,
label: 'Open'
});
};
export const OPEN_WITH: Command = {
id: 'navigator.openWith',
};
export const NEW_FILE_TOOLBAR: Command = {
id: `${WorkspaceCommands.NEW_FILE.id}.toolbar`,
iconClass: codicon('new-file')
Expand Down
35 changes: 21 additions & 14 deletions packages/navigator/src/browser/navigator-contribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************

import { inject, injectable, postConstruct } from '@theia/core/shared/inversify';
import { inject, injectable, optional, postConstruct } from '@theia/core/shared/inversify';
import { AbstractViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
import {
CommonCommands,
Expand All @@ -31,7 +31,8 @@ import {
ApplicationShell,
TabBar,
Title,
SHELL_TABBAR_CONTEXT_MENU
SHELL_TABBAR_CONTEXT_MENU,
OpenWithService
} from '@theia/core/lib/browser';
import { FileDownloadCommands } from '@theia/filesystem/lib/browser/download/file-download-command-contribution';
import {
Expand All @@ -40,6 +41,7 @@ import {
MenuModelRegistry,
MenuPath,
Mutable,
QuickInputService,
} from '@theia/core/lib/common';
import {
DidCreateNewResourceEvent,
Expand Down Expand Up @@ -113,6 +115,7 @@ export namespace NavigatorContextMenu {
/** @deprecated use MODIFICATION */
export const ACTIONS = MODIFICATION;

/** @deprecated use the `FileNavigatorCommands.OPEN_WITH` command */
export const OPEN_WITH = [...NAVIGATION, 'open_with'];
}

Expand Down Expand Up @@ -148,6 +151,12 @@ export class FileNavigatorContribution extends AbstractViewContribution<FileNavi
@inject(WorkspaceCommandContribution)
protected readonly workspaceCommandContribution: WorkspaceCommandContribution;

@inject(OpenWithService)
protected readonly openWithService: OpenWithService;

@inject(QuickInputService) @optional()
protected readonly quickInputService: QuickInputService;

constructor(
@inject(FileNavigatorPreferences) protected readonly fileNavigatorPreferences: FileNavigatorPreferences,
@inject(OpenerService) protected readonly openerService: OpenerService,
Expand Down Expand Up @@ -293,6 +302,11 @@ export class FileNavigatorContribution extends AbstractViewContribution<FileNavi
});
}
});
registry.registerCommand(FileNavigatorCommands.OPEN_WITH, UriAwareCommandHandler.MonoSelect(this.selectionService, {
isEnabled: uri => this.openWithService.getHandlers(uri).length > 0,
isVisible: uri => this.openWithService.getHandlers(uri).length > 0,
execute: uri => this.openWithService.openWith(uri)
}));
registry.registerCommand(OpenEditorsCommands.CLOSE_ALL_TABS_FROM_TOOLBAR, {
execute: widget => this.withOpenEditorsWidget(widget, () => this.shell.closeMany(this.editorWidgets)),
isEnabled: widget => this.withOpenEditorsWidget(widget, () => true),
Expand Down Expand Up @@ -366,18 +380,11 @@ export class FileNavigatorContribution extends AbstractViewContribution<FileNavi

registry.registerMenuAction(NavigatorContextMenu.NAVIGATION, {
commandId: FileNavigatorCommands.OPEN.id,
label: FileNavigatorCommands.OPEN.label
});
registry.registerSubmenu(NavigatorContextMenu.OPEN_WITH, nls.localizeByDefault('Open With...'));
this.openerService.getOpeners().then(openers => {
for (const opener of openers) {
const openWithCommand = WorkspaceCommands.FILE_OPEN_WITH(opener);
registry.registerMenuAction(NavigatorContextMenu.OPEN_WITH, {
commandId: openWithCommand.id,
label: opener.label,
icon: opener.iconClass
});
}
label: nls.localizeByDefault('Open')
});
registry.registerMenuAction(NavigatorContextMenu.NAVIGATION, {
commandId: FileNavigatorCommands.OPEN_WITH.id,
label: nls.localizeByDefault('Open With...')
});

registry.registerMenuAction(NavigatorContextMenu.CLIPBOARD, {
Expand Down
68 changes: 48 additions & 20 deletions packages/notebook/src/browser/notebook-open-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,56 @@
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************

import { URI, MaybePromise } from '@theia/core';
import { URI, MaybePromise, Disposable } from '@theia/core';
import { NavigatableWidgetOpenHandler, WidgetOpenerOptions } from '@theia/core/lib/browser';
import { inject, injectable } from '@theia/core/shared/inversify';
import { injectable } from '@theia/core/shared/inversify';
import { NotebookFileSelector, NotebookTypeDescriptor } from '../common/notebook-protocol';
import { NotebookTypeRegistry } from './notebook-type-registry';
import { NotebookEditorWidget } from './notebook-editor-widget';
import { match } from '@theia/core/lib/common/glob';
import { NotebookEditorWidgetOptions } from './notebook-editor-widget-factory';

export interface NotebookWidgetOpenerOptions extends WidgetOpenerOptions {
notebookType?: string;
}

@injectable()
export class NotebookOpenHandler extends NavigatableWidgetOpenHandler<NotebookEditorWidget> {

id: string = 'notebook';
readonly id = NotebookEditorWidget.ID;

protected notebookTypes: NotebookTypeDescriptor[] = [];

@inject(NotebookTypeRegistry)
protected notebookTypeRegistry: NotebookTypeRegistry;
registerNotebookType(notebookType: NotebookTypeDescriptor): Disposable {
this.notebookTypes.push(notebookType);
return Disposable.create(() => {
this.notebookTypes.splice(this.notebookTypes.indexOf(notebookType), 1);
});
}

canHandle(uri: URI, options?: NotebookWidgetOpenerOptions): MaybePromise<number> {
if (options?.notebookType) {
return this.canHandleType(uri, this.notebookTypes.find(type => type.type === options.notebookType));
}
return Math.max(...this.notebookTypes.map(type => this.canHandleType(uri, type)));
}

canHandleType(uri: URI, notebookType?: NotebookTypeDescriptor): number {
if (notebookType?.selector && this.matches(notebookType.selector, uri)) {
return this.calculatePriority(notebookType);
} else {
return 0;
}
}

canHandle(uri: URI, options?: WidgetOpenerOptions | undefined): MaybePromise<number> {
const priorities = this.notebookTypeRegistry.notebookTypes
.filter(notebook => notebook.selector && this.matches(notebook.selector, uri))
.map(notebook => this.calculatePriority(notebook));
return Math.max(...priorities);
protected calculatePriority(notebookType: NotebookTypeDescriptor | undefined): number {
if (!notebookType) {
return 0;
}
return notebookType.priority === 'option' ? 100 : 200;
}

protected findHighestPriorityType(uri: URI): NotebookTypeDescriptor | undefined {
const matchingTypes = this.notebookTypeRegistry.notebookTypes
const matchingTypes = this.notebookTypes
.filter(notebookType => notebookType.selector && this.matches(notebookType.selector, uri))
.map(notebookType => ({ descriptor: notebookType, priority: this.calculatePriority(notebookType) }));

Expand All @@ -56,15 +80,19 @@ export class NotebookOpenHandler extends NavigatableWidgetOpenHandler<NotebookEd
return type.descriptor;
}

protected calculatePriority(notebookType: NotebookTypeDescriptor | undefined): number {
if (!notebookType) {
return 0;
}
return notebookType.priority === 'option' ? 100 : 200;
// Override for better options typing
override open(uri: URI, options?: NotebookWidgetOpenerOptions): Promise<NotebookEditorWidget> {
return super.open(uri, options);
}

protected override createWidgetOptions(uri: URI, options?: WidgetOpenerOptions | undefined): NotebookEditorWidgetOptions {
protected override createWidgetOptions(uri: URI, options?: NotebookWidgetOpenerOptions): NotebookEditorWidgetOptions {
const widgetOptions = super.createWidgetOptions(uri, options);
if (options?.notebookType) {
return {
notebookType: options.notebookType,
...widgetOptions
};
}
const notebookType = this.findHighestPriorityType(uri);
if (!notebookType) {
throw new Error('No notebook types registered for uri: ' + uri.toString());
Expand All @@ -75,11 +103,11 @@ export class NotebookOpenHandler extends NavigatableWidgetOpenHandler<NotebookEd
};
}

matches(selectors: readonly NotebookFileSelector[], resource: URI): boolean {
protected matches(selectors: readonly NotebookFileSelector[], resource: URI): boolean {
return selectors.some(selector => this.selectorMatches(selector, resource));
}

selectorMatches(selector: NotebookFileSelector, resource: URI): boolean {
protected selectorMatches(selector: NotebookFileSelector, resource: URI): boolean {
return !!selector.filenamePattern
&& match(selector.filenamePattern, resource.path.name + resource.path.ext);
}
Expand Down
Loading
Loading