Package jsynoptic.ui

Source Code of jsynoptic.ui.JSynopticBatch

/* ========================
* JSynoptic : a free Synoptic editor
* ========================
*
* Project Info:  http://jsynoptic.sourceforge.net/index.html
*
* This program is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*
* (C) Copyright 2001-2003, by :
*     Corporate:
*         Astrium SAS
*         EADS CRC
*     Individual:
*         Nicolas Brodu
*
* $Id: JSynopticBatch.java,v 1.17 2008/11/27 11:16:21 ogor Exp $
*
* Changes
* -------
* 25-Sep-2003 : Initial public release (NB);
*
*/
package jsynoptic.ui;

import java.awt.print.PageFormat;
import java.awt.print.Pageable;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.print.PrintService;
import javax.print.StreamPrintService;
import javax.print.StreamPrintServiceFactory;
import javax.swing.filechooser.FileFilter;

import jsynoptic.base.Plugin;
import jsynoptic.base.PrintFormat;
import jsynoptic.builtin.Builtin;
import simtools.data.DataSourceCollection;
import simtools.data.DataSourcePool;
import simtools.diagram.DiagramComponent;
import simtools.ui.BasicMessageWriter;
import simtools.ui.MenuResourceBundle;
import simtools.ui.ResourceFinder;
import simtools.util.CurrentPathProvider;
import simtools.util.FileSerializer;

/**
* Process commands in batch mode
*
* @author Nicolas Brodu
*
* @version 1.0 2001
*/
public class JSynopticBatch extends PrintFormat implements Pageable {
    /** Reuse the same resources as JSynoptic */
    public static MenuResourceBundle resources = ResourceFinder.getMenu(JSynoptic.class);

    public static BasicMessageWriter messageWriter = ResourceFinder.getMessages(JSynoptic.class);

    public static JSynopticBatch batch = null;

    protected Vector containers;

    protected Vector files;

    protected Vector plugins;

    /**
     * Plugin used to save synoptics
     */
    public static Builtin builtInPlugin = null;

    public JSynopticBatch(Vector plugins, Vector commands) {
        if (commands == null) {
            return;
        }
        // Get builtin plugin
        if ((builtInPlugin == null) && (Run.plugins != null)) {
            for (int i = 0; i < Run.plugins.size(); ++i) {
                Plugin p = (Plugin) Run.plugins.get(i);
                if (p instanceof Builtin) {
                    builtInPlugin = (Builtin) p;
                }
            }
        }
        batch = this;
        this.plugins = (plugins == null) ? new Vector() : plugins;
        Vector sortedCommands = new Vector();
        for (Iterator it = commands.iterator(); it.hasNext();) {
            String cmd = (String) it.next();
            if (cmd.startsWith("load ")) {
                sortedCommands.add(cmd);
            }
        }
        for (Iterator it = commands.iterator(); it.hasNext();) {
            String cmd = (String) it.next();
            if (!cmd.startsWith("load ")) {
                sortedCommands.add(cmd);
            }
        }
        containers = new Vector();
        files = new Vector();
        for (Iterator it = sortedCommands.iterator(); it.hasNext();) {
            processCommand((String) it.next());
        }
        System.exit(-1);
    }

    public boolean addContainer(ShapesContainer sc, File f) {
        files.add(f);
        return containers.add(sc);
    }

