Skip to content

Refactor globalVars into a Separate Class for Improved Encapsulation #310

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

Merged
merged 1 commit into from
Oct 30, 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
10 changes: 5 additions & 5 deletions vscode/src/commands/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@
limitations under the License.
*/
import { commands, window } from "vscode";
import { globalVars } from "../extension";
import { builtInCommands, extCommands } from "./commands";
import { ICommand } from "./types";
import { l10n } from "../localiser";
import * as fs from 'fs';
import * as path from 'path';
import { globalState } from "../globalState";

const deleteCache = async () => {
// TODO: Change workspace path to userdir path
const storagePath = globalVars.extensionInfo.getWorkspaceStorage()?.fsPath;
const storagePath = globalState.getExtensionContextInfo().getWorkspaceStorage()?.fsPath;
if (!storagePath) {
window.showErrorMessage(l10n.value("jdk.extension.cache.error_msg.cannotFindWrkSpacePath"));
return;
Expand All @@ -38,9 +38,9 @@ const deleteCache = async () => {
if (confirmation === yes) {
const reloadWindowActionLabel = l10n.value("jdk.extension.cache.label.reloadWindow");
try {
await globalVars.clientPromise.stopClient();
globalVars.deactivated = true;
await globalVars.nbProcessManager?.killProcess(false);
await globalState.getClientPromise().stopClient();
globalState.setDeactivated(true);
await globalState.getNbProcessManager()?.killProcess(false);
await fs.promises.rmdir(userDir, { recursive: true });
await window.showInformationMessage(l10n.value("jdk.extension.message.cacheDeleted"), reloadWindowActionLabel);
} catch (err) {
Expand Down
6 changes: 3 additions & 3 deletions vscode/src/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ import { l10n } from "../localiser";
import * as os from 'os';
import * as fs from 'fs';
import { ICommand } from "./types";
import { globalVars } from "../extension";
import { getContextUri, isNbCommandRegistered } from "./utils";
import { isString } from "../utils";
import { globalState } from "../globalState";

const newFromTemplate = async (ctx: any, template: any) => {
const client: LanguageClient = await globalVars.clientPromise.client;
const client: LanguageClient = await globalState.getClientPromise().client;
if (await isNbCommandRegistered(nbCommands.newFromTemplate)) {
const workspaces = workspace.workspaceFolders;

Expand Down Expand Up @@ -72,7 +72,7 @@ const newFromTemplate = async (ctx: any, template: any) => {
}

const newProject = async (ctx: any) => {
const client: LanguageClient = await globalVars.clientPromise.client;
const client: LanguageClient = await globalState.getClientPromise().client;
if (await isNbCommandRegistered(nbCommands.newProject)) {
const res = await commands.executeCommand(nbCommands.newProject, getContextUri(ctx)?.toString());
if (isString(res)) {
Expand Down
4 changes: 2 additions & 2 deletions vscode/src/commands/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ import { l10n } from "../localiser";
import * as path from 'path';
import { ICommand } from "./types";
import { LanguageClient } from "vscode-languageclient/node";
import { globalVars } from "../extension";
import { LOGGER } from '../logger';
import { getContextUri, isNbCommandRegistered, wrapCommandWithProgress } from "./utils";
import { globalState } from "../globalState";

const goToTest = async (ctx: any) => {
let client: LanguageClient = await globalVars.clientPromise.client;
let client: LanguageClient = await globalState.getClientPromise().client;
if (await isNbCommandRegistered(nbCommands.goToTest)) {
try {
const res: any = await commands.executeCommand(nbCommands.goToTest, getContextUri(ctx)?.toString());
Expand Down
8 changes: 4 additions & 4 deletions vscode/src/commands/refactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import { ICommand } from "./types";
import { extConstants } from "../constants";
import { builtInCommands, extCommands, nbCommands } from "./commands";
import { l10n } from "../localiser";
import { globalVars } from "../extension";
import { WorkspaceEdit } from 'vscode-languageserver-protocol';
import { SymbolInformation } from 'vscode-languageclient';
import { globalState } from "../globalState";

const goToSuperImplementationHandler = async () => {
if (window.activeTextEditor?.document.languageId !== extConstants.LANGUAGE_ID) {
Expand Down Expand Up @@ -48,7 +48,7 @@ const surroundWithHandler = async (items: any) => {
const selected: any = await window.showQuickPick(items, { placeHolder: l10n.value('jdk.extension.command.quickPick.placeholder.surroundWith') });
if (selected) {
if (selected.userData.edit) {
const client = await globalVars.clientPromise.client;
const client = await globalState.getClientPromise().client;
const edit = await client.protocol2CodeConverter.asWorkspaceEdit(selected.userData.edit as WorkspaceEdit);
await workspace.applyEdit(edit);
await commands.executeCommand(builtInCommands.focusActiveEditorGroup);
Expand All @@ -60,7 +60,7 @@ const surroundWithHandler = async (items: any) => {
const codeGenerateHandler = async (command: any, data: any) => {
const edit: any = await commands.executeCommand(command, data);
if (edit) {
const client = await globalVars.clientPromise.client;
const client = await globalState.getClientPromise().client;
const wsEdit = await client.protocol2CodeConverter.asWorkspaceEdit(edit as WorkspaceEdit);
await workspace.applyEdit(wsEdit);
await commands.executeCommand(builtInCommands.focusActiveEditorGroup);
Expand All @@ -76,7 +76,7 @@ const completeAbstractMethodsHandler = async () => {
}

const workspaceSymbolsHandler = async (query: any) => {
const client = await globalVars.clientPromise.client;
const client = await globalState.getClientPromise().client;
return (await client.sendRequest<SymbolInformation[]>("workspace/symbol", { "query": query })) ?? [];
}

Expand Down
4 changes: 2 additions & 2 deletions vscode/src/commands/runConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@
*/

import { extCommands } from "./commands";
import { globalVars } from "../extension";
import { configureRunSettings } from "../views/runConfiguration";
import { ICommand } from "./types";
import { globalState } from "../globalState";


const configureRunSettingsHandler = (...params: any[]) => {
configureRunSettings(globalVars.extensionInfo.getExtensionContext(), params);
configureRunSettings(globalState.getExtensionContextInfo().getExtensionContext(), params);
}


Expand Down
11 changes: 3 additions & 8 deletions vscode/src/commands/utilCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,16 @@
See the License for the specific language governing permissions and
limitations under the License.
*/
import { globalVars } from "../extension";
import { globalState } from "../globalState";
import { extCommands } from "./commands";
import { ICommand } from "./types";

const startupConditionHandler = () => {
return globalVars.clientPromise.client;
return globalState.getClientPromise().client;
}

const addEventListenerHandler = async (eventName: any, listener: any) => {
let ls = globalVars.listeners.get(eventName);
if (!ls) {
ls = [];
globalVars.listeners.set(eventName, ls);
}
ls.push(listener);
globalState.addListener(eventName, listener);
}


Expand Down
4 changes: 2 additions & 2 deletions vscode/src/commands/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import { commands, OutputChannel, ProgressLocation, Uri, window } from "vscode";
import { nbCommands } from "./commands";
import { ProjectActionParams } from "../lsp/protocol";
import { LanguageClient } from "vscode-languageclient/node";
import { globalVars } from "../extension";
import { l10n } from "../localiser";
import { LOGGER } from "../logger";
import { globalState } from "../globalState";

export const getContextUri = (ctx: any): Uri | undefined => {
if (ctx?.fsPath) {
Expand Down Expand Up @@ -78,7 +78,7 @@ export const wrapProjectActionWithProgress = (action: string, configuration: str
export const wrapCommandWithProgress = (lsCommand: string, title: string, log?: OutputChannel, ...args: any[]): Thenable<unknown> => {
return window.withProgress({ location: ProgressLocation.Window }, p => {
return new Promise(async (resolve, reject) => {
let c: LanguageClient = await globalVars.clientPromise.client;
let c: LanguageClient = await globalState.getClientPromise().client;
if (await isNbCommandRegistered(lsCommand)) {
p.report({ message: title });
c.outputChannel.show(true);
Expand Down
7 changes: 4 additions & 3 deletions vscode/src/configurations/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ import { ConfigurationTarget, extensions, workspace, WorkspaceConfiguration } fr
import { builtInConfigKeys, configKeys } from "./configuration";
import { extConstants, NODE_WINDOWS_LABEL } from "../constants";
import * as os from 'os';
import { globalVars } from "../extension";
import { LOGGER } from "../logger";
import * as path from 'path';
import * as fs from 'fs';
import { globalState } from "../globalState";

export const getConfiguration = (key: string = extConstants.COMMAND_PREFIX): WorkspaceConfiguration => {
return workspace.getConfiguration(key);
Expand Down Expand Up @@ -114,11 +114,12 @@ export const isDarkColorThemeHandler = (): boolean => {
}

export const userdirHandler = (): string => {
const extensionContextInfo = globalState.getExtensionContextInfo();
const userdirScope = process.env['nbcode_userdir'] || getConfigurationValue(configKeys.userdir, "local");
const workspaceStoragePath = globalVars.extensionInfo.getWorkspaceStorage()?.fsPath;
const workspaceStoragePath = extensionContextInfo.getWorkspaceStorage()?.fsPath;
const userdirParentDir = userdirScope === "local" && workspaceStoragePath
? workspaceStoragePath
: globalVars.extensionInfo.getGlobalStorage().fsPath;
: extensionContextInfo.getGlobalStorage().fsPath;

if (!userdirParentDir) {
throw new Error(`Cannot create path for ${userdirScope} directory.`);
Expand Down
4 changes: 2 additions & 2 deletions vscode/src/configurations/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
*/

import { ConfigurationChangeEvent, ExtensionContext, workspace } from "vscode";
import { globalVars } from "../extension";
import { userConfigsListened } from "./configuration";
import { Disposable } from "vscode-languageclient";
import { globalState } from "../globalState";

const configChangeHandler = (params: ConfigurationChangeEvent) => {
userConfigsListened.forEach((config: string) => {
const doesAffect = params.affectsConfiguration(config);
if (doesAffect) {
globalVars.clientPromise.restartExtension(globalVars.nbProcessManager, true);
globalState.getClientPromise().restartExtension(globalState.getNbProcessManager(), true);
}
});
}
Expand Down
17 changes: 9 additions & 8 deletions vscode/src/debugger/debugger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ import { DebugConnector } from '../lsp/protocol';
import { extConstants } from '../constants';
import { l10n } from '../localiser';
import { StreamDebugAdapter } from './streamDebugAdapter';
import { globalVars } from '../extension';
import { extCommands, nbCommands } from '../commands/commands';
import { argumentsNode, environmentVariablesNode, vmOptionsNode, workingDirectoryNode } from '../views/runConfiguration';
import { initializeRunConfiguration } from '../utils';
import { globalState } from '../globalState';

export function registerDebugger(context: ExtensionContext): void {
let debugTrackerFactory = new NetBeansDebugAdapterTrackerFactory();
Expand All @@ -50,8 +50,9 @@ class NetBeansDebugAdapterTrackerFactory implements vscode.DebugAdapterTrackerFa
createDebugAdapterTracker(_session: vscode.DebugSession): vscode.ProviderResult<vscode.DebugAdapterTracker> {
return {
onDidSendMessage(message: any): void {
if (globalVars.testAdapter && message.type === 'event' && message.event === 'output') {
globalVars.testAdapter.testOutput(message.body.output);
const testAdapter = globalState.getTestAdapter();
if (testAdapter && message.type === 'event' && message.event === 'output') {
testAdapter.testOutput(message.body.output);
}
}
}
Expand All @@ -64,18 +65,18 @@ class NetBeansDebugAdapterDescriptionFactory implements vscode.DebugAdapterDescr
return new Promise<vscode.DebugAdapterDescriptor>((resolve, reject) => {
let cnt = 10;
const fnc = () => {
if (globalVars.debugPort < 0) {
if (globalState.getDebugPort() < 0) {
if (cnt-- > 0) {
setTimeout(fnc, 1000);
} else {
reject(new Error(l10n.value('jdk.extension.debugger.error_msg.debugAdapterNotInitialized')));
}
} else {
// resolve(new vscode.DebugAdapterServer(debugPort));
const socket = net.connect(globalVars.debugPort, "127.0.0.1", () => { });
const socket = net.connect(globalState.getDebugPort(), "127.0.0.1", () => { });
socket.on("connect", () => {
const adapter = new StreamDebugAdapter();
socket.write(globalVars.debugHash ? globalVars.debugHash : "");
socket.write(globalState?.getDebugHash() || "");
adapter.connect(socket, socket);
resolve(new vscode.DebugAdapterInlineImplementation(adapter));
});
Expand All @@ -94,7 +95,7 @@ class NetBeansConfigurationInitialProvider implements vscode.DebugConfigurationP
}

async doProvideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, _token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration[]> {
let c: LanguageClient = await globalVars.clientPromise.client;
let c: LanguageClient = await globalState.getClientPromise().client;
if (!folder) {
return [];
}
Expand Down Expand Up @@ -145,7 +146,7 @@ class NetBeansConfigurationDynamicProvider implements vscode.DebugConfigurationP
}

async doProvideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, context: ExtensionContext, commandValues: Map<string, string>, _token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration[]> {
let c: LanguageClient = await globalVars.clientPromise.client;
let c: LanguageClient = await globalState.getClientPromise().client;
if (!folder) {
return [];
}
Expand Down
37 changes: 9 additions & 28 deletions vscode/src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates.
* Copyright (c) 2024, Oracle and/or its affiliates.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
Expand All @@ -19,44 +19,25 @@
* under the License.
*/

/* This file has been modified for Oracle Java SE extension */

'use strict';

import { ExtensionContext, TextEditorDecorationType, Uri } from 'vscode';
import { NbTestAdapter } from './views/TestViewController';
import { SetTextEditorDecorationParams } from './lsp/protocol';
import { ExtensionContext } from 'vscode';
import * as launchConfigurations from './launchConfigurations';
import { extConstants } from './constants';
import { ExtensionInfo } from './extensionInfo';
import { ClientPromise } from './lsp/clientPromise';
import { NbProcessManager } from './lsp/nbProcessManager';
import { clientInit } from './lsp/initializer';
import { subscribeCommands } from './commands/register';
import { VSNetBeansAPI } from './lsp/types';
import { registerDebugger } from './debugger/debugger';
import { registerConfigChangeListeners } from './configurations/listener';
import { registerFileProviders } from './lsp/listeners/textDocumentContentProvider';

export namespace globalVars {
export const listeners = new Map<string, string[]>();
export let extensionInfo: ExtensionInfo;
export let clientPromise: ClientPromise;
export let debugPort: number = -1;
export let debugHash: string | undefined;
export let deactivated: boolean = true;
export let nbProcessManager: NbProcessManager | null;
export let testAdapter: NbTestAdapter | undefined;
export let decorations = new Map<string, TextEditorDecorationType>();
export let decorationParamsByUri = new Map<Uri, SetTextEditorDecorationParams>();
}

import { ExtensionContextInfo } from './extensionContextInfo';
import { ClientPromise } from './lsp/clientPromise';
import { globalState } from './globalState';

export function activate(context: ExtensionContext): VSNetBeansAPI {
globalVars.clientPromise = new ClientPromise();
globalVars.extensionInfo = new ExtensionInfo(context);
globalState.initialize(new ExtensionContextInfo(context), new ClientPromise());
globalState.getClientPromise().initialize();

globalVars.clientPromise.initialize();
registerConfigChangeListeners(context);
clientInit();

Expand All @@ -78,10 +59,10 @@ export function activate(context: ExtensionContext): VSNetBeansAPI {


export function deactivate(): Thenable<void> {
const process = globalVars.nbProcessManager?.getProcess();
const process = globalState.getNbProcessManager()?.getProcess();
if (process != null) {
process?.kill();
}
return globalVars.clientPromise.stopClient();
return globalState.getClientPromise().stopClient();
}

Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/
import { Disposable, ExtensionContext } from "vscode";

export class ExtensionInfo {
export class ExtensionContextInfo {
constructor(private context: ExtensionContext) { }

getGlobalStorage = () => this.context.globalStorageUri;
Expand Down
Loading