//This file is part of SECONDO. //Copyright (C) 2004, University in Hagen, Department of Computer Science, //Database Systems for New Applications. //SECONDO is free software; you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation; either version 2 of the License, or //(at your option) any later version. //SECONDO is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. //You should have received a copy of the GNU General Public License //along with SECONDO; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package gui; import java.awt.*; import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; import sj.lang.*; import viewer.*; import java.util.*; import java.io.*; import gui.idmanager.*; import java.awt.image.BufferedImage; import java.awt.geom.*; import tools.Reporter; import javax.swing.filechooser.FileFilter; import mmdb.MMDBUserInterfaceController; public class MainWindow extends JFrame implements ResultProcessor,ViewerControl,SecondoChangeListener{ public final static String AUTO_HISTORY_FILE=".gui_history"; public final static String AUTO_QUERY_FILE=".gui_queries"; // the last ... entries of the history are stored public final static int AUTO_HISTORY_LENGTH=100; public final static int MIN_FONTSIZE = 6; public final static int MAX_FONTSIZE = 24; // shows additional informations if an error occurs private boolean DEBUG_MODE = true; /* The version-line of the history This line is used as the first line in a history file starting with version 2.0. */ private final static String HIST_VERSION20_LINE = "# VER 2.0"; private JPanel PanelTop; // change to the desired components private static CommandPanel ComPanel; private ObjectList OList; private JPanel PanelTopRight; private JSplitPane HSplitPane; private JSplitPane VSplitPane; private ServerDialog ServerDlg; private UserDialog ud; private Vector VCLs; private Vector ListOfObjects=null; // contains all objects of the currently opened database /* the current Viewer and all possible Viewers */ private SecondoViewer CurrentViewer; private SecondoViewer emptyViewer; private Vector AllViewers; private Vector ViewerMenuItems; private Vector SeparatedViewers; // boolean flags for speparatly showed viewers private JFileChooser ViewerFileChooser; private MenuVector CurrentMenuVector; /* the Menubar with Menuitems */ private JMenuBar MainMenu; private JMenu ProgramMenu; private JMenuItem MI_FontSize_Console_Bigger; private JMenuItem MI_FontSize_Console_Smaller; private JMenuItem MI_FontSize_List_Bigger; private JMenuItem MI_FontSize_List_Smaller; private JMenuItem MI_ExecuteFile_HaltOnError; private JMenuItem MI_ExecuteFile_IgnoreErrors; private JMenuItem MI_SaveHistory; private JMenuItem MI_ClearHistory; private JMenuItem MI_ExtendHistory; private JMenuItem MI_ReplaceHistory; private JMenuItem MI_AddLastQuery; private JMenuItem MI_ShowQueries; private JMenuItem MI_SaveQueries; private JMenuItem MI_LoadQueries; private JMenuItem MI_Close; private JMenuItem MI_Snapshot; private JMenu ServerMenu; private JMenuItem MI_Connect; private JMenuItem MI_Disconnect; private JMenuItem MI_Settings; private JMenuItem MI_User; private JMenu OptimizerMenu; private JMenuItem MI_OptimizerEnable; private JMenuItem MI_OptimizerDisable; private JMenuItem MI_OptimizerUpdateCatalog; private JMenuItem MI_OptimizerTestOptimizer; private JCheckBoxMenuItem MI_OptimizerReconnectWhenOpenDB; private JCheckBoxMenuItem MI_OptimizerAutoUpdateCatalog; private JMenuItem MI_OptimizerResetKnowledgeDB; private JMenu OptimizerCommandMenu; private JMenu UpdateRelationsMenu; private JMenu UpdateIndexMenu; private JMenuItem MI_UpdateRelationList; private JMenuItem MI_UpdateIndexList; // flag indicating whether the entropy menu parts should be included private boolean useEntropy; private JMenuItem MI_EnableEntropy; private JMenuItem MI_DisableEntropy; private JMenuItem MI_OptimizerSettings; private JMenu Menu_ServerCommand; private JMenu Menu_BasicCommands; private JMenu Menu_Inquiries; private JMenu Menu_Databases; private JMenu Menu_Transactions; private JMenu Menu_ImExport; //Inquiries private JMenuItem MI_ListDatabases; private JMenuItem MI_ListTypes; private JMenuItem MI_ListTypeConstructors; private JMenuItem MI_ListObjects; private JMenuItem MI_ListOperators; private JMenuItem MI_ListAlgebras; private JMenu AlgebraMenu; // Databases private JMenu OpenDatabaseMenu; private JMenu DeleteDatabaseMenu; private JMenuItem MI_UpdateDatabases; private JMenuItem MI_CloseDatabase; private JMenuItem MI_CreateDatabase; // Transactions private JMenuItem MI_BeginTransaction; private JMenuItem MI_CommitTransaction; private JMenuItem MI_AbortTransaction; // Import Export private JMenuItem MI_SaveDatabase; private JMenu Menu_RestoreDatabase; private JMenuItem MI_SaveObject; private JMenuItem MI_RestoreObject; // Basic Commands private JMenuItem MI_CreateType; private JMenuItem MI_DeleteType; private JMenuItem MI_CreateObject; private JMenuItem MI_DeleteObject; private JMenuItem MI_UpdateObject; private JMenuItem MI_Let; private JMenuItem MI_Query; private JMenu HelpMenu; private JMenuItem MI_ShowGuiCommands; private JMenuItem MI_ShowSecondoCommands; private HelpScreen MyHelp; private JMenu Viewers; private JMenuItem MI_ShowOnlyViewer; private boolean onlyViewerShow = false; private JMenuItem MI_AddViewer; private JMenuItem MI_SeparateViewer; private Container DefaultContentPane; private MenuListener BlendOutList; // a Menu cannot overlap a List ?? private String ObjectDirectory ="./"; // where search for Objects private ProgressView progressView; private ProgressTimer progressTimer; private String configFile; private JFileChooser FC_History = new JFileChooser("."); private JFileChooser FC_Queries = new JFileChooser("."); private JFileChooser FC_ExecuteFile = new JFileChooser("."); private JFileChooser FC_Database = new JFileChooser("."); private JFileChooser FC_Snapshot = new JFileChooser("."); private JFileChooser FC_Object = new JFileChooser("."); private FileFilter pngFilter; private FileFilter epsFilter; private static String pngTitle = "Save PNG image"; private static String epsTitle = "Save EPS image"; private PriorityDialog PriorityDlg; private static String LAF = null; /* return this */ public Frame getMainFrame(){ return this; } /* creates a new MainWindow */ public MainWindow(String Title,String user,String passwd, String configFile){ super(Title); this.configFile = configFile; VCLs = new Vector(10); // ViewerChangeListeners ViewerMenuItems = new Vector(10); AllViewers = new Vector(10); SeparatedViewers = new Vector(10); String StartScript=null; setSize(800,600); ServerDlg = new ServerDialog(this); ud = new UserDialog(this); MyHelp = new HelpScreen(this); this.getContentPane().setLayout(new BorderLayout()); PanelTop = new JPanel(new BorderLayout(),true); ComPanel = new CommandPanel(this,user, passwd); ComPanel.addSecondoChangeListener(this); OList = new ObjectList(this,this); PanelTopRight = new JPanel(); CurrentMenuVector = null; VSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,true, PanelTop,PanelTopRight); HSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,false, ComPanel,OList); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(VSplitPane,BorderLayout.CENTER); // add the splitpanes progressView = new ProgressView(); this.getContentPane().add(progressView,BorderLayout.EAST); ComPanel.addMessageListener(progressView); ErrorHandler errorHandler = new ErrorHandler(ComPanel); ComPanel.addMessageListener(errorHandler); progressTimer = new ProgressTimer(); ComPanel.addMessageListener(progressTimer); PanelTop.add(HSplitPane); ViewerFileChooser = new JFileChooser("."+File.separatorChar+"viewer"); VSplitPane.setPreferredSize(new Dimension(600,400)); VSplitPane.setDividerLocation(200); VSplitPane.setDividerSize(4); HSplitPane.setDividerLocation(500); HSplitPane.setDividerSize(4); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent evt){ ComPanel.disableOptimizer(); ComPanel.disconnect(); saveHistory(new File(AUTO_HISTORY_FILE),false,AUTO_HISTORY_LENGTH); ComPanel.saveQueries(new File(AUTO_QUERY_FILE)); System.exit(0); } }); PriorityDlg = new PriorityDialog(this); CurrentViewer = null; emptyViewer = new SecondoViewer(){ public String getName(){ return "empty";} public void removeObject(SecondoObject o) {} public void removeAll(){} public boolean canDisplay(SecondoObject o) { return false;} public boolean isDisplayed(SecondoObject o){ return false;} public boolean selectObject(SecondoObject o){ return false;} public boolean addObject(SecondoObject o){ return false;} public Dimension getMinimumSize( ) { return d; } public Dimension getMaximumSize() { return d; } public Dimension getPreferredSize() { return d;} private Dimension d = new Dimension(1,1); }; DefaultContentPane = getContentPane(); String ServerName = "localhost"; int ServerPort = 2550; boolean StartConnection = false; // try to read a configuration-File Properties Config = new Properties(); File CF = new File(configFile); boolean config_file_ok =true; if(!CF.exists()){ Reporter.writeError("Javagui: configuration file not found \n" + "searched configuration file: "+CF.getAbsolutePath()); config_file_ok = false; } if(config_file_ok){ try{ Reporter.writeInfo("load configuration data from: "+CF.getAbsolutePath()); FileInputStream CFG = new FileInputStream(CF); Config.load(CFG); CFG.close(); } catch(Exception e){ config_file_ok = false; Reporter.debug(e); } } int maxStringLength=48; useEntropy=false; if(config_file_ok){ String UseEntropy = Config.getProperty("USE_ENTROPY"); if(UseEntropy!=null){ if(UseEntropy.toLowerCase().trim().equals("true")) useEntropy=true; } UseEntropy=null; String UseFormattedText = Config.getProperty("FORMATTED_TEXT"); if(UseFormattedText!=null){ if(UseFormattedText.toLowerCase().trim().equals("true")){ tools.Environment.FORMATTED_TEXT=true; } } UseFormattedText=null; String keepCurrentViewer = Config.getProperty("KEEP_CURRENT_VIEWER", "TRUE"); if(keepCurrentViewer.toLowerCase().equals("true")){ PriorityDlg.setKeepCurrentViewer(true); } else { PriorityDlg.setKeepCurrentViewer(false); } String objectDependingViewerSelection = Config.getProperty("OBJECT_DEPENDING_VIEWER_SELECTION", "TRUE"); if(objectDependingViewerSelection.toLowerCase().equals("true")){ PriorityDlg.setObjectDependingViewerSelection(true); } else { PriorityDlg.setObjectDependingViewerSelection(false); } String TestOptimizerConfig = Config.getProperty("TESTOPTFILE"); if(TestOptimizerConfig!=null){ gui.Environment.testOptimizerConfigFile = TestOptimizerConfig; } TestOptimizerConfig = null; LAF = Config.getProperty("LAF"); if(LAF!=null){ LAF=LAF.trim(); } String Encoding = Config.getProperty("ENCODING"); if(Encoding!=null){ tools.Environment.ENCODING=Encoding.trim(); if(tools.Environment.ENCODING.length()==0){ tools.Environment.ENCODING=null; } } String OldObjectStyle = Config.getProperty("OLD_OBJECT_STYLE"); gui.Environment.OLD_OBJECT_STYLE=OldObjectStyle!=null && OldObjectStyle.toLowerCase().trim().equals("true"); OldObjectStyle=null; String TraceServerCommands = Config.getProperty("TRACE_SERVER_COMMANDS"); if(TraceServerCommands!=null && TraceServerCommands.trim().toLowerCase().equals("true")){ tools.Environment.TRACE_SERVER_COMMANDS = true; } String ScriptStyle = Config.getProperty("SCRIPT_STYLE"); if(ScriptStyle!=null){ ScriptStyle = ScriptStyle.trim().toUpperCase(); if(ScriptStyle.equals("GUI")){ gui.Environment.TTY_STYLED_SCRIPT=false; } } String extensions = Config.getProperty("EXTENSIONS"); if(extensions!=null){ StringTokenizer st = new StringTokenizer(extensions); while(st.hasMoreTokens()){ gui.Environment.insertExtension(st.nextToken()); } } String CommandStyle = Config.getProperty("COMMAND_STYLE"); if(CommandStyle!=null){ if(CommandStyle.trim().toUpperCase().equals("TTY")){ gui.Environment.TTY_STYLED_COMMAND=true; } } } createMenuBar(); if(config_file_ok){ String TMPServerName = Config.getProperty("SERVERNAME"); if (TMPServerName==null){ Reporter.writeError("Servername not found in "+configFile); } else{ ServerName = TMPServerName; Reporter.writeInfo("set ServerName to "+ServerName); } String TMPServerPort = Config.getProperty("SERVERPORT"); if(TMPServerPort==null){ Reporter.writeError("Serverport not found in "+ configFile); } else{ try{ int PortInt = (new Integer(TMPServerPort)).intValue(); if(PortInt <0){ Reporter.writeError("ServerPort in "+ configFile+" less than 0"); } else{ Reporter.writeInfo("set port to "+PortInt); ServerPort = PortInt; } } catch(Exception wrongport){ Reporter.writeError("error in ServerPort (not an Integer)"); } } String Connection = Config.getProperty("START_CONNECTION"); if(Connection==null){ Reporter.writeError("START_CONNECTION not found in "+configFile); } else{ Connection=Connection.trim().toLowerCase(); if(Connection.equals("true")) StartConnection = true; else if(Connection.equals("false")) StartConnection = false; else{ Reporter.writeError("START_CONNECTION has unknown value in "+configFile); Reporter.writeInfo("allowed values are true and false"); } } String FontSize = Config.getProperty("COMMAND_FONTSIZE"); if(FontSize==null){ Reporter.writeError("COMMAND_FONTSIZE NOT found in "+configFile); } else{ try{ int size = Integer.parseInt(FontSize.trim()); ComPanel.setFontSize(size); } catch(Exception e){ Reporter.writeError("COMMAND_FONTSIZE has no valid value (not an integer)"); } } FontSize = Config.getProperty("LIST_FONTSIZE"); if(FontSize==null){ Reporter.writeError("LIST_FONTSIZE not found in "+configFile); } else{ try{ int size = Integer.parseInt(FontSize.trim()); OList.setFontSize(size); } catch(Exception e){ Reporter.writeError("LIST_FONTSIZE has no valid value (not an integer)"); } } String MaxStringLen = Config.getProperty("MAX_STRING_LENGTH"); if(MaxStringLen!=null){ try{ int tmp = Integer.parseInt(MaxStringLen.trim()); if(tmp>0) maxStringLength = tmp; } catch(Exception e){ Reporter.writeError("invalid value for MAX_STRING_LENGTH"); } } String NLCache = Config.getProperty("NL_CACHE"); if(NLCache!=null){ try{ int tmp = Integer.parseInt(NLCache); Reporter.writeInfo("initialize NLCache : "+ tmp); ListExpr.initialize(tmp); } catch(Exception e){ Reporter.writeError("invalid value for NLCACHE"); } } String KnownViewers = Config.getProperty("KNOWN_VIEWERS"); if(KnownViewers!=null){ StringTokenizer View = new StringTokenizer(KnownViewers," "); Vector ViewerVector = new Vector(10); while(View.hasMoreTokens()){ ViewerVector.add(View.nextToken()); } String ViewerName; for(int i=0;i=MAX_FONTSIZE) MI_FontSize_List_Bigger.setEnabled(false); fs = ComPanel.getFontSize(); if(fs<=MIN_FONTSIZE) MI_FontSize_Console_Smaller.setEnabled(false); if(fs>=MAX_FONTSIZE) MI_FontSize_Console_Bigger.setEnabled(false); // load the last history loadHistory(new File(AUTO_HISTORY_FILE),false,false); // load the queries ComPanel.loadQueries(AUTO_QUERY_FILE); // we create a global keylistener for making screenshots AWTEventListener SnapshotKL = new AWTEventListener(){ public void eventDispatched(AWTEvent e){ if(! (e instanceof KeyEvent)) return; KeyEvent evt = (KeyEvent) e; if(e.getID()!=KeyEvent.KEY_PRESSED) return; if(!evt.isAltDown()) return; int c = evt.getKeyCode(); if(!evt.isShiftDown()){ if(c==KeyEvent.VK_S){ if(saveSnapshot(true)){ Reporter.showInfo("Snapshot written"); } evt.consume(); } if(c==KeyEvent.VK_C){ if(saveSnapshot(false)){ Reporter.showInfo("Snapshot written"); } evt.consume(); } } else{ if(c==KeyEvent.VK_F){ Object s = evt.getSource(); if(!(s instanceof Component)){ Reporter.showError("source is not a component"); return; } Component c1 = (Component) s; Component c2 = c1.getParent(); while(c2!=null && !(c2 instanceof Window)){ c1 = c2; c2 = c1.getParent(); } exportToPS(c1);; } } } }; Toolkit.getDefaultToolkit().addAWTEventListener(SnapshotKL,AWTEvent.KEY_EVENT_MASK); MMDBUserInterfaceController.getInstance().injectElementsToMMDB(OList, MainWindow.ComPanel); } private void showUserSettings(StringBuffer u, StringBuffer p){ ud.show(); if(ud.getResultValue()==UserDialog.OK){ u.append(ud.getUserName()); p.append(ud.getPassword()); } } public void addViewerChangeListener(ViewerChangeListener VCL){ if(VCLs.indexOf(VCL)<0) VCLs.add(VCL); } public void removeViewerChangeListener(ViewerChangeListener VCL){ VCLs.remove(VCL); } /** returns the name of the main type of the given ListExpr; * this means for a list (rel(...)) "rel is returned */ private String getMainType(ListExpr Type){ while(!Type.isAtom() && Type.listLength()>0) Type = Type.first(); int atomType = Type.atomType(); if(atomType!=ListExpr.SYMBOL_ATOM) return "unknow type"; return Type.symbolValue(); } /** updates the list of objects in the database */ private void updateObjectList(){ if(!ComPanel.isConnected()){ ListOfObjects = null; return; } ListExpr LE = ComPanel.getCommandResult("list objects"); if(LE==null){ ListOfObjects = null; return; } LE = LE.second().second().rest(); ListOfObjects = null; ListExpr CurrentObject = null; if(LE.isEmpty()){ return; } ListOfObjects = new Vector(LE.listLength()+1); while(!LE.isEmpty()){ ListOfObjects.add(ListExpr.threeElemList(LE.first().second(), ListExpr.symbolAtom(getMainType(LE.first().fourth())), LE.first().fourth())); LE = LE.rest(); } } /** Creates a snapshot from the current Javagui. * If the snapshot can't be created, null is returned. **/ private BufferedImage makeSnapshot(){ Rectangle2D R = getBounds(); BufferedImage bi = new BufferedImage((int)R.getWidth(),(int)R.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); this.printAll(g); g.dispose(); return bi; } /** Created a snapshot of the whole screen. * If an error occurs, the result will be null. **/ private BufferedImage makeScreenSnapshot(){ try{ return (new Robot()).createScreenCapture( new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); }catch(Exception e){ return null; } } /** Saves a snapshot of the current state of Javagui */ private boolean saveSnapshot(boolean completeScreen){ BufferedImage snapshot; if(completeScreen) snapshot=makeScreenSnapshot(); else snapshot = makeSnapshot(); if(snapshot==null){ Reporter.showError("Error in creating snapshot"); return false; } FC_Snapshot.setDialogTitle(pngTitle); FC_Snapshot.setFileFilter(pngFilter); if(FC_Snapshot.showSaveDialog(this)==JFileChooser.APPROVE_OPTION){ try{ return javax.imageio.ImageIO.write(snapshot,"png",FC_Snapshot.getSelectedFile()); } catch(Exception e){ Reporter.debug(e); Reporter.showError("Error in saving snapshot"); return false; } }else return false; } /** exports the given component into a eps file **/ private boolean exportToPS(Component c){ FC_Snapshot.setDialogTitle(epsTitle); FC_Snapshot.setFileFilter(epsFilter); if(FC_Snapshot.showSaveDialog(this)==JFileChooser.APPROVE_OPTION){ File F = FC_Snapshot.getSelectedFile(); if(F.exists() && Reporter.showQuestion("File exists \n overwrite it ?")!=Reporter.YES){ return true; } extern.psexport.PSCreator.export(c,F); } return true; } /** Function enabling or disabling the entropy function of the Optimizer. **/ private void enableEntropy(boolean on){ String command = on?"use_entropy":"dont_use_entropy"; ComPanel.appendText("\noptimizer "+command+" "); if(ComPanel.sendToOptimizer(command)==null){ ComPanel.appendText(" ... failed"); }else{ ComPanel.appendText(" ... successful"); } ComPanel.showPrompt(); } private void updateCatalog(){ String command ="updateCatalog"; ComPanel.appendText("\noptimizer "+ command +" "); if(ComPanel.sendToOptimizer(command)==null){ ComPanel.appendText(" ... failed"); }else{ ComPanel.appendText(" ... successful"); } ComPanel.showPrompt(); } private void testOptimizer(){ OptimizerTest ot = new OptimizerTest(ComPanel,this); ComPanel.appendText("\n test optimizer \n"); int errors = ot.testOptimizer(); if(errors>0){ ComPanel.appendText("test Optimizer failed with " + errors + " errors"); } else { ComPanel.appendText("test optimizer successful"); } ComPanel.showPrompt(); } private void resetKnowledgeDB(){ String command ="resetKnowledgeDB"; ComPanel.appendText("\noptimizer "+ command +" "); if(ComPanel.sendToOptimizer(command)==null){ ComPanel.appendText(" ... failed"); }else{ ComPanel.appendText(" ... successful"); } ComPanel.showPrompt(); } /** reconstructed the menu updateRelationMenu * the values are given through the current ListOfObjects-Vector */ private void updateRelationList(){ // first remove all entries without the first two one UpdateRelationsMenu.removeAll(); UpdateRelationsMenu.add(MI_UpdateRelationList); UpdateIndexMenu.removeAll(); UpdateIndexMenu.add(MI_UpdateIndexList); boolean first = true; if(ListOfObjects==null) return; ListExpr CurrentObject; for(int i=0;i=0) MainWindow.this.setViewerindex(index); }}); PriorityDlg.addViewer(NewViewer); viewersChanged(); } setViewer(NewViewer); } /** returns all loaded viewers */ public SecondoViewer[] getViewers(){ SecondoViewer[] tmpViewers = new SecondoViewer[AllViewers.size()]; for(int i=0;i * selectViewer * clearHistory * saveHistory * loadHistory [-r] * showObject * hideObject * removeObject * clearObjectList * saveObject * loadObject * setObjectDirectory * loadObjectFrom * storeObject * connect * disconnect * serverSettings * renameObject -> * onlyViewer * listCommands * showAll * hideAll * executeFile [-i] * insertExtensions ext_1 ... ext_n * deleteExtensions ext_1 ... ext_n */ public boolean execGuiCommand(String command){ ComPanel.appendText("\n"); command=command.trim(); boolean success=true; if(command.startsWith("exit")){ setVisible(false); ComPanel.disconnect(); ComPanel.disableOptimizer(); saveHistory(new File(AUTO_HISTORY_FILE),false,AUTO_HISTORY_LENGTH); System.exit(0); } else if(command.startsWith("addViewer")){ String ViewerName = command.substring(9).trim(); // command without "addviewer" try{ String ClassName; if (ViewerName.startsWith(".")) ClassName=ViewerName.substring(1); else ClassName="viewer."+ViewerName; Class VC = Class.forName(ClassName); Object Cand = VC.newInstance(); if(Cand instanceof SecondoViewer) addViewer((SecondoViewer)Cand); else{ ComPanel.appendText("this is not a SecondoViewer"); success=false; } }catch(Exception e){ ComPanel.appendText("cannot load viewer:"+ViewerName+"\n"); success=false; Reporter.debug(e); } ComPanel.showPrompt(); } else if(command.startsWith("selectViewer")) { String ViewerName=command.substring(12).trim(); // command without "selectViewer" boolean found=false; // check first for ViewerName int i=0; while(i"); if(pos <0){ // no correct input ComPanel.appendText("usage: \"gui rename -> \""); success=false; } else{ String oldName = command.substring(0,pos).trim(); String newName = command.substring(pos+2).trim(); if(oldName.equals("") || newName.equals("")){ ComPanel.appendText("usage: \"gui rename -> \""); success=false; } else{ int EC = OList.renameObject(oldName,newName); ComPanel.appendText(OList.getErrorText(EC)); } } ComPanel.showPrompt(); } else if(command.startsWith("onlyViewer")){ onlyViewerSwitch(); ComPanel.showPrompt(); } else if(command.startsWith("hideAll")){ OList.hideAll(); ComPanel.showPrompt(); } else if(command.startsWith("showAll")){ OList.showAll(); ComPanel.showPrompt(); } else if(command.startsWith("executeFile")){ String crest = command.substring(11).trim(); int errors = 0; if (crest.startsWith("-i")) errors = executeFile(crest.substring(2).trim(),true, false); else errors = executeFile(crest,false, false); if(errors>0){ ComPanel.appendText("there are "+errors+" errors"); success=false; } else ComPanel.appendText("executeFile successful"); ComPanel.showPrompt(); } else if(command.startsWith("setObjectDirectory")){ String dir = command.substring(18).trim(); String sep = System.getProperties().getProperty("file.separator"); if(dir.endsWith(sep)) dir = dir.substring(1,dir.length()-1); // remove a fileseparator ObjectDirectory = dir; OList.setObjectDirectory(new File(dir)); ComPanel.appendText("ObjectDirectory ="+dir); ComPanel.showPrompt(); } else if(command.startsWith("loadObjectFrom")){ String sep = System.getProperties().getProperty("file.separator"); String Name = command.substring(14).trim(); if(!Name.startsWith(sep)) if(ObjectDirectory.endsWith(sep)) Name = ObjectDirectory+Name; else Name = ObjectDirectory+sep+Name; if(OList.loadObject(new File(Name))) ComPanel.appendText("Object loaded"); else ComPanel.appendText("i can't load this object"); ComPanel.showPrompt(); } else if(command.startsWith("saveHistory")){ saveHistory(); } else if(command.startsWith("loadHistory")){ String Param = command.substring(11).trim(); if(Param.equals("")) loadHistory(false); else if(Param.equals("-r")) loadHistory(true); else ComPanel.appendText("unknown parameter\n"); ComPanel.showPrompt(); } else if(command.startsWith("clearAll")){ clearAll(); //ComPanel.showPrompt(); } else if(command.startsWith("status")){ if(ComPanel.isConnected()){ ComPanel.appendText("connected to Secondo\n"); if(ComPanel.getOpenedDatabase().equals("")) ComPanel.appendText("no database open"); else ComPanel.appendText("opened database: "+ComPanel.getOpenedDatabase()); }else{ ComPanel.appendText("not connected"); } ComPanel.showPrompt(); } else if(command.startsWith("insertExtensions")){ command = command.substring(16).trim(); StringTokenizer st = new StringTokenizer(command); while(st.hasMoreTokens()){ gui.Environment.insertExtension(st.nextToken()); } ComPanel.showPrompt(); } else if(command.startsWith("deleteExtensions")){ command = command.substring(16).trim(); StringTokenizer st = new StringTokenizer(command); while(st.hasMoreTokens()){ gui.Environment.removeExtension(st.nextToken()); } ComPanel.showPrompt(); }else if(command.startsWith("set")){ command = command.substring(3).trim().toLowerCase(); StringTokenizer st = new StringTokenizer(command," \n\t="); if(st.countTokens()!=2){ // format set xxx = yyy ComPanel.appendText("invalid format for set command"); ComPanel.showPrompt(); success=false; }else{ String var = st.nextToken(); String value = st.nextToken(); if(var.equals("debugmode")){ if(value.equals("true")){ tools.Environment.DEBUG_MODE = true; ComPanel.appendText("enable debug mode"); ComPanel.showPrompt(); }else if(value.equals("false")){ tools.Environment.DEBUG_MODE = false; ComPanel.appendText("disable debug mode"); ComPanel.showPrompt(); } else{ ComPanel.appendText("invalid value for debug mode"); ComPanel.showPrompt(); } } else if(var.equals("timemeasures")){ if(value.equals("true")){ tools.Environment.MEASURE_TIME = true; ComPanel.appendText("enable time measures"); ComPanel.showPrompt(); }else if(value.equals("false")){ tools.Environment.MEASURE_TIME = false; ComPanel.appendText("disable time measures"); ComPanel.showPrompt(); } else{ ComPanel.appendText("invalid value for time measures"); ComPanel.showPrompt(); } } else if(var.equals("formattedtext")){ if(value.equals("true")){ tools.Environment.FORMATTED_TEXT = true; ComPanel.appendText("enable colorized text"); ComPanel.showPrompt(); }else if(value.equals("false")){ tools.Environment.FORMATTED_TEXT = false; ComPanel.appendText("disable colorized text"); ComPanel.showPrompt(); } else{ ComPanel.appendText("invalid value for text formatting"); ComPanel.showPrompt(); } } else if(var.equals("showcommand")){ if(value.equals("true")){ tools.Environment.SHOW_COMMAND = true; ComPanel.appendText("show command before executing it"); ComPanel.showPrompt(); }else if(value.equals("false")){ tools.Environment.SHOW_COMMAND = false; ComPanel.appendText("do not show command before executing it"); ComPanel.showPrompt(); } else{ ComPanel.appendText("invalid value for command echo"); ComPanel.showPrompt(); } } else if(var.equals("servertrace")){ if(value.equals("true")){ tools.Environment.TRACE_SERVER_COMMANDS = true; ComPanel.appendText("enable tracing of client server protocol"); ComPanel.showPrompt(); }else if(value.equals("false")){ tools.Environment.TRACE_SERVER_COMMANDS= false; ComPanel.appendText("disable tracing of client server protocol"); ComPanel.showPrompt(); } else{ ComPanel.appendText("invalid value for server trace"); ComPanel.showPrompt(); } } else if(var.equals("commandstyle")){ if(value.equals("tty")){ gui.Environment.TTY_STYLED_COMMAND = true; ComPanel.appendText("use commands in tty style"); ComPanel.showPrompt(); }else if(value.equals("gui")){ gui.Environment.TTY_STYLED_COMMAND= false; ComPanel.appendText("use commands in gui style"); ComPanel.showPrompt(); } else{ ComPanel.appendText("invalid value for command style (tty, gui are allowed)"); ComPanel.showPrompt(); } } else if(var.equals("scriptstyle")){ if(value.equals("tty")){ gui.Environment.TTY_STYLED_SCRIPT = true; ComPanel.appendText("use scripts in tty style"); ComPanel.showPrompt(); }else if(value.equals("gui")){ gui.Environment.TTY_STYLED_SCRIPT= false; ComPanel.appendText("use scripts in gui style"); ComPanel.showPrompt(); } else{ ComPanel.appendText("invalid value for script style (tty,gui are allowed)"); ComPanel.showPrompt(); } } else{ ComPanel.appendText("unknown option for set command"); ComPanel.showPrompt(); success=false; } } } else if(command.startsWith("display ")){ OList.displayObject(command.substring(8)); ComPanel.showPrompt(); } else if(command.equals("enableOptimizer")){ success=ComPanel.enableOptimizer(); } else if(command.equals("disableOptimizer")){ ComPanel.disableOptimizer(); success = true; } else { ComPanel.appendText("unknown gui command \n show help to get a list of available commands"); ComPanel.showPrompt(); success=false; } return success; } /** switches to the correct executeFile method * @param fileName name of the file to process * @param ignoreErrors stop if an errors is detected and the value is false * @return number of errors occured*/ public int executeFile(String fileName, boolean ignoreErrors, boolean showProgress){ if(gui.Environment.TTY_STYLED_SCRIPT){ return executeTTYScript(fileName,ignoreErrors, showProgress); }else{ return executeSimpleFile(fileName,ignoreErrors,showProgress); } } /** executes all commands contained in a file * each command is given within a single line **/ private int executeSimpleFile(String FileName,boolean ignoreErrors, boolean showProgress){ BufferedReader BR = null; try{ if(!showProgress){ BR = new BufferedReader(new FileReader(FileName)); } else { BR = new BufferedReader( new InputStreamReader( new ProgressMonitorInputStream(null, "Processing " + FileName, new FileInputStream(FileName)))); } } catch(Exception e){ ComPanel.appendText("File \""+FileName+"\" not found\n"); return 1; } int errors =0; try{ String Line=BR.readLine(); boolean ok=true; while(Line!=null & ok){ Line = Line.trim(); ComPanel.appendText(Line+"\n"); if (!ComPanel.execUserCommand(Line)){ errors++; if(!ignoreErrors || !ComPanel.isConnected()) ok=false; } Line = BR.readLine(); } } catch(Exception e){ ComPanel.appendText("a IO error occurred\n"); Reporter.debug("io error occurred",e); errors++; } finally{ try{ if(BR!=null) BR.close(); } catch(Exception e){} } return errors; } /** returns the next command within a file which is given in TTY style */ private String getNextCommand(BufferedReader in) throws IOException{ String line; String command = ""; boolean first=true; while(in.ready()){ line = in.readLine(); if(!line.startsWith("#")){ // ignore comments if(line.length()==0) { // an empty line if(command.length()>0){ // command finished return command; } }else{ if(line.endsWith(";")){ // command end line = line.substring(0,line.length()-1); // remove ';' if(!first){ command += "\n"; } command += line; return command; } else{ if(first){ command = line+" "; first=false; } else{ command += "\n" + line; } } } } } // end of file reached return command; } /** executes all commands in a file where the file syntax is * as a TTY script * @param FileName the name of the file to process * @param ignoreErrors if set to false, the processing will be stopped * when an error occurs * @return number of errors occured during processing of this file **/ private int executeTTYScript(String fileName, boolean ignoreErrors, boolean showProgress){ // open file for processing BufferedReader in = null; try{ if(!showProgress){ in = new BufferedReader(new FileReader(fileName)); } else { in = new BufferedReader( new InputStreamReader( new ProgressMonitorInputStream(null, "Processing " + fileName, new FileInputStream(fileName)))); } }catch(Exception e){ ComPanel.appendText("error in opening file \""+fileName+"\" \n"); return 1; } int errors = 0; try{ boolean done = false; while(in.ready() && !done){ // process the whole file String cmd = getNextCommand(in); if(cmd.length()>0){ if(cmd.startsWith("@")){ String subFileName = cmd.substring(1,cmd.length()-1); errors += executeTTYScript(subFileName.trim(),ignoreErrors, false); if(!ignoreErrors && errors>0){ done = true; } } else{ ComPanel.appendText(cmd+"\n"); if(!ComPanel.execUserCommand(cmd)){ Reporter.debug("error during process command " + cmd); errors++; if(!ignoreErrors || !ComPanel.isConnected()){ done = true; } } } } } }catch(Exception e){ ComPanel.appendText("exception in processing file "+fileName+"\n"); Reporter.debug(e); errors++; } finally{ try{ if(in!=null){ in.close(); } }catch(Exception e){} } return errors; } /** Converts a list into a command. * The list can be a string atom, a text atom or a * list consisting of a sequence of text atoms and string atoms. * If the list has an invalid format, the reuslt will be null. **/ private String listToCommand(ListExpr list){ int at = list.atomType(); String command=""; switch(at){ case ListExpr.STRING_ATOM: command = list.stringValue(); break; case ListExpr.TEXT_ATOM: command = list.textValue(); break; case ListExpr.NO_ATOM: while(!list.isEmpty()){ ListExpr part = list.first(); list = list.rest(); int atp = part.atomType(); switch(atp){ case ListExpr.STRING_ATOM: command += part.stringValue(); break; case ListExpr.TEXT_ATOM: command += part.textValue(); break; default: return null; } } break; default: return null; } return command; } /** Executes the test describen in the testlist. * The listformat has to be: * ( COMMAND RESULT ) * The COMMAND format is described in listToCommand. * The RESULT must be a list formatted as * ( SUCCESS EPSILON RESULTLIST ) * where SUCCESS is a boolean atom (if false, the remaining parts * are ignored. The value of EPSILON described the precision used for * checking numeric values for equality. And the resultlist describes * expected result list. If an error occurs while executing a command, * the command is appended to theCommand). * @return: the succcess of the test **/ private boolean makeTest(ListExpr test,StringBuffer failedCommands){ if(test.listLength()!=2){ Reporter.writeError("invalid listlength for test"); test.writeListExpr(); return false; } String command = listToCommand(test.first()); if(command==null){ Reporter.writeError("invalid format of command in test"); test.writeListExpr(); return false; } ListExpr resultSpec = test.second(); if(resultSpec.listLength()!=2){ Reporter.writeError("Error in resultspecification detected, \n"+ "list containing two elements expected"); return false; } ListExpr resPlace=resultSpec.first(); int at = resPlace.atomType(); if(at!=ListExpr.SYMBOL_ATOM){ Reporter.writeError("first element of result must be an symbol "); return false; } String rp = resPlace.symbolValue(); boolean fromFile=false; if(rp.equals("file")){ fromFile=true; } else if(rp.equals("list")){ fromFile=false; } else{ Reporter.writeError("first element of result has to be 'list' or 'file'"); return false; } resultSpec=resultSpec.second(); at = resultSpec.atomType(); if(at!=ListExpr.BOOL_ATOM && at!=ListExpr.NO_ATOM){ Reporter.writeError("wrong result format in test"); test.writeListExpr(); return false; } boolean expSuccess=false; ListExpr expResult = null; double epsilon = 0.0; boolean isTest=true; if(at==ListExpr.BOOL_ATOM){ expSuccess=resultSpec.boolValue(); } else{ int len = resultSpec.listLength(); if(len==0){ // only a command, not a proper test isTest = false; } else { // read the value of success ListExpr f = resultSpec.first(); if(f.atomType()!=ListExpr.BOOL_ATOM){ Reporter.writeError("invalid result specification in test"); resultSpec.writeListExpr(); return false; } else{ expSuccess = f.boolValue(); } if(len>=2){ if(!fromFile){ expResult = resultSpec.second(); } else { int at2 = resultSpec.second().atomType(); String FileName=""; switch(at2){ case ListExpr.SYMBOL_ATOM: FileName = resultSpec.second().symbolValue(); break; case ListExpr.STRING_ATOM: FileName = resultSpec.second().stringValue(); break; case ListExpr.TEXT_ATOM: FileName = resultSpec.second().textValue(); break; default: Reporter.writeError("invalid filename specification in result"); } expResult = ListExpr.getListExprFromFile(FileName); if(expResult==null){ Reporter.writeError("Error in loading '" + FileName+"'"); return false; } } } if(len==3){ // full format ( ListExpr t = resultSpec.third(); int tat = t.atomType(); switch(tat){ case ListExpr.INT_ATOM : epsilon = t.intValue(); break; case ListExpr.REAL_ATOM : epsilon = t.realValue(); break; default: Reporter.writeError("invalid format for epsilon in test"); t.writeListExpr(); return false; } } } } Reporter.writeInfo("test command " + command); boolean res = ComPanel.execUserCommand(command,isTest,expSuccess, epsilon,true,expResult); if(!res){ failedCommands.append(command+"\n"); } return res; } /** executes a testfile * @param haltOnErrors: if set to true, the test section will be finished if an error occurs. * @return: numbe of errors found */ private int executeTestFile(String fileName, boolean haltOnErrors, StringBuffer failedCommands){ Reporter.writeInfo("test file "+ fileName); int errors = 0; try{ // Test specifications within Javagui are given as NestedList ListExpr testList = ListExpr.getListExprFromFile(fileName); if(testList==null){ Reporter.writeError("Error in loading of test specification"); return 1; } int len = testList.listLength(); if(len!=3){ // format has to be ( ) Reporter.writeError("Invalid listlength for testfile specification"); return 1; } ListExpr setup = testList.first(); // the setup file is a list in form ( ... ) if(setup.atomType()!=ListExpr.NO_ATOM){ Reporter.writeError("Invalid Setup part in TestList found "); return 1; } // execute all commands in setup part ignoring any errors in execution Reporter.writeInfo("--------------------------------\n"+ " enter setup section \n"+ "--------------------------------n"); while(!setup.isEmpty()){ String command = listToCommand(setup.first()); setup = setup.rest(); if(command==null){ Reporter.writeError("Invalid format for a command in setup section detected"); errors++; }else{ ComPanel.execUserCommand(command); } } ListExpr tests = testList.second(); // tests has to be in format ( ... ) if(tests.atomType() != ListExpr.NO_ATOM){ Reporter.writeError("Invalid format of tests found in file specification "); Reporter.writeInfo(" switch to teardown "); } else{ Reporter.writeInfo("--------------------------------------------\n"+ " enter test section \n"+ "---------------------------------------------"); boolean stop = false; int testno = 1; while(!tests.isEmpty() && !stop){ Reporter.writeInfo (" -------> test number " + testno + " <------"); if(!makeTest(tests.first(),failedCommands)){ errors++; stop = haltOnErrors; } testno++; tests = tests.rest(); } } // teardown: this section has the same format as the setup section // all errors except wrong formatted lists are ignored ListExpr teardown = testList.third(); if(teardown.atomType()!=ListExpr.NO_ATOM){ Reporter.writeError("Invalid format of teardown section in testfile "); return errors + 1; } Reporter.writeInfo("--------------------------------------------\n"+ " enter teardown section \n"+ "---------------------------------------------"); while(!teardown.isEmpty()){ String command = listToCommand(teardown.first()); if(command==null){ Reporter.writeError("Invalid command format in teardown section found"); errors++; }else{ ComPanel.execUserCommand(command); } teardown = teardown.rest(); } } catch(Exception e){ Reporter.writeError("Error in testing file "); Reporter.debug(e); errors++; } return errors; } /** make Menu appropriate to MenuVector from CurrentViewer */ public void updateMenu(){ cleanMenu(false); CurrentMenuVector = null; // add the new Menu if (CurrentViewer!=null){ try{ CurrentMenuVector = CurrentViewer.getMenuVector(); if (CurrentMenuVector!=null) for(int i=0;i0){ Reporter.writeError("during the test " + errors + " errors occurred" ); Reporter.writeError("failed commands :"+failedCommands); } else{ Reporter.writeInfo("All tests were performed successfully"); } try{ Thread.sleep(5000); }catch(Exception e){} SecGui.shutdown(errors); } if(tools.Environment.TESTMODE==tools.Environment.TESTRUNNER_MODE){ Reporter.writeInfo(" ====== TESTRUNNER MODE ===="); tools.Environment.DEBUG_MODE=true; if(testfile==null){ Reporter.writeError("file expected"); }else{ TestRunner tr = new TestRunner(ComPanel); int errors = tr.processFile(testfile.getAbsolutePath(),true); if(errors==0){ Reporter.writeInfo("all tests were ok"); } else{ Reporter.writeError("found "+errors+" errors during processing of "+args[1]); } try{ Thread.sleep(5000); }catch(Exception e){} SecGui.shutdown(errors); } } MainWindow.ComPanel.requestFocus(); } private static void setLAF(){ if(LAF!=null){ UIManager.LookAndFeelInfo installedLAFs[]; installedLAFs = UIManager.getInstalledLookAndFeels(); boolean done = false; for(int i=0;i=MAX_FONTSIZE) MI_FontSize_Console_Bigger.setEnabled(false); MI_FontSize_Console_Smaller.setEnabled(true); } if(src.equals(MI_FontSize_Console_Smaller)){ fs = ComPanel.getFontSize()-2; ComPanel.setFontSize(fs); if(fs<=MIN_FONTSIZE) MI_FontSize_Console_Smaller.setEnabled(false); MI_FontSize_Console_Bigger.setEnabled(true); } if(src.equals(MI_FontSize_List_Bigger)){ fs = OList.getFontSize()+2; OList.setFontSize(fs); if (fs>=MAX_FONTSIZE) MI_FontSize_List_Bigger.setEnabled(false); MI_FontSize_List_Smaller.setEnabled(true); } if(src.equals(MI_FontSize_List_Smaller)){ fs = OList.getFontSize()-2; OList.setFontSize(fs); if(fs<=MIN_FONTSIZE) MI_FontSize_List_Smaller.setEnabled(false); MI_FontSize_List_Bigger.setEnabled(true); } }}; MI_FontSize_Console_Bigger.addActionListener(FontSizeAL); MI_FontSize_Console_Smaller.addActionListener(FontSizeAL); MI_FontSize_List_Bigger.addActionListener(FontSizeAL); MI_FontSize_List_Smaller.addActionListener(FontSizeAL); JMenu MI_ExecuteFile = new JMenu("Execute file"); ProgramMenu.add(MI_ExecuteFile); MI_ExecuteFile_HaltOnError = new JMenuItem("Halt on error"); MI_ExecuteFile_IgnoreErrors = new JMenuItem("Ignore errors"); MI_ExecuteFile.add(MI_ExecuteFile_HaltOnError); MI_ExecuteFile.add(MI_ExecuteFile_IgnoreErrors); ActionListener ExecuteListener= new ActionListener(){ public void actionPerformed(ActionEvent evt){ if(FC_ExecuteFile.showOpenDialog(MainWindow.this)==JFileChooser.APPROVE_OPTION){ Object Source = evt.getSource(); if(Source.equals(MI_ExecuteFile_HaltOnError)){ executeFile(FC_ExecuteFile.getSelectedFile().getPath(),false, false); } else { executeFile(FC_ExecuteFile.getSelectedFile().getPath(),true, false); } } } }; MI_ExecuteFile_HaltOnError.addActionListener(ExecuteListener); MI_ExecuteFile_IgnoreErrors.addActionListener(ExecuteListener); JMenu HistoryMenu = new JMenu("History"); ProgramMenu.add(HistoryMenu); MI_SaveHistory=HistoryMenu.add("Save history"); MI_ClearHistory=HistoryMenu.add("Clear history"); JMenu LoadHistoryMenu = new JMenu("Load"); HistoryMenu.add(LoadHistoryMenu); MI_ExtendHistory = LoadHistoryMenu.add("Append"); MI_ReplaceHistory = LoadHistoryMenu.add("Replace"); ActionListener HistoryListener = new ActionListener(){ public void actionPerformed(ActionEvent evt){ Object Source = evt.getSource(); if(Source.equals(MI_ClearHistory)) ComPanel.clearHistory(); else if(Source.equals(MI_SaveHistory)) saveHistory(); else if(Source.equals(MI_ExtendHistory)) loadHistory(false); else if(Source.equals(MI_ReplaceHistory)) loadHistory(true); } }; MI_SaveHistory.addActionListener(HistoryListener); MI_ClearHistory.addActionListener(HistoryListener); MI_ExtendHistory.addActionListener(HistoryListener); MI_ReplaceHistory.addActionListener(HistoryListener); JMenu QueryMenu = new JMenu("Favoured Queries"); ProgramMenu.add(QueryMenu); MI_AddLastQuery = new JMenuItem("Add Last Query"); MI_ShowQueries = new JMenuItem("Show"); MI_SaveQueries = new JMenuItem("Save"); MI_LoadQueries = new JMenuItem("Load"); QueryMenu.add(MI_AddLastQuery); QueryMenu.add(MI_ShowQueries); QueryMenu.add(MI_SaveQueries); QueryMenu.add(MI_LoadQueries); ActionListener QueryListener = new ActionListener(){ public void actionPerformed(ActionEvent evt){ Object source = evt.getSource(); if(source.equals(MI_AddLastQuery)){ MainWindow.this.addLastQuery(); } else if(source.equals(MI_ShowQueries)){ MainWindow.this.showQueries(); } else if (source.equals(MI_SaveQueries)){ MainWindow.this.saveQueries(); } else if(source.equals(MI_LoadQueries)){ MainWindow.this.loadQueries(); } } }; MI_AddLastQuery.addActionListener(QueryListener); MI_ShowQueries.addActionListener(QueryListener); MI_SaveQueries.addActionListener(QueryListener); MI_LoadQueries.addActionListener(QueryListener); MI_Snapshot = ProgramMenu.add("Snapshot"); MI_Snapshot.setAccelerator(KeyStroke.getKeyStroke("alt C")); MI_Snapshot.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ if(saveSnapshot(false)){ Reporter.showInfo("Snapshot written"); } } }); JMenuItem MI_SnapshotEPS = ProgramMenu.add("Snapshot as EPS"); MI_SnapshotEPS.setAccelerator(KeyStroke.getKeyStroke("shift alt C")); MI_SnapshotEPS.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ if(exportToPS(MainWindow.this)){ Reporter.showInfo("Snapshot written"); } } }); /* JMenuItem MI_CurrentSnapshotEPS = ProgramMenu.add("Current window as EPS"); MI_SnapshotEPS.setAccelerator(KeyStroke.getKeyStroke("shift alt F")); MI_SnapshotEPS.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ if(exportToPS(MainWindow.this)){ Reporter.showInfo("Snapshot written"); } } }); */ JMenuItem MI_ScreenSnapshot = ProgramMenu.add("ScreenSnapshot"); MI_ScreenSnapshot.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ if(saveSnapshot(true)){ Reporter.showInfo("Snapshot written"); } } }); MI_ScreenSnapshot.setAccelerator(KeyStroke.getKeyStroke("alt S")); MI_Close = ProgramMenu.add("Exit"); MI_Close.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent E){ ComPanel.disconnect(); ComPanel.disableOptimizer(); saveHistory(new File(AUTO_HISTORY_FILE),false,AUTO_HISTORY_LENGTH); ComPanel.saveQueries(AUTO_QUERY_FILE); System.exit(0); }}); // Create the Server-Menu ServerMenu = new JMenu("Server"); ServerMenu.addMenuListener(new MenuListener(){ public void menuSelected(MenuEvent evt){ if(ComPanel.isConnected()){ MI_Connect.setEnabled(false); MI_Disconnect.setEnabled(true); } else{ MI_Connect.setEnabled(true); MI_Disconnect.setEnabled(false); } } public void menuDeselected(MenuEvent evt){} public void menuCanceled(MenuEvent evt){} } ); MI_Connect = ServerMenu.add("Connect"); MI_Disconnect = ServerMenu.add("Disconnect"); MI_Settings = ServerMenu.add("Settings"); MI_User = ServerMenu.add("User settings"); MI_Connect.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ if(ComPanel.connect()) getServerInfos(); }}); MI_Disconnect.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ ComPanel.disconnect(); }}); MI_Settings.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ showServerSettings(); }}); MI_User.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ StringBuffer u = new StringBuffer(); StringBuffer p = new StringBuffer(); showUserSettings(u,p); ComPanel.setConnection(u.toString(), p.toString(), ComPanel.getHostName(), ComPanel.getPort()); }}); OptimizerMenu = new JMenu("Optimizer"); MI_OptimizerEnable = OptimizerMenu.add("Enable"); MI_OptimizerDisable = OptimizerMenu.add("Disable"); OptimizerCommandMenu = new JMenu("Command"); OptimizerMenu.add(OptimizerCommandMenu); UpdateRelationsMenu = new JMenu("Update Relation"); OptimizerCommandMenu.add(UpdateRelationsMenu); UpdateIndexMenu = new JMenu("Update Index"); OptimizerCommandMenu.add(UpdateIndexMenu); MI_OptimizerUpdateCatalog = new JMenuItem("Update Catalog"); MI_OptimizerTestOptimizer = new JMenuItem("Test Optimizer"); MI_OptimizerReconnectWhenOpenDB = new JCheckBoxMenuItem("Auto Reconnect"); MI_OptimizerReconnectWhenOpenDB.setSelected(true); MI_OptimizerAutoUpdateCatalog = new JCheckBoxMenuItem("Auto Update Catalog"); MI_OptimizerAutoUpdateCatalog.setSelected(true); ComPanel.setAutoUpdateCatalog(true); MI_OptimizerAutoUpdateCatalog.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent evt){ ComPanel.setAutoUpdateCatalog(MI_OptimizerAutoUpdateCatalog.isEnabled()); } }); MI_OptimizerResetKnowledgeDB = new JMenuItem("Reset Optimizer's Knowledge Database"); OptimizerCommandMenu.add(MI_OptimizerUpdateCatalog); OptimizerCommandMenu.add(MI_OptimizerAutoUpdateCatalog); OptimizerCommandMenu.add(MI_OptimizerReconnectWhenOpenDB); OptimizerCommandMenu.add(MI_OptimizerResetKnowledgeDB); OptimizerCommandMenu.addSeparator(); OptimizerCommandMenu.add(MI_OptimizerTestOptimizer); MI_UpdateRelationList = UpdateRelationsMenu.add("Update List"); ActionListener A = new ActionListener(){ public void actionPerformed(ActionEvent evt){ updateObjectList(); updateRelationList(); } }; MI_UpdateIndexList = UpdateIndexMenu.add("Update List"); MI_UpdateRelationList.addActionListener(A); MI_UpdateIndexList.addActionListener(A); ActionListener b = new ActionListener(){ public void actionPerformed(ActionEvent evt){ Object src = evt.getSource(); if(src==null){ return; } if(src.equals(MI_OptimizerUpdateCatalog)){ updateCatalog(); } if(src.equals(MI_OptimizerResetKnowledgeDB)){ resetKnowledgeDB(); } if(src.equals(MI_OptimizerTestOptimizer)){ testOptimizer(); } } }; MI_OptimizerUpdateCatalog.addActionListener(b); MI_OptimizerTestOptimizer.addActionListener(b); MI_OptimizerResetKnowledgeDB.addActionListener(b); JMenu Entropy = new JMenu("Entropy"); MI_EnableEntropy = Entropy.add("enable"); MI_DisableEntropy = Entropy.add("disable"); ActionListener EntropyListener = new ActionListener(){ public void actionPerformed(ActionEvent evt){ if(MI_EnableEntropy.equals(evt.getSource())){ enableEntropy(true); }else{ enableEntropy(false); } } }; MI_EnableEntropy.addActionListener(EntropyListener); MI_DisableEntropy.addActionListener(EntropyListener); if(useEntropy) OptimizerCommandMenu.add(Entropy); MI_OptimizerSettings = OptimizerMenu.add("Settings"); OptimizerMenu.addMenuListener(new MenuListener(){ public void menuSelected(MenuEvent evt){ if(ComPanel.useOptimizer()){ MI_OptimizerEnable.setEnabled(false); MI_OptimizerDisable.setEnabled(true); OptimizerCommandMenu.setEnabled(true); } else{ MI_OptimizerEnable.setEnabled(true); MI_OptimizerDisable.setEnabled(false); OptimizerCommandMenu.setEnabled(false); } } public void menuDeselected(MenuEvent evt){} public void menuCanceled(MenuEvent evt){} } ); ActionListener OptimizerListener= new ActionListener(){ public void actionPerformed(ActionEvent evt){ Object source = evt.getSource(); if(source.equals(MI_OptimizerEnable)){ if(!ComPanel.enableOptimizer()){ ComPanel.appendText("enabling optimizer failed"); ComPanel.showPrompt(); } else{ ComPanel.appendText("optimizer enabled"); ComPanel.showPrompt(); } } if(source.equals(MI_OptimizerDisable)){ ComPanel.appendText("optimizer disabled"); ComPanel.showPrompt(); ComPanel.disableOptimizer(); } if(source.equals(MI_OptimizerSettings)) ComPanel.showOptimizerSettings(); }}; MI_OptimizerEnable.addActionListener(OptimizerListener); MI_OptimizerSettings.addActionListener(OptimizerListener); MI_OptimizerDisable.addActionListener(OptimizerListener); Menu_ServerCommand = new JMenu("Command"); // commands are only possible if connected Menu_ServerCommand.setEnabled(false); Menu_BasicCommands = new JMenu("Basic Commands"); Menu_BasicCommands.setEnabled(false); Menu_Inquiries = new JMenu("Inquiries"); Menu_Inquiries.setEnabled(false); Menu_Databases = new JMenu("Databases"); Menu_Databases.setEnabled(false); Menu_Transactions = new JMenu("Transactions"); Menu_Transactions.setEnabled(false); Menu_ImExport = new JMenu("Import / Export"); Menu_ImExport.setEnabled(false); Menu_ServerCommand.add(Menu_BasicCommands); Menu_ServerCommand.add(Menu_Inquiries); Menu_ServerCommand.add(Menu_Databases); Menu_ServerCommand.add(Menu_Transactions); Menu_ServerCommand.add(Menu_ImExport); // Inquiries MI_ListDatabases=Menu_Inquiries.add("list databases"); MI_ListTypes = Menu_Inquiries.add("list types"); MI_ListTypeConstructors = Menu_Inquiries.add("list type constructors"); MI_ListObjects = Menu_Inquiries.add("list objects"); MI_ListOperators = Menu_Inquiries.add("list operators"); MI_ListAlgebras = Menu_Inquiries.add("list algebras"); AlgebraMenu = new JMenu("list algebra"); Menu_Inquiries.add(AlgebraMenu); // databases MI_UpdateDatabases = new JMenuItem("Update"); Menu_Databases.add(MI_UpdateDatabases); MI_CreateDatabase = new JMenuItem("create database"); Menu_Databases.add(MI_CreateDatabase); OpenDatabaseMenu = new JMenu("open database"); Menu_Databases.add(OpenDatabaseMenu); MI_CloseDatabase = new JMenuItem("close database"); Menu_Databases.add(MI_CloseDatabase); DeleteDatabaseMenu = new JMenu("delete database"); Menu_Databases.add(DeleteDatabaseMenu); // Transactions MI_BeginTransaction = Menu_Transactions.add("begin"); MI_AbortTransaction = Menu_Transactions.add("abort"); MI_CommitTransaction = Menu_Transactions.add("commit"); // Import Export MI_SaveDatabase = Menu_ImExport.add("~save database~"); Menu_RestoreDatabase = new JMenu("restore database"); Menu_ImExport.add(Menu_RestoreDatabase); MI_SaveObject = Menu_ImExport.add("~save object~"); MI_RestoreObject = Menu_ImExport.add("restore object"); // Basic Commands MI_CreateType = Menu_BasicCommands.add("~create type~"); MI_DeleteType = Menu_BasicCommands.add("~delete type~"); MI_CreateObject = Menu_BasicCommands.add("~create object~"); MI_UpdateObject = Menu_BasicCommands.add("~update~"); MI_DeleteObject = Menu_BasicCommands.add("delete object"); MI_Let = Menu_BasicCommands.add("~let~"); MI_Query = Menu_BasicCommands.add("~query~"); Command_Listener Com_Listener = new Command_Listener(); MI_ListDatabases.addActionListener(Com_Listener); MI_ListTypes.addActionListener(Com_Listener); MI_ListTypeConstructors.addActionListener(Com_Listener); MI_ListObjects.addActionListener(Com_Listener); MI_ListOperators.addActionListener(Com_Listener); MI_ListAlgebras.addActionListener(Com_Listener); MI_UpdateDatabases.addActionListener(Com_Listener); MI_CloseDatabase.addActionListener(Com_Listener); MI_BeginTransaction.addActionListener(Com_Listener); MI_AbortTransaction.addActionListener(Com_Listener); MI_CommitTransaction.addActionListener(Com_Listener); MI_CreateDatabase.addActionListener(Com_Listener); MI_SaveDatabase.addActionListener(Com_Listener); MI_SaveObject.addActionListener(Com_Listener); MI_RestoreObject.addActionListener(Com_Listener); MI_CreateType.addActionListener(Com_Listener); MI_DeleteType.addActionListener(Com_Listener); MI_CreateObject.addActionListener(Com_Listener); MI_UpdateObject.addActionListener(Com_Listener); MI_DeleteObject.addActionListener(Com_Listener); MI_Let.addActionListener(Com_Listener); MI_Query.addActionListener(Com_Listener); HelpMenu = new JMenu("Help"); MI_ShowGuiCommands=HelpMenu.add("Show gui commands"); MI_ShowSecondoCommands = HelpMenu.add("Show secondo commands"); MI_ShowGuiCommands.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ MyHelp.setMode(HelpScreen.GUI_COMMANDS); MyHelp.setVisible(true); } }); MI_ShowSecondoCommands.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ MyHelp.setMode(HelpScreen.SECONDO_COMMANDS); MyHelp.setVisible(true); } }); Viewers = new JMenu("Viewers"); Viewers.addSeparator(); JMenuItem ViewerPriorities = Viewers.add("Set priorities"); ViewerPriorities.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ PriorityDlg.setVisible(true); } }); MI_ShowOnlyViewer = Viewers.add("Show only viewer"); MI_ShowOnlyViewer.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ onlyViewerSwitch(); } }); MI_AddViewer = Viewers.add("Add Viewer"); MI_AddViewer.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (ViewerFileChooser.showOpenDialog(MainWindow.this)==JFileChooser.APPROVE_OPTION){ String Name = ViewerFileChooser.getSelectedFile().getPath(); // a Viewer must be in "viewer" package and so in the viewer-directory int pos = Name.lastIndexOf("viewer"); if (pos<0){ Reporter.showWarning("a viewer must be in the viewer directory"); } else{ Name = Name.substring(pos); char FileSep = File.separatorChar; Name = Name.replace(FileSep,'.'); if (!Name.endsWith(".class")){ Reporter.showError("this is no class file"); } else{ Name= Name.substring(0,Name.length()-6); // remove ".class" extension try{ Class NViewerClass = Class.forName(Name); Object O = NViewerClass.newInstance(); if (!(O instanceof SecondoViewer)){ Reporter.showError("the selected class is not an SecondoViewer"); } else{ // is allright addViewer((SecondoViewer)O); } } catch(Exception e){ ComPanel.appendText(""+e); ComPanel.showPrompt(); Reporter.showError("cannot load the given Viewer\n"+ " see commandPanel for details"); Reporter.debug(e); } } } } } }); MI_SeparateViewer = Viewers.add("Show in own window"); MI_SeparateViewer.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ separateCurrentViewer(); } }); updateMenu(); // insert all stuff setJMenuBar(MainMenu); } /** clear the History, the ObjectList and the Content of all Viewers */ public void clearAll(){ long usedMemory=0; if(tools.Environment.MEASURE_MEMORY){ usedMemory=tools.Environment.usedMemory(); } ComPanel.clear(); OList.clearList(); for(int i=0;i"); return; } if(Source.equals(MainWindow.this.MI_SaveObject)){ ok = false; MainWindow.ComPanel.showPrompt(); MainWindow.ComPanel.appendText("save to "); return; } if(Source.equals(MainWindow.this.MI_RestoreObject)){ ok = true; String ObjectName = JOptionPane.showInputDialog("Please input the name for the object"); if(ObjectName==null || ObjectName.equals("")){ return; } MainWindow.ComPanel.showPrompt(); String fname; if(FC_Object.showOpenDialog(MainWindow.this)==JFileChooser.APPROVE_OPTION){ fname ="'"+FC_Object.getSelectedFile().getPath()+"'"; } else { return; } cmd = "restore "+ObjectName+" from "+fname; MainWindow.ComPanel.appendText(cmd); MainWindow.ComPanel.addToHistory(cmd); MainWindow.ComPanel.execUserCommand(cmd); return; } if(Source.equals(MainWindow.this.MI_CreateType)){ ok = false; MainWindow.ComPanel.showPrompt(); MainWindow.ComPanel.appendText("type = "); return; } if(Source.equals(MainWindow.this.MI_DeleteType)){ ok = true; String typename = JOptionPane.showInputDialog("Please enter the name of the type to delete"); if(typename==null || typename.trim().equals("")){ return; } MainWindow.ComPanel.showPrompt(); cmd = "delete type " + typename; MainWindow.ComPanel.appendText(cmd); MainWindow.ComPanel.addToHistory(cmd); MainWindow.ComPanel.execUserCommand(cmd); return; } if(Source.equals(MainWindow.this.MI_CreateObject)){ ok = false; MainWindow.ComPanel.showPrompt(); MainWindow.ComPanel.appendText("create : "); return; } if(Source.equals(MainWindow.this.MI_UpdateObject)){ ok = false; MainWindow.ComPanel.showPrompt(); MainWindow.ComPanel.appendText("update := "); return; } if(Source.equals(MainWindow.this.MI_DeleteObject)){ ok = true; String objname = JOptionPane.showInputDialog("Please enter the name of the object to delete"); if(objname==null || objname.trim().equals("")){ return; } MainWindow.ComPanel.showPrompt(); cmd = "delete " + objname; MainWindow.ComPanel.appendText(cmd); MainWindow.ComPanel.addToHistory(cmd); MainWindow.ComPanel.execUserCommand(cmd); return; } if(Source.equals(MainWindow.this.MI_Let)){ ok = false; MainWindow.ComPanel.showPrompt(); MainWindow.ComPanel.appendText("let = "); return; } if(Source.equals(MainWindow.this.MI_Query)){ ok = false; MainWindow.ComPanel.showPrompt(); MainWindow.ComPanel.appendText("query "); return; } if(Source.equals(MainWindow.this.MI_UpdateDatabases)){ ok = false; // execute no Secondo command if(!MainWindow.this.updateDatabases()) Reporter.showError("error in reading databases"); return; } if(Source.equals(MainWindow.this.MI_ListDatabases)){ ok = true; cmd = "list databases"; }else if (Source.equals(MainWindow.this.MI_ListTypes)){ ok = true; cmd ="list types"; } else if (Source.equals(MainWindow.this.MI_ListTypeConstructors)){ ok = true; cmd ="list type constructors"; } else if (Source.equals(MainWindow.this.MI_ListObjects)){ ok = true; cmd ="list objects"; } else if(Source.equals(MainWindow.this.MI_ListOperators)){ ok = true; cmd="list operators"; } else if(Source.equals(MainWindow.this.MI_ListAlgebras)){ ok = true; cmd = "list algebras"; }else if(Source.equals(MainWindow.this.MI_CloseDatabase)){ ok = true; cmd = "close database"; } else if(Source.equals(MainWindow.this.MI_BeginTransaction)){ ok = true; cmd = "begin transaction"; } else if(Source.equals(MainWindow.this.MI_AbortTransaction)){ ok = true; cmd = "abort transaction"; }else if(Source.equals(MainWindow.this.MI_CommitTransaction)){ ok = true; cmd = "commit transaction"; } if (ok) { MainWindow.ComPanel.showPrompt(); MainWindow.ComPanel.appendText(cmd); MainWindow.ComPanel.addToHistory(cmd); MainWindow.ComPanel.execUserCommand(cmd); } } } } public void setTestMode(int tm){ tools.Environment.TESTMODE=tm; boolean isTest = tm!=tools.Environment.NO_TESTMODE; for(int i=0;i