    public void processCommand(String command) {
        if (command.startsWith("load ")) {
            File f = FileSerializer.readFromString(command.substring(5), CurrentPathProvider.currentPathProvider
                    .getCurrentPath());
            if (f.exists()) {
                Plugin p = getPluginToProcessFile(f, Plugin.OPEN, null);
                if (p == null) {
                    System.err.println(messageWriter.print1args("fileLoadFailed", f.getAbsolutePath()));
                    return;
                }
                p.processFile(f, Plugin.OPEN);
            } else {
                System.err.println(messageWriter.print1args("fileLoadFailed", f.getAbsolutePath()));
            }
            return;
        }
        if (command.startsWith("paper ")) {
            String paperName = command.substring(6);
            boolean res = setPaper(paperName);
            if (res) {
                return;
            }
            System.err.println(messageWriter.print1args("unknownPaper", paperName));
            System.err.print(messageWriter.print0args("knownPapers"));
            String[] knownPapers = getKnownPapers();
            if (knownPapers != null) {
                for (int i = 0; i < knownPapers.length; ++i) {
                    System.err.print(knownPapers[i] + (i == (knownPapers.length - 1) ? "" : ", "));
                }
            }
            System.err.println();
            return;
        }
        if (command.startsWith("orientation ")) {
            String orientation = command.substring(12);
            if (!setOrientation(orientation)) {
                System.err.println(messageWriter.print1args("unknownOrientation", orientation));
                System.err.print(messageWriter.print0args("knownOrientations"));
                System.err.println("portrait landscape reverseLandscape");
                return;
            }
            return;
        }
        if (command.startsWith("transform ")) {
            String actionType = command.substring(10);
            if (!actionType.equals("")) {
               
                // synoptic transformation
                boolean canTransformSynoptics = false;
                for (int i = 0; i < getNumberOfPages(); i++) {
                    ShapesContainer sc = ((ShapesContainer) containers.get(i));
                    for (int j = 0; j < Run.plugins.size(); ++j) {
                        Plugin p = (Plugin) Run.plugins.get(j);
                        canTransformSynoptics |= p.processSynoptic(sc, actionType, false);
                    }
                }

                // data transformation
                boolean canTransformData = false;
                Set dataSourceCollections = DataSourcePool.global.dataSourceCollections();
                for(Iterator it=dataSourceCollections.iterator(); it.hasNext();){
                    DataSourceCollection dsc = (DataSourceCollection)it.next();
                    for (int j = 0; j < Run.plugins.size(); ++j) {
                        Plugin p = (Plugin) Run.plugins.get(j);
                        canTransformData |= p.processDataSourceCollection(dsc, actionType);
                    }
                }

                // Display result message

                if (!canTransformData){
                    if (getNumberOfPages()== 0) {
                        System.out.println(messageWriter.print0args("noSynopticToProcess"));

                    } else if (canTransformSynoptics) {
                        System.out.println(messageWriter.print1args("transformed", actionType));
                        saveAllSynoptics();
                    } else {
                        System.err.println(messageWriter.print1args("cannotTransform", actionType));
                    }
                }

                if (!canTransformSynoptics){
                    if (dataSourceCollections.isEmpty()) {
                        System.out.println(messageWriter.print0args("noDataToProcess"));

                    } else if (canTransformData) {
                        System.out.println(messageWriter.print1args("transformed", actionType));
                    } else {
                        System.err.println(messageWriter.print1args("cannotTransform", actionType));
                    }
                }
            }
           
           
            return;
        }
        if (command.startsWith("export ")) {
            File directory = new File(command.substring(7));
            for (int i = 0; i < getNumberOfPages(); i++) {
                DiagramComponent d = ((ShapesContainer) containers.get(i)).getComponent();
                try {
                    String fileName;
                    if (directory.exists()) {
                        fileName = new File(directory, d.toString() + ".PNG").getCanonicalPath();
                    } else {
                        fileName = new File(d.toString() + ".PNG").getCanonicalPath();
                    }
                    print(d, IMAGE_FILE_MODE, fileName);
                    System.out.println(messageWriter.print1args("exported", fileName));
                } catch (Exception ex) {
                    System.err.println(messageWriter.print2args("cannotExport", d.getName(), ex.getMessage()));
                    ex.printStackTrace();
                    return;
                }
            }
            return;
        }
        if (command.startsWith("printToFile ")) {
            String fileName = command.substring(12);
            FileOutputStream fos = null;
            StreamPrintService psPrinter = null;
            String psMimeType = "application/postscript";
            StreamPrintServiceFactory[] factories = PrinterJob.lookupStreamPrintServices(psMimeType);
            if (factories.length < 1) {
                System.err.println(messageWriter.print0args("noPSService"));
                return;
            }
            try {
                fos = new FileOutputStream(fileName);
                psPrinter = factories[0].getPrintService(fos);
            } catch (Exception e) {
                System.err.println(messageWriter.print2args("cannotPrintToFile", fileName, e.getMessage()));
                return;
            }
            print(psPrinter);
            psPrinter.dispose();
            try {
                fos.close();
            } catch (Exception e2) {
                System.err.println(messageWriter.print2args("cannotPrintToFile", fileName, e2.getMessage()));
                return;
            }
            return;
        }
        if (command.startsWith("printToPrinter")) {
            PrintService[] services = PrinterJob.lookupPrintServices();
            if (services.length < 1) {
                System.err.println(messageWriter.print0args("noPrinter"));
                return;
            }
            PrintService ps = null;
            if (command.length() > 14) {
                String printerName = command.substring(15);
                for (int i = 0; i < services.length; ++i) {
                    if (services[i].getName().equals(printerName)) {
                        ps = services[i];
                        break;
                    }
                }
                if (ps == null) {
                    System.err.println(messageWriter.print1args("cannotFindPrinter", printerName));
                    System.err.print(messageWriter.print0args("availablePrinters"));
                    for (int i = 0; i < services.length; ++i) {
                        System.err.print(services[i].getName() + " ");
                    }
                    System.err.println();
                    return;
                }
            } else {
                ps = services[0];
            }
            print(ps);
            return;
        }
    }

