File: BasicEdit.cpp

package info (click to toggle)
basic256 2.0.0.11-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 15,076 kB
  • sloc: cpp: 16,791; yacc: 3,979; lex: 1,446; makefile: 25
file content (1059 lines) | stat: -rwxr-xr-x 39,557 bytes parent folder | download
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
/** Copyright (C) 2006, Ian Paul Larsen.
 **
 **  This program is free software; you can redistribute it and/or modify
 **  it under the terms of the GNU General Public License as published by
 **  the Free Software Foundation; either version 2 of the License, or
 **  (at your option) any later version.
 **
 **  This program is distributed in the hope that it will be useful,
 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 **  GNU General Public License for more details.
 **
 **  You should have received a copy of the GNU General Public License along
 **  with this program; if not, write to the Free Software Foundation, Inc.,
 **  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 **/



#include <iostream>
#include <QScrollBar>
#include <QTextCursor>
#include <QTextBlock>
#include <QFlags>
#include <QPainter>
#include <QResizeEvent>
#include <QPaintEvent>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QStatusBar>
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrintDialog>
#include <QtWidgets/QFontDialog>

#include "MainWindow.h"
#include "BasicEdit.h"
#include "LineNumberArea.h"
#include "Settings.h"
#include "Constants.h"

extern int guiState;

BasicEdit::BasicEdit(const QString & defaulttitle) {
	currentLine = 1;
	runState = RUNSTATESTOP;
    rightClickBlockNumber = -1;
    breakPoints = new QList<int>;
    title = defaulttitle;
    windowtitle = defaulttitle;
    filename.clear();
    path.clear();
    undoButton = false;
    redoButton = false;
    copyButton = false;
    action = new QAction(windowtitle, this);
    action->setCheckable(true);
    fileChangedOnDiskFlag = false;

    setReadOnly(guiState!=GUISTATENORMAL);
    if(guiState==GUISTATEAPP){
        startPos=0;
        lineNumberArea = NULL;
        setDisabled(true);
    }else{
        lineNumberArea = new LineNumberArea(this);
        this->setInputMethodHints(Qt::ImhNoPredictiveText);
        startPos = this->textCursor().position();
        updateLineNumberAreaWidth(0);
        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(cursorMove()));
        connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
        connect(this, SIGNAL(modificationChanged(bool)), this, SLOT(updateTitle()));
        connect(this, SIGNAL(undoAvailable(bool)), this, SLOT(slotUndoAvailable(bool)));
        connect(this, SIGNAL(redoAvailable(bool)), this, SLOT(slotRedoAvailable(bool)));
        connect(this, SIGNAL(copyAvailable(bool)), this, SLOT(slotCopyAvailable(bool)));
        connect(action, SIGNAL(triggered()), this, SLOT(actionWasTriggered()));
        highlightCurrentLine();
    }
}


BasicEdit::~BasicEdit() {
    if (breakPoints) {
        delete breakPoints;
        breakPoints = NULL;
    }
    if (lineNumberArea) {
		delete lineNumberArea;
		lineNumberArea = NULL;
	}
}

void BasicEdit::setFont(QFont f) {
	// set the font and the tab stop at EDITOR_TAB_WIDTH spaces
	QPlainTextEdit::setFont(f);
	QFontMetrics metrics(f);
	setTabStopWidth(metrics.width(" ")*EDITOR_TAB_WIDTH);
    updateLineNumberAreaWidth(blockCount());
}


void
BasicEdit::cursorMove() {
	QTextCursor t(textCursor());
	emit(changeStatusBar(tr("Line: ") + QString::number(t.blockNumber()+1)
		+ tr(" Character: ") + QString::number(t.positionInBlock())));
}

void
BasicEdit::seekLine(int newLine) {
    // go to a line number and set
	// the text cursor
	//
	// code should be proximal in that it should be closest to look at the curent
    // position than to go and search the entire program from the top
    QTextCursor t = textCursor();
    int line = t.blockNumber()+1;	// current line number for the block
    // go back or forward to the line from the current position
    if (line<newLine) {
        // advance forward
        while (line < newLine && t.movePosition(QTextCursor::NextBlock)) {
            line++;
        }
    } else if (line>newLine){
        // go back to find the line
        while (line > newLine && t.movePosition(QTextCursor::PreviousBlock)) {
            line--;
        }
    }
	setTextCursor(t);
}

