CImage.java revision 11916:a1b10dc613a9
1/*
2 * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package sun.lwawt.macosx;
27
28import java.awt.*;
29import java.awt.geom.Dimension2D;
30import java.awt.image.*;
31
32import java.util.Arrays;
33import java.util.List;
34import sun.awt.image.MultiResolutionImage;
35import sun.awt.image.MultiResolutionCachedImage;
36
37import sun.awt.image.SunWritableRaster;
38
39public class CImage extends CFRetainedResource {
40    private static native long nativeCreateNSImageFromArray(int[] buffer, int w, int h);
41    private static native long nativeCreateNSImageFromBytes(byte[] buffer);
42    private static native long nativeCreateNSImageFromArrays(int[][] buffers, int w[], int h[]);
43    private static native long nativeCreateNSImageFromFileContents(String file);
44    private static native long nativeCreateNSImageOfFileFromLaunchServices(String file);
45    private static native long nativeCreateNSImageFromImageName(String name);
46    private static native long nativeCreateNSImageFromIconSelector(int selector);
47    private static native byte[] nativeGetPlatformImageBytes(int[] buffer, int w, int h);
48    private static native void nativeCopyNSImageIntoArray(long image, int[] buffer, int sw, int sh, int dw, int dh);
49    private static native Dimension2D nativeGetNSImageSize(long image);
50    private static native void nativeSetNSImageSize(long image, double w, double h);
51    private static native void nativeResizeNSImageRepresentations(long image, double w, double h);
52    private static native Dimension2D[] nativeGetNSImageRepresentationSizes(long image, double w, double h);
53
54    static Creator creator = new Creator();
55    static Creator getCreator() {
56        return creator;
57    }
58
59    public static class Creator {
60        Creator() { }
61
62        // This is used to create a CImage with an NSImage pointer. It MUST be a CFRetained
63        // NSImage, and the CImage takes ownership of the non-GC retain. If callers need the
64        // NSImage themselves, they MUST call retain on the NSImage themselves.
65        public Image createImageUsingNativeSize(final long image) {
66            if (image == 0) return null;
67            final Dimension2D size = nativeGetNSImageSize(image);
68            return createImage(image, size.getWidth(), size.getHeight());
69        }
70
71        // the width and height passed in as a parameter could differ than the width and the height of the NSImage (image), in that case, the image will be scaled
72        Image createImage(long image, double width, double height) {
73            if (image == 0) throw new Error("Unable to instantiate CImage with null native image reference.");
74            return createImageWithSize(image, width, height);
75        }
76
77        public Image createImageWithSize(final long image, final double width, final double height) {
78            final CImage img = new CImage(image);
79            img.resize(width, height);
80            return img.toImage();
81        }
82
83        // This is used to create a CImage that represents the icon of the given file.
84        public Image createImageOfFile(final String file, final int width, final int height) {
85            return createImage(nativeCreateNSImageOfFileFromLaunchServices(file), width, height);
86        }
87
88        public Image createImageFromFile(final String file, final double width, final double height) {
89            final long image = nativeCreateNSImageFromFileContents(file);
90            nativeSetNSImageSize(image, width, height);
91            return createImage(image, width, height);
92        }
93
94        public Image createSystemImageFromSelector(final String iconSelector, final int width, final int height) {
95            return createImage(nativeCreateNSImageFromIconSelector(getSelectorAsInt(iconSelector)), width, height);
96        }
97
98        public Image createImageFromName(final String name, final int width, final int height) {
99            return createImage(nativeCreateNSImageFromImageName(name), width, height);
100        }
101
102        public Image createImageFromName(final String name) {
103            return createImageUsingNativeSize(nativeCreateNSImageFromImageName(name));
104        }
105
106        private static int[] imageToArray(Image image, boolean prepareImage) {
107            if (image == null) return null;
108
109            if (prepareImage && !(image instanceof BufferedImage)) {
110                final MediaTracker mt = new MediaTracker(new Label());
111                final int id = 0;
112                mt.addImage(image, id);
113
114                try {
115                    mt.waitForID(id);
116                } catch (InterruptedException e) {
117                    return null;
118                }
119
120                if (mt.isErrorID(id)) {
121                    return null;
122                }
123            }
124
125            int w = image.getWidth(null);
126            int h = image.getHeight(null);
127
128            if (w < 0 || h < 0) {
129                return null;
130            }
131
132            BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
133            Graphics2D g2 = bimg.createGraphics();
134            g2.setComposite(AlphaComposite.Src);
135            g2.drawImage(image, 0, 0, null);
136            g2.dispose();
137
138            return ((DataBufferInt)bimg.getRaster().getDataBuffer()).getData();
139        }
140
141        public byte[] getPlatformImageBytes(final Image image) {
142            int[] buffer = imageToArray(image, false);
143
144            if (buffer == null) {
145                return null;
146            }
147
148            return nativeGetPlatformImageBytes(buffer, image.getWidth(null), image.getHeight(null));
149        }
150
151        /**
152         * Translates a byte array which contains platform-specific image data in the given format into an Image.
153         */
154        public Image createImageFromPlatformImageBytes(final byte[] buffer) {
155            return createImageUsingNativeSize(nativeCreateNSImageFromBytes(buffer));
156        }
157
158        // This is used to create a CImage from a Image
159        public CImage createFromImage(final Image image) {
160            return createFromImage(image, true);
161        }
162
163        public CImage createFromImageImmediately(final Image image) {
164            return createFromImage(image, false);
165        }
166
167        // This is used to create a CImage from a Image
168        private CImage createFromImage(final Image image, final boolean prepareImage) {
169            if (image instanceof MultiResolutionImage) {
170                List<Image> resolutionVariants
171                        = ((MultiResolutionImage) image).getResolutionVariants();
172                return createFromImages(resolutionVariants, prepareImage);
173            }
174
175            int[] buffer = imageToArray(image, prepareImage);
176            if (buffer == null) {
177                return null;
178            }
179            return new CImage(nativeCreateNSImageFromArray(buffer, image.getWidth(null), image.getHeight(null)));
180        }
181
182        public CImage createFromImages(final List<Image> images) {
183            return createFromImages(images, true);
184        }
185
186        private CImage createFromImages(final List<Image> images, final boolean prepareImage) {
187            if (images == null || images.isEmpty()) {
188                return null;
189            }
190
191            int num = images.size();
192
193            int[][] buffers = new int[num][];
194            int[] w = new int[num];
195            int[] h = new int[num];
196
197            num = 0;
198
199            for (final Image img : images) {
200                buffers[num] = imageToArray(img, prepareImage);
201                if (buffers[num] == null) {
202                    // Unable to process the image
203                    continue;
204                }
205                w[num] = img.getWidth(null);
206                h[num] = img.getHeight(null);
207                num++;
208            }
209
210            if (num == 0) {
211                return null;
212            }
213
214            return new CImage(nativeCreateNSImageFromArrays(
215                    Arrays.copyOf(buffers, num),
216                    Arrays.copyOf(w, num),
217                    Arrays.copyOf(h, num)));
218        }
219
220        static int getSelectorAsInt(final String fromString) {
221            final byte[] b = fromString.getBytes();
222            final int len = Math.min(b.length, 4);
223            int result = 0;
224            for (int i = 0; i < len; i++) {
225                if (i > 0) result <<= 8;
226                result |= (b[i] & 0xff);
227            }
228            return result;
229        }
230    }
231
232    CImage(long nsImagePtr) {
233        super(nsImagePtr, true);
234    }
235
236    /** @return A MultiResolution image created from nsImagePtr, or null. */
237    private Image toImage() {
238        if (ptr == 0) return null;
239
240        final Dimension2D size = nativeGetNSImageSize(ptr);
241        final int w = (int)size.getWidth();
242        final int h = (int)size.getHeight();
243
244        Dimension2D[] sizes
245                = nativeGetNSImageRepresentationSizes(ptr,
246                        size.getWidth(), size.getHeight());
247
248        return sizes == null || sizes.length < 2 ?
249                new MultiResolutionCachedImage(w, h, (width, height)
250                        -> toImage(w, h, width, height))
251                : new MultiResolutionCachedImage(w, h, sizes, (width, height)
252                        -> toImage(w, h, width, height));
253    }
254
255    private BufferedImage toImage(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
256        final BufferedImage bimg = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_INT_ARGB_PRE);
257        final DataBufferInt dbi = (DataBufferInt)bimg.getRaster().getDataBuffer();
258        final int[] buffer = SunWritableRaster.stealData(dbi, 0);
259        nativeCopyNSImageIntoArray(ptr, buffer, srcWidth, srcHeight, dstWidth, dstHeight);
260        SunWritableRaster.markDirty(dbi);
261        return bimg;
262    }
263
264    /** If nsImagePtr != 0 then scale this NSImage. @return *this* */
265    CImage resize(final double w, final double h) {
266        if (ptr != 0) nativeSetNSImageSize(ptr, w, h);
267        return this;
268    }
269
270    void resizeRepresentations(double w, double h) {
271        if (ptr != 0) nativeResizeNSImageRepresentations(ptr, w, h);
272    }
273}
274