/* Copyright (C) 2014-2017 A.Vontobel  
 *
 * This program 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.
 *
 * 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 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The license is in LICENCE-GPL.txt.
 * If not, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
 */

package net.sf.drawj2d;

import gnu.getopt.*;
import java.awt.BasicStroke;
import static java.awt.Color.*;
import java.awt.Graphics2D;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.geom.*;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;




/**
 * Diese Klasse dient dazu, das Programm Drawj2d über die Konsole aufzurufen.
 *
 * @author  A.Vontobel 
 */
public class Drawj2d implements inConst {
    
    double width = 210; //mm
    double height = 297; //mm
    double originX = 0; //mm x pos of origin
    double originY = 0; //mm y pos of origin
    boolean docenter = false; // if true, set origin to half width, half height. Ignore -X, -Y
    
    String outputtype = "pdf";
    String quelldatei; // Dateiname, oder "_opt_stdin"
    String zieldatei; // Dateiname, oder "_opt_stdout"
    boolean zieldateigesetzt = false;
    double res; // dpi
    boolean resgesetzt = false;
    boolean verbose = false;
    boolean quiet = false;
    
    final static int ModeJRE = 1;
    final static int ModeFreehep = 2;
    final static int ModeEpsgraphics = 4;
    final static int ModeJtikz = 5;
    int mode;
    boolean defaultmode = true;
    
    int srcType = srcTypeHcl; // default mode
    
    private String[] iArgs;
    
    private final static String PGM     = "Drawj2d";
    private final static String VERSION = "0.83";
    
    private final static String USAGE_en = "Usage:\n" +
            "java -jar drawj2d.jar  [-TWHcXYrfvqhV] \n" +
            "                       [-o OutputFile]  \n" +
            "                       [InputFile] \n\n" +
            "-T, --type                Output file type: pdf, svg, eps, emf, png \n" +
            "                                            screen (displays the drawing) \n" +
            "-W, --width               Graphics width (default 210mm)\n" +
            "-H, --height              Graphics height (default 297mm)\n" +
            "-c, --center              Set origin to center of sheet, instead of top left\n" +
            "-X, --originx             Offset origin right (default 0mm) \n" +
            "-Y, --originy             Offset origin down (default 0mm) \n" +
            "-r, --resolution          Resolution of images (default 200dpi), svg (96dpi)\n" +
            "-f, --fallback            Fallback mode\n" +
            "-F, --frontend            Input file type: hcl (default), bgd, ypd\n" +
            "-v, --verbose             Verbose output\n" +
            "-q, --quiet               No messages to stdout\n" +
            "-h, --help                Usage information; this help screen\n" +
            "-V, --version             Display version\n" +
            "-o  --outfile OutputFile  OutputFile name (default: out-filename)\n" +
            "InputFile                 InputFile. If omitted reads from stdin\n" +
            "\n" +
            "Examples:\n" +
            "java -jar drawj2d.jar mydrawing.hcl \n" +
            "java -jar drawj2d.jar -T png -W 100 -H 150 -X 50 -Y 75 mydrawing.hcl \n" +
            "java -jar drawj2d.jar -T svg mydrawing.hcl \n";
    
    /**
     * Creates a new instance of Drawj2d
     * @param args
     */
    public Drawj2d (String[] args) {
        iArgs = args;
    }
    
    /** Zeigt die Startinformatin an.*/
    private void startinfo() {
        System.out.println("");
        System.out.println("            " + "Welcome to" + " " + PGM);
        System.out.println("            Copyright (c) A. Vontobel, 2014-2017");
        System.out.println("            " + "Version" + " " + VERSION);
        System.out.println("");
    }
    
    /** Zeigt die Hilfe an und beendet anschliessend das Programm.
     @param exitStatus 0 wenn ordentlich beendet, sonst > 0
     */
    public void usage(int exitStatus) {
        startinfo();
        System.out.println(USAGE_en);
        System.exit(exitStatus);
    }
    
    /////////////////////////////////////////////////////////////////////////
    
