Skip to content

Commit

Permalink
Merge pull request #13 from printerboi/improve-code-style-for-release…
Browse files Browse the repository at this point in the history
…-v0_1_1

refactor: Improved code style and removed dead code
  • Loading branch information
printerboi authored Nov 24, 2024
2 parents f925e93 + f6c0943 commit 34c688d
Show file tree
Hide file tree
Showing 20 changed files with 570 additions and 195 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "spear-viewer",
"displayName": "spear-viewer",
"description": "Display data from spear",
"version": "0.0.1",
"version": "0.0.2",
"engines": {
"vscode": "^1.92.2"
},
Expand Down
18 changes: 0 additions & 18 deletions src/components/graphViewer.ts

This file was deleted.

58 changes: 46 additions & 12 deletions src/decorations/energyDecoration.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
/**
* Energy decoration file. Handles the coloured energy highlights
* Author: Maximilian Krebs
*
*/

import * as vscode from 'vscode';
import { BADCOLOR, Color, GOODCOLOR, MEDIUMCOLOR, interpolate } from '../helper/colorHelper';
import { SETTINGS } from '../helper/extensionConstants';


/**
* Enum to encode the type of a node
*/
enum NodeType {
UNDEFINED = 0,
NODE = 1,
Expand Down Expand Up @@ -36,10 +43,16 @@ interface EnergyNode{
instructions: Array<EnergyInstruction>
}

/**
* Define a Subgraph interface that represents a ProgramGraph inside LoopNodes
*/
interface Subgraph {
nodes: Array<EnergyNode | EnergyLoopNode>
}

/**
* Defines an interface to represent a LoopNode
*/
interface EnergyLoopNode{
type: NodeType,
repetitions: number,
Expand Down Expand Up @@ -91,15 +104,21 @@ export class AnalysisDecorationWrapper {
*/
maxVal: number;

/**
* Context of vscode
*/
context: vscode.ExtensionContext;

/**
* Defines a energy threshold, which hides energy decorations with an energy value lower than the defined value
*/
threshold: number;


/**
*
* @param engjsn
* @param relevantFile
* Constructs the energyDecoration object
* @param engjsn JSON file containing the analysis result
* @param relevantFile Files set to be analysed via the SPEAR-Viewer config file
*/
constructor(engjsn: any, relevantFile: string, context: vscode.ExtensionContext, threshold: number){
// Intialize the analysis result and the relevant file for the wrapper
Expand All @@ -118,7 +137,6 @@ export class AnalysisDecorationWrapper {

// Parse the analysis result
this.parse();
console.log(this.lineEnergyMapping);

}

Expand All @@ -128,10 +146,6 @@ export class AnalysisDecorationWrapper {
* the relevantFile property of the object.
*/
parse(){
//[TODO] We need to find a way that lines don't contain the doubled value of energy
// Currently the function will be calculated two times...the devil knows why...


// Iterate over the EnergyFunction objects
this.energyJson.functions.forEach((func) => {
// Iterate over the contained EnergyNodes of the Energyfunction
Expand All @@ -149,6 +163,11 @@ export class AnalysisDecorationWrapper {
});
}

/**
* Select the method to be called in order to handle the given node type
* @param node Node to be parsed
* @param multiplier Loop multiplier
*/
parseNode(node: EnergyNode | EnergyLoopNode, multiplier: number = 1){
if(node.type === 1){
const normalnode = node as EnergyNode;
Expand All @@ -161,6 +180,11 @@ export class AnalysisDecorationWrapper {
}
}

/**
* Parse a given node and calculate the energy
* @param normalnode Node to be parsed
* @param multiplier Loop multiplire
*/
parseNormalNode(normalnode: EnergyNode, multiplier: number = 1){
// Iterate over the contained EnergyInstruction objects
normalnode.instructions.forEach((inst: EnergyInstruction) => {
Expand All @@ -181,6 +205,11 @@ export class AnalysisDecorationWrapper {
});
}

/**
* Parse a given LoopNode
* @param loopnode LoopNode to be parsed
* @param multiplier LoopMultiplier
*/
parseLoopNode(loopnode: EnergyLoopNode, multiplier: number = 1){
loopnode.subgraphs.forEach((subgraph: Subgraph) => {
subgraph.nodes.forEach((node: EnergyNode | EnergyLoopNode) => {
Expand Down Expand Up @@ -239,13 +268,18 @@ export class AnalysisDecorationWrapper {
return `rgba(${interpolatedColor.red}, ${interpolatedColor.green}, ${interpolatedColor.blue}, 0.7)`;
}


/**
* Returns the actual gutter icon that highlights the energy used by the given line
* @param lineNumber The line number, the gutter icon will be displayed
* @returns A encoded svg object as URI to be displayed by vscode
*/
getGutterIcon(lineNumber: number): vscode.Uri | undefined{
const THRESHOLD = this.threshold;

if(THRESHOLD !== undefined){
// Check if the value of the line is above the defined threshold
if(this.lineEnergyMapping[lineNumber] > THRESHOLD){
//const svg = '<svg width="32" height="48" viewPort="0 0 32 48" xmlns="http://www.w3.org/2000/svg"><polygon points="16,0 32,0 32,48 16,48" fill="' + this.getColor(lineNumber) + '" stroke="white" stroke-width="4"/></svg>';
// Construct the svg image that will be displayed in the line
const svg = `<svg width="10" height="15" viewBox="0 0 10 15" xmlns="http://www.w3.org/2000/svg"><rect x="0" y="0" width="10" height="10" fill="${this.getColor(lineNumber)}" stroke="white" stroke-width="0"/></svg>`;
const icon = 'data:image/svg+xml;base64,' + Buffer.from(svg).toString('base64');
return vscode.Uri.parse(icon);
Expand Down
17 changes: 0 additions & 17 deletions src/decorations/graphDecoration.ts

This file was deleted.

6 changes: 5 additions & 1 deletion src/editors/virtualEnergyEditor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { error } from "console";
/**
* Defines a read only editor to enable the interaction with the calculated SPEAR analysis
* Author: Maximilian Krebs
*/

import * as vscode from "vscode";

/**
Expand Down
87 changes: 55 additions & 32 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs';
import generateGraph, { GenerateGraphParameters } from './subroutines/generateGraph';
Expand All @@ -13,33 +11,34 @@ import { StatusbarRunButton } from './statusbar/StatusbarRunButton';
import { ConfigParser } from './helper/configParser';
import { SpearSidebarCallgraphViewer } from './sidebar/SpearSidebarCallgraphViewer';

//export let TMPDIR: string = "";

// Init application wide path variables
export let PROJECTDIR: string = "";
export let CONFIGPATH: string = "";
export let CONFIGLOCATION: string = "";
export let EXTENSIONLOCATION: string = "";
export let initialized: boolean = false;

/**
* Init the UI components visible in the SPEAR tab
*/
export const ProfileProvider = new SpearSidebarProfileProvider();
export const OverviewProvider = new SpearSidebarAnalysisFilesViewer();
export const CallgraphProvider = new SpearSidebarCallgraphViewer();




// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
/**
* Activation function to run on the activation of the extension
* Will also run if a new folder will be open
* @param context VSC context
*/
export function activate(context: vscode.ExtensionContext) {
console.log("Creating tmp dir...");
try {
//TMPDIR = fs.mkdtempSync(path.join(os.tmpdir(), APPPREFIX));

// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Spear-viewer active!');
console.log('SPEAR-viewer active!');

let activeEditor = vscode.window.activeTextEditor;

// Define paths
if(vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0){
CONFIGPATH = `${vscode.workspace.workspaceFolders[0].uri.fsPath}/spear.yml`;
PROJECTDIR = `${vscode.workspace.workspaceFolders[0].uri.fsPath}/.spear`;
Expand All @@ -50,12 +49,12 @@ export function activate(context: vscode.ExtensionContext) {
OverviewProvider.refresh();
}



// Check if the current workspace includes a SPEAR-Viewer config. If not, present a dialog.
if(!fs.existsSync(CONFIGPATH)){
ConfigParser.presentConfigCreationDialog();
}

console.log('Adding commands...');
context.subscriptions.push(
/**
* Command to generate the graph for the currently open editor
Expand All @@ -69,80 +68,104 @@ export function activate(context: vscode.ExtensionContext) {
* Profiles the device and saves the generated profile in the tempory directory of the application
*/
vscode.commands.registerCommand('spear-viewer.profile', async () => {
// [TODO]: Validate config here
profile();
}),

/**
* Starts the analysis
*/
vscode.commands.registerCommand('spear-viewer.analyze', async () => {
analyzeHandler();
}),

/**
* Registers a tree view for displaying analysed files
*/
vscode.window.registerTreeDataProvider("spearsidebar.analysisresult", OverviewProvider),

/**
* Registers a tree view for displaying the energy call graph
*/
vscode.window.registerTreeDataProvider("spearsidebar.callgraph", CallgraphProvider),

/**
* Registers a tree view for displaying profile information
*/
vscode.window.registerTreeDataProvider("spearsidebar.profile", ProfileProvider),

/**
* Registers a command to allow for refreshment of profile information
*/
vscode.commands.registerCommand('spear-viewer.profile.refreshEntry', () =>
ProfileProvider.refresh()
),

/**
* Registers a command to allow for refreshing the analysis result
*/
vscode.commands.registerCommand('spear-viewer.analysisresult.refreshEntry', () =>
OverviewProvider.refresh()
),

/**
* Registers a command to allow for refreshing the energy callgraph
*/
vscode.commands.registerCommand('spear-viewer.callgraph.refreshEntry', () =>
CallgraphProvider.refresh()
),

/**
* Opens a readonly editor and display the code with energy highlighting
* Register a readonly editor to display code with energy highlightings
*/
vscode.workspace.registerTextDocumentContentProvider("spearenergy", energyEditorProvider),

/**
* Registers a button that enables users to run the analysis from the status bar
*/
StatusbarRunButton.get()
);

// Update the analysis button in the status bar
StatusbarRunButton.update();

if (activeEditor) {
triggerDecorationUpdate(true, activeEditor, context);
}

/**
* Adds a text editor change listener to update the visible decorations if the user
* opens a energy read only editor
*/
vscode.window.onDidChangeActiveTextEditor(editor => {
activeEditor = editor;
if (editor) {
triggerDecorationUpdate(false, activeEditor, context);
}

StatusbarRunButton.update();
}, null, context.subscriptions);


/**
* Adds a text editor change listener to update the visible decorations if the user
* switches a energy read only editor
*/
vscode.workspace.onDidChangeTextDocument(event => {
if (activeEditor && event.document === activeEditor.document) {
triggerDecorationUpdate(true, activeEditor, context);
}

StatusbarRunButton.update();
}, null, context.subscriptions);


}catch(e){
// Catch any error encoutered during the activation
console.error(e);
vscode.window.showErrorMessage('Error activating spear. A temporary directory could not be created!');
vscode.window.showErrorMessage('Error activating the SPEAR-Viewer. A temporary directory could not be created!');
}


}

// This method is called when your extension is deactivated
export function deactivate() {
/* try {
if (TMPDIR) {
fs.rmSync(TMPDIR, { recursive: true });
}
}
catch (e) {
vscode.window.showInformationMessage(`An error has occurred while removing the temporary directory at ${TMPDIR}. Please remove it manually. Error: ${e}`);
} */
}
/**
* Deactivation function
*/
export function deactivate() {}
Loading

0 comments on commit 34c688d

Please sign in to comment.