/*

 * Title: japlot.jaxodraw
 * Description: Graphical user interface for drawing Feynman diagrams
 * @author Daniele Binosi 
 * @author Lukas Theussl  

 Copyright (C) 2003-2006,  Daniele Binosi and Lukas Theussl

 See the file LICENSE in the source distribution home directory
 for a full copy of the GPL (GNU General Public License).

    This file is part of japlot.jaxodraw.

    japlot.jaxodraw 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.

    japlot.jaxodraw 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


 */
package japlot.jaxodraw;

import japlot.*;
import java.awt.*;
import java.awt.event.*;
import japlot.Plot;

import org.freehep.graphics2d.VectorGraphics;

import java.io.File;
import java.io.IOException;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;

import jhplot.JHPlot;
import jhplot.HPlotJa;
import jhplot.jadraw.JaLatexText;
import jhplot.jadraw.JaObject;
import jhplot.utils.HelpDialog;



/** The main panel: holds the menu bar, the button panel, the flag panel and the
 * canvas. Responsible for the interaction between those components.
 */
public class JaxoMainPanel extends JFrame {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// Possible modes (to be filled in with new modes as soon as we coded them)
    /** Default drawing mode: do nothing. */
    public static final int STANDBY = 0;

    /** Fermion line. */
    public static final int FLINE = 3;

    /** Fermion loop. */
    public static final int FLOOP = 4;

    /** Fermion arc. */
    public static final int FARC = 5;

    /** Scalar line. */
    public static final int SLINE = 6;

    /** Ghost line. */
    public static final int GLINE = 9;

    /** Scalar loop. */
    public static final int SLOOP = 7;

    /** Ghost loop. */
    public static final int GLOOP = 10;

    /** Scalar arc. */
    public static final int SARC = 8;

    /** Ghost arc. */
    public static final int GARC = 11;

    /** Photon line. */
    public static final int PLINE = 12;

    /** Photon loop. */
    public static final int PLOOP = 13;

    /** Photon arc. */
    public static final int PARC = 14;

    /** Gluon line. */
    public static final int GLLINE = 15;

    /** Gluon loop. */
    public static final int GLLOOP = 16;

    /** Gluon arc. */
    public static final int GLARC = 17;

    /** Box (filled rectangle). */
    public static final int BOX = 30;

    /** Blob (filled ellipse). */
    public static final int BLOB = 31;

    /** Vertex (black circle). */
    public static final int VERTEX = 32;

    /** ZigZag line. */
    public static final int ZIGZAG = 33;

    /** Normal text. */
    public static final int TEXT = 34;

    /** Latex text. */
    public static final int LATEX = 35;

    /** A vertex type 1 object (a dot). */
    public static final int VERTEXT1 = 36;

    /** A vertex type 2 object (a cross with a circle). */
    public static final int VERTEXT2 = 37;

    /** A vertex type 3 object (a filled square). */
    public static final int VERTEXT3 = 38;

    /** A vertex type 4 object (a cross). */
    public static final int VERTEXT4 = 39;

    /** A vertex type 5 object (a triangle). */
    public static final int VERTEXT5 = 40;

    /** A vertex type 6 object (a diamond). */
    public static final int VERTEXT6 = 41;

    /** Undo the last operation. */
    public static final int UNDO = 42;

    /** Clear the current graph. */
    public static final int CLEAR = 43;

    /** Exit this japlot.jaxodraw session. */
    public static final int QUIT = 44;

    /** Refresh the screen. */
    public static final int REFRESH = 45;

    /** Paste the most recently selected objects from the clipboard. */
    public static final int PASTE = 46;

    /** Dynamic zoom. */

    // I am not really happy to put this mode under the action command
    // but did not find anything better
    public static final int ZOOM = 47; // before it was 60

    /** Move an object. */
    public static final int MOVE = 50;

    /** Resize an object. */
    public static final int RESIZE = 51;

    /** Copy an object. */
    public static final int COPY = 52;

    /** Color an object. */
    public static final int COLOR = 53;

    /** Edit an object. */
    public static final int EDIT = 54;

    /** Delete an object. */
    public static final int DELETE = 55;

    /** Put an object in the background. */
    public static final int BACKGROUND = 56;

    /** Put an object in the foreground. */
    public static final int FOREGROUND = 57;

    /** Group objects. */
    public static final int GROUP = 58;

    /** Ungroup objects. */
    public static final int UNGROUP = 59;

    /** Start a new graph. */
    public static final int NEWG = 70;

    /** Open a japlot.jaxodraw file. */
    public static final int OPEN = 71;

    /** Save a japlot.jaxodraw graph. */
    public static final int SAVE = 72;

    /** Save a japlot.jaxodraw graph in a given file. */
    public static final int SAVE_AS = 73;

    /** Enter a description of the graph. */
    public static final int DESCRIBE = 74;

    /** Export the graph. */
    public static final int EXPORT = 75;

    /** Print the graph. */
    public static final int PRINT = 76;

    /** Preview the graph. */
    public static final int PREVIEW = 77;

    /** Close the current buffer. */
    public static final int CLOSE = 78;

    /** Start a new graph tab. */
    public static final int NEWT = 80;

    /** Add a  custom Latex package to the Latex output of japlot.jaxodraw. */
    public static final int PACKAGE = 79;

    /** Import a Latex file. */
    public static final int IMPORT = 81;

     /** Open a ROOT/AIDA file. */
    public static final int OPENDATA = 82;

    /** A dummy variable. */
    public static final int DUMMIE = 10000;

    /** Another dummy. */
    public static final int DUMMIE1 = 10001;
    private ResourceBundle language =
        ResourceBundle.getBundle(JaxoPrefs.getPref(JaxoPrefs.PREF_LANGUAGE));

    // Buttons to be added to the panel