    public void  parseArguments() {
        LongOpt[] longopts = new LongOpt[14];
        longopts[0] = new LongOpt("help",LongOpt.NO_ARGUMENT,null,'h');
        longopts[1] = new LongOpt("verbose",LongOpt.NO_ARGUMENT,null,'v');
        longopts[2] = new LongOpt("quiet",LongOpt.NO_ARGUMENT,null,'q');
        longopts[3] = new LongOpt("version",LongOpt.NO_ARGUMENT,null,'V');
        longopts[4] = new LongOpt("outfile",LongOpt.REQUIRED_ARGUMENT,null,'o');
        longopts[5] = new LongOpt("type",LongOpt.REQUIRED_ARGUMENT,null,'T');
        longopts[6] = new LongOpt("width",LongOpt.REQUIRED_ARGUMENT,null,'W');
        longopts[7] = new LongOpt("height",LongOpt.REQUIRED_ARGUMENT,null,'H');
        longopts[8] = new LongOpt("originx",LongOpt.REQUIRED_ARGUMENT,null,'X');
        longopts[9] = new LongOpt("originy",LongOpt.REQUIRED_ARGUMENT,null,'Y');
        longopts[10] = new LongOpt("fallback",LongOpt.NO_ARGUMENT,null,'f');
        longopts[11] = new LongOpt("resolution",LongOpt.REQUIRED_ARGUMENT,null,'r');
        longopts[12] = new LongOpt("center",LongOpt.NO_ARGUMENT,null,'c');
        longopts[13] = new LongOpt("frontend",LongOpt.REQUIRED_ARGUMENT,null,'F');
        
        
        Getopt g = new Getopt(PGM,iArgs,":T:W:H:X:Y:r:F:o:cfvqhV",longopts);
        g.setOpterr(false);
        int c;
        
        while ((c = g.getopt()) != -1) {
            switch (c) {
                case 'v':
                    verbose = true;
                    break;
                case 'q':
                    verbose = false;
                    quiet = true;
                    break;
                case 'h':
                    usage(0);
                    break;
                case 'V':
                    startinfo();
                    System.exit(0);
                    break; // diese Zeile wird nie erreicht.
                case 'T':
                    outputtype = g.getOptarg();
                    break;
                case 'f':
                    defaultmode = false;
                    break;
                case 'W':
                    String widthstring = g.getOptarg();
                    try {
                        width = Double.parseDouble(widthstring);
                    } catch (NumberFormatException e) {
                        System.err.println("Width not an Number");
                        usage(1);
                    }
                    break;
                case 'H':
                    String heightstring = g.getOptarg();
                    try {
                        height = Double.parseDouble(heightstring);
                    } catch (NumberFormatException e) {
                        System.err.println("Height not an Number");
                        usage(1);
                    }
                    break;
                case 'c':
                    docenter = true;
                    break;
                case 'X':
                    String originxstring = g.getOptarg();
                    try {
                        originX = Double.parseDouble(originxstring);
                    } catch (NumberFormatException e) {
                        System.err.println("Origin x position not an Number");
                        usage(1);
                    }
                    break;
                case 'Y':
                    String originystring = g.getOptarg();
                    try {
                        originY = Double.parseDouble(originystring);
                    } catch (NumberFormatException e) {
                        System.err.println("Origin y position not an Number");
                        usage(1);
                    }
                    break;
                case 'r':
                    String resstring = g.getOptarg();
                    try {
                        res = Double.parseDouble(resstring);
                        resgesetzt = res > 0;
                    } catch (NumberFormatException e) {
                        System.err.println("Resolution not an Number");
                        usage(1);
                    }
                    break;
                case 'F':
                    String srcTypestring = g.getOptarg();
                    if (srcTypestring.equalsIgnoreCase("hcl")) srcType = srcTypeHcl;
                    else if (srcTypestring.equalsIgnoreCase("bgd")) srcType = srcTypeBgd;
                    else if (srcTypestring.equalsIgnoreCase("ypd")) srcType = srcTypeYacasPlotData;
                    else {
                        System.err.println("Unknown frontend: " + srcTypestring);
                        System.err.println("Expected: hcl | bgd | ypd");
                        usage(1);
                    }
                    break;
                case 'o':
                    zieldatei = g.getOptarg();
                    if (zieldatei.equals("-")) {
                        System.err.println("Output to stdout not implemented.");
                    }
                    zieldateigesetzt = true;
                    break;
                case ':':
                    System.err.println("Missing Argument" + " " + (char) g.getOptopt());
                    usage(1);
                    break;
                case '?':
                    System.err.println("Option Not Valid" + " " + (char) g.getOptopt());
                    usage(1);
                    break;
                default:
                    usage(1);
            }
        }
        String[] iDateien = new String[iArgs.length - g.getOptind()];
        for (int i=g.getOptind();i 1) {
            System.err.println("Max one file");
        }
        
        if (!zieldateigesetzt) {
            if (quelldatei.equals("_opt_stdin")) {
                zieldatei = "out" + "." + outputtype.toLowerCase();
            }
            else {
                File d = new File(quelldatei);
                if (d.getParent() == null) {
                    zieldatei = "out-" +d.getName();
                } else zieldatei = d.getParent() + System.getProperty("file.separator") + "out-" +d.getName();
                if (zieldatei.endsWith(".hcl")) zieldatei = zieldatei.substring(0, zieldatei.lastIndexOf(".hcl"));
                zieldatei = zieldatei + "." + outputtype.toLowerCase();
            }
        }
        
        if (docenter) {
            originX = width / 2d;
            originY = height / 2d;
        }
        
        String suffix = outputtype.toLowerCase();
        if  (suffix.equals("pdf") || suffix.equals("svg")) {
            mode = ModeFreehep; // No fallback mode available.
        } else if (suffix.equals("eps") || suffix.equals("ps")) {
            if (defaultmode) mode = ModeEpsgraphics;
            else mode = ModeFreehep;
        } else if (suffix.equals("tikz") || suffix.equals("jtikz")) {
            mode = ModeJtikz; // No fallback mode available for tikz.
        } else if (suffix.equals("screen")) {
            mode = ModeJRE;
        } else { // img, etc.
            if (defaultmode) mode = ModeFreehep;
            else mode = ModeJRE;
        }
    }
    
   

    public static void Run(String[] args) {

      if (args.length == 1 && args[0].equals("TESTRUN")) {
            test("png");
            return;
        }


        Drawj2d c = new Drawj2d(args);
        c.parseArguments(); // Beendet das Prog, falls z.B. -h oder -V aufgerufen wird.
        if (!c.quiet) c.startinfo();

        boolean success;

        switch (c.mode) {
            case ModeFreehep:
                FreehepMode mF = new FreehepMode(c);
                if (c.resgesetzt) mF.setResolution(c.res);
                success = mF.run();
                break;
            case ModeEpsgraphics:
                EpsgraphicsMode mE = new EpsgraphicsMode(c);
                if (c.resgesetzt) mE.setResolution(c.res); // Just to get the message, not effect on eps
                success = mE.run();
                break;
            case ModeJtikz:
                JtikzMode mt = new JtikzMode(c);
                if (c.resgesetzt) mt.setResolution(c.res); // Just to get the message, not effect on eps
                success = mt.run();
                break;
            case ModeJRE:
            default:
                JREMode mJ = new JREMode(c);
                if (c.resgesetzt) mJ.setResolution(c.res);
                success = mJ.run();
        }

        if (c.outputtype.equalsIgnoreCase("screen")) {
            // keep the program running
        } else {
            if (success) System.out.println("Done!"); //  System.exit(0);
            else {
                if (c.verbose) System.out.println("ERROR occured! Drawj2d quits.");
                System.exit(1);
            }
        }


    }

 
    

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    

            Run(args);
    
    }
    
    
    // -----------------------------------------------------------------
    
    /** Test  */
    static void drawGraph(java.awt.Graphics2D g){
        g.setStroke(new BasicStroke(0.35f));
        
        // Draw a red ellipse at the position (20, 30) with a width of 100 and a height of 150
        g.setColor(RED);
        g.fillOval(20, 30, 100, 150);
        
        // Only draw in a ellipse at the position (70, 50) with a width of 50 and a height of 100
        g.setClip(new Ellipse2D.Double(70.0, 80.0, 50.0, 100.0));
        
        // Draw lines all over the page
        g.setColor(BLACK);
        for (double x = 0.0; x < 210.0; x += 2.0) {
                g.draw(new Line2D.Double(x, 0.0, x, 297.0));
        }
        
        g.setClip(null);
        // Draw lines all over the page
        g.setStroke(new BasicStroke(1f));
        g.setColor(BLUE);
        for (double x = 0.0; x < 210.0; x += 5.0) {
                g.draw(new Line2D.Double(x, 0.0, x, 297.0));
        }
    }
    
    /**
     * Test
     * @param suffix
     */
    public static void test(String suffix) {
        double width = 210; //mm
        double height = 297; //mm
        
        int type = 0;
        String IOsuffixes[] = ImageIO.getWriterFileSuffixes();
        for (String t: IOsuffixes) { //System.out.println(t); // 1.7: jpg,bmp,jpeg,wbmp,png,gif
            if (t.equals(suffix)) type = IMG;
        }
        
        String filename = "export." + suffix;
        switch (type) {
            case IMG:
                break;
            default:
                System.err.println("Not supported for test: " + suffix);
                return;
        }
        
        

        // Write the output to a file
        FileOutputStream file = null;
        try {
            file = new FileOutputStream(filename);
            
            int imgtype = BufferedImage.TYPE_INT_ARGB; // including transparency (alpha channel)
            if (suffix.equals("jpeg") || suffix.equals("jpg") || suffix.equals("bmp")) {
                imgtype = BufferedImage.TYPE_INT_RGB; // not supporting transparency, avoid black image
            }
            if (suffix.equals("wbmp")) {
                imgtype = BufferedImage.TYPE_BYTE_BINARY; // black-white, avoid empty file
            }
            float res = 200f / 25.4f; // dpi / mm/i = dpmm
            BufferedImage bi = new BufferedImage((int) (width * res), (int) (height * res), imgtype);
            Graphics2D ig2 = bi.createGraphics();
            ig2.scale(res, res);
            drawGraph(ig2);
            ImageIO.write(bi, suffix, file);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Drawj2d.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Drawj2d.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (file != null) {
                    file.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Drawj2d.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

 

Ads help maintain this website.