2283 lines · 83.3 KB · Java
RawDownload
     * @see Printable     */    public void setPageable(Pageable document) throws NullPointerException {        if (document != null) {            mDocument = document;         } else {            throw new NullPointerException();        }    }     protected void initPrinter() {        return;    }     protected boolean isSupportedValue(Attribute attrval,                                     PrintRequestAttributeSet attrset) {        PrintService ps = getPrintService();        return            (attrval != null && ps != null &&             ps.isAttributeValueSupported(attrval,                                          DocFlavor.SERVICE_FORMATTED.PAGEABLE,                                          attrset));    }     /* subclasses may need to pull extra information out of the attribute set     * They can override this method & call super.setAttributes()     */    protected  void setAttributes(PrintRequestAttributeSet attributes)        throws PrinterException {        /*  reset all values to defaults */        setCollated(false);        sidesAttr = null;        pageRangesAttr = null;        copiesAttr = 0;        jobNameAttr = null;        userNameAttr = null;        destinationAttr = null;        collateAttReq = false;         PrintService service = getPrintService();        if (attributes == null  || service == null) {            return;        }         boolean fidelity = false;        Fidelity attrFidelity = (Fidelity)attributes.get(Fidelity.class);        if (attrFidelity != null && attrFidelity == Fidelity.FIDELITY_TRUE) {            fidelity = true;        }         if (fidelity == true) {           AttributeSet unsupported =               service.getUnsupportedAttributes(                                         DocFlavor.SERVICE_FORMATTED.PAGEABLE,                                         attributes);           if (unsupported != null) {               throw new PrinterException("Fidelity cannot be satisfied");           }        }         /*         * Since we have verified supported values if fidelity is true,         * we can either ignore unsupported values, or substitute a         * reasonable alternative         */         SheetCollate collateAttr =            (SheetCollate)attributes.get(SheetCollate.class);        if (isSupportedValue(collateAttr,  attributes)) {            setCollated(collateAttr == SheetCollate.COLLATED);        }         sidesAttr = (Sides)attributes.get(Sides.class);        if (!isSupportedValue(sidesAttr,  attributes)) {            sidesAttr = Sides.ONE_SIDED;        }         pageRangesAttr =  (PageRanges)attributes.get(PageRanges.class);        if (!isSupportedValue(pageRangesAttr, attributes)) {            pageRangesAttr = null;        } else {            if ((SunPageSelection)attributes.get(SunPageSelection.class)                     == SunPageSelection.RANGE) {                // get to, from, min, max page ranges                int[][] range = pageRangesAttr.getMembers();                // setPageRanges uses 0-based indexing so we subtract 1                setPageRange(range[0][0] - 1, range[0][1] - 1);            } else {               setPageRange(-1, - 1);            }        }         Copies copies = (Copies)attributes.get(Copies.class);        if (isSupportedValue(copies,  attributes) ||            (!fidelity && copies != null)) {            copiesAttr = copies.getValue();            setCopies(copiesAttr);        } else {            copiesAttr = getCopies();        }         Destination destination =            (Destination)attributes.get(Destination.class);         if (isSupportedValue(destination,  attributes)) {            try {                // Old code (new File(destination.getURI())).getPath()                // would generate a "URI is not hierarchical" IAE                // for "file:out.prn" so we use getSchemeSpecificPart instead                destinationAttr = "" + new File(destination.getURI().                                                getSchemeSpecificPart());            } catch (Exception e) { // paranoid exception                Destination defaultDest = (Destination)service.                    getDefaultAttributeValue(Destination.class);                if (defaultDest != null) {                    destinationAttr = "" + new File(defaultDest.getURI().                                                getSchemeSpecificPart());                }            }        }         JobSheets jobSheets = (JobSheets)attributes.get(JobSheets.class);        if (jobSheets != null) {            noJobSheet = jobSheets == JobSheets.NONE;        }         JobName jobName = (JobName)attributes.get(JobName.class);        if (isSupportedValue(jobName,  attributes) ||            (!fidelity && jobName != null)) {            jobNameAttr = jobName.getValue();            setJobName(jobNameAttr);        } else {            jobNameAttr = getJobName();        }         RequestingUserName userName =            (RequestingUserName)attributes.get(RequestingUserName.class);        if (isSupportedValue(userName,  attributes) ||            (!fidelity && userName != null)) {            userNameAttr = userName.getValue();        } else {            try {                userNameAttr = getUserName();            } catch (SecurityException e) {                userNameAttr = "";            }        }         /* OpenBook is used internally only when app uses Printable.         * This is the case when we use the values from the attribute set.         */        Media media = (Media)attributes.get(Media.class);        OrientationRequested orientReq =           (OrientationRequested)attributes.get(OrientationRequested.class);        MediaPrintableArea mpa =            (MediaPrintableArea)attributes.get(MediaPrintableArea.class);         if ((orientReq != null || media != null || mpa != null) &&            getPageable() instanceof OpenBook) {             /* We could almost(!) use PrinterJob.getPageFormat() except             * here we need to start with the PageFormat from the OpenBook :             */            Pageable pageable = getPageable();            Printable printable = pageable.getPrintable(0);            PageFormat pf = (PageFormat)pageable.getPageFormat(0).clone();            Paper paper = pf.getPaper();             /* If there's a media but no media printable area, we can try             * to retrieve the default value for mpa and use that.             */            if (mpa == null && media != null &&                service.                isAttributeCategorySupported(MediaPrintableArea.class)) {                Object mpaVals = service.                    getSupportedAttributeValues(MediaPrintableArea.class,                                                null, attributes);                if (mpaVals instanceof MediaPrintableArea[] &&                    ((MediaPrintableArea[])mpaVals).length > 0) {                    mpa = ((MediaPrintableArea[])mpaVals)[0];                }            }             if (isSupportedValue(orientReq, attributes) ||                (!fidelity && orientReq != null)) {                int orient;                if (orientReq.equals(OrientationRequested.REVERSE_LANDSCAPE)) {                    orient = PageFormat.REVERSE_LANDSCAPE;                } else if (orientReq.equals(OrientationRequested.LANDSCAPE)) {                    orient = PageFormat.LANDSCAPE;                } else {                    orient = PageFormat.PORTRAIT;                }                pf.setOrientation(orient);            }             if (isSupportedValue(media, attributes) ||                (!fidelity && media != null)) {                if (media instanceof MediaSizeName) {                    MediaSizeName msn = (MediaSizeName)media;                    MediaSize msz = MediaSize.getMediaSizeForName(msn);                    if (msz != null) {                        float paperWid =  msz.getX(MediaSize.INCH) * 72.0f;                        float paperHgt =  msz.getY(MediaSize.INCH) * 72.0f;                        paper.setSize(paperWid, paperHgt);                        if (mpa == null) {                            paper.setImageableArea(72.0, 72.0,                                                   paperWid-144.0,                                                   paperHgt-144.0);                        }                    }                }            }             if (isSupportedValue(mpa, attributes) ||                (!fidelity && mpa != null)) {                float [] printableArea =                    mpa.getPrintableArea(MediaPrintableArea.INCH);                for (int i=0; i < printableArea.length; i++) {                    printableArea[i] = printableArea[i]*72.0f;                }                paper.setImageableArea(printableArea[0], printableArea[1],                                       printableArea[2], printableArea[3]);            }             pf.setPaper(paper);            pf = validatePage(pf);            setPrintable(printable, pf);        } else {            // for AWT where pageable is not an instance of OpenBook,            // we need to save paper info            this.attributes = attributes;        }     }     /*     * Services we don't recognize as built-in services can't be     * implemented as subclasses of PrinterJob, therefore we create     * a DocPrintJob from their service and pass a Doc representing     * the application's printjob     */    private void spoolToService(PrintService psvc,                                PrintRequestAttributeSet attributes)        throws PrinterException {         if (psvc == null) {            throw new PrinterException("No print service found.");        }         DocPrintJob job = psvc.createPrintJob();        Doc doc = new PageableDoc(getPageable());        if (attributes == null) {            attributes = new HashPrintRequestAttributeSet();        }        try {            job.print(doc, attributes);        } catch (PrintException e) {            throw new PrinterException(e.toString());        }    }     /**     * Prints a set of pages.     * @exception java.awt.print.PrinterException an error in the print system     *                                          caused the job to be aborted     * @see java.awt.print.Book     * @see java.awt.print.Pageable     * @see java.awt.print.Printable     */    public void print() throws PrinterException {        print(attributes);    }     public static boolean debugPrint = false;    protected void debug_println(String str) {        if (debugPrint) {            System.out.println("RasterPrinterJob "+str+" "+this);        }    }     public void print(PrintRequestAttributeSet attributes)        throws PrinterException {         /*         * In the future PrinterJob will probably always dispatch         * the print job to the PrintService.         * This is how third party 2D Print Services will be invoked         * when applications use the PrinterJob API.         * However the JRE's concrete PrinterJob implementations have         * not yet been re-worked to be implemented as standalone         * services, and are implemented only as subclasses of PrinterJob.         * So here we dispatch only those services we do not recognize         * as implemented through platform subclasses of PrinterJob         * (and this class).         */        PrintService psvc = getPrintService();        debug_println("psvc = "+psvc);        if (psvc == null) {            throw new PrinterException("No print service found.");        }         // Check the list of services.  This service may have been        // deleted already        PrinterState prnState = (PrinterState)psvc.getAttribute(                                                  PrinterState.class);        if (prnState == PrinterState.STOPPED) {            PrinterStateReasons prnStateReasons =                    (PrinterStateReasons)psvc.getAttribute(                                                 PrinterStateReasons.class);                if ((prnStateReasons != null) &&                    (prnStateReasons.containsKey(PrinterStateReason.SHUTDOWN)))                {                    throw new PrinterException("PrintService is no longer available.");                }        }         if ((PrinterIsAcceptingJobs)(psvc.getAttribute(                         PrinterIsAcceptingJobs.class)) ==                         PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS) {            throw new PrinterException("Printer is not accepting job.");        }         if ((psvc instanceof SunPrinterJobService) &&            ((SunPrinterJobService)psvc).usesClass(getClass())) {            setAttributes(attributes);            // throw exception for invalid destination            if (destinationAttr != null) {                // destinationAttr is null for Destination(new URI(""))                // because isAttributeValueSupported returns false in setAttributes                 // Destination(new URI(" ")) throws URISyntaxException                File f = new File(destinationAttr);                try {                    // check if this is a new file and if filename chars are valid                    if (f.createNewFile()) {                        f.delete();                    }                } catch (IOException ioe) {                    throw new PrinterException("Cannot write to file:"+                                               destinationAttr);                } catch (SecurityException se) {                    //There is already file read/write access so at this point                    // only delete access is denied.  Just ignore it because in                    // most cases the file created in createNewFile gets overwritten                    // anyway.                }                 File pFile = f.getParentFile();                if ((f.exists() &&                     (!f.isFile() || !f.canWrite())) ||                    ((pFile != null) &&                     (!pFile.exists() || (pFile.exists() && !pFile.canWrite())))) {                    throw new PrinterException("Cannot write to file:"+                                               destinationAttr);                }            }        } else {            spoolToService(psvc, attributes);            return;        }        /* We need to make sure that the collation and copies         * settings are initialised */        initPrinter();         int numCollatedCopies = getCollatedCopies();        int numNonCollatedCopies = getNoncollatedCopies();        debug_println("getCollatedCopies()  "+numCollatedCopies              + " getNoncollatedCopies() "+ numNonCollatedCopies);         /* Get the range of pages we are to print. If the         * last page to print is unknown, then we print to         * the end of the document. Note that firstPage         * and lastPage are 0 based page indices.         */        int numPages = mDocument.getNumberOfPages();        if (numPages == 0) {            return;        }         int firstPage = getFirstPage();        int lastPage = getLastPage();        if(lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES){            int totalPages = mDocument.getNumberOfPages();            if (totalPages != Pageable.UNKNOWN_NUMBER_OF_PAGES) {                lastPage = mDocument.getNumberOfPages() - 1;            }        }         try {            synchronized (this) {                performingPrinting = true;                userCancelled = false;            }             startDoc();            if (isCancelled()) {                cancelDoc();            }             // PageRanges can be set even if RANGE is not selected            // so we need to check if it is selected.            boolean rangeIsSelected = true;            if (attributes != null) {                SunPageSelection pages =                    (SunPageSelection)attributes.get(SunPageSelection.class);                if ((pages != null) && (pages != SunPageSelection.RANGE)) {                    rangeIsSelected = false;                }            }              debug_println("after startDoc rangeSelected? "+rangeIsSelected                      + " numNonCollatedCopies "+ numNonCollatedCopies);              /* Three nested loops iterate over the document. The outer loop             * counts the number of collated copies while the inner loop             * counts the number of nonCollated copies. Normally, one of             * these two loops will only execute once; that is we will             * either print collated copies or noncollated copies. The             * middle loop iterates over the pages.             * If a PageRanges attribute is used, it constrains the pages             * that are imaged. If a platform subclass (though a user dialog)             * requests a page range via setPageRange(). it too can             * constrain the page ranges that are imaged.             * It is expected that only one of these will be used in a             * job but both should be able to co-exist.             */            for(int collated = 0; collated < numCollatedCopies; collated++) {                for(int i = firstPage, pageResult = Printable.PAGE_EXISTS;                    (i <= lastPage ||                     lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES)                    && pageResult == Printable.PAGE_EXISTS;                    i++)                {                     if ((pageRangesAttr != null) && rangeIsSelected ){                        int nexti = pageRangesAttr.next(i);                        if (nexti == -1) {                            break;                        } else if (nexti != i+1) {                            continue;                        }                    }                     for(int nonCollated = 0;                        nonCollated < numNonCollatedCopies                        && pageResult == Printable.PAGE_EXISTS;                        nonCollated++)                    {                        if (isCancelled()) {                            cancelDoc();                        }                        debug_println("printPage "+i);                        pageResult = printPage(mDocument, i);                     }                }            }             if (isCancelled()) {                cancelDoc();            }         } finally {            // reset previousPaper in case this job is invoked again.            previousPaper = null;            synchronized (this) {                if (performingPrinting) {                    endDoc();                }                performingPrinting = false;                notify();            }        }    }     /**     * updates a Paper object to reflect the current printer's selected     * paper size and imageable area for that paper size.     * Default implementation copies settings from the original, applies     * applies some validity checks, changes them only if they are     * clearly unreasonable, then sets them into the new Paper.     * Subclasses are expected to override this method to make more     * informed decisons.     */    protected void validatePaper(Paper origPaper, Paper newPaper) {        if (origPaper == null || newPaper == null) {            return;        } else {            double wid = origPaper.getWidth();            double hgt = origPaper.getHeight();            double ix = origPaper.getImageableX();            double iy = origPaper.getImageableY();            double iw = origPaper.getImageableWidth();            double ih = origPaper.getImageableHeight();             /* Assume any +ve values are legal. Overall paper dimensions

Lines 1001–1500 of 2283. Previous lines