Bug Summary

File:OMOptim/OMOptim/build/../Core/OMC/MOomc.cpp
Warning:line 1242, column 14
Value stored to 'openOk' during its initialization is never read

Annotated Source Code

[?] Use j/k keys for keyboard navigation

1// $Id$
2/**
3 * This file is part of OpenModelica.
4 *
5 * Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC),
6 * c/o Linköpings universitet, Department of Computer and Information Science,
7 * SE-58183 Linköping, Sweden.
8 *
9 * All rights reserved.
10 *
11 * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
12 * THIS OSMC PUBLIC LICENSE (OSMC-PL).
13 * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE
14 * OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE.
15 *
16 * The OpenModelica software and the Open Source Modelica
17 * Consortium (OSMC) Public License (OSMC-PL) are obtained
18 * from OSMC, either from the above address,
19 * from the URLs: http://www.ida.liu.se/projects/OpenModelica or
20 * http://www.openmodelica.org, and in the OpenModelica distribution.
21 * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
22 *
23 * This program is distributed WITHOUT ANY WARRANTY; without
24 * even the implied warranty of MERCHANTABILITY or FITNESS
25 * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
26 * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
27 *
28 * See the full OSMC Public License conditions for more details.
29 *
30 * Main contributor 2010, Hubert Thierot, CEP - ARMINES (France)
31 * Main contributor 2010, Hubert Thierot, CEP - ARMINES (France)
32
33 @file MOOptVector.h
34 @brief Comments for file documentation.
35 @author Hubert Thieriot, hubert.thieriot@mines-paristech.fr
36 Company : CEP - ARMINES (France)
37 http://www-cep.ensmp.fr/english/
38 @version
39
40 */
41
42#ifdef WIN32
43#include "windows.h"
44#endif
45
46//STD Headers
47#include <iostream>
48#include <stdexcept>
49
50#include "MOomc.h"
51#include "OMCThreads.h"
52#include "MOSettings.h"
53
54//IAEX Headers
55#include "omcinteractiveenvironment.h"
56#include "MOThreads.h"
57#include "LowTools.h"
58#include "SleeperThread.h"
59#include "omc_config.h"
60#include "Utilities.h"
61#include "StringHandler.h"
62#include "ComponentInfo.h"
63
64#include <QApplication>
65
66class Project;
67
68using namespace std;
69
70
71MOomc::MOomc(QString appName,bool start)
72{
73 nbCalls = 0;
74 mName = appName;
75 //delegate_ = 0;
76 mHasInitialized= false;
77 // isStarted = false;
78 omc_version_ = "(version)";
79
80 InfoSender::instance()->send( Info("OMC: attempt to start",ListInfo::OMCNORMAL2));
81
82 if (start)
83 {
84 startServer();
85 }
86
87}
88
89MOomc::~MOomc()
90{
91 stopServer();
92 //delete delegate_;
93}
94
95// threads managment
96void MOomc::addUsingThread(QThread* _thread,QString _threadName)
97{
98 threads.append(_thread);
99 threadsNames.append(_threadName);
100 emit startOMCThread(_threadName);
101}
102void MOomc::removeUsingThread(QThread* _thread)
103{
104 int index = threads.indexOf(_thread);
105 if(index>-1)
106 {
107 emit finishOMCThread(threadsNames.at(index));
108 threads.removeAt(index);
109 threadsNames.removeAt(index);
110 }
111}
112
113QList<QThread*> MOomc::getThreads()
114{
115 return threads;
116}
117
118QStringList MOomc::getThreadsNames()
119{
120 return threadsNames;
121}
122
123// Modelica functions
124
125QStringList MOomc::getClassNames(QString parentClass)
126{
127 QString commandRes= evalCommand("getClassNames("+parentClass+")");
128 if(commandRes.contains("error",Qt::CaseInsensitive))
129 return QStringList();
130 else
131 {
132 commandRes.remove("{");
133 commandRes.remove("}");
134 return commandRes.split(",",QString::SkipEmptyParts);
135 }
136}
137
138QString MOomc::getText(QString className)
139{
140 QString moTxt = evalCommand("list("+className+")");
141 moTxt.remove(QRegExp("^([\\s|\\\"]+)"));
142 moTxt.remove(QRegExp("([\\s|\\\"]+)$"));
143 return moTxt;
144}
145
146QString MOomc::getWholeText(bool includeMSL)
147{
148 QString moTxt;
149 if(includeMSL)
150 {
151 moTxt = evalCommand("list()");
152 }
153 else
154 {
155 QStringList classLoaded = getClassNames();
156 classLoaded.removeAll("Modelica");
157
158 for(int i=0;i<classLoaded.size();i++)
159 {
160 moTxt += getText(classLoaded.at(i));
161 moTxt +="\n \n";
162 }
163 }
164
165 moTxt.replace("\\\\","\\");
166 moTxt.replace("\\\"","\"");
167 moTxt.remove(QRegExp("^([\\s|\\\"]+)"));
168 moTxt.remove(QRegExp("([\\s|\\\"]+)$"));
169
170 return moTxt;
171
172}
173
174
175QStringList MOomc::getPackages(QString parentClass)
176{
177 QString commandRes= evalCommand("getPackages(" + parentClass +")");
178
179 if(commandRes.contains("error",Qt::CaseInsensitive))
180 {
181 //InfoSender::instance()->send( Info(ListInfo::OMSGETCOMPERROR,parentClass));
182 return QStringList();
183
184 }
185 commandRes.remove("{");
186 commandRes.remove("}");
187
188 QStringList list = commandRes.split(",");
189
190 if(list.at(0)=="")
191 {
192 list.clear();
193 }
194 return list;
195}
196QStringList MOomc::getRecords(QString parentClass)
197{
198 QStringList allClasses = getClassNames(parentClass);
199 QStringList models;
200 QString fullClassName;
201 for(int i=0;i<allClasses.size();i++)
202 {
203 fullClassName = parentClass.isEmpty() ? allClasses.at(i) : parentClass+"."+allClasses.at(i);
204
205 // check if it is a record
206 if(isRecord(fullClassName))
207 models.push_back(allClasses.at(i));
208 }
209 return models;
210}
211
212QStringList MOomc::getClasses(QString parentClass)
213{
214
215 QStringList allClasses = getClassNames(parentClass);
216 QStringList models;
217 QString fullClassName;
218 for(int i=0;i<allClasses.size();i++)
219 {
220 fullClassName = parentClass.isEmpty() ? allClasses.at(i) : parentClass+"."+allClasses.at(i);
221
222 // check if it is a class
223 if(isClass(fullClassName))
224 models.push_back(allClasses.at(i));
225 }
226 return models;
227}
228
229QStringList MOomc::getModels(QString parentClass)
230{
231
232 QStringList allClasses = getClassNames(parentClass);
233 QStringList models;
234 QString fullClassName;
235 for(int i=0;i<allClasses.size();i++)
236 {
237 fullClassName = parentClass.isEmpty() ? allClasses.at(i) : parentClass+"."+allClasses.at(i);
238 // check if it is a model
239 if(isModel(fullClassName))
240 models.push_back(allClasses.at(i));
241 }
242 return models;
243}
244
245void MOomc::getContainedComponents(QString parentClass,QStringList & compNames,QStringList & compClasses,bool includeInherited)
246{
247
248 compNames.clear();
249 compClasses.clear();
250
251 QString commandRes;
252 QList<ComponentInfo*> componentInfoList;
253
254 if(!parentClass.isEmpty())
255 {
256 QString msg;
257 msg.sprintf("Reading components of class %s ",parentClass.toLatin1().data());
258 InfoSender::instance()->send(Info(msg,ListInfo::OMCNORMAL2));
259
260 commandRes = evalCommand("getComponents(" + parentClass +", useQuotes = true)");
261 commandRes.trimmed();
262
263 QStringList list = StringHandler::unparseArrays(commandRes);
264
265 for (int i = 0 ; i < list.size() ; i++) {
266 if (list.at(i) == "Error") {
267 continue;
268 }
269 ComponentInfo *pComponentInfo = new ComponentInfo();
270 pComponentInfo->parseComponentInfoString(list.at(i));
271 componentInfoList.append(pComponentInfo);
272 }
273
274 for(int i = 0; i < componentInfoList.size(); i++)
275 {
276 ComponentInfo *pComponentInfo = componentInfoList.at(i);
277 compNames.push_back(pComponentInfo->mName);
278 compClasses.push_back(pComponentInfo->mClassName);
279 }
280 }
281
282 QStringList inhNames, inhClasses;
283
284 if(includeInherited)
285 {
286 getInheritedComponents(parentClass,inhNames,inhClasses);
287 compNames.append(inhNames);
288 compClasses.append(inhClasses);
289 }
290}
291
292QString MOomc::getParameterValue(QString parentClass, QString parameterName)
293{
294 QString commandRes= evalCommand("getParameterValue(" + parentClass +","+ parameterName+")");
295 if(commandRes=="Error")
296 return QString();
297 else
298 return commandRes;
299}
300
301/** This function will try to find value of parameter corresponding to its type.
302 * Sometimes, a parameter value is a reference to another one. This functions will recursively
303 * seek through references until it finds one corresponding to the type specified.
304 */
305QVariant MOomc::getParameterValue(QString parentClass, QString parameterName,VariableType type, QVariant defaultValue)
306{
307 QString commandRes= evalCommand("getParameterValue(" + parentClass +","+ parameterName+")");
308 if(commandRes=="Error" || commandRes.isEmpty())
309 return defaultValue;
310
311
312 QVariant::Type variantType;
313 switch(type)
314 {
315 case OMREAL:
316 variantType = QVariant::Double;
317 break;
318 case OMBOOLEAN :
319 variantType = QVariant::Bool;
320 break;
321 case OMINTEGER :
322 variantType = QVariant::Int;
323 break;
324 case OMSTRING :
325 variantType = QVariant::String;
326 break;
327 default:
328 variantType = QVariant::String;
329 break;
330 }
331
332 int i=0; // to avoid infinite loop (if for whatever reason, incorrect case is catched by error boolean)
333 QVariant result = commandRes;
334
335 bool error = false;
336
337 while(!result.convert(variantType) && (i<100) &&!error)
338 {
339 parentClass = commandRes.section(".",0,-2);
340 parameterName= commandRes.section(".",-1,-1);
341 commandRes = evalCommand("getParameterValue(" + parentClass +","+ parameterName+")");
342 error = (commandRes=="Error" || commandRes.isEmpty());
343 result = commandRes;
344 i++;
345 }
346 if(result.convert(variantType) && result.convert(variantType))
347 return result;
348 else
349 return defaultValue;
350}
351
352QStringList MOomc::getParameterNames(QString parentClass,bool includeInherited)
353{
354 QStringList parameterNames;
355 QString commandRes= evalCommand("getParameterNames(" + parentClass +")");
356 if(commandRes=="Error")
357 return QStringList(commandRes);
358
359 commandRes.remove("}");
360 commandRes.remove("{");
361 commandRes.remove(" ");
362 parameterNames = commandRes.split(",");
363
364 if(includeInherited)
365 {
366 QStringList inheritedClass = getInheritedClasses(parentClass);
367 for(int i=0;i<inheritedClass.size();i++)
368 {
369 parameterNames << getParameterNames(inheritedClass.at(i),true);
370 }
371 }
372 return parameterNames;
373}
374
375QMap<QString,QString> MOomc::getConnections(const QString & curModel)
376{
377 QMap<QString,QString> result;
378 QStringList connectFields;
379 //getting nb connections
380 QString res= evalCommand("getConnectionCount("+curModel+")");
381 if (res!="Error")
382 {
383 int nbConnections = res.toInt();
384
385 // for each connection
386 for(int iC=0;iC<nbConnections;iC++)
387 {
388 //get its name
389 res= evalCommand("getNthConnection("+curModel+","+QString::number(iC+1)+")");
390 if (res!="Error")
391 {
392 res.remove("{");
393 res.remove("}");
394 connectFields = res.split(",");
395
396 result.insert(connectFields.at(0),connectFields.at(1));
397 }
398 }
399 }
400 return result;
401}
402
403QStringList MOomc::getInheritedClasses(QString inheritingClass)
404{
405 if(inheritingClass.isEmpty())
406 return QStringList();
407
408 // Getting number and names of inherited classes
409 QString commandText = "getInheritanceCount(" + inheritingClass +")";
410 QString commandRes= evalCommand(commandText);
411
412 int nbInheritance = 0;
413 QStringList inheritedClasses;
414
415 if ((commandRes!="Error"))
416 {
417 nbInheritance = commandRes.toInt();
418
419 for(int i=0;i<nbInheritance;i++)
420 {
421 commandText = "getNthInheritedClass(" + inheritingClass +","+QString::number(i+1)+")";
422 commandRes= evalCommand(commandText);
423 inheritedClasses << commandRes;
424 }
425 }
426 inheritedClasses.removeAll(inheritingClass); // sometimes, a class appears as inheriting itself
427 return inheritedClasses;
428}
429
430QString MOomc::getPrimitiveClass(QString className)
431{
432 if(isPrimitive(className))
433 return className;
434 else
435 {
436 QStringList inherited = getInheritedClasses(className);
437 if(inherited.size()==1)
438 {
439 return getPrimitiveClass(inherited.at(0));
440 }
441 else
442 return QString();
443 }
444}
445VariableType MOomc::getPrimitiveDataType(QString className)
446{
447 QString primitiveClass = getPrimitiveClass(className);
448
449 if(!primitiveClass.compare("Real"))
450 return OMREAL;
451 if(!primitiveClass.compare("Integer"))
452 return OMINTEGER;
453 if(!primitiveClass.compare("Boolean"))
454 return OMBOOLEAN;
455 if(!primitiveClass.compare("String"))
456 return OMSTRING;
457
458 // case not found, REAL is default DataType
459 return OMREAL;
460}
461bool MOomc::isPrimitivelyInteger(QString className)
462{
463 return !getPrimitiveClass(className).compare("Integer");
464}
465bool MOomc::isPrimitivelyReal(QString className)
466{
467 return !getPrimitiveClass(className).compare("Real");
468}
469bool MOomc::isPrimitivelyBoolean(QString className)
470{
471 return !getPrimitiveClass(className).compare("Boolean");
472}
473
474QString MOomc::getComponentClass(QString parameter)
475{
476 QString parent = parameter.section(".",0,-2);
477 QStringList compNames,compClasses;
478 getContainedComponents(parent,compNames,compClasses);
479 int iParameter = compNames.indexOf(parameter.section(".",-1,-1));
480 if(iParameter>-1)
481 return compClasses.at(iParameter);
482 else
483 return QString();
484}
485
486
487QStringList MOomc::getComponentModifierNames(QString componentName)
488{
489 QStringList modifierNames;
490 QString commandText,commandRes;
491
492
493 QStringList levelNames = componentName.split(".");
494 //Checking that component is a first level one
495 if(levelNames.size()!=2)
496 {
497 InfoSender::instance()->send( Info(ListInfo::OMSOBTMODIFIERSFAILED,componentName));
498 return QStringList();
499 }
500 else
501 {
502 commandText = "getComponentModifierNames(" + levelNames.at(0) +","+levelNames.at(1)+")";
503 commandRes = evalCommand(commandText);
504
505 if(commandRes.indexOf("Class getConnectionCount (its type) not found in scope <global scope>")>-1)
506 {
507 InfoSender::instance()->send( Info(ListInfo::OMSOBTMODIFIERSFAILED,componentName));
508 return QStringList();
509 }
510
511 commandRes.remove("{");
512 commandRes.remove("}");
513 commandRes.remove(" ");
514 return(commandRes.split(","));
515 }
516}
517
518
519QString MOomc::getFlattenedModel(const QString & modelName)
520{
521 InfoSender::instance()->sendCurrentTask("Instantiating model "+modelName);
522 initCommandLineOptions();
523 QString flatcmd = "instantiateModel("+modelName+")";
524 QString errorString;
525 QString flattened = evalCommand(flatcmd,errorString);
526
527 if(flattened=="\"\"")
528 flattened.clear();
529
530 if(!errorString.isEmpty() && !flattened.isEmpty())
531 InfoSender::instance()->sendWarning("Instantiating model warned ["+modelName+"]");
532 else if(!errorString.isEmpty() && flattened.isEmpty())
533 InfoSender::instance()->sendError("Instantiating model failed ["+modelName+"]");
534 else
535 InfoSender::instance()->sendNormal("Instantiating model successful ["+modelName+"]");
536
537 return flattened;
538}
539
540QString MOomc::getFlattenedModifierValue(const QString & modelName,const QString & componentName,const QString & modifierName)
541{
542 QString flattened = getFlattenedModel(modelName);
543 return getFlattenedModifierValue(modelName,componentName,modifierName,flattened);
544}
545
546QStringList MOomc::getFlattenedModifierVectorValue(const QString & modelName,const QString & componentName,const QString & modifierName, int size,QString & flattenedModel)
547{
548 QStringList result;
549 QString curModifier;
550 QString curValue;
551 for(int i=0;i<size;i++)
552 {
553 curModifier = modifierName+"\\["+QString::number(i+1)+"\\]";
554 curValue = getFlattenedModifierValue(modelName,componentName,curModifier,flattenedModel);
555 result.push_back(curValue);
556 }
557 return result;
558}
559
560
561QString MOomc::getFlattenedModifierUnit(const QString & modelName,const QString & componentName,const QString & modifierName, QString & flattenedModel)
562{
563 if(flattenedModel.isEmpty())
564 flattenedModel = getFlattenedModel(modelName);
565
566 QRegExp exp1(componentName+"."+modifierName+".*unit[\\s|=]*\\\\\\\"(.*)\\\\\\\"");
567 exp1.setMinimal(true);
568
569 int i1 = flattenedModel.indexOf(exp1);
570
571 if((i1>-1)&&exp1.capturedTexts().size()==2)
572 {
573 QString result = exp1.capturedTexts().at(1);
574 return result;
575 }
576 return QString();
577}
578
579
580
581QString MOomc::getFlattenedModifierValue(const QString & modelName,const QString & componentName,const QString & modifierName, QString & flattenedModel)
582{
583 if(flattenedModel.isEmpty())
584 flattenedModel = getFlattenedModel(modelName);
585
586 QStringList lines = flattenedModel.split("\n");
587 if(lines.size()==1)
588 {
589 lines = flattenedModel.split("\\n");
590 }
591
592
593 // 1st format : Real sterilisateur.Sterilisateur.FactMin = 0.0;
594 QRegExp exp1(".*\\b"+componentName+"."+modifierName+"\\b[\\s]*=[\\s]*([\\S|\\\\|\"]+);");
595
596 int i1 = lines.indexOf(exp1);
597
598 if((i1>-1)&&exp1.capturedTexts().size()==2)
599 {
600 QString result = exp1.capturedTexts().at(1);
601 result = result.remove(QRegExp("[\\\\|\"]*"));
602 return result;
603 }
604
605 // 2nd format with unit
606 QRegExp exp2(".*\\b"+componentName+"."+modifierName+"\\b\\([.*]\\)[\\s]*=[\\s]*( );");
607 int i2 = lines.indexOf(exp2);
608
609 if((i2>-1)&&exp2.capturedTexts().size()==2)
610 return exp2.capturedTexts().at(1);
611
612 // 3rd format
613 QRegExp exp3(".*\\b"+componentName+"\\b\\(.*\\b"+modifierName+"\\b[\\s]*=[\\s]*([\\d|\\.]*).*;");
614 int i3 = lines.indexOf(exp3);
615
616 if((i3>-1)&&exp3.capturedTexts().size()==2)
617 return exp3.capturedTexts().at(1);
618
619 // 4th format : a vector
620 // e.g. eIFactMultEquation.groups = {\"group1\", \"group2\"};
621 QRegExp exp4(".*\\b"+componentName+"."+modifierName+"\\b[\\s]*=[\\s]\\{(.*)\\};");
622 int i4 = lines.indexOf(exp4);
623
624 if((i4>-1)&&exp4.capturedTexts().size()==2)
625 {
626 return exp4.capturedTexts().at(1);
627 }
628
629 return QString();
630}
631
632QString MOomc::getComponentModifierValue(QString modelName,QString shortComponentName,QString modifierName)
633{
634 QStringList modifierNames;
635 QString commandText,commandRes;
636
637 // QStringList levelNames = componentName.split(".");
638 // //Checking that component is a first level one
639 // if(levelNames.size()!=2)
640 // {
641 // InfoSender::instance()->send( Info(ListInfo::OMSOBTMODIFIERSFAILED,componentName));
642 // QString errorString;
643 // return errorString;
644 // }
645 // else
646 // {
647 commandText = "getComponentModifierValue(" + modelName +","+shortComponentName+"."+modifierName+")";
648 commandRes = evalCommand(commandText);
649 if(commandRes.contains("Error",Qt::CaseInsensitive))
650 {
651 InfoSender::instance()->send( Info(ListInfo::OMSOBTMODIFIERSFAILED,shortComponentName));
652 return QString();
653 }
654 commandRes.remove("=");
655 commandRes.remove(" ");
656 return commandRes;
657 // }
658}
659
660bool MOomc::setComponentModifiers(QString compName,QString model, QStringList modNames,QStringList modValues)
661{
662 for(int i=0;i<modNames.size();i++)
663 {
664 QString commandText = "setComponentModifierValue(";
665 commandText += model+",";
666 commandText += compName.section(".",-1,-1)+"."+modNames.at(i)+","+"$Code(="+modValues.at(i)+"))";
667
668 QString commandRes = evalCommand(commandText);
669 }
670 return true;
671}
672
673
674bool MOomc::isConnector(QString className)
675{
676 QString commandText = "isConnector(" + className +")";
677 QString commandRes= evalCommand(commandText);
678 return (commandRes=="true");
679}
680
681bool MOomc::isModel(QString className)
682{
683 QString commandText = "isModel(" + className +")";
684 QString commandRes= evalCommand(commandText);
685 return (commandRes=="true");
686}
687
688bool MOomc::isRecord(QString className)
689{
690 QString commandText = "isRecord(" + className +")";
691 QString commandRes= evalCommand(commandText);
692 return (commandRes=="true");
693}
694
695bool MOomc::isClass(QString className)
696{
697 QString commandText = "isClass(" + className +")";
698 QString commandRes= evalCommand(commandText);
699 return (commandRes=="true");
700}
701
702bool MOomc::isPackage(QString className)
703{
704 QString commandText = "isPackage(" + className +")";
705 QString commandRes= evalCommand(commandText);
706 return (commandRes=="true");
707}
708
709bool MOomc::isPrimitive(QString className)
710{
711 QString commandText = "isPrimitive(" + className +")";
712 QString commandRes= evalCommand(commandText);
713 return (commandRes=="true");
714}
715
716bool MOomc::isComponent(QString name)
717{
718 // #TOCHECK
719 QStringList curNames, curClasses;
720 QString parentClass = name.section(".",0,-2);
721 getContainedComponents(parentClass,curNames,curClasses);
722 return (curNames.contains(name));
723}
724
725Modelica::ClassRestr MOomc::getClassRestriction(QString className)
726{
727 if(isPackage(className))
728 return Modelica::PACKAGE;
729 else
730 if(isModel(className))
731 return Modelica::MODEL;
732 else
733 if(isComponent(className))
734 return Modelica::COMPONENT;
735 else
736 return Modelica::OTHER;
737}
738
739QString MOomc::getAnnotation(QString compName,QString compClass,QString model)
740{
741
742 QString annot;
743 /// \todo
744 // QString commandText = "list("+model+")";
745 // QString list= evalCommand(commandText);
746
747
748 // QStringList listLines = list.split("\n");
749 // QString compShortName = compName.section(".",-1,-1);
750
751 // QRegExp regExp(".*"+compClass+"[\\s]*"+ compName.section(".",-1,-1)+"\\(.*\\)[\\s]*;");
752 // int iLine = listLines.indexOf(regExp);
753
754 // QStringList cap=regExp.capturedTexts();
755 // listLines.at(iLine).contains(regExp);
756 // cap = regExp.capturedTexts();
757
758 // if(iLine == -1)
759 // return QString();
760 // else
761 // {
762 // QString annot = listLines.at(iLine);
763 // if(!annot.contains("annotation"))
764 // return QString();
765 // else
766 // {
767 // annot.remove(QRegExp(".*annotation\\("));
768 // annot.remove(QRegExp("\\)[\\s]*;"));
769 // return annot;
770 // }
771 // }
772 return annot;
773}
774
775QString MOomc::getComment(QString modelName, QString compName)
776{
777 QString commandRes= evalCommand("getComponents(" + modelName +")");
778
779 if(commandRes.indexOf("error",Qt::CaseInsensitive)==0)
780 return QString();
781
782 // {{Modelica.SIunits.Temp_K,TorcH,"ORC hot temperature (K)", "public", false, false, false, false, "parameter", "none", "unspecified",{}},{Modelica.SIunits.Temp_K,TorcC,"ORC cold temperature (K)", "public", false, false, false, false, "parameter", "none", "unspecified",{}}}
783
784 QRegExp rexp(".*\\b"+compName+"\\b,"+"\"(.*)\"");
785 rexp.setMinimal(true);
786 if(commandRes.contains(rexp)&&rexp.capturedTexts().size()>1)
787 {
788 QStringList captured = rexp.capturedTexts();
789 return captured.at(1);
790 }
791 else
792 return QString();
793}
794
795int MOomc::getConnectionNumber(QString className)
796{
797 QString commandText = "getConnectionCount("+className+")";
798 QString commandRes= evalCommand(commandText);
799
800 return commandRes.toInt();
801}
802
803bool MOomc::initCommandLineOptions()
804{
805 QString value = MOSettings::value("OMCCommandLineOptions").toString();
806 QString commandText = "setCommandLineOptions(\""+value+"\");";
807 QString commandRes= evalCommand(commandText);
808 return (commandRes=="true");
809}
810
811bool MOomc::clearCommandLineOptions()
812{
813 QString commandText = "setCommandLineOptions(\" \");";
814 QString commandRes= evalCommand(commandText);
815 return (commandRes=="true");
816}
817
818bool MOomc::translateModel(QString model)
819{
820 initCommandLineOptions();
821 QString commandText = "translateModel(" + model +")";
822 QString commandRes= evalCommand(commandText);
823 return (commandRes=="true");
824}
825
826bool MOomc::buildModel(QString model,QString & exeFile,QString & initFile)
827{
828 initCommandLineOptions();
829 QString commandText = "buildModel("+model+")";
830 QString commandRes= evalCommand(commandText);
831 commandRes.remove(QRegExp("[{|}|\"]"));
832
833 exeFile = commandRes.section(",",0,0);
834 bool success = !exeFile.isEmpty();
835 if(!success)
836 {
837 exeFile.clear();
838 initFile.clear();
839 }
840 else
841 {
842#ifdef WIN32
843 exeFile.append(".exe");
844#endif
845 QDir dir = QFileInfo(exeFile).absoluteDir();
846 initFile = dir.absoluteFilePath(commandRes.section(",",1,1));
847 }
848 return success;
849}
850
851
852bool MOomc::deleteComponent(QString compName)
853{
854 QString model = compName.section(".",0,0);
855
856 compName = compName.section(".",1,-1);
857
858
859 QString commandText = "deleteComponent(" + compName +"," + model +")";
860 QString commandRes= evalCommand(commandText);
861 return (commandRes=="true");
862
863}
864
865bool MOomc::deleteClass(QString className)
866{
867 QString commandText = "deleteClass(" + className+")";
868 QString commandRes= evalCommand(commandText);
869 return (commandRes=="true");
870}
871
872bool MOomc::deleteConnection(const QString & org,const QString & dest, const QString & model)
873{
874 // getting short names
875 QString shortOrg = org;
876 shortOrg.remove(QRegExp("^"+model+"."));
877 QString shortDest = dest;
878 shortDest.remove(QRegExp("^"+model+"."));
879
880 QString commandText = "deleteConnection(" + shortOrg +"," + shortDest +"," + model +")";
881 QString commandRes= evalCommand(commandText);
882
883 commandText = "deleteConnection(" + shortDest +"," + shortOrg +"," + model +")";
884 commandRes= evalCommand(commandText);
885
886 QMap<QString,QString> existingConns = getConnections(model);
887
888 if((existingConns.value(shortOrg) == shortDest)||(existingConns.value(shortDest) == shortOrg))
889 {
890 QString msg = "deleting connection didn't work ["+org+","+dest+"]";
891 InfoSender::instance()->send(Info(msg,ListInfo::WARNING2));
892 return false;
893 }
894 else
895 return true;
896
897}
898bool MOomc::deleteConnections(const QStringList & orgs, const QStringList & dests, const QString & model)
899{
900 bool allOk = false;
901 if(orgs.size()==dests.size())
902 {
903 allOk = true;
904 for(int i=0;i<orgs.size();i++)
905 {
906 allOk = deleteConnection(orgs.at(i),dests.at(i),model) && allOk;
907 }
908 }
909 return allOk;
910}
911
912bool MOomc::deleteConnections(const QStringList & orgs,const QList<QStringList> & dests,const QString & model)
913{
914 bool allOk = false;
915 if(orgs.size()==dests.size())
916 {
917 allOk = true;
918 for(int i=0;i<orgs.size();i++)
919 {
920 for(int j=0;j<dests.at(i).size();j++)
921 allOk = deleteConnection(orgs.at(i),dests.at(i).at(j),model) && allOk;
922 }
923 }
924 return allOk;
925}
926
927bool MOomc::addConnection(QString org, QString dest)
928{
929 QString modelOrg = org.section(".",0,-3);
930 QString modelDest = dest.section(".",0,-3);
931
932 if(modelOrg!=modelDest || modelOrg.isEmpty())
933 return false;
934 else
935 {
936 QString shortOrg = org.section(".",-2,-1);
937 QString shortDest = dest.section(".",-2,-1);
938
939 QString commandText = "addConnection("+shortOrg+","+shortDest+","+modelOrg+")";
940 QString commandRes = evalCommand(commandText);
941
942 return ((commandRes=="true") || (commandRes=="Ok"));
943 }
944}
945
946bool MOomc::addConnections(QStringList orgs, QStringList dests)
947{
948 if(orgs.size()!=dests.size())
949 return false;
950 else
951 {
952 bool all = true;
953 for(int i =0;i < orgs.size();i++)
954 {
955 all = addConnection(orgs.at(i),dests.at(i)) && all;
956 }
957 return all;
958 }
959}
960
961bool MOomc::addConnections(QStringList orgs, QList<QStringList> dests)
962{
963 if(orgs.size()!=dests.size())
964 return false;
965 else
966 {
967 bool all = true;
968 for(int i =0;i < orgs.size();i++)
969 {
970 for(int j=0;j<dests.at(i).size();j++)
971 all = addConnection(orgs.at(i),dests.at(i).at(j)) && all;
972 }
973 return all;
974 }
975}
976
977bool MOomc::inherits(QString childClass, QString parentClass)
978{
979 QStringList inherited = getInheritedClasses(childClass);
980 while(!inherited.isEmpty())
981 {
982 if(inherited.contains(parentClass))
983 return true;
984 else
985 {
986 inherited.append(getInheritedClasses(inherited.at(0)));
987 inherited.removeAt(0);
988 }
989 }
990 return false;
991}
992
993
994bool MOomc::addComponent(QString name,QString className, QString modelName,QString annotation)
995{
996 if(annotation.isEmpty() || (annotation.left(1)!="\"") || (annotation.right(1)!="\""))
997 annotation = "\""+annotation+"\"";
998
999 QString commandText = "addComponent("+name.section(".",-1,-1)+","+className+","+modelName+",annotate="+annotation+")";
1000 QString commandRes= evalCommand(commandText);
1001 return (commandRes=="true");
1002}
1003bool MOomc::save(QString model)
1004{
1005 QString commandText = "save(" + model +")";
1006 QString commandRes= evalCommand(commandText);
1007 return (commandRes=="true");
1008}
1009
1010//void MOomc::setCommand(QString comm)
1011//{
1012// command=comm;
1013//}
1014
1015QString MOomc::evalCommand(QString command)
1016{
1017 QString errorString;
1018 return evalCommand(command,errorString);
1019}
1020
1021QString MOomc::evalCommand(QString command,QString &errorString)
1022{
1023 if(!evalMutex.tryLock())
1024 {
1025 errorString = "Could not launch OMC command";
1026 return QString();
1027 }
1028 else
1029 {
1030 errorString.clear();
1031 QString result;
1032
1033 QString msg;
1034 InfoSender::instance()->send( Info(msg.sprintf("OMC: %s",command.toLatin1().data()),ListInfo::OMCNORMAL2));
1035 nbCalls++;
1036
1037 if (!mHasInitialized)
1038 {
1039 InfoSender::instance()->send(Info(QString("OMC not started. Please start it again (menu OMC->restart)"),ListInfo::WARNING2));
1040 result = QString();
1041 }
1042 else
1043 {
1044 // Send command to server
1045 try
1046 {
1047 //mResult = mOMC->sendExpression(command.toLatin1());
1048 mResult = QString::fromLocal8Bit(mOMC->sendExpression(command.toLocal8Bit()));
1049 // logOMCMessages(command);
1050 InfoSender::instance()->send(Info(getResult(),ListInfo::OMCNORMAL2));
1051
1052 // display errors
1053 command = "getErrorString()";
1054 errorString = QString::fromLocal8Bit(mOMC->sendExpression(command.toLocal8Bit()));
1055 errorString.remove("\"");
1056 if((!errorString.isEmpty())&&(errorString!="\n"))
1057 InfoSender::instance()->send(Info(errorString,ListInfo::OMCWARNING2));
1058
1059 result = getResult();
1060 }
1061 catch(CORBA::Exception&)
1062 {
1063 QFile::remove(mObjectRefFile);
1064 InfoSender::instance()->send(Info(QString("Communication with OMC server has lost ")));
1065 }
1066 catch( omniORB::fatalException & ex)
1067 {
1068 InfoSender::instance()->debug("Caught omniORB2 fatalException. This is a bug in omniORB");
1069 }
1070 catch( CORBA::COMM_FAILURE &ex)
1071 {
1072 InfoSender::instance()->debug("Caught CORBA::COMM_FAILURE");
1073 }
1074 catch (...)
1075 {
1076 InfoSender::instance()->debug("Caught exception");
1077 }
1078 }
1079
1080
1081 evalMutex.unlock();
1082 return result;
1083 }
1084
1085
1086
1087 //if(!delegate_)
1088 // startServer();
1089
1090
1091 //QString msg;
1092 //InfoSender::instance()->send( Info(msg.sprintf("OMC : %s",_command.toLatin1().data()),ListInfo::OMCNORMAL2));
1093 //delegate_->evalExpression( _command );
1094 //QString result = delegate_->result();
1095 //InfoSender::instance()->send(Info(result,ListInfo::OMCNORMAL2));
1096 //if(result.compare("NOT RESPONDING",Qt::CaseInsensitive)==0)
1097 //{
1098 // // restart server
1099 // delegate_->closeConnection();
1100 // delete delegate_;
1101 // delegate_ = NULL;
1102 // startServer();
1103 // delegate_->evalExpression( _command );
1104 // result = delegate_->result();
1105 //}
1106 //return result;
1107}
1108//void MOomc::evalCommand()
1109//{
1110// nbCalls++;
1111//
1112// QString msg;
1113// QString error;
1114// QString warning;
1115//
1116// // send command to OMC
1117// if( isStarted )
1118// {
1119//eval:
1120// // 2006-02-02 AF, Added try-catch
1121// try
1122// {
1123// delegate_->evalExpression(command );
1124// }
1125// catch( exception &e )
1126// {
1127// exceptionInEval(e);
1128// return;
1129// }
1130//
1131// // get result
1132// msg = delegate_->result();
1133// InfoSender::instance()->send(Info(msg,ListInfo::OMCNORMAL2));
1134//
1135// //if(msg.contains("error",Qt::CaseInsensitive))
1136// if(true)
1137// {
1138// // get Error text
1139// try
1140// {
1141// QString getErrorString = "getErrorString()";
1142// delegate_->evalExpression(getErrorString);
1143// }
1144// catch( exception &e )
1145// {
1146// exceptionInEval(e);
1147// return;
1148// }
1149// msg = delegate_->result();
1150// if(msg!="\"\"")
1151// InfoSender::instance()->send(Info(msg,ListInfo::OMCERROR2));
1152// }
1153// }
1154// else
1155// {
1156// if( startServer() )
1157// {
1158// msg ="No OMC server started - restarted OMC\n" ;
1159// InfoSender::instance()->send(Info(msg,ListInfo::WARNING2));
1160// goto eval;
1161// }
1162// else
1163// {
1164// msg="No OMC server started - unable to restart OMC\n";
1165// InfoSender::instance()->send( Info(msg,ListInfo::ERROR2));
1166// }
1167// }
1168// return;
1169//}
1170
1171//void MOomc::exceptionInEval(exception &e)
1172//{
1173
1174// QString msg;
1175// // 2006-0-09 AF, try to reconnect to OMC first.
1176// try
1177// {
1178// msg = "Command did not achieve properly :"+QString( e.what() )+"\n";
1179// msg = msg + "Trying to reconnect...\n";
1180// InfoSender::instance()->send( Info(msg,ListInfo::WARNING2));
1181
1182// delegate_->closeConnection();
1183// delegate_->reconnect();
1184// evalCommand();
1185// }
1186// catch( exception &e )
1187// {
1188// // unable to reconnect
1189// InfoSender::instance()->send( Info("Still did not work. Aborting.",ListInfo::ERROR2));
1190
1191// }
1192//}
1193
1194QStringList MOomc::getDependenciesPaths(QString fileName,bool commentImportPaths)
1195{
1196 QStringList importFiles;
1197
1198
1199 //Openfile and read it
1200 QFile moFile(fileName);
1201 if(!moFile.exists())
1202 {
1203 return QStringList();
1204 }
1205 if(!moFile.open(QIODevice::ReadOnly))
1206 return QStringList();
1207
1208 QTextStream ts(&moFile);
1209 QString text = ts.readAll();
1210 ts.reset();
1211 moFile.close();
1212
1213 QStringList lines = text.split("\n");
1214 QString tmpDep;
1215
1216 QRegExp regExp("[\\s]*import.*\".*\"[\\s]*;[\\s]*");
1217
1218 int index0=0;
1219 int index=lines.indexOf(regExp,index0);
1220
1221 while(index>-1)
1222 {
1223 tmpDep = lines.at(index);
1224 tmpDep.remove(QRegExp("[\\s]*import[\\s]*\""));
1225 tmpDep.remove(QRegExp("\".*"));
1226 importFiles.push_back(tmpDep);
1227
1228 if(commentImportPaths)
1229 {
1230 tmpDep=lines.at(index);
1231 tmpDep.insert(0,"//");
1232 lines.replace(index,tmpDep);
1233 }
1234
1235 index0=index+1;
1236 index=lines.indexOf(regExp,index0);
1237 }
1238
1239
1240 if(commentImportPaths && importFiles.size()>0)
1241 {
1242 bool openOk = moFile.open(QIODevice::WriteOnly);
Value stored to 'openOk' during its initialization is never read
1243 QTextStream ts2(&moFile);
1244
1245 QString newText = lines.join("\n");
1246 ts2 << newText;
1247 moFile.close();
1248 }
1249
1250 return importFiles;
1251}
1252
1253void MOomc::loadModel(QString filename,bool force,bool &ok,QString & error)
1254{
1255 bool doLoad = true;
1256 if(!force)
1257 {
1258 QStringList classLoaded = getClassNames("");
1259 int i=0;
1260 while(doLoad && i<classLoaded.size())
1261 {
1262 QFileInfo fileOfClassInOMC = getFileOfClass(classLoaded.at(i));
1263
1264 if(fileOfClassInOMC == QFileInfo(filename))
1265 doLoad = false;
1266
1267 i++;
1268 }
1269 }
1270
1271 if(doLoad)
1272 {
1273 // store mo file before modifying it
1274 // (imports will be commented)
1275 QFile moFile(filename);
1276 QFileInfo moFileInfo(filename);
1277 QDir moDir(moFileInfo.absolutePath());
1278 QString copyPath=filename+"_bkp";
1279 moDir.remove(copyPath);
1280 moFile.copy(filename+"_bkp");
1281
1282
1283 // load dependencies
1284 QStringList depFiles = getDependenciesPaths(filename,true);
1285 for(int i=0;i<depFiles.size();i++)
1286 {
1287 bool _depOk;
1288 QString _depError;
1289 loadModel(depFiles.at(i),false,_depOk,_depError);
1290 }
1291
1292
1293 QString result = loadFileWThread(filename);
1294
1295
1296
1297 // Restore file
1298 moDir.remove(filename);
1299 QFile moCopiedFile(copyPath);
1300 moCopiedFile.copy(filename);
1301
1302 if(result.contains("true",Qt::CaseInsensitive))
1303 {
1304 InfoSender::instance()->send(Info(ListInfo::MODELLOADSUCCESS,filename));
1305 ok = true;
1306 error = "";
1307
1308 }
1309 else
1310 {
1311 ok = false;
1312 error = result;
1313 InfoSender::instance()->send(Info(ListInfo::MODELLOADFAIL,filename,error));
1314 }
1315 }
1316 else
1317 {
1318 InfoSender::instance()->send( Info(QString("Model file already loaded - ignoring. (" + filename + ")"),ListInfo::NORMAL2));
1319 ok = true;
1320 error = "";
1321 }
1322
1323 InfoSender::eraseCurrentTask();
1324}
1325
1326QStringList MOomc::loadFiles(const QStringList & filePaths)
1327{
1328 QStringList result;
1329 for(int i=0;i<filePaths.size();i++)
1330 {
1331 result.push_back(loadFile(filePaths.at(i)));
1332 }
1333 return result;
1334}
1335
1336QString MOomc::loadFile(const QString & filePath)
1337{
1338 InfoSender::sendCurrentTask("Loading model "+filePath);
1339
1340 QString localFile = filePath;
1341 localFile = localFile.replace("\\","/");
1342 QString cmd = QString("loadFile(\"") + localFile + QString("\")");
1343
1344 QString errorString;
1345 QString result = evalCommand(cmd,errorString);
1346
1347 // if file is not in UTF-8, try with another encoding
1348 if(result.contains("false",Qt::CaseInsensitive) && errorString.contains("The file was not encoded in UTF-8"))
1349 {
1350 cmd = QString("loadFile(\"") + localFile + QString("\",encoding=\"ISO-8859-1\")");
1351 result = evalCommand(cmd);
1352 }
1353
1354 emit loadedFile(localFile,result);
1355 InfoSender::eraseCurrentTask();
1356 return result;
1357}
1358
1359QString MOomc::loadFileWThread(QString filePath)
1360{
1361 MOThreads::OMCModelLoader* loader = new MOThreads::OMCModelLoader(filePath,this);
1362 //loader->start(QThread::HighestPriority);
1363 loader->run(); // avoid thread separation. Does not work properly yet...
1364 while (loader->isRunning())
1365 {
1366 InfoSender::instance()->sendNormal("refreshing");
1367 qApp(static_cast<QApplication *>(QCoreApplication::instance
()))
->processEvents();
1368 }
1369
1370 QString result = loader->_result;
1371 delete loader;
1372 return result;
1373}
1374
1375/**
1376 * if path is empty, load default one
1377 */
1378void MOomc::loadStandardLibrary(QString path)
1379{
1380 if(path.isEmpty())
1381 evalCommand("loadModel(Modelica)");
1382 else
1383 {
1384 loadFile(path);
1385 }
1386 //evalCommand("loadModel(ModelicaServices)");
1387
1388 // //! @todo Remove it once we have removed Media and and and and Fluid from MSL.
1389 // // just added to remove Fluid and and and and Media Library...
1390
1391 // evalCommand("deleteClass(Modelica.Media)");
1392 // evalCommand("deleteClass(Modelica.Fluid)");
1393}
1394
1395void MOomc::clear()
1396{
1397 if(isStarted())
1398 evalCommand("clear()");
1399
1400 initTempDirectory();
1401}
1402
1403
1404void MOomc::exit()
1405{
1406 // check if omc is running, if so: ask if it is ok that omc also closes.
1407 try
1408 {
1409 if( mHasInitialized )
1410 {
1411 // delegate_->closeConnection();
1412 // delegate_->reconnect();
1413 stopServer();
1414 }
1415 }
1416 catch(exception e)
1417 {}
1418
1419 //emit emitQuit();
1420}
1421
1422bool MOomc::startServer()
1423{
1424 try
1425 {
1426 // evalMutex.unlock();
1427 QString msg;
1428 const char *omhome = getenv("OPENMODELICAHOME");
1429 QString omcPath;
1430#ifdef WIN32
1431 if (!omhome)
1432 {
1433 InfoSender::instance()->send(Info("OPEN_MODELICA_HOME_NOT_FOUND"));
1434 return false;
1435 }
1436 omcPath = QString( omhome ) + "/bin/omc.exe";
1437#else /* unix */
1438 omcPath = (omhome ? QString(omhome)+"/bin/omc" : QString(CONFIG_DEFAULT_OPENMODELICAHOME"/var/lib/jenkins1/ws/iodic_Jenkins.slow_omlib-staging/build") + "/bin/omc");
1439#endif
1440
1441 // Check the IOR file created by omc.exe
1442 QFile objectRefFile;
1443 QString fileIdentifier;
1444 fileIdentifier = qApp(static_cast<QApplication *>(QCoreApplication::instance
()))
->sessionId().append(QTime::currentTime().toString(tr("hh:mm:ss:zzz")).remove(":"));
1445
1446 objectRefFile.setFileName(QString(Utilities::tempDirectory()).append(QDir::separator()).append("openmodelica.objid.").append(this->mName).append(fileIdentifier));
1447
1448 if (objectRefFile.exists())
1449 objectRefFile.remove();
1450
1451 mObjectRefFile = objectRefFile.fileName();
1452
1453
1454 // Start the omc.exe
1455 QStringList parameters;
1456 QString str;
1457 parameters << QString("+c=").append(mName).append(fileIdentifier) << QString("+d=interactiveCorba") << QString("+corbaObjectReferenceFilePath=").append(Utilities::tempDirectory());
1458 QProcess *omcProcess = new QProcess();
1459 QFile omcOutputFile;
1460#ifdef WIN32 // Win32
1461 omcOutputFile.setFileName(QString(Utilities::tempDirectory()).append(QDir::separator()).append("openmodelica.omc.output.").append(mName));
1462#else // UNIX environment
1463 char *u = getenv("USER");
1464 QString user = u ? u : "nobody";
1465 omcOutputFile.setFileName(QString(Utilities::tempDirectory()).append(QDir::separator()).append("openmodelica.").append(( QString(user))).append(".omc.output.").append(mName));
1466#endif
1467
1468 InfoSender::instance()->send( Info(str.sprintf("OMC: running command: %s %s",
1469 omcPath.toLatin1().data(),
1470 parameters.join(" ").toLatin1().data()),ListInfo::OMCNORMAL2));
1471 omcProcess->setProcessChannelMode(QProcess::MergedChannels);
1472 omcProcess->setStandardOutputFile(omcOutputFile.fileName());
1473 omcProcess->start(omcPath, parameters);
1474 // wait for the server to start.
1475 int ticks = 0;
1476 while (!objectRefFile.exists())
1477 {
1478 SleeperThread::msleep(1000);
1479 ticks++;
1480 if (ticks > 20)
1481 {
1482 msg = "OMC: unable to find OMC server, Object reference file " + mObjectRefFile + " not created.";
1483 throw std::runtime_error(msg.toStdString());
1484 }
1485 }
1486
1487 // ORB initialization.
1488 int argc = 2;
1489 static const char *argv[] = { "-ORBgiopMaxMsgSize", "10485760" };
1490 CORBA::ORB_var orb = CORBA::ORB_init(argc, (char **)argv);
1491
1492 objectRefFile.open(QIODevice::ReadOnly);
1493
1494 char buf[1024];
1495 objectRefFile.readLine( buf, sizeof(buf) );
1496 QString uri( (const char*)buf );
1497
1498 CORBA::Object_var obj = orb->string_to_object(uri.trimmed().toLatin1());
1499
1500 mOMC = OmcCommunication::_narrow(obj);
1501 mHasInitialized = true;
1502 }
1503 catch(std::exception &e)
1504 {
1505 QString msg = e.what();
1506 InfoSender::instance()->send(Info(msg,ListInfo::ERROR2));
1507 mHasInitialized = false;
1508 return false;
1509 }
1510 catch (CORBA::Exception&)
1511 {
1512 QString msg = "Unable to communicate with OMC";
1513 InfoSender::instance()->send(Info(msg,ListInfo::ERROR2));
1514 mHasInitialized = false;
1515 return false;
1516 }
1517
1518 evalCommand("getInstallationDirectoryPath()");
1519 OMCHelper::OpenModelicaHome = StringHandler::removeFirstLastQuotes(getResult());
1520
1521 initTempDirectory();
1522
1523 // set the OpenModelicaLibrary variable.
1524 evalCommand("getModelicaPath()");
1525 OMCHelper::OpenModelicaLibrary = StringHandler::removeFirstLastQuotes(getResult());
1526 return true;
1527}
1528
1529
1530
1531void MOomc::initTempDirectory()
1532{
1533 // set the temp directory.
1534 QString tmpPath = Utilities::tempDirectory();
1535 QString cdResult;
1536 if (!QDir().exists(tmpPath))
1537 {
1538 if (LowTools::mkpath(tmpPath,false))
1539 cdResult = changeDirectory(tmpPath);
1540 }
1541 else
1542 cdResult = changeDirectory(tmpPath);
1543}
1544
1545void MOomc::stopServer()
1546{
1547 if(isStarted())
1548 // if( delegate_ )
1549 {
1550 qDebugQMessageLogger(nullptr, 0, nullptr).debug("Stoping moomc...");
1551 QString quit = "quit()";
1552 evalCommand(quit);
1553 InfoSender::instance()->send( Info("Quiting OMC...",ListInfo::NORMAL2));
1554 // evalMutex.lock();
1555 }
1556 mHasInitialized = false;
1557}
1558
1559bool MOomc::isStarted()
1560{
1561 return mHasInitialized;
1562}
1563
1564QString MOomc::getResult()
1565{
1566 return mResult.trimmed();
1567}
1568
1569//OmcCommunicator* MOomc::getCommunicator()
1570//{
1571// //return mCommunicator;
1572//}
1573
1574QString MOomc::changeDirectory(QString directory)
1575{
1576 QString correctedDir = QDir(directory).absolutePath();
1577 if (correctedDir.isEmpty())
1578 {
1579 evalCommand("cd()");
1580 }
1581 else
1582 {
1583 correctedDir = correctedDir.replace("\\", "/");
1584 evalCommand("cd(\"" + correctedDir + "\")");
1585 }
1586 return getResult();
1587}
1588
1589QString MOomc::getWorkingDirectory()
1590{
1591 evalCommand("cd()");
1592 QString path = getResult();
1593 path = path.remove("\"");
1594 return path;
1595}
1596
1597QString MOomc::getTempDirectory()
1598{
1599 evalCommand("getTempDirectoryPath()");
1600 QString path = getResult();
1601 path = path.remove("\"");
1602 return path;
1603}
1604
1605QFileInfo MOomc::getFileOfClass(QString _className)
1606{
1607 QString filePath = "";
1608 QString res = evalCommand("getClassInformation("+_className+")");
1609
1610 if(res.compare("Error",Qt::CaseInsensitive))
1611 {
1612 filePath = res.section(",",2,2);
1613 filePath.remove("\"");
1614 }
1615
1616 return QFileInfo(filePath);
1617}
1618
1619QString MOomc::runScript(QString scriptFile)
1620{
1621 scriptFile = scriptFile.replace("\\","/");
1622 QString commandText = "runScript(\"" + scriptFile +"\")";
1623 QString commandRes= evalCommand(commandText);
1624 return commandRes;
1625}
1626
1627QStringList MOomc::getClassesOfFile(QString _fileName)
1628{
1629
1630 QStringList loadedClasses= this->getClassNames();
1631
1632 QFileInfo fileInfo(_fileName);
1633 QFileInfo fileInfo2;
1634
1635 QStringList fileClasses;
1636
1637 for(int i=0;i<loadedClasses.size();i++)
1638 {
1639 fileInfo2 = QFileInfo(getFileOfClass(loadedClasses.at(i)));
1640
1641 if(fileInfo.absoluteFilePath()==fileInfo2.absoluteFilePath())
1642 fileClasses.append(loadedClasses.at(i));
1643 }
1644
1645 return fileClasses;
1646}
1647
1648
1649void MOomc::getInheritedComponents(QString parentClass, QStringList & names, QStringList & classes)
1650{
1651
1652 // First inherited classes
1653 QStringList firstInheritedClasses = getInheritedClasses(parentClass);
1654
1655
1656 int nbInheritance = firstInheritedClasses.size();
1657 QStringList curNames,curClasses;
1658 //call to getContainedComponents which will call this function (recursive algorithm)
1659 for(int i=0;i<nbInheritance;i++)
1660 {
1661 getContainedComponents(firstInheritedClasses.at(i),curNames,curClasses);
1662 names<<curNames;
1663 classes<<curClasses;
1664 }
1665}
1666
1667
1668QStringList MOomc::getElementInfos(QString parentClass)
1669{
1670 QString res = evalCommand("getElementsInfo("+parentClass+")");
1671 QStringList list;
1672 if(res == "Error" || res.size()<=2)
1673 return QStringList();
1674 else
1675 {
1676 res.remove("{");
1677 res.remove("}");
1678 res.remove(")");
1679 list = res.split("rec(",QString::SkipEmptyParts);
1680
1681 LowTools::removeWhiteSpaceStrings(list);
1682 }
1683
1684 return list;
1685}
1686
1687void MOomc::readElementInfos(QString parentClass,QStringList &packagesClasses,QStringList &modelsClasses,QStringList &recordNames,QStringList &compsNames,QStringList &compsClasses)
1688{
1689 QString msg;
1690 msg.sprintf("Reading class infos : %s",parentClass.toLatin1().data());
1691 InfoSender::instance()->send(Info(msg,ListInfo::OMCNORMAL2));
1692
1693 packagesClasses.clear();
1694 modelsClasses.clear();
1695 compsNames.clear();
1696 compsClasses.clear();
1697 recordNames.clear();
1698
1699 QStringList elementsInfos = getElementInfos(parentClass);
1700 QString elementInfos;
1701 QStringList fields;
1702
1703
1704 QString type;
1705 QString compClass;
1706 QString compName;
1707
1708 for(int iEl=0; iEl<elementsInfos.size();iEl++)
1709 {
1710 elementInfos = elementsInfos.at(iEl);
1711 fields = elementInfos.split(",");
1712
1713 // get element type
1714 type = getValueFromElementInfo(elementInfos,"elementtype");
1715
1716 // Package or Model
1717 if(type=="classdef")
1718 {
1719 //get classrestriction (MODEL or PACKAGE or RECORD)
1720 QString restr = getValueFromElementInfo(elementInfos,"classrestriction");
1721
1722 //get classname
1723 QString className = getValueFromElementInfo(elementInfos,"classname");
1724
1725 //add it
1726 if(restr.contains("MODEL"))
1727 {
1728 modelsClasses.push_back(className);
1729 QString msg;
1730 msg.sprintf("Adding model: %s, Type : %s",className.toLatin1().data(),restr.toLatin1().data());
1731 InfoSender::instance()->send(Info(msg,ListInfo::OMCNORMAL2));
1732 }
1733 if(restr.contains("PACKAGE"))
1734 {
1735 packagesClasses.push_back(className);
1736 QString msg;
1737 msg.sprintf("Adding package: %s, Type : %s",className.toLatin1().data(),restr.toLatin1().data());
1738 InfoSender::instance()->send(Info(msg,ListInfo::OMCNORMAL2));
1739 }
1740 if(restr.contains("RECORD"))
1741 {
1742 recordNames.push_back(className);
1743 QString msg;
1744 msg.sprintf("Adding record: %s, Type : %s",className.toLatin1().data(),restr.toLatin1().data());
1745 InfoSender::instance()->send(Info(msg,ListInfo::OMCNORMAL2));
1746 }
1747
1748
1749 }
1750
1751 // Component
1752 if(type=="component")
1753 {
1754 //get component class
1755 compClass = getValueFromElementInfo(elementInfos,"typename");
1756
1757 //get classname
1758 compName = getValueFromElementInfo(elementInfos,"names");
1759 compName.remove("{");
1760 compName.remove("}");
1761 compName = compName.split(",").at(0);
1762
1763 compsClasses.push_back(compClass);
1764 compsNames.push_back(compName);
1765 }
1766
1767 }
1768}
1769
1770QString MOomc::getValueFromElementInfo(QString elementInfoLine,QString fieldName)
1771{
1772
1773 QStringList fields = elementInfoLine.split(",");
1774 QRegExp regExp(".*"+fieldName+"=.*");
1775
1776 int iField=fields.indexOf(regExp);
1777 if(iField>-1)
1778 {
1779 try{
1780 QString value = fields.at(iField).section("=",1,1);
1781
1782 // removing whitespaces for non-path fields
1783 if(value.indexOf("\"")==-1)
1784 {
1785 value.remove(" ");
1786 }
1787 return value;
1788 }
1789 catch(std::exception &e)
1790 {
1791 return QString();
1792 }
1793 }
1794 return QString();
1795}