CUPSPrinter.java 16.1 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
 */

package sun.print;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import sun.print.IPPPrintService;
import sun.print.CustomMediaSizeName;
import sun.print.CustomMediaTray;
import javax.print.attribute.standard.Media;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.MediaTray;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.Size2DSyntax;
import javax.print.attribute.Attribute;
import javax.print.attribute.EnumSyntax;
import javax.print.attribute.standard.PrinterName;


public class CUPSPrinter  {
49
    private static final String debugPrefix = "CUPSPrinter>> ";
D
duke 已提交
50
    private static final double PRINTER_DPI = 72.0;
51
    private boolean initialized;
D
duke 已提交
52 53
    private static native String getCupsServer();
    private static native int getCupsPort();
54
    private static native String getCupsDefaultPrinter();
D
duke 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    private static native boolean canConnect(String server, int port);
    private static native boolean initIDs();
    // These functions need to be synchronized as
    // CUPS does not support multi-threading.
    private static synchronized native String[] getMedia(String printer);
    private static synchronized native float[] getPageSizes(String printer);
    //public static boolean useIPPMedia = false; will be used later

    private MediaPrintableArea[] cupsMediaPrintables;
    private MediaSizeName[] cupsMediaSNames;
    private CustomMediaSizeName[] cupsCustomMediaSNames;
    private MediaTray[] cupsMediaTrays;

    public  int nPageSizes = 0;
    public  int nTrays = 0;
    private  String[] media;
    private  float[] pageSizes;
    private String printer;

    private static boolean libFound;
    private static String cupsServer = null;
    private static int cupsPort = 0;

    static {
        // load awt library to access native code
        java.security.AccessController.doPrivileged(
81 82 83 84 85 86
            new java.security.PrivilegedAction<Void>() {
                public Void run() {
                    System.loadLibrary("awt");
                    return null;
                }
            });
D
duke 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        libFound = initIDs();
        if (libFound) {
           cupsServer = getCupsServer();
           cupsPort = getCupsPort();
        }
    }


    CUPSPrinter (String printerName) {
        if (printerName == null) {
            throw new IllegalArgumentException("null printer name");
        }
        printer = printerName;
        cupsMediaSNames = null;
        cupsMediaPrintables = null;
        cupsMediaTrays = null;
        initialized = false;

        if (!libFound) {
            throw new RuntimeException("cups lib not found");
        } else {
            // get page + tray names
            media =  getMedia(printer);
            if (media == null) {
                // either PPD file is not found or printer is unknown
                throw new RuntimeException("error getting PPD");
            }

            // get sizes
            pageSizes = getPageSizes(printer);
            if (pageSizes != null) {
                nPageSizes = pageSizes.length/6;

                nTrays = media.length/2-nPageSizes;
                assert (nTrays >= 0);
            }
        }
    }


    /**
     * Returns array of MediaSizeNames derived from PPD.
     */
P
prr 已提交
130
    MediaSizeName[] getMediaSizeNames() {
D
duke 已提交
131 132 133 134 135 136 137 138
        initMedia();
        return cupsMediaSNames;
    }


    /**
     * Returns array of Custom MediaSizeNames derived from PPD.
     */
P
prr 已提交
139
    CustomMediaSizeName[] getCustomMediaSizeNames() {
D
duke 已提交
140 141 142 143
        initMedia();
        return cupsCustomMediaSNames;
    }

144 145 146
    public int getDefaultMediaIndex() {
        return ((pageSizes.length >1) ? (int)(pageSizes[pageSizes.length -1]) : 0);
    }
D
duke 已提交
147 148 149 150

    /**
     * Returns array of MediaPrintableArea derived from PPD.
     */
P
prr 已提交
151
    MediaPrintableArea[] getMediaPrintableArea() {
D
duke 已提交
152 153 154 155 156 157 158
        initMedia();
        return cupsMediaPrintables;
    }

    /**
     * Returns array of MediaTrays derived from PPD.
     */
P
prr 已提交
159
    MediaTray[] getMediaTrays() {
D
duke 已提交
160 161 162 163 164 165 166 167
        initMedia();
        return cupsMediaTrays;
    }


