Search in sources :

Example 31 with PrinterJob

use of java.awt.print.PrinterJob in project beast-mcmc by beast-dev.

the class BranchRatePlotter method main.

public static void main(String[] args) throws java.io.IOException, Importer.ImportException {
    String controlFile = args[0];
    // String treeFile1 = args[0];
    // String treeFile2 = args[1];
    String targetTreeFile = args[1];
    int burnin = 0;
    if (args.length > 2) {
        burnin = Integer.parseInt(args[2]);
    }
    System.out.println("Ignoring first " + burnin + " trees as burnin.");
    BufferedReader readerTarget = new BufferedReader(new FileReader(targetTreeFile));
    String lineTarget = readerTarget.readLine();
    readerTarget.close();
    TreeImporter targetImporter;
    if (lineTarget.toUpperCase().startsWith("#NEXUS")) {
        targetImporter = new NexusImporter(new FileReader(targetTreeFile));
    } else {
        targetImporter = new NewickImporter(new FileReader(targetTreeFile));
    }
    MutableTree targetTree = new FlexibleTree(targetImporter.importNextTree());
    targetTree = TreeUtils.rotateTreeByComparator(targetTree, TreeUtils.createNodeDensityComparator(targetTree));
    BufferedReader reader = new BufferedReader(new FileReader(controlFile));
    String line = reader.readLine();
    int totalTrees = 0;
    int totalTreesUsed = 0;
    while (line != null) {
        StringTokenizer tokens = new StringTokenizer(line);
        NexusImporter importer1 = new NexusImporter(new FileReader(tokens.nextToken()));
        NexusImporter importer2 = new NexusImporter(new FileReader(tokens.nextToken()));
        int fileTotalTrees = 0;
        while (importer1.hasTree()) {
            Tree timeTree = importer1.importNextTree();
            Tree mutationTree = importer2.importNextTree();
            if (fileTotalTrees >= burnin) {
                annotateRates(targetTree, targetTree.getRoot(), timeTree, mutationTree);
                totalTreesUsed += 1;
            }
            totalTrees += 1;
            fileTotalTrees += 1;
        }
        line = reader.readLine();
    }
    System.out.println("Total trees read: " + totalTrees);
    System.out.println("Total trees summarized: " + totalTreesUsed);
    // collect all rates
    double mutations = 0.0;
    double time = 0.0;
    double[] rates = new double[targetTree.getNodeCount() - 1];
    int index = 0;
    for (int i = 0; i < targetTree.getNodeCount(); i++) {
        NodeRef node = targetTree.getNode(i);
        if (!targetTree.isRoot(node)) {
            Integer count = ((Integer) targetTree.getNodeAttribute(node, "count"));
            if (count == null) {
                throw new RuntimeException("Count missing from node in target tree");
            }
            if (!targetTree.isExternal(node)) {
                double prob = (double) (int) count / (double) (totalTreesUsed);
                if (prob >= 0.5) {
                    String label = "" + (Math.round(prob * 100) / 100.0);
                    targetTree.setNodeAttribute(node, "label", label);
                }
            }
            Number totalMutations = (Number) targetTree.getNodeAttribute(node, "totalMutations");
            Number totalTime = (Number) targetTree.getNodeAttribute(node, "totalTime");
            mutations += totalMutations.doubleValue();
            time += totalTime.doubleValue();
            rates[index] = totalMutations.doubleValue() / totalTime.doubleValue();
            System.out.println(totalMutations.doubleValue() + " / " + totalTime.doubleValue() + " = " + rates[index]);
            targetTree.setNodeRate(node, rates[index]);
            index += 1;
        }
    }
    double minRate = DiscreteStatistics.min(rates);
    double maxRate = DiscreteStatistics.max(rates);
    double medianRate = DiscreteStatistics.median(rates);
    // double topThird = DiscreteStatistics.quantile(2.0/3.0,rates);
    // double bottomThird = DiscreteStatistics.quantile(1.0/3.0,rates);
    // double unweightedMeanRate = DiscreteStatistics.mean(rates);
    double meanRate = mutations / time;
    System.out.println(minRate + "\t" + maxRate + "\t" + medianRate + "\t" + meanRate);
    for (int i = 0; i < targetTree.getNodeCount(); i++) {
        NodeRef node = targetTree.getNode(i);
        if (!targetTree.isRoot(node)) {
            double rate = targetTree.getNodeRate(node);
            // double branchTime = ((Number)targetTree.getNodeAttribute(node, "totalTime")).doubleValue();
            // double branchMutations = ((Number)targetTree.getNodeAttribute(node, "totalMutations")).doubleValue();
            float relativeRate = (float) (rate / maxRate);
            float radius = (float) Math.sqrt(relativeRate * 36.0);
            if (rate > meanRate) {
                targetTree.setNodeAttribute(node, "color", new Color(1.0f, 0.5f, 0.5f));
            } else {
                targetTree.setNodeAttribute(node, "color", new Color(0.5f, 0.5f, 1.0f));
            }
            // targetTree.setNodeAttribute(node, "color", new Color(red, green, blue));
            targetTree.setNodeAttribute(node, "line", new BasicStroke(1.0f));
            targetTree.setNodeAttribute(node, "shape", new java.awt.geom.Ellipse2D.Double(0, 0, radius * 2.0, radius * 2.0));
        }
        java.util.List heightList = (java.util.List) targetTree.getNodeAttribute(node, "heightList");
        if (heightList != null) {
            double[] heights = new double[heightList.size()];
            for (int j = 0; j < heights.length; j++) {
                heights[j] = (Double) heightList.get(j);
            }
            targetTree.setNodeHeight(node, DiscreteStatistics.mean(heights));
            // if (heights.length >= (totalTreesUsed/2)) {
            targetTree.setNodeAttribute(node, "nodeHeight.mean", DiscreteStatistics.mean(heights));
            targetTree.setNodeAttribute(node, "nodeHeight.hpdUpper", DiscreteStatistics.quantile(0.975, heights));
            targetTree.setNodeAttribute(node, "nodeHeight.hpdLower", DiscreteStatistics.quantile(0.025, heights));
        // targetTree.setNodeAttribute(node, "nodeHeight.max", new Double(DiscreteStatistics.max(heights)));
        // targetTree.setNodeAttribute(node, "nodeHeight.min", new Double(DiscreteStatistics.min(heights)));
        // }
        }
    }
    StringBuffer buffer = new StringBuffer();
    writeTree(targetTree, targetTree.getRoot(), buffer, true, false);
    buffer.append(";\n");
    writeTree(targetTree, targetTree.getRoot(), buffer, false, true);
    buffer.append(";\n");
    System.out.println(buffer.toString());
    SquareTreePainter treePainter = new SquareTreePainter();
    treePainter.setColorAttribute("color");
    treePainter.setLineAttribute("line");
    // treePainter.setShapeAttribute("shape");
    // treePainter.setLabelAttribute("label");
    JTreeDisplay treeDisplay = new JTreeDisplay(treePainter, targetTree);
    JTreePanel treePanel = new JTreePanel(treeDisplay);
    JFrame frame = new JFrame();
    frame.setSize(800, 600);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(treePanel);
    frame.setVisible(true);
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(treeDisplay);
    if (printJob.printDialog()) {
        try {
            printJob.print();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
Also used : PrinterJob(java.awt.print.PrinterJob) NewickImporter(dr.evolution.io.NewickImporter) JTreeDisplay(dr.app.gui.tree.JTreeDisplay) FileReader(java.io.FileReader) ArrayList(java.util.ArrayList) NexusImporter(dr.evolution.io.NexusImporter) JTreePanel(dr.app.gui.tree.JTreePanel) SquareTreePainter(dr.app.gui.tree.SquareTreePainter) StringTokenizer(java.util.StringTokenizer) BufferedReader(java.io.BufferedReader) TreeImporter(dr.evolution.io.TreeImporter) java.awt(java.awt)

Example 32 with PrinterJob

use of java.awt.print.PrinterJob in project chuidiang-ejemplos by chuidiang.

the class printJobExample method main.

public static void main(String[] args) {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(new Printable() {

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            return 0;
        }
    });
    boolean top = job.printDialog();
}
Also used : PageFormat(java.awt.print.PageFormat) Printable(java.awt.print.Printable) PrinterException(java.awt.print.PrinterException) PrinterJob(java.awt.print.PrinterJob)

Example 33 with PrinterJob

use of java.awt.print.PrinterJob in project megameklab by MegaMek.

the class UnitPrintManager method printAllUnits.

/**
 * Creates and runs a print job using the provided record sheet options
 *
 * @param loadedUnits The units to print
 * @param singlePrint Whether to limit each record sheet to a single unit
 * @param options     The options to use for this print job
 */
public static void printAllUnits(List<Entity> loadedUnits, boolean singlePrint, RecordSheetOptions options) {
    HashPrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(options.getPaperSize().sizeName);
    aset.add(options.getPaperSize().printableArea);
    aset.add(DialogTypeSelection.COMMON);
    PrinterJob masterPrintJob = PrinterJob.getPrinterJob();
    if (!masterPrintJob.printDialog(aset)) {
        return;
    }
    PageFormat pageFormat = masterPrintJob.getPageFormat(aset);
    // If something besides letter and A4 is selected, use the template that's closest to the aspect
    // ratio of the paper size.
    options.setPaperSize(PaperSize.closestToAspect(pageFormat.getWidth(), pageFormat.getHeight()));
    List<PrintRecordSheet> sheets = createSheets(loadedUnits, singlePrint, options);
    if (loadedUnits.size() > 1) {
        masterPrintJob.setJobName(loadedUnits.get(0).getShortNameRaw() + " etc");
    } else if (loadedUnits.size() > 0) {
        masterPrintJob.setJobName(loadedUnits.get(0).getShortNameRaw());
    }
    RecordSheetTask task = RecordSheetTask.createPrintTask(sheets, masterPrintJob, aset, pageFormat);
    task.execute(CConfig.getBooleanParam(CConfig.RS_PROGRESS_BAR));
}
Also used : PageFormat(java.awt.print.PageFormat) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrinterJob(java.awt.print.PrinterJob)

Example 34 with PrinterJob

use of java.awt.print.PrinterJob in project intellij-community by JetBrains.

the class PrintManager method executePrint.

public static void executePrint(DataContext dataContext) {
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null)
        return;
    PsiDirectory psiDirectory = null;
    PsiElement psiElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
    if (psiElement instanceof PsiDirectory) {
        psiDirectory = (PsiDirectory) psiElement;
    }
    PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(dataContext);
    String shortFileName = null;
    String directoryName = null;
    if (psiFile != null || psiDirectory != null) {
        if (psiFile != null) {
            shortFileName = psiFile.getName();
            if (psiDirectory == null) {
                psiDirectory = psiFile.getContainingDirectory();
            }
        }
        if (psiDirectory != null) {
            directoryName = psiDirectory.getVirtualFile().getPresentableUrl();
        }
    }
    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    String text = null;
    if (editor != null) {
        if (editor.getSelectionModel().hasSelection()) {
            text = CodeEditorBundle.message("print.selected.text.radio");
        } else {
            text = psiFile == null ? "Console text" : null;
        }
    }
    List<PsiFile> psiFiles = getSelectedPsiFiles(dataContext);
    PrintDialog printDialog = new PrintDialog(shortFileName, directoryName, text, psiFiles.size(), project);
    printDialog.reset();
    if (!printDialog.showAndGet()) {
        return;
    }
    printDialog.apply();
    final PageFormat pageFormat = createPageFormat();
    final BasePainter painter;
    PrintSettings printSettings = PrintSettings.getInstance();
    if (printSettings.getPrintScope() == PrintSettings.PRINT_FILE && psiFiles.size() > 1) {
        painter = new MultiFilePainter(psiFiles, printSettings.EVEN_NUMBER_OF_PAGES);
    } else if (printSettings.getPrintScope() == PrintSettings.PRINT_DIRECTORY) {
        List<PsiFile> filesList = ContainerUtil.newArrayList();
        boolean isRecursive = printSettings.isIncludeSubdirectories();
        addToPsiFileList(psiDirectory, filesList, isRecursive);
        painter = new MultiFilePainter(filesList, printSettings.EVEN_NUMBER_OF_PAGES);
    } else {
        if (psiFile == null && editor == null)
            return;
        TextPainter textPainter = psiFile != null ? initTextPainter(psiFile) : initTextPainter((DocumentEx) editor.getDocument(), project);
        if (textPainter == null)
            return;
        if (printSettings.getPrintScope() == PrintSettings.PRINT_SELECTED_TEXT && editor != null && editor.getSelectionModel().hasSelection()) {
            textPainter.setSegment(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd());
        }
        painter = textPainter;
    }
    final PrinterJob printerJob = PrinterJob.getPrinterJob();
    try {
        printerJob.setPrintable(painter, pageFormat);
        if (!printerJob.printDialog()) {
            return;
        }
    } catch (Exception e) {
        LOG.warn(e);
    }
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    ProgressManager.getInstance().run(new Task.Backgroundable(project, CodeEditorBundle.message("print.progress"), true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            try {
                painter.setProgress(indicator);
                printerJob.print();
            } catch (ProcessCanceledException e) {
                LOG.info("Cancelled");
                printerJob.cancel();
            } catch (PrinterException e) {
                LOG.warn(e);
                String message = ObjectUtils.notNull(e.getMessage(), e.getClass().getName());
                Notifications.Bus.notify(new Notification("Print", CommonBundle.getErrorTitle(), message, NotificationType.ERROR));
            } catch (Exception e) {
                LOG.error(e);
            } finally {
                painter.dispose();
            }
        }
    });
}
Also used : PrinterException(java.awt.print.PrinterException) PrinterException(java.awt.print.PrinterException) Notification(com.intellij.notification.Notification) PrinterJob(java.awt.print.PrinterJob) Project(com.intellij.openapi.project.Project) PageFormat(java.awt.print.PageFormat) ArrayList(java.util.ArrayList) List(java.util.List) Editor(com.intellij.openapi.editor.Editor)

