/* * First Created on Jun 20, 2003 * * v1.0 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 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 the bug for installation of eclipse into a folder with spaces * Bug: Simulation will not work due to path problems [path with spaces] * Fix: All instances of "cmd" [dos/unix command] are fixed to a format that supports spaces * Quotes are added to path names so that it will support spaces in file names. * * - 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. * * v1.1 by Chiril Chidisiuc (4/07/2006) * - event file selected automatically. * Event file is automatically selected if makefile exists. * If more than one event files exist, the event file with the same name as MA is selected as default. * If neither of event files match MA name, the first event file in the directory is inserted as default. * If makefile is obtained from outside the project, then the desired event file must be selected manually. * - Added automation for log, out, and bat file naming system. * - Added tooltips to "Advanced field", changed text within labels (e.g. time) * * Bug: if text box for makefile is not empty, and then contents are manually deleted, * then the "out" and "log" text boxes are not cleared properly. * Fix: in progress... * * - Fixed loading procedure from batch file * Bug: parameters loaded from batch file have first letters missing or paramteres are not loaded at all * Fix: changed indexes to search through the string containing the parameters * * - Fixed loading parameters from batch file * Bug: advanced field is dependent on order of the parameters in Batch file. * Therefore, advanced field often won't load or load the whole command line * if LOG file or stop time parameter or both are missing. Also, duplication of * entries can occure (example: event file input through advanced fiels will * appear in both event file and advanced fields when bat file is loaded) * Fix: store the entries which have designated fields (ma, out, log, ev, time...) * in array. Then remove each entry of array from the command line. * * - Changed text on labels of Simulation dialog box ("Simulation stop time ..."). * * - Added new features: * ==>the log/out file names are generated in format [name]LOG_X.log/[name]OUT_X.out, where 'X' is a number. * if X==0, then [name]LOG.log/[name]OUT.out is created * ==> fields of simulation dialog box are automatically filled when MA file is selected * (names are selected/created with respect to MA file name) * ==>versions are stored in hashMap maVersions * ==>parameters are not duplicated in "Advanced" and other fields * * new methods added: * -traverseVersions(list:String[], maName:String):int * -setVersion(maName:String):void * -private void setInitialEventFileName() * -getTypeOfFileVersion(name:String, maName:String):int * -getNextBatVersion(batName:String):int * #getFileVersion(sequence:String):int * #getFileNames(extension:String):String[] * #convertPathToCmd(path:String):String * #checkEventFileExistence():void * -getAdvancedFieldText(command:String, excludeFromAdvancedFieldText:String[]):String */ package CDBuilder.buttons; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; 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.dialogs.IInputValidator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; 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.console.ConsoleDocument; import CDBuilder.console.StreamHandler; /** * This is constructor for SimuGui * * @author ssim */ public class SimuGui extends Dialog { private boolean isCellDev; private boolean OK2Close = true; private HashMap maVersions; private Shell parent; private String message1; private String message2; private String message3; private String message4; private String message5; private String message6; private String message7; private String messageAuto; private String title; private static String maName; private static String maValue; private static String evValue; private static String outValue; private static String logValue; private static String timeValue; private static String advValue; private static String commentValue; private Button simuButton; private Button doneButton; private Button killButton; private Button saveSetButton; private Button loadSetButton; private Button saveBatButton; private Button loadBatButton; private Label colon1, colon2, colon3; private Button checkBoxEv; private Button checkBoxOut; private Button checkBoxTime; private Button checkBoxLog; private Button checkBoxAdv; private Button checkBoxComment; private Button autoNameLog; private Button autoNameOut; private Button autoNameBoth; //this rudiment is yet to be implemented private Button fileButtonEv; private Button fileButtonMa; private Button fileButtonLog; private Button fileButtonOut; private IResource[] projectFiles; private Text textMa; private Text textEv; private Text textOut; private Text textLog; private Text textTime1, textTime2, textTime3, textTime4; private Text textAdv; private Text textComment; private static boolean checkedEv = false; //event file checkbox unchecked initially private static boolean checkedOut = true;//out file checkbox is selected initially private static boolean checkedLog = true;//log file checkbox is selected initially private static boolean checkedTime = true;//time checkbox is selected initially private static boolean checkedAdv = false;//advanced checkbox unchecked initially private static boolean checkedComment = false; private static boolean checkedAutoLog = false; //automate name generation for log files private static boolean checkedAutoOut = false; //automate name generation for out files private static String outAutoName; private static String logAutoName; private static String stdOutText; private static String stdLogText; private boolean simuKilled = false; private RunSimu rsimu; private IContainer container; private IWorkspaceRoot root; private IPath internalPath; private IPath projectPath; private IPath path; private Process simuProcess; private Label errorMessageLabel; private IInputValidator validator; private boolean noErrors; //modifications by Sameen Rehman private Composite composite; private int n; //Chiril Chidisiuc: this was used before 2006-05-15 for naming... 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; public RunSimu(String command, Dialog d) { this.command = command; this.d = d; } public void run() { try { ConsoleDocument cdos = ConsoleDocument.getCDOS(); IContainer container = ResourcesPlugin .getWorkspace() .getRoot() .getContainerForLocation( path); FileWriter tempFile = new FileWriter(path.append("tempSimu.bat").toString()); tempFile.write(command); tempFile.close(); //added quotes to work for file names that have spaces 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(); int exitVal = simuProcess.waitFor(); container.refreshLocal(1, null); ResourcesPlugin .getWorkspace() .getRoot() .getFileForLocation(path.append("tempSimu.bat")) .delete(true, null); Display.getDefault().syncExec(new Runnable() { public void run() { doneButton.setEnabled(true); killButton.setEnabled(false); simuButton.setEnabled(true); d.close(); } }); if (simuKilled) { Display.getDefault().syncExec( new conWrite( "***User has killed the simulation***" + "\n")); simuKilled = false; } } catch (Throwable T) { T.printStackTrace(); } } }//end class runSimu /** * constructor for SimuGui class */ public SimuGui( Shell parentShell, IPath path, boolean isCellDev, IPath internalPath) { super(parentShell); parent = parentShell; this.title = "Simulate Project"; message1 = "Coupled Model file name (.ma)"; message2 = "Event file name (.ev)"; message3 = "Output file name (.out)"; message4 = "Log file name (.log)"; message5 = "Simulation stop time (hh:mm:ss:ms)"+"\n" +"(NOTE: unchecked time option means 'infinity' as stop time)"; message6 = "Advanced Users Only. Enter desired parameters:"; message7 = "Comments"; messageAuto = "Autogenerate the names for \"out\", \"log\" files:"; this.internalPath = internalPath; this.isCellDev = isCellDev; this.path = path; this.root = (IWorkspaceRoot) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage().getInput(); this.projectPath = this.root.getLocation(); this.container = this.root.getContainerForLocation(this.projectPath); this.maVersions = new HashMap(); } /** * Determines if a text box is left empty and displays error message * * @param parameter:String * @param textBox:Text * @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(parent, SWT.ICON_ERROR | SWT.OK |SWT.APPLICATION_MODAL); 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; //removed the mbox.wait(); //along with the try-catch block so that now the msg box works correctly now 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 < files.length; i++) { if (files[i] instanceof IFile && files[i].getName().equalsIgnoreCase(file)) { fileHandle = (IFile) files[i]; break; } } if (fileHandle == null) { MessageBox mbox = new MessageBox(parent, SWT.ICON_ERROR | SWT.OK | SWT.APPLICATION_MODAL); mbox.setText("Error"); mbox.setMessage(errMsg); mbox.open(); return false; } return true; } catch (CoreException e) { MessageBox mbox = new MessageBox(parent, SWT.ICON_ERROR | SWT.OK); mbox.setText("Error"); mbox.setMessage("Error occured while accessing file"); mbox.open(); e.printStackTrace(); //removed the try-catch for msg.wait() return false; } } /** * This function will check to see if the file name has the specified * extension and adds the extension otherwise. The final file name WITH * extension is returned. * * @param Text name, the text box value containing the file name * @param String extention, the extention the name shoule have * @return A string containing the file name with the proper extention */ public String checkExtention(Text name, String extention) { String fileName = name.getText().trim(); if (!fileName.endsWith(extention) && !fileName.endsWith(extention.toUpperCase())) return fileName.concat(extention); return fileName; } /** * This method defines the advanced field text when a BAT file is loaded by removing the * unnecessary entries (ma, log, out, ev, time...) *@param command:String - command line containing all parameters *@param excludeFromAdvancedFieldText:String[] - array of parameters that should not appear in advanced field *@return advField:String - string representation of text for advanced field *@author Chiril Chidisiuc *@version 2006-07-11 */ private String getAdvancedFieldText(String command,String [] excludeFromAdvancedFieldText){ String advField = ""; int startParameter; int endParameter; int i=0; while (iname is not the same as MA file * '0'==>name is the same as MA file, but doesn't contain version * 'fileVersion'==>(fileVersion stands for any positive integer) name is the same as MA file and * contains version X. * * @param name:String - name of the file being checked * @param maName:String - name of the MA file * @return intger representation of the file version * @author Chiril Chidisiuc * @version 2006-06-24 */ private int getTypeOfFileVersion(String name, String maName){ String cleanName = ""; boolean needToClean = false; int startIndex = 0; if (name.contains("LOG")){ startIndex = name.indexOf("LOG"); needToClean = true; }else if (name.contains("OUT")){ startIndex = name.indexOf("OUT"); needToClean = true; } if (needToClean == true) { int endIndex = startIndex + 3; name = name.substring(0, startIndex) + name.substring(endIndex); if (name.equals(maName)) { return 0; // name is the same as MA file } int startSequence = name.lastIndexOf("_"); if (startSequence == -1 && name.equals(maName)) { return 0; // name is the same as MA file, but doesn't contain // version } else if (startSequence == -1 && !name.equals(maName)) { return -1; // name is not the same as MA file, and does not // contain version } String baseName = name.substring(0, startSequence); String sequence = name.substring(startSequence + 1); int fileVersion = this.getFileVersion(sequence); if (fileVersion != -1) { // an integer is returned if (baseName.equals(maName)) { return fileVersion; // name is the same as MA file, and // contains version } else { return -1; // name is not the same as MA file, and contains // version } } } return -1; //name not associated with any MA file } /** * This method traverses the list of files provided and checks for the most recent version found... * * @param list:String[] - a string array containing the list of files * @return none * @author Chiril Chidisiuc * * @version 2006-06-23 */ private int traverseVersions(String[] list, String maName){ int versionToStore = ((Integer)this.maVersions.get(maName)).intValue(); for (int i = 0; i < list.length; i++) { if (list[i] == null){ //no more files to check break; } int checkVersion = this.getTypeOfFileVersion(list[i], maName); if (checkVersion>versionToStore){ versionToStore = checkVersion; } } return versionToStore; } /** * When this method is called, it checks for the latest version of the files and sets the appropriate * version of simulation results. Example: if ATM_1.log or ATM_3.out already exist, * the new set will be named ATM_4.log and ATM_4.out * * @param none * @return next version of simulation results (for names of *.log and *.out files). * @author Chiril Chidisiuc * @version 2006-06-22 */ private void setVersion(String maName){ this.maVersions.put(maName,new Integer(-1)); String[] outFileList = this.getFileNames("out"); String[] logFileList = this.getFileNames("log"); String[] batFileList = this.getFileNames("bat"); // the folllowing three statements will check whichever file has the latest version: // Search for latest version of "*.out" files int version1 = traverseVersions(outFileList, maName); //latest "out" file // Search for latest version of "*.log" files int version2 = traverseVersions(logFileList, maName); //latest "log" file int temp; if (version1 > version2){ temp = version1; }else if (version1 < version2){ temp = version2; }else{ temp = version1; } temp++; this.maVersions.put(maName, new Integer(temp)); } /** * #getFileName(String extension):void - returns the list of all file names * with such extension as a String array. extension must be entered as * a parameter WITHOUT the ".". * Examples of proper extensions: "exe", "ma", "ev", "doc" etc. * * @param extension:String - the file with this extension is checked * @return fileName:String - name of the file is returned (without extension!) * @author Chiril Chidisiuc * * @version 2006-06-07 */ protected String[] getFileNames(String extension) { int count = 0; try { this.projectFiles = this.root.getContainerForLocation(path).members(); } catch (CoreException e) { Display.getDefault().syncExec( new conWrite( "Problem in getFileName(extension:String):String[] - " + e)); e.printStackTrace(); }//get files from working directory String [] fileNames = new String[projectFiles.length]; for (int i = 0; i < projectFiles.length; i++) { //search files if (projectFiles[i] instanceof IFile && (projectFiles[i].getName().toUpperCase() .endsWith("." + extension.toUpperCase()))) { //found the file with specified extension String fileNameWithExt = projectFiles[i].getName(); int offset = fileNameWithExt.length() - 1 - extension.length(); fileNames[count] = fileNameWithExt.substring(0, offset); count++; } } return fileNames; } /** * This method collects all inputs of the dialog box and arranges them for * further use as input for the command line. This method is called when * either "Proceed" or "Save BAT file" is pressed. * * ---modified by Chiril Chidisiuc 2006-06-12 * * @param none @return String containing the command line * * @version 2006-06-13 */ private String collectParameters() { String[] param = new String[10]; try { //*.ma file input (user-selected) if (isEmpty("Model file", textMa)) { composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); return null; } if (!checkFileExistence(checkExtention(textMa, ".ma"), "MA file does not exist")) { return null; } param[0] = "-m\"" + checkExtention(textMa, ".ma") + "\""; // event file input // Chiril Chidisiuc: NOTE - the event file is already dealt by // setEventFileName() in CreateDialogArea(Composite) method if (textEv.getEnabled() == true) { if (isEmpty("Event", textEv)) { composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); return null; } else { evValue = textEv.getText().trim(); } if (!checkFileExistence(checkExtention(textEv, ".ev"), "Event file does not exist")) { return null; } param[1] = "-e\"" + checkExtention(textEv, ".ev") + "\""; } //*.out file output if (textOut.getEnabled() == true) { if (isEmpty("Output file", textOut)) { composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); return null; } else { outValue = textOut.getText().trim(); param[2] = "-o\"" + checkExtention(textOut, ".out") + "\""; } } //*.log file output if (textLog.getEnabled() == true) { if (isEmpty("Log file", textLog)) { composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); return null; } else { logValue = textLog.getText().trim(); param[3] = "-l\"" + checkExtention(textLog, ".log") + "\""; } } //stop time parameter if (textTime1.getEnabled() == true) { if (isEmpty("Hour value", textTime1) || isEmpty("Minute value", textTime2) || isEmpty("Second value", textTime3) || isEmpty("Milli-second value", textTime3)) { composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); return null; } else timeValue = textTime1.getText().trim() + ":" + textTime2.getText().trim() + ":" + textTime3.getText().trim() + ":" + textTime4.getText().trim(); param[4] = "-t\"" + timeValue + "\""; } //Advanced users text field input if (textAdv.getEnabled() == true) { if (isEmpty("Advance parameter", textAdv)) { composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); return null; } param[5] = textAdv.getText().trim(); } } catch (Exception e) { e.printStackTrace(); } int n = 0; String combine = ""; while (n < 6) { if (param[n] != null) combine = combine + " " + param[n]; n++; } if (isCellDev) { //Chiril Chidisiuc: SOLUTION 1: combine = "cd /D \"" + convertPathToCmd(path.toString()) + "\"\n" + "\"" + internalPath + "simuOrig.exe\" " + combine + " "; //Chiril Chidisiuc: SOLUTION 2: // combine = "\"" + convertPathToCmd(internalPath.toString()) + "simuOrig.exe" + "\" " + combine + " "; /* String concatPath; int startConcatPath = internalPath.toString().lastIndexOf("eclipse"); int endConcatPath = startConcatPath + 8; concatPath = internalPath.toString().substring(endConcatPath); combine = "cd ./" + concatPath + "\n" + "simuOrig.exe " + combine + " ";*/ //Chiril Chidisiuc: SOLUTION 3: /* //alternative solution: //M:\>COPY "C:\My Downloads\RealPlayer10-5GOLD.exe" "E:/" /y // 1 file(s) copied. //startFrom - for "/plugins/CD++Builder_1.1.0/internal/" int startFrom = internalPath.toString().lastIndexOf("eclipse") + 8; //startTo - for "/workspace/.../" int startTo = path.toString().lastIndexOf("eclipse") + 8; //homePath - "C:\eclipse" (example) String homePath = convertPathToCmd( internalPath.toString().substring(0,startFrom) ); //copyFrom - "\plugins\CD++Builder_1.1.0\internal\" String copyFrom = convertPathToCmd( internalPath.toString().substring(startFrom) ); //copyTo - "\workspace\...\" String copyTo = convertPathToCmd( path.toString().substring(startTo) ); //this copies file simuOrig.exe to working directory... String copyFile = "COPY \""+homePath+copyFrom+"simuOrig.exe"+"\" \"" +homePath+copyTo+"\" /y"+"\n"; //the following line now copies SimuOrig.exe to working directory and runs it from this location combine = copyFile + "cd ./" + path.toString().substring(startTo)+ "\n" + "simuOrig.exe " + combine; */ }else{ String concatPath; int startConcatPath = path.toString().lastIndexOf("eclipse"); int endConcatPath = startConcatPath + 8; concatPath = path.toString().substring(endConcatPath); //simu.exe is created after compilation in working directory (.../workspace/.../) combine = "cd ./\"" + concatPath + "\"\n" + "simu.exe" + combine + " "; //Chiril Chidisiuc: batch must be run from Eclipse... // combine = "simu.exe" + combine + " "; Chiril Chidisiuc: this is original solution... } return combine; } /** * This method converts the given path to command line format by replacing * the path delimiters with Windows path delimiters. * (each '/' is replaced with '\') * * @param path:String - the given current path (e.g. "C:/eclipse/workspace") * @return converted path as a String - path with new delimiters (e.g. "C:\eclipse\workspace") * @author Chiril Chidisiuc * * @version 2006-06-20 */ protected String convertPathToCmd(String path){ char c1 = 47; // character 47 is: '/' char c2 = 92; // character 92 is: '\' return path.replace(c1,c2); //replace(char oldChar, char newChar) } /** * This method is required to determine the version of the file (applied to * *.out, *.log). This can later be used to determine the name of the next * version (if such must be created) See collectParameters method for * further use of this method. NOTE: this method has limits in max/min value * that it can return...[-2147483648,2147483647] * * @param sequence:String - sequence which must be traversed and converted * to integer representation * @return integer value of a string * @throws NumberFormatException * @author Chiril Chidisiuc * * @version 2006-06-09 */ protected int getFileVersion(String sequence){ try{ return Integer.parseInt(sequence, 10); } catch (NumberFormatException e){ // EXAMPLE: // parseInt("2147483647", 10) returns 2147483647 // parseInt("-2147483648", 10) returns -2147483648 // parseInt("2147483648", 10) throws a NumberFormatException return -1; } } /** * implementation of inherited method to define responce to buttons * * @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int) * @param buttonId:int * @return none */ protected void buttonPressed(int buttonId) { String[] param = new String[10]; String combine = ""; if (buttonId == IDialogConstants.CLOSE_ID) { OK2Close = true; close(); } if (buttonId == IDialogConstants.PROCEED_ID) { combine = collectParameters(); if (combine == null) { // Chiril Chidisiuc: to allow user correct the problem manually and run the // simulation right after the modifications composite.setEnabled(true); simuButton.setEnabled(true); doneButton.setEnabled(true); saveBatButton.setEnabled(true); return; } System.out.println("combine: " + combine); rsimu = new RunSimu(combine, this); rsimu.start(); } SimuGui.checkedEv = false; //Chiril Chidisiuc: restore window settings for event file super.buttonPressed(buttonId); } /** * sets up the Shell name * * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell) * @param shell:Shell * @return none */ protected void configureShell(Shell shell) { super.configureShell(shell); //the following line registers the shell of SimuGui to parent //which causes the file-dialog box modal to the SimuGui dialog //this fixes the problem associated with the file-dialog not being modal to SimuGui parent = shell; if (title != null) shell.setText(title); } /** * creates button set * * @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite) * @param parent:Composite * @return void */ protected void createButtonsForButtonBar(Composite parent) { // create OK and Cancel buttons by default simuButton = createButton( parent, IDialogConstants.PROCEED_ID, IDialogConstants.PROCEED_LABEL, true); simuButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { killButton.setEnabled(true); simuButton.setEnabled(false); doneButton.setEnabled(false); } }); doneButton = createButton( parent, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, true); killButton = createButton(parent, IDialogConstants.STOP_ID, "Kill", true); killButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { simuProcess.destroy(); try { //"ps" allow you to view the process table in linux/cygwin //('-W' parameter allows you to view window processes as well!) Process lookProcess = Runtime.getRuntime().exec("ps"); BufferedReader bf = new BufferedReader( new InputStreamReader( lookProcess.getInputStream())); String msg = null; while ((msg = bf.readLine()) != null) { //look for simu/simuOrig at the end of path portion of line to find process if (msg.endsWith("simuOrig") || msg.endsWith("simu")) { msg = msg.substring(2).trim(); Process killProcess = Runtime.getRuntime().exec( "kill -9 " + msg.substring(0, msg.indexOf(" "))); } } } catch (IOException e1) { e1.printStackTrace(); } doneButton.setEnabled(true); killButton.setEnabled(false); simuButton.setEnabled(true); simuKilled = true; } }); killButton.setEnabled(false); //do this here because setting the text will set enablement on the ok button textMa.setFocus(); } /** * #checkEventFileExistence():void - sets "checkedEv" to true if at least * one event file is present in the project. * * @param none * @return none * @author Chiril Chidisiuc * * @version 2006-06-07 */ private void checkEventFileExistence() { String[] fileNamesTemp = getFileNames("ev"); if (fileNamesTemp[0] == null) { // if first entry is null, then the rest // is null too return; } //there are some event files (at least one entry is not "null") SimuGui.checkedEv = true; } /** * #setEventFileName():void - places name of the event file in dialog box, * if the field is active (i.e. event file exists). * * @param none * @return none * @author Chiril Chidisiuc * * @version 2006-06-07 */ private void setInitialEventFileName(){ String [] eventFileNames = getFileNames("ev"); String [] maFileNames = getFileNames("ma"); if (eventFileNames[0]==null){ return; } for (int i=0; i= 3 && textMa.getText().toUpperCase().endsWith(".MA")){ //Chiril Chidisiuc: set proper ending // of the MA file (offset) offset = textMa.getText().length() - 3; }else{ offset = textMa.getText().length(); } return offset; } private void setSimuFileNames(boolean out, boolean log){ //Chirill Chidisiuc int offset = getMaOffset(textMa); SimuGui.maName = textMa.getText().substring(0, offset); // Chiril Chidisiuc: name is the same as //makefile, but without the ".MA" ending String[] maFiles = getFileNames("ma"); if (!maVersions.containsKey(maName)) { setVersion(maName); } int setThisVersion = ((Integer)maVersions.get(maName)).intValue(); if (out){ if (checkedAutoOut){ if (textMa.getText().length()!=0){ if (setThisVersion!=0){ //Chiril Chidisiuc: set appropriate name with index SimuGui.outAutoName= maName + "OUT_" + setThisVersion +".out"; textOut.setText(SimuGui.outAutoName); }else{ //Chiril Chidisiuc: set appropriate name without index SimuGui.outAutoName=maName + "OUT.out"; textOut.setText(SimuGui.outAutoName); } } } else { //textOut.setText("previously launched OUT file..."); } } if (log) { if (checkedAutoLog) { if (textMa.getText().length()!=0){ if (setThisVersion != 0) { // Chiril Chidisiuc: set appropriate name with version SimuGui.logAutoName= maName + "LOG_" + setThisVersion +".log"; textLog.setText(SimuGui.logAutoName); } else { // Chiril Chidisiuc: set appropriate name without version (no previous records of name) SimuGui.logAutoName=maName + "LOG.log"; textLog.setText(SimuGui.logAutoName); } } } else { //textLog.setText("previously launched LOG file..."); } } } /** * This method creates the dialog box when "Simulate" button is pressed. The * location of fields (labels, text boxes, buttons) is defined here. This * method also ensures that if an event file exists, it will be placed in * the "Event file name (.ev)" text box (however, if there are more than one * event file, please select the appropriate). Default event file name is * first checked (event file with the same name as Makefile name). If no * default event file found, then the first event file found in the * directory is inserted. If no event file exists, the field remains * inactive and user must locate event file himself, if desired. This method * also responds to Makefile selection. When makefile is selceted and input * into the field, the log and out file names are automatically generated * and will be written over, if such names already exist. * * --modified by Chiril Chidisiuc * * @param parent:Composite - the composite object is passed. Attributes of dialog box are added to it. * @return composite:Control - the object, which defines the structure and behaviour of the dialog box */ protected Control createDialogArea(Composite parent) { // create composite composite = (Composite) super.createDialogArea(parent); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 10; composite.setLayout(gridLayout); //Row One - Should be text description of ma text box Label label1 = new Label(composite, SWT.NONE); label1.setText(message1); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.horizontalSpan = 10; label1.setLayoutData(gridData); label1.setFont(parent.getFont()); // Row two - Text Box for the ma file and file button textMa = new Text(composite, SWT.SINGLE | SWT.BORDER); textMa.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { int offset = getMaOffset(textMa); //set Log file name if (textOut.getEnabled() == true) { setSimuFileNames(true, false); } //set Output file name if (textLog.getEnabled() == true) { setSimuFileNames(false, true); } //Chiril Chidisiuc: next "if" statement is needed to make changes to textEv text field if // another default name must be set if (textEv.getEnabled() == true){ //find appropriate default event file name String name = textMa.getText().substring(0, offset); // Chiril Chidisiuc: name is the same //as makefile without the ".MA" ending String [] eventFileNames = getFileNames("ev"); String [] maFileNames = getFileNames("ma"); if (eventFileNames[0]!=null){ for (int i=0; i 99) { textTime1.setText("00"); } else { textTime1.setText(time.toString()); } } if (e.keyCode == SWT.ARROW_DOWN) { time = new Integer(time.intValue() - 1); if (time.intValue() < 0) { textTime1.setText("99"); } else { textTime1.setText(time.toString()); } } } catch (NumberFormatException e2) { textTime1.setText(""); } catch (Exception e1) { e1.printStackTrace(); } } public void keyReleased(KeyEvent e) { } }); colon1 = new Label(composite, SWT.NONE); colon1.setText(":"); textTime2 = new Text(composite, SWT.SINGLE | SWT.BORDER); textTime2.setTextLimit(2); gridData15 = new GridData(); gridData15.widthHint = 15; gridData15.heightHint = 13; textTime2.setLayoutData(gridData15); textTime2.setEnabled(checkedTime); textTime2.setToolTipText("Minutes"); textTime2.setText("00"); textTime2.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { try { Integer time = new Integer(textTime2.getText()); if (e.keyCode == SWT.ARROW_UP) { time = new Integer(time.intValue() + 1); if (time.intValue() > 99) { textTime2.setText("00"); } else { textTime2.setText(time.toString()); } } if (e.keyCode == SWT.ARROW_DOWN) { time = new Integer(time.intValue() - 1); if (time.intValue() < 0) { textTime2.setText("99"); } else { textTime2.setText(time.toString()); } } } catch (NumberFormatException e2) { textTime2.setText(""); } catch (Exception e1) { e1.printStackTrace(); } } public void keyReleased(KeyEvent e) { } }); colon2 = new Label(composite, SWT.NONE); colon2.setText(":"); textTime3 = new Text(composite, SWT.SINGLE | SWT.BORDER); textTime3.setTextLimit(2); gridData15 = new GridData(); gridData15.widthHint = 15; gridData15.heightHint = 13; textTime3.setLayoutData(gridData15); textTime3.setEnabled(checkedTime); textTime3.setToolTipText("Seconds"); textTime3.setText("00"); textTime3.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { try { Integer time = new Integer(textTime3.getText()); if (e.keyCode == SWT.ARROW_UP) { time = new Integer(time.intValue() + 1); if (time.intValue() > 99) { textTime3.setText("00"); } else { textTime3.setText(time.toString()); } } if (e.keyCode == SWT.ARROW_DOWN) { time = new Integer(time.intValue() - 1); if (time.intValue() < 0) { textTime3.setText("99"); } else { textTime3.setText(time.toString()); } } } catch (NumberFormatException e2) { textTime3.setText(""); } catch (Exception e1) { e1.printStackTrace(); } } public void keyReleased(KeyEvent e) { } }); colon2 = new Label(composite, SWT.NONE); colon2.setText(":"); textTime4 = new Text(composite, SWT.SINGLE | SWT.BORDER); textTime4.setTextLimit(3); textTime4.setText("000"); gridData15 = new GridData(); gridData15.widthHint = 20; gridData15.heightHint = 13; textTime4.setLayoutData(gridData15); textTime4.setToolTipText("Milliseconds"); textTime4.setEnabled(checkedTime); textTime4.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { try { Integer time = new Integer(textTime4.getText()); if (e.keyCode == SWT.ARROW_UP) { time = new Integer(time.intValue() + 1); if (time.intValue() > 999) { textTime4.setText("000"); } else { textTime4.setText(time.toString()); } } if (e.keyCode == SWT.ARROW_DOWN) { time = new Integer(time.intValue() - 1); if (time.intValue() < 0) { textTime4.setText("999"); } else { textTime4.setText(time.toString()); } } } catch (NumberFormatException e2) { textTime4.setText(""); } catch (Exception e1) { e1.printStackTrace(); } } public void keyReleased(KeyEvent e) { } }); //Row Eleven - Text Discription of Advanced Label label6 = new Label(composite, SWT.WRAP); label6.setText(message6); GridData gridData16 = new GridData(); gridData16.horizontalAlignment = GridData.BEGINNING; gridData16.horizontalSpan = 10; label6.setLayoutData(gridData16); label6.setFont(parent.getFont()); //Row Tweleve - The check box and text box for advanced checkBoxAdv = new Button(composite, SWT.CHECK); GridData gridData17 = new GridData(); gridData17.horizontalAlignment = GridData.BEGINNING; checkBoxAdv.setLayoutData(gridData17); checkBoxAdv.setSelection(checkedAdv); //Chiril Chidisiuc: this is more readable. //Can be changed once in declaration... (originally set to "false" by default) checkBoxAdv.setToolTipText("This field will allow you to enter parameters in addition to command line"); checkBoxAdv.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (textAdv.getEnabled() == true) { textAdv.setEnabled(false); checkedAdv = false; } else { textAdv.setEnabled(true); checkedAdv = true; } } }); textAdv = new Text(composite, SWT.SINGLE | SWT.BORDER); GridData gridData18 = new GridData(); gridData18.horizontalAlignment = GridData.FILL; gridData18.grabExcessHorizontalSpace = true; gridData18.horizontalSpan = 9; textAdv.setLayoutData(gridData18); textAdv.setEnabled(checkedAdv); String toolTipMsg = "Enter desired parameters manually. " +"\n" + "Example: to add event file, type" +"\n" + " -e\"[your_file_name].ev\"" +"\n" + "NOTE: Separate the entries by putting a space between them"; textAdv.setToolTipText(toolTipMsg); //Chiril Chidisiuc: to help use the field //Row Ten - Text description of the Comment text box Label label8 = new Label(composite, SWT.WRAP); label8.setText(message7); GridData gridData19 = new GridData(); gridData19.horizontalAlignment = GridData.BEGINNING; gridData19.horizontalSpan = 10; label8.setLayoutData(gridData19); label8.setFont(parent.getFont()); //Row ten - The check box and text box for comment checkBoxComment = new Button(composite, SWT.CHECK); GridData gridData20 = new GridData(); gridData20.horizontalAlignment = GridData.BEGINNING; checkBoxComment.setLayoutData(gridData20); checkBoxComment.setSelection(false); checkBoxComment.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (textComment.getEnabled() == true) { textComment.setEnabled(false); checkedComment = false; } else { textComment.setEnabled(true); checkedComment = true; } } }); textComment = new Text(composite, SWT.SINGLE | SWT.BORDER); GridData gridData21 = new GridData(); gridData21.horizontalSpan = 9; gridData21.horizontalAlignment = GridData.FILL; gridData21.grabExcessHorizontalSpace = true; textComment.setLayoutData(gridData21); textComment.setEnabled(false); //Row Sixteen - Save as Batch button saveBatButton = new Button(composite, SWT.PUSH); saveBatButton.setText("Save as .bat"); saveBatButton.setToolTipText("Save Settings to batch file"); GridData gridDataSBB = new GridData(); gridDataSBB.horizontalAlignment = GridData.END; gridDataSBB.horizontalSpan = 9; saveBatButton.setLayoutData(gridDataSBB); saveBatButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { composite.setEnabled(false); doneButton.setEnabled(false); killButton.setEnabled(false); simuButton.setEnabled(false); saveBatButton.setEnabled(false); loadBatButton.setEnabled(false); OK2Close = false; SaveBatchFileGui("*.bat"); } }); //Row Fifteen - Load Batch button loadBatButton = new Button(composite, SWT.PUSH); loadBatButton.setText("Load .bat"); loadBatButton.setToolTipText("Load Batch from file"); GridData gridDataLBB = new GridData(); gridDataLBB.horizontalAlignment = GridData.BEGINNING; loadBatButton.setLayoutData(gridDataLBB); loadBatButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { int lastIndex = 0; // this is lastIndex to the default values loadBatButton.setEnabled(false); OK2Close = false; BufferedReader batchReader = new BufferedReader( new FileReader( path.toString() + NewFileGui("*.bat"))); String command = batchReader.readLine();//Chiril Chidisiuc: read first line of BAT file while(!command.trim().contains("simu")){//Chiril Chidisiuc: works for DEVs/Cell-DEVs command = batchReader.readLine(); } try { String comments = batchReader.readLine(); for (int n=1; !comments.trim().startsWith("rem");n++){//Chiril Chidisiuc: find comments n++; comments = batchReader.readLine(); } if (comments.substring(4).length()!=0){ //Chiril Chidisiuc: comments exist... textComment.setText(comments.substring(4)); checkedComment = true; checkBoxComment.setSelection(checkedComment); textComment.setEnabled(checkedComment); } else {//Chiril Chidisiuc: comments do not exist checkedComment = false; checkedComment = false; checkBoxComment.setSelection(checkedComment); textComment.setEnabled(checkedComment); } } catch (NullPointerException e1) { // some files may not contain comments e1.printStackTrace(); // and null may be returned } String tempCommand = command.toLowerCase(); //Chiril Chidisiuc: avoid case-sensetivity int indexStartMa = tempCommand.indexOf(" -m\"");//Chiril Chidisiuc: to avoid erroneous input int indexEndMa = tempCommand.indexOf(".ma\"");//Chiril Chidisiuc: to avoid erroneous input /* if (indexEndMa == -1) indexEndMa = command.indexOf(".MA"); //Chiril Chidisiuc: this can now be avoided... */ int indexStartEv = tempCommand.indexOf(" -e\""); //Chiril Chidisiuc: to avoid erroneous input int indexEndEv = tempCommand.indexOf(".ev\""); //Chiril Chidisiuc: to avoid erroneous input /* if (indexEndEv == -1) indexStartEv = command.indexOf(".EV"); //Chiril Chidisiuc: this can now be avoided... */ int indexStartOut = tempCommand.indexOf(" -o\"");//Chiril Chidisiuc: to avoid erroneous input int indexEndOut = tempCommand.indexOf(".out\"");//Chiril Chidisiuc: to avoid erroneous input int indexStartLog = tempCommand.indexOf(" -l\"");//Chiril Chidisiuc: to avoid erroneous input int indexEndLog = tempCommand.indexOf(".log\"");//Chiril Chidisiuc: to avoid erroneous input int hourIndexStart = tempCommand.indexOf(" -t\"");//Chiril Chidisiuc: to avoid erroneous input int hourIndexEnd = tempCommand.indexOf(":", hourIndexStart); int minuteIndexStart = tempCommand.indexOf(":", hourIndexStart); System.out.println("minute " + minuteIndexStart); int minuteIndexEnd = tempCommand.indexOf(":", minuteIndexStart + 1); int secondIndexStart = tempCommand.indexOf(":", minuteIndexEnd); int secondIndexEnd = tempCommand.indexOf(":", secondIndexStart + 1); int mSecondIndexStart = tempCommand.indexOf(":", secondIndexEnd); int mSecondIndexEnd = tempCommand.indexOf("\"", mSecondIndexStart);//Chiril Chidisiuc: originally it was " " //index for Advanced field int indexStartAdv = -1; if ((hourIndexStart != -1) && (mSecondIndexEnd != -1)) { indexStartAdv = command.indexOf(" ", mSecondIndexStart); } else if (hourIndexStart == -1) { indexStartAdv = command.indexOf(" ", indexEndLog); } String [] excludeFromAdvancedFieldText = new String[6]; int excludeIndex = 0; if (indexStartMa != -1) { String maFieldText = command.substring( indexStartMa + 4, //Chiril Chidisiuc: originally '+2', now 4 to avoid '"' character indexEndMa + 3); textMa.setText(maFieldText); int maFieldTextLength = maFieldText.length(); excludeFromAdvancedFieldText[excludeIndex] = command.substring(indexStartMa,indexEndMa+4); excludeIndex++; } else { textMa.setText(""); } if (indexStartEv != -1) { checkedEv = true; checkBoxEv.setSelection(checkedEv); textEv.setEnabled(checkedEv); fileButtonEv.setEnabled(checkedEv); textEv.setText( command.substring( indexStartEv + 4, //Chiril Chidisiuc: originally '+2', now 4 to avoid '"' character indexEndEv + 3)); excludeFromAdvancedFieldText[excludeIndex] = command.substring(indexStartEv,indexEndEv+4); excludeIndex++; lastIndex = indexEndEv + 4; //1 extra for the space at the end } else { checkedEv = false; checkBoxEv.setSelection(checkedEv); textEv.setEnabled(checkedEv); fileButtonEv.setEnabled(checkedEv); textEv.setText(""); } if (indexStartOut != -1) { textOut.setText( command.substring( indexStartOut + 4, //Chiril Chidisiuc: originally '+2', now 4 to avoid '"' character indexEndOut + 4)); checkedOut = true; checkBoxOut.setSelection(checkedOut); textOut.setEnabled(checkedOut); fileButtonOut.setEnabled(checkedOut); excludeFromAdvancedFieldText[excludeIndex] = command.substring(indexStartOut, indexEndOut+5); excludeIndex++; lastIndex = indexEndOut + 5; //1 extra for the space at the end } else { textOut.setText(""); checkedOut = false; checkBoxOut.setSelection(checkedOut); textOut.setEnabled(checkedOut); fileButtonOut.setEnabled(checkedOut); } if (indexStartLog != -1) { textLog.setText( command.substring( indexStartLog + 4, //Chiril Chidisiuc: originally '+2', now 4 to avoid '"' character indexEndLog + 4)); checkedLog = true; checkBoxLog.setSelection(checkedLog); textLog.setEnabled(checkedLog); fileButtonLog.setEnabled(checkedLog); excludeFromAdvancedFieldText[excludeIndex] = command.substring(indexStartLog, indexEndLog+5); excludeIndex++; lastIndex = indexEndLog + 5; //Chiril Chidisiuc: to avoid '"' character } else { textLog.setText(""); checkedLog = false; checkBoxLog.setSelection(checkedLog); textLog.setEnabled(checkedLog); fileButtonLog.setEnabled(checkedLog); } if (hourIndexStart != -1) { textTime1.setText( command.substring( hourIndexStart + 4, //Chiril Chidisiuc: originally '+2', now 4 to avoid '"' character hourIndexEnd)); textTime2.setText( command.substring( minuteIndexStart + 1, minuteIndexEnd)); textTime3.setText( command.substring( secondIndexStart + 1, secondIndexEnd)); textTime4.setText( command.substring( mSecondIndexStart + 1, mSecondIndexEnd)); checkedTime = true; checkBoxTime.setSelection(checkedTime); textTime1.setEnabled(checkedTime); textTime2.setEnabled(checkedTime); textTime3.setEnabled(checkedTime); textTime4.setEnabled(checkedTime); excludeFromAdvancedFieldText[excludeIndex] = command.substring(hourIndexStart, mSecondIndexEnd+1); excludeIndex++; lastIndex = mSecondIndexEnd + 1; //1 extra for the space at the end } else { textTime1.setText("00"); textTime2.setText("00"); textTime3.setText("00"); textTime4.setText("000"); checkedTime = false; checkBoxTime.setSelection(checkedTime); textTime1.setEnabled(checkedTime); textTime2.setEnabled(checkedTime); textTime3.setEnabled(checkedTime); textTime4.setEnabled(checkedTime); } //check if Advanced field is present String advancedFieldText = getAdvancedFieldText(command, excludeFromAdvancedFieldText); if (advancedFieldText.length()!=0){ //advanced present checkedAdv = true; checkBoxAdv.setSelection(checkedAdv); textAdv.setEnabled(checkedAdv); textAdv.setText(advancedFieldText.trim()); } else { //advanced not present textAdv.setText(""); checkedAdv = false; checkBoxAdv.setSelection(checkedAdv); textAdv.setEnabled(checkedAdv); } } catch (Exception error) { error.printStackTrace(); } loadBatButton.setEnabled(true); OK2Close = true; } }); errorMessageLabel = new Label(composite, SWT.NONE); errorMessageLabel.setFont(parent.getFont()); return composite; } /** * @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 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. * @author 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 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() /** * This method checks for latest BAT file and returns number of * next version of the BAT file. * * @param batName:String - specific batch file name to be checked (without extension!). * @return latestVersion:int - number to be used in name of the next BAT file with * the root name as batName. * * @author Chiril Chidisiuc * @version 2006-06-25 */ private int getNextBatVersion(String batName){ String [] batList = getFileNames("bat"); int latestVersion = 0; for(int i=0; ilatestVersion)){//check which version is latest latestVersion = number; } }else{ continue;//file names with different root name are irrelevent } } } latestVersion++; //next file name must be 1 higher than currently latest return latestVersion; } /** * this function is used by load.bat to load a new file. * @param filter:String * @return name of 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 used by save.bat to save a file * @param filter:String * @return none */ //code modified by Sameen Rehman private void SaveBatchFileGui(String filter) { String[] param = new String[10]; String command = collectParameters(); String temp; boolean fileExists = false; 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.toUpperCase().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()) { //Chiril Chidisiuc: file is already present in the directory fileExists = true; //Chiril Chidisiuc: for user to set his/her own *.bat file name... IPreferenceStore store = CDBuilderPlugin.getDefault().getPreferenceStore(); if (store.getInt("batchChoice") == 3) { //Chiril Chidisiuc: an existing file is selected OverwriteGui ovG = new OverwriteGui(this.parent);//Chiril Chidisiuc: origianlly 'new Shell()' ovG.open(); if (ovG.buttonPressed() == 0) { //Chiril Chidisiuc: cancel the promt 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; } //Chiril Chidisiuc: automatically generate the version of the selected file if (ovG.buttonPressed() == 2) { int newVersion = getNextBatVersion(fileName); //Chiril Chidisiuc fileName = fileName+"_"+newVersion; MessageBox mbox = new MessageBox( this.parent, 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); //Chiril Chidisiuc: "Don't ask again" selected to always automate naming } if (ovG.buttonPressed() == 1) {//Chiril Chidisiuc: overwrite the selected file if (ovG.noAskAgain()) store.setValue("batchChoice", 1); } } else if (store.getInt("batchChoice") == 2) { //store.setValue("batchChoice", 3); //Chiril Chidisiuc [debug purposes]: run this once, or modify the CDPreferencePage.java to restore settings int newVersion = getNextBatVersion(fileName); fileName = fileName+"_"+newVersion; } } if (!cancelled) { //Chiril Chidisiuc: saving file 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(); } } }