void BasicEdit::slotWhitespace(bool checked) {
	// toggle the display of whitespace characters
	// http://www.qtcentre.org/threads/27245-Printing-white-spaces-in-QPlainTextEdit-the-QtCreator-way
	QTextOption option = document()->defaultTextOption();
	if (checked) {
		option.setFlags(option.flags() | QTextOption::ShowTabsAndSpaces);
	} else {
		option.setFlags(option.flags() & ~QTextOption::ShowTabsAndSpaces);
	}
	option.setFlags(option.flags() | QTextOption::AddSpaceForLineAndParagraphSeparators);
	document()->setDefaultTextOption(option);
}

void
BasicEdit::goToLine(int newLine) {
    seekLine(newLine);
    setFocus();
}


void
BasicEdit::keyPressEvent(QKeyEvent *e) {
	e->accept();
    //Autoindent new line as previous one
	if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter){
		QPlainTextEdit::keyPressEvent(e);
		QTextCursor cur = textCursor();
		cur.movePosition(QTextCursor::PreviousBlock);
		cur.movePosition(QTextCursor::StartOfBlock);
		cur.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
		QString str = cur.selectedText();
		QRegExp rx("^([\\t ]+)");
		if(str.indexOf(rx) >= 0)
			textCursor().insertText(rx.cap(1));
	}else if(e->key() == Qt::Key_Tab && e->modifiers() == Qt::NoModifier){
		if(!indentSelection())
			QPlainTextEdit::keyPressEvent(e);
	}else if((e->key() == Qt::Key_Tab && e->modifiers() & Qt::ShiftModifier) || e->key() == Qt::Key_Backtab){
		unindentSelection();
	}else{
		QPlainTextEdit::keyPressEvent(e);
	}
}


void BasicEdit::saveFile(bool overwrite) {
	// BE SURE TO SET filename PROPERTY FIRST
	// or set it to '' to prompt for a new file name
	if (filename == "") {
        emit(setCurrentEditorTab(this)); //activate editor window
        filename = QFileDialog::getSaveFileName(this, tr("Save file as"), title+".kbs", tr("BASIC-256 File ") + "(*.kbs);;" + tr("Any File ")  + "(*.*)");
	}

	if (filename != "") {
		QRegExp rx("\\.[^\\/]*$");
		if (rx.indexIn(filename) == -1) {
			filename += ".kbs";
		}
		QFile f(filename);
		bool dooverwrite = true;
		if (!overwrite && f.exists()) {
			dooverwrite = ( QMessageBox::Yes == QMessageBox::warning(this, tr("Save File"),
				tr("The file ") + filename + tr(" already exists.")+ "\n" +tr("Do you want to overwrite?"),
				QMessageBox::Yes | QMessageBox::No,
				QMessageBox::No));
		}
		if (dooverwrite) {
			f.open(QIODevice::WriteOnly | QIODevice::Truncate);
			f.write(this->document()->toPlainText().toUtf8());
			f.close();
			QFileInfo fi(f);
            document()->setModified(false);
            setTitle(fi.fileName());
			QDir::setCurrent(fi.absolutePath());
            emit(addFileToRecentList(filename));
		}
	}
}

void BasicEdit::saveAllStep(int s) {
    if(document()->isModified()){
        if(s==1){
            // Step 1 - save changes
            if(!filename.isEmpty()) saveFile(true);
        }else{
            // Step 2 - save unsaved files (need user interaction)
            if(filename.isEmpty()) saveFile(true);
        }
    }
}

void BasicEdit::saveProgram() {
    saveFile(false);
}

void
BasicEdit::saveAsProgram() {
    QString tempfilename = QFileDialog::getSaveFileName(this, tr("Save file as"), ".", tr("BASIC-256 File ")+ "(*.kbs);;" + tr("Any File ")+ "(*.*)");
    if (tempfilename != "") {
        filename = tempfilename;
        saveFile(false);
    }
}




void BasicEdit::slotPrint() {
#ifdef ANDROID
    QMessageBox::warning(this, tr("Print"),
        tr("Printing is not supported in this platform at this time."));
#else
    QTextDocument *document = this->document();
    QPrinter printer;

    QPrintDialog *dialog = new QPrintDialog(&printer, this);
    dialog->setWindowTitle(tr("Print Code"));

    if (dialog->exec() == QDialog::Accepted) {
        if ((printer.printerState() != QPrinter::Error) && (printer.printerState() != QPrinter::Aborted)) {

            QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
            document->print(&printer);
            QApplication::restoreOverrideCursor();
        } else {
            QMessageBox::warning(this, tr("Print"),
                tr("Unable to carry out printing.\nPlease check your printer settings."));
        }

    }
    
    delete dialog;
#endif
}



