Skip to content
Snippets Groups Projects
Commit c8761387 authored by s1995588's avatar s1995588
Browse files

Cleaned up the code by adding sidebar.ts, adding regions to extension.ts, and optimizing imports.

parent c0cd7528
No related branches found
No related tags found
No related merge requests found
import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";
import { LogTraceNotification, SemanticTokensRefreshRequest } from "vscode-languageclient";
import * as vscode from "vscode";
export class AnalysisResultsProvider
implements vscode.TreeDataProvider<Result> {
......
import { pathToFileURL } from 'url';
import { client, provider, modestExecutable, extensionUri } from './extension';
import * as vscode from 'vscode';
import { TextDocumentIdentifier } from 'vscode-languageclient/node';
import { client, extensionUri, modestExecutable } from './extension';
import * as path from "path";
import { LanguageClient, TextDocumentIdentifier } from 'vscode-languageclient/node';
export namespace ModestCommands {
const paramHistory: Map<string, string> = new Map();
......
// tslint:disable
"use strict";
import * as fs from "fs";
import { existsSync } from "fs";
import * as vscode from "vscode";
import {
workspace,
ExtensionContext,
TextDocument,
CancellationToken,
ProviderResult,
ExtensionContext
} from "vscode";
import * as vscode from "vscode";
import {
CancellationTokenSource,
DocumentFormattingParams,
DocumentFormattingRegistrationOptions,
DocumentFormattingRequest,
FormattingOptions,
LanguageClient,
LanguageClientOptions,
NotificationType,
ProgressType,
ProtocolNotificationType,
ProtocolNotificationType0,
ServerOptions,
TextDocumentIdentifier,
TextEdit,
Trace,
TransportKind,
TransportKind
} from "vscode-languageclient/node";
import { ModestCommands } from "./commands";
import { AnalysisResultsProvider, Result } from "./analysisResults";
import * as path from "path";
import { fstat, existsSync } from "fs";
import * as fs from "fs";
import { ModestCommands } from "./commands";
import { getConstants, initializeTools, ModestSidebarProvider } from "./sidebar";
export let client: LanguageClient | undefined;
export let provider: ModestSidebarProvider;
export let analysisResultsProvider: AnalysisResultsProvider;
export let extensionUri:vscode.Uri;
let toolNames: Array<string> | undefined;
let constants: Array<{ uri: string, constants: Array<{ name: string, value: string }> }> = [];
let parameters: Array<{ toolName: string, parameters: Array<{ id: string, value: string, type: ParameterType}> }> = [];
export let extensionUri: vscode.Uri;
interface ParameterDefinitions {
parameterDefinitions: Array<ParameterDefinition>,
}
interface ParameterDefinition {
id: string,
name: string,
description: string,
category: string,
type: ParameterType
isOptional: boolean,
defaultValue: string,
}
interface ParameterType {
valueType: string,
innerType: Array<ParameterType>,
possibleValues: Array<string>,
}
export function modestExecutable(): string | undefined {
let executable: string | undefined = vscode.workspace
......@@ -88,7 +51,6 @@ function createClient(): LanguageClient | undefined {
// TODO: Check if path exists for a better user experience(so it doesn't spam the user with errors)
// The server is implemented in node
//let serverExe = "D:\\Desktop\\designproject\\modest-toolset\\Binaries\\Release\\win-x64\\Modest.LanguageServer.exe";
let serverExe = modestExecutable();
if (serverExe === undefined) {
......@@ -172,8 +134,9 @@ export function activate(context: ExtensionContext) {
context.subscriptions.push(ModestCommands.simCommand);
context.subscriptions.push(ModestCommands.viewDot);
extensionUri=context.extensionUri;
extensionUri = context.extensionUri;
//#region listeners
vscode.workspace.onDidChangeConfiguration((a) => {
if (a.affectsConfiguration("modest.executableLocation")) {
if (client) {
......@@ -197,6 +160,7 @@ export function activate(context: ExtensionContext) {
vscode.workspace.onDidSaveTextDocument(textEditor => {
getConstants(textEditor);
});
//#endregion
provider = new ModestSidebarProvider(context.extensionUri);
analysisResultsProvider = new AnalysisResultsProvider();
......@@ -212,6 +176,7 @@ export function activate(context: ExtensionContext) {
)
);
//#region register commands
vscode.commands.registerCommand(
"analysisResults.copyValue",
(res: Result) => copyToClipboard(res.getValue())
......@@ -236,114 +201,9 @@ export function activate(context: ExtensionContext) {
"analysisResults.export",
() => exportResults(analysisResultsProvider)
);
//#endregion
}
function initializeTools() {
client?.sendRequest<any>("modest/getTools").then(data => {
toolNames = data.availableTools;
provider.sendMessage({
type: "fillTools",
tools: toolNames
});
});
}
function getConstants(document: TextDocument) {
if (document.languageId === "modest") {
if (document.uri) {
let uri = document.uri.toString();
let jsonObject = { "textDocument": TextDocumentIdentifier.create(uri) };
client?.sendRequest<Array<string>>("modest/getConstants", jsonObject).then(data => {
const index = constants.findIndex(x => x.uri === uri);
const newConstants = data.map(constant => {
return { name: constant, value: "" };
});
if (index === -1) {
constants.push({ "uri": uri, constants: newConstants });
} else {
constants[index].constants = newConstants;
}
provider.sendMessage({
type: "updateConstants",
constants: constants,
"uri": uri
});
});
}
}
}
function getParameters(toolName: string) {
let jsonObject = { "toolName": toolName };
client?.sendRequest<ParameterDefinitions>("modest/getParameters", jsonObject).then(data => {
const index = parameters.findIndex(x => x.toolName === toolName);
const newParameters = data.parameterDefinitions.map(parameter => {
return { id: parameter.id, value: parameter.defaultValue, type: parameter.type };
});
if (index === -1) {
parameters.push({ toolName: toolName, parameters: newParameters });
} else {
parameters[index].parameters = newParameters;
}
provider.sendMessage({
type: "updateParameters",
parameters: parameters,
toolName: toolName
});
});
}
interface ProgressIndication {
message: string,
progress: number
}
interface ResultNotification {
progressToken: string,
data: string
}
function runTool(uri: string, toolName: string, constants: { name: string; value: string; }[], suppliedParameters: { id: string; value: string; }[]) {
const toolIndex = parameters.findIndex(x => x.toolName === toolName);
let serverParameters: Array<{ id: string, value: string}> = [];
if (toolIndex !== -1) {
for (const parameter of suppliedParameters) {
const parameterIndex = parameters[toolIndex].parameters.findIndex(x => x.id === parameter.id);
if (parameterIndex !== -1) {
if (parameters[toolIndex].parameters[parameterIndex].value !== parameter.value) {
serverParameters.push(parameter);
}
}
}
}
let jsonObject = {
textDocument: TextDocumentIdentifier.create(uri),
toolName: toolName,
constants: constants,
parameters: serverParameters,
progressToken: uri + toolName + constants + serverParameters + Date.now()
};
vscode.window.activeTextEditor?.document.save();
vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, cancellable: false, title: "Running " + toolName }, async (progress, token) => {
await new Promise<null>(async (resolve, _) => {
let progressHandler = client?.onProgress(new ProgressType<ProgressIndication>(), jsonObject.progressToken, indication => {
progress.report({ message: indication.message, increment: indication.progress * 100 });
});
let resultHandler = client?.onNotification(new NotificationType<ResultNotification>("modest/toolResult"), data => {
if (data.progressToken === jsonObject.progressToken) {
analysisResultsProvider.setJsonString(data.data);
progressHandler?.dispose();
resultHandler?.dispose();
resolve(null);
}
});
await client?.sendRequest<string>("modest/runTool", jsonObject, token);
});
});
}
export function deactivate(): Thenable<void> | undefined {
if (!client) {
return undefined;
......@@ -351,6 +211,7 @@ export function deactivate(): Thenable<void> | undefined {
return client.stop();
}
//#region analysis results functions
function copyToClipboard(text: string) {
vscode.env.clipboard.writeText(text);
vscode.window.showInformationMessage(`Copied ${text} to clipboard.`);
......@@ -436,125 +297,4 @@ function pathExists(p: string): boolean {
}
return true;
}
class ModestSidebarProvider implements vscode.WebviewViewProvider {
public static readonly viewType = "modest.modestSidebar";
private _view?: vscode.WebviewView;
constructor(private readonly _extensionUri: vscode.Uri) { }
resolveWebviewView(
webviewView: vscode.WebviewView,
context: vscode.WebviewViewResolveContext<unknown>,
token: vscode.CancellationToken
): void | Thenable<void> {
this._view = webviewView;
webviewView.webview.options = {
// Allow scripts in the webview
enableScripts: true,
localResourceRoots: [this._extensionUri],
};
webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);
webviewView.webview.onDidReceiveMessage(data => {
console.log(data);
switch (data.type) {
case 'init': {
if (toolNames) {
provider.sendMessage({
type: "fillTools",
tools: toolNames
});
}
if (constants) {
provider.sendMessage({
type: "updateConstants",
constants: constants
});
}
break;
}
case 'toolSelected': {
getParameters(data.toolName);
break;
}
case 'runTool': {
runTool(data.uri, data.toolName, data.constants, data.parameters);
break;
}
}
});
}
/**
* sendMessage
*/
public sendMessage(message: any) {
this._view?.show(true);
this._view?.webview?.postMessage(message);
}
private _getHtmlForWebview(webview: vscode.Webview) {
// Get the local path to main script run in the webview, then convert it to a uri we can use in the webview.
const scriptUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, "media", "main.js")
);
// Do the same for the stylesheet.
const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'reset.css'));
const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'vscode.css'));
const styleMainUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'main.css'));
const styleCodicons = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'node_modules', 'vscode-codicons', 'dist', 'codicon.css'));
const fontCodicons = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'node_modules', 'vscode-codicons', 'dist', 'codicon.ttf'));
// Use a nonce to only allow a specific script to be run.
const nonce = getNonce();
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${fontCodicons}; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${styleResetUri}" rel="stylesheet">
<link href="${styleVSCodeUri}" rel="stylesheet">
<link href="${styleMainUri}" rel="stylesheet">
<link href="${styleCodicons}" rel="stylesheet">
<title>Modest run dialog</title>
</head>
<body>
<h3>Select tool</h3>
<div id="run-box">
<select class="tools-dropdown" id="tools"> </select>
<button id="run-button"><i class="codicon codicon-play"></i></button>
</div>
<h3>Open constants</h3>
<ul class="option-list" id="constants">There are no undefined constants.</ul>
<h3>Parameters</h3>
<ul class="option-list" id="parameters">There are no parameters.</ul>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
function getNonce() {
let text = "";
const possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++) {
text += possible.charAt(
Math.floor(Math.random() * possible.length)
);
}
return text;
}
}
}
//#endregion
\ No newline at end of file
import * as vscode from "vscode";
import {
TextDocument
} from "vscode";
import {
NotificationType,
ProgressType,
TextDocumentIdentifier
} from "vscode-languageclient/node";
import { analysisResultsProvider, client, provider } from './extension';
export let toolNames: Array<string> | undefined;
export let constants: Array<{ uri: string, constants: Array<{ name: string, value: string }> }> = [];
export let parameters: Array<{ toolName: string, parameters: Array<{ id: string, value: string, type: ParameterType, category: string }> }> = [];
//#region interfaces
interface ParameterDefinitions {
parameterDefinitions: Array<ParameterDefinition>,
}
interface ParameterDefinition {
id: string,
name: string,
description: string,
category: string,
type: ParameterType
isOptional: boolean,
defaultValue: string,
}
interface ParameterType {
valueType: string,
innerType: Array<ParameterType>,
possibleValues: Array<string>,
}
interface ProgressIndication {
message: string,
progress: number
}
interface ResultNotification {
progressToken: string,
data: string
}
//#endregion
export function initializeTools() {
client?.sendRequest<any>("modest/getTools").then(data => {
toolNames = data.availableTools;
provider.sendMessage({
type: "fillTools",
tools: toolNames
});
});
}
export function getConstants(document: TextDocument) {
if (document.languageId === "modest") {
if (document.uri) {
let uri = document.uri.toString();
let jsonObject = { "textDocument": TextDocumentIdentifier.create(uri) };
client?.sendRequest<Array<string>>("modest/getConstants", jsonObject).then(data => {
const index = constants.findIndex(x => x.uri === uri);
const newConstants = data.map(constant => {
return { name: constant, value: "" };
});
if (index === -1) {
constants.push({ "uri": uri, constants: newConstants });
} else {
constants[index].constants = newConstants;
}
provider.sendMessage({
type: "updateConstants",
constants: constants,
"uri": uri
});
});
}
}
}
function getParameters(toolName: string) {
let jsonObject = { "toolName": toolName };
client?.sendRequest<ParameterDefinitions>("modest/getParameters", jsonObject).then(data => {
const index = parameters.findIndex(x => x.toolName === toolName);
const newParameters = data.parameterDefinitions.map(parameter => {
return { id: parameter.id, value: parameter.defaultValue, type: parameter.type, category: parameter.category };
});
if (index === -1) {
parameters.push({ toolName: toolName, parameters: newParameters });
} else {
parameters[index].parameters = newParameters;
}
provider.sendMessage({
type: "updateParameters",
parameters: parameters,
toolName: toolName
});
});
}
function runTool(uri: string, toolName: string, constants: { name: string; value: string; }[], suppliedParameters: { id: string; value: string; }[]) {
const toolIndex = parameters.findIndex(x => x.toolName === toolName);
let serverParameters: Array<{ id: string, value: string }> = [];
if (toolIndex !== -1) {
for (const parameter of suppliedParameters) {
const parameterIndex = parameters[toolIndex].parameters.findIndex(x => x.id === parameter.id);
if (parameterIndex !== -1) {
if (parameters[toolIndex].parameters[parameterIndex].value !== parameter.value) {
serverParameters.push(parameter);
}
}
}
}
let jsonObject = {
textDocument: TextDocumentIdentifier.create(uri),
toolName: toolName,
constants: constants,
parameters: serverParameters,
progressToken: uri + toolName + constants + serverParameters + Date.now()
};
vscode.window.activeTextEditor?.document.save();
vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, cancellable: false, title: "Running " + toolName }, async (progress, token) => {
await new Promise<null>(async (resolve, _) => {
let progressHandler = client?.onProgress(new ProgressType<ProgressIndication>(), jsonObject.progressToken, indication => {
progress.report({ message: indication.message, increment: indication.progress * 100 });
});
let resultHandler = client?.onNotification(new NotificationType<ResultNotification>("modest/toolResult"), data => {
if (data.progressToken === jsonObject.progressToken) {
analysisResultsProvider.setJsonString(data.data);
progressHandler?.dispose();
resultHandler?.dispose();
resolve(null);
}
});
await client?.sendRequest<string>("modest/runTool", jsonObject, token);
});
});
}
export class ModestSidebarProvider implements vscode.WebviewViewProvider {
public static readonly viewType = "modest.modestSidebar";
private _view?: vscode.WebviewView;
constructor(private readonly _extensionUri: vscode.Uri) { }
resolveWebviewView(
webviewView: vscode.WebviewView,
context: vscode.WebviewViewResolveContext<unknown>,
token: vscode.CancellationToken
): void | Thenable<void> {
this._view = webviewView;
webviewView.webview.options = {
// Allow scripts in the webview
enableScripts: true,
localResourceRoots: [this._extensionUri],
};
webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);
webviewView.webview.onDidReceiveMessage(data => {
console.log(data);
switch (data.type) {
case 'init': {
if (toolNames) {
provider.sendMessage({
type: "fillTools",
tools: toolNames
});
}
if (constants) {
provider.sendMessage({
type: "updateConstants",
constants: constants
});
}
break;
}
case 'toolSelected': {
getParameters(data.toolName);
break;
}
case 'runTool': {
runTool(data.uri, data.toolName, data.constants, data.parameters);
break;
}
}
});
}
/**
* sendMessage
* @param {any} message
*/
public sendMessage(message: any) {
this._view?.show(true);
this._view?.webview?.postMessage(message);
}
private _getHtmlForWebview(webview: vscode.Webview) {
// Get the local path to main script run in the webview, then convert it to a uri we can use in the webview.
const scriptUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, "media", "main.js")
);
// Do the same for the stylesheet.
const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'reset.css'));
const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'vscode.css'));
const styleMainUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'main.css'));
const styleCodicons = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'node_modules', 'vscode-codicons', 'dist', 'codicon.css'));
const fontCodicons = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'node_modules', 'vscode-codicons', 'dist', 'codicon.ttf'));
// Use a nonce to only allow a specific script to be run.
const nonce = getNonce();
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${fontCodicons}; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${styleResetUri}" rel="stylesheet">
<link href="${styleVSCodeUri}" rel="stylesheet">
<link href="${styleMainUri}" rel="stylesheet">
<link href="${styleCodicons}" rel="stylesheet">
<title>Modest run dialog</title>
</head>
<body>
<h3>Select tool</h3>
<div id="run-box">
<select class="tools-dropdown" id="tools"> </select>
<button id="run-button"><i class="codicon codicon-play"></i></button>
</div>
<h3>Open constants</h3>
<ul class="option-list" id="constants">There are no undefined constants.</ul>
<h3>Parameters</h3>
<ul class="option-list" id="parameters">There are no parameters.</ul>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
function getNonce() {
let text = "";
const possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++) {
text += possible.charAt(
Math.floor(Math.random() * possible.length)
);
}
return text;
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment