Package converter

Source Code of converter.Start

/**
* Copyright: t3am_C9 (Alexander Schäffer, Johannes Ebersold, Sebastian Geib, Thomas Kisiel)
*
* This file is part of GifToApngConverter
*
* GifToApngConverter 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 3 of the License, or
* (at your option) any later version.
*
* GifToApngConverter 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 GifToApngConverter. If not, see <a href="http://www.gnu.org/licenses/">here</a>
*/

package converter;

import giftoapng.APNG;
import gui.EJFrame;
import gui.I_UIupdater;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.swing.UIManager;

/**
* Has the main-function to start the gui and a static convert function to
* convert a .gif-file to a .png(aPNG) file
*
* @author Sebastian Geib
* @author Alexander Sch&auml;ffer
*/
public class Start
{

  public static boolean bQuietmode = false;
  public static boolean bForcemode = false;

  public static void main(String[] args)
  {

    if (args.length == 0)
    {
      // start GUI

      // applying look and feel
      try
      {
        // system look and feel
        UIManager.setLookAndFeel(UIManager
            .getSystemLookAndFeelClassName());
      } catch (Exception e)
      {
        // just ignore and pretend that we never tried to use Look&Feel
      }

      EJFrame.getEJFrame();
    } else if ( "--help -? /? -help /help".contains(args[0]) )
    {
      // print usage
      printhelp();
     
    } else
    {
      // run as console-app
      consoleRun(args);
    }

  }

  /**
   * reads a .gif, converts it to a apng and writes it to a .png file.
   * <i>callback</i> can send an update after each frame, may be <i>null</i>
   * if unused
   *
   * @param source
   *            the .gif file
   * @param destination
   *            the .png file
   * @param callback
   */
  public static void convert(File source, File destination,
      I_UIupdater callback) throws IOException
  {

    APNG apngObject = null;
    try
    {
      apngObject = APNG.convertGiftoAPNG(source, callback);
    } catch (IOException ex)
    {
      throw new IOException("error while reading", ex);
    }

    FileOutputStream fw;
    BufferedOutputStream bos;

    try
    {

      fw = new FileOutputStream(destination);
      bos = new BufferedOutputStream(fw);

      apngObject.write(bos);

      bos.close();
      fw.close();

    } catch (IOException ex)
    {
      throw new IOException("error while writing", ex);
    }

  }