    /** The particle button panel of this JaxoMainPanel. */
    private JaxoParticleButtons pbtpanel;

    /** The edit button panel of this JaxoMainPanel. */
    private JaxoEditButtons ebtpanel;

    /** The misc button panel of this JaxoMainPanel. */
    private JaxoMiscButtons mbtpanel;
    private JaxoActionButtons abtpanel;
    private JaxoGridButtons gbtpanel;

    // Menus to be added to the panel
    private JaxoFileMenu filemenu;
    private JaxoEditMenu editmenu;
    private JaxoOptionsMenu optionsmenu;
    private JaxoHelpMenu helpmenu;
    private JaxoToolBar toolbar;
    private JaxoFlags flagpanel;
    private int currentMode;
    private JToolBar jToolBar;
   // private JToolBar jToolBarBrowser;
   // private JSplitPane jToolBarBrowser;
    
    //    private int oldMode;
    private int currentVertex;
    private String[] envFonts;
 
    // Watch file mode
    private boolean watchMode = false;
    
    final private String help_file = "japlot";
    // Zoom
    private JaxoZoom zoom;

    /** The panel that holds the tabs*/
    private JaxoTabbedCanvasPanel canvasPanel;

    /** The clipboard (used to copy objects into different tabs)*/
    private JaxoGraph clipboard = new JaxoGraph();

    /** A boolean variable that indicates whether the drawing/dragging should be done
     * with the grid or not.
     */
    private boolean snap = false;

    private HPlotJa japlot;
   
    
    
    private static final String rootKey = JaxoMainPanel.class.getName();
    private static final String SAVE_AS_TYPE = rootKey +".SaveAsType";
    private static final String SAVE_AS_FILE = rootKey +".SaveAsFile";
    
    
 
