/
CodeEditor.cpp
479 lines (380 loc) · 14.7 KB
/
CodeEditor.cpp
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
/****************************************************************************
**
** Copyright (c) 2011 Digia Plc
** All rights reserved.
** For any questions to Digia, please use contact form at http://qt.digia.com
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia nor the names of its contributors
** may be used to endorse or promote products derived from this
** software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
****************************************************************************/
#include <QtGui>
#include "codeeditor.h"
CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent){
lineNumberArea = new LineNumberArea(this);
findDialog_ = new FindDialog(this);
findDialog_->setModal(false);
findDialog_->setTextEdit(this);
findReplaceDialog_ = new FindReplaceDialog(this);
findReplaceDialog_->setModal(false);
findReplaceDialog_->setTextEdit(this);
qtScriptReservedWords_<<"break"<<"case"<<"catch"<<"continue"<<"debugger"<<"default"<<"delete"<<"do"<<"else"<<"finally"<<\
"for"<<"function"<<"if"<<"in"<<"instanceof"<<"new"<<"return"<<"switch"<<"this"<<"throw"<<"try"<<\
"typeof"<<"var"<<"void"<<"while"<<"with";
syntaxHighlighter_ = new ScriptSyntaxHighlighter(this->document());
s = Global::guiSettings(this);
s->beginGroup("CodeEditor");
QFont font = s->value("font",this->font()).value<QFont>();
this->setFont(font);
s->endGroup();
findAction = new QAction("Find...",this);
connect(findAction, SIGNAL(triggered()), this, SLOT(findDialog()));
findAction->setShortcut(tr("Ctrl+F"));
addAction(findAction);
findReplaceAction = new QAction("Replace...",this);
connect(findReplaceAction, SIGNAL(triggered()), this, SLOT(findReplaceDialog()));
findReplaceAction->setShortcut(tr("Ctrl+R"));
addAction(findReplaceAction);
beautifyAction = new QAction("Beautify javascript code",this);
connect(beautifyAction, SIGNAL(triggered()), this, SLOT(beautify()));
beautifyAction->setShortcut(tr("Ctrl+B"));
addAction(beautifyAction);
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
updateLineNumberAreaWidth(0);
highlightCurrentLine();
completer_ = new QCompleter(this);
completer_->setModel(modelFromStringList(qtScriptReservedWords_));
completer_->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
completer_->setCaseSensitivity(Qt::CaseInsensitive);
completer_->setWrapAround(false);
this->setCompleter(completer_);
}
void CodeEditor::findDialog() {
findDialog_->show();
}
void CodeEditor::findReplaceDialog() {
findReplaceDialog_->show();
}
void CodeEditor::addCompletionWords(const QStringList& words){
QStringList words2=completionWords();
words2.append(words);
words2=words2.toSet().toList();
qSort(words2.begin(),words2.end(),Global::stringLessThanCaseInSensitive);
QStringListModel *model = qobject_cast<QStringListModel*>(completer_->model());
if(model){
model->setStringList(words2);
}
}
QHash<QString,QVariant> CodeEditor::userData() const{
return userData_;
}
void CodeEditor::setUserData( const QHash<QString,QVariant> &userData ){
userData_=userData;
}
void CodeEditor::setUserData( const QString &key, const QVariant &userData ){
userData_[key]=userData;
}
void CodeEditor::setCompletionWords(const QStringList& words){
QStringList words2=words;
words2=words2.toSet().toList();
qSort(words2.begin(),words2.end(),Global::stringLessThanCaseInSensitive);
QStringListModel *model = qobject_cast<QStringListModel*>(completer_->model());
if(model){
model->setStringList(words2);
}
}
QStringList CodeEditor::completionWords() const{
QStringList words;
QStringListModel *model = qobject_cast<QStringListModel*>(completer_->model());
if(model){
words=model->stringList();
}
return words;
}
void CodeEditor::insertCompletion(const QString& completion){
if (completer_->widget() != this){
return;
}
QTextCursor tc = textCursor();
//Delete the characters that the user has entered as it might be in
//wrong case, and insert entire completion word.
tc.movePosition(QTextCursor::StartOfWord);
int toDelete = completer_->completionPrefix().length();
for(int i=0;i<toDelete;i++){
tc.deleteChar();
}
tc.insertText(completion);
setTextCursor(tc);
/*
//original code, insert only missing characters and keep the characters
//the user has already entered.
int extra = completion.length() - completer_->completionPrefix().length();
tc.movePosition(QTextCursor::Left);
tc.movePosition(QTextCursor::EndOfWord);
tc.insertText(completion.right(extra));
setTextCursor(tc);
*/
}
QString CodeEditor::textUnderCursor() const{
QTextCursor tc = textCursor();
tc.select(QTextCursor::WordUnderCursor);
return tc.selectedText();
}
void CodeEditor::focusInEvent(QFocusEvent *e){
if (completer_){
completer_->setWidget(this);
}
QPlainTextEdit::focusInEvent(e);
}
QCompleter *CodeEditor::completer() const{
return completer_;
}
void CodeEditor::setCompleter(QCompleter *completer){
if(completer_){
QObject::disconnect(completer_, 0, this, 0);
}
completer_ = completer;
if (!completer_){
return;
}
completer_->setWidget(this);
completer_->setCompletionMode(QCompleter::PopupCompletion);
completer_->setCaseSensitivity(Qt::CaseInsensitive);
QObject::connect(completer_, SIGNAL(activated(QString)),
this, SLOT(insertCompletion(QString)));
}
CodeEditor::~CodeEditor() {
delete s;s=0;
}
void CodeEditor::beautify(){
//QString text = this->textCursor().selectedText();
QString text = this->toPlainText();
int current = currentLine();
text = beautifyJavaScriptCode(text);
this->setPlainText(text);
this->setCurrentLine(current);
}
int CodeEditor::currentLine() const{
return this->textCursor().blockNumber();
}
void CodeEditor::setCurrentLine(int line){
QTextCursor c = this->textCursor();
c.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor, line);
this->setTextCursor(c);
}
QString CodeEditor::beautifyJavaScriptCode( const QString &source ){
QScriptEngine engine;
QScriptValue options = engine.newObject();
options.setProperty("preserve_newlines", true);
options.setProperty("space_after_anon_function", true);
options.setProperty("braces_on_own_line", false);
options.setProperty("keep_array_indentation", true);
if (source.isEmpty()) {
return source;
}
QString fileName = qApp->applicationDirPath()+"/beautify.js";
QFile file(fileName);
if(!file.exists()){
QMessageBox::critical(0,"","Could not find 'beautify.js' in application directory! Cannot beautify code.");
return source;
}
if(!file.open(QFile::ReadOnly)) {
return source;
}
QString script = file.readAll();
file.close();
if (script.isEmpty()) {
return source;
}
engine.evaluate(script);
engine.globalObject().setProperty("source", QScriptValue(source));
engine.globalObject().setProperty("options", options);
QScriptValue result = engine.evaluate("js_beautify(source, options);");
return result.toString();
}
void CodeEditor::contextMenuEvent(QContextMenuEvent *event){
QMenu *menu = this->createStandardContextMenu();
menu->addAction(beautifyAction);
menu->addAction(findAction);
menu->addAction(findReplaceAction);
QAction *editFontAction = new QAction("Edit font...",this);
connect(editFontAction,SIGNAL(triggered()),this,SLOT(fontDialog()));
menu->addAction(editFontAction);
if(!example_.isEmpty()){
QAction *insertExampleAction = new QAction("Insert example code",this);
connect(insertExampleAction,SIGNAL(triggered()),this,SLOT(insertExample()));
menu->addAction(insertExampleAction);
}
menu->exec(event->globalPos());
}
int CodeEditor::lineNumberAreaWidth(){
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
return space;
}
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */){
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CodeEditor::updateLineNumberArea(const QRect &rect, int dy){
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CodeEditor::focusOutEvent(QFocusEvent *e) {
emit editingFinished();
QPlainTextEdit::focusOutEvent(e);
}
void CodeEditor::resizeEvent(QResizeEvent *e){
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CodeEditor::highlightCurrentLine(){
QList<QTextEdit::ExtraSelection> extraSelections;
if (!isReadOnly()) {
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor(Qt::yellow).lighter(160);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();
extraSelections.append(selection);
}
setExtraSelections(extraSelections);
}
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event){
QPainter painter(lineNumberArea);
painter.fillRect(event->rect(), Qt::lightGray);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(Qt::black);
painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
void CodeEditor::setExample(const QString &example){
example_=example;
if(this->toolTip().isEmpty()){
this->setToolTip(example);
}
}
QString CodeEditor::example() const{
return example_;
}
void CodeEditor::insertExample(){
this->insertPlainText(example_);
}
QStringListModel *CodeEditor::modelFromStringList(const QStringList &list){
QStringList words=list.toSet().toList();
qSort(words.begin(),words.end(),Global::stringLessThanCaseInSensitive);
return new QStringListModel(words, completer_);
}
void CodeEditor::setText(const QString &text){
this->setPlainText(text);
}
QString CodeEditor::text() const{
return this->toPlainText();
}
/*!
\brief Show a dialog to edit the font of the texteditor
*/
void CodeEditor::fontDialog(){
bool ok;
QFont font = QFontDialog::getFont(&ok, this->font(), this);
if( ok ){
this->setFont(font);
s->beginGroup("CodeEditor");
s->setValue("font",this->font());
s->endGroup();
s->sync();
}
}
void CodeEditor::keyPressEvent(QKeyEvent *e)
{
if (completer_ && completer_->popup()->isVisible()) {
// The following keys are forwarded by the completer to the widget
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
e->ignore();
return; // let the completer do default behavior
default:
break;
}
}
bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E
if (!completer_ || !isShortcut) // do not process the shortcut when we have a completer
QPlainTextEdit::keyPressEvent(e);
const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
if (!completer_ || (ctrlOrShift && e->text().isEmpty()))
return;
static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word
bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
QString completionPrefix = textUnderCursor();
if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3
|| eow.contains(e->text().right(1)))) {
completer_->popup()->hide();
return;
}
if (completionPrefix != completer_->completionPrefix()) {
completer_->setCompletionPrefix(completionPrefix);
completer_->popup()->setCurrentIndex(completer_->completionModel()->index(0, 0));
}
QRect cr = cursorRect();
cr.setWidth(completer_->popup()->sizeHintForColumn(0)
+ completer_->popup()->verticalScrollBar()->sizeHint().width());
completer_->complete(cr); // popup it up!
}