/
OMCProxy.cpp
3001 lines (2811 loc) · 96.2 KB
/
OMCProxy.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-2014, 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>
*/
extern "C" {
#include "meta/meta_modelica.h"
#include "omc_config.h"
#include "gc.h"
void (*omc_assert)(threadData_t*,FILE_INFO info,const char *msg,...) __attribute__((noreturn)) = omc_assert_function;
void (*omc_assert_warning)(FILE_INFO info,const char *msg,...) = omc_assert_warning_function;
void (*omc_terminate)(FILE_INFO info,const char *msg,...) = omc_terminate_function;
void (*omc_throw)(threadData_t*) __attribute__ ((noreturn)) = omc_throw_function;
int omc_Main_handleCommand(void *threadData, void *imsg, void **omsg);
void* omc_Main_init(void *threadData, void *args);
void omc_System_initGarbageCollector(void *threadData);
#ifdef WIN32
void omc_Main_setWindowsPaths(threadData_t *threadData, void* _inOMHome);
#endif
}
#include <stdlib.h>
#include <iostream>
#include "OMCProxy.h"
#include "MainWindow.h"
#include "Options/OptionsDialog.h"
#include "Modeling/MessagesWidget.h"
#include "simulation_options.h"
#include "omc_error.h"
#include <QMessageBox>
/*!
* \class OMCProxy
* \brief Interface to send commands to OpenModelica Compiler.
*/
/*!
* \brief OMCProxy::OMCProxy
* \param threadData
* \param pParent
*/
OMCProxy::OMCProxy(threadData_t* threadData, QWidget *pParent)
: QObject(pParent), mHasInitialized(false), mResult(""), mTotalOMCCallsTime(0.0)
{
mCurrentCommandIndex = -1;
// OMC Commands Logger Widget
mpOMCLoggerWidget = new QWidget;
mpOMCLoggerWidget->resize(640, 480);
mpOMCLoggerWidget->setWindowIcon(QIcon(":/Resources/icons/console.svg"));
mpOMCLoggerWidget->setWindowTitle(QString(Helper::applicationName).append(" - ").append(Helper::OpenModelicaCompilerCLI));
// OMC Logger textbox
mpOMCLoggerTextBox = new QPlainTextEdit;
mOMCLoggerTextCursor = QTextCursor(mpOMCLoggerTextBox->document());
mpOMCLoggerTextBox->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
mpOMCLoggerTextBox->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
mpOMCLoggerTextBox->setReadOnly(true);
mpOMCLoggerTextBox->setLineWrapMode(QPlainTextEdit::WidgetWidth);
mpExpressionTextBox = new CustomExpressionBox(this);
connect(mpExpressionTextBox, SIGNAL(returnPressed()), SLOT(sendCustomExpression()));
mpOMCLoggerSendButton = new QPushButton(tr("Send"));
connect(mpOMCLoggerSendButton, SIGNAL(clicked()), SLOT(sendCustomExpression()));
// Set the OMC Logger widget Layout
QHBoxLayout *pHorizontalLayout = new QHBoxLayout;
pHorizontalLayout->setContentsMargins(0, 0, 0, 0);
pHorizontalLayout->addWidget(mpExpressionTextBox);
pHorizontalLayout->addWidget(mpOMCLoggerSendButton);
QVBoxLayout *pVerticalalLayout = new QVBoxLayout;
pVerticalalLayout->setContentsMargins(1, 1, 1, 1);
pVerticalalLayout->addWidget(mpOMCLoggerTextBox);
pVerticalalLayout->addLayout(pHorizontalLayout);
mpOMCLoggerWidget->setLayout(pVerticalalLayout);
if (MainWindow::instance()->isDebug()) {
// OMC Diff widget
mpOMCDiffWidget = new QWidget;
mpOMCDiffWidget->resize(640, 480);
mpOMCDiffWidget->setWindowIcon(QIcon(":/Resources/icons/console.svg"));
mpOMCDiffWidget->setWindowTitle(QString(Helper::applicationName).append(" - ").append(tr("OMC Diff")));
mpOMCDiffBeforeLabel = new Label(tr("Before"));
mpOMCDiffBeforeTextBox = new QPlainTextEdit;
mpOMCDiffAfterLabel = new Label(tr("After"));
mpOMCDiffAfterTextBox = new QPlainTextEdit;
mpOMCDiffMergedLabel = new Label(tr("Merged"));
mpOMCDiffMergedTextBox = new QPlainTextEdit;
// Set the OMC Diff widget Layout
QGridLayout *pOMCDiffWidgetLayout = new QGridLayout;
pOMCDiffWidgetLayout->addWidget(mpOMCDiffBeforeLabel, 0, 0);
pOMCDiffWidgetLayout->addWidget(mpOMCDiffAfterLabel, 0, 1);
pOMCDiffWidgetLayout->addWidget(mpOMCDiffBeforeTextBox, 1, 0);
pOMCDiffWidgetLayout->addWidget(mpOMCDiffAfterTextBox, 1, 1);
pOMCDiffWidgetLayout->addWidget(mpOMCDiffMergedLabel, 2, 0, 1, 2);
pOMCDiffWidgetLayout->addWidget(mpOMCDiffMergedTextBox, 3, 0, 1, 2);
mpOMCDiffWidget->setLayout(pOMCDiffWidgetLayout);
}
mUnitConversionList.clear();
mDerivedUnitsMap.clear();
setLoggingEnabled(true);
//start the server
if(!initializeOMC(threadData)) { // if we are unable to start OMC. Exit the application.
MainWindow::instance()->setExitApplicationStatus(true);
return;
}
}
OMCProxy::~OMCProxy()
{
delete mpOMCLoggerWidget;
if (MainWindow::instance()->isDebug()) {
delete mpOMCDiffWidget;
}
}
/*!
Puts the previous send OMC command in the send command text box.\n
Invoked by the up arrow key.
*/
void OMCProxy::getPreviousCommand()
{
if (mCommandsList.isEmpty()) {
return;
}
mCurrentCommandIndex -= 1;
if (mCurrentCommandIndex > -1) {
mpExpressionTextBox->setText(mCommandsList.at(mCurrentCommandIndex));
} else {
mCurrentCommandIndex += 1;
}
}
/*!
Puts the most recently send OMC command in the send command text box.
Invoked by the down arrow key.
*/
void OMCProxy::getNextCommand()
{
if (mCommandsList.isEmpty()) {
return;
}
mCurrentCommandIndex += 1;
if (mCurrentCommandIndex < mCommandsList.count()) {
mpExpressionTextBox->setText(mCommandsList.at(mCurrentCommandIndex));
} else {
mCurrentCommandIndex -= 1;
}
}
/*!
Initializes the OpenModelica Compiler binary.\n
Creates the omeditcommunication.log & omeditcommands.mos files.
\return status - returns true if initialization is successful otherwise false.
*/
bool OMCProxy::initializeOMC(threadData_t *threadData)
{
/* create the tmp path */
QString& tmpPath = Utilities::tempDirectory();
/* create a file to write OMEdit communication log */
QString communicationLogFilePath = QString("%1omeditcommunication.log").arg(tmpPath);
mpCommunicationLogFile = fopen(communicationLogFilePath.toStdString().c_str(), "w");
/* create a file to write OMEdit commands */
QString commandsLogFilePath = QString("%1omeditcommands.mos").arg(tmpPath);
mpCommandsLogFile = fopen(commandsLogFilePath.toStdString().c_str(), "w");
// read the locale
QSettings *pSettings = Utilities::getApplicationSettings();
QLocale settingsLocale = QLocale(pSettings->value("language").toString());
settingsLocale = settingsLocale.name() == "C" ? pSettings->value("language").toLocale() : settingsLocale;
void *args = mmc_mk_nil();
QString locale = "+locale=" + settingsLocale.name();
args = mmc_mk_cons(mmc_mk_scon(locale.toStdString().c_str()), args);
// initialize garbage collector
omc_System_initGarbageCollector(NULL);
MMC_TRY_TOP_INTERNAL()
omc_Main_init(threadData, args);
threadData->plotClassPointer = MainWindow::instance();
threadData->plotCB = MainWindow::PlotCallbackFunction;
MMC_CATCH_TOP(return false;)
mpOMCInterface = new OMCInterface(threadData);
connect(mpOMCInterface, SIGNAL(logCommand(QString,QTime*)), this, SLOT(logCommand(QString,QTime*)));
connect(mpOMCInterface, SIGNAL(logResponse(QString,QTime*)), this, SLOT(logResponse(QString,QTime*)));
connect(mpOMCInterface, SIGNAL(throwException(QString)), SLOT(showException(QString)));
mHasInitialized = true;
// get OpenModelica version
Helper::OpenModelicaVersion = getVersion();
#ifdef WIN32
sendCommand("\"" + QString(GIT_SHA) + "\"");
#endif
// set OpenModelicaHome variable
Helper::OpenModelicaHome = mpOMCInterface->getInstallationDirectoryPath();
#ifdef WIN32
MMC_TRY_TOP_INTERNAL()
omc_Main_setWindowsPaths(threadData, mmc_mk_scon(Helper::OpenModelicaHome.toStdString().c_str()));
MMC_CATCH_TOP()
#endif
/* set the tmp directory as the working directory */
changeDirectory(tmpPath);
// set the OpenModelicaLibrary variable.
Helper::OpenModelicaLibrary = getModelicaPath();
return true;
}
/*!
* \brief OMCProxy::quitOMC
* Quits the OpenModelica Compiler.\n
* Closes the log files.
* \see startServer
*/
void OMCProxy::quitOMC()
{
sendCommand("quit()");
if (mpCommunicationLogFile) {
fclose(mpCommunicationLogFile);
}
if (mpCommandsLogFile) {
fclose(mpCommandsLogFile);
}
}
/*!
* \brief OMCProxy::sendCommand
* Sends the user commands to OMC.
* \param expression - is used to send command as a string.
*/
void OMCProxy::sendCommand(const QString expression)
{
// write command to the commands log.
QTime commandTime;
commandTime.start();
logCommand(expression, &commandTime);
// TODO: Call this in a thread that loops over received messages? Avoid MMC_TRY_TOP all the time, etc
void *reply_str = NULL;
threadData_t *threadData = mpOMCInterface->threadData;
MMC_TRY_TOP_INTERNAL()
MMC_TRY_STACK()
if (!omc_Main_handleCommand(threadData, mmc_mk_scon(expression.toStdString().c_str()), &reply_str)) {
if (expression == "quit()") {
return;
}
exitApplication();
}
mResult = MMC_STRINGDATA(reply_str);
logResponse(mResult.trimmed(), &commandTime);
MMC_ELSE()
mResult = "";
fprintf(stderr, "Stack overflow detected and was not caught.\nSend us a bug report at https://trac.openmodelica.org/OpenModelica/newticket\n Include the following trace:\n");
printStacktraceMessages();
fflush(NULL);
MMC_CATCH_STACK()
MMC_CATCH_TOP(mResult = "");
}
/*!
Sets the command result.
\param value the command result.
*/
void OMCProxy::setResult(QString value)
{
mResult = value;
}
/*!
Returns the result obtained from OMC.
\return the command result.
*/
QString OMCProxy::getResult()
{
return mResult.trimmed();
}
/*!
* \brief OMCProxy::logCommand
* Writes OMC command in OMC Logger window.
* Writes the command to the omeditcommunication.log file.
* Writes the command to the omeditcommands.mos file.
* \param command - the command to write
* \param commandTime - the command start time
*/
void OMCProxy::logCommand(QString command, QTime *commandTime)
{
if (isLoggingEnabled()) {
// insert the command to the logger window.
QFont font(Helper::monospacedFontInfo.family(), Helper::monospacedFontInfo.pointSize() - 2, QFont::Bold, false);
QTextCharFormat format;
format.setFont(font);
Utilities::insertText(mpOMCLoggerTextBox, command + "\n", format);
// add the expression to commands list
mCommandsList.append(command);
// set the current command index.
mCurrentCommandIndex = mCommandsList.count();
mpExpressionTextBox->setText("");
// write the log to communication log file
if (mpCommunicationLogFile) {
fputs(QString("%1 %2\n").arg(command, commandTime->currentTime().toString("hh:mm:ss:zzz")).toStdString().c_str(), mpCommunicationLogFile);
}
// write commands mos file
if (mpCommandsLogFile) {
if (command.compare("quit()") == 0) {
fputs(QString("%1;\n").arg(command).toStdString().c_str(), mpCommandsLogFile);
} else {
fputs(QString("%1; getErrorString();\n").arg(command).toStdString().c_str(), mpCommandsLogFile);
}
}
}
}
/*!
* \brief OMCProxy::logResponse
* Writes OMC response in OMC Logger window.
* Writes the response to the omeditcommunication.log file.
* \param response - the response to write
* \param responseTime - the response end time
*/
void OMCProxy::logResponse(QString response, QTime *responseTime)
{
if (isLoggingEnabled()) {
// insert the response to the logger window.
QFont font(Helper::monospacedFontInfo.family(), Helper::monospacedFontInfo.pointSize() - 2, QFont::Normal, false);
QTextCharFormat format;
format.setFont(font);
Utilities::insertText(mpOMCLoggerTextBox, response + "\n\n", format);
// write the log to communication log file
if (mpCommunicationLogFile) {
fputs(QString("%1 %2\n").arg(response).arg(responseTime->currentTime().toString("hh:mm:ss:zzz")).toStdString().c_str(), mpCommunicationLogFile);
mTotalOMCCallsTime += (double)responseTime->elapsed() / 1000;
fputs(QString("%1 secs (%2 secs)\n\n").arg(QString::number((double)responseTime->elapsed() / 1000)).arg(QString::number(mTotalOMCCallsTime)).toStdString().c_str(), mpCommunicationLogFile);
}
}
}
/*!
* \brief Writes the exception to MessagesWidget.
* \param exception
*/
void OMCProxy::showException(QString exception)
{
MessageItem messageItem(MessageItem::Modelica, "", false, 0, 0, 0, 0, exception, Helper::scriptingKind, Helper::errorLevel);
MessagesWidget::instance()->addGUIMessage(messageItem);
printMessagesStringInternal();
}
/*!
Opens the OMC Logger widget.
*/
void OMCProxy::openOMCLoggerWidget()
{
mpExpressionTextBox->setFocus(Qt::ActiveWindowFocusReason);
mpOMCLoggerWidget->show();
mpOMCLoggerWidget->raise();
mpOMCLoggerWidget->activateWindow();
mpOMCLoggerWidget->setWindowState(mpOMCLoggerWidget->windowState() & (~Qt::WindowMinimized | Qt::WindowActive));
}
/*!
Sends the command written in the OMC Logger textbox.
*/
void OMCProxy::sendCustomExpression()
{
if (mpExpressionTextBox->text().isEmpty())
return;
sendCommand(mpExpressionTextBox->text());
mpExpressionTextBox->setText("");
}
/*!
* \brief OMCProxy::openOMCDiffWidget
* Opens the OMC Diff widget.
*/
void OMCProxy::openOMCDiffWidget()
{
if (MainWindow::instance()->isDebug()) {
mpOMCDiffBeforeTextBox->setFocus(Qt::ActiveWindowFocusReason);
mpOMCDiffWidget->show();
mpOMCDiffWidget->raise();
mpOMCDiffWidget->activateWindow();
mpOMCDiffWidget->setWindowState(mpOMCDiffWidget->windowState() & (~Qt::WindowMinimized | Qt::WindowActive));
}
}
/*!
Removes the CORBA IOR file. We only call this method when we are unable to connect to OMC.\n
In normal case OMCProxy::stopServer will delete that file.
*/
void OMCProxy::removeObjectRefFile()
{
QFile::remove(mObjectRefFile);
}
/*!
Removes the CORBA IOR file.\n
Shows an error message that OMEdit connection with OMC is lost and exit the application.
\see OMCProxy::removeObjectRefFile()
*/
void OMCProxy::exitApplication()
{
removeObjectRefFile();
QMessageBox::critical(MainWindow::instance(), QString(Helper::applicationName).append(" - ").append(Helper::error),
QString(tr("Connection with the OpenModelica Compiler has been lost."))
.append("\n\n").append(Helper::applicationName).append(" will close."), Helper::ok);
exit(EXIT_FAILURE);
}
/*!
* \brief OMCProxy::getErrorString
* Returns the OMC error string.\n
* \param warningsAsErrors
* \return the error string.
* \deprecated Use printMessagesStringInternal(). Now used where we want to consume the error message without showing it to user.
*/
QString OMCProxy::getErrorString(bool warningsAsErrors)
{
return mpOMCInterface->getErrorString(warningsAsErrors);
}
/*!
* \brief OMCProxy::printMessagesStringInternal
* Gets the errors by using the getMessagesStringInternal API.
* Reads all the errors and add them to the Messages Browser.
* Reads the omeditoutput.txt and omediterror.txt files and add the data to Messages Browser if there is any.
* \see MessagesWidget::addGUIMessage
* \return true if there are any errors otherwise false.
*/
bool OMCProxy::printMessagesStringInternal()
{
// read stdout file
QFile outputFile(Utilities::tempDirectory() + "/omeditoutput.txt");
if (outputFile.open(QIODevice::ReadOnly)) {
static qint64 outputFilePosition = 0;
if (outputFile.seek(outputFilePosition)) {
QString outputFileData = outputFile.readAll();
if (!outputFileData.isEmpty()) {
outputFilePosition = outputFile.pos();
MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, "", false, 0, 0, 0, 0, outputFileData,
Helper::scriptingKind, Helper::notificationLevel));
}
}
outputFile.close();
}
// read stderr file
QFile errorFile(Utilities::tempDirectory() + "/omediterror.txt");
if (errorFile.open(QIODevice::ReadOnly)) {
static qint64 errorFilePosition = 0;
if (errorFile.seek(errorFilePosition)) {
QString errorFileData = errorFile.readAll();
if (!errorFileData.isEmpty()) {
errorFilePosition = errorFile.pos();
MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, "", false, 0, 0, 0, 0, errorFileData,
Helper::scriptingKind, Helper::errorLevel));
}
}
errorFile.close();
}
// read errors
int errorsSize = getMessagesStringInternal();
bool returnValue = errorsSize > 0 ? true : false;
/* Loop in reverse order since getMessagesStringInternal returns error messages in reverse order. */
for (int i = errorsSize; i > 0 ; i--) {
setCurrentError(i);
MessageItem messageItem(MessageItem::Modelica, getErrorFileName(), getErrorReadOnly(), getErrorLineStart(), getErrorColumnStart(), getErrorLineEnd(),
getErrorColumnEnd(), getErrorMessage(), getErrorKind(), getErrorLevel());
MessagesWidget::instance()->addGUIMessage(messageItem);
}
return returnValue;
}
/*!
Retrieves the list of errors from OMC
\return size of errors
*/
int OMCProxy::getMessagesStringInternal()
{
sendCommand("errors:=getMessagesStringInternal()");
sendCommand("size(errors,1)");
return getResult().toInt();
}
/*!
Sets the current error.
\param int the error index
*/
void OMCProxy::setCurrentError(int errorIndex)
{
sendCommand("currentError:=errors[" + QString::number(errorIndex) + "]");
}
/*!
Gets the error file name from current error.
\return the error file name
*/
QString OMCProxy::getErrorFileName()
{
sendCommand("currentError.info.filename");
QString file = StringHandler::unparse(getResult());
if (file.compare("<interactive>") == 0)
return "";
else
return file;
}
/*!
Gets the error read only state from current error.
\return the error read only state
*/
bool OMCProxy::getErrorReadOnly()
{
sendCommand("currentError.info.readonly");
return StringHandler::unparseBool(StringHandler::unparse(getResult()));
}
/*!
Gets the error line start index from current error.
\return the error line start index
*/
int OMCProxy::getErrorLineStart()
{
sendCommand("currentError.info.lineStart");
return getResult().toInt();
}
/*!
Gets the error column start index from current error.
\return the error column start index
*/
int OMCProxy::getErrorColumnStart()
{
sendCommand("currentError.info.columnStart");
return getResult().toInt();
}
/*!
Gets the error line end index from current error.
\return the error line end index
*/
int OMCProxy::getErrorLineEnd()
{
sendCommand("currentError.info.lineEnd");
return getResult().toInt();
}
/*!
Gets the error column end index from current error.
\return the error column end index
*/
int OMCProxy::getErrorColumnEnd()
{
sendCommand("currentError.info.columnEnd");
return getResult().toInt();
}
/*!
Gets the error message from current error.
\return the error message
*/
QString OMCProxy::getErrorMessage()
{
sendCommand("currentError.message");
return StringHandler::unparse(getResult());
}
/*!
Gets the error kind from current error.
\return the error kind
*/
QString OMCProxy::getErrorKind()
{
sendCommand("currentError.kind");
return getResult();
}
/*!
Gets the error level from current error.
\return the error level
*/
QString OMCProxy::getErrorLevel()
{
sendCommand("currentError.level");
return getResult();
}
/*!
Gets the OMC version. On Linux it also return the revision number as well.
\return the version
*/
QString OMCProxy::getVersion(QString className)
{
return mpOMCInterface->getVersion(className);
}
/*!
* \brief OMCProxy::loadSystemLibraries
* Loads the Modelica System Libraries.\n
* Reads the omedit.ini file to get the libraries to load.
*/
void OMCProxy::loadSystemLibraries()
{
QSettings *pSettings = Utilities::getApplicationSettings();
bool forceModelicaLoad = true;
if (pSettings->contains("forceModelicaLoad")) {
forceModelicaLoad = pSettings->value("forceModelicaLoad").toBool();
}
pSettings->beginGroup("libraries");
QStringList libraries = pSettings->childKeys();
pSettings->endGroup();
/*
Only force loading of Modelica & ModelicaReference if user is using OMEdit for the first time.
Later user must use the libraries options dialog.
*/
if (forceModelicaLoad) {
if (!pSettings->contains("libraries/Modelica")) {
pSettings->setValue("libraries/Modelica","default");
libraries.prepend("Modelica");
}
if (!pSettings->contains("libraries/ModelicaReference")) {
pSettings->setValue("libraries/ModelicaReference","default");
libraries.prepend("ModelicaReference");
}
}
foreach (QString lib, libraries) {
QString version = pSettings->value("libraries/" + lib).toString();
loadModel(lib, version);
}
OptionsDialog::instance()->readLibrariesSettings();
}
/*!
* \brief OMCProxy::loadUserLibraries
* Loads the Modelica User Libraries.
* Reads the omedit.ini file to get the libraries to load.
*/
void OMCProxy::loadUserLibraries()
{
QSettings *pSettings = Utilities::getApplicationSettings();
pSettings->beginGroup("userlibraries");
QStringList libraries = pSettings->childKeys();
pSettings->endGroup();
foreach (QString lib, libraries) {
QString encoding = pSettings->value("userlibraries/" + lib).toString();
QString fileName = QUrl::fromPercentEncoding(QByteArray(lib.toStdString().c_str()));
QStringList classesList = parseFile(fileName, encoding);
if (!classesList.isEmpty()) {
/*
Only allow loading of files that has just one nonstructured entity.
From Modelica specs section 13.2.2.2,
"A nonstructured entity [e.g. the file A.mo] shall contain only a stored-definition that defines a class [A] with a name
matching the name of the nonstructured entity."
*/
if (classesList.size() > 1) {
QMessageBox *pMessageBox = new QMessageBox(MainWindow::instance());
pMessageBox->setWindowTitle(QString(Helper::applicationName).append(" - ").append(Helper::error));
pMessageBox->setIcon(QMessageBox::Critical);
pMessageBox->setAttribute(Qt::WA_DeleteOnClose);
pMessageBox->setText(QString(GUIMessages::getMessage(GUIMessages::UNABLE_TO_LOAD_FILE).arg(fileName)));
pMessageBox->setInformativeText(QString(GUIMessages::getMessage(GUIMessages::MULTIPLE_TOP_LEVEL_CLASSES)).arg(fileName)
.arg(classesList.join(",")));
pMessageBox->setStandardButtons(QMessageBox::Ok);
pMessageBox->exec();
return;
}
QStringList existingmodelsList;
bool existModel = false;
// check if the model already exists
foreach(QString model, classesList) {
if (existClass(model)) {
existingmodelsList.append(model);
existModel = true;
}
}
// if existModel is true, show user an error message
if (existModel) {
QMessageBox *pMessageBox = new QMessageBox(MainWindow::instance());
pMessageBox->setWindowTitle(QString(Helper::applicationName).append(" - ").append(Helper::information));
pMessageBox->setIcon(QMessageBox::Information);
pMessageBox->setAttribute(Qt::WA_DeleteOnClose);
pMessageBox->setText(QString(GUIMessages::getMessage(GUIMessages::UNABLE_TO_LOAD_FILE).arg(encoding)));
pMessageBox->setInformativeText(QString(GUIMessages::getMessage(GUIMessages::REDEFINING_EXISTING_CLASSES))
.arg(existingmodelsList.join(",")).append("\n")
.append(GUIMessages::getMessage(GUIMessages::DELETE_AND_LOAD).arg(encoding)));
pMessageBox->setStandardButtons(QMessageBox::Ok);
pMessageBox->exec();
} else { // if no conflicting model found then just load the file simply
loadFile(fileName, encoding);
}
}
}
}
/*!
* \brief OMCProxy::getClassNames
* Gets the list of classes from OMC.
* \param className - is the name of the class whose sub classes are retrieved.
* \param recursive - recursively retrieve all the sub classes.
* \param qualified - returns the class names as qualified path.
* \param sort
* \param builtin
* \param showProtected - returns the protected classes as well.
* \return
*/
QStringList OMCProxy::getClassNames(QString className, bool recursive, bool qualified, bool sort, bool builtin, bool showProtected,
bool includeConstants)
{
return mpOMCInterface->getClassNames(className, recursive, qualified, sort, builtin, showProtected, includeConstants);
}
/*!
Searches the list of classes from OMC.
\param searchText - is the text to search for.
\param findInText - tells to look for the searchText inside Modelica Text also.
\return the list of searched classes.
*/
QStringList OMCProxy::searchClassNames(QString searchText, bool findInText)
{
return mpOMCInterface->searchClassNames(searchText, findInText);
}
/*!
Gets the information about the class.
\param className - is the name of the class whose information is retrieved.
\return the class information list.
*/
OMCInterface::getClassInformation_res OMCProxy::getClassInformation(QString className)
{
OMCInterface::getClassInformation_res classInformation = mpOMCInterface->getClassInformation(className);
QString comment = classInformation.comment.replace("\\\"", "\"");
comment = makeDocumentationUriToFileName(comment);
// since tooltips can't handle file:// scheme so we have to remove it in order to display images and make links work.
#ifdef WIN32
comment.replace("src=\"file:///", "src=\"");
#else
comment.replace("src=\"file://", "src=\"");
#endif
classInformation.comment = comment;
return classInformation;
}
/*!
Checks whether the class is a package or not.
\param className - is the name of the class which is checked.
\return true if the class is a pacakge otherwise false
*/
bool OMCProxy::isPackage(QString className)
{
return mpOMCInterface->isPackage(className);
}
/*!
* \brief OMCProxy::isBuiltinType
* Returns true if the given type is one of the predefined types in Modelica.
* \param typeName
* \return
*/
bool OMCProxy::isBuiltinType(QString typeName)
{
return (typeName == "Real" ||
typeName == "Integer" ||
typeName == "String" ||
typeName == "Boolean" ||
typeName == "ExternalObject");
}
/*!
Returns true if the given type is one of the predefined types in Modelica.
Returns also the name of the predefined type.
*/
QString OMCProxy::getBuiltinType(QString typeName)
{
QString result = "";
result = mpOMCInterface->getBuiltinType(typeName);
getErrorString();
return result;
}
/*!
Checks the class type.
\param type - the type to check.
\param className - the class to check.
\return true if the class is a specified type
*/
bool OMCProxy::isWhat(StringHandler::ModelicaClasses type, QString className)
{
bool result = false;
switch (type) {
case StringHandler::Model:
result = mpOMCInterface->isModel(className);
break;
case StringHandler::Class:
result = mpOMCInterface->isClass(className);
break;
case StringHandler::Connector:
result = mpOMCInterface->isConnector(className);
break;
case StringHandler::Record:
result = mpOMCInterface->isRecord(className);
break;
case StringHandler::Block:
result = mpOMCInterface->isBlock(className);
break;
case StringHandler::Function:
result = mpOMCInterface->isFunction(className);
break;
case StringHandler::Package:
result = mpOMCInterface->isPackage(className);
break;
case StringHandler::Type:
result = mpOMCInterface->isType(className);
break;
case StringHandler::Operator:
result = mpOMCInterface->isOperator(className);
break;
case StringHandler::OperatorRecord:
result = mpOMCInterface->isOperatorRecord(className);
break;
case StringHandler::OperatorFunction:
result = mpOMCInterface->isOperatorFunction(className);
break;
case StringHandler::Optimization:
result = mpOMCInterface->isOptimization(className);
break;
case StringHandler::Enumeration:
result = mpOMCInterface->isEnumeration(className);
break;
default:
result = false;
}
return result;
}
/*!
Checks whether the nested class is protected or not.
\param className - is the name of the class.
\param nestedClassName - is the nested class to check.
\return true if the nested class is protected otherwise false
*/
bool OMCProxy::isProtectedClass(QString className, QString nestedClassName)
{
if (className.isEmpty()) {
return false;
} else {
return mpOMCInterface->isProtectedClass(className, nestedClassName);
}
}
/*!
Checks whether the class is partial or not.
\param className - is the name of the class.
\return true if the class is partial otherwise false
*/
bool OMCProxy::isPartial(QString className)
{
return mpOMCInterface->isPartial(className);
}
/*!
* \brief OMCProxy::isReplaceable
* Returns true if the className is replaceable in parentClassName.
* \param parentClassName
* \param className
* \return
*/
bool OMCProxy::isReplaceable(QString parentClassName, QString className)
{
sendCommand("isReplaceable(" + parentClassName + ", \"" + className + "\")");
return StringHandler::unparseBool(getResult());
}
/*!
Gets the class type.
\param className - is the name of the class to check.
\return the class type.
*/
StringHandler::ModelicaClasses OMCProxy::getClassRestriction(QString className)
{
QString result = mpOMCInterface->getClassRestriction(className);
if (result.toLower().contains("model"))
return StringHandler::Model;
else if (result.toLower().contains("class"))
return StringHandler::Class;
//! @note Also handles the expandable connectors i.e we return StringHandler::CONNECTOR for expandable connectors.
else if (result.toLower().contains("connector"))
return StringHandler::Connector;
else if (result.toLower().contains("record"))
return StringHandler::Record;
else if (result.toLower().contains("block"))
return StringHandler::Block;
else if (result.toLower().contains("function"))
return StringHandler::Function;
else if (result.toLower().contains("package"))
return StringHandler::Package;
else if (result.toLower().contains("type"))
return StringHandler::Type;
else if (result.toLower().contains("operator"))
return StringHandler::Operator;
else if (result.toLower().contains("operator record"))
return StringHandler::OperatorRecord;
else if (result.toLower().contains("operator function"))
return StringHandler::OperatorFunction;
else if (result.toLower().contains("optimization"))
return StringHandler::Optimization;
else
return StringHandler::Model;
}
/*!
Gets the parameter value.
\param className - is the name of the class whose parameter value is retrieved.
\return the parameter value.
*/
QString OMCProxy::getParameterValue(QString className, QString parameter)
{
return mpOMCInterface->getParameterValue(className, parameter);
}
/*!
Gets the list of component modifier names.
\param className - is the name of the class whose modifier names are retrieved.
\param name - is the name of the component.
\return the list of modifier names
*/
QStringList OMCProxy::getComponentModifierNames(QString className, QString name)
{
return mpOMCInterface->getComponentModifierNames(className, name);
}
/*!
* \brief OMCProxy::getComponentModifierValue
* Gets the component modifier value excluding the submodifiers. Only returns the binding.
* \param className - is the name of the class whose modifier value is retrieved.
* \param name - is the name of the component.
* \return the value of modifier.
*/
QString OMCProxy::getComponentModifierValue(QString className, QString name)
{
return mpOMCInterface->getComponentModifierValue(className, name);
}
/*!
Sets the component modifier value.
\param className - is the name of the class whose modifier value is set.
\param name - is the name of the modifier whose value is set.
\param value - is the value to set.
\return true on success.
*/
bool OMCProxy::setComponentModifierValue(QString className, QString modifierName, QString modifierValue)
{
QString expression;
if (modifierValue.isEmpty()) {
expression = QString("setComponentModifierValue(%1, %2, $Code(()))").arg(className).arg(modifierName);
} else if (modifierValue.startsWith("(") && modifierValue.contains("=")) {
expression = QString("setComponentModifierValue(%1, %2, $Code(%3))").arg(className).arg(modifierName).arg(modifierValue);
} else {
expression = QString("setComponentModifierValue(%1, %2, $Code(=%3))").arg(className).arg(modifierName).arg(modifierValue);
}
sendCommand(expression);
if (getResult().toLower().compare("ok") == 0) {
return true;
} else {
QString msg = tr("Unable to set the component modifier value using command <b>%1</b>").arg(expression);
MessageItem messageItem(MessageItem::Modelica, "", false, 0, 0, 0, 0, msg, Helper::scriptingKind, Helper::errorLevel);
MessagesWidget::instance()->addGUIMessage(messageItem);
return false;
}
}
/*!