/* * v1.0 Edited by Jing and Omair (05/11/2005) * -Fixed FileDialog box; made modal with respect to "this class" so that when it is clicked it stays on top. * * -Fixed Save as .bat --> so that now when there's incorrect *.ma filename or if there's no filename * you won't be able to save a *.bat file. * * -Fixed Error in testString() * currently the function is setup so that it seeks numbers in the string [no matter where] and contatenates them, adds 1 to the concatenated number and appends the number to the end of the string. * so if you make a file name called 4567i and you overwrite the file [using automatic] you will get a new file called: 4567i4568 when it should be 4567i1 * Fix: rewrote the function by checking from the back instead of from the front to find the location of a character. Then the numbers [after the char] will be chopped off as a substring and returned. * * -Fixed Error in setDigit() * When trying to save a *.bat file called "2" and saving another file called "2" using the automatic save will result in either window not responding or nothing happens. * Fix: altered the setDigit() [no more index out of bounds exception] so that when filename is a number it returns a string representation of the newly updated number. * * -Fixed Error when closing window * Bug: When window is first opened, it will not close when clicking on the "X" (close button at the top right corner of window) * Fix: set OK2Close = true by default so that window will close. * * -Fixed Error for when canceling browse * BUG: When there's a file in the text box [text box filled] beside the browse button and if browse is clicked and you hit cancel to "cancel" file selection. * The file name will be erased from the text box [empty text box] and you will have to reselect the file. * Fix: Check for if the file returned from the file selection is equal to "" [nothing] if so then don't update text box field. * * -Fixed Error for when there's a space in file name * Bug: ltrans will not start due to space in folder name * Fix: TempFile.write(string) now has the string enclosed in quotes and ltrans.exe appended * * - Fixed the bug for browsing for files that contains spaces * Bug: Files with spaces will not run. * Fix: In collectParameters all file names are enclosed in quotes. * */ package CELLDEV.buttons; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import CDBuilder.CDBuilderPlugin; import CDBuilder.buttons.OverwriteGui; import CDBuilder.console.ConsoleDocument; import CDBuilder.console.StreamHandler; /** * @author Ali Monadi * * This class is responsible for the popup gui which appears when the Ltrans button * is pressed. The requested application will then run as a separate process. * */ public class LtransGUI extends Dialog{ private int fileCount; /*will be used for the number of files generated for each set of RULES*/ private Shell parent; private String title; private String message1; private String message2; private String message3; private String message4; private String message5; private String parseInfo; private String resultFile; private String hexagonal; private String triangular; private String coupleMessage; private String maFileName; /*It will also contain the extention*/ private String prsInfoName; private String conversionType;/*either 'hexagonal' or 'triangular' */ private String advOption; private Button simuButton; private Button doneButton; private Button killButton; private Button parseInfoButton; private Button saveSetButton; private Button loadSetButton; private Button saveBatButton; private Button loadBatButton; private Button checkBoxAdv; private Button checkBoxHex; private Button checkBoxTrian; private Button checkBoxparseInfo; private Button checkBoxComment; private Text textMa; private Text textResult; private Text textparseInfo; private Text textAdv; private Text textComment; private static boolean checkedparseInfo = false; private static boolean checkedAdv = false; private static boolean checkedComment = false; private boolean simuKilled = false; private RunSimu rsimu; private Process simuProcess; private IPath path; private IPath internalPath; private Composite composite; private int n; //window will only cose if OK2Close is true. This is set to true automatically at beginning [not set in constructor] private boolean OK2Close=true; class conWrite implements Runnable { String line; public conWrite(String line) { this.line = line; } public void run() { ConsoleDocument.getCDOS().set(line); } } class RunSimu extends Thread { Dialog d; String command; String maFile; String resultFile; public RunSimu( Dialog d, String maFile, String resultFile) { this.d = d; this.maFile = maFile; this.resultFile = resultFile; } public void run() { try { ConsoleDocument cdos = ConsoleDocument.getCDOS(); IContainer container = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(path); Display.getDefault().syncExec(new Runnable() { public void run(){ doneButton.setEnabled(true); killButton.setEnabled(false); simuButton.setEnabled(true); d.close(); } }); for(int i = 1; i < fileCount+1; i++){ command = collectParameters(i); System.out.println("button pressed "+command); if (command == null) return; FileWriter tempFile = new FileWriter(path.append("tempSimu.bat").toString()); //testing purposes System.out.println("command: " + command); tempFile.write("\"" + internalPath + "ltrans.exe\" " + command); //internalPath is where the cd++.exe is located tempFile.close(); simuProcess = Runtime.getRuntime().exec("cmd /c \"" + path.toString() + "tempSimu.bat\"", null, new File(path.toString())); StreamHandler outputHandler = new StreamHandler(simuProcess.getInputStream(), "OUTPUT", true); StreamHandler errorHandler = new StreamHandler(simuProcess.getErrorStream(), "ERROR", true); outputHandler.start(); errorHandler.start(); simuProcess.waitFor(); container.refreshLocal(1,null); ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path.append("tempSimu.bat")).delete(true,null); } if (simuKilled) { Display.getDefault().syncExec(new conWrite("***User has killed the simulation***" + "\n")); simuKilled = false; } putFileTogether(); container.refreshLocal(1,null); }catch (Throwable T) { T.printStackTrace(); } } /* * This function will creat a new ma file containing the new translated rules. * It will copy all contents of the old ma file(except for rules). If will get * Rules from the newly generated files by the ltrans.exe * */ public void putFileTogether(){ String line; int filesRead = 0; BufferedReader batchReader2; FileWriter tempFile = null; boolean write = true; System.out.println("puting files together"); try{ FileWriter newFile = new FileWriter(path.toString()+"\\"+ resultFile); BufferedReader batchReader = new BufferedReader(new FileReader(path.toString()+"\\"+ maFile)); line = batchReader.readLine(); while(line!= null){ System.out.println(line); if(line.startsWith("[") && line.trim().endsWith("-rule]") && (filesRead != fileCount) ){ String line2; write = false; filesRead++; System.out.println("write = false\n"); batchReader2 = new BufferedReader(new FileReader(path.toString()+ "trans" + filesRead+ ".ma")); newFile.write(line + "\n"); line2 = batchReader2.readLine(); while(line2 != null){ newFile.write(line2 + "\n"); line2 = batchReader2.readLine(); } newFile.write("\n"); batchReader2.close(); new File(path.toString()+ "trans" + filesRead+ ".ma").delete(); new File(path.toString()+ "rule" + filesRead+ ".ma").delete(); } if (write){ System.out.println("still writing"); newFile.write(line + "\n"); } line = batchReader.readLine(); }//end of while loop batchReader.close(); newFile.close(); }catch(Exception e){System.out.println("error"); e.printStackTrace(); } } /* * This function will record all the parameters entered into a string * * @param int count, used for adding an increment to the file name of the set of rules * @return String will contain all parameters. if there is an error found NULL will be returned */ public String collectParameters(int count){ String[] param = new String[9]; //checkExtention(textResult,".ma") //do this check before getting parameters param[0] = "-m" + "rule"+count + ".ma"; if ( conversionType != null ) param[1]= conversionType; param[2] = "-o" + "trans" + count + ".ma"; //Detailed parse info is an optional parameter if( prsInfoName != null ) param[3] = "-p" + count + prsInfoName; if( advOption != null ) param[4] = advOption; String combine = ""; for (int n = 0; n < 5; n++ ) { if (param[n] != null) combine = combine + " " + param[n]; } combine = combine.concat( " " ); return combine; } }// end of class RunSimu /* * constructor for main class * * @param Shell parentShell * @param IPath path, which is the project path * @param IPath internalPath, which is the path to the internal directory */ public LtransGUI(Shell parentShell,IPath path, IPath internalPath) { super(parentShell); parent = parentShell; this.title = "Lattice Translator"; message1 = "Model file (.ma)"; message4 = "Advanced Users Only. Enter desired parameters"; message5 = "Comments"; parseInfo = "Save Detailed Parsing Info (.txt)"; resultFile = "Resulting Model file (.ma)"; hexagonal = "Hexagonal to Square" ; triangular = "Triangular to Square"; fileCount = 0; OK2Close=true;//test this.internalPath = internalPath; this.path = path; } /* * Determines if a text box is left empty and displays error message * @return false of empty true otherwise */ private boolean isEmpty(String parameter,Text textBox){ String value = textBox.getText(); if(value.length()== 0){ MessageBox mbox = new MessageBox(new Shell(),SWT.ICON_ERROR | SWT.OK); mbox.setText("Error"); mbox.setMessage(parameter+" is not entered"); mbox.open(); composite.setEnabled(true); doneButton.setEnabled(true); killButton.setEnabled(false); simuButton.setEnabled(true); saveBatButton.setEnabled(true); loadBatButton.setEnabled(true); OK2Close = true; doneButton.setEnabled(true); killButton.setEnabled(false); simuButton.setEnabled(true); return true; } return false; } /* * checks to see if the given string matches a file name found in the project directory * * @param String file, name of file * @param String errMsg, message to be displayed IF file was not found */ private boolean checkFileExistence(String file, String errMsg){ IWorkspaceRoot root = (IWorkspaceRoot)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getInput(); IResource[] files; IFile fileHandle = null; try { files = root.getContainerForLocation(path).members(); for(int i=0;i indexEndMa2 && (command.indexOf( ".ma",indexStartMa2 ) != -1) ) ) indexEndMa2 = command.indexOf( ".ma",indexStartMa2 ); int indexStartparseInfo = command.indexOf( "-p",indexEndMa2 ); int indexEndparseInfo = command.indexOf(".txt",indexStartparseInfo ); //int indexStartAdv = command.indexOf( " ", indexEndMa2); //ME //ME REVISED SECTION START int indexStartAdv = -1; if ( (indexStartparseInfo!=-1) && (indexEndparseInfo!=-1) ) { indexStartAdv = command.indexOf( " ", indexEndparseInfo); } else if (indexStartparseInfo==-1) { indexStartAdv = command.indexOf( " ", indexEndMa2); } //ME REVISED SECTION END if (indexStartMa != -1){ textMa.setText( command.substring(indexStartMa + 2, indexEndMa + 3) ); } if (indexStartMa2 != -1){ textResult.setText( command.substring(indexStartMa2 + 2, indexEndMa2 + 3) ); lastIndex = indexEndMa2 + 4; } if( indexStrtConversion != -1 ){ if (command.indexOf( "hexagonal ") != -1){ //ME checkBoxHex.setEnabled(true); checkBoxHex.setSelection(true); checkBoxTrian.setSelection(false); //ME checkBoxTrian.setEnabled(false); }else if (command.indexOf( "triangular ") != -1){ //ME checkBoxTrian.setEnabled(true); checkBoxTrian.setSelection(true); checkBoxHex.setSelection(false); //ME checkBoxHex.setEnabled(false); } }else{ MessageBox mbox = new MessageBox(new Shell(),SWT.ICON_ERROR | SWT.OK); mbox.setText("Error loading"); mbox.setMessage("Parser does not detect expected parameter"); mbox.open(); return; } if (indexStartparseInfo != -1){ checkBoxparseInfo.setSelection(true); textparseInfo.setEnabled(true); textparseInfo.setText(command.substring(indexStartparseInfo + 2, indexEndparseInfo + 4)); lastIndex = indexEndparseInfo + 5; } else{ checkBoxparseInfo.setSelection(false); //ME textparseInfo.setEnabled(false); //ME textparseInfo.setText(""); //ME textparseInfo.setText("parseInfo.txt"); } /* //ORIGINAL SECTION START if (command.indexOf( " ",indexStrtConversion) < command.length()){ textAdv.setEnabled(true); checkBoxAdv.setEnabled(true); checkBoxAdv.setSelection(true); textAdv.setText( command.substring(lastIndex, command.length()) ); } */ //ORIGINAL SECTION END //ME REVISED SECTION START if ( (indexStartAdv!=-1) && ((command.length()-indexStartAdv) > 1) ) { //advanced present checkBoxAdv.setSelection(true); textAdv.setEnabled(true); textAdv.setText(command.substring(indexStartAdv+1, command.length()).trim() ); } else { //advanced not present textAdv.setText(""); checkBoxAdv.setSelection(false); textAdv.setEnabled(false); } //ME REVISED SECTION END }catch (Exception error) { error.printStackTrace(); System.out.println("************EXCEPTION: loading batch file******"); } } }); Label errorMessageLabel = new Label(composite, SWT.NONE); errorMessageLabel.setFont(parent.getFont()); return composite; } /* *creats a checkBox for dialog box * * @param Composite composite * @param boolean used to check off the box * * @return Button **/ private Button createCheckBoxButton(Composite composite, boolean checked) { Button checkBox = new Button(composite, SWT.CHECK); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.BEGINNING; checkBox.setLayoutData(gridData); checkBox.setSelection(checked); return checkBox; } //ME REVISED SECTION START private Button createRadioButton(Composite composite, boolean checked) { Button radioB = new Button(composite, SWT.RADIO); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.BEGINNING; radioB.setLayoutData(gridData); radioB.setSelection(checked); return radioB; } //ME REVISED SECTION END /* *creats a lable for dialog box * * @param String message * @param Composite composite * @param Composite parent * * @return Label **/ private Label createLabel(Composite parent, Composite composite, String message) { Label label = new Label(composite, SWT.NONE); label.setText(message); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.horizontalSpan=10; label.setLayoutData(gridData); label.setFont(parent.getFont()); return label; } private Label createLabel(Composite parent, Composite composite, String message, int size) { Label label = new Label(composite, SWT.NONE); label.setText(message); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.horizontalSpan=size; label.setLayoutData(gridData); label.setFont(parent.getFont()); return label; } /** * @see org.eclipse.jface.window.Window#close() */ public boolean close() { if (OK2Close) { boolean returnValue = super.close(); return returnValue; } return true; } /** * This method takes the fileName and concatenates the digits of n * [found through testString] to the end of the string [if required]. * Edited: by Jing Cao * * @param fileName * @param integer to be appended * @return String tempFileName [new file name with the number at end] */ private String setDigit(String fileName, int n) { //beg setDigit String tempFileName = new String(fileName); String tempString; char c; int i; //Note: the string array only extends from 0 -> (length of string-1) for (i = (fileName.length() - 1); i >= 0; i--) { //This for loop will find the location where the number starts. c = tempFileName.charAt(i); if ((c < '0') || (c > '9')) //if the chracter is not a number then break out of the for loop break; // the value of 'i' will be the index where there is a character [not a number] } tempFileName = tempFileName.trim(); //redundant, it gets rid of spaces infront or after the fileName tempString = new String(Integer.toString(n)); if (i < 0) //the fileName consists of all numbers return tempString; // then return the updated number as the file name! //else tempFileName = tempFileName.substring(0, i + 1); //get the character part of the string //note: the +1 is required because substring(beg,end) is "exclusive" of the end. return tempFileName.concat(tempString); //adds the updated number to the end of the characters and returns the string } //end setDigit /** * This method takes a file name (stripped off ".bat") and * returns the digits (numbers) at the end as a string. * Returns '0' if there's no number at the end of the file name. * Will return the file name if the string is composed of only numbers. * Edited by Jing Cao. * * @param fileName * @return number [of the type string] */ private String testString(String fileName) { //beg testString() //Variable Declarations String tempString = new String(fileName); //redunant but just to make shure that we don't make changes to testString() String number = new String(""); //this string stores the number int i; char c; //Note: the string array only extends from 0 -> (length of string-1) for (i = (fileName.length() - 1); i >= 0; i--) { //This for loop will find the location where the number starts. c = tempString.charAt(i); if ((c < '0') || (c > '9')) //if the chracter is not a number then break out of the for loop break; // the value of 'i' will be the index where there is a character [not a number] } //if statements to set the number string properly if (i == (fileName.length() - 1)) //sets number to 0 if no number found at end of the string. number = "0"; else if (i == -1) //means that the file name is a number! number = new String(fileName); //then set number to be the file name else number = tempString.substring(i + 1); //creates the number string by chopping off the letters number = number.trim(); //removes any spaces at the beginning or the end of the string return number; } //end testString() /* * opens up dialog box for opening/accessing files * * @param String filter, for viewing files of only type filter(ie: filter = *.ma) */ //this function is used by load.bat to load a new file. private String NewFileGui(String filter) { composite.setEnabled(false); simuButton.setEnabled(false); doneButton.setEnabled(false); OK2Close = false; FileDialog fileDialog = new FileDialog(parent); String[] extention = new String[1]; extention[0] = filter; fileDialog.setFilterPath(path.toString()); fileDialog.setFilterExtensions(extention); fileDialog.open(); composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); loadBatButton.setEnabled(true); saveBatButton.setEnabled(true); OK2Close = true; return fileDialog.getFileName(); } /* * This function is responsible for saving a batch file * * @param String filter, which should be ".bat" */ private void SaveBatchFileGui(String filter) { String[] param = new String[10]; String command = collectParameters(); String temp; if (command == null){ composite.setEnabled(true); doneButton.setEnabled(true); simuButton.setEnabled(true); saveBatButton.setEnabled(true); loadBatButton.setEnabled(true); OK2Close = true; return; } composite.setEnabled(false); simuButton.setEnabled(false); doneButton.setEnabled(false); FileDialog fileDialog = new FileDialog(parent, SWT.SAVE); String[] extention = new String[1]; extention[0] = filter; fileDialog.setFilterPath(path.toString()); fileDialog.setFilterExtensions(extention); fileDialog.open(); String fileName = fileDialog.getFileName(); try { if (fileName.endsWith(".bat")) { fileName = fileName.substring(0, fileName.length()-4); } //this code segment makes sure nothing is saved when u cancel the save dialog box if(fileName == ""){ fileDialog.setFilterPath(""); fileDialog.setFilterExtensions(null); composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); loadBatButton.setEnabled(true); OK2Close = true; return; } File existFile = new File(path.toString() + fileName + ".bat"); boolean cancelled = false; if (existFile.exists()) { IPreferenceStore store = CDBuilderPlugin.getDefault().getPreferenceStore(); if(store.getInt("batchChoice") == 3) { OverwriteGui ovG = new OverwriteGui(new Shell()); ovG.open(); if (ovG.buttonPressed() == 0) { System.out.print("canceled saving bat"); cancelled = true; composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); loadBatButton.setEnabled(true); OK2Close = true; } if (ovG.buttonPressed() == 2) { boolean looking = true; while(looking) { n=(Integer.decode(testString(fileName))).intValue(); n++; temp = setDigit(fileName,n); File existFileCount = new File(path.toString() + temp+ ".bat"); System.out.println(path.toString() + temp + ".bat"); fileName = temp; if(!existFileCount.exists()) { looking = false; MessageBox mbox = new MessageBox(new Shell(),SWT.ICON_INFORMATION | SWT.OK); mbox.setText("Saving File"); mbox.setMessage("The file has been saved as "+ fileName+".bat"); mbox.open(); composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); loadBatButton.setEnabled(true); } } if(ovG.noAskAgain() ) store.setValue("batchChoice", 2); } if (ovG.buttonPressed() == 1) { if(ovG.noAskAgain() ) store.setValue("batchChoice", 1); } } else if(store.getInt("batchChoice") == 2) { boolean looking = true; int n = 0; while(looking) { n++; File existFileCount = new File(path.toString() + fileName + "-" + n + ".bat"); System.out.println(path.toString() + fileName +"-" + n + ".bat"); if(!existFileCount.exists()) { looking = false; fileName = fileName.concat("-" + Integer.toString(n)); } } } else { } } if (!cancelled) { composite.setEnabled(false); simuButton.setEnabled(false); doneButton.setEnabled(false); OK2Close = false; FileWriter batchFile = new FileWriter(path.toString() + fileName + ".bat"); System.out.println(path.toString() + fileName + ".bat"); param[0] = "-m" +textMa.getText(); System.out.println(command); batchFile.write(command + "\n"); batchFile.write("rem " + textComment.getText() + "\n"); batchFile.write("pause"); batchFile.close(); composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); loadBatButton.setEnabled(true); OK2Close = true; } } catch (Exception e) { e.printStackTrace(); } } }