CPlatformWindow.java revision 14322:6cc7fef92fcf
1193323Sed/*
2193323Sed * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
3193323Sed * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4193323Sed *
5193323Sed * This code is free software; you can redistribute it and/or modify it
6193323Sed * under the terms of the GNU General Public License version 2 only, as
7193323Sed * published by the Free Software Foundation.  Oracle designates this
8193323Sed * particular file as subject to the "Classpath" exception as provided
9193323Sed * by Oracle in the LICENSE file that accompanied this code.
10193323Sed *
11193323Sed * This code is distributed in the hope that it will be useful, but WITHOUT
12193323Sed * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13193323Sed * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14193323Sed * version 2 for more details (a copy is included in the LICENSE file that
15193323Sed * accompanied this code).
16193323Sed *
17193323Sed * You should have received a copy of the GNU General Public License version
18193323Sed * 2 along with this work; if not, write to the Free Software Foundation,
19193323Sed * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20193323Sed *
21193323Sed * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22193323Sed * or visit www.oracle.com if you need additional information or have any
23193323Sed * questions.
24193323Sed */
25193323Sed
26193323Sedpackage sun.lwawt.macosx;
27193323Sed
28193323Sedimport java.awt.*;
29193323Sedimport java.awt.Dialog.ModalityType;
30193323Sedimport java.awt.event.*;
31193323Sedimport java.awt.peer.WindowPeer;
32193323Sedimport java.beans.*;
33193323Sedimport java.lang.reflect.InvocationTargetException;
34193323Sed
35193323Sedimport javax.swing.*;
36193323Sed
37193323Sedimport sun.awt.*;
38193323Sedimport sun.awt.AWTAccessor.ComponentAccessor;
39193323Sedimport sun.java2d.SurfaceData;
40234353Sdimimport sun.java2d.opengl.CGLSurfaceData;
41193323Sedimport sun.lwawt.*;
42193323Sedimport sun.util.logging.PlatformLogger;
43193323Sed
44193323Sedimport com.apple.laf.*;
45193323Sedimport com.apple.laf.ClientPropertyApplicator.Property;
46193323Sedimport com.sun.awt.AWTUtilities;
47193323Sed
48193323Sedpublic class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
49193323Sed    private native long nativeCreateNSWindow(long nsViewPtr,long ownerPtr, long styleBits, double x, double y, double w, double h);
50193323Sed    private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
51193323Sed    private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
52193323Sed    private static native Insets nativeGetNSWindowInsets(long nsWindowPtr);
53193323Sed    private static native void nativeSetNSWindowBounds(long nsWindowPtr, double x, double y, double w, double h);
54193323Sed    private static native void nativeSetNSWindowStandardFrame(long nsWindowPtr,
55193323Sed            double x, double y, double w, double h);
56193323Sed    private static native void nativeSetNSWindowMinMax(long nsWindowPtr, double minW, double minH, double maxW, double maxH);
57193323Sed    private static native void nativePushNSWindowToBack(long nsWindowPtr);
58193323Sed    private static native void nativePushNSWindowToFront(long nsWindowPtr);
59193323Sed    private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
60193323Sed    private static native void nativeRevalidateNSWindowShadow(long nsWindowPtr);
61193323Sed    private static native void nativeSetNSWindowMinimizedIcon(long nsWindowPtr, long nsImage);
62193323Sed    private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
63193323Sed    private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
64193323Sed    private static native void nativeSynthesizeMouseEnteredExitedEvents();
65193323Sed    private static native void nativeDispose(long nsWindowPtr);
66193323Sed    private static native void nativeEnterFullScreenMode(long nsWindowPtr);
67193323Sed    private static native void nativeExitFullScreenMode(long nsWindowPtr);
68239462Sdim    static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
69239462Sdim
70239462Sdim    // Loger to report issues happened during execution but that do not affect functionality
71239462Sdim    private static final PlatformLogger logger = PlatformLogger.getLogger("sun.lwawt.macosx.CPlatformWindow");
72239462Sdim    private static final PlatformLogger focusLogger = PlatformLogger.getLogger("sun.lwawt.macosx.focus.CPlatformWindow");
73239462Sdim
74239462Sdim    // for client properties
75239462Sdim    public static final String WINDOW_BRUSH_METAL_LOOK = "apple.awt.brushMetalLook";
76193323Sed    public static final String WINDOW_DRAGGABLE_BACKGROUND = "apple.awt.draggableWindowBackground";
77193323Sed
78193323Sed    public static final String WINDOW_ALPHA = "Window.alpha";
79193323Sed    public static final String WINDOW_SHADOW = "Window.shadow";
80193323Sed
81193323Sed    public static final String WINDOW_STYLE = "Window.style";
82193323Sed    public static final String WINDOW_SHADOW_REVALIDATE_NOW = "apple.awt.windowShadow.revalidateNow";
83193323Sed
84193323Sed    public static final String WINDOW_DOCUMENT_MODIFIED = "Window.documentModified";
85193323Sed    public static final String WINDOW_DOCUMENT_FILE = "Window.documentFile";
86193323Sed
87193323Sed    public static final String WINDOW_CLOSEABLE = "Window.closeable";
88193323Sed    public static final String WINDOW_MINIMIZABLE = "Window.minimizable";
89193323Sed    public static final String WINDOW_ZOOMABLE = "Window.zoomable";
90193323Sed    public static final String WINDOW_HIDES_ON_DEACTIVATE="Window.hidesOnDeactivate";
91193323Sed
92193323Sed    public static final String WINDOW_DOC_MODAL_SHEET = "apple.awt.documentModalSheet";
93234353Sdim    public static final String WINDOW_FADE_DELEGATE = "apple.awt._windowFadeDelegate";
94234353Sdim    public static final String WINDOW_FADE_IN = "apple.awt._windowFadeIn";
95234353Sdim    public static final String WINDOW_FADE_OUT = "apple.awt._windowFadeOut";
96193323Sed    public static final String WINDOW_FULLSCREENABLE = "apple.awt.fullscreenable";
97193323Sed
98193323Sed
99193323Sed    // Yeah, I know. But it's easier to deal with ints from JNI
100193323Sed    static final int MODELESS = 0;
101193323Sed    static final int DOCUMENT_MODAL = 1;
102193323Sed    static final int APPLICATION_MODAL = 2;
103193323Sed    static final int TOOLKIT_MODAL = 3;
104193323Sed
105193323Sed    // window style bits
106193323Sed    static final int _RESERVED_FOR_DATA = 1 << 0;
107193323Sed
108193323Sed    // corresponds to native style mask bits
109193323Sed    static final int DECORATED = 1 << 1;
110193323Sed    static final int TEXTURED = 1 << 2;
111193323Sed    static final int UNIFIED = 1 << 3;
112193323Sed    static final int UTILITY = 1 << 4;
113193323Sed    static final int HUD = 1 << 5;
114193323Sed    static final int SHEET = 1 << 6;
115193323Sed
116193323Sed    static final int CLOSEABLE = 1 << 7;
117234353Sdim    static final int MINIMIZABLE = 1 << 8;
118234353Sdim
119234353Sdim    static final int RESIZABLE = 1 << 9; // both a style bit and prop bit
120234353Sdim    static final int NONACTIVATING = 1 << 24;
121234353Sdim    static final int IS_DIALOG = 1 << 25;
122193323Sed    static final int IS_MODAL = 1 << 26;
123193323Sed    static final int IS_POPUP = 1 << 27;
124193323Sed
125193323Sed    static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE;
126193323Sed
127193323Sed    // corresponds to method-based properties
128193323Sed    static final int HAS_SHADOW = 1 << 10;
129193323Sed    static final int ZOOMABLE = 1 << 11;
130193323Sed
131193323Sed    static final int ALWAYS_ON_TOP = 1 << 15;
132193323Sed    static final int HIDES_ON_DEACTIVATE = 1 << 17;
133193323Sed    static final int DRAGGABLE_BACKGROUND = 1 << 19;
134193323Sed    static final int DOCUMENT_MODIFIED = 1 << 21;
135193323Sed    static final int FULLSCREENABLE = 1 << 23;
136193323Sed
137193323Sed    static final int _METHOD_PROP_BITMASK = RESIZABLE | HAS_SHADOW | ZOOMABLE | ALWAYS_ON_TOP | HIDES_ON_DEACTIVATE | DRAGGABLE_BACKGROUND | DOCUMENT_MODIFIED | FULLSCREENABLE;
138193323Sed
139193323Sed    // corresponds to callback-based properties
140193323Sed    static final int SHOULD_BECOME_KEY = 1 << 12;
141193323Sed    static final int SHOULD_BECOME_MAIN = 1 << 13;
142193323Sed    static final int MODAL_EXCLUDED = 1 << 16;
143193323Sed
144193323Sed    static final int _CALLBACK_PROP_BITMASK = SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN | MODAL_EXCLUDED;
145193323Sed
146193323Sed    static int SET(final int bits, final int mask, final boolean value) {
147193323Sed        if (value) return (bits | mask);
148234353Sdim        return bits & ~mask;
149193323Sed    }
150193323Sed
151193323Sed    static boolean IS(final int bits, final int mask) {
152193323Sed        return (bits & mask) != 0;
153193323Sed    }
154
155    @SuppressWarnings({"unchecked", "rawtypes"})
156    static ClientPropertyApplicator<JRootPane, CPlatformWindow> CLIENT_PROPERTY_APPLICATOR = new ClientPropertyApplicator<JRootPane, CPlatformWindow>(new Property[] {
157        new Property<CPlatformWindow>(WINDOW_DOCUMENT_MODIFIED) { public void applyProperty(final CPlatformWindow c, final Object value) {
158            c.setStyleBits(DOCUMENT_MODIFIED, value == null ? false : Boolean.parseBoolean(value.toString()));
159        }},
160        new Property<CPlatformWindow>(WINDOW_BRUSH_METAL_LOOK) { public void applyProperty(final CPlatformWindow c, final Object value) {
161            c.setStyleBits(TEXTURED, Boolean.parseBoolean(value.toString()));
162        }},
163        new Property<CPlatformWindow>(WINDOW_ALPHA) { public void applyProperty(final CPlatformWindow c, final Object value) {
164            AWTUtilities.setWindowOpacity(c.target, value == null ? 1.0f : Float.parseFloat(value.toString()));
165        }},
166        new Property<CPlatformWindow>(WINDOW_SHADOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
167            c.setStyleBits(HAS_SHADOW, value == null ? true : Boolean.parseBoolean(value.toString()));
168        }},
169        new Property<CPlatformWindow>(WINDOW_MINIMIZABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
170            c.setStyleBits(MINIMIZABLE, Boolean.parseBoolean(value.toString()));
171        }},
172        new Property<CPlatformWindow>(WINDOW_CLOSEABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
173            c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString()));
174        }},
175        new Property<CPlatformWindow>(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
176            c.setStyleBits(ZOOMABLE, Boolean.parseBoolean(value.toString()));
177        }},
178        new Property<CPlatformWindow>(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
179            c.setStyleBits(FULLSCREENABLE, Boolean.parseBoolean(value.toString()));
180        }},
181        new Property<CPlatformWindow>(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
182            nativeRevalidateNSWindowShadow(c.getNSWindowPtr());
183        }},
184        new Property<CPlatformWindow>(WINDOW_DOCUMENT_FILE) { public void applyProperty(final CPlatformWindow c, final Object value) {
185            if (value == null || !(value instanceof java.io.File)) {
186                nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), null);
187                return;
188            }
189
190            final String filename = ((java.io.File)value).getAbsolutePath();
191            nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), filename);
192        }}
193    }) {
194        @SuppressWarnings("deprecation")
195        public CPlatformWindow convertJComponentToTarget(final JRootPane p) {
196            Component root = SwingUtilities.getRoot(p);
197            final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
198            if (root == null || acc.getPeer(root) == null) return null;
199            return (CPlatformWindow)((LWWindowPeer)acc.getPeer(root)).getPlatformWindow();
200        }
201    };
202
203    // Bounds of the native widget but in the Java coordinate system.
204    // In order to keep it up-to-date we will update them on
205    // 1) setting native bounds via nativeSetBounds() call
206    // 2) getting notification from the native level via deliverMoveResizeEvent()
207    private Rectangle nativeBounds = new Rectangle(0, 0, 0, 0);
208    private volatile boolean isFullScreenMode;
209    private boolean isFullScreenAnimationOn;
210
211    private Window target;
212    private LWWindowPeer peer;
213    protected CPlatformView contentView;
214    protected CPlatformWindow owner;
215    protected boolean visible = false; // visibility status from native perspective
216    private boolean undecorated; // initialized in getInitialStyleBits()
217    private Rectangle normalBounds = null; // not-null only for undecorated maximized windows
218    private CPlatformResponder responder;
219
220    public CPlatformWindow() {
221        super(0, true);
222    }
223
224    /*
225     * Delegate initialization (create native window and all the
226     * related resources).
227     */
228    @Override // PlatformWindow
229    public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
230        initializeBase(_target, _peer, _owner, new CPlatformView());
231
232        final int styleBits = getInitialStyleBits();
233
234        responder = createPlatformResponder();
235        contentView = createContentView();
236        contentView.initialize(peer, responder);
237
238        final long ownerPtr = owner != null ? owner.getNSWindowPtr() : 0L;
239        Rectangle bounds;
240        if (!IS(DECORATED, styleBits)) {
241            // For undecorated frames the move/resize event does not come if the frame is centered on the screen
242            // so we need to set a stub location to force an initial move/resize. Real bounds would be set later.
243            bounds = new Rectangle(0, 0, 1, 1);
244        } else {
245            bounds = _peer.constrainBounds(_target.getBounds());
246        }
247        final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(),
248                ownerPtr, styleBits, bounds.x, bounds.y, bounds.width, bounds.height);
249        setPtr(nativeWindowPtr);
250
251        if (target instanceof javax.swing.RootPaneContainer) {
252            final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
253            if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
254                public void propertyChange(final PropertyChangeEvent evt) {
255                    CLIENT_PROPERTY_APPLICATOR.attachAndApplyClientProperties(rootpane);
256                    rootpane.removePropertyChangeListener("ancestor", this);
257                }
258            });
259        }
260
261        validateSurface();
262    }
263
264    protected void initializeBase(Window target, LWWindowPeer peer, PlatformWindow owner, CPlatformView view) {
265        this.peer = peer;
266        this.target = target;
267        if (owner instanceof CPlatformWindow) {
268            this.owner = (CPlatformWindow)owner;
269        }
270        this.contentView = view;
271    }
272
273    protected CPlatformResponder createPlatformResponder() {
274        return new CPlatformResponder(peer, false);
275    }
276
277    protected CPlatformView createContentView() {
278        return new CPlatformView();
279    }
280
281    protected int getInitialStyleBits() {
282        // defaults style bits
283        int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
284
285        if (isNativelyFocusableWindow()) {
286            styleBits = SET(styleBits, SHOULD_BECOME_KEY, true);
287            styleBits = SET(styleBits, SHOULD_BECOME_MAIN, true);
288        }
289
290        final boolean isFrame = (target instanceof Frame);
291        final boolean isDialog = (target instanceof Dialog);
292        final boolean isPopup = (target.getType() == Window.Type.POPUP);
293        if (isDialog) {
294            styleBits = SET(styleBits, MINIMIZABLE, false);
295        }
296
297        // Either java.awt.Frame or java.awt.Dialog can be undecorated, however java.awt.Window always is undecorated.
298        {
299            this.undecorated = isFrame ? ((Frame)target).isUndecorated() : (isDialog ? ((Dialog)target).isUndecorated() : true);
300            if (this.undecorated) styleBits = SET(styleBits, DECORATED, false);
301        }
302
303        // Either java.awt.Frame or java.awt.Dialog can be resizable, however java.awt.Window is never resizable
304        {
305            final boolean resizable = isFrame ? ((Frame)target).isResizable() : (isDialog ? ((Dialog)target).isResizable() : false);
306            styleBits = SET(styleBits, RESIZABLE, resizable);
307            if (!resizable) {
308                styleBits = SET(styleBits, ZOOMABLE, false);
309            }
310        }
311
312        if (target.isAlwaysOnTop()) {
313            styleBits = SET(styleBits, ALWAYS_ON_TOP, true);
314        }
315
316        if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
317            styleBits = SET(styleBits, MODAL_EXCLUDED, true);
318        }
319
320        // If the target is a dialog, popup or tooltip we want it to ignore the brushed metal look.
321        if (isPopup) {
322            styleBits = SET(styleBits, TEXTURED, false);
323            // Popups in applets don't activate applet's process
324            styleBits = SET(styleBits, NONACTIVATING, true);
325            styleBits = SET(styleBits, IS_POPUP, true);
326        }
327
328        if (Window.Type.UTILITY.equals(target.getType())) {
329            styleBits = SET(styleBits, UTILITY, true);
330        }
331
332        if (target instanceof javax.swing.RootPaneContainer) {
333            javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
334            Object prop = null;
335
336            prop = rootpane.getClientProperty(WINDOW_BRUSH_METAL_LOOK);
337            if (prop != null) {
338                styleBits = SET(styleBits, TEXTURED, Boolean.parseBoolean(prop.toString()));
339            }
340
341            if (isDialog && ((Dialog)target).getModalityType() == ModalityType.DOCUMENT_MODAL) {
342                prop = rootpane.getClientProperty(WINDOW_DOC_MODAL_SHEET);
343                if (prop != null) {
344                    styleBits = SET(styleBits, SHEET, Boolean.parseBoolean(prop.toString()));
345                }
346            }
347
348            prop = rootpane.getClientProperty(WINDOW_STYLE);
349            if (prop != null) {
350                if ("small".equals(prop))  {
351                    styleBits = SET(styleBits, UTILITY, true);
352                    if (target.isAlwaysOnTop() && rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE) == null) {
353                        styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, true);
354                    }
355                }
356                if ("textured".equals(prop)) styleBits = SET(styleBits, TEXTURED, true);
357                if ("unified".equals(prop)) styleBits = SET(styleBits, UNIFIED, true);
358                if ("hud".equals(prop)) styleBits = SET(styleBits, HUD, true);
359            }
360
361            prop = rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE);
362            if (prop != null) {
363                styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, Boolean.parseBoolean(prop.toString()));
364            }
365
366            prop = rootpane.getClientProperty(WINDOW_CLOSEABLE);
367            if (prop != null) {
368                styleBits = SET(styleBits, CLOSEABLE, Boolean.parseBoolean(prop.toString()));
369            }
370
371            prop = rootpane.getClientProperty(WINDOW_MINIMIZABLE);
372            if (prop != null) {
373                styleBits = SET(styleBits, MINIMIZABLE, Boolean.parseBoolean(prop.toString()));
374            }
375
376            prop = rootpane.getClientProperty(WINDOW_ZOOMABLE);
377            if (prop != null) {
378                styleBits = SET(styleBits, ZOOMABLE, Boolean.parseBoolean(prop.toString()));
379            }
380
381            prop = rootpane.getClientProperty(WINDOW_FULLSCREENABLE);
382            if (prop != null) {
383                styleBits = SET(styleBits, FULLSCREENABLE, Boolean.parseBoolean(prop.toString()));
384            }
385
386            prop = rootpane.getClientProperty(WINDOW_SHADOW);
387            if (prop != null) {
388                styleBits = SET(styleBits, HAS_SHADOW, Boolean.parseBoolean(prop.toString()));
389            }
390
391            prop = rootpane.getClientProperty(WINDOW_DRAGGABLE_BACKGROUND);
392            if (prop != null) {
393                styleBits = SET(styleBits, DRAGGABLE_BACKGROUND, Boolean.parseBoolean(prop.toString()));
394            }
395        }
396
397        if (isDialog) {
398            styleBits = SET(styleBits, IS_DIALOG, true);
399            if (((Dialog) target).isModal()) {
400                styleBits = SET(styleBits, IS_MODAL, true);
401            }
402        }
403
404        peer.setTextured(IS(TEXTURED, styleBits));
405
406        return styleBits;
407    }
408
409    // this is the counter-point to -[CWindow _nativeSetStyleBit:]
410    private void setStyleBits(final int mask, final boolean value) {
411        nativeSetNSWindowStyleBits(getNSWindowPtr(), mask, value ? mask : 0);
412    }
413
414    private native void _toggleFullScreenMode(final long model);
415
416    public void toggleFullScreen() {
417        _toggleFullScreenMode(getNSWindowPtr());
418    }
419
420    @Override // PlatformWindow
421    public void setMenuBar(MenuBar mb) {
422        final long nsWindowPtr = getNSWindowPtr();
423        CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
424        if (mbPeer != null) {
425            nativeSetNSWindowMenuBar(nsWindowPtr, mbPeer.getModel());
426        } else {
427            nativeSetNSWindowMenuBar(nsWindowPtr, 0);
428        }
429    }
430
431    @Override // PlatformWindow
432    public void dispose() {
433        if (owner != null) {
434            CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
435        }
436        contentView.dispose();
437        nativeDispose(getNSWindowPtr());
438        CPlatformWindow.super.dispose();
439    }
440
441    @Override // PlatformWindow
442    public FontMetrics getFontMetrics(Font f) {
443        // TODO: not implemented
444        (new RuntimeException("unimplemented")).printStackTrace();
445        return null;
446    }
447
448    @Override // PlatformWindow
449    public Insets getInsets() {
450        return nativeGetNSWindowInsets(getNSWindowPtr());
451    }
452
453    @Override // PlatformWindow
454    public Point getLocationOnScreen() {
455        return new Point(nativeBounds.x, nativeBounds.y);
456    }
457
458    @Override
459    public GraphicsDevice getGraphicsDevice() {
460        return contentView.getGraphicsDevice();
461    }
462
463    @Override // PlatformWindow
464    public SurfaceData getScreenSurface() {
465        // TODO: not implemented
466        return null;
467    }
468
469    @Override // PlatformWindow
470    public SurfaceData replaceSurfaceData() {
471        return contentView.replaceSurfaceData();
472    }
473
474    @Override // PlatformWindow
475    public void setBounds(int x, int y, int w, int h) {
476        nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
477    }
478
479    public void setMaximizedBounds(int x, int y, int w, int h) {
480        nativeSetNSWindowStandardFrame(getNSWindowPtr(), x, y, w, h);
481    }
482
483    private boolean isMaximized() {
484        return undecorated ? this.normalBounds != null
485                : CWrapper.NSWindow.isZoomed(getNSWindowPtr());
486    }
487
488    private void maximize() {
489        if (peer == null || isMaximized()) {
490            return;
491        }
492        if (!undecorated) {
493            CWrapper.NSWindow.zoom(getNSWindowPtr());
494        } else {
495            deliverZoom(true);
496
497            // We need an up to date size of the peer, so we flush the native events
498            // to be sure that there are no setBounds requests in the queue.
499            LWCToolkit.flushNativeSelectors();
500            this.normalBounds = peer.getBounds();
501            Rectangle maximizedBounds = peer.getMaximizedBounds();
502            setBounds(maximizedBounds.x, maximizedBounds.y,
503                    maximizedBounds.width, maximizedBounds.height);
504        }
505    }
506
507    private void unmaximize() {
508        if (!isMaximized()) {
509            return;
510        }
511        if (!undecorated) {
512            CWrapper.NSWindow.zoom(getNSWindowPtr());
513        } else {
514            deliverZoom(false);
515
516            Rectangle toBounds = this.normalBounds;
517            this.normalBounds = null;
518            setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
519        }
520    }
521
522    public boolean isVisible() {
523        return this.visible;
524    }
525
526    @Override // PlatformWindow
527    public void setVisible(boolean visible) {
528        final long nsWindowPtr = getNSWindowPtr();
529
530        // Process parent-child relationship when hiding
531        final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
532        if (!visible) {
533            // Unparent my children
534            for (Window w : target.getOwnedWindows()) {
535                WindowPeer p = acc.getPeer(w);
536                if (p instanceof LWWindowPeer) {
537                    CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
538                    if (pw != null && pw.isVisible()) {
539                        CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
540                    }
541                }
542            }
543
544            // Unparent myself
545            if (owner != null && owner.isVisible()) {
546                CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
547            }
548        }
549
550        // Configure stuff
551        updateIconImages();
552        updateFocusabilityForAutoRequestFocus(false);
553
554        boolean wasMaximized = isMaximized();
555
556        // Actually show or hide the window
557        LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
558        if (blocker == null || !visible) {
559            // If it ain't blocked, or is being hidden, go regular way
560            if (visible) {
561                CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
562
563                boolean isPopup = (target.getType() == Window.Type.POPUP);
564                if (isPopup) {
565                    // Popups in applets don't activate applet's process
566                    CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
567                } else {
568                    CWrapper.NSWindow.orderFront(nsWindowPtr);
569                }
570
571                boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
572                if (!isKeyWindow) {
573                    CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
574                }
575            } else {
576                // immediately hide the window
577                CWrapper.NSWindow.orderOut(nsWindowPtr);
578                // process the close
579                CWrapper.NSWindow.close(nsWindowPtr);
580            }
581        } else {
582            // otherwise, put it in a proper z-order
583            CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
584                    ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
585        }
586        this.visible = visible;
587
588        // Manage the extended state when showing
589        if (visible) {
590            // Apply the extended state as expected in shared code
591            if (target instanceof Frame) {
592                if (!wasMaximized && isMaximized()) {
593                    // setVisible could have changed the native maximized state
594                    deliverZoom(true);
595                } else {
596                    int frameState = ((Frame)target).getExtendedState();
597                    if ((frameState & Frame.ICONIFIED) != 0) {
598                        // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
599                        frameState = Frame.ICONIFIED;
600                    }
601                    switch (frameState) {
602                        case Frame.ICONIFIED:
603                            CWrapper.NSWindow.miniaturize(nsWindowPtr);
604                            break;
605                        case Frame.MAXIMIZED_BOTH:
606                            maximize();
607                            break;
608                        default: // NORMAL
609                            unmaximize(); // in case it was maximized, otherwise this is a no-op
610                            break;
611                    }
612                }
613            }
614        }
615
616        nativeSynthesizeMouseEnteredExitedEvents();
617
618        // Configure stuff #2
619        updateFocusabilityForAutoRequestFocus(true);
620
621        // Manage parent-child relationship when showing
622        if (visible) {
623            // Add myself as a child
624            if (owner != null && owner.isVisible()) {
625                CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
626                applyWindowLevel(target);
627            }
628
629            // Add my own children to myself
630            for (Window w : target.getOwnedWindows()) {
631                final Object p = acc.getPeer(w);
632                if (p instanceof LWWindowPeer) {
633                    CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
634                    if (pw != null && pw.isVisible()) {
635                        CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
636                        pw.applyWindowLevel(w);
637                    }
638                }
639            }
640        }
641
642        // Deal with the blocker of the window being shown
643        if (blocker != null && visible) {
644            // Make sure the blocker is above its siblings
645            ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
646        }
647    }
648
649    @Override // PlatformWindow
650    public void setTitle(String title) {
651        nativeSetNSWindowTitle(getNSWindowPtr(), title);
652    }
653
654    // Should be called on every window key property change.
655    @Override // PlatformWindow
656    public void updateIconImages() {
657        final long nsWindowPtr = getNSWindowPtr();
658        final CImage cImage = getImageForTarget();
659        nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
660    }
661
662    public long getNSWindowPtr() {
663        final long nsWindowPtr = ptr;
664        if (nsWindowPtr == 0L) {
665            if(logger.isLoggable(PlatformLogger.Level.FINE)) {
666                logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
667            }
668        }
669        return nsWindowPtr;
670    }
671
672    public SurfaceData getSurfaceData() {
673        return contentView.getSurfaceData();
674    }
675
676    @Override  // PlatformWindow
677    public void toBack() {
678        final long nsWindowPtr = getNSWindowPtr();
679        nativePushNSWindowToBack(nsWindowPtr);
680    }
681
682    @Override  // PlatformWindow
683    public void toFront() {
684        final long nsWindowPtr = getNSWindowPtr();
685        LWCToolkit lwcToolkit = (LWCToolkit) Toolkit.getDefaultToolkit();
686        Window w = DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
687        final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
688        if( w != null && acc.getPeer(w) != null
689                && ((LWWindowPeer)acc.getPeer(w)).getPeerType() == LWWindowPeer.PeerType.EMBEDDED_FRAME
690                && !lwcToolkit.isApplicationActive()) {
691            lwcToolkit.activateApplicationIgnoringOtherApps();
692        }
693        updateFocusabilityForAutoRequestFocus(false);
694        nativePushNSWindowToFront(nsWindowPtr);
695        updateFocusabilityForAutoRequestFocus(true);
696    }
697
698    @Override
699    public void setResizable(final boolean resizable) {
700        setStyleBits(RESIZABLE, resizable);
701    }
702
703    @Override
704    public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
705        nativeSetNSWindowMinMax(getNSWindowPtr(), minW, minH, maxW, maxH);
706    }
707
708    @Override
709    public boolean rejectFocusRequest(FocusEvent.Cause cause) {
710        // Cross-app activation requests are not allowed.
711        if (cause != FocusEvent.Cause.MOUSE_EVENT &&
712            !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
713        {
714            focusLogger.fine("the app is inactive, so the request is rejected");
715            return true;
716        }
717        return false;
718    }
719
720    @Override
721    public boolean requestWindowFocus() {
722
723        long ptr = getNSWindowPtr();
724        if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
725            CWrapper.NSWindow.makeMainWindow(ptr);
726        }
727        CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
728        return true;
729    }
730
731    @Override
732    public boolean isActive() {
733        long ptr = getNSWindowPtr();
734        return CWrapper.NSWindow.isKeyWindow(ptr);
735    }
736
737    @Override
738    public void updateFocusableWindowState() {
739        final boolean isFocusable = isNativelyFocusableWindow();
740        setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
741    }
742
743    @Override
744    public Graphics transformGraphics(Graphics g) {
745        // is this where we can inject a transform for HiDPI?
746        return g;
747    }
748
749    @Override
750    public void setAlwaysOnTop(boolean isAlwaysOnTop) {
751        setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
752    }
753
754    @Override
755    public void setOpacity(float opacity) {
756        CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
757    }
758
759    @Override
760    public void setOpaque(boolean isOpaque) {
761        CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
762        boolean isTextured = (peer == null) ? false : peer.isTextured();
763        if (!isTextured) {
764            if (!isOpaque) {
765                CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), 0);
766            } else if (peer != null) {
767                Color color = peer.getBackground();
768                if (color != null) {
769                    int rgb = color.getRGB();
770                    CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), rgb);
771                }
772            }
773        }
774
775        //This is a temporary workaround. Looks like after 7124236 will be fixed
776        //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
777        SwingUtilities.invokeLater(this::invalidateShadow);
778    }
779
780    @Override
781    public void enterFullScreenMode() {
782        isFullScreenMode = true;
783        nativeEnterFullScreenMode(getNSWindowPtr());
784    }
785
786    @Override
787    public void exitFullScreenMode() {
788        nativeExitFullScreenMode(getNSWindowPtr());
789        isFullScreenMode = false;
790    }
791
792    @Override
793    public boolean isFullScreenMode() {
794        return isFullScreenMode;
795    }
796
797    @Override
798    public void setWindowState(int windowState) {
799        if (peer == null || !peer.isVisible()) {
800            // setVisible() applies the state
801            return;
802        }
803
804        int prevWindowState = peer.getState();
805        if (prevWindowState == windowState) return;
806
807        final long nsWindowPtr = getNSWindowPtr();
808        if ((windowState & Frame.ICONIFIED) != 0) {
809            // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
810            windowState = Frame.ICONIFIED;
811        }
812        switch (windowState) {
813            case Frame.ICONIFIED:
814                if (prevWindowState == Frame.MAXIMIZED_BOTH) {
815                    // let's return into the normal states first
816                    // the zoom call toggles between the normal and the max states
817                    unmaximize();
818                }
819                CWrapper.NSWindow.miniaturize(nsWindowPtr);
820                break;
821            case Frame.MAXIMIZED_BOTH:
822                if (prevWindowState == Frame.ICONIFIED) {
823                    // let's return into the normal states first
824                    CWrapper.NSWindow.deminiaturize(nsWindowPtr);
825                }
826                maximize();
827                break;
828            case Frame.NORMAL:
829                if (prevWindowState == Frame.ICONIFIED) {
830                    CWrapper.NSWindow.deminiaturize(nsWindowPtr);
831                } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
832                    // the zoom call toggles between the normal and the max states
833                    unmaximize();
834                }
835                break;
836            default:
837                throw new RuntimeException("Unknown window state: " + windowState);
838        }
839
840        // NOTE: the SWP.windowState field gets updated to the newWindowState
841        //       value when the native notification comes to us
842    }
843
844    @Override
845    public void setModalBlocked(boolean blocked) {
846        if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
847            return;
848        }
849
850        nativeSetEnabled(getNSWindowPtr(), !blocked);
851        checkBlockingAndOrder();
852    }
853
854    public final void invalidateShadow(){
855        nativeRevalidateNSWindowShadow(getNSWindowPtr());
856    }
857
858    // ----------------------------------------------------------------------
859    //                          UTILITY METHODS
860    // ----------------------------------------------------------------------
861
862    /**
863     * Find image to install into Title or into Application icon. First try
864     * icons installed for toplevel. Null is returned, if there is no icon and
865     * default Duke image should be used.
866     */
867    private CImage getImageForTarget() {
868        CImage icon = null;
869        try {
870            icon = CImage.getCreator().createFromImages(target.getIconImages());
871        } catch (Exception ignored) {
872            // Perhaps the icon passed into Java is broken. Skipping this icon.
873        }
874        return icon;
875    }
876
877    /*
878     * Returns LWWindowPeer associated with this delegate.
879     */
880    @Override
881    public LWWindowPeer getPeer() {
882        return peer;
883    }
884
885    @Override
886    public boolean isUnderMouse() {
887        return contentView.isUnderMouse();
888    }
889
890    public CPlatformView getContentView() {
891        return contentView;
892    }
893
894    @Override
895    public long getLayerPtr() {
896        return contentView.getWindowLayerPtr();
897    }
898
899    private void validateSurface() {
900        SurfaceData surfaceData = getSurfaceData();
901        if (surfaceData instanceof CGLSurfaceData) {
902            ((CGLSurfaceData)surfaceData).validate();
903        }
904    }
905
906    void flushBuffers() {
907        if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
908            try {
909                LWCToolkit.invokeAndWait(new Runnable() {
910                    @Override
911                    public void run() {
912                        //Posting an empty to flush the EventQueue without blocking the main thread
913                    }
914                }, target);
915            } catch (InvocationTargetException e) {
916                e.printStackTrace();
917            }
918        }
919    }
920
921    /**
922     * Helper method to get a pointer to the native view from the PlatformWindow.
923     */
924    static long getNativeViewPtr(PlatformWindow platformWindow) {
925        long nativePeer = 0L;
926        if (platformWindow instanceof CPlatformWindow) {
927            nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
928        } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
929            nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
930        }
931        return nativePeer;
932    }
933
934    /*************************************************************
935     * Callbacks from the AWTWindow and AWTView objc classes.
936     *************************************************************/
937    private void deliverWindowFocusEvent(boolean gained, CPlatformWindow opposite){
938        // Fix for 7150349: ingore "gained" notifications when the app is inactive.
939        if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
940            focusLogger.fine("the app is inactive, so the notification is ignored");
941            return;
942        }
943
944        LWWindowPeer oppositePeer = (opposite == null)? null : opposite.getPeer();
945        responder.handleWindowFocusEvent(gained, oppositePeer);
946    }
947
948    protected void deliverMoveResizeEvent(int x, int y, int width, int height,
949                                        boolean byUser) {
950        checkZoom();
951
952        final Rectangle oldB = nativeBounds;
953        nativeBounds = new Rectangle(x, y, width, height);
954        if (peer != null) {
955            peer.notifyReshape(x, y, width, height);
956            // System-dependent appearance optimization.
957            if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
958                    || isFullScreenAnimationOn) {
959                flushBuffers();
960            }
961        }
962    }
963
964    private void deliverWindowClosingEvent() {
965        if (peer != null && peer.getBlocker() == null) {
966            peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
967        }
968    }
969
970    private void deliverIconify(final boolean iconify) {
971        if (peer != null) {
972            peer.notifyIconify(iconify);
973        }
974    }
975
976    private void deliverZoom(final boolean isZoomed) {
977        if (peer != null) {
978            peer.notifyZoom(isZoomed);
979        }
980    }
981
982    private void checkZoom() {
983        if (peer != null) {
984            int state = peer.getState();
985            if (state != Frame.MAXIMIZED_BOTH && isMaximized()) {
986                deliverZoom(true);
987            } else if (state == Frame.MAXIMIZED_BOTH && !isMaximized()) {
988                deliverZoom(false);
989            }
990        }
991    }
992
993    private void deliverNCMouseDown() {
994        if (peer != null) {
995            peer.notifyNCMouseDown();
996        }
997    }
998
999    /*
1000     * Our focus model is synthetic and only non-simple window
1001     * may become natively focusable window.
1002     */
1003    private boolean isNativelyFocusableWindow() {
1004        if (peer == null) {
1005            return false;
1006        }
1007
1008        return !peer.isSimpleWindow() && target.getFocusableWindowState();
1009    }
1010
1011    /*
1012     * An utility method for the support of the auto request focus.
1013     * Updates the focusable state of the window under certain
1014     * circumstances.
1015     */
1016    private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
1017        if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
1018        setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
1019    }
1020
1021    private boolean checkBlockingAndOrder() {
1022        LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
1023        if (blocker == null) {
1024            return false;
1025        }
1026
1027        if (blocker instanceof CPrinterDialogPeer) {
1028            return true;
1029        }
1030
1031        CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
1032
1033        pWindow.orderAboveSiblings();
1034
1035        final long nsWindowPtr = pWindow.getNSWindowPtr();
1036        CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
1037        CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
1038        CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
1039
1040        return true;
1041    }
1042
1043    private void orderAboveSiblings() {
1044        if (owner == null) {
1045            return;
1046        }
1047
1048        // NOTE: the logic will fail if we have a hierarchy like:
1049        //       visible root owner
1050        //          invisible owner
1051        //              visible dialog
1052        // However, this is an unlikely scenario for real life apps
1053        if (owner.isVisible()) {
1054            // Recursively pop up the windows from the very bottom so that only
1055            // the very top-most one becomes the main window
1056            owner.orderAboveSiblings();
1057
1058            // Order the window to front of the stack of child windows
1059            final long nsWindowSelfPtr = getNSWindowPtr();
1060            final long nsWindowOwnerPtr = owner.getNSWindowPtr();
1061            CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
1062            CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
1063        }
1064
1065        applyWindowLevel(target);
1066    }
1067
1068    protected void applyWindowLevel(Window target) {
1069        if (target.isAlwaysOnTop() && target.getType() != Window.Type.POPUP) {
1070            CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
1071        } else if (target.getType() == Window.Type.POPUP) {
1072            CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSPopUpMenuWindowLevel);
1073        }
1074    }
1075
1076    // ----------------------------------------------------------------------
1077    //                          NATIVE CALLBACKS
1078    // ----------------------------------------------------------------------
1079
1080    private void windowDidBecomeMain() {
1081        if (checkBlockingAndOrder()) return;
1082        // If it's not blocked, make sure it's above its siblings
1083        orderAboveSiblings();
1084    }
1085
1086    private void windowWillEnterFullScreen() {
1087        isFullScreenAnimationOn = true;
1088    }
1089
1090    private void windowDidEnterFullScreen() {
1091        isFullScreenAnimationOn = false;
1092    }
1093
1094    private void windowWillExitFullScreen() {
1095        isFullScreenAnimationOn = true;
1096    }
1097
1098    private void windowDidExitFullScreen() {
1099        isFullScreenAnimationOn = false;
1100    }
1101}
1102