All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.daisy.dotify.cli.EmbossPEF Maven / Gradle / Ivy

There is a newer version: 3.2.5
Show newest version
/*
 * Braille Utils (C) 2010-2011 Daisy Consortium 
 * 
 * This library 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 library 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 library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package org.daisy.dotify.cli;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.prefs.BackingStoreException;

import javax.print.PrintService;
import javax.xml.parsers.ParserConfigurationException;

import org.daisy.braille.utils.api.embosser.Device;
import org.daisy.braille.utils.api.embosser.Embosser;
import org.daisy.braille.utils.api.embosser.EmbosserCatalog;
import org.daisy.braille.utils.api.embosser.EmbosserFeatures;
import org.daisy.braille.utils.api.embosser.EmbosserProperties;
import org.daisy.braille.utils.api.embosser.EmbosserProperties.PrintMode;
import org.daisy.braille.utils.api.embosser.EmbosserWriter;
import org.daisy.braille.utils.api.embosser.PrintPage;
import org.daisy.braille.utils.api.factory.FactoryProperties;
import org.daisy.braille.utils.api.factory.FactoryPropertiesComparator;
import org.daisy.braille.utils.api.paper.Length;
import org.daisy.braille.utils.api.paper.PageFormat;
import org.daisy.braille.utils.api.paper.Paper;
import org.daisy.braille.utils.api.paper.PaperCatalog;
import org.daisy.braille.utils.api.paper.PaperFilter;
import org.daisy.braille.utils.api.paper.RollPaperFormat;
import org.daisy.braille.utils.api.paper.SheetPaperFormat;
import org.daisy.braille.utils.api.paper.SheetPaperFormat.Orientation;
import org.daisy.braille.utils.api.paper.TractorPaperFormat;
import org.daisy.braille.utils.api.table.Table;
import org.daisy.braille.utils.api.table.TableCatalog;
import org.daisy.braille.utils.pef.FileDevice;
import org.daisy.braille.utils.pef.PEFConverterFacade;
import org.daisy.braille.utils.pef.PEFHandler;
import org.daisy.braille.utils.pef.PrinterDevice;
import org.daisy.braille.utils.pef.Range;
import org.daisy.braille.utils.pef.UnsupportedWidthException;
import org.daisy.streamline.cli.Argument;
import org.daisy.streamline.cli.CommandDetails;
import org.daisy.streamline.cli.CommandParser;
import org.daisy.streamline.cli.CommandParserResult;
import org.daisy.streamline.cli.ExitCode;
import org.daisy.streamline.cli.OptionalArgument;
import org.daisy.streamline.cli.SwitchArgument;
import org.daisy.streamline.cli.SwitchMap;
import org.xml.sax.SAXException;

/**
 * Provides a UI for embossing a PEF-file.
 * Not for public use. This class is a package class. Use DotifyCLI 
 * @author Joel Håkansson
 */
class EmbossPEF implements CommandDetails {
	/**
	 * Prefix used for required arguments in the arguments map
	 */
	public static final String ARG_PREFIX = "required-";
	public static final String DEVICE_NAME = "device name";
	public static final String EMBOSSER_TYPE = "embosser type";
	public static final String TABLE_TYPE = "table type";
	public static final String PAPER_SIZE = "paper size";
	public static final String CUT_LENGTH = "cut length";
	public static final String ORIENTATION = "orientation";
	public static final String PRINT_MODE = "print mode";
	public static final String KEY_RANGE = "range";
	public static final String KEY_COPIES = "copies";
	public static final String KEY_DIR = "dir";

	private final List reqArgs;
	private final List optionalArgs;
	private final SwitchMap switches;
	private final CommandParser parser;
	
	private String deviceName;
	private Embosser type;
	private Table table;
	private Paper paper;
	private PageFormat pageFormat;
	
