-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.js
603 lines (466 loc) · 19 KB
/
main.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */
// Bracket extension. Permite que o desenvolvedor crie atalhos para os comandos de console.
define(function (require, exports, module) {
"use strict";
var AppInit = brackets.getModule('utils/AppInit'),
ExtensionUtils = brackets.getModule('utils/ExtensionUtils'),
NodeConnection = brackets.getModule('utils/NodeConnection'),
NodeDomain = brackets.getModule('utils/NodeDomain'),
CommandManager = brackets.getModule('command/CommandManager'),
KeyBindingManager = brackets.getModule('command/KeyBindingManager'),
Menus = brackets.getModule('command/Menus'),
QuickOpen = brackets.getModule('search/QuickOpen'),
ProjectManager = brackets.getModule('project/ProjectManager'),
StatusBar = brackets.getModule('widgets/StatusBar'),
FileSystem = brackets.getModule('filesystem/FileSystem'),
FileUtils = brackets.getModule('file/FileUtils'),
PanelManager = brackets.getModule('view/PanelManager'),
Resizer = brackets.getModule('utils/Resizer'),
DocumentManager = brackets.getModule('document/DocumentManager');
var ansi2html = require('ansi2html');
// Id do plugin
var COMMAND_RUNNER = 'br.com.softbox.brackets.plugin.commandrunner';
var COMMAND_RUNNER_KILL = COMMAND_RUNNER + '.kill';
var panelOutHtml = require('text!html/panel_output.html');
var panelArgsHtml = require('text!html/panel_args.html');
var panelOut, // Painel de saida.
panelArgs, // Painel utilizado para entrada de argumentos.
cmdConfig, // Configuracoes do projeto.
cmdSelected; // Comando corrente selecionado.
var DEBUG = true; // Debug
var cmdRunner = CommandManager.register('Open Command Runner', COMMAND_RUNNER, openSearch),
cmdKill = CommandManager.register('Kill Commands', COMMAND_RUNNER_KILL, killCommands),
fileMenu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU),
cmdsMenu = Menus.addMenu('Commands', COMMAND_RUNNER + '-menu', Menus.BEFORE, Menus.AppMenuBar.HELP_MENU),
regCount = 0,
cmdId = 0;
var hotkeyPressed = false;
// Parametros do sistema.
var systemParams = {
selectedFile: function(opts) {
var doc = DocumentManager.getCurrentDocument();
return !doc ? '' : doc.file.name;
},
dirOfSelectedFile: function(opts) {
var doc = DocumentManager.getCurrentDocument();
return !doc ? opts.defaultPath : doc.file.parentPath;
},
projectDir: function(opts) {
var dir = ProjectManager.getProjectRoot();
return dir ? dir.fullPath : '.';
}
};
/*$(document).keydown(function(evt) {
if (hotkeyPressed
&& evt.shiftKey
&& evt.ctrlKey
&& String.fromCharCode(evt.which).toUpperCase() == 'K') {
}
});*/
// Funcao que executa comandos atraves do NodeJS
var execCmdFnc = function(cmd, args, opts, callback) {
alert('Can not run the command, because NodeJS bridge not loaded!');
};
// Funcao que executa o comando kill.
var killCmdFnc = function() {
alert('Can not run kill command, because NodeJS bridge not loaded!');
}
//fileMenu.addMenuDivider();
//fileMenu.addMenuItem(cmdRunner);
cmdsMenu.addMenuItem(cmdRunner);
cmdsMenu.addMenuItem(cmdKill);
cmdsMenu.addMenuItem(CommandManager.register('Clear Console', COMMAND_RUNNER + '.clear.console', function() {
var elem = $('#brackets-cmd-runner-console').html('');
}));
cmdsMenu.addMenuItem(CommandManager.register('Show Console', COMMAND_RUNNER + '.show.console', function() {
appendOutput('');
}));
cmdsMenu.addMenuItem(CommandManager.register('Hide Console', COMMAND_RUNNER + '.hide.console', function() {
if (panelOut) {
panelOut.hide();
}
}));
cmdsMenu.addMenuDivider();
KeyBindingManager.addBinding(COMMAND_RUNNER, {key: 'Ctrl-Shift-M'});
KeyBindingManager.addBinding(COMMAND_RUNNER_KILL, {key: 'Ctrl-Shift-K'});
/**
* Finaliza todos os comandos iniciados.
*/
function killCommands() {
killCmdFnc('nop');
}
/**
* Remove todas as hotkeys associadas.
*/
function unbindAllHotkeys() {
if (!cmdConfig) {
return;
}
for (var i = 0; i < cmdConfig.length; i++) {
var cmd = cmdConfig[i];
if (cmd.key) {
KeyBindingManager.removeBinding(cmd.key);
}
if (cmd.cmdID) {
cmdsMenu.removeMenuItem(cmd.cmdID);
}
}
}
/**
* Cria uma funcao de evento para execucao de uma tecla de atalho.
*
* @param {object} cmd Comando que sera selecionado.
*
* @return {function} Funcao que executa a acao do comando selecionado.
*/
function createCommand(cmd) {
return function() {
cmdSelected = cmd;
showInputArgs();
};
}
/**
* Realiza o parse do arquivo de configuracao e carrega as novas configuracoes.
*
* @param {string} cfgData String contendo as informacoes de configuracao.
*/
function loadConfigs(cfgData) {
try {
var cfg = JSON.parse(cfgData);
if (!cfg) {
return;
}
cmdConfig = cfg;
for (var i = 0; i < cmdConfig.length; i++) {
var cmd = cmdConfig[i];
cmd.cmdID = COMMAND_RUNNER + '.cmd-' + regCount++;
var cmdObj = CommandManager.register(cmd.label, cmd.cmdID, createCommand(cmd));
cmdsMenu.addMenuItem(cmdObj);
if (cmd.key) {
KeyBindingManager.addBinding(cmdObj, {key: cmd.key});
}
}
} catch(err) {
appendOutput('Erro ao carregar o arquivo cmdrunner.json: ' + err);
cmdConfig = [];
}
}
/**
* Inicialmente remove todos os eventos associados anteriormente e entao
* carrega o arquivo de configuracao do executor de comandos caso exita.
*/
function readConfigFile() {
var rootPath = ProjectManager.getProjectRoot().fullPath,
cmdCfgFile = FileSystem.getFileForPath(rootPath + 'cmdrunner.json');
unbindAllHotkeys();
FileUtils.readAsText(cmdCfgFile).done(function (rawText) {
loadConfigs(rawText);
});
}
// Eventos que determinam a carga do arquivo de configuracao do cmd runner.
$(ProjectManager).on('projectOpen projectRefresh', readConfigFile);
$(DocumentManager).on('documentSaved', function(evt, doc) {
if (doc.file.name == 'cmdrunner.json') {
readConfigFile();
}
});
/**
* Adiciona o texto fornecido no painel inferior.
*
* @param {string} output String contendo o texto que sera adicionado ao painel de saida.
* @param {string} color Cor (nome cor, rgb) do texto que sera utilizada para exibicao.
* @param {bool} hiddenConsole True indica que o texto ser adicionado no painel, mas nao vai ser exibido.
*/
function appendOutput(output, color, hiddenConsole) {
if (!panelOut) {
panelOut = PanelManager.createBottomPanel(COMMAND_RUNNER + '.output', $(panelOutHtml));
$('.close', $('#brackets-cmd-runner-output')).click(function() {
panelOut.hide();
});
}
var elem = $('#brackets-cmd-runner-console');
output = output || '';
color = color || 'white';
var tmplate = [];
elem.append('<span style="color: ' + color + '">' + ansi2html(Mustache.render('{{row}}', {row: output})) + '</span>');
if (!hiddenConsole) {
panelOut.show();
}
elem.animate({ scrollTop: elem[0].scrollHeight }, 'fast');
}
/**
* Retorna um array com os parametros do tipo $digito fornecido no comando.
* @param {string} command String do comando que podera ser executado.
*
* @return Array com os paramentros fornecidos na stringo do comando.
*/
function getParams(command) {
var re = /\$[0-9]+/g,
matches = [],
m;
while ((m = re.exec(command)) !== null) {
m = m[0].substr(1);
if (m.match('[0-9]+')) {
matches.push(m);
}
}
return matches;
}
/**
* Constroi o comando mesclando os parametros com o template da string do comando.
*
* @param {string} command String do comando que podera ser executado.
* @param {array} params Array que contem os parametros especificados na string do comando.
* @param {array} args Array de argumentos informados pelo usuario.
* @param {array} argsDefault Array de argumentos padrao informados no arquivo cmdrunner.json.
* @param {object} opts Opcoes extras para a execucao do comando.
*
* @return String do comando meclado com os parametros pronto para ser executado.
*/
function buildCommand(command, params, args, argsDefault, opts) {
for (var i = 0; i < params.length; i++) {
var idx = parseInt(params[i]);
var value = '';
if (!isNaN(idx)) {
value = args[idx] ? args[idx] : (argsDefault[idx] ? argsDefault[idx] : '');
}
command = command.replace(new RegExp('\\$' + params[i], 'g'), replaceSystemParams(value, opts));
}
return command;
}
/**
* Obtem as opcoes extras fornecidas para o comando meclando-as com as opcoes de execucao padrao.
*
* @param {object} objCmd Objeto que contem as informacoes do comando configurado no arquivo cmdrunner.json.
*
* @return {object} Objeto que contem as informacoes extras para execucao do comando.
*/
function getOpts(objCmd) {
var defaultOpts = {
defaultPath: ProjectManager.getProjectRoot().fullPath
};
var opts = $.extend({}, defaultOpts, objCmd.opts);
//TODO Melhorar!
if (opts.defaultPath
&& typeof opts.defaultPath == 'string'
&& opts.defaultPath.length > 0
&& opts.defaultPath.charAt(0) === '.') {
opts.defaultPath = defaultOpts.defaultPath + '/' + opts.defaultPath;
}
opts = replaceSystemParams(opts, opts);
opts.id = cmdId++ + '';
return opts;
}
/**
* Substitui as variaveis do comando fornecido pelos valores do sistema.
*
* @param {any} command Qualquer valor que se queira substituir pela vlaores do sistema.
* @param {object} opts Opcoes extras informadas para a execucao do comando.
*
* @return {any} O objeto commando fornecido com as variaveis de sistema substituidas.
*/
function replaceSystemParams(command, opts) {
if (command == null) {
return null;
}
if (typeof command === 'string') {
var newCommand = command;
for (var param in systemParams) {
var paramValue = systemParams[param](opts);
while ((command = command.replace('$' + param, paramValue)) != newCommand) {
newCommand = command;
}
}
return command;
}
if (typeof command === 'object') {
var newCmd = command instanceof Array ? [] : {};
for (var elem in command) {
newCmd[elem] = replaceSystemParams(command[elem], opts);
}
return newCmd;
}
return command;
}
/**
* Executa o comando fornecido e imprime a saida no painel.
*
* @param {object} objCmd Objeto que contem as informacoes do comando que sera executado.
* @param {array} args Array com os argumentos fornecidos pelo usuario.
*/
function runCommand(objCmd, args) {
var opts = getOpts(objCmd);
var command = buildCommand(objCmd.cmd, getParams(objCmd.cmd), args, objCmd.args, opts);
command = replaceSystemParams(command, opts);
appendOutput('Executing: ' + command + '\n', null, opts.hiddenConsole);
execCmdFnc(command, null, opts, function(err, data) {
appendOutput(data, err ? 'red' : 'white');
});
}
/**
* Exibe paneil inferior para fornecer parametros para a execucao do comando.
*/
function showInputArgs() {
if (!panelArgs) {
panelArgs = PanelManager.createBottomPanel(COMMAND_RUNNER + '.args', $(panelArgsHtml), 40);
var btnClose = $('.close', $('#brackets-cmd-runner-args'));
btnClose.click(function() {
if (panelArgs) {
panelArgs.hide();
}
});
var input = $('input', $('#brackets-cmd-runner-args'));
input.focusout(function() {
btnClose.click();
});
input.keydown(function(evt) {
if (evt.which === 27) {
btnClose.click();
}
});
input.keypress(function(evt) {
if (evt.which === 13) {
btnClose.click();
var splitChar = cmdSelected.splitChar || ':';
runCommand(cmdSelected, $('#brackets-cmd-runner-args-val').val().split(splitChar));
}
});
}
$('#brackets-cmd-runner-args-text').html(cmdSelected.cmd);
$('#brackets-cmd-runner-args-val').val(cmdSelected.args);
// So exibe a caixa de argumentos, se existir pelo menos uma marcacao
// de parametros na construcao do comando.
if (getParams(cmdSelected.cmd).length === 0) {
runCommand(cmdSelected, '');
} else {
panelArgs.show();
}
//TODO Melhorar
setTimeout(function() {
var ipt = $('input', $('#brackets-cmd-runner-args'));
ipt.focus();
ipt.select();
}, 350);
}
/**
* Abre o paneil de busca de comandos.
*/
function openSearch() {
QuickOpen.beginSearch('#', '');
hotkeyPressed = true;
setTimeout(function() {
hotkeyPressed = false;
}, 300);
}
/**
* Helper function that chains a series of promise-returning functions together via their
* done callbacks.
*/
function chain() {
var functions = Array.prototype.slice.call(arguments, 0);
if (functions.length > 0) {
var firstFunction = functions.shift();
var firstPromise = firstFunction.call();
firstPromise.done(function () {
chain.apply(null, functions);
});
}
}
QuickOpen.addQuickOpenPlugin({
name: 'Command Runner',
label: 'Command Runner', // ignored before Sprint 34
languageIds: [], // empty array = all file types (Sprint 23+)
fileTypes: [], // (< Sprint 23)
done: function () {},
search: function(query) {
var cmd = query.substr(1);
var ret = cmdConfig.filter(function(elem) {
return cmd.length === 0 || elem.cmd.indexOf(cmd) >= 0 || elem.label.indexOf(cmd) >= 0;
});
return ret;
},
match: function(query) {
return query.length > 0 && query.charAt(0) === '#';
},
itemSelect: function(item) {
cmdSelected = item;
showInputArgs();
},
matcherOptions: { segmentedSearch: true }
//itemFocus: function () {},
//resultsFormatter: function(item) {
// var displayName = highlightMatch(item);
// return "<li>" + displayName + "</li>";
//},
});
// Inicia conexao com NodeJS
AppInit.appReady(function () {
var path = ExtensionUtils.getModulePath(module, 'node/NodeBridgeDomain');
var nodeConnection = new NodeConnection();
var startNodeTimeout = 0;
$(nodeConnection).on('nodebridge.update', function(evt, ret) {
appendOutput(ret.data, ret.err ? 'red' : 'white', ret.hiddenConsole);
});
// Inicia a conexao com o NodeJS.
function connect() {
var connectionPromise = nodeConnection.connect(true);
connectionPromise.fail(function (err) {
console.error('[brackets-tekton] failed to connect to node: ', err);
if (DEBUG) alert('Erro connect: ' + JSON.stringify(err));
});
return connectionPromise;
}
// Inicia a bridge que executara os comandos
function loadBridge() {
var path = ExtensionUtils.getModulePath(module, 'node/NodeBridgeDomain');
var loadPromise = nodeConnection.loadDomains([path], true);
loadPromise.fail(function (err) {
console.log('[brackets-tekton] failed to load domain: ', err);
if (DEBUG) alert('Erro loadBridge: ' + JSON.stringify(err));
});
return loadPromise;
}
// Executa comando a atraves da bridge do NodeJS.
function execCmd(cmd, args, options, callback, count) {
if (!nodeConnection.domains.nodebridge) {
clearTimeout(startNodeTimeout);
if (count > 10) {
appendOutput('Was not possible execute command ' + cmd + ' because NodeJS not started!\n');
return;
}
appendOutput('Waiting for NodeJS...\n');
startNodeTimeout = setTimeout(function() {
execCmd.call(null, cmd, args, options, callback, (count || 1) + 1);
}, 1000);
return;
}
var promise = nodeConnection.domains.nodebridge.execCmd(cmd, args, options);
promise.fail(function (err, data) {
console.error('[brackets-tekton] execution: ', arguments);
appendOutput('Error when executing supplied command: ' + cmd + (args || []).join(' ') + ' Log: ' + err);
});
promise.done(function (data) {
//funOutData(data);
});
}
// Mata os comandos atraves da bridge do NodeJS.
function killCmd(id) {
if (!nodeConnection.domains.nodebridge) {
return;
}
var promise = nodeConnection.domains.nodebridge.killCmd(id);
promise.fail(function (err, data) {
console.error('[brackets-tekton] kill execution: ', arguments);
appendOutput('Error when executing kill command!', 'red');
});
promise.done(function (data) {
appendOutput('Killed!');
});
appendOutput('Sent kill command.\n');
}
execCmdFnc = execCmd;
killCmdFnc = killCmd;
chain(connect, loadBridge);
});
});