1 /* 2 * Copyright (c) 2000, 2019, 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. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package sun.print; 27 28 import java.awt.BorderLayout; 29 import java.awt.Color; 30 import java.awt.Component; 31 import java.awt.Container; 32 import java.awt.Dialog; 33 import java.awt.FlowLayout; 34 import java.awt.Frame; 35 import java.awt.GraphicsConfiguration; 36 import java.awt.GridBagLayout; 37 import java.awt.GridBagConstraints; 38 import java.awt.GridLayout; 39 import java.awt.Insets; 40 import java.awt.Toolkit; 41 import java.awt.Window; 42 import java.awt.event.ActionEvent; 43 import java.awt.event.ActionListener; 44 import java.awt.event.FocusEvent; 45 import java.awt.event.FocusListener; 46 import java.awt.event.ItemEvent; 47 import java.awt.event.ItemListener; 48 import java.awt.event.WindowEvent; 49 import java.awt.event.WindowAdapter; 50 import java.awt.print.PrinterJob; 51 import java.io.File; 52 import java.io.FilePermission; 53 import java.io.IOException; 54 import java.net.URI; 55 import java.net.URL; 56 import java.text.DecimalFormat; 57 import java.util.Locale; 58 import java.util.ResourceBundle; 59 import java.util.Vector; 60 import javax.print.*; 61 import javax.print.attribute.*; 62 import javax.print.attribute.standard.*; 63 import javax.swing.*; 64 import javax.swing.border.Border; 65 import javax.swing.border.EmptyBorder; 66 import javax.swing.border.TitledBorder; 67 import javax.swing.event.ChangeEvent; 68 import javax.swing.event.ChangeListener; 69 import javax.swing.event.DocumentEvent; 70 import javax.swing.event.DocumentListener; 71 import javax.swing.event.PopupMenuEvent; 72 import javax.swing.event.PopupMenuListener; 73 import javax.swing.text.NumberFormatter; 74 import sun.print.SunPageSelection; 75 import java.awt.event.KeyEvent; 76 import java.net.URISyntaxException; 77 import java.lang.reflect.Field; 78 import java.net.MalformedURLException; 79 80 /** 81 * A class which implements a cross-platform print dialog. 82 * 83 * @author Chris Campbell 84 */ 85 @SuppressWarnings("serial") // Superclass is not serializable across versions 86 public class ServiceDialog extends JDialog implements ActionListener { 87 88 /** 89 * Waiting print status (user response pending). 90 */ 91 public static final int WAITING = 0; 92 93 /** 94 * Approve print status (user activated "Print" or "OK"). 95 */ 96 public static final int APPROVE = 1; 97 98 /** 99 * Cancel print status (user activated "Cancel"); 100 */ 101 public static final int CANCEL = 2; 102 103 private static final String strBundle = "sun.print.resources.serviceui"; 104 private static final Insets panelInsets = new Insets(6, 6, 6, 6); 105 private static final Insets compInsets = new Insets(3, 6, 3, 6); 106 107 private static ResourceBundle messageRB; 108 private JTabbedPane tpTabs; 109 private JButton btnCancel, btnApprove; 110 private PrintService[] services; 111 private int defaultServiceIndex; 112 private PrintRequestAttributeSet asOriginal; 113 private HashPrintRequestAttributeSet asCurrent; 114 private PrintService psCurrent; 115 private DocFlavor docFlavor; 116 private int status; 117 118 private ValidatingFileChooser jfc; 119 120 private GeneralPanel pnlGeneral; 121 private PageSetupPanel pnlPageSetup; 122 private AppearancePanel pnlAppearance; 123 124 private boolean isAWT = false; 125 static { 126 initResource(); 127 } 128 129 130 /** 131 * Constructor for the "standard" print dialog (containing all relevant 132 * tabs) 133 */ 134 public ServiceDialog(GraphicsConfiguration gc, 135 int x, int y, 136 PrintService[] services, 137 int defaultServiceIndex, 138 DocFlavor flavor, 139 PrintRequestAttributeSet attributes, 140 Window window) 141 { 142 super(window, getMsg("dialog.printtitle"), Dialog.DEFAULT_MODALITY_TYPE, gc); 143 initPrintDialog(x, y, services, defaultServiceIndex, 144 flavor, attributes); 145 } 146 147 /** 148 * Initialize print dialog. 149 */ 150 void initPrintDialog(int x, int y, 151 PrintService[] services, 152 int defaultServiceIndex, 153 DocFlavor flavor, 154 PrintRequestAttributeSet attributes) 155 { 156 this.services = services; 157 this.defaultServiceIndex = defaultServiceIndex; 158 this.asOriginal = attributes; 159 this.asCurrent = new HashPrintRequestAttributeSet(attributes); 160 this.psCurrent = services[defaultServiceIndex]; 161 this.docFlavor = flavor; 162 SunPageSelection pages = 163 (SunPageSelection)attributes.get(SunPageSelection.class); 164 if (pages != null) { 165 isAWT = true; 166 } 167 168 if (attributes.get(DialogOwner.class) != null) { 169 DialogOwner owner = (DialogOwner)attributes.get(DialogOwner.class); 170 /* When the ServiceDialog is constructed the caller of the 171 * constructor checks for this attribute and if it specifies a 172 * window then it will use that in the constructor instead of 173 * inferring one from keyboard focus. 174 * In this case the owner of the dialog is the same as that 175 * specified in the attribute and we do not need to set the 176 * on top property 177 */ 178 if ((getOwner() == null) || (owner.getOwner() != getOwner())) { 179 try { 180 setAlwaysOnTop(true); 181 } catch (SecurityException e) { 182 } 183 } 184 } 185 Container c = getContentPane(); 186 c.setLayout(new BorderLayout()); 187 188 tpTabs = new JTabbedPane(); 189 tpTabs.setBorder(new EmptyBorder(5, 5, 5, 5)); 190 191 String gkey = getMsg("tab.general"); 192 int gmnemonic = getVKMnemonic("tab.general"); 193 pnlGeneral = new GeneralPanel(); 194 tpTabs.add(gkey, pnlGeneral); 195 tpTabs.setMnemonicAt(0, gmnemonic); 196 197 String pkey = getMsg("tab.pagesetup"); 198 int pmnemonic = getVKMnemonic("tab.pagesetup"); 199 pnlPageSetup = new PageSetupPanel(); 200 tpTabs.add(pkey, pnlPageSetup); 201 tpTabs.setMnemonicAt(1, pmnemonic); 202 203 String akey = getMsg("tab.appearance"); 204 int amnemonic = getVKMnemonic("tab.appearance"); 205 pnlAppearance = new AppearancePanel(); 206 tpTabs.add(akey, pnlAppearance); 207 tpTabs.setMnemonicAt(2, amnemonic); 208 209 c.add(tpTabs, BorderLayout.CENTER); 210 211 updatePanels(); 212 213 JPanel pnlSouth = new JPanel(new FlowLayout(FlowLayout.TRAILING)); 214 btnApprove = createExitButton("button.print", this); 215 pnlSouth.add(btnApprove); 216 getRootPane().setDefaultButton(btnApprove); 217 btnCancel = createExitButton("button.cancel", this); 218 handleEscKey(btnCancel); 219 pnlSouth.add(btnCancel); 220 c.add(pnlSouth, BorderLayout.SOUTH); 221 222 addWindowListener(new WindowAdapter() { 223 public void windowClosing(WindowEvent event) { 224 dispose(CANCEL); 225 } 226 }); 227 228 getAccessibleContext().setAccessibleDescription(getMsg("dialog.printtitle")); 229 setResizable(false); 230 setLocation(x, y); 231 pack(); 232 } 233 234 /** 235 * Constructor for the solitary "page setup" dialog 236 */ 237 public ServiceDialog(GraphicsConfiguration gc, 238 int x, int y, 239 PrintService ps, 240 DocFlavor flavor, 241 PrintRequestAttributeSet attributes, 242 Window window) 243 { 244 super(window, getMsg("dialog.pstitle"), Dialog.DEFAULT_MODALITY_TYPE, gc); 245 initPageDialog(x, y, ps, flavor, attributes); 246 } 247 248 /** 249 * Initialize "page setup" dialog 250 */ 251 void initPageDialog(int x, int y, 252 PrintService ps, 253 DocFlavor flavor, 254 PrintRequestAttributeSet attributes) 255 { 256 this.psCurrent = ps; 257 this.docFlavor = flavor; 258 this.asOriginal = attributes; 259 this.asCurrent = new HashPrintRequestAttributeSet(attributes); 260 261 if (attributes.get(DialogOwner.class) != null) { 262 /* See comments in same block in initPrintDialog */ 263 DialogOwner owner = (DialogOwner)attributes.get(DialogOwner.class); 264 if ((getOwner() == null) || (owner.getOwner() != getOwner())) { 265 try { 266 setAlwaysOnTop(true); 267 } catch (SecurityException e) { 268 } 269 } 270 } 271 272 Container c = getContentPane(); 273 c.setLayout(new BorderLayout()); 274 275 pnlPageSetup = new PageSetupPanel(); 276 c.add(pnlPageSetup, BorderLayout.CENTER); 277 278 pnlPageSetup.updateInfo(); 279 280 JPanel pnlSouth = new JPanel(new FlowLayout(FlowLayout.TRAILING)); 281 btnApprove = createExitButton("button.ok", this); 282 pnlSouth.add(btnApprove); 283 getRootPane().setDefaultButton(btnApprove); 284 btnCancel = createExitButton("button.cancel", this); 285 handleEscKey(btnCancel); 286 pnlSouth.add(btnCancel); 287 c.add(pnlSouth, BorderLayout.SOUTH); 288 289 addWindowListener(new WindowAdapter() { 290 public void windowClosing(WindowEvent event) { 291 dispose(CANCEL); 292 } 293 }); 294 295 getAccessibleContext().setAccessibleDescription(getMsg("dialog.pstitle")); 296 setResizable(false); 297 setLocation(x, y); 298 pack(); 299 } 300 301 /** 302 * Performs Cancel when Esc key is pressed. 303 */ 304 private void handleEscKey(JButton btnCancel) { 305 @SuppressWarnings("serial") // anonymous class 306 Action cancelKeyAction = new AbstractAction() { 307 public void actionPerformed(ActionEvent e) { 308 dispose(CANCEL); 309 } 310 }; 311 KeyStroke cancelKeyStroke = 312 KeyStroke.getKeyStroke((char)KeyEvent.VK_ESCAPE, 0); 313 InputMap inputMap = 314 btnCancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); 315 ActionMap actionMap = btnCancel.getActionMap(); 316 317 if (inputMap != null && actionMap != null) { 318 inputMap.put(cancelKeyStroke, "cancel"); 319 actionMap.put("cancel", cancelKeyAction); 320 } 321 } 322 323 324 /** 325 * Returns the current status of the dialog (whether the user has selected 326 * the "Print" or "Cancel" button) 327 */ 328 public int getStatus() { 329 return status; 330 } 331 332 /** 333 * Returns an AttributeSet based on whether or not the user cancelled the 334 * dialog. If the user selected "Print" we return their new selections, 335 * otherwise we return the attributes that were passed in initially. 336 */ 337 public PrintRequestAttributeSet getAttributes() { 338 if (status == APPROVE) { 339 return asCurrent; 340 } else { 341 return asOriginal; 342 } 343 } 344 345 /** 346 * Returns a PrintService based on whether or not the user cancelled the 347 * dialog. If the user selected "Print" we return the user's selection 348 * for the PrintService, otherwise we return null. 349 */ 350 public PrintService getPrintService() { 351 if (status == APPROVE) { 352 return psCurrent; 353 } else { 354 return null; 355 } 356 } 357 358 /** 359 * Sets the current status flag for the dialog and disposes it (thus 360 * returning control of the parent frame back to the user) 361 */ 362 public void dispose(int status) { 363 this.status = status; 364 365 super.dispose(); 366 } 367 368 public void actionPerformed(ActionEvent e) { 369 Object source = e.getSource(); 370 boolean approved = false; 371 372 if (source == btnApprove) { 373 approved = true; 374 375 if (pnlGeneral != null) { 376 if (pnlGeneral.isPrintToFileRequested()) { 377 approved = showFileChooser(); 378 } else { 379 asCurrent.remove(Destination.class); 380 } 381 } 382 } 383 384 dispose(approved ? APPROVE : CANCEL); 385 } 386 387 /** 388 * Displays a JFileChooser that allows the user to select the destination 389 * for "Print To File" 390 */ 391 private boolean showFileChooser() { 392 Class<Destination> dstCategory = Destination.class; 393 394 Destination dst = (Destination)asCurrent.get(dstCategory); 395 if (dst == null) { 396 dst = (Destination)asOriginal.get(dstCategory); 397 if (dst == null) { 398 dst = (Destination)psCurrent.getDefaultAttributeValue(dstCategory); 399 // "dst" should not be null. The following code 400 // is only added to safeguard against a possible 401 // buggy implementation of a PrintService having a 402 // null default Destination. 403 if (dst == null) { 404 try { 405 dst = new Destination(new URI("file:out.prn")); 406 } catch (URISyntaxException e) { 407 } 408 } 409 } 410 } 411 412 File fileDest; 413 if (dst != null) { 414 try { 415 fileDest = new File(dst.getURI()); 416 } catch (Exception e) { 417 // all manner of runtime exceptions possible 418 fileDest = new File("out.prn"); 419 } 420 } else { 421 fileDest = new File("out.prn"); 422 } 423 424 ValidatingFileChooser jfc = new ValidatingFileChooser(); 425 jfc.setApproveButtonText(getMsg("button.ok")); 426 jfc.setDialogTitle(getMsg("dialog.printtofile")); 427 jfc.setDialogType(JFileChooser.SAVE_DIALOG); 428 jfc.setSelectedFile(fileDest); 429 430 int returnVal = jfc.showDialog(this, null); 431 if (returnVal == JFileChooser.APPROVE_OPTION) { 432 fileDest = jfc.getSelectedFile(); 433 434 try { 435 asCurrent.add(new Destination(fileDest.toURI())); 436 } catch (Exception e) { 437 asCurrent.remove(dstCategory); 438 } 439 } else { 440 asCurrent.remove(dstCategory); 441 } 442 443 return (returnVal == JFileChooser.APPROVE_OPTION); 444 } 445 446 /** 447 * Updates each of the top level panels 448 */ 449 private void updatePanels() { 450 pnlGeneral.updateInfo(); 451 pnlPageSetup.updateInfo(); 452 pnlAppearance.updateInfo(); 453 } 454 455 /** 456 * Initialize ResourceBundle 457 */ 458 public static void initResource() { 459 java.security.AccessController.doPrivileged( 460 new java.security.PrivilegedAction<Object>() { 461 public Object run() { 462 try { 463 messageRB = ResourceBundle.getBundle(strBundle); 464 return null; 465 } catch (java.util.MissingResourceException e) { 466 throw new Error("Fatal: Resource for ServiceUI " + 467 "is missing"); 468 } 469 } 470 } 471 ); 472 } 473 474 /** 475 * Returns message string from resource 476 */ 477 public static String getMsg(String key) { 478 try { 479 return removeMnemonics(messageRB.getString(key)); 480 } catch (java.util.MissingResourceException e) { 481 throw new Error("Fatal: Resource for ServiceUI is broken; " + 482 "there is no " + key + " key in resource"); 483 } 484 } 485 486 private static String removeMnemonics(String s) { 487 int i = s.indexOf('&'); 488 int len = s.length(); 489 if (i < 0 || i == (len - 1)) { 490 return s; 491 } 492 int j = s.indexOf('&', i+1); 493 if (j == i+1) { 494 if (j+1 == len) { 495 return s.substring(0, i+1); // string ends with && 496 } else { 497 return s.substring(0, i+1) + removeMnemonics(s.substring(j+1)); 498 } 499 } 500 // ok first & not double && 501 if (i == 0) { 502 return removeMnemonics(s.substring(1)); 503 } else { 504 return (s.substring(0, i) + removeMnemonics(s.substring(i+1))); 505 } 506 } 507 508 509 /** 510 * Returns mnemonic character from resource 511 */ 512 private static char getMnemonic(String key) { 513 String str = messageRB.getString(key).replace("&&", ""); 514 int index = str.indexOf('&'); 515 if (0 <= index && index < str.length() - 1) { 516 char c = str.charAt(index + 1); 517 return Character.toUpperCase(c); 518 } else { 519 return (char)0; 520 } 521 } 522 523 /** 524 * Returns the mnemonic as a KeyEvent.VK constant from the resource. 525 */ 526 static Class<?> _keyEventClazz = null; 527 private static int getVKMnemonic(String key) { 528 String s = String.valueOf(getMnemonic(key)); 529 if ( s == null || s.length() != 1) { 530 return 0; 531 } 532 String vkString = "VK_" + s.toUpperCase(); 533 534 try { 535 if (_keyEventClazz == null) { 536 _keyEventClazz= Class.forName("java.awt.event.KeyEvent", 537 true, (ServiceDialog.class).getClassLoader()); 538 } 539 Field field = _keyEventClazz.getDeclaredField(vkString); 540 int value = field.getInt(null); 541 return value; 542 } catch (Exception e) { 543 } 544 return 0; 545 } 546 547 /** 548 * Returns URL for image resource 549 */ 550 private static URL getImageResource(final String key) { 551 URL url = java.security.AccessController.doPrivileged( 552 new java.security.PrivilegedAction<URL>() { 553 public URL run() { 554 URL url = ServiceDialog.class.getResource( 555 "resources/" + key); 556 return url; 557 } 558 }); 559 560 if (url == null) { 561 throw new Error("Fatal: Resource for ServiceUI is broken; " + 562 "there is no " + key + " key in resource"); 563 } 564 565 return url; 566 } 567 568 /** 569 * Creates a new JButton and sets its text, mnemonic, and ActionListener 570 */ 571 private static JButton createButton(String key, ActionListener al) { 572 JButton btn = new JButton(getMsg(key)); 573 btn.setMnemonic(getMnemonic(key)); 574 btn.addActionListener(al); 575 576 return btn; 577 } 578 579 /** 580 * Creates a new JButton and sets its text, and ActionListener 581 */ 582 private static JButton createExitButton(String key, ActionListener al) { 583 String str = getMsg(key); 584 JButton btn = new JButton(str); 585 btn.addActionListener(al); 586 btn.getAccessibleContext().setAccessibleDescription(str); 587 return btn; 588 } 589 590 /** 591 * Creates a new JCheckBox and sets its text, mnemonic, and ActionListener 592 */ 593 private static JCheckBox createCheckBox(String key, ActionListener al) { 594 JCheckBox cb = new JCheckBox(getMsg(key)); 595 cb.setMnemonic(getMnemonic(key)); 596 cb.addActionListener(al); 597 598 return cb; 599 } 600 601 /** 602 * Creates a new JRadioButton and sets its text, mnemonic, 603 * and ActionListener 604 */ 605 private static JRadioButton createRadioButton(String key, 606 ActionListener al) 607 { 608 JRadioButton rb = new JRadioButton(getMsg(key)); 609 rb.setMnemonic(getMnemonic(key)); 610 rb.addActionListener(al); 611 612 return rb; 613 } 614 615 /** 616 * Creates a pop-up dialog for "no print service" 617 */ 618 public static void showNoPrintService(GraphicsConfiguration gc) 619 { 620 Frame dlgFrame = new Frame(gc); 621 JOptionPane.showMessageDialog(dlgFrame, 622 getMsg("dialog.noprintermsg")); 623 dlgFrame.dispose(); 624 } 625 626 /** 627 * Sets the constraints for the GridBagLayout and adds the Component 628 * to the given Container 629 */ 630 private static void addToGB(Component comp, Container cont, 631 GridBagLayout gridbag, 632 GridBagConstraints constraints) 633 { 634 gridbag.setConstraints(comp, constraints); 635 cont.add(comp); 636 } 637 638 /** 639 * Adds the AbstractButton to both the given ButtonGroup and Container 640 */ 641 private static void addToBG(AbstractButton button, Container cont, 642 ButtonGroup bg) 643 { 644 bg.add(button); 645 cont.add(button); 646 } 647 648 649 650 651 /** 652 * The "General" tab. Includes the controls for PrintService, 653 * PageRange, and Copies/Collate. 654 */ 655 @SuppressWarnings("serial") // Superclass is not serializable across versions 656 private class GeneralPanel extends JPanel { 657 658 private PrintServicePanel pnlPrintService; 659 private PrintRangePanel pnlPrintRange; 660 private CopiesPanel pnlCopies; 661 662 public GeneralPanel() { 663 super(); 664 665 GridBagLayout gridbag = new GridBagLayout(); 666 GridBagConstraints c = new GridBagConstraints(); 667 668 setLayout(gridbag); 669 670 c.fill = GridBagConstraints.BOTH; 671 c.insets = panelInsets; 672 c.weightx = 1.0; 673 c.weighty = 1.0; 674 675 c.gridwidth = GridBagConstraints.REMAINDER; 676 pnlPrintService = new PrintServicePanel(); 677 addToGB(pnlPrintService, this, gridbag, c); 678 679 c.gridwidth = GridBagConstraints.RELATIVE; 680 pnlPrintRange = new PrintRangePanel(); 681 addToGB(pnlPrintRange, this, gridbag, c); 682 683 c.gridwidth = GridBagConstraints.REMAINDER; 684 pnlCopies = new CopiesPanel(); 685 addToGB(pnlCopies, this, gridbag, c); 686 } 687 688 public boolean isPrintToFileRequested() { 689 return (pnlPrintService.isPrintToFileSelected()); 690 } 691 692 public void updateInfo() { 693 pnlPrintService.updateInfo(); 694 pnlPrintRange.updateInfo(); 695 pnlCopies.updateInfo(); 696 } 697 } 698 699 @SuppressWarnings("serial") // Superclass is not serializable across versions 700 private class PrintServicePanel extends JPanel 701 implements ActionListener, ItemListener, PopupMenuListener 702 { 703 private final String strTitle = getMsg("border.printservice"); 704 private FilePermission printToFilePermission; 705 private JButton btnProperties; 706 private JCheckBox cbPrintToFile; 707 private JComboBox<String> cbName; 708 private JLabel lblType, lblStatus, lblInfo; 709 private ServiceUIFactory uiFactory; 710 private boolean changedService = false; 711 private boolean filePermission; 712 713 public PrintServicePanel() { 714 super(); 715 716 uiFactory = psCurrent.getServiceUIFactory(); 717 718 GridBagLayout gridbag = new GridBagLayout(); 719 GridBagConstraints c = new GridBagConstraints(); 720 721 setLayout(gridbag); 722 setBorder(BorderFactory.createTitledBorder(strTitle)); 723 724 String[] psnames = new String[services.length]; 725 for (int i = 0; i < psnames.length; i++) { 726 psnames[i] = services[i].getName(); 727 } 728 cbName = new JComboBox<>(psnames); 729 cbName.setSelectedIndex(defaultServiceIndex); 730 cbName.addItemListener(this); 731 cbName.addPopupMenuListener(this); 732 733 c.fill = GridBagConstraints.BOTH; 734 c.insets = compInsets; 735 736 c.weightx = 0.0; 737 JLabel lblName = new JLabel(getMsg("label.psname"), JLabel.TRAILING); 738 lblName.setDisplayedMnemonic(getMnemonic("label.psname")); 739 lblName.setLabelFor(cbName); 740 addToGB(lblName, this, gridbag, c); 741 c.weightx = 1.0; 742 c.gridwidth = GridBagConstraints.RELATIVE; 743 addToGB(cbName, this, gridbag, c); 744 c.weightx = 0.0; 745 c.gridwidth = GridBagConstraints.REMAINDER; 746 btnProperties = createButton("button.properties", this); 747 addToGB(btnProperties, this, gridbag, c); 748 749 c.weighty = 1.0; 750 lblStatus = addLabel(getMsg("label.status"), gridbag, c); 751 lblStatus.setLabelFor(null); 752 753 lblType = addLabel(getMsg("label.pstype"), gridbag, c); 754 lblType.setLabelFor(null); 755 756 c.gridwidth = 1; 757 addToGB(new JLabel(getMsg("label.info"), JLabel.TRAILING), 758 this, gridbag, c); 759 c.gridwidth = GridBagConstraints.RELATIVE; 760 lblInfo = new JLabel(); 761 lblInfo.setLabelFor(null); 762 763 addToGB(lblInfo, this, gridbag, c); 764 765 c.gridwidth = GridBagConstraints.REMAINDER; 766 cbPrintToFile = createCheckBox("checkbox.printtofile", this); 767 addToGB(cbPrintToFile, this, gridbag, c); 768 769 filePermission = allowedToPrintToFile(); 770 } 771 772 public boolean isPrintToFileSelected() { 773 return cbPrintToFile.isSelected(); 774 } 775 776 private JLabel addLabel(String text, 777 GridBagLayout gridbag, GridBagConstraints c) 778 { 779 c.gridwidth = 1; 780 addToGB(new JLabel(text, JLabel.TRAILING), this, gridbag, c); 781 782 c.gridwidth = GridBagConstraints.REMAINDER; 783 JLabel label = new JLabel(); 784 addToGB(label, this, gridbag, c); 785 786 return label; 787 } 788 789 @SuppressWarnings("deprecation") 790 public void actionPerformed(ActionEvent e) { 791 Object source = e.getSource(); 792 793 if (source == btnProperties) { 794 if (uiFactory != null) { 795 JDialog dialog = (JDialog)uiFactory.getUI( 796 ServiceUIFactory.MAIN_UIROLE, 797 ServiceUIFactory.JDIALOG_UI); 798 799 if (dialog != null) { 800 dialog.show(); 801 } else { 802 DocumentPropertiesUI docPropertiesUI = null; 803 try { 804 docPropertiesUI = 805 (DocumentPropertiesUI)uiFactory.getUI 806 (DocumentPropertiesUI.DOCUMENTPROPERTIES_ROLE, 807 DocumentPropertiesUI.DOCPROPERTIESCLASSNAME); 808 } catch (Exception ex) { 809 } 810 if (docPropertiesUI != null) { 811 PrinterJobWrapper wrapper = (PrinterJobWrapper) 812 asCurrent.get(PrinterJobWrapper.class); 813 if (wrapper == null) { 814 return; // should not happen, defensive only. 815 } 816 PrinterJob job = wrapper.getPrinterJob(); 817 if (job == null) { 818 return; // should not happen, defensive only. 819 } 820 PrintRequestAttributeSet newAttrs = 821 docPropertiesUI.showDocumentProperties 822 (job, ServiceDialog.this, psCurrent, asCurrent); 823 if (newAttrs != null) { 824 asCurrent.addAll(newAttrs); 825 updatePanels(); 826 } 827 } 828 } 829 } 830 } 831 } 832 833 public void itemStateChanged(ItemEvent e) { 834 if (e.getStateChange() == ItemEvent.SELECTED) { 835 int index = cbName.getSelectedIndex(); 836 837 if ((index >= 0) && (index < services.length)) { 838 if (!services[index].equals(psCurrent)) { 839 psCurrent = services[index]; 840 uiFactory = psCurrent.getServiceUIFactory(); 841 changedService = true; 842 843 Destination dest = 844 (Destination)asOriginal.get(Destination.class); 845 // to preserve the state of Print To File 846 if ((dest != null || isPrintToFileSelected()) 847 && psCurrent.isAttributeCategorySupported( 848 Destination.class)) { 849 850 if (dest != null) { 851 asCurrent.add(dest); 852 } else { 853 dest = (Destination)psCurrent. 854 getDefaultAttributeValue(Destination.class); 855 // "dest" should not be null. The following code 856 // is only added to safeguard against a possible 857 // buggy implementation of a PrintService having a 858 // null default Destination. 859 if (dest == null) { 860 try { 861 dest = 862 new Destination(new URI("file:out.prn")); 863 } catch (URISyntaxException ue) { 864 } 865 } 866 867 if (dest != null) { 868 asCurrent.add(dest); 869 } 870 } 871 } else { 872 asCurrent.remove(Destination.class); 873 } 874 } 875 } 876 } 877 } 878 879 public void popupMenuWillBecomeVisible(PopupMenuEvent e) { 880 changedService = false; 881 } 882 883 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { 884 if (changedService) { 885 changedService = false; 886 updatePanels(); 887 } 888 } 889 890 public void popupMenuCanceled(PopupMenuEvent e) { 891 } 892 893 /** 894 * We disable the "Print To File" checkbox if this returns false 895 */ 896 private boolean allowedToPrintToFile() { 897 try { 898 throwPrintToFile(); 899 return true; 900 } catch (SecurityException e) { 901 return false; 902 } 903 } 904 905 /** 906 * Break this out as it may be useful when we allow API to 907 * specify printing to a file. In that case its probably right 908 * to throw a SecurityException if the permission is not granted. 909 */ 910 private void throwPrintToFile() { 911 SecurityManager security = System.getSecurityManager(); 912 if (security != null) { 913 if (printToFilePermission == null) { 914 printToFilePermission = 915 new FilePermission("<<ALL FILES>>", "read,write"); 916 } 917 security.checkPermission(printToFilePermission); 918 } 919 } 920 921 public void updateInfo() { 922 Class<Destination> dstCategory = Destination.class; 923 boolean dstSupported = false; 924 boolean dstSelected = false; 925 boolean dstAllowed = filePermission ? 926 allowedToPrintToFile() : false; 927 928 // setup Destination (print-to-file) widgets 929 Destination dst = (Destination)asCurrent.get(dstCategory); 930 if (dst != null) { 931 try { 932 dst.getURI().toURL(); 933 if (psCurrent.isAttributeValueSupported(dst, docFlavor, 934 asCurrent)) { 935 dstSupported = true; 936 dstSelected = true; 937 } 938 } catch (MalformedURLException ex) { 939 dstSupported = true; 940 } 941 } else { 942 if (psCurrent.isAttributeCategorySupported(dstCategory)) { 943 dstSupported = true; 944 } 945 } 946 cbPrintToFile.setEnabled(dstSupported && dstAllowed); 947 cbPrintToFile.setSelected(dstSelected && dstAllowed 948 && dstSupported); 949 950 // setup PrintService information widgets 951 Attribute type = psCurrent.getAttribute(PrinterMakeAndModel.class); 952 if (type != null) { 953 lblType.setText(type.toString()); 954 } 955 Attribute status = 956 psCurrent.getAttribute(PrinterIsAcceptingJobs.class); 957 if (status != null) { 958 lblStatus.setText(getMsg(status.toString())); 959 } 960 Attribute info = psCurrent.getAttribute(PrinterInfo.class); 961 if (info != null) { 962 lblInfo.setText(info.toString()); 963 } 964 btnProperties.setEnabled(uiFactory != null); 965 } 966 } 967 968 @SuppressWarnings("serial") // Superclass is not serializable across versions 969 private class PrintRangePanel extends JPanel 970 implements ActionListener, FocusListener 971 { 972 private final String strTitle = getMsg("border.printrange"); 973 private final PageRanges prAll = new PageRanges(1, Integer.MAX_VALUE); 974 private JRadioButton rbAll, rbPages, rbSelect; 975 private JFormattedTextField tfRangeFrom, tfRangeTo; 976 private JLabel lblRangeTo; 977 private boolean prSupported; 978 private boolean prPgRngSupported; 979 980 public PrintRangePanel() { 981 super(); 982 983 GridBagLayout gridbag = new GridBagLayout(); 984 GridBagConstraints c = new GridBagConstraints(); 985 986 setLayout(gridbag); 987 setBorder(BorderFactory.createTitledBorder(strTitle)); 988 989 c.fill = GridBagConstraints.BOTH; 990 c.insets = compInsets; 991 c.gridwidth = GridBagConstraints.REMAINDER; 992 993 ButtonGroup bg = new ButtonGroup(); 994 JPanel pnlTop = new JPanel(new FlowLayout(FlowLayout.LEADING)); 995 rbAll = createRadioButton("radiobutton.rangeall", this); 996 rbAll.setSelected(true); 997 bg.add(rbAll); 998 pnlTop.add(rbAll); 999 addToGB(pnlTop, this, gridbag, c); 1000 1001 // Selection never seemed to work so I'm commenting this part. 1002 /* 1003 if (isAWT) { 1004 JPanel pnlMiddle = 1005 new JPanel(new FlowLayout(FlowLayout.LEADING)); 1006 rbSelect = 1007 createRadioButton("radiobutton.selection", this); 1008 bg.add(rbSelect); 1009 pnlMiddle.add(rbSelect); 1010 addToGB(pnlMiddle, this, gridbag, c); 1011 } 1012 */ 1013 1014 JPanel pnlBottom = new JPanel(new FlowLayout(FlowLayout.LEADING)); 1015 rbPages = createRadioButton("radiobutton.rangepages", this); 1016 bg.add(rbPages); 1017 pnlBottom.add(rbPages); 1018 DecimalFormat format = new DecimalFormat("####0"); 1019 format.setMinimumFractionDigits(0); 1020 format.setMaximumFractionDigits(0); 1021 format.setMinimumIntegerDigits(0); 1022 format.setMaximumIntegerDigits(5); 1023 format.setParseIntegerOnly(true); 1024 format.setDecimalSeparatorAlwaysShown(false); 1025 NumberFormatter nf = new NumberFormatter(format); 1026 nf.setMinimum(1); 1027 nf.setMaximum(Integer.MAX_VALUE); 1028 nf.setAllowsInvalid(true); 1029 nf.setCommitsOnValidEdit(true); 1030 tfRangeFrom = new JFormattedTextField(nf); 1031 tfRangeFrom.setColumns(4); 1032 tfRangeFrom.setEnabled(false); 1033 tfRangeFrom.addActionListener(this); 1034 tfRangeFrom.addFocusListener(this); 1035 tfRangeFrom.setFocusLostBehavior( 1036 JFormattedTextField.PERSIST); 1037 tfRangeFrom.getAccessibleContext().setAccessibleName( 1038 getMsg("radiobutton.rangepages")); 1039 pnlBottom.add(tfRangeFrom); 1040 lblRangeTo = new JLabel(getMsg("label.rangeto")); 1041 lblRangeTo.setEnabled(false); 1042 pnlBottom.add(lblRangeTo); 1043 NumberFormatter nfto; 1044 try { 1045 nfto = (NumberFormatter)nf.clone(); 1046 } catch (CloneNotSupportedException e) { 1047 nfto = new NumberFormatter(); 1048 } 1049 tfRangeTo = new JFormattedTextField(nfto); 1050 tfRangeTo.setColumns(4); 1051 tfRangeTo.setEnabled(false); 1052 tfRangeTo.addFocusListener(this); 1053 tfRangeTo.getAccessibleContext().setAccessibleName( 1054 getMsg("label.rangeto")); 1055 pnlBottom.add(tfRangeTo); 1056 addToGB(pnlBottom, this, gridbag, c); 1057 } 1058 1059 public void actionPerformed(ActionEvent e) { 1060 Object source = e.getSource(); 1061 SunPageSelection select = SunPageSelection.ALL; 1062 1063 setupRangeWidgets(); 1064 1065 if (source == rbAll) { 1066 asCurrent.add(prAll); 1067 } else if (source == rbSelect) { 1068 select = SunPageSelection.SELECTION; 1069 } else if (source == rbPages || 1070 source == tfRangeFrom || 1071 source == tfRangeTo) { 1072 updateRangeAttribute(); 1073 select = SunPageSelection.RANGE; 1074 } 1075 1076 if (isAWT) { 1077 asCurrent.add(select); 1078 } 1079 } 1080 1081 public void focusLost(FocusEvent e) { 1082 Object source = e.getSource(); 1083 1084 if ((source == tfRangeFrom) || (source == tfRangeTo)) { 1085 updateRangeAttribute(); 1086 } 1087 } 1088 1089 public void focusGained(FocusEvent e) {} 1090 1091 private void setupRangeWidgets() { 1092 boolean rangeEnabled = (rbPages.isSelected() && prPgRngSupported); 1093 tfRangeFrom.setEnabled(rangeEnabled); 1094 tfRangeTo.setEnabled(rangeEnabled); 1095 lblRangeTo.setEnabled(rangeEnabled); 1096 } 1097 1098 private void updateRangeAttribute() { 1099 String strFrom = tfRangeFrom.getText(); 1100 String strTo = tfRangeTo.getText(); 1101 1102 int min; 1103 int max; 1104 1105 try { 1106 min = Integer.parseInt(strFrom); 1107 } catch (NumberFormatException e) { 1108 min = 1; 1109 } 1110 1111 try { 1112 max = Integer.parseInt(strTo); 1113 } catch (NumberFormatException e) { 1114 max = min; 1115 } 1116 1117 if (min < 1) { 1118 min = 1; 1119 tfRangeFrom.setValue(1); 1120 } 1121 1122 if (max < min) { 1123 max = min; 1124 tfRangeTo.setValue(min); 1125 } 1126 1127 PageRanges pr = new PageRanges(min, max); 1128 asCurrent.add(pr); 1129 } 1130 1131 public void updateInfo() { 1132 Class<PageRanges> prCategory = PageRanges.class; 1133 prSupported = false; 1134 1135 if (psCurrent.isAttributeCategorySupported(prCategory) || 1136 isAWT) { 1137 prSupported = true; 1138 prPgRngSupported = psCurrent.isAttributeValueSupported(prAll, 1139 docFlavor, 1140 asCurrent); 1141 } 1142 1143 SunPageSelection select = SunPageSelection.ALL; 1144 int min = 1; 1145 int max = 1; 1146 1147 PageRanges pr = (PageRanges)asCurrent.get(prCategory); 1148 if (pr != null) { 1149 if (!pr.equals(prAll)) { 1150 select = SunPageSelection.RANGE; 1151 1152 int[][] members = pr.getMembers(); 1153 if ((members.length > 0) && 1154 (members[0].length > 1)) { 1155 min = members[0][0]; 1156 max = members[0][1]; 1157 } 1158 } 1159 } 1160 1161 if (isAWT) { 1162 select = (SunPageSelection)asCurrent.get( 1163 SunPageSelection.class); 1164 } 1165 1166 if (select == SunPageSelection.ALL) { 1167 rbAll.setSelected(true); 1168 } else if (select == SunPageSelection.SELECTION) { 1169 // Comment this for now - rbSelect is not initialized 1170 // because Selection button is not added. 1171 // See PrintRangePanel above. 1172 1173 //rbSelect.setSelected(true); 1174 } else { // RANGE 1175 rbPages.setSelected(true); 1176 } 1177 tfRangeFrom.setValue(min); 1178 tfRangeTo.setValue(max); 1179 rbAll.setEnabled(prSupported); 1180 rbPages.setEnabled(prPgRngSupported); 1181 setupRangeWidgets(); 1182 } 1183 } 1184 1185 @SuppressWarnings("serial") // Superclass is not serializable across versions 1186 private class CopiesPanel extends JPanel 1187 implements ActionListener, ChangeListener 1188 { 1189 private final String strTitle = getMsg("border.copies"); 1190 private SpinnerNumberModel snModel; 1191 private JSpinner spinCopies; 1192 private JLabel lblCopies; 1193 private JCheckBox cbCollate; 1194 private boolean scSupported; 1195 1196 public CopiesPanel() { 1197 super(); 1198 1199 GridBagLayout gridbag = new GridBagLayout(); 1200 GridBagConstraints c = new GridBagConstraints(); 1201 1202 setLayout(gridbag); 1203 setBorder(BorderFactory.createTitledBorder(strTitle)); 1204 1205 c.fill = GridBagConstraints.HORIZONTAL; 1206 c.insets = compInsets; 1207 1208 lblCopies = new JLabel(getMsg("label.numcopies"), JLabel.TRAILING); 1209 lblCopies.setDisplayedMnemonic(getMnemonic("label.numcopies")); 1210 lblCopies.getAccessibleContext().setAccessibleName( 1211 getMsg("label.numcopies")); 1212 addToGB(lblCopies, this, gridbag, c); 1213 1214 snModel = new SpinnerNumberModel(1, 1, 999, 1); 1215 spinCopies = new JSpinner(snModel); 1216 lblCopies.setLabelFor(spinCopies); 1217 // REMIND 1218 ((JSpinner.NumberEditor)spinCopies.getEditor()).getTextField().setColumns(3); 1219 spinCopies.addChangeListener(this); 1220 c.gridwidth = GridBagConstraints.REMAINDER; 1221 addToGB(spinCopies, this, gridbag, c); 1222 1223 cbCollate = createCheckBox("checkbox.collate", this); 1224 cbCollate.setEnabled(false); 1225 addToGB(cbCollate, this, gridbag, c); 1226 } 1227 1228 public void actionPerformed(ActionEvent e) { 1229 if (cbCollate.isSelected()) { 1230 asCurrent.add(SheetCollate.COLLATED); 1231 } else { 1232 asCurrent.add(SheetCollate.UNCOLLATED); 1233 } 1234 } 1235 1236 public void stateChanged(ChangeEvent e) { 1237 updateCollateCB(); 1238 1239 asCurrent.add(new Copies(snModel.getNumber().intValue())); 1240 } 1241 1242 private void updateCollateCB() { 1243 int num = snModel.getNumber().intValue(); 1244 if (isAWT) { 1245 cbCollate.setEnabled(true); 1246 } else { 1247 cbCollate.setEnabled((num > 1) && scSupported); 1248 } 1249 } 1250 1251 public void updateInfo() { 1252 Class<Copies> cpCategory = Copies.class; 1253 Class<SheetCollate> scCategory = SheetCollate.class; 1254 boolean cpSupported = false; 1255 scSupported = false; 1256 1257 // setup Copies spinner 1258 if (psCurrent.isAttributeCategorySupported(cpCategory)) { 1259 cpSupported = true; 1260 } 1261 CopiesSupported cs = 1262 (CopiesSupported)psCurrent.getSupportedAttributeValues( 1263 cpCategory, null, null); 1264 if (cs == null) { 1265 cs = new CopiesSupported(1, 999); 1266 } 1267 Copies cp = (Copies)asCurrent.get(cpCategory); 1268 if (cp == null) { 1269 cp = (Copies)psCurrent.getDefaultAttributeValue(cpCategory); 1270 if (cp == null) { 1271 cp = new Copies(1); 1272 } 1273 } 1274 spinCopies.setEnabled(cpSupported); 1275 lblCopies.setEnabled(cpSupported); 1276 1277 int[][] members = cs.getMembers(); 1278 int min, max; 1279 if ((members.length > 0) && (members[0].length > 0)) { 1280 min = members[0][0]; 1281 max = members[0][1]; 1282 } else { 1283 min = 1; 1284 max = Integer.MAX_VALUE; 1285 } 1286 snModel.setMinimum(min); 1287 snModel.setMaximum(max); 1288 1289 int value = cp.getValue(); 1290 if ((value < min) || (value > max)) { 1291 value = min; 1292 } 1293 snModel.setValue(value); 1294 1295 // setup Collate checkbox 1296 if (psCurrent.isAttributeCategorySupported(scCategory)) { 1297 scSupported = true; 1298 } 1299 SheetCollate sc = (SheetCollate)asCurrent.get(scCategory); 1300 if (sc == null) { 1301 sc = (SheetCollate)psCurrent.getDefaultAttributeValue(scCategory); 1302 if (sc == null) { 1303 sc = SheetCollate.UNCOLLATED; 1304 } 1305 if (sc != null && 1306 !psCurrent.isAttributeValueSupported(sc, docFlavor, asCurrent)) { 1307 scSupported = false; 1308 } 1309 } else { 1310 if (!psCurrent.isAttributeValueSupported(sc, docFlavor, asCurrent)) { 1311 scSupported = false; 1312 } 1313 } 1314 cbCollate.setSelected(sc == SheetCollate.COLLATED && scSupported); 1315 updateCollateCB(); 1316 } 1317 } 1318 1319 1320 1321 1322 /** 1323 * The "Page Setup" tab. Includes the controls for MediaSource/MediaTray, 1324 * OrientationRequested, and Sides. 1325 */ 1326 @SuppressWarnings("serial") // Superclass is not serializable across versions 1327 private class PageSetupPanel extends JPanel { 1328 1329 private MediaPanel pnlMedia; 1330 private OrientationPanel pnlOrientation; 1331 private MarginsPanel pnlMargins; 1332 1333 public PageSetupPanel() { 1334 super(); 1335 1336 GridBagLayout gridbag = new GridBagLayout(); 1337 GridBagConstraints c = new GridBagConstraints(); 1338 1339 setLayout(gridbag); 1340 1341 c.fill = GridBagConstraints.BOTH; 1342 c.insets = panelInsets; 1343 c.weightx = 1.0; 1344 c.weighty = 1.0; 1345 1346 c.gridwidth = GridBagConstraints.REMAINDER; 1347 pnlMedia = new MediaPanel(); 1348 addToGB(pnlMedia, this, gridbag, c); 1349 1350 pnlOrientation = new OrientationPanel(); 1351 c.gridwidth = GridBagConstraints.RELATIVE; 1352 addToGB(pnlOrientation, this, gridbag, c); 1353 1354 pnlMargins = new MarginsPanel(); 1355 pnlOrientation.addOrientationListener(pnlMargins); 1356 pnlMedia.addMediaListener(pnlMargins); 1357 c.gridwidth = GridBagConstraints.REMAINDER; 1358 addToGB(pnlMargins, this, gridbag, c); 1359 } 1360 1361 public void updateInfo() { 1362 pnlMedia.updateInfo(); 1363 pnlOrientation.updateInfo(); 1364 pnlMargins.updateInfo(); 1365 } 1366 } 1367 1368 @SuppressWarnings("serial") // Superclass is not serializable across versions 1369 private class MarginsPanel extends JPanel 1370 implements ActionListener, FocusListener { 1371 1372 private final String strTitle = getMsg("border.margins"); 1373 private JFormattedTextField leftMargin, rightMargin, 1374 topMargin, bottomMargin; 1375 private JLabel lblLeft, lblRight, lblTop, lblBottom; 1376 private int units = MediaPrintableArea.MM; 1377 // storage for the last margin values calculated, -ve is uninitialised 1378 private float lmVal = -1f,rmVal = -1f, tmVal = -1f, bmVal = -1f; 1379 // storage for margins as objects mapped into orientation for display 1380 private Float lmObj,rmObj,tmObj,bmObj; 1381 1382 public MarginsPanel() { 1383 super(); 1384 1385 GridBagLayout gridbag = new GridBagLayout(); 1386 GridBagConstraints c = new GridBagConstraints(); 1387 c.fill = GridBagConstraints.HORIZONTAL; 1388 c.weightx = 1.0; 1389 c.weighty = 0.0; 1390 c.insets = compInsets; 1391 1392 setLayout(gridbag); 1393 setBorder(BorderFactory.createTitledBorder(strTitle)); 1394 1395 String unitsKey = "label.millimetres"; 1396 String defaultCountry = Locale.getDefault().getCountry(); 1397 if (defaultCountry != null && 1398 (defaultCountry.isEmpty() || 1399 defaultCountry.equals(Locale.US.getCountry()) || 1400 defaultCountry.equals(Locale.CANADA.getCountry()))) { 1401 unitsKey = "label.inches"; 1402 units = MediaPrintableArea.INCH; 1403 } 1404 String unitsMsg = getMsg(unitsKey); 1405 1406 DecimalFormat format; 1407 if (units == MediaPrintableArea.MM) { 1408 format = new DecimalFormat("###.##"); 1409 format.setMaximumIntegerDigits(3); 1410 } else { 1411 format = new DecimalFormat("##.##"); 1412 format.setMaximumIntegerDigits(2); 1413 } 1414 1415 format.setMinimumFractionDigits(1); 1416 format.setMaximumFractionDigits(2); 1417 format.setMinimumIntegerDigits(1); 1418 format.setParseIntegerOnly(false); 1419 format.setDecimalSeparatorAlwaysShown(true); 1420 NumberFormatter nf = new NumberFormatter(format); 1421 nf.setMinimum(Float.valueOf(0.0f)); 1422 nf.setMaximum(Float.valueOf(999.0f)); 1423 nf.setAllowsInvalid(true); 1424 nf.setCommitsOnValidEdit(true); 1425 1426 leftMargin = new JFormattedTextField(nf); 1427 leftMargin.addFocusListener(this); 1428 leftMargin.addActionListener(this); 1429 leftMargin.getAccessibleContext().setAccessibleName( 1430 getMsg("label.leftmargin")); 1431 rightMargin = new JFormattedTextField(nf); 1432 rightMargin.addFocusListener(this); 1433 rightMargin.addActionListener(this); 1434 rightMargin.getAccessibleContext().setAccessibleName( 1435 getMsg("label.rightmargin")); 1436 topMargin = new JFormattedTextField(nf); 1437 topMargin.addFocusListener(this); 1438 topMargin.addActionListener(this); 1439 topMargin.getAccessibleContext().setAccessibleName( 1440 getMsg("label.topmargin")); 1441 1442 bottomMargin = new JFormattedTextField(nf); 1443 bottomMargin.addFocusListener(this); 1444 bottomMargin.addActionListener(this); 1445 bottomMargin.getAccessibleContext().setAccessibleName( 1446 getMsg("label.bottommargin")); 1447 1448 c.gridwidth = GridBagConstraints.RELATIVE; 1449 lblLeft = new JLabel(getMsg("label.leftmargin") + " " + unitsMsg, 1450 JLabel.LEADING); 1451 lblLeft.setDisplayedMnemonic(getMnemonic("label.leftmargin")); 1452 lblLeft.setLabelFor(leftMargin); 1453 addToGB(lblLeft, this, gridbag, c); 1454 1455 c.gridwidth = GridBagConstraints.REMAINDER; 1456 lblRight = new JLabel(getMsg("label.rightmargin") + " " + unitsMsg, 1457 JLabel.LEADING); 1458 lblRight.setDisplayedMnemonic(getMnemonic("label.rightmargin")); 1459 lblRight.setLabelFor(rightMargin); 1460 addToGB(lblRight, this, gridbag, c); 1461 1462 c.gridwidth = GridBagConstraints.RELATIVE; 1463 addToGB(leftMargin, this, gridbag, c); 1464 1465 c.gridwidth = GridBagConstraints.REMAINDER; 1466 addToGB(rightMargin, this, gridbag, c); 1467 1468 // add an invisible spacing component. 1469 addToGB(new JPanel(), this, gridbag, c); 1470 1471 c.gridwidth = GridBagConstraints.RELATIVE; 1472 lblTop = new JLabel(getMsg("label.topmargin") + " " + unitsMsg, 1473 JLabel.LEADING); 1474 lblTop.setDisplayedMnemonic(getMnemonic("label.topmargin")); 1475 lblTop.setLabelFor(topMargin); 1476 addToGB(lblTop, this, gridbag, c); 1477 1478 c.gridwidth = GridBagConstraints.REMAINDER; 1479 lblBottom = new JLabel(getMsg("label.bottommargin") + 1480 " " + unitsMsg, JLabel.LEADING); 1481 lblBottom.setDisplayedMnemonic(getMnemonic("label.bottommargin")); 1482 lblBottom.setLabelFor(bottomMargin); 1483 addToGB(lblBottom, this, gridbag, c); 1484 1485 c.gridwidth = GridBagConstraints.RELATIVE; 1486 addToGB(topMargin, this, gridbag, c); 1487 1488 c.gridwidth = GridBagConstraints.REMAINDER; 1489 addToGB(bottomMargin, this, gridbag, c); 1490 1491 } 1492 1493 public void actionPerformed(ActionEvent e) { 1494 Object source = e.getSource(); 1495 updateMargins(source); 1496 } 1497 1498 public void focusLost(FocusEvent e) { 1499 Object source = e.getSource(); 1500 updateMargins(source); 1501 } 1502 1503 public void focusGained(FocusEvent e) {} 1504 1505 /* Get the numbers, use to create a MPA. 1506 * If its valid, accept it and update the attribute set. 1507 * If its not valid, then reject it and call updateInfo() 1508 * to re-establish the previous entries. 1509 */ 1510 public void updateMargins(Object source) { 1511 if (!(source instanceof JFormattedTextField)) { 1512 return; 1513 } else { 1514 JFormattedTextField tf = (JFormattedTextField)source; 1515 Float val = (Float)tf.getValue(); 1516 if (val == null) { 1517 return; 1518 } 1519 if (tf == leftMargin && val.equals(lmObj)) { 1520 return; 1521 } 1522 if (tf == rightMargin && val.equals(rmObj)) { 1523 return; 1524 } 1525 if (tf == topMargin && val.equals(tmObj)) { 1526 return; 1527 } 1528 if (tf == bottomMargin && val.equals(bmObj)) { 1529 return; 1530 } 1531 } 1532 1533 Float lmTmpObj = (Float)leftMargin.getValue(); 1534 Float rmTmpObj = (Float)rightMargin.getValue(); 1535 Float tmTmpObj = (Float)topMargin.getValue(); 1536 Float bmTmpObj = (Float)bottomMargin.getValue(); 1537 1538 float lm = lmTmpObj.floatValue(); 1539 float rm = rmTmpObj.floatValue(); 1540 float tm = tmTmpObj.floatValue(); 1541 float bm = bmTmpObj.floatValue(); 1542 1543 /* adjust for orientation */ 1544 Class<OrientationRequested> orCategory = OrientationRequested.class; 1545 OrientationRequested or = 1546 (OrientationRequested)asCurrent.get(orCategory); 1547 1548 if (or == null) { 1549 or = (OrientationRequested) 1550 psCurrent.getDefaultAttributeValue(orCategory); 1551 } 1552 1553 float tmp; 1554 if (or == OrientationRequested.REVERSE_PORTRAIT) { 1555 tmp = lm; lm = rm; rm = tmp; 1556 tmp = tm; tm = bm; bm = tmp; 1557 } else if (or == OrientationRequested.LANDSCAPE) { 1558 tmp = lm; 1559 lm = tm; 1560 tm = rm; 1561 rm = bm; 1562 bm = tmp; 1563 } else if (or == OrientationRequested.REVERSE_LANDSCAPE) { 1564 tmp = lm; 1565 lm = bm; 1566 bm = rm; 1567 rm = tm; 1568 tm = tmp; 1569 } 1570 MediaPrintableArea mpa; 1571 if ((mpa = validateMargins(lm, rm, tm, bm)) != null) { 1572 asCurrent.add(mpa); 1573 lmVal = lm; 1574 rmVal = rm; 1575 tmVal = tm; 1576 bmVal = bm; 1577 lmObj = lmTmpObj; 1578 rmObj = rmTmpObj; 1579 tmObj = tmTmpObj; 1580 bmObj = bmTmpObj; 1581 } else { 1582 if (lmObj == null || rmObj == null || 1583 tmObj == null || bmObj == null) { 1584 return; 1585 } else { 1586 leftMargin.setValue(lmObj); 1587 rightMargin.setValue(rmObj); 1588 topMargin.setValue(tmObj); 1589 bottomMargin.setValue(bmObj); 1590 1591 } 1592 } 1593 } 1594 1595 /* 1596 * This method either accepts the values and creates a new 1597 * MediaPrintableArea, or does nothing. 1598 * It should not attempt to create a printable area from anything 1599 * other than the exact values passed in. 1600 * But REMIND/TBD: it would be user friendly to replace margins the 1601 * user entered but are out of bounds with the minimum. 1602 * At that point this method will need to take responsibility for 1603 * updating the "stored" values and the UI. 1604 */ 1605 private MediaPrintableArea validateMargins(float lm, float rm, 1606 float tm, float bm) { 1607 1608 Class<MediaPrintableArea> mpaCategory = MediaPrintableArea.class; 1609 MediaPrintableArea mpa; 1610 MediaPrintableArea mpaMax = null; 1611 MediaSize mediaSize = null; 1612 1613 Media media = (Media)asCurrent.get(Media.class); 1614 if (media == null || !(media instanceof MediaSizeName)) { 1615 media = (Media)psCurrent.getDefaultAttributeValue(Media.class); 1616 } 1617 if (media != null && (media instanceof MediaSizeName)) { 1618 MediaSizeName msn = (MediaSizeName)media; 1619 mediaSize = MediaSize.getMediaSizeForName(msn); 1620 } 1621 if (mediaSize == null) { 1622 mediaSize = new MediaSize(8.5f, 11f, Size2DSyntax.INCH); 1623 } 1624 1625 if (media != null) { 1626 PrintRequestAttributeSet tmpASet = 1627 new HashPrintRequestAttributeSet(asCurrent); 1628 tmpASet.add(media); 1629 1630 Object values = 1631 psCurrent.getSupportedAttributeValues(mpaCategory, 1632 docFlavor, 1633 tmpASet); 1634 if (values instanceof MediaPrintableArea[] && 1635 ((MediaPrintableArea[])values).length > 0) { 1636 mpaMax = ((MediaPrintableArea[])values)[0]; 1637 1638 } 1639 } 1640 if (mpaMax == null) { 1641 mpaMax = new MediaPrintableArea(0f, 0f, 1642 mediaSize.getX(units), 1643 mediaSize.getY(units), 1644 units); 1645 } 1646 1647 float wid = mediaSize.getX(units); 1648 float hgt = mediaSize.getY(units); 1649 float pax = lm; 1650 float pay = tm; 1651 float par = rm; 1652 float pab = bm; 1653 float paw = wid - lm - rm; 1654 float pah = hgt - tm - bm; 1655 1656 if (paw <= 0f || pah <= 0f || pax < 0f || pay < 0f || 1657 par <= 0f || pab <= 0f || 1658 pax < mpaMax.getX(units) || paw > mpaMax.getWidth(units) || 1659 pay < mpaMax.getY(units) || pah > mpaMax.getHeight(units)) { 1660 return null; 1661 } else { 1662 return new MediaPrintableArea(lm, tm, paw, pah, units); 1663 } 1664 } 1665 1666 /* This is complex as a MediaPrintableArea is valid only within 1667 * a particular context of media size. 1668 * So we need a MediaSize as well as a MediaPrintableArea. 1669 * MediaSize can be obtained from MediaSizeName. 1670 * If the application specifies a MediaPrintableArea, we accept it 1671 * to the extent its valid for the Media they specify. If they 1672 * don't specify a Media, then the default is assumed. 1673 * 1674 * If an application doesn't define a MediaPrintableArea, we need to 1675 * create a suitable one, this is created using the specified (or 1676 * default) Media and default 1 inch margins. This is validated 1677 * against the paper in case this is too large for tiny media. 1678 */ 1679 public void updateInfo() { 1680 1681 if (isAWT) { 1682 leftMargin.setEnabled(false); 1683 rightMargin.setEnabled(false); 1684 topMargin.setEnabled(false); 1685 bottomMargin.setEnabled(false); 1686 lblLeft.setEnabled(false); 1687 lblRight.setEnabled(false); 1688 lblTop.setEnabled(false); 1689 lblBottom.setEnabled(false); 1690 return; 1691 } 1692 1693 Class<MediaPrintableArea> mpaCategory = MediaPrintableArea.class; 1694 MediaPrintableArea mpa = 1695 (MediaPrintableArea)asCurrent.get(mpaCategory); 1696 MediaPrintableArea mpaMax = null; 1697 MediaSize mediaSize = null; 1698 1699 Media media = (Media)asCurrent.get(Media.class); 1700 if (media == null || !(media instanceof MediaSizeName)) { 1701 media = (Media)psCurrent.getDefaultAttributeValue(Media.class); 1702 } 1703 if (media != null && (media instanceof MediaSizeName)) { 1704 MediaSizeName msn = (MediaSizeName)media; 1705 mediaSize = MediaSize.getMediaSizeForName(msn); 1706 } 1707 if (mediaSize == null) { 1708 mediaSize = new MediaSize(8.5f, 11f, Size2DSyntax.INCH); 1709 } 1710 1711 if (media != null) { 1712 PrintRequestAttributeSet tmpASet = 1713 new HashPrintRequestAttributeSet(asCurrent); 1714 tmpASet.add(media); 1715 1716 Object values = 1717 psCurrent.getSupportedAttributeValues(mpaCategory, 1718 docFlavor, 1719 tmpASet); 1720 if (values instanceof MediaPrintableArea[] && 1721 ((MediaPrintableArea[])values).length > 0) { 1722 mpaMax = ((MediaPrintableArea[])values)[0]; 1723 1724 } else if (values instanceof MediaPrintableArea) { 1725 mpaMax = (MediaPrintableArea)values; 1726 } 1727 } 1728 if (mpaMax == null) { 1729 mpaMax = new MediaPrintableArea(0f, 0f, 1730 mediaSize.getX(units), 1731 mediaSize.getY(units), 1732 units); 1733 } 1734 1735 /* 1736 * At this point we now know as best we can :- 1737 * - the media size 1738 * - the maximum corresponding printable area 1739 * - the media printable area specified by the client, if any. 1740 * The next step is to create a default MPA if none was specified. 1741 * 1" margins are used unless they are disproportionately 1742 * large compared to the size of the media. 1743 */ 1744 1745 float wid = mediaSize.getX(MediaPrintableArea.INCH); 1746 float hgt = mediaSize.getY(MediaPrintableArea.INCH); 1747 float maxMarginRatio = 5f; 1748 float xMgn, yMgn; 1749 if (wid > maxMarginRatio) { 1750 xMgn = 1f; 1751 } else { 1752 xMgn = wid / maxMarginRatio; 1753 } 1754 if (hgt > maxMarginRatio) { 1755 yMgn = 1f; 1756 } else { 1757 yMgn = hgt / maxMarginRatio; 1758 } 1759 1760 if (mpa == null) { 1761 mpa = new MediaPrintableArea(xMgn, yMgn, 1762 wid-(2*xMgn), hgt-(2*yMgn), 1763 MediaPrintableArea.INCH); 1764 asCurrent.add(mpa); 1765 } 1766 float pax = mpa.getX(units); 1767 float pay = mpa.getY(units); 1768 float paw = mpa.getWidth(units); 1769 float pah = mpa.getHeight(units); 1770 float paxMax = mpaMax.getX(units); 1771 float payMax = mpaMax.getY(units); 1772 float pawMax = mpaMax.getWidth(units); 1773 float pahMax = mpaMax.getHeight(units); 1774 1775 1776 boolean invalid = false; 1777 1778 // If the paper is set to something which is too small to 1779 // accommodate a specified printable area, perhaps carried 1780 // over from a larger paper, the adjustment that needs to be 1781 // performed should seem the most natural from a user's viewpoint. 1782 // Since the user is specifying margins, then we are biased 1783 // towards keeping the margins as close to what is specified as 1784 // possible, shrinking or growing the printable area. 1785 // But the API uses printable area, so you need to know the 1786 // media size in which the margins were previously interpreted, 1787 // or at least have a record of the margins. 1788 // In the case that this is the creation of this UI we do not 1789 // have this record, so we are somewhat reliant on the client 1790 // to supply a reasonable default 1791 wid = mediaSize.getX(units); 1792 hgt = mediaSize.getY(units); 1793 if (lmVal >= 0f) { 1794 invalid = true; 1795 1796 if (lmVal + rmVal > wid) { 1797 // margins impossible, but maintain P.A if can 1798 if (paw > pawMax) { 1799 paw = pawMax; 1800 } 1801 // try to centre the printable area. 1802 pax = (wid - paw)/2f; 1803 } else { 1804 pax = (lmVal >= paxMax) ? lmVal : paxMax; 1805 paw = wid - pax - rmVal; 1806 } 1807 if (tmVal + bmVal > hgt) { 1808 if (pah > pahMax) { 1809 pah = pahMax; 1810 } 1811 pay = (hgt - pah)/2f; 1812 } else { 1813 pay = (tmVal >= payMax) ? tmVal : payMax; 1814 pah = hgt - pay - bmVal; 1815 } 1816 } 1817 if (pax < paxMax) { 1818 invalid = true; 1819 pax = paxMax; 1820 } 1821 if (pay < payMax) { 1822 invalid = true; 1823 pay = payMax; 1824 } 1825 if (paw > pawMax) { 1826 invalid = true; 1827 paw = pawMax; 1828 } 1829 if (pah > pahMax) { 1830 invalid = true; 1831 pah = pahMax; 1832 } 1833 1834 if ((pax + paw > paxMax + pawMax) || (paw <= 0f)) { 1835 invalid = true; 1836 pax = paxMax; 1837 paw = pawMax; 1838 } 1839 if ((pay + pah > payMax + pahMax) || (pah <= 0f)) { 1840 invalid = true; 1841 pay = payMax; 1842 pah = pahMax; 1843 } 1844 1845 if (invalid) { 1846 mpa = new MediaPrintableArea(pax, pay, paw, pah, units); 1847 asCurrent.add(mpa); 1848 } 1849 1850 /* We now have a valid printable area. 1851 * Turn it into margins, using the mediaSize 1852 */ 1853 lmVal = pax; 1854 tmVal = pay; 1855 rmVal = mediaSize.getX(units) - pax - paw; 1856 bmVal = mediaSize.getY(units) - pay - pah; 1857 1858 lmObj = lmVal; 1859 rmObj = rmVal; 1860 tmObj = tmVal; 1861 bmObj = bmVal; 1862 1863 /* Now we know the values to use, we need to assign them 1864 * to the fields appropriate for the orientation. 1865 * Note: if orientation changes this method must be called. 1866 */ 1867 Class<OrientationRequested> orCategory = OrientationRequested.class; 1868 OrientationRequested or = 1869 (OrientationRequested)asCurrent.get(orCategory); 1870 1871 if (or == null) { 1872 or = (OrientationRequested) 1873 psCurrent.getDefaultAttributeValue(orCategory); 1874 } 1875 1876 Float tmp; 1877 1878 if (or == OrientationRequested.REVERSE_PORTRAIT) { 1879 tmp = lmObj; lmObj = rmObj; rmObj = tmp; 1880 tmp = tmObj; tmObj = bmObj; bmObj = tmp; 1881 } else if (or == OrientationRequested.LANDSCAPE) { 1882 tmp = lmObj; 1883 lmObj = bmObj; 1884 bmObj = rmObj; 1885 rmObj = tmObj; 1886 tmObj = tmp; 1887 } else if (or == OrientationRequested.REVERSE_LANDSCAPE) { 1888 tmp = lmObj; 1889 lmObj = tmObj; 1890 tmObj = rmObj; 1891 rmObj = bmObj; 1892 bmObj = tmp; 1893 } 1894 1895 leftMargin.setValue(lmObj); 1896 rightMargin.setValue(rmObj); 1897 topMargin.setValue(tmObj); 1898 bottomMargin.setValue(bmObj); 1899 } 1900 } 1901 1902 @SuppressWarnings("serial") // Superclass is not serializable across versions 1903 private class MediaPanel extends JPanel implements ItemListener { 1904 1905 private final String strTitle = getMsg("border.media"); 1906 private JLabel lblSize, lblSource; 1907 private JComboBox<Object> cbSize, cbSource; 1908 private Vector<MediaSizeName> sizes = new Vector<>(); 1909 private Vector<MediaTray> sources = new Vector<>(); 1910 private MarginsPanel pnlMargins = null; 1911 1912 public MediaPanel() { 1913 super(); 1914 1915 GridBagLayout gridbag = new GridBagLayout(); 1916 GridBagConstraints c = new GridBagConstraints(); 1917 1918 setLayout(gridbag); 1919 setBorder(BorderFactory.createTitledBorder(strTitle)); 1920 1921 cbSize = new JComboBox<>(); 1922 cbSource = new JComboBox<>(); 1923 1924 c.fill = GridBagConstraints.BOTH; 1925 c.insets = compInsets; 1926 c.weighty = 1.0; 1927 1928 c.weightx = 0.0; 1929 lblSize = new JLabel(getMsg("label.size"), JLabel.TRAILING); 1930 lblSize.setDisplayedMnemonic(getMnemonic("label.size")); 1931 lblSize.setLabelFor(cbSize); 1932 addToGB(lblSize, this, gridbag, c); 1933 c.weightx = 1.0; 1934 c.gridwidth = GridBagConstraints.REMAINDER; 1935 addToGB(cbSize, this, gridbag, c); 1936 1937 c.weightx = 0.0; 1938 c.gridwidth = 1; 1939 lblSource = new JLabel(getMsg("label.source"), JLabel.TRAILING); 1940 lblSource.setDisplayedMnemonic(getMnemonic("label.source")); 1941 lblSource.setLabelFor(cbSource); 1942 addToGB(lblSource, this, gridbag, c); 1943 c.gridwidth = GridBagConstraints.REMAINDER; 1944 addToGB(cbSource, this, gridbag, c); 1945 } 1946 1947 private String getMediaName(String key) { 1948 try { 1949 // replace characters that would be invalid in 1950 // a resource key with valid characters 1951 String newkey = key.replace(' ', '-'); 1952 newkey = newkey.replace('#', 'n'); 1953 1954 return messageRB.getString(newkey); 1955 } catch (java.util.MissingResourceException e) { 1956 return key; 1957 } 1958 } 1959 1960 public void itemStateChanged(ItemEvent e) { 1961 Object source = e.getSource(); 1962 1963 if (e.getStateChange() == ItemEvent.SELECTED) { 1964 if (source == cbSize) { 1965 int index = cbSize.getSelectedIndex(); 1966 1967 if ((index >= 0) && (index < sizes.size())) { 1968 if ((cbSource.getItemCount() > 1) && 1969 (cbSource.getSelectedIndex() >= 1)) 1970 { 1971 int src = cbSource.getSelectedIndex() - 1; 1972 MediaTray mt = sources.get(src); 1973 asCurrent.add(new SunAlternateMedia(mt)); 1974 } 1975 asCurrent.add(sizes.get(index)); 1976 } 1977 } else if (source == cbSource) { 1978 int index = cbSource.getSelectedIndex(); 1979 1980 if ((index >= 1) && (index < (sources.size() + 1))) { 1981 asCurrent.remove(SunAlternateMedia.class); 1982 MediaTray newTray = sources.get(index - 1); 1983 Media m = (Media)asCurrent.get(Media.class); 1984 if (m == null || m instanceof MediaTray) { 1985 asCurrent.add(newTray); 1986 } else if (m instanceof MediaSizeName) { 1987 MediaSizeName msn = (MediaSizeName)m; 1988 Media def = (Media)psCurrent.getDefaultAttributeValue(Media.class); 1989 if (def instanceof MediaSizeName && def.equals(msn)) { 1990 asCurrent.add(newTray); 1991 } else { 1992 /* Non-default paper size, so need to store tray 1993 * as SunAlternateMedia 1994 */ 1995 asCurrent.add(new SunAlternateMedia(newTray)); 1996 } 1997 } 1998 } else if (index == 0) { 1999 asCurrent.remove(SunAlternateMedia.class); 2000 if (cbSize.getItemCount() > 0) { 2001 int size = cbSize.getSelectedIndex(); 2002 asCurrent.add(sizes.get(size)); 2003 } 2004 } 2005 } 2006 // orientation affects display of margins. 2007 if (pnlMargins != null) { 2008 pnlMargins.updateInfo(); 2009 } 2010 } 2011 } 2012 2013 2014 /* this is ad hoc to keep things simple */ 2015 public void addMediaListener(MarginsPanel pnl) { 2016 pnlMargins = pnl; 2017 } 2018 public void updateInfo() { 2019 Class<Media> mdCategory = Media.class; 2020 Class<SunAlternateMedia> amCategory = SunAlternateMedia.class; 2021 boolean mediaSupported = false; 2022 2023 cbSize.removeItemListener(this); 2024 cbSize.removeAllItems(); 2025 cbSource.removeItemListener(this); 2026 cbSource.removeAllItems(); 2027 cbSource.addItem(getMediaName("auto-select")); 2028 2029 sizes.clear(); 2030 sources.clear(); 2031 2032 if (psCurrent.isAttributeCategorySupported(mdCategory)) { 2033 mediaSupported = true; 2034 2035 Object values = 2036 psCurrent.getSupportedAttributeValues(mdCategory, 2037 docFlavor, 2038 asCurrent); 2039 2040 if (values instanceof Media[]) { 2041 Media[] media = (Media[])values; 2042 2043 for (int i = 0; i < media.length; i++) { 2044 Media medium = media[i]; 2045 2046 if (medium instanceof MediaSizeName) { 2047 sizes.add((MediaSizeName)medium); 2048 cbSize.addItem(getMediaName(medium.toString())); 2049 } else if (medium instanceof MediaTray) { 2050 sources.add((MediaTray)medium); 2051 cbSource.addItem(getMediaName(medium.toString())); 2052 } 2053 } 2054 } 2055 } 2056 2057 boolean msSupported = (mediaSupported && (sizes.size() > 0)); 2058 lblSize.setEnabled(msSupported); 2059 cbSize.setEnabled(msSupported); 2060 2061 if (isAWT) { 2062 cbSource.setEnabled(false); 2063 lblSource.setEnabled(false); 2064 } else { 2065 cbSource.setEnabled(mediaSupported); 2066 } 2067 2068 if (mediaSupported) { 2069 2070 Media medium = (Media)asCurrent.get(mdCategory); 2071 2072 // initialize size selection to default 2073 Media defMedia = (Media)psCurrent.getDefaultAttributeValue(mdCategory); 2074 if (defMedia instanceof MediaSizeName) { 2075 cbSize.setSelectedIndex(sizes.size() > 0 ? sizes.indexOf(defMedia) : -1); 2076 } 2077 2078 if (medium == null || 2079 !psCurrent.isAttributeValueSupported(medium, 2080 docFlavor, asCurrent)) { 2081 2082 medium = defMedia; 2083 2084 if (medium == null) { 2085 if (sizes.size() > 0) { 2086 medium = (Media)sizes.get(0); 2087 } 2088 } 2089 if (medium != null) { 2090 asCurrent.add(medium); 2091 } 2092 } 2093 if (medium != null) { 2094 if (medium instanceof MediaSizeName) { 2095 MediaSizeName ms = (MediaSizeName)medium; 2096 cbSize.setSelectedIndex(sizes.indexOf(ms)); 2097 } else if (medium instanceof MediaTray) { 2098 MediaTray mt = (MediaTray)medium; 2099 cbSource.setSelectedIndex(sources.indexOf(mt) + 1); 2100 } 2101 } else { 2102 cbSize.setSelectedIndex(sizes.size() > 0 ? 0 : -1); 2103 cbSource.setSelectedIndex(0); 2104 } 2105 2106 SunAlternateMedia alt = (SunAlternateMedia)asCurrent.get(amCategory); 2107 if (alt != null) { 2108 Media md = alt.getMedia(); 2109 if (md instanceof MediaTray) { 2110 MediaTray mt = (MediaTray)md; 2111 cbSource.setSelectedIndex(sources.indexOf(mt) + 1); 2112 } 2113 } 2114 2115 int selIndex = cbSize.getSelectedIndex(); 2116 if ((selIndex >= 0) && (selIndex < sizes.size())) { 2117 asCurrent.add(sizes.get(selIndex)); 2118 } 2119 2120 selIndex = cbSource.getSelectedIndex(); 2121 if ((selIndex >= 1) && (selIndex < (sources.size()+1))) { 2122 MediaTray mt = sources.get(selIndex-1); 2123 if (medium instanceof MediaTray) { 2124 asCurrent.add(mt); 2125 } else { 2126 asCurrent.add(new SunAlternateMedia(mt)); 2127 } 2128 } 2129 2130 2131 } 2132 cbSize.addItemListener(this); 2133 cbSource.addItemListener(this); 2134 } 2135 } 2136 2137 @SuppressWarnings("serial") // Superclass is not serializable across versions 2138 private class OrientationPanel extends JPanel 2139 implements ActionListener 2140 { 2141 private final String strTitle = getMsg("border.orientation"); 2142 private IconRadioButton rbPortrait, rbLandscape, 2143 rbRevPortrait, rbRevLandscape; 2144 private MarginsPanel pnlMargins = null; 2145 2146 public OrientationPanel() { 2147 super(); 2148 2149 GridBagLayout gridbag = new GridBagLayout(); 2150 GridBagConstraints c = new GridBagConstraints(); 2151 2152 setLayout(gridbag); 2153 setBorder(BorderFactory.createTitledBorder(strTitle)); 2154 2155 c.fill = GridBagConstraints.BOTH; 2156 c.insets = compInsets; 2157 c.weighty = 1.0; 2158 c.gridwidth = GridBagConstraints.REMAINDER; 2159 2160 ButtonGroup bg = new ButtonGroup(); 2161 rbPortrait = new IconRadioButton("radiobutton.portrait", 2162 "orientPortrait.png", true, 2163 bg, this); 2164 rbPortrait.addActionListener(this); 2165 addToGB(rbPortrait, this, gridbag, c); 2166 rbLandscape = new IconRadioButton("radiobutton.landscape", 2167 "orientLandscape.png", false, 2168 bg, this); 2169 rbLandscape.addActionListener(this); 2170 addToGB(rbLandscape, this, gridbag, c); 2171 rbRevPortrait = new IconRadioButton("radiobutton.revportrait", 2172 "orientRevPortrait.png", false, 2173 bg, this); 2174 rbRevPortrait.addActionListener(this); 2175 addToGB(rbRevPortrait, this, gridbag, c); 2176 rbRevLandscape = new IconRadioButton("radiobutton.revlandscape", 2177 "orientRevLandscape.png", false, 2178 bg, this); 2179 rbRevLandscape.addActionListener(this); 2180 addToGB(rbRevLandscape, this, gridbag, c); 2181 } 2182 2183 public void actionPerformed(ActionEvent e) { 2184 Object source = e.getSource(); 2185 2186 if (rbPortrait.isSameAs(source)) { 2187 asCurrent.add(OrientationRequested.PORTRAIT); 2188 } else if (rbLandscape.isSameAs(source)) { 2189 asCurrent.add(OrientationRequested.LANDSCAPE); 2190 } else if (rbRevPortrait.isSameAs(source)) { 2191 asCurrent.add(OrientationRequested.REVERSE_PORTRAIT); 2192 } else if (rbRevLandscape.isSameAs(source)) { 2193 asCurrent.add(OrientationRequested.REVERSE_LANDSCAPE); 2194 } 2195 // orientation affects display of margins. 2196 if (pnlMargins != null) { 2197 pnlMargins.updateInfo(); 2198 } 2199 } 2200 2201 /* This is ad hoc to keep things simple */ 2202 void addOrientationListener(MarginsPanel pnl) { 2203 pnlMargins = pnl; 2204 } 2205 2206 public void updateInfo() { 2207 Class<OrientationRequested> orCategory = OrientationRequested.class; 2208 boolean pSupported = false; 2209 boolean lSupported = false; 2210 boolean rpSupported = false; 2211 boolean rlSupported = false; 2212 2213 if (isAWT) { 2214 pSupported = true; 2215 lSupported = true; 2216 } else 2217 if (psCurrent.isAttributeCategorySupported(orCategory)) { 2218 Object values = 2219 psCurrent.getSupportedAttributeValues(orCategory, 2220 docFlavor, 2221 asCurrent); 2222 2223 if (values instanceof OrientationRequested[]) { 2224 OrientationRequested[] ovalues = 2225 (OrientationRequested[])values; 2226 2227 for (int i = 0; i < ovalues.length; i++) { 2228 OrientationRequested value = ovalues[i]; 2229 2230 if (value == OrientationRequested.PORTRAIT) { 2231 pSupported = true; 2232 } else if (value == OrientationRequested.LANDSCAPE) { 2233 lSupported = true; 2234 } else if (value == OrientationRequested.REVERSE_PORTRAIT) { 2235 rpSupported = true; 2236 } else if (value == OrientationRequested.REVERSE_LANDSCAPE) { 2237 rlSupported = true; 2238 } 2239 } 2240 } 2241 } 2242 2243 2244 rbPortrait.setEnabled(pSupported); 2245 rbLandscape.setEnabled(lSupported); 2246 rbRevPortrait.setEnabled(rpSupported); 2247 rbRevLandscape.setEnabled(rlSupported); 2248 2249 OrientationRequested or = (OrientationRequested)asCurrent.get(orCategory); 2250 if (or == null || 2251 !psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) { 2252 2253 or = (OrientationRequested)psCurrent.getDefaultAttributeValue(orCategory); 2254 // need to validate if default is not supported 2255 if ((or != null) && 2256 !psCurrent.isAttributeValueSupported(or, docFlavor, asCurrent)) { 2257 or = null; 2258 Object values = 2259 psCurrent.getSupportedAttributeValues(orCategory, 2260 docFlavor, 2261 asCurrent); 2262 if (values instanceof OrientationRequested[]) { 2263 OrientationRequested[] orValues = 2264 (OrientationRequested[])values; 2265 if (orValues.length > 1) { 2266 // get the first in the list 2267 or = orValues[0]; 2268 } 2269 } 2270 } 2271 2272 if (or == null) { 2273 or = OrientationRequested.PORTRAIT; 2274 } 2275 asCurrent.add(or); 2276 } 2277 2278 if (or == OrientationRequested.PORTRAIT) { 2279 rbPortrait.setSelected(true); 2280 } else if (or == OrientationRequested.LANDSCAPE) { 2281 rbLandscape.setSelected(true); 2282 } else if (or == OrientationRequested.REVERSE_PORTRAIT) { 2283 rbRevPortrait.setSelected(true); 2284 } else { // if (or == OrientationRequested.REVERSE_LANDSCAPE) 2285 rbRevLandscape.setSelected(true); 2286 } 2287 } 2288 } 2289 2290 2291 2292 /** 2293 * The "Appearance" tab. Includes the controls for Chromaticity, 2294 * PrintQuality, JobPriority, JobName, and other related job attributes. 2295 */ 2296 @SuppressWarnings("serial") // Superclass is not serializable across versions 2297 private class AppearancePanel extends JPanel { 2298 2299 private ChromaticityPanel pnlChromaticity; 2300 private QualityPanel pnlQuality; 2301 private JobAttributesPanel pnlJobAttributes; 2302 private SidesPanel pnlSides; 2303 2304 public AppearancePanel() { 2305 super(); 2306 2307 GridBagLayout gridbag = new GridBagLayout(); 2308 GridBagConstraints c = new GridBagConstraints(); 2309 2310 setLayout(gridbag); 2311 2312 c.fill = GridBagConstraints.BOTH; 2313 c.insets = panelInsets; 2314 c.weightx = 1.0; 2315 c.weighty = 1.0; 2316 2317 c.gridwidth = GridBagConstraints.RELATIVE; 2318 pnlChromaticity = new ChromaticityPanel(); 2319 addToGB(pnlChromaticity, this, gridbag, c); 2320 2321 c.gridwidth = GridBagConstraints.REMAINDER; 2322 pnlQuality = new QualityPanel(); 2323 addToGB(pnlQuality, this, gridbag, c); 2324 2325 c.gridwidth = 1; 2326 pnlSides = new SidesPanel(); 2327 addToGB(pnlSides, this, gridbag, c); 2328 2329 c.gridwidth = GridBagConstraints.REMAINDER; 2330 pnlJobAttributes = new JobAttributesPanel(); 2331 addToGB(pnlJobAttributes, this, gridbag, c); 2332 2333 } 2334 2335 public void updateInfo() { 2336 pnlChromaticity.updateInfo(); 2337 pnlQuality.updateInfo(); 2338 pnlSides.updateInfo(); 2339 pnlJobAttributes.updateInfo(); 2340 } 2341 } 2342 2343 @SuppressWarnings("serial") // Superclass is not serializable across versions 2344 private class ChromaticityPanel extends JPanel 2345 implements ActionListener 2346 { 2347 private final String strTitle = getMsg("border.chromaticity"); 2348 private JRadioButton rbMonochrome, rbColor; 2349 2350 public ChromaticityPanel() { 2351 super(); 2352 2353 GridBagLayout gridbag = new GridBagLayout(); 2354 GridBagConstraints c = new GridBagConstraints(); 2355 2356 setLayout(gridbag); 2357 setBorder(BorderFactory.createTitledBorder(strTitle)); 2358 2359 c.fill = GridBagConstraints.BOTH; 2360 c.gridwidth = GridBagConstraints.REMAINDER; 2361 c.weighty = 1.0; 2362 2363 ButtonGroup bg = new ButtonGroup(); 2364 rbMonochrome = createRadioButton("radiobutton.monochrome", this); 2365 rbMonochrome.setSelected(true); 2366 bg.add(rbMonochrome); 2367 addToGB(rbMonochrome, this, gridbag, c); 2368 rbColor = createRadioButton("radiobutton.color", this); 2369 bg.add(rbColor); 2370 addToGB(rbColor, this, gridbag, c); 2371 } 2372 2373 public void actionPerformed(ActionEvent e) { 2374 Object source = e.getSource(); 2375 2376 // REMIND: use isSameAs if we move to a IconRB in the future 2377 if (source == rbMonochrome) { 2378 asCurrent.add(Chromaticity.MONOCHROME); 2379 } else if (source == rbColor) { 2380 asCurrent.add(Chromaticity.COLOR); 2381 } 2382 } 2383 2384 public void updateInfo() { 2385 Class<Chromaticity> chCategory = Chromaticity.class; 2386 boolean monoSupported = false; 2387 boolean colorSupported = false; 2388 2389 if (isAWT) { 2390 monoSupported = true; 2391 colorSupported = true; 2392 } else 2393 if (psCurrent.isAttributeCategorySupported(chCategory)) { 2394 Object values = 2395 psCurrent.getSupportedAttributeValues(chCategory, 2396 docFlavor, 2397 asCurrent); 2398 2399 if (values instanceof Chromaticity[]) { 2400 Chromaticity[] cvalues = (Chromaticity[])values; 2401 2402 for (int i = 0; i < cvalues.length; i++) { 2403 Chromaticity value = cvalues[i]; 2404 2405 if (value == Chromaticity.MONOCHROME) { 2406 monoSupported = true; 2407 } else if (value == Chromaticity.COLOR) { 2408 colorSupported = true; 2409 } 2410 } 2411 } 2412 } 2413 2414 2415 rbMonochrome.setEnabled(monoSupported); 2416 rbColor.setEnabled(colorSupported); 2417 2418 Chromaticity ch = (Chromaticity)asCurrent.get(chCategory); 2419 if (ch == null) { 2420 ch = (Chromaticity)psCurrent.getDefaultAttributeValue(chCategory); 2421 if (ch == null) { 2422 ch = Chromaticity.MONOCHROME; 2423 } 2424 } 2425 2426 if (ch == Chromaticity.MONOCHROME) { 2427 rbMonochrome.setSelected(true); 2428 } else { // if (ch == Chromaticity.COLOR) 2429 rbColor.setSelected(true); 2430 } 2431 } 2432 } 2433 2434 @SuppressWarnings("serial") // Superclass is not serializable across versions 2435 private class QualityPanel extends JPanel 2436 implements ActionListener 2437 { 2438 private final String strTitle = getMsg("border.quality"); 2439 private JRadioButton rbDraft, rbNormal, rbHigh; 2440 2441 public QualityPanel() { 2442 super(); 2443 2444 GridBagLayout gridbag = new GridBagLayout(); 2445 GridBagConstraints c = new GridBagConstraints(); 2446 2447 setLayout(gridbag); 2448 setBorder(BorderFactory.createTitledBorder(strTitle)); 2449 2450 c.fill = GridBagConstraints.BOTH; 2451 c.gridwidth = GridBagConstraints.REMAINDER; 2452 c.weighty = 1.0; 2453 2454 ButtonGroup bg = new ButtonGroup(); 2455 rbDraft = createRadioButton("radiobutton.draftq", this); 2456 bg.add(rbDraft); 2457 addToGB(rbDraft, this, gridbag, c); 2458 rbNormal = createRadioButton("radiobutton.normalq", this); 2459 rbNormal.setSelected(true); 2460 bg.add(rbNormal); 2461 addToGB(rbNormal, this, gridbag, c); 2462 rbHigh = createRadioButton("radiobutton.highq", this); 2463 bg.add(rbHigh); 2464 addToGB(rbHigh, this, gridbag, c); 2465 } 2466 2467 public void actionPerformed(ActionEvent e) { 2468 Object source = e.getSource(); 2469 2470 if (source == rbDraft) { 2471 asCurrent.add(PrintQuality.DRAFT); 2472 } else if (source == rbNormal) { 2473 asCurrent.add(PrintQuality.NORMAL); 2474 } else if (source == rbHigh) { 2475 asCurrent.add(PrintQuality.HIGH); 2476 } 2477 } 2478 2479 public void updateInfo() { 2480 Class<PrintQuality> pqCategory = PrintQuality.class; 2481 boolean draftSupported = false; 2482 boolean normalSupported = false; 2483 boolean highSupported = false; 2484 2485 if (isAWT) { 2486 draftSupported = true; 2487 normalSupported = true; 2488 highSupported = true; 2489 } else 2490 if (psCurrent.isAttributeCategorySupported(pqCategory)) { 2491 Object values = 2492 psCurrent.getSupportedAttributeValues(pqCategory, 2493 docFlavor, 2494 asCurrent); 2495 2496 if (values instanceof PrintQuality[]) { 2497 PrintQuality[] qvalues = (PrintQuality[])values; 2498 2499 for (int i = 0; i < qvalues.length; i++) { 2500 PrintQuality value = qvalues[i]; 2501 2502 if (value == PrintQuality.DRAFT) { 2503 draftSupported = true; 2504 } else if (value == PrintQuality.NORMAL) { 2505 normalSupported = true; 2506 } else if (value == PrintQuality.HIGH) { 2507 highSupported = true; 2508 } 2509 } 2510 } 2511 } 2512 2513 rbDraft.setEnabled(draftSupported); 2514 rbNormal.setEnabled(normalSupported); 2515 rbHigh.setEnabled(highSupported); 2516 2517 PrintQuality pq = (PrintQuality)asCurrent.get(pqCategory); 2518 if (pq == null) { 2519 pq = (PrintQuality)psCurrent.getDefaultAttributeValue(pqCategory); 2520 if (pq == null) { 2521 pq = PrintQuality.NORMAL; 2522 } 2523 } 2524 2525 if (pq == PrintQuality.DRAFT) { 2526 rbDraft.setSelected(true); 2527 } else if (pq == PrintQuality.NORMAL) { 2528 rbNormal.setSelected(true); 2529 } else { // if (pq == PrintQuality.HIGH) 2530 rbHigh.setSelected(true); 2531 } 2532 } 2533 2534 2535 } 2536 2537 @SuppressWarnings("serial") // Superclass is not serializable across versions 2538 private class SidesPanel extends JPanel 2539 implements ActionListener 2540 { 2541 private final String strTitle = getMsg("border.sides"); 2542 private IconRadioButton rbOneSide, rbTumble, rbDuplex; 2543 2544 public SidesPanel() { 2545 super(); 2546 2547 GridBagLayout gridbag = new GridBagLayout(); 2548 GridBagConstraints c = new GridBagConstraints(); 2549 2550 setLayout(gridbag); 2551 setBorder(BorderFactory.createTitledBorder(strTitle)); 2552 2553 c.fill = GridBagConstraints.BOTH; 2554 c.insets = compInsets; 2555 c.weighty = 1.0; 2556 c.gridwidth = GridBagConstraints.REMAINDER; 2557 2558 ButtonGroup bg = new ButtonGroup(); 2559 rbOneSide = new IconRadioButton("radiobutton.oneside", 2560 "oneside.png", true, 2561 bg, this); 2562 rbOneSide.addActionListener(this); 2563 addToGB(rbOneSide, this, gridbag, c); 2564 rbTumble = new IconRadioButton("radiobutton.tumble", 2565 "tumble.png", false, 2566 bg, this); 2567 rbTumble.addActionListener(this); 2568 addToGB(rbTumble, this, gridbag, c); 2569 rbDuplex = new IconRadioButton("radiobutton.duplex", 2570 "duplex.png", false, 2571 bg, this); 2572 rbDuplex.addActionListener(this); 2573 c.gridwidth = GridBagConstraints.REMAINDER; 2574 addToGB(rbDuplex, this, gridbag, c); 2575 } 2576 2577 public void actionPerformed(ActionEvent e) { 2578 Object source = e.getSource(); 2579 2580 if (rbOneSide.isSameAs(source)) { 2581 asCurrent.add(Sides.ONE_SIDED); 2582 } else if (rbTumble.isSameAs(source)) { 2583 asCurrent.add(Sides.TUMBLE); 2584 } else if (rbDuplex.isSameAs(source)) { 2585 asCurrent.add(Sides.DUPLEX); 2586 } 2587 } 2588 2589 public void updateInfo() { 2590 Class<Sides> sdCategory = Sides.class; 2591 boolean osSupported = false; 2592 boolean tSupported = false; 2593 boolean dSupported = false; 2594 2595 if (psCurrent.isAttributeCategorySupported(sdCategory)) { 2596 Object values = 2597 psCurrent.getSupportedAttributeValues(sdCategory, 2598 docFlavor, 2599 asCurrent); 2600 2601 if (values instanceof Sides[]) { 2602 Sides[] svalues = (Sides[])values; 2603 2604 for (int i = 0; i < svalues.length; i++) { 2605 Sides value = svalues[i]; 2606 2607 if (value == Sides.ONE_SIDED) { 2608 osSupported = true; 2609 } else if (value == Sides.TUMBLE) { 2610 tSupported = true; 2611 } else if (value == Sides.DUPLEX) { 2612 dSupported = true; 2613 } 2614 } 2615 } 2616 } 2617 rbOneSide.setEnabled(osSupported); 2618 rbTumble.setEnabled(tSupported); 2619 rbDuplex.setEnabled(dSupported); 2620 2621 Sides sd = (Sides)asCurrent.get(sdCategory); 2622 if (sd == null) { 2623 sd = (Sides)psCurrent.getDefaultAttributeValue(sdCategory); 2624 if (sd == null) { 2625 sd = Sides.ONE_SIDED; 2626 } 2627 } 2628 2629 if (sd == Sides.ONE_SIDED) { 2630 rbOneSide.setSelected(true); 2631 } else if (sd == Sides.TUMBLE) { 2632 rbTumble.setSelected(true); 2633 } else { // if (sd == Sides.DUPLEX) 2634 rbDuplex.setSelected(true); 2635 } 2636 } 2637 } 2638 2639 2640 @SuppressWarnings("serial") // Superclass is not serializable across versions 2641 private class JobAttributesPanel extends JPanel 2642 implements ActionListener, ChangeListener, FocusListener 2643 { 2644 private final String strTitle = getMsg("border.jobattributes"); 2645 private JLabel lblPriority, lblJobName, lblUserName; 2646 private JSpinner spinPriority; 2647 private SpinnerNumberModel snModel; 2648 private JCheckBox cbJobSheets; 2649 private JTextField tfJobName, tfUserName; 2650 2651 public JobAttributesPanel() { 2652 super(); 2653 2654 GridBagLayout gridbag = new GridBagLayout(); 2655 GridBagConstraints c = new GridBagConstraints(); 2656 2657 setLayout(gridbag); 2658 setBorder(BorderFactory.createTitledBorder(strTitle)); 2659 2660 c.fill = GridBagConstraints.NONE; 2661 c.insets = compInsets; 2662 c.weighty = 1.0; 2663 2664 cbJobSheets = createCheckBox("checkbox.jobsheets", this); 2665 c.anchor = GridBagConstraints.LINE_START; 2666 addToGB(cbJobSheets, this, gridbag, c); 2667 2668 JPanel pnlTop = new JPanel(); 2669 lblPriority = new JLabel(getMsg("label.priority"), JLabel.TRAILING); 2670 lblPriority.setDisplayedMnemonic(getMnemonic("label.priority")); 2671 2672 pnlTop.add(lblPriority); 2673 snModel = new SpinnerNumberModel(1, 1, 100, 1); 2674 spinPriority = new JSpinner(snModel); 2675 lblPriority.setLabelFor(spinPriority); 2676 // REMIND 2677 ((JSpinner.NumberEditor)spinPriority.getEditor()).getTextField().setColumns(3); 2678 spinPriority.addChangeListener(this); 2679 pnlTop.add(spinPriority); 2680 c.anchor = GridBagConstraints.LINE_END; 2681 c.gridwidth = GridBagConstraints.REMAINDER; 2682 pnlTop.getAccessibleContext().setAccessibleName( 2683 getMsg("label.priority")); 2684 addToGB(pnlTop, this, gridbag, c); 2685 2686 c.fill = GridBagConstraints.HORIZONTAL; 2687 c.anchor = GridBagConstraints.CENTER; 2688 c.weightx = 0.0; 2689 c.gridwidth = 1; 2690 char jmnemonic = getMnemonic("label.jobname"); 2691 lblJobName = new JLabel(getMsg("label.jobname"), JLabel.TRAILING); 2692 lblJobName.setDisplayedMnemonic(jmnemonic); 2693 addToGB(lblJobName, this, gridbag, c); 2694 c.weightx = 1.0; 2695 c.gridwidth = GridBagConstraints.REMAINDER; 2696 tfJobName = new JTextField(); 2697 lblJobName.setLabelFor(tfJobName); 2698 tfJobName.addFocusListener(this); 2699 tfJobName.setFocusAccelerator(jmnemonic); 2700 tfJobName.getAccessibleContext().setAccessibleName( 2701 getMsg("label.jobname")); 2702 addToGB(tfJobName, this, gridbag, c); 2703 2704 c.weightx = 0.0; 2705 c.gridwidth = 1; 2706 char umnemonic = getMnemonic("label.username"); 2707 lblUserName = new JLabel(getMsg("label.username"), JLabel.TRAILING); 2708 lblUserName.setDisplayedMnemonic(umnemonic); 2709 addToGB(lblUserName, this, gridbag, c); 2710 c.gridwidth = GridBagConstraints.REMAINDER; 2711 tfUserName = new JTextField(); 2712 lblUserName.setLabelFor(tfUserName); 2713 tfUserName.addFocusListener(this); 2714 tfUserName.setFocusAccelerator(umnemonic); 2715 tfUserName.getAccessibleContext().setAccessibleName( 2716 getMsg("label.username")); 2717 addToGB(tfUserName, this, gridbag, c); 2718 } 2719 2720 public void actionPerformed(ActionEvent e) { 2721 if (cbJobSheets.isSelected()) { 2722 asCurrent.add(JobSheets.STANDARD); 2723 } else { 2724 asCurrent.add(JobSheets.NONE); 2725 } 2726 } 2727 2728 public void stateChanged(ChangeEvent e) { 2729 asCurrent.add(new JobPriority(snModel.getNumber().intValue())); 2730 } 2731 2732 public void focusLost(FocusEvent e) { 2733 Object source = e.getSource(); 2734 2735 if (source == tfJobName) { 2736 asCurrent.add(new JobName(tfJobName.getText(), 2737 Locale.getDefault())); 2738 } else if (source == tfUserName) { 2739 asCurrent.add(new RequestingUserName(tfUserName.getText(), 2740 Locale.getDefault())); 2741 } 2742 } 2743 2744 public void focusGained(FocusEvent e) {} 2745 2746 public void updateInfo() { 2747 Class<JobSheets> jsCategory = JobSheets.class; 2748 Class<JobPriority> jpCategory = JobPriority.class; 2749 Class<JobName> jnCategory = JobName.class; 2750 Class<RequestingUserName> unCategory = RequestingUserName.class; 2751 boolean jsSupported = false; 2752 boolean jpSupported = false; 2753 boolean jnSupported = false; 2754 boolean unSupported = false; 2755 2756 // setup JobSheets checkbox 2757 if (psCurrent.isAttributeCategorySupported(jsCategory)) { 2758 jsSupported = true; 2759 } 2760 JobSheets js = (JobSheets)asCurrent.get(jsCategory); 2761 if (js == null) { 2762 js = (JobSheets)psCurrent.getDefaultAttributeValue(jsCategory); 2763 if (js == null) { 2764 js = JobSheets.STANDARD; 2765 } 2766 } 2767 cbJobSheets.setSelected(js != JobSheets.NONE && jsSupported); 2768 cbJobSheets.setEnabled(jsSupported); 2769 2770 // setup JobPriority spinner 2771 if (!isAWT && psCurrent.isAttributeCategorySupported(jpCategory)) { 2772 jpSupported = true; 2773 } 2774 JobPriority jp = (JobPriority)asCurrent.get(jpCategory); 2775 if (jp == null) { 2776 jp = (JobPriority)psCurrent.getDefaultAttributeValue(jpCategory); 2777 if (jp == null) { 2778 jp = new JobPriority(1); 2779 } 2780 } 2781 int value = jp.getValue(); 2782 if ((value < 1) || (value > 100)) { 2783 value = 1; 2784 } 2785 snModel.setValue(value); 2786 lblPriority.setEnabled(jpSupported); 2787 spinPriority.setEnabled(jpSupported); 2788 2789 // setup JobName text field 2790 if (psCurrent.isAttributeCategorySupported(jnCategory)) { 2791 jnSupported = true; 2792 } 2793 JobName jn = (JobName)asCurrent.get(jnCategory); 2794 if (jn == null) { 2795 jn = (JobName)psCurrent.getDefaultAttributeValue(jnCategory); 2796 if (jn == null) { 2797 jn = new JobName("", Locale.getDefault()); 2798 } 2799 } 2800 tfJobName.setText(jn.getValue()); 2801 tfJobName.setEnabled(jnSupported); 2802 lblJobName.setEnabled(jnSupported); 2803 2804 // setup RequestingUserName text field 2805 if (!isAWT && psCurrent.isAttributeCategorySupported(unCategory)) { 2806 unSupported = true; 2807 } 2808 RequestingUserName un = (RequestingUserName)asCurrent.get(unCategory); 2809 if (un == null) { 2810 un = (RequestingUserName)psCurrent.getDefaultAttributeValue(unCategory); 2811 if (un == null) { 2812 un = new RequestingUserName("", Locale.getDefault()); 2813 } 2814 } 2815 tfUserName.setText(un.getValue()); 2816 tfUserName.setEnabled(unSupported); 2817 lblUserName.setEnabled(unSupported); 2818 } 2819 } 2820 2821 2822 2823 2824 /** 2825 * A special widget that groups a JRadioButton with an associated icon, 2826 * placed to the left of the radio button. 2827 */ 2828 @SuppressWarnings("serial") // Superclass is not serializable across versions 2829 private class IconRadioButton extends JPanel { 2830 2831 private JRadioButton rb; 2832 private JLabel lbl; 2833 2834 public IconRadioButton(String key, String img, boolean selected, 2835 ButtonGroup bg, ActionListener al) 2836 { 2837 super(new FlowLayout(FlowLayout.LEADING)); 2838 final URL imgURL = getImageResource(img); 2839 Icon icon = java.security.AccessController.doPrivileged( 2840 new java.security.PrivilegedAction<Icon>() { 2841 public Icon run() { 2842 Icon icon = new ImageIcon(imgURL); 2843 return icon; 2844 } 2845 }); 2846 lbl = new JLabel(icon); 2847 add(lbl); 2848 2849 rb = createRadioButton(key, al); 2850 rb.setSelected(selected); 2851 addToBG(rb, this, bg); 2852 } 2853 2854 public void addActionListener(ActionListener al) { 2855 rb.addActionListener(al); 2856 } 2857 2858 public boolean isSameAs(Object source) { 2859 return (rb == source); 2860 } 2861 2862 public void setEnabled(boolean enabled) { 2863 rb.setEnabled(enabled); 2864 lbl.setEnabled(enabled); 2865 } 2866 2867 public boolean isSelected() { 2868 return rb.isSelected(); 2869 } 2870 2871 public void setSelected(boolean selected) { 2872 rb.setSelected(selected); 2873 } 2874 } 2875 2876 /** 2877 * Similar in functionality to the default JFileChooser, except this 2878 * chooser will pop up a "Do you want to overwrite..." dialog if the 2879 * user selects a file that already exists. 2880 */ 2881 @SuppressWarnings("serial") // JDK implementation class 2882 private class ValidatingFileChooser extends JFileChooser { 2883 public void approveSelection() { 2884 File selected = getSelectedFile(); 2885 boolean exists; 2886 2887 try { 2888 exists = selected.exists(); 2889 } catch (SecurityException e) { 2890 exists = false; 2891 } 2892 2893 if (exists) { 2894 int val; 2895 val = JOptionPane.showConfirmDialog(this, 2896 getMsg("dialog.overwrite"), 2897 getMsg("dialog.owtitle"), 2898 JOptionPane.YES_NO_OPTION); 2899 if (val != JOptionPane.YES_OPTION) { 2900 return; 2901 } 2902 } 2903 2904 try { 2905 if (selected.createNewFile()) { 2906 selected.delete(); 2907 } 2908 } catch (IOException ioe) { 2909 JOptionPane.showMessageDialog(this, 2910 getMsg("dialog.writeerror")+" "+selected, 2911 getMsg("dialog.owtitle"), 2912 JOptionPane.WARNING_MESSAGE); 2913 return; 2914 } catch (SecurityException se) { 2915 //There is already file read/write access so at this point 2916 // only delete access is denied. Just ignore it because in 2917 // most cases the file created in createNewFile gets 2918 // overwritten anyway. 2919 } 2920 File pFile = selected.getParentFile(); 2921 if ((selected.exists() && 2922 (!selected.isFile() || !selected.canWrite())) || 2923 ((pFile != null) && 2924 (!pFile.exists() || (pFile.exists() && !pFile.canWrite())))) { 2925 JOptionPane.showMessageDialog(this, 2926 getMsg("dialog.writeerror")+" "+selected, 2927 getMsg("dialog.owtitle"), 2928 JOptionPane.WARNING_MESSAGE); 2929 return; 2930 } 2931 2932 super.approveSelection(); 2933 } 2934 } 2935 }