	public EmbossPEF() {
		super();
		reqArgs = new ArrayList();
		/*ArrayList options = new ArrayList();
		options.add(new Definition("[path to file]", "Path to PEF-file"));
		options.add(new Definition("-clear", "to clear settings"));
		options.add(new Definition("-setup", "to change setup"));*/
		reqArgs.add(new Argument("path_to_file", "Path to PEF-file"));
		optionalArgs = new ArrayList();
		optionalArgs.add(new OptionalArgument(KEY_RANGE, "Emboss a range of pages", "1-"));
		optionalArgs.add(new OptionalArgument(KEY_COPIES, "Set copies", "1"));
		optionalArgs.add(new OptionalArgument(KEY_DIR, "Send the embosser data to a folder instead of the specified device.", ""));
		this.switches = new SwitchMap.Builder()
				.addSwitch(new SwitchArgument("clear", "settings", "clear", "To clear settings"))
				.addSwitch(new SwitchArgument("setup", "settings", "setup", "To change setup"))
				.build();
		this.parser = CommandParser.create(this);
	}
	
	protected void readSetup(boolean verify) {
		// Check setup
		InputHelper input = new InputHelper();
		ArrayList str = new ArrayList<>();
		for (PrintService ps : PrinterDevice.getDevices()) {
			str.add(ps.getName());
		}
		deviceName = input.select(DEVICE_NAME, str.toArray(new String[0]), "device", verify); 
		System.out.println("Using device: " + deviceName);
		
		EmbosserCatalog ec = EmbosserCatalog.newInstance();
		ArrayList sorted = new ArrayList(ec.list());
		Collections.sort(sorted, new FactoryPropertiesComparator());
		String embosserType = input.select(EMBOSSER_TYPE, sorted, "embosser", verify);
		type = ec.get(embosserType);
		System.out.println("Embosser: " + type.getDisplayName());
		
		if (getEmbosser().supportsPrintMode(EmbosserProperties.PrintMode.REGULAR) && getEmbosser().supportsPrintMode(EmbosserProperties.PrintMode.MAGAZINE)) {
			String printMode = input.select(PRINT_MODE, new String[]{
					EmbosserProperties.PrintMode.REGULAR.toString().toLowerCase(), 
					EmbosserProperties.PrintMode.MAGAZINE.toString().toLowerCase()}, 
					"print mode", verify);
			getEmbosser().setFeature(
					EmbosserFeatures.SADDLE_STITCH, 
					PrintMode.MAGAZINE.toString().toLowerCase().equals(printMode));
			System.out.println("Print mode: " + printMode);
		}

		TableCatalog tablef = TableCatalog.newInstance();
		Collection supportedTables = tablef.list(type.getTableFilter());
		if (supportedTables.size()>1) {
			String tableType = input.select(TABLE_TYPE, new ArrayList(supportedTables), "table", verify);
			table = tablef.get(tableType);
			System.out.println("Table: " + table.getDisplayName());
		} else {
			table = null;
		}

		boolean ok = false;
		do {
			PaperCatalog pc = PaperCatalog.newInstance();
			sorted = new ArrayList(pc.list(new EmbosserPaperFilter(type)));
			Collections.sort(sorted, new FactoryPropertiesComparator());
			String paperSize = input.select(PAPER_SIZE, sorted, "paper", verify);
			paper = pc.get(paperSize);
			
			switch (paper.getType()) {
				case ROLL:
					try {
						double d = input.getDouble("Cut length (in mm)", CUT_LENGTH, verify);
						this.pageFormat = new RollPaperFormat(paper.asRollPaper(), Length.newMillimeterValue(d));
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
					break;
				case SHEET:
					try {
						boolean b = input.getBoolean("Use default orientation (" + 
								new PrintPage((new SheetPaperFormat(paper.asSheetPaper(), Orientation.DEFAULT))).getShape().toString().toLowerCase()
								+ ")?", ORIENTATION, verify);
						this.pageFormat = new SheetPaperFormat(paper.asSheetPaper(), (b?Orientation.DEFAULT:Orientation.REVERSED));
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
					break;
				case TRACTOR: default:
					this.pageFormat = new TractorPaperFormat(paper.asTractorPaper());
					break;
				}
			ok = type.supportsPageFormat(pageFormat);
			if (!ok) {
				System.out.println("The setting is not supported");
			}
		} while (!ok);
		System.out.println("Paper: " + paper.getDisplayName() + " (" + pageFormat + ")");

	}
	
	public Table getTable() {
		return table;
	}
	
	public String getDeviceName() {
		return deviceName;
	}

	public PageFormat getPageFormat() {
		return pageFormat;
	}
	
	public Embosser getEmbosser() {
		return type;
	}
	
	void clearSettings()  throws BackingStoreException {
		InputHelper h = new InputHelper(getClass());
		h.clearSettings();
		System.out.println("Settings have been cleared.");
	}
	
	void setup() {
		readSetup(true);
		listCurrentSettings(System.out);
	}
	
	public static void main(String[] args) throws BackingStoreException {
		EmbossPEF ui = new EmbossPEF();
		if (args.length<1) {
			System.out.println("Expected at least one more argument.");
			System.out.println();
			ui.parser.displayHelp(System.out);
			ExitCode.MISSING_ARGUMENT.exitSystem();
		}

		CommandParserResult parserResult = ui.parser.parse(args);
		Map p = parserResult.toMap(ARG_PREFIX);
		String firstArg = p.remove(ARG_PREFIX+0);

		if ("clear".equalsIgnoreCase(p.get("settings"))) {
			ui.clearSettings();
			ExitCode.OK.exitSystem();
		}

		if ("setup".equalsIgnoreCase(p.get("settings"))) {
			ui.setup();
			if (firstArg==null) {
				ExitCode.OK.exitSystem();
			}
		} else {
			ui.readSetup(false);
		}
		
		Device device = null;
		String basePathStr = parserResult.getOptional().get(KEY_DIR);
		if (basePathStr!=null && !"".equals(basePathStr)) {
			File basePath = new File(basePathStr);
			if (basePath.isDirectory()) {
				File embossFolder = null;
				do {
					embossFolder = new File(basePath, System.currentTimeMillis()+"");
				} while (embossFolder.exists());
				embossFolder.mkdir();
				device = new FileDevice(embossFolder);
			} else {
				ExitCode.ILLEGAL_ARGUMENT_VALUE.exitSystem(basePathStr + " does not exist or is not a directory.");
			}
		} else {
			device = new PrinterDevice(ui.getDeviceName(), true);
		}

		PageFormat pf = ui.getPageFormat();
		ui.getEmbosser().setFeature(EmbosserFeatures.PAGE_FORMAT, pf);
		
		int copies = 1;
		String copiesStr = p.get(KEY_COPIES);
		if (copiesStr!=null && copiesStr!="") {
			try {
				copies = Integer.parseInt(copiesStr);
			} catch (NumberFormatException e) {
				System.out.println("Ignoring argument -"+ KEY_COPIES +"=" + copiesStr);
				copies = 1;
			}
		}
		try {
			ui.getEmbosser().setFeature(EmbosserFeatures.NUMBER_OF_COPIES, copies);
			//setting copies to 1 to avoid sending multiple requests below since 
			//copies has been enabled in implementation
			copies = 1;
		} catch (IllegalArgumentException e) {
			//nothing to do here at the moment, send multiple requests below instead...
		}
		
		if (ui.getTable()!=null) {
			ui.getEmbosser().setFeature(EmbosserFeatures.TABLE, ui.getTable());
		}

		File input = new File(firstArg);
		if (!input.exists()) {
			throw new RuntimeException("Cannot find input file: " + firstArg);
		}
		try {
			boolean ok = new ValidatorFacade().validate(input, System.out);
			if (!ok) {
				ExitCode.UNEXPECTED_RESOURCE_CONTENTS.exitSystem("Validation failed, exiting...");
			}
			for (int i=0; i getRequiredArguments() {
		return reqArgs;
	}

	@Override
	public List getOptionalArguments() {
		return optionalArgs;
	}

	@Override
	public SwitchMap getSwitches() {
		return switches;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy