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