Skip to content
This repository has been archived by the owner on Dec 23, 2021. It is now read-only.

Commit

Permalink
File dropdown on simulator (#127)
Browse files Browse the repository at this point in the history
PBI: 32819 
Task: 32687

* Get backend working for select file to play

* Make dropdown work and look better

* make dropdown work for high contrast

* Fix some UI from review

* remove log statement

* Address comments
  • Loading branch information
LukeSlev authored Aug 20, 2019
1 parent 0ae9c00 commit 442569c
Show file tree
Hide file tree
Showing 8 changed files with 247 additions and 94 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,6 @@
"css-loader": "^1.0.0",
"del": "^4.0.0",
"event-stream": "^4.0.1",
"glob": "^7.1.4",
"gulp": "^4.0.2",
"gulp-cli": "^2.1.0",
"gulp-filter": "^5.1.0",
Expand Down Expand Up @@ -310,6 +309,7 @@
"compare-versions": "^3.5.1",
"eventemitter2": "^5.0.1",
"open": "^6.4.0",
"glob": "^7.1.4",
"os": "^0.1.1",
"react": "^16.8.6",
"react-dom": "^16.8.6",
Expand Down
108 changes: 56 additions & 52 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ function loadScript(context: vscode.ExtensionContext, scriptPath: string) {
.toString()}"></script>`;
}

const setPathAndSendMessage = (currentPanel: vscode.WebviewPanel, newFilePath: string) => {
currentFileAbsPath = newFilePath;
currentPanel.webview.postMessage({
command: "current-file",
state: { running_file: newFilePath }
});
}

