-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.js
339 lines (293 loc) · 12.3 KB
/
extension.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// @ts-nocheck
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const express = require('express');
const { Server } = require('socket.io');
const path = require('path');
const fs = require('fs');
const jsonc = require('jsonc-parser');
const SC = require('./supercollider/lang');
const { isEnvironmentActive, envilEnvironmentContextKey } = require('./supercollider/util');
const osc = require("osc");
let hyperScopes = null;
let app = null;
let server = null;
let io = null;
let isLoadingCompleted = false;
let oscPort = null;
/**
* @param {vscode.ExtensionContext} context
*/
async function activate(context) {
console.log('Activating ENVIL Extension');
const workspaceFolder = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders[0].uri.fsPath : null;
const isEnvActive = vscode.workspace.getConfiguration().get(envilEnvironmentContextKey) || false;
if(isEnvActive){
showNotification('Loading ENVIL environment ...');
startServersAndSockets(workspaceFolder);
SC.initStatusBar();
const hyperScopesExt = vscode.extensions.getExtension('draivin.hscopes');
hyperScopes = await hyperScopesExt.activate();
}
// This refreshes the token scope, but I don't think this is optimized.. but I haven't run into issues yet.
vscode.window.onDidChangeActiveTextEditor(
() => {
const editor = vscode.window.activeTextEditor;
if (editor) {
const res = hyperScopes.reloadScope(editor.document);
console.log(res);
}
},
null,
context.subscriptions
);
const startSCLang = vscode.commands.registerCommand('envil.supercollider.startSCLang', SC.startSCLang);
const stopSCLang = vscode.commands.registerCommand('envil.supercollider.stopSCLang', SC.stopSCLang);
const toggleSCLang = vscode.commands.registerCommand('envil.supercollider.toggleSCLang', SC.toggleSCLang);
const startSCSynth = vscode.commands.registerCommand('envil.supercollider.startSCSynth', SC.startSCSynth);
const stopSCSynth = vscode.commands.registerCommand('envil.supercollider.stopSCSynth', SC.stopSCSynth);
const toggleSCSynth = vscode.commands.registerCommand('envil.supercollider.toggleSCSynth', SC.toggleSCSynth);
const evaluate = vscode.commands.registerCommand('envil.supercollider.evaluate', () => SC.evaluate(hyperScopes));
const hush = vscode.commands.registerCommand('envil.supercollider.hush', SC.hush);
context.subscriptions.push(startSCLang, stopSCLang, toggleSCLang, startSCSynth, stopSCSynth, toggleSCSynth, evaluate, hush);
const openEnvironmentCommand = vscode.commands.registerCommand('envil.start', async function () {
try {
showNotification('Loading ENVIL environment ...');
await updateCustomPropertyInSettings(true);
// Update workspace settings
if (workspaceFolder) {
const workspaceSettingsPath = path.join(workspaceFolder, '.vscode', 'settings.json');
await createSettingsFileIfNotExist(workspaceSettingsPath);
const newWorkspaceSettingsPath = path.join(__dirname, 'data', 'workspace_settings.json');
const newWorkspaceSettings = readJsonWithComments(newWorkspaceSettingsPath).json;
await updateUserSettings(newWorkspaceSettings, false, vscode.ConfigurationTarget.Workspace);
}
// Update user settings
const newGlobalSettingsPath = path.join(__dirname, 'data', 'global_settings.json');
const newGlobalSettings = readJsonWithComments(newGlobalSettingsPath).json;
await updateUserSettings(newGlobalSettings, false, vscode.ConfigurationTarget.Global);
const isExtensionActive = context.globalState.get('isExtensionActive') || false;
if (!isExtensionActive) {
context.globalState.update('isExtensionActive', true);
console.log("Enabling APC Customize UI++");
await vscode.commands.executeCommand('apc.extension.enable');
console.log("APC Customize UI++ enabled successfully!");
}
} catch (error) {
vscode.window.showErrorMessage(`Failed to load environment: ${error.message}`);
} finally {
isLoadingCompleted = true;
}
});
const closeEnvironmentCommand = vscode.commands.registerCommand('envil.stop', async function () {
try {
showNotification('Closing ENVIL environment ...');
closeServersAndSockets();
await updateCustomPropertyInSettings(false);
// Remove workspace settings
if (workspaceFolder) {
const newWorkspaceSettingsPath = path.join(__dirname, 'data', 'workspace_settings.json');
const newWorkspaceSettings = readJsonWithComments(newWorkspaceSettingsPath).json;
await updateUserSettings(newWorkspaceSettings, true, vscode.ConfigurationTarget.Workspace);
}
// Remove user settings
const newGlobalSettingsPath = path.join(__dirname, 'data', 'global_settings.json');
const newGlobalSettings = readJsonWithComments(newGlobalSettingsPath).json;
await updateUserSettings(newGlobalSettings, true, vscode.ConfigurationTarget.Global);
} catch (error) {
vscode.window.showErrorMessage(`Failed to close the environment: ${error.message}`);
} finally {
isLoadingCompleted = true;
}
});
const evaluateHydraCommand = vscode.commands.registerCommand('envil.hydra.evaluate', function () {
if(!isEnvironmentActive()){
return;
}
const editor = vscode.window.activeTextEditor;
if (editor) {
let command = "";
const document = editor.document;
const selection = editor.selection;
let text = document.getText(selection);
text = text.length === 0 ? document.getText() : text;
const lines = text.split('\n');
for (const currentLine of lines) {
let line = currentLine;
if (line.trimStart().startsWith('//')) {
line = "";
}
// local files handling
if (line.includes('local/files/')) {
line = line.replace("local/files/", "http://localhost:3000/files/");
}
if (line !== "") {
command = command + line;
if (line.trimEnd().endsWith(";")) {
// send command to client
console.log("\n\n");
io.sockets.emit('new-command', { data: command });
command = "";
}
}
}
}
});
context.subscriptions.push(openEnvironmentCommand);
context.subscriptions.push(closeEnvironmentCommand);
context.subscriptions.push(evaluateHydraCommand);
console.log('ENVIL Extension activated successfully!');
}
// This method is called when your extension is deactivated
async function deactivate() {
console.log('Deactivating ENVIL Extension');
closeServersAndSockets();
await updateCustomPropertyInSettings(undefined);
const currentWorkspaceFolder = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders[0].uri.fsPath : null;
// Remove workspace settings
if (currentWorkspaceFolder) {
const newWorkspaceSettingsPath = path.join(__dirname, 'data', 'workspace_settings.json');
const newWorkspaceSettings = readJsonWithComments(newWorkspaceSettingsPath).json;
await updateUserSettings(newWorkspaceSettings, true, vscode.ConfigurationTarget.Workspace);
}
// Remove user settings
const newGlobalSettingsPath = path.join(__dirname, 'data', 'global_settings.json');
const newGlobalSettings = readJsonWithComments(newGlobalSettingsPath).json;
await updateUserSettings(newGlobalSettings, true, vscode.ConfigurationTarget.Global);
await SC.stopSCLang();
console.log("Disabling APC Customize UI++");
await vscode.commands.executeCommand('apc.extension.disable');
console.log("APC Customize UI++ disabled successfully!");
console.log('ENVIL Extension deactivated successfully!');
}
function closeServersAndSockets() {
if (io) {
io.close(() => {
console.log('Socket.io server closed');
});
io = null;
}
if (server) {
server.close(() => {
console.log('Express server closed');
});
server = null;
}
if (oscPort) {
oscPort.close();
}
}
function startServersAndSockets(workspaceFolder) {
// shut down servers if needed
if (app || server || io || oscPort) {
closeServersAndSockets();
}
// create servers
app = express();
server = app.listen(3000, async () => {
console.log('Express server is running at http://localhost:3000');
// Open the URL in the default browser
vscode.env.openExternal(vscode.Uri.parse('http://localhost:3000'));
});
io = new Server(3001, {
cors: {
origin: '*',
}
});
io.on('connection', (socket) => {
console.log('Socket.io: Client connected');
socket.on('disconnect', () => {
console.log('Socket.io: Client disconnected');
});
});
oscPort = new osc.UDPPort({
localAddress: "localhost",
localPort: 3002
});
oscPort.open();
oscPort.on("message", (oscMsg) => {
console.debug("Received OSC message from Supercollider:", oscMsg);
if (io) {
io.sockets.emit('new-command', { data: oscMsg.args[0] });
}
});
// serve static files
app.use(express.static(path.join(__dirname, 'hydra')));
if (workspaceFolder) {
app.use('/files', express.static(path.join(workspaceFolder, 'public')));
} else {
vscode.window.showErrorMessage("Can't serve static local files: No workspace folder is open.");
}
isLoadingCompleted = true;
}
async function createSettingsFileIfNotExist(settingsPath) {
try {
const dir = path.dirname(settingsPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
if (!fs.existsSync(settingsPath)) {
fs.writeFileSync(settingsPath, JSON.stringify({}, null, 4));
}
} catch (err) {
const errorMessage = `Failed to create settings file: ${err.message}`;
console.error(errorMessage);
vscode.window.showErrorMessage(errorMessage);
throw errorMessage;
}
}
function readJsonWithComments(filePath) {
const content = fs.readFileSync(filePath, 'utf-8');
const errors = [];
const json = jsonc.parse(content, errors);
if (errors.length) {
console.error('Error parsing JSON:', errors);
return null;
}
return { json, content };
}
async function updateUserSettings(updates, deleteSettings, configurationTarget) {
var config = vscode.workspace.getConfiguration();
for (const [key, value] of Object.entries(updates)) {
config.update(key, deleteSettings ? undefined : value, configurationTarget);
}
}
async function updateCustomPropertyInSettings(value) {
const config = vscode.workspace.getConfiguration();
config.update(envilEnvironmentContextKey, value, vscode.ConfigurationTarget.Global);
}
async function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function checkLoadingCompletion() {
return new Promise((resolve) => {
const checkCondition = async () => {
if (isLoadingCompleted) {
await delay(3500);
resolve();
} else {
// Check again after a delay
setTimeout(checkCondition, 1000);
}
};
checkCondition();
});
}
function showNotification(message) {
isLoadingCompleted = false;
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: message,
cancellable: false,
},
async (progress, token) => {
await checkLoadingCompletion();
}
);
}
module.exports = {
activate,
deactivate
}