    /**
     * Initialize media by translating PPD info to PrintService attributes.
     */
168
    private synchronized void initMedia() {
D
duke 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
        if (initialized) {
            return;
        } else {
            initialized = true;
        }

        if (pageSizes == null) {
            return;
        }

        cupsMediaPrintables = new MediaPrintableArea[nPageSizes];
        cupsMediaSNames = new MediaSizeName[nPageSizes];
        cupsCustomMediaSNames = new CustomMediaSizeName[nPageSizes];

        CustomMediaSizeName msn;
        MediaPrintableArea mpa;
        float length, width, x, y, w, h;

        // initialize names and printables
        for (int i=0; i<nPageSizes; i++) {
            // media width and length
            width = (float)(pageSizes[i*6]/PRINTER_DPI);
            length = (float)(pageSizes[i*6+1]/PRINTER_DPI);
            // media printable area
            x = (float)(pageSizes[i*6+2]/PRINTER_DPI);
            h = (float)(pageSizes[i*6+3]/PRINTER_DPI);
            w = (float)(pageSizes[i*6+4]/PRINTER_DPI);
            y = (float)(pageSizes[i*6+5]/PRINTER_DPI);

            msn = new CustomMediaSizeName(media[i*2], media[i*2+1],
                                          width, length);

            // add to list of standard MediaSizeNames
            if ((cupsMediaSNames[i] = msn.getStandardMedia()) == null) {
                // add custom if no matching standard media
                cupsMediaSNames[i] = msn;

                // add this new custom msn to MediaSize array
                if ((width > 0.0) && (length > 0.0)) {
208
                    try {
D
duke 已提交
209 210
                    new MediaSize(width, length,
                                  Size2DSyntax.INCH, msn);
211 212 213 214 215 216
                    } catch (IllegalArgumentException e) {
                        /* PDF printer in Linux for Ledger paper causes
                        "IllegalArgumentException: X dimension > Y dimension".
                        We rotate based on IPP spec. */
                        new MediaSize(length, width, Size2DSyntax.INCH, msn);
                    }
D
duke 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                }
            }

            // add to list of custom MediaSizeName
            // for internal use of IPPPrintService
            cupsCustomMediaSNames[i] = msn;

            mpa = null;
            try {
                mpa = new MediaPrintableArea(x, y, w, h,
                                             MediaPrintableArea.INCH);
            } catch (IllegalArgumentException e) {
                if (width > 0 && length > 0) {
                    mpa = new MediaPrintableArea(0, 0, width, length,
                                             MediaPrintableArea.INCH);
                }
            }
            cupsMediaPrintables[i] = mpa;
        }

        // initialize trays
        cupsMediaTrays = new MediaTray[nTrays];

        MediaTray mt;
        for (int i=0; i<nTrays; i++) {
            mt = new CustomMediaTray(media[(nPageSizes+i)*2],
                                     media[(nPageSizes+i)*2+1]);
            cupsMediaTrays[i] = mt;
        }

    }

    /**
     * Get CUPS default printer using IPP.
251
     * Returns 2 values - index 0 is printer name, index 1 is the uri.
D
duke 已提交
252
     */
253
    static String[] getDefaultPrinter() {
254 255 256 257 258 259 260 261 262
        // Try to get user/lpoptions-defined printer name from CUPS
        // if not user-set, then go for server default destination
        String printerInfo[] = new String[2];
        printerInfo[0] = getCupsDefaultPrinter();

        if (printerInfo[0] != null) {
            printerInfo[1] = null;
            return printerInfo.clone();
        }
D
duke 已提交
263 264 265 266 267 268 269 270 271 272 273 274
        try {
            URL url = new URL("http", getServer(), getPort(), "");
            final HttpURLConnection urlConnection =
                IPPPrintService.getIPPConnection(url);

            if (urlConnection != null) {
                OutputStream os = (OutputStream)java.security.AccessController.
                    doPrivileged(new java.security.PrivilegedAction() {
                        public Object run() {
                            try {
                                return urlConnection.getOutputStream();
                            } catch (Exception e) {
275
                               IPPPrintService.debug_println(debugPrefix+e);
D
duke 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288
                            }
                            return null;
                        }
                    });

                if (os == null) {
                    return null;
                }

                AttributeClass attCl[] = {
                    AttributeClass.ATTRIBUTES_CHARSET,
                    AttributeClass.ATTRIBUTES_NATURAL_LANGUAGE,
                    new AttributeClass("requested-attributes",
289 290
                                       AttributeClass.TAG_URI,
                                       "printer-uri")
D
duke 已提交
291 292 293 294 295 296 297
                };

                if (IPPPrintService.writeIPPRequest(os,
                                        IPPPrintService.OP_CUPS_GET_DEFAULT,
                                        attCl)) {

                    HashMap defaultMap = null;
298

D
duke 已提交
299 300 301 302 303
                    InputStream is = urlConnection.getInputStream();
                    HashMap[] responseMap = IPPPrintService.readIPPResponse(
                                         is);
                    is.close();

304
                    if (responseMap != null && responseMap.length > 0) {
D
duke 已提交
305
                        defaultMap = responseMap[0];
306 307 308
                    } else {
                       IPPPrintService.debug_println(debugPrefix+
                           " empty response map for GET_DEFAULT.");
D
duke 已提交
309 310 311 312 313
                    }

                    if (defaultMap == null) {
                        os.close();
                        urlConnection.disconnect();
314 315 316 317 318 319 320

                        /* CUPS on OS X, as initially configured, considers the
                         * default printer to be the last one used that's
                         * presently available. So if no default was
                         * reported, exec lpstat -d which has all the Apple
                         * special behaviour for this built in.
                         */
321 322
                         if (PrintServiceLookupProvider.isMac()) {
                             printerInfo[0] = PrintServiceLookupProvider.
323
                                                   getDefaultPrinterNameSysV();
324 325
                             printerInfo[1] = null;
                             return (String[])printerInfo.clone();
326 327 328
                         } else {
                             return null;
                         }
D
duke 已提交
329 330
                    }

331

D
duke 已提交
332 333 334 335
                    AttributeClass attribClass = (AttributeClass)
                        defaultMap.get("printer-name");

                    if (attribClass != null) {
336
                        printerInfo[0] = attribClass.getStringValue();
337 338 339 340
                        attribClass = (AttributeClass)
                            defaultMap.get("printer-uri-supported");
                        IPPPrintService.debug_println(debugPrefix+
                          "printer-uri-supported="+attribClass);
341 342 343 344 345
                        if (attribClass != null) {
                            printerInfo[1] = attribClass.getStringValue();
                        } else {
                            printerInfo[1] = null;
                        }
D
duke 已提交
346 347
                        os.close();
                        urlConnection.disconnect();
348
                        return (String [])printerInfo.clone();
D
duke 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362
                    }
                }
                os.close();
                urlConnection.disconnect();
            }
        } catch (Exception e) {
        }
        return null;
    }