// Extension activation
export async function activate(context: vscode.ExtensionContext) {
console.info(CONSTANTS.INFO.EXTENSION_ACTIVATED);
Expand All @@ -49,6 +57,7 @@ export async function activate(context: vscode.ExtensionContext) {
let currentPanel: vscode.WebviewPanel | undefined;
let childProcess: cp.ChildProcess | undefined;
let messageListener: vscode.Disposable;
let activeEditorListener: vscode.Disposable;

// Add our library path to settings.json for autocomplete functionality
updatePythonExtraPaths();
Expand All @@ -70,20 +79,18 @@ export async function activate(context: vscode.ExtensionContext) {
);
}

vscode.workspace.onDidSaveTextDocument(
async (document: vscode.TextDocument) => {
await updateCurrentFileIfPython(document);
}
);
vscode.workspace.onDidSaveTextDocument(async (document: vscode.TextDocument) => {
await updateCurrentFileIfPython(document, currentPanel);
});

const openWebview = () => {
if (currentPanel) {
currentPanel.reveal(vscode.ViewColumn.Two);
currentPanel.reveal(vscode.ViewColumn.Beside);
} else {
currentPanel = vscode.window.createWebviewPanel(
"adafruitSimulator",
CONSTANTS.LABEL.WEBVIEW_PANEL,
{ preserveFocus: true, viewColumn: vscode.ViewColumn.Two },
{ preserveFocus: true, viewColumn: vscode.ViewColumn.Beside },
{
// Only allow the webview to access resources in our extension's media directory
localResourceRoots: [
Expand All @@ -103,6 +110,14 @@ export async function activate(context: vscode.ExtensionContext) {
}
}

if (activeEditorListener !== undefined) {
activeEditorListener.dispose();
const index = context.subscriptions.indexOf(activeEditorListener);
if (index > -1) {
context.subscriptions.splice(index, 1);
}
}

if (currentPanel) {
// Handle messages from webview
messageListener = currentPanel.webview.onDidReceiveMessage(
Expand All @@ -121,10 +136,15 @@ export async function activate(context: vscode.ExtensionContext) {
break;
case WebviewMessages.PLAY_SIMULATOR:
console.log(`Play button ${messageJson} \n`);
if (message.text as boolean) {
telemetryAI.trackFeatureUsage(
TelemetryEventName.COMMAND_RUN_SIMULATOR_BUTTON
);
if (message.text.state as boolean) {
setPathAndSendMessage(currentPanel, message.text.selected_file);
if (currentFileAbsPath) {
const foundDocument = utils.getActiveEditorFromPath(currentFileAbsPath);
if (foundDocument !== undefined) {
currentTextDocument = foundDocument;
}
}
telemetryAI.trackFeatureUsage(TelemetryEventName.COMMAND_RUN_SIMULATOR_BUTTON);
runSimulatorCommand();
} else {
killProcessIfRunning();
Expand Down Expand Up @@ -156,6 +176,9 @@ export async function activate(context: vscode.ExtensionContext) {
undefined,
context.subscriptions
);

activeEditorListener = utils.addVisibleTextEditorCallback(currentPanel, context);
console.log("sent");
}

currentPanel.onDidDispose(
Expand Down Expand Up @@ -305,14 +328,15 @@ export async function activate(context: vscode.ExtensionContext) {

killProcessIfRunning();

await updateCurrentFileIfPython(vscode.window.activeTextEditor!.document);
await updateCurrentFileIfPython(vscode.window.activeTextEditor!.document, currentPanel);

if (currentFileAbsPath === "") {
utils.logToOutputChannel(
outChannel,
CONSTANTS.ERROR.NO_FILE_TO_RUN,
true
);
utils.logToOutputChannel(outChannel, CONSTANTS.ERROR.NO_FILE_TO_RUN, true);
vscode.window
.showErrorMessage(
CONSTANTS.ERROR.NO_FILE_TO_RUN,
DialogResponses.MESSAGE_UNDERSTOOD
)
} else {
// Save on run
await currentTextDocument.save();
Expand Down Expand Up @@ -389,7 +413,7 @@ export async function activate(context: vscode.ExtensionContext) {
case "print":
console.log(
`Process print statement output = ${
messageToWebview.data
messageToWebview.data
}`
);
utils.logToOutputChannel(
Expand Down Expand Up @@ -456,14 +480,15 @@ export async function activate(context: vscode.ExtensionContext) {

utils.logToOutputChannel(outChannel, CONSTANTS.INFO.DEPLOY_DEVICE);

await updateCurrentFileIfPython(vscode.window.activeTextEditor!.document);
await updateCurrentFileIfPython(vscode.window.activeTextEditor!.document, currentPanel);

if (currentFileAbsPath === "") {
utils.logToOutputChannel(
outChannel,
CONSTANTS.ERROR.NO_FILE_TO_RUN,
true
);
utils.logToOutputChannel(outChannel, CONSTANTS.ERROR.NO_FILE_TO_RUN, true);
vscode.window
.showErrorMessage(
CONSTANTS.ERROR.NO_FILE_TO_RUN,
DialogResponses.MESSAGE_UNDERSTOOD
);
} else if (!utils.validCodeFileName(currentFileAbsPath)) {
// Save on run
await currentTextDocument.save();
Expand Down Expand Up @@ -698,40 +723,19 @@ const getActivePythonFile = () => {
return activeEditor ? activeEditor.document.fileName : "";
};

const getFileFromFilePicker = () => {
const options: vscode.OpenDialogOptions = {
canSelectMany: false,
filters: {
"All files": ["*"],
"Python files": ["py"]
},
openLabel: "Run File"
};

return vscode.window.showOpenDialog(options).then(async fileUri => {
if (fileUri && fileUri[0] && fileUri[0].fsPath.endsWith(".py")) {
console.log(`Selected file: ${fileUri[0].fsPath}`);
currentTextDocument = await vscode.workspace.openTextDocument(fileUri[0]);
return fileUri[0].fsPath;
}
});
};

const updateCurrentFileIfPython = async (
activeTextDocument: vscode.TextDocument | undefined
activeTextDocument: vscode.TextDocument | undefined,
currentPanel: vscode.WebviewPanel
) => {
if (activeTextDocument && activeTextDocument.languageId === "python") {
currentFileAbsPath = activeTextDocument.fileName;
setPathAndSendMessage(currentPanel, activeTextDocument.fileName);
currentTextDocument = activeTextDocument;
} else if (currentFileAbsPath === "") {
currentFileAbsPath =
getActivePythonFile() || (await getFileFromFilePicker()) || "";
setPathAndSendMessage(currentPanel,
getActivePythonFile() || "");
}
if (currentFileAbsPath) {
await vscode.window.showTextDocument(
currentTextDocument,
vscode.ViewColumn.One
);
if (utils.getActiveEditorFromPath(currentTextDocument.fileName) === undefined) {
await vscode.window.showTextDocument(currentTextDocument, vscode.ViewColumn.One);
}
};

Expand Down
83 changes: 49 additions & 34 deletions src/extension_utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,7 @@ import * as fs from "fs";
import * as path from "path";
import { DependencyChecker } from "./dependencyChecker";
import { DeviceContext } from "../deviceContext";
import {
ExtensionContext,
MessageItem,
OutputChannel,
Uri,
window,
workspace
} from "vscode";
import * as vscode from "vscode";
import {
CONSTANTS,
CPX_CONFIG_FILE,
Expand All @@ -24,11 +17,11 @@ import { CPXWorkspace } from "../cpxWorkspace";

// tslint:disable-next-line: export-name
export const getPathToScript = (
context: ExtensionContext,
context: vscode.ExtensionContext,
folderName: string,
fileName: string
) => {
const onDiskPath = Uri.file(
const onDiskPath = vscode.Uri.file(
path.join(context.extensionPath, folderName, fileName)
);
const scriptPath = onDiskPath.with({ scheme: "vscode-resource" });
Expand All @@ -43,13 +36,12 @@ export const validCodeFileName = (filePath: string) => {
};

export const showPrivacyModal = (okAction: () => void) => {
window
.showInformationMessage(
`${CONSTANTS.INFO.THIRD_PARTY_WEBSITE}: ${CONSTANTS.LINKS.PRIVACY}`,
DialogResponses.AGREE_AND_PROCEED,
DialogResponses.CANCEL
)
.then((privacySelection: MessageItem | undefined) => {
vscode.window.showInformationMessage(
`${CONSTANTS.INFO.THIRD_PARTY_WEBSITE}: ${CONSTANTS.LINKS.PRIVACY}`,
DialogResponses.AGREE_AND_PROCEED,
DialogResponses.CANCEL,
)
.then((privacySelection: vscode.MessageItem | undefined) => {
if (privacySelection === DialogResponses.AGREE_AND_PROCEED) {
okAction();
} else if (privacySelection === DialogResponses.CANCEL) {
Expand All @@ -59,7 +51,7 @@ export const showPrivacyModal = (okAction: () => void) => {
};

export const logToOutputChannel = (
outChannel: OutputChannel | undefined,
outChannel: vscode.OutputChannel | undefined,
message: string,
show: boolean = false
): void => {
Expand All @@ -77,18 +69,18 @@ export function tryParseJSON(jsonString: string): any | boolean {
if (jsonObj && typeof jsonObj === "object") {
return jsonObj;
}
} catch (exception) {}
} catch (exception) { }

return false;
}
};

export function fileExistsSync(filePath: string): boolean {
try {
return fs.statSync(filePath).isFile();
} catch (error) {
return false;
}
}
};

export function mkdirRecursivelySync(dirPath: string): void {
if (directoryExistsSync(dirPath)) {
Expand All @@ -103,15 +95,15 @@ export function mkdirRecursivelySync(dirPath: string): void {
mkdirRecursivelySync(dirname);
fs.mkdirSync(dirPath);
}
}
};

export function directoryExistsSync(dirPath: string): boolean {
try {
return fs.statSync(dirPath).isDirectory();
} catch (e) {
return false;
}
}
};

/**
* This method pads the current string with another string (repeated, if needed)
Expand Down Expand Up @@ -142,11 +134,11 @@ export function padStart(
} else {
return (sourceString as any).padStart(targetLength, padString);
}
}
};

export function convertToHex(num: number, width = 0): string {
return padStart(num.toString(16), width, "0");
}
};

export function generateCPXConfig(): void {
const deviceContext: DeviceContext = DeviceContext.getInstance();
Expand All @@ -159,7 +151,7 @@ export function generateCPXConfig(): void {
);
mkdirRecursivelySync(path.dirname(cpxConfigFilePath));
fs.writeFileSync(cpxConfigFilePath, JSON.stringify(cpxJson, null, 4));
}
};
export const checkPythonDependency = async () => {
const dependencyChecker: DependencyChecker = new DependencyChecker();
const result = await dependencyChecker.checkDependency(
Expand All @@ -175,12 +167,9 @@ export const setPythonExectuableName = async () => {
if (dependencyCheck.installed) {
executableName = dependencyCheck.dependency;
} else {
window
.showErrorMessage(
CONSTANTS.ERROR.NO_PYTHON_PATH,
DialogResponses.INSTALL_PYTHON
)
.then((selection: MessageItem | undefined) => {
vscode.window.showErrorMessage(CONSTANTS.ERROR.NO_PYTHON_PATH,
DialogResponses.INSTALL_PYTHON)
.then((selection: vscode.MessageItem | undefined) => {
if (selection === DialogResponses.INSTALL_PYTHON) {
const okAction = () => {
open(CONSTANTS.LINKS.DOWNLOAD_PYTHON);
Expand All @@ -193,10 +182,36 @@ export const setPythonExectuableName = async () => {
return executableName;
};

export const addVisibleTextEditorCallback = (currentPanel: vscode.WebviewPanel, context: vscode.ExtensionContext): vscode.Disposable => {
const initialPythonEditors = filterForPythonFiles(vscode.window.visibleTextEditors);
currentPanel.webview.postMessage({
command: "visible-editors",
state: { activePythonEditors: initialPythonEditors }
});
return vscode.window.onDidChangeVisibleTextEditors((textEditors: vscode.TextEditor[]) => {
const activePythonEditors = filterForPythonFiles(textEditors);
currentPanel.webview.postMessage({
command: "visible-editors",
state: { activePythonEditors }
});
}, {}, context.subscriptions)
};

export const filterForPythonFiles = (textEditors: vscode.TextEditor[]) => {
return textEditors.filter(
editor => editor.document.languageId === "python"
).map(editor => editor.document.fileName);
};

export const getActiveEditorFromPath = (filePath: string): vscode.TextDocument => {
const activeEditor = vscode.window.visibleTextEditors.find((editor: vscode.TextEditor) => editor.document.fileName === filePath);
return activeEditor ? activeEditor.document : undefined;
};

export const getServerPortConfig = (): number => {
// tslint:disable: no-backbone-get-set-outside-model prefer-type-cast
if (workspace.getConfiguration().has(SERVER_INFO.SERVER_PORT_CONFIGURATION)) {
return workspace
if (vscode.workspace.getConfiguration().has(SERVER_INFO.SERVER_PORT_CONFIGURATION)) {
return vscode.workspace
.getConfiguration()
.get(SERVER_INFO.SERVER_PORT_CONFIGURATION) as number;
}
Expand Down
Loading

0 comments on commit 442569c

Please sign in to comment.