  /**
   * The actual console-application: checks the switches (-q/-f), checks
   * source file: exists?, can be read?, is a gif-file? checks destination:
   * exists? if yes depends the action on the switches: <br>
   * [nothing]: asks for overwriting<br>
   * only -q : no question, no overwriting<br>
   * only -f : displays message and overwrites<br>
   * -q and -f: no question, but overwrites<br>
   *
   * @param args
   */
  private static void consoleRun(String[] args)
  {
    /*
     * syntax {file} {options} options: -o filename saves converted file as
     * 'filename'
     *
     * -q quiet mode. No output
     *
     * -f force mode. Don't ask any questions
     */
    ArrayList<File> fileList = new ArrayList<File>();
    // File source = null;
    File destination = null;
   
    StringBuffer notice=new StringBuffer();

    for (int i = 0; i < args.length; i++)
    {
      if (args[i].equals("-q"))
      {
        bQuietmode = true;
      } else if (args[i].equals("-f"))
      {
        bForcemode = true;
      } else if (args[i].equals("-o"))
      {  
        if(i+1<args.length){
          destination = new File(args[i + 1]);
          i++;
        } else {
          System.err.println("Last argument was '-o', but a path is expected after '-o'. Aborting.");
          return; //abort
        }
      } else
      {
        // add file to process list
        File f = new File(args[i]);
        if (f.isFile() && args[i].toLowerCase().endsWith(".gif"))
        {
          fileList.add(f);
        } else if(!f.exists()){
          notice.append("'"+f.getName()+"' doesn't exist.\n");
        } else if(!f.isDirectory() && !args[i].toLowerCase().endsWith(".gif")){
          notice.append("'"+f.getName()+"' doesn't end with '.gif'.\n");
        } else {
          //this should be a directory. just ignore.
        }
      }
     
    } // for

    if (!bQuietmode)
    {
      System.out.println("GIF to APNG - Converter\n");
      notice.append("\n");
      System.out.print(notice);
     
    }

    // source = new File(args[0]);
    // destination = new File(args[1]);

    for (File source : fileList)
    {
      // if there are more items ignore the user destination
      if (fileList.size() > 1 || destination == null)
      {
        String ab = source.getAbsolutePath();
        destination = new File(ab.substring(0, ab.length() - 4)
            + ".apng");
      }

      if (!bQuietmode)
      {
        System.out.println("converting:");
        System.out.println("Source:      " + source.getAbsolutePath());
        System.out.println("Destination: "
            + destination.getAbsolutePath());
      }

      if (!source.exists())
      {
        if (!bQuietmode)
        {
          System.out.println("Source-file doesn't seem to exist.");
        }
        continue;
      } else if (!source.canRead())
      {
        if (!bQuietmode)
        {
          System.out.println("Cannot read from the source-file");
        }
        continue;
      }
      String sourcename = source.getName();
      if (sourcename.length() < 4
          || !sourcename.substring(sourcename.length() - 4,
              sourcename.length()).toLowerCase().equals(".gif"))
      {
        if (!bQuietmode)
        {
          System.out
              .println("Source-file must have the extension '.gif'");
        }
        continue;
      }

      if (destination.exists())
      {
        boolean overwrite = bForcemode; // standard: don't overwrite if
        // bForcemode==false
        // and overwrite if bForcemode==true
        if (!bQuietmode && !bForcemode)
        {
          // input
          BufferedReader bin = new BufferedReader(
              new InputStreamReader(System.in));
          String answer=" ";
          while (!("yjn".contains(answer.toLowerCase()
              .substring(0, 1))))
          {
            System.out
                .print("Destination-file seems to exist. Overwrite? (y/n) ");

            try
            {
              answer = bin.readLine()+" ";
            } catch (IOException e)
            {
              e.printStackTrace();
            }
            if ("yj".contains(answer.toLowerCase().substring(0, 1)))
            {
              overwrite = true;
            }
            if ("n".contains(answer.toLowerCase().substring(0, 1)))
            {
              overwrite = false;
            }
          }

        } else if (!bQuietmode && bForcemode)
        {
          System.out.println("Destination-file seems to exist.");
          System.out
              .println("Force-mode is active: it will be overwritten.");
        }
        if (!overwrite)
        {
          continue; // next file
        }
      }

      // convert it!
      try
      {
        I_UIupdater toconsole = null;

        if (!bQuietmode)
        {
          toconsole = new I_UIupdater()
          {
            int miMaximum;

            @Override
            public void updatecur(int current)
            {
              if(current<=miMaximum){
                System.out.print("reading frame " + current + "/"
                  + miMaximum + "\r");
              } else { // if current is > miMaximum, then file-writing is meant
                System.out.print("writing file  ");
                for(int i=0;i< (Math.log10(miMaximum)+1)*2+1;i++){
                  //print spaces to overwrite "number/number"
                  System.out.print(" ");
                }
                System.out.print("\r");
              }
            }

            @Override
            public void updatemax(int maximum)
            {
              miMaximum = maximum;
            }

          };
        }

        convert(source, destination, toconsole);

        if (!bQuietmode)
        {
          System.out.println("\nAPNG written to \""
              + destination.getName() + "\"");
        }

      } catch (IOException e)
      {

        String errmsg = e.getMessage();
        String errtype = "";

        if (errmsg.contains("reading"))
        {
          errtype = " while reading";
        } else if (errmsg.contains("writing"))
        {
          errtype = " while writing";
        }
        if (e.getCause() != null && errtype.length() != 0)
        {
          errmsg = e.getCause().getMessage();
        }

        System.err.println("IO Error" + errtype + ": " + errmsg);
      } catch (Exception e)
      {
        System.err.println("Error: " + e.getMessage());
      }
     
    } //for all files in list
  }

  /**
   * only prints the usage/help-info
   */
  private static void printhelp()
  {
    System.out.println("GIF to APNG - Converter");
    System.out
        .println("usage: java -jar giftoapng.jar file(s) [-o destinationname] [-q] [-f]");
    System.out.println();
    System.out.println("  -o destinationname: only used if exactly one file is given");
    System.out.println("  -q quiet mode: no output, no questions");
    System.out
        .println("  -f force overwrite: overwrites any existing output file");
  }

}
TOP

Related Classes of converter.Start

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.