/*

 * 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 java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;

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

import java.util.ResourceBundle;

import org.freehep.graphics2d.VectorGraphics;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

import jhplot.jadraw.JaObject;

import japlot.Plot;


/** Responsible for previewing the results of an export. In general, creates
 * temporary files that are opened with a default application and deleted
 * after the program terminates. For postscript preview, it is mandatory to
 * specify a default application in the preferences, the LaTex preview may be
 * done with Java's internal JEditorPane.
 */
public class JaxoPreview {
    private ResourceBundle language =
        ResourceBundle.getBundle(JaxoPrefs.getPref(JaxoPrefs.PREF_LANGUAGE));
    private JaxoGraph graph;
    private JFrame frame;
    private String userDIR = System.getProperty("user.dir");

    /** Previews the current JaxoGraph in postscript mode
     * (portrait or landscape).
     * @param newGraph The JaxoGraph to be previewed.
     * @param d The current dimension of the canvas.
     * @param mode The preview mode: JaxoExport.PS_PORTRAIT or
     *  JaxoExport.PS_LANDSCAPE.
     */
    public final void previewPS(JaxoGraph newGraph, Dimension d, int mode) {
        this.graph = newGraph;

        checkforLatexText();

        String previewFileName = "Jaxo_tmp.ps";
        String prefPSVIEWER = JaxoPrefs.getStringPref(JaxoPrefs.PREF_PSVIEWER);

        if (prefPSVIEWER.length() == 0) {
            JOptionPane.showMessageDialog(null,
                language.getString("Please_choose_a_Postscript_viewer_\n")
                + language.getString("from_the_Preferences_dialog!"));
        } else {
            String command =
                prefPSVIEWER + " " + userDIR + File.separator
                + previewFileName;
            File previewFile = new File(previewFileName);
            new FilePermission(previewFileName, "read, write, delete");
            previewFile.deleteOnExit();

            JaxoExportPS p = new JaxoExportPS();
            p.exportPS(graph, d, previewFileName, mode);

            try {
                //Process pr = Runtime.getRuntime().exec(command);
                Runtime.getRuntime().exec(command);
            } catch (IOException anIOException) {
                JOptionPane.showMessageDialog(null,
                    language.getString("IOException:_Cannot_find_ps_viewer!"));

                if (JaxoPrefs.verbose()) {
                    System.err.println(anIOException);
                }
            } catch (SecurityException aSecurityException) {
                JOptionPane.showMessageDialog(null,
                    language.getString(
                        "SecurityException:_Cannot_run_external_command!"));

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

    /** Previews the current JaxoGraph in EPS mode.
     * @param newGraph The JaxoGraph to be previewed.
     * @param d The current dimension of the canvas.
     */
    public final void previewEPS(JaxoGraph newGraph, Dimension d) {
        this.graph = newGraph;

        checkforLatexText();

        String previewFileName = "Jaxo_tmp.eps";
        String prefPSVIEWER = JaxoPrefs.getStringPref(JaxoPrefs.PREF_PSVIEWER);

        if (prefPSVIEWER.length() == 0) {
            JOptionPane.showMessageDialog(null,
                language.getString("Please_choose_a_Postscript_viewer_\n")
                + language.getString("from_the_Preferences_dialog!"));
        } else {
            String command =
                prefPSVIEWER + " " + userDIR + File.separator
                + previewFileName;

            File previewFile = new File(previewFileName);
            new FilePermission(previewFileName, "read, write, delete");
            previewFile.deleteOnExit();

            JaxoExportPS eps = new JaxoExportPS();
            eps.setCanvasD(d);
            eps.exportEPS(graph, previewFileName);

            try {
                //Process pr = Runtime.getRuntime().exec(command);
                Runtime.getRuntime().exec(command);
            } catch (IOException anIOException) {
                JOptionPane.showMessageDialog(null,
                    language.getString("IOException:_Cannot_find_ps_viewer!"));

                if (JaxoPrefs.verbose()) {
                    System.err.println(anIOException);
                }
            } catch (SecurityException aSecurityException) {
                JOptionPane.showMessageDialog(null,
                    language.getString(
                        "SecurityException:_Cannot_run_external_command!"));

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

    /** Previews the current JaxoGraph in LaTex mode.
     * @param newGraph The current graph to be previewed.
     */
    public final void previewLatex(JaxoGraph newGraph) {
        this.graph = newGraph;

        checkforPSText();

        String fs = File.separator;

        String previewFileName = "Jaxo_tmp.tex";
        File previewFile = new File(previewFileName);
        new FilePermission(previewFileName, "read, write, delete");
        previewFile.deleteOnExit();

        JaxoExportLatex lat = new JaxoExportLatex();
        lat.exportLatex(graph, previewFileName);

        String prefEDITOR = JaxoPrefs.getStringPref(JaxoPrefs.PREF_EDITOR);

        if (prefEDITOR.length() == 0) {
            JOptionPane.showMessageDialog(null,
                language.getString("You_may_choose_a_custom_text_editor_\n")
                + language.getString("from_the_Preferences_dialog!"));

            String url = "file:" + userDIR + fs + previewFileName;

            JEditorPane editorPane = new JEditorPane();
            editorPane.setEditable(false);
            editorPane.setContentType("text/plain");

            try {
                editorPane.setPage(url);
            } catch (Exception e) {
                if (JaxoPrefs.verbose()) {
                    System.err.println(e);
                }

                JOptionPane.showMessageDialog(null,
                    language.getString("Could_not_open:_") + url + "!");
            }

            JScrollPane scroller = new JScrollPane(editorPane);
            scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            scroller.setPreferredSize(new Dimension(250, 145));
            scroller.setMinimumSize(new Dimension(10, 10));
            scroller.setBorder(BorderFactory.createEtchedBorder());
            scroller.setVisible(true);

            JButton closeButton = new JButton(language.getString("Close"));
            closeButton.setBorder(BorderFactory.createRaisedBevelBorder());

            //closeButton.setToolTipText();
            closeButton.addMouseListener(new JaxoCloseMouseAdapter());

            JPanel buttonPanel = new JPanel();
            buttonPanel.add(closeButton, BorderLayout.CENTER);

            frame = new JFrame();
            frame.getContentPane().add(scroller, BorderLayout.CENTER);
            frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.setSize(700, 600);
            frame.setTitle(language.getString("Latex_Preview"));
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        } else {
            String command =
                prefEDITOR + " " + userDIR + File.separator + previewFileName;

            try {
                //Process pr = Runtime.getRuntime().exec(command);
                Runtime.getRuntime().exec(command);
            } catch (IOException anIOException) {
                JOptionPane.showMessageDialog(null,
                    language.getString("IOException:_Cannot_find_text_editor!"));

                if (JaxoPrefs.verbose()) {
                    System.err.println(anIOException);
                }
            } catch (SecurityException aSecurityException) {
                JOptionPane.showMessageDialog(null,
                    language.getString(
                        "SecurityException:_Cannot_run_external_command!"));

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

    /**
     * If a postscript viewer has been specified in the Preferencies,
     * runs external comands to produce a postscript file via LaTeX and
     * opens a window to view it. All temporary files created during the
     * process are deleted when the application is closed.
     * @param wMode A boolean variable that indicates whether the
     * Preview is done in watch mode.
     * @param newGraph The current JaxoGraph to be previewed.
     * @param d The current canvas dimension.
     */
    public final void previewLatexPS(JaxoGraph newGraph, Dimension d, boolean wMode) {
        this.graph = newGraph;

        checkforPSText();

        String previewFileName = "Jaxo_tmp.eps";
        String prefPSVIEWER = JaxoPrefs.getStringPref(JaxoPrefs.PREF_PSVIEWER);

        if (prefPSVIEWER.length() == 0) {
            JOptionPane.showMessageDialog(null,
                language.getString("Please_choose_a_Postscript_viewer_\n")
                + language.getString("from_the_Preferences_dialog!"));
        } else {
            previewLatexPS(prefPSVIEWER, previewFileName, wMode);
        }
    }

    private void previewLatexPS(String prefPSVIEWER, String previewFileName,
        boolean wMode) {
        String command =
            prefPSVIEWER + " " + userDIR + File.separator + previewFileName;
        File previewFile = new File(previewFileName);
        boolean previewFileExists = previewFile.exists();
        new FilePermission(previewFileName, "read, write, delete");
        previewFile.deleteOnExit();

        JaxoExportLatexPS eps = new JaxoExportLatexPS();
        int status = eps.exportLatexPS(graph, previewFileName);

        boolean newWindow = (!wMode || (wMode && !previewFileExists));

        if ((status == 0) && newWindow) {
            try {
                Runtime.getRuntime().exec(command);
            } catch (IOException anIOException) {
                JOptionPane.showMessageDialog(null,
                    language.getString("IOException:_Cannot_find_ps_viewer!"));

                if (JaxoPrefs.verbose()) {
                    System.err.println(anIOException);
                }
            } catch (SecurityException aSecurityException) {
                JOptionPane.showMessageDialog(null,
                    language.getString(
                        "SecurityException:_Cannot_run_external_command!"));
                if (JaxoPrefs.verbose()) {
                    System.err.println(aSecurityException);
                }
            }
        }
    }

    /** Previews the current JaxoGraph in JPG/PNG mode.
     * @param previewGraph The current graph to be previewed.
     * @param d The dimension of the canvas.
     */
    public final void previewIMG(JaxoGraph previewGraph, Dimension d) {
        this.graph = previewGraph;
        checkforLatexText();

        Image image = (Image) createImage(d);
        frame = new JFrame();

        JLabel label = new JLabel(new ImageIcon(image));
        frame.getContentPane().add(label, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.setTitle(language.getString("Image_Preview"));
        frame.setLocationRelativeTo(null);
        frame.addKeyListener(new JaxoCloseKeyAdapter());
        frame.pack();
        frame.setVisible(true);
    }

    private RenderedImage createImage(Dimension d) {
        int width = d.width;
        int height = d.height;

        BufferedImage bufferedImage =
            new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        VectorGraphics g2d = (VectorGraphics)bufferedImage.createGraphics();
        g2d.setColor(JaxoCanvas.BCKG_COLOR);
        g2d.fillRect(0, 0, width, height);

        int length = graph.listSize();

       
            // this is first
            for (int i = 0; i < length; i++) {
                JaObject ob = (JaObject) graph.listElementAt(i);
                if (Plot.drawFirst(ob)) ob.jaxoDraw(g2d, false);
            }

            // this is second
            for (int i = 0; i < length; i++) {
                JaObject ob = (JaObject) graph.listElementAt(i);
                Plot.drawRest(ob,g2d,false);
            }


        g2d.dispose();

        double[] bb = graph.getBoundingBox();
        int x = (int) Math.round(bb[JaObject.BB_MIN_X]);
        int y = (int) Math.round(bb[JaObject.BB_MIN_Y]);
        int w = (int) Math.round(bb[JaObject.BB_MAX_X]
            - bb[JaObject.BB_MIN_X]) + 1;
        int h = (int) Math.round(bb[JaObject.BB_MAX_Y]
            - bb[JaObject.BB_MIN_Y]) + 1;

        return bufferedImage.getSubimage(x, y, w, h);
    }

    private void checkforLatexText() {
        if (graph.containsLatexText()) {
            Object[] message =
            {
                language.getString(
                    "There_are_LaTeX_text_objects_in_this_graph."),
                language.getString("They_will_not_be_exported_to_this_format!")
            };

            JOptionPane.showMessageDialog(null, message,
                language.getString("Warning"), JOptionPane.WARNING_MESSAGE);
        }
    }

    private void checkforPSText() {
        if (graph.containsPSText()) {
            Object[] message =
            {
                language.getString(
                    "There_are_Postscript_text_objects_in_this_graph."),
                language.getString("They_will_not_be_exported_to_LaTeX!")
            };

            JOptionPane.showMessageDialog(null, message,
                language.getString("Warning"), JOptionPane.WARNING_MESSAGE);
        }
    }

    class JaxoCloseKeyAdapter extends KeyAdapter {
        public final void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                frame.dispose();
            }
        }
    }

    class JaxoCloseMouseAdapter extends MouseAdapter {
        public final void mouseClicked(MouseEvent evt) {
            frame.dispose();
        }
    }
}

 

Ads help maintain this website.