From: jkauttio Date: Mon, 10 Mar 2014 09:22:35 +0000 (+0000) Subject: Attempt to fix a svn commit error X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=commitdiff_plain;h=c253c894f651c4b42472294a5b19d85146db58f8;p=simantics%2Fsysdyn.git Attempt to fix a svn commit error refs #2924 git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/branches/dev-jkauttio@29061 ac1ea38d-2e2b-0410-8846-a27921b304fc --- diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/ImportUtils.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/ImportUtils.java deleted file mode 100644 index 761663cc..00000000 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/ImportUtils.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2011 Association for Decentralized Information Management in - * Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.sysdyn.mdlImport; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringReader; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ImportUtils { - - public static String escapeExpression(String string) { - string = string.replace("Ä", "A"); - string = string.replace("ä", "a"); - string = string.replace("ö", "o"); - string = string.replace("Ö", "O"); - string = string.replace("\\", "\n"); - - StringBuilder sb = new StringBuilder(); - - if(string.contains("\"")) { - boolean startedQuote = false; - StringBuilder var = new StringBuilder(); - for(char c : string.toCharArray()) { - if(c == '"') { - if(!startedQuote) { - startedQuote = true; - var = new StringBuilder(); - continue; - } else { - startedQuote = false; - sb.append(var.toString().replaceAll("[^a-zA-Z 0-9]+", "")); - continue; - } - } - if(startedQuote) { - var.append(c); - } else { - sb.append(c); - } - } - - string = sb.toString(); - } - - return string; - - } - - public static String escapeName(String string) { - string = string.replace("Ä", "A"); - string = string.replace("ä", "a"); - string = string.replace("ö", "o"); - string = string.replace("Ö", "O"); - string = string.replaceAll("[^a-zA-Z 0-9]+", ""); - return string; - } - -} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlFile.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlFile.java deleted file mode 100644 index d0811de9..00000000 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlFile.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2011 Association for Decentralized Information Management in - * Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.sysdyn.mdlImport; - -import java.util.ArrayList; - -public class MdlFile { - - private ArrayList variableData; - private ArrayList controlData; - private ArrayList otherData; - private ArrayList> sketchData; - private ArrayList currentSketch; - - public MdlFile() { - variableData = new ArrayList(); - controlData = new ArrayList(); - otherData = new ArrayList(); - sketchData = new ArrayList>(); - } - - public void addVariableData(String line) { - variableData.add(line); - } - - public ArrayList getVariableData() { - return variableData; - } - - public void addControlData(String line) { - controlData.add(line); - } - - public ArrayList getControlData() { - return controlData; - } - - public void addOtherData(String line) { - otherData.add(line); - } - - public ArrayList getOtherData() { - return otherData; - } - - public void startSketch() { - currentSketch = new ArrayList(); - sketchData.add(currentSketch); - } - - public void addSketchData(String line) { - currentSketch.add(line); - } - - public ArrayList> getSketchData() { - return sketchData; - } - -} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlParser.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlParser.java deleted file mode 100644 index ac88fe34..00000000 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlParser.java +++ /dev/null @@ -1,1020 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2011 Association for Decentralized Information Management in - * Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.sysdyn.mdlImport; - -import java.awt.geom.Point2D; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.simantics.sysdyn.mdlImport.model.Auxiliary; -import org.simantics.sysdyn.mdlImport.model.Cloud; -import org.simantics.sysdyn.mdlImport.model.Connection; -import org.simantics.sysdyn.mdlImport.model.Dependency; -import org.simantics.sysdyn.mdlImport.model.Element; -import org.simantics.sysdyn.mdlImport.model.EquivalenceSubscript; -import org.simantics.sysdyn.mdlImport.model.Expression; -import org.simantics.sysdyn.mdlImport.model.Flow; -import org.simantics.sysdyn.mdlImport.model.Function; -import org.simantics.sysdyn.mdlImport.model.Model; -import org.simantics.sysdyn.mdlImport.model.Model2; -import org.simantics.sysdyn.mdlImport.model.Stock; -import org.simantics.sysdyn.mdlImport.model.Subscript; -import org.simantics.sysdyn.mdlImport.model.Valve; -import org.simantics.sysdyn.mdlImport.model.Variable; -import org.simantics.sysdyn.mdlImport.model.View; - -/* - * THINGS TO FIX: - * - vensim apparently supports infix operators (:AND: instead of AND()), these must be handled - * - "public" seems to be a keyboard of some sort which causes a problem in certain variable names - * - something is seriously wrong with the sketch import - * - how should models with multiple sketches be handled (this might already work) - * - instead of splitting the file into blocks, the parser could already process the data further which would greatly simplify later methods - */ - -public class MdlParser { - - private enum State { - VARIABLE, CONTROL, SKETCH, OTHER - } - - public static Model parse(File file) { - - Model2 model = new Model2(file.getName()); - - try { - // peek at the first line to see if we need to use UTF-8 - BufferedReader reader = new BufferedReader(new FileReader(file)); - String line = reader.readLine(); - reader.close(); - - if (line == null) { - // file is empty, nothing to do here - return null; - } - - if (line.startsWith(UTF_8)) { - reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); - // skip the first line - reader.readLine(); - } - else { - reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); - } - - // read the model structure from the file contents - readVariables(reader, model); - readControls(reader, model); - readSketches(reader, model); - readOthers(reader, model); - } - catch (IOException e) { - e.printStackTrace(); - } - - return null; - } - - public static Model parse2(File file) { - - Model2 model = new Model2(file.getName()); - - //String[] name = file.getName().split("\\.mdl"); - //model.setName(name[0]); - - MdlFile mdlFile = getMdlFile(file); - - for (String variable : mdlFile.getVariableData()) { - parseElement(variable); - } - - for (ArrayList sketch : mdlFile.getSketchData()) { - parseSketch(sketch); - } - - //MdlFile test = getMdlContents(file); - - //getVariableData(model, test.getVariableData()); - - //getSketchData(model, mdlFile.getSketchData()); - - //getControlData(model, mdlFile.getControlData()); - - //getOthertData(model, mdlFile.getOtherData()); - - //setAllSubscripts(model); - - return null; - } - - private static final String UTF_8 = "{UTF-8}"; - private static final String CONTROL_STR = ".Control"; - private static final String SKETCH_START = "\\\\\\---///"; - private static final String SKETCH_END = "///---\\\\\\"; - - private static MdlFile getMdlFile(File file) { - MdlFile mdl = new MdlFile(); - - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); - String line = reader.readLine(); - - if (line != null && line.startsWith(UTF_8)) { - reader.close(); - reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); - // skip the "{UTF-8}" line - reader.readLine(); - line = reader.readLine(); - } - - State state = State.VARIABLE; - - while (line != null) { - line = line.trim(); - - // skip all empty lines - if (line.isEmpty()) { - line = reader.readLine(); - continue; - } - - switch (state) { - // the file starts with variable declarations that always - // start with a variable name and end with a '|' - case VARIABLE: - if (line.startsWith(SKETCH_START)) { - state = State.SKETCH; - continue; - } - - String variable = readVariable(reader, line); - - // simulation control variables are separated from model - // variables with a control block that looks basically - // like a variable but can be safely ignored - if (variable.contains(CONTROL_STR)) { - state = State.CONTROL; - break; - } - - mdl.addVariableData(variable); - break; - - // simulation control variables look like model variables but - // are handled differently - case CONTROL: - if (line.startsWith(SKETCH_START)) { - state = State.SKETCH; - continue; - } - - String control = readVariable(reader, line); - mdl.addControlData(control); - break; - - // sketch information contains the details on the structure - // and the visual representation of the model and is situated - // in the file after variable declarations - case SKETCH: - if (line.startsWith(SKETCH_END)) { - state = State.OTHER; - break; - } - - if (line.startsWith(SKETCH_START)) { - mdl.startSketch(); - break; - } - - mdl.addSketchData(line); - break; - - // the file ends with a section of data that contains some - // additional information which is not handled currently - case OTHER: - mdl.addOtherData(line); - break; - - default: break; // should not get this far - } - - line = reader.readLine(); - } - - reader.close(); - } - catch (IOException e) { - e.printStackTrace(); - } - - return mdl; - } - - private static void readVariables(BufferedReader reader, Model2 model) - throws IOException { - StringBuilder buffer = new StringBuilder(); - - String line = reader.readLine(); - while (line != null && !line.startsWith(SKETCH_START)) { - if (line.endsWith("\\")) { - buffer.append(line.substring(0, line.length()-1)); - } - else { - buffer.append(line); - } - - if (line.endsWith("|")) { - parseElement(buffer.toString()); - buffer.setLength(0); - } - } - } - - private static void readControls(BufferedReader reader, Model2 model) - throws IOException { - String line = reader.readLine(); - while (line != null && !line.startsWith(SKETCH_START)) { - - } - } - - private static void readSketches(BufferedReader reader, Model2 model) - throws IOException { - - } - - private static void readOthers(BufferedReader reader, Model2 model) - throws IOException { - - } - - - private static String readVariable(BufferedReader reader, String current) - throws IOException { - // TODO: does not support subscript stuff at all currently - StringBuilder element = new StringBuilder(); - - while (current != null) { - current = current.trim().replace('\t', ' '); - - if (current.endsWith("|")) { - element.append(current.substring(0, current.length() - 1)); - break; - } - else if (current.endsWith("\\")) { - element.append(current.substring(0, current.length() - 1)); - } - else { - element.append(current); - } - - current = reader.readLine(); - } - - return element.toString(); - } - - private static void parseElement(String element) { - String left, right, unit, desc; - - String[] data = element.split("~"); - - if (data.length != 3) { - System.err.println("INVALID ELEMENT DATA "+element); - return; - } - - String equation = normalize(data[0]); - - left = equation.substring(0, equation.indexOf('=')).trim(); - right = equation.substring(equation.indexOf('=') + 1).trim(); - unit = data[1].trim(); - desc = data[2].trim(); - - //System.err.println("FOUND VARIABLE "+left); - //System.err.println(" EQUATION "+right); - //System.err.println(" UNIT "+unit); - //System.err.println(" DESC "+desc); - - } - - // TODO: name should probably be escaped just before writing to graph - - // matches a quoted string that may contain escaped special characters - // (which includes other quotation marks) - private static final String QUOTED_PATTERN = "\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\""; - // matches (possibly escaped) unsupported characters - private static final String BADCHARS_PATTERN = "\\\\?[-+*/()=<>\"]"; - // matches a substring that should be capitalized (see below for details) - private static final String NAMEPART_PATTERN = "([A-Za-z])[A-Za-z]*"; - - // normalize a variable name - private static String normalize(String str) { - StringBuilder result = new StringBuilder(str); - - Matcher matcher; - - matcher = Pattern.compile(QUOTED_PATTERN).matcher(str); - while (matcher.find()) { - // TODO: could do something more clever than just an underscore - String replacement = Pattern.compile(BADCHARS_PATTERN).matcher(matcher.group(1)).replaceAll("_"); - result.replace(matcher.start(), matcher.end(), replacement); - } - - // also capitalize all variable names to remove certain openmodelica - // keywords such as "public" or "private", this might not seem like - // the most sane variable name handling scheme possible, but it is - // nevertheless the one we are forced to use - matcher = Pattern.compile(NAMEPART_PATTERN).matcher(result.toString()); - while (matcher.find()) { - // replace the first character of the match with the same - // character in upper case - result.replace(matcher.start(1), matcher.end(1), matcher.group(1).toUpperCase()); - } - - return result.toString(); - } - - private static void parseSketch(ArrayList sketch) { - // the sketch should have at least three lines, version, name and font - if (sketch.size() < 3 || - !sketch.get(0).startsWith("V300") || - !sketch.get(1).startsWith("*") || - !sketch.get(2).startsWith("$")) { - System.err.println("INVALID SKETCH DATA"); - return; - } - - // parse name - String name = sketch.get(1).substring(1); - // parse font - String font = sketch.get(2).substring(2); - - for (int i = 3; i < sketch.size(); i++) { - String line = sketch.get(i); - if (line.startsWith(CONNECTION_PREFIX)) { - parseConnection(line.substring(2)); - } - else if (line.startsWith(VARIABLE_PREFIX)) { - parseVariable(line.substring(3)); - } - else if (line.startsWith(VALVE_PREFIX)) { - //parseValve(line.substring(3)); - } - else if (line.startsWith(COMMENT_PREFIX)) { - //parseComment(line.substring(3)); - } - else { - //System.err.println("UNSUPPORTED SKETCH OBJECT "+line); - } - } - } - - // these methods are implemented according to the documentation on the .mdl - // file format available in http://www.vensim.com/documentation/24305.htm - - // (1,)id,from,to,shape,hid,pol,thick,hasf,dtype,res,color,font,np|plist - private static final String CONNECTION_PREFIX = "1,"; - private static final String CONNECTION_PATTERN = - "(\\d+),(\\d+),(\\d+).*"; - // (n,)id,name,x,y,w,h,sh,bits,hid,hasf,tpos,bw,nav1,nav2(,box,fill,font) - private static final String VARIABLE_PREFIX = "10,"; - private static final String VALVE_PREFIX = "11,"; - private static final String COMMENT_PREFIX = "12,"; - private static final String ELEMENT_PATTERN = - "(\\d+),(\".*\"|[^\",]*),(-?\\d+),(-?\\d+),(\\d+),(\\d+).*"; - - private static void parseConnection(String line) { - Matcher matcher = Pattern.compile(CONNECTION_PATTERN).matcher(line); - if (!matcher.matches()) { - System.err.println("MALFORMED CONNECTION"); - return; - } - - // the fields of interest are: id, from, to, ... (TODO) - int id = Integer.parseInt(matcher.group(1)); - int from = Integer.parseInt(matcher.group(2)); - int to = Integer.parseInt(matcher.group(3)); - - System.err.println("connection "+id+": "+from+" -> "+to); - } - - private static void parseVariable(String line) { - Matcher matcher = Pattern.compile(ELEMENT_PATTERN).matcher(line); - if (!matcher.matches()) { - System.err.println("MALFORMED VARIABLE "+line); - return; - } - - int id = Integer.parseInt(matcher.group(1)); - String name = normalize(matcher.group(2)); - int x = Integer.parseInt(matcher.group(3)); - int y = Integer.parseInt(matcher.group(4)); - int width = Integer.parseInt(matcher.group(5)); - int height = Integer.parseInt(matcher.group(6)); - - System.err.println("variable "+id+": "+name+" ("+x+","+y+")"); - } - - private static void parseValve(String line) { - - } - - private static void parseComment(String line) { - - } - - - - - - - - - - - private static MdlFile getMdlContents(File aFile) { - MdlFile mdlFile = new MdlFile(); - - try { - BufferedReader input = new BufferedReader(new FileReader(aFile)); - - try { - String line = null; // not declared within while loop - - mdlFile.startSketch(); - - // See if the document is encoded with UTF-8. It will be marked with {UTF-8} on the first line - input.mark(30); - if ((line = input.readLine()) != null && line.contains("{UTF-8}")){ - Reader in = new InputStreamReader(new FileInputStream(aFile), "UTF-8"); - input = new BufferedReader(in); - line = input.readLine(); - } else { - input.reset(); - } - - - boolean isControl = false; - - while ((line = input.readLine()) != null) { - // Build an element (combine the lines to one string) - StringBuilder elementBuilder = new StringBuilder(); - while (line != null && !line.contains("\\\\\\---///")) { - // Add a new line for the element - elementBuilder.append(line); - if(line.endsWith("|") && !line.endsWith("~~|")) { - //Element definition has ended - break; - } - line = input.readLine(); - } - - if (line.contains("\\\\\\---///")) - break; - - String variable = elementBuilder.toString(); - - if (variable.trim().matches("[\\*]{46}.+[\\*]{46}.+")) { - if(variable.contains(".Control")) { - isControl = true; - } else { - isControl = false; - } - continue; - } - - // Add element string to model - if(isControl) { - mdlFile.addControlData(variable); - } else { - mdlFile.addVariableData(variable); - } - } - - while ((line = input.readLine()) != null && !line.contains("///---\\\\\\")) { - mdlFile.addSketchData(line); - } - - while ((line = input.readLine()) != null){ - mdlFile.addOtherData(line); - } - } - finally { - input.close(); - } - } - catch (IOException ex){ - ex.printStackTrace(); - } - - return mdlFile; - } - - private static void getVariableData(Model model, ArrayList elements) { - ArrayList equivalenceSubscripts = new ArrayList(); - for(String elementString : elements) { - Variable v = createVariable(model, elementString); - if(v instanceof EquivalenceSubscript){ - equivalenceSubscripts.add((EquivalenceSubscript) v); - } - } - - // All variables are ready, determine subscript equivalences - for(EquivalenceSubscript es : equivalenceSubscripts) { - Element e = model.getElement(es.getEquivalentToName()); - if(e != null && e instanceof Subscript) { - es.setEquivalentTo((Subscript)e); - } - } - } - - - private static void getControlData(Model model, ArrayList controls) { - for(String controlString : controls) { - String[] nameAndData = controlString.split("="); - String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]"); - - if(nameAndData[0].trim().equals("FINAL TIME")) { - model.setEndTime(Double.parseDouble(expressionUnitsAndComments[0])); - } else if(nameAndData[0].trim().equals("INITIAL TIME")) { - model.setStartTime(Double.parseDouble(expressionUnitsAndComments[0])); - } else if(nameAndData[0].trim().equals("TIME STEP")) { - model.setTimeStep(Double.parseDouble(expressionUnitsAndComments[0])); - } else if(nameAndData[0].trim().equals("SAVEPER")) { - model.setSaveper(expressionUnitsAndComments[0]); - model.setTimeUnit(expressionUnitsAndComments[1]); - } - } - - } - - private static Variable getVariable(Model model, String name) { - Element e = model.getElement(name); - Variable variable = null; - if(e != null && e instanceof Variable) - variable = (Variable)e; - return variable; - } - - private static String[] getNormalVariableNameDataAndRange(String element) { - String[] nameAndData = element.split("=", 2); - String[] nameAndRange = nameAndData[0].trim().split("[\\[|\\]]"); - if(nameAndData.length == 2) - return new String[] {nameAndRange[0], nameAndData[1], nameAndRange.length == 2 ? nameAndRange[1] : null}; - return null; - } - - private static String[] getSubscriptNameAndData(String element) { - String[] nameAndData = element.split(":"); - if(nameAndData.length == 2) - return nameAndData; - return null; - } - - private static String[] getEquivalenceSubscriptNameAndData(String element) { - String[] nameAndData = element.split("\\<\\-\\>"); - if(nameAndData.length == 2) - return nameAndData; - return null; - } - - private static String[] getTableNameDataAndRange(String element) { - String[] parts = element.split("\\~"); - if(!parts[0].contains("(") || !parts[0].contains(")")) - return null; - String name = element.substring(0, element.indexOf("(")); - String theRest = element.substring(element.indexOf("(")); - String[] nameAndData = {name, theRest}; - String[] nameAndRange = nameAndData[0].trim().split("[\\[|\\]]"); - if(nameAndData.length == 2) - return new String[] {nameAndRange[0], nameAndData[1], nameAndRange.length == 2 ? nameAndRange[1] : null}; - return nameAndData; - } - - private static String[] getDataVariableNameAndData(String element) { - String[] nameAndData = { - element.substring(0, element.indexOf("~")), - " " + element.substring(element.indexOf("~"))}; - return nameAndData; - } - - private static Variable createVariable(Model model, String elementString) { - - String[] elementExpressions = elementString.split("\\~\\~\\|"); - - Variable variable = null; - - System.err.println("CREATE VARIABLE "+elementString); - - for(String s : elementExpressions) { - System.err.println(" INSIDE FOR"); - - // Skip these definitions at least for now - if(elementExpressions.length > 1 && s.contains("A FUNCTION OF")) - continue; - - Expression expression = new Expression(); - - String[] nameAndData = null; - String name; - - // Create the expression based on the expression string - if((nameAndData = getNormalVariableNameDataAndRange(s)) != null) { - - name = nameAndData[0].replace("\"", ""); - variable = getVariable(model, name); - if(variable == null) { - variable = new Auxiliary(); - variable.setName(name); - model.addElement(variable); - } - - if(!nameAndData[1].trim().endsWith("|")) { - // Multiple expressions - expression.setExpression(nameAndData[1].trim()); - } else { - String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]"); - expression.setExpression(expressionUnitsAndComments[0].trim()); - } - - } else if((nameAndData = getSubscriptNameAndData(s)) != null) { - - name = nameAndData[0].replace("\"", ""); - variable = getVariable(model, name); - if(variable == null) { - variable = new Subscript(); - variable.setName(name); - model.addElement(variable); - } - - // No support for multidimensional variables. Don't know what that would mean - String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]"); - expression.setExpression(expressionUnitsAndComments[0].trim()); - variable.setUnits(expressionUnitsAndComments[1].trim()); - variable.setComments(expressionUnitsAndComments[2].trim()); - - } else if((nameAndData = getEquivalenceSubscriptNameAndData(s)) != null) { - - name = nameAndData[0].replace("\"", ""); - variable = getVariable(model, name); - if(variable == null) { - variable = new EquivalenceSubscript(); - variable.setName(name); - model.addElement(variable); - } - - // No support for multidimensional variables. Don't know what that would mean - String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]"); - expression.setExpression(expressionUnitsAndComments[0].trim()); - variable.setUnits(expressionUnitsAndComments[1].trim()); - variable.setComments(expressionUnitsAndComments[2].trim()); - - } else if((nameAndData = getTableNameDataAndRange(s)) != null) { - - name =(nameAndData[0].replace("\"", "")); - variable = getVariable(model, name); - if(variable == null) { - variable = new Function(); - variable.setName(name); - model.addElement(variable); - } - - String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]"); - // ([(0,0)-(2,5)],(0,5),(0.5,3),(1,0.5),(2,0.5) => ( ; (0,0)-(2,5) ; ,(0,5),(0.5,3),(1,0.5),(2,0.5) - String table = expressionUnitsAndComments[0].trim().split("[\\[|\\]]")[2]; - // ,(0,5),(0.5,3),(1,0.5),(2,0.5) => (0,5),(0.5,3),(1,0.5),(2,0.5) - table = table.substring(table.indexOf(",") + 1, table.lastIndexOf(")")); - table = "{" + table + "}"; - table = table.replace("(", "{"); - table = table.replace(")", "}"); - expression.setExpression(table); - - - } else if((nameAndData = getDataVariableNameAndData(s)) != null) { - - name = nameAndData[0].replace("\"", ""); - variable = getVariable(model, name); - if(variable == null) { - variable = new Auxiliary(); - variable.setName(name); - model.addElement(variable); - } - - expression.setExpression(""); - } - - if(nameAndData == null || variable == null) - continue; - - // Set possible range for the expression - if(nameAndData.length == 3) - expression.setRange(nameAndData[2]); - - // Set units and comments for the variable - if(nameAndData[1].trim().endsWith("|")) { - String[] expressionUnitsAndComments = nameAndData[1].split("[\\~|\\|]"); - String units = expressionUnitsAndComments[1].trim(); - if(units.contains("[") && - units.contains("]") && - units.lastIndexOf("]") == units.length() - 1) { - // Range definitions are at the end - String range = units.substring( - units.lastIndexOf("[") + 1, - units.length() - 1); - String[] rangeParts = range.split(","); - - try { - variable.setRangeStart(Double.parseDouble(rangeParts[0])); - if(rangeParts.length >= 2) - variable.setRangeEnd(Double.parseDouble(rangeParts[1])); - if(rangeParts.length >= 3) - variable.setRangeStep(Double.parseDouble(rangeParts[2])); - } catch (NumberFormatException e) { - // Not a double - } - expressionUnitsAndComments[1] = units.substring(0, units.lastIndexOf("[")); - } - variable.setUnits(expressionUnitsAndComments[1].trim()); - variable.setComments(expressionUnitsAndComments[2].trim()); - } - - // Finally add the expression to element - variable.getExpressions().add(expression); - } - return variable; - } - - private static int SCALE = 4; - - private static void getSketchData(Model model, ArrayList sketchData) { - String line = null; - View view = null; - - int i = 0; - - while(i < sketchData.size()) { - line = sketchData.get(i); - if(line.startsWith("*")) { - view = new View(); - model.addView(view); - - view.setName(line.substring(1)); - - // STARTED A NEW VIEW - - HashMap elementNumbers = new HashMap(); - ArrayList ghostNumbers = new ArrayList(); - ArrayList connections = new ArrayList(); - HashMap emptyValves = new HashMap(); // map for valves that don't have an element - - - i++; - line = sketchData.get(i); - while(i < sketchData.size() && !sketchData.get(i).startsWith("*")) { - line = sketchData.get(i); - - if(line.startsWith("$")) { - view.setFontParameters(line); - i++; - continue; - } - - String[] data = line.split(","); - if (data[0].equals("1")) { - // Connections are handled after all elements - String[] connectionData = line.split(","); - connections.add(connectionData); - - } else if (data[0].equals("11")){ - // Valve - i = i + 1; - String elementLine = sketchData.get(i); - String[] elementData = elementLine.split(","); - // FIXME: Assumes that element is always attached to the valve - Element element = model.getElement(elementData[2].replace("\"", "")); - Valve valve = new Valve(); - if (element != null && element instanceof Variable) { - Variable v = (Variable) element; - valve.setName(v.getName()); - valve.setExpressions(v.getExpressions()); - valve.setUnits(v.getUnits()); - valve.setComments(v.getComments()); - valve.setX(Integer.parseInt(data[3]) / SCALE); - valve.setY(Integer.parseInt(data[4]) / SCALE); - - model.removeElement(element); - model.addElement(view, valve); - - // Add valve to the element list with both valve and variable symbol numbers - elementNumbers.put(elementData[1], valve); - elementNumbers.put(data[1], valve); - } else { - i = i - 1; - emptyValves.put(data[1], data); - } - } else if (data[0].equals("12")){ - // Cloud - Cloud cloud = new Cloud(); - cloud.setX(Integer.parseInt(data[3]) / SCALE); - cloud.setY(Integer.parseInt(data[4]) / SCALE); - elementNumbers.put(data[1], cloud); - model.addElement(view, cloud); - } else if (data[0].equals("10") && data.length <= 15){ - // Some variable - Element e = model.getElement(data[2].replace("\"", "").trim()); - - if (e != null && e instanceof Variable) { - Variable v = (Variable) e; - if (v.getExpressions().get(0).getExpression().startsWith("INTEG (") && !(e instanceof Stock)) { - // Stock - Stock s = new Stock(); - s.setName(v.getName()); - s.setUnits(v.getUnits()); - s.setComments(v.getComments()); - s.setExpressions(v.getExpressions()); - model.removeElement(e); - e = s; - model.addElement(view, e); - } - } - - e.setX(Integer.parseInt(data[3]) / SCALE); - e.setY(Integer.parseInt(data[4]) / SCALE); - elementNumbers.put(data[1], e); - model.relocateElement(view, e); - } else if (data[0].equals("10") && data.length > 15){ - // TODO: Ghost - // for now, direct back to the original element - Element originalElement = model.getElement(data[2].replace("\"", "")); - if(originalElement != null) { - elementNumbers.put(data[1], originalElement); - ghostNumbers.add(data[1]); - } - } - - i++; - } - - i--; - - // Find the first variable that is connected to an empty valve - for(String[] connectionData : connections) { - if(!connectionData[9].equals("64")) - continue; // not dependency - String[] end = emptyValves.get(connectionData[3]); - if (end != null && elementNumbers.get(connectionData[3]) == null) { - // Use the connected element to create a valve and give it a name - Element start = elementNumbers.get(connectionData[2]); - if (start == null) - continue; - - Valve valve = new Valve(); - valve.setName(start.getName() + " Rate"); - valve.setX(Integer.parseInt(end[3]) / SCALE); - valve.setY(Integer.parseInt(end[4]) / SCALE); - - model.addElement(view, valve); - elementNumbers.put(connectionData[3], valve); - valve.setUnits(""); - valve.setComments(""); - } - } - - - - for(String[] connectionData : connections) { - - Element start = elementNumbers.get(connectionData[2]); - Element end = elementNumbers.get(connectionData[3]); - // Discard connection if one of the ends is null - if(start == null || end == null) - continue; - - - Connection connection; - if(connectionData[9].equals("64")) { - // Dependency - Point2D startPoint = new Point2D.Double(start.getX(), start.getY()); - Point2D endPoint = new Point2D.Double(end.getX(), end.getY()); - String controlX = connectionData[13].substring(connectionData[13].indexOf("(") + 1); - String controlY = connectionData[14].substring(0, connectionData[14].indexOf(")")); - Point2D controlPoint = new Point2D.Double(Double.parseDouble(controlX) / SCALE, Double.parseDouble(controlY) / SCALE); - - if(ghostNumbers.contains(connectionData[2]) || - ghostNumbers.contains(connectionData[3])) { - connection = new Dependency(); - } else { - double angle = Dependency.angleOfArc( - startPoint.getX(), startPoint.getY(), - controlPoint.getX(), controlPoint.getY(), - endPoint.getX(), endPoint.getY()); - - connection = new Dependency(angle); - } - - } else { - // Flow - connection = new Flow(); - if(connectionData[4].equals("100")) { - // Flip the flow - Element temp = start; - start = end; - end = temp; - } - } - connection.setStart(start); - connection.setEnd(end); - model.addConnection(connection); - } - - - // Generate expressions for empty valves - for(String key : emptyValves.keySet()) { - Element e = elementNumbers.get(key); - if(e instanceof Valve && ((Valve)e).getExpressions().isEmpty()) { - Valve valve = (Valve)e; - // Find the stock - Stock stock = null; - for(Connection connection : valve.getConnections()) { - if(!(connection instanceof Flow)) - continue; - if(connection.getStart().equals(valve) && - connection.getEnd() instanceof Stock) { - stock = (Stock)connection.getEnd(); - break; - } - } - - // Create the expression. Use the expression of the stock, and undo the effect of other valves - if(stock != null && stock instanceof Stock) { - Expression expression = new Expression(); - - StringBuilder sb = new StringBuilder(); - sb.append(((Stock)stock).getIntegralParts(stock.getExpressions().get(0))[0]); - - for(Connection c : stock.getConnections()) { - if(c instanceof Flow) { - if(c.getStart().equals(stock) && !c.getEnd().equals(valve)) { - sb.append("+"); - sb.append(c.getEnd().getName()); - } else if(!c.getStart().equals(valve)){ - sb.append("-"); - sb.append(c.getStart().getName()); - } - } - } - expression.setExpression(sb.toString()); - ArrayList expressions = new ArrayList(); - expressions.add(expression); - valve.setExpressions(expressions); - } - } - } - } - - i++; - } - - } - - private static void getOthertData(Model model, String otherData) { - - } - - private static void setAllSubscripts(Model model) { - - // Set subscripts for all elements - ArrayList elements = new ArrayList(); - elements.addAll(model.getUnlocatedElements()); - for(View view : model.getViews()) { - elements.addAll(view.getElements()); - } - - for(Element e : elements) { - if(!(e instanceof Variable)) - continue; - Variable v = (Variable)e; - v.initializeSubscripts(model); - } - } - -} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlParser2.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlParser2.java deleted file mode 100644 index 89cae0a2..00000000 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlParser2.java +++ /dev/null @@ -1,259 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2011 Association for Decentralized Information Management in - * Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.sysdyn.mdlImport; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.HashMap; - -import org.simantics.sysdyn.mdlImport.model.Connection2; -import org.simantics.sysdyn.mdlImport.model.Element2; -import org.simantics.sysdyn.mdlImport.model.Model; -import org.simantics.sysdyn.mdlImport.model.Model2; -import org.simantics.sysdyn.mdlImport.model.Sketch2; -import org.simantics.sysdyn.mdlImport.model.SketchComment; -import org.simantics.sysdyn.mdlImport.model.SketchConnection; -import org.simantics.sysdyn.mdlImport.model.SketchElement; -import org.simantics.sysdyn.mdlImport.model.SketchValve; -import org.simantics.sysdyn.mdlImport.model.SketchVariable; -import org.simantics.sysdyn.mdlImport.model.Variable2; - -/* - * THINGS TO FIX: - * - vensim apparently supports infix operators (:AND: instead of AND()), these must be handled - * - "public" seems to be a keyboard of some sort which causes a problem in certain variable names - * - something is seriously wrong with the sketch import - * - how should models with multiple sketches be handled (this might already work) - * - instead of splitting the file into blocks, the parser could already process the data further which would greatly simplify later methods - */ - -public class MdlParser2 { - - private static final String UTF_8 = "{UTF-8}"; - private static final String CONTROL_STR = ".Control"; - private static final String SKETCH_VERSION = "V300"; - - // each .mdl is divided into three sections, these are the the delimiter - // strings used to identify where each section starts - private static final String SKETCH_START = "\\\\\\---///"; - private static final String SKETCH_END = "///---\\\\\\"; - - private HashMap variables; - private HashMap controls; - private ArrayList sketches; - - public MdlParser2() { - variables = new HashMap(); - controls = new HashMap(); - sketches = new ArrayList(); - } - - public Model parse(File file) { - try { - // peek at the first line to see if we need to use UTF-8 - BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); - String line = reader.readLine(); - - if (line == null) { - // file is empty, nothing to do here - reader.close(); - return null; - } - - if (line.startsWith(UTF_8)) { - reader.close(); - reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); - // skip the first line - reader.readLine(); - line = reader.readLine(); - } - - // read variable data - line = readVariables(reader, line); - - if (line == null) { - // unexpected end of file - System.err.println("unexpected end of file"); - reader.close(); - return null; - } - - // read sketch data - line = readSketches(reader, line); - - if (line == null) { - // unexpected end of file - System.err.println("unexpected end of file"); - reader.close(); - return null; - } - - // read other data - - do { - // ignore other data for now - } while ((line = reader.readLine()) != null); - - reader.close(); - } - catch (IOException e) { - e.printStackTrace(); - return null; - } - - // create new model - - Model2 model = new Model2(file.getName()); - - int offset = 0; - - for (Sketch2 sketch : sketches) { - // must keep track of which elements in the sketch correspond to - // which elements in the model so connections can be constructed - // accurately - HashMap elementMap = new HashMap(); - - for (SketchElement element : sketch.getElements()) { - Element2 e = element.getWriteableElement(0, 0); - //model.addElement(e); - //elementMap.put(element, e); - } - - for (SketchConnection connection : sketch.getConnections()) { - Connection2 c = connection.getWriteableConnection(); - //model.addConnection(c); - } - - offset += sketch.getWidth() + 100; - } - - return null; - } - - private String readVariables(BufferedReader reader, String line) - throws IOException { - - String category = null; - - do { - if (line.isEmpty()) { - continue; - } - - StringBuilder buffer = new StringBuilder(line); - - while ((line = reader.readLine()) != null) { - if (line.endsWith("\\")) - buffer.append(line.substring(0, line.length()-1)); - else - buffer.append(line); - - if (line.endsWith("|")) - break; - } - - String str = buffer.toString(); - - // TODO: must handle categories other than .Control - - Variable2 var = MdlUtils.getPossibleVariable(str, category); - if (var != null) { - variables.put(var.getName(), var); - continue; - } - - System.err.println("unrecognized variable "+str); - - } while ((line = reader.readLine()) != null && !line.startsWith(SKETCH_START)); - - return line; - } - - private String readSketches(BufferedReader reader, String line) - throws IOException { - - Sketch2 sketch = null; - - do { - if (line.startsWith(SKETCH_START)) { - sketch = new Sketch2(); - sketches.add(sketch); - continue; - } - else if (line.startsWith(SKETCH_VERSION)) { - // version declaration, nothing to do here - continue; - } - else if (line.startsWith("*")) { - sketch.setName(line.substring(1)); - continue; - } - else if (line.startsWith("$")) { - // font declaration, nothing to do here - continue; - } - - SketchConnection connection = MdlUtils.getPossibleSketchConnection(line); - if (connection != null) { - sketch.addSketchObject(connection); - continue; - } - - SketchVariable variable = MdlUtils.getPossibleSketchVariable(line, variables); - if (variable != null) { - sketch.addSketchObject(variable); - continue; - } - - SketchValve valve = MdlUtils.getPossibleSketchValve(line); - if (valve != null) { - // the next row after a valve should always the variable associated with the valve - SketchVariable attached = MdlUtils.getPossibleSketchVariable(reader.readLine(), variables); - if (attached == null || !attached.isAttached()) { - // TODO: should also verify that the variable is in fact attached - System.err.println("attached variable not found for valve"); - continue; - } - valve.setAttachedVariable(attached); - sketch.addSketchObject(valve); - sketch.addSketchObject(attached); - continue; - } - - SketchComment comment = MdlUtils.getPossibleSketchComment(line); - if (comment != null) { - if (comment.hasTextNextLine()) { - comment.setText(reader.readLine()); - } - - if (comment.isIOElement()) { - System.err.println("IO elements are not currently supported"); - continue; - } - - sketch.addSketchObject(comment); - continue; - } - - // if we got this far, the element was not recognized - System.err.println("unrecognized element "+line); - - } while ((line = reader.readLine()) != null && !line.startsWith(SKETCH_END)); - - return line; - } - -} diff --git a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlUtils.java b/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlUtils.java deleted file mode 100644 index 7389c872..00000000 --- a/org.simantics.sysdyn/src/org/simantics/sysdyn/mdlImport/MdlUtils.java +++ /dev/null @@ -1,307 +0,0 @@ -package org.simantics.sysdyn.mdlImport; - -import java.util.HashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.simantics.sysdyn.mdlImport.model.SketchComment; -import org.simantics.sysdyn.mdlImport.model.SketchConnection; -import org.simantics.sysdyn.mdlImport.model.SketchElement; -import org.simantics.sysdyn.mdlImport.model.SketchValve; -import org.simantics.sysdyn.mdlImport.model.SketchVariable; -import org.simantics.sysdyn.mdlImport.model.Variable2; -import org.simantics.sysdyn.mdlImport.model.Valve2.TextPosition; -import org.simantics.utils.datastructures.Pair; - -public class MdlUtils { - - public enum ConnectionType { - ARROW, LINE_ARROW, LINE_SEGMENT, OTHER - } - - public enum CommentIcon { - CLOUD, OTHER - } - - // most of this data is from the documentation of the .mdl file format - // available in http://www.vensim.com/documentation/24305.htm - - // a Vensim variable name is either a plain string that contains letters, - // numbers and whitespace, or a quoted string that can also contain any - // special characters (including other quotation marks that must be escaped) - private static final String VAR_NAME_QUOTED = - "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""; - private static final String VAR_NAME_SIMPLE = - "[A-Za-z](?![ \\w]*\\()(?: *\\w+)*"; - private static final String VAR_NAME = - "("+VAR_NAME_QUOTED+"|"+VAR_NAME_SIMPLE+")"; - - private static final String SUBSCRIPT = - "("+VAR_NAME_SIMPLE+")\\[("+VAR_NAME_SIMPLE+"(?:,"+VAR_NAME_SIMPLE+")*)\\]"; - - // the first part of the variable string is the variable name - // followed by a delimiter which depends on the type of the declaration - private static final String VARIABLE_PATTERN = - VAR_NAME+"\\s*=\\s*"; - private static final String SUBSCRIPT_PATTERN = - SUBSCRIPT+"\\s*=\\s*"; - private static final String VALUE_NEW_PATTERN = - VAR_NAME+"\\s*:\\s*"; - private static final String VALUE_EQUALS_PATTERN = - VAR_NAME+"\\s*<->\\s*"; - - // the second part is the equation followed by '~' - private static final String EQUATION_PATTERN = - "([^~]*?(?:"+VAR_NAME_QUOTED+"[^~]*?)*)\\s*~\\s*"; - - // the third part is the unit followed by '~' - private static final String UNIT_PATTERN = - "([^~]*?)\\s*~\\s*"; - - // the last part is the description followed by '|' - private static final String DESC_PATTERN = - "([^\\|]*?)\\s*\\|"; - - public static final String variablePattern = - VARIABLE_PATTERN+EQUATION_PATTERN+UNIT_PATTERN+DESC_PATTERN; - public static final String subscriptPattern = - SUBSCRIPT_PATTERN+EQUATION_PATTERN+UNIT_PATTERN+DESC_PATTERN; - public static final String valueNewPattern = - VALUE_NEW_PATTERN+EQUATION_PATTERN+UNIT_PATTERN+DESC_PATTERN; - public static final String valueEqualsPattern = - VALUE_EQUALS_PATTERN+EQUATION_PATTERN+UNIT_PATTERN+DESC_PATTERN; - - private static final int variableName = 1; - private static final int variableEquation = 2; - private static final int variableUnit = 3; - private static final int variableDesc = 4; - - public static Variable2 getPossibleVariable(String line, String category) { - Matcher matcher = Pattern.compile(variablePattern).matcher(line); - - if (!matcher.matches()) { - return null; - } - - String name = matcher.group(variableName); - String equation = matcher.group(variableEquation); - String unit = matcher.group(variableUnit); - String description = matcher.group(variableDesc); - - return new Variable2(name, equation, unit, description); - } - - public static Pair getPossibleIntegral(String equation) { - - Matcher matcher = Pattern.compile("INTEG\\s*\\((.*),(.*)\\)").matcher(equation); - if (matcher.matches()) { - return new Pair(matcher.group(1), matcher.group(2)); - } - - return null; - } - - // sketch object data is defined similarly - - private static final String SAVE = "(-?\\d+),"; - private static final String SKIP = "-?\\d+,"; - private static final String POINTS = "(\\d+\\|(?:\\(-?\\d+,-?\\d+\\)\\|)+)"; - - public static final String sketchConnection = - // 1, id, from,to, shape,hid, pol, thick,hasf,dtype,res,color,font,np|plist - "1,"+SAVE+SAVE+SAVE+SAVE+ SKIP+SKIP+SKIP+ SKIP+SKIP+ "0,-1--1--1,.*,"+POINTS; - - // group indices for later use - private static final int connectionId = 1; - private static final int connectionFrom = 2; - private static final int connectionTo = 3; - private static final int connectionShape = 4; - private static final int connectionPoints = 5; - - private static final String COMMON = - // x, y, w, h, sh, bits,hid, hasf,tpos,bw,nav1,nav2(,box,fill,font) - SAVE+SAVE+SAVE+SAVE+SAVE+SAVE+SKIP+SKIP+SAVE+".*"; - - public static final String sketchVariable = - // n, id, name, x,y,w,h,sh,bits,hid,hasf,tpos,bw,nav1,nav2(,box,fill,font) - "10,"+SAVE+VAR_NAME+","+COMMON; - public static final String sketchValve = - "11,"+SAVE+SAVE+ COMMON; - public static final String sketchComment = - "12,"+SAVE+SAVE+ COMMON; - - // group indices for later use - private static final int elementId = 1; - private static final int elementName = 2; - private static final int elementX = 3; - private static final int elementY = 4; - private static final int elementWidth = 5; - private static final int elementHeight = 6; - private static final int elementShape = 7; - private static final int elementBits = 8; - private static final int elementTextPos = 9; - - public static SketchConnection getPossibleSketchConnection(String line) { - Matcher matcher = Pattern.compile(sketchConnection).matcher(line); - - if (!matcher.matches()) { - return null; - } - - int id = Integer.parseInt(matcher.group(connectionId)); - int from = Integer.parseInt(matcher.group(connectionFrom)); - int to = Integer.parseInt(matcher.group(connectionTo)); - ConnectionType type = getConnectionType(matcher); - - return new SketchConnection(id, from, to, type); - } - - public static SketchVariable getPossibleSketchVariable(String line, HashMap variables) { - Matcher matcher = Pattern.compile(sketchVariable).matcher(line); - - if (!matcher.matches()) { - return null; - } - - int id = Integer.parseInt(matcher.group(elementId)); - Variable2 var = variables.get(matcher.group(elementName)); - boolean attached = elementIsAttached(matcher); - boolean in = elementAllowsInBound(matcher); - boolean out = elementAllowsOutBound(matcher); - - SketchVariable variable = new SketchVariable(id, var, attached, in, out); - - initializeElement(variable, matcher); - - return variable; - } - - public static SketchValve getPossibleSketchValve(String line) { - Matcher matcher = Pattern.compile(sketchValve).matcher(line); - - if (!matcher.matches()) { - return null; - } - - int id = Integer.parseInt(matcher.group(elementId)); - - SketchValve valve = new SketchValve(id); - - initializeElement(valve, matcher); - - return valve; - } - - public static SketchComment getPossibleSketchComment(String line) { - Matcher matcher = Pattern.compile(sketchComment).matcher(line); - - if (!matcher.matches()) { - return null; - } - - int id = Integer.parseInt(matcher.group(elementId)); - CommentIcon icon = getCommentIcon(matcher); - boolean nextLine = elementHasCommentLine(matcher); - boolean isIO = elementIsIO(matcher); - - SketchComment comment = new SketchComment(id, icon, nextLine, isIO); - - initializeElement(comment, matcher); - - return comment; - } - - public static void initializeElement(SketchElement element, Matcher matcher) { - int x = Integer.parseInt(matcher.group(elementX)); - int y = Integer.parseInt(matcher.group(elementY)); - int w = Integer.parseInt(matcher.group(elementWidth)); - int h = Integer.parseInt(matcher.group(elementHeight)); - - element.setLocationAndSize(x, y, w, h); - } - - public static ConnectionType getConnectionType(Matcher matcher) { - switch(Integer.parseInt(matcher.group(connectionShape))) { - case 0: return ConnectionType.ARROW; - case 4: return ConnectionType.LINE_ARROW; - case 100: return ConnectionType.LINE_SEGMENT; - default: return ConnectionType.OTHER; - } - } - - public static CommentIcon getCommentIcon(Matcher matcher) { - switch(Integer.parseInt(matcher.group(elementName))) { - case 48: return CommentIcon.CLOUD; - default: return CommentIcon.OTHER; - } - } - - public static TextPosition getTextPos(Matcher matcher) { - switch (Integer.parseInt(matcher.group(elementTextPos))) { - case 0: return TextPosition.INSIDE; - case 1: return TextPosition.BELOW; - case 2: return TextPosition.LEFT; - case 3: return TextPosition.ABOVE; - case 4: return TextPosition.RIGHT; - default: return TextPosition.UNSET; - } - } - - public static boolean elementIsAttached(Matcher matcher) { - return (Integer.parseInt(matcher.group(elementShape)) & 1<<5) != 0; - } - - public static boolean elementAllowsInBound(Matcher matcher) { - return (Integer.parseInt(matcher.group(elementBits)) & 1) != 0; - } - - public static boolean elementAllowsOutBound(Matcher matcher) { - return (Integer.parseInt(matcher.group(elementBits)) & 1<<1) != 0; - } - - public static boolean elementHasCommentLine(Matcher matcher) { - return (Integer.parseInt(matcher.group(elementBits)) & 1<<2) != 0; - } - - public static boolean elementIsIO(Matcher matcher) { - return (Integer.parseInt(matcher.group(elementBits)) & 1<<3) != 0; - } - - public static String normalize(String str) { - // start by removing all tabs from the string, not really necessary - // but does make the equation cleaner (could also be done in the read - // method above) - str = str.replaceAll("\t", ""); - - // remove inline :AND: and :OR: etc (not done currently) - - // transform all variable names to (single-)quoted modelica syntax - StringBuilder result = new StringBuilder(); - int offset = 0; - - Matcher matcher = Pattern.compile(VAR_NAME).matcher(str); - while (matcher.find()) { - result.append(str.substring(offset, matcher.start())); - - String replacement = matcher.group(); - - if (replacement.startsWith("\"")) { - replacement = replacement.substring(1, replacement.length() - 1); - } - - result.append('\''); - result.append(replacement); - result.append('\''); - - offset = matcher.end(); - } - if (offset < str.length()) { - result.append(str.substring(offset)); - } - - str = result.toString(); - - return str; - } - -}