forked from Ericsson/CodeCompass
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathText.js
More file actions
716 lines (590 loc) · 21.9 KB
/
Copy pathText.js
File metadata and controls
716 lines (590 loc) · 21.9 KB
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
define([
'dojo/_base/declare',
'dojo/dom-class',
'dojo/dom-construct',
'dojo/dom-style',
'dojo/query',
'dojo/topic',
'dijit/layout/ContentPane',
'dijit/Dialog',
'dijit/MenuItem',
'codecompass/astHelper',
'codecompass/util',
'codecompass/model',
'codecompass/urlHandler',
'codecompass/viewHandler',
'codecompass/view/component/ContextMenu'],
function (declare, domClass, dom, style, query, topic, ContentPane, Dialog,
MenuItem, astHelper, util, model, urlHandler, viewHandler, ContextMenu) {
var BuildDialog = declare(Dialog, {
postCreate : function () {
this.inherited(arguments);
this.set('title', 'Build logs');
this._table = dom.create('table', { class : 'buildlogtable' });
this._addHeader();
this.set('content', this._table);
},
/**
* This function appends an array of build logs in the table of the dialog.
* @param {[BuildLog]} buildLogs An array of BuildLog thrift objects.
*/
addBuildLogs : function (buildLogs) {
var that = this;
buildLogs.forEach(function (buildLog) {
var row = dom.create('tr', { onclick : function () {
that.hide();
if (!that.textmodule)
console.error("Editor object must be given in constructor");
that.textmodule.set('selection', [
buildLog.range.startpos.line,
buildLog.range.startpos.column,
buildLog.range.endpos.line,
buildLog.range.endpos.column
]);
that.textmodule.jumpToPos(
buildLog.range.startpos.line,
buildLog.range.startpos.end);
}});
var type = dom.create('span');
var col;
switch (buildLog.messageType) {
case MessageType.Unknown:
domClass.add(type, 'unknown');
dom.place(dom.toDom('Unknown'), type);
break;
case MessageType.Error:
domClass.add(type, 'error');
dom.place(dom.toDom('Error'), type);
break;
case MessageType.FatalError:
domClass.add(type, 'fatalerror');
dom.place(dom.toDom('Fatal Error'), type);
break;
case MessageType.Warning:
domClass.add(type, 'warning');
dom.place(dom.toDom('Warning'), type);
break;
case MessageType.Note:
domClass.add(type, 'note');
dom.place(dom.toDom('Note'), type);
break;
case MessageType.CodingRule:
domClass.add(type, 'codingrule');
dom.place(dom.toDom('Coding Rule'), type);
break;
}
col = dom.create('td');
dom.place(type, col);
dom.place(col, row);
col = dom.create('td', { innerHTML : buildLog.message });
dom.place(col, row);
col = dom.create('td', { innerHTML : buildLog.range.startpos.line });
dom.place(col, row);
col = dom.create('td', { innerHTML : buildLog.range.startpos.column });
dom.place(col, row);
col = dom.create('td', { innerHTML : buildLog.range.endpos.line });
dom.place(col, row);
col = dom.create('td', { innerHTML : buildLog.range.endpos.column });
dom.place(col, row);
dom.place(row, this._table);
}, this);
},
/**
* This function clears the build log table in the dialog. Only a header row
* is left there.
*/
clearBuildLogs : function () {
dom.empty(this._table);
this._addHeader();
},
/**
* This function appends a header row in the table of the given dialog
* instance.
*/
_addHeader : function () {
var row = dom.create('tr');
var col;
col = dom.create('th', { innerHTML : 'Type' });
dom.place(col, row);
col = dom.create('th', { innerHTML : 'Message' });
dom.place(col, row);
col = dom.create('th', { innerHTML : 'From', colspan : 2 });
dom.place(col, row);
col = dom.create('th', { innerHTML : 'To', colspan : 2 });
dom.place(col, row);
dom.place(row, this._table);
}
});
/**
* This function returns true if the given position is inside the given range.
* @param {Array} position An array with two elements: line and column
* respectively.
* @param {Array} range An array with four elements: start line, start column,
* end line, end column respectively.
*/
function positionInRange(position, range) {
var pos = { line : position[0], column : position[1] };
var ran = {
from : { line : range[0], column : range[1] },
to : { line : range[2], column : range[3] }
};
if (pos.line > ran.from.line && pos.line < ran.to.line)
return true;
return ran.from.line === ran.to.line
? pos.line === ran.from.line &&
pos.column >= ran.from.column && pos.column <= ran.to.column
: pos.line === ran.from.line && pos.column >= ran.from.column ||
pos.line === ran.to.line && pos.column <= ran.to.column;
}
/**
* This function adds menu items to the given context menu. The menu items
* come from the language service which are applicable for the AST node at
* the given position. Moreover some client-side menu items are also added.
* @param {Array} position An array with two elements: line and column
* respectively.
* @param {FileInfo} fileInfo A Thrift object which contains the information
* of the file in which the click happens.
* @param {ContextMenu} contextMenu A Menu which will be filled with menu
* items.
*/
function buildContextMenu(position, fileInfo, contextMenu) {
var astNodeInfo = astHelper.getAstNodeInfoByPosition(position, fileInfo);
//--- Build menu ---//
contextMenu.clear();
viewHandler.getModules({
type : viewHandler.moduleType.TextContextMenu,
fileType : fileInfo.type
}).forEach(function (menuItem) {
var item = menuItem.render(astNodeInfo, fileInfo);
if (item)
contextMenu.addChild(item);
});
contextMenu.addChild(new MenuItem({
label : 'Get permalink to selection',
onClick : function (event) {
var text = dom.create('div', {
innerHTML : 'You can copy the page URL from this text box which\
encodes the selection too.',
style : 'margin-bottom: 5px; width: 300px; text-align: center'
});
var textInput = dom.create('input', {
value : urlHandler.getURL(),
style : 'width: 100%'
});
var content = dom.create('div');
dom.place(text, content);
dom.place(textInput, content);
(new Dialog({ title : 'Copy URL', content : content })).show();
textInput.select();
}
}));
}
return declare(ContentPane, {
constructor : function () {
this.class = 'editor';
this.firstLineNumber = 1;
this._buildDialog = new BuildDialog({ textmodule : this });
this._marks = {};
this._markIdCounter = 0;
this._syntaxHighlightStep = 500;
this._subscribeTopics();
},
postCreate : function () {
var that = this;
//--- Header ---//
this._header = {
header : dom.create('div', { class : 'header' }),
parsestatus : dom.create('span', {
class : 'parsestatus',
onclick : function () {
var dialog = that._buildDialog;
dialog.clearBuildLogs();
var file = urlHandler.getFileInfo();
var buildLogs = model.project.getBuildLog(file.id);
if (buildLogs.length === 0)
{
new Dialog({
title : 'Build logs',
content : '<b>No build logs for this file.</b>'
}).show();
return;
}
dialog.addBuildLogs(buildLogs);
dialog.show();
}
}),
filename : dom.create('span', { class : 'filename' }),
path : dom.create('span', { class : 'path' }),
colons : dom.toDom('<span class="colons">::</span>')
};
dom.place(this._header.header, this.domNode);
dom.place(this._header.parsestatus, this._header.header);
dom.place(this._header.filename, this._header.header);
dom.place(this._header.colons, this._header.header);
dom.place(this._header.path, this._header.header);
//--- CodeMirror ---//
this._codeMirror = new CodeMirror(this.domNode, {
matchBrackets : true,
lineNumbers : true,
firstLineNumber : that.firstLineNumber,
readOnly : true,
mode : 'text/x-c++src',
foldGutter : true,
gutters : ['CodeMirror-linenumbers', 'bugInfo'],
extraKeys : {}
});
this._codeMirror.on("mousedown", function (cm, event) {
that._eventHandler(event);
});
this._codeMirror.on('contextmenu', function (cm, event) {
event.preventDefault();
});
this._contextMenu = new ContextMenu();
},
startup : function () {
this.inherited(arguments);
// TODO: if add new resizehandler it will not be the last node of domNode
this._contextMenu.bindDomNode(query('.CodeMirror', this.domNode)[0]);
},
resize : function () {
this.inherited(arguments);
this._refresh();
},
setState : function (state) {
if (!state.fid)
return;
var selection
= state.select
? state.select.split('|').map(function (x) { return parseInt(x); })
: [1, 1, 1, 1];
this.loadFile(state.fid);
this.set('selection', selection);
this.jumpToPos(selection[0], selection[1]);
},
/**
* This function loads a file in the Text module.
* @param {FileInfo | String} file This can be a FileInfo thrift object or a
* file ID.
*/
loadFile : function (file) {
var urlFileInfo = urlHandler.getFileInfo();
if (!(file instanceof FileInfo)) {
// The same file shouldn't be loaded twice after each other.
if (this._fileInfo && file === this._fileInfo.id)
return;
this._fileInfo = urlFileInfo && urlFileInfo.id === file
? urlFileInfo
: model.project.getFileInfo(file);
} else {
this._fileInfo = file;
}
var fileContent = urlFileInfo && urlFileInfo.id === this._fileInfo.id
? urlHandler.getFileContent()
: model.project.getFileContent(this._fileInfo.id);
this.set('content', fileContent);
this.set('header', this._fileInfo);
this._getSyntaxHighlight(this._fileInfo);
if (window.gtag) {
window.gtag('event', 'page_view', {
page_location: window.location.href,
page_path: window.location.pathname + window.location.hash,
page_title: urlFileInfo.path
});
}
},
/**
* This function jumps to the given location. The location will be about 100
* pixels inside from the edge of the editor.
*/
jumpToPos : function (line, column) {
var selPosPixel
= this._codeMirror.charCoords({ line : line, ch : column }, 'local');
var editorSize = {
width : style.get(this.domNode, 'width'),
height : style.get(this.domNode, 'height')
};
this._codeMirror.scrollIntoView({
top : selPosPixel.top - 100,
bottom : selPosPixel.top + editorSize.height - 150,
left : selPosPixel.left < editorSize.width - 100
? 0
: selPosPixel.left - 50,
right : selPosPixel.left < editorSize.width - 100
? 10
: selPosPixel.left + editorSize.width - 100
});
},
/**
* This function calls the markText() function of CodeMirror, thus its
* options are the same except that 'from' and 'to' objects has to have
* 'line' and 'column' attributes.
* @param {Object} from Mark text from this position.
* @param {Object} to Mark text till this position.
* @param {Object} options Pass these options to CodeMirror's markText
* function.
* @return {Number} This function returns an id which can be passed to
* clearMark() function to remove this selection.
*/
markText : function (from, to, options) {
var fln = this._codeMirror.options.firstLineNumber;
this._marks[this._markIdCounter] = this._codeMirror.markText(
{ line : from.line - fln, ch : from.column - 1 },
{ line : to.line - fln, ch : to.column - 1 },
options);
return this._markIdCounter++;
},
/**
* This function clears a text mark.
* @param {Number} markId Id of the selection to remove.
*/
clearMark : function (markId) {
if (markId in this._marks) {
this._marks[markId].clear();
delete this._marks[markId];
}
},
/**
* This function clears all the text marks.
*/
clearAllMarks : function () {
for (var markId in this._marks)
this.clearMark(markId);
this._marks = {};
},
clearSelection : function () {
for (var markId in this._marks) {
if (this._marks[markId].className === 'cb-marked-select')
this.clearMark(markId);
}
},
_eventHandler : function (event) {
//--- Select the clicked word ---//
var pos = this._codeMirror.coordsChar({
top : event.clientY,
left : event.clientX
});
pos = [
pos.line + this._codeMirror.options.firstLineNumber,
pos.ch + 1];
if (!positionInRange(pos, this.get('selection'))) {
var token = this._getWordAt(pos);
this.set('selection', [pos[0], token.start, pos[0], token.end]);
}
//--- Open Info Tree ---//
var astNodeInfo
= astHelper.getAstNodeInfoByPosition(pos, this._fileInfo);
topic.publish('codecompass/infotree', {
fileType : this._fileInfo.type,
elementInfo : astNodeInfo
});
//--- Update URL ---//
if (astNodeInfo)
{
var range = astNodeInfo.range.range;
var selection = [
range.startpos.line,
range.startpos.column,
range.endpos.line,
range.endpos.column];
urlHandler.setStateValue({
select : selection.join('|')
});
}
//--- Highlighting the same occurrence of the selected entity ---//
this._markUsages(pos, this._fileInfo);
//--- Right click ---//
if (event.button === 2)
buildContextMenu(pos, this._fileInfo, this._contextMenu);
//--- Ctrl-click ---//
if (event.button === 0 && event.ctrlKey) {
var service = model.getLanguageService(this._fileInfo.type);
astHelper.jumpToDef(astNodeInfo.id, service);
}
if (window.gtag) {
window.gtag('event', 'click_on_word', {
'event_category' : urlHandler.getState('wsid'),
'event_label' : urlHandler.getFileInfo().name
+ ': '
+ this._getWordAt(pos).string
});
}
},
/**
* This function marks the usages of an AST node.
*/
_markUsages : function (position, fileInfo) {
var that = this;
var astNodeInfo = astHelper.getAstNodeInfoByPosition(position, fileInfo);
if (!astNodeInfo)
return;
var service = model.getLanguageService(fileInfo.type);
var refTypes = service.getReferenceTypes(astNodeInfo.id);
var usages = service.getReferences(
astNodeInfo.id,
refTypes['Usage']);
this.clearSelection();
var fl = that._codeMirror.options.firstLineNumber;
usages.forEach(function (astNodeInfo) {
// TODO: getReferencesInFile() should be called when it will be
// implemented and then this check won't be necessary.
if (astNodeInfo.range.file !== fileInfo.id)
return;
var range = astNodeInfo.range.range;
if (range.endpos.line !== range.startpos.line) {
range.endpos.line = range.startpos.line;
var line = that._codeMirror.getLine(range.startpos.line - fl);
if (line)
range.endpos.column = line.length + 1;
}
that.markText(range.startpos, range.endpos, {
className : 'cb-marked-select'
});
}, this);
},
/**
* This function returns a token object which represents the clicked word.
* @param {Array} position This parameter describes the clicked position.
* The array has to have two elements: the line and column number
* respectively.
* @return {Object} The returning object has three attributes:
* - string: the word as a string under the clicked position.
* - start: the start position of the clicked word.
* - end: the end position of the clicked word.
*/
_getWordAt : function (position) {
var pattern = /[a-z0-9_]/i;
var line = this._codeMirror.getLine(
position[0] - this._codeMirror.options.firstLineNumber);
var start = position[1] - 1;
while (start > -1 && line[start] && line[start].match(pattern))
--start;
++start;
var end = position[1] - 1;
while (end < line.length && line[end] && line[end].match(pattern))
++end;
return {
string : line.substring(start, end),
start : start + 1,
end : end + 1
};
},
/**
* This function gets syntax highlight information from server and
* highlights the elements in the text editor.
* @param fileInfo
*/
_getSyntaxHighlight : function (fileInfo) {
var that = this;
var service = model.getLanguageService(fileInfo.type);
if (!service) {
return;
}
setTimeout(function () {
var lines = urlHandler.getFileContent().split('\n').length;
for (var i = 0; i < lines; i += that._syntaxHighlightStep) {
var range = new FileRange({
file : fileInfo.id,
range : new Range({
startpos : new Position({line : i}),
endpos : new Position({line : i + that._syntaxHighlightStep}),
})
});
service.getSyntaxHighlight(range, function (syntax) {
syntax.forEach(function (s) {
this.markText(s.range.startpos, s.range.endpos, {
className: s.className
});
}, that);
});
}
}, 500);
},
_refresh : function () {
var that = this;
setTimeout(function () {
var fullHeight = parseInt(style.getComputedStyle(that.domNode).height);
var headerHeight = util.getFullHeight(that._header.header);
that._codeMirror.setSize('100%', (fullHeight - headerHeight) + 'px');
that._codeMirror.refresh();
}, 0);
},
_subscribeTopics : function () {
var that = this;
// Opens a file and sets the center module to this. Message attributes:
// - fileId: The ID of the file to load.
// - selection (optional): An array of four elements which determines the
// range of highlight in the text: start line, start column, end line
// and end column respectively.
// - line (optional): The line number to jump to when the file is loaded.
topic.subscribe('codecompass/openFile', function (message) {
if (!message.selection)
message.selection = [1, 1, 1, 1];
urlHandler.setStateValue({
fid : message.fileId,
select : message.selection.join('|'),
center : that.id
});
topic.publish('codecompass/setCenterModule', that.id);
that.loadFile(message.fileId);
that.set('selection', message.selection);
that.jumpToPos(
message.line || 0,
message.selection ? message.selection[1] : 0);
});
},
/**
* This function highlights the given range in the editor.
* @param {Array} range An array containing four elements: start line, start
* column, end line, end column respectively. This array determined the
* range to select. The end column is exclusive, i.e. not part of the range.
*/
_setSelectionAttr : function (range) {
var that = this;
this.selection = range;
setTimeout(function () {
var fl = that._codeMirror.options.firstLineNumber;
that._codeMirror.doc.setSelection(
{ line : range[2] - fl, ch : range[3] - 1 },
{ line : range[0] - fl, ch : range[1] - 1 });
}, 0);
},
_setContentAttr : function (content) {
this._codeMirror.doc.setValue(content);
},
_setHeaderPathAttr : function (path) {
path = path.split('/').slice(1);
var pathElements = dom.create('span');
var string = '';
path.forEach(function (file) {
string += '/' + file;
var s = string; // This is needed because of closure affairs.
dom.place(dom.toDom('/'), pathElements);
dom.place(dom.create('span', {
innerHTML : file,
class : 'pathelement',
onclick : function () { topic.publish('codecompass/openPath', s); }
}), pathElements);
});
dom.place(pathElements, this._header.path, 'only');
},
_setHeaderAttr : function (fileInfo) {
var statusClasses = ['fullyparsed', 'partiallyparsed', 'notparsed'];
domClass.remove(this._header.parsestatus, statusClasses);
switch (fileInfo.parseStatus) {
case FileParseStatus.FullyParsed:
domClass.add(this._header.parsestatus, statusClasses[0]);
dom.place(dom.toDom('(Fully parsed)'), this._header.parsestatus, 'only');
break;
case FileParseStatus.PartiallyParsed:
domClass.add(this._header.parsestatus, statusClasses[1]);
dom.place(dom.toDom('(Partially parsed)'), this._header.parsestatus, 'only');
break;
default:
domClass.add(this._header.parsestatus, statusClasses[2]);
dom.place(dom.toDom('(Not parsed)'), this._header.parsestatus, 'only');
}
dom.place(dom.toDom(fileInfo.name), this._header.filename, 'only');
this.set('headerPath', fileInfo.path);
}
});
});