take care link in xcos diagram positionning
[scilab.git] / scilab / modules / xcos / src / java / org / scilab / modules / xcos / io / BlockReader.java
1 /*
2  * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
3  * Copyright (C) 2009 - DIGITEO - Allan SIMON
4  * Copyright (C) 2009 - DIGITEO - Bruno JOFRET
5  * 
6  * This file must be used under the terms of the CeCILL.
7  * This source file is licensed as described in the file COPYING, which
8  * you should have received as part of this distribution.  The terms
9  * are also available at
10  * http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt
11  *
12  */
13
14 package org.scilab.modules.xcos.io;
15
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
19
20 import ncsa.hdf.hdf5lib.exceptions.HDF5Exception;
21 import ncsa.hdf.hdf5lib.exceptions.HDF5LibraryException;
22
23 import org.scilab.modules.gui.messagebox.MessageBox;
24 import org.scilab.modules.gui.messagebox.ScilabMessageBox;
25 import org.scilab.modules.hdf5.read.H5Read;
26 import org.scilab.modules.hdf5.scilabTypes.ScilabBoolean;
27 import org.scilab.modules.hdf5.scilabTypes.ScilabDouble;
28 import org.scilab.modules.hdf5.scilabTypes.ScilabList;
29 import org.scilab.modules.hdf5.scilabTypes.ScilabMList;
30 import org.scilab.modules.hdf5.scilabTypes.ScilabString;
31 import org.scilab.modules.hdf5.scilabTypes.ScilabTList;
32 import org.scilab.modules.hdf5.scilabTypes.ScilabType;
33 import org.scilab.modules.xcos.block.BasicBlock;
34 import org.scilab.modules.xcos.block.TextBlock;
35 import org.scilab.modules.xcos.port.BasicPort;
36 import org.scilab.modules.xcos.port.BasicPort.DataType;
37 import org.scilab.modules.xcos.port.command.CommandPort;
38 import org.scilab.modules.xcos.port.control.ControlPort;
39 import org.scilab.modules.xcos.port.input.ExplicitInputPort;
40 import org.scilab.modules.xcos.port.input.ImplicitInputPort;
41 import org.scilab.modules.xcos.port.input.InputPort;
42 import org.scilab.modules.xcos.port.output.ExplicitOutputPort;
43 import org.scilab.modules.xcos.port.output.ImplicitOutputPort;
44 import org.scilab.modules.xcos.port.output.OutputPort;
45 import org.scilab.modules.xcos.utils.XcosMessages;
46
47 import com.mxgraph.model.mxGeometry;
48 import com.mxgraph.util.mxConstants;
49
50 public class BlockReader {
51
52
53         private static void INFO(String msg) {
54                 //System.err.println("[INFO] BlockReader : "+msg);
55         }
56
57         private static void WARNING(String msg) {
58                 //System.err.println("[WARNING] BlockReader : "+msg);
59         }
60
61
62         private static void DEBUG(String msg) {
63                 //System.err.println("[DEBUG] BlockReader : "+msg);
64         }
65
66         public static HashMap<String, Object> convertMListToDiagram(ScilabMList data) {
67
68                 try {
69                         isAValidScs_mStructure(data);
70                 } catch (WrongTypeException e2) {
71                         WARNING("Invalid data structure !!");
72                         e2.printStackTrace();
73                         return null;
74                 } catch (WrongStructureException e) {
75                         WARNING("Invalid data structure !!");
76                         e.printStackTrace();
77                         return null;
78                 } catch (VersionMismatchException e) {
79                         MessageBox messageBox = ScilabMessageBox.createMessageBox();
80                         messageBox.setTitle(XcosMessages.FAIL_LOADING_DIAGRAM);
81                         String[] message = {"Unknow Diagram Version : "+e.getVersion(), "Will try to continue..."};
82                         messageBox.setMessage(message);
83                         messageBox.displayAndWait();
84                 } 
85
86                 HashMap<String, Object> result = new HashMap<String, Object>();
87                 HashMap<Integer, BasicBlock> indexedBlock = new HashMap<Integer, BasicBlock>(); 
88
89                 List<BasicBlock> blocks = new ArrayList<BasicBlock>();
90                 List<TextBlock> textBlocks = new ArrayList<TextBlock>();
91                 HashMap<String, Object> links = new HashMap<String, Object>();
92
93                 double minX = Double.MAX_VALUE;
94                 double minY = Double.MAX_VALUE;
95
96                 int nbObjs = getNbObjs(data);
97
98                 // Read diagrams properties
99                 HashMap<String, Object> properties = null;
100                 try {
101                         properties = fillDiagrammProperties((ScilabTList) data.get(1));
102                 } catch (WrongStructureException e1) {
103                         e1.printStackTrace();
104                         return null;
105                 } catch (WrongTypeException e1) {
106                         e1.printStackTrace();
107                         return null;
108                 }
109                 result.put("Properties", properties);
110
111                 // Read all Blocks
112                 for (int i = 0; i < nbObjs; ++i) {
113                         try {
114                                 if (isBlock(data, i)) {
115                                         INFO("Reading Block " + i);
116                                         BasicBlock currentBlock = fillBlockStructure(getBlockAt(data, i));
117                                         currentBlock.setOrdering(i);
118                                         indexedBlock.put(i + 1, currentBlock);
119
120                                         //tips to set block direction at load "BLOCK_f;direction=east" 
121                                         currentBlock.setStyle(currentBlock.getInterfaceFunctionName() + currentBlock.getStyle());
122                                         //currentBlock.setValue(currentBlock.getInterfaceFunctionName());
123
124                                         blocks.add(currentBlock);
125                                         minX = Math.min(minX, currentBlock.getGeometry().getX());
126                                         minY = Math.min(minY, currentBlock.getGeometry().getY()/* - currentBlock.getGeometry().getHeight()*/);
127                                 }else if(isLink(data, i)){
128                                         System.err.println("Link !");
129                                         //for minX and minY
130                                 }
131                         } catch (BlockReaderException e) {
132                                 WARNING(" Fail reading Block " + (i + 1));
133                                 e.printStackTrace();
134                                 return null;
135                         }
136                 }
137                 
138                 List<BasicPort[]> linkPorts = new ArrayList<BasicPort[]>(); 
139                 List<double[][]> linkPoints = new ArrayList<double[][]>(); 
140                 // Read all Links
141                 for (int i = 0; i < nbObjs; ++i) {
142                         if (isLink(data, i)) {
143                                 try {
144
145                                         INFO("Reading Link " + (i + 1));
146                                         ScilabMList link = getLinkAt(data, i);
147                                         BasicPort startingPort = null;
148                                         BasicPort endingPort = null;
149
150                                         int startBlockIndex = getStartBlockIndex(link);//6.0
151                                         int startPortIndex = getStartPortIndex(link);//6.1
152                                         PortType startPortType = getStartPortType(link);//5.1
153
154                                         int endBlockIndex = getEndBlockIndex(link); // 7.0
155                                         int endPortIndex = getEndPortIndex(link);//7.1
156                                         PortType endPortType = getEndPortType(link);//5.1
157
158                                         DEBUG("Start : [" + startBlockIndex + ", " + startPortIndex + ", " + startPortType + "]");
159                                         DEBUG("End : [" + endBlockIndex + ", " + endPortIndex + ", " + endPortType + "]");
160                                         switch (startPortType) {
161                                         case INPUT:
162                                                 startingPort = indexedBlock.get(startBlockIndex).getAllInputPorts().get(startPortIndex - 1);
163                                                 break;
164                                         case OUTPUT:
165                                                 startingPort = indexedBlock.get(startBlockIndex).getAllOutputPorts().get(startPortIndex - 1);
166                                                 break;
167                                         case COMMAND:
168                                                 startingPort = indexedBlock.get(startBlockIndex).getAllCommandPorts().get(startPortIndex - 1);
169                                                 break;
170                                         case CONTROL:
171                                                 startingPort = indexedBlock.get(startBlockIndex).getAllControlPorts().get(startPortIndex - 1);
172                                                 break;
173                                         }
174
175                                         switch (endPortType) {
176                                         case INPUT:
177                                                 endingPort = indexedBlock.get(endBlockIndex).getAllInputPorts().get(endPortIndex - 1);
178                                                 break;
179                                         case OUTPUT:
180                                                 endingPort = indexedBlock.get(endBlockIndex).getAllOutputPorts().get(endPortIndex - 1);
181                                                 break;
182                                         case COMMAND:
183                                                 endingPort = indexedBlock.get(endBlockIndex).getAllCommandPorts().get(endPortIndex - 1);
184                                                 break;
185                                         case CONTROL:
186                                                 endingPort = indexedBlock.get(endBlockIndex).getAllControlPorts().get(endPortIndex - 1);
187                                                 break;
188                                         }
189
190                                         BasicPort[] startAndEnd = {startingPort, endingPort};
191                                         linkPorts.add(startAndEnd);
192
193                                         //First and last value -> start and end point
194                                         if(link.get(1).getHeight() > 2){
195                                                 double[][] linkPoint = new double[link.get(1).getHeight() - 2][2]; 
196                                                 for(int point = 0 ; point < link.get(1).getHeight() - 2 ; point++){
197                                                         linkPoint[point] = getLinkPoint(link, point);
198                                                         minX = Math.min(minX, linkPoint[point][0]);
199                                                         minY = Math.min(minY, linkPoint[point][1]);
200                                                 }
201                                                 linkPoints.add(linkPoint);
202                                         }
203                                         else{
204                                                 linkPoints.add(null);
205                                         }
206                                 } catch (BlockReaderException e) {
207                                         WARNING(" Fail reading Link " + (i + 1));
208                                         e.printStackTrace();
209                                         return null;
210                                 }
211                         }
212                 }
213
214                 // Read all Labels
215                 for (int i = 0; i < nbObjs; ++i) {
216                         try{
217                                 if (isLabel(data, i)) {
218                                         //TODO
219                                         INFO("Reading Label " + i);
220                                         TextBlock currentText = fillTextStructure(getBlockAt(data, i));
221                                         currentText.setOrdering(i);
222
223                                         //tips to set block direction at load "BLOCK_f;direction=east" 
224                                         //currentText.setStyle(currentText.getInterfaceFunctionName() + currentText.getStyle());
225                                         if (isEmptyField(currentText.getRealParameters())) {
226                                             currentText.setValue("");
227                                         }
228                                         else {
229                                             currentText.setValue(((ScilabString)currentText.getRealParameters()).getData()[0][0]);
230                                         }
231                                         
232                                         textBlocks.add(currentText);
233                                         minX = Math.min(minX, currentText.getGeometry().getX());
234                                         minY = Math.min(minY, currentText.getGeometry().getY()/* - currentBlock.getGeometry().getHeight()*/);
235                                 }else{
236                                         //for minX and minY
237                                 }
238                         } catch (BlockReaderException e) {
239                                 WARNING(" Fail reading Label " + (i + 1));
240                                 e.printStackTrace();
241                                 return null;
242                         }
243
244                 }
245
246                 double offsetX = -minX + 20;
247                 double offsetY = -minY + 20;
248
249                 
250                 for (int i = 0; i < blocks.size(); ++i) {
251                         blocks.get(i).getGeometry().setX(blocks.get(i).getGeometry().getX() + offsetX);
252                         blocks.get(i).getGeometry().setY(blocks.get(i).getGeometry().getY() + offsetY);
253                 }
254
255                 for (int i = 0; i < linkPoints.size(); i++) {
256                         if(linkPoints.get(i) != null){
257                                 System.err.println("");
258                                 for (int j = 0; j < linkPoints.get(i).length; j++) {
259                                         linkPoints.get(i)[j][0] += offsetX;
260                                         linkPoints.get(i)[j][1] += offsetY;
261                                         System.err.println("(" + linkPoints.get(i)[j][0] + "," + linkPoints.get(i)[j][1] + ")");
262                                 }
263                         }
264                 }
265
266                 for (int i = 0; i < textBlocks.size(); ++i) {
267                         textBlocks.get(i).getGeometry().setX(textBlocks.get(i).getGeometry().getX() + offsetX);
268                         textBlocks.get(i).getGeometry().setY(textBlocks.get(i).getGeometry().getY() + offsetY);
269                 }
270
271                 //put all data
272                 result.put("Blocks", blocks);
273                 result.put("TextBlocks", textBlocks);
274                 links.put("Ports", linkPorts);
275                 links.put("Points", linkPoints);
276                 result.put("Links", links);
277
278                 result.put("Blocks", blocks);
279
280                 return result;
281         }
282
283         public static HashMap<String, Object> readDiagramFromFile(String hdf5File) {
284                 ScilabMList data = new ScilabMList();
285
286                 try {
287                         int fileId = H5Read.openFile(hdf5File);
288                         if (fileId == -1) { 
289                                 throw new WrongStructureException();
290                         }
291                         H5Read.readDataFromFile(fileId, data);
292                         H5Read.closeFile(fileId);
293
294                         return convertMListToDiagram(data);
295                 } catch (HDF5LibraryException e) {
296                         return null;
297                 } catch (WrongStructureException e) {
298                         return null;
299                 } catch (HDF5Exception e) {
300                         return null;
301                 }
302         }
303
304         private static int getStartBlockIndex(ScilabMList link) throws WrongTypeException {
305                 if (!(link.get(6) instanceof ScilabDouble)) { throw new WrongTypeException(); }
306
307                 return (int) ((ScilabDouble) link.get(6)).getRealPart()[0][0];
308         }
309
310         private static double[] getLinkPoint(ScilabMList link, int index) throws WrongTypeException {
311                 if (!(link.get(1) instanceof ScilabDouble)) { 
312                         throw new WrongTypeException(); 
313                 }
314
315
316                 if(index < link.get(1).getHeight() - 2){
317
318                         double[] ret = new double[2];
319                         ret[0] = ((ScilabDouble)link.get(1)).getRealPart()[index + 1][0];
320                         ret[1] = -((ScilabDouble)link.get(2)).getRealPart()[index + 1][0];
321                         return ret;
322                 }
323                 return null;
324         }
325
326         private static int getStartPortIndex(ScilabMList link) throws WrongTypeException {
327                 if (!(link.get(6) instanceof ScilabDouble)) { throw new WrongTypeException(); }
328
329                 return (int) ((ScilabDouble) link.get(6)).getRealPart()[0][1];
330         }
331
332         private static PortType getStartPortType(ScilabMList link) throws WrongTypeException {
333                 if (!(link.get(5) instanceof ScilabDouble)) { throw new WrongTypeException(); }
334                 if (!(link.get(6) instanceof ScilabDouble)) { throw new WrongTypeException(); }
335
336                 // ct  = [color, type] 1 : data , -1 event
337                 int type = (int) ((ScilabDouble) link.get(5)).getRealPart()[0][1];
338                 // from = [ blockId, portNumber, I/O] 0 : Output , 1 : Input
339                 int io = (int) ((ScilabDouble) link.get(6)).getRealPart()[0][2];
340
341                 return getPortType(type, io);
342         }
343
344         private static int getEndBlockIndex(ScilabMList link) throws WrongTypeException {
345                 if (!(link.get(7) instanceof ScilabDouble)) { throw new WrongTypeException(); }
346
347                 return (int) ((ScilabDouble) link.get(7)).getRealPart()[0][0];
348         }
349
350         private static int getEndPortIndex(ScilabMList link) throws WrongTypeException {
351                 if (!(link.get(7) instanceof ScilabDouble)) { throw new WrongTypeException(); }
352
353                 return (int) ((ScilabDouble) link.get(7)).getRealPart()[0][1];
354         }
355
356         private static PortType getEndPortType(ScilabMList link) throws WrongTypeException {
357                 if (!(link.get(5) instanceof ScilabDouble)) { throw new WrongTypeException(); }
358                 if (!(link.get(7) instanceof ScilabDouble)) { throw new WrongTypeException(); }
359
360                 // ct  = [color, type] 1 : data , -1 event
361                 int type = (int) ((ScilabDouble) link.get(5)).getRealPart()[0][1];
362                 // from = [ blockId, portNumber, I/O] 0 : Output , 1 : Input
363                 int io = (int) ((ScilabDouble) link.get(7)).getRealPart()[0][2];
364
365                 return getPortType(type, io);
366         }
367
368         private static PortType getPortType(int type, int io) throws WrongTypeException {
369                 if (type == 1 && io == 0) { return PortType.OUTPUT; }
370                 if (type == 1 && io == 1) { return PortType.INPUT; }
371                 if (type == 2 && io == 0) { return PortType.OUTPUT; }
372                 if (type == 2 && io == 1) { return PortType.INPUT; }
373                 if (type == -1 && io == 0) { return PortType.COMMAND; }
374                 if (type == -1 && io == 1) { return PortType.CONTROL; }
375
376                 throw new WrongTypeException();
377         }
378
379
380         public static BasicBlock readBlockFromFile( String hdf5file ) {
381                 ScilabMList data = new ScilabMList();
382                 BasicBlock newBlock = BasicBlock.createBlock("FAILED !!");
383
384                 try {
385                         int fileId = H5Read.openFile(hdf5file);
386                         //if (fileId == -1) { throw new WrongStructureException(); }
387                         H5Read.readDataFromFile(fileId, data);
388                         H5Read.closeFile(fileId);
389                         newBlock = fillBlockStructure(data);
390                         newBlock.setStyle(newBlock.getInterfaceFunctionName()+newBlock.getStyle());
391                         newBlock.setGeometry(new mxGeometry(newBlock.getGeometry().getX(),
392                                         newBlock.getGeometry().getY(),
393                                         newBlock.getGeometry().getWidth(),
394                                         newBlock.getGeometry().getHeight()));
395                 }
396                 catch (Exception e) {
397                         // TODO Auto-generated catch block
398                         DEBUG("FAIL importing "+hdf5file);
399                         e.printStackTrace();
400                 }
401                 finally {
402                         return  newBlock;
403                 }
404         }
405
406         public static int getNbObjs(ScilabMList data) {
407                 return ((ScilabList) data.get(2)).size();
408         }
409
410         private static boolean isBlock(ScilabMList data , int index) {
411                 ScilabMList object = (ScilabMList) ((ScilabList) data.get(2)).get(index);
412
413                 if(object.get(0) instanceof ScilabString && 
414                                 ((ScilabString) object.get(0)).getData()[0][0].equals("Block")) {
415                         return true;
416                 }
417                 return false;
418         }
419
420         public static boolean isLabel(ScilabMList data , int index){
421                 ScilabMList object = (ScilabMList) ((ScilabList) data.get(2)).get(index);
422                 if(object.get(0) instanceof ScilabString && 
423                                 ((ScilabString) object.get(0)).getData()[0][0].equals("Text")) {
424                         
425                         return true;
426                 }else{
427                         return false;
428                 }
429                 
430         }
431         
432         private static boolean isLink(ScilabMList data , int index) {
433                 ScilabMList object = (ScilabMList) ((ScilabList) data.get(2)).get(index);
434
435                 if(object.get(0) instanceof ScilabString && 
436                                 ((ScilabString) object.get(0)).getData()[0][0].equals("Link")) {
437                         return true;
438                 }
439                 return false;
440         }
441
442         public static ScilabMList getBlockAt (ScilabMList data , int index ){
443                 return (ScilabMList)((ScilabList)data.get(2)).get(index);
444         }
445
446         public static ScilabMList getLinkAt (ScilabMList data , int index ){
447                 return (ScilabMList)((ScilabList)data.get(2)).get(index);
448         }
449
450         public static String[] getNameOfFieldsInStructure (ScilabMList structure ){
451                 return ((ScilabString)structure.get(0)).getData()[0];
452         }
453
454         private static String getBlockInterfaceName (ScilabMList blockFields ){
455                 return ((ScilabString)blockFields.get(3)).getData()[0][0];
456         }
457
458         private static String getBlockSimulationFunctionName(ScilabMList blockFields) {
459                 return ((ScilabString)blockFields.get(1)).getData()[0][0];
460         }
461
462         private static void isAValidScs_mStructure (ScilabMList data) throws WrongTypeException, VersionMismatchException, WrongStructureException {
463
464                 int numberOfFieldInScs_m = 4 ;
465                 String[] realNameOfScs_mFields = new String[]{"diagram", "props" , "objs" , "version"};
466                 String realScicosVersion = new String ("scicos4.2");
467
468                 // we test if the structure as enough field
469                 if (data.size() < numberOfFieldInScs_m ) { throw new WrongStructureException(); }
470
471                 // the first field is a list of string containing the name of the other fields
472                 if (!(data.get(0) instanceof ScilabString)) { throw new WrongTypeException(); }
473
474                 String[] nameOfScs_mFields = getNameOfFieldsInStructure(data);
475                 // check if all the expecting field's name are present
476                 if (nameOfScs_mFields.length < numberOfFieldInScs_m ) { throw new WrongStructureException(); }
477                 for (int i = 0 ; i < numberOfFieldInScs_m ; i++) {
478                         if (!nameOfScs_mFields[i].equals(realNameOfScs_mFields[i])) {
479                                 throw new WrongStructureException();
480                         }
481                 }
482
483                 // the second field must contain list of props
484                 if (!(data.get(1) instanceof ScilabTList)) { throw new WrongTypeException(); } 
485
486                 // the second field must contain list of props
487                 if (!(data.get(1) instanceof ScilabTList)) { throw new WrongTypeException(); }
488
489                 // the third field must contains lists of blocks and links 
490                 if (!( data.get(2) instanceof ScilabList)) { throw new WrongTypeException(); }
491
492                 // the last field must contain the scicos version used 
493                 if (!(data.get(3) instanceof ScilabString)) { throw new WrongTypeException(); } 
494
495                 String scicosVersion = ((ScilabString)data.get(3)).getData()[0][0];
496                 if(! scicosVersion.equals(realScicosVersion) ) { throw new VersionMismatchException(scicosVersion); }
497         }
498
499         private static boolean isEmptyField(ScilabType object) {
500                 if (object instanceof ScilabDouble && ((ScilabDouble) object).isEmpty()) {
501                         return true;
502                 }
503                 if (object instanceof ScilabList && ((ScilabList) object).isEmpty()) {
504                         return true;
505                 }
506                 return false;
507         }
508
509         private static HashMap<String, Object> fillDiagrammProperties(ScilabTList params) throws WrongStructureException, WrongTypeException {
510                 HashMap<String, Object> diagramProperties = new HashMap<String, Object>();
511
512                 String[] propsFields = {"params", "wpar", "title", "tol", "tf", "context", "void1", "options", "void2", "void3", "doc"};
513                 // we test if the structure as enough field
514                 if(params.size() != propsFields.length) { throw new WrongStructureException(); }
515
516                 // check if all fields are present
517                 if (!(params.get(0) instanceof ScilabString)) { throw new WrongStructureException(); }
518                 String[] nameOfScs_mFields = ((ScilabString)params.get(0)).getData()[0];
519
520                 // check if all the expecting field's name are present
521                 if (nameOfScs_mFields.length != propsFields.length ) { throw new WrongStructureException(); }
522                 for (int i = 0 ; i < propsFields.length ; i++){
523                         if (!nameOfScs_mFields[i].equals(propsFields[i])) {
524                                 throw new WrongStructureException();
525                         }
526                 }
527
528                 // wpar
529                 if(!(params.get(1) instanceof ScilabDouble)) { throw new WrongTypeException(); }
530
531                 // title
532                 if(!(params.get(2) instanceof ScilabString)) { throw new WrongTypeException(); }
533                 diagramProperties.put("title", ((ScilabString) params.get(2)).getData()[0][0]);
534
535                 //tol
536                 // !! WARNING !! parameters can be stored row or column wise
537                 if(!(params.get(3) instanceof ScilabDouble)) { throw new WrongTypeException(); }
538                 if( params.get(3).getHeight() >= params.get(3).getWidth()) {
539                         diagramProperties.put("integratorAbsoluteTolerance", ((ScilabDouble) params.get(3)).getRealPart()[0][0]);
540                         diagramProperties.put("integratorRelativeTolerance", ((ScilabDouble) params.get(3)).getRealPart()[1][0]);
541                         diagramProperties.put("toleranceOnTime", ((ScilabDouble) params.get(3)).getRealPart()[2][0]);
542                         diagramProperties.put("maxIntegrationTimeinterval", ((ScilabDouble) params.get(3)).getRealPart()[3][0]);
543                         diagramProperties.put("realTimeScaling", ((ScilabDouble) params.get(3)).getRealPart()[4][0]);
544                         diagramProperties.put("solver", ((ScilabDouble) params.get(3)).getRealPart()[5][0]);
545                         if(params.get(3).getHeight() >= 7) {
546                                 diagramProperties.put("maximumStepSize", ((ScilabDouble) params.get(3)).getRealPart()[6][0]);
547                         }
548                         else {
549                                 diagramProperties.put("maximumStepSize", 0.0);
550                         }
551                 }
552                 else {
553                         diagramProperties.put("integratorAbsoluteTolerance", ((ScilabDouble) params.get(3)).getRealPart()[0][0]);
554                         diagramProperties.put("integratorRelativeTolerance", ((ScilabDouble) params.get(3)).getRealPart()[0][1]);
555                         diagramProperties.put("toleranceOnTime", ((ScilabDouble) params.get(3)).getRealPart()[0][2]);
556                         diagramProperties.put("maxIntegrationTimeinterval", ((ScilabDouble) params.get(3)).getRealPart()[0][3]);
557                         diagramProperties.put("realTimeScaling", ((ScilabDouble) params.get(3)).getRealPart()[0][4]);
558                         diagramProperties.put("solver", ((ScilabDouble) params.get(3)).getRealPart()[0][5]);
559                         if(params.get(3).getWidth() >= 7) {
560                                 diagramProperties.put("maximumStepSize", ((ScilabDouble) params.get(3)).getRealPart()[0][6]);
561                         }
562                         else {
563                                 diagramProperties.put("maximumStepSize", 0.0);
564                         }
565                 }
566
567                 //tf
568                 if(!(params.get(4) instanceof ScilabDouble)) { throw new WrongTypeException(); }
569                 diagramProperties.put("finalIntegrationTime", ((ScilabDouble) params.get(4)).getRealPart()[0][0]);
570
571                 //context
572                 if (!(params.get(5) instanceof ScilabString) && !isEmptyField(params.get(5))) {
573                         throw new WrongTypeException();
574                 }
575                 ArrayList<String> context =  new ArrayList<String>();
576                 if( params.get(5).getHeight() >= params.get(5).getWidth()) {
577                         for (int i = 0; i < params.get(5).getHeight(); i++) {
578                                 context.add(((ScilabString) params.get(5)).getData()[i][0] + ";");
579                         }
580                 } else {
581                         for (int i = 0; i < params.get(5).getWidth(); i++) {
582                                 context.add(((ScilabString) params.get(5)).getData()[0][i] + ";");
583                         }
584
585                 }
586                 diagramProperties.put("context", context.toArray( new String[context.size()] ));
587
588                 //void1
589                 if(!isEmptyField(params.get(6))) { throw new WrongTypeException(); }
590
591                 //options
592                 if(!(params.get(7) instanceof ScilabTList)) { throw new WrongTypeException(); }
593
594                 //void2
595                 if(!isEmptyField(params.get(8))) { throw new WrongTypeException(); }
596
597                 //void3
598                 if(!isEmptyField(params.get(9))) { throw new WrongTypeException(); }
599
600                 //doc
601                 if(!(params.get(10) instanceof ScilabList) && !isEmptyField(params.get(10))) { throw new WrongTypeException(); }
602
603                 return diagramProperties;
604         }
605         
606         private static TextBlock fillTextStructure(ScilabMList blockFields) throws WrongStructureException, WrongTypeException {
607                 String[] realNameOfTextFields = {"Text", "graphics" , "model" , "void" , "gui"};
608                 
609                 TextBlock newBlock = (TextBlock) BasicBlock.createBlock("TEXT_f");
610                 // we test if the structure as enough field
611                 if (blockFields.size() != realNameOfTextFields.length ) { throw new WrongStructureException(); }
612                 
613                 // check if all fields are present
614                 if (!(blockFields.get(0) instanceof ScilabString)) { throw new WrongStructureException(); }
615                 String[] nameOfScs_mFields = ((ScilabString)blockFields.get(0)).getData()[0];
616                 
617
618                 // check if all the expecting field's name are present
619                 if (nameOfScs_mFields.length != realNameOfTextFields.length ) { throw new WrongStructureException(); }
620                 for (int i = 0 ; i < realNameOfTextFields.length ; i++){
621                         if (!nameOfScs_mFields[i].equals(realNameOfTextFields[i])) {
622                                 throw new WrongStructureException();
623                         }
624                 }
625                 
626                 // the second field must contain list of all graphic property (how the block will be displayed )
627                 if (!(blockFields.get(1) instanceof ScilabMList)) { throw new WrongTypeException(); }
628                 fillGraphicsStructure( blockFields, newBlock);
629
630
631                 // the third field must contains all the informations needed to compile the block
632                 if (!(blockFields.get(2) instanceof ScilabMList)) { throw new WrongTypeException(); }
633                 fillTextModelStructure(blockFields, newBlock);
634                 
635                 return newBlock ;
636                 
637         }
638         
639         
640         private static BasicBlock  fillBlockStructure(ScilabMList blockFields) throws WrongStructureException, WrongTypeException {
641                 String[] realNameOfBlockFields = {"Block", "graphics" , "model" , "gui" , "doc"};
642
643                 // we test if the structure as enough field
644                 if (blockFields.size() != realNameOfBlockFields.length ) { throw new WrongStructureException(); }
645
646                 // check if all fields are present
647                 if (!(blockFields.get(0) instanceof ScilabString)) { throw new WrongStructureException(); }
648                 String[] nameOfScs_mFields = ((ScilabString)blockFields.get(0)).getData()[0];
649
650                 // check if all the expecting field's name are present
651                 if (nameOfScs_mFields.length != realNameOfBlockFields.length ) { throw new WrongStructureException(); }
652                 for (int i = 0 ; i < realNameOfBlockFields.length ; i++){
653                         if (!nameOfScs_mFields[i].equals(realNameOfBlockFields[i])) {
654                                 throw new WrongStructureException();
655                         }
656                 }
657
658
659                 // !! WARNING !! create block with different type depending on the interfaceFunction name.
660                 // the fourth field must contain the name of the interface function
661                 if (!(blockFields.get(3) instanceof ScilabString)) { throw new WrongTypeException(); } 
662                 BasicBlock newBlock = BasicBlock.createBlock(getBlockInterfaceName (blockFields));
663                 //newBlock.setValue(getBlockInterfaceName (blockFields));
664                 newBlock.setInterfaceFunctionName( getBlockInterfaceName (blockFields) );
665
666                 // the second field must contain list of all graphic property (how the block will be displayed )
667                 if (!(blockFields.get(1) instanceof ScilabMList)) { throw new WrongTypeException(); }
668                 fillGraphicsStructure( blockFields, newBlock);
669
670
671                 // the third field must contains all the informations needed to compile the block
672                 if (!(blockFields.get(2) instanceof ScilabMList)) { throw new WrongTypeException(); }
673                 fillModelStructure(blockFields, newBlock);
674
675                 // the last field must contain a list of nothing aka scicos doc
676                 if (!(blockFields.get(4) instanceof ScilabList) && !isEmptyField(blockFields.get(4))) { throw new WrongTypeException(); }
677
678                 return newBlock;
679         }
680
681         public static void fillGraphicsStructure (ScilabMList blockFields ,BasicBlock newBlock ) throws WrongTypeException, WrongStructureException{
682
683                 ScilabMList graphicsStructure =(ScilabMList)blockFields.get(1);
684
685                 String[] realNameOfStructureFields = new String[]{"graphics"    ,"orig" ,"sz"   ,"flip","theta","exprs","pin","pout","pein","peout","gr_i","id","in_implicit","out_implicit"};
686
687                 int numberOfFieldInStructure = realNameOfStructureFields.length;
688
689                 // we test if the structure as enough field
690                 if (graphicsStructure.size() != numberOfFieldInStructure ) { throw new WrongStructureException(); }
691
692                 // the first field is a list of string containing the name of the other fields
693                 if (!(graphicsStructure.get(0) instanceof ScilabString)) { throw new WrongTypeException(); }
694                 String[] nameOfStructureFields = getNameOfFieldsInStructure(graphicsStructure);
695
696                 // check if all the expecting field's name are present
697                 if (nameOfStructureFields.length == numberOfFieldInStructure ){
698                         for (int i = 0 ; i < numberOfFieldInStructure ; i++){
699                                 if ( !nameOfStructureFields[i].equals(realNameOfStructureFields[i])) {
700                                         throw new WrongStructureException();
701                                 }
702                         }
703                 }
704
705                 // orig : must contain the coord of the block
706                 if (!(graphicsStructure.get(1) instanceof ScilabDouble)) { throw new WrongTypeException(); }
707                 // !!! WARNING !!!
708                 // scicos can store [x,y] or [x;y] watch out !!!!
709                 double x = 0;
710                 double y = 0;
711                 if (graphicsStructure.get(1).getHeight() == 1 &&  graphicsStructure.get(1).getWidth() == 2) {
712                         x = ((ScilabDouble) graphicsStructure.get(1)).getRealPart()[0][0];
713                         y = ((ScilabDouble) graphicsStructure.get(1)).getRealPart()[0][1];
714                 }
715                 else {
716                         if (graphicsStructure.get(1).getHeight() == 2 &&  graphicsStructure.get(1).getWidth() == 1) {
717                                 x = ((ScilabDouble) graphicsStructure.get(1)).getRealPart()[0][0];
718                                 y = ((ScilabDouble) graphicsStructure.get(1)).getRealPart()[1][0]; 
719                         }
720                 }
721                 // Multiply size by 40 for better visualisation
722                 int sizeFactor = 1;
723                 newBlock.getGeometry().setX(sizeFactor * x);
724                 newBlock.getGeometry().setY(-sizeFactor * y);
725
726                 // sz : must contains the size of the block
727                 if (!(graphicsStructure.get(2) instanceof ScilabDouble)) { throw new WrongTypeException(); }
728                 // !!! WARNING !!!
729                 // scicos can store [width, height] or [width; height] watch out !!!!
730                 // sz = [width, height]
731                 double width = 0;
732                 double height = 0;
733                 if (graphicsStructure.get(2).getHeight() == 1 &&  graphicsStructure.get(2).getWidth() == 2) {
734                         width = ((ScilabDouble) graphicsStructure.get(2)).getRealPart()[0][0];
735                         height = ((ScilabDouble) graphicsStructure.get(2)).getRealPart()[0][1];
736                 }
737                 else {
738                         if (graphicsStructure.get(2).getHeight() == 2 &&  graphicsStructure.get(2).getWidth() == 1) {
739                                 width = ((ScilabDouble) graphicsStructure.get(2)).getRealPart()[0][0];
740                                 height = ((ScilabDouble) graphicsStructure.get(2)).getRealPart()[1][0]; 
741                         }
742                 }
743
744                 // Multiply size by 2 and fix 20 as minimal size so I can see "hidden" blocks
745                 mxGeometry geom = newBlock.getGeometry();
746                 geom.setWidth(Math.max(sizeFactor * width, 40));
747                 geom.setHeight(Math.max(sizeFactor * height, 40));
748                 newBlock.setGeometry(geom);
749
750                 // Adjust block cause Scilab(0,0) is bottom left
751                 newBlock.getGeometry().setY(newBlock.getGeometry().getY() - newBlock.getGeometry().getHeight()); 
752
753                 if (!(graphicsStructure.get(3) instanceof ScilabBoolean)){// flip
754                         throw new WrongTypeException();
755                 }
756                 
757                 if(((ScilabBoolean)graphicsStructure.get(3)).getData()[0][0] == false){
758                         newBlock.setFlip(true);
759                 }else{
760                         newBlock.setFlip(false);
761                 }
762                 
763                 if (!(graphicsStructure.get(4) instanceof ScilabDouble)){// theta
764                         throw new WrongTypeException();
765                 }
766
767                 int theta = (int)((ScilabDouble)graphicsStructure.get(4)).getRealPart()[0][0];
768                 
769                 //convert negative value
770                 theta += 360;
771                 theta %= 360;
772                 
773                 if(theta > 315 || theta <= 45){
774                         if(newBlock.getFlip()){
775                                 newBlock.setStyle(newBlock.getStyle() + ";" + mxConstants.STYLE_DIRECTION + "=" + mxConstants.DIRECTION_WEST);
776                         }else{
777                                 newBlock.setStyle(newBlock.getStyle() + ";" + mxConstants.STYLE_DIRECTION + "=" + mxConstants.DIRECTION_EAST);
778                         }
779                 }else if(theta > 45 && theta <= 135){
780                         if(newBlock.getFlip()){
781                                 newBlock.setStyle(newBlock.getStyle() + ";" + mxConstants.STYLE_DIRECTION + "=" + mxConstants.DIRECTION_SOUTH);
782                         }else{
783                                 newBlock.setStyle(newBlock.getStyle() + ";" + mxConstants.STYLE_DIRECTION + "=" + mxConstants.DIRECTION_NORTH);
784                         }
785                 }else if(theta > 135 && theta <= 225){
786                         if(newBlock.getFlip()){
787                                 newBlock.setStyle(newBlock.getStyle() + ";" + mxConstants.STYLE_DIRECTION + "=" + mxConstants.DIRECTION_EAST);
788                         }else{
789                                 newBlock.setStyle(newBlock.getStyle() + ";" + mxConstants.STYLE_DIRECTION + "=" + mxConstants.DIRECTION_WEST);
790                         }
791                 }else if(theta > 225 && theta <= 315){
792                         if(newBlock.getFlip()){
793                                 newBlock.setStyle(newBlock.getStyle() + ";" + mxConstants.STYLE_DIRECTION + "=" + mxConstants.DIRECTION_NORTH);
794                         }else{
795                                 newBlock.setStyle(newBlock.getStyle() + ";" + mxConstants.STYLE_DIRECTION + "=" + mxConstants.DIRECTION_SOUTH);
796                         }
797                 } 
798
799                 // exprs 
800                 if (!(graphicsStructure.get(5) instanceof ScilabString) 
801                                 && !(graphicsStructure.get(5) instanceof ScilabList)
802                                 && !(graphicsStructure.get(5) instanceof ScilabTList)
803                                 && !isEmptyField(graphicsStructure.get(5))) {
804                         throw new WrongTypeException(); 
805                 }
806                 // exprs = ["a", "b", "c"]
807                 //if (graphicsStructure.get(5) instanceof ScilabString) {
808                 //          for (int i = 0 ; i < graphicsStructure.get(5).getHeight() ; i++){
809                 //              newBlock.getExprs().add(((ScilabString)graphicsStructure.get(5)).getData()[i][0]);
810                 //          }
811                 newBlock.setExprs(graphicsStructure.get(5));
812                 //}
813                 //else {
814                 // TODO : See how to store it properly;
815                 //WARNING("exprs defined as Scilab List : Not managed !!!");
816                 //}
817
818                 // pin
819                 if (!(graphicsStructure.get(6) instanceof ScilabDouble)) { throw new WrongTypeException(); }
820
821                 // pout
822                 if (!(graphicsStructure.get(7) instanceof ScilabDouble)) { throw new WrongTypeException(); }
823
824                 // pein
825                 if (!(graphicsStructure.get(8) instanceof ScilabDouble)) { throw new WrongTypeException(); }
826
827                 // peout
828                 if (!(graphicsStructure.get(9) instanceof ScilabDouble)) { throw new WrongTypeException(); }
829
830                 // gr_i
831                 // !! WARNING !! we do not care about gr_i because there are only
832                 // block look related.
833                 //      if (!(graphicsStructure.get(10) instanceof ScilabList)
834                 //              && !(graphicsStructure.get(10) instanceof ScilabString)) {
835                 //          throw new WrongTypeException(); 
836                 //      }
837
838                 // id
839                 if (!(graphicsStructure.get(11) instanceof ScilabString))  { throw new WrongTypeException(); }
840
841                 // in_implicit
842                 if (!(graphicsStructure.get(12) instanceof ScilabString) && !isEmptyField(graphicsStructure.get(12))) { 
843                         throw new WrongTypeException();
844                 }
845
846                 // out_implicit
847                 if (!(graphicsStructure.get(13) instanceof ScilabString) && !isEmptyField(graphicsStructure.get(13))) { 
848                         throw new WrongTypeException();
849                 }
850         }
851
852
853         public static void fillTextModelStructure ( ScilabMList blockFields,BasicBlock newBlock ) throws WrongTypeException, WrongStructureException {
854
855                 // graphicsStructure because some infromations about the port are stored there too 
856                 ScilabMList graphicsStructure =(ScilabMList)blockFields.get(1);
857                 ScilabMList modelFields =(ScilabMList)blockFields.get(2);
858
859                 String[] realNameOfStructureFields = new String[]{"model", "sim", "in", "in2", "intyp", "out", "out2", "outtyp", "evtin", "evtout",
860                                 "state", "dstate", "rpar", "ipar", "blocktype", "firing", "dep_ut", "label",
861                                 "nzcross", "nmode", "equations"};
862                 int numberOfFieldInStructure = realNameOfStructureFields.length;
863
864                 // we test if the structure as enough field
865                 if (modelFields.size() != numberOfFieldInStructure ) {
866                         String[] realNameOfBlockStructureFields = new String[]{"model", "sim", "in", "in2", "intyp", "out", "out2", "outtyp", "evtin", "evtout",
867                                         "state", "dstate", "odstate", "rpar", "ipar", "opar", "blocktype", "firing", "dep_ut", "label",
868                                         "nzcross", "nmode", "equations"};
869                         int numberOfFieldInBlockStructure =  realNameOfBlockStructureFields.length;
870                         if (modelFields.size() != numberOfFieldInBlockStructure ) {
871                         
872                                 throw new WrongStructureException();
873                         }
874                         else{
875                                 fillModelStructure ( blockFields, newBlock );
876                                 return ;
877                         }
878                 }
879
880                 // the first field is a list of string containing the name of the other fields
881                 if (!(modelFields.get(0) instanceof ScilabString)) { throw new WrongTypeException(); }
882
883                 String[] nameOfScs_mFields = ((ScilabString)modelFields.get(0)).getData()[0];
884
885                 // check if all the expecting field's name are present
886                 if (nameOfScs_mFields.length != numberOfFieldInStructure ) { throw new WrongStructureException(); }
887                 for (int i = 0 ; i < numberOfFieldInStructure ; i++) {
888                         if ( !nameOfScs_mFields[i].equals(realNameOfStructureFields[i])) {
889                                 throw new WrongTypeException();
890                         }
891                 }
892
893                 // sim : String or list(String, int)
894                 if (!(modelFields.get(1) instanceof ScilabDouble) && !(modelFields.get(1) instanceof ScilabString) && !(modelFields.get(1) instanceof ScilabList)) { throw new WrongTypeException(); }
895
896                 if (modelFields.get(1) instanceof ScilabString) { 
897                         newBlock.setSimulationFunctionName(getBlockSimulationFunctionName(modelFields) );
898                 }
899                 if (( modelFields.get(1) instanceof ScilabList)){
900                         newBlock.setSimulationFunctionName(((ScilabString)((ScilabList) modelFields.get(1)).get(0)).getData()[0][0]);   
901                         newBlock.setSimulationFunctionType((int) ((ScilabDouble)((ScilabList) modelFields.get(1)).get(1)).getRealPart()[0][0]);
902                 }
903
904                 // fill inputPort (in , in2 , intyp)
905                 if (!(modelFields.get(2) instanceof ScilabDouble) &&
906                                 !(modelFields.get(3) instanceof ScilabDouble) &&
907                                 !(modelFields.get(4) instanceof ScilabDouble)) { throw new WrongTypeException(); }  
908
909
910                 int size = modelFields.get(2).getHeight();
911
912                 // in_implicit = []
913                 // by defaults Ports are Explicit
914                 if (isEmptyField(graphicsStructure.get(12))) {
915                         for (int i = 0 ; i < size ; i++) {
916                                 ExplicitInputPort tempInputPort =  new ExplicitInputPort();
917                                 ScilabDouble dataLines = (ScilabDouble)modelFields.get(2);
918                                 ScilabDouble dataColumns = (ScilabDouble)modelFields.get(3);
919
920                                 if ( dataLines.getRealPart() != null ){
921                                         int nbLines = (int)dataLines.getRealPart()[i][0];
922                                         tempInputPort.setDataLines(nbLines);
923                                 }
924                                 if ( dataColumns.getRealPart() != null ){
925                                         int nbColumns = (int)dataColumns.getRealPart()[i][0];
926                                         tempInputPort.setDataColumns(nbColumns);
927                                 }
928                                 newBlock.addPort(tempInputPort);
929                         }
930                 }
931                 else {
932                         String[][] implicitExplicitInArray = ((ScilabString)graphicsStructure.get(12)).getData();
933
934                         for (int i = 0 ; i < size ; i++) {
935                                 InputPort tempInputPort = null;
936                                 // "E" -> Explicit
937                                 if (graphicsStructure.get(12).getHeight() > graphicsStructure.get(12).getWidth()) {
938                                         if (implicitExplicitInArray[i][0].equals("E")) { tempInputPort =  new ExplicitInputPort(); }
939                                         if (implicitExplicitInArray[i][0].equals("I")) { tempInputPort =  new ImplicitInputPort(); }
940                                 }
941                                 else {
942                                         if (implicitExplicitInArray[0][i].equals("E")) { tempInputPort =  new ExplicitInputPort(); }
943                                         if (implicitExplicitInArray[0][i].equals("I")) { tempInputPort =  new ImplicitInputPort(); }
944                                 }
945                                 ScilabDouble dataLines = (ScilabDouble)modelFields.get(2);
946                                 ScilabDouble dataColumns = (ScilabDouble)modelFields.get(3);
947
948                                 if ( dataLines.getRealPart() != null ){
949                                         int nbLines = (int)dataLines.getRealPart()[i][0];
950                                         tempInputPort.setDataLines(nbLines);
951                                 }
952                                 if ( dataColumns.getRealPart() != null ){
953                                         int nbColumns = (int)dataColumns.getRealPart()[i][0];
954                                         tempInputPort.setDataColumns(nbColumns);
955                                 }
956                                 newBlock.addPort(tempInputPort);
957                         }
958                 }
959
960                 // fill outputPort (out , out2 , outtyp)
961                 if (!(modelFields.get(5) instanceof ScilabDouble) &&
962                                 !(modelFields.get(6) instanceof ScilabDouble) &&
963                                 !(modelFields.get(7) instanceof ScilabDouble)) { throw new WrongTypeException(); }
964
965                 size = modelFields.get(5).getHeight();
966
967                 // out_implicit = []
968                 // by defaults Ports are Explicit
969                 if (isEmptyField(graphicsStructure.get(13))) {
970                         for (int i = 0 ; i < size ; i++) {
971                                 ExplicitOutputPort tempOutputPort =  new ExplicitOutputPort();
972                                 ScilabDouble dataLines = (ScilabDouble)modelFields.get(5);
973                                 ScilabDouble dataColumns = (ScilabDouble)modelFields.get(6);
974
975
976                                 if ( dataLines.getRealPart() != null ){
977                                         int nbLines = (int)dataLines.getRealPart()[i][0];
978                                         tempOutputPort.setDataLines(nbLines);
979                                 }
980                                 if ( dataColumns.getRealPart() != null ){
981                                         int nbColumns = (int)dataColumns.getRealPart()[i][0];
982                                         tempOutputPort.setDataColumns(nbColumns);
983                                 }
984                                 newBlock.addPort(tempOutputPort);
985                         }
986                 }
987                 else {
988                         String[][] implicitExplicitInArray = ((ScilabString)graphicsStructure.get(13)).getData();
989
990                         for (int i = 0 ; i < size ; i++){
991                                 OutputPort tempOutputPort = null;
992                                 if (graphicsStructure.get(13).getHeight() > graphicsStructure.get(13).getWidth()) {
993                                         if (implicitExplicitInArray[i][0].equals("E")) { tempOutputPort =  new ExplicitOutputPort(); }
994                                         if (implicitExplicitInArray[i][0].equals("I")) { tempOutputPort =  new ImplicitOutputPort(); }
995                                 }
996                                 else {
997                                         if (implicitExplicitInArray[0][i].equals("E")) { tempOutputPort =  new ExplicitOutputPort(); }
998                                         if (implicitExplicitInArray[0][i].equals("I")) { tempOutputPort =  new ImplicitOutputPort(); }
999                                 }
1000
1001                                 ScilabDouble dataLines = (ScilabDouble)modelFields.get(5);
1002                                 ScilabDouble dataColumns = (ScilabDouble)modelFields.get(6);
1003
1004
1005                                 if ( dataLines.getRealPart() != null ){
1006                                         int nbLines = (int)dataLines.getRealPart()[i][0];
1007                                         tempOutputPort.setDataLines(nbLines);
1008                                 }
1009                                 if ( dataColumns.getRealPart() != null ){
1010                                         int nbColumns = (int)dataColumns.getRealPart()[i][0];
1011                                         tempOutputPort.setDataColumns(nbColumns);
1012                                 }
1013                                 newBlock.addPort(tempOutputPort);
1014                         }
1015                 }
1016
1017
1018
1019                 if (!(modelFields.get(8) instanceof ScilabDouble) && //evtin
1020                                 !(modelFields.get(9) instanceof ScilabDouble)) { // evtout
1021                         throw new WrongTypeException();
1022                 }
1023
1024                 ScilabDouble dataNbControlPort = (ScilabDouble)modelFields.get(8);
1025                 ScilabDouble dataNbCommandPort = (ScilabDouble)modelFields.get(9);
1026
1027                 if (dataNbControlPort.getRealPart() != null ) { 
1028                         int nbControlPort = dataNbControlPort.getHeight();
1029                         for (int i = 0 ; i < nbControlPort ; i++) {
1030                                 newBlock.addPort(new ControlPort());
1031                         }
1032                 }
1033
1034                 if (dataNbCommandPort.getRealPart() != null ) { 
1035                         int nbCommandPort = dataNbCommandPort.getHeight();
1036                         for (int i = 0 ; i < nbCommandPort ; i++) {
1037                                 newBlock.addPort(new CommandPort());
1038                         }
1039                 }
1040
1041                 if (!(modelFields.get(10) instanceof ScilabDouble) && // state
1042                                 !(modelFields.get(11) instanceof ScilabDouble)) { // dstate
1043                                 //!(modelFields.get(12) instanceof ScilabList)) { //odstate
1044                         throw new WrongTypeException();
1045                 }
1046                 newBlock.setState(modelFields.get(10));
1047                 newBlock.setDState(modelFields.get(11));
1048                 //newBlock.setODState(modelFields.get(12));
1049
1050                 // rpar
1051                 // SuperBlocks store all "included" data in rpar field.
1052                 if (!(modelFields.get(12) instanceof ScilabDouble) && !(modelFields.get(12) instanceof ScilabString)) { throw new WrongTypeException(); }
1053
1054                 newBlock.setRealParameters(modelFields.get(12));
1055
1056
1057                 // ipar
1058                 // !! WARNING !! scifunc_block_m ipar = list(...)
1059                 if (!(modelFields.get(13) instanceof ScilabDouble) && !(modelFields.get(13) instanceof ScilabList)) { throw new WrongTypeException(); }
1060
1061                 newBlock.setIntegerParameters(modelFields.get(13));
1062
1063
1064                 //blocktype
1065                 if (!(modelFields.get(14) instanceof ScilabString)) { throw new WrongTypeException(); }
1066                 newBlock.setBlockType(((ScilabString) modelFields.get(14)).getData()[0][0]);
1067
1068                 //firing
1069                 if (!(modelFields.get(15) instanceof ScilabDouble)
1070                                 && !(modelFields.get(15) instanceof ScilabBoolean)) { 
1071                         throw new WrongTypeException(); 
1072                 }
1073                 if (modelFields.get(15) instanceof ScilabDouble && !isEmptyField(modelFields.get(15))) {
1074                         List<CommandPort> allCommandPorts = newBlock.getAllCommandPorts();
1075                         if(modelFields.get(15).getHeight() >= modelFields.get(15).getWidth()) {
1076                                 for (int i = 0 ; i < allCommandPorts.size() ; ++i) {
1077                                         allCommandPorts.get(i).setInitialState(((ScilabDouble) modelFields.get(15)).getRealPart()[i][0]);
1078                                 }
1079                         }
1080                         else {
1081                                 for (int i = 0 ; i < allCommandPorts.size() ; ++i) {
1082                                         allCommandPorts.get(i).setInitialState(((ScilabDouble) modelFields.get(15)).getRealPart()[0][i]);
1083                                 }
1084                         }
1085                 }
1086
1087
1088                 // dep-ut
1089                 if (!(modelFields.get(16) instanceof ScilabBoolean)){ throw new WrongTypeException(); }
1090                 newBlock.setDependsOnU( ((ScilabBoolean)modelFields.get(16)).getData()[0][0]);
1091                 newBlock.setDependsOnT( ((ScilabBoolean)modelFields.get(16)).getData()[0][1]);
1092
1093                 // label
1094                 if (!(modelFields.get(17) instanceof ScilabString)) { throw new WrongTypeException(); }
1095
1096                 // nzcross
1097                 if (!(modelFields.get(18) instanceof ScilabDouble)) { throw new WrongTypeException(); }
1098                 newBlock.setNbZerosCrossing(modelFields.get(18));
1099
1100                 //nmode 
1101                 if (!(modelFields.get(19) instanceof ScilabDouble)) { throw new WrongTypeException(); }
1102                 newBlock.setNmode(modelFields.get(19));
1103
1104                 // equations
1105                 if (!(modelFields.get(20) instanceof ScilabTList)
1106                                 && !isEmptyField(modelFields.get(20))) { 
1107                         throw new WrongTypeException(); 
1108                 }
1109                 newBlock.setEquations(modelFields.get(20));
1110         }
1111
1112
1113         
1114
1115         public static void fillModelStructure ( ScilabMList blockFields,BasicBlock newBlock ) throws WrongTypeException, WrongStructureException {
1116
1117                 // graphicsStructure because some infromations about the port are stored there too 
1118                 ScilabMList graphicsStructure =(ScilabMList)blockFields.get(1);
1119                 ScilabMList modelFields =(ScilabMList)blockFields.get(2);
1120
1121                 String[] realNameOfStructureFields = new String[]{"model", "sim", "in", "in2", "intyp", "out", "out2", "outtyp", "evtin", "evtout",
1122                                 "state", "dstate", "odstate", "rpar", "ipar", "opar", "blocktype", "firing", "dep_ut", "label",
1123                                 "nzcross", "nmode", "equations"};
1124                 int numberOfFieldInStructure = realNameOfStructureFields.length;
1125
1126                 // we test if the structure as enough field
1127                 if (modelFields.size() != numberOfFieldInStructure ) { throw new WrongStructureException(); }
1128
1129                 // the first field is a list of string containing the name of the other fields
1130                 if (!(modelFields.get(0) instanceof ScilabString)) { throw new WrongTypeException(); }
1131
1132                 String[] nameOfScs_mFields = ((ScilabString)modelFields.get(0)).getData()[0];
1133
1134                 // check if all the expecting field's name are present
1135                 if (nameOfScs_mFields.length != numberOfFieldInStructure ) { throw new WrongStructureException(); }
1136                 for (int i = 0 ; i < numberOfFieldInStructure ; i++) {
1137                         if ( !nameOfScs_mFields[i].equals(realNameOfStructureFields[i])) {
1138                                 throw new WrongTypeException();
1139                         }
1140                 }
1141
1142                 // sim : String or list(String, int)
1143                 if (!(modelFields.get(1) instanceof ScilabString) && !(modelFields.get(1) instanceof ScilabList)) { throw new WrongTypeException(); }
1144
1145                 if (modelFields.get(1) instanceof ScilabString) { 
1146                         newBlock.setSimulationFunctionName(getBlockSimulationFunctionName(modelFields) );
1147                 }
1148                 if (( modelFields.get(1) instanceof ScilabList)){
1149                         newBlock.setSimulationFunctionName(((ScilabString)((ScilabList) modelFields.get(1)).get(0)).getData()[0][0]);   
1150                         newBlock.setSimulationFunctionType((int) ((ScilabDouble)((ScilabList) modelFields.get(1)).get(1)).getRealPart()[0][0]);
1151                 }
1152
1153                 // fill inputPort (in , in2 , intyp)
1154                 if (!(modelFields.get(2) instanceof ScilabDouble) &&
1155                                 !(modelFields.get(3) instanceof ScilabDouble) &&
1156                                 !(modelFields.get(4) instanceof ScilabDouble)) { throw new WrongTypeException(); }  
1157
1158
1159                 int size = modelFields.get(2).getHeight();
1160
1161                 // in_implicit = []
1162                 // by defaults Ports are Explicit
1163                 if (isEmptyField(graphicsStructure.get(12))) {
1164                         for (int i = 0 ; i < size ; i++) {
1165                                 ExplicitInputPort tempInputPort =  new ExplicitInputPort();
1166                                 ScilabDouble dataLines = (ScilabDouble)modelFields.get(2);
1167                                 ScilabDouble dataColumns = (ScilabDouble)modelFields.get(3);
1168                                 ScilabDouble dataType = (ScilabDouble)modelFields.get(4);
1169
1170                                 if ( dataLines.getRealPart() != null ){
1171                                         int nbLines = (int)dataLines.getRealPart()[i][0];
1172                                         tempInputPort.setDataLines(nbLines);
1173                                 }
1174                                 if ( dataColumns.getRealPart() != null ){
1175                                         int nbColumns = (int)dataColumns.getRealPart()[i][0];
1176                                         tempInputPort.setDataColumns(nbColumns);
1177                                 }
1178                                 if ( dataType.getRealPart() != null ){
1179                                         int type = (int)dataType.getRealPart()[0][0];
1180                                         tempInputPort.setDataType(DataType.convertScilabValue(type));
1181                                 }
1182                                 newBlock.addPort(tempInputPort);
1183                         }
1184                 }
1185                 else {
1186                         String[][] implicitExplicitInArray = ((ScilabString)graphicsStructure.get(12)).getData();
1187
1188                         for (int i = 0 ; i < size ; i++) {
1189                                 InputPort tempInputPort = null;
1190                                 // "E" -> Explicit
1191                                 if (graphicsStructure.get(12).getHeight() > graphicsStructure.get(12).getWidth()) {
1192                                         if (implicitExplicitInArray[i][0].equals("E")) { tempInputPort =  new ExplicitInputPort(); }
1193                                         if (implicitExplicitInArray[i][0].equals("I")) { tempInputPort =  new ImplicitInputPort(); }
1194                                 }
1195                                 else {
1196                                         if (implicitExplicitInArray[0][i].equals("E")) { tempInputPort =  new ExplicitInputPort(); }
1197                                         if (implicitExplicitInArray[0][i].equals("I")) { tempInputPort =  new ImplicitInputPort(); }
1198                                 }
1199                                 ScilabDouble dataLines = (ScilabDouble)modelFields.get(2);
1200                                 ScilabDouble dataColumns = (ScilabDouble)modelFields.get(3);
1201                                 ScilabDouble dataType = (ScilabDouble)modelFields.get(4);
1202
1203                                 if ( dataLines.getRealPart() != null ){
1204                                         int nbLines = (int)dataLines.getRealPart()[i][0];
1205                                         tempInputPort.setDataLines(nbLines);
1206                                 }
1207                                 if ( dataColumns.getRealPart() != null ){
1208                                         int nbColumns = (int)dataColumns.getRealPart()[i][0];
1209                                         tempInputPort.setDataColumns(nbColumns);
1210                                 }
1211                                 if ( dataType.getRealPart() != null ){
1212                                         int type = (int)dataType.getRealPart()[0][0];
1213                                         tempInputPort.setDataType(DataType.convertScilabValue(type));
1214                                 }
1215                                 newBlock.addPort(tempInputPort);
1216                         }
1217                 }
1218
1219                 // fill outputPort (out , out2 , outtyp)
1220                 if (!(modelFields.get(5) instanceof ScilabDouble) &&
1221                                 !(modelFields.get(6) instanceof ScilabDouble) &&
1222                                 !(modelFields.get(7) instanceof ScilabDouble)) { throw new WrongTypeException(); }
1223
1224                 size = modelFields.get(5).getHeight();
1225
1226                 // out_implicit = []
1227                 // by defaults Ports are Explicit
1228                 if (isEmptyField(graphicsStructure.get(13))) {
1229                         for (int i = 0 ; i < size ; i++) {
1230                                 ExplicitOutputPort tempOutputPort =  new ExplicitOutputPort();
1231                                 ScilabDouble dataLines = (ScilabDouble)modelFields.get(5);
1232                                 ScilabDouble dataColumns = (ScilabDouble)modelFields.get(6);
1233
1234
1235                                 if ( dataLines.getRealPart() != null ){
1236                                         int nbLines = (int)dataLines.getRealPart()[i][0];
1237                                         tempOutputPort.setDataLines(nbLines);
1238                                 }
1239                                 if ( dataColumns.getRealPart() != null ){
1240                                         int nbColumns = (int)dataColumns.getRealPart()[i][0];
1241                                         tempOutputPort.setDataColumns(nbColumns);
1242                                 }
1243                                 newBlock.addPort(tempOutputPort);
1244                         }
1245                 }
1246                 else {
1247                         String[][] implicitExplicitInArray = ((ScilabString)graphicsStructure.get(13)).getData();
1248
1249                         for (int i = 0 ; i < size ; i++){
1250                                 OutputPort tempOutputPort = null;
1251                                 if (graphicsStructure.get(13).getHeight() > graphicsStructure.get(13).getWidth()) {
1252                                         if (implicitExplicitInArray[i][0].equals("E")) { tempOutputPort =  new ExplicitOutputPort(); }
1253                                         if (implicitExplicitInArray[i][0].equals("I")) { tempOutputPort =  new ImplicitOutputPort(); }
1254                                 }
1255                                 else {
1256                                         if (implicitExplicitInArray[0][i].equals("E")) { tempOutputPort =  new ExplicitOutputPort(); }
1257                                         if (implicitExplicitInArray[0][i].equals("I")) { tempOutputPort =  new ImplicitOutputPort(); }
1258                                 }
1259
1260                                 ScilabDouble dataLines = (ScilabDouble)modelFields.get(5);
1261                                 ScilabDouble dataColumns = (ScilabDouble)modelFields.get(6);
1262
1263
1264                                 if ( dataLines.getRealPart() != null ){
1265                                         int nbLines = (int)dataLines.getRealPart()[i][0];
1266                                         tempOutputPort.setDataLines(nbLines);
1267                                 }
1268                                 if ( dataColumns.getRealPart() != null ){
1269                                         int nbColumns = (int)dataColumns.getRealPart()[i][0];
1270                                         tempOutputPort.setDataColumns(nbColumns);
1271                                 }
1272                                 newBlock.addPort(tempOutputPort);
1273                         }
1274                 }
1275
1276
1277
1278                 if (!(modelFields.get(8) instanceof ScilabDouble) && //evtin
1279                                 !(modelFields.get(9) instanceof ScilabDouble)) { // evtout
1280                         throw new WrongTypeException();
1281                 }
1282
1283                 ScilabDouble dataNbControlPort = (ScilabDouble)modelFields.get(8);
1284                 ScilabDouble dataNbCommandPort = (ScilabDouble)modelFields.get(9);
1285
1286                 if (dataNbControlPort.getRealPart() != null ) { 
1287                         int nbControlPort = dataNbControlPort.getHeight();
1288                         for (int i = 0 ; i < nbControlPort ; i++) {
1289                                 newBlock.addPort(new ControlPort());
1290                         }
1291                 }
1292
1293                 if (dataNbCommandPort.getRealPart() != null ) { 
1294                         int nbCommandPort = dataNbCommandPort.getHeight();
1295                         for (int i = 0 ; i < nbCommandPort ; i++) {
1296                                 newBlock.addPort(new CommandPort());
1297                         }
1298                 }
1299
1300                 if (!(modelFields.get(10) instanceof ScilabDouble) && // state
1301                                 !(modelFields.get(11) instanceof ScilabDouble) && // dstate
1302                                 !(modelFields.get(12) instanceof ScilabList)) { //odstate
1303                         throw new WrongTypeException();
1304                 }
1305                 newBlock.setState(modelFields.get(10));
1306                 newBlock.setDState(modelFields.get(11));
1307                 newBlock.setODState(modelFields.get(12));
1308
1309                 // rpar
1310                 // SuperBlocks store all "included" data in rpar field.
1311                 if (!(modelFields.get(13) instanceof ScilabDouble) && !(modelFields.get(13) instanceof ScilabMList) && !(modelFields.get(13) instanceof ScilabString)) { throw new WrongTypeException(); }
1312                 //      if (modelFields.get(13) instanceof ScilabDouble) {
1313                 //          for (int i = 0; i < ((ScilabDouble)modelFields.get(13)).getHeight() ; i++){
1314                 //              newBlock.getRealParameters().add(((ScilabDouble)modelFields.get(13)).getRealPart()[i][0]); 
1315                 //          }
1316                 //      }
1317                 //      if (modelFields.get(13) instanceof ScilabList) {
1318                 //
1319                 //      }
1320                 newBlock.setRealParameters(modelFields.get(13));
1321
1322
1323                 // ipar
1324                 // !! WARNING !! scifunc_block_m ipar = list(...)
1325                 if (!(modelFields.get(14) instanceof ScilabDouble) && !(modelFields.get(14) instanceof ScilabList)) { throw new WrongTypeException(); }
1326                 //      for (int i = 0; i < ((ScilabDouble)modelFields.get(14)).getHeight() ; i++){
1327                 //          newBlock.getIntegerParameters().add((int) ((ScilabDouble)modelFields.get(14)).getRealPart()[i][0]); 
1328                 //      }
1329                 newBlock.setIntegerParameters(modelFields.get(14));
1330
1331                 // opar
1332                 if (!(modelFields.get(15) instanceof ScilabList)) { throw new WrongTypeException(); }
1333                 newBlock.setObjectsParameters(modelFields.get(15));
1334
1335                 //blocktype
1336                 if (!(modelFields.get(16) instanceof ScilabString)) { throw new WrongTypeException(); }
1337                 newBlock.setBlockType(((ScilabString) modelFields.get(16)).getData()[0][0]);
1338
1339                 //firing
1340                 if (!(modelFields.get(17) instanceof ScilabDouble)
1341                                 && !(modelFields.get(17) instanceof ScilabBoolean)) { 
1342                         throw new WrongTypeException(); 
1343                 }
1344                 if (modelFields.get(17) instanceof ScilabDouble && !isEmptyField(modelFields.get(17))) {
1345                         List<CommandPort> allCommandPorts = newBlock.getAllCommandPorts();
1346                         if(modelFields.get(17).getHeight() >= modelFields.get(17).getWidth()) {
1347                                 for (int i = 0 ; i < allCommandPorts.size() ; ++i) {
1348                                         allCommandPorts.get(i).setInitialState(((ScilabDouble) modelFields.get(17)).getRealPart()[i][0]);
1349                                 }
1350                         }
1351                         else {
1352                                 for (int i = 0 ; i < allCommandPorts.size() ; ++i) {
1353                                         allCommandPorts.get(i).setInitialState(((ScilabDouble) modelFields.get(17)).getRealPart()[0][i]);
1354                                 }
1355                         }
1356                 }
1357
1358
1359                 // dep-ut
1360                 if (!(modelFields.get(18) instanceof ScilabBoolean)){ throw new WrongTypeException(); }
1361                 newBlock.setDependsOnU( ((ScilabBoolean)modelFields.get(18)).getData()[0][0]);
1362                 newBlock.setDependsOnT( ((ScilabBoolean)modelFields.get(18)).getData()[0][1]);
1363
1364                 // label
1365                 if (!(modelFields.get(19) instanceof ScilabString)) { throw new WrongTypeException(); }
1366
1367                 // nzcross
1368                 if (!(modelFields.get(20) instanceof ScilabDouble)) { throw new WrongTypeException(); }
1369                 newBlock.setNbZerosCrossing(modelFields.get(20));
1370
1371                 //nmode 
1372                 if (!(modelFields.get(21) instanceof ScilabDouble)) { throw new WrongTypeException(); }
1373                 newBlock.setNmode(modelFields.get(21));
1374
1375                 // equations
1376                 if (!(modelFields.get(22) instanceof ScilabTList)
1377                                 && !isEmptyField(modelFields.get(22))) { 
1378                         throw new WrongTypeException(); 
1379                 }
1380                 newBlock.setEquations(modelFields.get(22));
1381         }
1382
1383         private static class BlockReaderException extends Exception { };
1384         private static class WrongTypeException extends BlockReaderException { };
1385         private static class WrongStructureException extends BlockReaderException { };
1386         private static class VersionMismatchException extends BlockReaderException {
1387                 private String version;
1388                 public VersionMismatchException(String version) {
1389                         this.version = version;
1390                 }
1391
1392                 public String getVersion() {
1393                         return version;
1394                 } };
1395
1396                 private static enum PortType {
1397                         INPUT,
1398                         OUTPUT,
1399                         CONTROL,
1400                         COMMAND
1401                 }
1402
1403 }
1404
1405
1406