    /**
     * Get list of all CUPS printers using IPP.
     */
363
    static String[] getAllPrinters() {
D
duke 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        try {
            URL url = new URL("http", getServer(), getPort(), "");

            final HttpURLConnection urlConnection =
                IPPPrintService.getIPPConnection(url);

            if (urlConnection != null) {
                OutputStream os = (OutputStream)java.security.AccessController.
                    doPrivileged(new java.security.PrivilegedAction() {
                        public Object run() {
                            try {
                                return urlConnection.getOutputStream();
                            } catch (Exception e) {
                            }
                            return null;
                        }
                    });

                if (os == null) {
                    return null;
                }

                AttributeClass attCl[] = {
                    AttributeClass.ATTRIBUTES_CHARSET,
                    AttributeClass.ATTRIBUTES_NATURAL_LANGUAGE,
                    new AttributeClass("requested-attributes",
                                       AttributeClass.TAG_KEYWORD,
391
                                       "printer-uri-supported")
D
duke 已提交
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
                };

                if (IPPPrintService.writeIPPRequest(os,
                                IPPPrintService.OP_CUPS_GET_PRINTERS, attCl)) {

                    InputStream is = urlConnection.getInputStream();
                    HashMap[] responseMap =
                        IPPPrintService.readIPPResponse(is);

                    is.close();
                    os.close();
                    urlConnection.disconnect();

                    if (responseMap == null || responseMap.length == 0) {
                        return null;
                    }

                    ArrayList printerNames = new ArrayList();
                    for (int i=0; i< responseMap.length; i++) {
                        AttributeClass attribClass = (AttributeClass)
412
                            responseMap[i].get("printer-uri-supported");
D
duke 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

                        if (attribClass != null) {
                            String nameStr = attribClass.getStringValue();
                            printerNames.add(nameStr);
                        }
                    }
                    return (String[])printerNames.toArray(new String[] {});
                } else {
                    os.close();
                    urlConnection.disconnect();
                }
            }

        } catch (Exception e) {
        }
        return null;

    }

    /**
     * Returns CUPS server name.
     */
    public static String getServer() {
        return cupsServer;
    }

    /**
     * Returns CUPS port number.
     */
    public static int getPort() {
        return cupsPort;
    }

    /**
     * Detects if CUPS is running.
     */
    public static boolean isCupsRunning() {
450
        IPPPrintService.debug_println(debugPrefix+"libFound "+libFound);
D
duke 已提交
451
        if (libFound) {
452
            IPPPrintService.debug_println(debugPrefix+"CUPS server "+getServer()+
D
duke 已提交
453 454 455 456 457 458 459 460 461
                                          " port "+getPort());
            return canConnect(getServer(), getPort());
        } else {
            return false;
        }
    }


}