    public JaxoMainPanel( HPlotJa japlot) {
    
    	this.japlot=japlot;
    	
    }
    
    
    /**
     * Get HPlotJa
     */
    public HPlotJa getJaPlot() {
    	return japlot;
  
    }
    
    
    /** The initialisation method of the panel: sets up the menus, the button panels,
     * the flag panel and the canvas. If an input file was given on the command line,
     * opens it and creates the JaxoGraph.
     * @param inputFileName The name of the file to be opened.
     */
    public final void init(String inputFileName, JaxoGraph fGraph) {
        currentMode = STANDBY; // Set default mode

        currentVertex = VERTEXT1;


         

          setDefaultCloseOperation(javax.swing.JFrame.DO_NOTHING_ON_CLOSE);
                addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent event) {
                                filemenu.quit(); 
                        }
                });



             ImageIcon icone = new ImageIcon(getClass().getClassLoader()
                                .getResource("jhplot/images/logo_jhepwork_24x24.jpg"));
             setIconImage(icone.getImage());









        // Buttons Panel
        pbtpanel = new JaxoParticleButtons(this);
        ebtpanel = new JaxoEditButtons(this);
        mbtpanel = new JaxoMiscButtons(this);
        abtpanel = new JaxoActionButtons(this);
        // gbtpanel = new JaxoGridButtons(this);

        Box btPanel = new Box(BoxLayout.Y_AXIS);
        btPanel.add(pbtpanel);
        btPanel.add(mbtpanel); // panel with text 
        btPanel.add(abtpanel);
        btPanel.add(ebtpanel);
        // btPanel.add(gbtpanel);
        jToolBar = new JToolBar(null, JToolBar.VERTICAL);
        jToolBar.setLayout(new BorderLayout());
        jToolBar.add(btPanel);


        // Flag Panel
        flagpanel = new JaxoFlags(this);

        // The Toolbar
        toolbar = new JaxoToolBar(this);

        // jabrowser = new JaBrowser(this);
        //JPanel  jpan = jabrowser.buildTree();
        //obrowser= new ObjectBrowser(this,jpan);
        //obrowser.setVisible(false);
    
         
        // create a new graph
         JaxoGraph firstGraph = fGraph;
         if (firstGraph == null) firstGraph=new JaxoGraph();

     
      // if an input file has been given on the command line, we open it
        if ( inputFileName != null &&  inputFileName.length() != 0) {
            File inputFile = new File(inputFileName);
            inputFileName = inputFile.getAbsolutePath();

            try {
                firstGraph = (JaxoGraph) JaxoIO.open(inputFileName);
                firstGraph.setSaveFileName(inputFileName);
                firstGraph.setSaved(true);
            } catch (NullPointerException e) {
                JOptionPane.showMessageDialog(null,
                    language.getString(
                        "NullPointerException:_Cannot_open_file_")
                    + inputFileName);

                if (JaxoPrefs.verbose()) {
                    System.err.println(e);
                }
            }

            setFlagPanelFileName(inputFileName);

        } 



        // No object is selected yet.
        firstGraph.setBackupSelectedObject(null);
        firstGraph.setSelectedObject(null);

        // The CanvasPanel
        JaxoCanvas firstCanvas = new JaxoCanvas(this);
        firstCanvas.setCanvasGraph(firstGraph);
        firstCanvas.addMouseMotionListener(firstCanvas);
        firstCanvas.addMouseListener(firstCanvas);
        
        if (firstGraph.getShortName().length() != 0) {
            String fileName;
            int lp = firstGraph.getShortName().lastIndexOf(".");

            if (lp != -1) {
                fileName = firstGraph.getShortName().substring(0, lp);
            } else {
                fileName = firstGraph.getShortName();
            }

            firstCanvas.setCanvasTick(fileName);
        } else {
            firstCanvas.setCanvasTick(language.getString("Untitled"));
        }

        canvasPanel = new JaxoTabbedCanvasPanel(this);

        canvasPanel.registerTitle(firstCanvas.getCanvasTick());
        (canvasPanel.add(canvasPanel.getIndexedTitle(
                firstCanvas.getCanvasTick()), firstCanvas)).setName(firstCanvas
            .getCanvasTick());

        canvasPanel.setSelectedComponent(firstCanvas);

        for (int i = 0; i < firstGraph.listSize(); i++) {
            JaObject jaxoOb = (JaObject) firstGraph.listElementAt(i);

            if (jaxoOb instanceof JaLatexText) {
                ((JaLatexText) jaxoOb).createLatexPanel();
                firstCanvas.add(((JaLatexText) jaxoOb).getLatexPanel());
                ((JaLatexText) jaxoOb).getLatexPanel().setVisible(false);
            }
        }

        // Menu Bar
        filemenu = new JaxoFileMenu(this);
        editmenu = new JaxoEditMenu(this);
        optionsmenu = new JaxoOptionsMenu(this);
        helpmenu = new JaxoHelpMenu(this);

        JMenuBar jaxomenubar = new JMenuBar();
        jaxomenubar.add(filemenu);
        jaxomenubar.add(editmenu);
        jaxomenubar.add(optionsmenu);
        jaxomenubar.add(helpmenu);

        
        
        
        // The final layout
        //setTitle(japlot.jaxodraw.VERSION);
        getContentPane().add(toolbar, BorderLayout.NORTH);
        
        getContentPane().add(canvasPanel, BorderLayout.CENTER);
        setJMenuBar(jaxomenubar);
        getContentPane().add(jToolBar, BorderLayout.WEST);
      //  getContentPane().add(jToolBarBrowser, BorderLayout.EAST);
        getContentPane().add(flagpanel, BorderLayout.SOUTH);

        this.zoom = new JaxoZoom();

        // apply the preferences
        applyPrefs();

        this.addWindowListener(new WindowAdapter() {
                public final void windowClosing(WindowEvent we) {
                    fileEvent(QUIT);
                }
            });
    }



     // set graph
     public void setGraph(JaxoGraph graph ) {  
      graph.setSaveFileName("Untitled");
      graph.setBackupSelectedObject(null);
      graph.setSelectedObject(null);
      filemenu.open(graph);

     }


    // Get the current mode

    /** Return the current drawing/editing mode.
     * @return The current drawing/editing mode.
     */
    public final int getMode() {
        return currentMode;
    }

    /** Sets the current drawing/edit mode.
     * @param newMode The drawing/edit mode to be set.
     */
    public final void setMode(int newMode) {
        currentMode = newMode;
    }

    /** Returns an instance of the canvas.
     * @return The canvas.
     */
    public final JaxoCanvas getCanvas() {
        return (JaxoCanvas) canvasPanel.getSelectedComponent();
    }

    /** Determines whether the current mode is an edit mode.
     * @return True if the current mode is an edit mode.
     */
    public final boolean isEditMode() {
        boolean iem = true;

        if ((currentMode < 50) || (currentMode > 70)) {
            iem = false;
        }

        return iem;
    }

    /** Determines whether the current mode is a particle mode.
     * @return True if the current mode is a particle mode.
     */
    public final boolean isParticleMode() {
        boolean ipm = true;

        if ((currentMode > 20) || (currentMode < 3)) {
            ipm = false;
        }

        return ipm;
    }

    /** Determines whether the current mode is a misc mode.
     * @return True if the current mode is a misc mode.
     */
    public final boolean isMiscMode() {
        boolean imm = true;

        if ((currentMode < 30) || (currentMode > 36)) {
            imm = false;
        }

        return imm;
    }

    /** Resets the canvas. */
    public final void reset() {
        JaxoCanvas actCan = getCanvas();

        if (actCan == null) return;

        actCan.clearOffScreenImage();

        VectorGraphics g2 = (VectorGraphics) actCan.getOffScreenImage().getGraphics();

        //         RenderingHints rhints = g2.getRenderingHints();
        //         boolean antialiasOn =
        //             rhints.containsValue(RenderingHints.VALUE_ANTIALIAS_ON);
        // Enable antialiasing for shapes
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

        JaxoGraph actCanGraph = actCan.getCanvasGraph();

        // first
        for (int i = 0; i < actCanGraph.listSize(); i++) {
            JaObject jaxoOb = (JaObject) actCanGraph.listElementAt(i);
            if (Plot.drawFirst(jaxoOb)) jaxoOb.jaxoDraw(g2, true);
        }
            // this is second
            for (int i = 0; i < actCanGraph.listSize(); i++) {
                 JaObject jaxoOb = (JaObject) actCanGraph.listElementAt(i); 
                 Plot.drawRest( jaxoOb,g2,true);
            }


        g2.dispose();
        actCan.repaint();
    }

    /** Sets the coordinates in the flag panel.
     * @param coordinates The coordinates to be set.
     */
    public final void setFlagPanelCoordinates(String coordinates) {
        flagpanel.setCoordFlagText(coordinates);
    }

    /** Sets the current drawing/edit mode in the flag panel.
     * @param mode The mode to be set.
     */
    public final void setFlagPanelMode(String mode) {
        flagpanel.setControlFlagText(mode);
    }

    /** Sets the current file being edited in the flag panel.
     * @param filename The filename to be set.
     */
    public final void setFlagPanelFileName(String filename) {
        flagpanel.setFileFlagText(filename);
    }

    /** Sets the text and tool tips for all components of the panel
     * (the menus, toolbar, button panels and status bar) in different languages.
     * @param languageString A string specifying the language to be set.
     */
    public final void setLanguage(String languageString) {
        JaxoPrefs.setPref(JaxoPrefs.PREF_LANGUAGE, languageString);

        filemenu.setLanguage(languageString);
        editmenu.setLanguage(languageString);
        optionsmenu.setLanguage(languageString);
        helpmenu.setLanguage(languageString);

        toolbar.setLanguage(languageString);

        pbtpanel.setLanguage(languageString);
        mbtpanel.setLanguage(languageString);
        abtpanel.setLanguage(languageString);
        ebtpanel.setLanguage(languageString);
        // gbtpanel.setLanguage(languageString);

        flagpanel.setLanguage(languageString);
        canvasPanel.setLanguage(languageString);
    }

    /** Processes the corresponding events whenever a particle button has been pressed.
     * @param i An integer specifying the particle button that was pressed.
     */
    public final void particleEvent(int i) {
        JaxoCanvas theCanvas = getCanvas();
        // chekanov
        // theCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
        resetButtons();

        int j = pbtpanel.getIndex(i);
        pbtpanel.pressButton(j);
        flagpanel.setControlFlagText(pbtpanel.getParticleFlagModes(j));
        setMode(i);
        theCanvas.getCanvasGraph().setSelectedObject(null);
        theCanvas.drawWithHandles(false);
        theCanvas.drawVisualAid(false);
        theCanvas.repaint();
    }

    /** Called when a misc item has been chosen from the button panel.
     * Presses the corresponding button in the button panel, sets
     * the mode in the flag panel, sets the current mode and shows all handles.
     * Finally, makes sure that no object is selected.
     * @param i Integer specifying the misc mode.
     */
    public final void miscEvent(int i) {
        JaxoCanvas theCanvas = getCanvas();
        resetButtons();

        int j = mbtpanel.getIndex(i);

        // chekanov
        /*
        if (j > 3) {
            theCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
        } else {
            theCanvas.setCursor(Cursor.getPredefinedCursor(
                    Cursor.CROSSHAIR_CURSOR));
        }
        */

        mbtpanel.pressButton(j);
        flagpanel.setControlFlagText(mbtpanel.getMiscFlagModes(j));
        setMode(i);
        theCanvas.getCanvasGraph().setSelectedObject(null);
        theCanvas.drawWithHandles(false);
        theCanvas.drawVisualAid(false);
        theCanvas.repaint();
    }

    
    /* Calls updateUI on all sub-components of the JFrame */
	public void updateUI() {
		SwingUtilities.updateComponentTreeUI(this);
	}
    
   
    
      /* set axes */ 
        public void setAxes(int n1, int n2) {
               japlot.clearAllData(); 
               japlot.clearAll();
               japlot.setAxesFrame(n1,n2); 
               japlot.update(); 
        }
 
    
    
    
    
    /** Called when an edit item has been chosen from the menu bar, the button panel or
     * via key shortcuts. Presses the corresponding button in the button panel, sets
     * the mode in the flag panel, sets the current mode and shows all handles.
     * Finally, makes sure that no object is selected.
     * @param i Integer specifying the edit mode.
     */
    public final void editEvent(int i) {
        JaxoCanvas theCanvas = getCanvas();
        resetButtons();

        int j = 0;

        
       //  if (i == ZOOM) { //Zoom event
       //      gbtpanel.pressButton(1);
       //  } else {
            j = ebtpanel.getIndex(i);
            ebtpanel.pressButton(j);
      //  }

        /* chekanov 
        if (j == 10) {
            theCanvas.setCursor(Cursor.getPredefinedCursor(
                    Cursor.DEFAULT_CURSOR));
        } else if (j < 3) {
            theCanvas.setCursor(Cursor.getPredefinedCursor(
                    Cursor.CROSSHAIR_CURSOR));
        } else {
            theCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        }
       */

        flagpanel.setControlFlagText(ebtpanel.getEditFlagModes(j));
        setMode(i);
        theCanvas.getCanvasGraph().setSelectedObject(null);

        if (getMode() == UNGROUP) {
            theCanvas.drawWithHandles(false);
        } else {
            theCanvas.drawWithHandles(true);
        }

        if (getMode() == ZOOM) {
            updateZoom();
        }

        theCanvas.drawVisualAid(false);
        theCanvas.repaint();
    }

    /** Called when a file item has been chosen from the menu , the tool bar or
     * via key shortcuts. Calls the corresponding methods in the JaxoFileMenu.
     * @param i Integer specifying the file event.
     */
    public final void fileEvent(int i) {
        //resetButtons();
        switch (i) {
            case NEWG:
                filemenu.aNewG();
                break;
            case NEWT:
                filemenu.aNewT();
                break;
            case OPEN:
                filemenu.open();
                break;
            case OPENDATA:
                filemenu.opendata();
                break;
            case IMPORT:
                filemenu.importLatex();
                break;
            case CLOSE:
                filemenu.close();
                break;
            case SAVE:
                filemenu.save();
                break;
            case SAVE_AS:
                filemenu.saveAs();
                break;
            case EXPORT:
                filemenu.export();
                break;
            case PRINT:
                filemenu.print();
                break;
            case QUIT:
                filemenu.quit();
                break;
            case PASTE:
                actionEvent(PASTE);
                break;
            case PREVIEW:
                JaxoCanvas theCanvas = getCanvas();
                Dimension d =
                    new Dimension(theCanvas.getWidth(), theCanvas.getHeight());

                JaxoPreview preLatex = new JaxoPreview();
                preLatex.previewLatexPS(theCanvas.getCanvasGraph(), d,
                    isWatchMode());
                actionEvent(REFRESH);

                break;
            default:
                break;
        }
    }

    public void helpEvent() {
    	
    	new HelpDialog(this, help_file+".html");
    }

    /** Called when an action item has been chosen from the menu bar, the button panel or
     * via key shortcuts. An action item calls for immediate action, without
     * further input, currently there is Undo, Clear and Quit.
     * @param i Integer specifying the action mode. Currently one of
     * JaxoMainPanel.UNDO, JaxoMainPanel.CLEAR or JaxoMainPanel.QUIT.
     */
    public final void actionEvent(int i) {
        JaxoCanvas theCanvas = getCanvas();
        JaxoGraph theGraph = theCanvas.getCanvasGraph();
        resetButtons();

        switch (i) {
            case UNDO:
                theGraph.undo();
                theCanvas.swapImages();
                updateZoom();

                if (isEditMode()) {
                    ebtpanel.pressButton(ebtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(true);
                    theCanvas.drawVisualAid(false);
                    repaint();
                } else if (isParticleMode()) {
                    pbtpanel.pressButton(pbtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(false);
                    theCanvas.drawVisualAid(false);
                    repaint();
                } else if (isMiscMode()) {
                    mbtpanel.pressButton(mbtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(false);
                    theCanvas.drawVisualAid(false);
                    repaint();
                }

                for (int j = 0; j < theGraph.listSize(); j++) {
                    JaObject jaxoOb = (JaObject) theGraph.listElementAt(j);

                    if (jaxoOb instanceof JaLatexText) {
                        ((JaLatexText) jaxoOb).createLatexPanel();
                        theCanvas.add(((JaLatexText) jaxoOb).getLatexPanel());
                        ((JaLatexText) jaxoOb).getLatexPanel().setVisible(false);
                    }
                }

                theGraph.setSelectedObject(null);

                break;
            case CLEAR:
                theCanvas.saveBackupImage();
                theGraph.backup();
                theGraph.clear();

                if (isEditMode()) {
                    ebtpanel.pressButton(ebtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(true);
                    theCanvas.drawVisualAid(false);
                } else if (isParticleMode()) {
                    pbtpanel.pressButton(pbtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(false);
                    theCanvas.drawVisualAid(false);
                    repaint();
                } else if (isMiscMode()) {
                    mbtpanel.pressButton(mbtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(false);
                    theCanvas.drawVisualAid(false);
                    repaint();
                }

                theGraph.setSelectedObject(null);
                theCanvas.clearOffScreenImage();
                theCanvas.repaint();

                break;
            case PASTE:
                theCanvas.saveBackupImage();
                theGraph.backup();

                for (int k = 0; k < clipboard.listSize(); k++) {
                    theGraph.addObject(clipboard.listElementAt(k).copy());
                }

                for (int j = 0; j < theGraph.listSize(); j++) {
                    JaObject jaxoOb = (JaObject) theGraph.listElementAt(j);

                    if (jaxoOb instanceof JaLatexText) {
                        ((JaLatexText) jaxoOb).createLatexPanel();
                        theCanvas.add(((JaLatexText) jaxoOb).getLatexPanel());
                        ((JaLatexText) jaxoOb).getLatexPanel().setVisible(false);
                    }
                }

                theCanvas.setOldbb(clipboard.getBoundingBox());
                theCanvas.updateOffScreenImage();
                editEvent(MOVE);
                theCanvas.unsavedCanvas();
                actionEvent(REFRESH);

                break;
            case REFRESH:
                theCanvas.setOldbb(theGraph.getBoundingBox());
                theCanvas.updateOffScreenImage();

                if (isEditMode()) {
                    ebtpanel.pressButton(ebtpanel.getIndex(currentMode));

                    if (ebtpanel.getIndex(currentMode) == 9) {
                        theCanvas.drawWithHandles(false);
                    } else {
                        theCanvas.drawWithHandles(true);
                    }

                    theCanvas.drawVisualAid(false);
                    repaint();
                } else if (isParticleMode()) {
                    pbtpanel.pressButton(pbtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(false);
                    theCanvas.drawVisualAid(false);
                    repaint();
                } else if (isMiscMode()) {
                    mbtpanel.pressButton(mbtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(false);
                    theCanvas.drawVisualAid(false);
                    repaint();
                }

                theGraph.setSelectedObject(null);

                break;
            default:
                break;
        }
    }

    
    
    /**
     * Refresh
     */
    

     /**
     * Clear the data  
     */
      public void clearData(int padX, int padY ) {
        japlot.clearData(padX,padY);
      } 


    
/**
 * Update
 */
     public void update() {   
 
        JaxoCanvas theCanvas = getCanvas();
        if (theCanvas == null) return;
        
        JaxoGraph theGraph = theCanvas.getCanvasGraph();
        if (theGraph == null) return;
        
        resetButtons();
      //   repaintCanvas();
        getCanvas().update();
     //   updateUI();
        
        
        
                theCanvas.setOldbb(theGraph.getBoundingBox());
                theCanvas.updateOffScreenImage();

                if (isEditMode()) {
                    ebtpanel.pressButton(ebtpanel.getIndex(currentMode));

                    if (ebtpanel.getIndex(currentMode) == 9) {
                        theCanvas.drawWithHandles(false);
                    } else {
                        theCanvas.drawWithHandles(true);
                    }

                    theCanvas.drawVisualAid(false);
                    repaint();
                } else if (isParticleMode()) {
                    pbtpanel.pressButton(pbtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(false);
                    theCanvas.drawVisualAid(false);
                    repaint();
                } else if (isMiscMode()) {
                    mbtpanel.pressButton(mbtpanel.getIndex(currentMode));
                    theCanvas.drawWithHandles(false);
                    theCanvas.drawVisualAid(false);
                    repaint();
                }

      
                theGraph.setSelectedObject(null);

      };
 
    
    
    /** Sets all the buttons as not pressed and hides the handles. */
    public final void resetButtons() {
        mbtpanel.reset();
        pbtpanel.reset();
        ebtpanel.reset();
        // gbtpanel.reset();
    }

    /** Repaints the canvas. */
    public final void repaintCanvas() {
        getCanvas().repaint();
    }

    /** Repaints the canvas. */
    public int getSizeX() {
        Dimension d= getCanvas().getSize();
        return (int)d.getWidth();
    }

    /** Repaints the canvas. */
    public int getSizeY() {
        Dimension d= getCanvas().getSize();
        return (int)d.getHeight();
    }


    /**  Get graph of this canvas */
    public JaxoGraph getGraph() {
        return getCanvas().getCanvasGraph();
    }



  /**
         *  Clear from all objects and dispose the frame. 
         *
         */
        public void shutdown() {


                // System.out.println("Debug: Exit the application");
//              System.exit(status);
                getCanvas().dispose(); 
                japlot.clearAllData();
                japlot.clearAll();
                setVisible(false);
                clipboard=null;
                mbtpanel=null;
                abtpanel=null;
                // gbtpanel=null;
                editmenu=null;
                helpmenu=null;
                optionsmenu=null;
                flagpanel=null;
                System.gc();
                this.dispose();
        }


     /**  set size */
    public void setSizeCanvas(int xsize, int ysize) {
        Dimension d = new Dimension(xsize, ysize); 
        // canvasPanel.setSize(d); 
        JaxoCanvas theCanvas = getCanvas();
        theCanvas.setSize(d);
        SwingUtilities.updateComponentTreeUI(this);
        theCanvas.repaint();
 
    }



    /** Applies the preferences. */
    public final void applyPrefs() {
        JaxoCanvas theCanvas = getCanvas();
        optionsmenu.showStatusbar(JaxoPrefs.getBooleanPref(
                JaxoPrefs.PREF_SHOWSTATUS));
        optionsmenu.showToolbar(JaxoPrefs.getBooleanPref(
                JaxoPrefs.PREF_SHOWTOOL));
        optionsmenu.showEditorbar(JaxoPrefs.getBooleanPref(
                JaxoPrefs.PREF_SHOWEDITOR));
        optionsmenu.antialiasOn(JaxoPrefs.getBooleanPref(
                JaxoPrefs.PREF_ANTIALIAS));
        optionsmenu.arrow(JaxoPrefs.getBooleanPref(JaxoPrefs.PREF_ARROW));
        optionsmenu.setDefault(JaxoPrefs.getIntPref(
                JaxoPrefs.PREF_DEFAULTACTION));
       theCanvas.setSize(JaxoPrefs.getIntPref(JaxoPrefs.PREF_SCREENSIZEX),
            JaxoPrefs.getIntPref(JaxoPrefs.PREF_SCREENSIZEY));

    //    theCanvas.setSize(JaxoPrefs.getIntPref(700),
    //        JaxoPrefs.getIntPref(200));

        zoom.setZoomFactor(JaxoPrefs.getIntPref(JaxoPrefs.PREF_ZOOMFACTOR));
        zoom.setZoomWindowWidth(JaxoPrefs.getIntPref(JaxoPrefs.PREF_ZOOMSIZEX));
        zoom.setZoomWindowHeight(JaxoPrefs.getIntPref(JaxoPrefs.PREF_ZOOMSIZEY));

        // the Look n Feel
        LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
        int num = info.length;
        String[] humanReadableName = new String[num];
        String[] className = new String[num];
        String newLAF = info[0].getClassName();
        String newLAFname = info[0].getName();

        for (int i = 0; i < num; i++) {
            humanReadableName[i] = info[i].getName();
            className[i] = info[i].getClassName();

            String prefLOOKNFEEL =
                JaxoPrefs.getStringPref(JaxoPrefs.PREF_LOOKNFEEL);

            if (prefLOOKNFEEL.equals(humanReadableName[i])) {
                newLAF = className[i];
                newLAFname = humanReadableName[i];
            }
        }

        try {
            UIManager.setLookAndFeel(newLAF);
        } catch (Exception exc) {
            if (JaxoPrefs.verbose()) {
                System.err.println(exc);
            }

            JOptionPane.showMessageDialog(null,
                newLAFname
                + language.getString(
                    "_Look_and_Feel_is_not_supported_on_this_platform!"));
        }

        SwingUtilities.updateComponentTreeUI(this);

        setLanguage(JaxoPrefs.getPref(JaxoPrefs.PREF_LANGUAGE));

        theCanvas.repaint();
    }

    /** Switches the toolbar on or off.
     * @param show A boolean variable that indicates whether the toolbar is visible or not.
     */
    public final void showToolbar(boolean show) {
        toolbar.setVisible(show);
        JaxoPrefs.setBooleanPref(JaxoPrefs.PREF_SHOWTOOL, show);
    }

   /** Switches the editor on or off.
     * @param show A boolean variable that indicates whether the editor is visible or not.
     */
    public final void showEditorbar(boolean show) {
        jToolBar.setVisible(show);
        JaxoPrefs.setBooleanPref(JaxoPrefs.PREF_SHOWEDITOR, show);
    }

    /** Switches the browser  on or off.
     * @param show A boolean variable that indicates whether the browser visible or not.
     */
    public final void showBrowserbar(boolean show) {
      // obrowser.showIt(show);
       JaxoPrefs.setBooleanPref(JaxoPrefs.PREF_SHOWBROWSER, show);
   }



    /** Switches the status bar on or off.
     * @param show A boolean variable that indicates whether the status bar is visible or not.
     */
    public final void showStatusbar(boolean show) {
        flagpanel.setVisible(show);
        JaxoPrefs.setBooleanPref(JaxoPrefs.PREF_SHOWSTATUS, show);
    }

    /** Switches antialiasing on or off.
     * @param on A boolean variable that indicates whether antialising is on or not.
     */
    public final void antialiasOn(boolean on) {
        JaxoCanvas theCanvas = getCanvas();
        JaxoPrefs.setBooleanPref(JaxoPrefs.PREF_ANTIALIAS, on);

        if (theCanvas.getOffScreenImage() != null) {
            theCanvas.setOldbb(theCanvas.getCanvasGraph().getBoundingBox());
            theCanvas.updateOffScreenImage();
        }
    }

    /** Switches the grid on or off.
     * @param on A boolean variable that indicates whether the grid is on or not.
     */
    public final void gridOn(boolean on) {
/*
        JaxoCanvas theCanvas = getCanvas();
        JaxoPrefs.setBooleanPref(JaxoPrefs.PREF_GRIDONOFF, on);
        if (!on && snap) {
            gbtpanel.disableSnap();
        }
        gbtpanel.enableGridBt(on);
        if (theCanvas.getOffScreenImage() != null) {
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            double[] bbox =
            {5.d, 5.d, (double) d.width - 5.d, (double) d.height - 5.d};
            theCanvas.setOldbb(bbox);
            theCanvas.updateOffScreenImage();
        }
*/
    }

    /** Determines whether to draw arrows on lines, arcs and loops.
     * @param on A boolean variable that indicates whether to draw arrows on
     * lines, arcs and loops.
     */
    public final void arrow(boolean on) {
        JaxoCanvas theCanvas = getCanvas();
        JaxoPrefs.setBooleanPref(JaxoPrefs.PREF_ARROW, on);

        if (theCanvas.getOffScreenImage() != null) {
            theCanvas.setOldbb(theCanvas.getCanvasGraph().getBoundingBox());
            theCanvas.updateOffScreenImage();
        }
    }

    /** Sets the current type of vertex.
     * @param type An integer specifying the vertex type.
     */
    public final void setVertexType(int type) {
        currentVertex = type;
    }

    /** Returns the current vertex type.
     * @return The current vertex type.
     */
    public final int getVertexType() {
        return currentVertex;
    }

    /** Sets the clipboard.
     * @param newClipboard A JaxoGraph containing the new clipboard.
     */
    public final void setClipboard(JaxoGraph newClipboard) {
        this.clipboard = newClipboard;
    }

    /** Returns the current clipboard.
     * @return The current clipboard.
     */
    public final JaxoGraph getClipboard() {
        return clipboard;
    }

    /** Sets the snap mode.
     * @param newSnap The new snap mode.
     */
    public final void setSnap(boolean newSnap) {
        this.snap = newSnap;
    }

    /** Returns the current snap mode.
     * @return The current snap mode.
     */
    public final boolean getSnap() {
        return snap;
    }

    /**
     * Indicates whether watch mode is active or not.
     * @return True when watch mode is active, false otherwise.
     */
    public final boolean isWatchMode() {
        return watchMode;
    }

    /**
     * Sets the current watch mode.
     * @param choice True, if watch mode is to be switched on, false
     * otherwise.
     */
    public final void setWatchMode(boolean choice) {
        this.watchMode = choice;
    }

    /** Returns the particle button panel.
     * @return The current particle button panel.
     */
    public final JaxoParticleButtons getPbtPanel() {
        return pbtpanel;
    }

    /** Returns the edit button panel.
     * @return The current edit button panel.
     */
    public final JaxoEditButtons getEbtPanel() {
        return ebtpanel;
    }

    /** Returns the miscellaneous button panel.
     * @return The current  miscalleneous button panel.
     */
    public final JaxoMiscButtons getMbtPanel() {
        return mbtpanel;
    }

    /** Returns the grid button panel.
     * @return The current grid button panel.
     */
    public final JaxoGridButtons getGbtPanel() {
        return gbtpanel;
    }

    /** Returns the particle button panel.
     * @return The current particle button panel.
     */
    public final JaxoTabbedCanvasPanel getCanvasPanel() {
        return canvasPanel;
    }

    /** Returns the options menu.
     * @return The current options menu.
     */
    public final JaxoOptionsMenu getOptMenu() {
        return optionsmenu;
    }

    /** Sets the zoom.
     * @param z The zoom.
     */
    public final void setZoom(JaxoZoom z) {
        this.zoom = z;
    }

    /** Returns the zoom.
     * @return The zoom.
     */
    public final JaxoZoom getZoom() {
        return this.zoom;
    }

    /** Initializes the zoom: sets the background image, graphics context,
     * image dimensions and canvas dimensions.
     */
    public final void updateZoom() {
        JaxoCanvas theCanvas = getCanvas();

        zoom.setBackground(theCanvas.getOffScreenImage());
        zoom.setGraphics(theCanvas.getGraphics());
        zoom.setImageWidth(theCanvas.getOffScreenImage().getWidth(null));
        zoom.setImageHeight(theCanvas.getOffScreenImage().getHeight(null));
        zoom.setCanvasWidth(theCanvas.getWidth());
        zoom.setCanvasHeight(theCanvas.getHeight());
        zoom.setTmpImage();
    }

 

    
    /**
     * Fill browser.
     * @param map
     */
    public final void fillBrowser(final Map map) {

     


           int N1 = getJaPlot().getNtotX();
            int N2 = getJaPlot().getNtotY();
           if (N1 ==0 || N2 == 0) {
                          JOptionPane.showMessageDialog(this, "Warning!  You cannot plot objects using the mouse before creating drawing pad. \n Press exit \"ObjectBrowser\" and create pads using the menu \"Option - Add Pads\"\n",
                                        "JaBrowser warning",
                                        JOptionPane.WARNING_MESSAGE);

         }

           jhplot.io.BrowserDataGeneric jabrowser = new jhplot.io.BrowserDataGeneric();
           jabrowser.setDataFileBrowser(this,map,true);
           //JaBrowser jabrowser = new JaBrowser(this);
           //JPanel jpan = jabrowser.buildTree(map);
           //jabrowser.rebuildPopup(); // rebuild pop up if frames changed
           //ObjectBrowser browser= new ObjectBrowser(this,jpan);
           //browser.showIt(true);
       
           /*
           Thread t = new Thread("Browser file") {
               public void run() {
                   JPanel jpan = jabrowser.buildTree(map);
                   ObjectBrowser browser= new ObjectBrowser(this,jpan);
                   obrowser.showIt(true);
               };
       };
                 t.start();
*/
    }

 


    /** Returns the zoom.
     * @return The zoom.
     */
  
    /*
    public final void fillBrowser(final File f) {
   
        jabrowser.rebuildPopup(); // rebuild pop up if frames changed
 
    	Thread t = new Thread("Browser file") {
            public void run() {
         	jabrowser.load(f);
            	showBrowserbar(true);   
            };
    };
    t.start();

            int N1 = getJaPlot().getNtotX();
            int N2 = getJaPlot().getNtotY();
           if (N1 ==0 || N2 == 0) {
                          JOptionPane.showMessageDialog(this, "Warning!  You cannot plot objects using the mouse before creating drawing pad. \n Press exit \"ObjectBrowser\" and create pads using the menu \"Option - Add Pads\"\n",
                                        "JaBrowser warning",
                                        JOptionPane.WARNING_MESSAGE);

         }
 
  
    
    }
*/

    
    
    /**
	 * Exports the image to some graphic format using a dialog
	 */
	public void exportImage() {

/*
		 Dimension d =
	            new Dimension(getCanvas().getWidth(),
	                getCanvas().getHeight());
	        String tab =
	            getCanvasPanel().getSelectedComponent().getName();
	        JaxoExport.ExportFile = null;
	        JaxoExportPanel e = new JaxoExportPanel();
	        e.setCurrentTab(tab);
	        e.export(getCanvas().getCanvasGraph(), d);
*/

                 String tab =
                    getCanvasPanel().getSelectedComponent().getName();

                JaxoExportPanel e = new JaxoExportPanel();
                e.setCurrentTab(tab);

               jhplot.io.images.ExportVGraphics.exportDialog(getCanvas(),JaxoMainPanel.class.getName(),this);

                



	}

    
    
    

	/**
	 * Fast export of the canvas to an image file (depends on the extension,
	 * i.e. PNG, JPG,  EPS, PS). No questions will be asked, an existing file
	 * will be rewritten
	 * 
	 * @param file
	 *            Output file with the proper extension. If no extension, PNG
	 *            file is assumed.
     *	
	 */


/*
	public  void export(String f) {

		int ff = JaxoExportPanel.PNG;
		String sf = f.toLowerCase();
		if (sf.endsWith(".eps"))
			ff = JaxoExportPanel.PS_EPS;
		if (sf.endsWith(".ps"))
			ff = JaxoExportPanel.PS_PORTRAIT;
		if (sf.endsWith(".png"))
			ff = JaxoExportPanel.PNG;
		if (sf.endsWith(".jpg") || sf.endsWith(".jpeg"))
			ff = JaxoExportPanel.JPG;

		Dimension canvasD = new Dimension(getCanvas().getWidth(),
				getCanvas().getHeight());
		String currentTab = getCanvasPanel().getSelectedComponent()
				.getName();

		JaxoGraph graph = getCanvas().getCanvasGraph();
		
		// set export file 
		JaxoExport.ExportFile = f;

		switch (ff) {

		case JaxoExportPanel.PS_PORTRAIT:
			JaxoExportPS psPortrait = new JaxoExportPS();
			psPortrait.setCurrentTab(currentTab);
			psPortrait.setMode(JaxoExportPanel.PS_PORTRAIT);
			psPortrait.setCanvasD(canvasD);
			psPortrait.export(graph);

			break;
		case JaxoExportPanel.PS_LANDSCAPE:
			JaxoExportPS psLandscape = new JaxoExportPS();
			psLandscape.setCurrentTab(currentTab);
			psLandscape.setMode(JaxoExportPanel.PS_LANDSCAPE);
			psLandscape.setCanvasD(canvasD);
			psLandscape.export(graph);

			break;
		case JaxoExportPanel.PS_EPS:
			JaxoExportPS eps = new JaxoExportPS();
			eps.setCurrentTab(currentTab);
			eps.setMode(JaxoExportPanel.PS_EPS);
			eps.setCanvasD(canvasD);
			eps.export(graph);

			break;
		case JaxoExportPanel.JPG:
			JaxoExportImg imgJPG = new JaxoExportImg();
			imgJPG.setCurrentTab(currentTab);
			imgJPG.setMode(JaxoExportPanel.JPG);
			imgJPG.setCanvasD(canvasD);
			imgJPG.export(graph);

			break;
		case JaxoExportPanel.PNG:
			JaxoExportImg imgPNG = new JaxoExportImg();
			imgPNG.setCurrentTab(currentTab);
			imgPNG.setMode(JaxoExportPanel.PNG);
			imgPNG.setCanvasD(canvasD);
			imgPNG.export(graph);

			break;
		default:
			break;

		}

	
	}

   
   */

   
 /**
         * Fast export of the canvas to an image file (depends on the extension,
         * i.e. PNG, PDF, EPS, PS). No questions will be asked, an existing file
         * will be rewritten
         * 
         * @param file
         *            Output file with the proper extension. If no extension, PNG
         *            file is assumed.
         */

        public void export(String file) {
        	
        	
        	 String currentTab = getCanvasPanel().getSelectedComponent()
                     .getName();
       JaxoGraph graph = getCanvas().getCanvasGraph();

      Component cc= (Component)getCanvasPanel().getSelectedComponent();
      cc.validate();
      
      jhplot.io.images.ExportVGraphics.export(cc,rootKey,file);
      
     
        }
 
    
    
    

}

 

Ads help maintain this website.