Debian Codegraph @

codeeditor.cpp

raw symbols SCIP
1 /****************************************************************************
2 **
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation ([email protected])
6 **
7 ** This file is part of the examples of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** Commercial Usage
11 ** Licensees holding valid Qt Commercial licenses may use this file in
12 ** accordance with the Qt Commercial License Agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and Nokia.
15 **
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23 **
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27 **
28 ** GNU General Public License Usage
29 ** Alternatively, this file may be used under the terms of the GNU
30 ** General Public License version 3.0 as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL included in the
32 ** packaging of this file. Please review the following information to
33 ** ensure the GNU General Public License version 3.0 requirements will be
34 ** met: http://www.gnu.org/copyleft/gpl.html.
35 **
36 ** If you have questions regarding the use of this file, please contact
37 ** Nokia at [email protected].
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include <QtGui>
43
44 #include "codeeditor.h"
45 #include "fcvsfo.h"
46 #include "shx_helper.h"
47 #include "window.h"
48 #include "dsrgui.h"
49 #include "deprecation.h"
50 #include "partcolor.h"
51 #include <QClipboard>
52
53 CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent), c(0){
54 lineNumberArea = new LineNumberArea(this);
55 lineNumberArea->setObjectName("lineNumberArea");
56 lineNumberArea->setMouseTracking(true);
57 afixHighlightArea = new AfixHighlightArea(this);
58 afixHighlightArea->setObjectName("afixHighlightArea");
59 afixHighlightArea->setMouseTracking(true);
60 startMouseMoveCursor1=false;
61 setMouseTracking(true);
62 m_cursorVisible = false;
63 midCursorpos=0;
64 dark=false;
65 QString theIconPath;
66 if (!QString(PROGRAM_NAME).compare("shelXle")){
67 theIconPath=QString(":/xle-icons/");
68 }else{
69 theIconPath=QString(":/bicons/");
70 }
71 //setTabChangesFocus(true);
72 highlighter = new Highlighter(document());
73 // updateLineNumberAreaWidth(0);
74 //highlightCurrentLine();
75
76 updateAfix();
77
78 suchbox = new QGroupBox("Search and Replace",this);
79 searchLE = new QLineEdit(suchbox);
80 searchLE->setMinimumSize(QSize(150, 0));
81 suchbox->setFlat(true);
82 slt=new QGridLayout(suchbox);
83 hidesearch = new QToolButton(suchbox);
84 hidesearch->setIcon(QIcon(theIconPath+"cancel.svg"));
85 hidesearch->setAutoRaise(true);
86 prev = new QToolButton(suchbox);
87 prev->setIcon(QIcon(theIconPath+"moveleft.svg"));
88 prev->setText("Previous");
89 prev->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
90 prev->setAutoRaise(true);
91 next = new QToolButton(suchbox);
92 next->setIcon(QIcon(theIconPath+"moveright.svg"));
93 next->setText("Next");
94 next->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
95 next->setAutoRaise(true);
96 wholeLine = new QCheckBox("Select whole lines",suchbox);
97 wholeLine->setChecked(false);
98
99 slt->setSpacing(5);
100 //slt->setMargin(0);
101 slt->addWidget(hidesearch,0,0);
102 slt->addWidget(searchLE,0,1);
103 slt->addWidget(prev,0,2);
104 slt->addWidget(next,0,3);
105 slt->setVerticalSpacing (0);
106 slt->addWidget(wholeLine,0,4);
107 // slt->setColumnStretch(6,10);
108 replace = new QLineEdit(suchbox);
109 replace->setMinimumSize(QSize(150, 0));
110
111 replaceButton = new QToolButton(suchbox);
112 replaceButton->setIcon(QIcon(theIconPath+"moveright.svg"));
113 replaceButton->setText("Replace");
114 replaceButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
115 replaceButton->setAutoRaise(true);
116
117 replacePButton = new QToolButton(suchbox);
118 replacePButton->setIcon(QIcon(theIconPath+"moveleft.svg"));
119 replacePButton->setText("Replace");
120 replacePButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
121 replacePButton->setAutoRaise(true);
122 replaceAButton= new QToolButton(suchbox);
123 //ediVis=oupVis=false;
124 replaceAButton->setIcon(QIcon(theIconPath+"all.svg"));
125 //
126
127 replaceAButton->setText("Replace All!");
128 replaceAButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
129 replaceAButton->setAutoRaise(true);
130 slt->addWidget(replace,1,1);
131 slt->addWidget(replacePButton,1,2);
132 slt->addWidget(replaceButton,1,3);
133 slt->addWidget(replaceAButton,1,4);
134 suchbox->setLayout(slt);
135 suchbox->hide();
136 connect(searchLE, SIGNAL(textChanged(const QString&)),this,SLOT(findText()));
137 connect(searchLE, SIGNAL(textChanged(const QString&)),highlighter,SLOT(highlightSearch(const QString &)));
138 connect(next, SIGNAL(clicked() ), this, SLOT(findNext()));
139 connect(prev, SIGNAL(clicked() ), this, SLOT(findPrev()));
140 connect(searchLE, SIGNAL(returnPressed()), this, SLOT(findNext()));
141 connect(replaceButton, SIGNAL(clicked() ), this, SLOT(replaceNext()));
142 connect(replacePButton, SIGNAL(clicked() ), this, SLOT(replacePrev()));
143 connect(replaceAButton, SIGNAL(clicked() ), this, SLOT(replaceAll()));
144 connect(hidesearch, SIGNAL(clicked() ), this, SLOT(hideSearch()));
145
146 //
147 resiFinder = new QComboBox();
148 resiFinder->setSizeAdjustPolicy(QComboBox::AdjustToContents);
149 connect(resiFinder, SIGNAL(activated(int)), this, SLOT(findResi(int)));
150 connect(resiFinder, SIGNAL(destroyed(QObject*)), this, SLOT(resiFinderDestroyed()));
151 //m_cursors = MultiTextCursor(textCursor());
152 connect(this, SIGNAL(cursorPositionChanged()),this, SLOT(slotCursorPositionChanged()));
153 connect(this, SIGNAL(cursorPositionChanged()),this, SLOT(updateCursorPosition()));
154
155
156 connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
157 connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
158 connect(this, SIGNAL(textChanged()),this,SLOT(updateAfix()));
159 connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(testCpd()));
160
161 }
162
163 CodeEditor::~CodeEditor(){
164 //printf("CodeEditor will close%d\n",__LINE__);
165 disconnect(this);
166 //printf("ce%d\n",__LINE__);
167 delete lineNumberArea;
168 //printf("ce%d\n",__LINE__);
169 delete afixHighlightArea;
170 //printf("ce%d\n",__LINE__);
171 delete highlighter;
172 //printf("CodeEditor closed. %d %p\n",__LINE__,chgl);
173
174 }
175
176 int CodeEditor::lineNumberAreaWidth(){
177 int digits = 4;//2;
178 //int max = qMax(1, blockCount());
179 //while (max >= 10) {
180 // max /= 10;
181 // ++digits;
182 //}
183 #if (QT_VERSION>=0x050000)
184 int space = 5 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
185 #else
186 int space = 5 + fontMetrics().width(QLatin1Char('9')) * digits;
187 #endif
188 return space;
189 }
190
191 void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */){
192 setViewportMargins(lineNumberAreaWidth()+15, 0, 0, 0);
193 }
194
195 void CodeEditor::updateLineNumberArea(const QRect &rect, int dy){
196 Q_UNUSED ( rect );
197 // printf("updateLineNumberArea\n");
198 if (dy){
199 lineNumberArea->scroll(0, dy);
200 afixHighlightArea->scroll(0,dy);
201 }
202 /*
203 else{
204 printf("Area->update1 %d %d\n",rect.x(),rect.y());
205 //lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
206 printf("Area->update2\n");
207 //afixHighlightArea->update(0,rect.y(),10,rect.height());
208 printf("Area->update3\n");
209 }*/
210 if (rect.contains(viewport()->rect()))
211 updateLineNumberAreaWidth(0);
212 //*/
213 }
214
215 void CodeEditor::restoreMinimumWidth(){
216 setMinimumWidth(150);
217 //bool b=disconnect(SIGNAL(timeout()),this,SLOT(restoreMinimumWidth()));
218 //printf("restoreMinimumWidth() %d\n",b);
219 }
220
221 void CodeEditor::fitWidth(){
222 //we do not want horizontal scrollbars
223 #if (QT_VERSION>=0x050000)
224 int w=75+
225 fontMetrics().horizontalAdvance(
226 "12345678901234567890123456789012345678901234567890123456789012345678901234567890123"
227 // 0 10 20 30 40 50 60 70 80 90
228 );
229
230 #else
231 int w=75+
232 fontMetrics().width(
233 "12345678901234567890123456789012345678901234567890123456789012345678901234567890123"
234 // 0 10 20 30 40 50 60 70 80 90
235 );
236 #endif
237 //printf("fitWidth %d\n",w);
238 setMinimumWidth(w);
239 update();
240 // the timer is to allow the user make the editor wiget smaller but with scrollbars
241 QTimer *sish =new QTimer(this);
242 connect(sish,SIGNAL(timeout()),this,SLOT(restoreMinimumWidth()));
243 sish->setSingleShot(true);
244 sish->start(5000);
245 }
246
247 void CodeEditor::resizeEvent(QResizeEvent *e){
248 QPlainTextEdit::resizeEvent(e);
249 QRect cr = contentsRect();
250 /*printf("CodeEditor::resizeEvent %d %d (%s) %d %d %d\n",cr.width(),cr.height(),this->objectName().toStdString().c_str(),
251 e->size().width(),e->size().height(),
252 fontMetrics().horizontalAdvance("123456789012345678901234567890123456789012345678901234567890123456789012345678901234")
253 );*/
254 lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
255 afixHighlightArea->setGeometry(QRect(
256 cr.left()+lineNumberAreaWidth()+1,
257 cr.top(),
258 10,cr.height()
259 ));
260 e->accept();
261 }
262
263 void CodeEditor::expandGreaterThan(){//!< some SHELXL re- or constrainst use > to specify a range of atoms this is a problem for sorting atoms
264 QTextDocument *document = this->document();
265 // printf("expandGreaterThan\n");
266 for (int i=0; i<blocks.size(); i++){
267 if (blocks.at(i).startsWith("REM",Qt::CaseInsensitive)) continue;
268 if (blocks.at(i).contains('>')){
269 int comRN=-1,comPart=9999;
270 QString comRL="";
271 QString orig=blocks.at(i);
272 QStringList tokens=orig.split(spaces);
273 int da=tokens.indexOf(">");
274 QRegularExpression toReplace = QRegularExpression(QString("%1\\s+>\\s+%2").arg(tokens.at(da-1),tokens.at(da+1)));
275 QString with="";
276 if (tokens.at(0).contains("_")){
277 QString spec = tokens.at(0).section('_',1,1);
278 if (spec.contains(onlydigits)) comRN=spec.toInt();
279 else if (spec.contains(grossbuch)) comRL=spec;
280 else if (spec.contains(onlysmall)) comPart=spec.toInt(0,36)-9;
281 }
282 bool on=false;
283 //printf("%d %d \n",comRN,comPart);
284 for (int j=0; j< chgl->mol->asymm.size(); j++){
285 if (chgl->mol->asymm.at(j).an<1)continue;
286 QString s=chgl->mol->asymm.at(j).Label.section(QString::fromUtf8("_"),0,0);
287 if ((comRN>0)&&(chgl->mol->asymm.at(j).resiNr!=comRN))continue;
288 if ((comPart!=9999)&&((chgl->mol->asymm.at(j).part!=comPart)||(chgl->mol->asymm.at(j).part!=(25-comPart)))) continue;
289 if ((!comRL.isEmpty())&&(chgl->mol->asymm.at(j).ResiClass!=comRL))continue;
290 if (s==tokens.at(da-1)) on=true;
291 if (on) if (!with.contains(s+" ")){
292 with.append(QString("%1 ").arg(s));
293 if (with.section('=',-1,-1).length()>60) with.append(" = \n ");
294 }
295 if (s==tokens.at(da+1)) on=false;
296 }
297 //DSRGui::textWrap(buffer)
298 //qDebug()<<orig<<toReplace.pattern()<<with;
299 QTextCursor cursor = textCursor();
300 cursor.movePosition(QTextCursor::Start);
301 cursor = document->find(orig,cursor);
302 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
303 cursor =document->find(toReplace);
304 cursor.insertText(with);
305 }
306 if (blocks.at(i).contains('<')){
307 int comRN=-1,comPart=9999;
308 QString comRL="";
309 QString orig=blocks.at(i);
310 QStringList tokens=orig.split(spaces);
311 int da=tokens.indexOf("<");
312 QRegularExpression toReplace=QRegularExpression(QString("%1\\s+<\\s+%2").arg(tokens.at(da-1), tokens.at(da+1)));
313 QString with="";
314 if (tokens.at(0).contains("_")){
315 QString spec = tokens.at(0).section('_',1,1);
316 if (spec.contains(onlydigits)) comRN=spec.toInt();
317 else if (spec.contains(grossbuch)) comRL=spec;
318 else if (spec.contains(onlysmall)) comPart=spec.toInt(0,36)-9;
319 }
320 bool on=false;
321 for (int j=chgl->mol->asymm.size()-1; j>=0; j--){
322 if (chgl->mol->asymm.at(j).an<1)continue;
323 QString s=chgl->mol->asymm.at(j).Label.section(QString::fromUtf8("_"),0,0);
324 if ((comRN>0)&&(chgl->mol->asymm.at(j).resiNr!=comRN))continue;
325 if ((comPart!=9999)&&((chgl->mol->asymm.at(j).part!=comPart)||(chgl->mol->asymm.at(j).part!=(25-comPart)))) continue;
326 if ((!comRL.isEmpty())&&(chgl->mol->asymm.at(j).ResiClass!=comRL))continue;
327 if (s==tokens.at(da-1)) on=true;
328 if (on) if (!with.contains(s+" ")) {
329 with.append(QString("%1 ").arg(s));
330 if (with.section('=',-1,-1).length()>60) with.append(" = \n ");
331 }
332 if (s==tokens.at(da+1)) on=false;
333 }
334 //DSRGui::textWrap(buffer)
335 //qDebug()<<orig<<toReplace.pattern()<<with;
336 QTextCursor cursor = textCursor();
337 cursor.movePosition(QTextCursor::Start);
338 cursor = document->find(orig,cursor);
339 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
340 cursor =document->find(toReplace);
341 cursor.insertText(with);
342 }
343 }
344 }
345
346 QString CodeEditor::selectedRestraintsAtoms(QString buffer, QList<MyAtom> selected, QString resiSpec, bool exclude_H){
347 //! Assembles the selected atom names to parameters for the specific restraint.
348 for (QList<MyAtom>::iterator atom = selected.begin(); atom != selected.end(); atom++) {
349 if((atom->an==0) && (exclude_H)) {//Hydrogen have an == 0 !
350 // excludes hydrogen atoms
351 continue;
352 }
353 if (atom->an < 0) {//non atoms have an < 0
354 // excludes q-peaks, even if exclude_H is false
355 continue;
356 }
357 // Do not add atoms outside of the asymmetric unit to the restraints:
358 if (atom->symmGroup!=0) {
359 continue;
360 }
361 if ((resiSpec.isEmpty()) && (atom->resiNr > 0)) {//I think 'and' is confusing and I prefere &&
362 buffer += (atom->Label.section("_", 0, 0) + QString("_%1").arg(atom->resiNr) + " ");
363 } else {
364 buffer += (atom->Label.section("_", 0, 0) + " ");
365 }
366 }
367 return buffer + "\n";
368 }
369
370 void CodeEditor::updateWght(){
371 if (chgl->mol->asymm.isEmpty()) return;
372 QTextDocument *document = this->document();
373 QTextCursor cursor = textCursor();
374 cursor.beginEditBlock ();
375 cursor.movePosition(QTextCursor::End);
376 cursor = document->find("WGHT",cursor,QTextDocument::FindBackward);
377 if (cursor.isNull()) {
378 cursor = textCursor();
379 cursor.endEditBlock ();
380 return;
381 }
382 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
383 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
384 QString newWeight= cursor.selectedText();
385 cursor.clearSelection();
386
387 cursor.movePosition(QTextCursor::Up);
388
389 cursor = document->find("WGHT",cursor,QTextDocument::FindBackward);
390
391 cursor.movePosition(QTextCursor::StartOfLine);
392 cursor.clearSelection();
393 cursor.insertText(" ");
394 cursor.movePosition(QTextCursor::Down);
395 cursor.insertText(newWeight);
396 cursor.insertText("\n");
397
398 cursor.endEditBlock ();
399 setTextCursor(cursor);
400 centerCursor () ;
401 cursor.clearSelection ();
402 setFocus () ;
403 update();
404 }
405
406 void CodeEditor::insertList4(){
407 //we have a active LIST already in the file let's replace it
408 replace->setText("REM LIST ");
409 searchLE->setText("^LIST ");
410 replaceAll();
411 replace->setText("");
412 searchLE->setText("");
413 if (!toPlainText().contains(listinst)){
414 QTextDocument *document = this->document();
415 QTextCursor cursor = textCursor();
416 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
417 cursor = document->find(unitinst,cursor);
418 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
419 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
420 cursor.insertText("LIST 4\n");
421 emit saveMe(true,false);
422 }
423
424 }
425
426 void CodeEditor::insertList6(){
427 if (!toPlainText().contains(listinst)){
428 QTextDocument *document = this->document();
429 QTextCursor cursor = textCursor();
430 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
431 cursor = document->find(unitinst,cursor);
432 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
433 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
434 cursor.insertText("LIST 6 ! automatically inserted. Change 6 to 4 for CHECKCIF!!\n");
435 emit saveMe(true,false);
436 }
437 }
438
439 void CodeEditor::insertAnis(){
440 QTextDocument *document = this->document();
441 QTextCursor cursor = textCursor();
442 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
443 cursor = document->find(unitinst,cursor);
444 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
445 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
446 cursor.insertText("ANIS ! automatically inserted\n");
447 }
448
449 void CodeEditor::insertActa(){
450 insertList4();
451 QTextDocument *document = this->document();
452 QTextCursor cc,cursor = textCursor();
453 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
454
455 cc = document->find(actainst,cursor);
456 if (cc.isNull()) {
457 cursor = textCursor();
458 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
459 }else return;
460 cursor = document->find(unitinst,cursor);
461 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
462 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
463 cursor.insertText("ACTA \n");
464 }
465
466 QString CodeEditor::dispFromWave(int an){
467 if (chgl->mol->asymm.isEmpty()) return "";
468 QFile kis(":kisselwave");
469 kis.open(QIODevice::ReadOnly|QIODevice::Text);
470 QByteArray ba=kis.readAll();
471 QStringList all= QString(ba).split('\n');
472 kis.close();
473 QStringList nn,ann;
474 QString disp;
475 double aw=0,w;
476 w=aw;
477
478 int x=all.indexOf(QString("#S %1 %2").arg(an+1,2,10,QChar('0')).arg(chgl->mol->pse(an)));
479 int y=all.indexOf(QString("#S %1 %2").arg(an+2,2,10,QChar('0')).arg(chgl->mol->pse(an+1)));
480 //printf("SFAC <<%d>> %s\n",x,QString("#S %1 %2").arg(sfac.at(i)+1,2,10,QChar('0')).arg(chgl->mol->pse(sfac.at(i))).toStdString().c_str());
481 //printf("SFAC <<%d>> %s\n",y,QString("#S %1 %2").arg(sfac.at(i)+2,2,10,QChar('0')).arg(chgl->mol->pse(sfac.at(i)+1)).toStdString().c_str());
482 for (int j=x+1; j<y; j++){
483 ann=nn;
484 nn=all.at(j).split(" ",skipEmptyParts);
485 aw=w;
486 w=nn.at(0).toDouble();
487 if ((w!=aw)&&(chgl->mol->cell.wave>w)) {
488 double f= (chgl->mol->cell.wave-aw)/(w-aw);
489 //printf("DISP $%s %f %f\n",chgl->mol->pse(sfac.at(i)).toStdString().c_str(),f*nn.at(1).toDouble()+(1-f)*an.at(1).toDouble(),f*nn.at(2).toDouble()+(1-f)*an.at(2).toDouble());
490 if (nn.size()>3){
491 disp=QString("%1 %2 %3\n")//REM %5\nREM %6\n")
492 .arg(f*nn.at(1).toDouble()+(1-f)*ann.at(1).toDouble(),8,'f',5)
493 .arg(f*nn.at(2).toDouble()+(1-f)*ann.at(2).toDouble(),8,'f',5)
494 .arg(f*nn.at(3).toDouble()+(1-f)*ann.at(3).toDouble(),8,'f',5)
495 ;}else{
496 disp=QString("%1 %2 0.0\n")//REM %5\nREM %6\n")
497 .arg(f*nn.at(1).toDouble()+(1-f)*ann.at(1).toDouble(),8,'f',5)
498 .arg(f*nn.at(2).toDouble()+(1-f)*ann.at(2).toDouble(),8,'f',5)
499 ;
500 }
501 j=5000+x;
502 }
503 }
504 return disp;
505 }
506 void CodeEditor::dispFromWave(){
507 if (chgl->mol->asymm.isEmpty()) return;
508 QFile kis(":kisselwave");
509 kis.open(QIODevice::ReadOnly|QIODevice::Text);
510 QByteArray ba=kis.readAll();
511 QStringList all= QString(ba).split('\n');
512 kis.close();
513 QTextDocument *document = this->document();
514 QTextCursor cursor = textCursor();
515 cursor.beginEditBlock();
516 replace->setText("REM DISP ");
517 searchLE->setText("^DISP ");
518 replaceAll();
519 replace->setText("");
520 searchLE->setText("");
521 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
522 cursor = document->find("UNIT",cursor);
523 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
524 QStringList nn,an;
525 QString disp;
526 for (int i=0; i<sfac.size();i++){
527 double aw=0,w;
528 w=aw;
529
530 int x=all.indexOf(QString("#S %1 %2").arg(sfac.at(i)+1,2,10,QChar('0')).arg(chgl->mol->pse(sfac.at(i))));
531 int y=all.indexOf(QString("#S %1 %2").arg(sfac.at(i)+2,2,10,QChar('0')).arg(chgl->mol->pse(sfac.at(i)+1)));
532 //printf("SFAC <<%d>> %s\n",x,QString("#S %1 %2").arg(sfac.at(i)+1,2,10,QChar('0')).arg(chgl->mol->pse(sfac.at(i))).toStdString().c_str());
533 //printf("SFAC <<%d>> %s\n",y,QString("#S %1 %2").arg(sfac.at(i)+2,2,10,QChar('0')).arg(chgl->mol->pse(sfac.at(i)+1)).toStdString().c_str());
534 for (int j=x+1; j<y; j++){
535 an=nn;
536 nn=all.at(j).split(" ",skipEmptyParts);
537 aw=w;
538 w=nn.at(0).toDouble();
539 if ((w!=aw)&&(chgl->mol->cell.wave>w)) {
540 double f= (chgl->mol->cell.wave-aw)/(w-aw);
541 //printf("DISP $%s %f %f\n",chgl->mol->pse(sfac.at(i)).toStdString().c_str(),f*nn.at(1).toDouble()+(1-f)*an.at(1).toDouble(),f*nn.at(2).toDouble()+(1-f)*an.at(2).toDouble());
542 if (nn.size()>3){
543 disp=QString("DISP $%1 %2 %3 %4!source kissel\n")//REM %5\nREM %6\n")
544 .arg(sfacsmbl.at(i))
545 .arg(f*nn.at(1).toDouble()+(1-f)*an.at(1).toDouble(),8,'f',5)
546 .arg(f*nn.at(2).toDouble()+(1-f)*an.at(2).toDouble(),8,'f',5)
547 .arg(f*nn.at(3).toDouble()+(1-f)*an.at(3).toDouble(),8,'f',5)
548 ;}else{
549 disp=QString("DISP $%1 %2 %3!source kissel\n")//REM %5\nREM %6\n")
550 .arg(sfacsmbl.at(i))
551 .arg(f*nn.at(1).toDouble()+(1-f)*an.at(1).toDouble(),8,'f',5)
552 .arg(f*nn.at(2).toDouble()+(1-f)*an.at(2).toDouble(),8,'f',5)
553 ;
554 }
555 cursor.insertText(disp);
556 j=5000+x;
557 }
558 }
559
560 }
561
562 cursor.endEditBlock();
563 }
564
565 void CodeEditor::updateUnit(){
566 if (chgl->mol->asymm.isEmpty()) return;
567 QTextDocument *document = this->document();
568 QTextCursor cursor = textCursor();
569 cursor.beginEditBlock ();
570 cursor.movePosition(QTextCursor::Start);
571 cursor = document->find(unitAlt,cursor);
572 if (cursor.isNull()) {
573 cursor = textCursor();
574 cursor.endEditBlock ();
575 // printf("can't find unit\n");
576 update();
577 return;
578 }
579 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
580 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
581 cursor.deleteChar();
582 cursor.insertText(unitNeu);
583 cursor.endEditBlock ();
584 setTextCursor(cursor);
585 centerCursor () ;
586 cursor.clearSelection ();
587 setTextCursor(cursor);
588 setFocus () ;
589 update();
590 }
591
592 void CodeEditor::weedEmptySfacs(){
593 if (chgl->mol->asymm.isEmpty()) return;
594 emit saveMe(true,true);
595 if (1){//(maybeSave()){
596 QMap<int,double> unit;
597 for (int i=0; i<chgl->mol->asymm.size(); i++){
598 if (chgl->mol->asymm.at(i).an>=0) unit[chgl->mol->asymm.at(i).an]+= chgl->mol->asymm.at(i).sof * chgl->mol->cell.symmops.size();
599 }
600 unitNeu="UNIT";
601 for (int i = 0; i < sfac.size() ; i++){
602 if (unit.value(sfac.at(i))) {
603 if (unit.value(sfac.at(i))>9999)
604 unitNeu.append(QString(" %1").arg((int)unit.value(sfac.at(i)))); else
605 unitNeu.append(QString(" %1").arg(unit.value(sfac.at(i)),0,'g'));
606 }
607 if (unitNeu.split('\n').last().size()>76) unitNeu.append("=\n ");
608 }
609 updateUnit();
610 QTextDocument *document = this->document();
611 QTextCursor cursor = textCursor();
612 QTextCursor c=cursor;
613 cursor.movePosition(QTextCursor::Start);
614 int apos=0,pos=0;
615 QList<int> mussweg,newSfac=sfac;
616 for (int i = 0; i < sfac.size() ; i++){
617 if (unit.value(sfac.at(i))==0) {
618 mussweg.append(i);
619 newSfac.removeOne(sfac.at(i));
620 }
621 }
622 if (mussweg.isEmpty()) return;
623 cursor = document->find(sfacinst,cursor);
624 if (cursor.isNull()){setTextCursor(c);return;}
625 cursor.movePosition(QTextCursor::Start);
626 while ((!cursor.isNull())&&(pos<sfac.size())){
627 cursor = document->find(sfacinst,cursor);
628 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
629 if (cursor.selectedText().contains(plusfloat)){
630 bool hatgleich=cursor.selectedText().contains(linecontinue);
631 cursor.clearSelection();
632 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
633 if (mussweg.contains(pos)) {
634 cursor.insertText("REM ");
635 if (hatgleich) {
636 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
637 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
638 cursor.insertText("REM ");
639 }
640 }else if (hatgleich) cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
641 pos++;
642 }
643 else {
644 pos+=cursor.selectedText().split(" ",skipEmptyParts).size()-1;
645 cursor.deleteChar();
646 QString ac;
647 for (int i =apos; i<newSfac.size() && i<pos+apos;i++) ac.append(QString("%1 ").arg(chgl->mol->pse(newSfac.at(i))));
648 apos=pos;
649 cursor.insertText(QString("SFAC %1\n").arg(ac));
650 }
651 }
652 for (int i=0; i<chgl->mol->asymm.size();i++){
653 if ((sfac.indexOf(chgl->mol->asymm.at(i).an)>-1)&&
654 (newSfac.indexOf(chgl->mol->asymm.at(i).an)>-1)&&
655 (sfac.indexOf(chgl->mol->asymm.at(i).an)!=newSfac.indexOf(chgl->mol->asymm.at(i).an))){
656 jumpToAtom(i);
657 cursor = textCursor();
658 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
659 QString repla=cursor.selectedText();
660 cursor.deleteChar();
661 repla.replace(QString(" %1 ").arg(1+sfac.indexOf(chgl->mol->asymm.at(i).an)), QString(" %1 ").arg(1+newSfac.indexOf(chgl->mol->asymm.at(i).an)));
662 cursor.insertText(repla);
663 chgl->mol->asymm[i].orginalLine=repla;
664 }
665 }
666 emit saveMe(true,true);
667 document = this->document();
668 if(document->toPlainText().contains("DISP"))
669 dispFromWave();
670 }
671 }
672
673 void CodeEditor::jumpToAtom(int index){
674 // printf("1===========Jump 2 Atom!\n");
675 QString label = chgl->mol->showatoms.at(index).orginalLine.left(80).trimmed();
676 // qDebug()<<index<<chgl->mol->showatoms.at(index).Label<<label;
677 QTextDocument *document = this->document();
678 QTextCursor cursor = textCursor();
679 cursor.movePosition(QTextCursor::Start);
680 cursor = document->find(label,cursor);
681 if (cursor.isNull()){
682 cursor = textCursor();
683 cursor.movePosition(QTextCursor::Start);
684 label.chop(10);
685 cursor = document->find(label,cursor);
686 if (cursor.isNull()) cursor = textCursor();
687 cursor.movePosition(QTextCursor::Start);
688 label = chgl->mol->showatoms.at(index).orginalLine.left(80).simplified();
689 cursor = document->find(label,cursor);
690 if (cursor.isNull()) cursor = textCursor();
691 }
692 cursor.movePosition(QTextCursor::StartOfLine);
693 setTextCursor(cursor);
694 centerCursor();
695 cursor.clearSelection();
696 setTextCursor(cursor);
697 // printf("===========Jump 2 Atom!\n");
698 doSetTextCursor(cursor,false);
699 setFocus();
700 }
701
702 void CodeEditor::insertANIS(QList<MyAtom> selected){
703 QTextDocument *document = this->document();
704 QTextCursor cursor = textCursor();
705 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
706 cursor = document->find(unitinst,cursor);
707 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
708 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
709 QString buffer("ANIS ");
710 buffer = selectedRestraintsAtoms(buffer, selected, "", true);
711 cursor.insertText(DSRGui::textWrap(buffer));
712 }
713
714 void CodeEditor::insertDFIX(double value, double esd, QList<MyAtom> selected, QString resiSpec){
715
716 QTextDocument *document = this->document();
717 QTextCursor cursor = textCursor();
718 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
719 cursor = document->find(unitinst,cursor);
720 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
721 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
722 QString buffer = QString("DFIX%1 %2 %3 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec).arg(value).arg(esd);
723 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
724 cursor.insertText(DSRGui::textWrap(buffer));
725 }
726
727 void CodeEditor::insertDANG(double value, double esd, QList<MyAtom> selected, QString resiSpec){
728
729 QTextDocument *document = this->document();
730 QTextCursor cursor = textCursor();
731 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
732 cursor = document->find(unitinst,cursor);
733 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
734 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
735 QString buffer =QString("DANG%1 %2 %3 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec).arg(value).arg(esd);
736 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
737 cursor.insertText(DSRGui::textWrap(buffer));
738 }
739
740 void CodeEditor::insertFLAT(double esd, QList<MyAtom> selected, QString resiSpec){
741 QTextDocument *document = this->document();
742 QTextCursor cursor = textCursor();
743 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
744 cursor = document->find(unitinst,cursor);
745 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
746 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
747 QString buffer =QString("FLAT%1 %2 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec).arg(esd);
748 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
749 cursor.insertText(DSRGui::textWrap(buffer));
750 }
751
752 void CodeEditor::insertEXYZ(QList<MyAtom> selected, QString resiSpec){
753 QTextDocument *document = this->document();
754 QTextCursor cursor = textCursor();
755 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
756 cursor = document->find(unitinst,cursor);
757 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
758 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
759 QString buffer =QString("EXYZ%1 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec);
760 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
761 cursor.insertText(DSRGui::textWrap(buffer));
762 }
763
764 void CodeEditor::jumpToError(){
765 QTextCursor c = textCursor();
766 if (!errorInLine.isEmpty()){
767 c.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
768 c.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor,errorInLine.first());
769 setTextCursor(c);
770 ensureCursorVisible ();
771 }
772 }
773
774 void CodeEditor::findResi(int i){
775 if (i!=-1) {
776 QString index = resiFinder->itemText(i);
777 QTextCursor c=this->document()->find(index);
778 if (!c.isNull()) {
779 c.movePosition(QTextCursor::StartOfLine);
780 setTextCursor(c);
781 centerCursor();
782 c.clearSelection ();
783 //QTextBlock b =c.block();
784 QStringList tt=index.split(spaces,skipEmptyParts);
785
786 int nr=0;
787 if ((tt.size()>1)&&(tt.at(1).indexOf(onlydigits)!=-1))//QRegularExpression("^[0-9]+")
788 nr=tt.at(1).toInt();
789 else if (tt.size()>2) nr=tt.at(2).toInt();
790 //QString tt = index.section(spaces,1,1).toInt();
791 chgl->selectResiByNr(nr);
792 setTextCursor(c);
793 setFocus () ;
794 }
795 }
796 }
797
798 void CodeEditor::increaseEdtiorFont(){
799 QFont f =font();
800 f.setPointSize(qMin(f.pointSize()+1,24));
801 printf("Font increased %s %d\n", f.family().toStdString().c_str(),f.pointSize());
802 setFont(f);
803 update();
804 }
805
806 void CodeEditor::decreaseEdtiorFont(){
807 QFont f =font();
808 f.setPointSize(qMax(f.pointSize()-1,6));
809 printf("Font decreased %s %d\n", f.family().toStdString().c_str(),f.pointSize());
810 setFont(f);
811 update();
812 }
813
814 void CodeEditor::hideSearch(){
815 searchLE->clear();
816 suchbox->hide();
817 }
818
819 void CodeEditor::showSearch(){
820 suchbox->show();
821 if (isReadOnly()){
822 replace->hide();
823 replaceButton->hide();
824 replacePButton->hide();
825 replaceAButton->hide();
826 }else{
827 replace->show();
828 replaceButton->show();
829 replacePButton->show();
830 replaceAButton->show();
831 }
832 suchbox->setTitle(QString("Search and Replace:"));
833 searchLE->setFocus();
834 }
835
836 void CodeEditor::findNext(){
837 suchbox->show();
838 if (isReadOnly()){
839 replace->hide();
840 replaceButton->hide();
841 replacePButton->hide();
842 replaceAButton->hide();
843 }else{
844 replace->show();
845 replaceButton->show();
846 replacePButton->show();
847 replaceAButton->show();
848 }
849 suchbox->setTitle(QString("Search and Replace:"));
850 searchchanged(false,false);
851 }
852
853 void CodeEditor::findPrev(){
854 suchbox->show();
855 if (isReadOnly()){
856 replace->hide();
857 replaceButton->hide();
858 replacePButton->hide();
859 replaceAButton->hide();
860 }else{
861 replace->show();
862 replaceButton->show();
863 replacePButton->show();
864 replaceAButton->show();
865 }
866 suchbox->setTitle(QString("Search and Replace:"));
867 searchchanged(false,true);
868 }
869
870 void CodeEditor::findText(){
871 searchchanged(true,false);
872 }
873
874 void CodeEditor::searchchanged(bool current,bool back){
875 QRegularExpression searchString = QRegularExpression(searchLE->text(),QRegularExpression::CaseInsensitiveOption);
876 QPalette p = searchLE->palette();
877 p.setBrush(QPalette::Active,QPalette::Base,Qt::white);
878 QTextDocument *document;
879 QTextCursor cursor;
880
881 document = this->document();
882 cursor = textCursor();
883
884 if (searchString.isValid()){
885 if (cursor.hasSelection())
886 cursor.setPosition((current|back)?cursor.anchor():cursor.position(), QTextCursor::MoveAnchor);
887 QTextDocument::FindFlags options;
888 if (back) options|=QTextDocument::FindBackward;
889 cursor=document->find(searchString,cursor,options);
890 if (cursor.isNull()){
891 QTextCursor ac(document);
892 ac.movePosition(options & QTextDocument::FindBackward
893 ? QTextCursor::End : QTextCursor::Start);
894 cursor = document->find(searchString, ac,options);
895 if (cursor.isNull()){
896 p.setBrush(QPalette::Active,QPalette::Base,QColor(205,100,100));
897 cursor = textCursor();
898 cursor.movePosition(QTextCursor::Start);
899 }
900 }
901 if ((!cursor.isNull())&&(wholeLine->isChecked())){
902 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
903 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
904 while ((cursor.selectedText().endsWith("="))||(cursor.selectedText().endsWith("= "))){
905 cursor.movePosition(QTextCursor::Down,QTextCursor::KeepAnchor);
906 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
907 }
908 }
909 }
910 else cursor.movePosition(QTextCursor::Start);
911
912 setTextCursor(cursor);
913 searchLE->setPalette(p);
914 }
915
916 void CodeEditor::replaceNext(){
917 suchbox->setTitle(QString("Search and Replace:"));
918 QRegularExpression searchString = QRegularExpression(searchLE->text(),QRegularExpression::CaseInsensitiveOption);
919 QPalette p = searchLE->palette();
920 p.setBrush(QPalette::Active,QPalette::Base,Qt::white);
921 QTextDocument *document;
922 QTextCursor cursor;
923 int lastpos=-1;
924
925 document = this->document();
926 cursor = textCursor();
927
928 if (searchString.isValid()){
929 if (cursor.hasSelection()){
930 cursor.beginEditBlock();
931 if (wholeLine->isChecked()){
932 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
933 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
934 while ((cursor.selectedText().endsWith("="))||(cursor.selectedText().endsWith("= "))){
935 cursor.movePosition(QTextCursor::Down,QTextCursor::KeepAnchor);
936 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
937 }
938 }
939 cursor.deleteChar();
940 if (replace->text().isEmpty())cursor.deleteChar();
941 else cursor.insertText(replace->text());
942 lastpos=cursor.position();
943 cursor.endEditBlock();
944 cursor.setPosition(cursor.position(), QTextCursor::MoveAnchor);
945 }
946 cursor=document->find(searchString,cursor);
947 if (cursor.isNull()){
948 QTextCursor ac(document);
949 ac.movePosition(QTextCursor::Start);
950 cursor = document->find(searchString, ac);
951 if (cursor.isNull()){
952 p.setBrush(QPalette::Active,QPalette::Base,QColor(205,100,100));
953 }
954 }
955 if ((!cursor.isNull())&&(wholeLine->isChecked())){
956 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
957 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
958 while ((cursor.selectedText().endsWith("="))||(cursor.selectedText().endsWith("= "))){
959 cursor.movePosition(QTextCursor::Down,QTextCursor::KeepAnchor);
960 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
961 }
962 }
963 }
964 else cursor.movePosition(QTextCursor::Start);
965 if (cursor.isNull()){
966 QTextCursor ac(document);
967 ac.setPosition(lastpos);
968 cursor=ac;
969 }
970 doSetTextCursor(cursor,false);
971 setTextCursor(cursor);
972 searchLE->setPalette(p);
973 centerCursor();
974 return;
975 }
976
977 void CodeEditor::replaceAll(){
978 suchbox->setTitle(QString("Search and Replace:"));
979 QRegularExpression searchString = QRegularExpression(searchLE->text(),QRegularExpression::CaseInsensitiveOption);
980 QPalette p = searchLE->palette();
981 p.setBrush(QPalette::Active,QPalette::Base,Qt::white);
982 QTextDocument *document;
983 QTextCursor cursor;
984
985 document = this->document();
986 cursor = textCursor();
987 int occurrence=0;
988 cursor.beginEditBlock();
989 cursor.movePosition(QTextCursor::Start);
990 if (searchString.isValid()){
991 do {
992 cursor=document->find(searchString,cursor);
993 if (cursor.hasSelection()){
994 cursor.beginEditBlock();
995 if (wholeLine->isChecked()){
996 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
997 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
998 while ((cursor.selectedText().endsWith("="))||(cursor.selectedText().endsWith("= "))){
999 cursor.movePosition(QTextCursor::Down,QTextCursor::KeepAnchor);
1000 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
1001 }
1002 }
1003 cursor.deleteChar();
1004 if (replace->text().isEmpty())cursor.deleteChar();
1005 else cursor.insertText(replace->text());
1006 cursor.endEditBlock();
1007 cursor.setPosition(cursor.position(), QTextCursor::MoveAnchor);
1008 occurrence++;
1009 }
1010 }
1011 while (!cursor.isNull());
1012 }
1013
1014 cursor = textCursor();
1015 cursor.endEditBlock();
1016 setTextCursor(cursor);
1017 searchLE->setPalette(p);
1018 centerCursor();
1019 if (occurrence){
1020 suchbox->setTitle(QString("Search and Replace: Replaced %1 occurrencies of '%2' by '%3'.").arg(occurrence).arg(searchString.pattern()).arg(replace->text()));
1021 }
1022 return;
1023 }
1024
1025 void CodeEditor::replacePrev(){
1026 suchbox->setTitle(QString("Search and Replace:"));
1027 QRegularExpression searchString = QRegularExpression(searchLE->text(),QRegularExpression::CaseInsensitiveOption);
1028
1029 QPalette p = searchLE->palette();
1030 p.setBrush(QPalette::Active,QPalette::Base,Qt::white);
1031 QTextDocument *document;
1032 QTextCursor cursor;
1033 int lastpos=-1;
1034
1035 document = this->document();
1036 cursor = textCursor();
1037
1038 if (searchString.isValid()){
1039 if (cursor.hasSelection()){
1040 cursor.beginEditBlock();
1041 if (wholeLine->isChecked()){
1042 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1043 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
1044 }
1045 cursor.deleteChar();
1046 if (replace->text().isEmpty())cursor.deleteChar();
1047 else cursor.insertText(replace->text());
1048 lastpos=cursor.position();
1049 cursor.endEditBlock();
1050 cursor.setPosition(cursor.anchor(), QTextCursor::MoveAnchor);
1051 }
1052 cursor=document->find(searchString,cursor,QTextDocument::FindBackward);
1053 if (cursor.isNull()){
1054 QTextCursor ac(document);
1055 ac.movePosition(QTextCursor::End);
1056 cursor = document->find(searchString, ac,QTextDocument::FindBackward);
1057 if (cursor.isNull()){
1058 p.setBrush(QPalette::Active,QPalette::Base,QColor(205,100,100));
1059 }
1060 }
1061 }
1062 else cursor.movePosition(QTextCursor::Start);
1063 if (cursor.isNull()){
1064 QTextCursor ac(document);
1065 ac.setPosition(lastpos);
1066 cursor=ac;
1067 }
1068 doSetTextCursor(cursor,false);
1069 setTextCursor(cursor);
1070 searchLE->setPalette(p);
1071 centerCursor();
1072 searchchanged(false,true);
1073 return;
1074 }
1075
1076 void CodeEditor::resiFinderDestroyed(){
1077 resiFinder = NULL;
1078 }
1079
1080 void CodeEditor::changeSortierWeise(QAction* action){
1081 int index = action->data().toInt();
1082 sortierWeise = index;
1083 QSettings einstellung( QSettings::IniFormat, QSettings::UserScope ,PROGRAM_NAME,chgl->mol->mynewnameis );
1084 einstellung.beginGroup("Sorting");
1085 einstellung.setValue("SortingOption",sortierWeise);
1086 einstellung.endGroup();
1087 }
1088
1089 QString CodeEditor::sortLabelList(CEnvironment &asymm, MyAtom &tatze){
1090 if (asymm.isEmpty()) return "HKLF";
1091 QMultiMap<long double,MyAtom> atomSortMap;
1092 long double lodo=0.0l;
1093 int amax = asymm.size();
1094
1095 int t1=0,t2=0;
1096 for (int i=0; i < asymm.size(); i++){
1097 if (asymm.at(i).an<0) continue;
1098 t1++;
1099 QString s1 = asymm.at(i).Label.section('_',0,0);
1100 s1.remove(0,chgl->mol->pse(asymm.at(i).an).size());
1101 int n1 = s1.section(nodigits,0,0).toInt();
1102 int r1 = 0 ;
1103 char cc[10];
1104 strncpy(cc,s1.section(digits,1,-1).toStdString().c_str(),4);
1105 for (size_t k=0; k<strlen(cc);k++) {r1*=256;r1+=(size_t)cc[k];}
1106 switch (sortierWeise){
1107 case 1:
1108 lodo=asymm.at(i).resiNr*99*amax+
1109 asymm.at(i).part*amax+
1110 n1+
1111 ((110-asymm.at(i).an)/220.0l)+
1112 (r1 / 50000.0l);//46656
1113 //atomSortMap.insertMulti(lodo,asymm.at(i));
1114 atomSortMap.insert(lodo,asymm.at(i));
1115 break;
1116 case 2:
1117 lodo=asymm.at(i).resiNr*99*amax+
1118 asymm.at(i).part*amax+
1119 n1/999.0l+
1120 ((110-asymm.at(i).an))+
1121 (r1 / 50000.0l);//46656
1122
1123 atomSortMap.insert(lodo,asymm.at(i));
1124 //printf("##= %Lf %d %d %d %d %d\n",lodo,asymm.at(i).resiNr,asymm.at(i).part,n1,(110-asymm.at(i).an),r1);
1125 break;
1126 case 3:
1127 lodo= asymm.at(i).resiNr*99*amax+
1128 asymm.at(i).part*amax+
1129 n1/999.0l+
1130 sfac.indexOf(asymm.at(i).an)*10+
1131 (r1 / 50000.0l);//46656
1132 atomSortMap.insert(lodo,asymm.at(i));
1133 break;
1134 case 4:
1135 lodo=
1136 asymm.at(i).resiNr*99*amax+
1137 asymm.at(i).part*amax+
1138 n1/50000.0l+
1139 ((110-asymm.at(i).an)/220)+
1140 (r1 );//46656
1141 atomSortMap.insert(lodo,asymm.at(i));
1142 t2++;
1143 break;
1144 case 5:
1145 lodo=
1146 asymm.at(i).molindex*9999*amax+
1147 asymm.at(i).resiNr*99*amax+
1148 asymm.at(i).part*amax+
1149 n1/999.0l+
1150 ((110-asymm.at(i).an))+
1151 (r1 / 50000.0l);//46656
1152 atomSortMap.insert(lodo,asymm.at(i));
1153 /*printf("%s %g\n", asymm.at(i).Label.toStdString().c_str(),asymm.at(i).molindex*9999*amax+
1154 asymm.at(i).resiNr*99*amax+
1155 asymm.at(i).part*amax+
1156 n1/999.0+
1157 ((110-asymm.at(i).an))+
1158 (r1 / 50000.0));*/
1159 break;
1160 case 6:
1161 lodo= asymm.at(i).resiNr*99*amax+
1162 asymm.at(i).part*amax+
1163 chgl->mol->ueq(asymm.at(i).uf);
1164
1165 atomSortMap.insert(lodo,asymm.at(i));
1166 break;
1167 default:
1168 atomSortMap.insert(i, asymm.at(i));
1169 break;
1170 }
1171 }
1172 {
1173 QString s1 = tatze.Label.section('_',0,0);
1174 s1.remove(0,chgl->mol->pse(tatze.an).size());
1175 int n1 = s1.section(nodigits,0,0).toInt();
1176 int r1 = 0 ;
1177 char cc[10];
1178 strncpy(cc,s1.section(digits,1,-1).toStdString().c_str(),4);
1179 for (size_t k=0; k<strlen(cc);k++) {r1*=256;r1+=(size_t)cc[k];}
1180 //printf("VV= %Lf %d %d %d %d %d\n",lodo,tatze.resiNr,tatze.part,n1,(110-tatze.an),r1);
1181 switch (sortierWeise){
1182 case 1:
1183 lodo=tatze.resiNr*99*amax+
1184 tatze.part*amax+
1185 n1+
1186 ((110-tatze.an)/220.0l)+
1187 (r1 / 50000.0l);//46656
1188 break;
1189 case 2:
1190 lodo=tatze.resiNr*99*amax+
1191 tatze.part*amax+
1192 n1/999.0l+
1193 ((110-tatze.an))+
1194 (r1 / 50000.0l);//46656
1195 break;
1196 case 3:
1197 lodo= tatze.resiNr*99*amax+
1198 tatze.part*amax+
1199 n1/999.0l+
1200 sfac.indexOf(tatze.an)*10+
1201 (r1 / 50000.0l);//46656
1202 break;
1203 case 4:
1204 lodo=
1205 tatze.resiNr*99*amax+
1206 tatze.part*amax+
1207 n1/50000.0l+
1208 ((110-tatze.an)/220)+
1209 (r1 );//46656
1210 break;
1211 case 5:
1212 lodo=
1213 tatze.molindex*9999*amax+
1214 tatze.resiNr*99*amax+
1215 tatze.part*amax+
1216 n1/999.0l+
1217 ((110-tatze.an))+
1218 (r1 / 50000.0l);//46656
1219 break;
1220 case 6:
1221 lodo= tatze.resiNr*99*amax+
1222 tatze.part*amax+
1223 chgl->mol->ueq(tatze.uf);
1224 break;
1225 }
1226 }
1227 QList<long double> kys = atomSortMap.keys();
1228 long double fi = kys.first();//, la = kys.last();
1229 QString l="HKLF";
1230 //printf("value = %Lf first = %Lf last = %Lf\n", lodo, fi, la);
1231 if ((lodo>=fi)) {//
1232 CEnvironment asymm2 = atomSortMap.values();
1233 int idx=0;
1234 for (; (idx<kys.size())&& (lodo>kys.at(idx)); idx++){}
1235 if (idx>0) idx--;
1236 // printf("idx %d\n",idx);
1237 l = asymm2.at(idx).orginalLine.left(80).trimmed();
1238 asymm2.clear();
1239 }else{
1240 QTextDocument *doc = this->document();
1241 QTextCursor cursor = textCursor();
1242 cursor.movePosition(QTextCursor::Start);
1243 l=asymm.first().orginalLine.left(80).trimmed();
1244 cursor=doc->find(l, cursor);
1245 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1246 cursor.movePosition(QTextCursor::Up,QTextCursor::MoveAnchor);
1247 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
1248 l=cursor.selectedText();
1249 cursor.clearSelection();
1250 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1251 }
1252 kys.clear();
1253 atomSortMap.clear();
1254 return l;
1255 }
1256 void CodeEditor::sortAtoms(CEnvironment &as){
1257 if (as.isEmpty()) return;
1258 /*if (toPlainText().contains(QRegularExpression("[<>]"))){
1259 expandGreaterThan();
1260 }
1261 */
1262 QMap<long double,MyAtom> atomSortMap;
1263
1264 int amax = as.size();
1265 int t1=0,t2=0;
1266 //printf("sortAtoms%d %lld\n",sortierWeise, as.size());
1267 for (int i=0; i < as.size(); i++){
1268 if (as.at(i).an<0) continue;
1269 t1++;
1270 QString s1 = as.at(i).Label;
1271 s1.remove(0,chgl->mol->pse(as.at(i).an).size());
1272 int n1 = s1.section(nodigits,0,0).toInt();
1273 int r1 = 0 ;
1274 char cc[10];
1275 strncpy(cc,s1.section(digits,1,-1).toStdString().c_str(),4);
1276 for (size_t k=0; k<strlen(cc);k++) {r1*=256;r1+=(size_t)cc[k];}
1277 switch (sortierWeise){
1278 case 1:
1279 atomSortMap.insert(
1280 as.at(i).resiNr*99*amax+
1281 as.at(i).part*amax+
1282 n1+
1283 ((110-as.at(i).an)/220.0)+
1284 (r1 / 50000.0)//46656
1285 ,as.at(i));
1286 break;
1287 case 2:
1288 atomSortMap.insert(
1289 as.at(i).resiNr*99*amax+
1290 as.at(i).part*amax+
1291 n1/999.0+
1292 ((110-as.at(i).an))+
1293 (r1 / 50000.0)//46656
1294 ,as.at(i));
1295 break;
1296 case 3:
1297 atomSortMap.insert(
1298 as.at(i).resiNr*99*amax+
1299 as.at(i).part*amax+
1300 n1/999.0+
1301 sfac.indexOf(as.at(i).an)*10+
1302 (r1 / 50000.0)//46656
1303 ,as.at(i));
1304 break;
1305 case 4:
1306 atomSortMap.insert(
1307 as.at(i).resiNr*99*amax+
1308 as.at(i).part*amax+
1309 n1/50000.0+
1310 ((110-as.at(i).an)/220)+
1311 (r1 )//46656
1312 ,as.at(i));
1313 t2++;
1314 break;
1315 case 5:
1316 atomSortMap.insert(
1317 as.at(i).molindex*9999*amax+
1318 as.at(i).resiNr*99*amax+
1319 as.at(i).part*amax+
1320 n1/999.0+
1321 ((110-as.at(i).an))+
1322 (r1 / 50000.0)//46656
1323 ,as.at(i));
1324 /* printf("%s %g\n", as.at(i).Label.toStdString().c_str(),as.at(i).molindex*9999*amax+
1325 as.at(i).resiNr*99*amax+
1326 as.at(i).part*amax+
1327 n1/999.0+
1328 ((110-as.at(i).an))+
1329 (r1 / 50000.0));*/
1330 break;
1331
1332 case 6:{
1333 long double lodo=0.0l;
1334 lodo= as.at(i).resiNr*99*amax+
1335 as.at(i).part*amax+
1336 chgl->mol->ueq(as.at(i).uf);
1337 atomSortMap.insert(lodo,as.at(i));
1338 }
1339 break;
1340 default:
1341 atomSortMap.insert(i
1342 ,as.at(i));
1343 break;
1344 }
1345 }
1346 as= atomSortMap.values();
1347 //printf("done sorting.\n");
1348 }
1349
1350 void CodeEditor::sortAtoms(){
1351 if (chgl->mol->asymm.isEmpty()) return;
1352
1353 const QString sicher = toPlainText();
1354 //find atomranges
1355 if (sicher.contains(QRegularExpression("[<>]"))){
1356 //QStringList ranges;
1357 /*QStringList lines = sicher.split('\n');
1358 for (int i=0; (i<lines.size()); i++){
1359 if (lines.at(i).startsWith(' ')) continue;
1360 if (lines.at(i).startsWith("REM",QRegularExpression::CaseInsensitiveOption)) continue;
1361 if (lines.at(i).startsWith("HKLF",QRegularExpression::CaseInsensitiveOption)) break;
1362 if (lines.at(i).contains(QRegularExpression("[<>]"))) ranges.append(QString("LINE %1: %2")
1363 .arg(i+1)
1364 .arg(lines.at(i)));
1365 }*/
1366 expandGreaterThan();
1367 /*if (!ranges.isEmpty()){
1368 QMessageBox::information(0,"information",QString("<h3>Atom ranges detected! %1 "
1369 " can not sort here without destroying functionality of the file.</h3 <pre>%2 </pre>").arg(PROGRAM_NAME).arg(ranges.join("\n")));
1370 return;
1371 }*/
1372 }
1373 QMap<long double,MyAtom> atomSortMap;
1374
1375 int amax = chgl->mol->asymm.size();
1376 printf("sortAtoms%d %d\n",sortierWeise, amax);
1377 int t1=0,t2=0;
1378 for (int i=0; i < chgl->mol->asymm.size(); i++){
1379 if (chgl->mol->asymm.at(i).an<0) continue;
1380 t1++;
1381 QString s1 = chgl->mol->asymm.at(i).Label;
1382 s1.remove(0,chgl->mol->pse(chgl->mol->asymm.at(i).an).size());
1383 int n1 = s1.section(nodigits,0,0).toInt();
1384 int r1 = 0 ;
1385 char cc[10];
1386 strncpy(cc,s1.section(digits,1,-1).toStdString().c_str(),4);
1387 for (size_t k=0; k<strlen(cc);k++) {r1*=256;r1+=(size_t)cc[k];}
1388 switch (sortierWeise){
1389 case 1:
1390 atomSortMap.insert(
1391 chgl->mol->asymm.at(i).resiNr*99*amax+
1392 chgl->mol->asymm.at(i).part*amax+
1393 n1+
1394 ((110-chgl->mol->asymm.at(i).an)/220.0)+
1395 (r1 / 50000.0)//46656
1396 ,chgl->mol->asymm.at(i));
1397 break;
1398 case 2:
1399 atomSortMap.insert(
1400 chgl->mol->asymm.at(i).resiNr*99*amax+
1401 chgl->mol->asymm.at(i).part*amax+
1402 n1/999.0+
1403 ((110-chgl->mol->asymm.at(i).an))+
1404 (r1 / 50000.0)//46656
1405 ,chgl->mol->asymm.at(i));
1406 break;
1407 case 3:
1408 atomSortMap.insert(
1409 chgl->mol->asymm.at(i).resiNr*99*amax+
1410 chgl->mol->asymm.at(i).part*amax+
1411 n1/999.0+
1412 sfac.indexOf(chgl->mol->asymm.at(i).an)*10+
1413 (r1 / 50000.0)//46656
1414 ,chgl->mol->asymm.at(i));
1415 break;
1416 case 4:
1417 atomSortMap.insert(
1418 chgl->mol->asymm.at(i).resiNr*99*amax+
1419 chgl->mol->asymm.at(i).part*amax+
1420 n1/50000.0+
1421 ((110-chgl->mol->asymm.at(i).an)/220)+
1422 (r1 )//46656
1423 ,chgl->mol->asymm.at(i));
1424 t2++;
1425 break;
1426 case 5:
1427 atomSortMap.insert(
1428 chgl->mol->asymm.at(i).molindex*9999*amax+
1429 chgl->mol->asymm.at(i).resiNr*99*amax+
1430 chgl->mol->asymm.at(i).part*amax+
1431 n1/999.0+
1432 ((110-chgl->mol->asymm.at(i).an))+
1433 (r1 / 50000.0)//46656
1434 ,chgl->mol->asymm.at(i));
1435 /* printf("%s %g\n", chgl->mol->asymm.at(i).Label.toStdString().c_str(),chgl->mol->asymm.at(i).molindex*9999*amax+
1436 chgl->mol->asymm.at(i).resiNr*99*amax+
1437 chgl->mol->asymm.at(i).part*amax+
1438 n1/999.0+
1439 ((110-chgl->mol->asymm.at(i).an))+
1440 (r1 / 50000.0));// */
1441 break;
1442
1443 case 6:{
1444 long double lodo=0.0l;
1445 lodo= chgl->mol->asymm.at(i).resiNr*99*amax+
1446 chgl->mol->asymm.at(i).part*amax+
1447 chgl->mol->ueq(chgl->mol->asymm.at(i).uf);
1448 atomSortMap.insert(lodo,chgl->mol->asymm.at(i));
1449 }
1450 break;
1451 default:
1452 atomSortMap.insert(i
1453 ,chgl->mol->asymm.at(i));
1454 break;
1455 }
1456 }
1457 CEnvironment asymm2=
1458 atomSortMap.values();
1459
1460 QTextDocument *document = this->document();
1461 QTextCursor cursor = textCursor();
1462 wholeLine->setChecked(false);
1463 replace->setText("");
1464 searchLE->setText("^part.*$");
1465 replaceAll();
1466 replace->setText("");
1467 searchLE->setText("^resi.*$");
1468 replaceAll();
1469 cursor.beginEditBlock();
1470 cursor.movePosition(QTextCursor::Start);
1471 cursor = document->find("HKLF",cursor);
1472 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1473 cursor.movePosition(QTextCursor::Up,QTextCursor::KeepAnchor);
1474 if (parenthesis.at(cursor.blockNumber())){
1475 cursor.select(QTextCursor::WordUnderCursor);
1476 if ((cursor.selectedText().contains("RESI",Qt::CaseInsensitive))||(cursor.selectedText().contains("PART",Qt::CaseInsensitive)))
1477 cursor.movePosition(QTextCursor::Up,QTextCursor::KeepAnchor);
1478 cursor.select(QTextCursor::WordUnderCursor);
1479 if ((cursor.selectedText().contains("RESI",Qt::CaseInsensitive))||(cursor.selectedText().contains("PART",Qt::CaseInsensitive)))
1480 cursor.movePosition(QTextCursor::Up,QTextCursor::KeepAnchor);
1481 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
1482 cursor.clearSelection();
1483 cursor.insertText("AFIX 0 \n");
1484 }
1485
1486 /*QProgressDialog progress("Sorting atoms in Editor", QString(), 0, asymm2.size(), this);
1487 progress.setWindowModality(Qt::WindowModal);*/
1488 int ares=0, apart=0;
1489 for (int i=0; i < asymm2.size(); i++){
1490 //progress.setValue(i);
1491 QString label = asymm2.at(i).orginalLine.left(80).trimmed();
1492 cursor.movePosition(QTextCursor::Start);
1493 cursor = document->find(label,cursor);
1494 //printf("find=>>%s {%d}\n",label.toStdString().c_str(),cursor.blockNumber());
1495 if (cursor.isNull()){
1496 cursor = textCursor();
1497 cursor.movePosition(QTextCursor::Start);
1498 label.chop(10);
1499 cursor = document->find(label,cursor);
1500 if (cursor.isNull()) {
1501 cursor = textCursor();
1502 printf("label not found #%d %s\n",i,label.toStdString().c_str());
1503 continue;
1504 }
1505 }
1506
1507 if (parenthesis.at(cursor.blockNumber()))continue;//Afix not sorted here
1508 QString vorherig,neues;
1509 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1510 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
1511 while (cursor.selectedText().endsWith("=")) {
1512 cursor.movePosition(QTextCursor::Down,QTextCursor::KeepAnchor);
1513 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
1514 }
1515 while (parenthesis.at(cursor.blockNumber()+1)){
1516 cursor.movePosition(QTextCursor::Down,QTextCursor::KeepAnchor);
1517 cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
1518 }
1519 neues = vorherig= cursor.selectedText();
1520 cursor.deleteChar();
1521 cursor.deleteChar();
1522 cursor = textCursor();
1523 cursor.movePosition(QTextCursor::Start);
1524 cursor = document->find(hklfinst,cursor);
1525 cursor.clearSelection();
1526 cursor.movePosition(QTextCursor::StartOfLine);
1527 if ((asymm2.at(i).resiNr!=ares))
1528 cursor.insertText(QString("RESI %1 %2\n")
1529 .arg(asymm2.at(i).resiNr)
1530 .arg(asymm2.at(i).ResiClass));
1531 if ((asymm2.at(i).part!=apart))
1532 cursor.insertText(QString("PART %1\n")
1533 .arg(asymm2.at(i).part));
1534 //printf("=>%d\n",cursor.blockNumber());
1535 cursor.insertText(neues);
1536 cursor.insertText("\n");
1537 ares = asymm2.at(i).resiNr;
1538 apart = asymm2.at(i).part;
1539 updateAfix();
1540 }
1541 cursor = document->find("HKLF",cursor);
1542 cursor.clearSelection();
1543 cursor.movePosition(QTextCursor::StartOfLine);
1544 if ((0!=apart)) cursor.insertText(QString("PART 0\n"));
1545 if ((0!=ares)) cursor.insertText(QString("RESI 0\n"));
1546 cursor.endEditBlock ();
1547 emit updateLabel();
1548
1549 chgl->disSelection();
1550 if (chgl->fuse->isVisible())chgl->mol->grow();
1551 else chgl->mol->fuse();
1552 //chgl->=__LINE__;
1553 setUndoRedoEnabled ( true );
1554 chgl->update();
1555 searchLE->setText("");
1556 replace->setText("");
1557 wholeLine->setChecked(false);
1558 setTextCursor(cursor);
1559
1560 //progress.setValue(asymm2.size());
1561 }
1562
1563 void CodeEditor::sortSelectedRegion(){
1564
1565 QTextCursor cursor = textCursor();
1566 int sta=cursor.selectionStart();
1567 int end=cursor.selectionEnd();
1568 cursor.setPosition(sta);
1569 cursor.movePosition(QTextCursor::StartOfLine);
1570 cursor.setPosition(end, QTextCursor::KeepAnchor);
1571 cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
1572 if (cursor.selectedText().endsWith("=")) cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor);
1573 //cursor.movePosition(QTextCursor::StartOfLine);
1574 QString sel=cursor.selectedText();
1575 CEnvironment toms;
1576 for (int i=0; i<chgl->mol->asymm.size(); i++){
1577 if (chgl->mol->asymm.at(i).afix!=0) continue;
1578 if (chgl->mol->asymm.at(i).orginalLine.size()<30) continue;
1579 if (sel.contains(chgl->mol->asymm.at(i).orginalLine,Qt::CaseInsensitive)){
1580 toms.append(chgl->mol->asymm[i]);
1581 }
1582 }
1583 int amax = toms.size();
1584 //int zeilen=sel.count(QChar::ParagraphSeparator);
1585 if (amax <3) {
1586 toms.clear();
1587 cursor.clearSelection ();
1588 setTextCursor(cursor);
1589 update();
1590 qDebug()<<"not enough atoms selected!";
1591 return;
1592 }
1593 int t1=0,t2=0;
1594 QMap<long double,MyAtom> atomSortMap;
1595 QMap<long double,int> atomSortMapi;
1596 for (int i=0; i < amax; i++){
1597 if (toms.at(i).an<0) continue;
1598 t1++;
1599 QString s1 = toms.at(i).Label;
1600 s1.remove(0,chgl->mol->pse(toms.at(i).an).size());
1601 int n1 = s1.section(nodigits,0,0).toInt();
1602 int r1 = 0 ;
1603 char cc[10];
1604 strncpy(cc,s1.section(digits,1,-1).toStdString().c_str(),4);
1605 for (size_t k=0; k<strlen(cc);k++) {r1*=256;r1+=(size_t)cc[k];}
1606 switch (sortierWeise){
1607 case 1:
1608 atomSortMap.insert(
1609 toms.at(i).resiNr*99*amax+
1610 toms.at(i).part*amax+
1611 n1+
1612 ((110-toms.at(i).an)/220.0)+
1613 (r1 / 50000.0)//46656
1614 ,toms.at(i));
1615 atomSortMapi.insert(
1616 toms.at(i).resiNr*99*amax+
1617 toms.at(i).part*amax+
1618 n1+
1619 ((110-toms.at(i).an)/220.0)+
1620 (r1 / 50000.0)//46656
1621 ,i);
1622 break;
1623 case 2:
1624 atomSortMap.insert(
1625 toms.at(i).resiNr*99*amax+
1626 toms.at(i).part*amax+
1627 n1/999.0+
1628 ((110-toms.at(i).an))+
1629 (r1 / 50000.0)//46656
1630 ,toms.at(i));
1631 atomSortMapi.insert(
1632 toms.at(i).resiNr*99*amax+
1633 toms.at(i).part*amax+
1634 n1/999.0+
1635 ((110-toms.at(i).an))+
1636 (r1 / 50000.0)//46656
1637 ,i);
1638 break;
1639 case 3:
1640 atomSortMap.insert(
1641 toms.at(i).resiNr*99*amax+
1642 toms.at(i).part*amax+
1643 n1/999.0+
1644 sfac.indexOf(toms.at(i).an)*10+
1645 (r1 / 50000.0)//46656
1646 ,toms.at(i));
1647 atomSortMapi.insert(
1648 toms.at(i).resiNr*99*amax+
1649 toms.at(i).part*amax+
1650 n1/999.0+
1651 sfac.indexOf(toms.at(i).an)*10+
1652 (r1 / 50000.0)//46656
1653 ,i);
1654 break;
1655 case 4:
1656 atomSortMap.insert(
1657 toms.at(i).resiNr*99*amax+
1658 toms.at(i).part*amax+
1659 n1/50000.0+
1660 ((110-toms.at(i).an)/220)+
1661 (r1 )//46656
1662 ,toms.at(i));
1663 atomSortMapi.insert(
1664 toms.at(i).resiNr*99*amax+
1665 toms.at(i).part*amax+
1666 n1/50000.0+
1667 ((110-toms.at(i).an)/220)+
1668 (r1 )//46656
1669 ,i);
1670 t2++;
1671 break;
1672 case 5:
1673 atomSortMap.insert(
1674 toms.at(i).molindex*9999*amax+
1675 toms.at(i).resiNr*99*amax+
1676 toms.at(i).part*amax+
1677 n1/999.0+
1678 ((110-toms.at(i).an))+
1679 (r1 / 50000.0)//46656
1680 ,toms.at(i));
1681 atomSortMapi.insert(
1682 toms.at(i).molindex*9999*amax+
1683 toms.at(i).resiNr*99*amax+
1684 toms.at(i).part*amax+
1685 n1/999.0+
1686 ((110-toms.at(i).an))+
1687 (r1 / 50000.0)//46656
1688 ,i);
1689 /* printf("%s %g\n", chgl->mol->asymm.at(i).Label.toStdString().c_str(),chgl->mol->asymm.at(i).molindex*9999*amax+
1690 chgl->mol->asymm.at(i).resiNr*99*amax+
1691 chgl->mol->asymm.at(i).part*amax+
1692 n1/999.0+
1693 ((110-chgl->mol->asymm.at(i).an))+
1694 (r1 / 50000.0));*/
1695 break;
1696 default:
1697 atomSortMap.insert(i
1698 ,toms.at(i));
1699 atomSortMapi.insert(i
1700 ,i);
1701 break;
1702 }
1703 }
1704 CEnvironment asymm2=
1705 atomSortMap.values();
1706 QList<int> kk=atomSortMapi.values();
1707 cursor.beginEditBlock ();
1708 cursor.removeSelectedText ();
1709
1710 QStringList neu,li= sel.split(QChar::ParagraphSeparator);
1711
1712 QRegularExpression sep=spaces;
1713 QString neues;
1714 bool fix=false;
1715 for (int i=0; i<li.size(); i++){
1716 int cmd=Window::isacommand(li.at(i).section(sep,0,0));
1717 switch (cmd){
1718 case 1:fix=true;
1719 //printf("afix\n");
1720 // intentional fall-through !
1721 case -1:
1722 if ((!fix)&&(cmd==-1)&&(!li.at(i).startsWith(" "))&&(!neues.isEmpty())){
1723 neu.append(neues);
1724 neues.clear();
1725 }
1726 neues.append('\n');
1727 neues.append(li.at(i));
1728 if (li.at(i).contains (afix0inst)){
1729 neu.append(neues);
1730 neues.clear();
1731 fix=false;
1732 }
1733 break;
1734 case 51:
1735 case 58:break;
1736 default:
1737 if (!neues.isEmpty()){
1738 neu.append(neues);
1739 neues.clear();
1740 }
1741 cursor.insertText(li.at(i));
1742 cursor.insertText("\n");
1743 }
1744
1745 }
1746 if (!neues.isEmpty()){
1747 neu.append(neues);
1748 neues.clear();
1749 }
1750 //qDebug()<<neu<<neu.size()<<kk;
1751 int ares=0, apart=0;
1752 for (int i=0; i < asymm2.size(); i++){
1753 if ((asymm2.at(i).resiNr!=ares))
1754 cursor.insertText(QString("RESI %1 %2\n")
1755 .arg(asymm2.at(i).resiNr)
1756 .arg(asymm2.at(i).ResiClass));
1757 if ((asymm2.at(i).part!=apart))
1758 cursor.insertText(QString("PART %1\n")
1759 .arg(asymm2.at(i).part));
1760 cursor.insertText(neu.at(kk.at(i)));
1761 ares = asymm2.at(i).resiNr;
1762 apart = asymm2.at(i).part;
1763 }
1764 cursor.endEditBlock ();
1765 updateAfix();
1766 //todo editieren!!
1767 }
1768
1769 void CodeEditor::insertEADP(QList<MyAtom> selected, QString resiSpec){
1770 QTextDocument *document = this->document();
1771 QTextCursor cursor = textCursor();
1772 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
1773 cursor = document->find(unitinst,cursor);
1774 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1775 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
1776 QString buffer =QString("EADP%1 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec);
1777 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
1778 cursor.insertText(DSRGui::textWrap(buffer));
1779 }
1780
1781 void CodeEditor::insertDELU(double esd1, double esd2, QList<MyAtom> selected, QString resiSpec){
1782 QTextDocument *document = this->document();
1783 QTextCursor cursor = textCursor();
1784 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
1785 cursor = document->find(unitinst,cursor);
1786 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1787 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
1788 QString buffer = QString("DELU%1 %2 %3 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec).arg(esd1).arg(esd2);
1789 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
1790 cursor.insertText(DSRGui::textWrap(buffer));
1791 }
1792
1793 void CodeEditor::insertSIMU(double esd1, double esd2, double dmax, QList<MyAtom> selected, QString resiSpec){
1794 QTextDocument *document = this->document();
1795 QTextCursor cursor = textCursor();
1796 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
1797 cursor = document->find(unitinst,cursor);
1798 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1799 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
1800 QString buffer =QString("SIMU%1 %2 %3 %4 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec).arg(esd1).arg(esd2).arg(dmax);
1801 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
1802 cursor.insertText(DSRGui::textWrap(buffer));
1803 }
1804
1805 void CodeEditor::insertISOR(double esd1, double esd2, QList<MyAtom> selected, QString resiSpec){
1806 QTextDocument *document = this->document();
1807 QTextCursor cursor = textCursor();
1808 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
1809 cursor = document->find(unitinst,cursor);
1810 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1811 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
1812 QString buffer =QString("ISOR%1 %2 %3 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec).arg(esd1).arg(esd2);
1813 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
1814 cursor.insertText(DSRGui::textWrap(buffer));
1815 }
1816
1817 void CodeEditor::insertRIGU(double esd1, double esd2, QList<MyAtom> selected, QString resiSpec){
1818 QTextDocument *document = this->document();
1819 QTextCursor cursor = textCursor();
1820 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
1821 cursor = document->find(unitinst,cursor);
1822 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1823 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
1824 QString buffer =QString("RIGU%1 %2 %3 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec).arg(esd1).arg(esd2);
1825 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
1826 cursor.insertText(DSRGui::textWrap(buffer));
1827 }
1828
1829 void CodeEditor::insertCHIV(double vol, double esd1, QList<MyAtom> selected, QString resiSpec){
1830 QTextDocument *document = this->document();
1831 QTextCursor cursor = textCursor();
1832 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
1833 cursor = document->find(unitinst,cursor);
1834 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1835 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
1836 QString buffer =QString("CHIV%1 %2 %3 ").arg((resiSpec.isEmpty())?"":"_"+resiSpec).arg(vol).arg(esd1);
1837 buffer = selectedRestraintsAtoms(buffer, selected, resiSpec);
1838 cursor.insertText(DSRGui::textWrap(buffer));
1839 }
1840
1841 void CodeEditor::omitsome(const QString &s){
1842 QList<Omit> schonWeg;
1843 Omit o;
1844 QTextDocument *document = this->document();
1845 QTextCursor cursor = textCursor();
1846 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
1847 QStringList sli;
1848 while (!cursor.isNull()){
1849 cursor = document->find(omithklinst,cursor);
1850 if (!cursor.isNull()){
1851 sli=cursor.selectedText().split(" ",skipEmptyParts);
1852 o.h=sli.at(1).toInt();
1853 o.k=sli.at(2).toInt();
1854 o.l=sli.at(3).toInt();
1855 schonWeg.append(o);
1856 }
1857 }
1858 QString sm=s;
1859 for (int i=0; i<schonWeg.size(); i++){
1860 sm.remove(QString("OMIT %1 %2 %3\n").arg(schonWeg.at(i).h).arg(schonWeg.at(i).k).arg(schonWeg.at(i).l));
1861 }
1862 cursor = textCursor();
1863 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
1864 if (!sm.isEmpty()){
1865 cursor = document->find("UNIT",cursor);
1866 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
1867 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
1868 cursor.insertText(sm);
1869 emit saveMe(true, true);
1870 }
1871 }
1872
1873 void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event){
1874 QPainter painter(lineNumberArea);
1875 int current = textCursor().blockNumber();
1876 if (!dark){
1877 painter.fillRect(event->rect(), QColor("#eeeeee"));
1878 QTextBlock block = firstVisibleBlock();
1879 // printf("edidor Font: %s italic%d bold %d point %d pixel %d height %d\n",fontInfo().family().toStdString().c_str(),fontInfo().italic (),fontInfo().bold (),fontInfo().pointSize (),fontInfo().pixelSize (),fontMetrics().height());
1880 // printf("lineNumberAreaPaintEvent\n");
1881 int blockNumber = block.blockNumber();
1882 int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
1883 int bottom = top + (int) blockBoundingRect(block).height();
1884 // printf ("line %d %d\n",top,bottom);
1885 int minbl=8888888,maxbl=0;
1886 while (block.isValid() && top <= event->rect().bottom()) {
1887 if (block.isVisible() && bottom >= event->rect().top()) {
1888 QString number = QString::number(blockNumber + 1);
1889 bool iscurrent=(blockNumber==current);
1890 if (m_cursors.hasMultipleCursors()){
1891 iscurrent=m_cursors.aCursorInThisBlock(blockNumber);
1892 }
1893 if (blockNumber%2) painter.fillRect(0, top,
1894 lineNumberArea->width(),
1895 fontMetrics().height(),QColor("#dddddd"));
1896 if (iscurrent) painter.fillRect(0, top,
1897 lineNumberArea->width(),
1898 fontMetrics().height(),QColor("#242424"));
1899 // /*
1900 QFont f=font();
1901 //printf("Font painter font %s %d\n", f.family().toStdString().c_str(),f.pointSize());
1902 if (errorInLine.contains(blockNumber)) {
1903 painter.fillRect(0, top,
1904 lineNumberArea->width(),
1905 fontMetrics().height(),QColor("#aa0000"));
1906 iscurrent=true;
1907 }
1908 if (comment.at(blockNumber)) {
1909 painter.fillRect(5, top+2,
1910 3,//lineNumberArea->width()
1911 fontMetrics().height()-4,(iscurrent)?QColor("#99aaff"):QColor("#0000aa"));
1912 }
1913
1914
1915 //printf("edidor Font: %s %d %d %d\n",f.family().toStdString().c_str(),f.pointSize(),fontMetrics().height(),fontMetrics().lineSpacing ());
1916 f.setWeight((iscurrent)?QFont::Black:QFont::Light);
1917 painter.setFont(f);
1918 // */
1919 painter.setPen((iscurrent)?Qt::white:Qt::darkGray);
1920 painter.drawText(0, top,
1921 lineNumberArea->width(),
1922 fontMetrics().lineSpacing () ,
1923 Qt::AlignRight, number);
1924 minbl=qMin(minbl,blockNumber + 1);
1925 maxbl=qMax(maxbl,blockNumber + 1);
1926 }
1927 if (ListFile)
1928 midCursorpos=(minbl+maxbl)/2;
1929 block = block.next();
1930 top = bottom;
1931 bottom = top + (int) blockBoundingRect(block).height();
1932 ++blockNumber;
1933 }
1934 }else{
1935 painter.fillRect(event->rect(), QColor("#242424"));//"#eeeeee"));
1936 QTextBlock block = firstVisibleBlock();
1937 // printf("edidor Font: %s italic%d bold %d point %d pixel %d height %d\n",fontInfo().family().toStdString().c_str(),fontInfo().italic (),fontInfo().bold (),fontInfo().pointSize (),fontInfo().pixelSize (),fontMetrics().height());
1938 // printf("lineNumberAreaPaintEvent\n");
1939 int blockNumber = block.blockNumber();
1940 int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
1941 int bottom = top + (int) blockBoundingRect(block).height();
1942 // printf ("line %d %d\n",top,bottom);
1943 int minbl=8888888,maxbl=0;
1944 while (block.isValid() && top <= event->rect().bottom()) {
1945 if (block.isVisible() && bottom >= event->rect().top()) {
1946 QString number = QString::number(blockNumber + 1);
1947 bool iscurrent=(blockNumber==current);
1948 if (m_cursors.hasMultipleCursors()){
1949 iscurrent=m_cursors.aCursorInThisBlock(blockNumber);
1950 }
1951 if (blockNumber%2) painter.fillRect(0, top,
1952 lineNumberArea->width(),
1953 fontMetrics().height(),QColor("424242"));//"#dddddd"));
1954 if (iscurrent) painter.fillRect(0, top,
1955 lineNumberArea->width(),
1956 fontMetrics().height(),QColor("#eeeeee"));
1957 // /*
1958 QFont f=font();//painter.font();
1959 if (errorInLine.contains(blockNumber)) {
1960 painter.fillRect(0, top,
1961 lineNumberArea->width(),
1962 fontMetrics().height(),QColor("#aa0000"));
1963 iscurrent=true;
1964 }
1965 if (comment.at(blockNumber)) {
1966 painter.fillRect(5, top+2,
1967 3,//lineNumberArea->width()
1968 fontMetrics().height()-4,(!iscurrent)?QColor("#99aaff"):QColor("#0000aa"));
1969 }
1970
1971
1972 //printf("edidor Font: %s %d %d %d\n",f.family().toStdString().c_str(),f.pointSize(),fontMetrics().height(),fontMetrics().lineSpacing ());
1973 f.setWeight((iscurrent)?QFont::Black:QFont::Light);
1974 painter.setFont(f);
1975 // */
1976 painter.setPen((!iscurrent)?Qt::lightGray:Qt::black);
1977 painter.drawText(0, top,
1978 lineNumberArea->width(),
1979 fontMetrics().lineSpacing () ,
1980 Qt::AlignRight, number);
1981 minbl=qMin(minbl,blockNumber + 1);
1982 maxbl=qMax(maxbl,blockNumber + 1);
1983 }
1984 if (ListFile)
1985 midCursorpos=(minbl+maxbl)/2;
1986 block = block.next();
1987 top = bottom;
1988 bottom = top + (int) blockBoundingRect(block).height();
1989 ++blockNumber;
1990 }
1991 }
1992
1993
1994 //updateAfix();
1995 //afixHighlightArea->update();
1996 event->accept();
1997 }
1998
1999 void CodeEditor::lineNumberToggled(QMouseEvent *event){
2000 QTextBlock block=firstVisibleBlock();
2001 int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
2002 int bn=firstVisibleBlock().blockNumber();
2003 int idx=(int) (event->y()-top)/ ((int) blockBoundingRect(block).height()) + bn + 1;
2004 // printf("remark-> idx-1 %d event.y %d top %d first %d height %g\n",idx-1,event->y(),top,bn,blockBoundingRect(block).height());
2005 remark(idx-1);
2006 }
2007
2008 void CodeEditor::updateAfix(){
2009 // printf("updateAfix\n");
2010 blocks=toPlainText().split('\n');
2011
2012 /*printf("test die Zeilenanzahl ist jetzt %d %d\n",
2013 blocks.size(),
2014 blockCount()
2015 );*/
2016 parenthesis.clear();
2017 parenthesis2.clear();
2018 comment.clear();
2019 int probe=0,aprobe=0,amn=0;
2020 bool kommentar=false;
2021 for (int i=0; i<blocks.size();i++){
2022 kommentar = (blocks.at(i).contains(comments));
2023 comment.append(kommentar);
2024 if (blocks.at(i).contains(afix0inst)) {
2025 probe=0;
2026 amn=0;
2027 }
2028 else {
2029 if (blocks.at(i).contains(afixinst)) {
2030 probe++;
2031 int m=blocks.at(i).section(spaces,1,1,QString::SectionSkipEmpty).toInt()/10;
2032 int n=blocks.at(i).section(spaces,1,1,QString::SectionSkipEmpty).toInt()%10;
2033 if (amn==(m*10+n)) {
2034 probe--;
2035 parenthesis.last()=2;
2036 }
2037 if (n==5) {
2038 // printf("%d be---\n",probe);
2039 probe=(qMax(probe-2,0));
2040 // printf("%d----\n",probe);
2041 }
2042 amn=m*10+n;
2043 }
2044 }
2045 if (blocks.at(i).contains(hklfinst)) {probe=aprobe=0;}
2046 parenthesis.append(qMax(probe,aprobe));
2047 aprobe=probe;
2048 }
2049 probe=0;
2050 for (int i=0; i<blocks.size();i++){
2051 if (blocks.at(i).contains(part0inst)) probe=0;
2052 else if (blocks.at(i).contains(partinst))
2053 probe=blocks.at(i).section(' ',1,1,QString::SectionSkipEmpty).toInt();
2054 if (blocks.at(i).contains(hklfinst)) {probe=0;}
2055 parenthesis2.append(probe);
2056 }
2057 afixHighlightArea->update();
2058 }
2059
2060 void CodeEditor::remark(int line){
2061 if (isReadOnly ())return;
2062 if (blocks.size()<=line) return;
2063 QString zeile=blocks.at(line).simplified();
2064 bool cont= blocks.at(qMax(0,line-1)).contains(linecontinue);
2065 if (zeile.contains(comments)) {
2066 zeile=zeile.remove(0,4);
2067 if (cont) zeile.prepend(' ');
2068 }
2069 else zeile.prepend("REM ");
2070 QTextCursor cu=textCursor ();
2071 cu.movePosition(QTextCursor::Start);
2072 cu.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor,line);
2073 cu.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
2074 cu.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
2075 if (!cu.selectedText().isEmpty()) cu.deleteChar();
2076 cu.insertText(zeile);
2077 //qDebug()<<zeile;
2078
2079 }
2080
2081 void CodeEditor::toggleRemarks(){
2082 QTextCursor cu=textCursor();
2083 if (!cu.hasSelection())return;
2084 cu.beginEditBlock();
2085 int start=-1,end=-1,hilf=0;
2086 start=cu.selectionStart();
2087 end=cu.selectionEnd();
2088 cu.setPosition(start);
2089 start=cu.blockNumber();
2090 cu.setPosition(end);
2091 end=cu.blockNumber();
2092 //printf("start %d end %d\n",start,end);
2093 hilf=start;
2094 start=qMin(start,end);
2095 end=qMax(hilf,end);
2096 if (end!=start) {
2097 cu.clearSelection();
2098 for (int i=start; i<=end; i++) remark(i);
2099 //qDebug()<<cu.selectedText()<<"\n"<<start<<end;
2100 }
2101 cu.endEditBlock();
2102 cu.clearSelection();
2103 cu.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
2104
2105 if (!cu.isNull()) setTextCursor(cu);
2106 }
2107
2108 void CodeEditor::afixHighlightAreaPaintEvent(QPaintEvent *event){
2109 // printf("\nafixHighlightAreaPaintEvent\n");
2110 QPainter apainter(afixHighlightArea);
2111 apainter.fillRect(afixHighlightArea->rect(), (dark)?QColor(0xfff242424u):QColor(0xfffafafau));
2112 QTextBlock block = firstVisibleBlock();
2113 QColor color;
2114 QColor pcolor;
2115 int blockNumber = block.blockNumber();
2116
2117
2118 int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
2119 int bottom = top + (int) blockBoundingRect(block).height();
2120 //printf ("afix %d %d %d %d \n",top,bottom,block.isVisible(),event->rect().top());
2121 while (block.isValid() && top <= event->rect().bottom()) {
2122 switch (parenthesis.at(blockNumber)){
2123 case 0: color=(dark)?QColor(0xff242424u):QColor(0xfffafafau);
2124 // Qt::white;
2125 break;
2126 case 1: color=Qt::darkGreen;break;
2127 default:
2128 color=QColor("blueviolet");
2129 break;
2130 }
2131 pcolor=PartColor::color(parenthesis2.at(blockNumber),dark);
2132 if (block.isVisible() && bottom >= event->rect().top()) {
2133 // printf("%d %d %d %d %d %d\n",0,top, 4,fontMetrics().height(),parenthesis.at(blockNumber),blockNumber);
2134 apainter.fillRect(5,top, 4,fontMetrics().lineSpacing (),color);
2135 apainter.fillRect(0,top, 4,fontMetrics().lineSpacing (),pcolor);
2136 }
2137 block = block.next();
2138 blockNumber = block.blockNumber();
2139 top = bottom;
2140 bottom = top + (int) blockBoundingRect(block).height();
2141 }
2142 event->accept();
2143 }
2144
2145 void CodeEditor::hoverLineNumber(QMouseEvent *event){
2146 if (!isVisible()) {event->ignore(); return;}
2147 //fontMetrics().lineSpacing ()
2148 QTextBlock block=firstVisibleBlock();
2149 int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
2150 int bn=firstVisibleBlock().blockNumber();
2151 int idx=(int) (event->y()-top)/ ((int) blockBoundingRect(block).height()) + bn;
2152 if (idx>=parenthesis.size()) {event->accept();return;}
2153 QString msg;
2154 if (parenthesis2.at(idx)){
2155 msg = QString("Line:%6%1 PART=%2 %3<br> Color:<font color=%5>%4 ## %5</font>")
2156 .arg((parenthesis.at(idx))?"<br>AFIXed<br>":"")
2157 .arg(parenthesis2.at(idx))
2158 .arg((comment.at(idx))?"<br>This line is a comment.":"")
2159 .arg(PartColor::name(parenthesis2.at(idx),dark))
2160 .arg(PartColor::color(parenthesis2.at(idx),dark).name())
2161 .arg(idx+1);
2162 }else{
2163 msg = QString("Line:%4%1 PART=%2 %3")
2164 .arg((parenthesis.at(idx))?"<br>AFIXed<br>":"")
2165 .arg(parenthesis2.at(idx))
2166 .arg((comment.at(idx))?"<br>This line is a comment.":"")
2167 .arg(idx+1);
2168 }
2169 QToolTip::showText(event->globalPos(),msg);
2170 event->accept();
2171 }
2172 bool CodeEditor::viewportEvent(QEvent *event){
2173 // printf("lala %d\n",event->type());
2174 if (!isVisible()) {event->ignore(); return false;}
2175 if (event->type() == QEvent::ToolTip) {
2176 QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
2177 QTextCursor cursor = cursorForPosition( helpEvent->pos());
2178 if(cursor.block().text().isEmpty()) return true;
2179 QStringList block=shxToolTips.filter(cursor.block().text().left(4),Qt::CaseInsensitive);
2180 if (block.size())
2181 QToolTip::showText(helpEvent->globalPos(),block.first());
2182 int lnr=cursor.block().blockNumber()+1;
2183 QRegularExpression re=QRegularExpression("[-]*\\d{2,}\\.\\d+");
2184 double fvar=6666.6666;
2185 QString fvs;
2186 QString msg;
2187
2188 //int pos=0,len=0;
2189 if ((block.isEmpty())&&(!highlighter->outputStyle())&&(cursor.block().blockNumber() > fvMinLine)){
2190 QRegularExpressionMatchIterator matchIterator = re.globalMatch(cursor.block().text());
2191 while (matchIterator.hasNext()){
2192 //fvs=re.cap(0);
2193 QRegularExpressionMatch match = matchIterator.next();
2194 fvs=match.captured();
2195 //len=fvs.size();
2196 fvar=fvs.toDouble();
2197 if (fvar!=6666.6666) {
2198 double av=qAbs(fvar),res=0.0,var=1.0;
2199 int m=0;
2200 while ((-10*m+av) > 5){m++;}
2201 if ((m>1)&&(m<=fv.size())) var = fv.at(m-1);
2202 if (!m) res = fvar;
2203 else if (fvar>0) res = (av-(10*m))*var;
2204 else res = (av-(10*m))*(1.0-var);
2205 //qDebug()<<v<<res<<m;
2206 // std::cout<< av <<"abs v"<< v <<" m ="<< m << " var =" << var <<" res = "<<res<< std::endl ;
2207 //return res;
2208 if ((m)>fv.size()){
2209 if (m>1) msg+=QString("<font color=\"red\">Error in line %2!<br>Free Variable %1 is not defined yet!</font><hr>")
2210 .arg(m).arg(lnr);}
2211 else
2212 msg+=QString("Line <b>%3</b>: Free Variable <b>%1</b> gives <b> %2</b> here.<hr>")
2213 .arg(m).arg(res).arg(lnr);
2214 }
2215 }
2216 QToolTip::showText(helpEvent->globalPos(),msg);
2217 // printf("shxToolTips size+%d %d %f\n", shxToolTips.size(),block.size(),fvar);
2218 }
2219 event->accept();
2220 return true;
2221 }
2222 return QAbstractScrollArea::viewportEvent ( event);
2223 }
2224
2225 void CodeEditor::contextMenuEvent(QContextMenuEvent *event) {
2226 //QMenu *menu = new QMenu();//createStandardContextMenu();
2227 QMenu *menu = createStandardContextMenu();
2228 QAction *a;
2229 QTextCursor cursor = cursorForPosition( event->pos());
2230 QTextBlock block=cursor.block();
2231 QString aname=block.text().section(" ",0,0);
2232 QStringList bfl=shxToolTips.filter(QRegularExpression(QString("^%1\\b").arg(aname)));
2233 if (bfl.isEmpty()){
2234 QString data=block.text().remove("=").trimmed(); // findInStructure
2235 if (data.startsWith("+")) a=menu->addAction(QString("+Open inluded file '%1'").arg(data) ,this,SLOT(openAnIncludeFile()));
2236 else a=menu->addAction(QString("locate %1 in structure").arg(aname) ,this,SLOT(searchInStructure()));
2237 a->setData(data);
2238 }//else {qDebug()<<bfl;}
2239
2240 if (textCursor().hasSelection()){
2241 a=menu->addAction(QString("select atoms in structure found in selected text"),
2242 this, SLOT(selectInStructure()));
2243 a->setData(textCursor().selectedText());
2244 a=menu->addAction(QString("sort atoms found in selected text"),
2245 this, SLOT(sortSelectedRegion()));
2246 a->setData(textCursor().selectedText());
2247 menu->addAction(QString("toggle remarks states of selected text"),
2248 this,SLOT(toggleRemarks()));
2249 }
2250 //...
2251 menu->exec(event->globalPos());
2252 delete menu;
2253
2254 event->accept();
2255 }
2256
2257 void CodeEditor::diffTo(QString org){
2258 QList<QTextEdit::ExtraSelection> extraSelections;
2259 QTextEdit::ExtraSelection selection;
2260 QStringList orgZ = org.split('\n');
2261 QColor lineColor = QColor(0xffffddaau);
2262 setReadOnly(false);
2263 selection.cursor = textCursor();
2264 selection.cursor.clearSelection();
2265 selection.cursor.movePosition(QTextCursor::Start);
2266
2267 selection.format.setBackground(lineColor);
2268 selection.format.setProperty(QTextFormat::FullWidthSelection, true);
2269
2270 QTextBlock b = selection.cursor.block();
2271 int i=0;
2272 while (b.isValid()){
2273 if (b.text()!=orgZ.at(i)){
2274 /* printf(">>%s!\n<<%s!%d\n",
2275 b.text().toStdString().c_str(),
2276 orgZ.at(i).toStdString().c_str(),b.position()
2277 );// */
2278 selection.cursor.clearSelection();
2279 selection.cursor.setPosition(b.position());
2280 selection.cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
2281 selection.cursor.movePosition(QTextCursor::EndOfLine,QTextCursor::MoveAnchor);
2282
2283 extraSelections.append(selection);
2284 }
2285 b=b.next();
2286 int j=orgZ.indexOf(b.text(),i);
2287 i=(j<0)?i+1:j;
2288 i=qMin(i,orgZ.size()-1);
2289 }
2290 setExtraSelections(extraSelections);
2291 setReadOnly(true);
2292 update();
2293 }
2294
2295 void CodeEditor::searchInStructure(){
2296 QAction *action = qobject_cast<QAction *>(sender());
2297 if (action)
2298 emit findInStructure(action->data().toString());
2299
2300 }
2301
2302 void CodeEditor::openAnIncludeFile(){
2303 QAction *action = qobject_cast<QAction *>(sender());
2304 if (action)
2305 emit openIncludeFile(action->data().toString());
2306
2307 }
2308
2309 void CodeEditor::selectInStructure(){
2310 QAction *action = qobject_cast<QAction *>(sender());
2311 if (action)
2312 emit electInStructure(action->data().toString());
2313
2314 }
2315
2316 void CodeEditor::setCompleter(QCompleter *completer){
2317 //printf("setCompleter %p %p\n",c,completer);
2318 if (c)
2319 QObject::disconnect(c, 0, this, 0);
2320
2321 c = completer;
2322
2323 if (!c)
2324 return;
2325
2326 c->setWidget(this);
2327 //c->setMaxVisibleItems(13);
2328 c->setCompletionMode(QCompleter::PopupCompletion);
2329 c->setCaseSensitivity(Qt::CaseInsensitive);
2330 QObject::connect(c, SIGNAL(activated(QString)),
2331 this, SLOT(insertCompletion(QString)));
2332 }
2333
2334 QCompleter *CodeEditor::completer() const{
2335 return c;
2336 }
2337
2338 void CodeEditor::insertCompletion(const QString& completion){
2339 if (c->widget() != this)
2340 return;
2341 QTextCursor tc = textCursor();
2342 tc.joinPreviousEditBlock ();
2343 MultiTextCursor mc=multiTextCursor();
2344 //printf("compl:%s: %d %d\n",completion.toStdString().c_str(),tc.position(),mc.mainCursor().position());
2345 //int extra = completion.length() - c->completionPrefix().length();
2346 //tc.movePosition(QTextCursor::Left);
2347 // int p=tc.selectionStart()- tc.block().position();
2348 tc.movePosition(QTextCursor::EndOfWord,QTextCursor::MoveAnchor);
2349 tc.movePosition(QTextCursor::StartOfLine,QTextCursor::KeepAnchor);
2350 QString extra = tc.selectedText();
2351 //extra.remove(0,1);
2352 extra.remove(startsmall);
2353 if ((completion!="REM "))extra.clear();
2354 tc.deleteChar();
2355 tc.insertText(completion+" "+extra);
2356 tc.endEditBlock();
2357 setTextCursor(tc);
2358 }
2359
2360 QString CodeEditor::textUnderCursor() const{
2361 QTextCursor tc = textCursor();
2362 tc.select(QTextCursor::WordUnderCursor);
2363 if (tc.selectedText().contains("_")) return "";
2364 int si=tc.selectedText().size();
2365 if (((tc.selectionStart () - tc.block().position())<4)&&(si>4)) return tc.selectedText().left(si-4);
2366 if ((tc.position() - tc.block().position())>2) return "";
2367 return tc.selectedText();
2368 }
2369
2370
2371
2372 void CodeEditor::insertFree(){
2373 if (chgl->mol->selectedatoms.size()!=2) return;
2374 QAction *action = qobject_cast<QAction *>(sender());
2375 if (action){
2376 int index= action->data().toInt();
2377 QString frei=QString("FREE %1 %2 !experimental does not work with EQIV AND PART\n")
2378 .arg(chgl->mol->selectedatoms.at(0).Label.section(QString::fromUtf8("»"),0,0),chgl->mol->selectedatoms.at(1).Label.section(QString::fromUtf8("»"),0,0));
2379 QTextDocument *document = this->document();
2380 QTextCursor cursor = textCursor();
2381 cursor.beginEditBlock();
2382 cursor = document->find("HKLF",cursor);
2383 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
2384 cursor.insertText(frei);
2385 cursor.endEditBlock();
2386 chgl->disConnectSelection(index);
2387 }
2388 }
2389
2390 void CodeEditor::insertBind(){
2391 if (chgl->mol->selectedatoms.size()!=2) return;
2392 QString binde=QString("BIND %1 %2 !experimental does not work with EQIV AND PART\n")
2393 .arg(chgl->mol->selectedatoms.at(0).Label.section(QString::fromUtf8("»"),0,0),chgl->mol->selectedatoms.at(1).Label.section(QString::fromUtf8("»"),0,0));
2394 QTextDocument *document = this->document();
2395 QTextCursor cursor = textCursor();
2396 cursor.beginEditBlock();
2397 cursor = document->find("HKLF",cursor);
2398 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
2399 cursor.insertText(binde);
2400 cursor.endEditBlock();
2401 chgl->connectSelection();
2402 }
2403
2404 void CodeEditor::keyPressEvent(QKeyEvent *e){
2405 // printf("kp\n");
2406 // if (!chgl->mol->selectedatoms.isEmpty()){
2407
2408 if (c && c->popup()->isVisible()) {
2409 // The following keys are forwarded by the completer to the widget
2410 switch (e->key()) {
2411 case Qt::Key_Enter:
2412 case Qt::Key_Return:
2413 case Qt::Key_Escape:
2414 case Qt::Key_Tab:
2415 // case Qt::Key_Left:
2416 // case Qt::Key_Right:
2417 case Qt::Key_Backtab:
2418 e->ignore();
2419 return; // let the completer do default behavior
2420 default:
2421 break;
2422 }
2423 }
2424 MultiTextCursor mcursor = multiTextCursor();
2425
2426 if (e->key() == Qt::Key_Escape ) {
2427 if (mcursor.hasMultipleCursors()) {
2428 QTextCursor c = mcursor.mainCursor();
2429 c.setPosition(c.position(), QTextCursor::MoveAnchor);
2430 // printf("%d\n",__LINE__);
2431 doSetTextCursor1(c);
2432 return;
2433 }
2434 }
2435
2436
2437 // Pressing F1 when the mouse cursor is over a SHELX command will
2438 // open the SHELXL help text:
2439 if (e->key() == Qt::Key_F1) {
2440 QTextCursor tc = textCursor();
2441 //tc.select(QTextCursor::WordUnderCursor);
2442 tc.select(QTextCursor::LineUnderCursor);
2443 QString txt = tc.selectedText().toUpper().left(4).trimmed();
2444 //printf("%s\n",txt.toStdString().c_str());
2445 if ( Window::isacommand(txt) >= 0 ) {
2446 QUrl help_url = QString("http://shelx.uni-goettingen.de/shelxl_html.php#%1").arg(txt);
2447 QDesktopServices::openUrl(help_url);
2448 }
2449 }
2450 const bool ro = isReadOnly();
2451 const bool inOverwriteMode = overwriteMode();
2452 const bool hasMultipleCursors = mcursor.hasMultipleCursors();
2453 if (!ro && e == QKeySequence::Paste){
2454 // printf("wanna pasta\n");
2455 mpaste();
2456 e->accept();
2457 return;
2458 } else if (!ro && e == QKeySequence::Cut){
2459 mcut();
2460 e->accept();
2461 return;
2462 } else
2463 if (!ro && (e == QKeySequence::MoveToStartOfBlock
2464 || e == QKeySequence::SelectStartOfBlock
2465 || e == QKeySequence::MoveToStartOfLine
2466 || e == QKeySequence::SelectStartOfLine)) {
2467 const bool blockOp = e == QKeySequence::MoveToStartOfBlock || e == QKeySequence::SelectStartOfBlock;
2468 const bool select = e == QKeySequence::SelectStartOfLine || e == QKeySequence::SelectStartOfBlock;
2469 handleHomeKey(select, blockOp);
2470 e->accept();
2471 return;
2472 } else if (!ro && e == QKeySequence::DeleteStartOfWord) {
2473 e->accept();
2474 if (!mcursor.hasSelection()) {
2475 mcursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
2476 }
2477 mcursor.removeSelectedText();
2478 setMultiTextCursor(mcursor);
2479 return;
2480 } else if (!ro && e == QKeySequence::DeleteEndOfWord) {
2481 e->accept();
2482 if (!mcursor.hasSelection()) {
2483 mcursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor);
2484 }
2485 mcursor.removeSelectedText();
2486 setMultiTextCursor(mcursor);
2487 return;
2488 } else if (!ro && e == QKeySequence::Undo){
2489 QPlainTextEdit::undo();
2490 e->accept();
2491 return;
2492 }
2493
2494 /*else if (!ro && e == QKeySequence::DeleteCompleteLine) {
2495 e->accept();
2496 for (QTextCursor &c : cursor)
2497 c.select(QTextCursor::BlockUnderCursor);
2498 cursor.mergeCursors();
2499 cursor.removeSelectedText();
2500 setMultiTextCursor(cursor);
2501 return;
2502 } else*/
2503
2504 switch (e->key()) {
2505 case Qt::Key_Backspace:
2506 if (ro) break;
2507 if ((e->modifiers() & (Qt::ControlModifier
2508 | Qt::ShiftModifier
2509 | Qt::AltModifier
2510 | Qt::MetaModifier)) == Qt::NoModifier) {
2511 e->accept();
2512 if (mcursor.hasSelection()) {
2513 mcursor.removeSelectedText();
2514 setMultiTextCursor(mcursor);
2515 return;
2516 }
2517 handleBackspaceKey();
2518 return;
2519 }
2520 break;
2521 case Qt::Key_Insert:
2522 if (ro) break;
2523 if (e->modifiers() == Qt::NoModifier) {
2524 // printf("insert or overwirte %d\n",inOverwriteMode);
2525 // setOverwriteMode(!inOverwriteMode);
2526 e->accept();
2527 return;
2528 }
2529 break;
2530 case Qt::Key_Delete:
2531 if (hasMultipleCursors && !ro && e->modifiers() == Qt::NoModifier) {
2532 if (mcursor.hasSelection()) {
2533 mcursor.removeSelectedText();
2534 } else {
2535 mcursor.beginEditBlock();
2536 for (int i=0; i<mcursor.m_cursors.size(); i++) mcursor.m_cursors[i].deleteChar();
2537 mcursor.mergeCursors();
2538 mcursor.endEditBlock();
2539 }
2540 e->accept();
2541 return;
2542 }
2543 break;
2544 default:
2545 break;
2546 }
2547
2548 if ((e->modifiers() & Qt::ControlModifier)&&(e->key()==Qt::Key_Delete)) {
2549 e->ignore();
2550 emit deleteSelected();
2551 return;
2552 }
2553
2554 const QString eventText = e->text();
2555 if (ro || !isPrintableText(eventText)) {
2556 QTextCursor::MoveOperation blockSelectionOperation = QTextCursor::NoMove;
2557 if (e->modifiers() & Qt::AltModifier) {
2558 if (MultiTextCursor::multiCursorAddEvent(e, QKeySequence::MoveToNextLine))
2559 blockSelectionOperation = QTextCursor::Down;
2560 else if (MultiTextCursor::multiCursorAddEvent(e, QKeySequence::MoveToPreviousLine))
2561 blockSelectionOperation = QTextCursor::Up;
2562 else if (MultiTextCursor::multiCursorAddEvent(e, QKeySequence::MoveToNextChar))
2563 blockSelectionOperation = QTextCursor::NextCharacter;
2564 else if (MultiTextCursor::multiCursorAddEvent(e, QKeySequence::MoveToPreviousChar))
2565 blockSelectionOperation = QTextCursor::PreviousCharacter;
2566 }
2567
2568
2569 if (blockSelectionOperation != QTextCursor::NoMove) {
2570 //auto doNothing = [](){};
2571 //[](){};(doNothing);
2572 //printf("about to handleMoveBlockSelection\n");
2573 handleMoveBlockSelection(blockSelectionOperation);
2574 } else if (!cursorMoveKeyEvent(e)) {
2575 QTextCursor cursor = textCursor();
2576 //printf("ro=%d %s\n",ro,eventText.toStdString().c_str());
2577 QPlainTextEdit::keyPressEvent(e);
2578 }
2579 } else if (hasMultipleCursors) {
2580 //printf("hasMultipleCursors\n");
2581 if (inOverwriteMode) {
2582 mcursor.beginEditBlock();
2583 for (int i=0; i<mcursor.m_cursors.size(); i++){
2584 // for (QTextCursor &c : cursor) {
2585 QTextBlock block = mcursor.m_cursors[i].block();
2586 int eolPos = block.position() + block.length() - 1;
2587 int selEndPos = qMin(mcursor.m_cursors[i].position() + eventText.length(), eolPos);
2588 mcursor.m_cursors[i].setPosition(selEndPos, QTextCursor::KeepAnchor);
2589 mcursor.m_cursors[i].insertText(eventText);
2590 }
2591 mcursor.endEditBlock();
2592 } else {
2593 mcursor.insertText(eventText);
2594 }
2595 setMultiTextCursor(mcursor);
2596 } else if ((e->modifiers() & (Qt::ControlModifier|Qt::AltModifier)) != Qt::ControlModifier){
2597 // only go here if control is not pressed, except if also alt is pressed
2598 // because AltGr maps to Alt + Ctrl
2599
2600 QTextCursor cursor = textCursor();
2601
2602 if (inOverwriteMode) {
2603 QTextBlock block = cursor.block();
2604 int eolPos = block.position() + block.length() - 1;
2605 int selEndPos = qMin(cursor.position() + eventText.length(), eolPos);
2606 cursor.setPosition(selEndPos, QTextCursor::KeepAnchor);
2607 cursor.insertText(eventText);
2608 } else {
2609 cursor.insertText(eventText);
2610 }
2611 setTextCursor(cursor);
2612 }// */
2613
2614 //}
2615
2616
2617 // bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E
2618 // if (!c) // do not process the shortcut when we have a completer
2619 //printf("here\n");
2620 // QPlainTextEdit::keyPressEvent(e);
2621
2622 const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
2623 if (!c || (ctrlOrShift && e->text().isEmpty()))
2624 return;
2625
2626 static QString eow("!"); // end of word
2627 bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
2628 QString completionPrefix = textUnderCursor();
2629 if ((hasModifier || e->text().isEmpty()|| completionPrefix.length() < 1
2630 || eow.contains(e->text().right(1)))) {
2631 c->popup()->hide();
2632 return;
2633 }
2634
2635 if (completionPrefix != c->completionPrefix()) {
2636 c->setCompletionPrefix(completionPrefix);
2637 c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
2638 }
2639 QRect cr = cursorRect();
2640 cr.moveRight(lineNumberAreaWidth()+11);;
2641 cr.setWidth(c->popup()->sizeHintForColumn(0)
2642 + c->popup()->verticalScrollBar()->sizeHint().width());
2643 c->complete(cr); // popup it up!
2644 }
2645
2646
2647 void CodeEditor::insertCONF(){//!< inserts CONF instruction into the file...
2648 QTextDocument *document = this->document();
2649 QTextCursor cc,cursor = textCursor();
2650 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
2651
2652 cc = document->find(confinst,cursor);
2653 if (cc.isNull()) {
2654 cursor = textCursor();
2655 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
2656 }else return;
2657 cursor = document->find(unitinst,cursor);
2658 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
2659 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
2660 cursor.insertText("CONF \n");
2661 }
2662
2663 void CodeEditor::insertEXTI(){//!< inserts a EXTI instruction into the file...
2664 QTextDocument *document = this->document();
2665 QTextCursor cc,cursor = textCursor();
2666 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
2667
2668 cc = document->find(extiinst,cursor);
2669 if (cc.isNull()) {
2670 cursor = textCursor();
2671 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
2672 }else return;
2673 cursor = document->find(unitinst,cursor);
2674 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
2675 cursor.movePosition(QTextCursor::Down,QTextCursor::MoveAnchor);
2676 cursor.insertText("EXTI \n");
2677 }
2678
2679
2680
2681 MultiTextCursor CodeEditor::multiTextCursor() const{
2682 const QTextCursor c=textCursor();
2683 if ((m_cursors.isNull())&&(!c.isNull())){
2684 MultiTextCursor mc(c);
2685 const_cast<MultiTextCursor &>(m_cursors) = mc;
2686 // printf("nun %d %d %d\n",m_cursors.isNull(), m_cursors.cursorCount(),m_cursors.mainCursor().isNull());
2687 }
2688 return m_cursors;
2689 }
2690
2691 void CodeEditor::setMultiTextCursor(const MultiTextCursor &cursor){
2692 const MultiTextCursor oldCursor = m_cursors;
2693 const_cast<MultiTextCursor &>(m_cursors) = cursor;
2694 if (oldCursor == m_cursors)
2695 return;
2696 // printf("%d\n",__LINE__);
2697 doSetTextCursor(m_cursors.mainCursor(), /*keepMultiSelection*/ true);
2698 QRect updateRect = cursorUpdateRect(oldCursor);
2699 //if (d->m_highlightCurrentLine) updateRect = QRect(0, updateRect.y(), viewport()->rect().width(), updateRect.height());
2700 updateRect |= cursorUpdateRect(m_cursors);
2701 viewport()->update(updateRect);
2702 emit cursorPositionChanged();
2703 }
2704
2705 QRect CodeEditor::cursorUpdateRect(const MultiTextCursor &cursor){
2706 QRect result(0, 0, 0, 0);
2707 // for (const QTextCursor &c : cursor)
2708 for (int i=0; i<cursor.m_cursors.size(); i++){
2709 result |= cursorRect(cursor.m_cursors[i]);
2710 }
2711 //printf("%d %d %d %d \n",result.x(),result.y(),result.width(),result.height());
2712 return result;
2713 }
2714
2715 void CodeEditor::doSetTextCursor(const QTextCursor &cursor, bool keepMultiSelection){
2716 // workaround for QTextControl bug
2717 //bool selectionChange = cursor.hasSelection() || textCursor().hasSelection();
2718 //printf("doSetTextCursor\n");
2719 QTextCursor c = cursor;
2720 c.setVisualNavigation(true);
2721 const MultiTextCursor oldCursor = m_cursors;
2722 if (!keepMultiSelection){
2723 QList<QTextCursor> cs;
2724 cs.append(c);
2725 const_cast<MultiTextCursor &>(m_cursors).setCursors(cs); //{c}
2726 //printf("doSetTextCursor %d %d not keepMultiSelection\n",cs.size(),m_cursors.cursorCount());
2727 }
2728 else
2729 const_cast<MultiTextCursor &>(m_cursors).replaceMainCursor(c);
2730 updateCursorSelections();
2731 resetCursorFlashTimer();
2732 //printf("=>doSetTextCursor %d\n",m_cursors.cursorCount());
2733 //doSetTextCursor(c);
2734 setTextCursor(c);
2735 //QPlainTextEdit::doSetTextCursor(c);
2736 if (oldCursor != m_cursors) {
2737 //printf("must uptadte rect\n");
2738 QRect updateRect = cursorUpdateRect(oldCursor);
2739 //if (d->m_highlightCurrentLine) updateRect = QRect(0, updateRect.y(), viewport()->rect().width(), updateRect.height());
2740 updateRect |= cursorUpdateRect(m_cursors);
2741 viewport()->update(updateRect);
2742 //emit cursorPositionChanged();
2743 }
2744 //if (selectionChange) d->slotSelectionChanged();
2745 }
2746
2747
2748 void CodeEditor::updateCursorSelections(){
2749 //const QTextCharFormat selectionFormat = TextEditorSettings::fontSettings().toTextCharFormat(C_SELECTION);
2750 QTextCharFormat selectionFormat;
2751 selectionFormat.setBackground((dark)?QColor("#346792"):QColor("#a5cbfa"));
2752 QList<QTextEdit::ExtraSelection> selections;
2753 //for (const QTextCursor &cursor : m_cursors) {
2754 for (int i=0; i<m_cursors.m_cursors.size(); i++) {
2755 if (m_cursors.m_cursors.at(i).hasSelection()){
2756 QTextEdit::ExtraSelection s;
2757 s.cursor=m_cursors.m_cursors[i];
2758 s.format=selectionFormat;
2759 selections << s;
2760 }
2761 }
2762 if (selections.isEmpty()) m_blockSelections.clear();
2763 setExtraSelections(selections);
2764 }
2765
2766 void CodeEditor::startCursorFlashTimer()
2767 {
2768 const int flashTime = QApplication::cursorFlashTime();
2769 //printf("cursorFlashTime %d\n",flashTime);
2770 if (flashTime > 0) {
2771 m_cursorFlashTimer.stop();
2772 m_cursorFlashTimer.start(flashTime / 2,this);
2773 }
2774 if (!m_cursorVisible) {
2775 m_cursorVisible = true;
2776 viewport()->update(cursorUpdateRect(m_cursors));
2777 }
2778 }
2779
2780 void CodeEditor::resetCursorFlashTimer(){
2781 //return;
2782 if (!m_cursorFlashTimer.isActive())
2783 return;
2784 const int flashTime = QApplication::cursorFlashTime();
2785 if (flashTime > 0) {
2786 m_cursorFlashTimer.stop();
2787 m_cursorFlashTimer.start(flashTime / 2,this);
2788 }
2789 if (!m_cursorVisible) {
2790 m_cursorVisible = true;
2791 viewport()->update(cursorUpdateRect(m_cursors));
2792 }
2793 }
2794
2795
2796 void CodeEditor::focusInEvent(QFocusEvent *e){
2797 if (c) c->setWidget(this);
2798 QPlainTextEdit::focusInEvent(e);
2799 startCursorFlashTimer();
2800 //d->updateHighlights();
2801 }
2802
2803 void CodeEditor::focusOutEvent(QFocusEvent *e){
2804 QPlainTextEdit::focusOutEvent(e);
2805 if (viewport()->cursor().shape() == Qt::BlankCursor)
2806 viewport()->setCursor(Qt::IBeamCursor);
2807 m_cursorFlashTimer.stop();
2808 if (m_cursorVisible) {
2809 m_cursorVisible = false;
2810 viewport()->update(cursorUpdateRect(m_cursors));
2811 }
2812 //d->updateHighlights();
2813 }
2814
2815
2816 void CodeEditor::doSetTextCursor1(const QTextCursor &cursor){
2817 // const char* str = __builtin_FUNCTION();
2818 // printf("called by %s\n", str);
2819 // printf("%d\n",__LINE__);
2820 doSetTextCursor(cursor, false);
2821 }
2822
2823
2824 void CodeEditor::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode){
2825 MultiTextCursor cursor = m_cursors;
2826 cursor.movePosition(operation, mode);
2827 setMultiTextCursor(cursor);
2828 }
2829
2830 bool CodeEditor::cursorMoveKeyEvent(QKeyEvent *e){
2831 MultiTextCursor cursor = m_cursors;
2832 if (cursor.handleMoveKeyEvent(e)) {
2833 //printf("handleMoveKeyEvent %d!!\n",cursor.cursorCount());
2834 resetCursorFlashTimer();
2835 setMultiTextCursor(cursor);
2836 ensureCursorVisible();
2837 //updateCurrentLineHighlight();
2838 return true;
2839 }
2840 return false;
2841 }
2842 void CodeEditor::handleHomeKey(bool anchor, bool block){
2843 const QTextCursor::MoveMode mode = anchor ? QTextCursor::KeepAnchor
2844 : QTextCursor::MoveAnchor;
2845
2846 MultiTextCursor mcursor = multiTextCursor();
2847 //for (QTextCursor &c : cursor) {
2848 for (int i=0; i<mcursor.m_cursors.size(); i++){
2849 const int initpos = mcursor.m_cursors[i].position();
2850 int pos = mcursor.m_cursors[i].block().position();
2851
2852 if (!block) {
2853 // only go to the first non space if we are in the first line of the layout
2854 //c++17...
2855 if (mcursor.m_cursors[i].block().layout()->lineForTextPosition(initpos - pos).lineNumber()!=0)
2856 /*if (QTextLayout *layout = mcursor.m_cursors[i].block().layout();
2857 layout->lineForTextPosition(initpos - pos).lineNumber() != 0)*/ {
2858 mcursor.m_cursors[i].movePosition(QTextCursor::StartOfLine, mode);
2859 }
2860 }
2861
2862 QChar character = document()->characterAt(pos);
2863 const QLatin1Char tab = QLatin1Char('\t');
2864
2865 while (character == tab || character.category() == QChar::Separator_Space) {
2866 ++pos;
2867 if (pos == initpos)
2868 break;
2869 character = document()->characterAt(pos);
2870 }
2871
2872 // Go to the start of the block when we're already at the start of the text
2873 if (pos == initpos)
2874 pos = mcursor.m_cursors[i].block().position();
2875
2876 mcursor.m_cursors[i].setPosition(pos, mode);
2877 }
2878 setMultiTextCursor(mcursor);
2879 }
2880
2881 void CodeEditor::handleBackspaceKey(){
2882 //if (!multiTextCursor().hasSelection()) return;
2883 MultiTextCursor mcursor = m_cursors;
2884 if (mcursor.cursorCount()<2) {
2885 QTextCursor c=textCursor();
2886 c.deletePreviousChar();
2887 setTextCursor(c);
2888 return;
2889 }
2890 mcursor.beginEditBlock();
2891 //for (QTextCursor &c : cursor) {
2892 for (int i=0; i<mcursor.m_cursors.size(); i++){
2893 const int pos = mcursor.m_cursors[i].position();
2894 if (!pos)
2895 continue;
2896 mcursor.m_cursors[i].deletePreviousChar();
2897 }
2898 mcursor.endEditBlock();
2899 setMultiTextCursor(mcursor);
2900 }
2901
2902 void CodeEditor::mouseMoveEvent(QMouseEvent *e){
2903
2904 static MultiTextCursor startMouseMoveCursor;
2905 if (e->buttons() == Qt::LeftButton && e->modifiers() & Qt::AltModifier) {
2906 if (!startMouseMoveCursor1) {
2907 startMouseMoveCursor1=true;
2908 startMouseMoveCursor = multiTextCursor();
2909 QTextCursor c = startMouseMoveCursor.takeMainCursor();
2910 if (!startMouseMoveCursor.hasMultipleCursors()
2911 && !startMouseMoveCursor.hasSelection()) {
2912 startMouseMoveCursor.emplace(MultiTextCursor());
2913 }
2914
2915 c.setPosition(c.anchor());
2916 startMouseMoveCursor.addCursor(c);
2917 }
2918 MultiTextCursor cursor = startMouseMoveCursor;
2919 const QTextCursor anchorCursor = cursor.takeMainCursor();
2920 const QTextCursor eventCursor = cursorForPosition(e->pos());
2921 int eventColumn = eventCursor.columnNumber();
2922 int anchorColumn = anchorCursor.columnNumber();
2923 const BlockSelection blockSelection =
2924 {eventCursor.blockNumber(), eventColumn, anchorCursor.blockNumber(), anchorColumn};
2925
2926 cursor.setCursors(generateCursorsForBlockSelection(blockSelection));
2927
2928 if (!cursor.isNull()) setMultiTextCursor(cursor);
2929 } else {
2930 if (startMouseMoveCursor1)
2931 startMouseMoveCursor1=false;
2932 if (e->buttons() == Qt::NoButton) {
2933 //printf("Kick ma mama keine knoepfe\n");
2934 /*
2935 const QTextBlock collapsedBlock = d->foldedBlockAt(e->pos());
2936 const int blockNumber = collapsedBlock.next().blockNumber();
2937 if (blockNumber < 0) {
2938 d->clearVisibleFoldedBlock();
2939 } else if (blockNumber != d->visibleFoldedBlockNumber) {
2940 d->suggestedVisibleFoldedBlockNumber = blockNumber;
2941 d->foldedBlockTimer.start(40, this);
2942 }
2943
2944 const RefactorMarker refactorMarker = d->m_refactorOverlay->markerAt(e->pos());
2945
2946 // Update the mouse cursor
2947 if ((collapsedBlock.isValid() || refactorMarker.isValid())
2948 && !d->m_mouseOnFoldedMarker) {
2949 d->m_mouseOnFoldedMarker = true;
2950 viewport()->setCursor(Qt::PointingHandCursor);
2951 } else if (!collapsedBlock.isValid() && !refactorMarker.isValid()
2952 && d->m_mouseOnFoldedMarker) {
2953 d->m_mouseOnFoldedMarker = false;
2954 viewport()->setCursor(Qt::IBeamCursor);
2955 }
2956 */
2957 } else {
2958 QPlainTextEdit::mouseMoveEvent(e);
2959 }
2960 }
2961
2962 if (viewport()->cursor().shape() == Qt::BlankCursor)
2963 viewport()->setCursor(Qt::IBeamCursor);
2964 }
2965 /*
2966 static bool handleForwardBackwardMouseButtons(QMouseEvent *e)
2967 {
2968 if (e->button() == Qt::XButton1) {
2969 EditorManager::goBackInNavigationHistory();
2970 return true;
2971 }
2972 if (e->button() == Qt::XButton2) {
2973 EditorManager::goForwardInNavigationHistory();
2974 return true;
2975 }
2976
2977 return false;
2978 }
2979 */
2980 void CodeEditor::mousePressEvent(QMouseEvent *e){
2981 if (e->button() == Qt::LeftButton) {
2982 MultiTextCursor multiCursor = multiTextCursor();
2983 const QTextCursor &cursor = cursorForPosition(e->pos());
2984 if (e->modifiers() & Qt::AltModifier && !(e->modifiers() & Qt::ControlModifier)) {
2985 if (e->modifiers() & Qt::ShiftModifier) {
2986 QTextCursor c = multiCursor.mainCursor();
2987 c.setPosition(cursor.position(), QTextCursor::KeepAnchor);
2988 multiCursor.replaceMainCursor(c);
2989 //printf("replaceMainCursor\n");
2990 } else {
2991 multiCursor.addCursor(cursor);
2992 //printf("addCursor %d %d %d %d\n",cursor.isNull(),m_cursors.isNull(), m_cursors.hasMultipleCursors(),m_cursors.cursorCount());
2993 }
2994 setMultiTextCursor(multiCursor);
2995 return;
2996 } else {
2997 //printf("was multi? %d\n",m_cursors.hasMultipleCursors());
2998 if (multiCursor.hasMultipleCursors()) setMultiTextCursor(MultiTextCursor(cursor));
2999 //printf(" is multi? %d\n",m_cursors.hasMultipleCursors());
3000 /*
3001 RefactorMarker refactorMarker = d->m_refactorOverlay->markerAt(e->pos());
3002 if (refactorMarker.isValid()) {
3003 if (refactorMarker.callback)
3004 refactorMarker.callback(this);
3005 } else {
3006 d->m_linkPressed = d->isMouseNavigationEvent(e);
3007 }*/
3008 }
3009 } else if (e->button() == Qt::RightButton) {
3010 int eventCursorPosition = cursorForPosition(e->pos()).position();
3011 if (eventCursorPosition < textCursor().selectionStart()
3012 || eventCursorPosition > textCursor().selectionEnd()) {
3013 setTextCursor(cursorForPosition(e->pos()));
3014 }
3015 }
3016
3017 /*if (HostOsInfo::isLinuxHost() && handleForwardBackwardMouseButtons(e))
3018 return;*/
3019
3020 QPlainTextEdit::mousePressEvent(e);
3021 }
3022
3023 QList<QTextCursor> CodeEditor::generateCursorsForBlockSelection(const BlockSelection &blockSelection){
3024 //const TabSettings tabSettings = m_document->tabSettings();
3025 /*printf("%d %d %d %d\n",
3026 blockSelection.column,
3027 blockSelection.blockNumber,
3028 blockSelection.anchorColumn,
3029 blockSelection.anchorBlockNumber);*/
3030 QList<QTextCursor> result;
3031 QTextBlock block = document()->findBlockByNumber(blockSelection.anchorBlockNumber);
3032 QTextCursor cursor(block);
3033 cursor.setPosition(block.position()+blockSelection.anchorColumn);//check this?
3034
3035 const bool forward = blockSelection.blockNumber > blockSelection.anchorBlockNumber
3036 || (blockSelection.blockNumber == blockSelection.anchorBlockNumber
3037 && blockSelection.column == blockSelection.anchorColumn);
3038
3039 while (block.isValid()) {
3040 const QString &blockText = block.text();
3041 const int columnCount = blockText.length();
3042 if (blockSelection.anchorColumn <= columnCount || blockSelection.column <= columnCount) {
3043 const int anchor = blockSelection.anchorColumn;
3044 const int position = blockSelection.column;
3045 cursor.setPosition(block.position() + anchor);
3046 cursor.setPosition(block.position() + position, QTextCursor::KeepAnchor);
3047 result.append(cursor);
3048 }
3049 /*else {
3050 const int anchor = blockSelection.anchorColumn;
3051 const int position = blockSelection.column;
3052 cursor.setPosition(block.position() + columnCount);
3053 int ee=qMax(anchor,position)-columnCount-1;
3054 for (int j=0; j<ee; j++)cursor.insertText(" ");
3055 cursor.setPosition(block.position() + anchor);
3056 cursor.setPosition(block.position() + position, QTextCursor::KeepAnchor);
3057 // printf("eng %d %d %d null?%d %d %d\n",columnCount,blockSelection.anchorColumn,blockSelection.column,
3058 cursor.isNull(),cursor.blockNumber(),cursor.columnNumber());
3059
3060 result.append(cursor);
3061 }*/
3062 if (block.blockNumber() == blockSelection.blockNumber)
3063 break;
3064 block = forward ? block.next() : block.previous();
3065
3066 }
3067 return result;
3068 }
3069
3070 void CodeEditor::initBlockSelection(){
3071 //const TabSettings tabSettings = m_document->tabSettings();
3072 //for (const QTextCursor &cursor : m_cursors) {
3073 //printf("initBlockSelection %d %d\n",m_cursors.m_cursors.size(),m_cursors.cursorCount());
3074 for (int i=0; i<m_cursors.m_cursors.size(); i++){
3075 const int column = m_cursors.m_cursors[i].columnNumber();
3076 QTextCursor anchor = m_cursors.m_cursors[i];
3077 anchor.setPosition(anchor.anchor());
3078 const int anchorColumn = anchor.columnNumber();
3079 BlockSelection bs;
3080 bs.column=column;
3081 bs.blockNumber=m_cursors.m_cursors[i].blockNumber();
3082 bs.anchorColumn=anchorColumn;
3083 bs.anchorBlockNumber=anchor.blockNumber();
3084 m_blockSelections.append(bs);
3085 }
3086 }
3087
3088 void CodeEditor::clearBlockSelection(){
3089 m_blockSelections.clear();
3090 }
3091
3092 void CodeEditor::handleMoveBlockSelection(QTextCursor::MoveOperation op){
3093 //printf("!!handleMoveBlockSelection leer?%d size=%d\n",m_blockSelections.isEmpty(),m_blockSelections.size());
3094 if (m_blockSelections.isEmpty())
3095 initBlockSelection();
3096 QList<QTextCursor> cursors;
3097 for (int i=0; i<m_blockSelections.size(); i++) { //m_blockSelections[i]
3098 switch (op) {
3099 case QTextCursor::Up:
3100 m_blockSelections[i].blockNumber = qMax(0, m_blockSelections[i].blockNumber - 1);
3101 break;
3102 case QTextCursor::Down:
3103 m_blockSelections[i].blockNumber = qMin(document()->blockCount() - 1, m_blockSelections[i].blockNumber + 1);
3104 break;
3105 case QTextCursor::NextCharacter:
3106 ++m_blockSelections[i].column;
3107 break;
3108 case QTextCursor::PreviousCharacter:
3109 m_blockSelections[i].column = qMax(0, m_blockSelections[i].column - 1);
3110 break;
3111 default:
3112 return;
3113 }
3114 cursors.append(generateCursorsForBlockSelection(m_blockSelections[i]));
3115 }
3116 setMultiTextCursor(MultiTextCursor(cursors));
3117 }
3118
3119 void CodeEditor::timerEvent(QTimerEvent *e){
3120 if (m_cursors.m_cursors.size()<2)return;
3121 if (e->timerId() == m_cursorFlashTimer.timerId()) {
3122 m_cursorVisible = !m_cursorVisible;
3123 QRect updateRect = cursorUpdateRect(m_cursors);
3124 //printf("updateRect %d %d %d %d\n",updateRect.topLeft().x(),updateRect.topLeft().y(),updateRect.bottomRight().x(),updateRect.bottomRight().y());
3125 viewport()->update(updateRect);
3126 }
3127 else {
3128 printf("other event? %d\n",e->timerId());
3129 QPlainTextEdit::timerEvent(e);
3130 }
3131 }
3132
3133
3134 void CodeEditor::paintCursor(const PaintEventData &data, QPainter &painter) const{
3135 bool multi=data.cursors.size()>1;
3136 if (!multi) return;
3137 int cw = QPlainTextEdit::cursorWidth();
3138 for (int i=0; i< data.cursors.size();i++) {
3139 QPen pen(QColor("#4284ff"));//Qt::red);//data.cursors.at(i).pen);
3140 pen.setStyle(Qt::SolidLine);
3141 painter.setPen(pen);
3142 QBrush brush(QColor("#4284ff"));
3143 painter.setBrush(brush);
3144 data.cursors.at(i).layout->drawCursor(&painter, data.cursors.at(i).offset, data.cursors.at(i).pos, cw);
3145 }
3146 }
3147
3148 bool CodeEditor::blockContainsCursor(const PaintEventBlockData &blockData, const QTextCursor &cursor){
3149 const int pos = cursor.position();
3150 return pos >= blockData.position && pos < blockData.position + blockData.length;
3151 }
3152
3153 CodeEditor::CursorData CodeEditor::generateCursorData(const int cursorPos,
3154 const PaintEventData &data,
3155 const PaintEventBlockData &blockData,
3156 QPainter &painter){
3157 CursorData cursorData;
3158 cursorData.layout = blockData.layout;
3159 cursorData.offset = data.offset;
3160 cursorData.pos = cursorPos;
3161 cursorData.pen = painter.pen();
3162 return cursorData;
3163 }
3164
3165 void CodeEditor::addCursorsPosition(PaintEventData &data,
3166 QPainter &painter,
3167 const PaintEventBlockData &blockData) const{
3168 for (int i=0; i<m_cursors.m_cursors.size(); i++){
3169 if (blockContainsCursor(blockData, m_cursors.m_cursors[i])) {
3170 data.cursors.append(
3171 generateCursorData(m_cursors.m_cursors[i].positionInBlock(), data, blockData, painter));
3172 }
3173 }
3174
3175 }
3176
3177 void CodeEditor::paintEvent(QPaintEvent *e){
3178 //if ((m_cursors.m_cursors.size()>1)&&((e->rect().width() - fontMetrics().width('9'))<6)&&((e->rect().height() - fontMetrics().height())<3)) {e->accept();return;}
3179 /*printf("i need to paint %d %d \n",
3180 e->rect().width() - fontMetrics().width('_'),
3181 e->rect().height() - fontMetrics().height());*/
3182 PaintEventData data(this, e, contentOffset());
3183 //QTC_ASSERT(data.documentLayout, return);
3184
3185
3186 QPlainTextEdit::paintEvent(e);
3187
3188 QPainter painter(viewport());
3189 // Set a brush origin so that the WaveUnderline knows where the wave started
3190 painter.setBrushOrigin(data.offset);
3191
3192 data.block = firstVisibleBlock();
3193 data.context = getPaintContext();
3194 //const QTextCharFormat textFormat = textDocument()->fontSettings().toTextCharFormat(C_TEXT);
3195 //data.context.palette.setBrush(QPalette::Text, textFormat.foreground());
3196 //data.context.palette.setBrush(QPalette::Base, textFormat.background());
3197
3198 while (data.block.isValid()) {
3199
3200 PaintEventBlockData blockData;
3201 blockData.boundingRect = blockBoundingRect(data.block).translated(data.offset);
3202
3203 if (blockData.boundingRect.bottom() >= data.eventRect.top()
3204 && blockData.boundingRect.top() <= data.eventRect.bottom()) {
3205
3206 setupBlockLayout(data, painter, blockData);
3207 blockData.position = data.block.position();
3208 blockData.length = data.block.length();
3209 setupSelections(data, blockData);
3210
3211 //d->paintCurrentLineHighlight(data, painter);
3212
3213 bool drawCursor = false;
3214 bool drawCursorAsBlock = false;
3215 //if (d->m_dndCursor.isNull()) {
3216 bool anyof=false;
3217 for (int i=0; i<m_cursors.m_cursors.size(); i++){
3218 if (blockContainsCursor(blockData,m_cursors.m_cursors[i])) {anyof=true;break;}
3219 }
3220 drawCursor = m_cursorVisible && anyof;
3221 drawCursorAsBlock = drawCursor && overwriteMode();
3222 /*} else {
3223 drawCursor = blockContainsCursor(blockData, d->m_dndCursor);
3224 }*/
3225 /*
3226 if (drawCursorAsBlock) {
3227 MultiTextCursor mc= multiTextCursor();
3228 for (int i=0; i<mc.m_cursors.size(); i++){
3229 if (blockContainsCursor(blockData, mc.m_cursors[i]))
3230 paintCursorAsBlock(data, painter, blockData, mc.m_cursors.at(i).position());
3231 }
3232 }*/
3233
3234 //paintBlock(&painter, data.block, data.offset, blockData.selections, data.eventRect);
3235
3236 if (data.isEditable && data.context.cursorPosition < -1
3237 && !blockData.layout->preeditAreaText().isEmpty()) {
3238 const int cursorPos = blockData.layout->preeditAreaPosition()
3239 - (data.context.cursorPosition + 2);
3240 data.cursors.append(generateCursorData(cursorPos, data, blockData, painter));
3241 }
3242
3243 if (drawCursor && !drawCursorAsBlock) addCursorsPosition(data, painter, blockData);
3244
3245 //d->paintAdditionalVisualWhitespaces(data, painter, blockData.boundingRect.top());
3246 //d->paintReplacement(data, painter, blockData.boundingRect.top());
3247 }
3248 //d->updateLineAnnotation(data, blockData, painter);
3249
3250 data.offset.ry() += blockData.boundingRect.height();
3251
3252 if (data.offset.y() > data.viewportRect.height())
3253 break;
3254
3255 data.block = data.block.next();
3256
3257 /*if (!data.block.isVisible()) {
3258 if (data.block.blockNumber() == d->visibleFoldedBlockNumber) {
3259 data.visibleCollapsedBlock = data.block;
3260 data.visibleCollapsedBlockOffset = data.offset;
3261 }
3262
3263 // invisible blocks do have zero line count
3264 data.block = data.doc->findBlockByLineNumber(data.block.firstLineNumber());
3265 }*/
3266 }
3267
3268 //d->cleanupAnnotationCache();
3269
3270 painter.setPen(data.context.palette.text().color());
3271
3272
3273 // draw the cursor last, on top of everything
3274 paintCursor(data, painter);
3275 //printf("paintEvent font size: %dpt\n",font().pointSize());
3276
3277 }
3278
3279 void CodeEditor::setupBlockLayout(const PaintEventData &data,
3280 QPainter &painter,
3281 PaintEventBlockData &blockData) const
3282
3283 {
3284 blockData.layout = data.block.layout();
3285
3286 QTextOption option = blockData.layout->textOption();
3287 option.setFlags(option.flags() & ~QTextOption::SuppressColors);
3288 painter.setPen(data.context.palette.text().color());
3289 blockData.layout->setTextOption(option);
3290 blockData.layout->setFont(data.doc->defaultFont());
3291 }
3292
3293 void CodeEditor::setupSelections(const PaintEventData &data,
3294 PaintEventBlockData &blockData) const
3295 {
3296 QVector<QTextLayout::FormatRange> prioritySelections;
3297 for (int i = 0; i < data.context.selections.size(); ++i) {
3298 const QAbstractTextDocumentLayout::Selection &range = data.context.selections.at(i);
3299 const int selStart = range.cursor.selectionStart() - blockData.position;
3300 const int selEnd = range.cursor.selectionEnd() - blockData.position;
3301 if (selStart < blockData.length && selEnd >= 0
3302 && selEnd >= selStart) {
3303 QTextLayout::FormatRange o;
3304 o.start = selStart;
3305 o.length = selEnd - selStart;
3306 o.format = range.format;
3307 if (data.textCursor.hasSelection() && data.textCursor == range.cursor
3308 && data.textCursor.anchor() == range.cursor.anchor()) {
3309 /*const QTextCharFormat selectionFormat = data.fontSettings.toTextCharFormat(C_SELECTION);
3310 if (selectionFormat.background().style() != Qt::NoBrush)
3311 o.format.setBackground(selectionFormat.background());
3312 o.format.setForeground(selectionFormat.foreground());
3313 */
3314 }
3315 if ((data.textCursor.hasSelection() && i == data.context.selections.size() - 1)
3316 || (o.format.foreground().style() == Qt::NoBrush
3317 && o.format.underlineStyle() != QTextCharFormat::NoUnderline
3318 && o.format.background() == Qt::NoBrush)) {
3319 //if (q->selectionVisible(data.block.blockNumber())) prioritySelections.append(o);
3320 } else {
3321 blockData.selections.append(o);
3322 }
3323 }
3324 }
3325 //blockData.selections.append(prioritySelections);
3326 }
3327
3328 void CodeEditor::slotCursorPositionChanged(){
3329 #if 0
3330 qDebug() << "block" << textCursor().blockNumber()+1
3331 << "brace depth:" << BaseTextDocumentLayout::braceDepth(textCursor().block())
3332 << "indent:" << BaseTextDocumentLayout::userData(textCursor().block())->foldingIndent();
3333 #endif
3334 /*if (!d->m_contentsChanged && d->m_lastCursorChangeWasInteresting) {
3335 if (EditorManager::currentEditor() && EditorManager::currentEditor()->widget() == this)
3336 EditorManager::addCurrentPositionToNavigationHistory(d->m_tempNavigationState);
3337 d->m_lastCursorChangeWasInteresting = false;
3338 } else if (d->m_contentsChanged) {
3339 d->saveCurrentCursorPositionForNavigation();
3340 if (EditorManager::currentEditor() && EditorManager::currentEditor()->widget() == this)
3341 EditorManager::setLastEditLocation(EditorManager::currentEditor());
3342 }*/
3343 MultiTextCursor cursor = multiTextCursor();
3344 cursor.replaceMainCursor(textCursor());
3345 setMultiTextCursor(cursor);
3346 updateCursorSelections();
3347 //d->updateHighlights();
3348 }
3349
3350
3351 void CodeEditor::updateCursorPosition(){
3352 if (!textCursor().block().isVisible()) ensureCursorVisible();
3353 }
3354
3355 void CodeEditor::mpaste(){
3356 if (m_cursors.hasMultipleCursors()){
3357 QClipboard *clipboard = QApplication::clipboard();
3358 m_cursors.insertText(clipboard->text());
3359 }else QPlainTextEdit::paste();
3360 }
3361
3362 void CodeEditor::mcut(){
3363 MultiTextCursor cursor = multiTextCursor();
3364 QString str=cursor.selectedText();
3365 cursor.removeSelectedText();
3366 setMultiTextCursor(cursor);
3367 QClipboard *clipboard = QApplication::clipboard();
3368 clipboard->setText(str);
3369 QPlainTextEdit::copy();
3370 /* if (m_cursors.hasMultipleCursors()){
3371
3372 }*/
3373 }
3374
3375 void CodeEditor::testCpd(){
3376 /*
3377 QClipboard *clipboard = QApplication::clipboard();
3378 const QMimeData *mmd=clipboard->mimeData();
3379 printf("MIMEDATA:%d %d\n",mmd->hasText(),mmd->hasUrls());
3380 qDebug()<<mmd->formats();
3381 printf(" %d %d CLIP: \n%s\n :BOARD\n",
3382 m_cursors.hasSelection(),
3383 textCursor().hasSelection(),
3384 clipboard->text().toStdString().c_str());*/
3385 if ((m_cursors.hasMultipleCursors())&&(m_cursors.hasSelection())){
3386 QClipboard *clipboard = QApplication::clipboard();
3387 // printf("Clip: \n%s=>\n",clipboard->text().toStdString().c_str());
3388 QString str=m_cursors.selectedText();
3389 m_cursors.clearSelection();
3390 printf(" MCOPY\n");
3391 clipboard->setText(str);
3392 printf("!%s!\n",clipboard->text().toLatin1().data());
3393
3394 }
3395 }
3396
3397 void CodeEditor::insertElectronSFACs(){
3398 QTextDocument *document = this->document();
3399 QTextCursor cursor = textCursor();
3400 cursor.beginEditBlock ();
3401 replace->setText("");
3402 searchLE->setText("^SFAC");
3403 bool wl=wholeLine->isChecked();
3404 wholeLine->setChecked(true);
3405 replaceAll();
3406 replace->setText("");
3407 searchLE->setText("");
3408 wholeLine->setChecked(wl);
3409 //for (int i=0; i<easf.size(); i++){printf("%s",easf.at(i).toStdString().c_str());}//\n are already in the strings
3410 if (cursor.isNull()){
3411 cursor = textCursor();
3412 //printf("war null\n");
3413 }
3414 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
3415 cursor = document->find(unitinst,cursor);
3416 if (cursor.isNull()){
3417 cursor = textCursor();
3418 //printf("war schon wieder null\n");
3419 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
3420 }
3421 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
3422 for (int i=0; i<sfacsmbl.size(); i++){
3423 int idx= easf.indexOf(QRegularExpression(QString("^SFAC %1 .*\n").arg(sfacsmbl.at(i)), QRegularExpression::CaseInsensitiveOption));
3424 //printf("searching %d %s\n",idx,QString("SFAC %1 .*").arg(sfacsmbl.at(i)).toStdString().c_str());
3425 if (idx!=-1) cursor.insertText(DSRGui::textWrap(easf.at(idx)));
3426 }
3427 cursor.insertText(
3428 "REM source:\nREM for neutral atoms:\nREM Electron atomic scattering factors and scattering potentials of crystals\n"
3429 "REM L.-M. Peng, Micron 30 (1999) 625–648.\n"
3430 "REM for ions:\nREM International Tables for Crystallography Vol C Table 4.3.1.2\n"
3431 "REM (gnuplot fit of Cromer-Mann parameters inspired by Tim Gruene))\n");
3432 cursor.endEditBlock();
3433 }
3434
3435 void CodeEditor::handleCBstates(int state){
3436 QCheckBox *cb = qobject_cast<QCheckBox *>(sender());
3437 if ((cb)&&(cbhandled)) {
3438 printf("%s ->%d\n",cb->objectName().toStdString().c_str(),state);
3439 QStringList anl = cb->objectName().split(' ');
3440 QList<QCheckBox *> cbs = cb->parent()->findChildren<QCheckBox *>();
3441 cbhandled=false;
3442 for (int i=0; i<cbs.size(); i++){
3443 if (cbs.at(i)->objectName().startsWith(anl.at(0)+" "))
3444 cbs[i]->setCheckState(static_cast<Qt::CheckState>((cbs.at(i)!=cb)?Qt::Checked-state:state));
3445 }
3446 cbhandled=true;
3447 }
3448 }
3449
3450 double CodeEditor::cromerMann(double sintl, double a1, double b1, double a2, double b2, double a3, double b3, double a4, double b4, double c){
3451 double stl2=sintl*sintl;
3452 return a1 * exp(-b1 * stl2) +a2 * exp(-b2 * stl2) +a3 * exp(-b3 * stl2) + a4 * exp(-b4 * stl2) + c;
3453 }
3454
3455 void CodeEditor::plotSFAC(){
3456 QGraphicsScene *scene = new QGraphicsScene(-25,-25,870,650);
3457 scene->setBackgroundBrush(QBrush(QColor("#e9f7d6")));
3458 QDialog *dlg = new QDialog();
3459 dlg->setObjectName("plotSFAC()");
3460 QGraphicsView *gv = new QGraphicsView(scene,dlg);
3461 QGridLayout *glo = new QGridLayout(dlg);
3462 int maxan=0;
3463 for (int k=0;k<sfac.size(); k++){
3464 int an = sfac.at(k)+1;
3465 maxan = qMax(maxan,an);
3466 }
3467 maxan++;
3468 int l=0;
3469 int pan=-1;
3470 printf("sintl min %f max %f %f %f\n",smin,smax,0.5/smin,0.5/smax);
3471 double maxsintl=(smax)?smax:2.0;
3472 for (int j=0; j<xasf.size(); j++){
3473 for (int k=0;k<sfac.size(); k++){
3474 int an = sfac.at(k)+1;
3475 maxan =qMax(maxan,an);
3476 QStringList tok = xasf.at(j).split(" ",skipEmptyParts);
3477 if (tok.size()<12) continue;
3478 if (tok.at(0).toInt()!=an) continue;
3479 CheckBox *cb = new CheckBox(scene, xasf.at(j).section('!',1), dlg);
3480 cb->setChecked(an!=pan);
3481 QString on=QString("%1 %2").arg(an).arg(j);
3482 cb->setObjectName(on);
3483 connect(cb,SIGNAL(stateChanged(int)),this,SLOT(handleCBstates(int)));
3484 glo->addWidget(cb, l, 1, Qt::AlignBottom);
3485 pan=an;
3486
3487 QGraphicsSimpleTextItem *t = scene->addSimpleText(xasf.at(j).section('!',1));
3488 t->moveBy(750,l*QFontMetrics(t->font()).height());
3489 t->setPen(QPen(chgl->mol->atomColor(an-1,true)));
3490 double a1 = tok.at(3).toDouble() ;
3491 double b1 = tok.at(4).toDouble() ;
3492 double a2 = tok.at(5).toDouble() ;
3493 double b2 = tok.at(6).toDouble() ;
3494 double a3 = tok.at(7).toDouble() ;
3495 double b3 = tok.at(8).toDouble() ;
3496 double a4 = tok.at(9).toDouble() ;
3497 double b4 = tok.at(10).toDouble() ;
3498 double c = tok.at(11).toDouble() ;
3499 //printf("%f %f %f %f %f %f %f %f %f\n",a1,b1,a2,b2,a3,b3,a4,b4,c);
3500
3501 for (int i=0; i<80; i++){
3502 double s1=i/80.0*maxsintl;
3503 double s2=(i+1)/80.0*maxsintl;
3504 double y1=600.0-600.0/maxan*cromerMann(s1,a1,b1,a2,b2,a3,b3,a4,b4,c);
3505 double y2=600.0-600.0/maxan*cromerMann(s2,a1,b1,a2,b2,a3,b3,a4,b4,c);
3506 QGraphicsLineItem *lit = scene->addLine(i*10,y1,(i+1)*10,y2,QPen(chgl->mol->atomColor(an-1,true)));
3507 lit->setData(0,on);
3508 }
3509
3510 l++;
3511 }
3512 }
3513 for (int i=0; i<=maxan; i++)scene->addLine(-7.0,600.0-600.0/maxan*i,0.0,600.0-600.0/maxan*i,QPen(Qt::black));
3514 for (int i=0; i<=maxan; i++){
3515 QGraphicsSimpleTextItem *t = scene->addSimpleText(QString::number(i));
3516 t->moveBy(-15.0,600.0-600.0/maxan*i);
3517 //t->setPen(QPen(chgl->mol->atomColor(an-1,true)));
3518 }
3519 for (int i=0; i<=10; i++)scene->addLine(80*i,607.0,80*i,600.0,QPen(Qt::black));
3520 for (int i=0; i<=10; i++){
3521 double s1=i/10.0*maxsintl;
3522 double d1=0.5/s1;
3523 QGraphicsSimpleTextItem *t = scene->addSimpleText(QString("%1Å").arg(d1,0,'g',3));
3524 t->moveBy(80*i,610);
3525 }
3526 scene->addLine(0.0,600.0,800.0,600.0,QPen(Qt::black));
3527 scene->addLine(0.0,0.0,0.0,600.0,QPen(Qt::black));
3528 scene->addLine(smin*800.0/maxsintl,-20.0,smin*800.0/maxsintl,620.0,QPen(Qt::blue));
3529 QGraphicsSimpleTextItem *t = scene->addSimpleText(QString("%1Å").arg(0.5/smin,0,'g',3));
3530 t->moveBy(smin*800.0/maxsintl,625);
3531 t->setPen(QPen(Qt::blue));
3532 QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Cancel,Qt::Vertical);
3533 bb->addButton(new QPushButton("Replace SFAC instructions",dlg),QDialogButtonBox::AcceptRole);
3534 glo->addWidget(gv,0,0,l,1);
3535 glo->addWidget(bb,0,3,1,1);
3536 connect(bb, SIGNAL(accepted()), dlg, SLOT(accept()));
3537 connect(bb, SIGNAL(rejected()), dlg, SLOT(reject()));
3538 connect(dlg,SIGNAL(accepted ()),this,SLOT(insertXRaySFACs()));
3539 dlg->exec();
3540
3541 }
3542
3543 void CodeEditor::insertXRaySFACs(){
3544 QString sdr=sender()->objectName();
3545 QList<QCheckBox *> cbs = sender()->findChildren<QCheckBox *>();
3546 //printf("insertXRaySFACs {%s}%lld\n",sdr.toStdString().c_str(),cbs.size());
3547 QTextDocument *document = this->document();
3548 QTextCursor cursor = textCursor();
3549 cursor.beginEditBlock ();
3550 replace->setText("");
3551 searchLE->setText("^SFAC");
3552 bool wl=wholeLine->isChecked();
3553 wholeLine->setChecked(true);
3554 replaceAll();
3555 replace->setText("");
3556 searchLE->setText("");
3557 wholeLine->setChecked(wl);
3558 /*for (int i=0; i<easf.size(); i++){
3559 printf("%s\n",easf.at(i).toStdString().c_str());
3560 }*/
3561 if (cursor.isNull()){
3562 cursor = textCursor();
3563 //printf("war null\n");
3564 }
3565 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
3566 cursor = document->find(unitinst,cursor);
3567 if (cursor.isNull()){
3568 cursor = textCursor();
3569 //printf("war schon wieder null\n");
3570 cursor.movePosition(QTextCursor::Start,QTextCursor::MoveAnchor);
3571 }
3572 cursor.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
3573 for (int k=0; k<sfac.size();k++){
3574 for (int i=0; i<cbs.size(); i++){
3575 if (cbs.at(i)->isChecked()){
3576 QStringList anl = cbs.at(i)->objectName().split(' ');
3577 if (anl.at(0).toInt()-1 != sfac.at(k)) continue;
3578 //printf("%d <> %lld \n",anl.at(0).toInt(),anl.size());
3579 if (anl.size()==2){
3580 int idx = anl.at(1).toInt();
3581 //printf("searching %d %s\n",idx,QString("SFAC %1 .*").arg(sfacsmbl.at(i)).toStdString().c_str());
3582 QString sfacstr=xasf.at(idx).section(' ',1).simplified();
3583 sfacstr=sfacstr.replace("fp fdp mu",dispFromWave(anl.at(0).toInt()-1)).simplified();
3584 sfacstr=DSRGui::textWrap(sfacstr);
3585 sfacstr.append("\n");
3586 cursor.insertText(sfacstr);
3587 }
3588 }
3589 /*
3590 cursor.insertText(
3591 "REM source:\nREM for neutral atoms:\nREM Electron atomic scattering factors and scattering potentials of crystals\n"
3592 "REM L.-M. Peng, Micron 30 (1999) 625–648.\n"
3593 "REM for ions:\nREM International Tables for Crystallography Vol C Table 4.3.1.2\n"
3594 "REM (gnuplot fit of Cromer-Mann parameters inspired by Tim Gruene))\n");
3595 */
3596 }//i
3597 }//k
3598 cursor.endEditBlock();
3599 }
3600
3601 void CheckBox::hoverEnter(QHoverEvent *event){
3602 event->accept();
3603 QList<QGraphicsItem *> itms = scene->items();
3604 for (int i=0; i<itms.size(); i++){
3605 if (itms.at(i)->data(0)==objectName()){
3606 QPen p=static_cast<QGraphicsLineItem*>(itms[i])->pen();
3607 p.setWidth(2);
3608 static_cast<QGraphicsLineItem*>(itms[i])->setPen(p);
3609 } else if (itms.at(i)->data(0).isValid()){
3610 QPen p=static_cast<QGraphicsLineItem*>(itms[i])->pen();
3611 p.setWidth(1);
3612 static_cast<QGraphicsLineItem*>(itms[i])->setPen(p);
3613 }
3614 }
3615 }
3616
3617 void CheckBox::hoverLeave(QHoverEvent *event){
3618 event->accept();
3619 QList<QGraphicsItem *> itms = scene->items();
3620 for (int i=0; i<itms.size(); i++){
3621
3622 if (itms.at(i)->data(0)==objectName()){
3623 QPen p=static_cast<QGraphicsLineItem*>(itms[i])->pen();
3624 p.setWidth(1);
3625 static_cast<QGraphicsLineItem*>(itms[i])->setPen(p);
3626 }else if (itms.at(i)->data(0).isValid()){
3627 QPen p=static_cast<QGraphicsLineItem*>(itms[i])->pen();
3628 p.setWidth(1);
3629 static_cast<QGraphicsLineItem*>(itms[i])->setPen(p);
3630 }
3631 }
3632
3633 }
3634
3635 void CheckBox::hoverMove(QHoverEvent *event){
3636 event->ignore();
3637 }
3638
3639 CheckBox::CheckBox(QGraphicsScene * _scene, const QString & _text, QWidget * _parent ) : QCheckBox(_text,_parent), scene(_scene){
3640 }