CUPSPrinter.java 14.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2012, 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 54 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
    private static native String getCupsServer();
    private static native int getCupsPort();
    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(
80 81 82 83 84 85
            new java.security.PrivilegedAction<Void>() {
                public Void run() {
                    System.loadLibrary("awt");
                    return null;
                }
            });
D
duke 已提交
86 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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        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.
     */
    public MediaSizeName[] getMediaSizeNames() {
        initMedia();
        return cupsMediaSNames;
    }


    /**
     * Returns array of Custom MediaSizeNames derived from PPD.
     */
    public CustomMediaSizeName[] getCustomMediaSizeNames() {
        initMedia();
        return cupsCustomMediaSNames;
    }


    /**
     * Returns array of MediaPrintableArea derived from PPD.
     */
    public MediaPrintableArea[] getMediaPrintableArea() {
        initMedia();
        return cupsMediaPrintables;
    }

    /**
     * Returns array of MediaTrays derived from PPD.
     */
    public MediaTray[] getMediaTrays() {
        initMedia();
        return cupsMediaTrays;
    }


    /**
     * Initialize media by translating PPD info to PrintService attributes.
     */
164
    private synchronized void initMedia() {
D
duke 已提交
165 166 167 168 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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        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)) {
                    new MediaSize(width, length,
                                  Size2DSyntax.INCH, msn);
                }
            }

            // 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.
240
     * Returns 2 values - index 0 is printer name, index 1 is the uri.
D
duke 已提交
241
     */
242
    static String[] getDefaultPrinter() {
D
duke 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        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",
268 269
                                       AttributeClass.TAG_URI,
                                       "printer-uri")
D
duke 已提交
270 271 272 273 274 275 276
                };

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

                    HashMap defaultMap = null;
277
                    String[] printerInfo = new String[2];
D
duke 已提交
278 279 280 281 282
                    InputStream is = urlConnection.getInputStream();
                    HashMap[] responseMap = IPPPrintService.readIPPResponse(
                                         is);
                    is.close();

283
                    if (responseMap != null && responseMap.length > 0) {
D
duke 已提交
284 285 286 287 288 289
                        defaultMap = responseMap[0];
                    }

                    if (defaultMap == null) {
                        os.close();
                        urlConnection.disconnect();
290 291 292 293 294 295 296 297

                        /* 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.
                         */
                         if (UnixPrintServiceLookup.isMac()) {
298
                             printerInfo[0] = UnixPrintServiceLookup.
299
                                                   getDefaultPrinterNameSysV();
300 301
                             printerInfo[1] = null;
                             return (String[])printerInfo.clone();
302 303 304
                         } else {
                             return null;
                         }
D
duke 已提交
305 306
                    }

307

D
duke 已提交
308 309 310 311
                    AttributeClass attribClass = (AttributeClass)
                        defaultMap.get("printer-name");

                    if (attribClass != null) {
312 313 314 315 316 317 318
                        printerInfo[0] = attribClass.getStringValue();
                        attribClass = (AttributeClass)defaultMap.get("device-uri");
                        if (attribClass != null) {
                            printerInfo[1] = attribClass.getStringValue();
                        } else {
                            printerInfo[1] = null;
                        }
D
duke 已提交
319 320
                        os.close();
                        urlConnection.disconnect();
321
                        return (String [])printerInfo.clone();
D
duke 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335
                    }
                }
                os.close();
                urlConnection.disconnect();
            }
        } catch (Exception e) {
        }
        return null;
    }


    /**
     * Get list of all CUPS printers using IPP.
     */
336
    static String[] getAllPrinters() {
D
duke 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        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,
364
                                       "printer-uri-supported")
D
duke 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
                };

                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)
385
                            responseMap[i].get("printer-uri-supported");
D
duke 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422

                        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() {
423
        IPPPrintService.debug_println(debugPrefix+"libFound "+libFound);
D
duke 已提交
424
        if (libFound) {
425
            IPPPrintService.debug_println(debugPrefix+"CUPS server "+getServer()+
D
duke 已提交
426 427 428 429 430 431 432 433 434
                                          " port "+getPort());
            return canConnect(getServer(), getPort());
        } else {
            return false;
        }
    }


}