Example 35 with PrinterJob

use of java.awt.print.PrinterJob in project adempiere by adempiere.

the class PrintUtil method testPS.

//	dump
/*************************************************************************/
/**
	 * 	Test Print Services
	 */
private static void testPS() {
    PrintService ps = getDefaultPrintService();
    ServiceUIFactory factory = ps.getServiceUIFactory();
    System.out.println(factory);
    if (factory != null) {
        System.out.println("Factory");
        JPanel p0 = (JPanel) factory.getUI(ServiceUIFactory.ABOUT_UIROLE, ServiceUIFactory.JDIALOG_UI);
        p0.setVisible(true);
        JPanel p1 = (JPanel) factory.getUI(ServiceUIFactory.ADMIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
        p1.setVisible(true);
        JPanel p2 = (JPanel) factory.getUI(ServiceUIFactory.MAIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
        p2.setVisible(true);
    }
    System.out.println("1----------");
    PrinterJob pj = PrinterJob.getPrinterJob();
    PrintRequestAttributeSet pratts = getDefaultPrintRequestAttributes();
    //	Page Dialog
    PageFormat pf = pj.pageDialog(pratts);
    System.out.println("Pratts Size = " + pratts.size());
    Attribute[] atts = pratts.toArray();
    for (int i = 0; i < atts.length; i++) System.out.println(atts[i].getName() + " = " + atts[i] + " - " + atts[i].getCategory());
    System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth() + " - Orient=" + pf.getOrientation());
    ps = pj.getPrintService();
    System.out.println("PrintService = " + ps.getName());
    //	Print Dialog
    System.out.println("2----------");
    pj.printDialog(pratts);
    System.out.println("Pratts Size = " + pratts.size());
    atts = pratts.toArray();
    for (int i = 0; i < atts.length; i++) System.out.println(atts[i].getName() + " = " + atts[i] + " - " + atts[i].getCategory());
    pf = pj.defaultPage();
    System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth() + " - Orient=" + pf.getOrientation());
    ps = pj.getPrintService();
    System.out.println("PrintService= " + ps.getName());
    System.out.println("3----------");
    try {
        pj.setPrintService(ps);
    } catch (PrinterException pe) {
        System.out.println(pe);
    }
    pf = pj.validatePage(pf);
    System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth() + " - Orient=" + pf.getOrientation());
    ps = pj.getPrintService();
    System.out.println("PrintService= " + ps.getName());
    System.out.println("4----------");
    pj.printDialog();
}
Also used : JPanel(javax.swing.JPanel) PageFormat(java.awt.print.PageFormat) Attribute(javax.print.attribute.Attribute) PrinterException(java.awt.print.PrinterException) PrintService(javax.print.PrintService) ServiceUIFactory(javax.print.ServiceUIFactory) PrinterJob(java.awt.print.PrinterJob) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet)

Aggregations

PrinterJob (java.awt.print.PrinterJob)57 PrinterException (java.awt.print.PrinterException)28 PageFormat (java.awt.print.PageFormat)22 HashPrintRequestAttributeSet (javax.print.attribute.HashPrintRequestAttributeSet)19 PrintRequestAttributeSet (javax.print.attribute.PrintRequestAttributeSet)17 PDFPageable (org.apache.pdfbox.printing.PDFPageable)9 IOException (java.io.IOException)7 Paper (java.awt.print.Paper)6 Printable (java.awt.print.Printable)5 File (java.io.File)5 Copies (javax.print.attribute.standard.Copies)5 ActionEvent (java.awt.event.ActionEvent)4 PrintService (javax.print.PrintService)4 Container (java.awt.Container)3 Book (java.awt.print.Book)3 JobName (javax.print.attribute.standard.JobName)3 PageRanges (javax.print.attribute.standard.PageRanges)3 AbstractAction (javax.swing.AbstractAction)3 JButton (javax.swing.JButton)3 JFrame (javax.swing.JFrame)3