void BasicEdit::beautifyProgram() {
	QString program;
	QStringList lines;
	int indent = 0;
	bool indentThisLine = true;
	bool increaseIndent = false;
	bool decreaseIndent = false;
	bool increaseIndentDouble = false;
	bool decreaseIndentDouble = false;
	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
	program = this->document()->toPlainText();
	lines = program.split(QRegExp("\\n"));
	for (int i = 0; i < lines.size(); i++) {
		QString line = lines.at(i);
		line = line.trimmed();
        if(line.isEmpty()){
            // label - empty line no indent
            indentThisLine = false;
        } else if (line.contains(QRegExp("^\\S+[:]"))) {
			// label - one line no indent
			indentThisLine = false;
		} else if (line.contains(QRegExp("^(for)|(foreach)\\s", Qt::CaseInsensitive))) {
			// for - indent next (block of code)
			increaseIndent = true;
		} else if (line.contains(QRegExp("^next(\\s)", Qt::CaseInsensitive))) {
			// next var - come out of block - reduce indent
			decreaseIndent = true;
		} else if (line.contains(QRegExp("^next$", Qt::CaseInsensitive))) {
			// next - come out of block - reduce indent
			decreaseIndent = true;
		} else if (line.contains(QRegExp("^if\\s.+\\sthen\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// if/then (NOTHING FOLLOWING) - indent next (block of code)
			increaseIndent = true;
		} else if (line.contains(QRegExp("^else\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// else - come out of block and start new block
			decreaseIndent = true;
			increaseIndent = true;
		} else if (line.contains(QRegExp("^end\\s*if\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// end if - come out of block - reduce indent
			decreaseIndent = true;
		} else if (line.contains(QRegExp("^while\\s", Qt::CaseInsensitive))) {
			// while - indent next (block of code)
			increaseIndent = true;
		} else if (line.contains(QRegExp("^end\\s*while\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// endwhile - come out of block
			decreaseIndent = true;
		} else if (line.contains(QRegExp("^function\\s", Qt::CaseInsensitive))) {
			// function - indent next (block of code)
			increaseIndent = true;
		} else if (line.contains(QRegExp("^end\\s*function\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// endfunction - come out of block
			decreaseIndent = true;
		} else if (line.contains(QRegExp("^subroutine\\s", Qt::CaseInsensitive))) {
			// function - indent next (block of code)
			increaseIndent = true;
		} else if (line.contains(QRegExp("^end\\s*subroutine\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// endfunction - come out of block
			decreaseIndent = true;
		} else if (line.contains(QRegExp("^do\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// do - indent next (block of code)
			increaseIndent = true;
		} else if (line.contains(QRegExp("^until\\s", Qt::CaseInsensitive))) {
			// until - come out of block
			decreaseIndent = true;
		} else if (line.contains(QRegExp("^try\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// try indent next (block of code)
			increaseIndent = true;
		} else if (line.contains(QRegExp("^catch\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// catch - come out of block and start new block
			decreaseIndent = true;
			increaseIndent = true;
		} else if (line.contains(QRegExp("^end\\s*try\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// end try - come out of block - reduce indent
			decreaseIndent = true;
		} else if (line.contains(QRegExp("^begin\\s*case\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// begin case double indent next (block of code)
			increaseIndentDouble = true;
		} else if (line.contains(QRegExp("^end\\s*case\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// end case double reduce
			decreaseIndentDouble = true;
		} else if (line.contains(QRegExp("^case\\s.+\\s*((#|(rem\\s)).*)?$", Qt::CaseInsensitive))) {
			// case expression - indent one line
			decreaseIndent = true;
			increaseIndent = true;
		}
		//
		if (decreaseIndent) {
			indent--;
			if (indent<0) indent=0;
			decreaseIndent = false;
		}
		if (decreaseIndentDouble) {
			indent-=2;
			if (indent<0) indent=0;
			decreaseIndentDouble = false;
		}
		if (indentThisLine) {
			line = QString(indent, QChar('\t')) + line;
		} else {
			indentThisLine = true;
		}
		if (increaseIndent) {
			indent++;
			increaseIndent = false;
		}
		if (increaseIndentDouble) {
			indent+=2;
			increaseIndentDouble = false;
		}
		//
		lines.replace(i, line);
	}
    //this->setPlainText(lines.join("\n"));
    QTextCursor cursor = this->textCursor();
    cursor.select(QTextCursor::Document);
    cursor.insertText(lines.join("\n"));
	QApplication::restoreOverrideCursor();
}

void BasicEdit::findString(QString s, bool reverse, bool casesens, bool words)
{
	if(s.length()==0) return;
	QTextDocument::FindFlags flag;
	if (reverse) flag |= QTextDocument::FindBackward;
	if (casesens) flag |= QTextDocument::FindCaseSensitively;
	if (words) flag |= QTextDocument::FindWholeWords;

	QTextCursor cursor = this->textCursor();
	// here we save the cursor position and the verticalScrollBar value
    QTextCursor cursorSaved = cursor;
    int scroll = verticalScrollBar()->value();

    if (!find(s, flag))
	{
        //nothing is found | jump to start/end
        setUpdatesEnabled(false);
        cursor.movePosition(reverse?QTextCursor::End:QTextCursor::Start);
        setTextCursor(cursor);

        if (!find(s, flag))
        {
            // word not found : we set the cursor back to its initial position and restore verticalScrollBar value
			setTextCursor(cursorSaved);
            verticalScrollBar()->setValue(scroll);
            setUpdatesEnabled(true);
            QMessageBox::information(this, tr("Find"),
                tr("String not found."),
                QMessageBox::Ok, QMessageBox::Ok);
        }else{
            //start from current screen position -> no scroll or scroll only as needed
            //if next search is in the same view
            verticalScrollBar()->setValue(scroll);
            // we can use ensureCursorVisible() but we want to make sure that entire selection is visible
            cursor = this->textCursor();
            cursorSaved = cursor;
            cursor.setPosition(cursor.selectionStart());
            setTextCursor(cursor);
            setTextCursor(cursorSaved);
            setUpdatesEnabled(true);
        }
    }
}

void BasicEdit::replaceString(QString from, QString to, bool reverse, bool casesens, bool words, bool doall) {
	if(from.length()==0) return;

	// Replace one time.
	if(!doall){
		//Replace if text is selected - use the cursor from the last find not the copy
        QTextCursor cursor = this->textCursor();
        if (from.compare(cursor.selectedText(),(casesens ? Qt::CaseSensitive : Qt::CaseInsensitive))==0){
			cursor.insertText(to);
		}

		//Make a search
        findString(from, reverse, casesens, words);

    //Replace all
    }else{
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
        setUpdatesEnabled(false);
        QTextCursor cursor = this->textCursor();
        QTextCursor cursorSaved = cursor;
        int scroll = verticalScrollBar()->value();
        cursor.beginEditBlock();
        int n = 0;
		cursor.movePosition(QTextCursor::Start);
		setTextCursor(cursor);
        QTextDocument::FindFlags flag;
        if (casesens) flag |= QTextDocument::FindCaseSensitively;
        if (words) flag |= QTextDocument::FindWholeWords;
		while (find(from, flag)){
			if (textCursor().hasSelection()){
				textCursor().insertText(to);
				n++;
			}
		}
		// set the cursor back to its initial position and restore verticalScrollBar value
        setTextCursor(cursorSaved);
        verticalScrollBar()->setValue(scroll);
        cursor.endEditBlock();
        setUpdatesEnabled(true);
        QApplication::restoreOverrideCursor();
        if(n==0)
			QMessageBox::information(this, tr("Replace"),
				tr("String not found."),
				QMessageBox::Ok, QMessageBox::Ok);
		else
            QMessageBox::information(this, tr("Replace"),
				tr("Replace completed.") + "\n" + QString::number(n) + " " + tr("occurrence(s) were replaced."),
				QMessageBox::Ok, QMessageBox::Ok);
	}
}

QString BasicEdit::getCurrentWord() {
    // get the cursor and find the current word on this line
    // anything but letters delimits
    QString w;
    QTextCursor t(textCursor());
    QTextBlock b(t.block());
    w = b.text();
    w = w.left(w.indexOf(QRegExp("[^a-zA-Z0-9]"),t.positionInBlock()));
    w = w.mid(w.lastIndexOf(QRegExp("[^a-zA-Z0-9]"))+1);
    return w;
}

int BasicEdit::lineNumberAreaWidth() {
    int digits = 1;
    int max = qMax(1, blockCount());
    while (max >= 10) {
        max /= 10;
        ++digits;
    }
    int space = 10 + fontMetrics().width(QLatin1Char('9')) * digits;
    return space;
}

void BasicEdit::updateLineNumberAreaWidth(int /* newBlockCount */) {
    //update setViewportMargins only when lineNumberAreaWidth is changed - save CPU
    //(this signal is emitted even when user scroll up or scroll down code)
    int w = lineNumberAreaWidth();
    if(w!=lastLineNumberAreaWidth){
        lastLineNumberAreaWidth=w;
        setViewportMargins(w, 0, 0, 0);
    }
}

void BasicEdit::updateLineNumberArea(const QRect &rect, int dy) {
    if (dy) {
        lineNumberArea->scroll(0, dy);
    } else {
        lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
    }
}



void BasicEdit::highlightCurrentLine() {
    if(guiState==GUISTATEAPP) return;
    QList<QTextEdit::ExtraSelection> extraSelections;
    QTextEdit::ExtraSelection blockSelection;
    QTextEdit::ExtraSelection selection;
    QColor lineColor;
    QColor blockColor;

    if(guiState==GUISTATERUN || runState==RUNSTATERUN){
        // editor is in readOnly mode so line will be red (forbidden)
        lineColor = QColor(Qt::red).lighter(175);
        blockColor = QColor(Qt::red).lighter(190);
    }else if (runState==RUNSTATERUNDEBUG || runState==RUNSTATEDEBUG) {
        // if we are executing in debug mode
        lineColor = QColor(Qt::green).lighter(175);
        blockColor = lineColor;
    }else{
        // in edit mode
        lineColor = QColor(Qt::yellow).lighter(165);
        blockColor = QColor(Qt::yellow).lighter(190);
    }

    blockSelection.format.setBackground(blockColor);
    blockSelection.format.setProperty(QTextFormat::FullWidthSelection, true);
    blockSelection.cursor = textCursor();
    blockSelection.cursor.movePosition(QTextCursor::StartOfBlock,QTextCursor::MoveAnchor);
    blockSelection.cursor.movePosition(QTextCursor::EndOfBlock,QTextCursor::KeepAnchor);
    extraSelections.append(blockSelection);

    selection.format.setBackground(lineColor);
    selection.format.setProperty(QTextFormat::FullWidthSelection, true);
    selection.cursor = textCursor();
    selection.cursor.clearSelection();
    extraSelections.append(selection);


    //mark brackets if we are editing
	if (runState==RUNSTATESTOP && !isReadOnly()) {
        QTextCursor cur = textCursor();
        int pos = cur.position();
        cur.movePosition(QTextCursor::EndOfBlock, QTextCursor::MoveAnchor);
        cur.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
        int posDoc = cur.position();
        pos = pos - posDoc -1;
        QString s = cur.selectedText(); //current line as QString
        int length = s.length();
        QChar cPrev, cNext;


        if(length>1){
            QChar open;
            QChar close;
            QChar c;
            bool lookBefore = false;
            bool lookAfter = false;
            int quote=0;
            int doubleQuote=0;
            int i = 0;
            const QColor bracketColor = QColor(Qt::green).lighter(165);
            QTextEdit::ExtraSelection selectionBracket;

            if(pos>0){
                cPrev = s.at(pos);
                if(cPrev==')'){
                    open = '(';
                    lookBefore = true;
                }else if(cPrev==']'){
                    open = '[';
                    lookBefore = true;
                }else if(cPrev=='}'){
                    open = '{';
                    lookBefore = true;
                }
            }

            if(pos<length-1){
                cNext = s.at(pos+1);
                if(cNext=='('){
                    close = ')';
                    lookAfter = true;
                }else if(cNext=='['){
                    close = ']';
                    lookAfter = true;
                }else if(cNext=='{'){
                    close = '}';
                    lookAfter = true;
                }
            }

            if(lookBefore){
                //check for open bracket
                QList<int> list;
                for(i=0;i<pos;i++){
                    c=s.at(i);
                    if(c=='\"' && quote==0){
                        doubleQuote^=1;
                    }else if(c=='\'' && doubleQuote==0){
                        quote^=1;
                    }else if(quote==0 && doubleQuote==0){
                        if(c==open){
                            list.append(i);
                        }else if(c==cPrev){
                            if(!list.isEmpty())
                                list.removeLast();
                        }
                    }
                }
                if(quote==0 && doubleQuote==0 && !list.isEmpty()){
                    //mark current bracket and the corresponding bracket
                    selectionBracket.format.setBackground(bracketColor);
                    selectionBracket.cursor = textCursor();
                    selectionBracket.cursor.setPosition(pos+posDoc+1);
                    selectionBracket.cursor.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor);
                    extraSelections.append(selectionBracket);
                    selectionBracket.cursor.setPosition(list.last()+posDoc+1);
                    selectionBracket.cursor.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor);
                    extraSelections.append(selectionBracket);
                }
            }else if(lookAfter){
                //else check only for quotes if lookAfter
                for(i=0;i<pos;i++){
                    c=s.at(i);
                    if(c=='\"' && quote==0){
                        doubleQuote^=1;
                    }else if(c=='\'' && doubleQuote==0){
                        quote^=1;
                    }
                }
            }

            if(lookAfter && quote==0 && doubleQuote==0){
                //check for bracket if current bracket is not quoted
                int count = 1;
                for(i=pos+2;i<length;i++){
                    c=s.at(i);
                    if(c=='\"' && quote==0){
                        doubleQuote^=1;
                    }else if(c=='\'' && doubleQuote==0){
                        quote^=1;
                    }else if(quote==0 && doubleQuote==0){
                        if(c==cNext){
                            count++;
                        }else if(c==close){
                            count--;
                            if(count==0){
                                //mark current bracket and the corresponding bracket
                                selectionBracket.format.setBackground(bracketColor);
                                selectionBracket.cursor = textCursor();
                                selectionBracket.cursor.setPosition(pos+posDoc+1);
                                selectionBracket.cursor.movePosition(QTextCursor::NextCharacter,QTextCursor::KeepAnchor);
                                extraSelections.append(selectionBracket);
                                selectionBracket.cursor.setPosition(i+posDoc+1);
                                selectionBracket.cursor.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor);
                                extraSelections.append(selectionBracket);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    setExtraSelections(extraSelections);
}


void BasicEdit::resizeEvent(QResizeEvent *e) {
    QPlainTextEdit::resizeEvent(e);
    if(lineNumberArea){
        QRect cr = contentsRect();
        lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
    }
}


void BasicEdit::lineNumberAreaPaintEvent(QPaintEvent *event) {
    //We need lastBlockNumber to adjust Qt bug (see below)
    QTextCursor t(textCursor());
    int currentBlockNumber = t.blockNumber();
    t.movePosition(QTextCursor::End);
    int lastBlockNumber = t.block().blockNumber();

    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();
    int y = -1;

    if(lineNumberArea->underMouse())
        y = lineNumberArea->mapFromGlobal(QCursor::pos()).y();

    while (block.isValid() && top <= event->rect().bottom()) {
        if (block.isVisible() && bottom > event->rect().top()) {
            QString number = QString::number(blockNumber + 1);

            //Draw lighter background for current paragraph
            //For this to work (and to correctly change the color of current paragraph number) highlightCurrentLine()
            //must set a specialSelection for entire current block. If not, QPaintEvent will update only
            //a small portion of lineNumberAreaPaint (just current line, not entire paragraph), acording with Automatic Clipping.
            //Also there is a bug with last block. See http://stackoverflow.com/questions/37890906/qt-linenumberarea-example-blockboundingrectlastblock
            //or http://www.forum.crossplatform.ru/index.php?showtopic=3963
            if (blockNumber==currentBlockNumber)
                painter.fillRect(0,top,lineNumberArea->width(),bottom-top-(blockNumber==lastBlockNumber?3:0), QColor(Qt::lightGray).lighter(110));
            else if(top <= y && bottom > y && y>=0 && runState != RUNSTATERUN)
                painter.fillRect(0,top,lineNumberArea->width(),bottom-top-(blockNumber==lastBlockNumber?3:0), QColor(Qt::lightGray).lighter(104));

            // Draw breakpoints
            if (block.userState()==STATEBREAKPOINT) {
                    painter.setBrush(Qt::red);
                    painter.setPen(Qt::red);
                    int w = lineNumberArea->width();
                    int bh = blockBoundingRect(block).height();
                    int fh = fontMetrics().height();
                    painter.drawEllipse((w-(fh-6))/2, top+(bh-(fh-6))/2, fh-6, fh-6);
            }
            // draw text
            if (blockNumber==currentBlockNumber) {
                painter.setPen(Qt::blue);
            } else {
                painter.setPen(Qt::black);
            }
            painter.drawText(0, top, lineNumberArea->width()-5, fontMetrics().height(), Qt::AlignRight, number);
        }

        block = block.next();
        top = bottom;
        bottom = top + (int) blockBoundingRect(block).height();
        ++blockNumber;
    }
}


void BasicEdit::lineNumberAreaMouseWheelEvent(QWheelEvent *event) {
    QPlainTextEdit::wheelEvent(event);
}


//Breakpoints are stick to each paragraph by using setUserState to avoid messing up while delete/edit/drop/paste large sections of text.
//breakPoints list is also needed by interpretor. Before running in debug mode breakPoints list is update by calling updateBreakPointsList().
//Because setting/removing breakpoints is enabled in debug mode, we set/unset breakpoints in breakPoints list too.
void BasicEdit::lineNumberAreaMouseClickEvent(QMouseEvent *event) {
    if (runState == RUNSTATERUN)
        return;
    // based on mouse click - set the breakpoint in the map/block and highlight the line
	int line;
	QTextBlock block = firstVisibleBlock();
    int bottom = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); //bottom from previous block
    line = block.blockNumber();
	// line 0 ... (n-1) of what was clicked
	while(block.isValid()) {
		bottom += blockBoundingRect(block).height();
		if (event->y() < bottom) {
            if(event->button() == Qt::LeftButton){
                //keep breakPoints list update for debug running mode
                if(block.userState()==STATEBREAKPOINT){
                    block.setUserState(STATECLEAR);
                    if (breakPoints->contains(line))
                        breakPoints->removeAt(breakPoints->indexOf(line,0));
                }else{
                    block.setUserState(STATEBREAKPOINT);
                    breakPoints->append(line);
                }
                lineNumberArea->repaint();
            }else if(event->button() == Qt::RightButton){
                rightClickBlockNumber = line;
                QMenu contextMenu(this);
                if(block.userState()==STATEBREAKPOINT)
                    contextMenu.addAction ( tr("Remove breakpoint from line") + " " + QString::number(line+1), this , SLOT (toggleBreakPoint()) );
                else
                    contextMenu.addAction ( tr("Set breakpoint at line") + " " + QString::number(line+1), this , SLOT (toggleBreakPoint()) );
                QAction *act = contextMenu.addAction ( tr("Clear all breakpoints") , this , SLOT (clearBreakPoints()) );
                act->setEnabled(isBreakPoint());
                contextMenu.exec (event->globalPos());
            }
            return;
        }
		block = block.next();
		line++;
	}
    QMenu contextMenu(this);
    contextMenu.addAction ( tr("Clear all breakpoints") , this , SLOT (clearBreakPoints()) );
    contextMenu.exec (event->globalPos());
}

void BasicEdit::toggleBreakPoint(){
    if(rightClickBlockNumber<0)
        return;
    QTextBlock block = firstVisibleBlock();
    int n = block.blockNumber();
    if(n<rightClickBlockNumber){
        for(;n<rightClickBlockNumber;n++){
            block = block.next();
        }
    }else if(n>rightClickBlockNumber){
        for(;n>rightClickBlockNumber;n--){
            block = block.previous();
        }
    }
    if(block.isValid()){
        if(block.blockNumber()==rightClickBlockNumber){
            //keep breakPoints list update for debug running mode
            if(block.userState()==STATEBREAKPOINT){
                block.setUserState(STATECLEAR);
                if (breakPoints->contains(rightClickBlockNumber))
                    breakPoints->removeAt(breakPoints->indexOf(rightClickBlockNumber,0));
            }else{
                block.setUserState(STATEBREAKPOINT);
                breakPoints->append(rightClickBlockNumber);
            }
            lineNumberArea->repaint();
        }
    }
    rightClickBlockNumber=-1;
}

void BasicEdit::clearBreakPoints() {
    // remove all breakpoints
    QTextBlock b(document()->firstBlock());
    while (b.isValid()){
        b.setUserState(STATECLEAR);
        b = b.next();
    }
    breakPoints->clear();
    lineNumberArea->repaint();
}

bool BasicEdit::isBreakPoint() {
    // check if there are breakpoints to be cleared (usefull to update menu)
    QTextBlock b(document()->firstBlock());
    while (b.isValid()){
        if(b.userState()==STATEBREAKPOINT)
            return true;
        b = b.next();
    }
    return false;
}

void BasicEdit::updateBreakPointsList() {
    breakPoints->clear();
    QTextBlock b(document()->firstBlock());
    while (b.isValid()){
        if(b.userState()==STATEBREAKPOINT)
            breakPoints->append(b.blockNumber());
        b = b.next();
    }
}


int BasicEdit::indentSelection() {
	QTextCursor cur = textCursor();
	if(!cur.hasSelection())
			return false;
	int a = cur.anchor();
	int p = cur.position();
	int start = (a<=p?a:p);
	int end = (a>p?a:p);

	cur.beginEditBlock();
	cur.setPosition(end);
	int eblock = cur.block().blockNumber();
	cur.setPosition(start);
	int sblock = cur.block().blockNumber();

	for(int i = sblock; i <= eblock; i++)
	{
		cur.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
		cur.insertText("\t");
		cur.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor);
	}
	cur.endEditBlock();
return true;
}


void BasicEdit::unindentSelection() {
	QTextCursor cur = textCursor();
	int a = cur.anchor();
	int p = cur.position();
	int start = (a<=p?a:p);
	int end = (a>p?a:p);

	cur.beginEditBlock();
	cur.setPosition(end);
	int eblock = cur.block().blockNumber();
	cur.setPosition(start);
	int sblock = cur.block().blockNumber();
	QString s;

	for(int i = sblock; i <= eblock; i++)
	{
		cur.movePosition(QTextCursor::EndOfBlock, QTextCursor::MoveAnchor);
		cur.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
		s = cur.selectedText();
		if(!s.isEmpty()){
			if(s.startsWith("    ") || s.startsWith("   \t")){
				cur.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
				cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 4);
				cur.removeSelectedText();
			}else if(s.startsWith("   ") || s.startsWith("  \t")){
				cur.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
				cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 3);
				cur.removeSelectedText();
			}else if(s.startsWith("  ") || s.startsWith(" \t")){
				cur.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
				cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 2);
				cur.removeSelectedText();
			}else if(s.startsWith(" ") || s.startsWith("\t")){
				cur.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
				cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 1);
				cur.removeSelectedText();
			}
		}
		cur.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor);
	}
	cur.endEditBlock();
}

void BasicEdit::setTitle(QString newTitle){
    title = newTitle;
    updateTitle();
}

void BasicEdit::updateTitle(){
    windowtitle = (document()->isModified()?"*":"") + title;
    action->setText(windowtitle);
    emit(updateWindowTitle(this));
}

void BasicEdit::dragEnterEvent(QDragEnterEvent *event){
    if (event->mimeData()->hasFormat("text/plain")){
        event->acceptProposedAction();
        QPlainTextEdit::dragEnterEvent(event);
    }else{
        event->ignore();
    }
}

void BasicEdit::dropEvent(QDropEvent *event){
    if (event->mimeData()->hasFormat("text/plain")){
        event->acceptProposedAction();
        QPlainTextEdit::dropEvent(event);
    }else{
        event->ignore();
    }
}

void BasicEdit::setEditorRunState(int state){
    if(runState == state) return;
    runState = state;
    if(guiState!=GUISTATEAPP){
        if(state==RUNSTATESTOP&&guiState==GUISTATENORMAL){
            setReadOnly(false);
            setTextInteractionFlags(Qt::TextEditorInteraction);
            if(fileChangedOnDiskFlag) handleFileChangedOnDisk();
        } else if(state==RUNSTATERUN||guiState!=GUISTATENORMAL){
            setReadOnly(true);
        }else{
            //Just like readonly but user can not change current line and highlight another one (need in debug mode)
            setTextInteractionFlags(Qt::NoTextInteraction);
        }
        //setDisabled(!(state==RUNSTATESTOP&&guiState==GUISTATENORMAL));
        highlightCurrentLine();
    }
}

void BasicEdit::slotUndoAvailable(bool val){
    undoButton = val;
    emit(updateEditorButtons());
}

void BasicEdit::slotRedoAvailable(bool val){
    redoButton = val;
    emit(updateEditorButtons());
}
void BasicEdit::slotCopyAvailable(bool val){
    copyButton = val;
    emit(updateEditorButtons());
}

void BasicEdit::actionWasTriggered(){
    emit(setCurrentEditorTab(this));
}

void BasicEdit::fileChangedOnDiskSlot(QString fn){
    if(fn==filename){
        if(runState==RUNSTATESTOP){
            if(!fileChangedOnDiskFlag){
                //avoid fileChangedOnDiskSlot to be fired multiple times while program waits user confirmation
                fileChangedOnDiskFlag=true;
                handleFileChangedOnDisk();
            }
        }else{
            fileChangedOnDiskFlag=true;
        }
    }
}

void BasicEdit::handleFileChangedOnDisk(){
    document()->setModified(true);
    updateTitle();
    emit(setCurrentEditorTab(this));
    QFileInfo check_file(filename);
    if(!check_file.exists()){
        QMessageBox::information(this, tr("File has been removed."),
        tr("It seems that file %1 was removed from disk. Don't forget to save your work.").arg(filename));
    }else{
        if( QMessageBox::Yes == QMessageBox::warning(this, tr("File changed"),
        tr("The file %1 has changed outside BASIC256 editor. Do you want to reload it?").arg(filename),
        QMessageBox::Yes | QMessageBox::No, QMessageBox::No)){
            //reload changed file from disk but keep undo history to allow reversing this action
            QFile f(filename);
            if(f.open(QIODevice::ReadOnly)){
                QByteArray ba = f.readAll();
                f.close();
                QTextCursor cursor = this->textCursor();
                cursor.beginEditBlock();
                cursor.select(QTextCursor::Document);
                cursor.insertText(QString::fromUtf8(ba.data()));
                cursor.movePosition(QTextCursor::Start);
                setTextCursor(cursor);
                cursor.endEditBlock();
                document()->setModified(false);
                updateTitle();
            }else{
                QMessageBox::critical(this, tr("Load File"), tr("Unable to open program file") + " \"" + filename + "\".\n" + tr("File permissions problem or file open by another process."));
            }
        }
    }
    fileChangedOnDiskFlag=false;
}