    public void saveAllSynoptics() {
        for (int i = 0; i < getNumberOfPages(); i++) {
            ShapesContainer sc = ((ShapesContainer) containers.get(i));
            if (builtInPlugin != null) {
                File oldFile = (File) files.get(i);
                if (oldFile != null) {
                    try {
                        builtInPlugin.saveShapeContainer(sc, oldFile);
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    public void print(PrintService ps) {
        if (ps == null) {
            System.err.println(messageWriter.print0args("noPrinter"));
            return;
        }
        System.out.println(messageWriter.print1args("printingTo", ps.getName()));
        PrinterJob pj = PrinterJob.getPrinterJob();
        try {
            pj.setPrintService(ps);
        } catch (PrinterException pe) {
            System.err.println(messageWriter.print2args("invalidPrinter", ps.getName(), pe.getMessage()));
            return;
        }
        pj.setPageable(this);
        try {
            pj.print();
        } catch (PrinterException pe2) {
            System.err.println(messageWriter.print1args("printFailed", pe2.getMessage()));
            return;
        }
    }

    protected Plugin getPluginToProcessFile(File f, int action, FileFilter activeFilter) {
        boolean accepted;
        if (activeFilter != null) {
            if (activeFilter instanceof simtools.ui.MenuResourceBundle.FileFilter) {
                accepted = ((simtools.ui.MenuResourceBundle.FileFilter)activeFilter).canProcess(f);
            }else {
                accepted = activeFilter.accept(f);
            }

        } else {
            accepted = false;
        }


        // if the active filter accepts the file, use its plugin in priority
        // otherwise, take the first plugin (excuding the builtin) that can
        // accept the file
        Plugin acceptedPlugin = null;
        for (int i = 0; i < Run.plugins.size(); ++i) {
            Plugin p = (Plugin) Run.plugins.get(i);
            FileFilter[] fft = p.getFileFilters(action);
            if (fft == null) {
                continue;
            }
            for (int j = 0; j < fft.length; ++j) {
                if (accepted && fft[j].equals(activeFilter)) {
                    return p;
                }

                if ((acceptedPlugin == null) || (acceptedPlugin instanceof Builtin)) {

                    if (fft[j] instanceof simtools.ui.MenuResourceBundle.FileFilter) {
                        if (((simtools.ui.MenuResourceBundle.FileFilter) fft[j]).canProcess(f)) {
                            acceptedPlugin = p;
                        }

                    } else {
                        accepted = fft[j].accept(f);
                    }
                }
            }
        }
        if (acceptedPlugin == null) {
            System.err.println(resources.getStringValue("unknownFileType"));
            System.err.println(messageWriter.print1args("noPluginForFile", f.getName()));
            return null;
        }
        return acceptedPlugin;
    }

    // Pageable interface
    public int getNumberOfPages() {
        return containers.size();
    }

    public PageFormat getPageFormat(int index) {
        return pageFormat; // same for all
    }

    public Printable getPrintable(int index) {
        Printable p = ((ShapesContainer) containers.get(index)).getComponent();
        return p;
    }
}
TOP

Related Classes of jsynoptic.ui.JSynopticBatch

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.