/
Utilities.cpp
1292 lines (1185 loc) · 36.7 KB
/
Utilities.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
/*
* @author Adeel Asghar <adeel.asghar@liu.se>
*/
#include "Utilities.h"
#include "Helper.h"
#include "StringHandler.h"
#include "OMC/OMCProxy.h"
#include "Modeling/ItemDelegate.h"
#include "Editors/BaseEditor.h"
#include <QApplication>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
#include <QScreen>
#else // QT_VERSION_CHECK
#include <QDesktopWidget>
#endif // QT_VERSION_CHECK
#include <QGridLayout>
#include <QStylePainter>
#include <QPainter>
#include <QColorDialog>
#include <QXmlSchema>
#include <QXmlSchemaValidator>
#include <QDir>
SplashScreen *SplashScreen::mpInstance = 0;
SplashScreen *SplashScreen::instance()
{
if (!mpInstance) {
mpInstance = new SplashScreen;
}
return mpInstance;
}
TreeSearchFilters::TreeSearchFilters(QWidget *pParent)
: QWidget(pParent)
{
// create the filter text box
mpFilterTextBox = new QLineEdit;
mpFilterTextBox->installEventFilter(this);
connect(this, SIGNAL(clearFilter(QString)), mpFilterTextBox, SIGNAL(textEdited(QString)));
// filter timer
mpFilterTimer = new QTimer;
mpFilterTimer->setSingleShot(true);
mpScrollToActiveButton = new QToolButton;
QString scrollToActiveButtonText = tr("Scroll to Active");
mpScrollToActiveButton->setText(scrollToActiveButtonText);
mpScrollToActiveButton->setIcon(QIcon(":/Resources/icons/step-into.svg"));
mpScrollToActiveButton->setToolTip(scrollToActiveButtonText);
mpScrollToActiveButton->setAutoRaise(true);
mpScrollToActiveButton->hide();
// expand all button
mpExpandAllButton = new QToolButton;
mpExpandAllButton->setText(Helper::expandAll);
mpExpandAllButton->setIcon(QIcon(":/Resources/icons/bottom.svg"));
mpExpandAllButton->setToolTip(Helper::expandAll);
mpExpandAllButton->setAutoRaise(true);
// collapse all button
mpCollapseAllButton = new QToolButton;
mpCollapseAllButton->setText(Helper::collapseAll);
mpCollapseAllButton->setIcon(QIcon(":/Resources/icons/top.svg"));
mpCollapseAllButton->setToolTip(Helper::collapseAll);
mpCollapseAllButton->setAutoRaise(true);
// show hide button
mpShowHideButton = new QToolButton;
QString showHideButtonText = tr("Show/hide filters");
mpShowHideButton->setText(showHideButtonText);
mpShowHideButton->setIcon(QIcon(":/Resources/icons/down.svg"));
mpShowHideButton->setToolTip(showHideButtonText);
mpShowHideButton->setAutoRaise(true);
mpShowHideButton->setCheckable(true);
connect(mpShowHideButton, SIGNAL(toggled(bool)), SLOT(showHideFilters(bool)));
// filters widget
mpFiltersWidget = new QWidget;
// create the case sensitivity checkbox
mpCaseSensitiveCheckBox = new QCheckBox(tr("Case Sensitive"));
// create the search syntax combobox
mpSyntaxComboBox = new QComboBox;
mpSyntaxComboBox->addItem(tr("Regular Expression"), QRegExp::RegExp);
mpSyntaxComboBox->setItemData(0, tr("A rich Perl-like pattern matching syntax."), Qt::ToolTipRole);
mpSyntaxComboBox->addItem(tr("Wildcard"), QRegExp::Wildcard);
mpSyntaxComboBox->setItemData(1, tr("A simple pattern matching syntax similar to that used by shells (command interpreters) for \"file globbing\"."), Qt::ToolTipRole);
mpSyntaxComboBox->addItem(tr("Fixed String"), QRegExp::FixedString);
mpSyntaxComboBox->setItemData(2, tr("Fixed string matching."), Qt::ToolTipRole);
// create the layout
QGridLayout *pFiltersWidgetLayout = new QGridLayout;
pFiltersWidgetLayout->setContentsMargins(0, 0, 0, 0);
pFiltersWidgetLayout->setAlignment(Qt::AlignTop);
pFiltersWidgetLayout->addWidget(mpCaseSensitiveCheckBox, 0, 0);
pFiltersWidgetLayout->addWidget(mpSyntaxComboBox, 0, 1);
mpFiltersWidget->setLayout(pFiltersWidgetLayout);
mpFiltersWidget->hide();
// create the layout
QGridLayout *pMainLayout = new QGridLayout;
pMainLayout->setContentsMargins(0, 0, 0, 0);
pMainLayout->setSpacing(0);
pMainLayout->setAlignment(Qt::AlignTop);
pMainLayout->addWidget(mpFilterTextBox, 0, 0);
pMainLayout->addWidget(mpScrollToActiveButton, 0, 1);
pMainLayout->addWidget(mpExpandAllButton, 0, 2);
pMainLayout->addWidget(mpCollapseAllButton, 0, 3);
pMainLayout->addWidget(mpShowHideButton, 0, 4);
pMainLayout->addWidget(mpFiltersWidget, 1, 0, 1, 5);
setLayout(pMainLayout);
}
/*!
* \brief TreeSearchFilters::eventFilter
* Handles the ESC key press for filter text box
* \param pObject
* \param pEvent
* \return
*/
bool TreeSearchFilters::eventFilter(QObject *pObject, QEvent *pEvent)
{
/* Ticket #3987
* Clear contents of filter field by clicking ESC key.
*/
QLineEdit *pFilterTextBox = qobject_cast<QLineEdit*>(pObject);
if (pFilterTextBox && pEvent->type() == QEvent::KeyPress) {
QKeyEvent *pKeyEvent = static_cast<QKeyEvent*>(pEvent);
if (pKeyEvent && pKeyEvent->key() == Qt::Key_Escape) {
pFilterTextBox->clear();
/* Ticket #5998
* Emit clearFilter signal which calls textEdited signal of mpFilterTextBox to reset filter.
*/
emit clearFilter("");
return true;
}
}
return QWidget::eventFilter(pObject, pEvent);
}
void TreeSearchFilters::showHideFilters(bool On)
{
if (On) {
mpFiltersWidget->show();
} else {
mpFiltersWidget->hide();
}
}
/*!
* \class FileDataNotifier
* \brief Looks for new data on file. When data is available emits bytesAvailable SIGNAL.
* \brief FileDataNotifier::FileDataNotifier
* \param fileName
*/
FileDataNotifier::FileDataNotifier(const QString fileName)
{
mFile.setFileName(fileName);
mStop = false;
}
/*!
* \brief FileDataNotifier::exit
* Reimplementation of QThread::exit()
* Sets mStop to true.
* \param retcode
*/
void FileDataNotifier::exit(int retcode)
{
mStop = true;
QThread::exit(retcode);
}
/*!
* \brief FileDataNotifier::run
* Reimplentation of QThread::run().
* Looks for when is new data available for reading on file.
* Emits the bytesAvailable SIGNAL.
*/
void FileDataNotifier::run()
{
if (mFile.open(QIODevice::ReadOnly)) {
while (!mStop) {
// if file doesn't exist then break.
if (!mFile.exists()) {
break;
}
// if file has bytes available to read.
if (mFile.bytesAvailable() > 0) {
emit sendData(QString(mFile.readAll()));
}
Sleep::sleep(1);
}
}
}
/*!
* \brief FileDataNotifier::start
* Reimplementation of QThread::start()
* Sets mStop to false.
* \param priority
*/
void FileDataNotifier::start(Priority priority)
{
mStop = false;
QThread::start(priority);
}
Label::Label(QWidget *parent, Qt::WindowFlags flags)
: QLabel(parent, flags), mElideMode(Qt::ElideNone), mText("")
{
setTextInteractionFlags(Qt::TextSelectableByMouse);
}
Label::Label(const QString &text, QWidget *parent, Qt::WindowFlags flags)
: QLabel(text, parent, flags), mElideMode(Qt::ElideNone), mText(text)
{
setTextInteractionFlags(Qt::TextSelectableByMouse);
setToolTip(text);
}
QSize Label::minimumSizeHint() const
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
if (!pixmap(Qt::ReturnByValue).isNull() || mElideMode == Qt::ElideNone) {
#else // QT_VERSION_CHECK
if (pixmap() != NULL || mElideMode == Qt::ElideNone) {
#endif // QT_VERSION_CHECK
return QLabel::minimumSizeHint();
}
const QFontMetrics &fm = fontMetrics();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
QSize size(fm.horizontalAdvance("..."), fm.height()+5);
#else // QT_VERSION_CHECK
QSize size(fm.width("..."), fm.height()+5);
#endif // QT_VERSION_CHECK
return size;
}
QSize Label::sizeHint() const
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
if (!pixmap(Qt::ReturnByValue).isNull() || mElideMode == Qt::ElideNone) {
#else // QT_VERSION_CHECK
if (pixmap() != NULL || mElideMode == Qt::ElideNone) {
#endif // QT_VERSION_CHECK
return QLabel::sizeHint();
}
const QFontMetrics& fm = fontMetrics();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
QSize size(fm.horizontalAdvance(mText), fm.height()+5);
#else // QT_VERSION_CHECK
QSize size(fm.width(mText), fm.height()+5);
#endif // QT_VERSION_CHECK
return size;
}
void Label::setText(const QString &text)
{
mText = text;
setToolTip(text);
QLabel::setText(elidedText());
}
QString Label::elidedText() const
{
if (mElideMode != Qt::ElideNone) {
return fontMetrics().elidedText(mText, mElideMode, size().width());
} else {
return mText;
}
}
void Label::resizeEvent(QResizeEvent *event)
{
QLabel::resizeEvent(event);
QLabel::setText(elidedText());
}
FixedCheckBox::FixedCheckBox(QWidget *parent)
: QCheckBox(parent)
{
setCheckable(false);
mDefaultValue = false;
mTickState = false;
}
void FixedCheckBox::setTickState(bool defaultValue, bool tickState)
{
mDefaultValue = defaultValue;
mTickState = tickState;
}
QString FixedCheckBox::tickStateString()
{
if (mDefaultValue) {
return "";
} else if (mTickState) {
return "true";
} else {
return "false";
}
}
/*!
Reimplementation of QCheckBox::paintEvent.\n
Draws a custom checkbox suitable for fixed modifier.
*/
void FixedCheckBox::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QStylePainter p(this);
QStyleOptionButton opt;
opt.initFrom(this);
if (mDefaultValue) {
p.setBrush(QColor(225, 225, 225));
} else {
p.setBrush(Qt::white);
}
p.drawRect(opt.rect.adjusted(0, 0, -1, -1));
// if is checked then draw a tick
if (mTickState) {
p.setRenderHint(QPainter::Antialiasing);
QPen pen = p.pen();
pen.setWidthF(1.5);
p.setPen(pen);
QVector<QPoint> lines;
lines << QPoint(opt.rect.left() + 3, opt.rect.center().y());
lines << QPoint(opt.rect.center().x() - 1, opt.rect.bottom() - 3);
lines << QPoint(opt.rect.center().x() - 1, opt.rect.bottom() - 3);
lines << QPoint(opt.rect.width() - 3, opt.rect.top() + 3);
p.drawLines(lines);
}
}
PreviewPlainTextEdit::PreviewPlainTextEdit(QWidget *parent)
: QPlainTextEdit(parent)
{
QTextDocument *pTextDocument = document();
pTextDocument->setDocumentMargin(2);
BaseEditorDocumentLayout *pModelicaTextDocumentLayout = new BaseEditorDocumentLayout(pTextDocument);
pTextDocument->setDocumentLayout(pModelicaTextDocumentLayout);
setDocument(pTextDocument);
// parentheses matcher
mParenthesesMatchFormat = Utilities::getParenthesesMatchFormat();
mParenthesesMisMatchFormat = Utilities::getParenthesesMisMatchFormat();
updateHighlights();
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateHighlights()));
}
/*!
* \brief PreviewPlainTextEdit::highlightCurrentLine
* Hightlights the current line.
*/
void PreviewPlainTextEdit::highlightCurrentLine()
{
Utilities::highlightCurrentLine(this);
}
/*!
* \brief PreviewPlainTextEdit::highlightParentheses
* Highlights the matching parentheses.
*/
void PreviewPlainTextEdit::highlightParentheses()
{
Utilities::highlightParentheses(this, mParenthesesMatchFormat, mParenthesesMisMatchFormat);
}
void PreviewPlainTextEdit::updateHighlights()
{
QList<QTextEdit::ExtraSelection> selections;
setExtraSelections(selections);
highlightCurrentLine();
highlightParentheses();
}
ListWidgetItem::ListWidgetItem(QString text, QColor color, QListWidget *pParentListWidget)
: QListWidgetItem(pParentListWidget)
{
setText(text);
mColor = color;
setForeground(mColor);
}
CodeColorsWidget::CodeColorsWidget(QWidget *pParent)
: QWidget(pParent)
{
// colors groupbox
mpColorsGroupBox = new QGroupBox(Helper::Colors);
// Item color label and pick color button
mpItemColorLabel = new Label(tr("Item Color:"));
mpItemColorPickButton = new QPushButton(Helper::pickColor);
mpItemColorPickButton->setAutoDefault(false);
connect(mpItemColorPickButton, SIGNAL(clicked()), SLOT(pickColor()));
// Items list
mpItemsLabel = new Label(tr("Items:"));
mpItemsListWidget = new QListWidget;
mpItemsListWidget->setItemDelegate(new ItemDelegate(mpItemsListWidget));
mpItemsListWidget->setMaximumHeight(90);
// text (black)
new ListWidgetItem("Text", QColor(0, 0, 0), mpItemsListWidget);
// make first item in the list selected
mpItemsListWidget->setCurrentRow(0, QItemSelectionModel::Select);
// preview textbox
mpPreviewLabel = new Label(tr("Preview:"));
mpPreviewPlainTextEdit = new PreviewPlainTextEdit;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
mpPreviewPlainTextEdit->setTabStopDistance((qreal)Helper::tabWidth);
#else // QT_VERSION_CHECK
mpPreviewPlainTextEdit->setTabStopWidth(Helper::tabWidth);
#endif // QT_VERSION_CHECK
// set colors groupbox layout
QGridLayout *pColorsGroupBoxLayout = new QGridLayout;
pColorsGroupBoxLayout->addWidget(mpItemsLabel, 1, 0);
pColorsGroupBoxLayout->addWidget(mpItemColorLabel, 1, 1);
pColorsGroupBoxLayout->addWidget(mpItemsListWidget, 2, 0);
pColorsGroupBoxLayout->addWidget(mpItemColorPickButton, 2, 1, Qt::AlignTop);
pColorsGroupBoxLayout->addWidget(mpPreviewLabel, 3, 0, 1, 2);
pColorsGroupBoxLayout->addWidget(mpPreviewPlainTextEdit, 4, 0, 1, 2);
mpColorsGroupBox->setLayout(pColorsGroupBoxLayout);
// set the layout
QVBoxLayout *pMainLayout = new QVBoxLayout;
pMainLayout->setContentsMargins(0, 0, 0, 0);
pMainLayout->addWidget(mpColorsGroupBox);
setLayout(pMainLayout);
}
/*!
* \brief CodeColorsWidget::pickColor
* Picks a color for one of the Text Settings rules.
* This method is called when mpColorPickButton clicked SIGNAL raised.
*/
void CodeColorsWidget::pickColor()
{
QListWidgetItem *pItem = mpItemsListWidget->currentItem();
ListWidgetItem *pListWidgetItem = dynamic_cast<ListWidgetItem*>(pItem);
if (!pListWidgetItem) {
return;
}
QColor color = QColorDialog::getColor(pListWidgetItem->getColor());
if (!color.isValid()) {
return;
}
pListWidgetItem->setColor(color);
pListWidgetItem->setForeground(color);
emit colorUpdated();
}
/*!
* \brief QDetachableProcess::QDetachableProcess
* Implementation from https://stackoverflow.com/questions/42051405/qprocess-with-cmd-command-does-not-result-in-command-line-window
* \param pParent
*/
QDetachableProcess::QDetachableProcess(QObject *pParent)
: QProcess(pParent)
{
#ifdef Q_OS_WIN
setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments *args) {
args->flags |= CREATE_NEW_CONSOLE;
args->startupInfo->dwFlags &=~ STARTF_USESTDHANDLES;
});
#endif
}
/*!
* \brief QDetachableProcess::start
* Starts a process and detaches from it.
* \param program
* \param arguments
* \param mode
*/
void QDetachableProcess::start(const QString &program, const QStringList &arguments, QIODevice::OpenMode mode)
{
QProcess::start(program, arguments, mode);
waitForStarted();
setProcessState(QProcess::NotRunning);
}
JsonDocument::JsonDocument(QObject *pParent)
: QObject(pParent)
{
result.clear();
errorString = "";
}
bool JsonDocument::parse(const QString &fileName)
{
bool success = true;
QFile file(fileName);
if (file.exists()) {
if (file.open(QIODevice::ReadOnly)) {
QJsonParseError jsonParserError;
QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &jsonParserError);
if (doc.isNull()) {
errorString = QString("Failed to parse file %1 with error %2").arg(file.fileName(), jsonParserError.errorString());
success = false;
} else {
result = doc.toVariant();
}
file.close();
} else {
errorString = GUIMessages::getMessage(GUIMessages::ERROR_OPENING_FILE).arg(file.fileName(), file.errorString());
success = false;
}
}
return success;
}
bool JsonDocument::parse(const QByteArray &jsonData)
{
bool success = true;
QString msg("Failed to parse json %1 with error %2");
QJsonParseError jsonParserError;
QJsonDocument doc = QJsonDocument::fromJson(jsonData, &jsonParserError);
if (doc.isNull()) {
errorString = QString(msg).arg(jsonData, jsonParserError.errorString());
success = false;
} else {
result = doc.toVariant();
}
return success;
}
VariableNode::VariableNode(const QVector<QVariant> &variableNodeData)
{
mVariableNodeData = variableNodeData;
mEditable = false;
mVariability = "";
mChildren.clear();
}
VariableNode::~VariableNode()
{
qDeleteAll(mChildren);
mChildren.clear();
}
VariableNode* VariableNode::findVariableNode(const QString &name, VariableNode *pParentVariableNode)
{
VariableNode *pVariableNode = pParentVariableNode->mChildren.value(name, 0);
if (pVariableNode) {
return pVariableNode;
} else {
QHash<QString, VariableNode*>::const_iterator iterator = pParentVariableNode->mChildren.constBegin();
while (iterator != pParentVariableNode->mChildren.constEnd()) {
if (VariableNode *node = VariableNode::findVariableNode(name, iterator.value())) {
return node;
}
++iterator;
}
}
return 0;
}
QString Utilities::escapeForHtmlNonSecure(const QString &str)
{
return QString(str)
.replace("& ", "&") // should be the first replacement
.replace("< ", "<");
}
/*!
* \brief Utilities::tempDirectory
* Returns the application temporary directory.
* \return
*/
QString& Utilities::tempDirectory()
{
static int init = 0;
static QString tmpPath;
if (!init) {
init = 1;
#ifdef WIN32
tmpPath = QDir::tempPath() + "/OpenModelica/OMEdit/";
#else // UNIX environment
char *user = getenv("USER");
tmpPath = QDir::tempPath() + "/OpenModelica_" + QString(user ? user : "nobody") + "/OMEdit/";
#endif
tmpPath.remove("\"");
if (!QDir().exists(tmpPath))
QDir().mkpath(tmpPath);
}
return tmpPath;
}
/*!
* \brief Utilities::getApplicationSettings
* Returns the application settings object.
* \return
*/
QSettings* Utilities::getApplicationSettings()
{
static int init = 0;
static QSettings *pSettings;
if (!init) {
init = 1;
pSettings = new QSettings(QSettings::IniFormat, QSettings::UserScope, Helper::organization, Helper::application);
pSettings->setIniCodec(Helper::utf8.toUtf8().constData());
}
return pSettings;
}
/*!
* \brief Utilities::parseCompositeModelText
* Parses the CompositeModel text against the schema.
* \param pMessageHandler
* \param contents
*/
void Utilities::parseCompositeModelText(MessageHandler *pMessageHandler, QString contents)
{
QFile schemaFile(QString(":/Resources/XMLSchema/tlmModelDescription.xsd"));
schemaFile.open(QIODevice::ReadOnly);
const QString schemaText(QString::fromUtf8(schemaFile.readAll()));
schemaFile.close();
const QByteArray schemaData = schemaText.toUtf8();
QXmlSchema schema;
schema.setMessageHandler(pMessageHandler);
schema.load(schemaData);
if (!schema.isValid()) {
pMessageHandler->setFailed(true);
} else {
QXmlSchemaValidator validator(schema);
if (!validator.validate(contents.toUtf8())) {
pMessageHandler->setFailed(true);
}
}
}
/*!
* \brief Utilities::convertUnit
* Converts the value using the unit offset and scale factor.
* \param value
* \param offset
* \param scaleFactor
* \return
*/
qreal Utilities::convertUnit(qreal value, qreal offset, qreal scaleFactor)
{
return (value - offset) / scaleFactor;
}
/*!
* \brief Utilities::isValueLiteralConstant
* \param value
* \return
*/
bool Utilities::isValueLiteralConstant(QString value)
{
bool ok = true;
value.toDouble(&ok);
if (ok) return true;
QStringList valuesArray = StringHandler::removeFirstLastCurlBrackets(value).split(",");
foreach (QString valueElement, valuesArray) {
valueElement.toDouble(&ok);
}
return ok;
}
/*!
* \brief Utilities::arrayExpressionUnitConversion
* If the expression is like an array of constants see ticket:4840
* \param pOMCProxy
* \param modifierValue
* \param fromUnit
* \param toUnit
* \return
*/
QString Utilities::arrayExpressionUnitConversion(OMCProxy *pOMCProxy, QString modifierValue, QString fromUnit, QString toUnit)
{
QStringList modifierValuesArray = StringHandler::removeFirstLastCurlBrackets(modifierValue).split(",");
QStringList modifierConvertedValuesArray;
OMCInterface::convertUnits_res convertUnit;
int i = 0;
bool ok = true;
foreach (QString modifierValueArrayElement, modifierValuesArray) {
qreal modifierRealValueArrayElement = modifierValueArrayElement.toDouble(&ok);
if (ok) {
if (i == 0) {
convertUnit = pOMCProxy->convertUnits(fromUnit, toUnit);
}
if (convertUnit.unitsCompatible) {
modifierRealValueArrayElement = Utilities::convertUnit(modifierRealValueArrayElement, convertUnit.offset, convertUnit.scaleFactor);
modifierConvertedValuesArray.append(StringHandler::number(modifierRealValueArrayElement));
}
}
}
if (ok) {
modifierValue = QString("{%1}").arg(modifierConvertedValuesArray.join(","));
}
return modifierValue;
}
Label* Utilities::getHeadingLabel(QString heading)
{
Label *pHeadingLabel = new Label(heading);
pHeadingLabel->setFont(QFont(Helper::systemFontInfo.family(), Helper::headingFontSize));
return pHeadingLabel;
}
QFrame* Utilities::getHeadingLine()
{
QFrame *pHeadingLine = new QFrame();
pHeadingLine->setFrameShape(QFrame::HLine);
pHeadingLine->setFrameShadow(QFrame::Sunken);
return pHeadingLine;
}
/*!
* \brief Utilities::detectBOM
* Detects if the file has byte order mark (BOM) or not.
* \param fileName
* \return
*/
bool Utilities::detectBOM(QString fileName)
{
QFile file(fileName);
if (file.exists()) {
if (file.open(QIODevice::ReadOnly)) {
QByteArray data = file.readAll();
const int bytesRead = data.size();
const unsigned char *buf = reinterpret_cast<const unsigned char *>(data.constData());
// code taken from qtextstream
if (bytesRead >= 3 && ((buf[0] == 0xef && buf[1] == 0xbb) && buf[2] == 0xbf)) {
return true;
} else {
return false;
}
file.close();
} else {
qDebug() << QString("Failed to detect byte order mark. Unable to open file %1.").arg(fileName);
}
}
return false;
}
QTextCharFormat Utilities::getParenthesesMatchFormat()
{
QTextCharFormat parenthesesMatchFormat;
parenthesesMatchFormat.setForeground(Qt::red);
parenthesesMatchFormat.setBackground(QColor(160, 238, 160));
return parenthesesMatchFormat;
}
QTextCharFormat Utilities::getParenthesesMisMatchFormat()
{
QTextCharFormat parenthesesMisMatchFormat;
parenthesesMisMatchFormat.setBackground(Qt::red);
return parenthesesMisMatchFormat;
}
void Utilities::highlightCurrentLine(QPlainTextEdit *pPlainTextEdit)
{
QList<QTextEdit::ExtraSelection> selections = pPlainTextEdit->extraSelections();
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor(232, 242, 254);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = pPlainTextEdit->textCursor();
selection.cursor.clearSelection();
selections.append(selection);
pPlainTextEdit->setExtraSelections(selections);
}
void Utilities::highlightParentheses(QPlainTextEdit *pPlainTextEdit, QTextCharFormat parenthesesMatchFormat,
QTextCharFormat parenthesesMisMatchFormat)
{
if (pPlainTextEdit->isReadOnly()) {
return;
}
QTextCursor backwardMatch = pPlainTextEdit->textCursor();
QTextCursor forwardMatch = pPlainTextEdit->textCursor();
if (pPlainTextEdit->overwriteMode()) {
backwardMatch.movePosition(QTextCursor::Right);
}
const TextBlockUserData::MatchType backwardMatchType = TextBlockUserData::matchCursorBackward(&backwardMatch);
const TextBlockUserData::MatchType forwardMatchType = TextBlockUserData::matchCursorForward(&forwardMatch);
QList<QTextEdit::ExtraSelection> selections = pPlainTextEdit->extraSelections();
if (backwardMatchType == TextBlockUserData::NoMatch && forwardMatchType == TextBlockUserData::NoMatch) {
pPlainTextEdit->setExtraSelections(selections);
return;
}
if (backwardMatch.hasSelection()) {
QTextEdit::ExtraSelection selection;
if (backwardMatchType == TextBlockUserData::Mismatch) {
selection.cursor = backwardMatch;
selection.format = parenthesesMisMatchFormat;
selections.append(selection);
} else {
selection.cursor = backwardMatch;
selection.format = parenthesesMatchFormat;
selection.cursor.setPosition(backwardMatch.selectionStart());
selection.cursor.setPosition(selection.cursor.position() + 1, QTextCursor::KeepAnchor);
selections.append(selection);
selection.cursor.setPosition(backwardMatch.selectionEnd());
selection.cursor.setPosition(selection.cursor.position() - 1, QTextCursor::KeepAnchor);
selections.append(selection);
}
}
if (forwardMatch.hasSelection()) {
QTextEdit::ExtraSelection selection;
if (forwardMatchType == TextBlockUserData::Mismatch) {
selection.cursor = forwardMatch;
selection.format = parenthesesMisMatchFormat;
selections.append(selection);
} else {
selection.cursor = forwardMatch;
selection.format = parenthesesMatchFormat;
selection.cursor.setPosition(forwardMatch.selectionStart());
selection.cursor.setPosition(selection.cursor.position() + 1, QTextCursor::KeepAnchor);
selections.append(selection);
selection.cursor.setPosition(forwardMatch.selectionEnd());
selection.cursor.setPosition(selection.cursor.position() - 1, QTextCursor::KeepAnchor);
selections.append(selection);
}
}
pPlainTextEdit->setExtraSelections(selections);
}
/*!
* \brief Utilities::getProcessId
* Returns the process id.
* \param pProcess
* \return
*/
qint64 Utilities::getProcessId(QProcess *pProcess)
{
qint64 processId = 0;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0))
processId = pProcess->processId();
#else /* Qt4 */
#ifdef WIN32
_PROCESS_INFORMATION *procInfo = pProcess->pid();
if (procInfo) {
processId = procInfo->dwProcessId;
}
#else
processId = pProcess->pid();
#endif /* WIN32 */
#endif /* QT_VERSION */
return processId;
}
/*!
* \brief Utilities::formatExitCode
* Returns the given process exit code as a string in an OS appropriate format.
* \param code
* \return
*/
QString Utilities::formatExitCode(int code)
{
#ifdef WIN32
// Use 0xXXXXXXXX format on Windows.
return QStringLiteral("0x%1").arg(code, 8, 16, QChar('0'));
#else
// Use normal decimal on other OS.
return QString::number(code);
#endif
}
#ifdef WIN32
/* adrpo: found this on http://stackoverflow.com/questions/1173342/terminate-a-process-tree-c-for-windows
* thanks go to: mjmarsh & Firas Assaad
* adapted to recurse on children ids
*/
void Utilities::killProcessTreeWindows(DWORD myprocID)
{
PROCESSENTRY32 pe;
HANDLE hSnap = NULL, hProc = NULL;
memset(&pe, 0, sizeof(PROCESSENTRY32));
pe.dwSize = sizeof(PROCESSENTRY32);
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (Process32First(hSnap, &pe))
{
BOOL bContinue = TRUE;
// kill child processes
while (bContinue)
{
// only kill child processes
if (pe.th32ParentProcessID == myprocID)
{
HANDLE hChildProc = NULL;
// recurse
killProcessTreeWindows(pe.th32ProcessID);
hChildProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
if (hChildProc)
{
TerminateProcess(hChildProc, 1);
CloseHandle(hChildProc);
}
}
bContinue = Process32Next(hSnap, &pe);
}
// kill the main process
hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, myprocID);
if (hProc)
{
TerminateProcess(hProc, 1);
CloseHandle(hProc);
}
}
}
#endif
/*!
* \brief Utilities::isCFile
* Returns true if extension is of C file.
* \param extension
* \return
*/
bool Utilities::isCFile(QString extension)
{
if (extension.compare("c") == 0 ||
extension.compare("cpp") == 0 ||
extension.compare("cc") == 0 ||
extension.compare("h") == 0 ||
extension.compare("hpp") == 0) {
return true;
} else {
return false;
}
}
/*!
* \brief Utilities::isModelicaFile
* Returns true if extension is of Modelica file.
* \param extension
* \return
*/
bool Utilities::isModelicaFile(QString extension)
{
if (extension.compare("mo") == 0) {
return true;
} else {
return false;
}
}
/*!
* \brief Utilities::getRotationMatrix
* Computes the corresponding rotation matrix for specified rotation vector
* \param rotation Rotation vector with Euler angles
* \return
*/
QGenericMatrix<3,3, double> Utilities::getRotationMatrix(QGenericMatrix<3,1,double> rotation)
{
double c1 = cos(rotation(0,0));
double s1 = sin(rotation(0,0));
double c2 = cos(rotation(0,1));
double s2 = sin(rotation(0,1));
double c3 = cos(rotation(0,2));
double s3 = sin(rotation(0,2));
double R_data[9];