Source Code Cross Referenced for ServiceUIDialog.java in  » Apache-Harmony-Java-SE » org-package » org » apache » harmony » x » print » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Apache Harmony Java SE » org package » org.apache.harmony.x.print 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         *  Licensed to the Apache Software Foundation (ASF) under one or more
0003:         *  contributor license agreements.  See the NOTICE file distributed with
0004:         *  this work for additional information regarding copyright ownership.
0005:         *  The ASF licenses this file to You under the Apache License, Version 2.0
0006:         *  (the "License"); you may not use this file except in compliance with
0007:         *  the License.  You may obtain a copy of the License at
0008:         *
0009:         *     http://www.apache.org/licenses/LICENSE-2.0
0010:         *
0011:         *  Unless required by applicable law or agreed to in writing, software
0012:         *  distributed under the License is distributed on an "AS IS" BASIS,
0013:         *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014:         *  See the License for the specific language governing permissions and
0015:         *  limitations under the License.
0016:         */
0017:
0018:        /*
0019:         * ServiceUIDialog class - the class for the PrintService selecting
0020:         * and page setup dialogs.
0021:         * 
0022:         * This class can be used in the following cases:
0023:         * 
0024:         * 1. ServiceUI.printDialog(...) method calls this class to show dialog for the
0025:         *    PrintServices selecting;
0026:         * 
0027:         * 2. Default implementation of java.awt.prin.PrinterJob class may call this
0028:         *    class to show dialogs in printDialog(), printDialog
0029:         *    (PrintRequestAttributeSet), pageDialog(), pageDialog(PageFormat) methods.
0030:         *    (Please, see org.apache.harmony.x.print.awt.PSPrinterJob class and 
0031:         *    org.apache.harmony.x.print.DefaultPrinterJob test class as examples of 
0032:         *    ServiceUIDialog using for the awt.print printing)
0033:         * 
0034:         * 
0035:         * Our printing dialogs look like competitor dialogs, however there are some
0036:         * distinctions and problems there:
0037:         * 
0038:         * 1. Internationalization - will we internationalize the dialogs? It is not
0039:         *    internationalized yet.
0040:         * 
0041:         * 2. Icons for Orientation ("Page Setup" tab) and Sides ("Appearance" tab) - 
0042:         *    how to obtain them?
0043:         * 
0044:         * 3. How to select Media attribute ("Page Setup" tab)? Competitor dialogs 
0045:         *    contain "Source" and "Size" comboboxes. "Source" combobox contains 
0046:         *    MediaTray list and "Size" combobox contains all the others Medias 
0047:         *    including non-standard (i.e. MediaSizeName, MediaName and all the others
0048:         *    but the MediaTray). Do we really need both these comboboxes? Which Media
0049:         *    (from "Size" or "Source" combobox) should we add into the result 
0050:         *    attribute set? Specification says nothing. Now I made "Source" combobox
0051:         *    invisible and add all the Medias supported by the selected PrintService 
0052:         *    into the "Size" combobox.
0053:         * 
0054:         * 4. How to use Margins fields ("Left (mm)", "Right (mm)", "Top (mm)", 
0055:         *    "Bottom (mm)" fields in the "Page Setup" tab)? 
0056:         *    There is only one standard printing attribute related with paper margins 
0057:         *    - MediaPrintableArea. It is a printing attribute used to distingwish 
0058:         *    printable and not printable areas of media. However, this attribute is 
0059:         *    not described as the edges of the paper: MediaPrintableArea is defined 
0060:         *    as a rectangle with its x and y coordinates and its width and height. So,
0061:         *    this attribute depends on selected media size. But printing dialog
0062:         *    contains input fields for margins, not for printable area. In other 
0063:         *    words, we can construct MediaPrintableArea attribute (using dialog 
0064:         *    margins input fields) for the result attribute set only if we can get
0065:         *    selected Media width and height, i.e. if selected media is MediaSizeName
0066:         *    attribute. To avoid this problem, we launched additional (non-standard)
0067:         *    printing attribute - MediaMargins. We suppose that our standard print 
0068:         *    services will support this attribute. 
0069:         *    As a standard java attribute, MediaPrintableArea always should have 
0070:         *    the first priority in case of conflict between MediaPrintableArea and 
0071:         *    MediaMargins attributes. It means, that if we have MediaSizeName, 
0072:         *    MediaPrintableArea and MediaMargins in print request attribute set, we
0073:         *    should use MediaSizeName + MediaPrintableArea to calculate margins. 
0074:         *    However, if we can not get Media size for the required media (for
0075:         *    example, for MediaTray), we may work with Margins attribute, if 
0076:         *    PrintSerevice supports MediaMargins.
0077:         *    Using of MediaMargins attribute is also very convinient if we are setting
0078:         *    page parameters (for example, in standard page dialog) and do not know 
0079:         *    Media which will be used for the printing yet.
0080:         *    Please, see fillMarginsFields() method for more details about the 
0081:         *    MediaPrintableArea and MediaMargins attributes using in dialog result 
0082:         *    attribute set. 
0083:         *    Please, see also comments for the MediaMargins class. 
0084:         * 
0085:         * 5. Specification says nothing about the using of "Properties" button, 
0086:         *    however it reads that if print service provides any vendor extention,
0087:         *    this extention may be accessibly throw additional vendor supplied 
0088:         *    dialog tab panel.
0089:         *    So, I made "Properties" button invisible now and added "Vendor Supplied"
0090:         *    tab instead. I make "Vendor supplied" tab visible if selected print 
0091:         *    service provides some kinds of vendor extentions.
0092:         * 
0093:         * 6. The main problem is that current MRTD version does not support many Swing
0094:         *    components yet, so this dialog can not work now.
0095:         */
0096:
0097:        package org.apache.harmony.x.print;
0098:
0099:        import java.awt.Dialog;
0100:        import java.awt.Frame;
0101:        import java.awt.GraphicsConfiguration;
0102:        import java.awt.GraphicsEnvironment;
0103:        import java.awt.GridBagConstraints;
0104:        import java.awt.GridBagLayout;
0105:        import java.awt.HeadlessException;
0106:        import java.awt.Panel;
0107:        import java.awt.Window;
0108:        import java.awt.event.ActionEvent;
0109:        import java.awt.event.ActionListener;
0110:        import java.awt.event.WindowAdapter;
0111:        import java.awt.event.WindowEvent;
0112:        import java.io.File;
0113:        import java.io.FilePermission;
0114:        import java.net.URI;
0115:        import java.security.AccessController;
0116:        import java.security.Permission;
0117:        import java.security.PrivilegedAction;
0118:        import java.text.ParseException;
0119:        import java.util.Locale;
0120:
0121:        import javax.print.DocFlavor;
0122:        import javax.print.PrintService;
0123:        import javax.print.PrintServiceLookup;
0124:        import javax.print.ServiceUIFactory;
0125:        import javax.print.attribute.Attribute;
0126:        import javax.print.attribute.HashPrintRequestAttributeSet;
0127:        import javax.print.attribute.PrintRequestAttributeSet;
0128:        import javax.print.attribute.Size2DSyntax;
0129:        import javax.print.attribute.TextSyntax;
0130:        import javax.print.attribute.standard.Chromaticity;
0131:        import javax.print.attribute.standard.Copies;
0132:        import javax.print.attribute.standard.CopiesSupported;
0133:        import javax.print.attribute.standard.Destination;
0134:        import javax.print.attribute.standard.JobName;
0135:        import javax.print.attribute.standard.JobPriority;
0136:        import javax.print.attribute.standard.JobSheets;
0137:        import javax.print.attribute.standard.Media;
0138:        import javax.print.attribute.standard.MediaPrintableArea;
0139:        import javax.print.attribute.standard.MediaSize;
0140:        import javax.print.attribute.standard.MediaSizeName;
0141:        import javax.print.attribute.standard.OrientationRequested;
0142:        import javax.print.attribute.standard.PageRanges;
0143:        import javax.print.attribute.standard.PrintQuality;
0144:        import javax.print.attribute.standard.PrinterInfo;
0145:        import javax.print.attribute.standard.PrinterIsAcceptingJobs;
0146:        import javax.print.attribute.standard.PrinterMakeAndModel;
0147:        import javax.print.attribute.standard.RequestingUserName;
0148:        import javax.print.attribute.standard.SheetCollate;
0149:        import javax.print.attribute.standard.Sides;
0150:        import javax.swing.ButtonGroup;
0151:        import javax.swing.JComponent;
0152:        import javax.swing.JDialog;
0153:        import javax.swing.JFileChooser;
0154:        import javax.swing.JOptionPane;
0155:        import javax.swing.JPanel;
0156:        import javax.swing.JRadioButton;
0157:        import javax.swing.SpinnerNumberModel;
0158:        import javax.swing.event.ChangeEvent;
0159:        import javax.swing.event.ChangeListener;
0160:        import javax.swing.text.NumberFormatter;
0161:
0162:        import org.apache.harmony.x.print.attributes.MediaMargins;
0163:
0164:        public class ServiceUIDialog extends ServiceUIDialogTemplate {
0165:
0166:            // State of dialog:
0167:            public static int APPROVE_PRINT = 1; // OK button was pressed
0168:            public static int CANSEL_PRINT = -1; // Cancel button was pressed
0169:            public static int SETUP_ERROR = 2; // Dialog Setup was finished with 
0170:            // error, dialog can not be shown
0171:            public static int SETUP_OK = 3; // Dialog setup was OK, 
0172:            // you can show the dialog
0173:            int dialogResult = 0; // Current dialog status
0174:
0175:            // Dialog type:
0176:            public static int PRINT_DIALOG = 1; // Dialog for PrintService selecting,
0177:            // all dialog tabs are visible 
0178:            public static int PAGE_DIALOG = 2; // Page setup dialog:
0179:            // only PageSetup dialog tab is visible
0180:            private int dialogType = PRINT_DIALOG; // dialog type
0181:
0182:            PrintService[] services = null; // Print services array for the choice
0183:
0184:            private DocFlavor flavor = null; // DocFlavor for the dialog
0185:
0186:            private PrintRequestAttributeSet attrs = null;
0187:            // AttributeSet for the dialog creation
0188:            private PrintRequestAttributeSet newAttrs = null;
0189:            // Result AttributeSet
0190:
0191:            PrintService myService = null; // Last selected PrintService
0192:
0193:            // Button groups:
0194:            ButtonGroup prnRngGrp = null;
0195:            ButtonGroup orientGrp = null;
0196:            ButtonGroup colorGrp = null;
0197:            ButtonGroup sidesGrp = null;
0198:            ButtonGroup qualGrp = null;
0199:
0200:            // Last selected Orientation
0201:            OrientationRequested lastOrient = null;
0202:
0203:            // True means that dialog fields were not initialized yet.
0204:            boolean firstUse = true;
0205:
0206:            // Do we have permitions for the Destination attribute using?
0207:            private Permission destPermission = new FilePermission(
0208:                    "<<ALL FILES>>", "read,write");
0209:
0210:            //---------------------------------------------------------------------
0211:            /*
0212:             * Constructor for the PRINT_DIALOG dialog type. 
0213:             * The dialog is modal. 
0214:             * It can be called from javax.print.ServiceUI.printDialog(...) and from 
0215:             * printDialog(), printDialog(PrintRequestAttributeSet) methods of default 
0216:             * java.awt.print.PrinterJob class implementation.
0217:             * 
0218:             * Parameters:
0219:             *  gc - GraphicsConfiguration to select screen. If gc is null, default screen 
0220:             *       is used.
0221:             *  x - x location of the dialog in screen coordinates
0222:             *  y - y location of the dialog in screen coordinates
0223:             *  services - PrintServices array to be browsable (should be non-null)
0224:             *  defPrintService - initially selected PrintService index in services array
0225:             *                    (should be more then 0 and less then services array 
0226:             *                    length)
0227:             *  flavor - printed DocFlavor (may be null) 
0228:             *  attrs - Initial print request attribute set. It can not be null, but may be
0229:             *          empty. On output this attribute set reflects changes made by user.
0230:             *  owner - dialog owner, should be Frame or Dialog.
0231:             * 
0232:             * Throws:
0233:             *  HeadlessException if current graphics environment is headless
0234:             * 
0235:             * Set dialogResult to SETUP_ERROR if HeadlessException was thrown, owner is 
0236:             * not Frame or Dialog object, services array is null or empty, defServiceIndex
0237:             * is incorrect or attrs is null; set dialogResult to SETUP_OK otherwise. 
0238:             */
0239:            public ServiceUIDialog(GraphicsConfiguration gc, int x, int y,
0240:                    PrintService[] dialogServices, int defServiceIndex,
0241:                    DocFlavor dialogFlavor,
0242:                    PrintRequestAttributeSet dialogAttrs, Window owner) {
0243:                if (GraphicsEnvironment.isHeadless()) {
0244:                    dialogResult = SETUP_ERROR;
0245:                    throw new HeadlessException();
0246:                }
0247:
0248:                if (owner instanceof  Frame) {
0249:                    printDialog = new JDialog((Frame) owner, "Print", true, gc);
0250:                } else if (owner instanceof  Dialog) {
0251:                    printDialog = new JDialog((Dialog) owner, "Print", true, gc);
0252:                } else {
0253:                    dialogResult = SETUP_ERROR;
0254:                }
0255:
0256:                if (printDialog != null) {
0257:                    printDialog.setSize(542, 444);
0258:                    printDialog.setLocation(x, y);
0259:                    printDialog.setContentPane(getPanel());
0260:                    printDialog.setResizable(false);
0261:                    dialogResult = setup(dialogServices, defServiceIndex,
0262:                            dialogFlavor, dialogAttrs);
0263:                }
0264:            }
0265:
0266:            /*
0267:             * Constructor for the PAGE_DIALOG dialog type. 
0268:             * The dialog is modal. 
0269:             * It can be called from pageDialog(), pageDialog(PageFormat) methods of 
0270:             * default java.awt.print.PrinterJob class implementation.
0271:             * 
0272:             * Parameters:
0273:             *  gc - GraphicsConfiguration to select screen. If gc is null, default screen 
0274:             *       is used.
0275:             *  x - x location of the dialog in screen coordinates
0276:             *  y - y location of the dialog in screen coordinates
0277:             *  aService - print service for this page dialog 
0278:             *  attrs - initial print request attribute set. It can not be null, but may be
0279:             *          empty. On output this attribute set reflects changes made by user.
0280:             *          Attributes not related with page foemat settings are ignored.
0281:             *  owner - dialog owner, should be Frame or Dialog.
0282:             * 
0283:             * Throws:
0284:             *  HeadlessException if current graphics environment is headless
0285:             * 
0286:             * Set dialogResult to SETUP_ERROR if HeadlessException was thrown, owner is 
0287:             * not Frame or Dialog object, aService or attrs is null.
0288:             */
0289:            public ServiceUIDialog(GraphicsConfiguration gc, int x, int y,
0290:                    PrintService aService,
0291:                    PrintRequestAttributeSet dialogAttrs, Window owner) {
0292:
0293:                dialogType = PAGE_DIALOG;
0294:
0295:                if (GraphicsEnvironment.isHeadless()) {
0296:                    dialogResult = SETUP_ERROR;
0297:                    throw new HeadlessException();
0298:                }
0299:
0300:                if (owner instanceof  Frame) {
0301:                    printDialog = new JDialog((Frame) owner, "Print", true, gc);
0302:                } else if (owner instanceof  Dialog) {
0303:                    printDialog = new JDialog((Dialog) owner, "Print", true, gc);
0304:                } else {
0305:                    dialogResult = SETUP_ERROR;
0306:                }
0307:
0308:                if (printDialog != null) {
0309:                    printDialog.setSize(530, 400);
0310:                    printDialog.setLocation(x, y);
0311:                    printDialog.setContentPane(getPageDialogPanel());
0312:                    printDialog.setResizable(false);
0313:                    dialogResult = pageSetup(aService, dialogAttrs);
0314:                }
0315:            }
0316:
0317:            // ---------------------------------------------------------------------
0318:            /*
0319:             * Shows the dialog if the dialog fields were successfully initialized before
0320:             */
0321:            public void show() {
0322:                if (dialogResult == SETUP_OK) {
0323:                    AccessController.doPrivileged(new PrivilegedAction() {
0324:                        public Object run() {
0325:                            printDialog.show();
0326:                            return null;
0327:                        }
0328:                    });
0329:                }
0330:            }
0331:
0332:            //---------------------------------------------------------------------
0333:            /*
0334:             * Initialization for PRINT_DIALOG dialog
0335:             * 
0336:             * Parameters:
0337:             *  services - PrintServices array to be browsable
0338:             *  defPrintService - initially selected PrintService index in services array
0339:             *  flavor - printed DocFlavor (may be null) 
0340:             *  attrs - Initial print request attribute set. 
0341:             * 
0342:             * Set dialogResult to SETUP_ERROR services array is null or empty, 
0343:             * defServiceIndex is incorrect or attrs is null; set dialogResult to SETUP_OK 
0344:             * otherwise. 
0345:             */
0346:            private int setup(PrintService[] dialogServices,
0347:                    int defServiceIndex, DocFlavor dialogFlavor,
0348:                    PrintRequestAttributeSet dialogAttrs) {
0349:                if ((dialogServices == null) || (dialogServices.length <= 0)
0350:                        || (defServiceIndex < 0)
0351:                        || (defServiceIndex >= dialogServices.length)
0352:                        || (dialogAttrs == null)) {
0353:                    return SETUP_ERROR;
0354:                }
0355:
0356:                services = dialogServices;
0357:                flavor = dialogFlavor;
0358:                attrs = dialogAttrs;
0359:                this .myService = services[defServiceIndex];
0360:                if (servicesBox.getItemCount() <= 0) {
0361:                    for (int i = 0; i < services.length; i++) {
0362:                        servicesBox.addItem(services[i].getName());
0363:                    }
0364:                }
0365:                newAttrs = new HashPrintRequestAttributeSet(attrs);
0366:
0367:                prepareDialog(); // Prepare dialog
0368:                servicesBox.setSelectedIndex(defServiceIndex);
0369:                // Select default PrintService and
0370:                // initialize dialog fields
0371:                firstUse = false;
0372:                return SETUP_OK;
0373:            }
0374:
0375:            /*
0376:             * Initialization for PAGE_DIALOG dialog
0377:             *  
0378:             * Parameters:
0379:             *  aService - print service for this page dialog 
0380:             *  attrs - initial print request attribute set.
0381:             * 
0382:             * Set dialogResult to SETUP_ERROR if aService or attrs is null.
0383:             */
0384:            private int pageSetup(PrintService aService,
0385:                    PrintRequestAttributeSet requestAttrs) {
0386:                myService = (aService == null) ? PrintServiceLookup
0387:                        .lookupDefaultPrintService() : aService;
0388:
0389:                if ((requestAttrs == null) || (aService == null)) {
0390:                    return SETUP_ERROR;
0391:                }
0392:
0393:                attrs = requestAttrs;
0394:                newAttrs = new HashPrintRequestAttributeSet(attrs);
0395:                myService = aService;
0396:
0397:                prepareDialog(); // prepare dialog
0398:                fillPageSetupFields(); // Initialize dialog fields
0399:                firstUse = false;
0400:                return SETUP_OK;
0401:            }
0402:
0403:            /*
0404:             * Dialog preparing: create button groups, add listeners to components, etc.
0405:             * This method logically should belong to the ServiceUIDialogTemplate class,
0406:             * however I place it in ServiceUIDialog because ServiceUIDialogTemplated was
0407:             * generated automatically by Eclipse Visual Editor
0408:             */
0409:            private void prepareDialog() {
0410:                JRadioButton[] orientArr = new JRadioButton[] { portraitBtn,
0411:                        landscapeBtn, rvportraitBtn, rvlandscapeBtn };
0412:                organizeButtonGroup(orientGrp, orientArr);
0413:
0414:                sourceBox.setVisible(false);
0415:                sourceLabel.setVisible(false);
0416:
0417:                if (dialogType == PRINT_DIALOG) {
0418:                    JRadioButton[] rangesArr = new JRadioButton[] { allRngBtn,
0419:                            pageRngBtn };
0420:                    JRadioButton[] colorsArr = new JRadioButton[] { monoBtn,
0421:                            colorBtn };
0422:                    JRadioButton[] sidesArr = new JRadioButton[] { oneSideBtn,
0423:                            tumbleBtn, duplexBtn };
0424:                    JRadioButton[] qualityArr = new JRadioButton[] { draftBtn,
0425:                            normalBtn, highBtn };
0426:
0427:                    organizeButtonGroup(prnRngGrp, rangesArr);
0428:                    organizeButtonGroup(colorGrp, colorsArr);
0429:                    organizeButtonGroup(sidesGrp, sidesArr);
0430:                    organizeButtonGroup(qualGrp, qualityArr);
0431:
0432:                    propertiesBtn.setVisible(false);
0433:
0434:                    prtSpinner.setModel(new SpinnerNumberModel(1, 1, 100, 1));
0435:
0436:                    cpSpinner.addChangeListener(new CopiesChangeListener());
0437:                    allRngBtn
0438:                            .addChangeListener(new PagesButtonChangeListener());
0439:                    pageRngBtn
0440:                            .addChangeListener(new PagesButtonChangeListener());
0441:                    servicesBox.addActionListener(new ServicesActionListener());
0442:                }
0443:
0444:                portraitBtn.addChangeListener(new OrientationChangeListener());
0445:                landscapeBtn.addChangeListener(new OrientationChangeListener());
0446:                rvportraitBtn
0447:                        .addChangeListener(new OrientationChangeListener());
0448:                rvlandscapeBtn
0449:                        .addChangeListener(new OrientationChangeListener());
0450:                printBtn.addActionListener(new OKButtonListener());
0451:                cancelBtn.addActionListener(new cancelButtonListener());
0452:
0453:                printDialog.addWindowListener(new WindowAdapter() {
0454:                    public void windowClosing(WindowEvent event) {
0455:                        dialogResult = CANSEL_PRINT;
0456:                    }
0457:                });
0458:            }
0459:
0460:            /*
0461:             * Adds all JRadioButtons from "buttons" array to "group" ButtonGroup
0462:             */
0463:            private void organizeButtonGroup(ButtonGroup group,
0464:                    JRadioButton[] buttons) {
0465:                group = new ButtonGroup();
0466:                for (int i = 0; i < buttons.length; i++) {
0467:                    group.add(buttons[i]);
0468:                }
0469:            }
0470:
0471:            //---------------------------------------------------------------------
0472:
0473:            /*
0474:             * ActionListener for the PrintServices combo box:
0475:             * Update all dialog fields if new print service is selected.
0476:             * As the user browses print services, attributes and values are copied to new
0477:             * display. If user select a print service which does not support particular
0478:             * attribute value, default attribute for this print service is used instead. 
0479:             * Unsupported attributes fields are disabled for the selected print service.
0480:             */
0481:            class ServicesActionListener implements  ActionListener {
0482:                public void actionPerformed(ActionEvent e) {
0483:                    if (firstUse
0484:                            || (myService != services[servicesBox
0485:                                    .getSelectedIndex()])) {
0486:                        myService = services[servicesBox.getSelectedIndex()];
0487:
0488:                        fillGeneralFields(); // General standard tab
0489:                        fillPageSetupFields(); // Page Setup standard tab
0490:                        fillAppearanceFields(); // Appearance standard tab
0491:                        fillVendorSuppliedTab(); // vendor supplied tab (if exists)
0492:                    }
0493:                }
0494:            } /* End of ServiceActionListener class */
0495:
0496:            //---------------------------------------------------------------------
0497:            /*
0498:             *General tab fields filling after PrintService selecting
0499:             */
0500:            void fillGeneralFields() {
0501:                fillStatusField();
0502:                fillTypeField();
0503:                fillInfoField();
0504:                filltoFileBox();
0505:                fillCopiesFields();
0506:                fillPrintRangeFields();
0507:            }
0508:
0509:            /*
0510:             * "Status" field from "General" tab:
0511:             * If selected print service does not support PrinterIsAcceptingJobs attribute,
0512:             * "Status" field is empty. Otherwise, it is "Accepting jobs" if 
0513:             * PrinterIsAcceptingJob attribute for this print service is ACCEPTING_JOBS; or 
0514:             * "Not accepting jobs" if PrinterIsAcceptingJobs is NOT_ACCEPTING_JOBS.  
0515:             */
0516:            void fillStatusField() {
0517:                String text;
0518:                PrinterIsAcceptingJobs job = (PrinterIsAcceptingJobs) myService
0519:                        .getAttribute(PrinterIsAcceptingJobs.class);
0520:                if (job != null) {
0521:                    text = job.equals(PrinterIsAcceptingJobs.ACCEPTING_JOBS) ? "Accepting jobs"
0522:                            : "Not accepting jobs";
0523:                } else {
0524:                    text = "";
0525:                }
0526:
0527:                statusText.setText(text);
0528:            }
0529:
0530:            /*
0531:             * "Type" field from "General" tab:
0532:             * This field contains PrinterMakeAndModel attribute of selected print service
0533:             * or is empty if service does not support PrinterMakeAndModel.
0534:             */
0535:            void fillTypeField() {
0536:                PrinterMakeAndModel type = (PrinterMakeAndModel) myService
0537:                        .getAttribute(PrinterMakeAndModel.class);
0538:                typeText.setText(type == null ? "" : type.getValue());
0539:            }
0540:
0541:            /*
0542:             * "Info" field from "General" tab:
0543:             * This field contains PrinterInfo attribute of selected print service
0544:             * or is empty if service does not support PrinterInfo.
0545:             */
0546:            void fillInfoField() {
0547:                PrinterInfo info = (PrinterInfo) myService
0548:                        .getAttribute(PrinterInfo.class);
0549:                infoText.setText(info == null ? "" : info.getValue());
0550:            }
0551:
0552:            /*
0553:             * "Print to file" combobox from "General" tab:
0554:             * This combobox will be enabled if Destination attribute is supported by 
0555:             * selected print service and user can write to file.
0556:             */
0557:            void filltoFileBox() {
0558:                if (firstUse && attrs.containsKey(Destination.class)) {
0559:                    toFileBox.setSelected(true);
0560:                }
0561:                toFileBox
0562:                        .setEnabled(checkFilePermission(destPermission)
0563:                                && myService
0564:                                        .isAttributeCategorySupported(Destination.class));
0565:            }
0566:
0567:            /*
0568:             * Checks if the user has given permission
0569:             */
0570:            boolean checkFilePermission(Permission permission) {
0571:                SecurityManager manager = System.getSecurityManager();
0572:                if (manager != null) {
0573:                    try {
0574:                        manager.checkPermission(permission);
0575:                        return true;
0576:                    } catch (SecurityException e) {
0577:                        return false;
0578:                    }
0579:                }
0580:                return true;
0581:            }
0582:
0583:            /*
0584:             * Copies and Collate fields
0585:             */
0586:            void fillCopiesFields() {
0587:                fillCopiesSpinner();
0588:                fillCollateBox();
0589:            }
0590:
0591:            /*
0592:             * "Number of copies" spinner from "General" tab:
0593:             * It is enabled if selected printer supports Copies attribute. Maximum and
0594:             * minimum values of the spinner are minimum and maximum supported Copies 
0595:             * values for selected print service.
0596:             */
0597:            void fillCopiesSpinner() {
0598:                boolean isEnabled = myService
0599:                        .isAttributeCategorySupported(Copies.class);
0600:
0601:                copiesLabel.setEnabled(isEnabled);
0602:                cpSpinner.setEnabled(isEnabled);
0603:
0604:                if (firstUse && !isEnabled) {
0605:                    int value = (attrs.containsKey(Copies.class) ? ((Copies) (attrs
0606:                            .get(Copies.class))).getValue()
0607:                            : 1);
0608:                    cpSpinner.setModel(new SpinnerNumberModel(value, value,
0609:                            value, 1));
0610:                }
0611:
0612:                if (isEnabled) {
0613:                    int value = (firstUse && attrs.containsKey(Copies.class) ? ((Copies) (attrs
0614:                            .get(Copies.class))).getValue()
0615:                            : ((Integer) cpSpinner.getValue()).intValue());
0616:                    CopiesSupported supported = (CopiesSupported) myService
0617:                            .getSupportedAttributeValues(Copies.class, flavor,
0618:                                    attrs);
0619:                    Copies defaul = (Copies) myService
0620:                            .getDefaultAttributeValue(Copies.class);
0621:
0622:                    if (supported == null) {
0623:                        /* 
0624:                         * It is incorrect situation, however it is possible: Copies
0625:                         * category is supported, but there are no supported values. I 
0626:                         * suppose that only default Copies value is supported in this 
0627:                         * case. If default Copies value is null - I suppose that default 
0628:                         * and supported value is 1 Copy only. 
0629:                         */
0630:                        supported = new CopiesSupported(
0631:                                (defaul == null) ? defaul.getValue() : 1);
0632:                    }
0633:
0634:                    int[][] range = supported.getMembers();
0635:
0636:                    if (!supported.contains(value)) {
0637:                        value = (((defaul == null) || (!supported
0638:                                .contains(defaul.getValue()))) ? range[0][0]
0639:                                : defaul.getValue());
0640:                    }
0641:
0642:                    cpSpinner.setModel(new SpinnerNumberModel(value,
0643:                            range[0][0], range[0][1], 1));
0644:                }
0645:            }
0646:
0647:            /*
0648:             * Change listener for "Number of copies" spinner.
0649:             * "Collate" combobox is enabled if Copies > 1 only
0650:             */
0651:            class CopiesChangeListener implements  ChangeListener {
0652:                public void stateChanged(ChangeEvent e) {
0653:                    fillCollateBox();
0654:                }
0655:            }
0656:
0657:            /* 
0658:             * "Collate" combobox from "General" tab.
0659:             * This box will be enabled if more then one SheetCollate attribute 
0660:             * is supported by selected print service and "Number of copies" value > 1
0661:             */
0662:            void fillCollateBox() {
0663:                boolean isSupported = myService
0664:                        .isAttributeCategorySupported(SheetCollate.class);
0665:                SheetCollate[] supported = (SheetCollate[]) (myService
0666:                        .getSupportedAttributeValues(SheetCollate.class,
0667:                                flavor, attrs));
0668:                Attribute attr = attrs.get(SheetCollate.class);
0669:                int spinnerValue = ((Integer) cpSpinner.getValue()).intValue();
0670:
0671:                if ((supported == null) || !isSupported) {
0672:                    if (attrs.containsKey(SheetCollate.class)) {
0673:                        collateBox.setSelected(attr
0674:                                .equals(SheetCollate.COLLATED));
0675:                    }
0676:                } else {
0677:                    boolean isValueSupported = myService
0678:                            .isAttributeValueSupported(SheetCollate.COLLATED,
0679:                                    flavor, attrs);
0680:                    if (attrs.containsKey(SheetCollate.class)
0681:                            && isValueSupported) {
0682:                        collateBox.setSelected(attr
0683:                                .equals(SheetCollate.COLLATED));
0684:                    } else {
0685:                        Object defaul = myService
0686:                                .getDefaultAttributeValue(SheetCollate.class);
0687:                        collateBox.setSelected(defaul != null ? defaul
0688:                                .equals(SheetCollate.COLLATED) : true);
0689:                    }
0690:                }
0691:
0692:                collateBox.setEnabled(isSupported && (spinnerValue > 1)
0693:                        && (!(supported == null || supported.length <= 1)));
0694:            }
0695:
0696:            /*
0697:             * "Print ranges" fields from "General" tab.
0698:             * "From" and "to" text fields are enabled only if "Pages" radiobutton is 
0699:             * selected. If attr set does not contain PageRanges attribute, default value
0700:             * is always "All". 
0701:             */
0702:            void fillPrintRangeFields() {
0703:                if (firstUse) {
0704:                    if (attrs.containsKey(PageRanges.class)) {
0705:                        PageRanges aRange = (PageRanges) (attrs
0706:                                .get(PageRanges.class));
0707:                        int[][] range = aRange.getMembers();
0708:                        fromTxt.setText(range.length > 0 ? Integer
0709:                                .toString(range[0][0]) : "1");
0710:                        toTxt.setText(range.length > 0 ? Integer
0711:                                .toString(range[0][1]) : "1");
0712:                        pageRngBtn.setSelected(true);
0713:                    } else {
0714:                        allRngBtn.setSelected(true);
0715:                        fromTxt.setEnabled(false);
0716:                        toTxt.setEnabled(false);
0717:                        fromTxt.setText("1");
0718:                        toTxt.setText("1");
0719:                        toLabel.setEnabled(false);
0720:                    }
0721:                }
0722:            }
0723:
0724:            /*
0725:             * Change listener for "Print Ranges" fields:
0726:             * Range fields are enabled only if not all the pages should be printed, i.e.
0727:             * if "Pages" button is selected.  
0728:             */
0729:            class PagesButtonChangeListener implements  ChangeListener {
0730:                public void stateChanged(ChangeEvent e) {
0731:                    fromTxt.setEnabled(pageRngBtn.isSelected());
0732:                    toTxt.setEnabled(pageRngBtn.isSelected());
0733:                    toLabel.setEnabled(pageRngBtn.isSelected());
0734:                }
0735:            } /* End of PagesButtonChangeListener class */
0736:
0737:            //---------------------------------------------------------------------
0738:            /*
0739:             * Page Setup fields filling after PrintService selecting
0740:             */
0741:            void fillPageSetupFields() {
0742:                fillMediaFields();
0743:                fillOrientationFields();
0744:                fillMarginsFields();
0745:            }
0746:
0747:            /*
0748:             * "Size" and "Source" comboboxes from "Page Setup" tab.
0749:             * 
0750:             * I made "Source" combobox invisible because it is unclear how to work with
0751:             * two different Media comboboxes in one dialog (please, see comments in the 
0752:             * beginning of the ServiceUIDialog class for more details).
0753:             * Probably, we will need to change it in the future.
0754:             * 
0755:             * "Size" combobox contains all medias supported by the selected print service.
0756:             * It is disabled if given service does not support Media attribute or 
0757:             * supported media list is empty.
0758:             */
0759:            void fillMediaFields() {
0760:                if (myService.isAttributeCategorySupported(Media.class)) {
0761:                    Media[] mediaList = (Media[]) myService
0762:                            .getSupportedAttributeValues(Media.class, flavor,
0763:                                    attrs);
0764:                    Media oldMedia = (sizeBox.getItemCount() <= 0) ? null
0765:                            : (Media) sizeBox.getSelectedItem();
0766:
0767:                    sizeBox.removeAllItems();
0768:                    if ((mediaList != null) && (mediaList.length > 0)) {
0769:                        for (int i = 0; i < mediaList.length; i++) {
0770:                            sizeBox.addItem(mediaList[i]);
0771:                        }
0772:                        selectMedia(oldMedia);
0773:                    }
0774:                    sizeBox.setEnabled((mediaList != null)
0775:                            && (mediaList.length > 0));
0776:                    sizeLabel.setEnabled((mediaList != null)
0777:                            && (mediaList.length > 0));
0778:                } else {
0779:                    sizeBox.setEnabled(false);
0780:                    sizeLabel.setEnabled(false);
0781:                }
0782:                sizeBox.updateUI();
0783:            }
0784:
0785:            /*
0786:             * Selects media in "Sizes" combobox. Selected media is previously 
0787:             * selected Media if it is supported by current print service.
0788:             * Otherwise selected media Media from attrs (if it is supported) or default
0789:             * Media for selected service.
0790:             */
0791:            void selectMedia(Media oldMedia) {
0792:                if (sizeBox.getItemCount() > 0) {
0793:
0794:                    /* if media was not set - get it from attributes */
0795:                    if ((oldMedia == null) && attrs.containsKey(Media.class)) {
0796:                        oldMedia = (Media) attrs.get(Media.class);
0797:                    }
0798:                    sizeBox.setSelectedItem(oldMedia);
0799:
0800:                    if ((sizeBox.getSelectedIndex() < 0)
0801:                            || (!sizeBox.getSelectedItem().equals(oldMedia))) {
0802:                        Object media = myService
0803:                                .getDefaultAttributeValue(Media.class);
0804:                        if (media != null) {
0805:                            sizeBox.setSelectedItem(media);
0806:                        }
0807:                    }
0808:
0809:                    /* select first media if there is still no selection */
0810:                    if (sizeBox.getSelectedIndex() < 0) {
0811:                        sizeBox.setSelectedIndex(0);
0812:                    }
0813:                }
0814:            }
0815:
0816:            /*
0817:             * "Orientation" radiobuttons from "Page Setup" tab.
0818:             * All these buttons are disabled if selected print service does not support 
0819:             * OrientationRequested attribute. Only supported by service orientations 
0820:             * are enabled.
0821:             */
0822:            void fillOrientationFields() {
0823:
0824:                OrientationRequested orient = (OrientationRequested) attrs
0825:                        .get(OrientationRequested.class);
0826:                boolean isSupported = myService
0827:                        .isAttributeCategorySupported(OrientationRequested.class);
0828:
0829:                OrientationRequested[] supportedList = (isSupported ? (OrientationRequested[]) myService
0830:                        .getSupportedAttributeValues(
0831:                                OrientationRequested.class, flavor, attrs)
0832:                        : null);
0833:
0834:                enableOrient(supportedList);
0835:
0836:                /* Select orientation at first time (orientation from attributes set or 
0837:                   default orientation for this Print Service) */
0838:                if (firstUse) {
0839:                    if (orient != null) {
0840:                        selectOrient(orient);
0841:                    } else {
0842:                        OrientationRequested defaul = (OrientationRequested) myService
0843:                                .getDefaultAttributeValue(OrientationRequested.class);
0844:                        selectOrient(isSupported ? defaul : null);
0845:                    }
0846:                }
0847:
0848:                /* Select orientation if previosly selected button is disabled now */
0849:                if (supportedList != null) {
0850:                    OrientationRequested oldValue = getOrient();
0851:                    if (!orientEnabled(oldValue)) {
0852:                        selectOrient(orientEnabled(orient) ? orient
0853:                                : supportedList[0]);
0854:                    }
0855:                }
0856:            }
0857:
0858:            /*
0859:             * Select "Orientation" button corresponding to the given orientation
0860:             */
0861:            private void selectOrient(OrientationRequested par) {
0862:                if (par == null) {
0863:                    par = OrientationRequested.PORTRAIT;
0864:                }
0865:                if (par.equals(OrientationRequested.LANDSCAPE)) {
0866:                    landscapeBtn.setSelected(true);
0867:                } else if (par.equals(OrientationRequested.REVERSE_LANDSCAPE)) {
0868:                    rvlandscapeBtn.setSelected(true);
0869:                } else if (par.equals(OrientationRequested.REVERSE_PORTRAIT)) {
0870:                    rvportraitBtn.setSelected(true);
0871:                } else {
0872:                    portraitBtn.setSelected(true);
0873:                }
0874:            }
0875:
0876:            /*
0877:             enable/disable corresponding "Orientation" buttons
0878:             */
0879:            private void enableOrient(OrientationRequested[] list) {
0880:                portraitBtn.setEnabled(false);
0881:                landscapeBtn.setEnabled(false);
0882:                rvportraitBtn.setEnabled(false);
0883:                rvlandscapeBtn.setEnabled(false);
0884:
0885:                if (list != null) {
0886:                    for (int i = 0; i < list.length; i++) {
0887:                        if (list[i].equals(OrientationRequested.LANDSCAPE)) {
0888:                            landscapeBtn.setEnabled(true);
0889:                        } else if (list[i]
0890:                                .equals(OrientationRequested.PORTRAIT)) {
0891:                            portraitBtn.setEnabled(true);
0892:                        } else if (list[i]
0893:                                .equals(OrientationRequested.REVERSE_LANDSCAPE)) {
0894:                            rvlandscapeBtn.setEnabled(true);
0895:                        } else if (list[i]
0896:                                .equals(OrientationRequested.REVERSE_PORTRAIT)) {
0897:                            rvportraitBtn.setEnabled(true);
0898:                        }
0899:                    }
0900:                }
0901:            }
0902:
0903:            /*
0904:             * get selected orientation
0905:             */
0906:            OrientationRequested getOrient() {
0907:                if (portraitBtn.isSelected()) {
0908:                    return OrientationRequested.PORTRAIT;
0909:                } else if (landscapeBtn.isSelected()) {
0910:                    return OrientationRequested.LANDSCAPE;
0911:                } else if (rvportraitBtn.isSelected()) {
0912:                    return OrientationRequested.REVERSE_PORTRAIT;
0913:                } else if (rvlandscapeBtn.isSelected()) {
0914:                    return OrientationRequested.REVERSE_LANDSCAPE;
0915:                } else {
0916:                    return null;
0917:                }
0918:            }
0919:
0920:            /*
0921:             * returns true if button for the given orientation is enabled
0922:             */
0923:            private boolean orientEnabled(OrientationRequested par) {
0924:                if (par == null) {
0925:                    return false;
0926:                } else if (par.equals(OrientationRequested.LANDSCAPE)) {
0927:                    return landscapeBtn.isEnabled();
0928:                } else if (par.equals(OrientationRequested.PORTRAIT)) {
0929:                    return portraitBtn.isEnabled();
0930:                } else if (par.equals(OrientationRequested.REVERSE_LANDSCAPE)) {
0931:                    return rvlandscapeBtn.isEnabled();
0932:                } else if (par.equals(OrientationRequested.REVERSE_PORTRAIT)) {
0933:                    return rvportraitBtn.isEnabled();
0934:                } else {
0935:                    return false;
0936:                }
0937:            }
0938:
0939:            /*
0940:             * return true if at least one orientation button is enabled,
0941:             * i.e. at least one OrientationRequested attribute is supported.
0942:             */
0943:            private boolean isOrientSupported() {
0944:                return landscapeBtn.isEnabled() || portraitBtn.isEnabled()
0945:                        || rvlandscapeBtn.isEnabled()
0946:                        || rvportraitBtn.isEnabled();
0947:            }
0948:
0949:            /* 
0950:             * Change listener for "Orientation" buttons:
0951:             * "Margins" fields should be updated after the orientation is changed.
0952:             */
0953:            class OrientationChangeListener implements  ChangeListener {
0954:
0955:                public void stateChanged(ChangeEvent e) {
0956:                    OrientationRequested now = getOrient();
0957:
0958:                    if ((lastOrient != null) && (now != null)
0959:                            && (!lastOrient.equals(now))) {
0960:                        /* if orientation was really changed */
0961:
0962:                        String txt = leftTxt.getText();
0963:
0964:                        if ((lastOrient.equals(OrientationRequested.PORTRAIT) && now
0965:                                .equals(OrientationRequested.LANDSCAPE))
0966:                                || (lastOrient
0967:                                        .equals(OrientationRequested.LANDSCAPE) && now
0968:                                        .equals(OrientationRequested.REVERSE_PORTRAIT))
0969:                                || (lastOrient
0970:                                        .equals(OrientationRequested.REVERSE_PORTRAIT) && now
0971:                                        .equals(OrientationRequested.REVERSE_LANDSCAPE))
0972:                                || (lastOrient
0973:                                        .equals(OrientationRequested.REVERSE_LANDSCAPE) && now
0974:                                        .equals(OrientationRequested.PORTRAIT))) {
0975:                            leftTxt.setText(bottomTxt.getText());
0976:                            bottomTxt.setText(rightTxt.getText());
0977:                            rightTxt.setText(topTxt.getText());
0978:                            topTxt.setText(txt);
0979:
0980:                        } else if ((lastOrient
0981:                                .equals(OrientationRequested.PORTRAIT) && now
0982:                                .equals(OrientationRequested.REVERSE_PORTRAIT))
0983:                                || (lastOrient
0984:                                        .equals(OrientationRequested.LANDSCAPE) && now
0985:                                        .equals(OrientationRequested.REVERSE_LANDSCAPE))
0986:                                || (lastOrient
0987:                                        .equals(OrientationRequested.REVERSE_PORTRAIT) && now
0988:                                        .equals(OrientationRequested.PORTRAIT))
0989:                                || (lastOrient
0990:                                        .equals(OrientationRequested.REVERSE_LANDSCAPE) && now
0991:                                        .equals(OrientationRequested.LANDSCAPE))) {
0992:                            leftTxt.setText(rightTxt.getText());
0993:                            rightTxt.setText(txt);
0994:                            txt = topTxt.getText();
0995:                            topTxt.setText(bottomTxt.getText());
0996:                            bottomTxt.setText(txt);
0997:
0998:                        } else {
0999:                            leftTxt.setText(topTxt.getText());
1000:                            topTxt.setText(rightTxt.getText());
1001:                            rightTxt.setText(bottomTxt.getText());
1002:                            bottomTxt.setText(txt);
1003:                        }
1004:                    }
1005:
1006:                    if (now != null) {
1007:                        lastOrient = now;
1008:                    }
1009:                }
1010:            } /* End of OrientationChangeListener class */
1011:
1012:            /*
1013:             * "Margins" fields from "Page Setup" tab.
1014:             * 
1015:             * These fields are related with Media, MediaPrintableArea and MediaMargins
1016:             * attributes. 
1017:             * These fields are enabled if selected print service supports MediaMargins
1018:             * attribute, or service supports Media + MediaPrintebleArea attributes and at
1019:             * lease one Media is supported. They are also always enabled if this is a
1020:             * PAGE_DIALOG.
1021:             * 
1022:             * Meaning of this fields should be updated if Orientation is changed.
1023:             * 
1024:             * When we initialize the dialog at first time, "Margins" values are 
1025:             * calculated using the following algorithm: 
1026:             *
1027:             *  * 1. If MediaPrintableArea + Media attributes are supported, attrs set 
1028:             *    contains MediaPrintableArea and Media, Media attribute from attrs is 
1029:             *    supported by selected print service and this is MediaSizeName object 
1030:             *    (i.e. we can get size of this Media) and margins may be correctly 
1031:             *    calculated using these Media and MediaMargins attributes - we get 
1032:             *    margins from these Media and MediaPrintableArea.
1033:             * 2. If margins fields are not defined yet and MediaMargins is supported by 
1034:             *    selected service or this is a page setup dialog, we get MediaMargins from 
1035:             *    attribute set (if it is present) or default MediaMargins for selected 
1036:             *    print service (if service has default MediaMargins)
1037:             * 3. If margins fields are not defined yet, try to obtain MediaMargins from 
1038:             *    selected Media and default MediaPrintebleArea (if it is present) for 
1039:             *    selected print service. If margins can be calculated - fill "Margins"
1040:             *    fields with these meanings.
1041:             * 4. If margins fields are not defined yet, we set them just to some default
1042:             *    meanings (25.4 mm). 
1043:             *  
1044:             * Please, see also comments in the beginning of the ServiceUIDialog class.
1045:             */
1046:            void fillMarginsFields() {
1047:                boolean isMediaSupported = myService
1048:                        .isAttributeCategorySupported(Media.class);
1049:                boolean isPaSupported = myService
1050:                        .isAttributeCategorySupported(MediaPrintableArea.class);
1051:                boolean isMarginsSupported = myService
1052:                        .isAttributeCategorySupported(MediaMargins.class);
1053:
1054:                /* We enable margins fields if this is a PAGE_DIALOG or Media and 
1055:                   MediaPrintableArea attributes are supported or MediaMargins attribute is
1056:                   supported by selected PrintService */
1057:                boolean isMarginsEnabled = ((dialogType == PAGE_DIALOG)
1058:                        || isMarginsSupported || (isMediaSupported
1059:                        && isPaSupported && (sizeBox.getSelectedItem() != null)));
1060:
1061:                enableMargins(isMarginsEnabled);
1062:
1063:                if (firstUse) {
1064:                    /* set margins at first time */
1065:                    MediaMargins margins = null; // Margins for the dialog Margins fields
1066:
1067:                    if (isMarginsEnabled) { // Margins fields are enabled and can be edited
1068:
1069:                        Media selectedMedia = (Media) sizeBox.getSelectedItem();
1070:                        boolean isMediaSizeSelected = (selectedMedia == null) ? false
1071:                                : selectedMedia.getClass().isAssignableFrom(
1072:                                        MediaSizeName.class);
1073:                        MediaSize selectedSize = isMediaSizeSelected ? MediaSize
1074:                                .getMediaSizeForName((MediaSizeName) selectedMedia)
1075:                                : null;
1076:
1077:                        if (isMediaSupported && isPaSupported
1078:                                && attrs.containsKey(Media.class)
1079:                                && attrs.containsKey(MediaPrintableArea.class)
1080:                                && attrs.get(Media.class).equals(selectedMedia)
1081:                                && isMediaSizeSelected) {
1082:                            /* p.1 - see fillMarginsFields() comments above*/
1083:                            try {
1084:                                MediaPrintableArea attrsPA = (MediaPrintableArea) attrs
1085:                                        .get(MediaPrintableArea.class);
1086:                                margins = new MediaMargins(selectedSize,
1087:                                        attrsPA);
1088:                            } catch (IllegalArgumentException e) {
1089:                                /*
1090:                                 * If we are unable to get correct margins values from the 
1091:                                 * given MediaPrintableArea (attrsPA) and MediaSize 
1092:                                 * (selectedSize), we just ignore this case
1093:                                 */
1094:                            }
1095:                        }
1096:
1097:                        if ((margins == null)
1098:                                && (isMarginsSupported || (dialogType == PAGE_DIALOG))) {
1099:                            /* p.2 - see fillMarginsFields() comments above*/
1100:                            margins = (MediaMargins) (attrs
1101:                                    .containsKey(MediaMargins.class) ? attrs
1102:                                    .get(MediaMargins.class)
1103:                                    : myService
1104:                                            .getDefaultAttributeValue(MediaMargins.class));
1105:                        }
1106:
1107:                        if ((margins == null) && isPaSupported
1108:                                && isMediaSupported && isMediaSizeSelected) {
1109:                            /* p.3 - see fillMarginsFields() comments above*/
1110:                            try {
1111:                                MediaPrintableArea defaultPA = (MediaPrintableArea) myService
1112:                                        .getDefaultAttributeValue(MediaPrintableArea.class);
1113:                                if ((defaultPA != null)
1114:                                        && (selectedSize != null)) {
1115:                                    margins = new MediaMargins(selectedSize,
1116:                                            defaultPA);
1117:                                }
1118:                            } catch (IllegalArgumentException e) {
1119:                                /*
1120:                                 * If we are unable to get correct margins value from the
1121:                                 * default MediaPrintableArea (defPA) for this service and
1122:                                 * MediaSize (selectedSize), we just ignoew this case.
1123:                                 */
1124:                            }
1125:                        }
1126:
1127:                        if (margins == null) {
1128:                            /* Just 25.4 mm margins! */
1129:                            margins = new MediaMargins(25.4F, 25.4F, 25.4F,
1130:                                    25.4F, MediaMargins.MM);
1131:                        }
1132:
1133:                    } else {
1134:                        /* Margins fields are disabled, but we always set them to some 
1135:                           default meanings (25.4 mm) */
1136:                        margins = (attrs.containsKey(MediaMargins.class) ? (MediaMargins) attrs
1137:                                .get(MediaMargins.class)
1138:                                : new MediaMargins(25.4F, 25.4F, 25.4F, 25.4F,
1139:                                        MediaMargins.MM));
1140:                    }
1141:                    setMargins(margins);
1142:                }
1143:            }
1144:
1145:            /* 
1146:             * Enable/disable all Margins fields
1147:             */
1148:            private void enableMargins(boolean flg) {
1149:                leftLabel.setEnabled(flg);
1150:                rightLabel.setEnabled(flg);
1151:                topLabel.setEnabled(flg);
1152:                bottomLabel.setEnabled(flg);
1153:                leftTxt.setEnabled(flg);
1154:                rightTxt.setEnabled(flg);
1155:                topTxt.setEnabled(flg);
1156:                bottomTxt.setEnabled(flg);
1157:            }
1158:
1159:            /*
1160:             * Set Margins dialog fields in accordance with the given MediaMargins object
1161:             */
1162:            private void setMargins(MediaMargins margins) {
1163:                NumberFormatter fmt = getFloatFormatter();
1164:                try {
1165:                    leftTxt.setText(fmt.valueToString(new Float(margins
1166:                            .getX1(MediaMargins.MM))));
1167:                    rightTxt.setText(fmt.valueToString(new Float(margins
1168:                            .getX2(MediaMargins.MM))));
1169:                    topTxt.setText(fmt.valueToString(new Float(margins
1170:                            .getY1(MediaMargins.MM))));
1171:                    bottomTxt.setText(fmt.valueToString(new Float(margins
1172:                            .getY2(MediaMargins.MM))));
1173:                } catch (ParseException e) {
1174:                    /* Ignore incorrect float format */
1175:                }
1176:            }
1177:
1178:            //---------------------------------------------------------------------
1179:            /* 
1180:             * "Apparance" tab fields filling after new PrintService selecting
1181:             */
1182:            void fillAppearanceFields() {
1183:                fillColorFields();
1184:                fillQualityFields();
1185:                fillSidesFields();
1186:                fillJobAttributesFields();
1187:            }
1188:
1189:            /*
1190:             * "Color" panel radiobuttons from "Appearance" tab.
1191:             * The buttons are enabled only if selected service supports both COLOR and
1192:             * MONOCHROME Chromaticity attributes.  
1193:             */
1194:            void fillColorFields() {
1195:                boolean lastIsMonochrome = getLastColor();
1196:
1197:                monoBtn.setEnabled(false);
1198:                colorBtn.setEnabled(false);
1199:
1200:                if (myService.isAttributeCategorySupported(Chromaticity.class)) {
1201:                    Chromaticity[] supported = (Chromaticity[]) (myService
1202:                            .getSupportedAttributeValues(Chromaticity.class,
1203:                                    flavor, attrs));
1204:                    if (supported != null) {
1205:                        if (supported.length == 1) {
1206:                            lastIsMonochrome = setMonochrome((supported[0])
1207:                                    .equals(Chromaticity.MONOCHROME));
1208:                        } else if (supported.length > 1) {
1209:                            monoBtn.setEnabled(true);
1210:                            colorBtn.setEnabled(true);
1211:                        }
1212:                    }
1213:                }
1214:
1215:                if (lastIsMonochrome) {
1216:                    monoBtn.setSelected(true);
1217:                } else {
1218:                    colorBtn.setSelected(true);
1219:                }
1220:            }
1221:
1222:            /* 
1223:             * get last selected Chromaticity button 
1224:             */
1225:            private boolean getLastColor() {
1226:                if (firstUse) {
1227:                    if (attrs.containsKey(Chromaticity.class)) {
1228:                        Attribute value = attrs.get(Chromaticity.class);
1229:                        return value.equals(Chromaticity.MONOCHROME);
1230:                    }
1231:
1232:                    Object defaul = myService
1233:                            .getDefaultAttributeValue(Chromaticity.class);
1234:                    return (myService
1235:                            .isAttributeCategorySupported(Chromaticity.class) && (defaul != null)) ? defaul
1236:                            .equals(Chromaticity.MONOCHROME)
1237:                            : true;
1238:                }
1239:
1240:                return monoBtn.isSelected();
1241:            }
1242:
1243:            private boolean setMonochrome(boolean flg) {
1244:                monoBtn.setEnabled(flg);
1245:                colorBtn.setEnabled(!flg);
1246:                return flg;
1247:            }
1248:
1249:            /* 
1250:             * "Quality" panel radiobuttons from "Appearance" tab 
1251:             * Only supported by selected print service PrintQualities are enabled.  
1252:             */
1253:            void fillQualityFields() {
1254:                PrintQuality quality = (PrintQuality) attrs
1255:                        .get(PrintQuality.class);
1256:                if (firstUse) {
1257:                    selectQualityButton(quality);
1258:                }
1259:
1260:                PrintQuality[] aList = (myService
1261:                        .isAttributeCategorySupported(PrintQuality.class) ? (PrintQuality[]) myService
1262:                        .getSupportedAttributeValues(PrintQuality.class,
1263:                                flavor, attrs)
1264:                        : null);
1265:                enableQualityButtons(aList); /* enable qualities which are supported */
1266:
1267:                /* select quality */
1268:                if ((aList != null)
1269:                        && (!qualityIsEnabled(getSelectedQuality()))) {
1270:                    selectQualityButton(qualityIsEnabled(quality) ? quality
1271:                            : (PrintQuality) (myService
1272:                                    .getDefaultAttributeValue(PrintQuality.class)));
1273:                }
1274:            }
1275:
1276:            /* 
1277:             * select "Quality" button for the given PrintQuality attribute 
1278:             */
1279:            private void selectQualityButton(PrintQuality par) {
1280:                if (par == null) {
1281:                    par = PrintQuality.NORMAL;
1282:                }
1283:                if (par.equals(PrintQuality.DRAFT)) {
1284:                    draftBtn.setSelected(true);
1285:                } else if (par.equals(PrintQuality.HIGH)) {
1286:                    highBtn.setSelected(true);
1287:                } else {
1288:                    normalBtn.setSelected(true);
1289:                }
1290:            }
1291:
1292:            /* 
1293:             * enable "Quality" buttons for the PrintQuality attributes from the given list 
1294:             */
1295:            private void enableQualityButtons(PrintQuality[] list) {
1296:                normalBtn.setEnabled(false);
1297:                draftBtn.setEnabled(false);
1298:                highBtn.setEnabled(false);
1299:
1300:                if (list != null) {
1301:                    for (int i = 0; i < list.length; i++) {
1302:                        if (list[i].equals(PrintQuality.DRAFT)) {
1303:                            draftBtn.setEnabled(true);
1304:                        } else if (list[i].equals(PrintQuality.NORMAL)) {
1305:                            normalBtn.setEnabled(true);
1306:                        } else if (list[i].equals(PrintQuality.HIGH)) {
1307:                            highBtn.setEnabled(true);
1308:                        }
1309:                    }
1310:                }
1311:            }
1312:
1313:            /* 
1314:             * return PrintQuality attribute for the selected "Quality" button 
1315:             */
1316:            private PrintQuality getSelectedQuality() {
1317:                if (normalBtn.isSelected()) {
1318:                    return PrintQuality.NORMAL;
1319:                } else if (draftBtn.isSelected()) {
1320:                    return PrintQuality.DRAFT;
1321:                } else if (highBtn.isSelected()) {
1322:                    return PrintQuality.HIGH;
1323:                } else {
1324:                    return null;
1325:                }
1326:            }
1327:
1328:            /* 
1329:             * returns true if "Quality" button for the given PrintQuality attribute 
1330:             * enabled
1331:             */
1332:            private boolean qualityIsEnabled(PrintQuality par) {
1333:                if (par == null) {
1334:                    return false;
1335:                } else if (par.equals(PrintQuality.NORMAL)) {
1336:                    return normalBtn.isEnabled();
1337:                } else if (par.equals(PrintQuality.DRAFT)) {
1338:                    return draftBtn.isEnabled();
1339:                } else if (par.equals(PrintQuality.HIGH)) {
1340:                    return highBtn.isEnabled();
1341:                } else {
1342:                    return false;
1343:                }
1344:            }
1345:
1346:            /* 
1347:             * returns true if at least one "Quality" button enabled 
1348:             */
1349:            private boolean isQualitySupported() {
1350:                return (normalBtn.isEnabled() || draftBtn.isEnabled() || highBtn
1351:                        .isEnabled());
1352:            }
1353:
1354:            /* 
1355:             * "Sides" panel radiobuttons from "Appearance" tab 
1356:             * Only supported by selected print service Sides are enabled.  
1357:             */
1358:            void fillSidesFields() {
1359:                Sides side = (Sides) attrs.get(Sides.class);
1360:                if (firstUse) {
1361:                    selectSidesButton(side);
1362:                }
1363:
1364:                Sides[] aList = (myService
1365:                        .isAttributeCategorySupported(Sides.class) ? (Sides[]) (myService
1366:                        .getSupportedAttributeValues(Sides.class, flavor, attrs))
1367:                        : null);
1368:                enableSidesButtons(aList);
1369:
1370:                if ((aList != null) && !sideIsEnabled(getSelectedSide())) {
1371:                    selectSidesButton(sideIsEnabled(side) ? side
1372:                            : (Sides) (myService
1373:                                    .getDefaultAttributeValue(Sides.class)));
1374:                }
1375:            }
1376:
1377:            /* 
1378:             * Select "Sides" button for the given Sides attribute 
1379:             */
1380:            private void selectSidesButton(Sides par) {
1381:                if (par == null) {
1382:                    par = Sides.ONE_SIDED;
1383:                }
1384:                if (par.equals(Sides.TUMBLE)
1385:                        || par.equals(Sides.TWO_SIDED_SHORT_EDGE)) {
1386:                    tumbleBtn.setSelected(true);
1387:                } else if (par.equals(Sides.DUPLEX)
1388:                        || par.equals(Sides.TWO_SIDED_LONG_EDGE)) {
1389:                    duplexBtn.setSelected(true);
1390:                } else {
1391:                    oneSideBtn.setSelected(true);
1392:                }
1393:            }
1394:
1395:            /* 
1396:             * enable "Sides" buttons for the Sides attributes from the given list 
1397:             */
1398:            private void enableSidesButtons(Sides[] list) {
1399:                oneSideBtn.setEnabled(false);
1400:                duplexBtn.setEnabled(false);
1401:                tumbleBtn.setEnabled(false);
1402:
1403:                if (list != null) {
1404:                    for (int i = 0; i < list.length; i++) {
1405:                        if (list[i].equals(Sides.ONE_SIDED)) {
1406:                            oneSideBtn.setEnabled(true);
1407:                        } else if (list[i].equals(Sides.DUPLEX)
1408:                                || list[i].equals(Sides.TWO_SIDED_LONG_EDGE)) {
1409:                            duplexBtn.setEnabled(true);
1410:                        } else if (list[i].equals(Sides.TUMBLE)
1411:                                || list[i].equals(Sides.TWO_SIDED_SHORT_EDGE)) {
1412:                            tumbleBtn.setEnabled(true);
1413:                        }
1414:                    }
1415:                }
1416:            }
1417:
1418:            /* 
1419:             * returns Sides attribute object for the selected "Sides" button 
1420:             */
1421:            private Sides getSelectedSide() {
1422:                if (oneSideBtn.isSelected()) {
1423:                    return Sides.ONE_SIDED;
1424:                } else if (duplexBtn.isSelected()) {
1425:                    return Sides.DUPLEX;
1426:                } else if (tumbleBtn.isSelected()) {
1427:                    return Sides.TUMBLE;
1428:                } else {
1429:                    return null;
1430:                }
1431:            }
1432:
1433:            /* 
1434:             * returns true if "Sides" button for this Sides attribute enabled 
1435:             */
1436:            private boolean sideIsEnabled(Sides par) {
1437:                if (par == null) {
1438:                    return false;
1439:                } else if (par.equals(Sides.ONE_SIDED)) {
1440:                    return oneSideBtn.isEnabled();
1441:                } else if (par.equals(Sides.DUPLEX)
1442:                        || par.equals(Sides.TWO_SIDED_LONG_EDGE)) {
1443:                    return duplexBtn.isEnabled();
1444:                } else if (par.equals(Sides.TUMBLE)
1445:                        || par.equals(Sides.TWO_SIDED_SHORT_EDGE)) {
1446:                    return tumbleBtn.isEnabled();
1447:                } else {
1448:                    return false;
1449:                }
1450:            }
1451:
1452:            /*
1453:             * returns true if at least one "Sides" button is enabled
1454:             * (that means at least one Sides attribute supported)
1455:             */
1456:            private boolean isSidesSupported() {
1457:                return (oneSideBtn.isEnabled() || duplexBtn.isEnabled() || tumbleBtn
1458:                        .isEnabled());
1459:            }
1460:
1461:            /*
1462:             * "Job Attribute" panel fields from "Appearance" tab 
1463:             */
1464:            void fillJobAttributesFields() {
1465:                fillBannerPageField();
1466:                fillPriorityField();
1467:                fillJobNameField();
1468:                fillUserNameField();
1469:            }
1470:
1471:            /* 
1472:             * "Banner Page" checkbox from "Appearance" tab.
1473:             * This checkbox is enabled if selected print service supports more then one 
1474:             * JobSheets attributes. This checkbox is selected if it is corresponds to 
1475:             * JobSheets.STANDARD attribute and unselected otherwise.
1476:             */
1477:            void fillBannerPageField() {
1478:                JobSheets[] supported = (myService
1479:                        .isAttributeCategorySupported(JobSheets.class) ? (JobSheets[]) (myService
1480:                        .getSupportedAttributeValues(JobSheets.class, flavor,
1481:                                attrs))
1482:                        : null);
1483:                Attribute value = attrs.get(JobSheets.class);
1484:
1485:                if ((supported != null) && (supported.length == 0)) {
1486:                    supported = null;
1487:                }
1488:
1489:                if (supported == null) {
1490:                    /* if PrintService does not supported any JobSheets, set current 
1491:                       meaning from attribute set (if present) and disable checkbox */
1492:                    if (firstUse && attrs.containsKey(JobSheets.class)) {
1493:                        bannerBox.setSelected(value.equals(JobSheets.STANDARD));
1494:                    }
1495:                } else {
1496:                    if (supported.length == 1) {
1497:                        bannerBox
1498:                                .setSelected(supported[0] == JobSheets.STANDARD);
1499:                    } else if (attrs.containsKey(JobSheets.class)) {
1500:                        bannerBox.setSelected(value.equals(JobSheets.STANDARD));
1501:                    } else {
1502:                        Object def = myService
1503:                                .getDefaultAttributeValue(JobSheets.class);
1504:                        bannerBox.setSelected(def == null ? false : def
1505:                                .equals(JobSheets.STANDARD));
1506:                    }
1507:                }
1508:                bannerBox.setEnabled((supported != null)
1509:                        && (supported.length > 1));
1510:            }
1511:
1512:            /* 
1513:             * "Priority" spinner from "Appearance" tab.
1514:             * It is enabled if selected print service supports JobPriority attribute. 
1515:             */
1516:            void fillPriorityField() {
1517:                boolean enabled = myService
1518:                        .isAttributeCategorySupported(JobPriority.class);
1519:                priorityLabel.setEnabled(enabled);
1520:                prtSpinner.setEnabled(enabled);
1521:
1522:                if (firstUse) {
1523:                    if (attrs.containsKey(JobPriority.class)) {
1524:                        JobPriority value = (JobPriority) (attrs
1525:                                .get(JobPriority.class));
1526:                        prtSpinner.setValue(new Integer(value.getValue()));
1527:                    } else {
1528:                        if (enabled) {
1529:                            JobPriority defaul = (JobPriority) (myService
1530:                                    .getDefaultAttributeValue(JobPriority.class));
1531:                            prtSpinner.setValue(defaul == null ? new Integer(1)
1532:                                    : new Integer(defaul.getValue()));
1533:                        } else {
1534:                            prtSpinner.setValue(new Integer(1));
1535:                        }
1536:                    }
1537:                }
1538:            }
1539:
1540:            /* 
1541:             * "Job Name" text field from "Appearance" tab
1542:             * It is enabled if selected print service supports JobName attribute. 
1543:             */
1544:            void fillJobNameField() {
1545:                boolean supported = myService
1546:                        .isAttributeCategorySupported(JobName.class);
1547:                jobNameTxt.setEnabled(supported);
1548:                jobNameLabel.setEnabled(supported);
1549:
1550:                if (firstUse && attrs.containsKey(JobName.class)) {
1551:                    jobNameTxt.setText(((TextSyntax) attrs.get(JobName.class))
1552:                            .getValue());
1553:                }
1554:
1555:                if (supported && (jobNameTxt.getText().length() <= 0)) {
1556:                    TextSyntax txt = (TextSyntax) (myService
1557:                            .getDefaultAttributeValue(JobName.class));
1558:                    jobNameTxt.setText(txt == null ? "" : txt.getValue());
1559:                }
1560:            }
1561:
1562:            /* 
1563:             * "User Name" text field from "Appaerance" tab 
1564:             * It is enabled if selected print service supports RequestingUserName 
1565:             * attribute. 
1566:             */
1567:            void fillUserNameField() {
1568:                boolean flg = myService
1569:                        .isAttributeCategorySupported(RequestingUserName.class);
1570:                userNameTxt.setEnabled(flg);
1571:                userNameLabel.setEnabled(flg);
1572:
1573:                if (firstUse && attrs.containsKey(RequestingUserName.class)) {
1574:                    userNameTxt.setText(((TextSyntax) attrs
1575:                            .get(RequestingUserName.class)).getValue());
1576:                }
1577:
1578:                if (flg && (userNameTxt.getText().length() <= 0)) {
1579:                    RequestingUserName defaul = (RequestingUserName) (myService
1580:                            .getDefaultAttributeValue(RequestingUserName.class));
1581:                    userNameTxt.setText(defaul == null ? "" : (String) (defaul
1582:                            .getValue()));
1583:                }
1584:            }
1585:
1586:            //---------------------------------------------------------------------
1587:            /* 
1588:             * We add Vendor supplied tab to the dialog panel if selected print service has
1589:             * UIFactory and this factory has MAIN_UIROLE Panel or JComponent. 
1590:             */
1591:            void fillVendorSuppliedTab() {
1592:                ServiceUIFactory factory = myService.getServiceUIFactory();
1593:
1594:                if (tabbedPane.getTabCount() > 3) {
1595:                    tabbedPane.remove(3);
1596:                }
1597:
1598:                if (factory != null) {
1599:                    JComponent swingUI = (JComponent) factory.getUI(
1600:                            ServiceUIFactory.MAIN_UIROLE,
1601:                            ServiceUIFactory.JCOMPONENT_UI);
1602:                    if (swingUI != null) {
1603:                        tabbedPane.addTab("Vendor Supplied", swingUI);
1604:                        tabbedPane.setMnemonicAt(3, 'V');
1605:                    } else {
1606:                        Panel panelUI = (Panel) factory.getUI(
1607:                                ServiceUIFactory.MAIN_UIROLE,
1608:                                ServiceUIFactory.PANEL_UI);
1609:                        if (panelUI != null) {
1610:                            tabbedPane.addTab("Vendor Supplied", panelUI);
1611:                            tabbedPane.setMnemonicAt(3, 'V');
1612:                        }
1613:                    }
1614:                }
1615:            }
1616:
1617:            //---------------------------------------------------------------------
1618:            /*
1619:             * ActionListener for "Print" button:
1620:             * if we can get correct result attribute set (newAttrs),
1621:             * hides the dialog and set dialog result to APPROVE_PRINT
1622:             */
1623:            class OKButtonListener implements  ActionListener {
1624:                public void actionPerformed(ActionEvent e) {
1625:                    if (updateAttributes()) { // form result attribute set for the dialog
1626:                        dialogResult = APPROVE_PRINT;
1627:                        printDialog.hide();
1628:                    }
1629:                }
1630:            } /* End of OKButtonListener */
1631:
1632:            /*
1633:             * ActionListener for "Cancel" button:
1634:             * hides the dialog and set dialog result to CANCEL_PRINT.
1635:             * This method does not change dialog result attribute set (newAttrs)
1636:             */
1637:            class cancelButtonListener implements  ActionListener {
1638:                public void actionPerformed(ActionEvent e) {
1639:                    dialogResult = CANSEL_PRINT;
1640:                    printDialog.hide();
1641:                }
1642:            } /* End of cancelButtonListener */
1643:
1644:            /*
1645:             * returns current dialogResult
1646:             */
1647:            public int getResult() {
1648:                return dialogResult;
1649:            }
1650:
1651:            /*
1652:             * returns result attribute set.
1653:             */
1654:            public PrintRequestAttributeSet getAttributes() {
1655:                return newAttrs;
1656:            }
1657:
1658:            /*
1659:             * returns result PrintService if dialogResult is APPROVE_PRINT
1660:             */
1661:            public PrintService getPrintService() {
1662:                return (dialogResult == APPROVE_PRINT) ? myService : null;
1663:            }
1664:
1665:            /*
1666:             * returns dialog's PrintServices list
1667:             */
1668:            public PrintService[] getServices() {
1669:                return services;
1670:            }
1671:
1672:            /*
1673:             * returns last selected PrintService
1674:             */
1675:            public PrintService getSelectedService() {
1676:                return myService;
1677:            }
1678:
1679:            /*
1680:             * returns dialog's docflavor
1681:             */
1682:            public DocFlavor getFlavor() {
1683:                return flavor;
1684:            }
1685:
1686:            //---------------------------------------------------------------------
1687:            /* 
1688:             * Getting result attribute set after OK button click 
1689:             */
1690:            protected boolean updateAttributes() {
1691:                newAttrs = new HashPrintRequestAttributeSet(attrs);
1692:                if (dialogType == PRINT_DIALOG) {
1693:                    updateCopies();
1694:                    updateCollate();
1695:                    if (!updatePrintRange()) {
1696:                        JOptionPane.showMessageDialog(printDialog,
1697:                                "Incorrect Print Range!",
1698:                                "Incorrect parameter",
1699:                                JOptionPane.ERROR_MESSAGE);
1700:                        return false;
1701:                    }
1702:                    updateColor();
1703:                    updateQuality();
1704:                    updateSides();
1705:                    updateBannerPage();
1706:                    updatePriority();
1707:                    updateJobName();
1708:                    updateUserName();
1709:                    updatePrintToFile();
1710:                }
1711:                updateMedia();
1712:                updateOrientation();
1713:                if (!updateMargins()) {
1714:                    JOptionPane.showMessageDialog(printDialog,
1715:                            "Incorrect margins!", "Incorrect parameter",
1716:                            JOptionPane.ERROR_MESSAGE);
1717:                    return false;
1718:                }
1719:                return true;
1720:            }
1721:
1722:            /* 
1723:             * Select output file and add/update Destination attribute to the result 
1724:             * attribute set if "Print to file" box is enabled and selected. 
1725:             * Remove Destination attribute otherwise.
1726:             */
1727:            private void updatePrintToFile() {
1728:                if (toFileBox.isEnabled() && toFileBox.isSelected()) {
1729:
1730:                    Destination dest = (Destination) (newAttrs
1731:                            .containsKey(Destination.class) ? newAttrs
1732:                            .get(Destination.class) : myService
1733:                            .getDefaultAttributeValue(Destination.class));
1734:                    File file = null;
1735:                    DestinationChooser chooser = new DestinationChooser();
1736:
1737:                    if (dest == null) {
1738:                        dest = new Destination((new File("out.prn")).toURI());
1739:                        /* Default file name for the output file is "out.prn" */
1740:                    }
1741:
1742:                    try {
1743:                        file = new File(dest.getURI());
1744:                    } catch (Exception e) {
1745:                        file = new File("out.prn");
1746:                    }
1747:
1748:                    chooser.setSelectedFile(file);
1749:                    chooser.setDialogTitle("Print to file");
1750:                    int chooserResult = chooser.showDialog(printDialog, "OK");
1751:                    if (chooserResult == JFileChooser.APPROVE_OPTION) {
1752:                        try {
1753:                            URI selectedFile = chooser.getSelectedFile()
1754:                                    .toURI();
1755:                            newAttrs.add(new Destination(selectedFile));
1756:                        } catch (Exception e) {
1757:                            removeAttribute(Destination.class);
1758:                        }
1759:                    }
1760:                } else {
1761:                    removeAttribute(Destination.class);
1762:                }
1763:            }
1764:
1765:            /* 
1766:             * Add/update Copies attribute to the result attribute set if "Number of 
1767:             * copies" spinner is enabled. Remove Copies attribute otherwise. 
1768:             */
1769:            private void updateCopies() {
1770:                if (cpSpinner.isEnabled()) {
1771:                    int copiesValue = ((SpinnerNumberModel) (cpSpinner
1772:                            .getModel())).getNumber().intValue();
1773:                    newAttrs.add(new Copies(copiesValue));
1774:                } else {
1775:                    removeAttribute(Copies.class);
1776:                }
1777:            }
1778:
1779:            /* 
1780:             * Add/update SheetCollate attribute to the result attribute set if "Collate"
1781:             * checkbox is enabled. Remove SheetCollate attribute otherwise.
1782:             */
1783:            private void updateCollate() {
1784:                if (collateBox.isEnabled()) {
1785:                    newAttrs
1786:                            .add(collateBox.isSelected() ? SheetCollate.COLLATED
1787:                                    : SheetCollate.UNCOLLATED);
1788:                } else {
1789:                    removeAttribute(SheetCollate.class);
1790:                }
1791:            }
1792:
1793:            /* 
1794:             * Add/update PageRanges attribute to the result attribute set if "Pages"
1795:             * radiobutton is selected and enabled and "from" <= "to". Remove PageRanges
1796:             * otherwise. "All" is always default print range, so we do not need to add
1797:             * PageRanges to the result attribute set if "All" button is selected.
1798:             * 
1799:             * Returns false if "from" > "to" or "from" or "to" have incorrect number
1800:             * format.
1801:             */
1802:            protected boolean updatePrintRange() {
1803:                if (pageRngBtn.isEnabled() && pageRngBtn.isSelected()) {
1804:                    try {
1805:                        int fromValue = Integer.valueOf(fromTxt.getText())
1806:                                .intValue();
1807:                        int toValue = Integer.valueOf(toTxt.getText())
1808:                                .intValue();
1809:                        if (fromValue > toValue) {
1810:                            throw new NumberFormatException();
1811:                        }
1812:                        newAttrs.add(new PageRanges(fromValue, toValue));
1813:                    } catch (NumberFormatException e) {
1814:                        return false;
1815:                    } catch (IllegalArgumentException e) {
1816:                        return false;
1817:                    }
1818:                } else {
1819:                    removeAttribute(PageRanges.class);
1820:                }
1821:                return true;
1822:            }
1823:
1824:            /*
1825:             * Add Media attribute to result attribute set if "Size" combobox is enabled,
1826:             * remove Media otherwise.
1827:             */
1828:            private void updateMedia() {
1829:                if (sizeBox.isEnabled() && (sizeBox.getItemCount() > 0)) {
1830:                    newAttrs.add((Media) (sizeBox.getSelectedItem()));
1831:                } else {
1832:                    removeAttribute(Media.class);
1833:                }
1834:            }
1835:
1836:            /*
1837:             * Add OrientationRequested attribute if selected service supports Orientation
1838:             * attribute, remove OrientationRequested otherwise
1839:             */
1840:            private void updateOrientation() {
1841:                if (isOrientSupported()) {
1842:                    newAttrs.add(getOrient());
1843:                } else {
1844:                    removeAttribute(OrientationRequested.class);
1845:                }
1846:            }
1847:
1848:            /*
1849:             * If Margins fields are disabled, remove MediaPrintableArea and MediaMargins
1850:             * from the result attribute set and returns true.
1851:             * Otherwise try to add/update MediaPrintableArea attribute if print service
1852:             * supports MediaPrintableArea, try to add/update MediaMargins attribute if
1853:             * service supports MediaMargins attribute. 
1854:             * 
1855:             * Returns false if margins fields have incorrect number format or margins too
1856:             * big for selected Media. 
1857:             */
1858:            private boolean updateMargins() {
1859:                float x1;
1860:                float y1;
1861:                float x2;
1862:                float y2;
1863:                NumberFormatter format = getFloatFormatter();
1864:
1865:                if (!leftTxt.isEnabled()) {
1866:                    removeAttribute(MediaPrintableArea.class);
1867:                    removeAttribute(MediaMargins.class);
1868:                    return true;
1869:                }
1870:
1871:                try {
1872:                    x1 = ((Float) format.stringToValue(leftTxt.getText()))
1873:                            .floatValue();
1874:                    x2 = ((Float) format.stringToValue(rightTxt.getText()))
1875:                            .floatValue();
1876:                    y1 = ((Float) format.stringToValue(topTxt.getText()))
1877:                            .floatValue();
1878:                    y2 = ((Float) format.stringToValue(bottomTxt.getText()))
1879:                            .floatValue();
1880:                } catch (ParseException e) {
1881:                    return false;
1882:                }
1883:
1884:                if (sizeBox.isEnabled()
1885:                        && (sizeBox.getSelectedItem() instanceof  MediaSizeName)
1886:                        && myService
1887:                                .isAttributeCategorySupported(MediaPrintableArea.class)) {
1888:                    MediaSize mediaSize = MediaSize
1889:                            .getMediaSizeForName((MediaSizeName) sizeBox
1890:                                    .getSelectedItem());
1891:                    float paperWidth = mediaSize.getX(Size2DSyntax.MM);
1892:                    float paperHeight = mediaSize.getY(Size2DSyntax.MM);
1893:                    if ((x1 + x2 >= paperWidth) || (y1 + y2 >= paperHeight)) {
1894:                        return false;
1895:                    }
1896:                    newAttrs
1897:                            .add(new MediaPrintableArea(x1, y1, paperWidth - x1
1898:                                    - x2, paperHeight - y1 - y2,
1899:                                    MediaPrintableArea.MM));
1900:                } else {
1901:                    removeAttribute(MediaPrintableArea.class);
1902:                }
1903:
1904:                if (myService.isAttributeCategorySupported(MediaMargins.class)) {
1905:                    newAttrs.add(new MediaMargins(x1, y1, x2, y2,
1906:                            MediaMargins.MM));
1907:                } else {
1908:                    removeAttribute(MediaMargins.class);
1909:                }
1910:                return true;
1911:            }
1912:
1913:            /* 
1914:             * Add/update Chromaticity attribute to the result attribute set if needed.
1915:             * Remove Chromaticity otherwise. 
1916:             */
1917:            private void updateColor() {
1918:                if (monoBtn.isEnabled() && monoBtn.isSelected()) {
1919:                    newAttrs.add(Chromaticity.MONOCHROME);
1920:                } else if (colorBtn.isEnabled() && colorBtn.isSelected()) {
1921:                    newAttrs.add(Chromaticity.COLOR);
1922:                } else {
1923:                    removeAttribute(Chromaticity.class);
1924:                }
1925:            }
1926:
1927:            /* 
1928:             * Add/update PrintQuality attribute to the result attribute set if print 
1929:             * service supports PrintQuality. Remove PrintQuality otherwise. 
1930:             */
1931:            private void updateQuality() {
1932:                if (isQualitySupported()) {
1933:                    newAttrs.add(getSelectedQuality());
1934:                } else {
1935:                    removeAttribute(PrintQuality.class);
1936:                }
1937:            }
1938:
1939:            /* 
1940:             * Add/update Sides attribute to the result attribute set if print service 
1941:             * supports Sides. Remove Sides otherwise. 
1942:             */
1943:            private void updateSides() {
1944:                if (isSidesSupported()) {
1945:                    newAttrs.add(getSelectedSide());
1946:                } else {
1947:                    removeAttribute(Sides.class);
1948:                }
1949:            }
1950:
1951:            /* 
1952:             * Add/update JobSheets attribute to the result attribute set if "Banner Page"
1953:             * combobox box is enabled. Remove JobSheets otherwise. 
1954:             */
1955:            private void updateBannerPage() {
1956:                if (bannerBox.isEnabled()) {
1957:                    newAttrs.add(bannerBox.isSelected() ? JobSheets.STANDARD
1958:                            : JobSheets.NONE);
1959:                } else {
1960:                    removeAttribute(JobSheets.class);
1961:                }
1962:            }
1963:
1964:            /* 
1965:             * Add/update JobPriority attribute to the result attribute set if "Priority"
1966:             * spinner is enabled. Remove JobPriority otherwise. 
1967:             */
1968:            private void updatePriority() {
1969:                if (prtSpinner.isEnabled()) {
1970:                    int priority = ((Integer) (prtSpinner.getValue()))
1971:                            .intValue();
1972:                    newAttrs.add(new JobPriority(priority));
1973:                } else {
1974:                    removeAttribute(JobPriority.class);
1975:                }
1976:            }
1977:
1978:            /* 
1979:             * Add/update JobName attribute to the result attribute set if "Job name" field
1980:             * is enabled and is not empty. Remove JobName otherwise. 
1981:             */
1982:            private void updateJobName() {
1983:                if (jobNameTxt.isEnabled()) {
1984:                    String name = jobNameTxt.getText();
1985:                    if (name.length() == 0) {
1986:                        removeAttribute(JobName.class);
1987:                    } else {
1988:                        newAttrs.add(new JobName(name, Locale.getDefault()));
1989:                    }
1990:                } else {
1991:                    removeAttribute(JobName.class);
1992:                }
1993:            }
1994:
1995:            /* 
1996:             * Add/update JobName attribute to the result attribute set if "User name" 
1997:             * field is enabled and is not empty. Remove UserName otherwise. 
1998:             */
1999:            private void updateUserName() {
2000:                if (userNameTxt.isEnabled()) {
2001:                    String name = userNameTxt.getText();
2002:                    if (name.length() == 0) {
2003:                        removeAttribute(RequestingUserName.class);
2004:                    } else {
2005:                        newAttrs.add(new RequestingUserName(name, Locale
2006:                                .getDefault()));
2007:                    }
2008:                } else {
2009:                    removeAttribute(RequestingUserName.class);
2010:                }
2011:            }
2012:
2013:            private void removeAttribute(Class cls) {
2014:                if (newAttrs.containsKey(cls)) {
2015:                    newAttrs.remove(cls);
2016:                }
2017:            }
2018:
2019:            //---------------------------------------------------------------------
2020:            /* 
2021:             * Panel for the Page Setup dialog 
2022:             */
2023:            private JPanel getPageDialogPanel() {
2024:                JPanel pageDialogPanel = new JPanel(new GridBagLayout());
2025:                GridBagConstraints gridBagConstraints182 = new GridBagConstraints();
2026:                GridBagConstraints gridBagConstraints172 = new GridBagConstraints();
2027:                pageDialogPanel.setPreferredSize(new java.awt.Dimension(100,
2028:                        100));
2029:                pageDialogPanel.setSize(532, 389);
2030:                gridBagConstraints172.gridx = 0;
2031:                gridBagConstraints172.gridy = 1;
2032:                gridBagConstraints172.anchor = java.awt.GridBagConstraints.EAST;
2033:                gridBagConstraints172.gridwidth = 3;
2034:                gridBagConstraints182.gridx = 0;
2035:                gridBagConstraints182.gridy = 0;
2036:                gridBagConstraints182.weightx = 1.0;
2037:                gridBagConstraints182.weighty = 1.0;
2038:                gridBagConstraints182.fill = java.awt.GridBagConstraints.BOTH;
2039:                pageDialogPanel.add(getButtonsPanel(), gridBagConstraints172);
2040:                pageDialogPanel.add(getPageSetupPanel(), gridBagConstraints182);
2041:                return pageDialogPanel;
2042:            }
2043:
2044:            //---------------------------------------------------------------------
2045:            /* 
2046:             * JFileChooser for the selecting file for the Destination attribute.
2047:             * Shows confirm message if the selected file is always exists
2048:             */
2049:            private class DestinationChooser extends JFileChooser {
2050:
2051:                static final long serialVersionUID = 5429146989329327138L;
2052:
2053:                public void approveSelection() {
2054:                    boolean doesFileExists = false; // Does selected file exist?
2055:                    boolean result = true; // File selection result
2056:
2057:                    try {
2058:                        doesFileExists = getSelectedFile().exists();
2059:                    } catch (Exception e) {
2060:                        /* if exception was thrown, fileExists flag remains false */
2061:                    }
2062:
2063:                    if (doesFileExists) {
2064:                        FilePermission delPermission = new FilePermission(
2065:                                getSelectedFile().getAbsolutePath(), "delete");
2066:                        if (checkFilePermission(delPermission)) {
2067:                            String msg = "File " + getSelectedFile()
2068:                                    + " is already exists.\n"
2069:                                    + "Do you want to overwrite it?";
2070:                            int approveDelete = JOptionPane.showConfirmDialog(
2071:                                    null, "File exists!", msg,
2072:                                    JOptionPane.YES_NO_OPTION);
2073:                            result = (approveDelete == JOptionPane.YES_OPTION);
2074:                        } else {
2075:                            JOptionPane.showMessageDialog(null,
2076:                                    "Can not delete file " + getSelectedFile());
2077:                            result = false;
2078:                        }
2079:                    }
2080:
2081:                    if (result) {
2082:                        super .approveSelection();
2083:                    }
2084:                }
2085:            } /* End of DestinationChooser class */
2086:        } /* End of ServiceUIDialog class */
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.