1 /*
   2  * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /* @test
  25    @bug 8167102
  26    @summary PrintRequestAttributeSet breaks page size set using PageFormat
  27    @run main/manual WrongPaperPrintingTest
  28  */
  29 
  30 import java.awt.BorderLayout;
  31 import java.awt.Color;
  32 import java.awt.FlowLayout;
  33 import java.awt.Graphics;
  34 import java.awt.event.WindowAdapter;
  35 import java.awt.event.WindowEvent;
  36 import java.awt.print.PageFormat;
  37 import java.awt.print.Paper;
  38 import java.awt.print.Printable;
  39 import java.awt.print.PrinterException;
  40 import java.awt.print.PrinterJob;
  41 import java.util.concurrent.CountDownLatch;
  42 import java.util.concurrent.TimeUnit;
  43 import javax.print.attribute.HashPrintRequestAttributeSet;
  44 import javax.print.attribute.PrintRequestAttributeSet;
  45 import javax.print.attribute.Size2DSyntax;
  46 import javax.print.attribute.standard.Chromaticity;
  47 import javax.print.attribute.standard.MediaSize;
  48 import javax.print.attribute.standard.MediaSizeName;
  49 import javax.swing.JButton;
  50 import javax.swing.JDialog;
  51 import javax.swing.JLabel;
  52 import javax.swing.JPanel;
  53 import javax.swing.JTextArea;
  54 import javax.swing.SwingUtilities;
  55 import javax.swing.Timer;
  56 import javax.swing.WindowConstants;
  57 
  58 public class WrongPaperPrintingTest implements Printable {
  59     private static final CountDownLatch testEndedSignal = new CountDownLatch(1);
  60     private static final int testTimeout = 300000;
  61     private static volatile String testFailureMsg;
  62     private static volatile boolean testPassed;
  63     private static volatile boolean testFinished;
  64 
  65     public static void main(String[] args) {
  66         SwingUtilities.invokeLater(() -> createAndShowTestDialog());
  67 
  68         try {
  69             if (!testEndedSignal.await(testTimeout, TimeUnit.MILLISECONDS)) {
  70                 throw new RuntimeException(String.format(
  71                     "Test timeout '%d ms' elapsed.", testTimeout));
  72             }
  73             if (!testPassed) {
  74                 String failureMsg = testFailureMsg;
  75                 if ((failureMsg != null) && (!failureMsg.trim().isEmpty())) {
  76                     throw new RuntimeException(failureMsg);
  77                 } else {
  78                     throw new RuntimeException("Test failed.");
  79                 }
  80             }
  81         } catch (InterruptedException ie) {
  82             throw new RuntimeException(ie);
  83         } finally {
  84             testFinished = true;
  85         }
  86     }
  87 
  88     private static void doTest() {
  89         PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
  90         aset.add(Chromaticity.MONOCHROME);
  91 
  92         MediaSize isoA5Size = MediaSize.getMediaSizeForName(MediaSizeName.ISO_A5);
  93         float[] size = isoA5Size.getSize(Size2DSyntax.INCH);
  94         Paper paper = new Paper();
  95         paper.setSize(size[0] * 72.0, size[1] * 72.0);
  96         paper.setImageableArea(0.0, 0.0, size[0] * 72.0, size[1] * 72.0);
  97         PageFormat pf = new PageFormat();
  98         pf.setPaper(paper);
  99 
 100         PrinterJob job = PrinterJob.getPrinterJob();
 101         job.setPrintable(new WrongPaperPrintingTest(), job.validatePage(pf));
 102         if (job.printDialog()) {
 103             try {
 104                 job.print(aset);
 105             } catch (PrinterException pe) {
 106                 throw new RuntimeException(pe);
 107             }
 108         }
 109     }
 110 
 111     private static void pass() {
 112         testPassed = true;
 113         testEndedSignal.countDown();
 114     }
 115 
 116     private static void fail(String failureMsg) {
 117         testFailureMsg = failureMsg;
 118         testPassed = false;
 119         testEndedSignal.countDown();
 120     }
 121 
 122     private static String convertMillisToTimeStr(int millis) {
 123         if (millis < 0) {
 124             return "00:00:00";
 125         }
 126         int hours = millis / 3600000;
 127         int minutes = (millis - hours * 3600000) / 60000;
 128         int seconds = (millis - hours * 3600000 - minutes * 60000) / 1000;
 129         return String.format("%02d:%02d:%02d", hours, minutes, seconds);
 130     }
 131 
 132     private static void createAndShowTestDialog() {
 133         String description =
 134             " To run this test it is required to have a virtual PDF\r\n" +
 135             " printer or any other printer supporting A5 paper size.\r\n" +
 136             "\r\n" +
 137             " 1. Verify that NOT A5 paper size is set as default for the\r\n" +
 138             " printer to be used.\r\n" +
 139             " 2. Click on \"Start Test\" button.\r\n" +
 140             " 3. In the shown print dialog select the printer and click\r\n" +
 141             " on \"Print\" button.\r\n" +
 142             " 4. Verify that a page with a drawn rectangle is printed on\r\n" +
 143             " a paper of A5 size which is (5.8 x 8.3 in) or\r\n" +
 144             " (148 x 210 mm).\r\n" +
 145             "\r\n" +
 146             " If the printed page size is correct, click on \"PASS\"\r\n" +
 147             " button, otherwise click on \"FAIL\" button.";
 148 
 149         final JDialog dialog = new JDialog();
 150         dialog.setTitle("WrongPaperPrintingTest");
 151         dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
 152         dialog.addWindowListener(new WindowAdapter() {
 153             @Override
 154             public void windowClosing(WindowEvent e) {
 155                 dialog.dispose();
 156                 fail("Main dialog was closed.");
 157             }
 158         });
 159 
 160         final JLabel testTimeoutLabel = new JLabel(String.format(
 161             "Test timeout: %s", convertMillisToTimeStr(testTimeout)));
 162         final long startTime = System.currentTimeMillis();
 163         final Timer timer = new Timer(0, null);
 164         timer.setDelay(1000);
 165         timer.addActionListener((e) -> {
 166             int leftTime = testTimeout - (int)(System.currentTimeMillis() - startTime);
 167             if ((leftTime < 0) || testFinished) {
 168                 timer.stop();
 169                 dialog.dispose();
 170             }
 171             testTimeoutLabel.setText(String.format(
 172                 "Test timeout: %s", convertMillisToTimeStr(leftTime)));
 173         });
 174         timer.start();
 175 
 176         JTextArea textArea = new JTextArea(description);
 177         textArea.setEditable(false);
 178 
 179         final JButton testButton = new JButton("Start Test");
 180         final JButton passButton = new JButton("PASS");
 181         final JButton failButton = new JButton("FAIL");
 182         testButton.addActionListener((e) -> {
 183             testButton.setEnabled(false);
 184             new Thread(() -> {
 185                 try {
 186                     doTest();
 187 
 188                     SwingUtilities.invokeLater(() -> {
 189                         passButton.setEnabled(true);
 190                         failButton.setEnabled(true);
 191                     });
 192                 } catch (Throwable t) {
 193                     t.printStackTrace();
 194                     dialog.dispose();
 195                     fail("Exception occurred in a thread executing the test.");
 196                 }
 197             }).start();
 198         });
 199         passButton.setEnabled(false);
 200         passButton.addActionListener((e) -> {
 201             dialog.dispose();
 202             pass();
 203         });
 204         failButton.setEnabled(false);
 205         failButton.addActionListener((e) -> {
 206             dialog.dispose();
 207             fail("Size of a printed page is wrong.");
 208         });
 209 
 210         JPanel mainPanel = new JPanel(new BorderLayout());
 211         JPanel labelPanel = new JPanel(new FlowLayout());
 212         labelPanel.add(testTimeoutLabel);
 213         mainPanel.add(labelPanel, BorderLayout.NORTH);
 214         mainPanel.add(textArea, BorderLayout.CENTER);
 215         JPanel buttonPanel = new JPanel(new FlowLayout());
 216         buttonPanel.add(testButton);
 217         buttonPanel.add(passButton);
 218         buttonPanel.add(failButton);
 219         mainPanel.add(buttonPanel, BorderLayout.SOUTH);
 220         dialog.add(mainPanel);
 221 
 222         dialog.pack();
 223         dialog.setVisible(true);
 224     }
 225 
 226     @Override
 227     public int print(Graphics g, PageFormat pf, int pageIndex)
 228         throws PrinterException {
 229         if (pageIndex == 0) {
 230             g.setColor(Color.RED);
 231             g.drawRect((int)pf.getImageableX(), (int)pf.getImageableY(),
 232                 (int)pf.getImageableWidth(), (int)pf.getImageableHeight());
 233             return Printable.PAGE_EXISTS;
 234         } else {
 235             return Printable.NO_SUCH_PAGE;
 236         }
 237     }
 238 }