CImage.java revision 17083:73e2d15f0145
1/*
2 * Copyright (c) 2011, 2016, 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 java.awt.image.MultiResolutionImage;
35import java.util.concurrent.atomic.AtomicReference;
36
37import sun.awt.image.MultiResolutionCachedImage;
38
39import sun.awt.image.SunWritableRaster;
40
41public class CImage extends CFRetainedResource {
42    private static native long nativeCreateNSImageFromArray(int[] buffer, int w, int h);
43    private static native long nativeCreateNSImageFromBytes(byte[] buffer);
44    private static native long nativeCreateNSImageFromArrays(int[][] buffers, int w[], int h[]);
45    private static native long nativeCreateNSImageFromFileContents(String file);
46    private static native long nativeCreateNSImageOfFileFromLaunchServices(String file);
47    private static native long nativeCreateNSImageFromImageName(String name);
48    private static native long nativeCreateNSImageFromIconSelector(int selector);
49    private static native byte[] nativeGetPlatformImageBytes(int[] buffer, int w, int h);
50    private static native void nativeCopyNSImageIntoArray(long image, int[] buffer, int sw, int sh, int dw, int dh);
51    private static native Dimension2D nativeGetNSImageSize(long image);
52    private static native void nativeSetNSImageSize(long image, double w, double h);
53    private static native void nativeResizeNSImageRepresentations(long image, double w, double h);
54    private static native Dimension2D[] nativeGetNSImageRepresentationSizes(long image, double w, double h);
55
56    static Creator creator = new Creator();
57    static Creator getCreator() {
58        return creator;
59    }
60
61    // This is used to create a CImage that represents the icon of the given file.
62    public static Image createImageOfFile(String file, int width, int height) {
63        return getCreator().createImageOfFile(file, width, height);
64    }
65
66    public static Image createSystemImageFromSelector(String iconSelector,
67            int width, int height) {
68        return getCreator().createSystemImageFromSelector(iconSelector, width, height);
69    }
70
71    public static Image createImageFromFile(String file, double width, double height) {
72        return getCreator().createImageFromFile(file, width, height);
73    }
74
75    // This is used to create a CImage from a Image
76    public static CImage createFromImage(final Image image) {
77        return getCreator().createFromImage(image);
78    }
79
80    public static class Creator {
81        Creator() { }
82
83        // This is used to create a CImage with an NSImage pointer. It MUST be a CFRetained
84        // NSImage, and the CImage takes ownership of the non-GC retain. If callers need the
85        // NSImage themselves, they MUST call retain on the NSImage themselves.
86        public Image createImageUsingNativeSize(final long image) {
87            if (image == 0) return null;
88            final Dimension2D size = nativeGetNSImageSize(image);
89            return createImage(image, size.getWidth(), size.getHeight());
90        }
91
92        // 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
93        Image createImage(long image, double width, double height) {
94            if (image == 0) throw new Error("Unable to instantiate CImage with null native image reference.");
95            return createImageWithSize(image, width, height);
96        }
97
98        public Image createImageWithSize(final long image, final double width, final double height) {
99            final CImage img = new CImage(image);
100            img.resize(width, height);
101            return img.toImage();
102        }
103
104        // This is used to create a CImage that represents the icon of the given file.
105        public Image createImageOfFile(final String file, final int width, final int height) {
106            return createImage(nativeCreateNSImageOfFileFromLaunchServices(file), width, height);
107        }
108
109        public Image createImageFromFile(final String file, final double width, final double height) {
110            final long image = nativeCreateNSImageFromFileContents(file);
111            nativeSetNSImageSize(image, width, height);
112            return createImage(image, width, height);
113        }
114
115        public Image createSystemImageFromSelector(final String iconSelector, final int width, final int height) {
116            return createImage(nativeCreateNSImageFromIconSelector(getSelectorAsInt(iconSelector)), width, height);
117        }
118
119        public Image createImageFromName(final String name, final int width, final int height) {
120            return createImage(nativeCreateNSImageFromImageName(name), width, height);
121        }
122
123        public Image createImageFromName(final String name) {
124            return createImageUsingNativeSize(nativeCreateNSImageFromImageName(name));
125        }
126
127        private static int[] imageToArray(Image image, boolean prepareImage) {
128            if (image == null) return null;
129
130            if (prepareImage && !(image instanceof BufferedImage)) {
131                final MediaTracker mt = new MediaTracker(new Label());
132                final int id = 0;
133                mt.addImage(image, id);
134
135                try {
136                    mt.waitForID(id);
137                } catch (InterruptedException e) {
138                    return null;
139                }
140
141                if (mt.isErrorID(id)) {
142                    return null;
143                }
144            }
145
146            int w = image.getWidth(null);
147            int h = image.getHeight(null);
148
149            if (w < 0 || h < 0) {
150                return null;
151            }
152
153            BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
154            Graphics2D g2 = bimg.createGraphics();
155            g2.setComposite(AlphaComposite.Src);
156            g2.drawImage(image, 0, 0, null);
157            g2.dispose();
158
159            return ((DataBufferInt)bimg.getRaster().getDataBuffer()).getData();
160        }
161
162        public byte[] getPlatformImageBytes(final Image image) {
163            int[] buffer = imageToArray(image, false);
164
165            if (buffer == null) {
166                return null;
167            }
168
169            return nativeGetPlatformImageBytes(buffer, image.getWidth(null), image.getHeight(null));
170        }
171
172        /**
173         * Translates a byte array which contains platform-specific image data in the given format into an Image.
174         */
175        public Image createImageFromPlatformImageBytes(final byte[] buffer) {
176            return createImageUsingNativeSize(nativeCreateNSImageFromBytes(buffer));
177        }
178
179        // This is used to create a CImage from a Image
180        public CImage createFromImage(final Image image) {
181            return createFromImage(image, true);
182        }
183
184        public CImage createFromImageImmediately(final Image image) {
185            return createFromImage(image, false);
186        }
187
188        // This is used to create a CImage from a Image
189        private CImage createFromImage(final Image image, final boolean prepareImage) {
190            if (image instanceof MultiResolutionImage) {
191                List<Image> resolutionVariants
192                        = ((MultiResolutionImage) image).getResolutionVariants();
193                return createFromImages(resolutionVariants, prepareImage);
194            }
195
196            int[] buffer = imageToArray(image, prepareImage);
197            if (buffer == null) {
198                return null;
199            }
200            return new CImage(nativeCreateNSImageFromArray(buffer, image.getWidth(null), image.getHeight(null)));
201        }
202
203        public CImage createFromImages(final List<Image> images) {
204            return createFromImages(images, true);
205        }
206
207        private CImage createFromImages(final List<Image> images, final boolean prepareImage) {
208            if (images == null || images.isEmpty()) {
209                return null;
210            }
211
212            int num = images.size();
213
214            int[][] buffers = new int[num][];
215            int[] w = new int[num];
216            int[] h = new int[num];
217
218            num = 0;
219
220            for (final Image img : images) {
221                buffers[num] = imageToArray(img, prepareImage);
222                if (buffers[num] == null) {
223                    // Unable to process the image
224                    continue;
225                }
226                w[num] = img.getWidth(null);
227                h[num] = img.getHeight(null);
228                num++;
229            }
230
231            if (num == 0) {
232                return null;
233            }
234
235            return new CImage(nativeCreateNSImageFromArrays(
236                    Arrays.copyOf(buffers, num),
237                    Arrays.copyOf(w, num),
238                    Arrays.copyOf(h, num)));
239        }
240
241        static int getSelectorAsInt(final String fromString) {
242            final byte[] b = fromString.getBytes();
243            final int len = Math.min(b.length, 4);
244            int result = 0;
245            for (int i = 0; i < len; i++) {
246                if (i > 0) result <<= 8;
247                result |= (b[i] & 0xff);
248            }
249            return result;
250        }
251    }
252
253    CImage(long nsImagePtr) {
254        super(nsImagePtr, true);
255    }
256
257    /** @return A MultiResolution image created from nsImagePtr, or null. */
258    private Image toImage() {
259        if (ptr == 0) {
260            return null;
261        }
262
263        AtomicReference<Dimension2D> sizeRef = new AtomicReference<>();
264        execute(ptr -> {
265            sizeRef.set(nativeGetNSImageSize(ptr));
266        });
267        final Dimension2D size = sizeRef.get();
268        if (size == null) {
269            return null;
270        }
271        final int w = (int)size.getWidth();
272        final int h = (int)size.getHeight();
273        AtomicReference<Dimension2D[]> repRef = new AtomicReference<>();
274        execute(ptr -> {
275            repRef.set(nativeGetNSImageRepresentationSizes(ptr, size.getWidth(),
276                                                           size.getHeight()));
277        });
278        Dimension2D[] sizes = repRef.get();
279
280        return sizes == null || sizes.length < 2 ?
281                new MultiResolutionCachedImage(w, h, (width, height)
282                        -> toImage(w, h, width, height))
283                : new MultiResolutionCachedImage(w, h, sizes, (width, height)
284                        -> toImage(w, h, width, height));
285    }
286
287    private BufferedImage toImage(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
288        final BufferedImage bimg = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_INT_ARGB_PRE);
289        final DataBufferInt dbi = (DataBufferInt)bimg.getRaster().getDataBuffer();
290        final int[] buffer = SunWritableRaster.stealData(dbi, 0);
291        execute(ptr->nativeCopyNSImageIntoArray(ptr, buffer, srcWidth, srcHeight, dstWidth, dstHeight));
292        SunWritableRaster.markDirty(dbi);
293        return bimg;
294    }
295
296    /** If nsImagePtr != 0 then scale this NSImage. @return *this* */
297    CImage resize(final double w, final double h) {
298        execute(ptr -> nativeSetNSImageSize(ptr, w, h));
299        return this;
300    }
301
302    void resizeRepresentations(double w, double h) {
303        execute(ptr -> nativeResizeNSImageRepresentations(ptr, w, h));
304    }
305}
306