From ac0b8d6ebe0f2b450a31f2a55089fcfad0705485 Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Wed, 4 Jun 2008 12:32:05 +0400 Subject: [PATCH 001/325] 6280057: I have audited SystemTray and TrayIcon code Small refactoring Reviewed-by: dcherepanov --- .../share/classes/java/awt/SystemTray.java | 15 ++++++------ jdk/src/share/classes/java/awt/TrayIcon.java | 23 ++++--------------- 2 files changed, 12 insertions(+), 26 deletions(-) diff --git a/jdk/src/share/classes/java/awt/SystemTray.java b/jdk/src/share/classes/java/awt/SystemTray.java index 650821e726e..7d193fc6e65 100644 --- a/jdk/src/share/classes/java/awt/SystemTray.java +++ b/jdk/src/share/classes/java/awt/SystemTray.java @@ -125,6 +125,8 @@ public class SystemTray { transient private SystemTrayPeer peer; + private static final TrayIcon[] EMPTY_TRAY_ARRAY = new TrayIcon[0]; + /** * Private SystemTray constructor. * @@ -203,13 +205,12 @@ public class SystemTray { public static boolean isSupported() { initializeSystemTrayIfNeeded(); - if (Toolkit.getDefaultToolkit() instanceof SunToolkit) { + Toolkit toolkit = Toolkit.getDefaultToolkit(); - return ((SunToolkit)Toolkit.getDefaultToolkit()).isTraySupported(); - - } else if (Toolkit.getDefaultToolkit() instanceof HeadlessToolkit) { - - return ((HeadlessToolkit)Toolkit.getDefaultToolkit()).isTraySupported(); + if (toolkit instanceof SunToolkit) { + return ((SunToolkit)toolkit).isTraySupported(); + } else if (toolkit instanceof HeadlessToolkit) { + return ((HeadlessToolkit)toolkit).isTraySupported(); } return false; } @@ -323,7 +324,7 @@ public class SystemTray { if (icons != null) { return (TrayIcon[])icons.toArray(new TrayIcon[icons.size()]); } - return new TrayIcon[0]; + return EMPTY_TRAY_ARRAY; } /** diff --git a/jdk/src/share/classes/java/awt/TrayIcon.java b/jdk/src/share/classes/java/awt/TrayIcon.java index 32ee66c25ba..d3a6e570feb 100644 --- a/jdk/src/share/classes/java/awt/TrayIcon.java +++ b/jdk/src/share/classes/java/awt/TrayIcon.java @@ -142,9 +142,6 @@ public class TrayIcon { */ public TrayIcon(Image image) { this(); - if (image == null) { - throw new IllegalArgumentException("creating TrayIcon with null Image"); - } setImage(image); } @@ -433,7 +430,7 @@ public class TrayIcon { * @see java.awt.event.MouseListener */ public synchronized MouseListener[] getMouseListeners() { - return (MouseListener[])(getListeners(MouseListener.class)); + return AWTEventMulticaster.getListeners(mouseListener, MouseListener.class); } /** @@ -494,7 +491,7 @@ public class TrayIcon { * @see java.awt.event.MouseMotionListener */ public synchronized MouseMotionListener[] getMouseMotionListeners() { - return (MouseMotionListener[]) (getListeners(MouseMotionListener.class)); + return AWTEventMulticaster.getListeners(mouseMotionListener, MouseMotionListener.class); } /** @@ -581,7 +578,7 @@ public class TrayIcon { * @see java.awt.event.ActionListener */ public synchronized ActionListener[] getActionListeners() { - return (ActionListener[])(getListeners(ActionListener.class)); + return AWTEventMulticaster.getListeners(actionListener, ActionListener.class); } /** @@ -635,7 +632,7 @@ public class TrayIcon { TrayIconPeer peer = this.peer; if (peer != null) { - peer.displayMessage(caption, text, messageType.toString()); + peer.displayMessage(caption, text, messageType.name()); } } @@ -657,18 +654,6 @@ public class TrayIcon { // **************************************************************** // **************************************************************** - T[] getListeners(Class listenerType) { - EventListener l = null; - if (listenerType == MouseListener.class) { - l = mouseListener; - } else if (listenerType == MouseMotionListener.class) { - l = mouseMotionListener; - } else if (listenerType == ActionListener.class) { - l = actionListener; - } - return AWTEventMulticaster.getListeners(l, listenerType); - } - void addNotify() throws AWTException { From 4db94beee6a3bbb45b0f9fca6d365cab82c23ad7 Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Wed, 4 Jun 2008 14:16:44 +0400 Subject: [PATCH 002/325] 6708322: test/closed/java/awt/Focus/TemporaryLostComponentDeadlock fails Introduced new package private object for synchronization purposes. It should replace "this" in some deadlock prone cases. Reviewed-by: anthony, art --- jdk/src/share/classes/java/awt/Component.java | 40 ++++++++++++------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index 6d3a7497042..5a0de21c6c5 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -635,11 +635,21 @@ public abstract class Component implements ImageObserver, MenuContainer, */ private PropertyChangeSupport changeSupport; - // Note: this field is considered final, though readObject() prohibits - // initializing final fields. - private transient Object changeSupportLock = new Object(); - private Object getChangeSupportLock() { - return changeSupportLock; + /* + * In some cases using "this" as an object to synchronize by + * can lead to a deadlock if client code also uses synchronization + * by a component object. For every such situation revealed we should + * consider possibility of replacing "this" with the package private + * objectLock object introduced below. So far there're 2 issues known: + * - CR 6708322 (the getName/setName methods); + * - CR 6608764 (the PropertyChangeListener machinery). + * + * Note: this field is considered final, though readObject() prohibits + * initializing final fields. + */ + private transient Object objectLock = new Object(); + Object getObjectLock() { + return objectLock; } boolean isPacked = false; @@ -812,7 +822,7 @@ public abstract class Component implements ImageObserver, MenuContainer, */ public String getName() { if (name == null && !nameExplicitlySet) { - synchronized(this) { + synchronized(getObjectLock()) { if (name == null && !nameExplicitlySet) name = constructComponentName(); } @@ -829,7 +839,7 @@ public abstract class Component implements ImageObserver, MenuContainer, */ public void setName(String name) { String oldName; - synchronized(this) { + synchronized(getObjectLock()) { oldName = this.name; this.name = name; nameExplicitlySet = true; @@ -7838,7 +7848,7 @@ public abstract class Component implements ImageObserver, MenuContainer, */ public void addPropertyChangeListener( PropertyChangeListener listener) { - synchronized (getChangeSupportLock()) { + synchronized (getObjectLock()) { if (listener == null) { return; } @@ -7864,7 +7874,7 @@ public abstract class Component implements ImageObserver, MenuContainer, */ public void removePropertyChangeListener( PropertyChangeListener listener) { - synchronized (getChangeSupportLock()) { + synchronized (getObjectLock()) { if (listener == null || changeSupport == null) { return; } @@ -7887,7 +7897,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * @since 1.4 */ public PropertyChangeListener[] getPropertyChangeListeners() { - synchronized (getChangeSupportLock()) { + synchronized (getObjectLock()) { if (changeSupport == null) { return new PropertyChangeListener[0]; } @@ -7929,7 +7939,7 @@ public abstract class Component implements ImageObserver, MenuContainer, public void addPropertyChangeListener( String propertyName, PropertyChangeListener listener) { - synchronized (getChangeSupportLock()) { + synchronized (getObjectLock()) { if (listener == null) { return; } @@ -7959,7 +7969,7 @@ public abstract class Component implements ImageObserver, MenuContainer, public void removePropertyChangeListener( String propertyName, PropertyChangeListener listener) { - synchronized (getChangeSupportLock()) { + synchronized (getObjectLock()) { if (listener == null || changeSupport == null) { return; } @@ -7983,7 +7993,7 @@ public abstract class Component implements ImageObserver, MenuContainer, */ public PropertyChangeListener[] getPropertyChangeListeners( String propertyName) { - synchronized (getChangeSupportLock()) { + synchronized (getObjectLock()) { if (changeSupport == null) { return new PropertyChangeListener[0]; } @@ -8004,7 +8014,7 @@ public abstract class Component implements ImageObserver, MenuContainer, protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { PropertyChangeSupport changeSupport; - synchronized (getChangeSupportLock()) { + synchronized (getObjectLock()) { changeSupport = this.changeSupport; } if (changeSupport == null || @@ -8306,7 +8316,7 @@ public abstract class Component implements ImageObserver, MenuContainer, private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { - changeSupportLock = new Object(); + objectLock = new Object(); s.defaultReadObject(); From 7d7546ef37ae4e601b30fb3c255042e026ac3fc4 Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Tue, 17 Jun 2008 13:37:28 +0400 Subject: [PATCH 003/325] 4685768: A11y issue - Focus set to disabled component, can't Tab/Shift-Tab The restore-focus procedure should skip disabled components. Reviewed-by: art, dcherepanov --- jdk/src/share/classes/java/awt/Component.java | 20 ++-- jdk/src/share/classes/java/awt/Container.java | 4 +- .../ContainerOrderFocusTraversalPolicy.java | 3 +- .../java/awt/DefaultKeyboardFocusManager.java | 12 +- jdk/src/share/classes/java/awt/Window.java | 4 +- .../NoAutotransferToDisabledCompTest.java | 109 ++++++++++++++++++ .../RequestFocusToDisabledCompTest.java | 97 ++++++++++++++++ jdk/test/java/awt/regtesthelpers/Util.java | 26 +++++ 8 files changed, 255 insertions(+), 20 deletions(-) create mode 100644 jdk/test/java/awt/Focus/NoAutotransferToDisabledCompTest/NoAutotransferToDisabledCompTest.java create mode 100644 jdk/test/java/awt/Focus/RequestFocusToDisabledCompTest/RequestFocusToDisabledCompTest.java diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index 5a0de21c6c5..057fefa1945 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -7488,9 +7488,7 @@ public abstract class Component implements ImageObserver, MenuContainer, Container rootAncestor = getTraversalRoot(); Component comp = this; while (rootAncestor != null && - !(rootAncestor.isShowing() && - rootAncestor.isFocusable() && - rootAncestor.isEnabled())) + !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner())) { comp = rootAncestor; rootAncestor = comp.getFocusCycleRootAncestor(); @@ -7539,9 +7537,7 @@ public abstract class Component implements ImageObserver, MenuContainer, Container rootAncestor = getTraversalRoot(); Component comp = this; while (rootAncestor != null && - !(rootAncestor.isShowing() && - rootAncestor.isFocusable() && - rootAncestor.isEnabled())) + !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner())) { comp = rootAncestor; rootAncestor = comp.getFocusCycleRootAncestor(); @@ -8518,6 +8514,14 @@ public abstract class Component implements ImageObserver, MenuContainer, setComponentOrientation(orientation); } + final boolean canBeFocusOwner() { + // It is enabled, visible, focusable. + if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) { + return true; + } + return false; + } + /** * Checks that this component meets the prerequesites to be focus owner: * - it is enabled, visible, focusable @@ -8527,9 +8531,9 @@ public abstract class Component implements ImageObserver, MenuContainer, * this component as focus owner * @since 1.5 */ - final boolean canBeFocusOwner() { + final boolean canBeFocusOwnerRecursively() { // - it is enabled, visible, focusable - if (!(isEnabled() && isDisplayable() && isVisible() && isFocusable())) { + if (!canBeFocusOwner()) { return false; } diff --git a/jdk/src/share/classes/java/awt/Container.java b/jdk/src/share/classes/java/awt/Container.java index d79bde285f3..260ec515a2f 100644 --- a/jdk/src/share/classes/java/awt/Container.java +++ b/jdk/src/share/classes/java/awt/Container.java @@ -860,11 +860,11 @@ public class Container extends Component { // If component is focus owner or parent container of focus owner check that after reparenting // focus owner moved out if new container prohibit this kind of focus owner. - if (comp.isFocusOwner() && !comp.canBeFocusOwner()) { + if (comp.isFocusOwner() && !comp.canBeFocusOwnerRecursively()) { comp.transferFocus(); } else if (comp instanceof Container) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - if (focusOwner != null && isParentOf(focusOwner) && !focusOwner.canBeFocusOwner()) { + if (focusOwner != null && isParentOf(focusOwner) && !focusOwner.canBeFocusOwnerRecursively()) { focusOwner.transferFocus(); } } diff --git a/jdk/src/share/classes/java/awt/ContainerOrderFocusTraversalPolicy.java b/jdk/src/share/classes/java/awt/ContainerOrderFocusTraversalPolicy.java index 5e75cdaf763..187ddc54931 100644 --- a/jdk/src/share/classes/java/awt/ContainerOrderFocusTraversalPolicy.java +++ b/jdk/src/share/classes/java/awt/ContainerOrderFocusTraversalPolicy.java @@ -556,8 +556,7 @@ public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy * enabled, and focusable; false otherwise */ protected boolean accept(Component aComponent) { - if (!(aComponent.isVisible() && aComponent.isDisplayable() && - aComponent.isFocusable() && aComponent.isEnabled())) { + if (!aComponent.canBeFocusOwner()) { return false; } diff --git a/jdk/src/share/classes/java/awt/DefaultKeyboardFocusManager.java b/jdk/src/share/classes/java/awt/DefaultKeyboardFocusManager.java index 928379ec286..1f346bcb9f1 100644 --- a/jdk/src/share/classes/java/awt/DefaultKeyboardFocusManager.java +++ b/jdk/src/share/classes/java/awt/DefaultKeyboardFocusManager.java @@ -154,7 +154,7 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { private boolean doRestoreFocus(Component toFocus, Component vetoedComponent, boolean clearOnFailure) { - if (toFocus != vetoedComponent && toFocus.isShowing() && toFocus.isFocusable() && + if (toFocus != vetoedComponent && toFocus.isShowing() && toFocus.canBeFocusOwner() && toFocus.requestFocus(false, CausedFocusEvent.Cause.ROLLBACK)) { return true; @@ -500,8 +500,11 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { } } - if (!(newFocusOwner.isFocusable() && newFocusOwner.isEnabled() - && newFocusOwner.isShowing())) + if (!(newFocusOwner.isFocusable() && newFocusOwner.isShowing() && + // Refuse focus on a disabled component if the focus event + // isn't of UNKNOWN reason (i.e. not a result of a direct request + // but traversal, activation or system generated). + (newFocusOwner.isEnabled() || cause.equals(CausedFocusEvent.Cause.UNKNOWN)))) { // we should not accept focus on such component, so reject it. dequeueKeyEvents(-1, newFocusOwner); @@ -742,8 +745,7 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { public boolean dispatchKeyEvent(KeyEvent e) { Component focusOwner = (((AWTEvent)e).isPosted) ? getFocusOwner() : e.getComponent(); - if (focusOwner != null && focusOwner.isShowing() && - focusOwner.isFocusable() && focusOwner.isEnabled()) { + if (focusOwner != null && focusOwner.isShowing() && focusOwner.canBeFocusOwner()) { if (!e.isConsumed()) { Component comp = e.getComponent(); if (comp != null && comp.isEnabled()) { diff --git a/jdk/src/share/classes/java/awt/Window.java b/jdk/src/share/classes/java/awt/Window.java index 3ebeee00639..94a8ff2ed5b 100644 --- a/jdk/src/share/classes/java/awt/Window.java +++ b/jdk/src/share/classes/java/awt/Window.java @@ -3145,9 +3145,7 @@ public class Window extends Container implements Accessible { Component previousComp = temporaryLostComponent; // Check that "component" is an acceptable focus owner and don't store it otherwise // - or later we will have problems with opposite while handling WINDOW_GAINED_FOCUS - if (component == null - || (component.isDisplayable() && component.isVisible() && component.isEnabled() && component.isFocusable())) - { + if (component == null || component.canBeFocusOwner()) { temporaryLostComponent = component; } else { temporaryLostComponent = null; diff --git a/jdk/test/java/awt/Focus/NoAutotransferToDisabledCompTest/NoAutotransferToDisabledCompTest.java b/jdk/test/java/awt/Focus/NoAutotransferToDisabledCompTest/NoAutotransferToDisabledCompTest.java new file mode 100644 index 00000000000..b4bcdccfda0 --- /dev/null +++ b/jdk/test/java/awt/Focus/NoAutotransferToDisabledCompTest/NoAutotransferToDisabledCompTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + @test + @bug 4685768 + @summary Tests that auto-transfering focus doesn't stuck on a disabled component. + @author Anton Tarasov: area=awt.focus + @library ../../regtesthelpers + @build Util + @run main NoAutotransferToDisabledCompTest +*/ + +import java.awt.Robot; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.applet.Applet; +import test.java.awt.regtesthelpers.Util; + +public class NoAutotransferToDisabledCompTest extends Applet { + Robot robot; + JFrame frame = new JFrame("Frame"); + JButton b0 = new JButton("b0"); + JButton b1 = new JButton("b1"); + JButton b2 = new JButton("b2"); + + public static void main(String[] args) { + NoAutotransferToDisabledCompTest app = new NoAutotransferToDisabledCompTest(); + app.init(); + app.start(); + } + + public void init() { + robot = Util.createRobot(); + frame.add(b0); + frame.add(b1); + frame.add(b2); + frame.setLayout(new FlowLayout()); + frame.pack(); + + b1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + b1.setEnabled(false); + b2.setEnabled(false); + } + }); + } + + public void start() { + Util.showWindowWait(frame); + + // Request focus on b1. + if (!Util.focusComponent(b1, 2000)) { + throw new TestErrorException("couldn't focus " + b1); + } + + // Activate b1. + robot.keyPress(KeyEvent.VK_SPACE); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_SPACE); + Util.waitForIdle(robot); + + // Check that focus has been transfered to b0. + if (!b0.hasFocus()) { + throw new TestFailedException("focus wasn't auto-transfered properly!"); + } + System.out.println("Test passed."); + } +} + +/** + * Thrown when the behavior being verified is found wrong. + */ +class TestFailedException extends RuntimeException { + TestFailedException(String msg) { + super("Test failed: " + msg); + } +} + +/** + * Thrown when an error not related to the behavior being verified is encountered. + */ +class TestErrorException extends RuntimeException { + TestErrorException(String msg) { + super("Unexpected error: " + msg); + } +} + diff --git a/jdk/test/java/awt/Focus/RequestFocusToDisabledCompTest/RequestFocusToDisabledCompTest.java b/jdk/test/java/awt/Focus/RequestFocusToDisabledCompTest/RequestFocusToDisabledCompTest.java new file mode 100644 index 00000000000..b86a792f42c --- /dev/null +++ b/jdk/test/java/awt/Focus/RequestFocusToDisabledCompTest/RequestFocusToDisabledCompTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + @test + @bug 4685768 + @summary Tests that it's possible to manually request focus on a disabled component. + @author Anton Tarasov: area=awt.focus + @library ../../regtesthelpers + @build Util + @run main RequestFocusToDisabledCompTest +*/ + +import java.awt.Robot; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.applet.Applet; +import test.java.awt.regtesthelpers.Util; + +public class RequestFocusToDisabledCompTest extends Applet { + Robot robot; + JFrame frame = new JFrame("Frame"); + JButton b0 = new JButton("b0"); + JButton b1 = new JButton("b1"); + + public static void main(String[] args) { + RequestFocusToDisabledCompTest app = new RequestFocusToDisabledCompTest(); + app.init(); + app.start(); + } + + public void init() { + robot = Util.createRobot(); + frame.add(b0); + frame.add(b1); + frame.setLayout(new FlowLayout()); + frame.pack(); + + b1.setEnabled(false); + } + + public void start() { + Util.showWindowWait(frame); + + if (!b0.hasFocus()) { + // Request focus on b0. + if (!Util.focusComponent(b0, 2000)) { + throw new TestErrorException("couldn't focus " + b0); + } + } + + // Try to request focus on b1. + if (!Util.focusComponent(b1, 2000)) { + throw new TestFailedException("focus wasn't requested on disabled " + b1); + } + System.out.println("Test passed."); + } +} + +/** + * Thrown when the behavior being verified is found wrong. + */ +class TestFailedException extends RuntimeException { + TestFailedException(String msg) { + super("Test failed: " + msg); + } +} + +/** + * Thrown when an error not related to the behavior being verified is encountered. + */ +class TestErrorException extends RuntimeException { + TestErrorException(String msg) { + super("Unexpected error: " + msg); + } +} diff --git a/jdk/test/java/awt/regtesthelpers/Util.java b/jdk/test/java/awt/regtesthelpers/Util.java index bdabff33d37..e1c165912d1 100644 --- a/jdk/test/java/awt/regtesthelpers/Util.java +++ b/jdk/test/java/awt/regtesthelpers/Util.java @@ -123,6 +123,14 @@ public final class Util { throw new RuntimeException("Unexpected toolkit - " + tk); } + /** + * Makes the window visible and waits until it's shown. + */ + public static void showWindowWait(Window win) { + win.setVisible(true); + waitTillShown(win); + } + /** * Moves mouse pointer in the center of given {@code comp} component * using {@code robot} parameter. @@ -574,4 +582,22 @@ public final class Util { public static boolean trackActionPerformed(Button button, Runnable action, int time, boolean printEvent) { return trackEvent(ActionEvent.ACTION_PERFORMED, button, action, time, printEvent); } + + /* + * Requests focus on the component provided and waits for the result. + * @return true if the component has been focused, false otherwise. + */ + public static boolean focusComponent(Component comp, int time) { + return focusComponent(comp, time, false); + } + public static boolean focusComponent(final Component comp, int time, boolean printEvent) { + return trackFocusGained(comp, + new Runnable() { + public void run() { + comp.requestFocus(); + } + }, + time, printEvent); + + } } From 3a5617e9f7c270e61efff097626fc5d499443049 Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Wed, 18 Jun 2008 15:35:37 +0400 Subject: [PATCH 004/325] 6616323: consider benefits of replacing a componen array with other collection from the awt.Container class Reviewed-by: uta, art --- jdk/src/share/classes/java/awt/Component.java | 2 +- jdk/src/share/classes/java/awt/Container.java | 396 ++++++++---------- .../share/classes/java/awt/ScrollPane.java | 78 ++-- .../native/sun/windows/awt_Container.cpp | 10 +- .../native/sun/windows/awt_Container.h | 4 +- .../CheckZOrderChange/CheckZOrderChange.java | 48 +++ 6 files changed, 276 insertions(+), 262 deletions(-) create mode 100644 jdk/test/java/awt/Container/CheckZOrderChange/CheckZOrderChange.java diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index 057fefa1945..221506d80e1 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -2141,7 +2141,7 @@ public abstract class Component implements ImageObserver, MenuContainer, Toolkit.getEventQueue().postEvent(e); } } else { - if (this instanceof Container && ((Container)this).ncomponents > 0) { + if (this instanceof Container && ((Container)this).countComponents() > 0) { boolean enabledOnToolkit = Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK); if (resized) { diff --git a/jdk/src/share/classes/java/awt/Container.java b/jdk/src/share/classes/java/awt/Container.java index 260ec515a2f..febd964265a 100644 --- a/jdk/src/share/classes/java/awt/Container.java +++ b/jdk/src/share/classes/java/awt/Container.java @@ -1,5 +1,5 @@ /* - * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,8 +44,6 @@ import java.io.PrintWriter; import java.util.Arrays; import java.util.EventListener; import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; import java.util.Set; import java.util.logging.*; @@ -90,21 +88,14 @@ public class Container extends Component { private static final Logger log = Logger.getLogger("java.awt.Container"); private static final Logger eventLog = Logger.getLogger("java.awt.event.Container"); - /** - * The number of components in this container. - * This value can be null. - * @see #getComponent - * @see #getComponents - * @see #getComponentCount - */ - int ncomponents; + private static final Component[] EMPTY_ARRAY = new Component[0]; /** * The components in this container. * @see #add * @see #getComponents */ - Component component[] = new Component[0]; + private java.util.List component = new java.util.ArrayList(); /** * Layout manager for this container. @@ -290,7 +281,9 @@ public class Container extends Component { */ @Deprecated public int countComponents() { - return ncomponents; + synchronized (getTreeLock()) { + return component.size(); + } } /** @@ -302,10 +295,10 @@ public class Container extends Component { */ public Component getComponent(int n) { synchronized (getTreeLock()) { - if ((n < 0) || (n >= ncomponents)) { + if ((n < 0) || (n >= component.size())) { throw new ArrayIndexOutOfBoundsException("No such child: " + n); } - return component[n]; + return component.get(n); } } @@ -322,7 +315,7 @@ public class Container extends Component { // DO NOT INVOKE CLIENT CODE ON THIS THREAD! final Component[] getComponents_NoClientCode() { synchronized (getTreeLock()) { - return Arrays.copyOf(component, ncomponents); + return component.toArray(EMPTY_ARRAY); } } // getComponents_NoClientCode() @@ -421,6 +414,29 @@ public class Container extends Component { return comp; } + /** + * Checks that the component + * isn't supposed to be added into itself. + */ + private void checkAddToSelf(Component comp){ + if (comp instanceof Container) { + for (Container cn = this; cn != null; cn=cn.parent) { + if (cn == comp) { + throw new IllegalArgumentException("adding container's parent to itself"); + } + } + } + } + + /** + * Checks that the component is not a Window instance. + */ + private void checkNotAWindow(Component comp){ + if (comp instanceof Window) { + throw new IllegalArgumentException("adding a window to a container"); + } + } + /** * Checks that the component comp can be added to this container * Checks : index in bounds of container's size, @@ -437,26 +453,18 @@ public class Container extends Component { GraphicsConfiguration thisGC = getGraphicsConfiguration(); - if (index > ncomponents || index < 0) { + if (index > component.size() || index < 0) { throw new IllegalArgumentException("illegal component position"); } if (comp.parent == this) { - if (index == ncomponents) { + if (index == component.size()) { throw new IllegalArgumentException("illegal component position " + - index + " should be less then " + ncomponents); + index + " should be less then " + component.size()); } } - if (comp instanceof Container) { - for (Container cn = this; cn != null; cn=cn.parent) { - if (cn == comp) { - throw new IllegalArgumentException("adding container's parent to itself"); - } - } + checkAddToSelf(comp); + checkNotAWindow(comp); - if (comp instanceof Window) { - throw new IllegalArgumentException("adding a window to a container"); - } - } Window thisTopLevel = getContainingWindow(); Window compTopLevel = comp.getContainingWindow(); if (thisTopLevel != compTopLevel) { @@ -495,25 +503,19 @@ public class Container extends Component { adjustDescendants(-(comp.countHierarchyMembers())); comp.parent = null; - System.arraycopy(component, index + 1, - component, index, - ncomponents - index - 1); - component[--ncomponents] = null; + component.remove(index); if (valid) { invalidate(); } } else { - if (newIndex > index) { // 2->4: 012345 -> 013425, 2->5: 012345 -> 013452 - if (newIndex-index > 0) { - System.arraycopy(component, index+1, component, index, newIndex-index); - } - } else { // 4->2: 012345 -> 014235 - if (index-newIndex > 0) { - System.arraycopy(component, newIndex, component, newIndex+1, index-newIndex); - } - } - component[newIndex] = comp; + // We should remove component and then + // add it by the newIndex without newIndex decrement if even we shift components to the left + // after remove. Consult the rules below: + // 2->4: 012345 -> 013425, 2->5: 012345 -> 013452 + // 4->2: 012345 -> 014235 + component.remove(index); + component.add(newIndex, comp); } if (comp.parent == null) { // was actually removed if (containerListener != null || @@ -779,17 +781,11 @@ public class Container extends Component { // Check if moving between containers if (curParent != this) { - /* Add component to list; allocate new array if necessary. */ - if (ncomponents == component.length) { - component = Arrays.copyOf(component, ncomponents * 2 + 1); - } - if (index == -1 || index == ncomponents) { - component[ncomponents++] = comp; + //index == -1 means add to the end. + if (index == -1) { + component.add(comp); } else { - System.arraycopy(component, index, component, - index + 1, ncomponents - index); - component[index] = comp; - ncomponents++; + component.add(index, comp); } comp.parent = this; @@ -799,8 +795,8 @@ public class Container extends Component { comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)); adjustDescendants(comp.countHierarchyMembers()); } else { - if (index < ncomponents) { - component[index] = comp; + if (index < component.size()) { + component.set(index, comp); } } @@ -901,14 +897,8 @@ public class Container extends Component { if (comp.parent != this) { return -1; } - for (int i = 0; i < ncomponents; i++) { - if (component[i] == comp) { - return i; - } - } + return component.indexOf(comp); } - // To please javac - return -1; } /** @@ -1042,22 +1032,12 @@ public class Container extends Component { */ GraphicsConfiguration thisGC = this.getGraphicsConfiguration(); - if (index > ncomponents || (index < 0 && index != -1)) { + if (index > component.size() || (index < 0 && index != -1)) { throw new IllegalArgumentException( "illegal component position"); } - if (comp instanceof Container) { - for (Container cn = this; cn != null; cn=cn.parent) { - if (cn == comp) { - throw new IllegalArgumentException( - "adding container's parent to itself"); - } - } - if (comp instanceof Window) { - throw new IllegalArgumentException( - "adding a window to a container"); - } - } + checkAddToSelf(comp); + checkNotAWindow(comp); if (thisGC != null) { comp.checkGD(thisGC.getDevice().getIDstring()); } @@ -1065,22 +1045,16 @@ public class Container extends Component { /* Reparent the component and tidy up the tree's state. */ if (comp.parent != null) { comp.parent.remove(comp); - if (index > ncomponents) { + if (index > component.size()) { throw new IllegalArgumentException("illegal component position"); } } - /* Add component to list; allocate new array if necessary. */ - if (ncomponents == component.length) { - component = Arrays.copyOf(component, ncomponents * 2 + 1); - } - if (index == -1 || index == ncomponents) { - component[ncomponents++] = comp; + //index == -1 means add to the end. + if (index == -1) { + component.add(comp); } else { - System.arraycopy(component, index, component, - index + 1, ncomponents - index); - component[index] = comp; - ncomponents++; + component.add(index, comp); } comp.parent = this; @@ -1129,11 +1103,9 @@ public class Container extends Component { * IllegalArgumentException. */ void checkGD(String stringID) { - Component tempComp; - for (int i = 0; i < component.length; i++) { - tempComp= component[i]; - if (tempComp != null) { - tempComp.checkGD(stringID); + for (Component comp : component) { + if (comp != null) { + comp.checkGD(stringID); } } } @@ -1163,10 +1135,10 @@ public class Container extends Component { */ public void remove(int index) { synchronized (getTreeLock()) { - if (index < 0 || index >= ncomponents) { + if (index < 0 || index >= component.size()) { throw new ArrayIndexOutOfBoundsException(index); } - Component comp = component[index]; + Component comp = component.get(index); if (peer != null) { comp.removeNotify(); } @@ -1181,10 +1153,7 @@ public class Container extends Component { adjustDescendants(-(comp.countHierarchyMembers())); comp.parent = null; - System.arraycopy(component, index + 1, - component, index, - ncomponents - index - 1); - component[--ncomponents] = null; + component.remove(index); if (valid) { invalidate(); @@ -1229,14 +1198,9 @@ public class Container extends Component { public void remove(Component comp) { synchronized (getTreeLock()) { if (comp.parent == this) { - /* Search backwards, expect that more recent additions - * are more likely to be removed. - */ - Component component[] = this.component; - for (int i = ncomponents; --i >= 0; ) { - if (component[i] == comp) { - remove(i); - } + int index = component.indexOf(comp); + if (index >= 0) { + remove(index); } } } @@ -1258,9 +1222,8 @@ public class Container extends Component { -listeningBoundsChildren); adjustDescendants(-descendantsCount); - while (ncomponents > 0) { - Component comp = component[--ncomponents]; - component[ncomponents] = null; + while (!component.isEmpty()) { + Component comp = component.remove(component.size()-1); if (peer != null) { comp.removeNotify(); @@ -1300,8 +1263,8 @@ public class Container extends Component { if (eventLog.isLoggable(Level.FINE)) { // Verify listeningChildren is correct int sum = 0; - for (int i = 0; i < ncomponents; i++) { - sum += component[i].numListening(mask); + for (Component comp : component) { + sum += comp.numListening(mask); } if (listeningChildren != sum) { eventLog.log(Level.FINE, "Assertion (listeningChildren == sum) failed"); @@ -1312,8 +1275,8 @@ public class Container extends Component { if (eventLog.isLoggable(Level.FINE)) { // Verify listeningBoundsChildren is correct int sum = 0; - for (int i = 0; i < ncomponents; i++) { - sum += component[i].numListening(mask); + for (Component comp : component) { + sum += comp.numListening(mask); } if (listeningBoundsChildren != sum) { eventLog.log(Level.FINE, "Assertion (listeningBoundsChildren == sum) failed"); @@ -1375,8 +1338,8 @@ public class Container extends Component { if (log.isLoggable(Level.FINE)) { // Verify descendantsCount is correct int sum = 0; - for (int i = 0; i < ncomponents; i++) { - sum += component[i].countHierarchyMembers(); + for (Component comp : component) { + sum += comp.countHierarchyMembers(); } if (descendantsCount != sum) { log.log(Level.FINE, "Assertion (descendantsCount == sum) failed"); @@ -1408,7 +1371,7 @@ public class Container extends Component { int listeners = getListenersCount(id, enabledOnToolkit); for (int count = listeners, i = 0; count > 0; i++) { - count -= component[i].createHierarchyEvents(id, changed, + count -= component.get(i).createHierarchyEvents(id, changed, changedParent, changeFlags, enabledOnToolkit); } return listeners + @@ -1420,13 +1383,13 @@ public class Container extends Component { boolean enabledOnToolkit) { assert Thread.holdsLock(getTreeLock()); - if (ncomponents == 0) { + if (component.isEmpty()) { return; } int listeners = getListenersCount(id, enabledOnToolkit); for (int count = listeners, i = 0; count > 0; i++) { - count -= component[i].createHierarchyEvents(id, this, parent, + count -= component.get(i).createHierarchyEvents(id, this, parent, changeFlags, enabledOnToolkit); } } @@ -1562,12 +1525,11 @@ public class Container extends Component { ((ContainerPeer)peer).beginLayout(); } doLayout(); - Component component[] = this.component; - for (int i = 0 ; i < ncomponents ; ++i) { - Component comp = component[i]; + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); if ( (comp instanceof Container) - && !(comp instanceof Window) - && !comp.valid) { + && !(comp instanceof Window) + && !comp.valid) { ((Container)comp).validateTree(); } else { comp.validate(); @@ -1586,8 +1548,8 @@ public class Container extends Component { */ void invalidateTree() { synchronized (getTreeLock()) { - for (int i = 0; i < ncomponents; ++i) { - Component comp = component[i]; + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); if (comp instanceof Container) { ((Container)comp).invalidateTree(); } @@ -1838,7 +1800,7 @@ public class Container extends Component { // super.paint(); -- Don't bother, since it's a NOP. GraphicsCallback.PaintCallback.getInstance(). - runComponents(component, g, GraphicsCallback.LIGHTWEIGHTS); + runComponents(component.toArray(EMPTY_ARRAY), g, GraphicsCallback.LIGHTWEIGHTS); } } @@ -1893,7 +1855,7 @@ public class Container extends Component { } GraphicsCallback.PrintCallback.getInstance(). - runComponents(component, g, GraphicsCallback.LIGHTWEIGHTS); + runComponents(component.toArray(EMPTY_ARRAY), g, GraphicsCallback.LIGHTWEIGHTS); } } @@ -1906,7 +1868,7 @@ public class Container extends Component { public void paintComponents(Graphics g) { if (isShowing()) { GraphicsCallback.PaintAllCallback.getInstance(). - runComponents(component, g, GraphicsCallback.TWO_PASSES); + runComponents(component.toArray(EMPTY_ARRAY), g, GraphicsCallback.TWO_PASSES); } } @@ -1928,7 +1890,7 @@ public class Container extends Component { void paintHeavyweightComponents(Graphics g) { if (isShowing()) { GraphicsCallback.PaintHeavyweightComponentsCallback.getInstance(). - runComponents(component, g, GraphicsCallback.LIGHTWEIGHTS | + runComponents(component.toArray(EMPTY_ARRAY), g, GraphicsCallback.LIGHTWEIGHTS | GraphicsCallback.HEAVYWEIGHTS); } } @@ -1942,7 +1904,7 @@ public class Container extends Component { public void printComponents(Graphics g) { if (isShowing()) { GraphicsCallback.PrintAllCallback.getInstance(). - runComponents(component, g, GraphicsCallback.TWO_PASSES); + runComponents(component.toArray(EMPTY_ARRAY), g, GraphicsCallback.TWO_PASSES); } } @@ -1964,7 +1926,7 @@ public class Container extends Component { void printHeavyweightComponents(Graphics g) { if (isShowing()) { GraphicsCallback.PrintHeavyweightComponentsCallback.getInstance(). - runComponents(component, g, GraphicsCallback.LIGHTWEIGHTS | + runComponents(component.toArray(EMPTY_ARRAY), g, GraphicsCallback.LIGHTWEIGHTS | GraphicsCallback.HEAVYWEIGHTS); } } @@ -2260,11 +2222,9 @@ public class Container extends Component { boolean searchHeavyweightChildren, boolean searchHeavyweightDescendants) { synchronized (getTreeLock()) { - int ncomponents = this.ncomponents; - Component component[] = this.component; - for (int i = 0 ; i < ncomponents ; i++) { - Component comp = component[i]; + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); if (comp != null && comp.visible && ((!searchHeavyweightChildren && comp.peer instanceof LightweightPeer) || @@ -2415,8 +2375,8 @@ public class Container extends Component { } synchronized (getTreeLock()) { // Two passes: see comment in sun.awt.SunGraphicsCallback - for (int i = 0 ; i < ncomponents ; i++) { - Component comp = component[i]; + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); if (comp != null && !(comp.peer instanceof LightweightPeer)) { if (comp.contains(x - comp.x, y - comp.y)) { @@ -2424,8 +2384,8 @@ public class Container extends Component { } } } - for (int i = 0 ; i < ncomponents ; i++) { - Component comp = component[i]; + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); if (comp != null && comp.peer instanceof LightweightPeer) { if (comp.contains(x - comp.x, y - comp.y)) { @@ -2544,43 +2504,43 @@ public class Container extends Component { if (!(contains(x, y) && visible && (ignoreEnabled || enabled))) { return null; } - int ncomponents = this.ncomponents; - Component component[] = this.component; // Two passes: see comment in sun.awt.SunGraphicsCallback - for (int i = 0 ; i < ncomponents ; i++) { - Component comp = component[i]; - if (comp != null && - !(comp.peer instanceof LightweightPeer)) { - if (comp instanceof Container) { - comp = ((Container)comp).findComponentAtImpl(x - comp.x, - y - comp.y, - ignoreEnabled); - } else { - comp = comp.locate(x - comp.x, y - comp.y); - } - if (comp != null && comp.visible && - (ignoreEnabled || comp.enabled)) - { - return comp; + synchronized (getTreeLock()) { + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); + if (comp != null && + !(comp.peer instanceof LightweightPeer)) { + if (comp instanceof Container) { + comp = ((Container)comp).findComponentAtImpl(x - comp.x, + y - comp.y, + ignoreEnabled); + } else { + comp = comp.locate(x - comp.x, y - comp.y); + } + if (comp != null && comp.visible && + (ignoreEnabled || comp.enabled)) + { + return comp; + } } } - } - for (int i = 0 ; i < ncomponents ; i++) { - Component comp = component[i]; - if (comp != null && - comp.peer instanceof LightweightPeer) { - if (comp instanceof Container) { - comp = ((Container)comp).findComponentAtImpl(x - comp.x, - y - comp.y, - ignoreEnabled); - } else { - comp = comp.locate(x - comp.x, y - comp.y); - } - if (comp != null && comp.visible && - (ignoreEnabled || comp.enabled)) - { - return comp; + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); + if (comp != null && + comp.peer instanceof LightweightPeer) { + if (comp instanceof Container) { + comp = ((Container)comp).findComponentAtImpl(x - comp.x, + y - comp.y, + ignoreEnabled); + } else { + comp = comp.locate(x - comp.x, y - comp.y); + } + if (comp != null && comp.visible && + (ignoreEnabled || comp.enabled)) + { + return comp; + } } } } @@ -2632,10 +2592,14 @@ public class Container extends Component { if (! (peer instanceof LightweightPeer)) { dispatcher = new LightweightDispatcher(this); } - int ncomponents = this.ncomponents; - Component component[] = this.component; - for (int i = 0 ; i < ncomponents ; i++) { - component[i].addNotify(); + + // We shouldn't use iterator because of the Swing menu + // implementation specifics: + // the menu is being assigned as a child to JLayeredPane + // instead of particular component so always affect + // collection of component if menu is becoming shown or hidden. + for (int i = 0; i < component.size(); i++) { + component.get(i).addNotify(); } // Update stacking order if native platform allows ContainerPeer cpeer = (ContainerPeer)peer; @@ -2658,21 +2622,25 @@ public class Container extends Component { */ public void removeNotify() { synchronized (getTreeLock()) { - int ncomponents = this.ncomponents; - Component component[] = this.component; - for (int i = ncomponents - 1; i >= 0; i--) { - if( component[i] != null ) { + // We shouldn't use iterator because of the Swing menu + // implementation specifics: + // the menu is being assigned as a child to JLayeredPane + // instead of particular component so always affect + // collection of component if menu is becoming shown or hidden. + for (int i = component.size()-1 ; i >= 0 ; i--) { + Component comp = component.get(i); + if (comp != null) { // Fix for 6607170. // We want to suppress focus change on disposal // of the focused component. But because of focus // is asynchronous, we should suppress focus change // on every component in case it receives native focus // in the process of disposal. - component[i].setAutoFocusTransferOnDisposal(false); - component[i].removeNotify(); - component[i].setAutoFocusTransferOnDisposal(true); - } - } + comp.setAutoFocusTransferOnDisposal(false); + comp.removeNotify(); + comp.setAutoFocusTransferOnDisposal(true); + } + } // If some of the children had focus before disposal then it still has. // Auto-transfer focus to the next (or previous) component if auto-transfer // is enabled. @@ -2683,7 +2651,7 @@ public class Container extends Component { } if ( dispatcher != null ) { dispatcher.dispose(); - dispatcher = null; + dispatcher = null; } super.removeNotify(); } @@ -2873,12 +2841,12 @@ public class Container extends Component { */ public void list(PrintStream out, int indent) { super.list(out, indent); - int ncomponents = this.ncomponents; - Component component[] = this.component; - for (int i = 0 ; i < ncomponents ; i++) { - Component comp = component[i]; - if (comp != null) { - comp.list(out, indent+1); + synchronized(getTreeLock()) { + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); + if (comp != null) { + comp.list(out, indent+1); + } } } } @@ -2899,12 +2867,12 @@ public class Container extends Component { */ public void list(PrintWriter out, int indent) { super.list(out, indent); - int ncomponents = this.ncomponents; - Component component[] = this.component; - for (int i = 0 ; i < ncomponents ; i++) { - Component comp = component[i]; - if (comp != null) { - comp.list(out, indent+1); + synchronized(getTreeLock()) { + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); + if (comp != null) { + comp.list(out, indent+1); + } } } } @@ -3414,9 +3382,11 @@ public class Container extends Component { */ public void applyComponentOrientation(ComponentOrientation o) { super.applyComponentOrientation(o); - - for (int i = 0 ; i < ncomponents ; ++i) { - component[i].applyComponentOrientation(o); + synchronized (getTreeLock()) { + for (int i = 0; i < component.size(); i++) { + Component comp = component.get(i); + comp.applyComponentOrientation(o); + } } } @@ -3534,8 +3504,8 @@ public class Container extends Component { */ private void writeObject(ObjectOutputStream s) throws IOException { ObjectOutputStream.PutField f = s.putFields(); - f.put("ncomponents", ncomponents); - f.put("component", component); + f.put("ncomponents", component.size()); + f.put("component", component.toArray(EMPTY_ARRAY)); f.put("layoutMgr", layoutMgr); f.put("dispatcher", dispatcher); f.put("maxSize", maxSize); @@ -3574,8 +3544,12 @@ public class Container extends Component { throws ClassNotFoundException, IOException { ObjectInputStream.GetField f = s.readFields(); - ncomponents = f.get("ncomponents", 0); - component = (Component[])f.get("component", new Component[0]); + Component [] tmpComponent = (Component[])f.get("component", EMPTY_ARRAY); + int ncomponents = (Integer) f.get("ncomponents", 0); + component = new java.util.ArrayList(ncomponents); + for (int i = 0; i < ncomponents; ++i) { + component.add(tmpComponent[i]); + } layoutMgr = (LayoutManager)f.get("layoutMgr", null); dispatcher = (LightweightDispatcher)f.get("dispatcher", null); // Old stream. Doesn't contain maxSize among Component's fields. @@ -3585,16 +3559,14 @@ public class Container extends Component { focusCycleRoot = f.get("focusCycleRoot", false); containerSerializedDataVersion = f.get("containerSerializedDataVersion", 1); focusTraversalPolicyProvider = f.get("focusTraversalPolicyProvider", false); - - Component component[] = this.component; - for(int i = 0; i < ncomponents; i++) { - component[i].parent = this; + java.util.List component = this.component; + for(Component comp : component) { + comp.parent = this; adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK, - component[i].numListening(AWTEvent.HIERARCHY_EVENT_MASK)); + comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK)); adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, - component[i].numListening( - AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)); - adjustDescendants(component[i].countHierarchyMembers()); + comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)); + adjustDescendants(comp.countHierarchyMembers()); } Object keyOrNull; diff --git a/jdk/src/share/classes/java/awt/ScrollPane.java b/jdk/src/share/classes/java/awt/ScrollPane.java index b34c978474f..99997dba20f 100644 --- a/jdk/src/share/classes/java/awt/ScrollPane.java +++ b/jdk/src/share/classes/java/awt/ScrollPane.java @@ -357,7 +357,7 @@ public class ScrollPane extends Container implements Accessible { */ public void setScrollPosition(int x, int y) { synchronized (getTreeLock()) { - if (ncomponents <= 0) { + if (getComponentCount()==0) { throw new NullPointerException("child is null"); } hAdjustable.setValue(x); @@ -393,10 +393,12 @@ public class ScrollPane extends Container implements Accessible { */ @Transient public Point getScrollPosition() { - if (ncomponents <= 0) { - throw new NullPointerException("child is null"); + synchronized (getTreeLock()) { + if (getComponentCount()==0) { + throw new NullPointerException("child is null"); + } + return new Point(hAdjustable.getValue(), vAdjustable.getValue()); } - return new Point(hAdjustable.getValue(), vAdjustable.getValue()); } /** @@ -486,26 +488,27 @@ public class ScrollPane extends Container implements Accessible { */ @Deprecated public void layout() { - if (ncomponents > 0) { - Component c = getComponent(0); - Point p = getScrollPosition(); - Dimension cs = calculateChildSize(); - Dimension vs = getViewportSize(); - Insets i = getInsets(); - - c.reshape(i.left - p.x, i.top - p.y, cs.width, cs.height); - ScrollPanePeer peer = (ScrollPanePeer)this.peer; - if (peer != null) { - peer.childResized(cs.width, cs.height); - } - - // update adjustables... the viewport size may have changed - // with the scrollbars coming or going so the viewport size - // is updated before the adjustables. - vs = getViewportSize(); - hAdjustable.setSpan(0, cs.width, vs.width); - vAdjustable.setSpan(0, cs.height, vs.height); + if (getComponentCount()==0) { + return; } + Component c = getComponent(0); + Point p = getScrollPosition(); + Dimension cs = calculateChildSize(); + Dimension vs = getViewportSize(); + Insets i = getInsets(); + + c.reshape(i.left - p.x, i.top - p.y, cs.width, cs.height); + ScrollPanePeer peer = (ScrollPanePeer)this.peer; + if (peer != null) { + peer.childResized(cs.width, cs.height); + } + + // update adjustables... the viewport size may have changed + // with the scrollbars coming or going so the viewport size + // is updated before the adjustables. + vs = getViewportSize(); + hAdjustable.setSpan(0, cs.width, vs.width); + vAdjustable.setSpan(0, cs.height, vs.height); } /** @@ -515,20 +518,21 @@ public class ScrollPane extends Container implements Accessible { * @see Component#printAll */ public void printComponents(Graphics g) { - if (ncomponents > 0) { - Component c = component[0]; - Point p = c.getLocation(); - Dimension vs = getViewportSize(); - Insets i = getInsets(); + if (getComponentCount()==0) { + return; + } + Component c = getComponent(0); + Point p = c.getLocation(); + Dimension vs = getViewportSize(); + Insets i = getInsets(); - Graphics cg = g.create(); - try { - cg.clipRect(i.left, i.top, vs.width, vs.height); - cg.translate(p.x, p.y); - c.printAll(cg); - } finally { - cg.dispose(); - } + Graphics cg = g.create(); + try { + cg.clipRect(i.left, i.top, vs.width, vs.height); + cg.translate(p.x, p.y); + c.printAll(cg); + } finally { + cg.dispose(); } } @@ -589,7 +593,7 @@ public class ScrollPane extends Container implements Accessible { default: sdpStr = "invalid display policy"; } - Point p = ncomponents > 0? getScrollPosition() : new Point(0,0); + Point p = (getComponentCount()>0)? getScrollPosition() : new Point(0,0); Insets i = getInsets(); return super.paramString()+",ScrollPosition=("+p.x+","+p.y+")"+ ",Insets=("+i.top+","+i.left+","+i.bottom+","+i.right+")"+ diff --git a/jdk/src/windows/native/sun/windows/awt_Container.cpp b/jdk/src/windows/native/sun/windows/awt_Container.cpp index c136e4bd85e..65ded591096 100644 --- a/jdk/src/windows/native/sun/windows/awt_Container.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Container.cpp @@ -1,5 +1,5 @@ /* - * Copyright 1998-2000 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,8 +30,6 @@ * AwtContainer fields */ -jfieldID AwtContainer::ncomponentsID; -jfieldID AwtContainer::componentID; jfieldID AwtContainer::layoutMgrID; jmethodID AwtContainer::findComponentAtMID; @@ -45,18 +43,12 @@ JNIEXPORT void JNICALL Java_java_awt_Container_initIDs(JNIEnv *env, jclass cls) { TRY; - AwtContainer::ncomponentsID = env->GetFieldID(cls, "ncomponents", "I"); - AwtContainer::componentID = - env->GetFieldID(cls, "component", "[Ljava/awt/Component;"); - AwtContainer::layoutMgrID = env->GetFieldID(cls, "layoutMgr", "Ljava/awt/LayoutManager;"); AwtContainer::findComponentAtMID = env->GetMethodID(cls, "findComponentAt", "(IIZ)Ljava/awt/Component;"); - DASSERT(AwtContainer::ncomponentsID != NULL); - DASSERT(AwtContainer::componentID != NULL); DASSERT(AwtContainer::layoutMgrID != NULL); DASSERT(AwtContainer::findComponentAtMID); diff --git a/jdk/src/windows/native/sun/windows/awt_Container.h b/jdk/src/windows/native/sun/windows/awt_Container.h index a1f244b219a..88dc92d4351 100644 --- a/jdk/src/windows/native/sun/windows/awt_Container.h +++ b/jdk/src/windows/native/sun/windows/awt_Container.h @@ -1,5 +1,5 @@ /* - * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,8 +37,6 @@ class AwtContainer { public: /* java.awt.Container field ids */ - static jfieldID ncomponentsID; - static jfieldID componentID; static jfieldID layoutMgrID; static jmethodID findComponentAtMID; diff --git a/jdk/test/java/awt/Container/CheckZOrderChange/CheckZOrderChange.java b/jdk/test/java/awt/Container/CheckZOrderChange/CheckZOrderChange.java new file mode 100644 index 00000000000..0814b52b25d --- /dev/null +++ b/jdk/test/java/awt/Container/CheckZOrderChange/CheckZOrderChange.java @@ -0,0 +1,48 @@ +/* + @test %I% %E% + @bug 2161766 + @summary Component is missing after changing the z-order of the component & focus is not transfered in + @author Andrei Dmitriev : area=awt.container + @run main CheckZOrderChange +*/ +import java.awt.*; +import java.awt.event.*; + +public class CheckZOrderChange { + + private static Button content[] = new Button[]{new Button("Button 1"), new Button("Button 2"), new Button("Button 3"), new Button("Button 4")}; + private static Frame frame; + + public static void main(String[] args) { + + frame = new Frame("Test Frame"); + frame.setLayout(new FlowLayout()); + + for (Button b: content){ + frame.add(b); + } + + frame.setSize(300, 300); + frame.setVisible(true); + + /* INITIAL ZORDERS ARE*/ + for (Button b: content){ + System.out.println("frame.getComponentZOrder("+ b +") = " + frame.getComponentZOrder(b)); + } + + //Change the Z Order + frame.setComponentZOrder(content[0], 2); + System.out.println("ZOrder of button1 changed to 2"); + + if (frame.getComponentZOrder(content[0]) != 2 || + frame.getComponentZOrder(content[1]) != 0 || + frame.getComponentZOrder(content[2]) != 1 || + frame.getComponentZOrder(content[3]) != 3) + { + for (Button b: content){ + System.out.println("frame.getComponentZOrder("+ b +") = " + frame.getComponentZOrder(b)); + } + throw new RuntimeException("TEST FAILED: getComponentZOrder did not return the correct value"); + } + } +} From 85148f4cf0c6851767624354e865602a2520d0ea Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Wed, 18 Jun 2008 19:20:28 +0400 Subject: [PATCH 005/325] 6716137: Fix 6691328 is broken Reviewed-by: dcherepanov, denis --- jdk/src/share/classes/java/awt/dnd/DragSourceContext.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/jdk/src/share/classes/java/awt/dnd/DragSourceContext.java b/jdk/src/share/classes/java/awt/dnd/DragSourceContext.java index 89d0619b063..07768598fd5 100644 --- a/jdk/src/share/classes/java/awt/dnd/DragSourceContext.java +++ b/jdk/src/share/classes/java/awt/dnd/DragSourceContext.java @@ -486,6 +486,8 @@ public class DragSourceContext Cursor c = null; switch (status) { + default: + targetAct = DnDConstants.ACTION_NONE; case ENTER: case OVER: case CHANGED: @@ -506,10 +508,6 @@ public class DragSourceContext else c = DragSource.DefaultCopyDrop; } - break; - default: - targetAct = DnDConstants.ACTION_NONE; - } setCursorImpl(c); From f8d7c817f6b9a338fb31a2084902804609988740 Mon Sep 17 00:00:00 2001 From: Yuri Nesterenko Date: Thu, 19 Jun 2008 11:26:54 +0400 Subject: [PATCH 006/325] 6706121: makefile: unnecessary Motif classes compilation in JDK7 Removed 80 obsolete .c and .java files, temporary modified some more Reviewed-by: denis --- jdk/make/sun/awt/FILES_c_unix.gmk | 106 +- jdk/make/sun/awt/FILES_export_unix.gmk | 37 +- jdk/make/sun/awt/mapfile-mawt-vers | 486 +- jdk/make/sun/awt/mapfile-vers-linux | 474 +- jdk/make/sun/awt/mawt.gmk | 102 +- jdk/make/sun/jawt/Makefile | 1 - .../classes/sun/awt/motif/MButtonPeer.java | 97 - .../classes/sun/awt/motif/MCanvasPeer.java | 113 - .../sun/awt/motif/MCheckboxMenuItemPeer.java | 93 - .../classes/sun/awt/motif/MCheckboxPeer.java | 187 - .../classes/sun/awt/motif/MChoicePeer.java | 177 - .../classes/sun/awt/motif/MComponentPeer.java | 1182 ---- .../classes/sun/awt/motif/MCustomCursor.java | 68 - .../sun/awt/motif/MDataTransferer.java | 386 -- .../classes/sun/awt/motif/MDialogPeer.java | 110 - .../sun/awt/motif/MDragSourceContextPeer.java | 120 - .../sun/awt/motif/MDropTargetContextPeer.java | 147 - .../sun/awt/motif/MEmbedCanvasPeer.java | 584 -- .../classes/sun/awt/motif/MEmbeddedFrame.java | 141 - .../sun/awt/motif/MEmbeddedFramePeer.java | 213 - .../sun/awt/motif/MFileDialogPeer.java | 300 - .../classes/sun/awt/motif/MFramePeer.java | 511 -- .../sun/awt/motif/MGlobalCursorManager.java | 118 - .../classes/sun/awt/motif/MInputMethod.java | 177 - .../sun/awt/motif/MInputMethodControl.java | 73 - .../sun/awt/motif/MInputMethodDescriptor.java | 48 - .../classes/sun/awt/motif/MLabelPeer.java | 104 - .../classes/sun/awt/motif/MListPeer.java | 390 -- .../classes/sun/awt/motif/MMenuBarPeer.java | 192 - .../classes/sun/awt/motif/MMenuItemPeer.java | 190 - .../classes/sun/awt/motif/MMenuPeer.java | 83 - .../motif/MMouseDragGestureRecognizer.java | 233 - .../classes/sun/awt/motif/MPanelPeer.java | 201 - .../classes/sun/awt/motif/MPopupMenuPeer.java | 132 - .../classes/sun/awt/motif/MRobotPeer.java | 96 - .../sun/awt/motif/MScrollPanePeer.java | 411 -- .../classes/sun/awt/motif/MScrollbarPeer.java | 187 - .../classes/sun/awt/motif/MTextAreaPeer.java | 555 -- .../classes/sun/awt/motif/MTextFieldPeer.java | 356 -- .../classes/sun/awt/motif/MToolkit.java | 237 +- .../classes/sun/awt/motif/MWindowPeer.java | 602 -- .../classes/sun/awt/motif/X11Clipboard.java | 151 - .../awt/motif/X11DragSourceContextPeer.java | 131 - .../awt/motif/X11DropTargetContextPeer.java | 167 - .../classes/sun/awt/motif/X11Selection.java | 203 - .../sun/awt/motif/X11SelectionHolder.java | 33 - jdk/src/solaris/native/sun/awt/awt_Button.c | 276 - jdk/src/solaris/native/sun/awt/awt_Canvas.c | 130 - jdk/src/solaris/native/sun/awt/awt_Checkbox.c | 428 -- jdk/src/solaris/native/sun/awt/awt_Choice12.c | 843 --- jdk/src/solaris/native/sun/awt/awt_Choice21.c | 764 --- .../solaris/native/sun/awt/awt_Component.c | 1656 ------ jdk/src/solaris/native/sun/awt/awt_Cursor.c | 216 - .../native/sun/awt/awt_DataTransferer.c | 1068 ---- .../native/sun/awt/awt_DataTransferer.h | 275 - .../native/sun/awt/awt_DrawingSurface.c | 2 +- .../solaris/native/sun/awt/awt_FileDialog.c | 925 --- .../native/sun/awt/awt_GlobalCursorManager.c | 127 - .../native/sun/awt/awt_KeyboardFocusManager.c | 175 - jdk/src/solaris/native/sun/awt/awt_Label.c | 212 - jdk/src/solaris/native/sun/awt/awt_List.c | 600 -- jdk/src/solaris/native/sun/awt/awt_MToolkit.c | 2 +- jdk/src/solaris/native/sun/awt/awt_Menu.c | 407 -- jdk/src/solaris/native/sun/awt/awt_Menu.h | 32 - jdk/src/solaris/native/sun/awt/awt_MenuBar.c | 198 - jdk/src/solaris/native/sun/awt/awt_MenuBar.h | 30 - .../native/sun/awt/awt_MenuComponent.c | 48 - jdk/src/solaris/native/sun/awt/awt_MenuItem.c | 654 --- .../solaris/native/sun/awt/awt_PopupMenu.c | 491 -- jdk/src/solaris/native/sun/awt/awt_Robot.c | 22 +- .../solaris/native/sun/awt/awt_ScrollPane.c | 927 --- .../solaris/native/sun/awt/awt_Scrollbar.c | 440 -- .../solaris/native/sun/awt/awt_Selection.c | 508 -- jdk/src/solaris/native/sun/awt/awt_TextArea.c | 1003 ---- jdk/src/solaris/native/sun/awt/awt_TextArea.h | 36 - .../solaris/native/sun/awt/awt_TextField.c | 989 ---- .../solaris/native/sun/awt/awt_TextField.h | 36 - jdk/src/solaris/native/sun/awt/awt_TopLevel.c | 5095 ----------------- jdk/src/solaris/native/sun/awt/awt_XmDnD.c | 2282 -------- jdk/src/solaris/native/sun/awt/awt_XmDnD.h | 41 - jdk/src/solaris/native/sun/awt/awt_dnd.c | 887 --- jdk/src/solaris/native/sun/awt/awt_dnd.h | 242 - jdk/src/solaris/native/sun/awt/awt_dnd_ds.c | 1796 ------ jdk/src/solaris/native/sun/awt/awt_dnd_dt.c | 3700 ------------ jdk/src/solaris/native/sun/awt/awt_motif.c | 58 - jdk/src/solaris/native/sun/awt/awt_motif12.c | 435 -- jdk/src/solaris/native/sun/awt/awt_motif21.c | 234 - jdk/src/solaris/native/sun/awt/awt_p.h | 2 +- jdk/src/solaris/native/sun/awt/awt_xembed.c | 430 -- jdk/src/solaris/native/sun/awt/canvas.c | 3227 ----------- jdk/src/solaris/native/sun/awt/cursor.c | 132 - jdk/src/solaris/native/sun/awt/initIDs.c | 2 +- jdk/src/solaris/native/sun/awt/multi_font.c | 8 +- 93 files changed, 729 insertions(+), 42067 deletions(-) delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MButtonPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MCanvasPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MCheckboxMenuItemPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MCheckboxPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MChoicePeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MComponentPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MCustomCursor.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MDataTransferer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MDialogPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MDragSourceContextPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MDropTargetContextPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MEmbedCanvasPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MEmbeddedFrame.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MEmbeddedFramePeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MFileDialogPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MFramePeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MGlobalCursorManager.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MInputMethod.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MInputMethodControl.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MInputMethodDescriptor.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MLabelPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MListPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MMenuBarPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MMenuItemPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MMenuPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MMouseDragGestureRecognizer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MPanelPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MPopupMenuPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MRobotPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MScrollPanePeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MScrollbarPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MTextAreaPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MTextFieldPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/MWindowPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/X11Clipboard.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/X11DragSourceContextPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/X11DropTargetContextPeer.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/X11Selection.java delete mode 100644 jdk/src/solaris/classes/sun/awt/motif/X11SelectionHolder.java delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Button.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Canvas.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Checkbox.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Choice12.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Choice21.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Component.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Cursor.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_DataTransferer.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_DataTransferer.h delete mode 100644 jdk/src/solaris/native/sun/awt/awt_FileDialog.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_GlobalCursorManager.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_KeyboardFocusManager.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Label.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_List.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Menu.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Menu.h delete mode 100644 jdk/src/solaris/native/sun/awt/awt_MenuBar.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_MenuBar.h delete mode 100644 jdk/src/solaris/native/sun/awt/awt_MenuComponent.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_MenuItem.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_PopupMenu.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_ScrollPane.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Scrollbar.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_Selection.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_TextArea.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_TextArea.h delete mode 100644 jdk/src/solaris/native/sun/awt/awt_TextField.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_TextField.h delete mode 100644 jdk/src/solaris/native/sun/awt/awt_TopLevel.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_XmDnD.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_XmDnD.h delete mode 100644 jdk/src/solaris/native/sun/awt/awt_dnd.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_dnd.h delete mode 100644 jdk/src/solaris/native/sun/awt/awt_dnd_ds.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_dnd_dt.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_motif.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_motif12.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_motif21.c delete mode 100644 jdk/src/solaris/native/sun/awt/awt_xembed.c delete mode 100644 jdk/src/solaris/native/sun/awt/canvas.c delete mode 100644 jdk/src/solaris/native/sun/awt/cursor.c diff --git a/jdk/make/sun/awt/FILES_c_unix.gmk b/jdk/make/sun/awt/FILES_c_unix.gmk index c7ea9857da0..f85635f00fb 100644 --- a/jdk/make/sun/awt/FILES_c_unix.gmk +++ b/jdk/make/sun/awt/FILES_c_unix.gmk @@ -142,59 +142,59 @@ FILES_2D_c = \ # These files rely on motif to be built, and should not be included # in a headless build. -FILES_MOTIF_c = \ - awt_AWTEvent.c \ - awt_Button.c \ - awt_Canvas.c \ - awt_Checkbox.c \ - awt_Component.c \ - awt_Cursor.c \ - awt_DataTransferer.c \ - awt_DrawingSurface.c \ - awt_Event.c \ - awt_FileDialog.c \ - awt_GlobalCursorManager.c \ - awt_GraphicsEnv.c \ - awt_InputMethod.c \ - awt_Insets.c \ - awt_KeyboardFocusManager.c \ - awt_Label.c \ - awt_List.c \ - awt_Menu.c \ - awt_MenuBar.c \ - awt_MenuComponent.c \ - awt_MenuItem.c \ - awt_motif.c \ - awt_Plugin.c \ - awt_PopupMenu.c \ - awt_Robot.c \ - awt_Scrollbar.c \ - awt_ScrollPane.c \ - awt_Selection.c \ - awt_UNIXToolkit.c \ - awt_TextArea.c \ - awt_TextField.c \ - awt_TopLevel.c \ - awt_mgrsel.c \ - awt_util.c \ - awt_wm.c \ - awt_XmDnD.c \ - awt_dnd.c \ - awt_dnd_ds.c \ - awt_dnd_dt.c \ - canvas.c \ - cursor.c \ - multi_font.c \ - robot_common.c \ - list.c \ - multiVis.c \ - XDrawingArea.c \ - MouseInfo.c \ - awt_xembed.c \ - awt_xembed_server.c \ - gtk2_interface.c \ - swing_GTKEngine.c \ - swing_GTKStyle.c +#FILES_MOTIF_c = \ +#keep awt_AWTEvent.c \ +# awt_Button.c \ +# awt_Canvas.c \ +# awt_Checkbox.c \ +#keep .h awt_Component.c \ +#keep .h awt_Cursor.c \ +# awt_DataTransferer.c \ +# awt_DrawingSurface.c \ +# awt_Event.c \ +# awt_FileDialog.c \ +# awt_GlobalCursorManager.c \ +# awt_GraphicsEnv.c \ +# awt_InputMethod.c \ +#keep awt_Insets.c \ +# awt_KeyboardFocusManager.c \ +# awt_Label.c \ +# awt_List.c \ +# awt_Menu.c \ +# awt_MenuBar.c \ +# awt_MenuComponent.c \ +# awt_MenuItem.c \ +# awt_motif.c \ +# awt_Plugin.c \ +# awt_PopupMenu.c \ +# awt_Robot.c \ +# awt_Scrollbar.c \ +# awt_ScrollPane.c \ +# awt_Selection.c \ +# awt_UNIXToolkit.c \ +# awt_TextArea.c \ +# awt_TextField.c \ +# awt_TopLevel.c \ +# awt_mgrsel.c \ +# awt_util.c \ +# awt_wm.c \ +# awt_XmDnD.c \ +# awt_dnd.c \ +# awt_dnd_ds.c \ +# awt_dnd_dt.c \ +# canvas.c \ +# cursor.c \ +# multi_font.c \ +# robot_common.c \ +# list.c \ +# multiVis.c \ +# XDrawingArea.c \ +# MouseInfo.c \ +# awt_xembed.c \ +# awt_xembed_server.c \ +# gtk2_interface.c \ +# swing_GTKEngine.c \ +# swing_GTKStyle.c # These files are required to be built, with or without motif. Some of diff --git a/jdk/make/sun/awt/FILES_export_unix.gmk b/jdk/make/sun/awt/FILES_export_unix.gmk index fba920be993..f20666caaf0 100644 --- a/jdk/make/sun/awt/FILES_export_unix.gmk +++ b/jdk/make/sun/awt/FILES_export_unix.gmk @@ -57,48 +57,15 @@ FILES_export = \ sun/awt/image/DataBufferNative.java \ \ sun/awt/motif/X11FontMetrics.java \ - sun/awt/motif/X11Clipboard.java \ - sun/awt/motif/X11Selection.java \ - sun/awt/motif/X11SelectionHolder.java \ sun/awt/X11InputMethod.java \ - sun/awt/motif/MInputMethod.java \ - sun/awt/motif/MInputMethodControl.java \ - sun/awt/motif/MCustomCursor.java \ sun/awt/motif/MFontConfiguration.java \ sun/awt/motif/MFontPeer.java \ sun/awt/motif/MToolkit.java \ - sun/awt/motif/MComponentPeer.java \ - sun/awt/motif/MButtonPeer.java \ - sun/awt/motif/MCanvasPeer.java \ - sun/awt/motif/MCheckboxPeer.java \ - sun/awt/motif/MFileDialogPeer.java \ - sun/awt/motif/MGlobalCursorManager.java \ - sun/awt/motif/MTextFieldPeer.java \ - sun/awt/motif/MLabelPeer.java \ - sun/awt/motif/MListPeer.java \ - sun/awt/motif/MWindowPeer.java \ - sun/awt/motif/MMenuBarPeer.java \ - sun/awt/motif/MMenuPeer.java \ - sun/awt/motif/MPopupMenuPeer.java \ - sun/awt/motif/MDialogPeer.java \ - sun/awt/motif/MMenuItemPeer.java \ - sun/awt/motif/MCheckboxMenuItemPeer.java \ - sun/awt/motif/MChoicePeer.java \ - sun/awt/motif/MTextAreaPeer.java \ - sun/awt/motif/MScrollbarPeer.java \ - sun/awt/motif/MScrollPanePeer.java \ - sun/awt/motif/MFramePeer.java \ sun/awt/DebugSettings.java \ sun/awt/EmbeddedFrame.java \ - sun/awt/motif/MEmbeddedFramePeer.java \ sun/awt/PlatformFont.java \ sun/awt/FontDescriptor.java \ sun/awt/NativeLibLoader.java \ - sun/awt/motif/MDropTargetContextPeer.java \ - sun/awt/motif/MDragSourceContextPeer.java \ - sun/awt/motif/MRobotPeer.java \ - sun/awt/motif/X11DragSourceContextPeer.java \ - sun/awt/motif/X11DropTargetContextPeer.java \ sun/awt/X11GraphicsEnvironment.java \ sun/awt/X11GraphicsDevice.java \ sun/awt/X11GraphicsConfig.java \ @@ -120,7 +87,6 @@ FILES_export = \ sun/java2d/cmm/ColorTransform.java \ sun/awt/datatransfer/DataTransferer.java \ sun/awt/dnd/SunDragSourceContextPeer.java \ - sun/awt/motif/MDataTransferer.java \ sun/awt/motif/MToolkitThreadBlockedHandler.java \ sun/java2d/opengl/OGLBlitLoops.java \ sun/java2d/opengl/OGLContext.java \ @@ -216,6 +182,5 @@ FILES_export2 = \ java/awt/event/NativeLibLoader.java \ java/awt/peer/ComponentPeer.java \ java/awt/dnd/DnDConstants.java \ - sun/awt/CausedFocusEvent.java \ - sun/awt/motif/MEmbedCanvasPeer.java + sun/awt/CausedFocusEvent.java diff --git a/jdk/make/sun/awt/mapfile-mawt-vers b/jdk/make/sun/awt/mapfile-mawt-vers index 9b46be89f6f..8e4d99c562c 100644 --- a/jdk/make/sun/awt/mapfile-mawt-vers +++ b/jdk/make/sun/awt/mapfile-mawt-vers @@ -31,7 +31,7 @@ SUNWprivate_1.1 { global: JNI_OnLoad; - Java_sun_awt_motif_MComponentPeer_restoreFocus; + #Java_sun_awt_motif_MComponentPeer_restoreFocus; Java_sun_awt_DefaultMouseInfoPeer_fillPointWithCoords; Java_sun_awt_DefaultMouseInfoPeer_isWindowUnderMouse; Java_java_awt_AWTEvent_nativeSetSource; @@ -56,163 +56,163 @@ SUNWprivate_1.1 { Java_sun_awt_UNIXToolkit_load_1stock_1icon; Java_sun_awt_UNIXToolkit_load_1gtk_1icon; Java_sun_awt_UNIXToolkit_nativeSync; - Java_sun_awt_motif_MButtonPeer_create; - Java_sun_awt_motif_MButtonPeer_setLabel; - Java_sun_awt_motif_MPanelPeer_pEnsureIndex; - Java_sun_awt_motif_MPanelPeer_pRestack; - Java_sun_awt_motif_MCanvasPeer_create; - Java_sun_awt_motif_MCanvasPeer_initIDs; - Java_sun_awt_motif_MCanvasPeer_resetTargetGC; - Java_sun_awt_motif_MCheckboxMenuItemPeer_pSetState; - Java_sun_awt_motif_MCheckboxPeer_create; - Java_sun_awt_motif_MCheckboxPeer_setCheckboxGroup; - Java_sun_awt_motif_MCheckboxPeer_setLabel; - Java_sun_awt_motif_MCheckboxPeer_pSetState; - Java_sun_awt_motif_MCheckboxPeer_pGetState; - Java_sun_awt_motif_MChoicePeer_addItem; - Java_sun_awt_motif_MChoicePeer_appendItems; - Java_sun_awt_motif_MChoicePeer_create; - Java_sun_awt_motif_MChoicePeer_pReshape; - Java_sun_awt_motif_MChoicePeer_remove; - Java_sun_awt_motif_MChoicePeer_removeAll; - Java_sun_awt_motif_MChoicePeer_setBackground; - Java_sun_awt_motif_MChoicePeer_pSelect; - Java_sun_awt_motif_MChoicePeer_setFont; - Java_sun_awt_motif_MChoicePeer_setForeground; - Java_sun_awt_motif_MComponentPeer_addNativeDropTarget; - Java_sun_awt_motif_MComponentPeer_getNativeColor; - Java_sun_awt_motif_MComponentPeer_getWindow; - Java_sun_awt_motif_MComponentPeer_pDisable; - Java_sun_awt_motif_MComponentPeer_pDispose; - Java_sun_awt_motif_MComponentPeer_pEnable; - Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen; - Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen2; - Java_sun_awt_motif_MComponentPeer_pHide; - Java_sun_awt_motif_MComponentPeer_pInitialize; - Java_sun_awt_motif_MComponentPeer_pMakeCursorVisible; - Java_sun_awt_motif_MComponentPeer_pReshape; - Java_sun_awt_motif_MComponentPeer_pShow; - Java_sun_awt_motif_MComponentPeer_removeNativeDropTarget; - Java_sun_awt_motif_MComponentPeer_pSetBackground; - Java_sun_awt_motif_MComponentPeer_pSetFont; - Java_sun_awt_motif_MComponentPeer_processSynchronousLightweightTransfer; - Java_sun_awt_motif_MComponentPeer__1requestFocus; - Java_sun_awt_motif_MComponentPeer_getNativeFocusedWindow; - Java_sun_awt_motif_MCheckboxMenuItemPeer_getState; - Java_sun_awt_motif_MComponentPeer_pSetForeground; - Java_sun_awt_motif_MDragSourceContextPeer_startDrag; - Java_sun_awt_motif_MDragSourceContextPeer_setNativeCursor; - Java_sun_awt_motif_MDropTargetContextPeer_addTransfer; - Java_sun_awt_motif_MDropTargetContextPeer_dropDone; - Java_sun_awt_motif_MDropTargetContextPeer_startTransfer; - Java_sun_awt_motif_X11DragSourceContextPeer_startDrag; - Java_sun_awt_motif_X11DragSourceContextPeer_setNativeCursor; - Java_sun_awt_motif_X11DropTargetContextPeer_sendResponse; - Java_sun_awt_motif_X11DropTargetContextPeer_dropDone; - Java_sun_awt_motif_X11DropTargetContextPeer_getData; - Java_sun_awt_motif_MEmbeddedFramePeer_NEFcreate; - Java_sun_awt_motif_MEmbeddedFramePeer_pShowImpl; - Java_sun_awt_motif_MEmbeddedFramePeer_requestXEmbedFocus; - Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedApplicationActive; - Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedActive; - Java_sun_awt_motif_MEmbeddedFramePeer_synthesizeFocusInOut; - Java_sun_awt_motif_MEmbeddedFramePeer_pReshapePrivate; - Java_sun_awt_motif_MEmbeddedFramePeer_getBoundsPrivate; - Java_sun_awt_motif_MEmbeddedFrame_getWidget; - Java_sun_awt_motif_MEmbeddedFrame_mapWidget; - Java_sun_awt_motif_MEmbedCanvasPeer_forwardEventToEmbedded; - Java_sun_awt_motif_MFramePeer_pSetIconImage___3B_3I_3SII; - Java_sun_awt_motif_MFileDialogPeer_create; - Java_sun_awt_motif_MFileDialogPeer_pDispose; - Java_sun_awt_motif_MFileDialogPeer_pHide; - Java_sun_awt_motif_MFileDialogPeer_pReshape; - Java_sun_awt_motif_MFileDialogPeer_pShow; - Java_sun_awt_motif_MFileDialogPeer_setFileEntry; - Java_sun_awt_motif_MFileDialogPeer_setFont; - Java_sun_awt_motif_MFramePeer_pGetIconSize; - Java_sun_awt_motif_MGlobalCursorManager_cacheInit; - Java_sun_awt_motif_MGlobalCursorManager_findComponentAt; - Java_sun_awt_motif_MGlobalCursorManager_findHeavyweightUnderCursor; - Java_sun_awt_motif_MGlobalCursorManager_getCursorPos; - Java_sun_awt_motif_MGlobalCursorManager_getLocationOnScreen; - Java_sun_awt_motif_MLabelPeer_create; - Java_sun_awt_motif_MLabelPeer_setAlignment; - Java_sun_awt_motif_MLabelPeer_setText; - Java_sun_awt_motif_MListPeer_addItem; - Java_sun_awt_motif_MListPeer_create; - Java_sun_awt_motif_MListPeer_delItems; - Java_sun_awt_motif_MListPeer_deselect; - Java_sun_awt_motif_MListPeer_isSelected; - Java_sun_awt_motif_MListPeer_makeVisible; - Java_sun_awt_motif_MListPeer_nativeHandleMouseWheel; - Java_sun_awt_motif_MListPeer_select; - Java_sun_awt_motif_MListPeer_setMultipleSelections; - Java_sun_awt_motif_MMenuBarPeer_create; - Java_sun_awt_motif_MMenuItemPeer_createMenuItem; - Java_sun_awt_motif_MMenuItemPeer_pDisable; - Java_sun_awt_motif_MMenuItemPeer_pDispose; - Java_sun_awt_motif_MMenuItemPeer_pEnable; - Java_sun_awt_motif_MMenuItemPeer_pSetLabel; - Java_sun_awt_motif_MMenuPeer_createMenu; - Java_sun_awt_motif_MMenuPeer_createSubMenu; - Java_sun_awt_motif_MMenuPeer_pDispose; - Java_sun_awt_motif_MPopupMenuPeer_createMenu; - Java_sun_awt_motif_MPopupMenuPeer_pDispose; - Java_sun_awt_motif_MPopupMenuPeer_pShow; - Java_sun_awt_motif_MRobotPeer_getRGBPixelsImpl; - Java_sun_awt_motif_MRobotPeer_keyPressImpl; - Java_sun_awt_motif_MRobotPeer_keyReleaseImpl; - Java_sun_awt_motif_MRobotPeer_mouseMoveImpl; - Java_sun_awt_motif_MRobotPeer_mousePressImpl; - Java_sun_awt_motif_MRobotPeer_mouseReleaseImpl; - Java_sun_awt_motif_MRobotPeer_mouseWheelImpl; - Java_sun_awt_motif_MRobotPeer_setup; - Java_sun_awt_motif_MScrollbarPeer_create; - Java_sun_awt_motif_MScrollbarPeer_setLineIncrement; - Java_sun_awt_motif_MScrollbarPeer_setPageIncrement; - Java_sun_awt_motif_MScrollbarPeer_pSetValues; - Java_sun_awt_motif_MScrollPanePeer_create; - Java_sun_awt_motif_MScrollPanePeer_pGetBlockIncrement; - Java_sun_awt_motif_MScrollPanePeer_pGetScrollbarSpace; - Java_sun_awt_motif_MScrollPanePeer_pGetShadow; - Java_sun_awt_motif_MScrollPanePeer_pInsets; - Java_sun_awt_motif_MScrollPanePeer_pSetIncrement; - Java_sun_awt_motif_MScrollPanePeer_pSetScrollChild; - Java_sun_awt_motif_MScrollPanePeer_setScrollPosition; - Java_sun_awt_motif_MScrollPanePeer_setTypedValue; - Java_sun_awt_motif_MTextAreaPeer_initIDs; - Java_sun_awt_motif_MTextAreaPeer_pCreate; - Java_sun_awt_motif_MTextAreaPeer_getCaretPosition; - Java_sun_awt_motif_MTextAreaPeer_getExtraHeight; - Java_sun_awt_motif_MTextAreaPeer_getExtraWidth; - Java_sun_awt_motif_MTextAreaPeer_getSelectionEnd; - Java_sun_awt_motif_MTextAreaPeer_getSelectionStart; - Java_sun_awt_motif_MTextAreaPeer_getText; - Java_sun_awt_motif_MTextAreaPeer_insert; - Java_sun_awt_motif_MTextAreaPeer_nativeHandleMouseWheel; - Java_sun_awt_motif_MTextAreaPeer_pMakeCursorVisible; - Java_sun_awt_motif_MTextAreaPeer_pSetEditable; - Java_sun_awt_motif_MTextAreaPeer_pShow2; - Java_sun_awt_motif_MTextAreaPeer_replaceRange; - Java_sun_awt_motif_MTextAreaPeer_select; - Java_sun_awt_motif_MTextAreaPeer_setCaretPosition; - Java_sun_awt_motif_MTextAreaPeer_setFont; - Java_sun_awt_motif_MTextAreaPeer_setText; - Java_sun_awt_motif_MTextAreaPeer_setTextBackground; - Java_sun_awt_motif_MTextFieldPeer_initIDs; - Java_sun_awt_motif_MTextFieldPeer_pCreate; - Java_sun_awt_motif_MTextFieldPeer_getCaretPosition; - Java_sun_awt_motif_MTextFieldPeer_getSelectionEnd; - Java_sun_awt_motif_MTextFieldPeer_getSelectionStart; - Java_sun_awt_motif_MTextFieldPeer_getText; - Java_sun_awt_motif_MTextFieldPeer_insertReplaceText; - Java_sun_awt_motif_MTextFieldPeer_preDispose; - Java_sun_awt_motif_MTextFieldPeer_pSetEditable; - Java_sun_awt_motif_MTextFieldPeer_select; - Java_sun_awt_motif_MTextFieldPeer_setCaretPosition; - Java_sun_awt_motif_MTextFieldPeer_setEchoChar; - Java_sun_awt_motif_MTextFieldPeer_setFont; - Java_sun_awt_motif_MTextFieldPeer_setText; + #Java_sun_awt_motif_MButtonPeer_create; + #Java_sun_awt_motif_MButtonPeer_setLabel; + #Java_sun_awt_motif_MPanelPeer_pEnsureIndex; + #Java_sun_awt_motif_MPanelPeer_pRestack; + #Java_sun_awt_motif_MCanvasPeer_create; + #Java_sun_awt_motif_MCanvasPeer_initIDs; + #Java_sun_awt_motif_MCanvasPeer_resetTargetGC; + #Java_sun_awt_motif_MCheckboxMenuItemPeer_pSetState; + #Java_sun_awt_motif_MCheckboxPeer_create; + #Java_sun_awt_motif_MCheckboxPeer_setCheckboxGroup; + #Java_sun_awt_motif_MCheckboxPeer_setLabel; + #Java_sun_awt_motif_MCheckboxPeer_pSetState; + #Java_sun_awt_motif_MCheckboxPeer_pGetState; + #Java_sun_awt_motif_MChoicePeer_addItem; + #Java_sun_awt_motif_MChoicePeer_appendItems; + #Java_sun_awt_motif_MChoicePeer_create; + #Java_sun_awt_motif_MChoicePeer_pReshape; + #Java_sun_awt_motif_MChoicePeer_remove; + #Java_sun_awt_motif_MChoicePeer_removeAll; + #Java_sun_awt_motif_MChoicePeer_setBackground; + #Java_sun_awt_motif_MChoicePeer_pSelect; + #Java_sun_awt_motif_MChoicePeer_setFont; + #Java_sun_awt_motif_MChoicePeer_setForeground; + #Java_sun_awt_motif_MComponentPeer_addNativeDropTarget; + #Java_sun_awt_motif_MComponentPeer_getNativeColor; + #Java_sun_awt_motif_MComponentPeer_getWindow; + #Java_sun_awt_motif_MComponentPeer_pDisable; + #Java_sun_awt_motif_MComponentPeer_pDispose; + #Java_sun_awt_motif_MComponentPeer_pEnable; + #Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen; + #Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen2; + #Java_sun_awt_motif_MComponentPeer_pHide; + #Java_sun_awt_motif_MComponentPeer_pInitialize; + #Java_sun_awt_motif_MComponentPeer_pMakeCursorVisible; + #Java_sun_awt_motif_MComponentPeer_pReshape; + #Java_sun_awt_motif_MComponentPeer_pShow; + #Java_sun_awt_motif_MComponentPeer_removeNativeDropTarget; + #Java_sun_awt_motif_MComponentPeer_pSetBackground; + #Java_sun_awt_motif_MComponentPeer_pSetFont; + #Java_sun_awt_motif_MComponentPeer_processSynchronousLightweightTransfer; + #Java_sun_awt_motif_MComponentPeer__1requestFocus; + #Java_sun_awt_motif_MComponentPeer_getNativeFocusedWindow; + #Java_sun_awt_motif_MCheckboxMenuItemPeer_getState; + #Java_sun_awt_motif_MComponentPeer_pSetForeground; + #Java_sun_awt_motif_MDragSourceContextPeer_startDrag; + #Java_sun_awt_motif_MDragSourceContextPeer_setNativeCursor; + #Java_sun_awt_motif_MDropTargetContextPeer_addTransfer; + #Java_sun_awt_motif_MDropTargetContextPeer_dropDone; + #Java_sun_awt_motif_MDropTargetContextPeer_startTransfer; + #Java_sun_awt_motif_X11DragSourceContextPeer_startDrag; + #Java_sun_awt_motif_X11DragSourceContextPeer_setNativeCursor; + #Java_sun_awt_motif_X11DropTargetContextPeer_sendResponse; + #Java_sun_awt_motif_X11DropTargetContextPeer_dropDone; + #Java_sun_awt_motif_X11DropTargetContextPeer_getData; + #Java_sun_awt_motif_MEmbeddedFramePeer_NEFcreate; + #Java_sun_awt_motif_MEmbeddedFramePeer_pShowImpl; + #Java_sun_awt_motif_MEmbeddedFramePeer_requestXEmbedFocus; + #Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedApplicationActive; + #Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedActive; + #Java_sun_awt_motif_MEmbeddedFramePeer_synthesizeFocusInOut; + #Java_sun_awt_motif_MEmbeddedFramePeer_pReshapePrivate; + #Java_sun_awt_motif_MEmbeddedFramePeer_getBoundsPrivate; + #Java_sun_awt_motif_MEmbeddedFrame_getWidget; + #Java_sun_awt_motif_MEmbeddedFrame_mapWidget; + #Java_sun_awt_motif_MEmbedCanvasPeer_forwardEventToEmbedded; + #Java_sun_awt_motif_MFramePeer_pSetIconImage___3B_3I_3SII; + #Java_sun_awt_motif_MFileDialogPeer_create; + #Java_sun_awt_motif_MFileDialogPeer_pDispose; + #Java_sun_awt_motif_MFileDialogPeer_pHide; + #Java_sun_awt_motif_MFileDialogPeer_pReshape; + #Java_sun_awt_motif_MFileDialogPeer_pShow; + #Java_sun_awt_motif_MFileDialogPeer_setFileEntry; + #Java_sun_awt_motif_MFileDialogPeer_setFont; + #Java_sun_awt_motif_MFramePeer_pGetIconSize; + #Java_sun_awt_motif_MGlobalCursorManager_cacheInit; + #Java_sun_awt_motif_MGlobalCursorManager_findComponentAt; + #Java_sun_awt_motif_MGlobalCursorManager_findHeavyweightUnderCursor; + #Java_sun_awt_motif_MGlobalCursorManager_getCursorPos; + #Java_sun_awt_motif_MGlobalCursorManager_getLocationOnScreen; + #Java_sun_awt_motif_MLabelPeer_create; + #Java_sun_awt_motif_MLabelPeer_setAlignment; + #Java_sun_awt_motif_MLabelPeer_setText; + #Java_sun_awt_motif_MListPeer_addItem; + #Java_sun_awt_motif_MListPeer_create; + #Java_sun_awt_motif_MListPeer_delItems; + #Java_sun_awt_motif_MListPeer_deselect; + #Java_sun_awt_motif_MListPeer_isSelected; + #Java_sun_awt_motif_MListPeer_makeVisible; + #Java_sun_awt_motif_MListPeer_nativeHandleMouseWheel; + #Java_sun_awt_motif_MListPeer_select; + #Java_sun_awt_motif_MListPeer_setMultipleSelections; + #Java_sun_awt_motif_MMenuBarPeer_create; + #Java_sun_awt_motif_MMenuItemPeer_createMenuItem; + #Java_sun_awt_motif_MMenuItemPeer_pDisable; + #Java_sun_awt_motif_MMenuItemPeer_pDispose; + #Java_sun_awt_motif_MMenuItemPeer_pEnable; + #Java_sun_awt_motif_MMenuItemPeer_pSetLabel; + #Java_sun_awt_motif_MMenuPeer_createMenu; + #Java_sun_awt_motif_MMenuPeer_createSubMenu; + #Java_sun_awt_motif_MMenuPeer_pDispose; + #Java_sun_awt_motif_MPopupMenuPeer_createMenu; + #Java_sun_awt_motif_MPopupMenuPeer_pDispose; + #Java_sun_awt_motif_MPopupMenuPeer_pShow; + #Java_sun_awt_motif_MRobotPeer_getRGBPixelsImpl; + #Java_sun_awt_motif_MRobotPeer_keyPressImpl; + #Java_sun_awt_motif_MRobotPeer_keyReleaseImpl; + #Java_sun_awt_motif_MRobotPeer_mouseMoveImpl; + #Java_sun_awt_motif_MRobotPeer_mousePressImpl; + #Java_sun_awt_motif_MRobotPeer_mouseReleaseImpl; + #Java_sun_awt_motif_MRobotPeer_mouseWheelImpl; + #Java_sun_awt_motif_MRobotPeer_setup; + #Java_sun_awt_motif_MScrollbarPeer_create; + #Java_sun_awt_motif_MScrollbarPeer_setLineIncrement; + #Java_sun_awt_motif_MScrollbarPeer_setPageIncrement; + #Java_sun_awt_motif_MScrollbarPeer_pSetValues; + #Java_sun_awt_motif_MScrollPanePeer_create; + #Java_sun_awt_motif_MScrollPanePeer_pGetBlockIncrement; + #Java_sun_awt_motif_MScrollPanePeer_pGetScrollbarSpace; + #Java_sun_awt_motif_MScrollPanePeer_pGetShadow; + #Java_sun_awt_motif_MScrollPanePeer_pInsets; + #Java_sun_awt_motif_MScrollPanePeer_pSetIncrement; + #Java_sun_awt_motif_MScrollPanePeer_pSetScrollChild; + #Java_sun_awt_motif_MScrollPanePeer_setScrollPosition; + #Java_sun_awt_motif_MScrollPanePeer_setTypedValue; + #Java_sun_awt_motif_MTextAreaPeer_initIDs; + #Java_sun_awt_motif_MTextAreaPeer_pCreate; + #Java_sun_awt_motif_MTextAreaPeer_getCaretPosition; + #Java_sun_awt_motif_MTextAreaPeer_getExtraHeight; + #Java_sun_awt_motif_MTextAreaPeer_getExtraWidth; + #Java_sun_awt_motif_MTextAreaPeer_getSelectionEnd; + #Java_sun_awt_motif_MTextAreaPeer_getSelectionStart; + #Java_sun_awt_motif_MTextAreaPeer_getText; + #Java_sun_awt_motif_MTextAreaPeer_insert; + #Java_sun_awt_motif_MTextAreaPeer_nativeHandleMouseWheel; + #Java_sun_awt_motif_MTextAreaPeer_pMakeCursorVisible; + #Java_sun_awt_motif_MTextAreaPeer_pSetEditable; + #Java_sun_awt_motif_MTextAreaPeer_pShow2; + #Java_sun_awt_motif_MTextAreaPeer_replaceRange; + #Java_sun_awt_motif_MTextAreaPeer_select; + #Java_sun_awt_motif_MTextAreaPeer_setCaretPosition; + #Java_sun_awt_motif_MTextAreaPeer_setFont; + #Java_sun_awt_motif_MTextAreaPeer_setText; + #Java_sun_awt_motif_MTextAreaPeer_setTextBackground; + #Java_sun_awt_motif_MTextFieldPeer_initIDs; + #Java_sun_awt_motif_MTextFieldPeer_pCreate; + #Java_sun_awt_motif_MTextFieldPeer_getCaretPosition; + #Java_sun_awt_motif_MTextFieldPeer_getSelectionEnd; + #Java_sun_awt_motif_MTextFieldPeer_getSelectionStart; + #Java_sun_awt_motif_MTextFieldPeer_getText; + #Java_sun_awt_motif_MTextFieldPeer_insertReplaceText; + #Java_sun_awt_motif_MTextFieldPeer_preDispose; + #Java_sun_awt_motif_MTextFieldPeer_pSetEditable; + #Java_sun_awt_motif_MTextFieldPeer_select; + #Java_sun_awt_motif_MTextFieldPeer_setCaretPosition; + #Java_sun_awt_motif_MTextFieldPeer_setEchoChar; + #Java_sun_awt_motif_MTextFieldPeer_setFont; + #Java_sun_awt_motif_MTextFieldPeer_setText; Java_sun_awt_motif_MToolkit_beep; Java_sun_awt_motif_MToolkit_getLockingKeyStateNative; Java_sun_awt_motif_MToolkit_getMulticlickTime; @@ -236,30 +236,30 @@ SUNWprivate_1.1 { Java_sun_awt_motif_MToolkit_nativeGrab; Java_sun_awt_motif_MToolkit_getWMName; Java_sun_awt_motif_MWindowAttributes_initIDs; - Java_sun_awt_motif_MWindowPeer_pDispose; - Java_sun_awt_motif_MWindowPeer_pHide; - Java_sun_awt_motif_MWindowPeer_pReshape; - Java_sun_awt_motif_MWindowPeer_pSetTitle; - Java_sun_awt_motif_MWindowPeer_pShow; - Java_sun_awt_motif_MWindowPeer_setResizable; - Java_sun_awt_motif_MWindowPeer_toBack; - Java_sun_awt_motif_MWindowPeer_addTextComponentNative; - Java_sun_awt_motif_MWindowPeer_getState; - Java_sun_awt_motif_MWindowPeer_pSetIMMOption; - Java_sun_awt_motif_MWindowPeer_pSetMenuBar; - Java_sun_awt_motif_MWindowPeer_pShowModal; - Java_sun_awt_motif_MWindowPeer_removeTextComponentNative; - Java_sun_awt_motif_MWindowPeer_setSaveUnder; - Java_sun_awt_motif_MWindowPeer_setState; - Java_sun_awt_motif_MWindowPeer_resetTargetGC; - Java_sun_awt_motif_MWindowPeer_registerX11DropTarget; - Java_sun_awt_motif_MWindowPeer_unregisterX11DropTarget; - Java_sun_awt_motif_MWindowPeer_updateAlwaysOnTop; - Java_sun_awt_motif_MWindowPeer_setFocusableWindow; - Java_sun_awt_motif_MWindowPeer_pToFront; - Java_sun_awt_motif_MCustomCursor_cacheInit; - Java_sun_awt_motif_MCustomCursor_createCursor; - Java_sun_awt_motif_MCustomCursor_queryBestCursor; + #Java_sun_awt_motif_MWindowPeer_pDispose; + #Java_sun_awt_motif_MWindowPeer_pHide; + #Java_sun_awt_motif_MWindowPeer_pReshape; + #Java_sun_awt_motif_MWindowPeer_pSetTitle; + #Java_sun_awt_motif_MWindowPeer_pShow; + #Java_sun_awt_motif_MWindowPeer_setResizable; + #Java_sun_awt_motif_MWindowPeer_toBack; + #Java_sun_awt_motif_MWindowPeer_addTextComponentNative; + #Java_sun_awt_motif_MWindowPeer_getState; + #Java_sun_awt_motif_MWindowPeer_pSetIMMOption; + #Java_sun_awt_motif_MWindowPeer_pSetMenuBar; + #Java_sun_awt_motif_MWindowPeer_pShowModal; + #Java_sun_awt_motif_MWindowPeer_removeTextComponentNative; + #Java_sun_awt_motif_MWindowPeer_setSaveUnder; + #Java_sun_awt_motif_MWindowPeer_setState; + #Java_sun_awt_motif_MWindowPeer_resetTargetGC; + #Java_sun_awt_motif_MWindowPeer_registerX11DropTarget; + #Java_sun_awt_motif_MWindowPeer_unregisterX11DropTarget; + #Java_sun_awt_motif_MWindowPeer_updateAlwaysOnTop; + #Java_sun_awt_motif_MWindowPeer_setFocusableWindow; + #Java_sun_awt_motif_MWindowPeer_pToFront; + #Java_sun_awt_motif_MCustomCursor_cacheInit; + #Java_sun_awt_motif_MCustomCursor_createCursor; + #Java_sun_awt_motif_MCustomCursor_queryBestCursor; Java_sun_awt_motif_X11FontMetrics_bytesWidth; Java_sun_awt_motif_X11FontMetrics_getMFCharsWidth; Java_sun_awt_motif_X11FontMetrics_init; @@ -268,18 +268,18 @@ SUNWprivate_1.1 { Java_sun_awt_X11InputMethod_resetXIC; Java_sun_awt_X11InputMethod_setCompositionEnabledNative; Java_sun_awt_X11InputMethod_turnoffStatusWindow; - Java_sun_awt_motif_MInputMethod_openXIMNative; - Java_sun_awt_motif_MInputMethod_configureStatusAreaNative; - Java_sun_awt_motif_MInputMethod_createXICNative; - Java_sun_awt_motif_MInputMethod_reconfigureXICNative; - Java_sun_awt_motif_MInputMethod_setXICFocusNative; - Java_sun_awt_motif_X11Clipboard_getClipboardData; - Java_sun_awt_motif_X11Clipboard_getClipboardFormats; - Java_sun_awt_motif_X11Clipboard_registerClipboardViewer; - Java_sun_awt_motif_X11Clipboard_unregisterClipboardViewer; - Java_sun_awt_motif_X11Selection_init; - Java_sun_awt_motif_X11Selection_pGetSelectionOwnership; - Java_sun_awt_motif_X11Selection_clearNativeContext; + #Java_sun_awt_motif_MInputMethod_openXIMNative; + #Java_sun_awt_motif_MInputMethod_configureStatusAreaNative; + #Java_sun_awt_motif_MInputMethod_createXICNative; + #Java_sun_awt_motif_MInputMethod_reconfigureXICNative; + #Java_sun_awt_motif_MInputMethod_setXICFocusNative; + #Java_sun_awt_motif_X11Clipboard_getClipboardData; + #Java_sun_awt_motif_X11Clipboard_getClipboardFormats; + #Java_sun_awt_motif_X11Clipboard_registerClipboardViewer; + #Java_sun_awt_motif_X11Clipboard_unregisterClipboardViewer; + #Java_sun_awt_motif_X11Selection_init; + #Java_sun_awt_motif_X11Selection_pGetSelectionOwnership; + #Java_sun_awt_motif_X11Selection_clearNativeContext; Java_sun_awt_SunToolkit_closeSplashScreen; Java_sun_awt_PlatformFont_initIDs; Java_sun_awt_X11GraphicsConfig_init; @@ -311,25 +311,25 @@ SUNWprivate_1.1 { Java_sun_awt_X11GraphicsEnvironment_initGLX; Java_sun_awt_X11GraphicsEnvironment_pRunningXinerama; Java_sun_awt_X11GraphicsEnvironment_getXineramaCenterPoint; - Java_sun_awt_motif_MEmbedCanvasPeer_initXEmbedServer; - Java_sun_awt_motif_MEmbedCanvasPeer_destroyXEmbedServer; - Java_sun_awt_motif_MEmbedCanvasPeer_isXEmbedActive; - Java_sun_awt_motif_MEmbedCanvasPeer_initDispatching; - Java_sun_awt_motif_MEmbedCanvasPeer_endDispatching; - Java_sun_awt_motif_MEmbedCanvasPeer_embedChild; - Java_sun_awt_motif_MEmbedCanvasPeer_childDestroyed; - Java_sun_awt_motif_MEmbedCanvasPeer_getEmbedPreferredSize; - Java_sun_awt_motif_MEmbedCanvasPeer_getEmbedMinimumSize; - Java_sun_awt_motif_MEmbedCanvasPeer_getClientBounds; - Java_sun_awt_motif_MEmbedCanvasPeer_notifyChildEmbedded; - Java_sun_awt_motif_MEmbedCanvasPeer_detachChild; - Java_sun_awt_motif_MEmbedCanvasPeer_forwardKeyEvent; - Java_sun_awt_motif_MEmbedCanvasPeer_getAWTKeyCodeForKeySym; - Java_sun_awt_motif_MEmbedCanvasPeer_sendMessage__I; - Java_sun_awt_motif_MEmbedCanvasPeer_sendMessage__IJJJ; - Java_sun_awt_motif_MEmbedCanvasPeer_getWindow; - Java_sun_awt_motif_GrabbedKey_initKeySymAndModifiers; - Java_sun_awt_motif_MEmbeddedFramePeer_traverseOut; + #Java_sun_awt_motif_MEmbedCanvasPeer_initXEmbedServer; + #Java_sun_awt_motif_MEmbedCanvasPeer_destroyXEmbedServer; + #Java_sun_awt_motif_MEmbedCanvasPeer_isXEmbedActive; + #Java_sun_awt_motif_MEmbedCanvasPeer_initDispatching; + #Java_sun_awt_motif_MEmbedCanvasPeer_endDispatching; + #Java_sun_awt_motif_MEmbedCanvasPeer_embedChild; + #Java_sun_awt_motif_MEmbedCanvasPeer_childDestroyed; + #Java_sun_awt_motif_MEmbedCanvasPeer_getEmbedPreferredSize; + #Java_sun_awt_motif_MEmbedCanvasPeer_getEmbedMinimumSize; + #Java_sun_awt_motif_MEmbedCanvasPeer_getClientBounds; + #Java_sun_awt_motif_MEmbedCanvasPeer_notifyChildEmbedded; + #Java_sun_awt_motif_MEmbedCanvasPeer_detachChild; + #Java_sun_awt_motif_MEmbedCanvasPeer_forwardKeyEvent; + #Java_sun_awt_motif_MEmbedCanvasPeer_getAWTKeyCodeForKeySym; + #Java_sun_awt_motif_MEmbedCanvasPeer_sendMessage__I; + #Java_sun_awt_motif_MEmbedCanvasPeer_sendMessage__IJJJ; + #Java_sun_awt_motif_MEmbedCanvasPeer_getWindow; + #Java_sun_awt_motif_GrabbedKey_initKeySymAndModifiers; + #Java_sun_awt_motif_MEmbeddedFramePeer_traverseOut; Java_java_awt_AWTEvent_initIDs; Java_java_awt_Button_initIDs; Java_java_awt_Container_initIDs; @@ -343,39 +343,39 @@ SUNWprivate_1.1 { Java_java_awt_Insets_initIDs; Java_java_awt_TextField_initIDs; Java_java_awt_Window_initIDs; - Java_sun_awt_motif_MCheckboxPeer_getIndicatorSize; - Java_sun_awt_motif_MCheckboxPeer_getSpacing; - Java_sun_awt_motif_MChoicePeer_freeNativeData; - Java_sun_awt_motif_MComponentPeer_getComponents_1NoClientCode; - Java_sun_awt_motif_MComponentPeer_getParent_1NoClientCode; - Java_sun_awt_motif_MComponentPeer_initIDs; - Java_sun_awt_motif_MComponentPeer_nativeHandleEvent; - Java_sun_awt_motif_MComponentPeer_pSetCursor; - Java_sun_awt_motif_MComponentPeer_pSetInnerForeground; - Java_sun_awt_motif_MComponentPeer_pSetScrollbarBackground; - Java_sun_awt_motif_MComponentPeer_setTargetBackground; - Java_sun_awt_motif_MDataTransferer_dragQueryFile; - Java_sun_awt_motif_MDataTransferer_getAtomForTarget; - Java_sun_awt_motif_MDataTransferer_getTargetNameForAtom; - Java_sun_awt_motif_MFileDialogPeer_insertReplaceFileDialogText; + #Java_sun_awt_motif_MCheckboxPeer_getIndicatorSize; + #Java_sun_awt_motif_MCheckboxPeer_getSpacing; + #Java_sun_awt_motif_MChoicePeer_freeNativeData; + #Java_sun_awt_motif_MComponentPeer_getComponents_1NoClientCode; + #Java_sun_awt_motif_MComponentPeer_getParent_1NoClientCode; + #Java_sun_awt_motif_MComponentPeer_initIDs; + #Java_sun_awt_motif_MComponentPeer_nativeHandleEvent; + #Java_sun_awt_motif_MComponentPeer_pSetCursor; + #Java_sun_awt_motif_MComponentPeer_pSetInnerForeground; + #Java_sun_awt_motif_MComponentPeer_pSetScrollbarBackground; + #Java_sun_awt_motif_MComponentPeer_setTargetBackground; + #Java_sun_awt_motif_MDataTransferer_dragQueryFile; + #Java_sun_awt_motif_MDataTransferer_getAtomForTarget; + #Java_sun_awt_motif_MDataTransferer_getTargetNameForAtom; + #Java_sun_awt_motif_MFileDialogPeer_insertReplaceFileDialogText; Java_sun_awt_motif_MFontPeer_initIDs; - Java_sun_awt_motif_MListPeer_setBackground; - Java_sun_awt_motif_MMenuBarPeer_initIDs; - Java_sun_awt_motif_MMenuBarPeer_pDispose; - Java_sun_awt_motif_MMenuItemPeer_getParent_1NoClientCode; - Java_sun_awt_motif_MMenuItemPeer_initIDs; - Java_sun_awt_motif_MMenuItemPeer_pSetShortcut; - Java_sun_awt_motif_MPopupMenuPeer_initIDs; - Java_sun_awt_motif_MScrollbarPeer_initIDs; - Java_sun_awt_motif_MScrollPanePeer_initIDs; - Java_sun_awt_motif_MTextAreaPeer_pSetCursor; + #Java_sun_awt_motif_MListPeer_setBackground; + #Java_sun_awt_motif_MMenuBarPeer_initIDs; + #Java_sun_awt_motif_MMenuBarPeer_pDispose; + #Java_sun_awt_motif_MMenuItemPeer_getParent_1NoClientCode; + #Java_sun_awt_motif_MMenuItemPeer_initIDs; + #Java_sun_awt_motif_MMenuItemPeer_pSetShortcut; + #Java_sun_awt_motif_MPopupMenuPeer_initIDs; + #Java_sun_awt_motif_MScrollbarPeer_initIDs; + #Java_sun_awt_motif_MScrollPanePeer_initIDs; + #Java_sun_awt_motif_MTextAreaPeer_pSetCursor; Java_sun_awt_motif_MToolkit_shutdown; - Java_sun_awt_motif_MWindowPeer_initIDs; - Java_sun_awt_motif_MWindowPeer_pCreate; - Java_sun_awt_motif_MWindowPeer_wrapInSequenced; + #Java_sun_awt_motif_MWindowPeer_initIDs; + #Java_sun_awt_motif_MWindowPeer_pCreate; + #Java_sun_awt_motif_MWindowPeer_wrapInSequenced; Java_sun_awt_motif_X11FontMetrics_initIDs; - Java_sun_awt_X11InputMethod_initIDs; - Java_sun_awt_motif_X11Selection_initIDs; + #Java_sun_awt_X11InputMethod_initIDs; + #Java_sun_awt_motif_X11Selection_initIDs; Java_sun_awt_motif_MToolkitThreadBlockedHandler_enter; Java_sun_awt_motif_MToolkitThreadBlockedHandler_exit; Java_sun_awt_X11GraphicsConfig_init; diff --git a/jdk/make/sun/awt/mapfile-vers-linux b/jdk/make/sun/awt/mapfile-vers-linux index ccea692463c..4905e40f674 100644 --- a/jdk/make/sun/awt/mapfile-vers-linux +++ b/jdk/make/sun/awt/mapfile-vers-linux @@ -170,7 +170,7 @@ SUNWprivate_1.1 { GrPrim_Sg2dGetPixel; GrPrim_Sg2dGetLCDTextContrast; - Java_sun_awt_motif_MComponentPeer_restoreFocus; + #Java_sun_awt_motif_MComponentPeer_restoreFocus; Java_sun_awt_DefaultMouseInfoPeer_fillPointWithCoords; Java_sun_awt_DefaultMouseInfoPeer_isWindowUnderMouse; Java_java_awt_AWTEvent_nativeSetSource; @@ -189,158 +189,158 @@ SUNWprivate_1.1 { Java_java_awt_ScrollPane_initIDs; Java_java_awt_TextArea_initIDs; Java_sun_awt_FontDescriptor_initIDs; - Java_sun_awt_motif_MButtonPeer_create; - Java_sun_awt_motif_MButtonPeer_setLabel; - Java_sun_awt_motif_MCanvasPeer_create; - Java_sun_awt_motif_MCanvasPeer_initIDs; - Java_sun_awt_motif_MCanvasPeer_resetTargetGC; - Java_sun_awt_motif_MCheckboxMenuItemPeer_pSetState; - Java_sun_awt_motif_MCheckboxPeer_create; - Java_sun_awt_motif_MCheckboxPeer_setCheckboxGroup; - Java_sun_awt_motif_MCheckboxPeer_setLabel; - Java_sun_awt_motif_MCheckboxPeer_pSetState; - Java_sun_awt_motif_MCheckboxPeer_pGetState; - Java_sun_awt_motif_MChoicePeer_addItem; - Java_sun_awt_motif_MChoicePeer_appendItems; - Java_sun_awt_motif_MChoicePeer_create; - Java_sun_awt_motif_MChoicePeer_pReshape; - Java_sun_awt_motif_MChoicePeer_remove; - Java_sun_awt_motif_MChoicePeer_removeAll; - Java_sun_awt_motif_MChoicePeer_setBackground; - Java_sun_awt_motif_MChoicePeer_pSelect; - Java_sun_awt_motif_MChoicePeer_setFont; - Java_sun_awt_motif_MChoicePeer_setForeground; - Java_sun_awt_motif_MComponentPeer_addNativeDropTarget; - Java_sun_awt_motif_MComponentPeer_createBackBuffer; - Java_sun_awt_motif_MComponentPeer_destroyBackBuffer; - Java_sun_awt_motif_MComponentPeer_getNativeColor; - Java_sun_awt_motif_MComponentPeer_getWindow; - Java_sun_awt_motif_MComponentPeer_pDisable; - Java_sun_awt_motif_MComponentPeer_pDispose; - Java_sun_awt_motif_MComponentPeer_pEnable; - Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen; - Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen2; - Java_sun_awt_motif_MComponentPeer_pHide; - Java_sun_awt_motif_MComponentPeer_pInitialize; - Java_sun_awt_motif_MComponentPeer_pMakeCursorVisible; - Java_sun_awt_motif_MComponentPeer_pReshape; - Java_sun_awt_motif_MComponentPeer_pShow; - Java_sun_awt_motif_MComponentPeer_removeNativeDropTarget; - Java_sun_awt_motif_MComponentPeer_swapBuffers; - Java_sun_awt_motif_MComponentPeer_pSetBackground; - Java_sun_awt_motif_MComponentPeer_pSetFont; - Java_sun_awt_motif_MComponentPeer_processSynchronousLightweightTransfer; - Java_sun_awt_motif_MComponentPeer__1requestFocus; - Java_sun_awt_motif_MCheckboxMenuItemPeer_getState; - Java_sun_awt_motif_MComponentPeer_pSetForeground; - Java_sun_awt_motif_MDragSourceContextPeer_startDrag; - Java_sun_awt_motif_MDragSourceContextPeer_setNativeCursor; - Java_sun_awt_motif_MDropTargetContextPeer_addTransfer; - Java_sun_awt_motif_MDropTargetContextPeer_dropDone; - Java_sun_awt_motif_MDropTargetContextPeer_startTransfer; - Java_sun_awt_motif_X11DragSourceContextPeer_startDrag; - Java_sun_awt_motif_X11DragSourceContextPeer_setNativeCursor; - Java_sun_awt_motif_X11DropTargetContextPeer_sendResponse; - Java_sun_awt_motif_X11DropTargetContextPeer_dropDone; - Java_sun_awt_motif_X11DropTargetContextPeer_getData; - Java_sun_awt_motif_MEmbeddedFramePeer_NEFcreate; - Java_sun_awt_motif_MEmbeddedFramePeer_pShowImpl; - Java_sun_awt_motif_MEmbeddedFramePeer_pReshapePrivate; - Java_sun_awt_motif_MEmbeddedFramePeer_getBoundsPrivate; - Java_sun_awt_motif_MFramePeer_pSetIconImage___3B_3I_3SII; - Java_sun_awt_motif_MEmbeddedFramePeer_requestXEmbedFocus; - Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedApplicationActive; - Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedActive; - Java_sun_awt_motif_MEmbeddedFrame_getWidget; - Java_sun_awt_motif_MEmbeddedFrame_mapWidget; - Java_sun_awt_motif_MFileDialogPeer_create; - Java_sun_awt_motif_MFileDialogPeer_pDispose; - Java_sun_awt_motif_MFileDialogPeer_pHide; - Java_sun_awt_motif_MFileDialogPeer_pReshape; - Java_sun_awt_motif_MFileDialogPeer_pShow; - Java_sun_awt_motif_MFileDialogPeer_setFileEntry; - Java_sun_awt_motif_MFileDialogPeer_setFont; - Java_sun_awt_motif_MFramePeer_pGetIconSize; - Java_sun_awt_motif_MGlobalCursorManager_cacheInit; - Java_sun_awt_motif_MGlobalCursorManager_findComponentAt; - Java_sun_awt_motif_MGlobalCursorManager_findHeavyweightUnderCursor; - Java_sun_awt_motif_MGlobalCursorManager_getCursorPos; - Java_sun_awt_motif_MGlobalCursorManager_getLocationOnScreen; - Java_sun_awt_motif_MLabelPeer_create; - Java_sun_awt_motif_MLabelPeer_setAlignment; - Java_sun_awt_motif_MLabelPeer_setText; - Java_sun_awt_motif_MListPeer_addItem; - Java_sun_awt_motif_MListPeer_create; - Java_sun_awt_motif_MListPeer_delItems; - Java_sun_awt_motif_MListPeer_deselect; - Java_sun_awt_motif_MListPeer_isSelected; - Java_sun_awt_motif_MListPeer_makeVisible; - Java_sun_awt_motif_MListPeer_select; - Java_sun_awt_motif_MListPeer_setMultipleSelections; - Java_sun_awt_motif_MMenuBarPeer_create; - Java_sun_awt_motif_MMenuItemPeer_createMenuItem; - Java_sun_awt_motif_MMenuItemPeer_pDisable; - Java_sun_awt_motif_MMenuItemPeer_pDispose; - Java_sun_awt_motif_MMenuItemPeer_pEnable; - Java_sun_awt_motif_MMenuItemPeer_pSetLabel; - Java_sun_awt_motif_MMenuPeer_createMenu; - Java_sun_awt_motif_MMenuPeer_createSubMenu; - Java_sun_awt_motif_MMenuPeer_pDispose; - Java_sun_awt_motif_MPopupMenuPeer_createMenu; - Java_sun_awt_motif_MPopupMenuPeer_pDispose; - Java_sun_awt_motif_MPopupMenuPeer_pShow; - Java_sun_awt_motif_MRobotPeer_getRGBPixelsImpl; - Java_sun_awt_motif_MRobotPeer_keyPressImpl; - Java_sun_awt_motif_MRobotPeer_keyReleaseImpl; - Java_sun_awt_motif_MRobotPeer_mouseMoveImpl; - Java_sun_awt_motif_MRobotPeer_mousePressImpl; - Java_sun_awt_motif_MRobotPeer_mouseReleaseImpl; - Java_sun_awt_motif_MRobotPeer_mouseWheelImpl; - Java_sun_awt_motif_MRobotPeer_setup; - Java_sun_awt_motif_MScrollbarPeer_create; - Java_sun_awt_motif_MScrollbarPeer_setLineIncrement; - Java_sun_awt_motif_MScrollbarPeer_setPageIncrement; - Java_sun_awt_motif_MScrollbarPeer_pSetValues; - Java_sun_awt_motif_MScrollPanePeer_create; - Java_sun_awt_motif_MScrollPanePeer_pGetBlockIncrement; - Java_sun_awt_motif_MScrollPanePeer_pGetScrollbarSpace; - Java_sun_awt_motif_MScrollPanePeer_pGetShadow; - Java_sun_awt_motif_MScrollPanePeer_pInsets; - Java_sun_awt_motif_MScrollPanePeer_pSetIncrement; - Java_sun_awt_motif_MScrollPanePeer_pSetScrollChild; - Java_sun_awt_motif_MScrollPanePeer_setScrollPosition; - Java_sun_awt_motif_MTextAreaPeer_initIDs; - Java_sun_awt_motif_MTextAreaPeer_pCreate; - Java_sun_awt_motif_MTextAreaPeer_getCaretPosition; - Java_sun_awt_motif_MTextAreaPeer_getExtraHeight; - Java_sun_awt_motif_MTextAreaPeer_getExtraWidth; - Java_sun_awt_motif_MTextAreaPeer_getSelectionEnd; - Java_sun_awt_motif_MTextAreaPeer_getSelectionStart; - Java_sun_awt_motif_MTextAreaPeer_getText; - Java_sun_awt_motif_MTextAreaPeer_insert; - Java_sun_awt_motif_MTextAreaPeer_pMakeCursorVisible; - Java_sun_awt_motif_MTextAreaPeer_pSetEditable; - Java_sun_awt_motif_MTextAreaPeer_pShow2; - Java_sun_awt_motif_MTextAreaPeer_replaceRange; - Java_sun_awt_motif_MTextAreaPeer_select; - Java_sun_awt_motif_MTextAreaPeer_setCaretPosition; - Java_sun_awt_motif_MTextAreaPeer_setFont; - Java_sun_awt_motif_MTextAreaPeer_setText; - Java_sun_awt_motif_MTextAreaPeer_setTextBackground; - Java_sun_awt_motif_MTextFieldPeer_initIDs; - Java_sun_awt_motif_MTextFieldPeer_pCreate; - Java_sun_awt_motif_MTextFieldPeer_getCaretPosition; - Java_sun_awt_motif_MTextFieldPeer_getSelectionEnd; - Java_sun_awt_motif_MTextFieldPeer_getSelectionStart; - Java_sun_awt_motif_MTextFieldPeer_getText; - Java_sun_awt_motif_MTextFieldPeer_insertReplaceText; - Java_sun_awt_motif_MTextFieldPeer_preDispose; - Java_sun_awt_motif_MTextFieldPeer_pSetEditable; - Java_sun_awt_motif_MTextFieldPeer_select; - Java_sun_awt_motif_MTextFieldPeer_setCaretPosition; - Java_sun_awt_motif_MTextFieldPeer_setEchoChar; - Java_sun_awt_motif_MTextFieldPeer_setFont; - Java_sun_awt_motif_MTextFieldPeer_setText; + #Java_sun_awt_motif_MButtonPeer_create; + #Java_sun_awt_motif_MButtonPeer_setLabel; + #Java_sun_awt_motif_MCanvasPeer_create; + #Java_sun_awt_motif_MCanvasPeer_initIDs; + #Java_sun_awt_motif_MCanvasPeer_resetTargetGC; + #Java_sun_awt_motif_MCheckboxMenuItemPeer_pSetState; + #Java_sun_awt_motif_MCheckboxPeer_create; + #Java_sun_awt_motif_MCheckboxPeer_setCheckboxGroup; + #Java_sun_awt_motif_MCheckboxPeer_setLabel; + #Java_sun_awt_motif_MCheckboxPeer_pSetState; + #Java_sun_awt_motif_MCheckboxPeer_pGetState; + #Java_sun_awt_motif_MChoicePeer_addItem; + #Java_sun_awt_motif_MChoicePeer_appendItems; + #Java_sun_awt_motif_MChoicePeer_create; + #Java_sun_awt_motif_MChoicePeer_pReshape; + #Java_sun_awt_motif_MChoicePeer_remove; + #Java_sun_awt_motif_MChoicePeer_removeAll; + #Java_sun_awt_motif_MChoicePeer_setBackground; + #Java_sun_awt_motif_MChoicePeer_pSelect; + #Java_sun_awt_motif_MChoicePeer_setFont; + #Java_sun_awt_motif_MChoicePeer_setForeground; + #Java_sun_awt_motif_MComponentPeer_addNativeDropTarget; + #Java_sun_awt_motif_MComponentPeer_createBackBuffer; + #Java_sun_awt_motif_MComponentPeer_destroyBackBuffer; + #Java_sun_awt_motif_MComponentPeer_getNativeColor; + #Java_sun_awt_motif_MComponentPeer_getWindow; + #Java_sun_awt_motif_MComponentPeer_pDisable; + #Java_sun_awt_motif_MComponentPeer_pDispose; + #Java_sun_awt_motif_MComponentPeer_pEnable; + #Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen; + #Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen2; + #Java_sun_awt_motif_MComponentPeer_pHide; + #Java_sun_awt_motif_MComponentPeer_pInitialize; + #Java_sun_awt_motif_MComponentPeer_pMakeCursorVisible; + #Java_sun_awt_motif_MComponentPeer_pReshape; + #Java_sun_awt_motif_MComponentPeer_pShow; + #Java_sun_awt_motif_MComponentPeer_removeNativeDropTarget; + #Java_sun_awt_motif_MComponentPeer_swapBuffers; + #Java_sun_awt_motif_MComponentPeer_pSetBackground; + #Java_sun_awt_motif_MComponentPeer_pSetFont; + #Java_sun_awt_motif_MComponentPeer_processSynchronousLightweightTransfer; + #Java_sun_awt_motif_MComponentPeer__1requestFocus; + #Java_sun_awt_motif_MCheckboxMenuItemPeer_getState; + #Java_sun_awt_motif_MComponentPeer_pSetForeground; + #Java_sun_awt_motif_MDragSourceContextPeer_startDrag; + #Java_sun_awt_motif_MDragSourceContextPeer_setNativeCursor; + #Java_sun_awt_motif_MDropTargetContextPeer_addTransfer; + #Java_sun_awt_motif_MDropTargetContextPeer_dropDone; + #Java_sun_awt_motif_MDropTargetContextPeer_startTransfer; + #Java_sun_awt_motif_X11DragSourceContextPeer_startDrag; + #Java_sun_awt_motif_X11DragSourceContextPeer_setNativeCursor; + #Java_sun_awt_motif_X11DropTargetContextPeer_sendResponse; + #Java_sun_awt_motif_X11DropTargetContextPeer_dropDone; + #Java_sun_awt_motif_X11DropTargetContextPeer_getData; + #Java_sun_awt_motif_MEmbeddedFramePeer_NEFcreate; + #Java_sun_awt_motif_MEmbeddedFramePeer_pShowImpl; + #Java_sun_awt_motif_MEmbeddedFramePeer_pReshapePrivate; + #Java_sun_awt_motif_MEmbeddedFramePeer_getBoundsPrivate; + #Java_sun_awt_motif_MFramePeer_pSetIconImage___3B_3I_3SII; + #Java_sun_awt_motif_MEmbeddedFramePeer_requestXEmbedFocus; + #Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedApplicationActive; + #Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedActive; + #Java_sun_awt_motif_MEmbeddedFrame_getWidget; + #Java_sun_awt_motif_MEmbeddedFrame_mapWidget; + #Java_sun_awt_motif_MFileDialogPeer_create; + #Java_sun_awt_motif_MFileDialogPeer_pDispose; + #Java_sun_awt_motif_MFileDialogPeer_pHide; + #Java_sun_awt_motif_MFileDialogPeer_pReshape; + #Java_sun_awt_motif_MFileDialogPeer_pShow; + #Java_sun_awt_motif_MFileDialogPeer_setFileEntry; + #Java_sun_awt_motif_MFileDialogPeer_setFont; + #Java_sun_awt_motif_MFramePeer_pGetIconSize; + #Java_sun_awt_motif_MGlobalCursorManager_cacheInit; + #Java_sun_awt_motif_MGlobalCursorManager_findComponentAt; + #Java_sun_awt_motif_MGlobalCursorManager_findHeavyweightUnderCursor; + #Java_sun_awt_motif_MGlobalCursorManager_getCursorPos; + #Java_sun_awt_motif_MGlobalCursorManager_getLocationOnScreen; + #Java_sun_awt_motif_MLabelPeer_create; + #Java_sun_awt_motif_MLabelPeer_setAlignment; + #Java_sun_awt_motif_MLabelPeer_setText; + #Java_sun_awt_motif_MListPeer_addItem; + #Java_sun_awt_motif_MListPeer_create; + #Java_sun_awt_motif_MListPeer_delItems; + #Java_sun_awt_motif_MListPeer_deselect; + #Java_sun_awt_motif_MListPeer_isSelected; + #Java_sun_awt_motif_MListPeer_makeVisible; + #Java_sun_awt_motif_MListPeer_select; + #Java_sun_awt_motif_MListPeer_setMultipleSelections; + #Java_sun_awt_motif_MMenuBarPeer_create; + #Java_sun_awt_motif_MMenuItemPeer_createMenuItem; + #Java_sun_awt_motif_MMenuItemPeer_pDisable; + #Java_sun_awt_motif_MMenuItemPeer_pDispose; + #Java_sun_awt_motif_MMenuItemPeer_pEnable; + #Java_sun_awt_motif_MMenuItemPeer_pSetLabel; + #Java_sun_awt_motif_MMenuPeer_createMenu; + #Java_sun_awt_motif_MMenuPeer_createSubMenu; + #Java_sun_awt_motif_MMenuPeer_pDispose; + #Java_sun_awt_motif_MPopupMenuPeer_createMenu; + #Java_sun_awt_motif_MPopupMenuPeer_pDispose; + #Java_sun_awt_motif_MPopupMenuPeer_pShow; + #Java_sun_awt_motif_MRobotPeer_getRGBPixelsImpl; + #Java_sun_awt_motif_MRobotPeer_keyPressImpl; + #Java_sun_awt_motif_MRobotPeer_keyReleaseImpl; + #Java_sun_awt_motif_MRobotPeer_mouseMoveImpl; + #Java_sun_awt_motif_MRobotPeer_mousePressImpl; + #Java_sun_awt_motif_MRobotPeer_mouseReleaseImpl; + #Java_sun_awt_motif_MRobotPeer_mouseWheelImpl; + #Java_sun_awt_motif_MRobotPeer_setup; + #Java_sun_awt_motif_MScrollbarPeer_create; + #Java_sun_awt_motif_MScrollbarPeer_setLineIncrement; + #Java_sun_awt_motif_MScrollbarPeer_setPageIncrement; + #Java_sun_awt_motif_MScrollbarPeer_pSetValues; + #Java_sun_awt_motif_MScrollPanePeer_create; + #Java_sun_awt_motif_MScrollPanePeer_pGetBlockIncrement; + #Java_sun_awt_motif_MScrollPanePeer_pGetScrollbarSpace; + #Java_sun_awt_motif_MScrollPanePeer_pGetShadow; + #Java_sun_awt_motif_MScrollPanePeer_pInsets; + #Java_sun_awt_motif_MScrollPanePeer_pSetIncrement; + #Java_sun_awt_motif_MScrollPanePeer_pSetScrollChild; + #Java_sun_awt_motif_MScrollPanePeer_setScrollPosition; + #Java_sun_awt_motif_MTextAreaPeer_initIDs; + #Java_sun_awt_motif_MTextAreaPeer_pCreate; + #Java_sun_awt_motif_MTextAreaPeer_getCaretPosition; + #Java_sun_awt_motif_MTextAreaPeer_getExtraHeight; + #Java_sun_awt_motif_MTextAreaPeer_getExtraWidth; + #Java_sun_awt_motif_MTextAreaPeer_getSelectionEnd; + #Java_sun_awt_motif_MTextAreaPeer_getSelectionStart; + #Java_sun_awt_motif_MTextAreaPeer_getText; + #Java_sun_awt_motif_MTextAreaPeer_insert; + #Java_sun_awt_motif_MTextAreaPeer_pMakeCursorVisible; + #Java_sun_awt_motif_MTextAreaPeer_pSetEditable; + #Java_sun_awt_motif_MTextAreaPeer_pShow2; + #Java_sun_awt_motif_MTextAreaPeer_replaceRange; + #Java_sun_awt_motif_MTextAreaPeer_select; + #Java_sun_awt_motif_MTextAreaPeer_setCaretPosition; + #Java_sun_awt_motif_MTextAreaPeer_setFont; + #Java_sun_awt_motif_MTextAreaPeer_setText; + #Java_sun_awt_motif_MTextAreaPeer_setTextBackground; + #Java_sun_awt_motif_MTextFieldPeer_initIDs; + #Java_sun_awt_motif_MTextFieldPeer_pCreate; + #Java_sun_awt_motif_MTextFieldPeer_getCaretPosition; + #Java_sun_awt_motif_MTextFieldPeer_getSelectionEnd; + #Java_sun_awt_motif_MTextFieldPeer_getSelectionStart; + #Java_sun_awt_motif_MTextFieldPeer_getText; + #Java_sun_awt_motif_MTextFieldPeer_insertReplaceText; + #Java_sun_awt_motif_MTextFieldPeer_preDispose; + #Java_sun_awt_motif_MTextFieldPeer_pSetEditable; + #Java_sun_awt_motif_MTextFieldPeer_select; + #Java_sun_awt_motif_MTextFieldPeer_setCaretPosition; + #Java_sun_awt_motif_MTextFieldPeer_setEchoChar; + #Java_sun_awt_motif_MTextFieldPeer_setFont; + #Java_sun_awt_motif_MTextFieldPeer_setText; Java_sun_awt_motif_MToolkit_beep; Java_sun_awt_motif_MToolkit_getLockingKeyStateNative; Java_sun_awt_motif_MToolkit_getMulticlickTime; @@ -357,28 +357,28 @@ SUNWprivate_1.1 { Java_sun_awt_motif_MToolkit_sync; Java_sun_awt_motif_MToolkit_isAlwaysOnTopSupported; Java_sun_awt_motif_MWindowAttributes_initIDs; - Java_sun_awt_motif_MWindowPeer_pDispose; - Java_sun_awt_motif_MWindowPeer_pHide; - Java_sun_awt_motif_MWindowPeer_pReshape; - Java_sun_awt_motif_MWindowPeer_pSetTitle; - Java_sun_awt_motif_MWindowPeer_pShow; - Java_sun_awt_motif_MWindowPeer_setResizable; - Java_sun_awt_motif_MWindowPeer_toBack; - Java_sun_awt_motif_MWindowPeer_addTextComponentNative; - Java_sun_awt_motif_MWindowPeer_getState; - Java_sun_awt_motif_MWindowPeer_pSetIMMOption; - Java_sun_awt_motif_MWindowPeer_pSetMenuBar; - Java_sun_awt_motif_MWindowPeer_pShowModal; - Java_sun_awt_motif_MWindowPeer_removeTextComponentNative; - Java_sun_awt_motif_MWindowPeer_setSaveUnder; - Java_sun_awt_motif_MWindowPeer_setState; - Java_sun_awt_motif_MWindowPeer_resetTargetGC; - Java_sun_awt_motif_MWindowPeer_registerX11DropTarget; - Java_sun_awt_motif_MWindowPeer_unregisterX11DropTarget; - Java_sun_awt_motif_MWindowPeer_updateAlwaysOnTop; - Java_sun_awt_motif_X11CustomCursor_cacheInit; - Java_sun_awt_motif_X11CustomCursor_createCursor; - Java_sun_awt_motif_X11CustomCursor_queryBestCursor; + #Java_sun_awt_motif_MWindowPeer_pDispose; + #Java_sun_awt_motif_MWindowPeer_pHide; + #Java_sun_awt_motif_MWindowPeer_pReshape; + #Java_sun_awt_motif_MWindowPeer_pSetTitle; + #Java_sun_awt_motif_MWindowPeer_pShow; + #Java_sun_awt_motif_MWindowPeer_setResizable; + #Java_sun_awt_motif_MWindowPeer_toBack; + #Java_sun_awt_motif_MWindowPeer_addTextComponentNative; + #Java_sun_awt_motif_MWindowPeer_getState; + #Java_sun_awt_motif_MWindowPeer_pSetIMMOption; + #Java_sun_awt_motif_MWindowPeer_pSetMenuBar; + #Java_sun_awt_motif_MWindowPeer_pShowModal; + #Java_sun_awt_motif_MWindowPeer_removeTextComponentNative; + #Java_sun_awt_motif_MWindowPeer_setSaveUnder; + #Java_sun_awt_motif_MWindowPeer_setState; + #Java_sun_awt_motif_MWindowPeer_resetTargetGC; + #Java_sun_awt_motif_MWindowPeer_registerX11DropTarget; + #Java_sun_awt_motif_MWindowPeer_unregisterX11DropTarget; + #Java_sun_awt_motif_MWindowPeer_updateAlwaysOnTop; + #Java_sun_awt_motif_X11CustomCursor_cacheInit; + #Java_sun_awt_motif_X11CustomCursor_createCursor; + #Java_sun_awt_motif_X11CustomCursor_queryBestCursor; Java_sun_awt_motif_X11FontMetrics_bytesWidth; Java_sun_awt_motif_X11FontMetrics_getMFCharsWidth; Java_sun_awt_motif_X11FontMetrics_init; @@ -387,18 +387,18 @@ SUNWprivate_1.1 { Java_sun_awt_X11InputMethod_resetXIC; Java_sun_awt_X11InputMethod_setCompositionEnabledNative; Java_sun_awt_X11InputMethod_turnoffStatusWindow; - Java_sun_awt_motif_MInputMethod_openXIMNative; - Java_sun_awt_motif_MInputMethod_configureStatusAreaNative; - Java_sun_awt_motif_MInputMethod_createXICNative; - Java_sun_awt_motif_MInputMethod_reconfigureXICNative; - Java_sun_awt_motif_MInputMethod_setXICFocusNative; - Java_sun_awt_motif_X11Clipboard_getClipboardData; - Java_sun_awt_motif_X11Clipboard_getClipboardFormats; - Java_sun_awt_motif_X11Clipboard_registerClipboardViewer; - Java_sun_awt_motif_X11Clipboard_unregisterClipboardViewer; - Java_sun_awt_motif_X11Selection_init; - Java_sun_awt_motif_X11Selection_pGetSelectionOwnership; - Java_sun_awt_motif_X11Selection_clearNativeContext; + #Java_sun_awt_motif_MInputMethod_openXIMNative; + #Java_sun_awt_motif_MInputMethod_configureStatusAreaNative; + #Java_sun_awt_motif_MInputMethod_createXICNative; + #Java_sun_awt_motif_MInputMethod_reconfigureXICNative; + #Java_sun_awt_motif_MInputMethod_setXICFocusNative; + #Java_sun_awt_motif_X11Clipboard_getClipboardData; + #Java_sun_awt_motif_X11Clipboard_getClipboardFormats; + #Java_sun_awt_motif_X11Clipboard_registerClipboardViewer; + #Java_sun_awt_motif_X11Clipboard_unregisterClipboardViewer; + #Java_sun_awt_motif_X11Selection_init; + #Java_sun_awt_motif_X11Selection_pGetSelectionOwnership; + #Java_sun_awt_motif_X11Selection_clearNativeContext; Java_sun_awt_SunToolkit_closeSplashScreen; Java_sun_awt_PlatformFont_initIDs; Java_sun_awt_X11GraphicsConfig_init; @@ -442,40 +442,40 @@ SUNWprivate_1.1 { Java_java_awt_Insets_initIDs; Java_java_awt_TextField_initIDs; Java_java_awt_Window_initIDs; - Java_sun_awt_motif_MCheckboxPeer_getIndicatorSize; - Java_sun_awt_motif_MCheckboxPeer_getSpacing; - Java_sun_awt_motif_MChoicePeer_freeNativeData; - Java_sun_awt_motif_MComponentPeer_getComponents_1NoClientCode; - Java_sun_awt_motif_MComponentPeer_getParent_1NoClientCode; - Java_sun_awt_motif_MComponentPeer_initIDs; - Java_sun_awt_motif_MComponentPeer_nativeHandleEvent; - Java_sun_awt_motif_MComponentPeer_pSetCursor; - Java_sun_awt_motif_MComponentPeer_pSetInnerForeground; - Java_sun_awt_motif_MComponentPeer_pSetScrollbarBackground; - Java_sun_awt_motif_MComponentPeer_setTargetBackground; - Java_sun_awt_motif_MDataTransferer_dragQueryFile; - Java_sun_awt_motif_MDataTransferer_getAtomForTarget; - Java_sun_awt_motif_MDataTransferer_getTargetNameForAtom; - Java_sun_awt_motif_MFileDialogPeer_insertReplaceFileDialogText; + #Java_sun_awt_motif_MCheckboxPeer_getIndicatorSize; + #Java_sun_awt_motif_MCheckboxPeer_getSpacing; + #Java_sun_awt_motif_MChoicePeer_freeNativeData; + #Java_sun_awt_motif_MComponentPeer_getComponents_1NoClientCode; + #Java_sun_awt_motif_MComponentPeer_getParent_1NoClientCode; + #Java_sun_awt_motif_MComponentPeer_initIDs; + #Java_sun_awt_motif_MComponentPeer_nativeHandleEvent; + #Java_sun_awt_motif_MComponentPeer_pSetCursor; + #Java_sun_awt_motif_MComponentPeer_pSetInnerForeground; + #Java_sun_awt_motif_MComponentPeer_pSetScrollbarBackground; + #Java_sun_awt_motif_MComponentPeer_setTargetBackground; + #Java_sun_awt_motif_MDataTransferer_dragQueryFile; + #Java_sun_awt_motif_MDataTransferer_getAtomForTarget; + #Java_sun_awt_motif_MDataTransferer_getTargetNameForAtom; + #Java_sun_awt_motif_MFileDialogPeer_insertReplaceFileDialogText; Java_sun_awt_motif_MFontPeer_initIDs; - Java_sun_awt_motif_MListPeer_setBackground; - Java_sun_awt_motif_MMenuBarPeer_initIDs; - Java_sun_awt_motif_MMenuBarPeer_pDispose; - Java_sun_awt_motif_MMenuItemPeer_getParent_1NoClientCode; - Java_sun_awt_motif_MMenuItemPeer_initIDs; - Java_sun_awt_motif_MMenuItemPeer_pSetShortcut; - Java_sun_awt_motif_MPopupMenuPeer_initIDs; - Java_sun_awt_motif_MScrollbarPeer_initIDs; - Java_sun_awt_motif_MScrollPanePeer_initIDs; - Java_sun_awt_motif_MTextAreaPeer_pSetCursor; + #Java_sun_awt_motif_MListPeer_setBackground; + #Java_sun_awt_motif_MMenuBarPeer_initIDs; + #Java_sun_awt_motif_MMenuBarPeer_pDispose; + #Java_sun_awt_motif_MMenuItemPeer_getParent_1NoClientCode; + #Java_sun_awt_motif_MMenuItemPeer_initIDs; + #Java_sun_awt_motif_MMenuItemPeer_pSetShortcut; + #Java_sun_awt_motif_MPopupMenuPeer_initIDs; + #Java_sun_awt_motif_MScrollbarPeer_initIDs; + #Java_sun_awt_motif_MScrollPanePeer_initIDs; + #Java_sun_awt_motif_MTextAreaPeer_pSetCursor; Java_sun_awt_motif_MToolkit_shutdown; - Java_sun_awt_motif_MWindowPeer_initIDs; - Java_sun_awt_motif_MWindowPeer_pCreate; - Java_sun_awt_motif_MWindowPeer_wrapInSequenced; + #Java_sun_awt_motif_MWindowPeer_initIDs; + #Java_sun_awt_motif_MWindowPeer_pCreate; + #Java_sun_awt_motif_MWindowPeer_wrapInSequenced; Java_sun_awt_motif_X11FontMetrics_initIDs; - Java_sun_awt_X11InputMethod_initIDs; + #Java_sun_awt_X11InputMethod_initIDs; Java_sun_awt_motif_X11OffScreenImage_updateBitmask; - Java_sun_awt_motif_X11Selection_initIDs; + #Java_sun_awt_motif_X11Selection_initIDs; Java_sun_awt_motif_MToolkitThreadBlockedHandler_enter; Java_sun_awt_motif_MToolkitThreadBlockedHandler_exit; Java_sun_awt_X11GraphicsConfig_init; @@ -503,26 +503,26 @@ SUNWprivate_1.1 { Java_sun_awt_X11SurfaceData_isDgaAvailable; Java_sun_awt_X11SurfaceData_setInvalid; Java_sun_awt_X11SurfaceData_flushNativeSurface; - Java_sun_awt_motif_MEmbedCanvasPeer_initXEmbedServer; - Java_sun_awt_motif_MEmbedCanvasPeer_destroyXEmbedServer; - Java_sun_awt_motif_MEmbedCanvasPeer_isXEmbedActive; - Java_sun_awt_motif_MEmbedCanvasPeer_initDispatching; - Java_sun_awt_motif_MEmbedCanvasPeer_endDispatching; - Java_sun_awt_motif_MEmbedCanvasPeer_embedChild; - Java_sun_awt_motif_MEmbedCanvasPeer_childDestroyed; - Java_sun_awt_motif_MEmbedCanvasPeer_getEmbedPreferredSize; - Java_sun_awt_motif_MEmbedCanvasPeer_getEmbedMinimumSize; - Java_sun_awt_motif_MEmbedCanvasPeer_getClientBounds; - Java_sun_awt_motif_MEmbedCanvasPeer_notifyChildEmbedded; - Java_sun_awt_motif_MEmbedCanvasPeer_detachChild; - Java_sun_awt_motif_MEmbedCanvasPeer_forwardKeyEvent; - Java_sun_awt_motif_MEmbedCanvasPeer_getAWTKeyCodeForKeySym; - Java_sun_awt_motif_MEmbedCanvasPeer_sendMessage__I; - Java_sun_awt_motif_MEmbedCanvasPeer_sendMessage__IJJJ; - Java_sun_awt_motif_MEmbedCanvasPeer_getWindow; - Java_sun_awt_motif_MEmbedCanvasPeer_forwardEventToEmbedded; - Java_sun_awt_motif_GrabbedKey_initKeySymAndModifiers; - Java_sun_awt_motif_MEmbeddedFramePeer_traverseOut; + #Java_sun_awt_motif_MEmbedCanvasPeer_initXEmbedServer; + #Java_sun_awt_motif_MEmbedCanvasPeer_destroyXEmbedServer; + #Java_sun_awt_motif_MEmbedCanvasPeer_isXEmbedActive; + #Java_sun_awt_motif_MEmbedCanvasPeer_initDispatching; + #Java_sun_awt_motif_MEmbedCanvasPeer_endDispatching; + #Java_sun_awt_motif_MEmbedCanvasPeer_embedChild; + #Java_sun_awt_motif_MEmbedCanvasPeer_childDestroyed; + #Java_sun_awt_motif_MEmbedCanvasPeer_getEmbedPreferredSize; + #Java_sun_awt_motif_MEmbedCanvasPeer_getEmbedMinimumSize; + #Java_sun_awt_motif_MEmbedCanvasPeer_getClientBounds; + #Java_sun_awt_motif_MEmbedCanvasPeer_notifyChildEmbedded; + #Java_sun_awt_motif_MEmbedCanvasPeer_detachChild; + #Java_sun_awt_motif_MEmbedCanvasPeer_forwardKeyEvent; + #Java_sun_awt_motif_MEmbedCanvasPeer_getAWTKeyCodeForKeySym; + #Java_sun_awt_motif_MEmbedCanvasPeer_sendMessage__I; + #Java_sun_awt_motif_MEmbedCanvasPeer_sendMessage__IJJJ; + #Java_sun_awt_motif_MEmbedCanvasPeer_getWindow; + #Java_sun_awt_motif_MEmbedCanvasPeer_forwardEventToEmbedded; + #Java_sun_awt_motif_GrabbedKey_initKeySymAndModifiers; + #Java_sun_awt_motif_MEmbeddedFramePeer_traverseOut; awt_display; awt_lock; awt_Lock; diff --git a/jdk/make/sun/awt/mawt.gmk b/jdk/make/sun/awt/mawt.gmk index ffe222c9a2e..c7d1b41d02b 100644 --- a/jdk/make/sun/awt/mawt.gmk +++ b/jdk/make/sun/awt/mawt.gmk @@ -28,14 +28,6 @@ # INIT += $(LIB_LOCATION) -ifndef HEADLESS -ifeq ($(PLATFORM), linux) -ifeq ($(STATIC_MOTIF),false) -INIT += $(LIB_LOCATION)/libXm.so -endif -endif -endif - # # Files # @@ -52,13 +44,9 @@ include $(BUILDDIR)/sun/awt/FILES_export_unix.gmk ifdef HEADLESS FILES_c = $(FILES_NO_MOTIF_c) else - FILES_c = $(FILES_MOTIF_c) $(FILES_NO_MOTIF_c) - - ifeq ($(MOTIF_VERSION), 2) - FILES_c += awt_motif21.c - FILES_c += awt_Choice21.c - endif - +# FILES_c = $(FILES_MOTIF_c) $(FILES_NO_MOTIF_c) +# XXX if in FILES_MOTIF_c there are unrelated to motif stuff, create a separate list! + FILES_c = $(FILES_NO_MOTIF_c) endif ifeq ($(PLATFORM), solaris) @@ -93,15 +81,6 @@ include $(BUILDDIR)/common/Library.gmk $(LIB_LOCATION): $(MKDIR) -p $@ -ifeq ($(PLATFORM), linux) -ifeq ($(STATIC_MOTIF),false) -$(LIB_LOCATION)/libXm.so: - $(CP) $(MOTIF_LIB)/libXm.so $(LIB_LOCATION)/libXm.so -# Automounter problem makes the link fail on Redhat 6.1. -# $(LN) -s $(MOTIF_LIB)/libXm.so $(LIB_LOCATION)/libXm.so -endif -endif - clean:: # @@ -135,33 +114,49 @@ CFLAGS += -DHEADLESS=$(HEADLESS) CPPFLAGS += -DHEADLESS=$(HEADLESS) OTHER_LDLIBS = else -CFLAGS += -DMOTIF_VERSION=$(MOTIF_VERSION) +#CFLAGS += -DMOTIF_VERSION=$(MOTIF_VERSION) -ifeq ($(STATIC_MOTIF),true) - LIBXM = $(MOTIF_LIB)/libXm.a -lXp -lXmu - ifeq ($(PLATFORM), linux) - ifeq ($(ARCH_DATA_MODEL), 64) - LIBXT = -lXt - else - # Allows for builds on Debian GNU Linux, X11 is in a different place - LIBXT = $(firstword $(wildcard /usr/X11R6/lib/libXt.a) \ - $(wildcard /usr/lib/libXt.a)) - LIBSM = $(firstword $(wildcard /usr/X11R6/lib/libSM.a) \ - $(wildcard /usr/lib/libSM.a)) - LIBICE = $(firstword $(wildcard /usr/X11R6/lib/libICE.a) \ - $(wildcard /usr/lib/libICE.a)) - endif - endif -else - LIBXM = -L$(MOTIF_LIB) -lXm -lXp - ifeq ($(PLATFORM), linux) - LIBXT = -lXt - LIBSM = - LIBICE = - endif -endif +#ifeq ($(STATIC_MOTIF),true) +# LIBXM = $(MOTIF_LIB)/libXm.a -lXp -lXmu +# ifeq ($(PLATFORM), linux) +# ifeq ($(ARCH_DATA_MODEL), 64) +# LIBXT = -lXt +# else +# # Allows for builds on Debian GNU Linux, X11 is in a different place +# LIBXT = $(firstword $(wildcard /usr/X11R6/lib/libXt.a) \ +# $(wildcard /usr/lib/libXt.a)) +# LIBSM = $(firstword $(wildcard /usr/X11R6/lib/libSM.a) \ +# $(wildcard /usr/lib/libSM.a)) +# LIBICE = $(firstword $(wildcard /usr/X11R6/lib/libICE.a) \ +# $(wildcard /usr/lib/libICE.a)) +# endif +# endif +#else +# LIBXM = -L$(MOTIF_LIB) -lXm -lXp +# ifeq ($(PLATFORM), linux) +# LIBXT = -lXt +# LIBSM = +# LIBICE = +# endif +#endif LIBXTST = -lXtst +ifeq ($(PLATFORM), linux) + ifeq ($(ARCH_DATA_MODEL), 64) + # XXX what about the rest of them? + LIBXT = -lXt + else + # Allows for builds on Debian GNU Linux, X11 is in a different place + LIBXT = $(firstword $(wildcard /usr/X11R6/lib/libXt.a) \ + $(wildcard /usr/lib/libXt.a)) + LIBSM = $(firstword $(wildcard /usr/X11R6/lib/libSM.a) \ + $(wildcard /usr/lib/libSM.a)) + LIBICE = $(firstword $(wildcard /usr/X11R6/lib/libICE.a) \ + $(wildcard /usr/lib/libICE.a)) + LIBXTST = $(firstword $(wildcard /usr/X11R6/lib/libXtst.a) \ + $(wildcard /usr/lib/libXtst.a)) + endif +endif # Use -lXmu for EditRes support LIBXMU_DBG = -lXmu @@ -169,14 +164,14 @@ LIBXMU_OPT = LIBXMU = $(LIBXMU_$(VARIANT)) ifeq ($(PLATFORM), solaris) -OTHER_LDLIBS = $(LIBXM) -lXt -lXext $(LIBXTST) $(LIBXMU) -lX11 -lXi +OTHER_LDLIBS = -lXt -lXext $(LIBXTST) $(LIBXMU) -lX11 -lXi endif ifeq ($(PLATFORM), linux) OTHER_CFLAGS += -DMLIB_NO_LIBSUNMATH -OTHER_CFLAGS += -DMOTIF_VERSION=2 +# XXX what is this define below? Isn't it motif-related? OTHER_CFLAGS += -DXMSTRINGDEFINES=1 -OTHER_LDLIBS = $(LIBXM) $(LIBXMU) $(LIBXTST) -lXext $(LIBXT) $(LIBSM) $(LIBICE) -lX11 -lXi +OTHER_LDLIBS = $(LIBXMU) $(LIBXTST) -lXext $(LIBXT) $(LIBSM) $(LIBICE) -lX11 -lXi endif endif @@ -199,9 +194,8 @@ endif CPPFLAGS += -I$(CUPS_HEADERS_PATH) ifndef HEADLESS -CPPFLAGS += -I$(MOTIF_DIR)/include \ - -I$(OPENWIN_HOME)/include -LDFLAGS += -L$(MOTIF_LIB) -L$(OPENWIN_LIB) +CPPFLAGS += -I$(OPENWIN_HOME)/include +LDFLAGS += -L$(OPENWIN_LIB) endif # !HEADLESS diff --git a/jdk/make/sun/jawt/Makefile b/jdk/make/sun/jawt/Makefile index 4f733e4cfd6..96723281450 100644 --- a/jdk/make/sun/jawt/Makefile +++ b/jdk/make/sun/jawt/Makefile @@ -93,7 +93,6 @@ else # PLATFORM # Other extra flags needed for compiling. # CPPFLAGS += -I$(OPENWIN_HOME)/include \ - -I$(MOTIF_DIR)/include \ -I$(SHARE_SRC)/native/$(PKGDIR)/debug \ -I$(SHARE_SRC)/native/$(PKGDIR)/image \ -I$(SHARE_SRC)/native/$(PKGDIR)/image/cvutils \ diff --git a/jdk/src/solaris/classes/sun/awt/motif/MButtonPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MButtonPeer.java deleted file mode 100644 index 0fbb4420ebf..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MButtonPeer.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 1995-2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.ActionEvent; - -class MButtonPeer extends MComponentPeer implements ButtonPeer { - native void create(MComponentPeer peer); - public native void setLabel(String label); - - MButtonPeer(Button target) { - super(target); - } - - public Dimension getMinimumSize() { - FontMetrics fm = getFontMetrics(target.getFont()); - String label = ((Button)target).getLabel(); - if ( label == null ) { - label = ""; - } - return new Dimension(fm.stringWidth(label) + 14, - fm.getHeight() + 8); - } - - public boolean isFocusable() { - return true; - } - - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void action(final long when, final int modifiers) { - MToolkit.executeOnEventHandlerThread(target, new Runnable() { - public void run() { - postEvent(new ActionEvent(target, ActionEvent.ACTION_PERFORMED, - ((Button)target).getActionCommand(), - when, modifiers)); - } - }); - } - - /* - * Print the native component by rendering the Motif look ourselves. - * ToDo(aim): needs to query native motif for more accurate size and - * color information. - */ - public void print(Graphics g) { - Button b = (Button)target; - Dimension d = b.size(); - Color bg = b.getBackground(); - Color fg = b.getForeground(); - - g.setColor(bg); - g.fillRect(2, 2, d.width - 3, d.height - 3); - draw3DRect(g, bg, 1, 1, d.width - 2, d.height - 2, true); - - g.setColor(fg); - g.setFont(b.getFont()); - FontMetrics fm = g.getFontMetrics(); - String lbl = b.getLabel(); - g.drawString(lbl, (d.width - fm.stringWidth(lbl)) / 2, - (d.height + fm.getMaxAscent() - fm.getMaxDescent()) / 2); - - target.print(g); - } - - /** - * DEPRECATED - */ - public Dimension minimumSize() { - return getMinimumSize(); - } - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MCanvasPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MCanvasPeer.java deleted file mode 100644 index c7063ac6a18..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MCanvasPeer.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 1995-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import sun.awt.DisplayChangedListener; -import sun.awt.X11GraphicsConfig; -import sun.awt.X11GraphicsDevice; -import sun.awt.X11GraphicsEnvironment; - -class MCanvasPeer extends MComponentPeer implements CanvasPeer, - DisplayChangedListener { - - native void create(MComponentPeer parent); - private static native void initIDs(); - static { - initIDs(); - } - - MCanvasPeer() {} - - MCanvasPeer(Component target) { - super(target); - } - - MCanvasPeer(Component target, Object arg) { - super(target, arg); - } - -/* --- DisplayChangedListener Stuff --- */ - public void displayChanged() {} - public void paletteChanged() {} - native void resetTargetGC(Component target); - - /* - * Called when the Window this - * Canvas is on is moved onto another Xinerama screen. - * - * Canvases can be created with a non-defulat GraphicsConfiguration. The - * GraphicsConfiguration needs to be changed to one on the new screen, - * preferably with the same visual ID. - * - * Up-called for other windows peer instances (WPanelPeer, WWindowPeer). - * - * Should only be called from the event thread. - */ - public void displayChanged(int screenNum) { - resetLocalGC(screenNum); - resetTargetGC(target); /* call Canvas.setGCFromPeer() via native */ - } - - /* Set graphicsConfig to a GraphicsConfig with the same visual on the new - * screen, which should be easy in Xinerama mode. - * - * Should only be called from displayChanged(), and therefore only from - * the event thread. - */ - void resetLocalGC(int screenNum) { - // Opt: Only need to do if we're not using the default GC - if (graphicsConfig != null) { - X11GraphicsConfig parentgc; - // save vis id of current gc - int visual = graphicsConfig.getVisual(); - - X11GraphicsDevice newDev = (X11GraphicsDevice) GraphicsEnvironment. - getLocalGraphicsEnvironment(). - getScreenDevices()[screenNum]; - - for (int i = 0; i < newDev.getNumConfigs(screenNum); i++) { - if (visual == newDev.getConfigVisualId(i, screenNum)) { - // use that - graphicsConfig = (X11GraphicsConfig)newDev.getConfigurations()[i]; - break; - } - } - // just in case... - if (graphicsConfig == null) { - graphicsConfig = (X11GraphicsConfig) GraphicsEnvironment. - getLocalGraphicsEnvironment(). - getScreenDevices()[screenNum]. - getDefaultConfiguration(); - } - } - } - - protected boolean shouldFocusOnClick() { - // Canvas should always be able to be focused by mouse clicks. - return true; - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MCheckboxMenuItemPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MCheckboxMenuItemPeer.java deleted file mode 100644 index 6acc0bfd6a4..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MCheckboxMenuItemPeer.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 1995-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - - -import java.awt.*; -import java.awt.event.*; -import java.awt.peer.*; - -class MCheckboxMenuItemPeer extends MMenuItemPeer - implements CheckboxMenuItemPeer { - private boolean inUpCall=false; - private boolean inInit=false; - - native void pSetState(boolean t); - native boolean getState(); - - void create(MMenuPeer parent) { - super.create(parent); - inInit=true; - setState(((CheckboxMenuItem)target).getState()); - inInit=false; - } - - MCheckboxMenuItemPeer(CheckboxMenuItem target) { - this.target = target; - isCheckbox = true; - MMenuPeer parent = (MMenuPeer) MToolkit.targetToPeer(getParent_NoClientCode(target)); - create(parent); - } - - public void setState(boolean t) { - if (!nativeCreated) { - return; - } - if (!inUpCall && (t != getState())) { - pSetState(t); - if (!inInit) { - // 4135725 : do not notify on programatic changes - // notifyStateChanged(t); - } - } - } - - void notifyStateChanged(boolean state) { - CheckboxMenuItem cb = (CheckboxMenuItem)target; - ItemEvent e = new ItemEvent(cb, - ItemEvent.ITEM_STATE_CHANGED, - cb.getLabel(), - state ? ItemEvent.SELECTED : ItemEvent.DESELECTED); - postEvent(e); - } - - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void action(long when, int modifiers, boolean state) { - final CheckboxMenuItem cb = (CheckboxMenuItem)target; - final boolean newState = state; - - MToolkit.executeOnEventHandlerThread(cb, new Runnable() { - public void run() { - cb.setState(newState); - notifyStateChanged(newState); - } - }); - //Fix for 5005195: MAWT: CheckboxMenuItem fires action events - //super.action() is not invoked - } // action() -} // class MCheckboxMenuItemPeer diff --git a/jdk/src/solaris/classes/sun/awt/motif/MCheckboxPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MCheckboxPeer.java deleted file mode 100644 index c2e4ac21e8f..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MCheckboxPeer.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright 1995-2000 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.*; - -public class MCheckboxPeer extends MComponentPeer implements CheckboxPeer { - private boolean inUpCall = false; - private boolean inInit=false; - - native void create(MComponentPeer parent); - native void pSetState(boolean state); - native boolean pGetState(); - - public native void setLabel(String label); - public native void setCheckboxGroup(CheckboxGroup g); - - - void initialize() { - Checkbox t = (Checkbox)target; - inInit=true; - - setState(t.getState()); - setCheckboxGroup(t.getCheckboxGroup()); - super.initialize(); - inInit=false; - } - - public MCheckboxPeer(Checkbox target) { - super(target); - } - - public boolean isFocusable() { - return true; - } - - public void setState(boolean state) { - if (inInit) { - pSetState(state); - } else if (!inUpCall && (state != pGetState())) { - pSetState(state); - // 4135725 : do not notify on programatic changes - // notifyStateChanged(state); - } - } - private native int getIndicatorSize(); - private native int getSpacing(); - - public Dimension getMinimumSize() { - String lbl = ((Checkbox)target).getLabel(); - if (lbl == null) { - lbl = ""; - } - FontMetrics fm = getFontMetrics(target.getFont()); - /* - * Spacing (number of pixels between check mark and label text) is - * currently set to 0, but in case it ever changes we have to add - * it. 8 is a heuristic number. Indicator size depends on font - * height, so we don't need to include it in checkbox's height - * calculation. - */ - int wdth = fm.stringWidth(lbl) + getIndicatorSize() + getSpacing() + 8; - int hght = Math.max(fm.getHeight() + 8, 15); - return new Dimension(wdth, hght); - } - - - void notifyStateChanged(boolean state) { - Checkbox cb = (Checkbox) target; - ItemEvent e = new ItemEvent(cb, - ItemEvent.ITEM_STATE_CHANGED, - cb.getLabel(), - state ? ItemEvent.SELECTED : ItemEvent.DESELECTED); - postEvent(e); - } - - - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - void action(boolean state) { - final Checkbox cb = (Checkbox)target; - final boolean newState = state; - MToolkit.executeOnEventHandlerThread(cb, new Runnable() { - public void run() { - CheckboxGroup cbg = cb.getCheckboxGroup(); - /* Bugid 4039594. If this is the current Checkbox in - * a CheckboxGroup, then return to prevent deselection. - * Otherwise, it's logical state will be turned off, - * but it will appear on. - */ - if ((cbg != null) && (cbg.getSelectedCheckbox() == cb) && - cb.getState()) { - inUpCall = false; - cb.setState(true); - return; - } - // All clear - set the new state - cb.setState(newState); - notifyStateChanged(newState); - } // run() - }); - } // action() - - - - static final int SIZE = 19; - static final int BORDER = 4; - static final int SIZ = SIZE - BORDER*2 - 1; - - /* - * Print the native component by rendering the Motif look ourselves. - * ToDo(aim): needs to query native motif for more accurate size and - * color information; need to render check mark. - */ - public void print(Graphics g) { - Checkbox cb = (Checkbox)target; - Dimension d = cb.size(); - Color bg = cb.getBackground(); - Color fg = cb.getForeground(); - Color shadow = bg.darker(); - int x = BORDER; - int y = ((d.height - SIZE) / 2) + BORDER; - - g.setColor(cb.getState()? shadow : bg); - - if (cb.getCheckboxGroup() != null) { - g.fillOval(x, y, SIZ, SIZ); - draw3DOval(g, bg, x, y, SIZ, SIZ, !(cb.getState())); - if (cb.getState()) { - g.setColor(fg); - g.fillOval(x + 3, y + 3, SIZ - 6, SIZ - 6); - } - } else { - g.fillRect(x, y, SIZ, SIZ); - draw3DRect(g, bg, x, y, SIZ, SIZ, !(cb.getState())); - if (cb.getState()) { - g.setColor(fg); - g.drawLine(x+1, y+1, x+SIZ-1, y+SIZ-1); - g.drawLine(x+1, y+SIZ-1, x+SIZ-1, y+1); - } - } - g.setColor(fg); - String lbl = cb.getLabel(); - if (lbl != null) { - // REMIND: align - g.setFont(cb.getFont()); - FontMetrics fm = g.getFontMetrics(); - g.drawString(lbl, SIZE, - (d.height + fm.getMaxAscent() - fm.getMaxDescent()) / 2); - } - - target.print(g); - } - - /** - * DEPRECATED - */ - public Dimension minimumSize() { - return getMinimumSize(); - } - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MChoicePeer.java b/jdk/src/solaris/classes/sun/awt/motif/MChoicePeer.java deleted file mode 100644 index 1a6b32d8b63..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MChoicePeer.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.ItemEvent; - -class MChoicePeer extends MComponentPeer implements ChoicePeer { - boolean inUpCall=false; - - native void create(MComponentPeer parent); - native void pReshape(int x, int y, int width, int height); - native void pSelect(int index, boolean init); - native void appendItems(String[] items); - - void initialize() { - Choice opt = (Choice)target; - int itemCount = opt.countItems(); - String[] items = new String[itemCount]; - for (int i=0; i < itemCount; i++) { - items[i] = opt.getItem(i); - } - if (itemCount > 0) { - appendItems(items); - pSelect(opt.getSelectedIndex(), true); - } - super.initialize(); - } - - public MChoicePeer(Choice target) { - super(target); - } - - public boolean isFocusable() { - return true; - } - - public Dimension getMinimumSize() { - FontMetrics fm = getFontMetrics(target.getFont()); - Choice c = (Choice)target; - int w = 0; - for (int i = c.countItems() ; i-- > 0 ;) { - w = Math.max(fm.stringWidth(c.getItem(i)), w); - } - return new Dimension(32 + w, Math.max(fm.getHeight() + 8, 15) + 5); - } - - public native void setFont(Font f); - - public void add(String item, int index) { - addItem(item, index); - // Adding an item can change the size of the Choice, so do - // a reshape, based on the font size. - Rectangle r = target.getBounds(); - reshape(r.x, r.y, 0, 0); - } - - public native void remove(int index); - - public native void removeAll(); - - /** - * DEPRECATED, but for now, called by add(String, int). - */ - public native void addItem(String item, int index); - - // public native void remove(int index); - - public native void setBackground(Color c); - - public native void setForeground(Color c); - - public void select(int index) { - if (!inUpCall) { - pSelect(index, false); - } - } - - void notifySelection(String item) { - Choice c = (Choice)target; - ItemEvent e = new ItemEvent(c, ItemEvent.ITEM_STATE_CHANGED, - item, ItemEvent.SELECTED); - postEvent(e); - } - - - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - void action(final int index) { - final Choice c = (Choice)target; - inUpCall = false; /* Used to prevent native selection. */ - MToolkit.executeOnEventHandlerThread(c, new Runnable() { - public void run() { - String item; - synchronized(c) { - if (index >= c.getItemCount()) { - /* Nothing to do when the list is too short */ - return; - } - inUpCall = true; /* Prevent native selection. */ - c.select(index); /* set value in target */ - item = c.getItem(index); - inUpCall = false; - } - notifySelection(item); - } - }); - } - - /* - * Print the native component by rendering the Motif look ourselves. - * ToDo(aim): needs to query native motif for more accurate size and - * color information. - */ - public void print(Graphics g) { - Choice ch = (Choice)target; - Dimension d = ch.size(); - Color bg = ch.getBackground(); - Color fg = ch.getForeground(); - - g.setColor(bg); - g.fillRect(2, 2, d.width-1, d.height-1); - draw3DRect(g, bg, 1, 1, d.width-2, d.height-2, true); - draw3DRect(g, bg, d.width - 18, (d.height / 2) - 3, 10, 6, true); - - g.setColor(fg); - g.setFont(ch.getFont()); - FontMetrics fm = g.getFontMetrics(); - String lbl = ch.getSelectedItem(); - if (lbl == null){ - lbl = ""; - } - if (lbl != ""){ - g.drawString(lbl, 5, (d.height + fm.getMaxAscent()-fm.getMaxDescent())/2); - } - - target.print(g); - } - - /** - * DEPRECATED - */ - public Dimension minimumSize() { - return getMinimumSize(); - } - - protected void disposeImpl() { - freeNativeData(); - super.disposeImpl(); - } - - private native void freeNativeData(); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MComponentPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MComponentPeer.java deleted file mode 100644 index 23c06c363c4..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MComponentPeer.java +++ /dev/null @@ -1,1182 +0,0 @@ -/* - * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.PaintEvent; -import java.awt.event.MouseEvent; -import java.awt.event.InputEvent; - -import sun.awt.*; -import sun.awt.image.ToolkitImage; -import sun.awt.image.SunVolatileImage; -import java.awt.image.ImageProducer; -import java.awt.image.ImageObserver; -import java.awt.image.ColorModel; -import java.awt.image.VolatileImage; - -import java.awt.dnd.DropTarget; -import java.awt.dnd.peer.DropTargetPeer; - -import sun.java2d.SunGraphics2D; -import sun.java2d.SurfaceData; - -import java.lang.reflect.Method; - -import java.util.logging.*; - -import sun.java2d.pipe.Region; - - -public /* REMIND: should not be public */ -abstract class MComponentPeer implements ComponentPeer, DropTargetPeer, X11ComponentPeer { - - private static final Logger log = Logger.getLogger("sun.awt.motif.MComponentPeer"); - private static final Logger focusLog = Logger.getLogger("sun.awt.motif.focus.MComponentPeer"); - - Component target; - long pData; - long jniGlobalRef; - protected X11GraphicsConfig graphicsConfig; - SurfaceData surfaceData; - int oldWidth = -1; - int oldHeight = -1; - - private RepaintArea paintArea; - - boolean isLayouting = false; - boolean paintPending = false; - - protected boolean disposed = false; - private static int JAWT_LOCK_ERROR=0x00000001; - private static int JAWT_LOCK_CLIP_CHANGED=0x00000002; - private static int JAWT_LOCK_BOUNDS_CHANGED=0x00000004; - private static int JAWT_LOCK_SURFACE_CHANGED=0x00000008; - private int drawState = JAWT_LOCK_CLIP_CHANGED | - JAWT_LOCK_BOUNDS_CHANGED | - JAWT_LOCK_SURFACE_CHANGED; - - /* These are the enumerated types in awt_p.h*/ - static final int MOTIF_NA = 0 ; - static final int MOTIF_V1 = 1 ; - static final int MOTIF_V2 = 2 ; - - private Font font; - private long backBuffer = 0; - private VolatileImage xBackBuffer = null; - - static { - initIDs(); - } - - /* initialize the fieldIDs of fields that may be accessed from C */ - private native static void initIDs(); - - - /* This will return the last state of a window. ie the specific - * "gotcha" is that if you iconify a window its obscurity remains - * unchanged. Current use of this is just in user-initiated scrolling. - * If that use expands to more cases you may need to "and" this with - * the value of the iconic state of a Frame. - * Note that de-iconifying an X11 window DOES generate a new event - * correctly notifying you of the new visibility of the window - */ - public boolean isObscured() { - - Container container = (target instanceof Container) ? - (Container)target : target.getParent(); - - if (container == null) { - return true; - } - - Container parent; - while ((parent = container.getParent()) != null) { - container = parent; - } - - if (container instanceof Window) { - MWindowPeer wpeer = (MWindowPeer)(container.getPeer()); - if (wpeer != null) { - return (wpeer.winAttr.visibilityState != - MWindowAttributes.AWT_UNOBSCURED); - } - } - return true; - } - - public boolean canDetermineObscurity() { - return true; - } - - abstract void create(MComponentPeer parent); - void create(MComponentPeer parent, Object arg) { - create(parent); - } - - void EFcreate(MComponentPeer parent, int x){} - - native void pInitialize(); - native void pShow(); - native void pHide(); - native void pEnable(); - native void pDisable(); - native void pReshape(int x, int y, int width, int height); - native void pDispose(); - native void pMakeCursorVisible(); - native Point pGetLocationOnScreen(); - native Point pGetLocationOnScreen2(Window win, MWindowPeer wpeer); - native void pSetForeground(Color c); - native void pSetBackground(Color c); - private native void pSetFont(Font f); - - //Added for bug 4175560 - //Returns the native representation for the Color argument, - //using the given GraphicsConfiguration. - native int getNativeColor(Color clr, GraphicsConfiguration gc); - - // Returns the parent of the component, without invoking client - // code. This must go through native code, because it invokes - // private methods in the java.awt package, which we cannot - // do from this package. - static native Container getParent_NoClientCode(Component component); - - // Returns the parent of the component, without invoking client - // code. This must go through native code, because it invokes - // private methods in the java.awt package, which we cannot - // do from this package. - static native Component[] getComponents_NoClientCode(Container container); - - void initialize() { - if (!target.isVisible()) { - hide(); - } - Color c; - Font f; - Cursor cursor; - - pInitialize(); - - if ((c = target.getForeground()) != null) { - setForeground(c); - } - if ((c = target.getBackground()) != null) { - setBackground(c); - } - if ((f = target.getFont()) != null) { - setFont(f); - } - pSetCursor(target.getCursor()); - if (!target.isEnabled()) { - disable(); - } - Rectangle r = target.getBounds(); - reshape(r.x, r.y, r.width, r.height); - if (target.isVisible()) { - show(); - } - - surfaceData = graphicsConfig.createSurfaceData(this); - } - - public void init(Component target, Object arg) { - this.target = target; - this.paintArea = new RepaintArea(); - - Container parent = MToolkit.getNativeContainer(target); - MComponentPeer parentPeer = (MComponentPeer) MToolkit.targetToPeer(parent); - create(parentPeer, arg); - - initialize(); - } - - MComponentPeer(Component target, Object arg) { - init(target, arg); - } - - MComponentPeer() {} - - public void init(Component target) { - this.target = target; - this.paintArea = new RepaintArea(); - - Container parent = MToolkit.getNativeContainer(target); - MComponentPeer parentPeer = (MComponentPeer) MToolkit.targetToPeer(parent); - create(parentPeer); - - if (parent != null && parent instanceof ScrollPane) { - MScrollPanePeer speer = (MScrollPanePeer) parentPeer; - speer.setScrollChild(this); - } - initialize(); - } - - MComponentPeer(Component target) { - init(target); - } - - protected void finalize() throws Throwable { - dispose(); - super.finalize(); - } - - public void setForeground(Color c) { - pSetForeground(c); - } - - public void setBackground(Color c) { - pSetBackground(c); - } - - public void updateCursorImmediately() { - MGlobalCursorManager.getCursorManager().updateCursorImmediately(); - } - - public void setFont(Font f) { - ComponentPeer peer; - if (f == null) { - f = defaultFont; - } - pSetFont(f); - if ( target instanceof Container ) { - Container container = (Container) target; - int count = container.getComponentCount(); - Component[] children = container.getComponents(); - for (int i=0; i>1)); - v2 = 7; - } - - int ctr = thickness/2; - int sbmin = ctr - w2/2; - int sbmax = ctr + w2/2; - - // paint the background slightly darker - { - Color d = new Color((int) (bg.getRed() * 0.85), - (int) (bg.getGreen() * 0.85), - (int) (bg.getBlue() * 0.85)); - - g.setColor(d); - if (horizontal) { - g.fillRect(0, 0, length, thickness); - } else { - g.fillRect(0, 0, thickness, length); - } - } - - // paint the thumb and arrows in the normal background color - g.setColor(bg); - if (v1 > 0) { - if (horizontal) { - g.fillRect(v1, 3, v2, thickness-3); - } else { - g.fillRect(3, v1, thickness-3, v2); - } - } - - tpts_x[0] = ctr; tpts_y[0] = 2; - tpts_x[1] = sbmin; tpts_y[1] = w2; - tpts_x[2] = sbmax; tpts_y[2] = w2; - if (horizontal) { - g.fillPolygon(tpts_y, tpts_x, 3); - } else { - g.fillPolygon(tpts_x, tpts_y, 3); - } - - tpts_y[0] = length-2; - tpts_y[1] = length-w2; - tpts_y[2] = length-w2; - if (horizontal) { - g.fillPolygon(tpts_y, tpts_x, 3); - } else { - g.fillPolygon(tpts_x, tpts_y, 3); - } - - Color highlight = bg.brighter(); - - // // // // draw the "highlighted" edges - g.setColor(highlight); - - // outline & arrows - if (horizontal) { - g.drawLine(1, thickness, length - 1, thickness); - g.drawLine(length - 1, 1, length - 1, thickness); - - // arrows - g.drawLine(1, ctr, w2, sbmin); - g.drawLine(length - w2, sbmin, length - w2, sbmax); - g.drawLine(length - w2, sbmin, length - 2, ctr); - - } else { - g.drawLine(thickness, 1, thickness, length - 1); - g.drawLine(1, length - 1, thickness, length - 1); - - // arrows - g.drawLine(ctr, 1, sbmin, w2); - g.drawLine(sbmin, length - w2, sbmax, length - w2); - g.drawLine(sbmin, length - w2, ctr, length - 2); - } - - // thumb - if (v1 > 0) { - if (horizontal) { - g.drawLine(v1, 2, v1 + v2, 2); - g.drawLine(v1, 2, v1, thickness-3); - } else { - g.drawLine(2, v1, 2, v1 + v2); - g.drawLine(2, v1, thickness-3, v1); - } - } - - Color shadow = bg.darker(); - - // // // // draw the "shadowed" edges - g.setColor(shadow); - - // outline && arrows - if (horizontal) { - g.drawLine(0, 0, 0, thickness); - g.drawLine(0, 0, length - 1, 0); - - // arrows - g.drawLine(w2, sbmin, w2, sbmax); - g.drawLine(w2, sbmax, 1, ctr); - g.drawLine(length-2, ctr, length-w2, sbmax); - - } else { - g.drawLine(0, 0, thickness, 0); - g.drawLine(0, 0, 0, length - 1); - - // arrows - g.drawLine(sbmin, w2, sbmax, w2); - g.drawLine(sbmax, w2, ctr, 1); - g.drawLine(ctr, length-2, sbmax, length-w2); - } - - // thumb - if (v1 > 0) { - if (horizontal) { - g.drawLine(v1 + v2, 2, v1 + v2, thickness-2); - g.drawLine(v1, thickness-2, v1 + v2, thickness-2); - } else { - g.drawLine(2, v1 + v2, thickness-2, v1 + v2); - g.drawLine(thickness-2, v1, thickness-2, v1 + v2); - } - } - g.setColor(c); - } - - public String toString() { - return getClass().getName() + "[" + target + "]"; - } - - /* New 1.1 API */ - public void setVisible(boolean b) { - if (b) { - Dimension s = target.getSize(); - oldWidth = s.width; - oldHeight = s.height; - pShow(); - } else { - pHide(); - } - } - - /* New 1.1 API */ - public void setEnabled(boolean b) { - if (b) { - pEnable(); - } else { - pDisable(); - } - } - - /* New 1.1 API */ - public Point getLocationOnScreen() { - synchronized (target.getTreeLock()) { - Component comp = target; - while (comp != null && !(comp instanceof Window)) { - comp = getParent_NoClientCode(comp); - } - - // applets, embedded, etc - translate directly - if (comp == null || comp instanceof sun.awt.EmbeddedFrame) { - return pGetLocationOnScreen(); - } - - MWindowPeer wpeer = (MWindowPeer)(MToolkit.targetToPeer(comp)); - if (wpeer == null) { - return pGetLocationOnScreen(); - } - return pGetLocationOnScreen2((Window)comp, wpeer); - } - } - - public int serialNum = 0; - - /* Returns the native paint should be posted after setting new size - */ - public boolean checkNativePaintOnSetBounds(int width, int height) { - return (width != oldWidth) || (height != oldHeight); - } - - void setBounds(int x, int y, int width, int height) { - setBounds(x, y, width, height, SET_BOUNDS); - } - - /* New 1.1 API */ - public void setBounds(int x, int y, int width, int height, int op) { - if (disposed) return; - - Container parent = getParent_NoClientCode(target); - - // Should set paintPending before reshape to prevent - // thread race between PaintEvent and setBounds - // This part of the 4267393 fix proved to be unstable under solaris, - // dissabled due to regressions 4418155, 4486762, 4490079 - paintPending = false; //checkNativePaintOnSetBounds(width, height); - - // Note: it would be ideal to NOT execute this if it's - // merely a Move which is occurring. - if (parent != null && parent instanceof ScrollPane) { - MScrollPanePeer speer = (MScrollPanePeer)parent.getPeer(); - if (!speer.ignore) { - pReshape(x, y, width, height); - speer.childResized(width, height); - } - } else { - pReshape(x, y, width, height); - } - - if ((width != oldWidth) || (height != oldHeight)) { - SurfaceData oldData = surfaceData; - if (oldData != null) { - surfaceData = graphicsConfig.createSurfaceData(this); - oldData.invalidate(); - } - oldWidth = width; - oldHeight = height; - } - validateSurface(width, height); - serialNum++; - } - - void validateSurface(int width, int height) { - SunToolkit.awtLock(); - try { - if (!disposed && (width != oldWidth || height != oldHeight)) { - SurfaceData oldData = surfaceData; - if (oldData != null) { - surfaceData = graphicsConfig.createSurfaceData(this); - oldData.invalidate(); - } - oldWidth = width; - oldHeight = height; - } - } finally { - SunToolkit.awtUnlock(); - } - } - - public void beginValidate() { - } - - native void restoreFocus(); - - public void endValidate() { - restoreFocus(); - } - - public void beginLayout() { - // Skip all painting till endLayout - isLayouting = true; - } - - public void endLayout() { - if (!paintPending && !paintArea.isEmpty() && - !((Component)target).getIgnoreRepaint()) { - // if not waiting for native painting repaint damaged area - postEvent(new PaintEvent((Component)target, PaintEvent.PAINT, - new Rectangle())); - } - isLayouting = false; - } - - /** - * DEPRECATED: Replaced by setVisible(boolean). - */ - public void show() { - setVisible(true); - } - - /** - * DEPRECATED: Replaced by setVisible(boolean). - */ - public void hide() { - setVisible(false); - } - - /** - * DEPRECATED: Replaced by setEnabled(boolean). - */ - public void enable() { - setEnabled(true); - } - - /** - * DEPRECATED: Replaced by setEnabled(boolean). - */ - public void disable() { - setEnabled(false); - } - - /** - * DEPRECATED: Replaced by setBounds(int, int, int, int). - */ - public void reshape(int x, int y, int width, int height) { - setBounds(x, y, width, height); - } - - /** - * DEPRECATED: Replaced by getMinimumSize(). - */ - public Dimension minimumSize() { - return getMinimumSize(); - } - - /** - * DEPRECATED: Replaced by getPreferredSize(). - */ - public Dimension preferredSize() { - return getPreferredSize(); - } - - /** - * - */ - - public void addDropTarget(DropTarget dt) { - if (MToolkit.useMotifDnD()) { - addNativeDropTarget(dt); - } else { - Component comp = target; - while(!(comp == null || comp instanceof java.awt.Window)) { - comp = getParent_NoClientCode(comp); - } - - if (comp instanceof Window) { - MWindowPeer wpeer = (MWindowPeer)(comp.getPeer()); - if (wpeer != null) { - wpeer.addDropTarget(); - } - } - } - } - - /** - * - */ - - public void removeDropTarget(DropTarget dt) { - if (MToolkit.useMotifDnD()) { - removeNativeDropTarget(dt); - } else { - Component comp = target; - while(!(comp == null || comp instanceof java.awt.Window)) { - comp = getParent_NoClientCode(comp); - } - - if (comp instanceof Window) { - MWindowPeer wpeer = (MWindowPeer)(comp.getPeer()); - if (wpeer != null) { - wpeer.removeDropTarget(); - } - } - } - } - - public void notifyTextComponentChange(boolean add){ - Container parent = getParent_NoClientCode(target); - while(!(parent == null || - parent instanceof java.awt.Frame || - parent instanceof java.awt.Dialog)) { - parent = getParent_NoClientCode(parent); - } - - if (parent instanceof java.awt.Frame || - parent instanceof java.awt.Dialog) { - if (add) - ((MInputMethodControl)parent.getPeer()).addTextComponent((MComponentPeer)this); - else - ((MInputMethodControl)parent.getPeer()).removeTextComponent((MComponentPeer)this); - } - } - - native void addNativeDropTarget(DropTarget dt); - - native void removeNativeDropTarget(DropTarget dt); - - public GraphicsConfiguration getGraphicsConfiguration() { - GraphicsConfiguration ret = graphicsConfig; - if (ret == null) { - ret = target.getGraphicsConfiguration(); - } - return ret; - } - - // Returns true if we are inside begin/endLayout and - // are waiting for native painting - public boolean isPaintPending() { - return paintPending && isLayouting; - } - - public boolean handlesWheelScrolling() { - return false; - } - - /** - * The following multibuffering-related methods delegate to our - * associated GraphicsConfig (X11 or GLX) to handle the appropriate - * native windowing system specific actions. - */ - - private native long getWindow(long pData); - - public long getContentWindow() { - return getWindow(pData); - } - - public void createBuffers(int numBuffers, BufferCapabilities caps) - throws AWTException - { - backBuffer = graphicsConfig.createBackBuffer(this, numBuffers, caps); - xBackBuffer = graphicsConfig.createBackBufferImage(target, - backBuffer); - } - - public void flip(BufferCapabilities.FlipContents flipAction) { - if (backBuffer == 0) { - throw new IllegalStateException("Buffers have not been created"); - } - graphicsConfig.flip(this, target, xBackBuffer, flipAction); - } - - public Image getBackBuffer() { - if (backBuffer == 0) { - throw new IllegalStateException("Buffers have not been created"); - } - return xBackBuffer; - } - - public void destroyBuffers() { - graphicsConfig.destroyBackBuffer(backBuffer); - backBuffer = 0; - xBackBuffer = null; - } - - /** - * @see java.awt.peer.ComponentPeer#isReparentSupported - */ - public boolean isReparentSupported() { - return false; - } - - /** - * @see java.awt.peer.ComponentPeer#reparent - */ - public void reparent(ContainerPeer newNativeParent) { - throw new UnsupportedOperationException(); - } - - /** - * Applies the shape to the native component window. - * @since 1.7 - */ - public void applyShape(Region shape) { - } - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MCustomCursor.java b/jdk/src/solaris/classes/sun/awt/motif/MCustomCursor.java deleted file mode 100644 index 075ea36289b..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MCustomCursor.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import sun.awt.X11CustomCursor; -import sun.awt.CustomCursor; -import java.awt.*; -import java.awt.image.*; -import sun.awt.image.ImageRepresentation; - -public class MCustomCursor extends X11CustomCursor { - - public MCustomCursor(Image cursor, Point hotSpot, String name) - throws IndexOutOfBoundsException { - super(cursor, hotSpot, name); - } - /** - * Returns the supported cursor size - */ - public static Dimension getBestCursorSize( - int preferredWidth, int preferredHeight) { - - // Fix for bug 4212593 The Toolkit.createCustomCursor does not - // check absence of the image of cursor - // We use XQueryBestCursor which accepts unsigned ints to obtain - // the largest cursor size that could be dislpayed - Dimension d = new Dimension(Math.abs(preferredWidth), Math.abs(preferredHeight)); - - queryBestCursor(d); - return d; - } - - private static native void queryBestCursor(Dimension d); - - protected native void createCursor(byte[] xorMask, byte[] andMask, - int width, int height, - int fcolor, int bcolor, - int xHotSpot, int yHotSpot); - - static { - cacheInit(); - } - - private native static void cacheInit(); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MDataTransferer.java b/jdk/src/solaris/classes/sun/awt/motif/MDataTransferer.java deleted file mode 100644 index 805410aa527..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MDataTransferer.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Copyright 2000-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.Image; - -import java.awt.datatransfer.DataFlavor; - -import java.awt.image.BufferedImage; -import java.awt.image.ColorModel; -import java.awt.image.WritableRaster; - -import java.io.InputStream; -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.imageio.ImageIO; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.ImageWriter; -import javax.imageio.spi.ImageWriterSpi; - -import sun.awt.datatransfer.DataTransferer; -import sun.awt.datatransfer.ToolkitThreadBlockedHandler; - -/** - * Platform-specific support for the data transfer subsystem. - * - * @author Roger Brinkley - * @author Danila Sinopalnikov - * - * @since 1.3.1 - */ -public class MDataTransferer extends DataTransferer { - private static final long FILE_NAME_ATOM; - private static final long DT_NET_FILE_ATOM; - private static final long PNG_ATOM; - private static final long JFIF_ATOM; - - static { - FILE_NAME_ATOM = getAtomForTarget("FILE_NAME"); - DT_NET_FILE_ATOM = getAtomForTarget("_DT_NETFILE"); - PNG_ATOM = getAtomForTarget("PNG"); - JFIF_ATOM = getAtomForTarget("JFIF"); - } - - /** - * Singleton constructor - */ - private MDataTransferer() { - } - - private static MDataTransferer transferer; - - static MDataTransferer getInstanceImpl() { - if (transferer == null) { - synchronized (MDataTransferer.class) { - if (transferer == null) { - transferer = new MDataTransferer(); - } - } - } - return transferer; - } - - public String getDefaultUnicodeEncoding() { - return "iso-10646-ucs-2"; - } - - public boolean isLocaleDependentTextFormat(long format) { - return false; - } - - public boolean isTextFormat(long format) { - return super.isTextFormat(format) - || isMimeFormat(format, "text"); - } - - protected String getCharsetForTextFormat(Long lFormat) { - long format = lFormat.longValue(); - if (isMimeFormat(format, "text")) { - String nat = getNativeForFormat(format); - DataFlavor df = new DataFlavor(nat, null); - // Ignore the charset parameter of the MIME type if the subtype - // doesn't support charset. - if (!DataTransferer.doesSubtypeSupportCharset(df)) { - return null; - } - String charset = df.getParameter("charset"); - if (charset != null) { - return charset; - } - } - return super.getCharsetForTextFormat(lFormat); - } - - public boolean isFileFormat(long format) { - return format == FILE_NAME_ATOM || format == DT_NET_FILE_ATOM; - } - - public boolean isImageFormat(long format) { - return format == PNG_ATOM || format == JFIF_ATOM - || isMimeFormat(format, "image"); - } - - protected Long getFormatForNativeAsLong(String str) { - // Just get the atom. If it has already been retrived - // once, we'll get a copy so this should be very fast. - long atom = getAtomForTarget(str); - if (atom <= 0) { - throw new InternalError("Cannot register a target"); - } - return Long.valueOf(atom); - } - - protected String getNativeForFormat(long format) { - return getTargetNameForAtom(format); - } - - public ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler() { - return MToolkitThreadBlockedHandler.getToolkitThreadBlockedHandler(); - } - - /** - * Gets an atom for a format name. - */ - static native long getAtomForTarget(String name); - - /** - * Gets an format name for a given format (atom) - */ - private static native String getTargetNameForAtom(long atom); - - protected byte[] imageToPlatformBytes(Image image, long format) - throws IOException { - String mimeType = null; - if (format == PNG_ATOM) { - mimeType = "image/png"; - } else if (format == JFIF_ATOM) { - mimeType = "image/jpeg"; - } else { - // Check if an image MIME format. - try { - String nat = getNativeForFormat(format); - DataFlavor df = new DataFlavor(nat); - String primaryType = df.getPrimaryType(); - if ("image".equals(primaryType)) { - mimeType = df.getPrimaryType() + "/" + df.getSubType(); - } - } catch (Exception e) { - // Not an image MIME format. - } - } - if (mimeType != null) { - return imageToStandardBytes(image, mimeType); - } else { - String nativeFormat = getNativeForFormat(format); - throw new IOException("Translation to " + nativeFormat + - " is not supported."); - } - } - - /** - * Translates either a byte array or an input stream which contain - * platform-specific image data in the given format into an Image. - */ - protected Image platformImageBytesOrStreamToImage(InputStream inputStream, - byte[] bytes, - long format) - throws IOException { - String mimeType = null; - if (format == PNG_ATOM) { - mimeType = "image/png"; - } else if (format == JFIF_ATOM) { - mimeType = "image/jpeg"; - } else { - // Check if an image MIME format. - try { - String nat = getNativeForFormat(format); - DataFlavor df = new DataFlavor(nat); - String primaryType = df.getPrimaryType(); - if ("image".equals(primaryType)) { - mimeType = df.getPrimaryType() + "/" + df.getSubType(); - } - } catch (Exception e) { - // Not an image MIME format. - } - } - if (mimeType != null) { - return standardImageBytesOrStreamToImage(inputStream, bytes, mimeType); - } else { - String nativeFormat = getNativeForFormat(format); - throw new IOException("Translation from " + nativeFormat + - " is not supported."); - } - } - - /** - * Returns true if and only if the name of the specified format Atom - * constitutes a valid MIME type with the specified primary type. - */ - private boolean isMimeFormat(long format, String primaryType) { - String nat = getNativeForFormat(format); - - if (nat == null) { - return false; - } - - try { - DataFlavor df = new DataFlavor(nat); - if (primaryType.equals(df.getPrimaryType())) { - return true; - } - } catch (Exception e) { - // Not a MIME format. - } - - return false; - } - - /* - * The XDnD protocol prescribes that the Atoms used as targets for data - * transfer should have string names that represent the corresponding MIME - * types. - * To meet this requirement we check if the passed native format constitutes - * a valid MIME and return a list of flavors to which the data in this MIME - * type can be translated by the Data Transfer subsystem. - */ - public List getPlatformMappingsForNative(String nat) { - List flavors = new ArrayList(); - - if (nat == null) { - return flavors; - } - - DataFlavor df = null; - - try { - df = new DataFlavor(nat); - } catch (Exception e) { - // The string doesn't constitute a valid MIME type. - return flavors; - } - - Object value = df; - final String primaryType = df.getPrimaryType(); - final String baseType = primaryType + "/" + df.getSubType(); - - // For text formats we map natives to MIME strings instead of data - // flavors to enable dynamic text native-to-flavor mapping generation. - // See SystemFlavorMap.getFlavorsForNative() for details. - if ("text".equals(primaryType)) { - value = primaryType + "/" + df.getSubType(); - } else if ("image".equals(primaryType)) { - Iterator readers = ImageIO.getImageReadersByMIMEType(baseType); - if (readers.hasNext()) { - flavors.add(DataFlavor.imageFlavor); - } - } - - flavors.add(value); - - return flavors; - } - - private static ImageTypeSpecifier defaultSpecifier = null; - - private ImageTypeSpecifier getDefaultImageTypeSpecifier() { - if (defaultSpecifier == null) { - ColorModel model = ColorModel.getRGBdefault(); - WritableRaster raster = - model.createCompatibleWritableRaster(10, 10); - - BufferedImage bufferedImage = - new BufferedImage(model, raster, model.isAlphaPremultiplied(), - null); - - defaultSpecifier = new ImageTypeSpecifier(bufferedImage); - } - - return defaultSpecifier; - } - - /* - * The XDnD protocol prescribes that the Atoms used as targets for data - * transfer should have string names that represent the corresponding MIME - * types. - * To meet this requirement we return a list of formats that represent - * MIME types to which the data in this flavor can be translated by the Data - * Transfer subsystem. - */ - public List getPlatformMappingsForFlavor(DataFlavor df) { - List natives = new ArrayList(1); - - if (df == null) { - return natives; - } - - String charset = df.getParameter("charset"); - String baseType = df.getPrimaryType() + "/" + df.getSubType(); - String mimeType = baseType; - - if (charset != null && DataTransferer.isFlavorCharsetTextType(df)) { - mimeType += ";charset=" + charset; - } - - // Add a mapping to the MIME native whenever the representation class - // doesn't require translation. - if (df.getRepresentationClass() != null && - (df.isRepresentationClassInputStream() || - df.isRepresentationClassByteBuffer() || - byteArrayClass.equals(df.getRepresentationClass()))) { - natives.add(mimeType); - } - - if (DataFlavor.imageFlavor.equals(df)) { - String[] mimeTypes = ImageIO.getWriterMIMETypes(); - if (mimeTypes != null) { - for (int i = 0; i < mimeTypes.length; i++) { - Iterator writers = - ImageIO.getImageWritersByMIMEType(mimeTypes[i]); - - while (writers.hasNext()) { - ImageWriter imageWriter = (ImageWriter)writers.next(); - ImageWriterSpi writerSpi = - imageWriter.getOriginatingProvider(); - - if (writerSpi != null && - writerSpi.canEncodeImage(getDefaultImageTypeSpecifier())) { - natives.add(mimeTypes[i]); - break; - } - } - } - } - } else if (DataTransferer.isFlavorCharsetTextType(df)) { - final Iterator iter = DataTransferer.standardEncodings(); - - // stringFlavor is semantically equivalent to the standard - // "text/plain" MIME type. - if (DataFlavor.stringFlavor.equals(df)) { - baseType = "text/plain"; - } - - while (iter.hasNext()) { - String encoding = (String)iter.next(); - if (!encoding.equals(charset)) { - natives.add(baseType + ";charset=" + encoding); - } - } - - // Add a MIME format without specified charset. - if (!natives.contains(baseType)) { - natives.add(baseType); - } - } - - return natives; - } - protected native String[] dragQueryFile(byte[] bytes); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MDialogPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MDialogPeer.java deleted file mode 100644 index 5e22931aa60..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MDialogPeer.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.util.Vector; -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.*; -import sun.awt.motif.MInputMethodControl; -import sun.awt.im.*; - -class MDialogPeer extends MWindowPeer implements DialogPeer, MInputMethodControl { - - static Vector allDialogs = new Vector(); - - MDialogPeer(Dialog target) { - - /* create MWindowPeer object */ - super(); - - winAttr.nativeDecor = !target.isUndecorated(); - winAttr.initialFocus = true; - winAttr.isResizable = target.isResizable(); - winAttr.initialState = MWindowAttributes.NORMAL; - winAttr.title = target.getTitle(); - winAttr.icon = null; - if (winAttr.nativeDecor) { - winAttr.decorations = winAttr.AWT_DECOR_ALL | - winAttr.AWT_DECOR_MINIMIZE | - winAttr.AWT_DECOR_MAXIMIZE; - } else { - winAttr.decorations = winAttr.AWT_DECOR_NONE; - } - /* create and init native component */ - init(target); - allDialogs.addElement(this); - } - - public void setTitle(String title) { - pSetTitle(title); - } - - protected void disposeImpl() { - allDialogs.removeElement(this); - super.disposeImpl(); - } - - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleMoved(int x, int y) { - postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_MOVED)); - } - - public void show() { - pShowModal( ((Dialog)target).isModal() ); - updateAlwaysOnTop(alwaysOnTop); - } - - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleIconify() { -// Note: These routines are necessary for Coaleseing of native implementations -// As Dialogs do not currently send Iconify/DeIconify messages but -// Windows/Frames do. If this should be made consistent...to do so -// uncomment the postEvent. -// postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_ICONIFIED)); - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleDeiconify() { -// Note: These routines are necessary for Coaleseing of native implementations -// As Dialogs do not currently send Iconify/DeIconify messages but -// Windows/Frames do. If this should be made consistent...to do so -// uncomment the postEvent. -// postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_DEICONIFIED)); - } - - public void blockWindows(java.util.List toBlock) { - // do nothing - } - - @Override - final boolean isTargetUndecorated() { - return ((Dialog)target).isUndecorated(); - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MDragSourceContextPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MDragSourceContextPeer.java deleted file mode 100644 index 040c93e3b3d..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MDragSourceContextPeer.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Image; -import java.awt.Point; - -import java.awt.datatransfer.Transferable; - -import java.awt.dnd.DragSourceContext; -import java.awt.dnd.DragGestureEvent; -import java.awt.dnd.InvalidDnDOperationException; - -import java.awt.event.InputEvent; - -import java.awt.peer.ComponentPeer; -import java.awt.peer.LightweightPeer; - -import java.util.Map; -import sun.awt.SunToolkit; -import sun.awt.dnd.SunDragSourceContextPeer; - -/** - *

- * TBC - *

- * - * @since JDK1.2 - * - */ - -final class MDragSourceContextPeer extends SunDragSourceContextPeer { - - private static final MDragSourceContextPeer theInstance = - new MDragSourceContextPeer(null); - - /** - * construct a new MDragSourceContextPeer - */ - - private MDragSourceContextPeer(DragGestureEvent dge) { - super(dge); - } - - static MDragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException { - theInstance.setTrigger(dge); - return theInstance; - } - - protected void startDrag(Transferable transferable, - long[] formats, Map formatMap) { - try { - long nativeCtxtLocal = startDrag(getTrigger().getComponent(), - transferable, - getTrigger().getTriggerEvent(), - getCursor(), - getCursor() == null ? 0 : getCursor().getType(), - getDragSourceContext().getSourceActions(), - formats, - formatMap); - setNativeContext(nativeCtxtLocal); - } catch (Exception e) { - throw new InvalidDnDOperationException("failed to create native peer: " + e); - } - - if (getNativeContext() == 0) { - throw new InvalidDnDOperationException("failed to create native peer"); - } - - MDropTargetContextPeer.setCurrentJVMLocalSourceTransferable(transferable); - } - - /** - * downcall into native code - */ - - private native long startDrag(Component component, - Transferable transferable, - InputEvent nativeTrigger, - Cursor c, int ctype, int actions, - long[] formats, Map formatMap); - - /** - * set cursor - */ - - public void setCursor(Cursor c) throws InvalidDnDOperationException { - SunToolkit.awtLock(); - super.setCursor(c); - SunToolkit.awtUnlock(); - } - - protected native void setNativeCursor(long nativeCtxt, Cursor c, int cType); - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MDropTargetContextPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MDropTargetContextPeer.java deleted file mode 100644 index 5994cd1b839..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MDropTargetContextPeer.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.UnsupportedFlavorException; - -import java.awt.dnd.DnDConstants; -import java.awt.dnd.InvalidDnDOperationException; - -import java.io.InputStream; - -import java.util.Map; - -import java.io.IOException; -import sun.awt.dnd.SunDropTargetContextPeer; -import sun.awt.SunToolkit; - -/** - *

- * The MDropTargetContextPeer class is the class responsible for handling - * the interaction between the Motif DnD system and Java. - *

- * - * @since JDK1.2 - * - */ - -final class MDropTargetContextPeer extends SunDropTargetContextPeer { - - private long nativeDropTransfer; - - long nativeDataAvailable = 0; - Object nativeData = null; - - /** - * create the peer - */ - - static MDropTargetContextPeer createMDropTargetContextPeer() { - return new MDropTargetContextPeer(); - } - - /** - * create the peer - */ - - private MDropTargetContextPeer() { - super(); - } - - protected Object getNativeData(long format) { - SunToolkit.awtLock(); - if (nativeDropTransfer == 0) { - nativeDropTransfer = startTransfer(getNativeDragContext(), - format); - } else { - addTransfer (nativeDropTransfer, format); - } - - for (nativeDataAvailable = 0; - format != nativeDataAvailable;) { - try { - SunToolkit.awtLockWait(); - } catch (Throwable e) { - e.printStackTrace(); - } - } - SunToolkit.awtUnlock(); - - return nativeData; - } - - /** - * signal drop complete - */ - - protected void doDropDone(boolean success, int dropAction, - boolean isLocal) { - dropDone(getNativeDragContext(), nativeDropTransfer, isLocal, - success, dropAction); - } - - /** - * notify transfer complete - */ - - private void newData(long format, String type, byte[] data) { - nativeDataAvailable = format; - nativeData = data; - - SunToolkit.awtLockNotifyAll(); - } - - /** - * notify transfer failed - */ - - private void transferFailed(long format) { - nativeDataAvailable = format; - nativeData = null; - - SunToolkit.awtLockNotifyAll(); - } - - /** - * schedule a native DnD transfer - */ - - private native long startTransfer(long nativeDragContext, long format); - - /** - * schedule a native DnD data transfer - */ - - private native void addTransfer(long nativeDropTransfer, long format); - - /** - * signal that drop is completed - */ - - private native void dropDone(long nativeDragContext, long nativeDropTransfer, - boolean localTx, boolean success, int dropAction); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MEmbedCanvasPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MEmbedCanvasPeer.java deleted file mode 100644 index 0e189bfeb31..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MEmbedCanvasPeer.java +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.*; -import java.awt.dnd.DropTarget; -import java.awt.dnd.DropTargetListener; -import java.awt.event.*; -import java.awt.image.ColorModel; -import java.awt.image.ImageObserver; -import java.awt.image.ImageProducer; -import java.awt.image.VolatileImage; -import java.awt.peer.*; -import sun.awt.*; -import sun.awt.motif.X11FontMetrics; -import java.lang.reflect.*; -import java.util.logging.*; -import java.util.*; - -// FIXME: Add X errors handling -// FIXME: Add chaining of parameters to XEmbed-client if we are both(accelerators; XDND; focus already automatically) -public class MEmbedCanvasPeer extends MCanvasPeer implements WindowFocusListener, KeyEventPostProcessor, ModalityListener, WindowIDProvider { - private static final Logger xembedLog = Logger.getLogger("sun.awt.motif.xembed.MEmbedCanvasPeer"); - - final static int XEMBED_VERSION = 0, - XEMBED_MAPPED = (1 << 0); -/* XEMBED messages */ - final static int XEMBED_EMBEDDED_NOTIFY = 0; - final static int XEMBED_WINDOW_ACTIVATE = 1; - final static int XEMBED_WINDOW_DEACTIVATE = 2; - final static int XEMBED_REQUEST_FOCUS =3; - final static int XEMBED_FOCUS_IN = 4; - final static int XEMBED_FOCUS_OUT = 5; - final static int XEMBED_FOCUS_NEXT = 6; - final static int XEMBED_FOCUS_PREV = 7; -/* 8-9 were used for XEMBED_GRAB_KEY/XEMBED_UNGRAB_KEY */ - final static int XEMBED_GRAB_KEY = 8; - final static int XEMBED_UNGRAB_KEY = 9; - final static int XEMBED_MODALITY_ON = 10; - final static int XEMBED_MODALITY_OFF = 11; - final static int XEMBED_REGISTER_ACCELERATOR = 12; - final static int XEMBED_UNREGISTER_ACCELERATOR= 13; - final static int XEMBED_ACTIVATE_ACCELERATOR = 14; - - final static int NON_STANDARD_XEMBED_GTK_GRAB_KEY = 108; - final static int NON_STANDARD_XEMBED_GTK_UNGRAB_KEY = 109; - -// A detail code is required for XEMBED_FOCUS_IN. The following values are valid: -/* Details for XEMBED_FOCUS_IN: */ - final static int XEMBED_FOCUS_CURRENT = 0; - final static int XEMBED_FOCUS_FIRST = 1; - final static int XEMBED_FOCUS_LAST = 2; - -// Modifiers bits - final static int XEMBED_MODIFIER_SHIFT = (1 << 0); - final static int XEMBED_MODIFIER_CONTROL = (1 << 1); - final static int XEMBED_MODIFIER_ALT = (1 << 2); - final static int XEMBED_MODIFIER_SUPER = (1 << 3); - final static int XEMBED_MODIFIER_HYPER = (1 << 4); - - boolean applicationActive; // Whether the application is active(has focus) - Map accelerators = new HashMap(); // Maps accelerator ID into AWTKeyStroke - Map accel_lookup = new HashMap(); // Maps AWTKeyStroke into accelerator ID - Set grabbed_keys = new HashSet(); // A set of keys grabbed by client - Object ACCEL_LOCK = accelerators; // Lock object for working with accelerators; - Object GRAB_LOCK = grabbed_keys; // Lock object for working with keys grabbed by client - - MEmbedCanvasPeer() {} - - MEmbedCanvasPeer(Component target) { - super(target); - } - - void initialize() { - super.initialize(); - - installActivateListener(); - installAcceleratorListener(); - installModalityListener(); - - // XEmbed canvas should be non-traversable. - // FIXME: Probably should be removed and enforced setting of it by the users - target.setFocusTraversalKeysEnabled(false); - - initXEmbedServer(); - } - - void installModalityListener() { - ((SunToolkit)Toolkit.getDefaultToolkit()).addModalityListener(this); - } - - void deinstallModalityListener() { - ((SunToolkit)Toolkit.getDefaultToolkit()).removeModalityListener(this); - } - - void installAcceleratorListener() { - KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(this); - } - - void deinstallAcceleratorListener() { - KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(this); - } - - void installActivateListener() { - // FIXME: should watch for hierarchy changes - Window toplevel = getTopLevel(target); - if (toplevel != null) { - toplevel.addWindowFocusListener(this); - applicationActive = toplevel.isFocused(); - } - } - - void deinstallActivateListener() { - Window toplevel = getTopLevel(target); - if (toplevel != null) { - toplevel.removeWindowFocusListener(this); - } - } - - native boolean isXEmbedActive(); - - boolean isApplicationActive() { - return applicationActive; - } - - native void initDispatching(); - - native void endDispatching(); - - native void embedChild(long child); - - native void childDestroyed(); - - public void handleEvent(AWTEvent e) { - super.handleEvent(e); - if (isXEmbedActive()) { - switch (e.getID()) { - case FocusEvent.FOCUS_GAINED: - canvasFocusGained((FocusEvent)e); - break; - case FocusEvent.FOCUS_LOST: - canvasFocusLost((FocusEvent)e); - break; - case KeyEvent.KEY_PRESSED: - case KeyEvent.KEY_RELEASED: - if (!((InputEvent)e).isConsumed()) { - forwardKeyEvent((KeyEvent)e); - } - break; - } - } - } - - public Dimension getPreferredSize() { - if (isXEmbedActive()) { - Dimension dim = getEmbedPreferredSize(); - if (dim == null) { - return super.getPreferredSize(); - } else { - return dim; - } - } else { - return super.getPreferredSize(); - } - } - native Dimension getEmbedPreferredSize(); - public Dimension getMinimumSize() { - if (isXEmbedActive()) { - Dimension dim = getEmbedMinimumSize(); - if (dim == null) { - return super.getMinimumSize(); - } else { - return dim; - } - } else { - return super.getMinimumSize(); - } - } - native Dimension getEmbedMinimumSize(); - protected void disposeImpl() { - if (isXEmbedActive()) { - detachChild(); - } - deinstallActivateListener(); - deinstallModalityListener(); - deinstallAcceleratorListener(); - - destroyXEmbedServer(); - super.disposeImpl(); - } - - public boolean isFocusable() { - return true; - } - - Window getTopLevel(Component comp) { - while (comp != null && !(comp instanceof Window)) { - comp = comp.getParent(); - } - return (Window)comp; - } - - native Rectangle getClientBounds(); - - void childResized() { - if (xembedLog.isLoggable(Level.FINER)) { - Rectangle bounds = getClientBounds(); - xembedLog.finer("Child resized: " + bounds); - // It is not required to update embedder's size when client size changes - // However, since there is no any means to get client size it seems to be the - // only way to provide it. However, it contradicts with Java layout concept - - // so it is disabled for now. -// Rectangle my_bounds = getBounds(); -// setBounds(my_bounds.x, my_bounds.y, bounds.width, bounds.height, SET_BOUNDS); - } - postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED)); - } - - void focusNext() { - if (isXEmbedActive()) { - xembedLog.fine("Requesting focus for the next component after embedder"); - postEvent(new InvocationEvent(target, new Runnable() { - public void run() { - KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(target); - } - })); - } else { - xembedLog.fine("Application is not active - denying focus next"); - } - } - - void focusPrev() { - if (isXEmbedActive()) { - xembedLog.fine("Requesting focus for the next component after embedder"); - postEvent(new InvocationEvent(target, new Runnable() { - public void run() { - KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent(target); - } - })); - } else { - xembedLog.fine("Application is not active - denying focus prev"); - } - } - - void requestXEmbedFocus() { - if (isXEmbedActive()) { - xembedLog.fine("Requesting focus for client"); - postEvent(new InvocationEvent(target, new Runnable() { - public void run() { - target.requestFocusInWindow(); - } - })); - } else { - xembedLog.fine("Application is not active - denying request focus"); - } - } - - native void notifyChildEmbedded(); - - native void detachChild(); - - public void windowGainedFocus(WindowEvent e) { - applicationActive = true; - if (isXEmbedActive()) { - xembedLog.fine("Sending WINDOW_ACTIVATE"); - sendMessage(XEMBED_WINDOW_ACTIVATE); - } - } - - public void windowLostFocus(WindowEvent e) { - applicationActive = false; - if (isXEmbedActive()) { - xembedLog.fine("Sending WINDOW_DEACTIVATE"); - sendMessage(XEMBED_WINDOW_DEACTIVATE); - } - } - - void canvasFocusGained(FocusEvent e) { - if (isXEmbedActive()) { - xembedLog.fine("Forwarding FOCUS_GAINED"); - int flavor = XEMBED_FOCUS_CURRENT; - if (e instanceof CausedFocusEvent) { - CausedFocusEvent ce = (CausedFocusEvent)e; - if (ce.getCause() == CausedFocusEvent.Cause.TRAVERSAL_FORWARD) { - flavor = XEMBED_FOCUS_FIRST; - } else if (ce.getCause() == CausedFocusEvent.Cause.TRAVERSAL_BACKWARD) { - flavor = XEMBED_FOCUS_LAST; - } - } - sendMessage(XEMBED_FOCUS_IN, flavor, 0, 0); - } - } - - void canvasFocusLost(FocusEvent e) { - if (isXEmbedActive() && !e.isTemporary()) { - xembedLog.fine("Forwarding FOCUS_LOST"); - Component opp = e.getOppositeComponent(); - int num = 0; - try { - num = Integer.parseInt(opp.getName()); - } catch (NumberFormatException nfe) { - } - sendMessage(XEMBED_FOCUS_OUT, num, 0, 0); - } - } - - native void forwardKeyEvent(KeyEvent e); - - void grabKey(final long keysym, final long modifiers) { - postEvent(new InvocationEvent(target, new Runnable() { - public void run() { - GrabbedKey grab = new GrabbedKey(keysym, modifiers); - if (xembedLog.isLoggable(Level.FINE)) xembedLog.fine("Grabbing key: " + grab); - synchronized(GRAB_LOCK) { - grabbed_keys.add(grab); - } - } - })); - } - - void ungrabKey(final long keysym, final long modifiers) { - postEvent(new InvocationEvent(target, new Runnable() { - public void run() { - GrabbedKey grab = new GrabbedKey(keysym, modifiers); - if (xembedLog.isLoggable(Level.FINE)) xembedLog.fine("UnGrabbing key: " + grab); - synchronized(GRAB_LOCK) { - grabbed_keys.remove(grab); - } - } - })); - } - - void registerAccelerator(final long accel_id, final long keysym, final long modifiers) { - postEvent(new InvocationEvent(target, new Runnable() { - public void run() { - AWTKeyStroke stroke = getKeyStrokeForKeySym(keysym, modifiers); - if (stroke != null) { - if (xembedLog.isLoggable(Level.FINE)) xembedLog.fine("Registering accelerator " + accel_id + " for " + stroke); - synchronized(ACCEL_LOCK) { - accelerators.put(accel_id, stroke); - accel_lookup.put(stroke, accel_id); - } - } - // Propogate accelerators to the another embedder - propogateRegisterAccelerator(stroke); - } - })); - } - - void unregisterAccelerator(final long accel_id) { - postEvent(new InvocationEvent(target, new Runnable() { - public void run() { - AWTKeyStroke stroke = null; - synchronized(ACCEL_LOCK) { - stroke = accelerators.get(accel_id); - if (stroke != null) { - if (xembedLog.isLoggable(Level.FINE)) xembedLog.fine("Unregistering accelerator: " + accel_id); - accelerators.remove(accel_id); - accel_lookup.remove(stroke); // FIXME: How about several accelerators with the same stroke? - } - } - // Propogate accelerators to the another embedder - propogateUnRegisterAccelerator(stroke); - } - })); - } - - void propogateRegisterAccelerator(AWTKeyStroke stroke) { - // Find the top-level and see if it is XEmbed client. If so, ask him to - // register the accelerator - MWindowPeer parent = getParentWindow(); - if (parent != null && parent instanceof MEmbeddedFramePeer) { - MEmbeddedFramePeer embedded = (MEmbeddedFramePeer)parent; - embedded.registerAccelerator(stroke); - } - } - - void propogateUnRegisterAccelerator(AWTKeyStroke stroke) { - // Find the top-level and see if it is XEmbed client. If so, ask him to - // register the accelerator - MWindowPeer parent = getParentWindow(); - if (parent != null && parent instanceof MEmbeddedFramePeer) { - MEmbeddedFramePeer embedded = (MEmbeddedFramePeer)parent; - embedded.unregisterAccelerator(stroke); - } - } - - public boolean postProcessKeyEvent(KeyEvent e) { - // Processing events only if we are in the focused window. - MWindowPeer parent = getParentWindow(); - if (parent == null || !((Window)parent.target).isFocused() || target.isFocusOwner()) { - return false; - } - - boolean result = false; - - if (xembedLog.isLoggable(Level.FINER)) xembedLog.finer("Post-processing event " + e); - - // Process ACCELERATORS - AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e); - long accel_id = 0; - boolean exists = false; - synchronized(ACCEL_LOCK) { - exists = accel_lookup.containsKey(stroke); - if (exists) { - accel_id = accel_lookup.get(stroke).longValue(); - } - } - if (exists) { - if (xembedLog.isLoggable(Level.FINE)) xembedLog.fine("Activating accelerator " + accel_id); - sendMessage(XEMBED_ACTIVATE_ACCELERATOR, accel_id, 0, 0); // FIXME: How about overloaded? - result = true; - } - - // Process Grabs, unofficial GTK feature - exists = false; - GrabbedKey key = new GrabbedKey(e); - synchronized(GRAB_LOCK) { - exists = grabbed_keys.contains(key); - } - if (exists) { - if (xembedLog.isLoggable(Level.FINE)) xembedLog.fine("Forwarding grabbed key " + e); - forwardKeyEvent(e); - result = true; - } - - return result; - } - - public void modalityPushed(ModalityEvent ev) { - sendMessage(XEMBED_MODALITY_ON); - } - - public void modalityPopped(ModalityEvent ev) { - sendMessage(XEMBED_MODALITY_OFF); - } - - int getModifiers(int state) { - int mods = 0; - if ((state & XEMBED_MODIFIER_SHIFT) != 0) { - mods |= InputEvent.SHIFT_DOWN_MASK; - } - if ((state & XEMBED_MODIFIER_CONTROL) != 0) { - mods |= InputEvent.CTRL_DOWN_MASK; - } - if ((state & XEMBED_MODIFIER_ALT) != 0) { - mods |= InputEvent.ALT_DOWN_MASK; - } - // FIXME: What is super/hyper? - // FIXME: Experiments show that SUPER is ALT. So what is Alt then? - if ((state & XEMBED_MODIFIER_SUPER) != 0) { - mods |= InputEvent.ALT_DOWN_MASK; - } -// if ((state & XEMBED_MODIFIER_HYPER) != 0) { -// mods |= InputEvent.DOWN_MASK; -// } - return mods; - } - - // Shouldn't be called on Toolkit thread. - AWTKeyStroke getKeyStrokeForKeySym(long keysym, long state) { - - int keycode = getAWTKeyCodeForKeySym((int)keysym); - int modifiers = getModifiers((int)state); - return AWTKeyStroke.getAWTKeyStroke(keycode, modifiers); - } - native int getAWTKeyCodeForKeySym(int keysym); - native void sendMessage(int msg); - native void sendMessage(int msg, long detail, long data1, long data2); - MWindowPeer getParentWindow() { - Component parent = target.getParent(); - synchronized(target.getTreeLock()) { - while (parent != null && !(parent.getPeer() instanceof MWindowPeer)) { - parent = parent.getParent(); - } - return (parent != null)?(MWindowPeer)parent.getPeer():null; - } - } - - private static class XEmbedDropTarget extends DropTarget { - public void addDropTargetListener(DropTargetListener dtl) - throws TooManyListenersException { - // Drop target listeners registered with this target will never be - // notified, since all drag notifications are routed to the XEmbed - // client. To avoid confusion we prohibit listeners registration - // by throwing TooManyListenersException as if there is a listener - // registered with this target already. - throw new TooManyListenersException(); - } - } - - public void setXEmbedDropTarget() { - // Register a drop site on the top level. - Runnable r = new Runnable() { - public void run() { - target.setDropTarget(new XEmbedDropTarget()); - } - }; - SunToolkit.executeOnEventHandlerThread(target, r); - } - - public void removeXEmbedDropTarget() { - // Unregister a drop site on the top level. - Runnable r = new Runnable() { - public void run() { - if (target.getDropTarget() instanceof XEmbedDropTarget) { - target.setDropTarget(null); - } - } - }; - SunToolkit.executeOnEventHandlerThread(target, r); - } - - public boolean processXEmbedDnDEvent(long ctxt, int eventID) { - if (target.getDropTarget() instanceof XEmbedDropTarget) { - forwardEventToEmbedded(ctxt, eventID); - return true; - } else { - return false; - } - } - - native void forwardEventToEmbedded(long ctxt, int eventID); - native void initXEmbedServer(); - native void destroyXEmbedServer(); - public native long getWindow(); -} -class GrabbedKey { - long keysym; - long modifiers; - GrabbedKey(long keysym, long modifiers) { - this.keysym = keysym; - this.modifiers = modifiers; - } - - GrabbedKey(KeyEvent ev) { - init(ev); - } - - native void initKeySymAndModifiers(KeyEvent e); - - private void init(KeyEvent e) { - initKeySymAndModifiers(e); - } - - public int hashCode() { - return (int)keysym & 0xFFFFFFFF; - } - - public boolean equals(Object o) { - if (!(o instanceof GrabbedKey)) { - return false; - } - GrabbedKey key = (GrabbedKey)o; - return (keysym == key.keysym && modifiers == key.modifiers); - } - - public String toString() { - return "Key combination[keysym=" + keysym + ", mods=" + modifiers + "]"; - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MEmbeddedFrame.java b/jdk/src/solaris/classes/sun/awt/motif/MEmbeddedFrame.java deleted file mode 100644 index 762508187bc..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MEmbeddedFrame.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 1996-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.Component; -import java.awt.peer.FramePeer; -import sun.awt.EmbeddedFrame; -import java.awt.peer.ComponentPeer; -import sun.awt.*; -import java.awt.*; - -public class MEmbeddedFrame extends EmbeddedFrame { - - /** - * Widget id of the shell widget - */ - long handle; - - public enum IDKind { - WIDGET, - WINDOW - }; - - public MEmbeddedFrame() { - } - - /** - * Backward-compatible implementation. This constructor takes widget which represents Frame's - * shell and uses it as top-level to build hierarchy of top-level widgets upon. It assumes that - * no XEmbed support is provided. - * @param widget a valid Xt widget pointer. - */ - public MEmbeddedFrame(long widget) { - this(widget, IDKind.WIDGET, false); - } - - /** - * New constructor, gets X Window id and allows to specify whether XEmbed is supported by parent - * X window. Creates hierarchy of top-level widgets under supplied window ID. - * @param winid a valid X window - * @param supportsXEmbed whether the host application supports XEMBED protocol - */ - public MEmbeddedFrame(long winid, boolean supportsXEmbed) { - this(winid, IDKind.WINDOW, supportsXEmbed); - } - - /** - * Creates embedded frame using ID as parent. - * @param ID parent ID - * @param supportsXEmbed whether the host application supports XEMBED protocol - * @param kind if WIDGET, ID represents a valid Xt widget pointer; if WINDOW, ID is a valid X Window - * ID - */ - public MEmbeddedFrame(long ID, IDKind kind, boolean supportsXEmbed) { - super(supportsXEmbed); - if (kind == IDKind.WIDGET) { - this.handle = ID; - } else { - this.handle = getWidget(ID); - } - MToolkit toolkit = (MToolkit)Toolkit.getDefaultToolkit(); - setPeer(toolkit.createEmbeddedFrame(this)); - /* - * addNotify() creates a LightweightDispatcher that propagates - * SunDropTargetEvents to subcomponents. - * NOTE: show() doesn't call addNotify() for embedded frames. - */ - addNotify(); - show(); - } - - public void synthesizeWindowActivation(boolean b) { - MEmbeddedFramePeer peer = (MEmbeddedFramePeer)getPeer(); - if (peer != null) { - if (peer.supportsXEmbed()) { - if (peer.isXEmbedActive()) { - // If XEmbed is active no synthetic focus events are allowed - everything - // should go through XEmbed - if (b) { - peer.requestXEmbedFocus(); - } - } - } else { - peer.synthesizeFocusInOut(b); - } - } - } - - public void show() { - if (handle != 0) { - mapWidget(handle); - } - super.show(); - } - - protected boolean traverseOut(boolean direction) { - MEmbeddedFramePeer xefp = (MEmbeddedFramePeer) getPeer(); - xefp.traverseOut(direction); - return true; - } - - // Native methods to handle widget <-> X Windows mapping - // - static native long getWidget(long winid); - static native int mapWidget(long widget); - public void registerAccelerator(AWTKeyStroke stroke) { - MEmbeddedFramePeer xefp = (MEmbeddedFramePeer) getPeer(); - if (xefp != null) { - xefp.registerAccelerator(stroke); - } - } - public void unregisterAccelerator(AWTKeyStroke stroke) { - MEmbeddedFramePeer xefp = (MEmbeddedFramePeer) getPeer(); - if (xefp != null) { - xefp.unregisterAccelerator(stroke); - } - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MEmbeddedFramePeer.java b/jdk/src/solaris/classes/sun/awt/motif/MEmbeddedFramePeer.java deleted file mode 100644 index 60de1a245f6..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MEmbeddedFramePeer.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright 1996-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import sun.awt.EmbeddedFrame; -import java.util.logging.*; -import java.awt.Component; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Window; -import java.awt.AWTKeyStroke; -import java.awt.Component; -import java.awt.Container; -import sun.awt.SunToolkit; -import java.util.LinkedList; -import java.util.Iterator; - -import sun.java2d.SurfaceData; - -public class MEmbeddedFramePeer extends MFramePeer { - private static final Logger xembedLog = Logger.getLogger("sun.awt.motif.xembed.MEmbeddedFramePeer"); - -// A detail code is required for XEMBED_FOCUS_IN. The following values are valid: -/* Details for XEMBED_FOCUS_IN: */ - final static int XEMBED_FOCUS_CURRENT = 0; - final static int XEMBED_FOCUS_FIRST = 1; - final static int XEMBED_FOCUS_LAST = 2; - - LinkedList strokes = new LinkedList(); - - public MEmbeddedFramePeer(EmbeddedFrame target) { - super(target); - xembedLog.fine("Creating XEmbed-enabled motif embedded frame, frame supports XEmbed:" + supportsXEmbed()); - } - - void create(MComponentPeer parent) { - NEFcreate(parent, ((MEmbeddedFrame)target).handle); - } - native void NEFcreate(MComponentPeer parent, long handle); - native void pShowImpl(); - void pShow() { - pShowImpl(); - } - - boolean supportsXEmbed() { - EmbeddedFrame frame = (EmbeddedFrame)target; - if (frame != null) { - return frame.supportsXEmbed(); - } else { - return false; - } - } - - public void setVisible(boolean vis) { - super.setVisible(vis); - xembedLog.fine("Peer made visible"); - if (vis && !supportsXEmbed()) { - xembedLog.fine("Synthesizing FocusIn"); - // Fix for 4878303 - generate WINDOW_GAINED_FOCUS and update if we were focused - // since noone will do it for us(WM does it for regular top-levels) - synthesizeFocusInOut(true); - } - } - public native void synthesizeFocusInOut(boolean b); - - native boolean isXEmbedActive(); - native boolean isXEmbedApplicationActive(); - native void requestXEmbedFocus(); - - public boolean requestWindowFocus() { - xembedLog.fine("In requestWindowFocus"); - // Should check for active state of host application - if (isXEmbedActive()) { - if (isXEmbedApplicationActive()) { - xembedLog.fine("Requesting focus from embedding host"); - requestXEmbedFocus(); - return true; - } else { - xembedLog.fine("Host application is not active"); - return false; - } - } else { - xembedLog.fine("Requesting focus from X"); - return super.requestWindowFocus(); - } - } - - void registerAccelerator(AWTKeyStroke stroke) { -// if (stroke == null) return; -// strokes.add(stroke); -// if (isXEmbedActive()) { -// nativeRegisterAccelerator(stroke, strokes.size()-1); -// } - } - - void unregisterAccelerator(AWTKeyStroke stroke) { -// if (stroke == null) return; -// if (isXEmbedActive()) { -// int index = strokes.indexOf(stroke); -// nativeUnregisterAccelerator(index); -// } - } - - void notifyStarted() { - // Register accelerators -// int i = 0; -// Iterator iter = strokes.iterator(); -// while (iter.hasNext()) { -// nativeRegisterAccelerator(iter.next(), i++); -// } - - updateDropTarget(); - } - - native void traverseOut(boolean direction); - - void handleFocusIn(int detail) { - xembedLog.log(Level.FINE, "handleFocusIn {0}", new Object[]{Integer.valueOf(detail)}); - switch(detail) { - case XEMBED_FOCUS_CURRENT: - // Do nothing - just restore to the current value - break; - case XEMBED_FOCUS_FIRST: - SunToolkit.executeOnEventHandlerThread(target, new Runnable() { - public void run() { - Component comp = ((Container)target).getFocusTraversalPolicy().getFirstComponent((Container)target); - if (comp != null) { - comp.requestFocusInWindow(); - } - }}); - break; - case XEMBED_FOCUS_LAST: - SunToolkit.executeOnEventHandlerThread(target, new Runnable() { - public void run() { - Component comp = ((Container)target).getFocusTraversalPolicy().getLastComponent((Container)target); - if (comp != null) { - comp.requestFocusInWindow(); - } - }}); - break; - } - } - public void handleWindowFocusIn() { - super.handleWindowFocusIn(); - xembedLog.fine("windowFocusIn"); - } - public void handleWindowFocusOut(Window oppositeWindow) { - super.handleWindowFocusOut(oppositeWindow); - xembedLog.fine("windowFocusOut, opposite is null?:" + (oppositeWindow==null)); - } - - native void pReshapePrivate(int x, int y, int w, int h); - - public void setBoundsPrivate(int x, int y, int width, int height) - { - if (disposed) - { - return; - } - - // Should set paintPending before reshape to prevent - // thread race between PaintEvent and setBounds - // This part of the 4267393 fix proved to be unstable under solaris, - // dissabled due to regressions 4418155, 4486762, 4490079 - paintPending = false; //checkNativePaintOnSetBounds(width, height); - - pReshapePrivate(x, y, width, height); - - if ((width != oldWidth) || (height != oldHeight)) - { - SurfaceData oldData = surfaceData; - if (oldData != null) { - surfaceData = graphicsConfig.createSurfaceData(this); - oldData.invalidate(); - } - oldWidth = width; - oldHeight = height; - } - validateSurface(width, height); - serialNum++; - } - - public native Rectangle getBoundsPrivate(); - - @Override - Rectangle constrainBounds(int x, int y, int width, int height) { - // We don't constrain the bounds of the EmbeddedFrames - return new Rectangle(x, y, width, height); - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MFileDialogPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MFileDialogPeer.java deleted file mode 100644 index e51aaa71b50..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MFileDialogPeer.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.io.*; -import java.awt.datatransfer.*; -import java.util.ArrayList; -import sun.awt.datatransfer.ToolkitThreadBlockedHandler; - -public class MFileDialogPeer extends MDialogPeer implements FileDialogPeer { - private FilenameFilter filter; - private String[] NativeFilteredFiles; - native void create(MComponentPeer parent); - void create(MComponentPeer parent, Object arg) { - create(parent); - } - public MFileDialogPeer(FileDialog target) { - super(target); - FileDialog fdialog = (FileDialog)target; - String dir = fdialog.getDirectory(); - String file = fdialog.getFile(); - FilenameFilter filter = fdialog.getFilenameFilter(); - - insets = new Insets(0, 0, 0, 0); - setDirectory(dir); - if (file != null) { - setFile(file); - } - setFilenameFilter(filter); - } - native void pReshape(int x, int y, int width, int height); - native void pDispose(); - native void pShow(); - native void pHide(); - native void setFileEntry(String dir, String file, String[] ffiles); - native void insertReplaceFileDialogText(String l); - public native void setFont(Font f); - - String getFilteredFile(String file) { - if (file == null) { - file = ((FileDialog)target).getFile(); - } - String dir = ((FileDialog)target).getDirectory(); - if (dir == null) { - dir = "./"; - } - if (file == null) { - file = ""; - } - if (filter != null && !filter.accept(new File(dir), file)) { - file = ""; - } - return file; - } - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleSelected(final String file) { - final FileDialog fileDialog = (FileDialog)target; - MToolkit.executeOnEventHandlerThread(fileDialog, new Runnable() { - public void run() { - int index = file.lastIndexOf(java.io.File.separatorChar);/*2509*//*ibm*/ - String dir; - - if (index == -1) { - dir = "."+java.io.File.separator; - fileDialog.setFile(file); - } else { - dir = file.substring(0, index + 1); - fileDialog.setFile(file.substring(index + 1)); - } - fileDialog.setDirectory(dir); - fileDialog.hide(); - } - }); - } // handleSelected() - - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleCancel() { - final FileDialog fileDialog = (FileDialog)target; - MToolkit.executeOnEventHandlerThread(fileDialog, new Runnable() { - public void run() { - fileDialog.setFile(null); - fileDialog.hide(); - } - }); - } // handleCancel() - - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleQuit() { - final FileDialog fileDialog = (FileDialog)target; - MToolkit.executeOnEventHandlerThread(fileDialog, new Runnable() { - public void run() { - fileDialog.hide(); - } - }); - } // handleQuit() - - public void setDirectory(String dir) { - String file = ((FileDialog)target).getFile(); - setFileEntry((dir != null) ? dir : "./", (file != null) ? file - : "", null); - } - - - public void setFile(String file) { - String dir = ((FileDialog)target).getDirectory(); - if (dir == null) { - dir = "./"; - } - setFileEntry((dir != null) ? dir : "./", getFilteredFile(null), null); - } - class DirectoryFilter implements FilenameFilter { - FilenameFilter userFilter; - DirectoryFilter(FilenameFilter userFilter) { - this.userFilter = userFilter; - } - public boolean accept(File parent, String name) { - File toTest = new File(parent, name); - if (toTest.isDirectory()) { - return false; - } else if (userFilter != null) { - return userFilter.accept(parent, name); - } else { - return true; - } - } - } - public void doFilter(FilenameFilter filter, String dir) { - String d = (dir == null) ? (((FileDialog)target).getDirectory()):(dir); - String f = getFilteredFile(null); - File df = new File((d != null) ? d : "."); - String[] files = df.list(new DirectoryFilter(filter)); - String[] nffiles = NativeFilteredFiles; - - // At this point we have two file lists. - // The first one is a filtered list of files that we retrieve - // by using Java code and Java filter. - // The second one is a filtered list of files that we retrieve - // by using the native code and native pattern. - // We should find an intersection of these two lists. The result - // will be exactly what we expect to see in setFileEntry. - // For more details please see 4784704. - if ( files != null ) { - ArrayList filearr = new ArrayList(); - if (nffiles != null) { - for (int j = 0; j < files.length; j++) { - for (int n = 0; n < nffiles.length; n++) { - if (files[j].equals(nffiles[n])) { - filearr.add(files[j]); - break; - } - } - } - } - files = new String[filearr.size()]; - for (int i = 0; i < files.length; i++) { - files[i] = (String)filearr.get(i); - } - } - if (files == null || files.length == 0) { - files = new String[1]; - files[0] = ""; - } - setFileEntry((d != null) ? d : ".", (f != null) ? f : "", files); - } - private boolean proceedFiltering(final String dir, String[] nffiles, - boolean isPrivileged) - { - // Transfer the native filtered file list to the doFilter method. - NativeFilteredFiles = nffiles; - // If we are not on the Toolkit thread we can call doFilter() directly. - // If the filter is null no user code will be invoked - if (!isPrivileged || filter == null) { - try { - doFilter(filter, dir); - return true; - } catch(Exception e) { - e.printStackTrace(); - return false; - } - } - // Otherwise we have to call user code on EvenDispatchThread - final ToolkitThreadBlockedHandler priveleged_lock = - MToolkitThreadBlockedHandler.getToolkitThreadBlockedHandler(); - final boolean[] finished = new boolean[1]; - final boolean[] result = new boolean[1]; - finished[0] = false; - result[0] = false; - - - // Use the same Toolkit blocking mechanism as in DnD. - priveleged_lock.lock(); - - MToolkit.executeOnEventHandlerThread((FileDialog)target, new Runnable() { - public void run() { - priveleged_lock.lock(); - try { - doFilter(filter, dir); - result[0] = true; - } catch (Exception e) { - e.printStackTrace(); - result[0] = false; - } finally { - finished[0] = true; - priveleged_lock.exit(); - priveleged_lock.unlock(); - } - } - }); - - while (!finished[0]) { - priveleged_lock.enter(); - } - - priveleged_lock.unlock(); - - return result[0]; - } - - public void setFilenameFilter(FilenameFilter filter) { - this.filter = filter; - FileDialog fdialog = (FileDialog)target; - String dir = fdialog.getDirectory(); - String file = fdialog.getFile(); - setFile(file); - doFilter(filter, null); - } - - // Called from native widget when paste key is pressed and we - // already own the selection (prevents Motif from hanging while - // waiting for the selection) - // - public void pasteFromClipboard() { - Clipboard clipboard = target.getToolkit().getSystemClipboard(); - - Transferable content = clipboard.getContents(this); - if (content != null) { - try { - String data = (String)(content.getTransferData(DataFlavor.stringFlavor)); - insertReplaceFileDialogText(data); - } catch (Exception e) { - } - } - } - -// CAVEAT: -// Peer coalescing code turned over the fact that the following functions -// were being inherited from Dialog and were not implemented in awt_FileDialog.c -// Five methods decribed by the peer interface are at fault (setResizable, setTitle, -// toFront, toBack and handleFocusTraversalEvent). Additionally show has to be overridden -// as it was necessary to add a show function in MDialogPeer for modality flag passing. -// As a result we were winding up in awt_Dialog.c (now coalesced into awt_TopLevel). -// As Filedialogs are modal and its unclear to me that any of these functions -// can be called while the FD is on-screen let it go. RJM. - public void show() { - // must have our own show or we wind up in pShow for Window. Bad. Very bad. - setVisible(true); - setFilenameFilter(filter); - } - - /** - * MFileDialogPeer doesn't have native pData so we don't do restack on it - * @see java.awt.peer.ContainerPeer#restack - */ - public void restack() { - } - - /** - * @see java.awt.peer.ContainerPeer#isRestackSupported - */ - public boolean isRestackSupported() { - return false; - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MFramePeer.java b/jdk/src/solaris/classes/sun/awt/motif/MFramePeer.java deleted file mode 100644 index d772b99c4c2..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MFramePeer.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - * Copyright 1995-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.util.Vector; -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.*; -import sun.awt.motif.MInputMethodControl; -import sun.awt.im.*; -import java.awt.image.ColorModel; -import java.awt.image.BufferedImage; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferInt; -import java.awt.image.DataBufferByte; -import java.awt.image.DataBufferUShort; -import java.awt.image.ImageObserver; -import java.awt.image.WritableRaster; -import sun.awt.image.ImageRepresentation; -import sun.awt.image.ToolkitImage; - -class MFramePeer extends MWindowPeer implements FramePeer, MInputMethodControl { - static Vector allFrames = new Vector(); - - // XXX: Stub out for now. Need to propagate to normal size hints. - public void setMaximizedBounds(Rectangle b) {} - - public void create(MComponentPeer parent, Object arg) { - super.create( parent ); - } - - MFramePeer(Frame target) { - super(); - // set the window attributes for this Frame - winAttr.nativeDecor = !target.isUndecorated(); - winAttr.initialFocus = true; - winAttr.isResizable = target.isResizable(); - winAttr.initialState = target.getState(); - winAttr.title = target.getTitle(); - winAttr.icon = target.getIconImage(); - if (winAttr.nativeDecor) { - winAttr.decorations = winAttr.AWT_DECOR_ALL; - } else { - winAttr.decorations = winAttr.AWT_DECOR_NONE; - } - - // for input method windows, use minimal decorations - if (target instanceof InputMethodWindow) { - winAttr.initialFocus = false; - winAttr.decorations = (winAttr.AWT_DECOR_TITLE | winAttr.AWT_DECOR_BORDER); - } - - // create and init native component - init( target); - if (winAttr.icon != null) { - setIconImage(winAttr.icon); - } - allFrames.addElement(this); - } - - public void setTitle(String title) { - pSetTitle(title); - } - - protected void disposeImpl() { - allFrames.removeElement(this); - super.disposeImpl(); - } - - public void setMenuBar(MenuBar mb) { - MMenuBarPeer mbpeer = (MMenuBarPeer) MToolkit.targetToPeer(mb); - pSetMenuBar(mbpeer); - - Rectangle r = target.bounds(); - - pReshape(r.x, r.y, r.width, r.height); - if (target.isVisible()) { - target.validate(); - } - } - - public void setIconImage(Image im) { - int width; - int height; - GraphicsConfiguration defaultGC; - if (im != null) { // 4633887 Avoid Null pointer exception. - if (im instanceof ToolkitImage) { - ImageRepresentation ir = ((ToolkitImage)im).getImageRep(); - ir.reconstruct(ImageObserver.ALLBITS); - width = ir.getWidth(); - height = ir.getHeight(); - } - else { - width = im.getWidth(null); - height = im.getHeight(null); - } - if (pGetIconSize(width, height)) { - //Icons are displayed using the default visual, so create image - //using default GraphicsConfiguration - defaultGC = getGraphicsConfiguration().getDevice(). - getDefaultConfiguration(); - ColorModel model = defaultGC.getColorModel(); - WritableRaster raster = - model.createCompatibleWritableRaster(iconWidth, iconHeight); - Image image = new BufferedImage(model, raster, - model.isAlphaPremultiplied(), - null); - - // ARGB BufferedImage to hunt for transparent pixels - BufferedImage bimage = - new BufferedImage(iconWidth, iconHeight, - BufferedImage.TYPE_INT_ARGB); - ColorModel alphaCheck = bimage.getColorModel(); - Graphics g = image.getGraphics(); - Graphics big = bimage.getGraphics(); - try { - g.drawImage(im, 0, 0, iconWidth, iconHeight, null); - big.drawImage(im, 0, 0, iconWidth, iconHeight, null); - } finally { - g.dispose(); - big.dispose(); - } - - DataBuffer db = ((BufferedImage)image).getRaster().getDataBuffer(); - DataBuffer bidb = bimage.getRaster().getDataBuffer(); - byte[] bytedata = null; - int[] intdata = null; - int bidbLen = bidb.getSize(); - int imgDataIdx; - //Get native RGB value for window background color - //Should work for byte as well as int - int bgRGB = getNativeColor(SystemColor.window, defaultGC); - - /* My first attempt at a solution to bug 4175560 was to use - * the iconMask and iconPixmap attributes of Windows. - * This worked fine on CDE/dtwm, however olwm displayed only - * single color icons (white on background). Instead, the - * fix gets the default background window color and replaces - * transparent pixels in the icon image with this color. This - * solutions works well with dtwm as well as olwm. - */ - - for (imgDataIdx = 0; imgDataIdx < bidbLen; imgDataIdx++) { - if (alphaCheck.getAlpha(bidb.getElem(imgDataIdx)) == 0 ) { - //Assuming single data bank - db.setElem(imgDataIdx, bgRGB); - } - } - short[] ushortdata = null; - if (db instanceof DataBufferByte) { - // Pseudocolor data - bytedata = ((DataBufferByte)db).getData(); - } - else if (db instanceof DataBufferInt) { - // Truecolor data - intdata = ((DataBufferInt) db).getData(); - } - else if (db instanceof DataBufferUShort) { - // Truecolor data - ushortdata = ((DataBufferUShort) db).getData(); - } - pSetIconImage(bytedata, intdata, ushortdata, - iconWidth, iconHeight); - } - } - } - - native boolean pGetIconSize(int widthHint, int heightHint); - - // [jk] added ushortData for 16-bpp displays - native void pSetIconImage(byte[] byteData, - int[] intData, - short[] ushortData, - int iconWidth, int iconHeight); - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleIconify() { - postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_ICONIFIED)); - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleDeiconify() { - postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_DEICONIFIED)); - } - - - /** - * Called to inform the Frame that it has moved. - */ - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleMoved(int x, int y) { - postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_MOVED)); - } - - static final int CROSSHAIR_INSET = 5; - - static final int BUTTON_Y = CROSSHAIR_INSET + 1; - static final int BUTTON_W = 17; - static final int BUTTON_H = 17; - - static final int SYS_MENU_X = CROSSHAIR_INSET + 1; - static final int SYS_MENU_CONTAINED_X = SYS_MENU_X + 5; - static final int SYS_MENU_CONTAINED_Y = BUTTON_Y + 7; - static final int SYS_MENU_CONTAINED_W = 8; - static final int SYS_MENU_CONTAINED_H = 3; - - static final int MAXIMIZE_X_DIFF = CROSSHAIR_INSET + BUTTON_W; - static final int MAXIMIZE_CONTAINED_X_DIFF = MAXIMIZE_X_DIFF - 5; - static final int MAXIMIZE_CONTAINED_Y = BUTTON_Y + 5; - static final int MAXIMIZE_CONTAINED_W = 8; - static final int MAXIMIZE_CONTAINED_H = 8; - - static final int MINIMIZE_X_DIFF = MAXIMIZE_X_DIFF + BUTTON_W; - static final int MINIMIZE_CONTAINED_X_DIFF = MINIMIZE_X_DIFF - 7; - static final int MINIMIZE_CONTAINED_Y = BUTTON_Y + 7; - static final int MINIMIZE_CONTAINED_W = 3; - static final int MINIMIZE_CONTAINED_H = 3; - - static final int TITLE_X = SYS_MENU_X + BUTTON_W; - static final int TITLE_W_DIFF = BUTTON_W * 3 + CROSSHAIR_INSET * 2 - 1; - static final int TITLE_MID_Y = BUTTON_Y + (BUTTON_H / 2); - - static final int MENUBAR_X = CROSSHAIR_INSET + 1; - static final int MENUBAR_Y = BUTTON_Y + BUTTON_H; - - static final int HORIZ_RESIZE_INSET = CROSSHAIR_INSET + BUTTON_H; - static final int VERT_RESIZE_INSET = CROSSHAIR_INSET + BUTTON_W; - - - /* - * Print the native component by rendering the Motif look ourselves. - * We also explicitly print the MenuBar since a MenuBar isn't a subclass - * of Component (and thus it has no "print" method which gets called by - * default). - */ - public void print(Graphics g) { - super.print(g); - - Frame f = (Frame)target; - Insets finsets = f.getInsets(); - Dimension fsize = f.getSize(); - - Color bg = f.getBackground(); - Color fg = f.getForeground(); - Color highlight = bg.brighter(); - Color shadow = bg.darker(); - - // Well, we could query for the currently running window manager - // and base the look on that, or we could just always do dtwm. - // aim, tball, and levenson all agree we'll just do dtwm. - - if (hasDecorations(MWindowAttributes.AWT_DECOR_BORDER)) { - - // top outer -- because we'll most likely be drawing on white paper, - // for aesthetic reasons, don't make any part of the outer border - // pure white - if (highlight.equals(Color.white)) { - g.setColor(new Color(230, 230, 230)); - } - else { - g.setColor(highlight); - } - g.drawLine(0, 0, fsize.width, 0); - g.drawLine(0, 1, fsize.width - 1, 1); - - // left outer - // if (highlight.equals(Color.white)) { - // g.setColor(new Color(230, 230, 230)); - // } - // else { - // g.setColor(highlight); - // } - g.drawLine(0, 0, 0, fsize.height); - g.drawLine(1, 0, 1, fsize.height - 1); - - // bottom cross-hair - g.setColor(highlight); - g.drawLine(CROSSHAIR_INSET + 1, fsize.height - CROSSHAIR_INSET, - fsize.width - CROSSHAIR_INSET, - fsize.height - CROSSHAIR_INSET); - - // right cross-hair - // g.setColor(highlight); - g.drawLine(fsize.width - CROSSHAIR_INSET, CROSSHAIR_INSET + 1, - fsize.width - CROSSHAIR_INSET, - fsize.height - CROSSHAIR_INSET); - - // bottom outer - g.setColor(shadow); - g.drawLine(1, fsize.height, fsize.width, fsize.height); - g.drawLine(2, fsize.height - 1, fsize.width, fsize.height - 1); - - // right outer - // g.setColor(shadow); - g.drawLine(fsize.width, 1, fsize.width, fsize.height); - g.drawLine(fsize.width - 1, 2, fsize.width - 1, fsize.height); - - // top cross-hair - // g.setColor(shadow); - g.drawLine(CROSSHAIR_INSET, CROSSHAIR_INSET, - fsize.width - CROSSHAIR_INSET, CROSSHAIR_INSET); - - // left cross-hair - // g.setColor(shadow); - g.drawLine(CROSSHAIR_INSET, CROSSHAIR_INSET, CROSSHAIR_INSET, - fsize.height - CROSSHAIR_INSET); - } - - if (hasDecorations(MWindowAttributes.AWT_DECOR_TITLE)) { - - if (hasDecorations(MWindowAttributes.AWT_DECOR_MENU)) { - - // system menu - g.setColor(bg); - g.fill3DRect(SYS_MENU_X, BUTTON_Y, BUTTON_W, BUTTON_H, true); - g.fill3DRect(SYS_MENU_CONTAINED_X, SYS_MENU_CONTAINED_Y, - SYS_MENU_CONTAINED_W, SYS_MENU_CONTAINED_H, true); - } - - // title bar - // g.setColor(bg); - g.fill3DRect(TITLE_X, BUTTON_Y, fsize.width - TITLE_W_DIFF, BUTTON_H, - true); - - if (hasDecorations(MWindowAttributes.AWT_DECOR_MINIMIZE)) { - - // minimize button - // g.setColor(bg); - g.fill3DRect(fsize.width - MINIMIZE_X_DIFF, BUTTON_Y, BUTTON_W, - BUTTON_H, true); - g.fill3DRect(fsize.width - MINIMIZE_CONTAINED_X_DIFF, - MINIMIZE_CONTAINED_Y, MINIMIZE_CONTAINED_W, - MINIMIZE_CONTAINED_H, true); - } - - if (hasDecorations(MWindowAttributes.AWT_DECOR_MAXIMIZE)) { - - // maximize button - // g.setColor(bg); - g.fill3DRect(fsize.width - MAXIMIZE_X_DIFF, BUTTON_Y, BUTTON_W, - BUTTON_H, true); - g.fill3DRect(fsize.width - MAXIMIZE_CONTAINED_X_DIFF, - MAXIMIZE_CONTAINED_Y, MAXIMIZE_CONTAINED_W, - MAXIMIZE_CONTAINED_H, true); - } - - // title bar text - g.setColor(fg); - Font sysfont = new Font(Font.SANS_SERIF, Font.PLAIN, 10); - g.setFont(sysfont); - FontMetrics sysfm = g.getFontMetrics(); - String ftitle = f.getTitle(); - g.drawString(ftitle, - ((TITLE_X + TITLE_X + fsize.width - TITLE_W_DIFF) / 2) - - (sysfm.stringWidth(ftitle) / 2), - TITLE_MID_Y + sysfm.getMaxDescent()); - } - - if (f.isResizable() && - hasDecorations(MWindowAttributes.AWT_DECOR_RESIZEH)) { - - // add resize cross hairs - - // upper-left horiz (shadow) - g.setColor(shadow); - g.drawLine(1, HORIZ_RESIZE_INSET, CROSSHAIR_INSET, - HORIZ_RESIZE_INSET); - // upper-left vert (shadow) - // g.setColor(shadow); - g.drawLine(VERT_RESIZE_INSET, 1, VERT_RESIZE_INSET, CROSSHAIR_INSET); - // upper-right horiz (shadow) - // g.setColor(shadow); - g.drawLine(fsize.width - CROSSHAIR_INSET + 1, HORIZ_RESIZE_INSET, - fsize.width, HORIZ_RESIZE_INSET); - // upper-right vert (shadow) - // g.setColor(shadow); - g.drawLine(fsize.width - VERT_RESIZE_INSET - 1, 2, - fsize.width - VERT_RESIZE_INSET - 1, CROSSHAIR_INSET + 1); - // lower-left horiz (shadow) - // g.setColor(shadow); - g.drawLine(1, fsize.height - HORIZ_RESIZE_INSET - 1, - CROSSHAIR_INSET, fsize.height - HORIZ_RESIZE_INSET - 1); - // lower-left vert (shadow) - // g.setColor(shadow); - g.drawLine(VERT_RESIZE_INSET, fsize.height - CROSSHAIR_INSET + 1, - VERT_RESIZE_INSET, fsize.height); - // lower-right horiz (shadow) - // g.setColor(shadow); - g.drawLine(fsize.width - CROSSHAIR_INSET + 1, - fsize.height - HORIZ_RESIZE_INSET - 1, fsize.width, - fsize.height - HORIZ_RESIZE_INSET - 1); - // lower-right vert (shadow) - // g.setColor(shadow); - g.drawLine(fsize.width - VERT_RESIZE_INSET - 1, - fsize.height - CROSSHAIR_INSET + 1, - fsize.width - VERT_RESIZE_INSET - 1, fsize.height); - - // upper-left horiz (highlight) - g.setColor(highlight); - g.drawLine(2, HORIZ_RESIZE_INSET + 1, CROSSHAIR_INSET, - HORIZ_RESIZE_INSET + 1); - // upper-left vert (highlight) - // g.setColor(highlight); - g.drawLine(VERT_RESIZE_INSET + 1, 2, VERT_RESIZE_INSET + 1, - CROSSHAIR_INSET); - // upper-right horiz (highlight) - // g.setColor(highlight); - g.drawLine(fsize.width - CROSSHAIR_INSET + 1, - HORIZ_RESIZE_INSET + 1, fsize.width - 1, - HORIZ_RESIZE_INSET + 1); - // upper-right vert (highlight) - // g.setColor(highlight); - g.drawLine(fsize.width - VERT_RESIZE_INSET, 2, - fsize.width - VERT_RESIZE_INSET, CROSSHAIR_INSET); - // lower-left horiz (highlight) - // g.setColor(highlight); - g.drawLine(2, fsize.height - HORIZ_RESIZE_INSET, CROSSHAIR_INSET, - fsize.height - HORIZ_RESIZE_INSET); - // lower-left vert (highlight) - // g.setColor(highlight); - g.drawLine(VERT_RESIZE_INSET + 1, - fsize.height - CROSSHAIR_INSET + 1, - VERT_RESIZE_INSET + 1, fsize.height - 1); - // lower-right horiz (highlight) - // g.setColor(highlight); - g.drawLine(fsize.width - CROSSHAIR_INSET + 1, - fsize.height - HORIZ_RESIZE_INSET, fsize.width - 1, - fsize.height - HORIZ_RESIZE_INSET); - // lower-right vert (highlight) - // g.setColor(highlight); - g.drawLine(fsize.width - VERT_RESIZE_INSET, - fsize.height - CROSSHAIR_INSET + 1, - fsize.width - VERT_RESIZE_INSET, fsize.height - 1); - } - - MenuBar mb = f.getMenuBar(); - if (mb != null) { - MMenuBarPeer peer = (MMenuBarPeer) MToolkit.targetToPeer(mb); - if (peer != null) { - Insets insets = getInsets(); - Graphics ng = g.create(); - int menubarX = 0; - int menubarY = 0; - if (hasDecorations(MWindowAttributes.AWT_DECOR_BORDER)) { - menubarX += CROSSHAIR_INSET + 1; - menubarY += CROSSHAIR_INSET + 1; - } - if (hasDecorations(MWindowAttributes.AWT_DECOR_TITLE)) { - menubarY += BUTTON_H; - } - try { - ng.translate(menubarX, menubarY); - peer.print(ng); - } finally { - ng.dispose(); - } - } - } - } - - // Saveunders are not done by Frame. - void setSaveUnder(boolean state) {} - - /* Returns the native paint should be posted after setting new size - */ - public boolean checkNativePaintOnSetBounds(int width, int height) { - // Fix for 4418155. Undecorated Frame does not repaint - // automticaly if shrinking. Should not wait for Expose - return ((Frame)target).isUndecorated() ? - ((width > oldWidth) || (height > oldHeight)): - ((width != oldWidth) || (height != oldHeight)); - } - - public void setBoundsPrivate(int x, int y, int width, int height) { - setBounds(x, y, width, height); - } - - public Rectangle getBoundsPrivate() { - return getBounds(); - } - - @Override - final boolean isTargetUndecorated() { - return ((Frame)target).isUndecorated(); - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MGlobalCursorManager.java b/jdk/src/solaris/classes/sun/awt/motif/MGlobalCursorManager.java deleted file mode 100644 index dfa8452995d..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MGlobalCursorManager.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.*; -import sun.awt.GlobalCursorManager; -import sun.awt.GlobalCursorManager.*; - -public final class MGlobalCursorManager extends GlobalCursorManager { - - static { - cacheInit(); - } - - private native static void cacheInit(); - - // cached nativeContainer - private Component nativeContainer; - - - /** - * The MGlobalCursorManager is a singleton. - */ - private static MGlobalCursorManager manager; - - - static GlobalCursorManager getCursorManager() { - if (manager == null) { - manager = new MGlobalCursorManager(); - } - return manager; - } - - /** - * Should be called in response to a native mouse enter or native mouse - * button released message. Should not be called during a mouse drag. - */ - static void nativeUpdateCursor(Component heavy) { - MGlobalCursorManager.getCursorManager().updateCursorLater(heavy); - } - - - protected void setCursor(Component comp, Cursor cursor, boolean useCache) { - if (comp == null) { - return; - } - - Cursor cur = useCache ? cursor : getCapableCursor(comp); - - Component nc = useCache ? nativeContainer : getNativeContainer(comp); - - // System.out.println(" set cursor="+cursor+" on "+comp+" new curs="+cur); - if (nc != null && nc.isDisplayable()) { - nativeContainer = nc; - ((MComponentPeer)nc.getPeer()).pSetCursor(cur); - } - } - - private Component getNativeContainer(Component comp) { - while (comp != null && comp.isLightweight()) { - comp = comp.getParent(); - } - return comp; - } - - protected native void getCursorPos(Point p); - protected native Component findHeavyweightUnderCursor(); - - /* - * two native methods to call corresponding methods in Container and - * Component - */ - protected native Component findComponentAt(Container con, int x, int y); - protected native Point getLocationOnScreen(Component com); - - protected Component findHeavyweightUnderCursor(boolean useCache) { - return findHeavyweightUnderCursor(); - } - - private Cursor getCapableCursor(Component comp) { - Component c = comp; - while ((c != null) && !(c instanceof Window) && - c.isEnabled() && c.isVisible() && c.isDisplayable()) { - c = c.getParent(); - } - if (c instanceof Window) { - return (c.isEnabled() && c.isVisible() && c.isDisplayable() && comp.isEnabled()) ? - comp.getCursor() : - Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); - } else if (c == null) { - return null; - } - return getCapableCursor(c.getParent()); - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MInputMethod.java b/jdk/src/solaris/classes/sun/awt/motif/MInputMethod.java deleted file mode 100644 index 3c2a5f15368..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MInputMethod.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.AWTException; -import java.awt.Component; -import java.awt.Container; -import java.awt.Window; -import java.awt.peer.ComponentPeer; -import sun.awt.X11InputMethod; -import sun.awt.SunToolkit; - -/** - * Input Method Adapter for XIM (with Motif) - * - * @author JavaSoft International - */ -public class MInputMethod extends X11InputMethod { - - public MInputMethod() throws AWTException { - super(); - } - - protected boolean openXIM() { - return openXIMNative(); - } - - protected boolean createXIC() { - MComponentPeer peer = (MComponentPeer)getPeer(clientComponentWindow); - if (peer == null) { - return false; - } - MComponentPeer tc = null; - if (peer instanceof MInputMethodControl) { - tc = ((MInputMethodControl)peer).getTextComponent(); - } - if (!createXICNative(peer, tc)) { - return false; - } - if (peer instanceof MInputMethodControl) { - ((MInputMethodControl)peer).addInputMethod(this); - } - return true; - } - - protected void setXICFocus(ComponentPeer peer, - boolean value, boolean active) { - setXICFocusNative((MComponentPeer)peer, value, active); - } - - protected Container getParent(Component client) { - // SECURITY: Use _NoClientCode(), because this thread may - // be privileged - return MComponentPeer.getParent_NoClientCode(client); - } - - /** - * Returns peer of the given client component. If the given client component - * doesn't have peer, peer of the native container of the client is returned. - */ - protected ComponentPeer getPeer(Component client) { - MComponentPeer peer = (MComponentPeer)MToolkit.targetToPeer(client); - if (peer != null) - return peer; - - Container nativeContainer = MToolkit.getNativeContainer(client); - peer = (MComponentPeer)MToolkit.targetToPeer(nativeContainer); - return peer; - } - - /** - * Changes the status area configuration that is to be requested - * by Frame or Dialog. - */ - void configureStatus() { - if (isDisposed()) { - return; - } - - MComponentPeer peer = (MComponentPeer)getPeer((Window) clientComponentWindow); - MComponentPeer tc = ((MInputMethodControl)peer).getTextComponent(); - if (tc != null) { - configureStatusAreaNative(tc); - } - } - - /* - * Subclasses should override disposeImpl() instead of dispose(). Client - * code should always invoke dispose(), never disposeImpl(). - */ - protected synchronized void disposeImpl() { - if (clientComponentWindow != null) { - MComponentPeer peer = (MComponentPeer)getPeer(clientComponentWindow); - if (peer instanceof MInputMethodControl) - ((MInputMethodControl)peer).removeInputMethod(this); - clientComponentWindow = null; - } - - super.disposeImpl(); - } - - /** - * @see java.awt.im.spi.InputMethod#removeNotify - */ - public synchronized void removeNotify() { - if (MToolkit.targetToPeer(getClientComponent()) != null) { - dispose(); - } else { - // We do not have to dispose XICs in case of lightweight component. - resetXIC(); - } - } - - /** - * Changes the internal XIC configurations. This is required the - * case that addition or elimination of text components has - * happened in the containment hierarchy. This method is invoked - * by Frame or Dialog. - */ - synchronized void reconfigureXIC(MInputMethodControl control) { - if (!isDisposed()) { - // Some IM servers require to reset XIC before destroying - // the XIC. I.e., Destroying XIC doesn't reset the internal - // state of the IM server. endComposition() takes care of - // resetting XIC and preedit synchronization. However, - // there is no client at this point. It is assumed that - // the previous client is still available for dispatching - // committed text which maintains client's composition - // context. - endComposition(); - resetXICifneeded(); - reconfigureXICNative((MComponentPeer) control, control.getTextComponent()); - } - } - - protected void awtLock() { - SunToolkit.awtLock(); - } - - protected void awtUnlock() { - SunToolkit.awtUnlock(); - } - - /* - * Native methods - */ - private native boolean openXIMNative(); - private native boolean createXICNative(MComponentPeer peer, MComponentPeer tc); - private native void reconfigureXICNative(MComponentPeer peer, - MComponentPeer tc); - private native void configureStatusAreaNative(MComponentPeer tc); - private native void setXICFocusNative(MComponentPeer peer, - boolean value, boolean active); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MInputMethodControl.java b/jdk/src/solaris/classes/sun/awt/motif/MInputMethodControl.java deleted file mode 100644 index 6dc89897ea5..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MInputMethodControl.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import sun.awt.motif.MComponentPeer; -import sun.awt.motif.MInputMethod; - -/** - * An interface for controlling containment hierarchy configuration to - * keep track of existence of any TextArea or TextField and to manage - * input method status area. - * - * @auther JavaSoft International - */ -interface MInputMethodControl { - - /** - * Informs Frame or Dialog that a text component has been added to - * the hierarchy. - * @param textComponentPeer peer of the text component - */ - void addTextComponent(MComponentPeer textComponentPeer); - - /** - * Informs Frame or Dialog that a text component has been removed - * from the hierarchy. - * @param textComponentPeer peer of the text component - */ - void removeTextComponent(MComponentPeer textComponentPeer); - - /** - * Returns a text component peer in the containment hierarchy - * to obtain the Motif status area information - */ - MComponentPeer getTextComponent(); - - /** - * Inform Frame or Dialog that an MInputMethod has been - * constructed so that Frame and Dialog can invoke the method in - * MInputMethod to reconfigure XICs. - * @param inputMethod an MInputMethod instance - */ - void addInputMethod(MInputMethod inputMethod); - - /** - * Inform Frame or Dialog that an X11InputMethod is being destroyed. - * @param inputMethod an X11InputMethod instance - */ - void removeInputMethod(MInputMethod inputMethod); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MInputMethodDescriptor.java b/jdk/src/solaris/classes/sun/awt/motif/MInputMethodDescriptor.java deleted file mode 100644 index cbd9a73f63c..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MInputMethodDescriptor.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - - -package sun.awt.motif; - -import java.awt.im.spi.InputMethod; -import sun.awt.X11InputMethodDescriptor; - -/** - * Provides sufficient information about an input method - * to enable selection and loading of that input method. - * The input method itself is only loaded when it is actually used. - * - * @since JDK1.3 - */ - -class MInputMethodDescriptor extends X11InputMethodDescriptor { - - /** - * @see java.awt.im.spi.InputMethodDescriptor#createInputMethod - */ - public InputMethod createInputMethod() throws Exception { - return new MInputMethod(); - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MLabelPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MLabelPeer.java deleted file mode 100644 index 16cfc4ef972..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MLabelPeer.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 1995-1996 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; - -class MLabelPeer extends MComponentPeer implements LabelPeer { - native void create(MComponentPeer parent); - - public void initialize() { - Label l = (Label)target; - String txt; - int align; - - if ((txt = l.getText()) != null) { - setText(l.getText()); - } - if ((align = l.getAlignment()) != Label.LEFT) { - setAlignment(align); - } - super.initialize(); - } - - MLabelPeer(Label target) { - super(target); - } - - public Dimension getMinimumSize() { - FontMetrics fm = getFontMetrics(target.getFont()); - String label = ((Label)target).getText(); - if (label == null) label = ""; - return new Dimension(fm.stringWidth(label) + 14, - fm.getHeight() + 8); - } - - public native void setText(String label); - public native void setAlignment(int alignment); - - /* - * Print the native component by rendering the Motif look ourselves. - */ - public void print(Graphics g) { - Label l = (Label)target; - Dimension d = l.size(); - Color bg = l.getBackground(); - Color fg = l.getForeground(); - - g.setColor(bg); - g.fillRect(1, 1, d.width - 2, d.height - 2); - - g.setColor(fg); - g.setFont(l.getFont()); - FontMetrics fm = g.getFontMetrics(); - String lbl = l.getText(); - - switch (l.getAlignment()) { - case Label.LEFT: - g.drawString(lbl, 2, - (d.height + fm.getMaxAscent() - fm.getMaxDescent()) / 2); - break; - case Label.RIGHT: - g.drawString(lbl, d.width - (fm.stringWidth(lbl) + 2), - (d.height + fm.getMaxAscent() - fm.getMaxDescent()) / 2); - break; - case Label.CENTER: - g.drawString(lbl, (d.width - fm.stringWidth(lbl)) / 2, - (d.height + fm.getMaxAscent() - fm.getMaxDescent()) / 2); - break; - } - - target.print(g); - } - - /** - * DEPRECATED - */ - public Dimension minimumSize() { - return getMinimumSize(); - } - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MListPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MListPeer.java deleted file mode 100644 index 66442533724..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MListPeer.java +++ /dev/null @@ -1,390 +0,0 @@ -/* - * Copyright 1995-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.ActionEvent; -import java.awt.event.ItemEvent; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; - -class MListPeer extends MComponentPeer implements ListPeer { - native void create(MComponentPeer parent); - - void initialize() { - List li = (List)target; - - /* add any items that were already inserted in the target. */ - int nitems = li.countItems(); - for (int i = 0; i < nitems; i++) { - addItem(li.getItem(i), -1); - } - - /* set whether this list should allow multiple selections. */ - setMultipleSelections(li.allowsMultipleSelections()); - - /* make the visible position visible. */ - int index = li.getVisibleIndex(); - if (index >= 0) { - makeVisible(index); - } - - /* select the item if necessary. */ - int sel[] = li.getSelectedIndexes(); - for (int i = 0 ; i < sel.length ; i++) { - select(sel[i]); - } - - /* BugID 4060345 to avoid showing scrollbar in empty List */ - if (nitems == 0) { - addItem(" ", 0); - delItems(0, 0); - } - super.pSetScrollbarBackground(getParent_NoClientCode(li).getBackground()); - - if (!target.isBackgroundSet()) { - target.setBackground(SystemColor.text); - } - if (!target.isForegroundSet()) { - target.setForeground(SystemColor.textText); - } - - super.initialize(); - } - - MListPeer(List target) { - super(target); - } - - /* New method name for 1.1 */ - public void add(String item, int index) { - addItem(item, index); - } - - /* New method name for 1.1 */ - public void removeAll() { - clear(); - } - - /* New method name for 1.1 */ - public void setMultipleMode (boolean b) { - setMultipleSelections(b); - } - - /* New method name for 1.1 */ - public Dimension getPreferredSize(int rows) { - return preferredSize(rows); - } - - /* New method name for 1.1 */ - public Dimension getMinimumSize(int rows) { - return minimumSize(rows); - } - - public void setForeground(Color c) { - pSetInnerForeground(c); - } - - public native void setBackground(Color c); - public native void setMultipleSelections(boolean v); - public native boolean isSelected(int index); - public native void addItem(String item, int index); - public native void delItems(int start, int end); - public native void select(int index); - public native void deselect(int index); - public native void makeVisible(int index); - - public void clear() { - List l = (List)target; - int count = l.countItems(); - if (count > 0) { - delItems(0, count-1); - } - } - - public int[] getSelectedIndexes() { - List l = (List)target; - int len = l.countItems(); - int sel[] = new int[len]; - int nsel = 0; - for (int i = 0 ; i < len ; i++) { - if (isSelected(i)) { - sel[nsel++] = i; - } - } - int selected[] = new int[nsel]; - System.arraycopy(sel, 0, selected, 0, nsel); - return selected; - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void action(int index, final long when, final int modifiers) { - final List list = (List)target; - final int selectIndex = index; - - MToolkit.executeOnEventHandlerThread(list, new Runnable() { - public void run() { - list.select(selectIndex); - postEvent(new ActionEvent(target, ActionEvent.ACTION_PERFORMED, - list.getItem(selectIndex), when, - modifiers)); - } - }); - } // action() - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleListChanged(int index) { - final MListPeer listPeer = this; - final List list = (List)target; - final int listIndex = index; - - MToolkit.executeOnEventHandlerThread(list, new Runnable() { - public void run() { - int selected[] = listPeer.getSelectedIndexes(); - boolean isSelected = false; - - for (int i=0; i < selected.length; i++) { - if (listIndex == selected[i]) { - isSelected = true; - break; - } - } - postEvent(new ItemEvent(list, ItemEvent.ITEM_STATE_CHANGED, - Integer.valueOf(listIndex), - isSelected? ItemEvent.SELECTED : ItemEvent.DESELECTED)); - - } - }); - } // handleListChanged() - - public Dimension minimumSize() { - return minimumSize(4); - } - - public Dimension preferredSize(int v) { - return minimumSize(v); - } - - public Dimension minimumSize(int v) { - FontMetrics fm = getFontMetrics(((List)target).getFont()); - return new Dimension(SCROLLBAR + 2*MARGIN + - fm.stringWidth("0123456789abcde"), - ((fm.getHeight()+2*SPACE) * v) + - 2*MARGIN); - } - - public boolean isFocusable() { - return true; - } - - /* - * Print the native component by rendering the Motif look ourselves. - * ToDo(aim): needs to query native motif for more accurate size and - * color information, selected items, and item offset. - */ - final static int MARGIN = 2; - final static int SPACE = 1; - final static int SCROLLBAR = 16; - int fontHeight; - int fontAscent; - int fontLeading; - int vval; - int hval; - int vmax; - int hmax; - - public void print(Graphics g) { - List l = (List)target; - Dimension d = l.size(); - Color bg = l.getBackground(); - Color fg = l.getForeground(); - int numItems = l.getItemCount(); - FontMetrics fm = getFontMetrics(l.getFont()); - int w, h; - int vvis, hvis, vmin, hmin; - int max = 0; - - for (int i = 0; i < numItems; i++) { - int len = fm.stringWidth(l.getItem(i)); - max = Math.max(max, len); - } - - fontHeight = fm.getHeight(); - fontAscent = fm.getAscent(); - fontLeading = fm.getLeading(); - - hmin = vmin = 0; - - vvis = itemsInWindow(true); - vmax = Math.max(numItems - vvis, 0); - h = d.height - SCROLLBAR; - - if (vmax != 0) { - w = d.width - SCROLLBAR; - hvis = w - ((2 * SPACE) + (2 * MARGIN)); - hmax = Math.max(max - hvis, 0); - } else { - w = d.width; - hvis = w - ((2 * SPACE) + (2 * MARGIN)); - hmax = Math.max(max - hvis, 0); - } - if (hmax == 0) { - h = d.height; - vvis = itemsInWindow(false); - vmax = Math.max(numItems - vvis, 0); - } - if (vmax == 0) { - w = d.width; - hvis = w - ((2 * SPACE) + (2 * MARGIN)); - hmax = Math.max(max - hvis, 0); - } - - hval = 0; - vval = 0; - /* -System.out.println("print List: "+d.width+"x"+d.height+" numItems="+numItems+ -"max="+max+" vsb=("+vmin+".."+vmax+","+vval+","+vvis+ -") hsb=("+hmin+".."+hmax+","+hval+","+hvis+")"); -*/ - - g.setColor(bg); - g.fillRect(0, 0, w, h); - - if (hmax != 0) { - int sbw = d.width - ((vmax == 0) ? 0 : SCROLLBAR); - g.fillRect(1, d.height - SCROLLBAR - 3, sbw - 1, SCROLLBAR - 3); - Graphics ng = g.create(); - try { - ng.translate(0, d.height - (SCROLLBAR - 2)); - drawScrollbar(ng, bg, SCROLLBAR - 2, sbw, - hmin, hmax, hval, hvis, true); - } finally { - ng.dispose(); - } - } - if (vmax != 0) { - int sbh = d.height - ((hmax == 0) ? 0 : SCROLLBAR); - g.fillRect(d.width - SCROLLBAR - 3, 1, SCROLLBAR - 3, sbh - 1); - Graphics ng = g.create(); - try { - ng.translate(d.width - (SCROLLBAR - 2), 0); - drawScrollbar(ng, bg, SCROLLBAR - 2, sbh, - vmin, vmax, vval, vvis, false); - } finally { - ng.dispose(); - } - } - - draw3DRect(g, bg, 0, 0, w - 1, h - 1, false); - - if (numItems > 0) { - int n = itemsInWindow(hmax != 0); - int e = Math.min(numItems - 1, (vval + n) - 1); - paintItems(g, bg, fg, vval, e); - } - - target.print(g); - } - - int itemsInWindow(boolean scrollbarVisible) { - Dimension d = target.size(); - int h; - if (scrollbarVisible) { - h = d.height - ((2 * MARGIN) + SCROLLBAR); - } else { - h = d.height - 2*MARGIN; - } - int i = fontHeight - fontLeading; - return h / (i + (2 * SPACE)); - } - - void paintItem(Graphics g, Color bg, Color fg, int index, boolean isSelected) { - List l = (List)target; - Dimension d = l.size(); - int numItems = l.getItemCount(); - Color shadow = bg.darker(); - - if ((index < vval) || (index >= (vval + itemsInWindow(hmax != 0)))) { - return; - } - int w = d.width - ((2 * MARGIN) + ((vmax != 0)? SCROLLBAR : 0)); - int h = (fontHeight - fontLeading); - int htotal = h + (2 * SPACE); - int index2y = MARGIN + (index * htotal) + SPACE; - int y = index2y - (vval * htotal); - int x = MARGIN + SPACE; - Graphics ng = g.create(); - try { - if (index > numItems - 1) { - ng.setColor(bg); - ng.fillRect(x - 2, y - 2, w, h + 4); - return; - } - if (isSelected) { - ng.setColor(shadow); - ng.fillRect(x - 1, y - 1, w - 2, h + 2); - } else { - ng.setColor(bg); - ng.fillRect(x - 1, y - 1, w - 2, h + 2); - } - ng.setColor(bg); - - ng.drawRect(x - 2, y - 2, w - 1, h + 3); - ng.setColor(fg); - String str = (String)l.getItem(index); - ng.clipRect(x, y, w - (2 * SPACE), h); - ng.drawString(str, x - hval, y + fontAscent); - } finally { - ng.dispose(); - } - } - - void paintItems(Graphics g, Color bg, Color fg, int s, int e) { - for (int i = s ; i <= e ; i++) { - paintItem(g, bg, fg, i, false); - } - } - - public boolean handlesWheelScrolling() {return true;} - - public void handleEvent(AWTEvent e) { - if (e.getID() == MouseEvent.MOUSE_WHEEL) { - MouseWheelEvent mwe = (MouseWheelEvent)e; - nativeHandleMouseWheel(mwe.getScrollType(), - mwe.getScrollAmount(), - mwe.getWheelRotation()); - } - else { - super.handleEvent(e); - } - } - - native void nativeHandleMouseWheel(int scrollType, - int scrollAmount, - int wheelRotation); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MMenuBarPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MMenuBarPeer.java deleted file mode 100644 index de88ea0e8f4..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MMenuBarPeer.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import sun.awt.*; - -public class MMenuBarPeer implements MenuBarPeer { - long pData; - MenuBar target; - private X11GraphicsConfig graphicsConfig=null; - - private boolean disposed = false; - - static { - initIDs(); - } - - /** - * Initialize JNI field and method IDs for fields that may be accessed - from C. - */ - private static native void initIDs(); - - native void create(MFramePeer f); - - public MMenuBarPeer(MenuBar target) { - this.target = target; - MFramePeer parent = (MFramePeer) MToolkit.targetToPeer(MMenuItemPeer.getParent_NoClientCode(target)); - create(parent); - } - - protected void finalize() throws Throwable { - dispose(); - super.finalize(); - } - - /* - * Subclasses should override disposeImpl() instead of dispose(). Client - * code should always invoke dispose(), never disposeImpl(). - */ - private native void pDispose(); - protected void disposeImpl() { - MToolkit.targetDisposedPeer(target, this); - pDispose(); - } - public final void dispose() { - boolean call_disposeImpl = false; - - if (!disposed) { - synchronized (this) { - if (!disposed) { - disposed = call_disposeImpl = true; - } - } - } - - if (call_disposeImpl) { - disposeImpl(); - } - } - public void addMenu(Menu m) { - } - public void delMenu(int index) { - } - public void addHelpMenu(Menu m) { - } - - static final int GAP = 10; - static final int W_DIFF = (MFramePeer.CROSSHAIR_INSET + 1) * 2; - static final int H_DIFF = MFramePeer.BUTTON_Y + MFramePeer.BUTTON_H; - - /* - * Print the native component by rendering the Motif look ourselves. - * ToDo(aim): needs to query native motif for more appropriate size and - * color information. - */ - void print(Graphics g) { - MenuBar mb = (MenuBar)target; - Frame f = (Frame)MMenuItemPeer.getParent_NoClientCode(target); - Dimension fd = f.size(); - Insets insets = f.insets(); - - /* Calculate menubar dimension. */ - int width = fd.width; - int height = insets.top; - if (f.getPeer() instanceof MFramePeer) { - MFramePeer fpeer = (MFramePeer)f.getPeer(); - if (fpeer.hasDecorations(MWindowAttributes.AWT_DECOR_BORDER)) { - width -= W_DIFF; - height -= MFramePeer.BUTTON_Y; - } - if (fpeer.hasDecorations(MWindowAttributes.AWT_DECOR_MENU)) { - height -= MFramePeer.BUTTON_H; - } - } - Dimension d = new Dimension(width, height); - - Shape oldClipArea = g.getClip(); - g.clipRect(0, 0, d.width, d.height); - - Color bg = f.getBackground(); - Color fg = f.getForeground(); - Color highlight = bg.brighter(); - Color shadow = bg.darker(); - - // because we'll most likely be drawing on white paper, - // for aesthetic reasons, don't make any part of the outer border - // pure white - if (highlight.equals(Color.white)) { - g.setColor(new Color(230, 230, 230)); - } - else { - g.setColor(highlight); - } - g.drawLine(0, 0, d.width, 0); - g.drawLine(1, 1, d.width - 1, 1); - g.drawLine(0, 0, 0, d.height); - g.drawLine(1, 1, 1, d.height - 1); - g.setColor(shadow); - g.drawLine(d.width, 1, d.width, d.height); - g.drawLine(d.width - 1, 2, d.width - 1, d.height); - g.drawLine(1, d.height, d.width, d.height); - g.drawLine(2, d.height - 1, d.width, d.height - 1); - - int x = GAP; - int nitems = mb.countMenus(); - - Menu helpMenu = target.getHelpMenu(); - - for (int i = 0 ; i < nitems ; i++) { - Menu mn = target.getMenu(i); - String item = mn.getLabel(); - if (item == null) { - item = ""; - } - Font menuFont = mn.getFont(); - g.setFont(menuFont); - FontMetrics menuMetrics = g.getFontMetrics(); - int y = (d.height / 2) + menuMetrics.getMaxDescent(); - int w = menuMetrics.stringWidth(item) + GAP * 2; - - if (x >= d.width) { - break; - } - if (mn.isEnabled()) { - g.setColor(fg); - } - else { - // draw text as grayed out - g.setColor(shadow); - } - - if (helpMenu == mn) { - g.drawString(item, d.width - w + GAP, y); - } - else { - g.drawString(item, x, y); - x += w; - } - } - - g.setClip(oldClipArea); - } - - // Needed for MenuComponentPeer. - public void setFont(Font f) { - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MMenuItemPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MMenuItemPeer.java deleted file mode 100644 index cb08c6b4485..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MMenuItemPeer.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.ActionEvent; -import sun.awt.AppContext; - -class MMenuItemPeer implements MenuItemPeer { - long pData; - long jniGlobalRef; - boolean isCheckbox = false; - MenuItem target; - boolean nativeCreated = false; - - private boolean disposed = false; - - static { - initIDs(); - } - - /** - * Initialize JNI field and method IDs - */ - private static native void initIDs(); - - native void createMenuItem(MMenuPeer parent); - - void create(MMenuPeer parent) { - if (parent.nativeCreated) { - createMenuItem(parent); - nativeCreated = true; - setEnabled(target.isEnabled()); - } - } - - protected MMenuItemPeer() { - } - - MMenuItemPeer(MenuItem target) { - this.target = target; - MMenuPeer parent = (MMenuPeer) MToolkit.targetToPeer(getParent_NoClientCode(target)); - create(parent); - } - - static native MenuContainer getParent_NoClientCode(MenuComponent menuComponent); - - protected void finalize() throws Throwable { - dispose(); - super.finalize(); - } - - public void setEnabled(boolean b) { - if (b) { - enable(); - } else { - disable(); - } - } - - public void setLabel(String label) { - if (!nativeCreated) { - return; - } - pSetLabel(label); - // Fix for bug 4234266 AWT component : MenuItem throw NullPointer exception. - MenuShortcut sc = target.getShortcut(); - setShortcut(sc != null ? sc.toString() : null ); - } - - public void setShortcut(String shortCut) { - if (!nativeCreated) { - return; - } - pSetShortcut(shortCut); - } - - native void pSetLabel(String label); - native void pSetShortcut(String shortCut); - - /** - * DEPRECATED but, for now, called by setEnabled(boolean). - */ - public void enable() { - if (!nativeCreated) { - return; - } - pEnable(); - } - native void pEnable(); - - /** - * DEPRECATED but, for now, called by setEnabled(boolean). - */ - public void disable() { - if (!nativeCreated) { - return; - } - pDisable(); - } - native void pDisable(); - - private void destroyNativeWidgetImpl() { - if (nativeCreated) { - pDispose(); - nativeCreated = false; - } - } - - void destroyNativeWidget() { - // We do not need to synchronize this method because the caller - // always holds the tree lock - - destroyNativeWidgetImpl(); - } - - /* - * Subclasses should override disposeImpl() instead of dispose(). Client - * code should always invoke dispose(), never disposeImpl(). - */ - protected void disposeImpl() { - // Don't call destroyNativeWidget() because on a Menu, this will - // cause a traversal of all the menu's MenuItems. This traversal was - // already done once by java.awt.Menu.removeNotify(). - - destroyNativeWidgetImpl(); - MToolkit.targetDisposedPeer(target, this); - } - public final void dispose() { - boolean call_disposeImpl = false; - - if (!disposed) { - synchronized (this) { - if (!disposed) { - disposed = call_disposeImpl = true; - } - } - } - - if (call_disposeImpl) { - disposeImpl(); - } - } - - native void pDispose(); - - void postEvent(AWTEvent event) { - MToolkit.postEvent(MToolkit.targetToAppContext(target), event); - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void action(final long when, final int modifiers) { - - MToolkit.executeOnEventHandlerThread(target, new Runnable() { - public void run() { - postEvent(new ActionEvent(target, ActionEvent.ACTION_PERFORMED, - target.getActionCommand(), when, - modifiers)); - } - }); - } - - // Needed for MenuComponentPeer. - public void setFont(Font f) { - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MMenuPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MMenuPeer.java deleted file mode 100644 index 4a378e74685..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MMenuPeer.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 1995-1999 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; - -public class MMenuPeer extends MMenuItemPeer implements MenuPeer { - native void createMenu(MMenuBarPeer parent); - native void createSubMenu(MMenuPeer parent); - - void create(MMenuPeer parent) { - if (parent.nativeCreated) { - createSubMenu(parent); - nativeCreated = true; - } - } - - protected MMenuPeer() { - } - - public MMenuPeer(Menu target) { - this.target = target; - MenuContainer parent = getParent_NoClientCode(target); - - if (parent instanceof MenuBar) { - MMenuBarPeer mb = (MMenuBarPeer) MToolkit.targetToPeer(parent); - createMenu(mb); - nativeCreated = true; - } else if (parent instanceof Menu) { - MMenuPeer m = (MMenuPeer) MToolkit.targetToPeer(parent); - create(m); - } else { - throw new IllegalArgumentException("unknown menu container class"); - } - } - - public void addSeparator() { - } - public void addItem(MenuItem item) { - } - public void delItem(int index) { - } - - void destroyNativeWidget() { - // We do not need to synchronize this method because the caller - // always holds the tree lock - - if (nativeCreated) { - Menu menu = (Menu) target; - int nitems = menu.getItemCount(); - for (int i = 0 ; i < nitems ; i++) { - MMenuItemPeer mipeer = - (MMenuItemPeer) MToolkit.targetToPeer(menu.getItem(i)); - mipeer.destroyNativeWidget(); - } - super.destroyNativeWidget(); - } - } - native void pDispose(); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MMouseDragGestureRecognizer.java b/jdk/src/solaris/classes/sun/awt/motif/MMouseDragGestureRecognizer.java deleted file mode 100644 index 460e189e5d4..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MMouseDragGestureRecognizer.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright 1998-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.Toolkit; -import java.awt.Component; - -import java.awt.Point; -import java.awt.dnd.DnDConstants; -import java.awt.dnd.DragSource; -import java.awt.dnd.MouseDragGestureRecognizer; -import java.awt.dnd.DragGestureListener; - -import java.awt.event.InputEvent; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; - -import java.lang.reflect.*; - -import sun.awt.dnd.SunDragSourceContextPeer; - -/** - *

- * This subclass of MouseDragGestureRecognizer defines a DragGestureRecognizer - * for Mouse based gestures on OSF/Motif. - *

- * - * @author Laurence P. G. Cable - * - * @see java.awt.dnd.DragGestureListener - * @see java.awt.dnd.DragGestureEvent - * @see java.awt.dnd.DragSource - */ - -class MMouseDragGestureRecognizer extends MouseDragGestureRecognizer { - - private static final long serialVersionUID = -841711780352520383L; - - /* - * constant for number of pixels hysterisis before drag is determined - * to have started - */ - - protected static int motionThreshold; - - - protected static final int ButtonMask = InputEvent.BUTTON1_DOWN_MASK | - InputEvent.BUTTON2_DOWN_MASK | - InputEvent.BUTTON3_DOWN_MASK; - - /** - * construct a new MMouseDragGestureRecognizer - * - * @param ds The DragSource for the Component c - * @param c The Component to observe - * @param act The actions permitted for this Drag - * @param dgl The DragGestureRecognizer to notify when a gesture is detected - * - */ - - protected MMouseDragGestureRecognizer(DragSource ds, Component c, int act, DragGestureListener dgl) { - super(ds, c, act, dgl); - } - - /** - * construct a new MMouseDragGestureRecognizer - * - * @param ds The DragSource for the Component c - * @param c The Component to observe - * @param act The actions permitted for this Drag - */ - - protected MMouseDragGestureRecognizer(DragSource ds, Component c, int act) { - this(ds, c, act, null); - } - - /** - * construct a new MMouseDragGestureRecognizer - * - * @param ds The DragSource for the Component c - * @param c The Component to observe - */ - - protected MMouseDragGestureRecognizer(DragSource ds, Component c) { - this(ds, c, DnDConstants.ACTION_NONE); - } - - /** - * construct a new MMouseDragGestureRecognizer - * - * @param ds The DragSource for the Component c - */ - - protected MMouseDragGestureRecognizer(DragSource ds) { - this(ds, null); - } - - /** - * determine the drop action from the event - */ - - protected int mapDragOperationFromModifiers(MouseEvent e) { - int mods = e.getModifiersEx(); - int btns = mods & ButtonMask; - - // Do not allow right mouse button drag since Motif DnD does not - // terminate drag operation on right mouse button release. - if (!(btns == InputEvent.BUTTON1_DOWN_MASK || - btns == InputEvent.BUTTON2_DOWN_MASK)) { - return DnDConstants.ACTION_NONE; - } - - return - SunDragSourceContextPeer.convertModifiersToDropAction(mods, - getSourceActions()); - } - - /** - * Invoked when the mouse has been clicked on a component. - */ - - public void mouseClicked(MouseEvent e) { - // do nothing - } - - /** - * Invoked when a mouse button has been pressed on a component. - */ - - public void mousePressed(MouseEvent e) { - events.clear(); - - if (mapDragOperationFromModifiers(e) != DnDConstants.ACTION_NONE) { - try { - motionThreshold = DragSource.getDragThreshold(); - } catch (Exception exc) { - motionThreshold = 5; - } - appendEvent(e); - } - } - - /** - * Invoked when a mouse button has been released on a component. - */ - - public void mouseReleased(MouseEvent e) { - events.clear(); - } - - /** - * Invoked when the mouse enters a component. - */ - - public void mouseEntered(MouseEvent e) { - events.clear(); - } - - /** - * Invoked when the mouse exits a component. - */ - - public void mouseExited(MouseEvent e) { - if (!events.isEmpty()) { // gesture pending - int dragAction = mapDragOperationFromModifiers(e); - - if (dragAction == DnDConstants.ACTION_NONE) { - events.clear(); - } - } - } - - /** - * Invoked when a mouse button is pressed on a component. - */ - - public void mouseDragged(MouseEvent e) { - if (!events.isEmpty()) { // gesture pending - int dop = mapDragOperationFromModifiers(e); - - - if (dop == DnDConstants.ACTION_NONE) { - return; - } - - MouseEvent trigger = (MouseEvent)events.get(0); - - Point origin = trigger.getPoint(); - Point current = e.getPoint(); - - int dx = Math.abs(origin.x - current.x); - int dy = Math.abs(origin.y - current.y); - - if (dx > motionThreshold || dy > motionThreshold) { - fireDragGestureRecognized(dop, ((MouseEvent)getTriggerEvent()).getPoint()); - } else - appendEvent(e); - } - } - - /** - * Invoked when the mouse button has been moved on a component - * (with no buttons no down). - */ - - public void mouseMoved(MouseEvent e) { - // do nothing - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MPanelPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MPanelPeer.java deleted file mode 100644 index 9a1833ecd9a..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MPanelPeer.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; - -import sun.awt.SunGraphicsCallback; - -class MPanelPeer extends MCanvasPeer implements PanelPeer { - - MPanelPeer() {} - - MPanelPeer(Component target) { - super(target); - } - - MPanelPeer(Component target, Object arg) { - super(target, arg); - } - - public Insets getInsets() { - return new Insets(0, 0, 0, 0); - } - - public void paint(Graphics g) { - super.paint(g); - SunGraphicsCallback.PaintHeavyweightComponentsCallback.getInstance(). - runComponents(((Container)target).getComponents(), g, - SunGraphicsCallback.LIGHTWEIGHTS | - SunGraphicsCallback.HEAVYWEIGHTS); - } - public void print(Graphics g) { - super.print(g); - SunGraphicsCallback.PrintHeavyweightComponentsCallback.getInstance(). - runComponents(((Container)target).getComponents(), g, - SunGraphicsCallback.LIGHTWEIGHTS | - SunGraphicsCallback.HEAVYWEIGHTS); - } - - public void setBackground(Color c) { - Component comp; - int i; - - Container cont = (Container) target; - synchronized(target.getTreeLock()) { - int n = cont.getComponentCount(); - for(i=0; i < n; i++) { - comp = cont.getComponent(i); - MComponentPeer peer = (MComponentPeer) MToolkit.targetToPeer(comp); - if (peer != null) { - Color color = comp.getBackground(); - if (color == null || color.equals(c)) { - peer.setBackground(c); - peer.pSetBackground(c); - } - if ((comp instanceof java.awt.List) || - (comp instanceof java.awt.TextArea) || - (comp instanceof java.awt.ScrollPane)) { - peer.pSetScrollbarBackground(c); - } - } - } - } - pSetBackground(c); - } - - public void setForeground(Color c) { - Component comp; - int i; - - Container cont = (Container) target; - synchronized(target.getTreeLock()) { - int n = cont.getComponentCount(); - for(i=0; i < n; i++) { - comp = cont.getComponent(i); - MComponentPeer peer = (MComponentPeer) MToolkit.targetToPeer(comp); - if (peer != null) { - Color color = comp.getForeground(); - if (color == null || color.equals(c)) { - peer.setForeground(c); - peer.pSetForeground(c); - } - if ((comp instanceof java.awt.List) || - (comp instanceof java.awt.TextArea) || - (comp instanceof java.awt.ScrollPane)) { - peer.pSetInnerForeground(c); - } - } - } - } - pSetForeground(c); - } - - /** - * DEPRECATED: Replaced by getInsets(). - */ - public Insets insets() { - return getInsets(); - } - - /** - * Recursive method that handles the propagation of the displayChanged - * event into the entire hierarchy of peers. - * Unlike on win32, on X we don't worry about handling on-the-fly - * display settings changes, only windows being dragged across Xinerama - * screens. Thus, we only need to tell MCanvasPeers, not all - * MComponentPeers. - */ - private void recursiveDisplayChanged(Component c, int screenNum) { - if (c instanceof Container) { - Component children[] = ((Container)c).getComponents(); - for (int i = 0; i < children.length; ++i) { - recursiveDisplayChanged(children[i], screenNum); - } - } - ComponentPeer peer = c.getPeer(); - if (peer != null && peer instanceof MCanvasPeer) { - MCanvasPeer mPeer = (MCanvasPeer)peer; - mPeer.displayChanged(screenNum); - } - } - - /* - * Often up-called from a MWindowPeer instance. - * Calls displayChanged() on all child canvas' peers. - * Recurses into Container children to ensure all canvases - * get the message. - */ - public void displayChanged(int screenNum) { - // Don't do super call because MWindowPeer has already updated its GC - - Component children[] = ((Container)target).getComponents(); - - for (int i = 0; i < children.length; i++) { - recursiveDisplayChanged(children[i], screenNum); - } - } - - protected boolean shouldFocusOnClick() { - // Return false if this container has children so in that case it won't - // be focused. Return true otherwise. - return ((Container)target).getComponentCount() == 0; - } - - private native void pEnsureIndex(ComponentPeer child, int index); - private native void pRestack(); - - private int restack(Container cont, int ind) { - for (int i = 0; i < cont.getComponentCount(); i++) { - Component comp = cont.getComponent(i); - if (!comp.isLightweight()) { - if (comp.getPeer() != null) { - pEnsureIndex(comp.getPeer(), ind++); - } - } - if (comp.isLightweight() && comp instanceof Container) { - ind = restack((Container)comp, ind); - } - } - return ind; - } - - /** - * @see java.awt.peer.ContainerPeer#restack - */ - public void restack() { - Container cont = (Container)target; - restack(cont, 0); - pRestack(); - } - - /** - * @see java.awt.peer.ContainerPeer#isRestackSupported - */ - public boolean isRestackSupported() { - return true; - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MPopupMenuPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MPopupMenuPeer.java deleted file mode 100644 index cdf8f209350..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MPopupMenuPeer.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; - -public class MPopupMenuPeer extends MMenuPeer implements PopupMenuPeer { - - static { - initIDs(); - } - - /* initialize the methodIDs of methods that may be accessed from C */ - private native static void initIDs(); - - native void createMenu(MComponentPeer parent); - - void createPopupMenu() { - if (MMenuItemPeer.getParent_NoClientCode(target) instanceof Component) { - Component parent = (Component)getParent_NoClientCode(target); - MComponentPeer parentPeer = (MComponentPeer) MToolkit.targetToPeer(parent); - if (parentPeer == null) { - // because the menu isn't a component (sigh) we first have to wait - // for a failure to map the peer which should only happen for a - // lightweight container, then find the actual native parent from - // that component. - parent = MToolkit.getNativeContainer(parent); - parentPeer = (MComponentPeer) MToolkit.targetToPeer(parent); - } - createMenu(parentPeer); - nativeCreated = true; - createItems((Menu)target); - - } else { - throw new IllegalArgumentException("illegal popup menu container class"); - } - } - - void createItems(Menu target) { - int nitems = target.getItemCount(); - MMenuPeer parent = (MMenuPeer)MToolkit.targetToPeer(target); - for (int i = 0 ; i < nitems ; i++) { - MenuItem mitem = target.getItem(i); - MMenuItemPeer mipeer = (MMenuItemPeer)MToolkit.targetToPeer(mitem); - mipeer.create(parent); - if (mitem instanceof Menu) { - createItems((Menu)mitem); - } - } - } - - public MPopupMenuPeer(PopupMenu target) { - // Do NOT instantiate native widget until just before showing the - // menu, else right mouse click will cause display to lock up - // (because of passive grab in Motif) - // - this.target = target; - } - - native void pShow(Event evt, int x, int y, MComponentPeer origin); - - public void show(Event evt) { - - if (!nativeCreated) - createPopupMenu(); - - Component origin = (Component)evt.target; - MComponentPeer peer = (MComponentPeer) MToolkit.targetToPeer(origin); - int x = evt.x; - int y = evt.y; - if (peer == null) { - // A failure to map the peer should only happen for a - // lightweight component, then find the actual native parent from - // that component. The event coorinates are going to have to be - Component nativeOrigin = MToolkit.getNativeContainer(origin); - peer = (MComponentPeer) MToolkit.targetToPeer(nativeOrigin); - - // remove the event coordinates - for (Component c = origin; c != nativeOrigin; - c = MComponentPeer.getParent_NoClientCode(c)) { - Point p = c.getLocation(); - x += p.x; - y += p.y; - } - } - pShow(evt, x, y, peer); - } - - /** - * This is the callback function called on the Motif thread by - * Popup_popdownCB(Widget, XtPointer, XtPointer) in awt_PopupMenu.c. - */ - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - private void destroyNativeWidgetAfterGettingTreeLock() { - - MToolkit.executeOnEventHandlerThread(target, new Runnable() { - public void run() { - - Object treeLock = new Button().getTreeLock(); - synchronized (treeLock) { - destroyNativeWidget(); - } - } - }); - } - - native void pDispose(); -} // class MPopupMenuPeer diff --git a/jdk/src/solaris/classes/sun/awt/motif/MRobotPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MRobotPeer.java deleted file mode 100644 index 08c38a942b8..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MRobotPeer.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.security.*; -import sun.awt.X11GraphicsConfig; - -class MRobotPeer implements RobotPeer { - private X11GraphicsConfig xgc = null; - /* - * native implementation uses some static shared data (pipes, processes) - * so use a class lock to synchronize native method calls - */ - static Object robotLock = new Object(); - - MRobotPeer(GraphicsConfiguration gc) { - this.xgc = (X11GraphicsConfig)gc; - setup(); - } - - public void dispose() { - // does nothing - } - - public void mouseMove(int x, int y) { - mouseMoveImpl(xgc, x, y); - } - - public void mousePress(int buttons) { - mousePressImpl(buttons); - } - - public void mouseRelease(int buttons) { - mouseReleaseImpl(buttons); - } - - public void mouseWheel(int wheelAmt) { - mouseWheelImpl(wheelAmt); - } - - public void keyPress(int keycode) { - keyPressImpl(keycode); - } - - public void keyRelease(int keycode) { - keyReleaseImpl(keycode); - } - - public int getRGBPixel(int x, int y) { - int pixelArray[] = new int[1]; - getRGBPixelsImpl(xgc, x, y, 1, 1, pixelArray); - return pixelArray[0]; - } - - public int [] getRGBPixels(Rectangle bounds) { - int pixelArray[] = new int[bounds.width*bounds.height]; - getRGBPixelsImpl(xgc, bounds.x, bounds.y, bounds.width, bounds.height, pixelArray); - return pixelArray; - } - - private static native synchronized void setup(); - - private static native synchronized void mouseMoveImpl(X11GraphicsConfig xgc, int x, int y); - private static native synchronized void mousePressImpl(int buttons); - private static native synchronized void mouseReleaseImpl(int buttons); - private static native synchronized void mouseWheelImpl(int wheelAmt); - - private static native synchronized void keyPressImpl(int keycode); - private static native synchronized void keyReleaseImpl(int keycode); - - private static native synchronized void getRGBPixelsImpl(X11GraphicsConfig xgc, int x, int y, int width, int height, int pixelArray[]); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MScrollPanePeer.java b/jdk/src/solaris/classes/sun/awt/motif/MScrollPanePeer.java deleted file mode 100644 index 2b310efdebc..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MScrollPanePeer.java +++ /dev/null @@ -1,411 +0,0 @@ -/* - * Copyright 1996-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.*; -import java.awt.event.AdjustmentEvent; -import java.awt.peer.ScrollPanePeer; - -import java.util.logging.*; - -import sun.awt.PeerEvent; - -class MScrollPanePeer extends MPanelPeer implements ScrollPanePeer { - - private static final Logger log = Logger.getLogger("sun.awt.motif.MScrollPanePeer"); - - final static int UNIT_INCREMENT = 0; - final static int BLOCK_INCREMENT = 1; - - boolean ignore; - - native void create(MComponentPeer parent); - - static { - initIDs(); - } - - /** - * Initialize JNI field and method IDs - */ - private static native void initIDs(); - - MScrollPanePeer(Component target) { - init(target); - scrollPaneInit(); - } - - MScrollPanePeer(Component target, Object arg) { - init(target, arg); - scrollPaneInit(); - } - - void scrollPaneInit() { - ignore = false; - ScrollPane sp = (ScrollPane)target; - Adjustable vadj, hadj; - if ((vadj = sp.getVAdjustable()) != null) { - pSetIncrement(Adjustable.VERTICAL, UNIT_INCREMENT, vadj.getUnitIncrement()); - } - if ((hadj = sp.getHAdjustable()) != null) { - pSetIncrement(Adjustable.HORIZONTAL, UNIT_INCREMENT, hadj.getUnitIncrement()); - } - super.pSetScrollbarBackground(sp.getBackground()); - } - - public void setScrollChild(MComponentPeer child) { - pSetScrollChild(child); - } - - public void setBackground(Color c) { - super.setBackground(c); - pSetScrollbarBackground(c); - } - - public void setForeground(Color c) { - super.setForeground(c); - pSetInnerForeground(c); - } - - native void pSetScrollChild(MComponentPeer child); - native void pSetIncrement(int orient, int type, int incr); - native int pGetScrollbarSpace(int orient); - native int pGetBlockIncrement(int orient); - native Insets pInsets(int w, int h, int childw, int childh); - native int pGetShadow(); - - public int getHScrollbarHeight() { - ScrollPane sp = (ScrollPane)target; - if (sp.getScrollbarDisplayPolicy() == ScrollPane.SCROLLBARS_NEVER) { - return 0; - } else { - return pGetScrollbarSpace(Adjustable.HORIZONTAL); - } - } - - public int getVScrollbarWidth() { - ScrollPane sp = (ScrollPane)target; - if (sp.getScrollbarDisplayPolicy() == ScrollPane.SCROLLBARS_NEVER) { - return 0; - } else { - return pGetScrollbarSpace(Adjustable.VERTICAL); - } - } - - public Insets insets() { - ScrollPane sp = (ScrollPane)target; - Dimension d = sp.size(); - Dimension cd; - Component c = getScrollChild(); - if (c != null) { - cd = c.size(); - } else { - cd = new Dimension(0, 0); - } - return pInsets(d.width, d.height, cd.width, cd.height); - } - - public void setUnitIncrement(Adjustable adj, int u) { - ScrollPane sp = (ScrollPane)target; - if (sp.getScrollbarDisplayPolicy() != ScrollPane.SCROLLBARS_NEVER) { - pSetIncrement(adj.getOrientation(), UNIT_INCREMENT, u); - } - } - - public void setValue(Adjustable adj, int v) { - if (! ignore) { - Point p; - Component c = getScrollChild(); - if (c == null) { - return; - } - p = c.getLocation(); - switch(adj.getOrientation()) { - case Adjustable.VERTICAL: - setScrollPosition(-(p.x), v); - break; - case Adjustable.HORIZONTAL: - setScrollPosition(v, -(p.y)); - break; - } - } - } - - public native void setScrollPosition(int x, int y); - - public void childResized(int w, int h) { - // REMIND AIM: May need to revisit this... - if (((ScrollPane)target).getScrollbarDisplayPolicy() != ScrollPane.SCROLLBARS_NEVER) { - ScrollPane sp = (ScrollPane)target; - Adjustable vAdj = sp.getVAdjustable(); - Adjustable hAdj = sp.getHAdjustable(); - pSetIncrement(Scrollbar.VERTICAL, UNIT_INCREMENT, vAdj.getUnitIncrement()); - pSetIncrement(Scrollbar.HORIZONTAL, UNIT_INCREMENT, hAdj.getUnitIncrement()); - pSetIncrement(Scrollbar.VERTICAL, BLOCK_INCREMENT, vAdj.getBlockIncrement()); - pSetIncrement(Scrollbar.HORIZONTAL, BLOCK_INCREMENT, hAdj.getBlockIncrement()); - } - - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - private void postScrollEvent(int orient, int type, - int pos, boolean isAdjusting) - { - Runnable adjustor = new Adjustor(orient, type, pos, isAdjusting); - MToolkit.executeOnEventHandlerThread(new ScrollEvent(target, adjustor)); - } - - /** - * This is used to change the adjustable on dispatch thread to - * represent a change made in the native scrollbar. Since the - * change was reflected immediately at the native level, - * notification from the adjustable is temporarily ignored. - */ - class ScrollEvent extends PeerEvent { - ScrollEvent(Object source, Runnable runnable) { - super(source, runnable, 0L); - } - - public PeerEvent coalesceEvents(PeerEvent newEvent) { - if (log.isLoggable(Level.FINEST)) { - log.log(Level.FINEST, "ScrollEvent coalesced " + newEvent); - } - if (newEvent instanceof ScrollEvent) { - return newEvent; - } - return null; - } - } - - native void setTypedValue(ScrollPaneAdjustable adjustable, int value, int type); - - /** - * Runnable for the ScrollEvent that performs the adjustment. - */ - class Adjustor implements Runnable { - int orient; // selects scrollbar - int type; // adjustment type - int pos; // new position (only used for absolute) - boolean isAdjusting; // isAdjusting status - - Adjustor(int orient, int type, int pos, boolean isAdjusting) { - this.orient = orient; - this.type = type; - this.pos = pos; - this.isAdjusting = isAdjusting; - } - - public void run() { - ScrollPane sp = (ScrollPane)MScrollPanePeer.this.target; - ScrollPaneAdjustable adj = null; - - // ScrollPaneAdjustable made public in 1.4, but - // get[HV]Adjustable can't be declared to return - // ScrollPaneAdjustable because it would break backward - // compatibility -- hence the cast - - if (orient == Adjustable.VERTICAL) { - adj = (ScrollPaneAdjustable)sp.getVAdjustable(); - } else if (orient == Adjustable.HORIZONTAL) { - adj = (ScrollPaneAdjustable)sp.getHAdjustable(); - } else { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Assertion failed: unknown orient"); - } - } - - if (adj == null) { - return; - } - - int newpos = adj.getValue(); - switch (type) { - case AdjustmentEvent.UNIT_DECREMENT: - newpos -= adj.getUnitIncrement(); - break; - case AdjustmentEvent.UNIT_INCREMENT: - newpos += adj.getUnitIncrement(); - break; - case AdjustmentEvent.BLOCK_DECREMENT: - newpos -= adj.getBlockIncrement(); - break; - case AdjustmentEvent.BLOCK_INCREMENT: - newpos += adj.getBlockIncrement(); - break; - case AdjustmentEvent.TRACK: - newpos = this.pos; - break; - default: - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Assertion failed: unknown type"); - } - return; - } - - // keep scroll position in acceptable range - newpos = Math.max(adj.getMinimum(), newpos); - newpos = Math.min(adj.getMaximum(), newpos); - - // set value; this will synchronously fire an AdjustmentEvent - try { - MScrollPanePeer.this.ignore = true; - adj.setValueIsAdjusting(isAdjusting); - - // Fix for 4075484 - consider type information when creating AdjustmentEvent - // We can't just call adj.setValue() because it creates AdjustmentEvent with type=TRACK - // Instead, we call private method setTypedValue of ScrollPaneAdjustable. - // Because ScrollPaneAdjustable is in another package we should call it through native code. - setTypedValue(adj, newpos, type); - } finally { - MScrollPanePeer.this.ignore = false; - } - } - } // class Adjustor - - - private Component getScrollChild() { - ScrollPane sp = (ScrollPane)target; - Component child = null; - try { - child = sp.getComponent(0); - } catch (ArrayIndexOutOfBoundsException e) { - // do nothing. in this case we return null - } - return child; - } - - final static int MARGIN = 1; - final static int SCROLLBAR = 16; - int hsbSpace; - int vsbSpace; - int vval; - int hval; - int vmax; - int hmax; - /* - * Print the native component by rendering the Motif look ourselves. - * ToDo(aim): needs to query native motif for more accurate size and - * color information. - */ - public void print(Graphics g) { - ScrollPane sp = (ScrollPane)target; - Dimension d = sp.size(); - Color bg = sp.getBackground(); - Color fg = sp.getForeground(); - Point p = sp.getScrollPosition(); - Component c = getScrollChild(); - Dimension cd; - if (c != null) { - cd = c.size(); - } else { - cd = new Dimension(0, 0); - } - int sbDisplay = sp.getScrollbarDisplayPolicy(); - int vvis, hvis, vmin, hmin, vmax, hmax, vval, hval; - - switch (sbDisplay) { - case ScrollPane.SCROLLBARS_NEVER: - hsbSpace = vsbSpace = 0; - break; - case ScrollPane.SCROLLBARS_ALWAYS: - hsbSpace = vsbSpace = SCROLLBAR; - break; - case ScrollPane.SCROLLBARS_AS_NEEDED: - hsbSpace = (cd.width <= (d.width - 2*MARGIN)? 0 : SCROLLBAR); - vsbSpace = (cd.height <= (d.height - 2*MARGIN)? 0 : SCROLLBAR); - - if (hsbSpace == 0 && vsbSpace != 0) { - hsbSpace = (cd.width <= (d.width - SCROLLBAR - 2*MARGIN)? 0 : SCROLLBAR); - } - if (vsbSpace == 0 && hsbSpace != 0) { - vsbSpace = (cd.height <= (d.height - SCROLLBAR - 2*MARGIN)? 0 : SCROLLBAR); - } - } - - vvis = hvis = vmin = hmin = vmax = hmax = vval = hval = 0; - - if (vsbSpace > 0) { - vmin = 0; - vvis = d.height - (2*MARGIN) - hsbSpace; - vmax = Math.max(cd.height - vvis, 0); - vval = p.y; - } - if (hsbSpace > 0) { - hmin = 0; - hvis = d.width - (2*MARGIN) - vsbSpace; - hmax = Math.max(cd.width - hvis, 0); - hval = p.x; - } - - // need to be careful to add the margins back in here because - // we're drawing the margin border, after all! - int w = d.width - vsbSpace; - int h = d.height - hsbSpace; - - g.setColor(bg); - g.fillRect(0, 0, d.width, d.height); - - if (hsbSpace > 0) { - int sbw = d.width - vsbSpace; - g.fillRect(1, d.height - SCROLLBAR - 3, sbw - 1, SCROLLBAR - 3); - Graphics ng = g.create(); - try { - ng.translate(0, d.height - (SCROLLBAR - 2)); - drawScrollbar(ng, bg, SCROLLBAR - 2, sbw, - hmin, hmax, hval, hvis, true); - } finally { - ng.dispose(); - } - } - if (vsbSpace > 0) { - int sbh = d.height - hsbSpace; - g.fillRect(d.width - SCROLLBAR - 3, 1, SCROLLBAR - 3, sbh - 1); - Graphics ng = g.create(); - try { - ng.translate(d.width - (SCROLLBAR - 2), 0); - drawScrollbar(ng, bg, SCROLLBAR - 2, sbh, - vmin, vmax, vval, vvis, false); - } finally { - ng.dispose(); - } - } - - draw3DRect(g, bg, 0, 0, w - 1, h - 1, false); - - target.print(g); - sp.printComponents(g); - } - - /** - * @see ContainerPeer#restack - */ - public void restack() { - // Since ScrollPane can only have one child its restacking does nothing. - // Also, it is dangerous, since SP child is actually not a child of SP widget - // but the child of SP content widget. - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MScrollbarPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MScrollbarPeer.java deleted file mode 100644 index 6aaddfcca62..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MScrollbarPeer.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright 1995-2002 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.AdjustmentEvent; - -class MScrollbarPeer extends MComponentPeer implements ScrollbarPeer { - static { - initIDs(); - } - - private boolean inUpCall = false; - - native void create(MComponentPeer parent); - - MScrollbarPeer(Scrollbar target) { - super(target); - } - - // Initialize JNI field and method IDs - private static native void initIDs(); - - public native void pSetValues(int value, int visible, int minimum, int maximum); - public native void setLineIncrement(int l); - public native void setPageIncrement(int l); - - /** - * Returns default size of Motif scrollbar on the platform - * Currently uses hardcoded values - */ - int getDefaultDimension() { - if (System.getProperty("os.name").equals("Linux")) { - return 15; - } else { - return 19; - } - } - - public Dimension getMinimumSize() { - if (((Scrollbar)target).getOrientation() == Scrollbar.VERTICAL) { - return new Dimension(getDefaultDimension(), 50); - } else { - return new Dimension(50, getDefaultDimension()); - } - } - - // NOTE: Callback methods are called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - - private void postAdjustmentEvent(final int type, final int value, - final boolean isAdjusting) - { - final Scrollbar sb = (Scrollbar)target; - MToolkit.executeOnEventHandlerThread(sb, new Runnable() { - public void run() { - inUpCall = true; - sb.setValueIsAdjusting(isAdjusting); - sb.setValue(value); - postEvent(new AdjustmentEvent(sb, - AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED, - type, value, isAdjusting)); - inUpCall = false; - } - }); - } - - void lineUp(int value) { - postAdjustmentEvent(AdjustmentEvent.UNIT_DECREMENT, value, false); - } - - void lineDown(int value) { - postAdjustmentEvent(AdjustmentEvent.UNIT_INCREMENT, value, false); - } - - void pageUp(int value) { - postAdjustmentEvent(AdjustmentEvent.BLOCK_DECREMENT, value, false); - } - - void pageDown(int value) { - postAdjustmentEvent(AdjustmentEvent.BLOCK_INCREMENT, value, false); - } - - // SB_TOP/BOTTOM are mapped to tracking - void warp(int value) { - postAdjustmentEvent(AdjustmentEvent.TRACK, value, false); - } - - private boolean dragInProgress = false; - - void drag(final int value) { - if (!dragInProgress) { - dragInProgress = true; - } - postAdjustmentEvent(AdjustmentEvent.TRACK, value, true); - } - - void dragEnd(final int value) { - final Scrollbar sb = (Scrollbar)target; - - if (!dragInProgress) { - return; - } - - dragInProgress = false; - MToolkit.executeOnEventHandlerThread(sb, new Runnable() { - public void run() { - // NB: notification only, no sb.setValue() - // last TRACK event will have done it already - inUpCall = true; - sb.setValueIsAdjusting(false); - postEvent(new AdjustmentEvent(sb, - AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED, - AdjustmentEvent.TRACK, value, false)); - inUpCall = false; - } - }); - } - - /** - * Set the value of the slider in the ScrollBar. - */ - public void setValues(int value, int visible, int minimum, int maximum) { - // Fix for BugTraq ID 4048060. Prevent unnecessary redrawing - // of the slider, when the slider is already in the correct - // position. Since the ScrollBar widget now receives the - // ButtonRelease X event before the Java Adjustor event is - // handled, the slider is already in the correct position and - // does not need to be set again and redrawn, when processing - // the Adjustor event. - if (!inUpCall) { - pSetValues(value, visible, minimum, maximum); - } - } - - public void print(Graphics g) { - Scrollbar sb = (Scrollbar)target; - Dimension d = sb.size(); - Color bg = sb.getBackground(); - - boolean horiz = (sb.getOrientation() == Scrollbar.HORIZONTAL); - - drawScrollbar(g, bg, horiz? d.height : d.width, - horiz? d.width : d.height, - sb.getMinimum(), sb.getMaximum(), - sb.getValue(), sb.getVisible(), - horiz); - - target.print(g); - } - - - /** - * DEPRECATED - */ - public Dimension minimumSize() { - return getMinimumSize(); - } - - protected boolean shouldFocusOnClick() { - // Changed in 1.4 - scroll bars are made focusable by mouse clicks. - return true; - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MTextAreaPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MTextAreaPeer.java deleted file mode 100644 index dde7e752753..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MTextAreaPeer.java +++ /dev/null @@ -1,555 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.TextEvent; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.datatransfer.*; -import java.io.BufferedReader; -import java.io.StringReader; -import java.io.IOException; -import java.util.Vector; -import java.awt.im.InputMethodRequests; - - -public class MTextAreaPeer extends MComponentPeer implements TextAreaPeer { - native void pCreate(MComponentPeer parent); - - private boolean firstChangeSkipped; - - /** - * Initialize JNI field and method IDs - */ - private static native void initIDs(); - - static { - initIDs(); - } - - void create(MComponentPeer parent) { - firstChangeSkipped = false; - pCreate(parent); - } - - void initialize() { - int start, end; - - TextArea txt = (TextArea)target; - String text; - - if ((text = txt.getText()) != null) { - setText(text); - } - - start = txt.getSelectionStart(); - end = txt.getSelectionEnd(); - - if (end > start) { - select(start, end); - } else { - setCaretPosition(start); - } - - super.pSetScrollbarBackground(getParent_NoClientCode(target).getBackground()); - - if (!target.isBackgroundSet()) { - // This is a way to set the background color of the TextArea - // without calling setBackground - go through native C code - setTargetBackground(SystemColor.text); - } - if (!target.isForegroundSet()) { - target.setForeground(SystemColor.textText); - } - - setEditable(txt.isEditable()); - -// oldSelectionStart = -1; // accessibility support -// oldSelectionEnd = -1; // accessibility support - - super.initialize(); - } - - public MTextAreaPeer(TextArea target) { - super(target); - } - - public void setEditable(boolean editable) { - pSetEditable(editable); - - /* 4136955 - Calling setBackground() here works around an Xt - * bug by forcing Xt to flush an internal widget cache - */ - setBackground(target.getBackground()); - } - public void setBackground(Color c) { - setTextBackground(c); - } - public void setForeground(Color c) { - pSetInnerForeground(c); - } - - native int getExtraWidth(); - native int getExtraHeight(); - public native void setTextBackground(Color c); - public native void pSetEditable(boolean e); - public native void select(int selStart, int selEnd); - public native int getSelectionStart(); - public native int getSelectionEnd(); - public native void setText(String txt); - public native String getText(); - public native void insert(String txt, int pos); - public native void replaceRange(String txt, int start, int end); - public native void setFont(Font f); - public native void setCaretPosition(int pos); - public native int getCaretPosition(); - public native void pSetCursor(Cursor c); - native void pShow2(); - native void pMakeCursorVisible(); - - - public Dimension getMinimumSize() { - return getMinimumSize(10, 60); - } - public Dimension getPreferredSize(int rows, int cols) { - return getMinimumSize(rows, cols); - } - public Dimension getMinimumSize(int rows, int cols) { - FontMetrics fm = getFontMetrics(target.getFont()); - - /* Calculate proper size for text area plus scrollbars. - * - Motif allows NO leading in its text areas ... - * - extra width and height counts everything outside the - * usable text space. - * (bug 4103248, 4120310): - * - Motif uses maxAscent + maxDescent, not ascent + descent. - */ - int colWidth = fm.charWidth('0'); - int rowHeight = fm.getMaxAscent() + fm.getMaxDescent(); - return new Dimension(cols * colWidth + getExtraWidth(), - rows * rowHeight + getExtraHeight()); - } - public boolean isFocusable() { - return true; - } - - // Called from native widget when paste key is pressed and we - // already own the selection (prevents Motif from hanging while - // waiting for the selection) - // - public void pasteFromClipboard() { - Clipboard clipboard = target.getToolkit().getSystemClipboard(); - - Transferable content = clipboard.getContents(this); - if (content != null) { - try { - String data = (String)(content.getTransferData(DataFlavor.stringFlavor)); - // fix for 4401853: to clear TextArea selection if null is pasted - data = (data == null ? "" : data); - replaceRange(data, getSelectionStart(), getSelectionEnd()); - - } catch (Exception e) { - } - } - } - - /* - * Print the native component by rendering the Motif look ourselves. - * ToDo(aim): needs to query native motif for more accurate size and - * color information, the top/left text offsets, and selected text. - */ - static final int MARGIN = 2; - static final int BORDER = 1; - static final int SCROLLBAR = 16; - int fontHeight; - int fontAscent; - int fontLeading; - int topLine = 0; - int numLines = 0; - int textLength = 0; - Vector lines; - int selStart = 0; - int selEnd = 0; - int movedRight = 0; - - // the following vars are assigned in print() method - transient boolean hscrollbar; - transient boolean vscrollbar; - - public void print(Graphics g) { - TextArea area = (TextArea)target; - Dimension d = area.size(); - Color bg = area.getBackground(); - Color fg = area.getForeground(); - FontMetrics fm = getFontMetrics(area.getFont()); - int vmin, vmax, vval, vvis; - int hmin, hmax, hval, hvis; - int max = 0; - - /* - Doesn't work right yet. - selStart = area.getSelectionStart(); - selEnd = area.getSelectionEnd(); - */ - - // Figure out number of lines and max line length - String text = area.getText(); - textLength = text.length(); - BufferedReader is = new BufferedReader(new StringReader(text)); - String line; - int pos = 0; - lines = new Vector(); - int sv = ((TextArea)target).getScrollbarVisibility(); - vscrollbar = (sv == TextArea.SCROLLBARS_BOTH || - sv == TextArea.SCROLLBARS_VERTICAL_ONLY); - hscrollbar = (sv == TextArea.SCROLLBARS_BOTH || - sv == TextArea.SCROLLBARS_HORIZONTAL_ONLY); - boolean wrap = !hscrollbar; - int w = d.width - (vscrollbar ? SCROLLBAR : 0); - int h = d.height - (hscrollbar ? SCROLLBAR : 0); - - try { - numLines = 0; - while((line = is.readLine()) != null) { - int len = fm.stringWidth(line); - if (len > w && wrap) { - // need to do line wrapping - int start = 0; - int end = 0; - int string_length = line.length(); - while (true) { - int line_width = 0; - end = start + 1; // at least one character per line - while (end < string_length) { - char c = line.charAt(end); - int cw = fm.charWidth(c); - if (line_width + cw + 10 > w) // +10? - break; - line_width += cw; - end++; - } - // form a line from start to end (not including end) - String substr = line.substring(start, end); - // System.out.println("wrap line: " + substr); - TextLine tline = new TextLine(); - tline.text = substr; - tline.pos = pos + start; - lines.addElement(tline); - start = end; - max = Math.max(max, len); - numLines ++; - if (end == string_length) { - // we have processed the whole string - pos += line.length() + 1; // +1 for the ending \n ? - break; - } - } - } else { - TextLine tline = new TextLine(); - tline.text = line; - tline.pos = pos; - lines.addElement(tline); - pos += line.length() + 1; - - max = Math.max(max, len); - numLines++; - } - } - is.close(); - - } catch (IOException e) { - } - - - fontHeight = fm.getHeight(); - fontAscent = fm.getAscent(); - fontLeading = fm.getLeading(); - - hmin = vmin = 0; - - vvis = linesInWindow(true); - vmax = Math.max(numLines - vvis, 0); - vval = 0; - - hvis = w - (2 * MARGIN); - hmax = Math.max(max - hvis, 0); - hval = 0; - - g.setColor(bg); - g.fillRect(BORDER, BORDER, w, h); - if (vscrollbar) - { - int sbh = d.height - (hscrollbar ? SCROLLBAR : 0); - g.fillRect(d.width - SCROLLBAR - 3, 1, SCROLLBAR - 3, sbh - 1); - Graphics ng = g.create(); - try { - ng.translate(d.width - (SCROLLBAR - 2), 0); - drawScrollbar(ng, bg, SCROLLBAR - 2, sbh, - vmin, vmax, vval, vvis, false); - } finally { - ng.dispose(); - } - } - if (hscrollbar) - { - int sbw = d.width - (vscrollbar ? SCROLLBAR : 0); - g.fillRect(1, d.height - SCROLLBAR - 3, sbw - 1, SCROLLBAR - 3); - Graphics ng = g.create(); - try { - ng.translate(0, d.height - (SCROLLBAR - 2)); - drawScrollbar(ng, bg, SCROLLBAR - 2, sbw, - hmin, hmax, hval, hvis, true); - } finally { - ng.dispose(); - } - } - - draw3DRect(g, bg, 0, 0, w - 1, h - 1, false); - - if (text != null) { - int l = linesInWindow(true); - h = d.height - ((2 * MARGIN) + SCROLLBAR); - int e = Math.min(numLines - 1, (topLine + l) - 1); - paintLines(g, bg, fg, topLine, e); - } - - - target.print(g); - } - - int linesInWindow(boolean horizScrollbar) { - Dimension d = target.size(); - int htotal = d.height - ((2 * MARGIN) + (horizScrollbar? SCROLLBAR : 0)); - return htotal / fontHeight; - } - - void paintLines(Graphics g, Color bg, Color fg, int s, int e) { - Dimension d = target.size(); - int w = d.width - ((2 * BORDER) + (vscrollbar ? SCROLLBAR : 0)); - int h = d.height - ((2 * BORDER) + (hscrollbar ? SCROLLBAR : 0)); - int lm = linesInWindow(true) + topLine; - s = Math.max(topLine, s); - e = Math.min(e, lm - 1); - Graphics ng = g.create(); - try { - ng.clipRect(BORDER + MARGIN, MARGIN + BORDER, w - (2*MARGIN), - h - (2*MARGIN)); - ng.setFont(target.getFont()); - for (int i = s ; i <= e; i++) { - paintLine(ng, bg, fg, i); - } - } finally { - ng.dispose(); - } - } - - void paintLine(Graphics g, Color bg, Color fg, int lnr) { - Dimension d = target.size(); - int l = linesInWindow(true); - - if((lnr < topLine) || (lnr >= l + topLine)) { - return; - } - int w = d.width - ((2 * BORDER) + (hscrollbar ? SCROLLBAR : 0)); - int y = MARGIN + fontLeading + ((lnr - topLine) * fontHeight); - String text = ((TextLine)lines.elementAt(lnr)).text; - int len = text.length(); - - if (lnr > numLines - 1) { - g.setColor(bg); - g.fillRect(BORDER, y - fontLeading, w, fontHeight); - return; - } - int s = 0; - int e = (lnr < numLines - 1) ? len : textLength; - int xs = pos2x(selStart) - movedRight; - int xe = pos2x(selEnd) - movedRight; - - Color highlight = bg.brighter(); - if ((selStart < s) && (selEnd > e)) { - g.setColor(highlight); - g.fillRect(BORDER, y - fontLeading, w, fontHeight); - } else { - g.setColor(bg); - g.fillRect(BORDER, y - fontLeading, w, fontHeight); - - if ((selStart >= s) && (selStart <= e)) { - g.setColor(highlight); - - if (selEnd > e) { - g.fillRect(xs, y - fontLeading, (w + BORDER) - xs, fontHeight); - } else if (selStart == selEnd) { - //g.fillRect(xs, y - fontLeading, 1, fontHeight); - } else { - g.fillRect(xs, y - fontLeading, xe - xs, fontHeight); - } - } else if ((selEnd >= s) && (selEnd <= e)) { - g.setColor(highlight); - g.fillRect(BORDER, y - fontLeading, xe - BORDER, fontHeight); - } - } - g.setColor(fg); - g.drawString(text, MARGIN - movedRight, y + fontAscent); - } - - int pos2x(int pos) { - FontMetrics fm = getFontMetrics(target.getFont()); - int widths[] = fm.getWidths(); - TextLine tl1 = (TextLine)lines.elementAt(0); - TextLine tl2; - int l = 0; - for (int i = 0; i < lines.size() - 1; i++) { - tl2 = (TextLine)lines.elementAt(i+1); - if (pos >= tl1.pos && pos < tl2.pos) { - l = i; - break; - } - tl1 = tl2; - } - int x = MARGIN; - for (int i = 0 ; i < (pos - tl1.pos - 1) ; i++) { - x += widths[tl1.text.charAt(i)]; - } - return x; - } - - /** - * DEPRECATED - */ - public void insertText(String txt, int pos) { - insert(txt, pos); - } - - /** - * DEPRECATED - */ - public void replaceText(String txt, int start, int end) { - replaceRange(txt, start, end); - } - - /** - * DEPRECATED - */ - public Dimension minimumSize() { - return getMinimumSize(); - } - - /** - * DEPRECATED - */ - public Dimension preferredSize(int rows, int cols) { - return getPreferredSize(rows, cols); - } - - /** - * DEPRECATED - */ - public Dimension minimumSize(int rows, int cols) { - return getMinimumSize(rows, cols); - } - - /* - * Post a new TextEvent when the value of a text component changes. - */ - public void valueChanged() { - postEvent(new TextEvent(target, TextEvent.TEXT_VALUE_CHANGED)); - } - - void pShow(){ - pShow2(); - notifyTextComponentChange(true); - } - - void pHide(){ - notifyTextComponentChange(false); - super.pHide(); - } - - void pDispose(){ - notifyTextComponentChange(false); - super.pDispose(); - } - - public boolean handlesWheelScrolling() {return true;} - - public void handleEvent(AWTEvent e) { - if (e.getID() == MouseEvent.MOUSE_WHEEL) { - MouseWheelEvent mwe = (MouseWheelEvent)e; - nativeHandleMouseWheel(mwe.getScrollType(), - mwe.getScrollAmount(), - mwe.getWheelRotation()); - } - else { - super.handleEvent(e); - } - } - - public InputMethodRequests getInputMethodRequests() { - return null; - } - - - - native void nativeHandleMouseWheel(int scrollType, - int scrollAmount, - int wheelRotation); - - // - // Accessibility support - // - - - // stub functions: to be fully implemented in a future release - public int getIndexAtPoint(int x, int y) { return -1; } - public Rectangle getCharacterBounds(int i) { return null; } - public long filterEvents(long mask) { return 0; } - -/* To be fully implemented in a future release - - int oldSelectionStart; - int oldSelectionEnd; - - public native int getIndexAtPoint(int x, int y); - public native Rectangle getCharacterBounds(int i); - public native long filterEvents(long mask); - - /** - * Handle a change in the text selection endpoints - * (Note: could be simply a change in the caret location) - * - public void selectionValuesChanged(int start, int end) { - return; // Need to write implementation of this. - } -*/ -} - - -class TextLine { - String text; - int pos; -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MTextFieldPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MTextFieldPeer.java deleted file mode 100644 index f11f5597c7c..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MTextFieldPeer.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.*; -import java.awt.peer.*; -import java.awt.datatransfer.*; -import java.awt.event.ActionEvent; -import java.awt.event.TextEvent; -import java.awt.im.InputMethodRequests; - - -public class MTextFieldPeer extends MComponentPeer implements TextFieldPeer { - native void pCreate(MComponentPeer parent); - - private boolean firstChangeSkipped; - - /** - * Initialize JNI field and method IDs - */ - private static native void initIDs(); - - static { - initIDs(); - } - - void create(MComponentPeer parent) { - firstChangeSkipped = false; - pCreate(parent); - } - - void initialize() { - int start, end; - - TextField txt = (TextField)target; - - setText(txt.getText()); - if (txt.echoCharIsSet()) { - setEchoChar(txt.getEchoChar()); - } - - start = txt.getSelectionStart(); - end = txt.getSelectionEnd(); - - if (end > start) { - select(start, end); - } else { - setCaretPosition(start); - } - - if (!target.isBackgroundSet()) { - // This is a way to set the background color of the TextArea - // without calling setBackground - go through native C code - setTargetBackground(SystemColor.text); - } - if (!target.isForegroundSet()) { - target.setForeground(SystemColor.textText); - } - - setEditable(txt.isEditable()); - -// oldSelectionStart = -1; // accessibility support -// oldSelectionEnd = -1; // accessibility support - - super.initialize(); - } - - public MTextFieldPeer(TextField target) { - super(target); - } - - public void setEditable(boolean editable) { - pSetEditable(editable); - - /* 4136955 - Calling setBackground() here works around an Xt - * bug by forcing Xt to flush an internal widget cache - */ - setBackground(target.getBackground()); - } - - public native void pSetEditable(boolean editable); - public native void select(int selStart, int selEnd); - public native int getSelectionStart(); - public native int getSelectionEnd(); - public native void setText(String l); - public native void insertReplaceText(String l); - public native void preDispose(); - public native String getText(); - public native void setEchoChar(char c); - public native void setFont(Font f); - public native void setCaretPosition(int pos); - public native int getCaretPosition(); - - // CDE/Motif defaults: margin=5, shadow=2, highlight=1 -- times 2. - // Should have asked the widgets for correct values (see MTextAreaPeer). - private static final int padding = 16; - - public Dimension getMinimumSize() { - FontMetrics fm = getFontMetrics(target.getFont()); - return new Dimension(fm.stringWidth(((TextField)target).getText())+20, - fm.getMaxDescent() + fm.getMaxAscent() + padding); - } - - public Dimension getPreferredSize(int cols) { - return getMinimumSize(cols); - } - - public Dimension getMinimumSize(int cols) { - FontMetrics fm = getFontMetrics(target.getFont()); - return new Dimension(fm.charWidth('0') * cols + 20, - fm.getMaxDescent() + fm.getMaxAscent() + padding); - } - - public boolean isFocusable() { - return true; - } - - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void action(final long when, final int modifiers) { - MToolkit.executeOnEventHandlerThread(target, new Runnable() { - public void run() { - postEvent(new ActionEvent(target, ActionEvent.ACTION_PERFORMED, - ((TextField)target).getText(), when, - modifiers)); - } - }); - } - - protected void disposeImpl() { - preDispose(); - super.disposeImpl(); - } - - /* - * Post a new TextEvent when the value of a text component changes. - */ - public void valueChanged() { - postEvent(new TextEvent(target, TextEvent.TEXT_VALUE_CHANGED)); - } - - // Called from native widget when paste key is pressed and we - // already own the selection (prevents Motif from hanging while - // waiting for the selection) - // - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void pasteFromClipboard() { - Clipboard clipboard = target.getToolkit().getSystemClipboard(); - - Transferable content = clipboard.getContents(this); - if (content != null) { - try { - String data = (String)(content.getTransferData(DataFlavor.stringFlavor)); - insertReplaceText(data); - - } catch (Exception e) { - } - } - } - - /* - * Print the native component by rendering the Motif look ourselves. - * ToDo(aim): needs to query native motif for more accurate size and - * color information, left text offset, and selected text. - */ - public final static int BORDER = 2; - public final static int MARGIN = 4; - - public void print(Graphics g) { - TextField txt = (TextField)target; - Dimension d = txt.size(); - int w = d.width - (2 * BORDER); - int h = d.height - (2 * BORDER); - Color bg = txt.getBackground(); - Color fg = txt.getForeground(); - Color highlight = bg.brighter(); - String text = txt.getText(); - int moved = 0; - int selStart = 0; - int selEnd = 0; - - g.setFont(txt.getFont()); - g.setColor(txt.isEditable() ? highlight : bg); - g.fillRect(BORDER, BORDER, w, h); - - g.setColor(bg); - //g.drawRect(0, 0, d.width-1, d.height-1); - draw3DRect(g, bg, 1, 1, d.width-3, d.height-3, false); - - if (text != null) { - g.clipRect(BORDER, MARGIN, w, d.height - (2 * MARGIN)); - FontMetrics fm = g.getFontMetrics(); - - w = d.width - BORDER; - h = d.height - (2 * MARGIN); - int xs = pos2x(selStart) - moved; - int xe = pos2x(selEnd) - moved; - - if ((xs < MARGIN) && (xe > w)) { - g.setColor(highlight); - g.fillRect(BORDER, MARGIN, w - BORDER, h); - } else { - g.setColor(bg); - //g.fillRect(BORDER, MARGIN, w - BORDER, h); - - if ((xs >= MARGIN) && (xs <= w)) { - g.setColor(highlight); // selected text - - if (xe > w) { - g.fillRect(xs, MARGIN, w - xs, h); - } else if (xs == xe) { - //g.fillRect(xs, MARGIN, 1, h); - } else { - g.fillRect(xs, MARGIN, xe - xs, h); - } - } else if ((xe >= MARGIN) && (xe <= w)) { - g.setColor(highlight); - g.fillRect(BORDER, MARGIN, xe - BORDER, h); - } - } - g.setColor(fg); - int x = MARGIN - moved; - char echoChar = txt.getEchoChar(); - if (echoChar == 0) { - g.drawString(text, x, BORDER + MARGIN + fm.getMaxAscent()); - } else { - char data[] = new char[text.length()]; - for (int i = 0 ; i < data.length ; i++) { - data[i] = echoChar; - } - g.drawChars(data, 0, data.length, x, - BORDER + MARGIN + fm.getMaxAscent()); - - } - } - - target.print(g); - } - - int pos2x(int pos) { - TextField txt = (TextField)target; - FontMetrics fm = getFontMetrics(txt.getFont()); - int x = MARGIN, widths[] = fm.getWidths(); - String text = txt.getText(); - char echoChar = txt.getEchoChar(); - if (echoChar == 0) { - for (int i = 0 ; i < pos ; i++) { - x += widths[text.charAt(i)]; - } - } else { - x += widths[echoChar] * pos; - } - return x; - } - - /** - * DEPRECATED - */ - public void setEchoCharacter(char c) { - setEchoChar(c); - } - - /** - * DEPRECATED - */ - public Dimension minimumSize() { - return getMinimumSize(); - } - - /** - * DEPRECATED - */ - public Dimension minimumSize(int cols) { - return getMinimumSize(cols); - } - - /** - * DEPRECATED - */ - public Dimension preferredSize(int cols) { - return getPreferredSize(cols); - } - void pShow(){ - super.pShow(); - notifyTextComponentChange(true); - } - - void pHide(){ - notifyTextComponentChange(false); - super.pHide(); - } - - void pDispose(){ - notifyTextComponentChange(false); - super.pDispose(); - } - - public InputMethodRequests getInputMethodRequests() { - return null; - } - - - - // - // Accessibility support - // - - // stub functions: to be fully implemented in a future release - public int getIndexAtPoint(int x, int y) { return -1; } - public Rectangle getCharacterBounds(int i) { return null; } - public long filterEvents(long mask) { return 0; } - - -/* To be fully implemented in a future release - - int oldSelectionStart; - int oldSelectionEnd; - - public native int getIndexAtPoint(int x, int y); - public native Rectangle getCharacterBounds(int i); - public native long filterEvents(long mask); - - /** - * Handle a change in the text selection endpoints - * (Note: could be simply a change in the caret location) - * - public void selectionValuesChanged(int start, int end) { - return; // Need to write implemetation of this. - } -*/ - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/MToolkit.java b/jdk/src/solaris/classes/sun/awt/motif/MToolkit.java index 3a71353c1f7..717990da2f7 100644 --- a/jdk/src/solaris/classes/sun/awt/motif/MToolkit.java +++ b/jdk/src/solaris/classes/sun/awt/motif/MToolkit.java @@ -60,12 +60,12 @@ import java.awt.dnd.MouseDragGestureRecognizer; import java.awt.dnd.InvalidDnDOperationException; import java.awt.dnd.peer.DragSourceContextPeer; -import sun.awt.motif.MInputMethod; +//import sun.awt.motif.MInputMethod; import sun.awt.X11GraphicsConfig; import sun.awt.X11GraphicsEnvironment; import sun.awt.XSettings; -import sun.awt.motif.MDragSourceContextPeer; +//import sun.awt.motif.MDragSourceContextPeer; import sun.print.PrintJob2D; @@ -79,9 +79,9 @@ public class MToolkit extends UNIXToolkit implements Runnable { private static final Logger log = Logger.getLogger("sun.awt.motif.MToolkit"); // the system clipboard - CLIPBOARD selection - X11Clipboard clipboard; + //X11Clipboard clipboard; // the system selection - PRIMARY selection - X11Clipboard selection; + //X11Clipboard selection; // Dynamic Layout Resize client code setting protected static boolean dynamicLayoutSetting = false; @@ -130,7 +130,7 @@ public class MToolkit extends UNIXToolkit implements Runnable { new GetBooleanAction("awt.dnd.motifdnd"))).booleanValue(); } - public static final String DATA_TRANSFERER_CLASS_NAME = "sun.awt.motif.MDataTransferer"; + //public static final String DATA_TRANSFERER_CLASS_NAME = "sun.awt.motif.MDataTransferer"; public MToolkit() { super(); @@ -150,7 +150,7 @@ public class MToolkit extends UNIXToolkit implements Runnable { } init(mainClassName); - SunToolkit.setDataTransfererClassName(DATA_TRANSFERER_CLASS_NAME); + //SunToolkit.setDataTransfererClassName(DATA_TRANSFERER_CLASS_NAME); Thread toolkitThread = new Thread(this, "AWT-Motif"); toolkitThread.setPriority(Thread.NORM_PRIORITY + 1); @@ -197,131 +197,152 @@ public class MToolkit extends UNIXToolkit implements Runnable { */ public ButtonPeer createButton(Button target) { - ButtonPeer peer = new MButtonPeer(target); - targetCreatedPeer(target, peer); - return peer; + //ButtonPeer peer = new MButtonPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public TextFieldPeer createTextField(TextField target) { - TextFieldPeer peer = new MTextFieldPeer(target); - targetCreatedPeer(target, peer); - return peer; + //TextFieldPeer peer = new MTextFieldPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public LabelPeer createLabel(Label target) { - LabelPeer peer = new MLabelPeer(target); - targetCreatedPeer(target, peer); - return peer; + //LabelPeer peer = new MLabelPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public ListPeer createList(List target) { - ListPeer peer = new MListPeer(target); - targetCreatedPeer(target, peer); - return peer; + //ListPeer peer = new MListPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public CheckboxPeer createCheckbox(Checkbox target) { - CheckboxPeer peer = new MCheckboxPeer(target); - targetCreatedPeer(target, peer); - return peer; + //CheckboxPeer peer = new MCheckboxPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public ScrollbarPeer createScrollbar(Scrollbar target) { - ScrollbarPeer peer = new MScrollbarPeer(target); - targetCreatedPeer(target, peer); - return peer; + //ScrollbarPeer peer = new MScrollbarPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public ScrollPanePeer createScrollPane(ScrollPane target) { - ScrollPanePeer peer = new MScrollPanePeer(target); - targetCreatedPeer(target, peer); - return peer; + //ScrollPanePeer peer = new MScrollPanePeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public TextAreaPeer createTextArea(TextArea target) { - TextAreaPeer peer = new MTextAreaPeer(target); - targetCreatedPeer(target, peer); - return peer; + //TextAreaPeer peer = new MTextAreaPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public ChoicePeer createChoice(Choice target) { - ChoicePeer peer = new MChoicePeer(target); - targetCreatedPeer(target, peer); - return peer; + //ChoicePeer peer = new MChoicePeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public FramePeer createFrame(Frame target) { - FramePeer peer = new MFramePeer(target); - targetCreatedPeer(target, peer); - return peer; + //FramePeer peer = new MFramePeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public CanvasPeer createCanvas(Canvas target) { - CanvasPeer peer = (isXEmbedServerRequested() ? new MEmbedCanvasPeer(target) : new MCanvasPeer(target)); - targetCreatedPeer(target, peer); - return peer; + //CanvasPeer peer = (isXEmbedServerRequested() ? new MEmbedCanvasPeer(target) : new MCanvasPeer(target)); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public PanelPeer createPanel(Panel target) { - PanelPeer peer = new MPanelPeer(target); - targetCreatedPeer(target, peer); - return peer; + //PanelPeer peer = new MPanelPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public WindowPeer createWindow(Window target) { - WindowPeer peer = new MWindowPeer(target); - targetCreatedPeer(target, peer); - return peer; + //WindowPeer peer = new MWindowPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public DialogPeer createDialog(Dialog target) { - DialogPeer peer = new MDialogPeer(target); - targetCreatedPeer(target, peer); - return peer; + //DialogPeer peer = new MDialogPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public FileDialogPeer createFileDialog(FileDialog target) { - FileDialogPeer peer = new MFileDialogPeer(target); - targetCreatedPeer(target, peer); - return peer; + //FileDialogPeer peer = new MFileDialogPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public MenuBarPeer createMenuBar(MenuBar target) { - MenuBarPeer peer = new MMenuBarPeer(target); - targetCreatedPeer(target, peer); - return peer; + //MenuBarPeer peer = new MMenuBarPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public MenuPeer createMenu(Menu target) { - MenuPeer peer = new MMenuPeer(target); - targetCreatedPeer(target, peer); - return peer; + //MenuPeer peer = new MMenuPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public PopupMenuPeer createPopupMenu(PopupMenu target) { - PopupMenuPeer peer = new MPopupMenuPeer(target); - targetCreatedPeer(target, peer); - return peer; + //PopupMenuPeer peer = new MPopupMenuPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public MenuItemPeer createMenuItem(MenuItem target) { - MenuItemPeer peer = new MMenuItemPeer(target); - targetCreatedPeer(target, peer); - return peer; + //MenuItemPeer peer = new MMenuItemPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } public CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target) { - CheckboxMenuItemPeer peer = new MCheckboxMenuItemPeer(target); - targetCreatedPeer(target, peer); - return peer; + //CheckboxMenuItemPeer peer = new MCheckboxMenuItemPeer(target); + //targetCreatedPeer(target, peer); + //return peer; + return null; } - public MEmbeddedFramePeer createEmbeddedFrame(MEmbeddedFrame target) - { - MEmbeddedFramePeer peer = new MEmbeddedFramePeer(target); - targetCreatedPeer(target, peer); - return peer; - } + //public MEmbeddedFramePeer createEmbeddedFrame(MEmbeddedFrame target) + //{ + //MEmbeddedFramePeer peer = new MEmbeddedFramePeer(target); + //targetCreatedPeer(target, peer); + //return peer; + // return null; + //} public FontPeer getFontPeer(String name, int style){ @@ -438,29 +459,31 @@ public class MToolkit extends UNIXToolkit implements Runnable { public native void beep(); public Clipboard getSystemClipboard() { - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkSystemClipboardAccess(); - } - synchronized (this) { - if (clipboard == null) { - clipboard = new X11Clipboard("System", "CLIPBOARD"); - } - } - return clipboard; + //SecurityManager security = System.getSecurityManager(); + //if (security != null) { + // security.checkSystemClipboardAccess(); + //} + //synchronized (this) { + // if (clipboard == null) { + // clipboard = new X11Clipboard("System", "CLIPBOARD"); + // } + //} + //return clipboard; + return null; } public Clipboard getSystemSelection() { - SecurityManager security = System.getSecurityManager(); - if (security != null) { - security.checkSystemClipboardAccess(); - } - synchronized (this) { - if (selection == null) { - selection = new X11Clipboard("Selection", "PRIMARY"); - } - } - return selection; + //SecurityManager security = System.getSecurityManager(); + //if (security != null) { + // security.checkSystemClipboardAccess(); + //} + //synchronized (this) { + // if (selection == null) { + // selection = new X11Clipboard("Selection", "PRIMARY"); + // } + //} + //return selection; + return null; } public boolean getLockingKeyState(int key) { @@ -492,11 +515,12 @@ public class MToolkit extends UNIXToolkit implements Runnable { } public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException { - if (MToolkit.useMotifDnD()) { - return MDragSourceContextPeer.createDragSourceContextPeer(dge); - } else { - return X11DragSourceContextPeer.createDragSourceContextPeer(dge); - } + //if (MToolkit.useMotifDnD()) { + // return MDragSourceContextPeer.createDragSourceContextPeer(dge); + //} else { + // return X11DragSourceContextPeer.createDragSourceContextPeer(dge); + //} + return null; } public T @@ -504,9 +528,9 @@ public class MToolkit extends UNIXToolkit implements Runnable { DragSource ds, Component c, int srcActions, DragGestureListener dgl) { - if (MouseDragGestureRecognizer.class.equals(abstractRecognizerClass)) - return (T)new MMouseDragGestureRecognizer(ds, c, srcActions, dgl); - else + //if (MouseDragGestureRecognizer.class.equals(abstractRecognizerClass)) + // return (T)new MMouseDragGestureRecognizer(ds, c, srcActions, dgl); + //else return null; } @@ -514,14 +538,14 @@ public class MToolkit extends UNIXToolkit implements Runnable { * Returns a new input method adapter descriptor for native input methods. */ public InputMethodDescriptor getInputMethodAdapterDescriptor() throws AWTException { - return new MInputMethodDescriptor(); + return null; // return new MInputMethodDescriptor(); } /** * Returns a style map for the input method highlight. */ public Map mapInputMethodHighlight(InputMethodHighlight highlight) { - return MInputMethod.mapInputMethodHighlight(highlight); + return null; //return MInputMethod.mapInputMethodHighlight(highlight); } /** @@ -529,15 +553,15 @@ public class MToolkit extends UNIXToolkit implements Runnable { */ public Cursor createCustomCursor(Image cursor, Point hotSpot, String name) throws IndexOutOfBoundsException { - return new MCustomCursor(cursor, hotSpot, name); + return null; //return new MCustomCursor(cursor, hotSpot, name); } /** * Returns the supported cursor size */ public Dimension getBestCursorSize(int preferredWidth, int preferredHeight) { - return MCustomCursor.getBestCursorSize( - java.lang.Math.max(1,preferredWidth), java.lang.Math.max(1,preferredHeight)); + return null; //MCustomCursor.getBestCursorSize( + //java.lang.Math.max(1,preferredWidth), java.lang.Math.max(1,preferredHeight)); } public int getMaximumCursorColors() { @@ -621,7 +645,8 @@ public class MToolkit extends UNIXToolkit implements Runnable { public RobotPeer createRobot(Robot target, GraphicsDevice screen) { /* 'target' is unused for now... */ - return new MRobotPeer(screen.getDefaultConfiguration()); + //return new MRobotPeer(screen.getDefaultConfiguration()); + return null; } static boolean useMotifDnD() { diff --git a/jdk/src/solaris/classes/sun/awt/motif/MWindowPeer.java b/jdk/src/solaris/classes/sun/awt/motif/MWindowPeer.java deleted file mode 100644 index 15c5c80de3b..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/MWindowPeer.java +++ /dev/null @@ -1,602 +0,0 @@ -/* - * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package sun.awt.motif; - -import java.util.Vector; -import java.awt.*; -import java.awt.peer.*; -import java.awt.event.*; -import java.awt.image.BufferedImage; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferByte; -import java.awt.image.DataBufferInt; -import java.awt.image.ImageObserver; -import sun.awt.image.ImageRepresentation; -import sun.awt.motif.MInputMethod; -import sun.awt.motif.MInputMethodControl; -import sun.awt.im.*; -import sun.awt.DisplayChangedListener; -import sun.awt.SunToolkit; -import sun.awt.X11GraphicsDevice; - -class MWindowPeer extends MPanelPeer implements WindowPeer, -DisplayChangedListener { - - Insets insets = new Insets( 0, 0, 0, 0 ); - MWindowAttributes winAttr; - static Vector allWindows = new Vector(); - int iconWidth = -1; - int iconHeight = -1; - - int dropTargetCount = 0; - boolean alwaysOnTop; - - native void pCreate(MComponentPeer parent, String targetClassName, boolean isFocusableWindow); - native void pShow(); - native void pToFront(); - native void pShowModal(boolean isModal); - native void pHide(); - native void pReshape(int x, int y, int width, int height); - native void pDispose(); - native void pSetTitle(String title); - public native void setState(int state); - public native int getState(); - - public native void setResizable(boolean resizable); - native void addTextComponentNative(MComponentPeer tc); - native void removeTextComponentNative(); - native void pSetIMMOption(String option); - native void pSetMenuBar(MMenuBarPeer mbpeer); - native void setSaveUnder(boolean state); - - native void registerX11DropTarget(Component target); - native void unregisterX11DropTarget(Component target); - native void updateAlwaysOnTop(boolean isAlwaysOnTop); - - private static native void initIDs(); - - static { - initIDs(); - } - - // this function is privileged! do not change it to public! - private static int getInset(final String name, final int def) { - Integer tmp = (Integer) java.security.AccessController.doPrivileged( - new sun.security.action.GetIntegerAction(name, def)); - return tmp.intValue(); - } - - MWindowPeer() { - insets = new Insets(0,0,0,0); - winAttr = new MWindowAttributes(); - } - - MWindowPeer(Window target) { - - this(); - init(target); - - allWindows.addElement(this); - } - - void create(MComponentPeer parent) { - pCreate(parent, target.getClass().getName(), ((Window)target).isFocusableWindow()); - } - - void init( Window target ) { - if ( winAttr.nativeDecor == true ) { - insets.top = getInset("awt.frame.topInset", -1); - insets.left = getInset("awt.frame.leftInset", -1); - insets.bottom = getInset("awt.frame.bottomInset", -1); - insets.right = getInset("awt.frame.rightInset", -1); - } - - Rectangle bounds = target.getBounds(); - sysX = bounds.x; - sysY = bounds.y; - sysW = bounds.width; - sysH = bounds.height; - - super.init(target); - InputMethodManager imm = InputMethodManager.getInstance(); - String menuString = imm.getTriggerMenuString(); - if (menuString != null) - { - pSetIMMOption(menuString); - } - pSetTitle(winAttr.title); - - /* - * For Windows and undecorated Frames and Dialogs this just - * disables/enables resizing functions in the system menu. - */ - setResizable(winAttr.isResizable); - - setSaveUnder(true); - - Font f = target.getFont(); - if (f == null) { - f = defaultFont; - target.setFont(f); - setFont(f); - } - Color c = target.getBackground(); - if (c == null) { - target.setBackground(SystemColor.window); - setBackground(SystemColor.window); - } - c = target.getForeground(); - if (c == null) { - target.setForeground(SystemColor.windowText); - setForeground(SystemColor.windowText); - } - alwaysOnTop = ((Window)target).isAlwaysOnTop() && ((Window)target).isAlwaysOnTopSupported(); - - GraphicsConfiguration gc = getGraphicsConfiguration(); - ((X11GraphicsDevice)gc.getDevice()).addDisplayChangedListener(this); - - } - - /* Support for multiple icons is not implemented in MAWT */ - public void updateIconImages() { - if (this instanceof MFramePeer) { - ((MFramePeer)this).setIconImage(((Frame)target).getIconImage()); - } - } - - - /* Not implemented in MAWT */ - public void updateMinimumSize() { - } - - protected void disposeImpl() { - allWindows.removeElement(this); - super.disposeImpl(); - } - - public native void toBack(); - - public void setAlwaysOnTop(boolean alwaysOnTop) { - this.alwaysOnTop = alwaysOnTop; - updateAlwaysOnTop(alwaysOnTop); - } - - public void toFront() { - if (target.isVisible()) { - updateFocusableWindowState(); - pToFront(); - } - } - - public void updateFocusableWindowState() { - setFocusableWindow(((Window)target).isFocusableWindow()); - } - native void setFocusableWindow(boolean value); - - public void setVisible( boolean b ) { - if (b) { - updateFocusableWindowState(); - } - super.setVisible(b); - updateAlwaysOnTop(alwaysOnTop); - } - - public Insets getInsets() { - return insets; - } - - public void handleQuit() { - postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_CLOSING)); - } - - // XXX: nasty WM, foul play. spank WM author. - public void handleDestroy() { - final Window target = (Window)this.target; - SunToolkit.executeOnEventHandlerThread(target, - new Runnable() { - public void run() { - // This seems like the only reasonable thing we - // could do in this situation as the native window - // is already dead. - target.dispose(); - } - }); - } - - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleIconify() { - postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_ICONIFIED)); - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleDeiconify() { - postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_DEICONIFIED)); - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleStateChange(int oldState, int newState) { - postEvent(new WindowEvent((Window)target, - WindowEvent.WINDOW_STATE_CHANGED, - oldState, newState)); - } - - /** - * Called to inform the Window that its size has changed and it - * should layout its children. - */ - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleResize(int width, int height) { - sysW = width; - sysH = height; - - // REMIND: Is this secure? Can client code subclass input method? - if (!tcList.isEmpty() && - !imList.isEmpty()){ - int i; - for (i = 0; i < imList.size(); i++){ - ((MInputMethod)imList.elementAt(i)).configureStatus(); - } - } - validateSurface(width, height); - postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED)); - } - - - /** - * DEPRECATED: Replaced by getInsets(). - */ - public Insets insets() { - return getInsets(); - } - - public void handleMoved(int x, int y) { - sysX = x; - sysY = y; - postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_MOVED)); - } - - private native AWTEvent wrapInSequenced(AWTEvent event); - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleWindowFocusIn() { - WindowEvent we = new WindowEvent((Window)target, WindowEvent.WINDOW_GAINED_FOCUS); - /* wrap in Sequenced, then post*/ - postEvent(wrapInSequenced((AWTEvent) we)); - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void handleWindowFocusOut(Window oppositeWindow) { - WindowEvent we = new WindowEvent((Window)target, WindowEvent.WINDOW_LOST_FOCUS, - oppositeWindow); - /* wrap in Sequenced, then post*/ - postEvent(wrapInSequenced((AWTEvent) we)); - } - - -// relocation of Imm stuff - private Vector imList = new Vector(); - private Vector tcList = new Vector(); - - // NOTE: This method is called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - void notifyIMMOptionChange(){ - - // REMIND: IS THIS SECURE??? CAN USER CODE SUBCLASS INPUTMETHODMGR??? - InputMethodManager.getInstance().notifyChangeRequest(target); - } - - public void addInputMethod(MInputMethod im) { - if (!imList.contains(im)) - imList.addElement(im); - } - - public void removeInputMethod(MInputMethod im) { - if (imList.contains(im)) - imList.removeElement(im); - } - - public void addTextComponent(MComponentPeer tc) { - if (tcList.contains(tc)) - return; - if (tcList.isEmpty()){ - addTextComponentNative(tc); - if (!imList.isEmpty()) { - for (int i = 0; i < imList.size(); i++) { - ((MInputMethod)imList.elementAt(i)).reconfigureXIC((MInputMethodControl)this); - } - } - MToolkit.executeOnEventHandlerThread(target, new Runnable() { - public void run() { - synchronized(target.getTreeLock()) { - target.doLayout(); - } - } - }); - } - tcList.addElement(tc); - - } - - public void removeTextComponent(MComponentPeer tc) { - if (!tcList.contains(tc)) - return; - tcList.removeElement(tc); - if (tcList.isEmpty()){ - removeTextComponentNative(); - if (!imList.isEmpty()) { - for (int i = 0; i < imList.size(); i++) { - ((MInputMethod)imList.elementAt(i)).reconfigureXIC((MInputMethodControl)this); - } - } - target.doLayout(); - } - } - - public MComponentPeer getTextComponent() { - if (!tcList.isEmpty()) { - return (MComponentPeer)tcList.firstElement(); - } else { - return null; - } - } - - boolean hasDecorations(int decor) { - if (!winAttr.nativeDecor) { - return false; - } - else { - int myDecor = winAttr.decorations; - boolean hasBits = ((myDecor & decor) == decor); - if ((myDecor & MWindowAttributes.AWT_DECOR_ALL) != 0) - return !hasBits; - else - return hasBits; - } - } - - /* Returns the native paint should be posted after setting new size - */ - public boolean checkNativePaintOnSetBounds(int width, int height) { - // Fix for 4418155. Window does not repaint - // automticaly if shrinking. Should not wait for Expose - return (width > oldWidth) || (height > oldHeight); - } - -/* --- DisplayChangedListener Stuff --- */ - - native void resetTargetGC(Component target); - - /* Xinerama - * called to update our GC when dragged onto another screen - */ - public void draggedToNewScreen(int screenNum) { - final int finalScreenNum = screenNum; - - SunToolkit.executeOnEventHandlerThread((Component)target, new Runnable() - { - public void run() { - displayChanged(finalScreenNum); - } - }); - } - - /* Xinerama - * called to update our GC when dragged onto another screen - */ - public void displayChanged(int screenNum) { - // update our GC - resetLocalGC(screenNum); /* upcall to MCanvasPeer */ - resetTargetGC(target); /* call Window.resetGC() via native */ - - //propagate to children - super.displayChanged(screenNum); /* upcall to MPanelPeer */ - } - - /** - * Helper method that executes the displayChanged(screen) method on - * the event dispatch thread. This method is used in the Xinerama case - * and after display mode change events. - */ - private void executeDisplayChangedOnEDT(int screenNum) { - final int finalScreenNum = screenNum; - Runnable dc = new Runnable() { - public void run() { - displayChanged(finalScreenNum); - } - }; - SunToolkit.executeOnEventHandlerThread((Component)target, dc); - } - - /** - * From the DisplayChangedListener interface; called from - * X11GraphicsDevice when the display mode has been changed. - */ - public void displayChanged() { - GraphicsConfiguration gc = getGraphicsConfiguration(); - int curScreenNum = ((X11GraphicsDevice)gc.getDevice()).getScreen(); - executeDisplayChangedOnEDT(curScreenNum); - } - - /** - * From the DisplayChangedListener interface; top-levels do not need - * to react to this event. - */ - public void paletteChanged() { - } - - public synchronized void addDropTarget() { - if (dropTargetCount == 0) { - registerX11DropTarget(target); - } - dropTargetCount++; - } - - public synchronized void removeDropTarget() { - dropTargetCount--; - if (dropTargetCount == 0) { - unregisterX11DropTarget(target); - } - } - - protected synchronized void updateDropTarget() { - if (dropTargetCount > 0) { - unregisterX11DropTarget(target); - registerX11DropTarget(target); - } - } - - public boolean requestWindowFocus() { - return false; - } - - public void setModalBlocked(Dialog blocker, boolean blocked) { - // do nothing - } - - public void postUngrabEvent() { - postEvent(new sun.awt.UngrabEvent((Window)target)); - } - - boolean isOwnerOf(MComponentPeer child) { - if (child == null) return false; - - Component comp = child.target; - while (comp != null && !(comp instanceof Window)) { - comp = getParent_NoClientCode(comp); - } - if (!(comp instanceof Window)) { - return false; - } - - while (comp != null && !(comp == target) && !(comp instanceof Dialog)) { - comp = getParent_NoClientCode(comp); - } - return (comp == target); - } - - boolean processUngrabMouseEvent(MComponentPeer compPeer, int x_root, int y_root, int type) { - switch (type) { - case 4: // ButtonPress - // Check that the target is the child of the grabbed - // window or the child of one of the owned windows of - // the grabbed window - if (!isOwnerOf(compPeer)) { - postUngrabEvent(); - return true; - } - } - return false; - } - - private final boolean hasWarningWindow() { - return ((Window)target).getWarningString() != null; - } - - // This method is overriden at Dialog and Frame peers. - boolean isTargetUndecorated() { - return true; - } - - private volatile int sysX = 0; - private volatile int sysY = 0; - private volatile int sysW = 0; - private volatile int sysH = 0; - - Rectangle constrainBounds(int x, int y, int width, int height) { - // We don't restrict the setBounds() operation if the code is trusted. - if (!hasWarningWindow()) { - return new Rectangle(x, y, width, height); - } - - int newX = x; - int newY = y; - int newW = width; - int newH = height; - - GraphicsConfiguration gc = ((Window)target).getGraphicsConfiguration(); - Rectangle sB = gc.getBounds(); - Insets sIn = ((Window)target).getToolkit().getScreenInsets(gc); - - int screenW = sB.width - sIn.left - sIn.right; - int screenH = sB.height - sIn.top - sIn.bottom; - - // If it's undecorated or is not currently visible, - // then check each point is within the visible part of the screen - if (!target.isVisible() || isTargetUndecorated()) { - int screenX = sB.x + sIn.left; - int screenY = sB.y + sIn.top; - - // First make sure the size is withing the visible part of the screen - if (newW > screenW) { - newW = screenW; - } - - if (newH > screenH) { - newH = screenH; - } - - // Tweak the location if needed - if (newX < screenX) { - newX = screenX; - } else if (newX + newW > screenX + screenW) { - newX = screenX + screenW - newW; - } - - if (newY < screenY) { - newY = screenY; - } else if (newY + newH > screenY + screenH) { - newY = screenY + screenH - newH; - } - } else { - int maxW = Math.max(screenW, sysW); - int maxH = Math.max(screenH, sysH); - - // Make sure the size is withing the visible part of the screen - // OR is less that the current size of the window. - if (newW > maxW) { - newW = maxW; - } - - if (newH > maxH) { - newH = maxH; - } - } - - return new Rectangle(newX, newY, newW, newH); - } - - public void setBounds(int x, int y, int width, int height, int op) { - Rectangle newBounds = constrainBounds(x, y, width, height); - super.setBounds(newBounds.x, newBounds.y, newBounds.width, newBounds.height, op); - } - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/X11Clipboard.java b/jdk/src/solaris/classes/sun/awt/motif/X11Clipboard.java deleted file mode 100644 index db9794de8a4..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/X11Clipboard.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright 1996-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.datatransfer.ClipboardOwner; -import java.awt.datatransfer.Transferable; - -import java.io.IOException; - -import java.security.AccessController; - -import sun.awt.datatransfer.SunClipboard; -import sun.awt.datatransfer.TransferableProxy; -import sun.awt.datatransfer.DataTransferer; - -import sun.security.action.GetIntegerAction; - - -/** - * A class which interfaces with the X11 selection service in order to support - * data transfer via Clipboard operations. Most of the work is provided by - * sun.awt.datatransfer.DataTransferer. - * - * @author Amy Fowler - * @author Roger Brinkley - * @author Danila Sinopalnikov - * @author Alexander Gerasimov - * - * @since JDK1.1 - */ -public class X11Clipboard extends SunClipboard implements X11SelectionHolder { - - private final X11Selection clipboardSelection; - - private static final Object classLock = new Object(); - - private static final int defaultPollInterval = 200; - - private static int pollInterval; - - private static int listenedClipboardsCount; - - /** - * Creates a system clipboard object. - */ - public X11Clipboard(String name, String selectionName) { - super(name); - clipboardSelection = new X11Selection(selectionName, this); - } - - protected void setContentsNative(Transferable contents) { - if (!clipboardSelection.getSelectionOwnership(contents, this)) { - // Need to figure out how to inform owner the request failed... - this.owner = null; - this.contents = null; - } - } - - public long getID() { - return clipboardSelection.atom; - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void lostSelectionOwnership() { - lostOwnershipImpl(); - } - - protected void clearNativeContext() { - clipboardSelection.clearNativeContext(); - } - - protected long[] getClipboardFormats() { - return getClipboardFormats(getID()); - } - private static native long[] getClipboardFormats(long clipboardID); - - protected byte[] getClipboardData(long format) - throws IOException { - return getClipboardData(getID(), format); - } - private static native byte[] getClipboardData(long clipboardID, long format) - throws IOException; - - - // Called on the toolkit thread under awtLock. - public void checkChange(long[] formats) { - if (!clipboardSelection.isOwner()) { - super.checkChange(formats); - } - } - - void checkChangeHere(Transferable contents) { - if (areFlavorListenersRegistered()) { - super.checkChange(DataTransferer.getInstance(). - getFormatsForTransferableAsArray(contents, flavorMap)); - } - } - - protected void registerClipboardViewerChecked() { - if (pollInterval <= 0) { - pollInterval = ((Integer)AccessController.doPrivileged( - new GetIntegerAction("awt.datatransfer.clipboard.poll.interval", - defaultPollInterval))).intValue(); - if (pollInterval <= 0) { - pollInterval = defaultPollInterval; - } - } - synchronized (X11Clipboard.classLock) { - if (listenedClipboardsCount++ == 0) { - registerClipboardViewer(pollInterval); - } - } - } - - private native void registerClipboardViewer(int pollInterval); - - protected void unregisterClipboardViewerChecked() { - synchronized (X11Clipboard.classLock) { - if (--listenedClipboardsCount == 0) { - unregisterClipboardViewer(); - } - } - } - - private native void unregisterClipboardViewer(); - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/X11DragSourceContextPeer.java b/jdk/src/solaris/classes/sun/awt/motif/X11DragSourceContextPeer.java deleted file mode 100644 index db4078b8da8..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/X11DragSourceContextPeer.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Window; - -import java.awt.datatransfer.Transferable; - -import java.awt.dnd.DragSourceContext; -import java.awt.dnd.DragSourceDragEvent; -import java.awt.dnd.DragSourceDropEvent; -import java.awt.dnd.DragSourceEvent; -import java.awt.dnd.DragGestureEvent; -import java.awt.dnd.InvalidDnDOperationException; - -import java.awt.event.InputEvent; - -import java.util.Map; - -import sun.awt.SunToolkit; - -import sun.awt.dnd.SunDragSourceContextPeer; -import sun.awt.dnd.SunDropTargetContextPeer; - -/** - * The X11DragSourceContextPeer class is the class responsible for handling - * the interaction between the XDnD/Motif DnD subsystem and Java drag sources. - * - * @since 1.5 - */ -final class X11DragSourceContextPeer extends SunDragSourceContextPeer { - - private static final X11DragSourceContextPeer theInstance = - new X11DragSourceContextPeer(null); - - /** - * construct a new X11DragSourceContextPeer - */ - - private X11DragSourceContextPeer(DragGestureEvent dge) { - super(dge); - } - - static X11DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException { - theInstance.setTrigger(dge); - return theInstance; - } - - protected void startDrag(Transferable transferable, - long[] formats, Map formatMap) { - Component component = getTrigger().getComponent(); - Component c = null; - MWindowPeer wpeer = null; - - for (c = component; c != null && !(c instanceof java.awt.Window); - c = MComponentPeer.getParent_NoClientCode(c)); - - if (c instanceof Window) { - wpeer = (MWindowPeer)c.getPeer(); - } - - if (wpeer == null) { - throw new InvalidDnDOperationException( - "Cannot find top-level for the drag source component"); - } - - startDrag(component, - wpeer, - transferable, - getTrigger().getTriggerEvent(), - getCursor(), - getCursor() == null ? 0 : getCursor().getType(), - getDragSourceContext().getSourceActions(), - formats, - formatMap); - - /* This implementation doesn't use native context */ - setNativeContext(0); - - SunDropTargetContextPeer.setCurrentJVMLocalSourceTransferable(transferable); - } - - /** - * downcall into native code - */ - - private native long startDrag(Component component, - MWindowPeer wpeer, - Transferable transferable, - InputEvent nativeTrigger, - Cursor c, int ctype, int actions, - long[] formats, Map formatMap); - - /** - * set cursor - */ - - public void setCursor(Cursor c) throws InvalidDnDOperationException { - SunToolkit.awtLock(); - super.setCursor(c); - SunToolkit.awtUnlock(); - } - - protected native void setNativeCursor(long nativeCtxt, Cursor c, int cType); - -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/X11DropTargetContextPeer.java b/jdk/src/solaris/classes/sun/awt/motif/X11DropTargetContextPeer.java deleted file mode 100644 index 48eb9bbed83..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/X11DropTargetContextPeer.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.Component; -import java.awt.peer.ComponentPeer; - -import sun.awt.AppContext; -import sun.awt.SunToolkit; - -import sun.awt.dnd.SunDropTargetContextPeer; -import sun.awt.dnd.SunDropTargetEvent; - -/** - * The X11DropTargetContextPeer class is the class responsible for handling - * the interaction between the XDnD/Motif DnD subsystem and Java drop targets. - * - * @since 1.5 - */ -final class X11DropTargetContextPeer extends SunDropTargetContextPeer { - - /* - * A key to store a peer instance for an AppContext. - */ - private static final Object DTCP_KEY = "DropTargetContextPeer"; - - private X11DropTargetContextPeer() {} - - public static X11DropTargetContextPeer getPeer(AppContext appContext) { - synchronized (_globalLock) { - X11DropTargetContextPeer peer = - (X11DropTargetContextPeer)appContext.get(DTCP_KEY); - if (peer == null) { - peer = new X11DropTargetContextPeer(); - appContext.put(DTCP_KEY, peer); - } - - return peer; - } - } - - /* - * Note: - * the method can be called on the toolkit thread while holding AWT_LOCK. - */ - private static void postDropTargetEventToPeer(final Component component, - final int x, final int y, - final int dropAction, - final int actions, - final long[] formats, - final long nativeCtxt, - final int eventID) { - - AppContext appContext = SunToolkit.targetToAppContext(component); - X11DropTargetContextPeer peer = getPeer(appContext); - - peer.postDropTargetEvent(component, x, y, dropAction, actions, formats, - nativeCtxt, eventID, - !SunDropTargetContextPeer.DISPATCH_SYNC); - } - - protected void eventProcessed(SunDropTargetEvent e, int returnValue, - boolean dispatcherDone) { - /* If the event was not consumed, send a response to the source. */ - long ctxt = getNativeDragContext(); - if (ctxt != 0) { - sendResponse(e.getID(), returnValue, ctxt, dispatcherDone, - e.isConsumed()); - } - } - - protected void doDropDone(boolean success, int dropAction, - boolean isLocal) { - dropDone(getNativeDragContext(), success, dropAction); - } - - protected Object getNativeData(long format) { - return getData(getNativeDragContext(), format); - } - - protected void processEnterMessage(SunDropTargetEvent event) { - if (!processSunDropTargetEvent(event)) { - super.processEnterMessage(event); - } - } - - protected void processExitMessage(SunDropTargetEvent event) { - if (!processSunDropTargetEvent(event)) { - super.processExitMessage(event); - } - } - - protected void processMotionMessage(SunDropTargetEvent event, - boolean operationChanged) { - if (!processSunDropTargetEvent(event)) { - super.processMotionMessage(event, operationChanged); - } - } - - protected void processDropMessage(SunDropTargetEvent event) { - if (!processSunDropTargetEvent(event)) { - super.processDropMessage(event); - } - } - - // If source is an XEmbedCanvasPeer, passes the event to it for processing and - // return true if the event is forwarded to the XEmbed child. - // Otherwise, does nothing and return false. - private boolean processSunDropTargetEvent(SunDropTargetEvent event) { - Object source = event.getSource(); - - if (source instanceof Component) { - ComponentPeer peer = ((Component)source).getPeer(); - if (peer instanceof MEmbedCanvasPeer) { - MEmbedCanvasPeer mEmbedCanvasPeer = (MEmbedCanvasPeer)peer; - /* The native context is the pointer to the XClientMessageEvent - structure. */ - long ctxt = getNativeDragContext(); - - /* If the event is not consumed, pass it to the - MEmbedCanvasPeer for processing. */ - if (!event.isConsumed()) { - // NOTE: ctxt can be zero at this point. - if (mEmbedCanvasPeer.processXEmbedDnDEvent(ctxt, - event.getID())) { - event.consume(); - return true; - } - } - } - } - - return false; - } - - private native void sendResponse(int eventID, int returnValue, - long nativeCtxt, boolean dispatcherDone, - boolean consumed); - - private native void dropDone(long nativeCtxt, boolean success, - int dropAction); - - private native Object getData(long nativeCtxt, long format); -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/X11Selection.java b/jdk/src/solaris/classes/sun/awt/motif/X11Selection.java deleted file mode 100644 index 16120093545..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/X11Selection.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 1996-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -import java.awt.Toolkit; - -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.FlavorMap; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.SystemFlavorMap; - -import java.util.Map; -import java.util.SortedMap; -import java.util.Vector; - -import sun.awt.AppContext; -import sun.awt.SunToolkit; - -import sun.awt.datatransfer.DataTransferer; - -/* - * Implements a general interface to the X11 selection mechanism. - * - * @author Amy Fowler - * @author Roger Brinkley - * @author Danila Sinopalnikov - * @author Alexander Gerasimov - * - * @since JDK1.1 - */ -public class X11Selection { - - static FlavorMap flavorMap = SystemFlavorMap.getDefaultFlavorMap(); - - static Vector selections; - - long atom; - - private X11Clipboard clipboard; - private X11SelectionHolder holder; - private Transferable contents; - - private boolean disposed = false; - private byte[] data = null; - private boolean dataAvailable = false; - private static final Object source = new Object(); - - static { - // 4154170: Need to ensure the the toolkit is initialized prior - // to executing this initializer - Toolkit toolkit = Toolkit.getDefaultToolkit(); - - selections = new Vector(); - - initIDs(); - init(); - - } - - private static native void initIDs(); - static native void init(); - - public X11Selection(String name, X11Clipboard clipboard) { - atom = ((MDataTransferer)DataTransferer.getInstance()).getAtomForTarget(name); - selections.addElement(this); - this.clipboard = clipboard; - } - - private static Object[] getSelectionsArray() { - return selections.toArray(); - } - - /* - * methods for acting as selection provider - */ - native boolean pGetSelectionOwnership(Object source, - Transferable transferable, - long[] formats, - Map formatMap, - X11SelectionHolder holder); - - boolean getSelectionOwnership(Transferable contents, - X11SelectionHolder holder) { - SortedMap formatMap = - DataTransferer.getInstance().getFormatsForTransferable - (contents, DataTransferer.adaptFlavorMap(flavorMap)); - long[] formats = - DataTransferer.getInstance().keysToLongArray(formatMap); - SunToolkit.insertTargetMapping(source, AppContext.getAppContext()); - - /* - * Update 'contents' and 'holder' fields in the native code under - * AWTLock protection to prevent race with lostSelectionOwnership(). - */ - SunToolkit.awtLock(); - try { - boolean isOwnerSet = pGetSelectionOwnership(source, contents, formats, formatMap, - holder); - if (isOwnerSet) { - clipboard.checkChangeHere(contents); - } - return isOwnerSet; - } finally { - SunToolkit.awtUnlock(); - } - } - - // To be MT-safe this method should be called under awtLock. - boolean isOwner() { - return holder != null; - } - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - private void lostSelectionOwnership() { - if (holder != null) { - holder.lostSelectionOwnership(); - holder = null; - } - contents = null; - } - - native void clearNativeContext(); - - /* - * Subclasses should override disposeImpl() instead of dispose(). Client - * code should always invoke dispose(), never disposeImpl(). - */ - protected void disposeImpl() { - selections.removeElement(this); - } - - public final void dispose() { - boolean call_disposeImpl = false; - - if (!disposed) { - synchronized (this) { - if (!disposed) { - disposed = call_disposeImpl = true; - } - } - } - - if (call_disposeImpl) { - disposeImpl(); - } - } - - /** - * Finds out all selections that have flavor listeners registered - * and returns their atoms. - * Upcall from native code. - * - * @return an array of selection atoms - */ - private static long[] getSelectionAtomsToCheckChange() { - Object[] sels = getSelectionsArray(); - long[] idArray = new long[sels.length]; - int count = 0; - - for (int i = 0; i < sels.length; i++) { - X11Clipboard clipboard = ((X11Selection)sels[i]).clipboard; - if (clipboard.areFlavorListenersRegistered()) { - idArray[count++] = clipboard.getID(); - } - } - - long[] atomArray = new long[count]; - System.arraycopy(idArray, 0, atomArray, 0, atomArray.length); - - return atomArray; - } - - /** - * Upcall from native code. - */ - private void checkChange(long[] formats) { - clipboard.checkChange(formats); - } -} diff --git a/jdk/src/solaris/classes/sun/awt/motif/X11SelectionHolder.java b/jdk/src/solaris/classes/sun/awt/motif/X11SelectionHolder.java deleted file mode 100644 index 523efc32ae6..00000000000 --- a/jdk/src/solaris/classes/sun/awt/motif/X11SelectionHolder.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package sun.awt.motif; - -interface X11SelectionHolder { - - // NOTE: This method may be called by privileged threads. - // DO NOT INVOKE CLIENT CODE ON THIS THREAD! - public void lostSelectionOwnership(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Button.c b/jdk/src/solaris/native/sun/awt/awt_Button.c deleted file mode 100644 index a522487c0d0..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Button.c +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright 1995-2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" - -#include -#include -#include "multi_font.h" - -#include "awt_Component.h" - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -/* - * When the -jni switch is thrown, these headers can be deleted. - */ -#include "java_awt_Button.h" -#include "sun_awt_motif_MButtonPeer.h" -#include "sun_awt_motif_MComponentPeer.h" - -/* fieldIDs for Button fields that may be accessed from C */ -static struct ButtonIDs { - jfieldID label; -} buttonIDs; - -static char emptyString[] = ""; - - -/* - * Class: java_awt_Button - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for Button.java - to initialize the fieldIDs for fields that may be accessed from C */ - -JNIEXPORT void JNICALL -Java_java_awt_Button_initIDs - (JNIEnv *env, jclass cls) -{ - buttonIDs.label = - (*env)->GetFieldID(env, cls, "label", "Ljava/lang/String;"); -} - -/* - * client_data is MButtonPeer instance - */ -static void -Button_callback (Widget w, - XtPointer client_data, - XmPushButtonCallbackStruct * call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - ConvertEventTimeAndModifiers converted; - - awt_util_convertEventTimeAndModifiers(call_data->event, &converted); - - JNU_CallMethodByName(env, NULL, (jobject)client_data, "action", "(JI)V", - converted.when, converted.modifiers); - if ((*env)->ExceptionOccurred (env)) { - (*env)->ExceptionDescribe (env); - (*env)->ExceptionClear (env); - } -} - -/* - * Class: sun_awt_motif_MButtonPeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MButtonPeer_create - (JNIEnv * env, jobject this, jobject parent) -{ - jobject target; - jobject label; - struct ComponentData *cdata; - struct ComponentData *wdata; - char *clabel; - Pixel bg; - XmString mfstr = NULL; - jobject globalRef = awtJNI_CreateAndSetGlobalRef (env, this); - jobject font = awtJNI_GetFont (env, this); - jboolean IsMultiFont = awtJNI_IsMultiFont (env, font); - AwtGraphicsConfigDataPtr adata; - - AWT_LOCK (); - - if (JNU_IsNull (env, parent)) { - JNU_ThrowNullPointerException (env, "NullPointerException"); - AWT_UNLOCK (); - - return; - } - target = (*env)->GetObjectField (env, this, mComponentPeerIDs.target); - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, parent, mComponentPeerIDs.pData); - - if (JNU_IsNull (env, target) || wdata == NULL) { - JNU_ThrowNullPointerException (env, "NullPointerException"); - AWT_UNLOCK (); - - return; - } - cdata = ZALLOC (ComponentData); - if (cdata == NULL) { - JNU_ThrowOutOfMemoryError (env, "OutOfMemoryError"); - AWT_UNLOCK (); - return; - } - JNU_SetLongFieldFromPtr(env, this, mComponentPeerIDs.pData, cdata); - - adata = copyGraphicsConfigToPeer(env, this); - - XtVaGetValues (wdata->widget, XmNbackground, &bg, NULL); - - label = - (*env)->GetObjectField (env, target, buttonIDs.label); - - if (IsMultiFont) { - /* - * We don't use makeCString() function here. - * We create Motif multi-font compound string to display - * unicode on the platform which is not spporting unicode. - */ - if (JNU_IsNull (env, label) || ((*env)->GetStringLength (env, label) == 0)) { - mfstr = XmStringCreateLocalized (""); - } else { - mfstr = awtJNI_MakeMultiFontString (env, label, font); - } - - cdata->widget = XtVaCreateManagedWidget - ("", xmPushButtonWidgetClass, - wdata->widget, - XmNlabelString, mfstr, - XmNrecomputeSize, False, - XmNbackground, bg, - XmNhighlightOnEnter, False, - XmNshowAsDefault, 0, - XmNdefaultButtonShadowThickness, 0, - XmNmarginTop, 0, - XmNmarginBottom, 0, - XmNmarginLeft, 0, - XmNmarginRight, 0, - XmNuserData, (XtPointer) globalRef, - XmNscreen, ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen), - NULL); - if (mfstr != NULL) { - XmStringFree(mfstr); - mfstr = NULL; - } - - } else { - if (JNU_IsNull (env, label)) { - clabel = emptyString; - } else { - clabel = (char *) JNU_GetStringPlatformChars (env, label, NULL); - if (clabel == NULL) { /* Exception? */ - AWT_UNLOCK (); - return; - } - } - - cdata->widget = XtVaCreateManagedWidget - (clabel, xmPushButtonWidgetClass, - wdata->widget, - XmNrecomputeSize, False, - XmNbackground, bg, - XmNhighlightOnEnter, False, - XmNshowAsDefault, 0, - XmNdefaultButtonShadowThickness, 0, - XmNmarginTop, 0, - XmNmarginBottom, 0, - XmNmarginLeft, 0, - XmNmarginRight, 0, - XmNuserData, (XtPointer) globalRef, - XmNscreen, ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen), - NULL); - - if (clabel != emptyString) { - JNU_ReleaseStringPlatformChars (env, label, (const char *) clabel);; - } - } - - XtSetMappedWhenManaged (cdata->widget, False); - XtAddCallback (cdata->widget, - XmNactivateCallback, - (XtCallbackProc) Button_callback, - (XtPointer) globalRef); - - AWT_UNLOCK (); -} - -/* - * Class: sun_awt_motif_MButtonPeer - * Method: setLabel - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MButtonPeer_setLabel - (JNIEnv * env, jobject this, jstring label) -{ - struct ComponentData *wdata; - char *clabel; - XmString xim; - - AWT_LOCK (); - - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL) { - JNU_ThrowNullPointerException (env, "NullPointerException"); - AWT_UNLOCK (); - return; - } - if (JNU_IsNull (env, label) || ((*env)->GetStringLength (env, label) == 0)) { - xim = XmStringCreateLocalized (""); - } else { - jobject font = awtJNI_GetFont (env, this); - - if (awtJNI_IsMultiFont (env, font)) { - xim = awtJNI_MakeMultiFontString (env, label, font); - } else { - if (JNU_IsNull (env, label)) { - clabel = emptyString; - } else { - clabel = (char *) JNU_GetStringPlatformChars (env, label, NULL); - - if (clabel == NULL) { /* Exception? */ - AWT_UNLOCK (); - return; - } - } - - xim = XmStringCreate (clabel, "labelFont"); - - if (clabel != emptyString) { - JNU_ReleaseStringPlatformChars (env, label, (const char *) clabel);; - } - } - } - - XtVaSetValues (wdata->widget, XmNlabelString, xim, NULL); - XmStringFree (xim); - AWT_FLUSH_UNLOCK (); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Canvas.c b/jdk/src/solaris/native/sun/awt/awt_Canvas.c deleted file mode 100644 index 98cf45e1cb0..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Canvas.c +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 1995-2002 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "java_awt_Canvas.h" -#include "sun_awt_motif_MCanvasPeer.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "color.h" -#include "canvas.h" -#include "awt_util.h" - -#include "awt_Component.h" -#include "awt_GraphicsEnv.h" - -#include -#include -#include "multi_font.h" - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct X11GraphicsConfigIDs x11GraphicsConfigIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); -struct CanvasIDs mCanvasIDs; - -/* - * Class: sun_awt_motif_MCanvasPeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCanvasPeer_create - (JNIEnv * env, jobject this, jobject parent) -{ - AwtGraphicsConfigDataPtr awtData; - - struct CanvasData *wdata; - struct CanvasData *cdata; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - - AWT_LOCK(); - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - cdata = (struct CanvasData *) - JNU_GetLongFieldAsPtr(env, parent, mComponentPeerIDs.pData); - if (cdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - wdata = ZALLOC(CanvasData); - if (wdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - JNU_SetLongFieldFromPtr(env, this, mComponentPeerIDs.pData, wdata); - - awtData = copyGraphicsConfigToPeer(env, this); - - wdata->comp.widget = awt_canvas_create((XtPointer) globalRef, - cdata->comp.widget, - "", - 1, 1, False, NULL, awtData); - XtVaSetValues(wdata->comp.widget, - XmNinsertPosition, awt_util_insertCallback, - NULL); - - /* Add an event handler so that we can track focus change requests - which will be initiated by Motif in response to ButtonPress events */ - - wdata->flags = 0; - wdata->shell = cdata->shell; - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MCanvasPeer - * Method: resetTargetGC - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCanvasPeer_resetTargetGC -(JNIEnv * env, jobject this, jobject target) -{ - (*env)->CallVoidMethod(env, target, mCanvasIDs.setGCFromPeerMID); -} - -/* - * Class: sun_awt_motif_MCanvasPeer - * Method: initIDs - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCanvasPeer_initIDs -(JNIEnv * env, jclass cls) -{ - jclass canvasCls = (*env)->FindClass(env, "java/awt/Canvas"); - mCanvasIDs.setGCFromPeerMID = - (*env)->GetMethodID(env, canvasCls, "setGCFromPeer","()V"); - - DASSERT(mCanvasIDs.setGCFromPeerMID); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Checkbox.c b/jdk/src/solaris/native/sun/awt/awt_Checkbox.c deleted file mode 100644 index e620d678e42..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Checkbox.c +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright 1995-2002 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "sun_awt_motif_MCheckboxPeer.h" -#include "java_awt_Checkbox.h" -#include "java_awt_CheckboxGroup.h" - -#include "awt_Component.h" - -#include "multi_font.h" -#include -#include - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -/* fieldIDs for Checkbox fields that may be accessed from C */ -static struct CheckboxIDs { - jfieldID label; -} checkboxIDs; - -static char emptyString[] = ""; - - -/* - * Class: java_awt_Checkbox - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for Checkbox.java - to initialize the fieldIDs for fields that may be accessed from C */ - -JNIEXPORT void JNICALL -Java_java_awt_Checkbox_initIDs - (JNIEnv *env, jclass cls) -{ - checkboxIDs.label = - (*env)->GetFieldID(env, cls, "label", "Ljava/lang/String;"); -} - -/* - * client_data is MCheckboxPeer instance pointer - */ -static void -Toggle_callback(Widget w, - XtPointer client_data, - XmAnyCallbackStruct * call_data) -{ - Boolean state; - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - XtVaGetValues(w, XmNset, &state, NULL); - - JNU_CallMethodByName(env, NULL, (jobject) client_data, "action", "(Z)V", state); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -/* - * Class: sun_awt_motif_MCheckboxPeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCheckboxPeer_create - (JNIEnv * env, jobject this, jobject parent) -{ - jobject target; - struct ComponentData *bdata; - struct ComponentData *wdata; - char *clabel; -#define MAX_ARGC 10 - Arg args[MAX_ARGC]; - Cardinal argc; - jobject label; - XmString mfstr = NULL; - jobject font = awtJNI_GetFont(env, this); - jboolean isMultiFont = awtJNI_IsMultiFont(env, font); - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; - XmFontList fontlist = NULL; - Dimension height; - Boolean labelIsEmpty = FALSE; - - AWT_LOCK(); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, parent, mComponentPeerIDs.pData); - - if (JNU_IsNull(env, target) || wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - bdata = ZALLOC(ComponentData); - if (bdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - - return; - } - JNU_SetLongFieldFromPtr(env, this, mComponentPeerIDs.pData, bdata); - - adata = copyGraphicsConfigToPeer(env, this); - - argc = 0; - XtSetArg(args[argc], XmNrecomputeSize, False); - argc++; - XtSetArg(args[argc], XmNvisibleWhenOff, True); - argc++; - XtSetArg(args[argc], XmNtraversalOn, True); - argc++; - XtSetArg(args[argc], XmNspacing, 0); - argc++; - XtSetArg(args[argc], XmNuserData, (XtPointer) globalRef); - argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen)); - argc++; - - label = (*env)->GetObjectField(env, target, checkboxIDs.label); - - // fix for 4383735. - // If the label is empty we need to set the indicator size - // proportional to the size of the font. - // kdm@sparc.spb.su - if (JNU_IsNull(env, label) || ((*env)->GetStringLength(env, label) == 0)) { - labelIsEmpty = TRUE; - if (!JNU_IsNull(env, font)) { - mfstr = XmStringCreateLocalized(" "); - if (mfstr != NULL) { - fontlist = awtJNI_GetFontList(env, font); - if (fontlist != NULL) { - height = XmStringHeight(fontlist, mfstr); - XtSetArg(args[argc], XmNindicatorSize, height); - argc++; - XmFontListFree(fontlist); - fontlist = NULL; - } - XmStringFree(mfstr); - mfstr = NULL; - } - } - } - - if (isMultiFont) { - /* - * We don't use makeCString() function here. - * We create Motif multi-font compound string to display - * unicode on the platform which is not spporting unicode. - */ - if (labelIsEmpty) { - mfstr = XmStringCreateLocalized(""); - } else { - mfstr = awtJNI_MakeMultiFontString(env, label, font); - } - - XtSetArg(args[argc], XmNlabelString, mfstr); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - bdata->widget = XmCreateToggleButton(wdata->widget, "", args, argc); - - if (mfstr != NULL) { - XmStringFree(mfstr); - mfstr = NULL; - } - } else { - if (labelIsEmpty) { - clabel = emptyString; - } else { - clabel = (char *) JNU_GetStringPlatformChars(env, label, NULL); - - if (clabel == NULL) { /* Exception? */ - AWT_UNLOCK(); - return; - } - } - - DASSERT(!(argc > MAX_ARGC)); - bdata->widget = XmCreateToggleButton(wdata->widget, clabel, args, argc); - - if (clabel != emptyString) { - JNU_ReleaseStringPlatformChars(env, label, (const char *) clabel);; - } - } - - XtAddCallback(bdata->widget, - XmNvalueChangedCallback, - (XtCallbackProc) Toggle_callback, - (XtPointer) globalRef); - - XtSetMappedWhenManaged(bdata->widget, False); - XtManageChild(bdata->widget); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MCheckboxPeer - * Method: setLabel - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCheckboxPeer_setLabel - (JNIEnv * env, jobject this, jstring label) -{ - struct ComponentData *wdata; - char *clabel; - XmString xim; - jobject font; - - AWT_LOCK(); - - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (JNU_IsNull(env, label) || ((*env)->GetStringLength(env, label) == 0)) { - xim = XmStringCreateLocalized(""); - } else { - font = awtJNI_GetFont(env, this); - - if (awtJNI_IsMultiFont(env, font)) { - xim = awtJNI_MakeMultiFontString(env, label, font); - } else { - clabel = (char *) JNU_GetStringPlatformChars(env, label, NULL); - - if (clabel == NULL) { - AWT_UNLOCK(); - return; - } - xim = XmStringCreate(clabel, "labelFont"); - - JNU_ReleaseStringPlatformChars(env, label, (const char *) clabel);; - } - } - - XtVaSetValues(wdata->widget, XmNlabelString, xim, NULL); - XmStringFree(xim); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MCheckboxPeer - * Method: pSetState - * Signature: (Z)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCheckboxPeer_pSetState - (JNIEnv * env, jobject this, jboolean state) -{ - struct ComponentData *bdata; - - AWT_LOCK(); - - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (bdata == NULL || bdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(bdata->widget, XmNset, (Boolean) state, NULL); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MCheckboxPeer - * Method: pGetState - * Signature: ()Z - */ -JNIEXPORT jboolean JNICALL Java_sun_awt_motif_MCheckboxPeer_pGetState - (JNIEnv * env, jobject this) -{ - struct ComponentData *bdata; - Boolean state; - - AWT_LOCK(); - - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (bdata == NULL || bdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return JNI_FALSE; - } - XtVaGetValues(bdata->widget, XmNset, &state, NULL); - AWT_FLUSH_UNLOCK(); - return ((state) ? JNI_TRUE : JNI_FALSE); -} - - -/* - * Class: sun_awt_motif_MCheckboxPeer - * Method: setCheckboxGroup - * Signature: (Ljava/awt/CheckboxGroup;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCheckboxPeer_setCheckboxGroup - (JNIEnv * env, jobject this, jobject group) -{ - struct ComponentData *bdata; - - AWT_LOCK(); - - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (bdata == NULL || bdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (JNU_IsNull(env, group)) { - XtVaSetValues(bdata->widget, - XmNindicatorType, XmN_OF_MANY, - NULL); - } else { - XtVaSetValues(bdata->widget, - XmNindicatorType, XmONE_OF_MANY, - NULL); - } - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MCheckboxPeer - * Method: getIndicatorSize - * Signature: (V)I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MCheckboxPeer_getIndicatorSize - (JNIEnv * env, jobject this) -{ - struct ComponentData *wdata; - Dimension size; - - AWT_LOCK(); - - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || wdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "Null pData"); - AWT_UNLOCK(); - return 0; - } - XtVaGetValues(wdata->widget, - XmNindicatorSize, &size, - NULL); - - AWT_FLUSH_UNLOCK(); - - return size; -} - -/* - * Class: sun_awt_motif_MCheckboxPeer - * Method: getSpacing - * Signature: (V)I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MCheckboxPeer_getSpacing - (JNIEnv * env, jobject this) -{ - struct ComponentData *wdata; - Dimension dim; - - AWT_LOCK(); - - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || wdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "Null pData"); - AWT_UNLOCK(); - return 0; - } - XtVaGetValues(wdata->widget, - XmNspacing, &dim, - NULL); - - AWT_FLUSH_UNLOCK(); - - return dim; -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Choice12.c b/jdk/src/solaris/native/sun/awt/awt_Choice12.c deleted file mode 100644 index 57f9e6d029e..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Choice12.c +++ /dev/null @@ -1,843 +0,0 @@ -/* - * Copyright 1995-2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "java_awt_Component.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "sun_awt_motif_MChoicePeer.h" - -#include "awt_Component.h" -#include "awt_MToolkit.h" - -#include "multi_font.h" -#include -#include -#include - -extern struct ComponentIDs componentIDs; -extern struct ContainerIDs containerIDs; -extern struct MComponentPeerIDs mComponentPeerIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -static void geometry_hook(Widget wid, Widget hooked_widget, XtGeometryHookData call_data) { - XtWidgetGeometry *request; - JNIEnv *env; - struct ChoiceData *cdata; - struct WidgetInfo *winfo = NULL; - - jobject target; - jobject parent; - jint y, height; - - if ((call_data->widget == hooked_widget) && - (call_data->type == XtHpostGeometry) && - (call_data->result == XtGeometryYes)) { - - request = call_data->request; - - env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - DASSERT(env != NULL); - - winfo=findWidgetInfo(hooked_widget); - - if (winfo != NULL && XmIsRowColumn(hooked_widget)) { - target = (*env)->GetObjectField(env, (jobject)winfo->peer, mComponentPeerIDs.target); - cdata = (struct ChoiceData *) JNU_GetLongFieldAsPtr(env, (jobject)winfo->peer, mComponentPeerIDs.pData); - DASSERT(target != NULL); - DASSERT(cdata != NULL && cdata->comp.widget != NULL) - if (request->request_mode & CWHeight) { - height = (*env)->GetIntField(env, target, componentIDs.height); - if (request->height > 0 && request->height != height) { - parent = (*env)->CallObjectMethod(env, target, componentIDs.getParent); - if ((parent != NULL) && ((*env)->GetObjectField(env, parent, containerIDs.layoutMgr) != NULL)) { - y = cdata->bounds_y; - if (request->height < cdata->bounds_height) { - y += (cdata->bounds_height - request->height) / 2; - } - XtVaSetValues(hooked_widget, XmNy, y, NULL); - (*env)->SetIntField(env, target, componentIDs.y, y); - } - if (parent != NULL) { - (*env)->DeleteLocalRef(env, parent); - } - } - (*env)->SetIntField(env, target, componentIDs.height, request->height); - } - if (request->request_mode & CWWidth) { - (*env)->SetIntField(env, target, componentIDs.width, request->width); - } - (*env)->DeleteLocalRef(env, target); - } - } -} - -static void -Choice_callback(Widget menu_item, - jobject this, - XmAnyCallbackStruct * cbs) -{ - intptr_t index; - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - XtVaGetValues(menu_item, XmNuserData, &index, NULL); - /* index stored in user-data is 1-based instead of 0-based because */ - /* of a bug in XmNuserData */ - index--; - - JNU_CallMethodByName(env, NULL, this, "action", "(I)V", (jint)index); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -static void addItems - (JNIEnv *env, jobject this, jstring *items, jsize nItems, jint index) -{ - char *citem = NULL; - struct ChoiceData *odata; - Widget bw; -#define MAX_ARGC 10 - Arg args[MAX_ARGC]; - Cardinal argc, argc1; - jsize i; - Pixel bg; - Pixel fg; - short cols; - int32_t sheight; - Dimension height; - Widget *firstNewItem = NULL; - - XmString mfstr = NULL; - XmFontList fontlist = NULL; - jobject font = awtJNI_GetFont(env, this); - Boolean IsMultiFont = awtJNI_IsMultiFont(env, font); - - if ((items == NULL) || (nItems == 0)) { - return; - } - - AWT_LOCK(); - - odata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (odata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - if (odata->maxitems == 0 || (index + nItems) > odata->maxitems) { - odata->maxitems = index + nItems + 20; - if (odata->n_items > 0) { - /* grow the list of items */ - odata->items = (Widget *) - realloc((void *) (odata->items) - ,sizeof(Widget) * odata->maxitems); - } else { - odata->items = (Widget *) malloc(sizeof(Widget) * odata->maxitems); - } - if (odata->items == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - } - XtVaGetValues(odata->comp.widget, XmNbackground, &bg, NULL); - XtVaGetValues(odata->comp.widget, XmNforeground, &fg, NULL); - - argc = 0; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNforeground, fg); - argc++; - - firstNewItem = &(odata->items[index]); - for (i = 0; i < nItems; i++) { - argc1 = argc; - if (IsMultiFont) { - mfstr = awtJNI_MakeMultiFontString(env, items[i], font); - fontlist = awtJNI_GetFontList(env, font); - /* XXX: XmNuserData doesn't seem to work when passing in zero */ - /* so we increment the index before passing it in. */ - XtSetArg(args[argc1], XmNuserData, (XtPointer)((intptr_t)(index + i + 1))); - argc1++; - XtSetArg(args[argc1], XmNfontList, fontlist); - argc1++; - XtSetArg(args[argc1], XmNlabelString, mfstr); - argc1++; - - DASSERT(!(argc1 > MAX_ARGC)); - - bw = XmCreatePushButton(odata->menu, "", args, argc1); - - /* Free resurces */ - if ( fontlist != NULL ) - { - XmFontListFree(fontlist); - fontlist = NULL; - } - if (mfstr != NULL) { - XmStringFree(mfstr); - mfstr = NULL; - } - } else { - citem = (char *) JNU_GetStringPlatformChars(env, items[i], NULL); - /* XXX: XmNuserData doesn't seem to work when passing in zero */ - /* so we increment the index before passing it in. */ - XtSetArg(args[argc1], XmNuserData, (XtPointer)((intptr_t)(index + i + 1))); - argc1++; - DASSERT(!(argc1> MAX_ARGC)); - bw = XmCreatePushButton(odata->menu, citem, args, argc1); - JNU_ReleaseStringPlatformChars(env, items[i], (const char *) citem); - citem = NULL; - } - - XtAddCallback(bw, - XmNactivateCallback, - (XtCallbackProc) Choice_callback, - (XtPointer) JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.jniGlobalRef)); - odata->items[index + i] = bw; - odata->n_items++; - } - - XtManageChildren(firstNewItem, nItems); - - sheight = DisplayHeight(awt_display, DefaultScreen(awt_display)); - - XtVaGetValues(odata->menu, XmNheight, &height, NULL); - - while ( height > sheight ) { - cols = ++odata->n_columns; - XtVaSetValues(odata->menu, XmNnumColumns, cols, NULL); - XtVaGetValues(odata->menu, XmNheight, &height, NULL); - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_create - (JNIEnv * env, jobject this, jobject parent) -{ - struct ChoiceData *odata; - struct ComponentData *wdata; -#undef MAX_ARGC -#define MAX_ARGC 30 - Arg args[MAX_ARGC]; - Cardinal argc; - Pixel bg; - Pixel fg; - Widget label; - Widget button; - Widget hookobj; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; - jobject target; - Dimension width = 0, height = 0; - jclass clsDimension; - jobject dimension; - jobject peer; - - AWT_LOCK(); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - - adata = copyGraphicsConfigToPeer(env, this); - - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,parent,mComponentPeerIDs.pData); - - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - - odata = ZALLOC(ChoiceData); - if (odata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - JNU_SetLongFieldFromPtr(env,this,mComponentPeerIDs.pData,odata); - - odata->items = NULL; - odata->maxitems = 0; - odata->n_items = 0; - odata->n_columns = 1; - - XtVaGetValues(wdata->widget, XmNbackground, &bg, NULL); - XtVaGetValues(wdata->widget, XmNforeground, &fg, NULL); - - argc = 0; - XtSetArg(args[argc], XmNx, 0); - argc++; - XtSetArg(args[argc], XmNy, 0); - argc++; - XtSetArg(args[argc], XmNvisual, adata->awt_visInfo.visual); - argc++; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNforeground, fg); - argc++; - - XtSetArg(args[argc], XmNorientation, XmVERTICAL); - argc++; - XtSetArg(args[argc], XmNpacking, XmPACK_COLUMN); - argc++; - XtSetArg(args[argc], XmNnumColumns, (short)1); - argc++; - /* Fix for 4303064 by ibd@sparc.spb.su: pop-up shells will have - * ancestor_sensitive False if the parent was insensitive when the shell - * was created. Since XtSetSensitive on the parent will not modify the - * resource of the pop-up child, clients are advised to include a resource - * specification of the form '*TransientShell.ancestorSensitive: True' in - * the application defaults resource file or to otherwise ensure that the - * parent is sensitive when creating pop-up shells. - */ - XtSetArg(args[argc], XmNancestorSensitive, True); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - odata->menu = XmCreatePulldownMenu(wdata->widget, "pulldown", args, argc); - - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - clsDimension = (*env)->FindClass(env, "java/awt/Dimension"); - dimension = JNU_CallMethodByName(env, - NULL, - this, - "getPreferredSize", - "()Ljava/awt/Dimension;").l; - DASSERT(clsDimension != NULL); - width = (Dimension)((*env)->GetIntField(env, dimension, (*env)->GetFieldID(env, clsDimension, "width" , "I"))); - height = (Dimension)((*env)->GetIntField(env, dimension, (*env)->GetFieldID(env, clsDimension, "height", "I"))); - - argc = 0; - XtSetArg(args[argc], XmNx, 0); - argc++; - XtSetArg(args[argc], XmNy, 0); - argc++; - XtSetArg(args[argc], XmNwidth, width); - argc++; - XtSetArg(args[argc], XmNheight, height); - argc++; - XtSetArg(args[argc], XmNmarginHeight, 0); - argc++; - XtSetArg(args[argc], XmNmarginWidth, 0); - argc++; - XtSetArg(args[argc], XmNrecomputeSize, False); - argc++; - XtSetArg(args[argc], XmNresizeHeight, False); - argc++; - XtSetArg(args[argc], XmNresizeWidth, False); - argc++; - XtSetArg(args[argc], XmNspacing, False); - argc++; - XtSetArg(args[argc], XmNborderWidth, 0); - argc++; - XtSetArg(args[argc], XmNnavigationType, XmTAB_GROUP); - argc++; - XtSetArg(args[argc], XmNtraversalOn, True); - argc++; - XtSetArg(args[argc], XmNorientation, XmVERTICAL); - argc++; - XtSetArg(args[argc], XmNadjustMargin, False); - argc++; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNforeground, fg); - argc++; - XtSetArg(args[argc], XmNsubMenuId, odata->menu); - argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, adata->awt_visInfo.screen)); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - odata->comp.widget = XmCreateOptionMenu(wdata->widget, "", args, argc); - - hookobj = XtHooksOfDisplay(XtDisplayOfObject(odata->comp.widget)); - XtAddCallback(hookobj, - XtNgeometryHook, - (XtCallbackProc) geometry_hook, - (XtPointer) odata->comp.widget); - - label = XmOptionLabelGadget(odata->comp.widget); - if (label != NULL) { - XtUnmanageChild(label); - } - XtSetMappedWhenManaged(odata->comp.widget, False); - XtManageChild(odata->comp.widget); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: addItem - * Signature: (Ljava/lang/String;I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_addItem - (JNIEnv *env, jobject this, jstring item, jint index) -{ - if (JNU_IsNull(env, item)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - addItems(env, this, &item, 1, index); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: pSelect - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_pSelect - (JNIEnv *env, jobject this, jint index, jboolean init) -{ - struct ChoiceData *odata; - - AWT_LOCK(); - - odata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (odata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (index > odata->n_items || index < 0) { - JNU_ThrowIllegalArgumentException(env, "IllegalArgumentException"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(odata->comp.widget, - XmNmenuHistory, odata->items[index], - NULL); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: setFont - * Signature: (Ljava/awt/Font;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_setFont - (JNIEnv *env, jobject this, jobject f) -{ - struct ChoiceData *cdata; - struct FontData *fdata; - XmFontList fontlist; - char *err; - - if (JNU_IsNull(env, f)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - - fdata = awtJNI_GetFontData(env, f, &err); - if (fdata == NULL) { - JNU_ThrowInternalError(env, err); - AWT_UNLOCK(); - return; - } - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (awtJNI_IsMultiFont(env, f)) { - fontlist = awtJNI_GetFontList(env, f); - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - - if (fontlist != NULL) { - jint i; - - XtVaSetValues(cdata->comp.widget, - XmNfontList, fontlist, - NULL); - XtVaSetValues(cdata->menu, - XmNfontList, fontlist, - NULL); - for (i = 0; i < cdata->n_items; i++) { - XtVaSetValues(cdata->items[i], - XmNfontList, fontlist, - NULL); - } - - XmFontListFree(fontlist); - } else { - JNU_ThrowNullPointerException(env, "NullPointerException"); - } - AWT_UNLOCK(); -} - -/* Fix for bug 4326619 */ -/* - * Class: sun_awt_motif_MChoicePeer - * Method: freeNativeData - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_freeNativeData - (JNIEnv *env, jobject this) -{ - struct ChoiceData *cdata; - - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - cdata->n_items = 0; - free((void *)cdata->items); - cdata->items = NULL; - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: setBackground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_setBackground - (JNIEnv *env, jobject this, jobject c) -{ - struct ChoiceData *bdata; - Pixel bg; - Pixel fg; - WidgetList children; - Cardinal numChildren; - int32_t i; - - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException: null color"); - return; - } - AWT_LOCK(); - - bdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (bdata == NULL || bdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - /* Get background color */ - bg = awtJNI_GetColor(env, c); - - /* - XmChangeColor(), in addtion to changing the background and - selection colors, also changes the foreground color to be - what it thinks should be. However, we want to use the color - that gets set by setForeground() instead. We therefore need to - save the current foreground color here, and then set it again - after the XmChangeColor() occurs. - */ - XtVaGetValues(bdata->comp.widget, XmNforeground, &fg, NULL); - - /* Set color */ - XmChangeColor(bdata->comp.widget, bg); - XtVaSetValues(bdata->comp.widget, XmNforeground, fg, NULL); - - /* - * The following recursion fixes a bug in Motif 2.1 that caused - * black colored choice buttons (change has no effect on Motif 1.2). - */ - XtVaGetValues(bdata->comp.widget, - XmNchildren, &children, - XmNnumChildren, &numChildren, - NULL); - for (i = 0; i < numChildren; i++) { - XmChangeColor(children[i], bg); - XtVaSetValues(children[i], XmNforeground, fg, NULL); - } - - - XmChangeColor(bdata->menu, bg); - XtVaSetValues(bdata->menu, XmNforeground, fg, NULL); - - for (i = 0; i < bdata->n_items; i++) { - XmChangeColor(bdata->items[i], bg); - XtVaSetValues(bdata->items[i], XmNforeground, fg, NULL); - } - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: setForeground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_setForeground - (JNIEnv *env, jobject this, jobject c) -{ - struct ChoiceData *bdata; - Pixel color; - int32_t i; - - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException: null color"); - return; - } - AWT_LOCK(); - - bdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (bdata == NULL || bdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - color = awtJNI_GetColor(env, c); - - XtVaSetValues(bdata->comp.widget, XmNforeground, color, NULL); - - XtVaSetValues(bdata->menu, XmNforeground, color, NULL); - for (i = 0; i < bdata->n_items; i++) { - XtVaSetValues(bdata->items[i], XmNforeground, color, NULL); - } - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: pReshape - * Signature: (IIII)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_pReshape - (JNIEnv *env, jobject this, jint x, jint y, jint w, jint h) -{ - struct ChoiceData *cdata; - Widget button; - jobject target; - Dimension width=0, height=0; - Position new_y = 0; - - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - button = XmOptionButtonGadget(cdata->comp.widget); - cdata->bounds_y = y; - cdata->bounds_height = h; - awt_util_reshape(cdata->comp.widget, x, y, w, h); - awt_util_reshape(button, x, y, w, h); - - /* Bug 4255631 Solaris: Size returned by Choice.getSize() does not match - * actual size - */ - XtVaGetValues(cdata->comp.widget, XmNy, &new_y, NULL); - XtVaGetValues(button, XmNwidth, &width, XmNheight, &height , NULL); - awt_util_reshape(cdata->comp.widget, x, new_y, width, height); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: remove - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_remove - (JNIEnv *env, jobject this, jint index) -{ - struct ChoiceData *cdata; - Widget selected; - jint i; - short cols; - int32_t sheight; - Dimension height; - - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (index < 0 || index > cdata->n_items) { - JNU_ThrowIllegalArgumentException(env, "IllegalArgumentException"); - AWT_UNLOCK(); - return; - } - XtUnmanageChild(cdata->items[index]); - awt_util_consumeAllXEvents(cdata->items[index]); - awt_util_cleanupBeforeDestroyWidget(cdata->items[index]); - XtDestroyWidget(cdata->items[index]); - for (i = index; i < cdata->n_items-1; i++) { - cdata->items[i] = cdata->items[i + 1]; - /* need to reset stored index value, (adding 1 to disambiguate it */ - /* from an arg list terminator) */ - /* bug fix 4079027 robi.khan@eng */ - XtVaSetValues(cdata->items[i], XmNuserData, (XtPointer)((intptr_t)(i+1)), NULL); - } - cdata->items[cdata->n_items-1] = NULL; - cdata->n_items--; - - XtVaGetValues(cdata->menu, XmNheight, &height, NULL); - - sheight = DisplayHeight(awt_display, DefaultScreen(awt_display)); - cols = cdata->n_columns; - - if (cols >1) { - /* first try to remove a column */ - cols = --cdata->n_columns; - XtVaSetValues(cdata->menu, XmNnumColumns, cols, NULL); - - /* then see if it fits, if not add it back */ - XtVaGetValues(cdata->menu, XmNheight, &height, NULL); - if ( height > sheight ) { - cols = ++cdata->n_columns; - XtVaSetValues(cdata->menu, XmNnumColumns, cols, NULL); - } - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: removeAll - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_removeAll - (JNIEnv *env, jobject this) -{ - struct ChoiceData *cdata; - Widget selected; - jint i; - - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - XtUnmanageChildren(cdata->items, cdata->n_items); - - for (i = cdata->n_items-1; i >= 0; i--) { - awt_util_consumeAllXEvents(cdata->items[i]); - awt_util_cleanupBeforeDestroyWidget(cdata->items[i]); - XtDestroyWidget(cdata->items[i]); - cdata->items[i] = NULL; - } - - cdata->n_items = 0; - - if (cdata->n_columns > 1) { - cdata->n_columns = 1; - XtVaSetValues(cdata->menu, XmNnumColumns, cdata->n_columns, NULL); - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: appendItems - * Signature: ([Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MChoicePeer_appendItems - (JNIEnv *env, jobject this, jarray items) -{ - struct ChoiceData *odata = NULL; - jstring *strItems = NULL; - jsize nItems, i; // MP - - if (JNU_IsNull(env, items)) { - return; - } - nItems = (*env)->GetArrayLength(env, items); - if (nItems == 0) { - return; - } - - AWT_LOCK(); - - odata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (odata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - goto cleanup; - } - - strItems = (jstring *) malloc(sizeof(jstring) * nItems); - if (strItems == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - goto cleanup; - } - - for (i = 0; i < nItems; i++) { - strItems[i] = (jstring)(*env)->GetObjectArrayElement(env, items, i); - if (JNU_IsNull(env, strItems[i])) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - goto cleanup; - } - } - - addItems(env, this, strItems, nItems, odata->n_items); - -cleanup: - if (strItems != NULL) { - free(strItems); - } - AWT_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Choice21.c b/jdk/src/solaris/native/sun/awt/awt_Choice21.c deleted file mode 100644 index 838f991f84e..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Choice21.c +++ /dev/null @@ -1,764 +0,0 @@ -/* - * Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#if MOTIF_VERSION!=2 - #error This file should only be compiled with motif 2.1 -#endif - -#include "awt_p.h" -#include "java_awt_Component.h" -#include "java_awt_AWTEvent.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "sun_awt_motif_MChoicePeer.h" - -#include "awt_Component.h" -#include "canvas.h" - -#include "multi_font.h" - -#include -#include -#include - -#define MAX_VISIBLE 10 - -extern struct ComponentIDs componentIDs; -extern struct ContainerIDs containerIDs; -extern struct MComponentPeerIDs mComponentPeerIDs; - -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -/* - setSelection - Set the selected text on the XmTextField of the XmComboBox. -*/ -static void -setSelection(JNIEnv *env, - jobject this, - Widget comboBox, - jint index) -{ - jstring item = NULL; - jobject target; - Widget text=NULL; - - AWT_LOCK(); - /* Get the java Choice component. */ - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - if (target == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - /* Get the XmTextField widget in the XmComboBox. */ - text = XtNameToWidget(comboBox, "*Text"); - /* Get the selected Unicode string from the java Choice component. */ - item = (jstring) JNU_CallMethodByName(env, NULL, - target, "getItem", "(I)Ljava/lang/String;", index).l; - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - if (!JNU_IsNull(env, item)) { - /* Convert the Unicode string to a multibyte string. */ - char *temp = (char *)JNU_GetStringPlatformChars(env, item, NULL); - /* Assign the multibyte string to the XmTextField of the XmComboBox. */ - XmTextSetString(text, temp); - JNU_ReleaseStringPlatformChars(env, item, (const char *)temp); - } - AWT_UNLOCK(); -} - -extern Boolean skipNextNotifyWhileGrabbed; -extern Boolean skipNextFocusIn; - -static void -GrabShellPopup(Widget grab_shell, - jobject this, - XmAnyCallbackStruct * call_data) -{ - skipNextNotifyWhileGrabbed = True; -} -static void -GrabShellPopdown(Widget grab_shell, - jobject this, - XmAnyCallbackStruct * call_data) -{ - skipNextNotifyWhileGrabbed = True; - skipNextFocusIn = True; -} - -static void -Choice_callback(Widget list, - jobject this, - XmAnyCallbackStruct * call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - XmListCallbackStruct *cbs = (XmListCallbackStruct *)call_data; - struct ChoiceData *cdata; - - - AWT_LOCK(); - /* Get the Choice data. */ - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - setSelection(env, this, cdata->comp.widget, cbs->item_position - 1); - /* Get the Choice data. */ - JNU_CallMethodByName(env, NULL, - this, "action", "(I)V", cbs->item_position - 1); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - AWT_UNLOCK(); -} - -static void -addItems(JNIEnv *env, jobject this, - jstring *items, int32_t nItems, jint index) -{ - struct ChoiceData *cdata; - int32_t i; - Widget list; - XmString mfstr = NULL; - XmFontList fontlist = NULL; - jobject font = awtJNI_GetFont(env, this); - Boolean IsMultiFont = awtJNI_IsMultiFont(env, font); - - if ((items == NULL) || (nItems == 0)) { - return; - } - - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (cdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - for (i = 0; i < nItems; ++i) { - char *temp = (char *)JNU_GetStringPlatformChars(env, items[i], NULL); - mfstr = XmStringCreateLocalized(temp); - JNU_ReleaseStringPlatformChars(env, items[i], (const char *)temp); - XmComboBoxAddItem(cdata->comp.widget, mfstr, index + i + 1, FALSE); - - if (mfstr != NULL) { - XmStringFree(mfstr); - mfstr = NULL; - } - } - - cdata->n_items += nItems; - - list = XtNameToWidget(cdata->comp.widget, "*List"); - XtVaSetValues(list, - XmNvisibleItemCount, min(MAX_VISIBLE, cdata->n_items), - NULL); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_create(JNIEnv * env, jobject this, - jobject parent) -{ - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - - struct ComponentData *wdata; /* parent's peer data */ - struct ChoiceData *cdata; /* our own peer data */ - Widget list, text, list_shell; /* components of drop dowwn list widget */ - - AwtGraphicsConfigDataPtr adata; - Pixel fg, bg; /* colors inherited from parent */ - Dimension width = 0, height = 0; - jclass clsDimension; - jobject dimension; - -#undef MAX_ARGC -#define MAX_ARGC 30 - Arg args[MAX_ARGC]; - int32_t argc; - - AWT_LOCK(); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - - /* get parent's peer data */ - wdata = (struct ComponentData *)JNU_GetLongFieldAsPtr(env, - parent, mComponentPeerIDs.pData); - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - /* create our own peer data */ - cdata = ZALLOC(ChoiceData); - if (cdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - JNU_SetLongFieldFromPtr(env, this, mComponentPeerIDs.pData, cdata); - - /* get desired size */ - clsDimension = (*env)->FindClass(env, "java/awt/Dimension"); - DASSERT(clsDimension != NULL); - - dimension = JNU_CallMethodByName(env, NULL, - this, "getPreferredSize", "()Ljava/awt/Dimension;").l; - width = (Dimension)((*env)->GetIntField(env, dimension, - (*env)->GetFieldID(env, clsDimension, - "width" , "I"))); - height = (Dimension)((*env)->GetIntField(env, dimension, - (*env)->GetFieldID(env, clsDimension, - "height", "I"))); - - /* Inherit visual/colors from parent component */ - XtVaGetValues(wdata->widget, XmNbackground, &bg, NULL); - XtVaGetValues(wdata->widget, XmNforeground, &fg, NULL); - adata = copyGraphicsConfigToPeer(env, this); - - argc = 0; - XtSetArg(args[argc], XmNuserData, (XtPointer)globalRef); ++argc; - XtSetArg(args[argc], XmNx, 0); ++argc; - XtSetArg(args[argc], XmNy, 0); ++argc; - XtSetArg(args[argc], XmNmarginHeight, 2); ++argc; - XtSetArg(args[argc], XmNmarginWidth, 1); ++argc; - XtSetArg(args[argc], XmNvisibleItemCount, 0); ++argc; - XtSetArg(args[argc], XmNancestorSensitive, True); ++argc; - /* Don't ding on key press */ - XtSetArg(args[argc], XmNverifyBell, False); ++argc; - XtSetArg(args[argc], XmNvisual, adata->awt_visInfo.visual); ++argc; - XtSetArg(args[argc], XmNscreen, - ScreenOfDisplay(awt_display, adata->awt_visInfo.screen)); ++argc; - XtSetArg(args[argc], XmNbackground, bg); ++argc; - XtSetArg(args[argc], XmNforeground, fg); ++argc; - - DASSERT(!(argc > MAX_ARGC)); - cdata->comp.widget = XmCreateDropDownList(wdata->widget, - "combobox", args, argc); - cdata->n_items = 0; - - list = XtNameToWidget(cdata->comp.widget, "*List"); - text = XtNameToWidget(cdata->comp.widget, "*Text"); - list_shell = XtNameToWidget(cdata->comp.widget, "*GrabShell"); - XtAddCallback(list_shell, - XmNpopupCallback, - (XtCallbackProc)GrabShellPopup, - globalRef); - XtAddCallback(list_shell, - XmNpopdownCallback, - (XtCallbackProc)GrabShellPopdown, - globalRef); - - /* - * Bug 4477410: Setting the width of the XmComboBox made the XmTextField - * too small, cutting off the dropdown list knob on the right side. Set - * the width of the TextField because it is the widget actually seen. - */ - /* Set the width and height of the TextField widget. */ - XtVaSetValues(text, - XmNwidth, width, - XmNheight, height, - NULL); - - XtAddCallback(list, - XmNbrowseSelectionCallback, - (XtCallbackProc)Choice_callback, - (XtPointer)globalRef); - - XtAddEventHandler(text, FocusChangeMask, True, - awt_canvas_event_handler, globalRef); - - awt_addWidget(text, cdata->comp.widget, globalRef, - java_awt_AWTEvent_KEY_EVENT_MASK - | java_awt_AWTEvent_MOUSE_EVENT_MASK - | java_awt_AWTEvent_MOUSE_MOTION_EVENT_MASK); - - XtSetMappedWhenManaged(cdata->comp.widget, False); - XtManageChild(cdata->comp.widget); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: pSelect - * Signature: (I)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_pSelect(JNIEnv *env, jobject this, - jint index, jboolean init) -{ - struct ChoiceData *cdata; - Widget list; - - AWT_LOCK(); - - cdata = (struct ChoiceData *)JNU_GetLongFieldAsPtr(env, - this, mComponentPeerIDs.pData); - if (cdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - list = XtNameToWidget(cdata->comp.widget, "*List"); - - XmListDeselectAllItems(list); - XmListSelectPos(list, index + 1, False); - setSelection(env, this, cdata->comp.widget, index); - XmComboBoxUpdate(cdata->comp.widget); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: setFont - * Signature: (Ljava/awt/Font;)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_setFont(JNIEnv *env, jobject this, - jobject f) -{ - struct ChoiceData *cdata; - struct FontData *fdata; - XmFontList fontlist; - Widget list; - Widget text; - char *err; - XmFontListEntry fontentry; - Position x=0, y=0; - - if (JNU_IsNull(env, f)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - - fdata = awtJNI_GetFontData(env, f, &err); - if (fdata == NULL) { - JNU_ThrowInternalError(env, err); - AWT_UNLOCK(); - return; - } - - cdata = (struct ChoiceData *)JNU_GetLongFieldAsPtr(env, - this, mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - /* Make a fontset and set it. */ - if (awtJNI_IsMultiFont(env, f)) { - if (fdata->xfs == NULL) { - fdata->xfs = awtJNI_MakeFontSet(env, f); - } - if (fdata->xfs != NULL) { - fontentry = XmFontListEntryCreate("labelFont", - XmFONT_IS_FONTSET, - (XtPointer) (fdata->xfs)); - fontlist = XmFontListAppendEntry(NULL, fontentry); - /* - * Some versions of motif have a bug in - * XmFontListEntryFree() which causes it to free more than it - * should. Use XtFree() instead. See O'Reilly's - * Motif Reference Manual for more information. - */ - XmFontListEntryFree(&fontentry); - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - XtVaSetValues(cdata->comp.widget, - XmNfontList, fontlist, - NULL); - list = XtNameToWidget(cdata->comp.widget, "*List"); - XtVaSetValues(list, - XmNfontList, fontlist, - NULL); - - text = XtNameToWidget(cdata->comp.widget, "*Text"); - XtVaSetValues(text, - XmNfontList, fontlist, - NULL); - XmFontListFree(fontlist); - XtVaGetValues(cdata->comp.widget, - XmNx, &x, - XmNy, &y, - NULL); - Java_sun_awt_motif_MChoicePeer_pReshape(env, this, x, y, 0, 0); - AWT_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: freeNativeData - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_freeNativeData(JNIEnv *env, jobject this) -{ - /* - * Fix for bug 4326619 - not necessary for Motif 2.1 - */ -} - - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: setBackground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_setBackground(JNIEnv *env, jobject this, - jobject c) -{ - struct ChoiceData *cdata; - Pixel bg; - Pixel fg; - int32_t i; - - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException: null color"); - return; - } - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - /* Get background color */ - bg = awtJNI_GetColor(env, c); - - /* - XmChangeColor(), in addtion to changing the background and - selection colors, also changes the foreground color to be - what it thinks should be. However, we want to use the color - that gets set by setForeground() instead. We therefore need to - save the current foreground color here, and then set it again - after the XmChangeColor() occurs. - */ - XtVaGetValues(cdata->comp.widget, XmNforeground, &fg, NULL); - - /* Set color */ - XmChangeColor(cdata->comp.widget, bg); - XtVaSetValues(cdata->comp.widget, XmNforeground, fg, NULL); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: setForeground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_setForeground(JNIEnv *env, jobject this, - jobject c) -{ - struct ChoiceData *cdata; - Pixel color; - int32_t i; - - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException: null color"); - return; - } - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - color = awtJNI_GetColor(env, c); - - XtVaSetValues(cdata->comp.widget, XmNforeground, color, NULL); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: pReshape - * Signature: (IIII)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_pReshape(JNIEnv *env, jobject this, - jint x, jint y, jint w, jint h) -{ - struct ChoiceData *cdata; - Widget list; - Dimension width = 0, height = 0; - jclass clsDimension; - jobject dimension; - jobject target; - Widget text=NULL; - - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - if (w == 0) { - /* Set the width and height of the TextField widget to the - * PreferredSize, based on the font size. - */ - clsDimension = (*env)->FindClass(env, "java/awt/Dimension"); - DASSERT(clsDimension != NULL); - dimension = JNU_CallMethodByName(env, NULL, - this, "getPreferredSize", "()Ljava/awt/Dimension;").l; - width = (Dimension)((*env)->GetIntField(env, dimension, - (*env)->GetFieldID(env, clsDimension, - "width" , "I"))); - height = (Dimension)((*env)->GetIntField(env, dimension, - (*env)->GetFieldID(env, clsDimension, - "height", "I"))); - } else { - /* Set the width and height of the TextField widget to the - * given values. BorderLayout passes these values, for example. - */ - width = w; - height = h; - } - text = XtNameToWidget(cdata->comp.widget, "*Text"); - /* - * Bug 4477410: Setting the width of the XmComboBox made the XmTextField - * too small, cutting off the dropdown list knob on the right side. Set - * the width of the TextField because it is the widget actually seen. - */ - XtVaSetValues(text, - XmNwidth, width, - XmNheight, height, - NULL); - - awt_util_reshape(cdata->comp.widget, x, y, width, height); - - list = XtNameToWidget(cdata->comp.widget, "*List"); - - XtVaSetValues(list, XmNwidth, width, NULL); - - /* Set the width and height of the Choice component. */ - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - if (target == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - (*env)->SetIntField(env, target, componentIDs.width, (jint)width); - (*env)->SetIntField(env, target, componentIDs.height, (jint)height); - - AWT_FLUSH_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: addItem - * Signature: (Ljava/lang/String;I)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_addItem(JNIEnv *env, jobject this, - jstring item, jint index) -{ - if (JNU_IsNull(env, item)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - addItems(env, this, &item, 1, index); -} - - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: appendItems - * Signature: ([Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_appendItems(JNIEnv *env, jobject this, - jarray items) -{ - struct ChoiceData *cdata = NULL; - jstring *strItems = NULL; - int32_t nItems, i; - - if (JNU_IsNull(env, items)) { - return; - } - nItems = (*env)->GetArrayLength(env, items); - if (nItems == 0) { - return; - } - - AWT_LOCK(); - - cdata = (struct ChoiceData *)JNU_GetLongFieldAsPtr(env, - this, mComponentPeerIDs.pData); - if (cdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - goto cleanup; - } - - strItems = (jstring *)malloc(sizeof(jstring) * nItems); - if (strItems == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - goto cleanup; - } - - for (i = 0; i < nItems; ++i) { - strItems[i] = (jstring)(*env)->GetObjectArrayElement(env, - items, (jsize)i); - if (JNU_IsNull(env, strItems[i])) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - goto cleanup; - } - } - - addItems(env, this, strItems, nItems, (jint)cdata->n_items); - - cleanup: - if (strItems != NULL) { - free(strItems); - } - AWT_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: remove - * Signature: (I)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_remove(JNIEnv *env, jobject this, - jint index) -{ - struct ChoiceData *cdata; - Widget list; - Widget text=NULL; - - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - XmComboBoxDeletePos(cdata->comp.widget, index + 1); - --(cdata->n_items); - - list = XtNameToWidget(cdata->comp.widget, "*List"); - XtVaSetValues(list, XmNvisibleItemCount, min(MAX_VISIBLE, cdata->n_items), NULL); - - if (cdata->n_items == 0) { - /* No item is selected, so clear the TextField. */ - text = XtNameToWidget(cdata->comp.widget, "*Text"); - XtVaSetValues(text, XmNvalue, "", NULL); - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MChoicePeer - * Method: removeAll - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MChoicePeer_removeAll(JNIEnv *env, jobject this) -{ - struct ChoiceData *cdata; - int32_t i; - Widget text=NULL; - Widget list; - - AWT_LOCK(); - - cdata = (struct ChoiceData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - for (i = cdata->n_items - 1; i >= 0; --i) { - XmComboBoxDeletePos(cdata->comp.widget, i); - } - cdata->n_items = 0; - - /* No item is selected, so clear the TextField. */ - text = XtNameToWidget(cdata->comp.widget, "*Text"); - XtVaSetValues(text, XmNvalue, "", NULL); - - /* should set XmNvisibleItemCount to 1 as 0 is invalid value */ - list = XtNameToWidget(cdata->comp.widget, "*List"); - XtVaSetValues(list, XmNvisibleItemCount, 1, NULL); - - AWT_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Component.c b/jdk/src/solaris/native/sun/awt/awt_Component.c deleted file mode 100644 index b61e89dfc7d..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Component.c +++ /dev/null @@ -1,1656 +0,0 @@ -/* - * Copyright 1995-2006 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS -#error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "canvas.h" -#include "awt_AWTEvent.h" -#include "VDrawingArea.h" -#include "awt_KeyboardFocusManager.h" -#include "awt_MToolkit.h" -#include "awt_TopLevel.h" -#include "java_awt_Color.h" -#include "java_awt_Cursor.h" -#include "java_awt_Font.h" -#include "java_awt_Point.h" -#include "java_awt_Component.h" -#include "java_awt_AWTEvent.h" -#include "java_awt_KeyboardFocusManager.h" -#include "java_awt_event_KeyEvent.h" -#include "java_awt_event_MouseEvent.h" -#include "sun_awt_motif_MComponentPeer.h" - -#include "multi_font.h" -#include "jni.h" -#include "jni_util.h" -#include -#include -#include -#include - -/* CanvasType widgets: Frame, Dialog, Window, Panel, Canvas, - * & all lightweights (Component, Container) - */ -#define IsCanvasTypeWidget(w) \ - XtIsSubclass(w, xmDrawingAreaWidgetClass) ||\ - XtIsSubclass(w, vDrawingAreaClass) - - -#include "awt_Component.h" -#include "awt_GraphicsEnv.h" - -#include "awt_AWTEvent.h" -#include "awt_Cursor.h" - -extern struct CursorIDs cursorIDs; -extern struct X11GraphicsConfigIDs x11GraphicsConfigIDs; -extern struct KeyboardFocusManagerIDs keyboardFocusManagerIDs; - -/* fieldIDs for Component fields that may be accessed from C */ -struct ComponentIDs componentIDs; - -/* - * Class: java_awt_Component - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for Component.java - to initialize the fieldIDs for fields that may be accessed from C */ - -JNIEXPORT void JNICALL -Java_java_awt_Component_initIDs -(JNIEnv *env, jclass cls) -{ - jclass keyclass = NULL; - - componentIDs.x = (*env)->GetFieldID(env, cls, "x", "I"); - componentIDs.y = (*env)->GetFieldID(env, cls, "y", "I"); - componentIDs.width = (*env)->GetFieldID(env, cls, "width", "I"); - componentIDs.height = (*env)->GetFieldID(env, cls, "height", "I"); - componentIDs.isPacked = (*env)->GetFieldID(env, cls, "isPacked", "Z"); - componentIDs.peer = - (*env)->GetFieldID(env, cls, "peer", "Ljava/awt/peer/ComponentPeer;"); - componentIDs.background = - (*env)->GetFieldID(env, cls, "background", "Ljava/awt/Color;"); - componentIDs.foreground = - (*env)->GetFieldID(env, cls, "foreground", "Ljava/awt/Color;"); - componentIDs.graphicsConfig = - (*env)->GetFieldID(env, cls, "graphicsConfig", - "Ljava/awt/GraphicsConfiguration;"); - componentIDs.name = - (*env)->GetFieldID(env, cls, "name", "Ljava/lang/String;"); - - /* Use _NoClientCode() methods for trusted methods, so that we - * know that we are not invoking client code on trusted threads - */ - componentIDs.getParent = - (*env)->GetMethodID(env, cls, "getParent_NoClientCode", - "()Ljava/awt/Container;"); - - componentIDs.getLocationOnScreen = - (*env)->GetMethodID(env, cls, "getLocationOnScreen_NoTreeLock", - "()Ljava/awt/Point;"); - - componentIDs.resetGCMID = - (*env)->GetMethodID(env, cls, "resetGC", "()V"); - - keyclass = (*env)->FindClass(env, "java/awt/event/KeyEvent"); - DASSERT (keyclass != NULL); - - componentIDs.isProxyActive = - (*env)->GetFieldID(env, keyclass, "isProxyActive", - "Z"); - - componentIDs.appContext = - (*env)->GetFieldID(env, cls, "appContext", - "Lsun/awt/AppContext;"); - - (*env)->DeleteLocalRef(env, keyclass); - - DASSERT(componentIDs.resetGCMID); -} - -/* fieldIDs for MComponentPeer fields that may be accessed from C */ -struct MComponentPeerIDs mComponentPeerIDs; - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - MComponentPeer.java to initialize the fieldIDs for fields that may - be accessed from C */ - -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_initIDs -(JNIEnv *env, jclass cls) -{ - mComponentPeerIDs.pData = (*env)->GetFieldID(env, cls, "pData", "J"); - mComponentPeerIDs.target = - (*env)->GetFieldID(env, cls, "target", "Ljava/awt/Component;"); - mComponentPeerIDs.jniGlobalRef = - (*env)->GetFieldID(env, cls, "jniGlobalRef", "J"); - mComponentPeerIDs.graphicsConfig = - (*env)->GetFieldID(env, cls, "graphicsConfig", - "Lsun/awt/X11GraphicsConfig;"); - mComponentPeerIDs.drawState = - (*env)->GetFieldID(env, cls, "drawState", "I"); - mComponentPeerIDs.isFocusableMID = - (*env)->GetMethodID(env, cls, "isFocusable", "()Z"); -} - -/* field and method IDs for java.awt.Container. */ -struct ContainerIDs containerIDs; - -/* - * Class: java_awt_Container - * Method: initIDs - * Signature: ()V - */ -/* This function gets called from the static initializer for java.awt.Container - to initialize the fieldIDs for fields that may be accessed from C */ -JNIEXPORT void JNICALL -Java_java_awt_Container_initIDs -(JNIEnv *env, jclass cls) -{ - containerIDs.layoutMgr = - (*env)->GetFieldID(env, cls, "layoutMgr", "Ljava/awt/LayoutManager;"); - - containerIDs.getComponents = - (*env)->GetMethodID(env, cls, "getComponents_NoClientCode", - "()[Ljava/awt/Component;"); - containerIDs.findComponentAt = - (*env)->GetMethodID(env, cls, "findComponentAt", - "(IIZ)Ljava/awt/Component;"); -} - -/* - * Fix for 4090493. When Motif computes indicator size, it uses - * (effectively) XmTextExtents, so the size of the indicator depends - * on the text of the label. The side effect is that if the label - * text is rendered using different platform fonts (for a single Java - * logical font) the display is inconsistent. E.g. for 12pt font - * English label will have a check mark, while Japanese label will - * not, because underlying X11 fonts have different metrics. - * - * The fix is to override Motif calculations for the indicatorSize and - * compute it ourselves based on the font metrics for all the platform - * fonts given Java font maps onto. Every time we set XmNfontList we - * should set XmNindicatorSize as well. - * - * The logic is in awt_computeIndicatorSize that just compute the - * arithmetic mean of platform fonts by now. HIE should take a look - * at this. - */ - -struct changeFontInfo { - XmFontList fontList; /* value to set */ - Boolean isMultiFont; /* only need to compute for multifont */ - struct FontData *fontData; /* need this to compute indicator size */ - Dimension indSize; /* computed once by changeFont */ - - Boolean initialized; - Boolean error; - JNIEnv *env; - jobject fObj; -}; - -static void -changeFont(Widget w, void *info) -{ - struct changeFontInfo *f = (struct changeFontInfo *)info; - WidgetClass widgetClass; - - if (f->error) - return; - - /* Some widgets use no fonts - skip them! */ - /* Also skip the Text widgets, since they each have their own setFont. */ - widgetClass = XtClass(w); - if (widgetClass == xmDrawingAreaWidgetClass || - widgetClass == xmScrollBarWidgetClass || - widgetClass == xmScrolledWindowWidgetClass || - widgetClass == xmComboBoxWidgetClass || - widgetClass == xmTextWidgetClass || - widgetClass == xmTextFieldWidgetClass) - return; - - if (!f->initialized) { - struct FontData *fdata; - char *err; - - f->initialized = TRUE; - - fdata = awtJNI_GetFontData(f->env, f->fObj, &err); - if (fdata == NULL) { - JNU_ThrowInternalError(f->env, err); - f->error = TRUE; - return; - } - - if (awtJNI_IsMultiFont(f->env, f->fObj)) { - f->fontList = awtJNI_GetFontList(f->env, f->fObj); - f->isMultiFont = TRUE; - } else { - f->fontList = XmFontListCreate(fdata->xfont, "labelFont"); - f->isMultiFont = FALSE; - } - - if (f->fontList == NULL) { - JNU_ThrowNullPointerException(f->env, "NullPointerException"); - f->error = TRUE; - return; - } - } - - /* Fix for 4090493. */ - if (f->isMultiFont && XmIsToggleButton(w)) { - Dimension indSize; - - /* Compute indicator size if first time through. Note that - ToggleButtons that are children of menus live in different - hierarchy (MenuComponent), so we don't check for this case - here. In fact, the only time the XmNfontList is set on - MCheckboxMenuItemPeer widget is when it is created. */ - if (f->indSize == 0) - f->indSize = awt_computeIndicatorSize(f->fontData); - - XtVaSetValues(w, XmNfontList, f->fontList, NULL); - if (f->indSize != MOTIF_XmINVALID_DIMENSION) - XtVaSetValues(w, XmNindicatorSize, f->indSize, NULL); - } - else { /* usual case */ - XtVaSetValues(w, XmNfontList, f->fontList, NULL); - } -} - -static void -changeForeground(Widget w, void *fg) -{ - XtVaSetValues(w, XmNforeground, fg, NULL); -} - -static void -changeBackground(Widget w, void *bg) -{ - Pixel fg; - - XtVaGetValues(w, XmNforeground, &fg, NULL); - XmChangeColor(w, (Pixel) bg); - XtVaSetValues(w, XmNforeground, fg, NULL); -} - -// Sets widget's traversalOn property into value 'value' -void setTraversal(Widget w, Boolean value) { - if (w == NULL) { - return; - } - if (XmIsPrimitive(w)) { - XmPrimitiveWidget prim = (XmPrimitiveWidget)w; - prim->primitive.traversal_on = value; - } else - if (XmIsManager(w)) { - XmManagerWidget man = (XmManagerWidget)w; - man->manager.traversal_on = value; - } -} - - -AwtGraphicsConfigDataPtr -getGraphicsConfigFromComponentPeer(JNIEnv *env, jobject this) { - AwtGraphicsConfigDataPtr adata; - jobject gc_object; - - /* GraphicsConfiguration object of MComponentPeer */ - gc_object = (*env)->GetObjectField(env, this, - mComponentPeerIDs.graphicsConfig); - - if (gc_object != NULL) { - adata = (AwtGraphicsConfigDataPtr) - JNU_GetLongFieldAsPtr(env, gc_object, - x11GraphicsConfigIDs.aData); - } else { - adata = getDefaultConfig(DefaultScreen(awt_display)); - } - - return adata; -} - -AwtGraphicsConfigDataPtr -copyGraphicsConfigToPeer(JNIEnv *env, jobject this) { - - jobject component_object, gc_object; - AwtGraphicsConfigDataPtr adata; - - /** - * Copy the GraphicsConfiguration object from Component object to - * MComponentPeer object. - */ - component_object = (*env)->GetObjectField(env, this, - mComponentPeerIDs.target); - /* GraphicsConfiguration object of Component */ - gc_object = (JNU_CallMethodByName(env, NULL, component_object, - "getGraphicsConfiguration", - "()Ljava/awt/GraphicsConfiguration;")).l; - - if (gc_object != NULL) { - /* Set graphicsConfig field of MComponentPeer */ - (*env)->SetObjectField (env, this, - mComponentPeerIDs.graphicsConfig, - gc_object); - adata = (AwtGraphicsConfigDataPtr) - JNU_GetLongFieldAsPtr(env, gc_object, - x11GraphicsConfigIDs.aData); - } else { - /* Component was not constructed with a GraphicsConfiguration - object */ - adata = getDefaultConfig(DefaultScreen(awt_display)); - } - - return adata; -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: getNativeColor - * Signature (Ljava/awt/Color;Ljava/awt/GraphicsConfiguration;)I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MComponentPeer_getNativeColor -(JNIEnv *env, jobject this, jobject color, jobject gc_object) { - AwtGraphicsConfigDataPtr adata; - adata = (AwtGraphicsConfigDataPtr) JNU_GetLongFieldAsPtr(env, gc_object, - x11GraphicsConfigIDs.aData); - return awtJNI_GetColorForVis(env, color, adata); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pInitialize - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pInitialize -(JNIEnv *env, jobject this) -{ - struct ComponentData *cdata; - Widget parent; - jobject target; - jobject globalRef; - EventMask xtMask; - jlong awtMask = (jlong) 0; - AwtGraphicsConfigDataPtr adata; - Boolean initialTraversal = False; - - globalRef = (jobject) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.jniGlobalRef); - - adata = copyGraphicsConfigToPeer(env, this); - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (JNU_IsNull(env, cdata) || (cdata == NULL)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - /* Allow FileDialog to have its own traversal policy because - * it doesn't interfer with our. - */ - if (XtIsSubclass(cdata->widget, xmFileSelectionBoxWidgetClass)) { - initialTraversal = True; - } - XtVaSetValues(cdata->widget, - XmNx, (*env)->GetIntField(env, target, componentIDs.x), - XmNy, (*env)->GetIntField(env, target, componentIDs.y), - XmNvisual, adata->awt_visInfo.visual, - XmNscreen, ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen), - /** - * From now we keep all but the focus owner widget unable - * to receive focus. This will prevent Motif from unexpected - * focus transfers. - */ - XmNtraversalOn, initialTraversal, - NULL); - - - /* For all but canvas-style components, pre-process - * mouse and keyboard events (which means posting them - * to the Java EventQueue before dispatching them to Xt). - * For canvas-style components ONLY pre-process mouse events - * because the input-method currently relies on key events - * being processed by Xt first. - */ - awtMask = java_awt_AWTEvent_MOUSE_EVENT_MASK | - java_awt_AWTEvent_MOUSE_MOTION_EVENT_MASK; - xtMask = ExposureMask | FocusChangeMask; - - if (!IsCanvasTypeWidget(cdata->widget)) { - awtMask |= java_awt_AWTEvent_KEY_EVENT_MASK; - } else { - xtMask |= (KeyPressMask | KeyReleaseMask); - } - XtAddEventHandler(cdata->widget, xtMask, - True, awt_canvas_event_handler, globalRef); - - awt_addWidget(cdata->widget, cdata->widget, globalRef, awtMask); - - cdata->repaintPending = RepaintPending_NONE; - - AWT_UNLOCK(); -} - -/** - * Updates stacking order of X windows according to the order of children widgets in - * parent widget - */ -void restack(Widget parent) { - WidgetList children; - int32_t num_children; - Window *windows; - int32_t num_windows = 0; - int32_t i; - XtVaGetValues(parent, - XmNnumChildren, &num_children, - XmNchildren, &children, - NULL); - - windows = (Window *) XtMalloc(num_children * sizeof(Window)); - for (i = 0; i < num_children; i++) { - if (XtIsRealized(children[i])) { - windows[num_windows++] = XtWindow(children[i]); - } - } - XRestackWindows(awt_display, windows, num_windows); - XtFree((char *) windows); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pShow - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pShow -(JNIEnv *env, jobject this) -{ - struct ComponentData *cdata; - - AWT_LOCK(); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - awt_util_show(cdata->widget); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pHide - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pHide -(JNIEnv *env, jobject this) -{ - struct ComponentData *cdata; - - AWT_LOCK(); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - awt_util_hide(cdata->widget); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pEnable - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pEnable -(JNIEnv *env, jobject this) -{ - struct ComponentData *cdata; - - AWT_LOCK(); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - awt_util_enable(cdata->widget); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pDisable - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pDisable -(JNIEnv *env, jobject this) -{ - struct ComponentData *cdata; - - AWT_LOCK(); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - awt_util_disable(cdata->widget); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pReshape - * Signature: (IIII)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pReshape -(JNIEnv *env, jobject this, jint x, jint y, jint w, jint h) -{ - struct ComponentData *cdata; - jint drawState; - - AWT_LOCK(); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - /* Set the draw state */ - drawState = (*env)->GetIntField(env, this, - mComponentPeerIDs.drawState); - (*env)->SetIntField(env, this, - mComponentPeerIDs.drawState, - drawState | JAWT_LOCK_BOUNDS_CHANGED | JAWT_LOCK_CLIP_CHANGED); - awt_util_reshape(cdata->widget, x, y, w, h); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pDispose - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pDispose -(JNIEnv *env, jobject this) -{ - struct ComponentData *cdata; - - AWT_LOCK(); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - XtUnmanageChild(cdata->widget); - - awt_delWidget(cdata->widget); - awt_util_consumeAllXEvents(cdata->widget); - awt_util_cleanupBeforeDestroyWidget(cdata->widget); - XtDestroyWidget(cdata->widget); - - free((void *) cdata); - (*env)->SetLongField(env,this,mComponentPeerIDs.pData, (int64_t) 0); - - awtJNI_DeleteGlobalRef(env, this); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pMakeCursorVisible - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pMakeCursorVisible -(JNIEnv *env, jobject this) -{ - struct ComponentData *cdata; - - AWT_LOCK(); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - // need to change, may not be needed - // awt_util_setCursor(cdata->widget, cdata->cursor); - - AWT_FLUSH_UNLOCK(); -} - - -/* - * Call with AWT_LOCK held. - */ -static jobject -MComponentPeer_doGetLocationOnScreen(JNIEnv *env, jobject this) -{ - jobject point = NULL; - struct ComponentData *cdata; - int32_t x = 0, y = 0; - Screen *widget_screen = NULL; - Window child_ignored; - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return NULL; - } - if (!XtIsRealized(cdata->widget)) { - JNU_ThrowInternalError(env, "widget not visible on screen"); - return NULL; - } - - /* Translate the component to the screen coordinate system */ - XtVaGetValues(cdata->widget, XmNscreen, &widget_screen, NULL); - XTranslateCoordinates(awt_display, XtWindow(cdata->widget), - XRootWindowOfScreen(widget_screen), - 0, 0, &x, &y, - &child_ignored); - - point = JNU_NewObjectByName(env, "java/awt/Point", "(II)V", - (jint)x, (jint)y); - if (((*env)->ExceptionOccurred(env)) || JNU_IsNull(env, point)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return NULL; - } - - return point; -} - - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pGetLocationOnScreen - * Signature: ()Ljava/awt/Point; - */ -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen(JNIEnv *env, - jobject this) -{ - jobject point; - - AWT_LOCK(); - point = MComponentPeer_doGetLocationOnScreen(env, this); - AWT_UNLOCK(); - return point; -} - - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pGetLocationOnScreen - * Signature: (Ljava/awt/Window;Lsun/awt/motif/MWindowPeer;)Ljava/awt/Point; - */ -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_MComponentPeer_pGetLocationOnScreen2( - JNIEnv *env, jobject this, jobject wtarget, jobject wpeer) -{ - jobject point; - struct ComponentData *cdata; - struct FrameData *wdata; - Screen *widget_screen = NULL; - Window child_ignored; - int32_t x = 0, y = 0; - - AWT_LOCK(); - - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, wpeer, mComponentPeerIDs.pData); - - if (wdata == NULL || wdata->winData.comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return NULL; - } - if (!XtIsRealized(wdata->winData.comp.widget)) { - JNU_ThrowInternalError(env, "widget not visible on screen"); - AWT_UNLOCK(); - return NULL; - } - - /* - * Translate directly if the parent window is already adopted by WM. - */ - if (wdata->configure_seen) { - point = MComponentPeer_doGetLocationOnScreen(env, this); - AWT_UNLOCK(); - return point; - } - - /* - * We are called while the parent window is still not adopted by - * WM (but may already be in the process of being reparented). - * Translate to the parent and add parent target's (x,y) to avoid - * racing with WM shuffling us into the final position. - */ - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (cdata == &wdata->winData.comp) { /* called for the window itself */ - x = y = 0; - } - else { - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return NULL; - } - if (!XtIsRealized(cdata->widget)) { - JNU_ThrowInternalError(env, "widget not visible on screen"); - AWT_UNLOCK(); - return NULL; - } - - /* Translate to the outer canvas coordinate system first */ - XtVaGetValues(cdata->widget, XmNscreen, &widget_screen, NULL); - XTranslateCoordinates(awt_display, XtWindow(cdata->widget), - XtWindow(wdata->winData.comp.widget), - 0, 0, &x, &y, - &child_ignored); - } - - x += (*env)->GetIntField(env, wtarget, componentIDs.x); - y += (*env)->GetIntField(env, wtarget, componentIDs.y); - - point = JNU_NewObjectByName(env, "java/awt/Point", "(II)V", - (jint)x, (jint)y); - if (((*env)->ExceptionOccurred(env)) || JNU_IsNull(env, point)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return NULL; - } - - AWT_UNLOCK(); - return point; -} - - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: getParent_NoClientCode - * Signature: (Ljava/awt/Component)Ljava/awt/Container; - * - * NOTE: This method may be called by privileged threads. - * DO NOT INVOKE CLIENT CODE ON THIS THREAD! - */ -JNIEXPORT jobject JNICALL Java_sun_awt_motif_MComponentPeer_getParent_1NoClientCode -(JNIEnv *env, jclass thisClass, jobject component) -{ - jobject parent = NULL; - - /* getParent is actually getParent_NoClientCode() */ - parent = (*env)->CallObjectMethod(env,component,componentIDs.getParent); - DASSERT(!((*env)->ExceptionOccurred(env))); - return parent; -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: getComponents_NoClientCode - * Signature: (Ljava/awt/Container)[Ljava/awt/Component; - * REMIND: Signature is incorrect for returned array value - * - * NOTE: This method may be called by privileged threads. - * DO NOT INVOKE CLIENT CODE ON THIS THREAD! - */ -JNIEXPORT jobjectArray JNICALL Java_sun_awt_motif_MComponentPeer_getComponents_1NoClientCode -(JNIEnv *env, jclass thisClass, jobject container) -{ - jobjectArray contents = NULL; - contents = (*env)->CallObjectMethod( - env, container, containerIDs.getComponents); - DASSERT(!((*env)->ExceptionOccurred(env))); - return contents; -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pSetForeground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pSetForeground -(JNIEnv *env, jobject this, jobject c) -{ - struct ComponentData *bdata; - Pixel color; - AwtGraphicsConfigDataPtr adata; - - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (bdata == NULL || bdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - adata = getGraphicsConfigFromComponentPeer(env, this); - - color = (Pixel) awtJNI_GetColorForVis (env, c, adata); - XtVaSetValues(bdata->widget, XmNforeground, color, NULL); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pSetBackground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pSetBackground -(JNIEnv *env, jobject this, jobject c) -{ - struct ComponentData *bdata; - Pixel color; - Pixel fg; - AwtGraphicsConfigDataPtr adata; - - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (bdata == NULL || bdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - adata = getGraphicsConfigFromComponentPeer(env, this); - - color = (Pixel) awtJNI_GetColorForVis (env, c, adata); - XtVaGetValues(bdata->widget, XmNforeground, &fg, NULL); - XmChangeColor(bdata->widget, color); - XtVaSetValues(bdata->widget, XmNforeground, fg, NULL); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pSetScrollbarBackground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pSetScrollbarBackground -(JNIEnv *env, jobject this, jobject c) -{ - struct ComponentData *bdata; - Pixel color; - Pixel fg; - int32_t i; - WidgetList wlist; - Cardinal wlen = 0; - - /* This method propagates the specified background color to the scrollbars in the composite widget. - * Used to set background scrollbar color in List, TextArea, ScrollPane to its parent. - */ - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (bdata == NULL || bdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (!XtIsComposite(bdata->widget)) { - AWT_UNLOCK(); - return; - } - color = (Pixel) awtJNI_GetColor(env, c); - - XtVaGetValues(bdata->widget, - XmNchildren, &wlist, - XmNnumChildren, &wlen, - NULL); - if (wlen > 0) { /* this test doesn't make much sense, since wlen - is a Cardinal and cardinal is unsigned int... */ - for (i=0; i < wlen; i++) { - if (XtIsSubclass(wlist[i], xmScrollBarWidgetClass)) { - XtVaGetValues(wlist[i], XmNforeground, &fg, NULL); - XmChangeColor(wlist[i], color); - XtVaSetValues(wlist[i], XmNforeground, fg, NULL); - } - } - XtVaGetValues(bdata->widget, XmNforeground, &fg, NULL); - XmChangeColor(bdata->widget, color); - XtVaSetValues(bdata->widget, XmNforeground, fg, NULL); - } - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pSetInnerForeground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pSetInnerForeground -(JNIEnv *env, jobject this, jobject c) -{ - struct ComponentData *bdata; - Pixel color; - - /* This method propagates the specified foreground color to all its children. - * It is called to set foreground color in List, TextArea, ScrollPane. - */ - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (bdata == NULL || bdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - color = awtJNI_GetColor(env, c); - awt_util_mapChildren(bdata->widget, changeForeground, 1, (void *) color); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pSetFont - * Signature: (Ljava/awt/Font;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pSetFont -(JNIEnv *env, jobject this, jobject f) -{ - struct ComponentData *cdata; - - struct changeFontInfo finfo = { NULL, FALSE, NULL, 0, - FALSE, FALSE, NULL, NULL }; - - if (JNU_IsNull(env, f)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - finfo.env = env; - finfo.fObj = f; - awt_util_mapChildren(cdata->widget, changeFont, 1, (void *)&finfo); - if (!finfo.error && finfo.fontList != NULL) { - XmFontListFree(finfo.fontList); - } - - AWT_FLUSH_UNLOCK(); -} /* MComponentPeer.pSetFont() */ - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: setTargetBackground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_setTargetBackground -(JNIEnv *env, jobject this, jobject c) -{ - jobject target = NULL; - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - return; - } - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - (*env)->SetObjectField(env, target, componentIDs.background, c); - (*env)->DeleteLocalRef(env, target); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: pSetCursor - * Signature: (Ljava/awt/Cursor;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_pSetCursor -(JNIEnv *env, jobject this, jobject cursor) -{ - Cursor xcursor; - struct ComponentData *cdata; - - AWT_LOCK(); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL || JNU_IsNull(env, cursor)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - awt_util_setCursor(cdata->widget, getCursor(env, cursor)); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: nativeHandleEvent - * Signature: (Ljava/awt/AWTEvent;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_nativeHandleEvent -(JNIEnv *env, jobject this, jobject event) -{ - extern void awt_modify_KeyEvent(JNIEnv *env, XEvent * xevent, jobject jevent); - jbyteArray array; - XEvent *xevent; - Widget widget = NULL; - Boolean consumed; - - if (JNU_IsNull(env, event)) { - return; - } - AWT_LOCK(); - - consumed = (*env)->GetBooleanField(env, event, awtEventIDs.consumed); - - /* - * Fix for bug 4280561 - * - * If a menu is up, we must dispatch all XEvents, to allow - * mouse grabs to be released and prevent server hangs. - */ - consumed = consumed && !awt_util_focusIsOnMenu(awt_display); - - if (consumed) { - AWT_UNLOCK(); - return; - } - - array = (jbyteArray)(*env)->GetObjectField(env, event, awtEventIDs.bdata); - if (array == NULL) { - AWT_UNLOCK(); - return; - } - - xevent = (XEvent *)(*env)->GetByteArrayElements(env, array, NULL); - if (xevent == NULL) { - AWT_UNLOCK(); - return; - } - - switch ((*env)->GetIntField(env, event, awtEventIDs.id)) { - case java_awt_event_KeyEvent_KEY_RELEASED: - case java_awt_event_KeyEvent_KEY_PRESSED: - awt_modify_KeyEvent(env, xevent, event); - if ((*env)->GetBooleanField(env, event, componentIDs.isProxyActive) == JNI_TRUE) { - xevent->xany.send_event = SPECIAL_KEY_EVENT; - } - break; - default: - break; - } - widget = XtWindowToWidget(awt_display, xevent->xany.window); - - if (!((widget == NULL) || (!XtIsObject(widget)) || - (widget->core.being_destroyed))) { - /* Queue the event to be handled by the AWT-Motif thread */ - if (!IsCanvasTypeWidget(widget)) { - awt_put_back_event(env, xevent); - } - } - - (*env)->ReleaseByteArrayElements(env, array, (jbyte *)xevent, JNI_ABORT); - (*env)->DeleteLocalRef(env, array); - - AWT_UNLOCK(); - return; -} - -// Returns the widget from parent's hierarchy which should be -// used for focus operations. This widget is stored in WidgetInfo -// structure and should be prepared by the appropriate component -// type constructor -Widget getFocusWidget(Widget parent) { - struct WidgetInfo * winfo = NULL; - DASSERT(parent != NULL); - if (parent == NULL) { - return NULL; - } - winfo = findWidgetInfo(parent); - if (winfo == NULL) { - return NULL; - } - return winfo->widget; -} - - -// Returns value of widget's traversalOn property -Boolean getTraversal(Widget w) { - if (w == NULL) { - return False; - } - if (XmIsPrimitive(w)) { - XmPrimitiveWidget prim = (XmPrimitiveWidget)w; - return prim->primitive.traversal_on; - } - if (XmIsManager(w)) { - XmManagerWidget man = (XmManagerWidget)w; - return man->manager.traversal_on; - } - return False; -} - - -void processTree(Widget from, Widget to, Boolean action) { -// Workhorse function that makes sure that the only widgets -// which have traversalOn == true are the ones on the path from -// shell to current focus widget. Function uses two widgets - -// the one which is supposed to have focus currently(from) and -// the one which will receive focus(to). Function disables and -// enables the appropriate widgets so 'to' can become focus owner. - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - int32_t count_from = 0, count_to = 0; - Widget parent_from = NULL, parent_to = NULL; - Widget * parents_from = NULL, * parents_to = NULL; - int32_t index = 0; - - // Count amount of parents up the tree from widget - parent_from = from; - while (parent_from != NULL) { - parent_from = XtParent(parent_from); - count_from++; - } - parent_to = to; - while (parent_to != NULL) { - parent_to = XtParent(parent_to); - count_to++; - } - - // Store all the parents in the list. Both list wittingly - // have common parts starting from the beginning. We need - // to find the end of this common part. - parents_from = (Widget*)malloc(count_from*sizeof(Widget*)); - parents_to = (Widget*)malloc(count_to*sizeof(Widget*)); - parent_from = from; - index = count_from; - while (parent_from != NULL) { - parents_from[index-1] = parent_from; - parent_from = XtParent(parent_from); - index--; - } - parent_to = to; - index = count_to; - while (parent_to != NULL) { - parents_to[index-1] = parent_to; - parent_to = XtParent(parent_to); - index--; - } - - // Process parents list. Find common part which is usually doesn't - // require changes. At the exit of the cycle index will point - // to the first widget which requeires the change. - - if (from != NULL && to != NULL) { - do { - if (index >= count_from-1 || index >= count_to-1) { - break; - } - if (parents_from[index] == parents_to[index]) - { - if (XtIsShell(parents_from[index])) { - index++; - continue; - } - if (action) { - if (getTraversal(parents_from[index])) { - index++; - } else { - break; - } - } else { - index++; - } - } else { - break; - } - } while (True); - } - - - if (action) { // enable the tree starting from uncommon part till 'to' - if (to != NULL) { - while (index < count_to - 1) { - if (!getTraversal(parents_to[index])) { - XtVaSetValues(parents_to[index], XmNtraversalOn, True, NULL); - } - index++; - } - XtVaSetValues(to, XmNtraversalOn, True, NULL); - } - } else if (from != NULL) { - // disable the tree starting from uncommon part to 'from' - if (parents_from[index] == parents_to[index]) { - if (index == count_from - 1) { - // 'from' is one of the parents of 'to' - no need - // to disable 'from' - goto skip_disable; - } - index++; - } - while (index < count_from - 1) { - if (!XmIsGadget(parents_from[index]) && !XtIsShell(parents_from[index])) { - setTraversal(parents_from[index], False); - } - index++; - } - if (!XmIsGadget(from)) { - setTraversal(parents_from[index], False); - } - } - skip_disable: - free(parents_from); - free(parents_to); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: requestFocus - * Signature: (Ljava/awt/Component;ZZJ)Z - */ -JNIEXPORT jboolean JNICALL Java_sun_awt_motif_MComponentPeer__1requestFocus -(JNIEnv *env, jobject this, jobject lightweightChild, jboolean temporary, - jboolean focusedWindowChangeAllowed, jlong time, jobject cause) -{ - struct ComponentData *bdata; - Boolean result; - jobject target; - jint retval; - Widget currentOwner = NULL; - jobject curPeer = NULL; - Widget shell; - Widget widgetToFocus = NULL; - - AWT_LOCK(); - - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (bdata == NULL || bdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return JNI_FALSE; - } - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - AWT_UNLOCK(); - return JNI_FALSE; - } - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - /* Don't need to free target explicitly. That will happen automatically - when this function returns. */ - - if (target == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return JNI_FALSE; - } - - /* The X11 implementation does not permit cross-Window focus transfers, - so always pass JNI_FALSE for that parameter. */ - retval = (*env)->CallStaticIntMethod - (env, keyboardFocusManagerIDs.keyboardFocusManagerCls, - keyboardFocusManagerIDs.shouldNativelyFocusHeavyweightMID, - target, lightweightChild, temporary, JNI_FALSE, time, cause); - - if (retval == java_awt_KeyboardFocusManager_SNFH_SUCCESS_HANDLED) { - AWT_UNLOCK(); - (*env)->DeleteLocalRef(env, target); - return JNI_TRUE; - } - if (retval == java_awt_KeyboardFocusManager_SNFH_FAILURE) { - AWT_UNLOCK(); - (*env)->DeleteLocalRef(env, target); - return JNI_FALSE; - } - - DASSERT(retval == java_awt_KeyboardFocusManager_SNFH_SUCCESS_PROCEED); - - shell = getShellWidget(bdata->widget); - currentOwner = XmGetFocusWidget(shell); - - widgetToFocus = getFocusWidget(bdata->widget); - - globalClearFocusPath(shell); - - // Prepare widgets tree - processTree(currentOwner, widgetToFocus, False); - processTree(currentOwner, widgetToFocus, True); - - /* - Fix for bug 4157017: replace XmProcessTraversal with - XtSetKeyboardFocus because XmProcessTraversal does not allow - focus to go to non-visible widgets. - - (There is a corresponding change to awt_MToolkit.c:dispatchToWidget) - - I found a last minute problem with this fix i.e. it broke the test - case for bug 4053856. XmProcessTraversal does something else (that - XtSetKeyboardFocus does not do) that stops this test case from - failing. So, as I do not have time to investigate, and having - both XmProcessTraversal and XtSetKeyboardFocus fixes 4157017 and - 4053856 and should be harmless (reviewer agreed), we have both - below - XmProcessTraversal AND XtSetKeyboardFocus. - */ - result = XmProcessTraversal(widgetToFocus, XmTRAVERSE_CURRENT); - if (!result) - { - Widget w = widgetToFocus; - - shell = getShellWidget(w); - XtSetKeyboardFocus(shell, w); - } - /* end 4157017 */ - - // Because Motif focus callbacks are disabled we need to generate - // the required events by ourselves. - // First, check if the current focused widget has the entry in focus - // list. If not, add it because it is required for further processing - if (currentOwner != NULL) { - jobject last = NULL; - curPeer = findPeer(¤tOwner); - if (curPeer == NULL) { - currentOwner = findTopLevelByShell(currentOwner); - if (currentOwner != NULL) { - curPeer = findPeer(¤tOwner); - } - } - if (curPeer != NULL) { - curPeer = (*env)->GetObjectField(env, curPeer, mComponentPeerIDs.target); - if (focusList == NULL) { - awt_canvas_addToFocusListWithDuplicates(curPeer, JNI_TRUE); - } else { - last = (*env)->NewLocalRef(env, focusList->requestor); - if (!(*env)->IsSameObject(env, last, curPeer)) { - awt_canvas_addToFocusList(curPeer); - } - if (!JNU_IsNull(env, last)) { - (*env)->DeleteLocalRef(env, last); - } - } - (*env)->DeleteLocalRef(env, curPeer); - } - } - awt_canvas_addToFocusList(target); - - // If new and current focus owners are the same do not generate FOCUS_LOST - // event because we don't expect it, but generate FOCUS_GAIN because we - // wait for it. - if ( currentOwner != NULL && !JNU_IsNull(env, curPeer) && - !(*env)->IsSameObject(env, curPeer, target)) { - callFocusHandler(currentOwner, FocusOut, cause); - } - callFocusHandler(widgetToFocus, FocusIn, cause); - (*env)->DeleteLocalRef(env, target); - - AWT_FLUSH_UNLOCK(); - return JNI_TRUE; -} - -Dimension -awt_computeIndicatorSize(struct FontData *fdata) -{ - int32_t height; - int32_t acc; - int32_t i; - - if (fdata == (struct FontData *) NULL) - return MOTIF_XmINVALID_DIMENSION; - - /* - * If Java font maps into single platform font - there's no - * problem. Let Motif use its usual calculations in this case. - */ - if (fdata->charset_num == 1) - return MOTIF_XmINVALID_DIMENSION; - - acc = 0; - for (i = 0; i < fdata->charset_num; ++i) { - XFontStruct *xfont = fdata->flist[i].xfont; - acc += xfont->ascent + xfont->descent; - } - - height = acc / fdata->charset_num; - if (height < MOTIF_XmDEFAULT_INDICATOR_DIM) - height = MOTIF_XmDEFAULT_INDICATOR_DIM; - - return height; -} - -Dimension -awt_adjustIndicatorSizeForMenu(Dimension indSize) -{ - if (indSize == 0 || indSize == MOTIF_XmINVALID_DIMENSION) - return MOTIF_XmINVALID_DIMENSION; /* let motif do the job */ - - /* Indicators in menus are smaller. - 2/3 is a magic number from Motif internals. */ - indSize = indSize * 2 / 3; - if (indSize < MOTIF_XmDEFAULT_INDICATOR_DIM) - indSize = MOTIF_XmDEFAULT_INDICATOR_DIM; - - return indSize; -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: getWindow - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_sun_awt_motif_MComponentPeer_getWindow -(JNIEnv *env, jobject this, jlong pData) -{ - jlong ret = (jlong)0; - struct ComponentData* cdata; - cdata = (struct ComponentData*)pData; - AWT_LOCK(); - ret = (jlong)XtWindow(cdata->widget); - AWT_FLUSH_UNLOCK(); - return ret; -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: restore_Focus - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_restoreFocus -(JNIEnv *env, jobject this) -{ - jobject focus_peer; - AWT_LOCK(); - - focus_peer = awt_canvas_getFocusOwnerPeer(); - if (!JNU_IsNull(env, focus_peer)) { - struct ComponentData *bdata; - Boolean result; - - bdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, focus_peer, mComponentPeerIDs.pData); - if (bdata != NULL) { - Widget widgetToFocus = getFocusWidget(bdata->widget); - result = XmProcessTraversal(widgetToFocus, XmTRAVERSE_CURRENT); - if (!result) - { - XtSetKeyboardFocus(getShellWidget(widgetToFocus), widgetToFocus); - } - } - } - (*env)->DeleteLocalRef(env, focus_peer); - - AWT_UNLOCK(); -} - -JNIEXPORT jboolean JNICALL -Java_sun_awt_motif_MComponentPeer_processSynchronousLightweightTransfer( - JNIEnv * env, jclass cls, jobject heavyweight, jobject descendant, - jboolean temporary, jboolean focusedWindowChangeAllowed, jlong time) -{ - return (*env)->CallStaticBooleanMethod(env, keyboardFocusManagerIDs.keyboardFocusManagerCls, - keyboardFocusManagerIDs.processSynchronousTransferMID, - heavyweight, descendant, temporary, - focusedWindowChangeAllowed, time); -} -/* - * Class: sun_awt_motif_MComponentPeer - * Method: getNativeFocusedWindow - * Signature: ()Ljava/awt/Window; - */ -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_MComponentPeer_getNativeFocusedWindow -(JNIEnv *env, jclass cls) -{ - jobject l_peer; - - AWT_LOCK(); - l_peer = awt_canvas_getFocusedWindowPeer(); - AWT_UNLOCK(); - - return (l_peer != NULL) - ? (*env)->GetObjectField(env, l_peer, mComponentPeerIDs.target) - : NULL; -} - -/** - * Makes sure that child has correct index inside parent - * Note: there was a short time when we were counting index in the - * opposite order when it seemed that X and Java z-order notions - * are different. Now we know they are not: last component is - * painted first and appears below all other components with - * smaller indices. - */ -void ensureIndex(Widget parent, Widget child, int index) { - WidgetList children; - int32_t num_children; - int32_t i; - - if (parent == NULL) { - return; - } - if (child == NULL) { - return; - } - XtVaGetValues(parent, - XmNnumChildren, &num_children, - XmNchildren, &children, - NULL); - if (index < 0 || index >= num_children) { - return; - } - if (children[index] != child) { - for (i = 0; i < num_children; i++) { - if (children[i] == child) { - break; - } - } - if (i < num_children) { - Widget temp = children[index]; - children[index] = child; - children[i] = temp; - } - } -} - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MPanelPeer_pEnsureIndex(JNIEnv * env, jobject this, jobject child, jint index) { - struct ComponentData *cdata; - Widget w_parent, w_child; - AWT_LOCK(); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - w_parent = cdata->widget; - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, child, mComponentPeerIDs.pData); - w_child = cdata->widget; - ensureIndex(w_parent, w_child, index); - AWT_UNLOCK(); -} - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MPanelPeer_pRestack(JNIEnv * env, jobject this) { - struct ComponentData *cdata; - Widget w_parent; - AWT_LOCK(); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - w_parent = cdata->widget; - restack(w_parent); - AWT_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Cursor.c b/jdk/src/solaris/native/sun/awt/awt_Cursor.c deleted file mode 100644 index 0555c854f58..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Cursor.c +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include -#include "awt_Component.h" -#include "awt_Cursor.h" -#include "java_awt_Cursor.h" -#include - -#include "jni.h" -#include "jni_util.h" - -/* fieldIDs for Cursor fields that may be accessed from C */ -struct CursorIDs cursorIDs; -extern struct MComponentPeerIDs mComponentPeerIDs; - -static jweak curComp = 0; - -/* - * Class: java_awt_Cursor - * Method: initIDs - * Signature: ()V - */ -/* - * This function gets called from the static initializer for Cursor.java - * to initialize the fieldIDs for fields that may be accessed from C - */ -JNIEXPORT void JNICALL -Java_java_awt_Cursor_initIDs(JNIEnv *env, jclass cls) -{ - cursorIDs.type = (*env)->GetFieldID(env, cls, "type", "I"); - cursorIDs.mSetPData = (*env)->GetMethodID(env, cls, "setPData", "(J)V"); - cursorIDs.pData = (*env)->GetFieldID(env, cls, "pData", "J"); -} - -/* - * A utility to retrieve cursor from java.awt.Cursor - * Create and save the cursor first if it is not yet - */ -Cursor getCursor(JNIEnv *env, jobject jCur) -{ - int32_t cursorType = 0; - Cursor xcursor; - - xcursor = (Cursor)(*env)->GetLongField(env, jCur, cursorIDs.pData); - - if (xcursor != None) { - return xcursor; - } - - cursorType = (*env)->GetIntField(env, jCur, cursorIDs.type); - - DASSERT(cursorType != java_awt_Cursor_CUSTOM_CURSOR); - - switch (cursorType) { - case java_awt_Cursor_DEFAULT_CURSOR: - cursorType = XC_left_ptr; - break; - case java_awt_Cursor_CROSSHAIR_CURSOR: - cursorType = XC_crosshair; - break; - case java_awt_Cursor_TEXT_CURSOR: - cursorType = XC_xterm; - break; - case java_awt_Cursor_WAIT_CURSOR: - cursorType = XC_watch; - break; - case java_awt_Cursor_SW_RESIZE_CURSOR: - cursorType = XC_bottom_left_corner; - break; - case java_awt_Cursor_NW_RESIZE_CURSOR: - cursorType = XC_top_left_corner; - break; - case java_awt_Cursor_SE_RESIZE_CURSOR: - cursorType = XC_bottom_right_corner; - break; - case java_awt_Cursor_NE_RESIZE_CURSOR: - cursorType = XC_top_right_corner; - break; - case java_awt_Cursor_S_RESIZE_CURSOR: - cursorType = XC_bottom_side; - break; - case java_awt_Cursor_N_RESIZE_CURSOR: - cursorType = XC_top_side; - break; - case java_awt_Cursor_W_RESIZE_CURSOR: - cursorType = XC_left_side; - break; - case java_awt_Cursor_E_RESIZE_CURSOR: - cursorType = XC_right_side; - break; - case java_awt_Cursor_HAND_CURSOR: - cursorType = XC_hand2; - break; - case java_awt_Cursor_MOVE_CURSOR: - cursorType = XC_fleur; - break; - } - xcursor = XCreateFontCursor(awt_display, cursorType); - - (*env)->CallVoidMethod(env, jCur, cursorIDs.mSetPData, xcursor); - return xcursor; -} - -/* - * Class: java_awt_Cursor - * Method: finalizeImpl - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_java_awt_Cursor_finalizeImpl(JNIEnv *env, jclass clazz, jlong pData) -{ - Cursor xcursor; - - xcursor = (Cursor)pData; - if (xcursor != None) { - AWT_LOCK(); - XFreeCursor(awt_display, xcursor); - AWT_UNLOCK(); - } -} - -/* - * normal replace : CACHE_UDPATE => update curComp and updateCursor - * not replace : UPDATE_ONLY => intact curComp but updateCursor - * only replace : CACHE_ONLY => update curComp only, not updateCursor - * - * This function should only be called under AWT_LOCK(). Otherwise - * multithreaded access can corrupt the value of curComp variable. - */ -void updateCursor(XPointer client_data, int32_t replace) { - - static jclass globalCursorManagerClass = NULL; - static jmethodID updateCursorID = NULL; - - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject peer = (jobject) client_data; - jobject target; - - if ((*env)->PushLocalFrame(env, 16) < 0) - return; - - target = (*env)->GetObjectField(env, peer, mComponentPeerIDs.target); - if (replace != UPDATE_ONLY) { - if (!JNU_IsNull(env, curComp)) { - (*env)->DeleteWeakGlobalRef(env, curComp); - } - curComp = (*env)->NewWeakGlobalRef(env, target); - if (replace == CACHE_ONLY) { - (*env)->PopLocalFrame(env, 0); - return; - } - } - - /* Initialize our java identifiers once. Checking before locking - * is a huge performance win. - */ - if (globalCursorManagerClass == NULL) { - jobject sysClass = (*env)->FindClass(env, "sun/awt/motif/MGlobalCursorManager"); - if (sysClass != NULL) { - /* Make this class 'sticky', we don't want it GC'd */ - globalCursorManagerClass = (*env)->NewGlobalRef(env, sysClass); - - updateCursorID = (*env)->GetStaticMethodID(env, - globalCursorManagerClass, - "nativeUpdateCursor", - "(Ljava/awt/Component;)V" - ); - } - if (JNU_IsNull(env, globalCursorManagerClass) || updateCursorID == NULL) { - JNU_ThrowClassNotFoundException(env, "sun/awt/motif/MGlobalCursorManager"); - (*env)->PopLocalFrame(env, 0); - return; - } - } /* globalCursorManagerClass == NULL*/ - - (*env)->CallStaticVoidMethod(env, globalCursorManagerClass, - updateCursorID, target); - DASSERT(!((*env)->ExceptionOccurred(env))); - (*env)->PopLocalFrame(env, 0); -} - -/* - * Only call this function under AWT_LOCK(). Otherwise multithreaded - * access can corrupt the value of curComp variable. - */ -jobject getCurComponent() { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - return (*env)->NewLocalRef(env, curComp); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_DataTransferer.c b/jdk/src/solaris/native/sun/awt/awt_DataTransferer.c deleted file mode 100644 index 4944f5ef1c1..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_DataTransferer.c +++ /dev/null @@ -1,1068 +0,0 @@ -/* - * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include -#include - -#include - -#include -#include - -#include "sun_awt_datatransfer_DataTransferer.h" -#include "sun_awt_motif_MDataTransferer.h" - -#include "awt_XmDnD.h" -#include "awt_DataTransferer.h" - -static jclass string; - -XContext awt_convertDataContext = 0; - -Atom XA_TARGETS; - -extern struct X11GraphicsConfigIDs x11GraphicsConfigIDs; - -typedef enum { - SelectionPending, - SelectionSuccess, - SelectionFailure, - SelectionOwnerTimedOut -} SelectionStatus; - -/* Should only be accessed by the current owner of AWT_LOCK. */ -static SelectionStatus globalSelectionStatus = SelectionPending; - -static SelectionStatus get_selection_status() { - return globalSelectionStatus; -} - -static void set_selection_status(SelectionStatus status) { - globalSelectionStatus = status; -} - -static void -selection_request_filter(Widget widget, XtPointer closure, XEvent *event, - Boolean *cont) { - if (event->type == SelectionRequest) { - Window awt_root_window = XtWindow(awt_root_shell); - Atom selection = event->xselectionrequest.selection; - Window owner = XGetSelectionOwner(event->xany.display, selection); - - if (owner != awt_root_window) { - XSelectionEvent notify; - - notify.type = SelectionNotify; - notify.display = event->xselectionrequest.display; - notify.requestor = event->xselectionrequest.requestor; - notify.selection = event->xselectionrequest.selection; - notify.time = event->xselectionrequest.time; - notify.target = event->xselectionrequest.target; - notify.property = None; - - XSendEvent(notify.display, notify.requestor, False, - (unsigned long)0, (XEvent*)¬ify); - *cont = False; - } - } -} - -/** - * global function to initialize this client as a Dynamic-only app. - * - * gets called once during toolkit initialization. - */ - -void awt_initialize_DataTransferer() { - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jclass stringClassLocal = NULL; - - DASSERT(string == NULL); - - stringClassLocal = (*env)->FindClass(env, "java/lang/String"); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - DASSERT(False); - } - - if (JNU_IsNull(env, stringClassLocal)) return; - - string = (*env)->NewGlobalRef(env, stringClassLocal); /* never freed! */ - (*env)->DeleteLocalRef(env, stringClassLocal); - - if (JNU_IsNull(env, string)) { - JNU_ThrowOutOfMemoryError(env, ""); - return; - } - - DASSERT(awt_convertDataContext == 0); - awt_convertDataContext = XUniqueContext(); - DASSERT(awt_convertDataContext != 0); - - /* - * Fixes for 4513976 and 4818143. - */ - XtAppSetSelectionTimeout(awt_appContext, - JNU_CallStaticMethodByName(env, NULL, "sun/awt/UNIXToolkit", - "getDatatransferTimeout", "()I").i); - - /* - * Xt selection machinery doesn't respond to SelectionRequests if the - * event arrives on a widget that is not the current selection owner. - * This can happen if XtDisownSelection was called when SelectionRequest was - * already on the native queue. - * If the requestor is another JVM, it hangs for the selection timeout - * as SelectionNotify is never sent. - * We install an event handler that filters out SelectionRequests if the - * awt_root_shell is not the current selection owner. - */ - XtAddEventHandler(awt_root_shell, (EventMask)0, True, - selection_request_filter, NULL); - - XA_TARGETS = XInternAtom(awt_display, "TARGETS", False); -} - -/* - * Single routine to convert to target FILE_NAME or _DT_FILENAME - */ -Boolean -convertFileType(jbyteArray data, Atom * type, XtPointer * value, - unsigned long *length, int32_t *format) -{ - /* - * Convert the internal representation to an File Name. - * The data passed is an array of - * null separated bytes. Each series of bytes is a string - * that is then converted to an XString which are then put - * into an XStringList and put into an XTextProperty for - * usage in other programs. - * - * It would be desireable to have dataConvert to this conversion - * but it isn't possible to return a byte array that represents - * the XTextProperty. - */ - - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jboolean isCopy=JNI_FALSE; - XTextProperty tp; - jsize len; - jsize strings = 0; - jsize i; - char** stringList; - Status s; - jbyte* bytes; - char* start; - size_t slen; - char* utf; - - if ((*env)->PushLocalFrame(env, 16) < 0) { - return False; - } - - /* convert the data to an Array of Byte Elements */ - bytes = (*env)->GetByteArrayElements(env, data, &isCopy); - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - (*env)->PopLocalFrame(env, NULL); - return False; - } - - if (JNU_IsNull(env, bytes)) { - (*env)->PopLocalFrame(env, NULL); - return False; - } - - /* Get the length of the area */ - len = (*env)->GetArrayLength(env, data); - if (len == 0) { - (*env)->ReleaseByteArrayElements(env, data, bytes, JNI_ABORT); - (*env)->PopLocalFrame(env, NULL); - return False; - } - - /* - * determine the number of lists. The byteArray is null separated list of - * strings. - */ - for (i = 0; i < len; i++) { - if (bytes[i] == '\0') { - strings++; - } - } - - /* Allocate an X11 string list */ - stringList = (char **)XtCalloc(strings, sizeof(char *)); - if (stringList == (char**)NULL) { - (*env)->ReleaseByteArrayElements(env, data, bytes, JNI_ABORT); - (*env)->PopLocalFrame(env, NULL); - return False; - } - - for (i = 0; i < strings; i++) { - if (i == 0) { - start = (char*)bytes; - } else { - start = (char*)&bytes[slen]; - } - - /* - * if start is a NULL we're at the end of the list - * We'll just a have null entry on the end of the list - */ - if (start[0] == '\0') { - stringList[i] = NULL; - continue; - } - slen = strlen(start) + 1; - - stringList[i] = (char*)XtCalloc(slen, sizeof(char)); - - if (stringList[i] == (char *)NULL) { - jsize j; - - (*env)->ReleaseByteArrayElements(env, data, bytes, JNI_ABORT); - - for (j = 0; j < i; j++) { - XtFree((void *)stringList[j]); - } - - (*env)->PopLocalFrame(env, NULL); - - return False; - } - - memcpy((void *)stringList[i], (const void*)start, slen); - } - - (*env)->ReleaseByteArrayElements(env, data, bytes, JNI_ABORT); - s = XStringListToTextProperty(stringList, strings, &tp); - - /* free the strings that were created */ - for (i = 0; i < strings; i++) { - if (stringList[i] != NULL) { - XtFree((void*)stringList[i]); - } - } - - XtFree((void*)stringList); - - if (s == 0) { - (*env)->PopLocalFrame(env, NULL); - return False; - } - - *value = (XtPointer)XtCalloc(tp.nitems, sizeof(char)); - - if (*value == (XtPointer)NULL) { - XFree((void*)tp.value); - - (*env)->PopLocalFrame(env, NULL); - - return False; - } - - memcpy((void *)(*value), (const void *)tp.value, tp.nitems); - - XFree((void*)tp.value); - - *length = tp.nitems; - *type = tp.encoding; - *format = tp.format; - (*env)->PopLocalFrame(env, NULL); - return True; -} - -/* - * Class: sun_awt_motif_MDataTransferer - * Method: getAtomForTarget - * Signature: (Ljava/lang/String;)J - */ - -JNIEXPORT jlong JNICALL -Java_sun_awt_motif_MDataTransferer_getAtomForTarget(JNIEnv *env, - jclass cls, - jstring targetString) -{ - Atom target; - char *target_str; - - if (JNU_IsNull(env, targetString)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return -1; - } - target_str = (char *) JNU_GetStringPlatformChars(env, targetString, NULL); - - AWT_LOCK(); - - target = XInternAtom(awt_display, target_str, False); - - AWT_UNLOCK(); - - JNU_ReleaseStringPlatformChars(env, targetString, - (const char *) target_str); - return target; -} - -/* - * Class: sun_awt_motif_MDataTransferer - * Method: getTargetNameForAtom - * Signature: (J)Ljava/lang/String; - */ - -JNIEXPORT jstring JNICALL -Java_sun_awt_motif_MDataTransferer_getTargetNameForAtom(JNIEnv *env, - jclass cls, - jlong atom) -{ - jstring targetString; - char *name; - - AWT_LOCK(); - - name = XGetAtomName(awt_display, (Atom) atom); - - if (name == NULL) { - JNU_ThrowNullPointerException(env, "Failed to retrieve atom name."); - AWT_UNLOCK(); - return NULL; - } - - targetString = (*env)->NewStringUTF(env, (const char *)name); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - XFree (name); - AWT_UNLOCK(); - return NULL; - } - - if (JNU_IsNull(env, targetString)) { - JNU_ThrowNullPointerException(env, "Failed to create a string."); - XFree (name); - AWT_UNLOCK(); - return NULL; - } - - XFree (name); - - AWT_UNLOCK(); - return targetString; -} - -/* - * Class: sun_awt_datatransfer_DataTransferer - * Method: dragQueryFile - * Signature: ([B)[Ljava/lang/String; - * - * This method converts a byte array that came from File most likely from a - * drag operation into a String array. - */ - -JNIEXPORT jobjectArray JNICALL -Java_sun_awt_motif_MDataTransferer_dragQueryFile - (JNIEnv *env, jobject this, jbyteArray bytes) -{ - XTextProperty tp; - jbyte *value; - - char** strings = (char **)NULL; - int32_t nstrings = 0; - jobject filenames; - jobject ret = NULL; - int32_t i; - jsize len; - jboolean isCopy=JNI_FALSE; - - /* - * If the length of the byte array is 0 just return a null - */ - len = (*env)->GetArrayLength(env, bytes); - if (len == 0) { - return NULL; - } - - value = (*env)->GetByteArrayElements(env, bytes, &isCopy); - if (JNU_IsNull(env, value)) { - return NULL; - } - - AWT_LOCK(); - - tp.encoding = XInternAtom(awt_display, "STRING", False); - tp.value = (unsigned char *)value; - tp.nitems = len; - tp.format = 8; - - /* - * Convert the byte stream into a list of X11 strings - */ - if (XTextPropertyToStringList(&tp, &strings, &nstrings) == 0 || - nstrings == 0) - { - (*env)->ReleaseByteArrayElements(env, bytes, value, JNI_ABORT); - AWT_UNLOCK(); - return NULL; - } - - (*env)->ReleaseByteArrayElements(env, bytes, value, JNI_ABORT); - - filenames = (*env)->NewObjectArray(env, nstrings, string, NULL); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - goto wayout; - } - - if (JNU_IsNull(env, filenames)) { - goto wayout; - } - - /* - * Actuall conversion code per X11 String - */ - for (i = 0; i < nstrings; i++) { - jstring string = (*env)->NewStringUTF(env, - (const char *)strings[i]); - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - goto wayout; - } - - if (JNU_IsNull(env, string)) { - goto wayout; - } - - (*env)->SetObjectArrayElement(env, filenames, i, string); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - goto wayout; - } - - (*env)->DeleteLocalRef(env, string); - } - - ret = filenames; - wayout: - /* - * Clean up and return - */ - XFreeStringList(strings); - AWT_UNLOCK(); - return ret; -} - -DECLARE_JAVA_CLASS(dataTransfererClazz, "sun/awt/datatransfer/DataTransferer") - -/** - * Returns a local reference to the singleton DataTransferer instance. - * The caller should delete the reference when done. - */ -static jobject -get_data_transferer(JNIEnv* env) { - jobject transferer = NULL; - - DECLARE_STATIC_OBJECT_JAVA_METHOD(getInstanceMethodID, dataTransfererClazz, - "getInstance", - "()Lsun/awt/datatransfer/DataTransferer;"); - - transferer = (*env)->CallStaticObjectMethod(env, clazz, getInstanceMethodID); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - DASSERT(!JNU_IsNull(env, transferer)); - - return transferer; -} - -static jobject -call_convertData(JNIEnv* env, jobject source, jobject contents, jlong format, - jobject formatMap) { - jobject transferer = get_data_transferer(env); - jobject ret = NULL; - DECLARE_OBJECT_JAVA_METHOD(convertDataMethodID, dataTransfererClazz, - "convertData", - "(Ljava/lang/Object;Ljava/awt/datatransfer/Transferable;JLjava/util/Map;Z)[B"); - - ret = (*env)->CallObjectMethod(env, transferer, convertDataMethodID, - source, contents, format, formatMap, - awt_currentThreadIsPrivileged(env)); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - (*env)->DeleteLocalRef(env, transferer); - - return ret; -} - -static void -process_convert_data_requests() { - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_4); - jobject transferer = get_data_transferer(env); - - DECLARE_VOID_JAVA_METHOD(processDataConversionRequestsMethodID, - dataTransfererClazz, - "processDataConversionRequests", - "()V"); - - (*env)->CallVoidMethod(env, transferer, - processDataConversionRequestsMethodID); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - (*env)->DeleteLocalRef(env, transferer); -} - -Boolean -awt_convertData(Widget w, Atom * selection, Atom * target, Atom * type, - XtPointer * value, unsigned long *length, int32_t *format) { - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - Display* dpy = XtDisplay(w); - awt_convertDataCallbackStruct* structPtr = NULL; - - if (XFindContext(dpy, *selection, awt_convertDataContext, - (XPointer*)&structPtr) == XCNOMEM || structPtr == NULL) { - return False; - } - - if ((*env)->PushLocalFrame(env, 2) < 0) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - return False; - } - - if (*target == XA_TARGETS) { - jlongArray formats = structPtr->formats; - jsize count; - jlong* targets; - jboolean isCopy; - -#ifndef _LP64 /* Atom and jlong are different sizes in the 32-bit build */ - Atom* aValue; - jlong* saveTargets; - jsize i; -#endif - - if (JNU_IsNull(env, formats)) { - (*env)->PopLocalFrame(env, NULL); - return False; - } - - count = (*env)->GetArrayLength(env, formats); - if (count == 0) { - (*env)->PopLocalFrame(env, NULL); - return False; - } - - targets = (*env)->GetLongArrayElements(env, formats, &isCopy); - - *type = XA_ATOM; - *format = 32; - -#ifdef _LP64 - *value = XtMalloc(count * sizeof(Atom)); - memcpy((void *)*value, (void *)targets, count * sizeof(Atom)); -#else - *value = aValue = (Atom *)XtMalloc(count * sizeof(Atom)); - saveTargets = targets; - for (i = 0; i < count; i++, aValue++, targets++) { - *aValue = (Atom)*targets; - } - targets = saveTargets; -#endif - (*env)->ReleaseLongArrayElements(env, formats, targets, JNI_ABORT); - - *length = count; - - } else if (*target == XInternAtom(dpy, _XA_DELETE, False)) { - - /* - * acknowledge the DELETE target here ... the "delete" semantic - * of move will take place after the drop is complete. - */ - - *type = XInternAtom(dpy, _XA_NULL, False); - *length = 0; - *value = (XtPointer)NULL; - /* Uninitialized format can cause crash in Xt conversion code. */ - *format = 8; - } else if (*target == XInternAtom(dpy, _XA_HOSTNAME, False)) { - struct utsname name; - XTextProperty tp; - - uname(&name); - - if (!XStringListToTextProperty((char **)&name.nodename, 1, &tp)) { - (*env)->PopLocalFrame(env, NULL); - return False; - } - - *value = (XtPointer)XtCalloc(tp.nitems, sizeof(char)); - - memcpy((void *)*value, (const void *)tp.value, tp.nitems); - - XFree((void *)tp.value); - - *type = tp.encoding; - *length = tp.nitems + 1; - *format = tp.format; - } else if (*target == XInternAtom(dpy, _XA_FILENAME, False) || - *target == XInternAtom(dpy, _DT_FILENAME, False)) { - - /* - * Convert the internal representation to an File Name. - * The data returned from dataConvert is a an array of - * null separated bytes. Each series of bytes is a string - * that is then converted to an XString which are then put - * into an XStringList and put into an XTextProperty for - * usage in other programs. - * - * It would be desireable to have dataConvert to this conversion - * but it isn't possible to return a byte array that represents - * the XTextProperty. - */ - jbyteArray data; - - /* - * Fix for 4513976. - * Type None should be used instead of XT_CONVERT_FAIL - * to report conversion failure. - */ - /* assume forthcoming error */ - *type = None; - *value = (XtPointer)NULL; - *length = 0; - *format = 8; - - data = call_convertData(env, structPtr->source, structPtr->transferable, - (jlong)*target, structPtr->formatMap); - - /* error test */ - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - (*env)->PopLocalFrame(env, NULL); - return False; - } - if (JNU_IsNull(env, data)) { - (*env)->PopLocalFrame(env, NULL); - return False; - } - - if (convertFileType(data, type, value, length, format) == False) { - (*env)->PopLocalFrame(env, NULL); - return False; - } - } else { - jbyteArray bytes = NULL; - jbyte* copy = NULL; - - /* - * Fix for 4513976. - * Type None should be used instead of XT_CONVERT_FAIL - * to report conversion failure. - */ - *type = None; /* assume forthcoming error */ - *value = (XtPointer)NULL; - *length = 0; - *format = 8; - - bytes = call_convertData(env, structPtr->source, structPtr->transferable, - (jlong)*target, structPtr->formatMap); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - (*env)->PopLocalFrame(env, NULL); - return False; - } - - if (bytes == NULL) { - (*env)->PopLocalFrame(env, NULL); - return False; - } else { - jsize len = (*env)->GetArrayLength(env, bytes); - - if (len == 0) { - *type = *target; - *format = 8; - (*env)->PopLocalFrame(env, NULL); - return True; - } - - copy = (jbyte*)XtCalloc(1, len * sizeof(jbyte)); - if (copy == (jbyte*)NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - (*env)->PopLocalFrame(env, NULL); - return False; - } - - (*env)->GetByteArrayRegion(env, (jbyteArray)bytes, 0, len, copy); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - XtFree((void *)copy); - (*env)->PopLocalFrame(env, NULL); - return False; - } - - *value = (XtPointer)copy; - *type = *target; - *length = len; - *format = 8; - } - } - - (*env)->PopLocalFrame(env, NULL); - return True; -} - - -jlongArray -getSelectionTargetsHelper(JNIEnv* env, XtPointer value, unsigned long length) -{ - Atom* targets = (Atom*)value; - jlongArray targetArray = NULL; - jlong* checkedTargets = NULL; - size_t count = 0, i = 0, j = 0; - - /* Get rid of zero atoms if there are any. */ - for (; i < length; i++) { - if (targets[i] != 0) { - count++; - } - } - checkedTargets = calloc(count, sizeof(jlong)); - if (checkedTargets == NULL) { - JNU_ThrowOutOfMemoryError(env, ""); - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } else { - for (i = 0; i < length; i++) { - if (targets[i] != 0) { - checkedTargets[j++] = targets[i]; - } - } - - DASSERT(j == count); - - if ((*env)->EnsureLocalCapacity(env, 1) >= 0) { - - targetArray = (*env)->NewLongArray(env, count); - - if (!JNU_IsNull(env, targetArray)) { - (*env)->SetLongArrayRegion(env, targetArray, 0, count, - checkedTargets); - - if ((*env)->ExceptionCheck(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - - (*env)->DeleteLocalRef(env, targetArray); - targetArray = NULL; - } - } - } - free(checkedTargets); - } - - return targetArray; -} - -static void -get_selection_targets_callback(Widget w, XtPointer client_data, Atom* selection, - Atom* type, XtPointer value, - unsigned long* length, int32_t* format) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject* pReturnArray = (jobject*)client_data; - SelectionStatus status = SelectionFailure; - - /* - * It is highly unlikely that TARGETS will ever be passed even though that - * was what was requested. However, XA_ATOM ("ATOM") is likely. - * Actually they are the same so treat them as such. See XToolKit - * Intrinsic Manual on XtSelectionCallbackProc for more details on type. - */ - if (*type == XA_TARGETS || *type == XA_ATOM) { - jlongArray targetArray = getSelectionTargetsHelper(env, value, *length); - if (!JNU_IsNull(env, targetArray)) { - *pReturnArray = (*env)->NewGlobalRef(env, targetArray); - status = SelectionSuccess; - (*env)->DeleteLocalRef(env, targetArray); - } - } else if (*type == XT_CONVERT_FAIL) { - status = SelectionOwnerTimedOut; - } else { - /* - * A part of the fix for 4259272. - * Actually Xt Intrinsics says about XtSelectionCallback that - * "if there is no owner for the specified selection, or that owner - * cannot convert the selected data to the requested type, then this - * callback is called with value NULL and length zero". - * But we report success if type is not TARGETS, XA_ATOM or XT_CONVERT_FAIL, - * and we should not change this behaviour. We just return zero-length - * array instead of null, because null denotes that we could not get - * selection targets at the time of tracking changes of available on - * the selection data flavors. - */ - jlongArray targetArray = (*env)->NewLongArray(env, 0); - *pReturnArray = (*env)->NewGlobalRef(env, targetArray); - /* - * Fix for 4655996. - * Report success if there is no owner for this selection or the owner - * fails to provide target types. - */ - status = SelectionSuccess; - (*env)->DeleteLocalRef(env, targetArray); - } - - if (value != NULL) { - XtFree(value); - value = NULL; - } - - set_selection_status(status); -} - -static void -get_selection_data_callback(Widget w, XtPointer client_data, Atom * selection, - Atom * type, XtPointer value, unsigned long *length, - int32_t *format) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject* pData = (jobject*)client_data; - SelectionStatus status = SelectionFailure; - - if (*type == XT_CONVERT_FAIL) { - status = SelectionOwnerTimedOut; - } else if (*type != None) { - if ((*env)->EnsureLocalCapacity(env, 1) >= 0) { - jsize size = (*length <= INT_MAX) ? *length : INT_MAX; - jbyteArray array = (*env)->NewByteArray(env, size); - - if (!JNU_IsNull(env, array)) { - (*env)->SetByteArrayRegion(env, array, 0, size, (jbyte*)value); - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } else { - *pData = (*env)->NewGlobalRef(env, array); - status = SelectionSuccess; - } - - (*env)->DeleteLocalRef(env, array); - } - } - } - - if (value != NULL) { - XtFree(value); - value = NULL; - } - - set_selection_status(status); -} - -static int32_t -wait_for_selection_event(void *data) { - process_convert_data_requests(); - return get_selection_status() != SelectionPending; -} - -jlongArray -get_selection_targets(JNIEnv *env, Atom selection, Time time_stamp) { - jlongArray ret = NULL; - jlongArray targets = NULL; - SelectionStatus status = SelectionPending; - - AWT_LOCK(); - - XtAppSetSelectionTimeout(awt_appContext, - JNU_CallStaticMethodByName(env, NULL, "sun/awt/UNIXToolkit", - "getDatatransferTimeout", "()I").i); - - set_selection_status(SelectionPending); - XtGetSelectionValue(awt_root_shell, selection, XA_TARGETS, - get_selection_targets_callback, (XtPointer)&targets, - time_stamp); - - awt_MToolkit_modalWait(wait_for_selection_event, NULL); - status = get_selection_status(); - - AWT_FLUSH_UNLOCK(); - - if (!JNU_IsNull(env, targets)) { - ret = (*env)->NewLocalRef(env, targets); - (*env)->DeleteGlobalRef(env, targets); - } - - switch (status) { - case SelectionSuccess: - break; - case SelectionFailure: - JNU_ThrowByName(env, "java/lang/IllegalStateException", - "Failed to get selection targets"); - break; - case SelectionOwnerTimedOut: - // return an empty array of targets if the selection owner timed out - ret = (*env)->NewLongArray(env, 0); - break; - default: - JNU_ThrowByName(env, "java/lang/IllegalStateException", - "Unexpected selection status"); - break; - } - - return ret; -} - -jbyteArray -get_selection_data(JNIEnv *env, Atom selection, Atom target, Time time_stamp) { - jbyteArray ret = NULL; - jbyteArray data = NULL; - SelectionStatus status = SelectionPending; - - AWT_LOCK(); - - XtAppSetSelectionTimeout(awt_appContext, - JNU_CallStaticMethodByName(env, NULL, "sun/awt/UNIXToolkit", - "getDatatransferTimeout", "()I").i); - - set_selection_status(SelectionPending); - XtGetSelectionValue(awt_root_shell, selection, target, - get_selection_data_callback, - (XtPointer)&data, time_stamp); - - awt_MToolkit_modalWait(wait_for_selection_event, NULL); - status = get_selection_status(); - - AWT_FLUSH_UNLOCK(); - - if (!JNU_IsNull(env, data)) { - ret = (*env)->NewLocalRef(env, data); - (*env)->DeleteGlobalRef(env, data); - } - - switch (status) { - case SelectionSuccess: - break; - case SelectionFailure: - JNU_ThrowIOException(env, "Failed to get selection data"); - break; - case SelectionOwnerTimedOut: - JNU_ThrowIOException(env, "Selection owner timed out"); - break; - default: - JNU_ThrowIOException(env, "Unexpected selection status"); - break; - } - - return ret; -} - -void -awt_cleanupConvertDataContext(JNIEnv *env, Atom selectionAtom) { - awt_convertDataCallbackStruct* structPtr = NULL; - - if (XFindContext(awt_display, selectionAtom, awt_convertDataContext, - (XPointer*)&structPtr) == 0 && structPtr != NULL) { - - (*env)->DeleteGlobalRef(env, structPtr->source); - (*env)->DeleteGlobalRef(env, structPtr->transferable); - (*env)->DeleteGlobalRef(env, structPtr->formatMap); - (*env)->DeleteGlobalRef(env, structPtr->formats); - free(structPtr); - } - /* - * Xlib Programming Manual says that it is better to erase - * the current entry with XDeleteContext() before XSaveContext(). - */ - XDeleteContext(awt_display, selectionAtom, awt_convertDataContext); - if (XSaveContext(awt_display, selectionAtom, awt_convertDataContext, - (XPointer)NULL) == XCNOMEM) { - JNU_ThrowInternalError(env, "XError"); - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -static Bool exitSecondaryLoop = True; - -/* - * This predicate procedure allows the Toolkit thread to process specific events - * while it is blocked waiting for the event dispatch thread to process - * a SunDropTargetEvent. We need this to prevent deadlock when the client code - * processing SunDropTargetEvent sets or gets the contents of the system - * clipboard/selection. In this case the event dispatch thread waits for the - * Toolkit thread to process PropertyNotify or SelectionNotify events. - */ -static Bool -secondary_loop_event(Display* dpy, XEvent* event, char* arg) { - return (event->type == SelectionNotify || - event->type == SelectionClear || - event->type == PropertyNotify) ? True : False; -} - - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MToolkitThreadBlockedHandler_enter(JNIEnv *env, jobject this) { - DASSERT(exitSecondaryLoop && awt_currentThreadIsPrivileged(env)); - exitSecondaryLoop = False; - while (!exitSecondaryLoop) { - XEvent event; - while (XCheckIfEvent(awt_display, &event, secondary_loop_event, NULL)) { - XtDispatchEvent(&event); - } - AWT_WAIT(AWT_DND_POLL_INTERVAL); - } -} - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MToolkitThreadBlockedHandler_exit(JNIEnv *env, jobject this) { - DASSERT(!exitSecondaryLoop && !awt_currentThreadIsPrivileged(env)); - exitSecondaryLoop = True; - AWT_NOTIFY_ALL(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_DataTransferer.h b/jdk/src/solaris/native/sun/awt/awt_DataTransferer.h deleted file mode 100644 index e4be5800759..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_DataTransferer.h +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright 2000-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifndef AWT_DATATRANSFERER_H -#define AWT_DATATRANSFERER_H - -#include -#include - -#define _XA_DELETE "DELETE" -#define _XA_FILENAME "FILE_NAME" -#define _XA_HOSTNAME "HOST_NAME" -#define _XA_NULL "NULL" -#define _DT_FILENAME "_DT_NETFILE" - -#define AWT_DND_POLL_INTERVAL ((unsigned long)250) /* milliseconds */ - -typedef struct { - jobject source; - jobject transferable; - jobject formatMap; - jlongArray formats; -} awt_convertDataCallbackStruct; - -extern XContext awt_convertDataContext; /* XContext is not 64 bits */ - -extern Atom XA_TARGETS; - -/* - * Single routine to convert to target FILE_NAME or _DT_FILENAME - */ -Boolean -convertFileType(jbyteArray data, Atom * type, XtPointer * value, - unsigned long *length, int32_t *format); - -Boolean -awt_convertData(Widget w, Atom * selection, Atom * target, Atom * type, - XtPointer * value, unsigned long *length, int32_t *format); - -jlongArray -get_selection_targets(JNIEnv *env, Atom selection, Time time_stamp); - -jlongArray -getSelectionTargetsHelper(JNIEnv* env, XtPointer value, unsigned long length); - -jbyteArray -get_selection_data(JNIEnv *env, Atom selection, Atom format, Time time_stamp); - -void -awt_cleanupConvertDataContext(JNIEnv *env, Atom selectionAtom); - -/* - * NOTE: You need these macros only if you take care of performance, since they - * provide proper caching. Otherwise you can use JNU_CallMethodByName etc. - */ - -/* - * This macro defines a function which returns the class for the specified - * class name with proper caching and error handling. - */ -#define DECLARE_JAVA_CLASS(javaclazz, name) \ -static jclass \ -get_ ## javaclazz(JNIEnv* env) { \ - static jclass javaclazz = NULL; \ - \ - if (JNU_IsNull(env, javaclazz)) { \ - jclass javaclazz ## Local = (*env)->FindClass(env, name); \ - \ - if (!JNU_IsNull(env, javaclazz ## Local)) { \ - javaclazz = (jclass)(*env)->NewGlobalRef(env, javaclazz ## Local); \ - (*env)->DeleteLocalRef(env, javaclazz ## Local); \ - if (JNU_IsNull(env, javaclazz)) { \ - JNU_ThrowOutOfMemoryError(env, ""); \ - } \ - } \ - \ - if (!JNU_IsNull(env, ((*env)->ExceptionOccurred(env)))) { \ - (*env)->ExceptionDescribe(env); \ - (*env)->ExceptionClear(env); \ - } \ - } \ - \ - DASSERT(!JNU_IsNull(env, javaclazz)); \ - \ - return javaclazz; \ -} - -/* - * The following macros defines blocks of code which retrieve a method of the - * specified class identified with the specified name and signature. - * The specified class should be previously declared with DECLARE_JAVA_CLASS. - * These macros should be placed at the beginning of a block, after definition - * of local variables, but before the code begins. - */ -#define DECLARE_VOID_JAVA_METHOD(method, javaclazz, name, signature) \ - static jmethodID method = NULL; \ - \ - if (JNU_IsNull(env, method)) { \ - jclass clazz = get_ ## javaclazz(env); \ - \ - if (JNU_IsNull(env, clazz)) { \ - return; \ - } \ - \ - method = (*env)->GetMethodID(env, clazz, name, signature); \ - \ - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { \ - (*env)->ExceptionDescribe(env); \ - (*env)->ExceptionClear(env); \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - DASSERT(False); \ - return; \ - } \ - } - -#define DECLARE_BOOLEAN_JAVA_METHOD(method, javaclazz, name, signature) \ - static jmethodID method = NULL; \ - \ - if (JNU_IsNull(env, method)) { \ - jclass clazz = get_ ## javaclazz(env); \ - \ - if (JNU_IsNull(env, clazz)) { \ - return False; \ - } \ - \ - method = (*env)->GetMethodID(env, clazz, name, signature); \ - \ - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { \ - (*env)->ExceptionDescribe(env); \ - (*env)->ExceptionClear(env); \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - DASSERT(False); \ - return False; \ - } \ - } - -#define DECLARE_JINT_JAVA_METHOD(method, javaclazz, name, signature) \ - static jmethodID method = NULL; \ - \ - if (JNU_IsNull(env, method)) { \ - jclass clazz = get_ ## javaclazz(env); \ - \ - if (JNU_IsNull(env, clazz)) { \ - return java_awt_dnd_DnDConstants_ACTION_NONE; \ - } \ - \ - method = (*env)->GetMethodID(env, clazz, name, signature); \ - \ - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { \ - (*env)->ExceptionDescribe(env); \ - (*env)->ExceptionClear(env); \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - DASSERT(False); \ - return java_awt_dnd_DnDConstants_ACTION_NONE; \ - } \ - } - -#define DECLARE_OBJECT_JAVA_METHOD(method, javaclazz, name, signature) \ - static jmethodID method = NULL; \ - \ - if (JNU_IsNull(env, method)) { \ - jclass clazz = get_ ## javaclazz(env); \ - \ - if (JNU_IsNull(env, clazz)) { \ - return NULL; \ - } \ - \ - method = (*env)->GetMethodID(env, clazz, name, signature); \ - \ - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { \ - (*env)->ExceptionDescribe(env); \ - (*env)->ExceptionClear(env); \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - DASSERT(False); \ - return NULL; \ - } \ - } - -#define DECLARE_STATIC_OBJECT_JAVA_METHOD(method, javaclazz, name, signature) \ - static jmethodID method = NULL; \ - jclass clazz = get_ ## javaclazz(env); \ - \ - if (JNU_IsNull(env, clazz)) { \ - return NULL; \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - method = (*env)->GetStaticMethodID(env, clazz, name, signature); \ - \ - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { \ - (*env)->ExceptionDescribe(env); \ - (*env)->ExceptionClear(env); \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - DASSERT(False); \ - return NULL; \ - } \ - } - -#define DECLARE_STATIC_VOID_JAVA_METHOD(method, javaclazz, name, signature) \ - static jmethodID method = NULL; \ - jclass clazz = get_ ## javaclazz(env); \ - \ - if (JNU_IsNull(env, clazz)) { \ - return; \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - method = (*env)->GetStaticMethodID(env, clazz, name, signature); \ - \ - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { \ - (*env)->ExceptionDescribe(env); \ - (*env)->ExceptionClear(env); \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - DASSERT(False); \ - return; \ - } \ - } - -#define DECLARE_STATIC_JINT_JAVA_METHOD(method, javaclazz, name, signature) \ - static jmethodID method = NULL; \ - jclass clazz = get_ ## javaclazz(env); \ - \ - if (JNU_IsNull(env, clazz)) { \ - return java_awt_dnd_DnDConstants_ACTION_NONE; \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - method = (*env)->GetStaticMethodID(env, clazz, name, signature); \ - \ - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { \ - (*env)->ExceptionDescribe(env); \ - (*env)->ExceptionClear(env); \ - } \ - \ - if (JNU_IsNull(env, method)) { \ - DASSERT(False); \ - return java_awt_dnd_DnDConstants_ACTION_NONE; \ - } \ - } - -#endif /* AWT_DATATRANSFERER_H */ diff --git a/jdk/src/solaris/native/sun/awt/awt_DrawingSurface.c b/jdk/src/solaris/native/sun/awt/awt_DrawingSurface.c index a7619660225..8af0c57e95a 100644 --- a/jdk/src/solaris/native/sun/awt/awt_DrawingSurface.c +++ b/jdk/src/solaris/native/sun/awt/awt_DrawingSurface.c @@ -29,7 +29,7 @@ #include "awt_p.h" #include "java_awt_Component.h" -#include "sun_awt_motif_MComponentPeer.h" +//#include "sun_awt_motif_MComponentPeer.h" #include "awt_Component.h" diff --git a/jdk/src/solaris/native/sun/awt/awt_FileDialog.c b/jdk/src/solaris/native/sun/awt/awt_FileDialog.c deleted file mode 100644 index a170deda9c4..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_FileDialog.c +++ /dev/null @@ -1,925 +0,0 @@ -/* - * Copyright 1995-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include -#include -#include -#include -#include -#include "awt_p.h" -#include "java_awt_FileDialog.h" -#include "java_awt_event_MouseWheelEvent.h" -#include "sun_awt_motif_MFileDialogPeer.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "multi_font.h" - -#include "awt_Component.h" - -#include -#include -#include - -#define MAX_DIR_PATH_LEN 1024 - -extern void Text_handlePaste(Widget w, XtPointer client_data, XEvent * event, - Boolean * cont); - -extern struct MComponentPeerIDs mComponentPeerIDs; - -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -/* fieldIDs for FileDialog fields and methods that may be accessed from C */ -static struct FileDialogIDs { - jfieldID mode; - jfieldID file; -} fileDialogIDs; - -/* the field to store the default search procedure */ -static XmSearchProc DefaultSearchProc = NULL; - -/* mouse wheel handler for scrolling */ -void File_handleWheel(Widget w, XtPointer client_data, XEvent* event, Boolean* cont); - -/* - * Class: java_awt_FileDialog - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for FileDialog.java - to initialize the fieldIDs for fields that may be accessed from C */ - -JNIEXPORT void JNICALL -Java_java_awt_FileDialog_initIDs - (JNIEnv *env, jclass cls) -{ - fileDialogIDs.mode = (*env)->GetFieldID(env, cls, "mode", "I"); - fileDialogIDs.file = - (*env)->GetFieldID(env, cls, "file", "Ljava/lang/String;"); - - DASSERT(fileDialogIDs.mode != NULL); - DASSERT(fileDialogIDs.file != NULL); -} - -/* - * client_data is MFileDialogPeer instance pointer - */ -static void -FileDialog_OK(Widget w, - void *client_data, - XmFileSelectionBoxCallbackStruct * call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject) client_data; - struct FrameData *fdata; - char *file; - jstring jstr; - XmStringContext stringContext; - XmStringDirection direction; - XmStringCharSet charset; - Boolean separator; - - fdata = (struct FrameData *)JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) - return; - - if (!XmStringInitContext(&stringContext, call_data->value)) - return; - - if (!XmStringGetNextSegment(stringContext, &file, &charset, - &direction, &separator)) - file = NULL; - - if (file == NULL) - jstr = NULL; - else - jstr = JNU_NewStringPlatform(env, (const char *) file); - - if (jstr != 0) { - JNU_CallMethodByName(env, NULL, this, "handleSelected", - "(Ljava/lang/String;)V", jstr); - (*env)->DeleteLocalRef(env, jstr); - } - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - XmStringFreeContext(stringContext); - if (file != NULL) - XtFree(file); -} - -/* - * client_data is MFileDialogPeer instance pointer - */ -static void -FileDialog_CANCEL(Widget w, - void *client_data, - XmFileSelectionBoxCallbackStruct * call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject) client_data; - struct FrameData *fdata; - - fdata = (struct FrameData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - JNU_CallMethodByName(env, NULL, (jobject) client_data, "handleCancel", "()V"); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - - -/* - * client_data is MFileDialogPeer instance pointer - */ -static void -FileDialog_quit(Widget w, - XtPointer client_data, - XtPointer call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - JNU_CallMethodByName(env, NULL, (jobject) client_data, "handleQuit", "()V"); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -static void -setDeleteCallback(jobject this, struct FrameData *wdata) -{ - Atom xa_WM_DELETE_WINDOW; - Atom xa_WM_PROTOCOLS; - - XtVaSetValues(wdata->winData.shell, - XmNdeleteResponse, XmDO_NOTHING, - NULL); - xa_WM_DELETE_WINDOW = XmInternAtom(XtDisplay(wdata->winData.shell), - "WM_DELETE_WINDOW", False); - xa_WM_PROTOCOLS = XmInternAtom(XtDisplay(wdata->winData.shell), - "WM_PROTOCOLS", False); - - XmAddProtocolCallback(wdata->winData.shell, - xa_WM_PROTOCOLS, - xa_WM_DELETE_WINDOW, - FileDialog_quit, (XtPointer) this); -} - -void -setFSBDirAndFile(Widget w, char *dir, char *file, - XmString *ffiles, int count) -{ - Widget textField, list; - char dirbuf[MAX_DIR_PATH_LEN]; - XmString xim, item; - size_t lastSelect; - - dirbuf[0] = (char) '\0'; - - if (dir != NULL && strlen(dir) < MAX_DIR_PATH_LEN) - strcpy(dirbuf, dir); - - /* -----> make sure dir ends in '/' */ - if (dirbuf[0] != (char) '\0') { - if (dirbuf[strlen(dirbuf) - 1] != (char) '/') - strcat(dirbuf, "/"); - } else { - getcwd(dirbuf, MAX_DIR_PATH_LEN - 16); - strcat(dirbuf, "/"); - } - - strcat(dirbuf, "[^.]*"); - xim = XmStringCreate(dirbuf, XmSTRING_DEFAULT_CHARSET); - XtVaSetValues(w, XmNdirMask, xim, NULL); - - if (ffiles != NULL) - XtVaSetValues(w, - XmNfileListItems, (count > 0) ? ffiles : NULL, - XmNfileListItemCount, count, - XmNlistUpdated, True, NULL); - - XmStringFree(xim); - - /* - * Select the filename from the filelist if it exists. - */ - - textField = XmFileSelectionBoxGetChild(w, XmDIALOG_TEXT); - list = XmFileSelectionBoxGetChild(w, XmDIALOG_LIST); - - if (textField != 0 && file != 0) { - lastSelect = strlen(file); - XtVaSetValues(textField, XmNvalue, file, NULL); - XmTextFieldSetSelection(textField, 0, lastSelect, CurrentTime); - - item = XmStringCreateLocalized(file); - XmListSelectItem(list, item, NULL); - XmStringFree(item); - } -} - -static void -changeBackground(Widget w, void *bg) -{ - /* - ** This is a work-around for bug 4325443, caused by motif bug 4345559, - ** XmCombobox dosn't return all children, so give it some help ... - */ - Widget grabShell; - grabShell = XtNameToWidget(w, "GrabShell"); - if (grabShell != NULL) { - awt_util_mapChildren(grabShell, changeBackground, 0, (void *) bg); - } - - XmChangeColor(w, (Pixel) bg); -} - -void -ourSearchProc(Widget w, XtPointer p) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - struct FrameData *wdata; - XtPointer peer; - jobject this; - jboolean res; - char * dir = NULL; - jstring dir_o; - int32_t i, filecount = 0; - XmString * filelist = NULL; - jobjectArray nffiles = NULL; - jclass clazz = NULL; - jstring jfilename = NULL; - char * cfilename = NULL; - XmFileSelectionBoxCallbackStruct * vals = (XmFileSelectionBoxCallbackStruct *)p; - - XtVaGetValues(w, XmNuserData, &peer, NULL); - this = (jobject)peer; - if (JNU_IsNull(env, this) ) { - return; - } - wdata = (struct FrameData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (wdata == 0 || - wdata->winData.comp.widget == 0 || - wdata->winData.shell == 0 || p == NULL ) { - return; - } - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - return; - } - - if (DefaultSearchProc != NULL) { - /* Unmap the widget temporary. If it takes a long time to generate - the list items some visual artifacts may be caused. However, - we need to do this to have the widget that works as we expect. - */ - XtSetMappedWhenManaged(w, False); - /* Call the default Motif search procedure to take the - native filtered file list. - */ - DefaultSearchProc(w, vals); - XtSetMappedWhenManaged(w, True); - XtVaGetValues(w, - XmNlistItemCount, &filecount, - XmNlistItems, &filelist, - NULL); - /* We need to construct the new String array to pass it to - the Java code. - */ - clazz = (*env)->FindClass(env, "java/lang/String"); - /* It is ok if filecount is 0. */ - nffiles = (*env)->NewObjectArray(env, filecount, clazz, NULL); - if (JNU_IsNull(env, nffiles)) { - nffiles = NULL; - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - } else { - for (i = 0; i < filecount; i++) { - DASSERT(filelist[i] != NULL); - - XmStringGetLtoR(filelist[i], XmFONTLIST_DEFAULT_TAG, &cfilename); - jfilename = JNU_NewStringPlatform(env, cfilename); - - if (JNU_IsNull(env, jfilename)) { - XtFree(cfilename); - nffiles = NULL; - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - break; - } - - (*env)->SetObjectArrayElement(env, nffiles, i, jfilename); - - (*env)->DeleteLocalRef(env, jfilename); - XtFree(cfilename); - } - } - } - - XmStringGetLtoR(vals->dir, XmFONTLIST_DEFAULT_TAG, &dir); - dir_o = JNU_NewStringPlatform(env, dir); - res = JNU_CallMethodByName(env, NULL, this, - "proceedFiltering", - "(Ljava/lang/String;[Ljava/lang/String;Z)Z", - dir_o, nffiles, - awt_currentThreadIsPrivileged(env)).z; - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - XtVaSetValues(w, - XmNlistUpdated, res, - NULL); - (*env)->DeleteLocalRef(env, dir_o); - free(dir); -} - -/* - * Class: sun_awt_motif_MFileDialogPeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFileDialogPeer_create - (JNIEnv *env, jobject this, jobject parent) -{ - struct FrameData *fdata; - struct CanvasData *wdata; - int32_t argc; -#define MAX_ARGC 20 - Arg args[MAX_ARGC]; - Widget child, textField, dirList, fileList; - XmString xim; - Pixel bg; - jobject target; - jstring file; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; -#ifndef NOMODALFIX - extern void awt_shellPoppedUp(Widget shell, XtPointer c, XtPointer d); - extern void awt_shellPoppedDown(Widget shell, XtPointer c, XtPointer d); -#endif NOMODALFIX - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if (JNU_IsNull(env, parent) || JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - - adata = copyGraphicsConfigToPeer(env, this); - - wdata = (struct CanvasData *) JNU_GetLongFieldAsPtr(env,parent,mComponentPeerIDs.pData); - - fdata = ZALLOC(FrameData); - JNU_SetLongFieldFromPtr(env,this,mComponentPeerIDs.pData,fdata); - - if (fdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - XtVaGetValues(wdata->comp.widget, XmNbackground, &bg, NULL); - - /* - * XXX: this code uses FrameData but doesn't bother to init a lot - * of its memebers. This confuses the hell out of the code in - * awt_TopLevel.c that gets passes such half-inited FrameData. - */ - fdata->decor = MWM_DECOR_ALL; - - argc = 0; - XtSetArg(args[argc], XmNmustMatch, False); - argc++; - XtSetArg(args[argc], XmNautoUnmanage, False); - argc++; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNvisual, adata->awt_visInfo.visual); - argc++; - XtSetArg(args[argc], XmNdialogStyle, XmDIALOG_FULL_APPLICATION_MODAL); - argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, adata->awt_visInfo.screen)); - argc++; - XtSetArg(args[argc], XmNuserData, (XtPointer)globalRef); - argc++; - XtSetArg(args[argc], XmNresizePolicy, XmRESIZE_NONE); - argc++; - - XtSetArg(args[argc], XmNbuttonFontList, getMotifFontList()); - argc++; - XtSetArg(args[argc], XmNlabelFontList, getMotifFontList()); - argc++; - XtSetArg(args[argc], XmNtextFontList, getMotifFontList()); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - - fdata->winData.comp.widget = XmCreateFileSelectionDialog(wdata->shell, - "", - args, - argc); - fdata->winData.shell = XtParent(fdata->winData.comp.widget); - awt_util_mapChildren(fdata->winData.shell, changeBackground, 0, - (void *) bg); - child = XmFileSelectionBoxGetChild(fdata->winData.comp.widget, - XmDIALOG_HELP_BUTTON); - - /* We should save a pointer to the default search procedure - to do some things that we cannot do else. For instance, - apply the native pattern. - */ - XtVaGetValues(fdata->winData.comp.widget, - XmNfileSearchProc, &DefaultSearchProc, - NULL); - XtVaSetValues(fdata->winData.comp.widget, - XmNfileSearchProc, ourSearchProc, - NULL); - - /* - * Get textfield in FileDialog. - */ - textField = XmFileSelectionBoxGetChild(fdata->winData.comp.widget, - XmDIALOG_TEXT); - if (child != NULL) { - /* - * Workaround for Bug Id 4415659. - * If the dialog child is unmanaged before the dialog is managed, - * the Motif drop site hierarchy may be broken if we associate - * a drop target with the dialog before it is shown. - */ - XtSetMappedWhenManaged(fdata->winData.shell, False); - XtManageChild(fdata->winData.comp.widget); - XtUnmanageChild(fdata->winData.comp.widget); - XtSetMappedWhenManaged(fdata->winData.shell, True); - XtUnmanageChild(child); - } - if (!awtJNI_IsMultiFont(env, awtJNI_GetFont(env, this))) { - /* This process should not be done other than English language - locale. */ - child = XmFileSelectionBoxGetChild(fdata->winData.comp.widget, - XmDIALOG_DEFAULT_BUTTON); - if (child != NULL) { - XmString xim; - - switch ((*env)->GetIntField(env, target, fileDialogIDs.mode)) { - case java_awt_FileDialog_LOAD: - xim = XmStringCreate("Open", "labelFont"); - XtVaSetValues(child, XmNlabelString, xim, NULL); - XmStringFree(xim); - break; - - case java_awt_FileDialog_SAVE: - xim = XmStringCreate("Save", "labelFont"); - XtVaSetValues(child, XmNlabelString, xim, NULL); - XmStringFree(xim); - break; - - default: - break; - } - } - } - XtAddCallback(fdata->winData.comp.widget, - XmNokCallback, - (XtCallbackProc) FileDialog_OK, - (XtPointer) globalRef); - XtAddCallback(fdata->winData.comp.widget, - XmNcancelCallback, - (XtCallbackProc) FileDialog_CANCEL, - (XtPointer) globalRef); - -#ifndef NOMODALFIX - XtAddCallback(fdata->winData.shell, - XtNpopupCallback, - awt_shellPoppedUp, - NULL); - XtAddCallback(fdata->winData.shell, - XtNpopdownCallback, - awt_shellPoppedDown, - NULL); -#endif NOMODALFIX - - setDeleteCallback(globalRef, fdata); - - if (textField != NULL) { - /* - * Insert event handler to correctly process cut/copy/paste keys - * such that interaction with our own clipboard mechanism will work - * properly. - * - * The Text_handlePaste() event handler is also used by both - * TextField/TextArea. - */ - XtInsertEventHandler(textField, - KeyPressMask, - False, Text_handlePaste, (XtPointer) globalRef, - XtListHead); - } - - /* To get wheel scrolling, we add an event handler to the directory list and - * file list widgets to handle mouse wheels */ - dirList = XmFileSelectionBoxGetChild(fdata->winData.comp.widget, XmDIALOG_DIR_LIST); - if (dirList != NULL) { - XtAddEventHandler(dirList, ButtonPressMask, False, File_handleWheel, - (XtPointer) globalRef); - } - - fileList = XmFileSelectionBoxGetChild(fdata->winData.comp.widget, XmDIALOG_LIST); - if (fileList != NULL) { - XtAddEventHandler(fileList, ButtonPressMask, False, File_handleWheel, - (XtPointer) globalRef); - } - - file = (*env)->GetObjectField(env, target, fileDialogIDs.file); - if (JNU_IsNull(env, file)) { - setFSBDirAndFile(fdata->winData.comp.widget, ".", "", NULL, -1); - } else { - char *fileString; - - fileString = (char *) JNU_GetStringPlatformChars(env, file, NULL); - setFSBDirAndFile(fdata->winData.comp.widget, ".", fileString, NULL, -1); - JNU_ReleaseStringPlatformChars(env, file, (const char *) fileString); - } - AWT_UNLOCK(); -} - -/* Event handler for making scrolling happen when the mouse wheel is rotated */ -void File_handleWheel(Widget w, XtPointer client_data, XEvent* event, Boolean* cont) { - unsigned int btn; - Widget scrolledWindow = NULL; - - /* only registered for ButtonPress, so don't need to check event type */ - btn = event->xbutton.button; - /* wheel up and wheel down show up as button 4 and 5, respectively */ - if (btn == 4 || btn == 5) { - scrolledWindow = XtParent(w); - if (scrolledWindow == NULL) { - return; - } - awt_util_do_wheel_scroll(scrolledWindow, - java_awt_event_MouseWheelEvent_WHEEL_UNIT_SCROLL, - 3, - btn == 4 ? -1 : 1); - } -} - - -/* - * Class: sun_awt_motif_MFileDialogPeer - * Method: pReshape - * Signature: (IIII)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFileDialogPeer_pReshape - (JNIEnv *env, jobject this, jint x, jint y, jint w, jint h) -{ - struct FrameData *wdata; - - AWT_LOCK(); - wdata = (struct FrameData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (wdata == NULL || wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - /* GES: AVH's hack from awt_util.c: - * Motif ignores attempts to move a toplevel window to 0,0. - * Instead we set the position to 1,1. The expected value is - * returned by Frame.getBounds() since it uses the internally - * held rectangle rather than querying the peer. - */ - - if ((x == 0) && (y == 0)) { - XtVaSetValues(wdata->winData.shell, XmNx, 1, XmNy, 1, NULL); - } - XtVaSetValues(wdata->winData.shell, - XtNx, (XtArgVal) x, - XtNy, (XtArgVal) y, - NULL); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MFileDialogPeer - * Method: pDispose - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFileDialogPeer_pDispose - (JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - - AWT_LOCK(); - wdata = (struct FrameData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtUnmanageChild(wdata->winData.shell); - awt_util_consumeAllXEvents(wdata->winData.shell); - XtDestroyWidget(wdata->winData.shell); - free((void *) wdata); - JNU_SetLongFieldFromPtr(env,this,mComponentPeerIDs.pData,NULL); - awtJNI_DeleteGlobalRef(env, this); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MFileDialogPeer - * Method: pShow - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFileDialogPeer_pShow - (JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - XmString dirMask = NULL; - - AWT_LOCK(); - wdata = (struct FrameData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtManageChild(wdata->winData.comp.widget); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MFileDialogPeer - * Method: pHide - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFileDialogPeer_pHide - (JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - - AWT_LOCK(); - wdata = (struct FrameData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (XtIsManaged(wdata->winData.comp.widget)) { - XtUnmanageChild(wdata->winData.comp.widget); - } - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MFileDialogPeer - * Method: setFileEntry - * Signature: (Ljava/lang/String;Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFileDialogPeer_setFileEntry - (JNIEnv *env, jobject this, jstring dir, jstring file, jobjectArray ffiles) -{ - struct ComponentData *cdata; - char *cdir; - char *cfile; - char *cf; - struct FrameData *wdata; - int32_t length, i; - XmString * files = NULL; - jstring jf; - - AWT_LOCK(); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (wdata == NULL || wdata->winData.comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - - cdir = (JNU_IsNull(env, dir)) - ? NULL - : (char *) JNU_GetStringPlatformChars(env, dir, NULL); - - cfile = (JNU_IsNull(env, file)) - ? NULL - : (char *) JNU_GetStringPlatformChars(env, file, NULL); - - if (ffiles != NULL) { - length = (*env)->GetArrayLength(env, ffiles); - files = (XmString*)calloc(length, sizeof(XmString)); - - for (i = 0; i < length; i++) { - jf = (jstring)(*env)->GetObjectArrayElement(env, ffiles, i); - cf = (char *) JNU_GetStringPlatformChars(env, jf, NULL); - - if ((*env)->GetStringLength(env, jf) == 0 && length == 1) { - length = 0; - files[0] = NULL; - } - else - files[i] = XmStringCreateLocalized(cf); - - if (cf) - JNU_ReleaseStringPlatformChars(env, jf, (const char *) cf); - } - - setFSBDirAndFile(wdata->winData.comp.widget, (cdir) ? cdir : "", - (cfile) ? cfile : "", files, length); - while(i > 0) { - XmStringFree(files[--i]); - } - if (files != NULL) { - free(files); - } - } - else - setFSBDirAndFile(wdata->winData.comp.widget, (cdir) ? cdir : "", - (cfile) ? cfile : "", NULL, -1); - - if (cdir) { - JNU_ReleaseStringPlatformChars(env, dir, (const char *) cdir); - } - - if (cfile) { - JNU_ReleaseStringPlatformChars(env, file, (const char *) cfile); - } - - AWT_FLUSH_UNLOCK(); -} - -static void -changeFont(Widget w, void *fontList) -{ - XtVaSetValues(w, XmNfontList, fontList, NULL); -} - -/* - * Class: sun_awt_motif_MFileDialogPeer - * Method: setFont - * Signature: (Ljava/awt/Font;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFileDialogPeer_setFont - (JNIEnv *env, jobject this, jobject f) -{ - struct ComponentData *tdata; - struct FontData *fdata; - XmFontListEntry fontentry; - XmFontList fontlist; - char *err; - - if (JNU_IsNull(env, f)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - fdata = awtJNI_GetFontData(env, f, &err); - if (fdata == NULL) { - JNU_ThrowInternalError(env, err); - AWT_UNLOCK(); - return; - } - tdata = (struct ComponentData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (tdata == NULL || tdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (awtJNI_IsMultiFont(env, f)) { - if (fdata->xfs == NULL) { - fdata->xfs = awtJNI_MakeFontSet(env, f); - } - if (fdata->xfs != NULL) { - fontentry = XmFontListEntryCreate("labelFont", - XmFONT_IS_FONTSET, - (XtPointer) (fdata->xfs)); - fontlist = XmFontListAppendEntry(NULL, fontentry); - /* - * Some versions of motif have a bug in - * XmFontListEntryFree() which causes it to free more than it - * should. Use XtFree() instead. See O'Reilly's - * Motif Reference Manual for more information. - */ - XmFontListEntryFree(&fontentry); - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - - if (fontlist != NULL) { - /* setting the fontlist in the FileSelectionBox is not good enough -- - you have to set the resource for all the descendants individually */ - awt_util_mapChildren(tdata->widget, changeFont, 1, (void *)fontlist); - XmFontListFree(fontlist); - } else { - JNU_ThrowNullPointerException(env, "NullPointerException"); - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MFileDialogPeer - * Method: insertReplaceFileDialogText - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFileDialogPeer_insertReplaceFileDialogText - (JNIEnv *env, jobject this, jstring l) -{ - struct ComponentData *cdata; - char *cl; - XmTextPosition start, end; - Widget textField; - jobject font; - - /* - * Replaces the text in the FileDialog's textfield with the passed - * string. - */ - - AWT_LOCK(); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - textField = XmFileSelectionBoxGetChild(cdata->widget, XmDIALOG_TEXT); - - if (textField == NULL) { - JNU_ThrowNullPointerException(env, "Null TextField in FileDialog"); - AWT_UNLOCK(); - return; - } - - font = awtJNI_GetFont(env, this); - - if (JNU_IsNull(env, l)) { - cl = NULL; - } else { - /* - * We use makePlatformCString() to convert unicode to EUC here, - * although output only components (Label/Button/Menu..) - * is not using make/allocCString() functions anymore. - * Because Motif TextFiled widget does not support multi-font - * compound string. - */ - - cl = (char *) JNU_GetStringPlatformChars(env, l, NULL); - } - - if (!XmTextGetSelectionPosition(textField, &start, &end)) { - start = end = XmTextGetInsertionPosition(textField); - } - XmTextReplace(textField, start, end, cl); - - if (cl != NULL && cl !="") { - JNU_ReleaseStringPlatformChars(env, l, cl); - } - AWT_FLUSH_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_GlobalCursorManager.c b/jdk/src/solaris/native/sun/awt/awt_GlobalCursorManager.c deleted file mode 100644 index a64aeed210a..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_GlobalCursorManager.c +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 1999-2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "awt_Component.h" -#include "sun_awt_motif_MComponentPeer.h" - -#include "jni.h" -#include "jni_util.h" - -static jfieldID xID; -static jfieldID yID; - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct ComponentIDs componentIDs; -extern struct ContainerIDs containerIDs; -extern jobject getCurComponent(); - -/* - * Class: sun_awt_motif_MGlobalCursorManager - * Method: cacheInit - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MGlobalCursorManager_cacheInit - (JNIEnv *env, jclass cls) -{ - jclass clsDimension = (*env)->FindClass(env, "java/awt/Point"); - xID = (*env)->GetFieldID(env, clsDimension, "x", "I"); - yID = (*env)->GetFieldID(env, clsDimension, "y", "I"); -} - -/* - * Class: sun_awt_motif_MGlobalCursorManager - * Method: getCursorPos - * Signature: (Ljava/awt/Point;)Ljava/awt/Component - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MGlobalCursorManager_getCursorPos - (JNIEnv *env, jobject this, jobject point) -{ - Window root, rw, cw; - int32_t rx, ry, x, y; - uint32_t kbs; - - AWT_LOCK(); - root = RootWindow(awt_display, DefaultScreen(awt_display)); - XQueryPointer(awt_display, root, &rw, &cw, &rx, &ry, &x, &y, &kbs); - - (*env)->SetIntField(env, point, xID, rx); - (*env)->SetIntField(env, point, yID, ry); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MGlobalCursorManager - * Method: getCursorPos - * Signature: ()Ljava/awt/Component - */ -JNIEXPORT jobject JNICALL Java_sun_awt_motif_MGlobalCursorManager_findHeavyweightUnderCursor - (JNIEnv *env, jobject this) -{ - jobject target; - - AWT_LOCK(); - target = getCurComponent(); - AWT_FLUSH_UNLOCK(); - return target; -} - -/* - * Class: sun_awt_motif_MGlobalCursorManager - * Method: getLocationOnScreen - * Signature: (Ljava/awt/Component;)Ljava/awt/Point - */ -JNIEXPORT jobject JNICALL Java_sun_awt_motif_MGlobalCursorManager_getLocationOnScreen - (JNIEnv *env, jobject this, jobject component) -{ - jobject point = - (*env)->CallObjectMethod(env, component, - componentIDs.getLocationOnScreen); - return point; -} - -/* - * Class: sun_awt_motif_MGlobalCursorManager - * Method: findComponentAt - * Signature: (Ljava/awt/Container;II)Ljava/awt/Component - */ -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_MGlobalCursorManager_findComponentAt - (JNIEnv *env, jobject this, jobject container, jint x, jint y) -{ - /* - * Call private version of Container.findComponentAt with the following - * flag set: ignoreEnabled = false (i.e., don't return or recurse into - * disabled Components). - * NOTE: it may return a JRootPane's glass pane as the target Component. - */ - jobject component = - (*env)->CallObjectMethod(env, container, containerIDs.findComponentAt, - x, y, JNI_FALSE); - return component; -} diff --git a/jdk/src/solaris/native/sun/awt/awt_KeyboardFocusManager.c b/jdk/src/solaris/native/sun/awt/awt_KeyboardFocusManager.c deleted file mode 100644 index 14774d771cf..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_KeyboardFocusManager.c +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "jni.h" -#include "jni_util.h" - -#include "awt_KeyboardFocusManager.h" -#include "java_awt_KeyboardFocusManager.h" -#include "java_awt_event_FocusEvent.h" -#include "awt_Component.h" -#include "canvas.h" -#include "awt_MToolkit.h" - -extern struct MComponentPeerIDs mComponentPeerIDs; - -struct KeyboardFocusManagerIDs keyboardFocusManagerIDs; - -/* - * Class: java_awt_KeyboardFocusManager - * Method: initIDs - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_java_awt_KeyboardFocusManager_initIDs - (JNIEnv *env, jclass cls) -{ - jclass keyclass = NULL; - - keyboardFocusManagerIDs.keyboardFocusManagerCls = (jclass) - (*env)->NewGlobalRef(env, cls); - keyboardFocusManagerIDs.shouldNativelyFocusHeavyweightMID = - (*env)->GetStaticMethodID(env, cls, "shouldNativelyFocusHeavyweight", - "(Ljava/awt/Component;Ljava/awt/Component;ZZJLsun/awt/CausedFocusEvent$Cause;)I"); - keyboardFocusManagerIDs.heavyweightButtonDownMID = - (*env)->GetStaticMethodID(env, cls, "heavyweightButtonDown", - "(Ljava/awt/Component;J)V"); - keyboardFocusManagerIDs.heavyweightButtonDownZMID = - (*env)->GetStaticMethodID(env, cls, "heavyweightButtonDown", - "(Ljava/awt/Component;JZ)V"); - keyboardFocusManagerIDs.markClearGlobalFocusOwnerMID = - (*env)->GetStaticMethodID(env, cls, "markClearGlobalFocusOwner", - "()Ljava/awt/Window;"); - - keyboardFocusManagerIDs.processSynchronousTransferMID = - (*env)->GetStaticMethodID(env, cls, "processSynchronousLightweightTransfer", - "(Ljava/awt/Component;Ljava/awt/Component;ZZJ)Z"); - - keyclass = (*env)->FindClass(env, "java/awt/event/KeyEvent"); - DASSERT (keyclass != NULL); - - keyboardFocusManagerIDs.isProxyActive = - (*env)->GetFieldID(env, keyclass, "isProxyActive", - "Z"); - - (*env)->DeleteLocalRef(env, keyclass); - - DASSERT(keyboardFocusManagerIDs.keyboardFocusManagerCls != NULL); - DASSERT(keyboardFocusManagerIDs.shouldNativelyFocusHeavyweightMID != - NULL); - DASSERT(keyboardFocusManagerIDs.heavyweightButtonDownMID != NULL); - DASSERT(keyboardFocusManagerIDs.heavyweightButtonDownZMID != NULL); - DASSERT(keyboardFocusManagerIDs.markClearGlobalFocusOwnerMID != NULL); - DASSERT(keyboardFocusManagerIDs.processSynchronousTransferMID != NULL); -} - -/* - * Class: java_awt_KeyboardFocusManager - * Method: getNativeFocusOwner - * Signature: ()Ljava/awt/Component; - */ -JNIEXPORT jobject JNICALL -Java_sun_awt_KeyboardFocusManagerPeerImpl_getNativeFocusOwner - (JNIEnv *env, jclass cls) -{ - jobject l_peer; - - AWT_LOCK(); - l_peer = awt_canvas_getFocusOwnerPeer(); - AWT_UNLOCK(); - - return (l_peer != NULL) - ? (*env)->GetObjectField(env, l_peer, mComponentPeerIDs.target) - : NULL; -} - -/* - * Class: java_awt_KeyboardFocusManager - * Method: getNativeFocusedWindow - * Signature: ()Ljava/awt/Window; - */ -JNIEXPORT jobject JNICALL -Java_sun_awt_KeyboardFocusManagerPeerImpl_getNativeFocusedWindow - (JNIEnv *env, jclass cls) -{ - jobject l_peer; - - AWT_LOCK(); - l_peer = awt_canvas_getFocusedWindowPeer(); - AWT_UNLOCK(); - - return (l_peer != NULL) - ? (*env)->GetObjectField(env, l_peer, mComponentPeerIDs.target) - : NULL; -} - -/* - * Class: java_awt_KeyboardFocusManager - * Method: clearGlobalFocusOwner - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_KeyboardFocusManagerPeerImpl_clearNativeGlobalFocusOwner - (JNIEnv *env, jobject self, jobject activeWindow) -{ - /* Redirect focus to the focus proxy of the active Window. The effect - we want is for the active Window to remain active, but for none of - its children to be the focus owner. AWT maintains state to know - that any key events delivered after this call (but before focus is - re-established elsewhere) get ignored. */ - - Widget proxy; - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - return; - } - - AWT_LOCK(); - - if (activeWindow != NULL) { - // Setting focus owner to proxy will be equivalent to having - // null focus owner in Java layer while we will still be - // able to receive key events. - proxy = findWindowsProxy(activeWindow, env); - - if (proxy != NULL) { - Widget curFocusWidget = XmGetFocusWidget(proxy); - if (curFocusWidget != NULL) { - callFocusHandler(curFocusWidget, FocusOut, NULL); - } - - // Disable all but proxy widgets - processTree(curFocusWidget, proxy, False); - - XmProcessTraversal(proxy, XmTRAVERSE_CURRENT); - } - } - - AWT_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Label.c b/jdk/src/solaris/native/sun/awt/awt_Label.c deleted file mode 100644 index f690ad939e9..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Label.c +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 1995-2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "java_awt_Color.h" -#include "java_awt_Font.h" -#include "java_awt_Label.h" -#include "sun_awt_motif_MLabelPeer.h" -#include "sun_awt_motif_MComponentPeer.h" - -#include "awt_Component.h" - -#include "multi_font.h" -#include -#include - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -static char emptyString[] = ""; - - -/* - * Class: sun_awt_motif_MLabelPeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MLabelPeer_create - (JNIEnv *env, jobject this, jobject parent) -{ - struct ComponentData *cdata; - struct ComponentData *wdata; - jobject target; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; - AWT_LOCK(); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, parent, mComponentPeerIDs.pData); - - if (JNU_IsNull(env, target) || wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - cdata = ZALLOC(ComponentData); - if (cdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - JNU_SetLongFieldFromPtr(env, this, mComponentPeerIDs.pData,cdata); - - adata = copyGraphicsConfigToPeer(env, this); - - cdata->widget = XtVaCreateManagedWidget("", - xmLabelWidgetClass, wdata->widget, - XmNhighlightThickness, 0, - XmNalignment, XmALIGNMENT_BEGINNING, - XmNrecomputeSize, False, - XmNuserData, (XtPointer) globalRef, - XmNtraversalOn, True, - XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen), - XmNfontList, getMotifFontList(), - NULL); - XtSetMappedWhenManaged(cdata->widget, False); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MLabelPeer - * Method: setText - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MLabelPeer_setText - (JNIEnv *env, jobject this, jstring label) -{ - char *clabel = NULL; - char *clabelEnd; - struct ComponentData *cdata; - XmString xim = NULL; - jobject font; - Boolean isMultiFont; - - AWT_LOCK(); - - font = awtJNI_GetFont(env, this); - isMultiFont = awtJNI_IsMultiFont(env, font); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (JNU_IsNull(env, label)) { - clabel = emptyString; - } else { - if (isMultiFont) { - if ((*env)->GetStringLength(env, label) <= 0) { - xim = XmStringCreateLocalized(""); - } else { - xim = awtJNI_MakeMultiFontString(env, label, font); - } - } else { - clabel = (char *) JNU_GetStringPlatformChars(env, label, NULL); - - /* scan for any \n's and terminate the string at that point */ - clabelEnd = strchr(clabel, '\n'); - if (clabelEnd != NULL) { - *clabelEnd = '\0'; - } - } - } - - if (!isMultiFont) { - xim = XmStringCreate(clabel, "labelFont"); - } - XtVaSetValues(cdata->widget, XmNlabelString, xim, NULL); - - if (!isMultiFont) { - /* Must test for "" too! */ - if (clabel != NULL && (*clabel != '\0')) { - JNU_ReleaseStringPlatformChars(env, label, (const char *) clabel); - } - } - XmStringFree(xim); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MLabelPeer - * Method: setAlignment - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MLabelPeer_setAlignment - (JNIEnv *env, jobject this, jint alignment) -{ - struct ComponentData *cdata; - - AWT_LOCK(); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - switch (alignment) { - case java_awt_Label_LEFT: - XtVaSetValues(cdata->widget, - XmNalignment, XmALIGNMENT_BEGINNING, - NULL); - break; - - case java_awt_Label_CENTER: - XtVaSetValues(cdata->widget, - XmNalignment, XmALIGNMENT_CENTER, - NULL); - break; - - case java_awt_Label_RIGHT: - XtVaSetValues(cdata->widget, - XmNalignment, XmALIGNMENT_END, - NULL); - break; - - default: - break; - } - - AWT_FLUSH_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_List.c b/jdk/src/solaris/native/sun/awt/awt_List.c deleted file mode 100644 index 00643444970..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_List.c +++ /dev/null @@ -1,600 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "java_awt_List.h" -#include "java_awt_AWTEvent.h" -#include "sun_awt_motif_MListPeer.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "java_awt_event_MouseWheelEvent.h" -#include "canvas.h" - -#include "awt_Component.h" - -#include "multi_font.h" -#include -#include - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct ComponentIDs componentIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - - -/* - * client_data = MListPeer instance - */ -static void -Slist_callback(Widget w, XtPointer client_data, XtPointer call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - XmListCallbackStruct *cbs = (XmListCallbackStruct *) call_data; - - switch (cbs->reason) { - case XmCR_DEFAULT_ACTION: { - ConvertEventTimeAndModifiers converted; - - awt_util_convertEventTimeAndModifiers(cbs->event, &converted); - - if (cbs->event->type == KeyPress) { - /* When Default action comes from keyboard, no notification - * is given by motif that a selection has been made, even - * though, internally, the item will now be selected regardless - * of whether or not it was previously selected. ( on mouse - * generated DEFAULT ACTIONS the XmCR_BROWSE_SELECT is - * generated first ). - */ - JNU_CallMethodByName(env, NULL, (jobject) client_data - ,"handleListChanged" - ,"(I)V" - ,(cbs->item_position - 1)); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - - JNU_CallMethodByName(env, NULL, (jobject) client_data - ,"action" - ,"(IJI)V" - ,(cbs->item_position - 1) - ,converted.when - ,converted.modifiers); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - break; - } - case XmCR_BROWSE_SELECT: - JNU_CallMethodByName(env, NULL, (jobject) client_data - ,"handleListChanged" - ,"(I)V" - ,(cbs->item_position - 1)); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - break; - - case XmCR_MULTIPLE_SELECT: - JNU_CallMethodByName(env, NULL, (jobject) client_data - ,"handleListChanged" - ,"(I)V" - ,(cbs->item_position - 1)); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - break; - - default: - break; - } -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_create - (JNIEnv *env, jobject this, jobject parent) -{ - Cardinal argc; -#define MAX_ARGC 40 - Arg args[MAX_ARGC]; - struct ComponentData *wdata; - struct ListData *sdata; - Pixel bg; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; - - AWT_LOCK(); - - adata = copyGraphicsConfigToPeer(env, this); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - wdata = (struct ComponentData *) JNU_GetLongFieldAsPtr(env,parent,mComponentPeerIDs.pData); - - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - sdata = (struct ListData *) calloc(1, sizeof(struct ListData)); - - JNU_SetLongFieldFromPtr(env,this,mComponentPeerIDs.pData,sdata); - if (sdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - XtVaGetValues(wdata->widget, XmNbackground, &bg, NULL); - argc = 0; - XtSetArg(args[argc], XmNrecomputeSize, False); - argc++; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNlistSizePolicy, XmCONSTANT); - argc++; - XtSetArg(args[argc], XmNx, 0); - argc++; - XtSetArg(args[argc], XmNy, 0); - argc++; - XtSetArg(args[argc], XmNmarginTop, 0); - argc++; - XtSetArg(args[argc], XmNmarginBottom, 0); - argc++; - XtSetArg(args[argc], XmNmarginLeft, 0); - argc++; - XtSetArg(args[argc], XmNmarginRight, 0); - argc++; - XtSetArg(args[argc], XmNmarginHeight, 0); - argc++; - XtSetArg(args[argc], XmNmarginWidth, 0); - argc++; - XtSetArg(args[argc], XmNlistMarginHeight, 0); - argc++; - XtSetArg(args[argc], XmNlistMarginWidth, 0); - argc++; - XtSetArg(args[argc], XmNscrolledWindowMarginWidth, 0); - argc++; - XtSetArg(args[argc], XmNscrolledWindowMarginHeight, 0); - argc++; - XtSetArg(args[argc], XmNuserData, (XtPointer) globalRef); - argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen)); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - sdata->list = XmCreateScrolledList(wdata->widget, - "slist", - args, - argc); - - sdata->comp.widget = XtParent(sdata->list); - XtSetMappedWhenManaged(sdata->comp.widget, False); - XtAddCallback(sdata->list, - XmNdefaultActionCallback, - Slist_callback, - (XtPointer) globalRef); - XtAddEventHandler(sdata->list, FocusChangeMask, - True, awt_canvas_event_handler, globalRef); - - awt_addWidget(sdata->list, sdata->comp.widget, globalRef, - java_awt_AWTEvent_KEY_EVENT_MASK | - java_awt_AWTEvent_MOUSE_EVENT_MASK | - java_awt_AWTEvent_MOUSE_MOTION_EVENT_MASK); - - XtManageChild(sdata->list); - XtManageChild(sdata->comp.widget); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: setMultipleSelections - * Signature: (Z)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_setMultipleSelections - (JNIEnv *env, jobject this, jboolean v) -{ - struct ListData *sdata; - jobject globalRef; - int32_t selPos; - Boolean selected; - - AWT_LOCK(); - - sdata = (struct ListData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - globalRef = (jobject) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.jniGlobalRef); - if (v == JNI_FALSE) { - XtVaSetValues(sdata->list, - XmNselectionPolicy, XmBROWSE_SELECT, - NULL); - XtRemoveCallback(sdata->list, - XmNmultipleSelectionCallback, - Slist_callback, - (XtPointer) globalRef); - XtAddCallback(sdata->list, - XmNbrowseSelectionCallback, - Slist_callback, - (XtPointer) globalRef); - - // If we change the selection mode from multiple to single - // we need to decide what the item should be selected: - // If a selected item has the location cursor, only that - // item will remain selected. If no selected item has the - // location cursor, all items will be deselected. - selPos = XmListGetKbdItemPos(sdata->list); - selected = XmListPosSelected(sdata->list, selPos); - XmListDeselectAllItems(sdata->list); - if (selected) { - Java_sun_awt_motif_MListPeer_select(env, this, selPos-1); - } - - } else { - XtVaSetValues(sdata->list, - XmNselectionPolicy, XmMULTIPLE_SELECT, - NULL); - XtRemoveCallback(sdata->list, - XmNbrowseSelectionCallback, - Slist_callback, - (XtPointer) globalRef); - XtAddCallback(sdata->list, - XmNmultipleSelectionCallback, - Slist_callback, - (XtPointer) globalRef); - } - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: setBackground - * Signature: (Ljava/awt/Color;)V - */ - -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_setBackground - (JNIEnv *env, jobject this, jobject c) -{ - struct ListData *ldata; - Pixel color; - - if (JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - ldata = (struct ListData *) - JNU_GetLongFieldAsPtr(env,this, mComponentPeerIDs.pData); - if (ldata == NULL || ldata->list == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - color = awtJNI_GetColor(env, c); - XtVaSetValues(ldata->list, - XmNbackground, color, - NULL); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: isSelected - * Signature: (I)Z - */ -JNIEXPORT jboolean JNICALL Java_sun_awt_motif_MListPeer_isSelected - (JNIEnv *env, jobject this, jint pos) -{ - struct ListData *sdata; - - AWT_LOCK(); - - sdata = (struct ListData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return JNI_FALSE; - } - pos++; - if (XmListPosSelected(sdata->list, pos) == True) { - AWT_UNLOCK(); - return JNI_TRUE; - } else { - AWT_UNLOCK(); - return JNI_FALSE; - } -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: addItem - * Signature: (Ljava/lang/String;I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_addItem - (JNIEnv *env, jobject this, jstring item, jint index) -{ - XmString im; - struct ListData *sdata; - jobject font; - - /* - * Note: - * There used to be code in this function to fix: - * 4067355 size of listbox depends on when pack() is called (solaris) - * The fix (for jdk1.1.7) involved unmapping the List widget before the add - * is done and resizing/remapping it after the add. This causes significant - * performance degradation if addItem() is called a lot. A bug was filed - * on this performance problem: 4117288 - * The fix was backed out after testing that: - * - the problem reported in 4067355 was no longer reproducible - * - the performance problem is gone - */ - - AWT_LOCK(); - if (JNU_IsNull(env, item)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - sdata = (struct ListData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - font = awtJNI_GetFont(env, this); - - if (awtJNI_IsMultiFont(env, font)) { - im = awtJNI_MakeMultiFontString(env, item, font); - } else { - char *temp; - - temp = (char *) JNU_GetStringPlatformChars(env, item, NULL); - im = XmStringCreateLocalized(temp); - JNU_ReleaseStringPlatformChars(env, item, (const char *)temp); - } - - /* motif uses 1-based indeces for the list operations with 0 */ - /* referring to the last item on the list. Thus if index is -1 */ - /* then we'll get the right effect of adding to the end of the */ - /* list. */ - index++; - - XmListAddItemUnselected(sdata->list, im, index); - XmStringFree(im); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: delItems - * Signature: (II)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_delItems - (JNIEnv *env, jobject this, jint start, jint end) -{ - struct ListData *sdata; - Boolean was_mapped; - jobject target; - Position width, height; - int32_t itemCount; - - AWT_LOCK(); - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - if (JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - sdata = (struct ListData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - /* [jk] catch bogus indexes (Sun bug) */ - XtVaGetValues(sdata->list, XmNitemCount, &itemCount, NULL); - if (itemCount == 0) { - AWT_UNLOCK(); - return; - } - if (start > itemCount) { - start = itemCount; - } - if (end > itemCount) { - end = itemCount; - } - start++; - end++; - - XtVaGetValues(sdata->comp.widget, XmNmappedWhenManaged, &was_mapped, NULL); - - /* If it was visible, then make it invisible while we update */ - if (was_mapped) { - XtSetMappedWhenManaged(sdata->comp.widget, False); - } - - if (start == end) { - XmListDeletePos(sdata->list, start); - } else { - XmListDeleteItemsPos(sdata->list, end - start + 1, start); - } - - width = (*env)->GetIntField(env, target, componentIDs.width); - height = (*env)->GetIntField(env, target, componentIDs.height); - XtVaSetValues(sdata->comp.widget, - XmNwidth, (width > 1) ? width-1 : 1, - XmNheight, (height > 1) ? height-1 : 1, - NULL); - XtVaSetValues(sdata->comp.widget, - XmNwidth, (width > 0) ? width : 1, - XmNheight, (height > 0) ? height : 1, - NULL); - /* If it was visible, then make it visible again once updated */ - if (was_mapped) { - XtSetMappedWhenManaged(sdata->comp.widget, True); - } - - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: pSelect - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_select - (JNIEnv *env, jobject this, jint pos) -{ - struct ListData *sdata; - - AWT_LOCK(); - sdata = (struct ListData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - pos++; - XmListSelectPos(sdata->list, pos, False); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: pDeselect - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_deselect - (JNIEnv *env, jobject this, jint pos) -{ - struct ListData *sdata; - - AWT_LOCK(); - sdata = (struct ListData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - pos++; - XmListDeselectPos(sdata->list, pos); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: makeVisible - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_makeVisible - (JNIEnv *env, jobject this, jint pos) -{ - int32_t top, visible; - struct ListData *sdata; - - AWT_LOCK(); - sdata = (struct ListData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtVaGetValues(sdata->list, - XmNtopItemPosition, &top, - XmNvisibleItemCount, &visible, - NULL); - pos++; - if (pos < top) { - XmListSetPos(sdata->list, pos); - } else { - XmListSetBottomPos(sdata->list, pos); - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MListPeer - * Method: nativeHandleMouseWheel - * Signature: (III)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MListPeer_nativeHandleMouseWheel - (JNIEnv *env, jobject this, jint scrollType, jint scrollAmt, jint wheelAmt) -{ - struct ListData *ldata; - Widget list = NULL; - Widget scroll = NULL; - - AWT_LOCK(); - ldata = (struct ListData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (ldata == NULL || ldata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - // get the List widget - list = ldata->list; - if (list == NULL) { - AWT_UNLOCK(); - return; - } - - // get the ScrolledWindow - scroll = XtParent(list); - if (scroll == NULL) { - AWT_UNLOCK(); - return; - } - - awt_util_do_wheel_scroll(scroll, scrollType, scrollAmt, wheelAmt); - AWT_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_MToolkit.c b/jdk/src/solaris/native/sun/awt/awt_MToolkit.c index aeeae217239..cef75987915 100644 --- a/jdk/src/solaris/native/sun/awt/awt_MToolkit.c +++ b/jdk/src/solaris/native/sun/awt/awt_MToolkit.c @@ -48,7 +48,7 @@ /* JNI field and method ids */ #include "awt_Component.h" -#include "awt_Cursor.h" +//#include "awt_Cursor.h" #include "awt_MenuComponent.h" #include "awt_TopLevel.h" #include "canvas.h" diff --git a/jdk/src/solaris/native/sun/awt/awt_Menu.c b/jdk/src/solaris/native/sun/awt/awt_Menu.c deleted file mode 100644 index 3b2b3918dec..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Menu.c +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright 1995-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "color.h" -#include "java_awt_Menu.h" -#include "sun_awt_motif_MMenuPeer.h" -#include "java_awt_MenuBar.h" -#include "sun_awt_motif_MMenuBarPeer.h" - -#include "awt_MenuBar.h" -#include "awt_MenuComponent.h" -#include "awt_MenuItem.h" -#include "awt_Menu.h" - -#include "multi_font.h" -#include -#include -#include - -extern struct MenuComponentIDs menuComponentIDs; -extern struct MenuItemIDs menuItemIDs; -extern struct MMenuItemPeerIDs mMenuItemPeerIDs; -extern struct MMenuBarPeerIDs mMenuBarPeerIDs; - -struct MenuIDs menuIDs; - -/* - * Class: java_awt_Menu - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - Menu.java to initialize the fieldIDs for fields that may - be accessed from C */ - -JNIEXPORT void JNICALL Java_java_awt_Menu_initIDs - (JNIEnv *env, jclass cls) -{ - menuIDs.tearOff = (*env)->GetFieldID(env, cls, "tearOff", "Z"); - menuIDs.isHelpMenu = (*env)->GetFieldID(env, cls, "isHelpMenu", "Z"); -} - -/* - * Fix for Bug Traq 4251941 - segfault after double tear-off and close - * Removes the lost callback from menu item on tear-off control re-creation. - * Only for internal use, to be used from awtTearOffActivatedCallback - */ -static void awtTearOffShellDestroy(Widget widget, XtPointer closure, XtPointer data) { - if (widget != NULL ) { - XtSetKeyboardFocus(widget, NULL); - } -} - -/* - * Fix for Bug Traq 4251941 - segfault after double tear-off and close - * This callback is added to menu after the creation. - * It adds the destroy callback awtTearOffShellDestroy to remove the lost focus callback on destroy - */ -static void awtTearOffActivatedCallback(Widget widget, XtPointer closure, XtPointer data) { - Widget shell; - shell = XtParent(widget); - if (shell != NULL && XtClass(shell) == transientShellWidgetClass) { - XtAddCallback(shell, XtNdestroyCallback, awtTearOffShellDestroy, widget); - } -} - -extern Boolean skipNextNotifyWhileGrabbed; - -static void -Menu_popDownCB(Widget w, XtPointer client_data, XtPointer calldata) -{ - skipNextNotifyWhileGrabbed = True; -} - - - -/* - * this is a MMenuPeer instance - */ -static void -awtJNI_CreateMenu(JNIEnv * env, jobject this, Widget menuParent) -{ - int32_t argc; -#define MAX_ARGC 10 - Arg args[MAX_ARGC]; - char *ctitle = NULL; - struct MenuData *mdata; - struct FontData *fdata; - Pixel bg; - Pixel fg; - XmFontList fontlist = NULL; - Widget tearOff; - XmString mfstr = NULL; - XmString str = NULL; - jobject target; - jobject targetFont; - jobject label; - jobject font; - jboolean IsMultiFont; - jboolean isTearOff; - - /* perhaps this is unncessary, if awtJNI_CreateMenu is only called - * from a native method. - */ - if ((*env)->PushLocalFrame(env, (jint)16) < (jint)0) { - return; - } - - fdata = NULL; - - target = (*env)->GetObjectField(env, this, mMenuItemPeerIDs.target); - if (JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - (*env)->PopLocalFrame(env, NULL); - return; - } - font = JNU_CallMethodByName(env, NULL, target, "getFont_NoClientCode", - "()Ljava/awt/Font;").l; - - mdata = ZALLOC(MenuData); - JNU_SetLongFieldFromPtr(env, this, mMenuItemPeerIDs.pData, mdata); - if (mdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - (*env)->PopLocalFrame(env, NULL); - return; - } - targetFont = (*env)->GetObjectField(env, target, menuComponentIDs.font); - if (!JNU_IsNull(env, targetFont) && - (fdata = awtJNI_GetFontData(env, targetFont, NULL)) != NULL) { - IsMultiFont = awtJNI_IsMultiFont(env, targetFont); - } else { - IsMultiFont = awtJNI_IsMultiFont(env, font); - } - - label = (*env)->GetObjectField(env, target, menuItemIDs.label); - if (JNU_IsNull(env, label)) { - mfstr = XmStringCreateLocalized(""); - ctitle = ""; - } else { - if (IsMultiFont) { - mfstr = awtJNI_MakeMultiFontString(env, label, font); - } else { - ctitle = (char *) JNU_GetStringPlatformChars(env, label, NULL); - } - } - - XtVaGetValues(menuParent, XmNbackground, &bg, NULL); - XtVaGetValues(menuParent, XmNforeground, &fg, NULL); - - argc = 0; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNforeground, fg); - argc++; - - XtSetArg(args[argc], XmNlabelFontList, getMotifFontList()); - argc++; - XtSetArg(args[argc], XmNbuttonFontList, getMotifFontList()); - argc++; - - isTearOff = (*env)->GetBooleanField(env, target, menuIDs.tearOff); - - if (isTearOff) { - XtSetArg(args[argc], XmNtearOffModel, XmTEAR_OFF_ENABLED); - argc++; - } - - if (IsMultiFont) { - DASSERT(!(argc > MAX_ARGC)); - mdata->itemData.comp.widget = XmCreatePulldownMenu(menuParent, - "", - args, - argc); - } else { - DASSERT(!(argc > MAX_ARGC)); - mdata->itemData.comp.widget = XmCreatePulldownMenu(menuParent, - ctitle, - args, - argc); - } - awt_addMenuWidget(mdata->itemData.comp.widget); - - if (isTearOff) { - tearOff = XmGetTearOffControl(mdata->itemData.comp.widget); - XtVaSetValues(tearOff, - XmNbackground, bg, - XmNforeground, fg, - XmNhighlightColor, fg, - NULL); - XtAddCallback(mdata->itemData.comp.widget, XmNtearOffMenuActivateCallback, - awtTearOffActivatedCallback, NULL); - } - argc = 0; - XtSetArg(args[argc], XmNsubMenuId, mdata->itemData.comp.widget); - argc++; - - if (IsMultiFont) { - XtSetArg(args[argc], XmNlabelString, mfstr); - } else { - str = XmStringCreate(ctitle, XmSTRING_DEFAULT_CHARSET); - XtSetArg(args[argc], XmNlabelString, str); - } - argc++; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNforeground, fg); - argc++; - - if (!JNU_IsNull(env, targetFont) && (fdata != NULL)) { - if (IsMultiFont) { - fontlist = awtJNI_GetFontList(env, targetFont); - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - XtSetArg(args[argc], XmNfontList, fontlist); - argc++; - } else { - if (IsMultiFont) { - fontlist = awtJNI_GetFontList(env, font); - XtSetArg(args[argc], XmNfontList, fontlist); - argc++; - } - } - - if (IsMultiFont) { - DASSERT(!(argc > MAX_ARGC)); - mdata->comp.widget = XmCreateCascadeButton(menuParent, "", args, argc); - } else { - DASSERT(!(argc > MAX_ARGC)); - mdata->comp.widget = XmCreateCascadeButton(menuParent, ctitle, args, argc); - } - - if ((*env)->GetBooleanField(env, target, menuIDs.isHelpMenu)) { - XtVaSetValues(menuParent, - XmNmenuHelpWidget, mdata->comp.widget, - NULL); - } - - /** - * Add callback to MenuShell of the menu so we know when - * menu pops down. mdata->itemData.comp.widget is RowColumn, - * its parent - MenuShell. - */ - XtAddCallback(XtParent(mdata->itemData.comp.widget), XtNpopdownCallback, - Menu_popDownCB, - (XtPointer) - JNU_GetLongFieldAsPtr(env, this, - mMenuItemPeerIDs.jniGlobalRef)); - - /* - * Free resources - */ - if (!JNU_IsNull(env, targetFont)) { - XmFontListFree(fontlist); - } - - if (mfstr != NULL) { - XmStringFree(mfstr); - mfstr = NULL; - } - - if (str) { - XmStringFree(str); - str = NULL; - } - - XtManageChild(mdata->comp.widget); - XtSetSensitive(mdata->comp.widget, - (*env)->GetBooleanField(env, target, menuItemIDs.enabled) ? - True : False); - - if (ctitle != NULL && ctitle != "") { - JNU_ReleaseStringPlatformChars(env, label, (const char *) ctitle); - } - (*env)->PopLocalFrame(env, NULL); -} - - -/* - * Class: sun_awt_motif_MMenuPeer - * Method: createMenu - * Signature: (Lsun/awt/motif/MMenuBarPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuPeer_createMenu - (JNIEnv *env, jobject this, jobject parent) -{ - struct ComponentData *mbdata; - AwtGraphicsConfigDataPtr adata; - - AWT_LOCK(); - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - mbdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, parent, mMenuBarPeerIDs.pData); - if (mbdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - awtJNI_CreateMenu(env, this, mbdata->widget); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MMenuPeer - * Method: createSubMenu - * Signature: (Lsun/awt/motif/MMenuPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuPeer_createSubMenu -(JNIEnv *env, jobject this, jobject parent) -{ - struct MenuData *mpdata; - AwtGraphicsConfigDataPtr adata; - - AWT_LOCK(); - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - mpdata = (struct MenuData *) - JNU_GetLongFieldAsPtr(env, parent, mMenuItemPeerIDs.pData); - if (mpdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - awtJNI_CreateMenu(env, this, mpdata->itemData.comp.widget); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MMenuPeer - * Method: pDispose - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuPeer_pDispose - (JNIEnv *env, jobject this) -{ - struct MenuData *mdata; - Widget parent; - Boolean isParentManaged = False; - - AWT_LOCK(); - - mdata = (struct MenuData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - if (mdata == NULL) { - AWT_UNLOCK(); - return; - } - awt_delMenuWidget(mdata->itemData.comp.widget); - XtUnmanageChild(mdata->comp.widget); - awt_util_consumeAllXEvents(mdata->itemData.comp.widget); - awt_util_consumeAllXEvents(mdata->comp.widget); - - parent = XtParent(mdata->itemData.comp.widget); - if (parent != NULL && XtIsManaged(parent)) { - isParentManaged = True; - XtUnmanageChild(parent); - } - - XtDestroyWidget(mdata->itemData.comp.widget); - - if (isParentManaged) { - XtManageChild(parent); - } - - XtDestroyWidget(mdata->comp.widget); - free((void *) mdata); - AWT_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Menu.h b/jdk/src/solaris/native/sun/awt/awt_Menu.h deleted file mode 100644 index 97a12c05270..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Menu.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#include - -/* fieldIDs for Menu fields that may be accessed from C */ -struct MenuIDs { - jfieldID tearOff; - jfieldID isHelpMenu; -}; diff --git a/jdk/src/solaris/native/sun/awt/awt_MenuBar.c b/jdk/src/solaris/native/sun/awt/awt_MenuBar.c deleted file mode 100644 index 903293e828e..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_MenuBar.c +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright 1995-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "java_awt_MenuBar.h" -#include "sun_awt_motif_MMenuBarPeer.h" -#include "java_awt_Menu.h" -#include "java_awt_Frame.h" -#include "sun_awt_motif_MFramePeer.h" - -#include "awt_GraphicsEnv.h" -#include "awt_MenuBar.h" -#include "awt_Component.h" - -#include -#include - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct X11GraphicsConfigIDs x11GraphicsConfigIDs; -struct MMenuBarPeerIDs mMenuBarPeerIDs; - -/* - * Class: sun_awt_motif_MMenuBarPeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for MMenuBarPeer.java - to initialize the fieldIDs fields that may be accessed from C */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MMenuBarPeer_initIDs - (JNIEnv *env, jclass cls) -{ - mMenuBarPeerIDs.pData = (*env)->GetFieldID(env, cls, "pData", "J"); - mMenuBarPeerIDs.graphicsConfig = - (*env)->GetFieldID(env, cls, "graphicsConfig", - "Lsun/awt/X11GraphicsConfig;"); -} - -static AwtGraphicsConfigDataPtr -copyGraphicsConfigToMenuBarPeer( -JNIEnv *env, jobject frame, jobject thisMenuBar) { - - jobject gc_object; - AwtGraphicsConfigDataPtr adata; - - /* GraphicsConfiguration object of Component */ - gc_object = (*env)->GetObjectField(env, frame, - mComponentPeerIDs.graphicsConfig); - - if (gc_object != NULL) { - /* Set graphicsConfig field of MComponentPeer */ - (*env)->SetObjectField (env, thisMenuBar, - mMenuBarPeerIDs.graphicsConfig, - gc_object); - adata = (AwtGraphicsConfigDataPtr) - JNU_GetLongFieldAsPtr(env, gc_object, - x11GraphicsConfigIDs.aData); - } else { - /* Component was not constructed with a GraphicsConfiguration - object */ - adata = getDefaultConfig(DefaultScreen(awt_display)); - } - - return adata; -} - -AwtGraphicsConfigDataPtr -getGraphicsConfigFromMenuBarPeer(JNIEnv *env, jobject menubarPeer) { - - jobject gc_object; - AwtGraphicsConfigDataPtr adata; - - /* GraphicsConfiguration object of Component */ - gc_object = (*env)->GetObjectField(env, menubarPeer, - mMenuBarPeerIDs.graphicsConfig); - - if (gc_object != NULL) { - adata = (AwtGraphicsConfigDataPtr) - JNU_GetLongFieldAsPtr(env, gc_object, - x11GraphicsConfigIDs.aData); - } else { - adata = getDefaultConfig(DefaultScreen(awt_display)); - } - - return adata; -} - -/* - * Class: sun_awt_motif_MMenuBarPeer - * Method: create - * Signature: (Lsun/awt/motif/MFramePeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuBarPeer_create - (JNIEnv * env, jobject this, jobject frame) -{ -#define MAX_ARGC 20 - Arg args[MAX_ARGC]; - int32_t argc; - struct ComponentData *mdata; - struct FrameData *wdata; - Pixel bg; - Pixel fg; - AwtGraphicsConfigDataPtr adata; - - if (JNU_IsNull(env, frame)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, frame, mComponentPeerIDs.pData); - mdata = ZALLOC(ComponentData); - - if (wdata == NULL || mdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - JNU_SetLongFieldFromPtr(env, this, mMenuBarPeerIDs.pData, mdata); - - adata = copyGraphicsConfigToMenuBarPeer(env, frame, this); - - XtVaGetValues(wdata->winData.comp.widget, - XmNbackground, &bg, - XmNforeground, &fg, - NULL); - - argc = 0; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNforeground, fg); - argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen)); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - mdata->widget = XmCreateMenuBar(wdata->mainWindow, "menu_bar", args, argc); - awt_addMenuWidget(mdata->widget); - XtSetMappedWhenManaged(mdata->widget, False); - XtManageChild(mdata->widget); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MMenuBarPeer - * Method: dispose - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuBarPeer_pDispose - (JNIEnv * env, jobject this) -{ - struct ComponentData *mdata; - - AWT_LOCK(); - - /*hania LOOK HERE does this make sense? look at original code */ - mdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mMenuBarPeerIDs.pData); - if (mdata == NULL) { - AWT_UNLOCK(); - return; - } - awt_delMenuWidget(mdata->widget); - XtUnmanageChild(mdata->widget); - awt_util_consumeAllXEvents(mdata->widget); - XtDestroyWidget(mdata->widget); - free((void *) mdata); - (*env)->SetLongField(env, this, mMenuBarPeerIDs.pData, (jlong)0); - AWT_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_MenuBar.h b/jdk/src/solaris/native/sun/awt/awt_MenuBar.h deleted file mode 100644 index 8d2cf8bf541..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_MenuBar.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -/* fieldIDs for MMenuBarPeer fields that may be accessed from C */ -struct MMenuBarPeerIDs { - jfieldID pData; - jfieldID graphicsConfig; -}; diff --git a/jdk/src/solaris/native/sun/awt/awt_MenuComponent.c b/jdk/src/solaris/native/sun/awt/awt_MenuComponent.c deleted file mode 100644 index b63123f26e7..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_MenuComponent.c +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 1998-2006 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "java_awt_MenuComponent.h" -#include "jni_util.h" - -#include "awt_MenuComponent.h" - -struct MenuComponentIDs menuComponentIDs; - - -JNIEXPORT void JNICALL -Java_java_awt_MenuComponent_initIDs(JNIEnv *env, jclass cls) -{ - menuComponentIDs.font = - (*env)->GetFieldID(env, cls, "font", "Ljava/awt/Font;"); - menuComponentIDs.appContext = - (*env)->GetFieldID(env, cls, "appContext", "Lsun/awt/AppContext;"); - menuComponentIDs.getParent = - (*env)->GetMethodID( - env, cls, "getParent_NoClientCode", "()Ljava/awt/MenuContainer;"); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_MenuItem.c b/jdk/src/solaris/native/sun/awt/awt_MenuItem.c deleted file mode 100644 index 28eebc49685..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_MenuItem.c +++ /dev/null @@ -1,654 +0,0 @@ -/* - * Copyright 1995-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include -#include "java_awt_MenuItem.h" -#include "sun_awt_motif_MMenuItemPeer.h" -#include "sun_awt_motif_MCheckboxMenuItemPeer.h" -#include "java_awt_Menu.h" -#include "sun_awt_motif_MMenuPeer.h" - -#include "awt_MenuComponent.h" -#include "awt_MenuItem.h" - -#include "multi_font.h" -#include -#include -#include - -extern struct MenuComponentIDs menuComponentIDs; - -/* fieldIDs for MenuItem fields that may be accessed from C */ -struct MenuItemIDs menuItemIDs; - -/* - * Class: java_awt_MenuItem - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - MenuItem.java to initialize the fieldIDs for fields that may - be accessed from C */ - -JNIEXPORT void JNICALL Java_java_awt_MenuItem_initIDs - (JNIEnv *env, jclass cls) -{ - menuItemIDs.label = - (*env)->GetFieldID(env, cls, "label", "Ljava/lang/String;"); - menuItemIDs.enabled = - (*env)->GetFieldID(env, cls, "enabled", "Z"); - menuItemIDs.shortcut = - (*env)->GetFieldID(env, cls, "shortcut", "Ljava/awt/MenuShortcut;"); -} - -/* fieldIDs for MMenuItemPeer fields that may be accessed from C */ -struct MMenuItemPeerIDs mMenuItemPeerIDs; - -/* - * Class: sun_awt_motif_MMenuItemPeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - MMenuItemPeer.java to initialize the fieldIDs for fields that may - be accessed from C */ - -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuItemPeer_initIDs - (JNIEnv *env, jclass cls) -{ - mMenuItemPeerIDs.target = - (*env)->GetFieldID(env, cls, "target", "Ljava/awt/MenuItem;"); - mMenuItemPeerIDs.pData = (*env)->GetFieldID(env, cls, "pData", "J"); - mMenuItemPeerIDs.isCheckbox = - (*env)->GetFieldID(env, cls, "isCheckbox", "Z"); - mMenuItemPeerIDs.jniGlobalRef = - (*env)->GetFieldID(env, cls, "jniGlobalRef", "J"); -} - -/* - * Class: sun_awt_motif_MMenuItemPeer - * Method: getParent_NoClientCode - * Signature: (Ljava/awt/MenuComponent;)Ljava/awt/MenuContainer; - * - * Gets the MenuContainer parent of this object, without executing client - * code (e.g., no code in subclasses will be executed). - */ -JNIEXPORT jobject JNICALL Java_sun_awt_motif_MMenuItemPeer_getParent_1NoClientCode - (JNIEnv *env, jclass thisClass, jobject menuComponent) -{ - jobject parent = NULL; - - /* getParent is actually getParent_NoClientCode() */ - parent = (*env)->CallObjectMethod( - env,menuComponent,menuComponentIDs.getParent); - DASSERT(!((*env)->ExceptionOccurred(env))); - return parent; -} - -/* - * client_data is MMenuItemPeer instance pointer - */ -static void -MenuItem_selected(Widget w, XtPointer client_data, XmAnyCallbackStruct * s) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject) client_data; - ConvertEventTimeAndModifiers converted; - - awt_util_convertEventTimeAndModifiers(s->event, &converted); - - if ((*env)->GetBooleanField(env, this, mMenuItemPeerIDs.isCheckbox)) { - jboolean state; - struct MenuItemData *mdata; - - mdata = (struct MenuItemData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - - if (mdata != NULL) { - XtVaGetValues(mdata->comp.widget, XmNset, &state, NULL); - - JNU_CallMethodByName(env, NULL, this - ,"action" - ,"(JIZ)V" - ,converted.when, converted.modifiers, - state); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - } else { - JNU_CallMethodByName(env, NULL, this, "action", "(JI)V", - converted.when, converted.modifiers); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } -} - -/* - * Class: sun_awt_motif_MMenuItemPeer - * Method: createMenuItem - * Signature: (Lsun/awt/motif/MMenuPeer;)V - * - * ASSUMES: This function is never called by a privileged thread - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuItemPeer_createMenuItem( -JNIEnv *env, jobject this, jobject parent) -{ - int32_t argc; -#define MAX_ARGC 20 - Arg args[MAX_ARGC]; - char *clabel; - struct MenuData *menuData; - struct MenuItemData *mdata; - struct FontData *fdata; - Pixel bg; - Pixel fg; - XmFontList fontlist = NULL; - jobject target; - jobject targetFont; - XmString mfstr = NULL; - XmString shortcut_str = NULL; - XmString str = NULL; - jobject font; - jobject shortcut; - jboolean IsMultiFont; - jboolean isCheckbox; - jstring label; - jobject globalRef = (*env)->NewGlobalRef(env, this); - const jchar *unicodeLabel = NULL; - jsize unicodeLabelLen = 0; - jboolean isCopy = JNI_FALSE; - - // We call client code on this thread, so it must *NOT* be privileged - DASSERT(!awt_currentThreadIsPrivileged(env)); - - JNU_SetLongFieldFromPtr(env, this, mMenuItemPeerIDs.jniGlobalRef, - globalRef); - - fdata = NULL; - - fflush(stderr); - target = - (*env)->GetObjectField(env, this, mMenuItemPeerIDs.target); - if (JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - font = JNU_CallMethodByName(env, NULL, target, "getFont_NoClientCode", - "()Ljava/awt/Font;").l; - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - menuData = (struct MenuData *) - JNU_GetLongFieldAsPtr(env, parent, mMenuItemPeerIDs.pData); - - targetFont = - (*env)->GetObjectField(env, target, menuComponentIDs.font); - if (!JNU_IsNull(env, targetFont) && - (fdata = awtJNI_GetFontData(env, targetFont, NULL)) != NULL) { - IsMultiFont = awtJNI_IsMultiFont(env, targetFont); - } else { - IsMultiFont = awtJNI_IsMultiFont(env, font); - } - - label = (*env)->GetObjectField(env, target, menuItemIDs.label); - if (JNU_IsNull(env, label) || ((*env)->GetStringLength (env, label) == 0)) { - mfstr = XmStringCreateLocalized(""); - clabel = ""; - } else { - if (IsMultiFont) { - mfstr = awtJNI_MakeMultiFontString(env, label, font); - } else { - mfstr = XmStringCreateLocalized(""); - } - clabel = (char *) JNU_GetStringPlatformChars(env, label, NULL); - } - - mdata = ZALLOC(MenuItemData); - JNU_SetLongFieldFromPtr(env, this, mMenuItemPeerIDs.pData, mdata); - - argc = 0; - XtSetArg(args[argc], XmNbackground, &bg); - argc++; - XtSetArg(args[argc], XmNforeground, &fg); - argc++; - XtGetValues(menuData->itemData.comp.widget, args, argc); - - argc = 0; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNforeground, fg); - argc++; - - /* check if the label is "-" but don't use strcmp(clabel, "-") because - * the high-order bytes in the unicode characters are not present in - * the C string (bugid 4099695) - */ - if (!JNU_IsNull(env, label)) { - unicodeLabel = (*env)->GetStringChars(env, label, &isCopy); - unicodeLabelLen = (*env)->GetStringLength(env, label); - } - if ((unicodeLabel != NULL) && (unicodeLabel[0] == '-') && - (unicodeLabelLen == 1)) { - DASSERT(!(argc > MAX_ARGC)); - mdata->comp.widget = XmCreateSeparator(menuData->itemData.comp.widget, - "", args, argc); - } else { - if (IsMultiFont) { - XtSetArg(args[argc], XmNlabelString, mfstr); - } else { - str = XmStringCreate(clabel, XmSTRING_DEFAULT_CHARSET); - XtSetArg(args[argc], XmNlabelString, str); - } - argc++; - - shortcut = - (*env)->GetObjectField(env, target, menuItemIDs.shortcut); - if (!JNU_IsNull(env, shortcut)) { - jstring shortcutText; - char *text = ""; - - shortcutText = JNU_CallMethodByName(env, NULL, shortcut, - "toString", - "()Ljava/lang/String;").l; - - if (!JNU_IsNull(env, shortcutText)) { - text = (char *) JNU_GetStringPlatformChars(env, shortcutText, NULL); - } - shortcut_str = XmStringCreate(text, XmSTRING_DEFAULT_CHARSET); - XtSetArg(args[argc], XmNacceleratorText, shortcut_str); - - argc++; - - if (!JNU_IsNull(env, shortcutText)) { - JNU_ReleaseStringPlatformChars(env, shortcutText, (const char *) text); - } - } - if (!JNU_IsNull(env, targetFont) && (fdata != NULL)) { - if (IsMultiFont) { - fontlist = awtJNI_GetFontList(env, targetFont); - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - XtSetArg(args[argc], XmNfontList, fontlist); - argc++; - } else { - if (IsMultiFont) { - fontlist = awtJNI_GetFontList(env, font); - XtSetArg(args[argc], XmNfontList, fontlist); - argc++; - } - } - - isCheckbox = - (*env)->GetBooleanField(env, this, mMenuItemPeerIDs.isCheckbox); - if (isCheckbox) { - /* Fix for 4090493 */ - if (IsMultiFont) { - /* FontData that correspond to XmNfontList we just set */ - struct FontData *fdataForIndSize; - Dimension indSize; - if (!JNU_IsNull(env, targetFont) && (fdata != NULL)) { - fdataForIndSize = fdata; - } - else { - fdataForIndSize = awtJNI_GetFontData(env, font, NULL); - } - indSize = awt_adjustIndicatorSizeForMenu(awt_computeIndicatorSize(fdataForIndSize)); - if (indSize != MOTIF_XmINVALID_DIMENSION) { - XtSetArg(args[argc], XmNindicatorSize, indSize); argc++; - } - } - /* End of fix for 4090493 */ - XtSetArg(args[argc], XmNset, False); - argc++; - XtSetArg(args[argc], XmNvisibleWhenOff, True); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - mdata->comp.widget = XmCreateToggleButton(menuData->itemData.comp.widget, - clabel, - args, - argc); - } else { - DASSERT(!(argc > MAX_ARGC)); - mdata->comp.widget = XmCreatePushButton(menuData->itemData.comp.widget, - clabel, - args, - argc); - } - XtAddCallback(mdata->comp.widget, - ((isCheckbox) ? XmNvalueChangedCallback : XmNactivateCallback), - (XtCallbackProc) MenuItem_selected, - (XtPointer) globalRef); - - XtSetSensitive(mdata->comp.widget, - (*env)->GetBooleanField(env, target, menuItemIDs.enabled) ? - True : False); - - - if (!JNU_IsNull(env, targetFont)) { - XmFontListFree(fontlist); - } - } - - if (clabel && (clabel != "")) { - JNU_ReleaseStringPlatformChars(env, label, clabel); - } - - /* - * Free up resources after we have created the widget - */ - if (mfstr != NULL) { - XmStringFree(mfstr); - mfstr = NULL; - } - if (str) { - XmStringFree(str); - str = NULL; - } - if (shortcut_str) { - XmStringFree(shortcut_str); - shortcut_str = NULL; - } - if (isCopy == JNI_TRUE) { - (*env)->ReleaseStringChars(env, label, unicodeLabel); - } - - XtManageChild(mdata->comp.widget); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MMenuItemPeer - * Method: pSetLabel - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuItemPeer_pSetLabel -(JNIEnv *env, jobject this, jstring label) -{ - struct ComponentData *wdata; - char *clabel; - XmString xim; - - AWT_LOCK(); - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (JNU_IsNull(env, label) || ((*env)->GetStringLength (env, label) == 0)) { - xim = XmStringCreateLocalized(""); - } else { - jobject font; - jobject target; - - target = (*env)->GetObjectField(env, this, mMenuItemPeerIDs.target); - if (JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - font = JNU_CallMethodByName(env, NULL, target, "getFont_NoClientCode", - "()Ljava/awt/Font;").l; - - if (awtJNI_IsMultiFont(env, font)) { - xim = awtJNI_MakeMultiFontString(env, label, font); - } else { - clabel = (char *) JNU_GetStringPlatformChars(env, label, NULL); - xim = XmStringCreate(clabel, "labelFont"); - JNU_ReleaseStringPlatformChars(env, label, clabel); - } - } - XtUnmanageChild(wdata->widget); - XtVaSetValues(wdata->widget, XmNlabelString, xim, NULL); - XtManageChild(wdata->widget); - XmStringFree(xim); - AWT_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MMenuItemPeer - * Method: pSetShortCut - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuItemPeer_pSetShortcut -(JNIEnv *env, jobject this, jstring shortcut) -{ - struct ComponentData *wdata; - char *cshortcut; - XmString xim; - - - AWT_LOCK(); - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (JNU_IsNull(env, shortcut)) { - xim = XmStringCreateLocalized(""); - } else { - jobject font; - jobject target; - - target = (*env)->GetObjectField(env, this, mMenuItemPeerIDs.target); - if (JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - font = JNU_CallMethodByName(env, NULL, target, "getFont_NoClientCode", - "()Ljava/awt/Font;").l; - - if (awtJNI_IsMultiFont(env, font)) { - xim = awtJNI_MakeMultiFontString(env, shortcut, font); - } else { - cshortcut = (char *) JNU_GetStringPlatformChars(env, shortcut, NULL); - xim = XmStringCreate(cshortcut, "labelFont"); - JNU_ReleaseStringPlatformChars(env, shortcut, cshortcut); - } - } - - XtUnmanageChild(wdata->widget); - XtVaSetValues(wdata->widget, XmNacceleratorText, xim, NULL); - XtManageChild(wdata->widget); - XmStringFree(xim); - AWT_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MMenuItemPeer - * Method: pEnable - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuItemPeer_pEnable -(JNIEnv *env, jobject this) -{ - struct MenuItemData *mdata; - - AWT_LOCK(); - - mdata = (struct MenuItemData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - - if (mdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtSetSensitive(mdata->comp.widget, True); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MMenuItemPeer - * Method: pDisable - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuItemPeer_pDisable -(JNIEnv *env, jobject this) -{ - struct MenuItemData *mdata; - - AWT_LOCK(); - - mdata = (struct MenuItemData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - - if (mdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtSetSensitive(mdata->comp.widget, False); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MMenuItemPeer - * Method: pDispose - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MMenuItemPeer_pDispose -(JNIEnv *env, jobject this) -{ - struct MenuItemData *mdata; - Widget parent; - Boolean isParentManaged = False; - - AWT_LOCK(); - - mdata = (struct MenuItemData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - - if (mdata != NULL) { - /* Fix for 4280561:Workspace freezes, does not respond to mouse clicks - ** - ** this really helps a lot of Fujitsu problems, take down a popup - ** menu when removing items, on windows you could never get here, since - ** the show() of a popup menu puts it in a menu loop where further - ** events are processed in that loop, its like a modal dialog show, - ** in that it dosn't return till it comes down. - ** in X - future xevents will be dispatched immeadiatly, but some - ** may be still waiting on the java queue - which can cause them to be - ** dispatched out of order (sometimes hanging system !) - */ - /* note: should realy only take down if XtParent(mdata->comp.widget) - ** is the activePopup (in awt_PopupMenu.c) but ... - */ - { - removePopupMenus(); - } - XtUnmanageChild(mdata->comp.widget); - awt_util_consumeAllXEvents(mdata->comp.widget); - - parent = XtParent(mdata->comp.widget); - if (parent != NULL && XtIsManaged(parent)) { - isParentManaged = True; - XtUnmanageChild(parent); - } - - XtDestroyWidget(mdata->comp.widget); - - if (isParentManaged) { - XtManageChild(parent); - } - - free((void *) mdata); - (*env)->SetLongField(env, this, mMenuItemPeerIDs.pData, (jlong)0); - awtJNI_DeleteGlobalMenuRef(env, this); - } - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MCheckboxMenuItemPeer - * Method: pSetState - * Signature: (Z)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCheckboxMenuItemPeer_pSetState - (JNIEnv *env, jobject this, jboolean state) -{ - struct MenuItemData *mdata; - - AWT_LOCK(); - - mdata = (struct MenuItemData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - - if (mdata == NULL) { - JNU_ThrowNullPointerException(env, "menuitem data is null"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(mdata->comp.widget, XmNset, (Boolean)state, NULL); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MCheckboxMenuItemPeer - * Method: getState - * Signature: ()Z - */ -JNIEXPORT jboolean JNICALL Java_sun_awt_motif_MCheckboxMenuItemPeer_getState - (JNIEnv *env, jobject this) -{ - struct MenuItemData *mdata; - Boolean state; - - AWT_LOCK(); - - mdata = (struct MenuItemData *) - (*env)->GetLongField(env, this, mMenuItemPeerIDs.pData); - - if (mdata == NULL) { - JNU_ThrowNullPointerException(env, "menuitem data is null"); - AWT_UNLOCK(); - return JNI_FALSE; - } - XtVaGetValues(mdata->comp.widget, XmNset, &state, NULL); - AWT_UNLOCK(); - return ((state) ? JNI_TRUE : JNI_FALSE); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_PopupMenu.c b/jdk/src/solaris/native/sun/awt/awt_PopupMenu.c deleted file mode 100644 index afd186b7e5a..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_PopupMenu.c +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Copyright 1996-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include -#include -#include -#include "color.h" -#include "java_awt_PopupMenu.h" -#include "java_awt_Component.h" -#include "java_awt_Event.h" -#include "sun_awt_motif_MPopupMenuPeer.h" -#include "sun_awt_motif_MComponentPeer.h" - -#include "awt_PopupMenu.h" -#include "awt_MenuItem.h" -#include "awt_Component.h" -#include "awt_MenuComponent.h" -#include "awt_Menu.h" -#include "awt_Event.h" - -#include "multi_font.h" -#include -#include - -extern struct MMenuItemPeerIDs mMenuItemPeerIDs; -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct MenuComponentIDs menuComponentIDs; -extern struct MenuItemIDs menuItemIDs; -extern struct MenuIDs menuIDs; -extern AwtGraphicsConfigDataPtr -getGraphicsConfigFromComponentPeer(JNIEnv *env, jobject parentPeer); -extern Boolean keyboardGrabbed; -Boolean poppingDown = False; - -struct MPopupMenuPeerIDs mPopupMenuPeerIDs; - -static Widget activePopup; - -void removePopupMenus() { - if (activePopup != NULL && - XtIsManaged(activePopup)) - { - XtUnmanageChild(activePopup); - activePopup = NULL; - } -} - -Boolean awtMenuIsActive() { - return ((activePopup != NULL) || (awt_util_focusIsOnMenu(awt_display))); -} - -struct ClientDataStruct { - struct ComponentData *wdata; - jobject mMenuItemPeerIDs; -}; - -/* - * Class: sun_awt_motif_MPopupMenuPeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - MPopupMenuPeer.java to initialize the methodIDs for methods that may - be accessed from C */ - -JNIEXPORT void JNICALL Java_sun_awt_motif_MPopupMenuPeer_initIDs - (JNIEnv *env, jclass cls) -{ - mPopupMenuPeerIDs.destroyNativeWidgetAfterGettingTreeLock = - (*env)->GetMethodID(env, cls, - "destroyNativeWidgetAfterGettingTreeLock", "()V"); -} - -extern Boolean skipNextNotifyWhileGrabbed; - -static void -Popup_popUpCB(Widget w, XtPointer client_data, XtPointer calldata) -{ - skipNextNotifyWhileGrabbed = True; -} -/* - * client_data is MPopupMenuPeer instance - */ -static void -Popup_popdownCB(Widget w, XtPointer client_data, XtPointer calldata) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject target = NULL; - - /* - * Fix for 4394847. Due to the race keyboard remains grabbed after menu - * was disposed. Clear the grab status here instead of processOneEvent. - */ - poppingDown = True; - keyboardGrabbed = False; - skipNextNotifyWhileGrabbed = True; - - XtRemoveCallback(w, XtNpopdownCallback, - Popup_popdownCB, (XtPointer) client_data); - - (*env)->CallVoidMethod(env, (jobject) client_data, - mPopupMenuPeerIDs.destroyNativeWidgetAfterGettingTreeLock); - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -/* - * Class: sun_awt_motif_MPopupMenuPeer - * Method: createMenu - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MPopupMenuPeer_createMenu - (JNIEnv *env, jobject this, jobject parent) -{ - struct ComponentData *wdata; - struct MenuData *mdata; - struct FontData *fdata; - char *ctitle = NULL; - int32_t argc; -#define MAX_ARGC 10 - Arg args[MAX_ARGC]; - Pixel bg; - Pixel fg; - XmFontList fontlist = NULL; - XmString mfstr = NULL; - jobject font; - jobject target; - jobject targetFont; - jobject label; - jboolean IsMultiFont; - jboolean tearOff; - jobject globalRef = (*env)->NewGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; - - JNU_SetLongFieldFromPtr(env, this, - mMenuItemPeerIDs.jniGlobalRef, globalRef); - - - AWT_LOCK(); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - target = - (*env)->GetObjectField(env, this, mMenuItemPeerIDs.target); - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, parent, mComponentPeerIDs.pData); - - if (wdata == NULL || JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - mdata = ZALLOC(MenuData); - if (mdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - JNU_SetLongFieldFromPtr(env, this, mMenuItemPeerIDs.pData, mdata); - - adata = getGraphicsConfigFromComponentPeer(env, parent); - - /* - * Why are these different? - */ - font = JNU_CallMethodByName(env, NULL, target, "getFont_NoClientCode", - "()Ljava/awt/Font;").l; - targetFont = - (*env)->GetObjectField(env, target, menuComponentIDs.font); - if (!JNU_IsNull(env, targetFont) && - (fdata = awtJNI_GetFontData(env, targetFont, NULL)) != NULL) { - IsMultiFont = awtJNI_IsMultiFont(env, targetFont); - } else { - IsMultiFont = awtJNI_IsMultiFont(env, font); - } - - label = (*env)->GetObjectField(env, target, menuItemIDs.label); - if (JNU_IsNull(env, label)) { - mfstr = XmStringCreateLocalized(""); - ctitle = ""; - } else { - if (IsMultiFont) { - mfstr = awtJNI_MakeMultiFontString(env, label, font); - } else { - ctitle = (char *) JNU_GetStringPlatformChars(env, label, NULL); - } - } - - XtVaGetValues(wdata->widget, XmNbackground, &bg, NULL); - XtVaGetValues(wdata->widget, XmNforeground, &fg, NULL); - - argc = 0; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNforeground, fg); - argc++; - tearOff = (*env)->GetBooleanField(env, target, menuIDs.tearOff); - if (tearOff) { - XtSetArg(args[argc], XmNtearOffModel, XmTEAR_OFF_ENABLED); - argc++; - } - if (!JNU_IsNull(env, targetFont) - && (fdata = awtJNI_GetFontData(env, targetFont, NULL)) != NULL) { - if (IsMultiFont) { - fontlist = awtJNI_GetFontList(env, targetFont); - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - - XtSetArg(args[argc], XmNfontList, fontlist); - argc++; - } else { - if (IsMultiFont) { - fontlist = awtJNI_GetFontList(env, font); - XtSetArg(args[argc], XmNfontList, fontlist); - argc++; - } - } - - XtSetArg(args[argc], XmNvisual, adata->awt_visInfo.visual); - argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen)); - argc++; - - if (IsMultiFont) { - DASSERT(!(argc > MAX_ARGC)); - mdata->itemData.comp.widget = XmCreatePopupMenu(wdata->widget, - "", - args, - argc); - } else { - DASSERT(!(argc > MAX_ARGC)); - mdata->itemData.comp.widget = XmCreatePopupMenu(wdata->widget, - ctitle, - args, - argc); - } - awt_addMenuWidget(mdata->itemData.comp.widget); - - /* - * Fix for bug 4180147 - - * screen can be frozen when interacting with MB3 using AWT on Motif - */ - XtUngrabButton(wdata->widget, AnyButton, AnyModifier); - XtUngrabPointer(wdata->widget, CurrentTime); - - /* fix for bug #4169155: Popup menus get a leading separator on Motif - system. - Additional check that title string is not empty*/ - if (!JNU_IsNull(env, label) && - (*env)->GetStringUTFLength( env, label) != (jsize)0 ) { - if (IsMultiFont) { - XtVaCreateManagedWidget("", - xmLabelWidgetClass, - mdata->itemData.comp.widget, - XmNfontList, fontlist, - XmNlabelString, mfstr, - XmNbackground, bg, - XmNforeground, fg, - XmNhighlightColor, fg, - NULL); - XmStringFree(mfstr); - } else { - XmString xmstr = XmStringCreateLocalized(ctitle); - - XtVaCreateManagedWidget(ctitle, - xmLabelWidgetClass, - mdata->itemData.comp.widget, - XmNlabelString, xmstr, - XmNbackground, bg, - XmNforeground, fg, - XmNhighlightColor, fg, - NULL); - XmStringFree(xmstr); - JNU_ReleaseStringPlatformChars(env, label, (const char *) ctitle); - } - /* Create separator */ - XtVaCreateManagedWidget("", - xmSeparatorWidgetClass, - mdata->itemData.comp.widget, - XmNbackground, bg, - XmNforeground, fg, - NULL); - } - if (tearOff) { - Widget tearOffWidget = XmGetTearOffControl(mdata->itemData.comp.widget); - - XtVaSetValues(tearOffWidget, - XmNbackground, bg, - XmNforeground, fg, - XmNhighlightColor, fg, - NULL); - } - mdata->comp.widget = mdata->itemData.comp.widget; - - if (!JNU_IsNull(env, targetFont)) { - XmFontListFree(fontlist); - } - XtSetSensitive(mdata->comp.widget, - ((*env)->GetBooleanField(env, target, menuItemIDs.enabled) ? - True : False)); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MPopupMenuPeer - * Method: pShow - * Signature: (Ljava/awt/Event;IILsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MPopupMenuPeer_pShow - (JNIEnv *env, jobject this, jobject event, jint x, jint y, jobject origin) -{ - struct MenuData *mdata; - struct ComponentData *wdata; - XButtonEvent *bevent; - XButtonEvent *newEvent = NULL; - void *data; - - AWT_LOCK(); - - mdata = (struct MenuData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - if (mdata == NULL || JNU_IsNull(env, event)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, origin, mComponentPeerIDs.pData); - - if ( wdata == NULL || wdata->widget == NULL ) { /* 425598 */ - JNU_ThrowNullPointerException(env, "NullPointerException"); /* 425598 */ - AWT_UNLOCK(); /* 425598 */ - return; /* 425598 */ - } /* 425598 */ - - if (!XtIsRealized(wdata->widget)) { - JNU_ThrowInternalError(env, "widget not visible on screen"); - AWT_UNLOCK(); - return; - } - - /* - * Fix for BugTraq ID 4186663 - Pural PopupMenus appear at the same time. - * If another popup is currently visible hide it. - */ - if (activePopup != NULL && - activePopup != mdata->comp.widget && - XtIsObject(activePopup) && - XtIsManaged(activePopup)) { - removePopupMenus(); - } - - /* If the raw x event is not available, then we must use an unfortunate - * round-trip call to XTranslateCoordiates to get the root coordinates. - */ - data = JNU_GetLongFieldAsPtr(env, event, eventIDs.data); - if (data == NULL || ((XEvent *) data)->type != ButtonPress) { - int32_t rx, ry; - Window root, win; - - root = RootWindowOfScreen(XtScreen(wdata->widget)); - XTranslateCoordinates(awt_display, - XtWindow(wdata->widget), - root, - (int32_t) x, (int32_t) y, - &rx, &ry, - &win); - /* - printf("translated coords %d,%d to root %d,%d\n", x, y, rx, ry); - */ - - newEvent = (XButtonEvent *) malloc(sizeof(XButtonEvent)); - newEvent->type = ButtonPress; - newEvent->display = awt_display; - newEvent->window = XtWindow(wdata->widget); - newEvent->time = awt_util_getCurrentServerTime(); - newEvent->x = (int32_t) x; - newEvent->y = (int32_t) y; - newEvent->x_root = rx; - newEvent->y_root = ry; - bevent = newEvent; - - } else { - bevent = (XButtonEvent *) data; - } - - XtAddCallback(XtParent(mdata->comp.widget), XtNpopdownCallback, - Popup_popdownCB, - (XtPointer) - JNU_GetLongFieldAsPtr(env, this, - mMenuItemPeerIDs.jniGlobalRef)); - - XtAddCallback(XtParent(mdata->comp.widget), XtNpopupCallback, - Popup_popUpCB, - (XtPointer) - JNU_GetLongFieldAsPtr(env, this, - mMenuItemPeerIDs.jniGlobalRef)); - - - XmMenuPosition(mdata->comp.widget, bevent); - XtManageChild(mdata->comp.widget); - - /* - * Fix for BugTraq ID 4186663 - Pural PopupMenus appear at the same time. - * Store the pointer to the currently showing popup. - */ - activePopup = mdata->comp.widget; - - if (newEvent) { - free((void *) newEvent); - } - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MPopupMenuPeer - * Method: pDispose - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MPopupMenuPeer_pDispose - (JNIEnv *env, jobject this) -{ - struct MenuData *mdata; - - AWT_LOCK(); - - mdata = (struct MenuData *) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.pData); - - if (mdata == NULL) { - AWT_UNLOCK(); - return; - } - /* - * Fix for BugTraq ID 4186663 - Pural PopupMenus appear at the same time. - * Clear the pointer to the currently showing popup. - */ - if (activePopup == mdata->comp.widget) { - activePopup = NULL; - } - awt_delMenuWidget(mdata->itemData.comp.widget); - XtUnmanageChild(mdata->comp.widget); - awt_util_consumeAllXEvents(mdata->comp.widget); - XtDestroyWidget(mdata->comp.widget); - free((void *) mdata); - (*env)->SetLongField(env, this, mMenuItemPeerIDs.pData, (jlong)0); - - awtJNI_DeleteGlobalMenuRef(env, this); - - poppingDown = False; - AWT_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Robot.c b/jdk/src/solaris/native/sun/awt/awt_Robot.c index 10cf652d77e..07c053bce28 100644 --- a/jdk/src/solaris/native/sun/awt/awt_Robot.c +++ b/jdk/src/solaris/native/sun/awt/awt_Robot.c @@ -204,14 +204,8 @@ static XImage *getWindowImage(Display * display, Window window, /*********************************************************************************************/ -#ifdef XAWT -#define FUNC_NAME(name) Java_sun_awt_X11_XRobotPeer_ ## name -#else -#define FUNC_NAME(name) Java_sun_awt_motif_MRobotPeer_ ## name -#endif - JNIEXPORT void JNICALL -FUNC_NAME(setup) (JNIEnv * env, jclass cls) { +Java_sun_awt_X11_XRobotPeer_setup (JNIEnv * env, jclass cls) { int32_t xtestAvailable; DTRACE_PRINTLN("RobotPeer: setup()"); @@ -232,7 +226,7 @@ FUNC_NAME(setup) (JNIEnv * env, jclass cls) { } JNIEXPORT void JNICALL -FUNC_NAME(getRGBPixelsImpl)( JNIEnv *env, +Java_sun_awt_X11_XRobotPeer_getRGBPixelsImpl( JNIEnv *env, jclass cls, jobject xgc, jint x, @@ -295,7 +289,7 @@ FUNC_NAME(getRGBPixelsImpl)( JNIEnv *env, } JNIEXPORT void JNICALL -FUNC_NAME(keyPressImpl) (JNIEnv *env, +Java_sun_awt_X11_XRobotPeer_keyPressImpl (JNIEnv *env, jclass cls, jint keycode) { @@ -315,7 +309,7 @@ FUNC_NAME(keyPressImpl) (JNIEnv *env, } JNIEXPORT void JNICALL -FUNC_NAME(keyReleaseImpl) (JNIEnv *env, +Java_sun_awt_X11_XRobotPeer_keyReleaseImpl (JNIEnv *env, jclass cls, jint keycode) { AWT_LOCK(); @@ -333,7 +327,7 @@ FUNC_NAME(keyReleaseImpl) (JNIEnv *env, } JNIEXPORT void JNICALL -FUNC_NAME(mouseMoveImpl) (JNIEnv *env, +Java_sun_awt_X11_XRobotPeer_mouseMoveImpl (JNIEnv *env, jclass cls, jobject xgc, jint root_x, @@ -355,7 +349,7 @@ FUNC_NAME(mouseMoveImpl) (JNIEnv *env, } JNIEXPORT void JNICALL -FUNC_NAME(mousePressImpl) (JNIEnv *env, +Java_sun_awt_X11_XRobotPeer_mousePressImpl (JNIEnv *env, jclass cls, jint buttonMask) { AWT_LOCK(); @@ -379,7 +373,7 @@ FUNC_NAME(mousePressImpl) (JNIEnv *env, } JNIEXPORT void JNICALL -FUNC_NAME(mouseReleaseImpl) (JNIEnv *env, +Java_sun_awt_X11_XRobotPeer_mouseReleaseImpl (JNIEnv *env, jclass cls, jint buttonMask) { AWT_LOCK(); @@ -403,7 +397,7 @@ FUNC_NAME(mouseReleaseImpl) (JNIEnv *env, } JNIEXPORT void JNICALL -FUNC_NAME(mouseWheelImpl) (JNIEnv *env, +Java_sun_awt_X11_XRobotPeer_mouseWheelImpl (JNIEnv *env, jclass cls, jint wheelAmt) { /* Mouse wheel is implemented as a button press of button 4 and 5, so it */ diff --git a/jdk/src/solaris/native/sun/awt/awt_ScrollPane.c b/jdk/src/solaris/native/sun/awt/awt_ScrollPane.c deleted file mode 100644 index 1c6777cb92b..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_ScrollPane.c +++ /dev/null @@ -1,927 +0,0 @@ -/* - * Copyright 1996-2002 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" - -#include "java_awt_Adjustable.h" -#include "java_awt_Insets.h" -#include "java_awt_ScrollPane.h" -#include "java_awt_event_AdjustmentEvent.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "sun_awt_motif_MScrollPanePeer.h" -#include "java_awt_AWTEvent.h" - -#include "awt_Component.h" -#include "canvas.h" - -#include -#include -#include - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -/* fieldIDs for ScrollPane fields that may be accessed from C */ -static struct ScrollPaneIDs { - jfieldID scrollbarDisplayPolicy; -} scrollPaneIDs; - -/* - * Class: java_awt_ScrollPane - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - ScrollPane.java to initialize the fieldIDs for fields that may - be accessed from C */ - -JNIEXPORT void JNICALL Java_java_awt_ScrollPane_initIDs - (JNIEnv *env, jclass cls) -{ - scrollPaneIDs.scrollbarDisplayPolicy = - (*env)->GetFieldID(env, cls, "scrollbarDisplayPolicy", "I"); -} - -/* fieldIDs for MScrollPanePeer fields that may be accessed from C */ -static struct MScrollPanePeerIDs { - jmethodID postScrollEventID; -} mScrollPanePeerIDs; - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - MScrollPanePeer.java to initialize the fieldIDs for fields that may - be accessed from C */ - -JNIEXPORT void JNICALL Java_sun_awt_motif_MScrollPanePeer_initIDs - (JNIEnv *env, jclass cls) -{ - mScrollPanePeerIDs.postScrollEventID = - (*env)->GetMethodID(env, cls, "postScrollEvent", "(IIIZ)V"); -} - -static void -dump_scroll_attrs(Widget scrollbar) -{ - unsigned char orient; - int32_t value, size, incr, pIncr, max, min; - - XtVaGetValues(scrollbar, - XmNvalue, &value, - XmNincrement, &incr, - XmNpageIncrement, &pIncr, - XmNsliderSize, &size, - XmNmaximum, &max, - XmNminimum, &min, - XmNorientation, &orient, - NULL); - - jio_fprintf(stdout, "%s: min=%d max=%d slider-size=%d incr=%d pageIncr=%d value = %d\n", - orient == XmVERTICAL ? "VSB" : "HSB", min, max, size, - incr, pIncr, value); -} - - -/* - * client_data is MScrollPanePeer instance - */ -static void -postScrollEvent(jint jorient, jobject peer, XmScrollBarCallbackStruct *scroll) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - jint jscrollcode; - jboolean jadjusting = JNI_FALSE; - - switch (scroll->reason) { - case XmCR_DECREMENT: - jscrollcode = java_awt_event_AdjustmentEvent_UNIT_DECREMENT; - break; - case XmCR_INCREMENT: - jscrollcode = java_awt_event_AdjustmentEvent_UNIT_INCREMENT; - break; - case XmCR_PAGE_DECREMENT: - jscrollcode = java_awt_event_AdjustmentEvent_BLOCK_DECREMENT; - break; - case XmCR_PAGE_INCREMENT: - jscrollcode = java_awt_event_AdjustmentEvent_BLOCK_INCREMENT; - break; - case XmCR_DRAG: - jscrollcode = java_awt_event_AdjustmentEvent_TRACK; - jadjusting = JNI_TRUE; - break; - case XmCR_VALUE_CHANGED: /* drag finished */ - case XmCR_TO_TOP: - case XmCR_TO_BOTTOM: - jscrollcode = java_awt_event_AdjustmentEvent_TRACK; - break; - default: - DASSERT(FALSE); - return; - } - - (*env)->CallVoidMethod(env, peer, mScrollPanePeerIDs.postScrollEventID, - jorient, jscrollcode, (jint)scroll->value, jadjusting); - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -/* - * client_data is MScrollPanePeer instance - */ -static void -ScrollPane_scrollV(Widget w, XtPointer client_data, XtPointer call_data) -{ - postScrollEvent(java_awt_Adjustable_VERTICAL, (jobject)client_data, - (XmScrollBarCallbackStruct *)call_data); -} - -/* - * client_data is MScrollPanePeer instance - */ -static void -ScrollPane_scrollH(Widget w, XtPointer client_data, XtPointer call_data) -{ - postScrollEvent(java_awt_Adjustable_HORIZONTAL, (jobject)client_data, - (XmScrollBarCallbackStruct *)call_data); -} - - -typedef XmNavigability (*NavigableCallback) (Widget); - -NavigableCallback oldClipNavigable = NULL; -Boolean clipCallbackInitialized = False; -XmNavigability MyClipNavigable(Widget wid) { - // We've installed this function for ClipWindow - if (XmIsClipWindow(wid)) { - // To be able to request focus on ClipWindow by call - // XmProcessTraversal(, XmTRAVERSE_CURRENT) we need to make - // it return XmCONTROL_NAVIGABLE. Default implementation returns - // DESCENDANTS_TAB_NAVIGABLE which doesn't allow this. - return XmCONTROL_NAVIGABLE; - } - if (oldClipNavigable) { - return oldClipNavigable(wid); - } - // this will never happen - return XmCONTROL_NAVIGABLE; -} - -const char * ScrollPaneManagerName = "ScrolledWindowClipWindow"; -NavigableCallback oldManagerNavigable = NULL; -Boolean managerCallbackInitialized = False; -XmNavigability MyManagerNavigable(Widget wid) { - // We've installed this function for Manager - // with the name ScrollPaneManagerName - if (XmIsManager(wid) - && ( XtName(wid) != NULL && strcmp(XtName(wid), ScrollPaneManagerName) == 0) ) - { - // To be able to request focus on Manager by call - // XmProcessTraversal(, XmTRAVERSE_CURRENT) we need to make - // it return XmCONTROL_NAVIGABLE. Default implementation returns - // DESCENDANTS_TAB_NAVIGABLE which doesn't allow this. - return XmCONTROL_NAVIGABLE; - } - if (oldManagerNavigable) { - return oldManagerNavigable(wid); - } - // this will never happen - return XmCONTROL_NAVIGABLE; -} - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MScrollPanePeer_create - (JNIEnv *env, jobject this, jobject parent) -{ - int32_t argc; -#define MAX_ARGC 40 - Arg args[MAX_ARGC]; - struct ComponentData *wdata; - struct ComponentData *sdata; - jobject target; - Pixel bg; - Widget vsb, hsb; - jint sbDisplay; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; - - AWT_LOCK(); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,parent,mComponentPeerIDs.pData); - - if (JNU_IsNull(env, target) || wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - sdata = ZALLOC(ComponentData); - JNU_SetLongFieldFromPtr(env,this,mComponentPeerIDs.pData,sdata); - - if (sdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - XtVaGetValues(wdata->widget, XmNbackground, &bg, NULL); - - adata = copyGraphicsConfigToPeer(env, this); - - argc = 0; - - sbDisplay = - (*env)->GetIntField(env, target, scrollPaneIDs.scrollbarDisplayPolicy); - - XtSetArg(args[argc], XmNuserData, (XtPointer) globalRef); - argc++; - - - if (sbDisplay == java_awt_ScrollPane_SCROLLBARS_NEVER) { - DASSERT(!(argc > MAX_ARGC)); - sdata->widget = XtCreateWidget(ScrollPaneManagerName, - xmManagerWidgetClass, wdata->widget, - args, argc); - - { - // To be able to request focus on Manager by call - // XmProcessTraversal(, XmTRAVERSE_CURRENT) we need to make - // it return XmCONTROL_NAVIGABLE from widgetNavigable callback. - // Default implementation returns DESCENDANTS_TAB_NAVIGABLE - // which doesn't allow this. - if (!managerCallbackInitialized) { - XmBaseClassExt *er; - WidgetClass wc; - managerCallbackInitialized = True; - wc = (WidgetClass) &xmManagerClassRec; - er = _XmGetBaseClassExtPtr(wc, XmQmotif); - oldManagerNavigable = (*er)->widgetNavigable; - (*er)->widgetNavigable = MyManagerNavigable; - } - } - } - else - { - XtSetArg(args[argc], XmNscrollingPolicy, XmAUTOMATIC); - argc++; - XtSetArg(args[argc], XmNvisualPolicy, XmCONSTANT); - argc++; - if (sbDisplay == java_awt_ScrollPane_SCROLLBARS_ALWAYS) { - DASSERT(!(argc > MAX_ARGC)); - XtSetArg(args[argc], XmNscrollBarDisplayPolicy, XmSTATIC); - argc++; - } else { - XtSetArg(args[argc], XmNscrollBarDisplayPolicy, XmAS_NEEDED); - argc++; - } - - XtSetArg(args[argc], XmNspacing, 0); - argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen)); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - sdata->widget = XmCreateScrolledWindow(wdata->widget, "scroller", args, argc); - - XtVaGetValues(sdata->widget, - XmNverticalScrollBar, &vsb, - XmNhorizontalScrollBar, &hsb, - NULL); - - if (vsb != NULL) { - XtAddCallback(vsb, XmNincrementCallback, ScrollPane_scrollV, (XtPointer) globalRef); - XtAddCallback(vsb, XmNdecrementCallback, ScrollPane_scrollV, (XtPointer) globalRef); - XtAddCallback(vsb, XmNpageIncrementCallback, ScrollPane_scrollV, (XtPointer) globalRef); - XtAddCallback(vsb, XmNpageDecrementCallback, ScrollPane_scrollV, (XtPointer) globalRef); - XtAddCallback(vsb, XmNtoTopCallback, ScrollPane_scrollV, (XtPointer) globalRef); - XtAddCallback(vsb, XmNtoBottomCallback, ScrollPane_scrollV, (XtPointer) globalRef); - XtAddCallback(vsb, XmNvalueChangedCallback, ScrollPane_scrollV, (XtPointer) globalRef); - XtAddCallback(vsb, XmNdragCallback, ScrollPane_scrollV, (XtPointer) globalRef); - - XtVaSetValues(vsb, XmNhighlightThickness, 0, NULL); - } - if (hsb != NULL) { - XtAddCallback(hsb, XmNincrementCallback, ScrollPane_scrollH, (XtPointer) globalRef); - XtAddCallback(hsb, XmNdecrementCallback, ScrollPane_scrollH, (XtPointer) globalRef); - XtAddCallback(hsb, XmNpageIncrementCallback, ScrollPane_scrollH, (XtPointer) globalRef); - XtAddCallback(hsb, XmNpageDecrementCallback, ScrollPane_scrollH, (XtPointer) globalRef); - XtAddCallback(hsb, XmNtoTopCallback, ScrollPane_scrollH, (XtPointer) globalRef); - XtAddCallback(hsb, XmNtoBottomCallback, ScrollPane_scrollH, (XtPointer) globalRef); - XtAddCallback(hsb, XmNvalueChangedCallback, ScrollPane_scrollH, (XtPointer) globalRef); - XtAddCallback(hsb, XmNdragCallback, ScrollPane_scrollH, (XtPointer) globalRef); - - XtVaSetValues(hsb, XmNhighlightThickness, 0, NULL); - } - { - /** - * Fix for 4033837 - ScrollPane doesn't generate mouse, focus, key events - * If ScrollPane created with ALWAYS or AS_NEEDED scrollbars policy then - * the upper widget is ClipWindow. We should install callbacks on it to - * receive event notifications. - */ - Widget clip = XtNameToWidget(sdata->widget, "*ClipWindow"); - if (clip != NULL) { - // To be able to request focus on Manager by call - // XmProcessTraversal(, XmTRAVERSE_CURRENT) we need to make - // it return XmCONTROL_NAVIGABLE from widgetNavigable callback. - // Default implementation returns DESCENDANTS_TAB_NAVIGABLE - // which doesn't allow this. - if (!clipCallbackInitialized) { - XmBaseClassExt *er; - clipCallbackInitialized = True; - er = _XmGetBaseClassExtPtr(XtClass(clip), XmQmotif); - oldClipNavigable = (*er)->widgetNavigable; - (*er)->widgetNavigable = MyClipNavigable; - } - awt_addWidget(clip, sdata->widget, globalRef, java_awt_AWTEvent_MOUSE_EVENT_MASK | - java_awt_AWTEvent_MOUSE_MOTION_EVENT_MASK | java_awt_AWTEvent_KEY_EVENT_MASK); - } - } - { - /** - * Fix for 4033837 - ScrollPane with ALWAYS doesn't have scrollbars visible - * It seems to be the bug in Motif, the workaround is to add empty child. - * User child will replace it when needed. This doesn't work if child had been - * removed. - */ - if (sbDisplay == java_awt_ScrollPane_SCROLLBARS_ALWAYS) { - Widget darea = NULL; - argc = 0; - XtSetArg(args[argc], XmNwidth, 1); - argc++; - XtSetArg(args[argc], XmNheight, 1); - argc++; - XtSetArg(args[argc], XmNmarginWidth, 0); - argc++; - XtSetArg(args[argc], XmNmarginHeight, 0); - argc++; - XtSetArg(args[argc], XmNspacing, 0); - argc++; - XtSetArg(args[argc], XmNresizePolicy, XmRESIZE_NONE); - argc++; - darea = XmCreateDrawingArea(sdata->widget, "null_child", args, argc); - - XmScrolledWindowSetAreas(sdata->widget, NULL, NULL, darea); - XtSetMappedWhenManaged(darea, False); - XtManageChild(darea); - } - } - - } - - XtSetMappedWhenManaged(sdata->widget, False); - XtManageChild(sdata->widget); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: pSetScrollChild - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MScrollPanePeer_pSetScrollChild - (JNIEnv *env, jobject this, jobject child) -{ - struct ComponentData *cdata; - struct ComponentData *sdata; - jobject target; - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if (JNU_IsNull(env, child) || JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,child,mComponentPeerIDs.pData); - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (sdata == NULL || cdata == NULL || sdata->widget == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - - return; - } - if ((*env)->GetIntField(env, target, scrollPaneIDs.scrollbarDisplayPolicy) - == java_awt_ScrollPane_SCROLLBARS_NEVER) { - /* Do Nothing */ - } else { - XmScrolledWindowSetAreas(sdata->widget, NULL, NULL, cdata->widget); - /* - XtInsertEventHandler(cdata->widget, StructureNotifyMask, FALSE, - child_event_handler, sdata->widget, XtListHead); - */ - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: pSetIncrement - * Signature: (III)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MScrollPanePeer_pSetIncrement - (JNIEnv *env, jobject this, jint orient, jint incrType, jint incr) -{ - struct ComponentData *sdata; - Widget scrollbar = NULL; - - AWT_LOCK(); - - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (sdata == NULL || sdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (!XtIsSubclass(sdata->widget, xmScrolledWindowWidgetClass)) { - AWT_UNLOCK(); - return; - } - if (orient == java_awt_Adjustable_VERTICAL) { - XtVaGetValues(sdata->widget, - XmNverticalScrollBar, &scrollbar, - NULL); - } else { - XtVaGetValues(sdata->widget, - XmNhorizontalScrollBar, &scrollbar, - NULL); - } - - if (scrollbar != NULL) { - if (incrType == sun_awt_motif_MScrollPanePeer_UNIT_INCREMENT) { - XtVaSetValues(scrollbar, - XmNincrement, (XtArgVal) incr, - NULL); - - } else { - /* BLOCK_INCREMENT */ - XtVaSetValues(scrollbar, - XmNpageIncrement, (XtArgVal) incr, - NULL); - } - } - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: pGetScrollbarSpace - * Signature: (I)I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MScrollPanePeer_pGetScrollbarSpace - (JNIEnv *env, jobject this, jint orient) -{ - struct ComponentData *sdata; - Widget scrollbar; - Dimension thickness = 0; - Dimension space = 0; - Dimension highlight = 0; - - AWT_LOCK(); - - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (sdata == NULL || sdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - if (orient == java_awt_Adjustable_VERTICAL) { - XtVaGetValues(sdata->widget, - XmNverticalScrollBar, &scrollbar, - XmNspacing, &space, - NULL); - XtVaGetValues(scrollbar, - XmNwidth, &thickness, - XmNhighlightThickness, &highlight, - NULL); - } else { - XtVaGetValues(sdata->widget, - XmNhorizontalScrollBar, &scrollbar, - XmNspacing, &space, - NULL); - XtVaGetValues(scrollbar, - XmNheight, &thickness, - XmNhighlightThickness, &highlight, - NULL); - } - - AWT_UNLOCK(); - return (jint) (thickness + space + 2 * highlight); -} - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: pGetBlockIncrement - * Signature: (I)I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MScrollPanePeer_pGetBlockIncrement - (JNIEnv *env, jobject this, jint orient) -{ - int32_t pageIncr = 0; - struct ComponentData *sdata; - Widget scrollbar; - - AWT_LOCK(); - - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (sdata == NULL || sdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - if (orient == java_awt_Adjustable_VERTICAL) { - - XtVaGetValues(sdata->widget, - XmNverticalScrollBar, &scrollbar, - NULL); - XtVaGetValues(scrollbar, - XmNpageIncrement, &pageIncr, - NULL); - } else { - - XtVaGetValues(sdata->widget, - XmNhorizontalScrollBar, &scrollbar, - NULL); - XtVaGetValues(scrollbar, - XmNpageIncrement, &pageIncr, - NULL); - } - - AWT_UNLOCK(); - return (jint) (pageIncr); -} - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: pInsets - * Signature: (IIII)Ljava/awt/Insets; - */ -JNIEXPORT jobject JNICALL Java_sun_awt_motif_MScrollPanePeer_pInsets - (JNIEnv *env, jobject this, jint width, jint height, jint childWidth, jint childHeight) -{ - struct ComponentData *sdata; - jobject target; - jobject insets = NULL; - Widget hsb, vsb; - Dimension hsbThickness, hsbHighlight, hsbSpace = 0, - vsbThickness, vsbHighlight, vsbSpace = 0, - space, border, shadow, hMargin, vMargin; - unsigned char placement; - Boolean hsbVisible, vsbVisible; - jint sbDisplay; - int32_t top, left, right, bottom; - jclass clazz; - jmethodID mid; - - AWT_LOCK(); - - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if (JNU_IsNull(env, target) || sdata == NULL || sdata->widget == NULL) - { - JNU_ThrowNullPointerException(env, "sdata is NULL"); - AWT_UNLOCK(); - return 0; - } - sbDisplay = - (*env)->GetIntField(env, target, scrollPaneIDs.scrollbarDisplayPolicy); - - /* REMIND: investigate caching these values rather than querying for - * them each time. - */ - - if (sbDisplay == java_awt_ScrollPane_SCROLLBARS_NEVER) { - XtVaGetValues(sdata->widget, - XmNshadowThickness, &shadow, - NULL); - space = border = hMargin = vMargin = 0; - - } else { - XtVaGetValues(sdata->widget, - XmNverticalScrollBar, &vsb, - XmNhorizontalScrollBar, &hsb, - XmNscrollBarPlacement, &placement, - XmNspacing, &space, - XmNshadowThickness, &shadow, - XmNscrolledWindowMarginHeight, &vMargin, - XmNscrolledWindowMarginWidth, &hMargin, - XmNborderWidth, &border, - NULL); - - XtVaGetValues(vsb, - XmNwidth, &vsbThickness, - XmNhighlightThickness, &vsbHighlight, - NULL); - - XtVaGetValues(hsb, - XmNheight, &hsbThickness, - XmNhighlightThickness, &hsbHighlight, - NULL); - - hsbSpace = hsbThickness + space + hsbHighlight; - vsbSpace = vsbThickness + space + vsbHighlight; - -/* - XtVaGetValues(clip, - XmNwidth, &clipw, XmNheight, &cliph, - XmNx, &clipx, XmNy, &clipy, - NULL); - printf("insets: spacing=%d shadow=%d swMarginH=%d swMarginW=%d border=%d ; \ - vsb=%d vsbHL=%d ; hsb=%d hsbHL=%d ; %dx%d ->clip=%d,%d %dx%d\n", - space, shadow, vMargin, hMargin, border, - vsbThickness, vsbHighlight, hsbThickness, hsbHighlight, - w, h, clipx, clipy, clipw, cliph); -*/ - } - - /* We unfortunately have to use the size parameters to determine - * whether or not "as needed" scrollbars are currently present or - * not because we can't necessarily rely on getting valid geometry - * values straight from the Motif widgets until they are mapped. :( - */ - switch (sbDisplay) { - case java_awt_ScrollPane_SCROLLBARS_NEVER: - vsbVisible = hsbVisible = FALSE; - break; - - case java_awt_ScrollPane_SCROLLBARS_ALWAYS: - vsbVisible = hsbVisible = TRUE; - break; - - case java_awt_ScrollPane_SCROLLBARS_AS_NEEDED: - default: - vsbVisible = hsbVisible = FALSE; - if (childWidth > width - 2 * shadow) { - hsbVisible = TRUE; - } - if (childHeight > height - 2 * shadow) { - vsbVisible = TRUE; - } - if (!hsbVisible && vsbVisible && childWidth > width - 2 * shadow - vsbSpace) { - hsbVisible = TRUE; - } else if (!vsbVisible && hsbVisible && childHeight > height - 2 * shadow - hsbSpace) { - vsbVisible = TRUE; - } - } - - top = bottom = shadow + vMargin; - left = right = shadow + hMargin; - - if (sbDisplay != java_awt_ScrollPane_SCROLLBARS_NEVER) { - switch (placement) { - case XmBOTTOM_RIGHT: - bottom += (hsbVisible ? hsbSpace : (vsbVisible ? vsbHighlight : 0)); - right += (vsbVisible ? vsbSpace : (hsbVisible ? hsbHighlight : 0)); - top += (vsbVisible ? vsbHighlight : 0); - left += (hsbVisible ? hsbHighlight : 0); - break; - - case XmBOTTOM_LEFT: - bottom += (hsbVisible ? hsbSpace : (vsbVisible ? vsbHighlight : 0)); - left += (vsbVisible ? hsbSpace : (hsbVisible ? hsbHighlight : 0)); - top += (vsbVisible ? vsbHighlight : 0); - right += (hsbVisible ? hsbHighlight : 0); - break; - - case XmTOP_RIGHT: - top += (hsbVisible ? hsbSpace : (vsbVisible ? vsbHighlight : 0)); - right += (vsbVisible ? vsbSpace : (hsbVisible ? hsbHighlight : 0)); - bottom += (vsbVisible ? vsbHighlight : 0); - left += (hsbVisible ? hsbHighlight : 0); - break; - - case XmTOP_LEFT: - top += (hsbVisible ? hsbSpace : (vsbVisible ? vsbHighlight : 0)); - left += (vsbVisible ? vsbSpace : (hsbVisible ? hsbHighlight : 0)); - bottom += (vsbVisible ? vsbHighlight : 0); - right += (hsbVisible ? hsbHighlight : 0); - } - } - /* Deadlock prevention: - * don't hold the toolkit lock while invoking constructor. - */ - AWT_UNLOCK(); - - clazz = (*env)->FindClass(env, "java/awt/Insets"); - mid = (*env)->GetMethodID(env, clazz, "", "(IIII)V"); - if (mid != NULL) { - insets = (*env)->NewObject(env, clazz, mid, - (jint) top, - (jint) left, - (jint) bottom, - (jint) right); - - } - /* This should catch both method not found and error exceptions */ - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - if (JNU_IsNull(env, insets)) { - JNU_ThrowNullPointerException(env, "NullPointerException: insets constructor failed"); - } - return insets; -} - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: setScrollPosition - * Signature: (II)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MScrollPanePeer_setScrollPosition - (JNIEnv *env, jobject this, jint x, jint y) -{ - struct ComponentData *sdata; - jobject target; - Widget hsb, vsb; - int32_t size, incr, pIncr; - - AWT_LOCK(); - - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if (JNU_IsNull(env, target) || sdata == NULL || sdata->widget == NULL) - { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if ((*env)->GetIntField(env, target, scrollPaneIDs.scrollbarDisplayPolicy) - == java_awt_ScrollPane_SCROLLBARS_NEVER) { - WidgetList children; - Cardinal numChildren; - - XtVaGetValues(sdata->widget, - XmNchildren, &children, - XmNnumChildren, &numChildren, - NULL); - - if (numChildren < 1) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtMoveWidget(children[0], (Position) -x, (Position) -y); - } else { - int32_t sb_min = 0; - int32_t sb_max = 0; - XtVaGetValues(sdata->widget, - XmNhorizontalScrollBar, &hsb, - XmNverticalScrollBar, &vsb, - NULL); - - if (vsb) { - XtVaGetValues(vsb, - XmNincrement, &incr, - XmNpageIncrement, &pIncr, - XmNsliderSize, &size, - XmNminimum, &sb_min, - XmNmaximum, &sb_max, - NULL); - /* Bug 4208972, 4275934 : Do range checking for scroll bar value. */ - if (y < sb_min) - y = sb_min; - if (y > (sb_max - size)) - y = sb_max - size; - XmScrollBarSetValues(vsb, (int32_t) y, size, incr, pIncr, TRUE); - } - if (hsb) { - XtVaGetValues(hsb, - XmNincrement, &incr, - XmNpageIncrement, &pIncr, - XmNsliderSize, &size, - XmNminimum, &sb_min, - XmNmaximum, &sb_max, - NULL); - /* Bug 4208972, 4275934 : Do range checking for scroll bar value. */ - if (x < sb_min) - x = sb_min; - if (x > (sb_max - size)) - x = sb_max - size; - XmScrollBarSetValues(hsb, (int32_t) x, size, incr, pIncr, TRUE); - } - } - AWT_FLUSH_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: pGetShadow - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MScrollPanePeer_pGetShadow( - JNIEnv *env, jobject this) { - struct ComponentData *sdata; - jobject target; - Dimension shadow=0 ; - - AWT_LOCK() ; - sdata = (struct ComponentData *) - (*env)->GetLongField(env,this,mComponentPeerIDs.pData); - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if (JNU_IsNull(env, target) || sdata == NULL || sdata->widget == NULL) - { - JNU_ThrowNullPointerException(env, "sdata is NULL"); - AWT_UNLOCK(); - return 0; - } - - XtVaGetValues(sdata->widget, - XmNshadowThickness, - &shadow, - NULL); - - AWT_UNLOCK() ; - - return((jint)shadow) ; -} - -/* - * Class: sun_awt_motif_MScrollPanePeer - * Method: setTypedValue - * Signature: (Ljava/awt/ScrollPaneAdjustable;II)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MScrollPanePeer_setTypedValue(JNIEnv *env, jobject peer, jobject adjustable, jint value, jint type) -{ - static jmethodID setTypedValueMID = 0; - if (setTypedValueMID == NULL) { - jclass clazz = (*env)->FindClass(env, "java/awt/ScrollPaneAdjustable"); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - return; - } - setTypedValueMID = (*env)->GetMethodID(env, clazz, "setTypedValue", "(II)V"); - (*env)->DeleteLocalRef(env, clazz); - - DASSERT(setTypedValueMID != NULL); - } - (*env)->CallVoidMethod(env, adjustable, setTypedValueMID, value, type); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Scrollbar.c b/jdk/src/solaris/native/sun/awt/awt_Scrollbar.c deleted file mode 100644 index 4b7586edf79..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Scrollbar.c +++ /dev/null @@ -1,440 +0,0 @@ -/* - * Copyright 1995-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "java_awt_Scrollbar.h" -#include "java_awt_event_MouseEvent.h" -#include "sun_awt_motif_MScrollbarPeer.h" -#include "sun_awt_motif_MComponentPeer.h" - -#include "awt_Component.h" -#include "canvas.h" - -#include -#include -#include "multi_font.h" - - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -/* fieldIDs for java.awt.Scrollbar fields that may be accessed from C */ -static struct ScrollbarIDs { - jfieldID orientation; - jfieldID visibleAmount; - jfieldID lineIncrement; - jfieldID pageIncrement; - jfieldID value; - jfieldID minimum; - jfieldID maximum; -} targetIDs; - -/* MScrollbarPeer callback methods */ -static struct { - jmethodID lineUp; - jmethodID lineDown; - jmethodID pageUp; - jmethodID pageDown; - jmethodID drag; - jmethodID dragEnd; - jmethodID warp; -} peerIDs; - - - -/* - * Class: java_awt_ScrollBar - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - Scrollbar.java to initialize the fieldIDs for fields that may - be accessed from C */ - -JNIEXPORT void JNICALL -Java_java_awt_Scrollbar_initIDs(JNIEnv *env, jclass cls) -{ - targetIDs.orientation = - (*env)->GetFieldID(env, cls, "orientation", "I"); - targetIDs.visibleAmount = - (*env)->GetFieldID(env, cls, "visibleAmount", "I"); - targetIDs.lineIncrement = - (*env)->GetFieldID(env, cls, "lineIncrement", "I"); - targetIDs.pageIncrement = - (*env)->GetFieldID(env, cls, "pageIncrement", "I"); - targetIDs.value = - (*env)->GetFieldID(env, cls, "value", "I"); - targetIDs.minimum = - (*env)->GetFieldID(env, cls, "minimum", "I"); - targetIDs.maximum = - (*env)->GetFieldID(env, cls, "maximum", "I"); -} - - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - MScrollbarPeer to initialize the JNI ids for fields and methods - that may be accessed from C */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MScrollbarPeer_initIDs(JNIEnv *env, jclass cls) -{ - peerIDs.lineUp = - (*env)->GetMethodID(env, cls, "lineUp", "(I)V"); - peerIDs.lineDown = - (*env)->GetMethodID(env, cls, "lineDown", "(I)V"); - peerIDs.pageUp = - (*env)->GetMethodID(env, cls, "pageUp", "(I)V"); - peerIDs.pageDown = - (*env)->GetMethodID(env, cls, "pageDown", "(I)V"); - peerIDs.drag = - (*env)->GetMethodID(env, cls, "drag", "(I)V"); - peerIDs.dragEnd = - (*env)->GetMethodID(env, cls, "dragEnd", "(I)V"); - peerIDs.warp = - (*env)->GetMethodID(env, cls, "warp", "(I)V"); -} - -/* - * Call peer.jcallback(value) - */ -static void -DoJavaCallback(jobject peer, jmethodID jcallback, jint value) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - (*env)->CallVoidMethod(env, peer, jcallback, value); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - - -static void /* XtCallbackProc */ -decrementCallback(Widget w, jobject peer, - XmScrollBarCallbackStruct *scroll) -{ - DASSERT(scroll->reason == XmCR_DECREMENT); - DoJavaCallback(peer, peerIDs.lineUp, scroll->value); -} - -static void /* XtCallbackProc */ -incrementCallback(Widget w, jobject peer, - XmScrollBarCallbackStruct *scroll) -{ - DASSERT(scroll->reason == XmCR_INCREMENT); - DoJavaCallback(peer, peerIDs.lineDown, scroll->value); -} - -static void /* XtCallbackProc */ -pageDecrementCallback(Widget w, jobject peer, - XmScrollBarCallbackStruct *scroll) -{ - DASSERT(scroll->reason == XmCR_PAGE_DECREMENT); - DoJavaCallback(peer, peerIDs.pageUp, scroll->value); -} - -static void /* XtCallbackProc */ -pageIncrementCallback(Widget w, jobject peer, - XmScrollBarCallbackStruct *scroll) -{ - DASSERT(scroll->reason == XmCR_PAGE_INCREMENT); - DoJavaCallback(peer, peerIDs.pageDown, scroll->value); -} - -static void /* XtCallbackProc */ -dragCallback(Widget w, jobject peer, - XmScrollBarCallbackStruct *scroll) -{ - DASSERT(scroll->reason == XmCR_DRAG); - DoJavaCallback(peer, peerIDs.drag, scroll->value); -} - -static void /* XtCallbackProc */ -dragEndCallback(Widget w, jobject peer, - XmScrollBarCallbackStruct *scroll) -{ - DASSERT(scroll->reason == XmCR_VALUE_CHANGED); - DoJavaCallback(peer, peerIDs.dragEnd, scroll->value); -} - -static void /* XtCallbackProc */ -toTopCallback(Widget w, jobject peer, - XmScrollBarCallbackStruct *scroll) -{ - DASSERT(scroll->reason == XmCR_TO_TOP); - DoJavaCallback(peer, peerIDs.warp, scroll->value); -} - -static void /* XtCallbackProc */ -toBottomCallback(Widget w, jobject peer, - XmScrollBarCallbackStruct *scroll) -{ - DASSERT(scroll->reason == XmCR_TO_BOTTOM); - DoJavaCallback(peer, peerIDs.warp, scroll->value); -} - - -/* - * Class: sun_awt_motif_MScrollbarPeer - * Method: create - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MScrollbarPeer_create(JNIEnv *env, jobject this, - jobject parent) -{ - Widget w; - - jobject target; - XtPointer globalRef = (XtPointer) /* jobject */ - awtJNI_CreateAndSetGlobalRef(env, this); - - struct ComponentData *pdata; /* for parent */ - struct ComponentData *sdata; /* for scrollbar */ - AwtGraphicsConfigDataPtr adata; - - int32_t value, visible, minimum, maximum; - int32_t lineIncrement, pageIncrement; - Pixel bg; - -#define MAX_ARGC 20 - Arg args[MAX_ARGC]; - int32_t argc = 0; - - - AWT_LOCK(); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - pdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, parent, mComponentPeerIDs.pData); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if (JNU_IsNull(env, target) || pdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - - switch ((*env)->GetIntField(env, target, targetIDs.orientation)) { - case java_awt_Scrollbar_HORIZONTAL: - XtSetArg(args[argc], XmNorientation, XmHORIZONTAL); - argc++; - break; - - case java_awt_Scrollbar_VERTICAL: - XtSetArg(args[argc], XmNorientation, XmVERTICAL); - argc++; - break; - - default: - JNU_ThrowIllegalArgumentException(env, "bad scrollbar orientation"); - AWT_UNLOCK(); - return; - } - - adata = copyGraphicsConfigToPeer(env, this); - XtVaGetValues(pdata->widget, XmNbackground, &bg, NULL); - - visible = (int32_t) (*env)->GetIntField(env, target, targetIDs.visibleAmount); - value = (int32_t) (*env)->GetIntField(env, target, targetIDs.value); - minimum = (int32_t) (*env)->GetIntField(env, target, targetIDs.minimum); - maximum = (int32_t) (*env)->GetIntField(env, target, targetIDs.maximum); - lineIncrement = - (int32_t) (*env)->GetIntField(env, target, targetIDs.lineIncrement); - pageIncrement = - (int32_t) (*env)->GetIntField(env, target, targetIDs.pageIncrement); - - /* - * Sanity check. Scrollbar.setValues should have taken care. - */ - DASSERT(maximum > minimum); - DASSERT(visible <= maximum - minimum); - DASSERT(visible >= 1); - DASSERT(value >= minimum); - DASSERT(value <= maximum - visible); - - XtSetArg(args[argc], XmNx, 0); argc++; - XtSetArg(args[argc], XmNy, 0); argc++; - XtSetArg(args[argc], XmNvalue, value); argc++; - XtSetArg(args[argc], XmNsliderSize, visible); argc++; - XtSetArg(args[argc], XmNminimum, minimum); argc++; - XtSetArg(args[argc], XmNmaximum, maximum); argc++; - XtSetArg(args[argc], XmNincrement, lineIncrement); argc++; - XtSetArg(args[argc], XmNpageIncrement, pageIncrement); argc++; - XtSetArg(args[argc], XmNbackground, bg); argc++; - XtSetArg(args[argc], XmNrecomputeSize, False); argc++; - XtSetArg(args[argc], XmNuserData, globalRef); argc++; - XtSetArg(args[argc], XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen)); argc++; - - DASSERT(argc <= MAX_ARGC); /* sanity check */ - - sdata = ZALLOC(ComponentData); - if (sdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - - JNU_SetLongFieldFromPtr(env, this, mComponentPeerIDs.pData, sdata); - - sdata->widget = w = - XmCreateScrollBar(pdata->widget, "scrollbar", args, argc); - - XtAddCallback(w, XmNdecrementCallback, - (XtCallbackProc)decrementCallback, globalRef); - XtAddCallback(w, XmNincrementCallback, - (XtCallbackProc)incrementCallback, globalRef); - XtAddCallback(w, XmNpageDecrementCallback, - (XtCallbackProc)pageDecrementCallback, globalRef); - XtAddCallback(w, XmNpageIncrementCallback, - (XtCallbackProc)pageIncrementCallback, globalRef); - XtAddCallback(w, XmNtoTopCallback, - (XtCallbackProc)toTopCallback, globalRef); - XtAddCallback(w, XmNtoBottomCallback, - (XtCallbackProc)toBottomCallback, globalRef); - XtAddCallback(w, XmNdragCallback, - (XtCallbackProc)dragCallback, globalRef); - XtAddCallback(w, XmNvalueChangedCallback, - (XtCallbackProc)dragEndCallback, globalRef); - - /* Set up workaround for the continuous scrolling bug */ - XtAddEventHandler(w, ButtonReleaseMask, False, - awt_motif_Scrollbar_ButtonReleaseHandler, NULL); - - /* Fix for 4955950. ButtonRelease & MotionNotify should be handled as well */ - XtAddEventHandler(w, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, - False, awt_canvas_event_handler, globalRef); - - XtSetMappedWhenManaged(w, False); - XtManageChild(w); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MScrollbarPeer - * Method: pSetValues - * Signature: (IIII)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MScrollbarPeer_pSetValues(JNIEnv *env, jobject this, - jint value, jint visible, jint minimum, jint maximum) -{ - struct ComponentData *sdata; - - AWT_LOCK(); - - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - /* pass in visible for sliderSize since Motif will calculate the */ - /* slider's size for us. */ - XtVaSetValues(sdata->widget, - XmNminimum, minimum, - XmNmaximum, maximum, - XmNvalue, value, - XmNsliderSize, visible, - NULL); - AWT_FLUSH_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MScrollbarPeer - * Method: setLineIncrement - * Signature: (I)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MScrollbarPeer_setLineIncrement(JNIEnv *env, jobject this, - jint value) -{ - struct ComponentData *sdata; - - AWT_LOCK(); - - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(sdata->widget, - XmNincrement, value, - NULL); - AWT_FLUSH_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MScrollbarPeer - * Method: setPageIncrement - * Signature: (I)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MScrollbarPeer_setPageIncrement(JNIEnv *env, jobject this, - jint value) -{ - struct ComponentData *sdata; - - AWT_LOCK(); - - sdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (sdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(sdata->widget, - XmNpageIncrement, value, - NULL); - AWT_FLUSH_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_Selection.c b/jdk/src/solaris/native/sun/awt/awt_Selection.c deleted file mode 100644 index 5d5b934459f..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_Selection.c +++ /dev/null @@ -1,508 +0,0 @@ -/* - * Copyright 1996-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "awt_DataTransferer.h" -#include "java_awt_datatransfer_Transferable.h" -#include "java_awt_datatransfer_DataFlavor.h" -#include "sun_awt_motif_X11Selection.h" -#include "sun_awt_motif_X11Clipboard.h" -#include -#include -#include - -#include -#include - -/* fieldIDs for X11Selection fields that may be accessed from C */ -static struct X11SelectionIDs { - jfieldID holder; - jfieldID atom; - jfieldID contents; - jfieldID selections; -} x11SelectionIDs; - -DECLARE_JAVA_CLASS(selectionClazz, "sun/awt/motif/X11Selection") - -static jobject -call_getSelectionsArray(JNIEnv* env) { - DECLARE_STATIC_OBJECT_JAVA_METHOD(getSelectionsArray, selectionClazz, - "getSelectionsArray", "()[Ljava/lang/Object;") - DASSERT(!JNU_IsNull(env, getSelectionsArray)); - return (*env)->CallStaticObjectMethod(env, clazz, getSelectionsArray); -} - -static void -call_checkChange(JNIEnv* env, jobject jselection, jlongArray targetArray) -{ - DECLARE_VOID_JAVA_METHOD(checkChangeMID, selectionClazz, - "checkChange", "([J)V") - DASSERT(!JNU_IsNull(env, jselection)); - - (*env)->CallVoidMethod(env, jselection, checkChangeMID, targetArray); -} - -static jlongArray -call_getSelectionAtomsToCheckChange(JNIEnv* env) -{ - DECLARE_STATIC_OBJECT_JAVA_METHOD(getSelectionAtomsToCheckChangeMID, - selectionClazz, "getSelectionAtomsToCheckChange", "()[J") - - return (jlongArray)(*env)->CallStaticObjectMethod(env, - get_selectionClazz(env), getSelectionAtomsToCheckChangeMID); - -} - - -/* - * Class: sun_awt_motif_X11Selection - * Method: initIDs - * Signature: ()V - */ -/* This function gets called from the static initializer for - X11Selection.java to initialize the fieldIDs for fields that may - be accessed from C */ -JNIEXPORT void JNICALL Java_sun_awt_motif_X11Selection_initIDs - (JNIEnv *env, jclass cls) -{ - x11SelectionIDs.holder = (*env)-> - GetFieldID(env, cls, "holder","Lsun/awt/motif/X11SelectionHolder;"); - x11SelectionIDs.atom = (*env)->GetFieldID(env, cls, "atom", "J"); - x11SelectionIDs.contents = (*env)-> - GetFieldID(env, cls, "contents", - "Ljava/awt/datatransfer/Transferable;"); - x11SelectionIDs.selections = (*env)-> - GetStaticFieldID(env, cls, "selections", "Ljava/util/Vector;"); -} - -/* - * Class: sun_awt_motif_X11Selection - * Method: init - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_X11Selection_init - (JNIEnv *env, jclass this) -{ - AWT_LOCK(); - - AWT_UNLOCK(); -} - -static jobject -getX11Selection(JNIEnv * env, Atom atom) -{ - jobjectArray selections; - jsize selectionCount, i; - jobject selection; - jobject returnSelection = NULL; - - selections = (jobjectArray)call_getSelectionsArray(env); - - if (JNU_IsNull(env, selections)) { - return NULL; - } - - selectionCount = (*env)->GetArrayLength(env, selections); - - for (i = 0; i < selectionCount; i++) { - selection = (*env)->GetObjectArrayElement(env, selections, i); - if ((*env)->ExceptionCheck(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - break; - } - if (JNU_IsNull(env, selection)) { - break; - } - if ((*env)->GetLongField(env, selection, x11SelectionIDs.atom) == atom) { - returnSelection = selection; - } else { - (*env)->DeleteLocalRef(env, selection); - } - } - - (*env)->DeleteLocalRef(env, selections); - - return returnSelection; -} - -Boolean -awtJNI_isSelectionOwner(JNIEnv * env, char *sel_str) -{ - Atom selection; - jobject x11sel; - - selection = XInternAtom(awt_display, sel_str, False); - - x11sel = getX11Selection(env, selection); - if (!JNU_IsNull(env, x11sel)) { - jobject holder; - - holder = (*env)->GetObjectField(env, x11sel, x11SelectionIDs.holder); - if (!JNU_IsNull(env, holder)) { - return TRUE; - } - } - return FALSE; -} - -static void losingSelectionOwnership(Widget w, Atom * selection); - -void -awtJNI_notifySelectionLost(JNIEnv * env, char *sel_str) -{ - Atom selection; - - selection = XInternAtom(awt_display, sel_str, False); - losingSelectionOwnership(NULL, &selection); -} - -static void -losingSelectionOwnership(Widget w, Atom * selection) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = getX11Selection(env, *selection); - - /* - * SECURITY: OK to call this on privileged thread - peer does - * not call into client code - */ - JNU_CallMethodByName(env, NULL, this, "lostSelectionOwnership", "()V"); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - /* - * Fix for 4692059. - * The native context is cleaned up on the event dispatch thread after the - * references to the current contents and owner are cleared. - */ -} - -/* - * Class: sun_awt_motif_X11Selection - * Method: pGetSelectionOwnership - * Signature: (Ljava/lang/Object;Ljava/awt/datatransfer/Transferable;[JLjava/util/Map;Lsun/awt/motif/X11SelectionHolder;)Z - */ -JNIEXPORT jboolean JNICALL -Java_sun_awt_motif_X11Selection_pGetSelectionOwnership(JNIEnv *env, - jobject this, - jobject source, - jobject transferable, - jlongArray formats, - jobject formatMap, - jobject holder) -{ - Boolean gotit = False; - Atom selection = (Atom)(*env)->GetLongField(env, this, - x11SelectionIDs.atom); - awt_convertDataCallbackStruct* structPtr = NULL; - Time time = CurrentTime; - - AWT_LOCK(); - - time = awt_util_getCurrentServerTime(); - - (*env)->SetObjectField(env, this, x11SelectionIDs.holder, NULL); - (*env)->SetObjectField(env, this, x11SelectionIDs.contents, NULL); - - gotit = XtOwnSelection(awt_root_shell, selection, time, awt_convertData, - losingSelectionOwnership, NULL); - - if (gotit) { - if (XFindContext(awt_display, selection, awt_convertDataContext, - (XPointer*)&structPtr) == 0 && structPtr != NULL) { - (*env)->DeleteGlobalRef(env, structPtr->source); - (*env)->DeleteGlobalRef(env, structPtr->transferable); - (*env)->DeleteGlobalRef(env, structPtr->formatMap); - (*env)->DeleteGlobalRef(env, structPtr->formats); - memset(structPtr, 0, sizeof(awt_convertDataCallbackStruct)); - } else { - XDeleteContext(awt_display, selection, awt_convertDataContext); - - structPtr = calloc(1, sizeof(awt_convertDataCallbackStruct)); - - if (structPtr == NULL) { - XtDisownSelection(awt_root_shell, selection, time); - AWT_UNLOCK(); - JNU_ThrowOutOfMemoryError(env, ""); - return JNI_FALSE; - } - - if (XSaveContext(awt_display, selection, awt_convertDataContext, - (XPointer)structPtr) == XCNOMEM) { - XtDisownSelection(awt_root_shell, selection, time); - free(structPtr); - AWT_UNLOCK(); - JNU_ThrowInternalError(env, "Failed to save context data for selection."); - return JNI_FALSE; - } - } - - structPtr->source = (*env)->NewGlobalRef(env, source); - structPtr->transferable = (*env)->NewGlobalRef(env, transferable); - structPtr->formatMap = (*env)->NewGlobalRef(env, formatMap); - structPtr->formats = (*env)->NewGlobalRef(env, formats); - - if (JNU_IsNull(env, structPtr->source) || - JNU_IsNull(env, structPtr->transferable) || - JNU_IsNull(env, structPtr->formatMap) || - JNU_IsNull(env, structPtr->formats)) { - - if (!JNU_IsNull(env, structPtr->source)) { - (*env)->DeleteGlobalRef(env, structPtr->source); - } - if (!JNU_IsNull(env, structPtr->transferable)) { - (*env)->DeleteGlobalRef(env, structPtr->transferable); - } - if (!JNU_IsNull(env, structPtr->formatMap)) { - (*env)->DeleteGlobalRef(env, structPtr->formatMap); - } - if (!JNU_IsNull(env, structPtr->formats)) { - (*env)->DeleteGlobalRef(env, structPtr->formats); - } - XtDisownSelection(awt_root_shell, selection, time); - XDeleteContext(awt_display, selection, awt_convertDataContext); - free(structPtr); - AWT_UNLOCK(); - JNU_ThrowOutOfMemoryError(env, ""); - return JNI_FALSE; - } - - (*env)->SetObjectField(env, this, x11SelectionIDs.holder, holder); - (*env)->SetObjectField(env, this, x11SelectionIDs.contents, transferable); - } - AWT_UNLOCK(); - - return (gotit ? JNI_TRUE : JNI_FALSE); -} - -/* - * Class: sun_awt_motif_X11Selection - * Method: clearNativeContext - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_X11Selection_clearNativeContext(JNIEnv *env, jobject this) { - Atom selection = (Atom)(*env)->GetLongField(env, this, - x11SelectionIDs.atom); - - AWT_LOCK(); - - XtDisownSelection(awt_root_shell, selection, CurrentTime); - awt_cleanupConvertDataContext(env, selection); - - AWT_UNLOCK(); -} - - -static void -getSelectionTargetsToCheckChange(Widget w, XtPointer client_data, - Atom * selection, Atom * type, XtPointer value, unsigned long *length, - int32_t *format) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - size_t count = 0, i = 0, j = 0; - jlongArray targetArray = NULL; - - // Should keep this in sync with getSelectionTargets() so that - // this function yields non-null targetArray iff - // getSelectionTargets() yields SelectionSuccess. - if (*type == XA_TARGETS || *type == XA_ATOM) { - targetArray = getSelectionTargetsHelper(env, value, *length); - } else if (*type != XT_CONVERT_FAIL) { - targetArray = (*env)->NewLongArray(env, 0); - } - - if (value != NULL) { - XtFree(value); - value = NULL; - } - - { - jobject jselection = getX11Selection(env, *selection); - call_checkChange(env, jselection, targetArray); - if ((*env)->ExceptionCheck(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - (*env)->DeleteLocalRef(env, targetArray); - (*env)->DeleteLocalRef(env, jselection); - } -} - - -static Atom _XA_JAVA_TIME_PROPERTY_ATOM_CHECK_SELECTION_CHANGE_ON_TIMEOUT = 0; - -static void -checkSelectionChangeOnTimeout(XtPointer client_data, XtIntervalId* id) -{ - // We don't call XtGetSelectionValue(..., TARGETS, ..., awt_util_getCurrentServerTime()) - // here because awt_util_getCurrentServerTime() may block toolkit therad for a while - // whereas the current function is called very often at regular intervals. - // Instead we call XtGetSelectionValue(..., XtLastTimestampProcessed(awt_display)) - // in the property change event handler wherein we have got an up-to-date timestamp. - - XChangeProperty(awt_display, XtWindow(awt_root_shell), - _XA_JAVA_TIME_PROPERTY_ATOM_CHECK_SELECTION_CHANGE_ON_TIMEOUT, - XA_ATOM, 32, PropModeAppend, (unsigned char *)"", 0); - XFlush(awt_display); -} - - -static unsigned long selectionPollInterval; - -static void -propertyChangeEventHandlerToSelectionCheck -(Widget w, XtPointer client_data, XEvent* event, Boolean* continue_to_dispatch) -{ - JNIEnv *env; - jlongArray jselectionAtoms; - - if (event->type != PropertyNotify || event->xproperty.atom != - _XA_JAVA_TIME_PROPERTY_ATOM_CHECK_SELECTION_CHANGE_ON_TIMEOUT) { - return; - } - - env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jselectionAtoms = call_getSelectionAtomsToCheckChange(env); - - DASSERT(!JNU_IsNull(env, jselectionAtoms)); - if ((*env)->ExceptionCheck(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } else { - jsize len = (*env)->GetArrayLength(env, jselectionAtoms); - jlong* selectionAtomsNative = - (*env)->GetLongArrayElements(env, jselectionAtoms, NULL); - if (!JNU_IsNull(env, selectionAtomsNative)) { - jsize i = 0; - for (i = 0; i < len; i++) { - XtGetSelectionValue(awt_root_shell, (Atom)selectionAtomsNative[i], XA_TARGETS, - getSelectionTargetsToCheckChange, (XtPointer)NULL, - XtLastTimestampProcessed(awt_display)); - } - (*env)->ReleaseLongArrayElements(env, jselectionAtoms, - selectionAtomsNative, JNI_ABORT); - } - } - - // Reschedule the timer callback. - XtAppAddTimeOut(awt_appContext, selectionPollInterval, - checkSelectionChangeOnTimeout, client_data); -} - - -static BOOL isClipboardViewerRegistered = FALSE; - -/* - * Class: sun_awt_motif_X11Clipboard - * Method: registerClipboardViewer - * Signature: (I)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_X11Clipboard_registerClipboardViewer(JNIEnv *env, jobject self, - jint pollInterval) -{ - AWT_LOCK(); - - if (isClipboardViewerRegistered) { - AWT_UNLOCK(); - return; - } - - if (_XA_JAVA_TIME_PROPERTY_ATOM_CHECK_SELECTION_CHANGE_ON_TIMEOUT == 0) { - _XA_JAVA_TIME_PROPERTY_ATOM_CHECK_SELECTION_CHANGE_ON_TIMEOUT = - XInternAtom(awt_display, - "_SUNW_JAVA_AWT_TIME_CHECK_SELECTION_CHANGE_ON_TIMEOUT", - False); - } - - XtAddEventHandler(awt_root_shell, PropertyChangeMask, False, - propertyChangeEventHandlerToSelectionCheck, NULL); - - selectionPollInterval = pollInterval; - - XtAppAddTimeOut(awt_appContext, selectionPollInterval, - checkSelectionChangeOnTimeout, (XtPointer)NULL); - - isClipboardViewerRegistered = TRUE; - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_X11Clipboard - * Method: unregisterClipboardViewer - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_X11Clipboard_unregisterClipboardViewer(JNIEnv *env, jobject self) -{ - AWT_LOCK(); - - if (!isClipboardViewerRegistered) { - AWT_UNLOCK(); - return; - } - - XtRemoveEventHandler(awt_root_shell, PropertyChangeMask, False, - propertyChangeEventHandlerToSelectionCheck, NULL); - - isClipboardViewerRegistered = FALSE; - - AWT_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_X11Clipboard - * Method: getClipboardFormats - * Signature: (J)[J - */ -JNIEXPORT jlongArray JNICALL -Java_sun_awt_motif_X11Clipboard_getClipboardFormats - (JNIEnv *env, jclass cls, jlong selectionAtom) -{ - Time time_stamp = awt_util_getCurrentServerTime(); - return get_selection_targets(env, selectionAtom, time_stamp); -} - -/* - * Class: sun_awt_motif_X11Clipboard - * Method: getClipboardData - * Signature: (JJ)[B - */ -JNIEXPORT jbyteArray JNICALL -Java_sun_awt_motif_X11Clipboard_getClipboardData - (JNIEnv *env, jclass cls, jlong selectionAtom, jlong format) -{ - Time time_stamp = awt_util_getCurrentServerTime(); - return get_selection_data(env, selectionAtom, format, time_stamp); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_TextArea.c b/jdk/src/solaris/native/sun/awt/awt_TextArea.c deleted file mode 100644 index 548b0d24310..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_TextArea.c +++ /dev/null @@ -1,1003 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "canvas.h" -#include "java_awt_TextArea.h" -#include "java_awt_Cursor.h" -#include "java_awt_Component.h" -#include "java_awt_Color.h" -#include "java_awt_AWTEvent.h" -#include "java_awt_Font.h" -#include "java_awt_event_MouseWheelEvent.h" -#include "sun_awt_motif_MTextAreaPeer.h" -#include "sun_awt_motif_MComponentPeer.h" - -#include "awt_Component.h" -#include "awt_Cursor.h" -#include "awt_TextArea.h" - -#include -#include -#include "multi_font.h" - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct CursorIDs cursorIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); -struct TextAreaIDs textAreaIDs; -struct MTextAreaPeerIDs mTextAreaPeerIDs; - -/* - * Class: java_awt_TextArea - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for TextArea.java - to initialize the fieldIDs for fields that may be accessed from C */ - -JNIEXPORT void JNICALL -Java_java_awt_TextArea_initIDs - (JNIEnv *env, jclass cls) -{ - textAreaIDs.scrollbarVisibility = - (*env)->GetFieldID(env, cls, "scrollbarVisibility", "I"); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - MTextAreaPeer.java to initialize the fieldIDs for fields that may - be accessed from C */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MTextAreaPeer_initIDs - (JNIEnv *env, jclass cls) -{ - mTextAreaPeerIDs.firstChangeSkipped = - (*env)->GetFieldID(env, cls, "firstChangeSkipped", "Z"); -} - -/* - * client_data is MTextAreaPeer instance - */ -void -TextArea_valueChanged(Widget w, XtPointer client_data, XtPointer call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jboolean skipped; - - skipped = (*env)->GetBooleanField(env, (jobject) client_data, - mTextAreaPeerIDs.firstChangeSkipped); - if (!(*env)->ExceptionOccurred(env)) { - if (skipped == JNI_FALSE) { - (*env)->SetBooleanField(env, (jobject) client_data, - mTextAreaPeerIDs.firstChangeSkipped, - JNI_TRUE); - } else { - JNU_CallMethodByName(env, NULL, (jobject) client_data, - "valueChanged", "()V"); - } - } - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -extern void Text_handlePaste(Widget w, XtPointer client_data, XEvent * event, - Boolean * cont); - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: pCreate - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_pCreate - (JNIEnv *env, jobject this, jobject parent) -{ - struct TextAreaData *tdata; -#define MAX_ARGC 30 - Arg args[MAX_ARGC]; - int32_t argc; - struct ComponentData *wdata; - jobject target; - Pixel bg; - int32_t sbVisibility; - Boolean wordWrap = False, hsb = False, vsb = False; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; - char *nonEmptyText = "* will never be shown *"; - - AWT_LOCK(); - - adata = copyGraphicsConfigToPeer(env, this); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,parent,mComponentPeerIDs.pData); - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - tdata = ZALLOC(TextAreaData); - JNU_SetLongFieldFromPtr(env,this,mComponentPeerIDs.pData,tdata); - - if (tdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - XtVaGetValues(wdata->widget, XmNbackground, &bg, NULL); - - sbVisibility = (*env)->GetIntField(env, target, - textAreaIDs.scrollbarVisibility); - switch (sbVisibility) { - case java_awt_TextArea_SCROLLBARS_NONE: - wordWrap = True; - hsb = False; - vsb = False; - break; - - case java_awt_TextArea_SCROLLBARS_VERTICAL_ONLY: - wordWrap = True; - hsb = False; - vsb = True; - break; - - case java_awt_TextArea_SCROLLBARS_HORIZONTAL_ONLY: - wordWrap = False; - hsb = True; - vsb = False; - break; - - default: - case java_awt_TextArea_SCROLLBARS_BOTH: - wordWrap = False; - hsb = True; - vsb = True; - break; - } - - argc = 0; - XtSetArg(args[argc], XmNrecomputeSize, False); - argc++; - XtSetArg(args[argc], XmNx, 0); - argc++; - XtSetArg(args[argc], XmNy, 0); - argc++; - XtSetArg(args[argc], XmNbackground, bg); - argc++; - XtSetArg(args[argc], XmNeditMode, XmMULTI_LINE_EDIT); - argc++; - XtSetArg(args[argc], XmNwordWrap, wordWrap); - argc++; - XtSetArg(args[argc], XmNscrollHorizontal, hsb); - argc++; - XtSetArg(args[argc], XmNscrollVertical, vsb); - argc++; - XtSetArg(args[argc], XmNmarginHeight, 2); - argc++; - XtSetArg(args[argc], XmNmarginWidth, 2); - argc++; - XtSetArg(args[argc], XmNuserData, (XtPointer) globalRef); - argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen)); - argc++; - XtSetArg(args[argc], XmNfontList, getMotifFontList()); - argc++; - - /* Initialize with a non-empty text, so the - * TextArea_valueChanged callback will be called - * even if the following conditions are true: - * 1. TextArea constructed with an empty initial text. - * 2. setText() with an empty argument is called - * immediately after the TextArea component is created. - * For more details please see #4028580. - */ - XtSetArg(args[argc], XmNvalue, nonEmptyText); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - tdata->txt = XmCreateScrolledText(wdata->widget, "textA", - args, argc); - tdata->comp.widget = XtParent(tdata->txt); - - /* Bug 4208972. Give the ScrolledWindow a minimum size. */ - XtVaSetValues(tdata->comp.widget, - XmNwidth, 1, - XmNheight, 1, NULL); - - XtSetMappedWhenManaged(tdata->comp.widget, False); - XtManageChild(tdata->txt); - XtManageChild(tdata->comp.widget); - - XtAddCallback(tdata->txt, - XmNvalueChangedCallback, - TextArea_valueChanged, - (XtPointer) globalRef); - - XtAddEventHandler(tdata->txt, FocusChangeMask, - True, awt_canvas_event_handler, globalRef); - - XtInsertEventHandler(tdata->txt, - KeyPressMask, - False, Text_handlePaste, (XtPointer) globalRef, - XtListHead); - - awt_addWidget(tdata->txt, tdata->comp.widget, globalRef, - java_awt_AWTEvent_KEY_EVENT_MASK | - java_awt_AWTEvent_MOUSE_EVENT_MASK | - java_awt_AWTEvent_MOUSE_MOTION_EVENT_MASK); - /* - * Fix for BugTraq ID 4349615. - * Unregister Motif drop site to prevent it from crash - * when dropping java objects. - */ - XmDropSiteUnregister(tdata->txt); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: getExtraWidth - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MTextAreaPeer_getExtraWidth - (JNIEnv *env, jobject this) -{ - struct TextAreaData *tdata; - Dimension spacing, shadowThickness, textMarginWidth, sbWidth; - Widget verticalScrollBar; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - XtVaGetValues(tdata->txt, XmNmarginWidth, &textMarginWidth, NULL); - XtVaGetValues(tdata->comp.widget, - XmNspacing, &spacing, - XmNverticalScrollBar, &verticalScrollBar, - NULL); - if (verticalScrollBar != NULL) { - /* Assumption: shadowThickness same for scrollbars and text area */ - XtVaGetValues(verticalScrollBar, - XmNwidth, &sbWidth, - XmNshadowThickness, &shadowThickness, - NULL); - } else { - sbWidth = 0; - shadowThickness = 0; - } - - AWT_UNLOCK(); - - return (jint) (sbWidth + spacing + 2 * textMarginWidth + 4 * shadowThickness); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: getExtraHeight - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MTextAreaPeer_getExtraHeight - (JNIEnv *env, jobject this) -{ - struct TextAreaData *tdata; - Dimension spacing, shadowThickness, textMarginHeight, sbHeight; - Dimension sbShadowThickness, highlightThickness, sbHighlightThickness; - int32_t height; - Widget horizontalScrollBar; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - - XtVaGetValues(tdata->txt, XmNmarginHeight, &textMarginHeight, - XmNshadowThickness, &shadowThickness, - XmNhighlightThickness, &highlightThickness, NULL); - height = 2 * (textMarginHeight + shadowThickness + highlightThickness); - - XtVaGetValues(tdata->comp.widget, - XmNspacing, &spacing, - XmNhorizontalScrollBar, &horizontalScrollBar, - NULL); - - if (horizontalScrollBar != NULL) { - XtVaGetValues(horizontalScrollBar, - XmNshadowThickness, &sbShadowThickness, - XmNhighlightThickness, &sbHighlightThickness, - XmNheight, &sbHeight, - NULL); - height += sbHeight + spacing - + 2 * (sbShadowThickness + sbHighlightThickness); - } - - AWT_UNLOCK(); - - return (jint)height; -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: setTextBackground - * Signature: (Ljava/awt/Color;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_setTextBackground - (JNIEnv *env, jobject this, jobject c) -{ - struct TextAreaData *tdata; - Pixel color; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL || JNU_IsNull(env, c)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - color = awtJNI_GetColor(env, c); - XtVaSetValues(tdata->txt, - XmNbackground, color, - NULL); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: pSetEditable - * Signature: (Z)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_pSetEditable - (JNIEnv *env, jobject this, jboolean editable) -{ - struct TextAreaData *tdata; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(tdata->txt, - XmNeditable, (editable ? True : False), - XmNcursorPositionVisible, (editable ? True : False), - NULL); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: select - * Signature: (II)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_select - (JNIEnv *env, jobject this, jint start, jint end) -{ - struct TextAreaData *tdata; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XmTextSetSelection(tdata->txt, (XmTextPosition) start, (XmTextPosition) end, 0); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: getSelectionStart - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MTextAreaPeer_getSelectionStart - (JNIEnv *env, jobject this) -{ - struct TextAreaData *tdata; - XmTextPosition start, end, pos; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - if (XmTextGetSelectionPosition(tdata->txt, &start, &end) && - (start != end)) { - pos = start; - } else { - pos = XmTextGetInsertionPosition(tdata->txt); - } - AWT_UNLOCK(); - - return (jint) pos; -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: getSelectionEnd - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MTextAreaPeer_getSelectionEnd - (JNIEnv *env, jobject this) -{ - struct TextAreaData *tdata; - XmTextPosition start, end, pos; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - if (XmTextGetSelectionPosition(tdata->txt, &start, &end) && - (start != end)) { - pos = end; - } else { - pos = XmTextGetInsertionPosition(tdata->txt); - } - AWT_UNLOCK(); - - return (jint) pos; -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: setText - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_setText - (JNIEnv *env, jobject this, jstring txt) -{ - struct TextAreaData *tdata; - char *cTxt; - jobject font = awtJNI_GetFont(env, this); - - if (JNU_IsNull(env, txt)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - cTxt = (char *) JNU_GetStringPlatformChars(env, txt, NULL); - - if (cTxt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(tdata->txt, XmNvalue, cTxt, NULL); - - if (cTxt != NULL) { - JNU_ReleaseStringPlatformChars(env, txt, cTxt); - } - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: getText - * Signature: ()Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_sun_awt_motif_MTextAreaPeer_getText - (JNIEnv *env, jobject this) -{ - struct TextAreaData *tdata; - char *cTxt; - jstring rval; - jobject font = awtJNI_GetFont(env, this); - - AWT_LOCK(); - - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env,this, mComponentPeerIDs.pData); - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return NULL; - } - cTxt = XmTextGetString(tdata->txt); - - rval = JNU_NewStringPlatform(env, (const char *) cTxt); - - XtFree(cTxt); - - AWT_UNLOCK(); - - return rval; -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: insert - * Signature: (Ljava/lang/String;I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_insert - (JNIEnv *env, jobject this, jstring txt, jint pos) -{ - struct TextAreaData *tdata; - char *cTxt; - jobject font = awtJNI_GetFont(env, this); - - if (JNU_IsNull(env, txt)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - cTxt = (char *) JNU_GetStringPlatformChars(env, txt, NULL); - - if (cTxt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XmTextInsert(tdata->txt, (XmTextPosition) pos, cTxt); - - if (cTxt != NULL) { - JNU_ReleaseStringPlatformChars(env, txt, cTxt); - } - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: replaceRange - * Signature: (Ljava/lang/String;II)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_replaceRange - (JNIEnv *env, jobject this, jstring txt, jint start, jint end) -{ - struct TextAreaData *tdata; - char *cTxt; - jobject font = awtJNI_GetFont(env, this); - - if (JNU_IsNull(env, txt)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - cTxt = (char *) JNU_GetStringPlatformChars(env, txt, NULL); - - if (cTxt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XmTextReplace(tdata->txt, - (XmTextPosition) start, - (XmTextPosition) end, - cTxt); - - if (cTxt != NULL) { - JNU_ReleaseStringPlatformChars(env, txt, cTxt); - } - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: setFont - * Signature: (Ljava/awt/Font;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_setFont - (JNIEnv *env, jobject this, jobject f) -{ - struct TextAreaData *tdata; - struct FontData *fdata; - XmFontList fontlist; - char *err; - XmFontListEntry fontentry; - - if (JNU_IsNull(env, f)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - AWT_LOCK(); - - fdata = awtJNI_GetFontData(env, f, &err); - if (fdata == NULL) { - JNU_ThrowInternalError(env, err); - AWT_UNLOCK(); - return; - } - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (awtJNI_IsMultiFont(env, f)) { - if (fdata->xfs == NULL) { - fdata->xfs = awtJNI_MakeFontSet(env, f); - } - if (fdata->xfs != NULL) { - fontentry = XmFontListEntryCreate("labelFont", - XmFONT_IS_FONTSET, - (XtPointer) (fdata->xfs)); - fontlist = XmFontListAppendEntry(NULL, fontentry); - /* - * Some versions of motif have a bug in - * XmFontListEntryFree() which causes it to free more than it - * should. Use XtFree() instead. See O'Reilly's - * Motif Reference Manual for more information. - */ - XmFontListEntryFree(&fontentry); - - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - - if (fontlist != NULL) { - Dimension textw, texth; - Dimension w, h; - - XtVaGetValues(tdata->txt, - XmNwidth, &textw, - XmNheight, &texth, - NULL); - XtVaGetValues(tdata->comp.widget, - XmNwidth, &w, - XmNheight, &h, - NULL); - - /* Must set width/height when we set the font, else - * Motif resets the text to a single row. - */ - XtVaSetValues(tdata->txt, - XmNfontList, fontlist, - XmNwidth, textw, - XmNheight, texth, - NULL); - XtVaSetValues(tdata->comp.widget, - XmNwidth, w, - XmNheight, h, - NULL); - - XmFontListFree(fontlist); - } else { - JNU_ThrowNullPointerException(env, "NullPointerException"); - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: setCaretPosition - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_setCaretPosition - (JNIEnv *env, jobject this, jint pos) -{ - struct TextAreaData *tdata; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XmTextSetInsertionPosition(tdata->txt, (XmTextPosition) pos); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: getCaretPosition - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MTextAreaPeer_getCaretPosition - (JNIEnv *env, jobject this) -{ - struct TextAreaData *tdata; - XmTextPosition pos; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - pos = XmTextGetInsertionPosition(tdata->txt); - - AWT_UNLOCK(); - - return (jint) pos; -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: pShow - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_pShow2 - (JNIEnv *env, jobject this) -{ - struct TextAreaData *tdata; - - AWT_LOCK(); - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - awt_util_show(tdata->comp.widget); - AWT_FLUSH_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: pMakeCursorVisible - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_pMakeCursorVisible - (JNIEnv *env, jobject this) -{ - struct TextAreaData *tdata; - - AWT_LOCK(); - tdata = (struct TextAreaData *) JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: pSetCursor - * Signature: (L/java/awt/Cursor;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_pSetCursor - (JNIEnv *env, jobject this, jobject cursor) -{ - Cursor xcursor; - struct TextAreaData *tdata; - - AWT_LOCK(); - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (tdata == NULL || tdata->comp.widget == NULL || JNU_IsNull(env, cursor)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - awt_util_setCursor(tdata->txt, getCursor(env, cursor)); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextAreaPeer - * Method: nativeHandleMouseWheel - * Signature: (III)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextAreaPeer_nativeHandleMouseWheel - (JNIEnv *env, jobject this, jint scrollType, jint scrollAmt, jint wheelAmt) -{ - struct TextAreaData *tdata; - Widget text = NULL; - Widget scroll = NULL; - - AWT_LOCK(); - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - // get the Text widget - text = tdata->txt; - if (text == NULL) { - AWT_UNLOCK(); - return; - } - - // get the ScrolledWindow - scroll = XtParent(text); - if (scroll == NULL) { - AWT_UNLOCK(); - return; - } - - awt_util_do_wheel_scroll(scroll, scrollType, scrollAmt, wheelAmt); - AWT_UNLOCK(); -} - - - -/* To be fully implemented in a future release - * - * Class: sun_awt_windows_MTextAreaPeer - * Method: getIndexAtPoint - * Signature: (II)I - * -JNIEXPORT jint JNICALL -Java_sun_awt_motif_MTextAreaPeer_getIndexAtPoint(JNIEnv *env, jobject self, - jint x, jint y) -{ - struct TextAreaData *tdata; - XmTextPosition pos; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env,self,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return -1; - } - pos = XmTextXYToPos(tdata->txt, x, y); - AWT_UNLOCK(); - - return (jint) pos; -} -*/ - -/* To be fully implemented in a future release - * - * Class: sun_awt_windows_MTextAreaPeer - * Method: getCharacterBounds - * Signature: (I)Ljava/awt/Rectangle; - * -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_MTextAreaPeer_getCharacterBounds(JNIEnv *env, jobject self, jint i) -{ -#define Text_FontAscent(tfg) (((XmTextWidget)(tfg)) -> \ - text.output->data->font_ascent) -#define Text_FontDescent(tfg) (((XmTextWidget)(tfg)) -> \ - text.output->data->font_descent) - - struct TextAreaData *tdata; - jobject rect=NULL; - Position x=0, y=0; - Position next_x=0, next_y=0; - int32_t w=0, h=0; - - AWT_LOCK(); - - tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env,self,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->txt == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return (jobject) NULL; - } - - XmTextPosToXY(tdata->txt, i, &x, &y); - y -= Text_FontAscent(tdata->txt); - XmTextPosToXY(tdata->txt, i+1, &next_x, &next_y); - w = next_x - x; - h = Text_FontAscent(tdata->txt) + Text_FontDescent(tdata->txt); - - AWT_UNLOCK(); - - if (w>0) { - jclass clazz; - jmethodID mid; - - clazz = (*env)->FindClass(env, "java/awt/Rectangle"); - mid = (*env)->GetMethodID(env, clazz, "", "(IIII)V"); - if (mid != NULL) { - rect = (*env)->NewObject(env, clazz, mid, x, y, w, h); - if ((*env)->ExceptionOccurred(env)) { - return (jobject) NULL; - } - } - } - return rect; -} -*/ diff --git a/jdk/src/solaris/native/sun/awt/awt_TextArea.h b/jdk/src/solaris/native/sun/awt/awt_TextArea.h deleted file mode 100644 index bf59017034a..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_TextArea.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#include "jni_util.h" - -/* fieldIDs for TextArea fields that may be accessed from C */ -static struct TextAreaIDs { - jfieldID scrollbarVisibility; -}; - -/* fieldIDs for MTextAreaPeer fields that may be accessed from C */ -struct MTextAreaPeerIDs { - jfieldID firstChangeSkipped; -}; diff --git a/jdk/src/solaris/native/sun/awt/awt_TextField.c b/jdk/src/solaris/native/sun/awt/awt_TextField.c deleted file mode 100644 index 889d82b718b..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_TextField.c +++ /dev/null @@ -1,989 +0,0 @@ -/* - * Copyright 1995-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include - -#include "awt_p.h" -#include "java_awt_TextField.h" -#include "java_awt_Color.h" -#include "java_awt_AWTEvent.h" -#include "java_awt_Font.h" -#include "java_awt_Canvas.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "sun_awt_motif_MCanvasPeer.h" -#include "sun_awt_motif_MTextFieldPeer.h" - -#include "awt_Component.h" -#include "awt_TextField.h" - -#include "multi_font.h" -#include -#include -#include -#include /* Motif TextField private header. */ - - -#define ECHO_BUFFER_LEN 1024 - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern AwtGraphicsConfigDataPtr - copyGraphicsConfigToPeer(JNIEnv *env, jobject this); -struct TextFieldIDs textFieldIDs; -struct MTextFieldPeerIDs mTextFieldPeerIDs; - -/* - * Class: java_awt_TextField - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for TextField.java - to initialize the fieldIDs for fields that may be accessed from C */ - -JNIEXPORT void JNICALL -Java_java_awt_TextField_initIDs - (JNIEnv *env, jclass cls) -{ - textFieldIDs.echoChar = - (*env)->GetFieldID(env, cls, "echoChar", "C"); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for - MTextFieldPeer.java to initialize the fieldIDs for fields that may - be accessed from C */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MTextFieldPeer_initIDs - (JNIEnv *env, jclass cls) -{ - mTextFieldPeerIDs.firstChangeSkipped = - (*env)->GetFieldID(env, cls, "firstChangeSkipped", "Z"); -} - -static void -echoChar(Widget text_w, XtPointer unused, XmTextVerifyCallbackStruct * cbs) -{ - size_t len; - int32_t c; - char *val; - struct DPos *dp; - int32_t ret; - jobject globalRef; - int32_t i, numbytes; - - struct TextFieldData *tdata; - - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - /* - * Get the echoContextID from the globalRef which is stored in - * the XmNuserData resource for the widget. - */ - XtVaGetValues(text_w,XmNuserData,&globalRef,NULL); - - tdata = (struct TextFieldData *) - (*env)->GetLongField(env,globalRef,mComponentPeerIDs.pData); - - ret = XFindContext(XtDisplay(text_w), (XID)text_w, tdata->echoContextID, - (XPointer *)&dp); - if ((ret != 0) || (dp == NULL)) { - /* no context found or DPos is NULL - shouldn't happen */ - return; - } - - c = dp->echoC; - val = (char *) (dp->data); - - len = strlen(val); - if (cbs->text->ptr == NULL) { - if (cbs->text->length == 0 && cbs->startPos == 0) { - val[0] = '\0'; - return; - } else if (cbs->startPos == (len - 1)) { - /* handle deletion */ - cbs->endPos = strlen(val); - val[cbs->startPos] = '\0'; - return; - } else { - /* disable deletes anywhere but at the end */ - cbs->doit = False; - return; - } - } - if (cbs->startPos != len) { - /* disable "paste" or inserts into the middle */ - cbs->doit = False; - return; - } - /* append the value typed in */ - if ((cbs->endPos + cbs->text->length) > ECHO_BUFFER_LEN) { - val = realloc(val, cbs->endPos + cbs->text->length + 10); - } - strncat(val, cbs->text->ptr, cbs->text->length); - val[cbs->endPos + cbs->text->length] = '\0'; - - /* modify the output to be the echo character */ - for (len = 0, i = 0; len < cbs->text->length; i++) { - /* Write one echo character for each multibyte character. */ - numbytes = mblen(cbs->text->ptr + len, cbs->text->length - len); - cbs->text->ptr[i] = (char) c; - len += numbytes; - } - cbs->text->length = i; -} - -/* - * Event handler used by both TextField/TextArea to correctly process - * cut/copy/paste keys such that interaction with our own - * clipboard mechanism will work properly. - * - * client_data is MTextFieldPeer instance - */ -void -Text_handlePaste(Widget w, XtPointer client_data, XEvent * event, Boolean * cont) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - KeySym keysym; - Modifiers mods; - - /* Any event handlers which take peer instance pointers as - * client_data should check to ensure the widget has not been - * marked as destroyed as a result of a dispose() call on the peer - * (which can result in the peer instance pointer already haven - * been gc'd by the time this event is processed) - */ - if (event->type != KeyPress || w->core.being_destroyed) { - return; - } - - XtTranslateKeycode(event->xkey.display, (KeyCode) event->xkey.keycode, - event->xkey.state, &mods, &keysym); - - /* Should be a temporary fix for 4052132 if a cleaner fix is found later */ - if ((event->xkey.state & ControlMask) && (keysym == 'v' || keysym == 'V')) - keysym = osfXK_Paste; - if ((event->xkey.state & ShiftMask) && (keysym == osfXK_Insert)) - keysym = osfXK_Paste; - - switch (keysym) { - case osfXK_Paste: - /* If we own the selection, then paste the data directly */ - if (awtJNI_isSelectionOwner(env, "CLIPBOARD")) { - JNU_CallMethodByName(env, NULL, (jobject) client_data, - "pasteFromClipboard", "()V"); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - *cont = FALSE; - } - break; - - case osfXK_Cut: - case osfXK_Copy: - /* For some reason if we own the selection, our loseSelection - * callback is not automatically called on cut/paste from - * text widgets. - */ - if (awtJNI_isSelectionOwner(env, "CLIPBOARD")) { - awtJNI_notifySelectionLost(env, "CLIPBOARD"); - } - break; - default: - break; - } -} - -/* - * client_data is MTextFieldPeer instance - */ -void -TextField_valueChanged(Widget w, XtPointer client_data, XtPointer call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jboolean skipped; - - skipped = (*env)->GetBooleanField(env, (jobject) client_data, - mTextFieldPeerIDs.firstChangeSkipped); - if (!(*env)->ExceptionOccurred(env)) { - if (skipped == JNI_FALSE) { - (*env)->SetBooleanField(env, (jobject) client_data, - mTextFieldPeerIDs.firstChangeSkipped, - JNI_TRUE); - } else { - JNU_CallMethodByName(env, NULL, (jobject) client_data, - "valueChanged", "()V"); - } - } - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -/* - * client_data is MTextFieldPeer instance - */ -static void -TextField_action(Widget w, XtPointer client_data, XmAnyCallbackStruct * s) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - ConvertEventTimeAndModifiers converted; - - awt_util_convertEventTimeAndModifiers(s->event, &converted); - - JNU_CallMethodByName(env, NULL, (jobject) client_data, "action", "(JI)V", - converted.when, converted.modifiers); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: pCreate - * Signature: (Lsun/awt/motif/MComponentPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_pCreate - (JNIEnv *env, jobject this, jobject parent) -{ - struct ComponentData *wdata; - struct TextFieldData *tdata; - - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - AwtGraphicsConfigDataPtr adata; - - AWT_LOCK(); - - adata = copyGraphicsConfigToPeer(env, this); - - if (JNU_IsNull(env, parent)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - wdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,parent,mComponentPeerIDs.pData); - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - tdata = ZALLOC(TextFieldData); - if (tdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - JNU_SetLongFieldFromPtr(env,this,mComponentPeerIDs.pData,tdata); - - tdata->comp.widget = XtVaCreateManagedWidget("textfield", - xmTextFieldWidgetClass, - wdata->widget, - XmNrecomputeSize, False, - XmNhighlightThickness, 1, - XmNshadowThickness, 2, - XmNuserData, (XtPointer) globalRef, - XmNscreen, - ScreenOfDisplay(awt_display, - adata->awt_visInfo.screen), - XmNfontList, getMotifFontList(), - NULL); - tdata->echoContextIDInit = FALSE; - - XtSetMappedWhenManaged(tdata->comp.widget, False); - XtAddCallback(tdata->comp.widget, - XmNactivateCallback, - (XtCallbackProc) TextField_action, - (XtPointer) globalRef); - XtAddCallback(tdata->comp.widget, - XmNvalueChangedCallback, - (XtCallbackProc) TextField_valueChanged, - (XtPointer) globalRef); - XtInsertEventHandler(tdata->comp.widget, - KeyPressMask, - False, Text_handlePaste, (XtPointer) globalRef, - XtListHead); - /* - * Fix for BugTraq ID 4349615. - * Unregister Motif drop site to prevent it from crash - * when dropping java objects. - */ - XmDropSiteUnregister(tdata->comp.widget); - - AWT_UNLOCK(); -} - -/* - * Class sun_awt_motif_MTextFieldPeer - * Method: pSetEditable - * Signature: (Z)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_pSetEditable - (JNIEnv *env, jobject this, jboolean editable) -{ - struct TextFieldData *tdata; - - AWT_LOCK(); - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(tdata->comp.widget, - XmNeditable, (editable ? True : False), - XmNcursorPositionVisible, (editable ? True : False), - NULL); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: select - * Signature: (II)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_select - (JNIEnv *env, jobject this, jint start, jint end) -{ - struct TextFieldData *tdata; - - AWT_LOCK(); - - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XmTextSetSelection(tdata->comp.widget, (XmTextPosition) start, (XmTextPosition) end, 0); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: getSelectionStart - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MTextFieldPeer_getSelectionStart - (JNIEnv *env, jobject this) -{ - struct TextFieldData *tdata; - XmTextPosition start, end, pos; - - AWT_LOCK(); - - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - if (XmTextGetSelectionPosition(tdata->comp.widget, &start, &end) && - (start != end)) { - pos = start; - } else { - pos = XmTextGetInsertionPosition(tdata->comp.widget); - } - AWT_UNLOCK(); - - return (jint) pos; -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: getSelectionEnd - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MTextFieldPeer_getSelectionEnd - (JNIEnv *env, jobject this) -{ - struct TextFieldData *tdata; - XmTextPosition start, end, pos; - - AWT_LOCK(); - - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - if (XmTextGetSelectionPosition(tdata->comp.widget, &start, &end) && - (start != end)) { - pos = end; - } else { - pos = XmTextGetInsertionPosition(tdata->comp.widget); - } - AWT_UNLOCK(); - - return (jint) pos; -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: setText - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_setText - (JNIEnv *env, jobject this, jstring l) -{ - struct TextFieldData *tdata; - char *cl; - jobject target; - - AWT_LOCK(); - - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (JNU_IsNull(env, l)) { - cl = ""; - } else { - /* - * Note: Motif TextField widgets do not support multi-font - * compound strings. - */ - cl = (char *) JNU_GetStringPlatformChars(env, l, NULL); - } - - /* Fix for bug 4084454 : setText appears in clear */ - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - if ((*env)->GetCharField(env, target, textFieldIDs.echoChar) != 0) { - XtVaSetValues(tdata->comp.widget, - XmNvalue, "", NULL); - XmTextFieldInsert(tdata->comp.widget,0,cl); - XmTextSetInsertionPosition(tdata->comp.widget, - (XmTextPosition) strlen(cl)); - } - else { - XtVaSetValues(tdata->comp.widget, - XmNvalue, cl, - NULL); - } - /* - * Fix for BugTraq Id 4185654 - TextField.setText() incorrect justification - * Comment out the next line. - */ - /* XmTextSetInsertionPosition(tdata->comp.widget, - * (XmTextPosition) strlen(cl)); - */ - - if (cl != NULL && cl != "") { - JNU_ReleaseStringPlatformChars(env, l, cl); - } - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: insertReplaceText - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_insertReplaceText - (JNIEnv *env, jobject this, jstring l) -{ - struct TextFieldData *tdata; - char *cl; - XmTextPosition start, end; - - AWT_LOCK(); - - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - if (JNU_IsNull(env, l)) { - cl = ""; - } else { - /* - * Note: Motif TextField widgets do not support multi-font - * compound strings. - */ - cl = (char *) JNU_GetStringPlatformChars(env, l, NULL); - } - - if (!XmTextGetSelectionPosition(tdata->comp.widget, &start, &end)) { - start = end = XmTextGetInsertionPosition(tdata->comp.widget); - } - XmTextReplace(tdata->comp.widget, start, end, cl); - - if (cl != NULL && cl != "") { - JNU_ReleaseStringPlatformChars(env, l, cl); - } - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: preDispose - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_preDispose - (JNIEnv *env, jobject this) -{ - struct TextFieldData *tdata; - struct DPos *dp; - jobject target; - int32_t ret; - - AWT_LOCK(); - - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if ((*env)->GetCharField(env, target, textFieldIDs.echoChar) != 0) { - ret = XFindContext(XtDisplay(tdata->comp.widget), (XID)(tdata->comp.widget), - tdata->echoContextID, (XPointer *)&dp); - if ((ret == 0) && dp != NULL) { - - /* Remove the X context associated with this textfield's - * echo character. BugId #4225734 - */ - XDeleteContext(XtDisplay(tdata->comp.widget), - (XID)(tdata->comp.widget), - tdata->echoContextID); - - tdata->echoContextIDInit = FALSE; - - /* Free up the space allocated for the echo character data. */ - if (dp->data) { - free(dp->data); - } - free(dp); - } - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: getText - * Signature: ()Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_sun_awt_motif_MTextFieldPeer_getText - (JNIEnv *env, jobject this) -{ - struct TextFieldData *tdata; - char *val; - struct DPos *dp; - jobject target; - int32_t ret; - jstring returnVal; - - AWT_LOCK(); - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return NULL; - } - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if ((*env)->GetCharField(env, target, textFieldIDs.echoChar) != 0) { - ret = XFindContext(XtDisplay(tdata->comp.widget), (XID)tdata->comp.widget, - tdata->echoContextID, (XPointer *)&dp); - if ((ret == 0) && (dp != NULL)) { - val = (char *)(dp->data); - } else { - val = ""; - } - } else { - XtVaGetValues(tdata->comp.widget, XmNvalue, &val, NULL); - } - AWT_UNLOCK(); - - returnVal = JNU_NewStringPlatform(env, (const char *) val); - if ((*env)->GetCharField(env, target, textFieldIDs.echoChar) == 0) { - free(val); - } - return returnVal; -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: setEchoChar - * Signature: (C)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_setEchoChar - (JNIEnv *env, jobject this, jchar c) -{ - char *val; - char *cval; - struct TextFieldData *tdata; - struct DPos *dp; - int32_t i; - size_t len; - int32_t ret; - - AWT_LOCK(); - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - XtVaGetValues(tdata->comp.widget, - XmNvalue, &cval, - NULL); - - DASSERT(c != 0 || tdata->echoContextIDInit); - - if (!tdata->echoContextIDInit) { - tdata->echoContextID = XUniqueContext(); - tdata->echoContextIDInit = TRUE; - } - ret = XFindContext(XtDisplay(tdata->comp.widget), (XID)(tdata->comp.widget), - tdata->echoContextID, (XPointer *)&dp); - /* - * Fix for BugTraq ID 4307281. - * Special case for setting echo char to 0: - * - remove the callback and X context associated with echo character; - * - restore the original text. - */ - if (c == 0) { - XtRemoveCallback(tdata->comp.widget, XmNmodifyVerifyCallback, - (XtCallbackProc) echoChar, NULL); - if (ret == 0 && dp != NULL) { - - /* Remove the X context associated with echo character. */ - XDeleteContext(XtDisplay(tdata->comp.widget), - (XID)(tdata->comp.widget), - tdata->echoContextID); - - tdata->echoContextIDInit = FALSE; - - /* Restore the original text. */ - if (dp->data != NULL) { - val = (char *)(dp->data); - } else { - val = ""; - } - XtVaSetValues(tdata->comp.widget, - XmNvalue, val, - NULL); - - /* Free up the space allocated for the echo character data. */ - if (dp->data) { - free(dp->data); - } - free(dp); - } - AWT_UNLOCK(); - return; - } - if (ret != 0) { - dp = NULL; - } - - if (dp != NULL) { - /* Fix bug 4124697: cannot change setEchoChar twice on Motif */ - XtRemoveCallback(tdata->comp.widget, XmNmodifyVerifyCallback, - (XtCallbackProc) echoChar, NULL); - } else { - if ((int32_t) strlen(cval) > ECHO_BUFFER_LEN) { - val = (char *) malloc(strlen(cval) + 1); - } else { - val = (char *) malloc(ECHO_BUFFER_LEN + 1); - } - if (val == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - if (cval != NULL) { - strcpy(val, cval); - } else { - *val = '\0'; - } - dp = (struct DPos *) malloc(sizeof(struct DPos)); - - dp->x = -1; - dp->data = (void *) val; - } - - dp->echoC = c; - len = strlen(cval); - for (i = 0; i < len; i++) { - cval[i] = (char) (c); - } - XtVaSetValues(tdata->comp.widget, - XmNvalue, cval, - NULL); - - ret = XSaveContext(XtDisplay(tdata->comp.widget), (XID)tdata->comp.widget, - tdata->echoContextID, (XPointer)dp); - if (ret == 0) { - XtAddCallback(tdata->comp.widget, XmNmodifyVerifyCallback, - (XtCallbackProc) echoChar, NULL); - } - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: setFont - * Signature: (Ljava/awt/Font;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_setFont - (JNIEnv *env, jobject this, jobject f) -{ - struct TextFieldData *tdata; - struct FontData *fdata; - XmFontListEntry fontentry; - XmFontList fontlist; - char *err; - - AWT_LOCK(); - if (JNU_IsNull(env, f)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - fdata = awtJNI_GetFontData(env, f, &err); - if (fdata == NULL) { - JNU_ThrowInternalError(env, err); - AWT_UNLOCK(); - return; - } - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (awtJNI_IsMultiFont(env, f)) { - if (fdata->xfs == NULL) { - fdata->xfs = awtJNI_MakeFontSet(env, f); - } - if (fdata->xfs != NULL) { - fontentry = XmFontListEntryCreate("labelFont", - XmFONT_IS_FONTSET, - (XtPointer) (fdata->xfs)); - fontlist = XmFontListAppendEntry(NULL, fontentry); - /* - * Some versions of motif have a bug in - * XmFontListEntryFree() which causes it to free more than it - * should. Use XtFree() instead. See O'Reilly's - * Motif Reference Manual for more information. - */ - XmFontListEntryFree(&fontentry); - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - } else { - fontlist = XmFontListCreate(fdata->xfont, "labelFont"); - } - - if (fontlist != NULL) { - XtVaSetValues(tdata->comp.widget, XmNfontList, fontlist, NULL); - XmFontListFree(fontlist); - } else { - JNU_ThrowNullPointerException(env, "NullPointerException"); - } - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: setCaretPosition - * Signature: (I)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MTextFieldPeer_setCaretPosition - (JNIEnv *env, jobject this, jint pos) -{ - struct TextFieldData *tdata; - - AWT_LOCK(); - - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XmTextSetInsertionPosition(tdata->comp.widget, (XmTextPosition) pos); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MTextFieldPeer - * Method: getCaretPosition - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_sun_awt_motif_MTextFieldPeer_getCaretPosition - (JNIEnv *env, jobject this) -{ - struct TextFieldData *tdata; - XmTextPosition pos; - - AWT_LOCK(); - - tdata = (struct TextFieldData *) - JNU_GetLongFieldAsPtr(env,this,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return 0; - } - pos = XmTextGetInsertionPosition(tdata->comp.widget); - AWT_UNLOCK(); - - return (jint) pos; -} - - -/* To be fully implemented in a future release - * - * Class: sun_awt_windows_MTextFieldPeer - * Method: getIndexAtPoint - * Signature: (Ljava/awt/Point;)I - * -JNIEXPORT jint JNICALL -Java_sun_awt_motif_MTextFieldPeer_getIndexAtPoint(JNIEnv *env, jobject self, - jint x, jint y) -{ - struct ComponentData *tdata; - XmTextPosition pos; - - AWT_LOCK(); - - tdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,self,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return -1; - } - pos = XmTextFieldXYToPos(tdata->widget, x, y); - AWT_UNLOCK(); - - return (jint) pos; -} -*/ - -/* To be fully implemented in a future release - * - * Class: sun_awt_windows_MTextFieldPeer - * Method: getCharacterBounds - * Signature: (I)Ljava/awt/Rectangle; - * -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_MTextFieldPeer_getCharacterBounds(JNIEnv *env, jobject self, jint i) -{ -#define TextF_FontAscent(tfg) (((XmTextFieldWidget)(tfg)) -> \ - text.font_ascent) -#define TextF_FontDescent(tfg) (((XmTextFieldWidget)(tfg)) -> \ - text.font_descent) - - struct ComponentData *tdata; - jobject rect=NULL; - Position x=0, y=0; - Position next_x=0, next_y=0; - int32_t w=0, h=0; - - AWT_LOCK(); - - tdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env,self,mComponentPeerIDs.pData); - - if (tdata == NULL || tdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return (jobject) NULL; - } - - XmTextFieldPosToXY(tdata->widget, i, &x, &y); - y -= TextF_FontAscent(tdata->widget); - XmTextFieldPosToXY(tdata->widget, i+1, &next_x, &next_y); - w = next_x - x; - h = TextF_FontAscent(tdata->widget) + TextF_FontDescent(tdata->widget); - - AWT_UNLOCK(); - - if (w>0) { - jclass clazz; - jmethodID mid; - - clazz = (*env)->FindClass(env, "java/awt/Rectangle"); - mid = (*env)->GetMethodID(env, clazz, "", "(IIII)V"); - if (mid != NULL) { - rect = (*env)->NewObject(env, clazz, mid, x, y, w, h); - if ((*env)->ExceptionOccurred(env)) { - return NULL; - } - } - } - return rect; -} -*/ diff --git a/jdk/src/solaris/native/sun/awt/awt_TextField.h b/jdk/src/solaris/native/sun/awt/awt_TextField.h deleted file mode 100644 index 1566ef79111..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_TextField.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#include "jni_util.h" - -/* fieldIDs for TextField fields that may be accessed from C */ -static struct TextFieldIDs { - jfieldID echoChar; -}; - -/* fieldIDs for MTextFieldPeer fields that may be accessed from C */ -struct MTextFieldPeerIDs { - jfieldID firstChangeSkipped; -}; diff --git a/jdk/src/solaris/native/sun/awt/awt_TopLevel.c b/jdk/src/solaris/native/sun/awt/awt_TopLevel.c deleted file mode 100644 index 165c1cfa562..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_TopLevel.c +++ /dev/null @@ -1,5095 +0,0 @@ -/* - * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include "VDrawingArea.h" - -#ifdef DEBUG -# include -#endif - -#include -#include - -/* JNI headers */ -#include "java_awt_Color.h" -#include "java_awt_Component.h" -#include "java_awt_Dialog.h" -#include "java_awt_Font.h" -#include "java_awt_Frame.h" -#include "java_awt_Image.h" -#include "java_awt_Insets.h" -#include "java_awt_Insets.h" -#include "java_awt_MenuBar.h" -#include "java_awt_Window.h" -#include "java_awt_event_FocusEvent.h" -#include "java_awt_TrayIcon.h" -#include "sun_awt_EmbeddedFrame.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "sun_awt_motif_MDialogPeer.h" -#include "sun_awt_motif_MEmbeddedFramePeer.h" -#include "sun_awt_motif_MFramePeer.h" -#include "sun_awt_motif_MMenuBarPeer.h" -#include "sun_awt_motif_MWindowPeer.h" - -/* JNI field and method ids */ -#include "awt_Component.h" -#include "awt_GraphicsEnv.h" -#include "awt_Insets.h" -#include "awt_MenuBar.h" -#include "awt_Window.h" -#include "awt_KeyboardFocusManager.h" -#include "awt_MToolkit.h" -#include "awt_Plugin.h" - -#include "color.h" -#include "canvas.h" -#include "awt_util.h" -#include "img_util.h" -#include "awt_wm.h" -#include "awt_util.h" -#include "awt_xembed.h" - - -#ifdef __linux__ -void adjustStatusWindow(Widget shell); -#endif -/* For the moment only InputMethodWindow is taking advantage of -** the posibility for different decor styles -** values could be passed are the MWM_DECOR defines -** for the moment we are full on or full off. -*/ -#define AWT_NO_DECOR 0x0 -#define AWT_FULL_DECOR MWM_DECOR_ALL - -static void reshape(JNIEnv *env, jobject this, struct FrameData *wdata, - jint x, jint y, jint w, jint h, Boolean setXY); -Widget findTopLevelByShell(Widget widget); - -extern EmbeddedFrame *theEmbeddedFrameList; -extern struct ComponentIDs componentIDs; -extern struct MMenuBarPeerIDs mMenuBarPeerIDs; -extern struct MComponentPeerIDs mComponentPeerIDs; -struct WindowIDs windowIDs; -struct MWindowPeerIDs mWindowPeerIDs; -extern struct InsetsIDs insetsIDs; -extern struct X11GraphicsConfigIDs x11GraphicsConfigIDs; -extern struct KeyboardFocusManagerIDs keyboardFocusManagerIDs; -extern struct X11GraphicsDeviceIDs x11GraphicsDeviceIDs; - -#ifndef NOMODALFIX -extern Boolean awt_isModal(); -extern Boolean awt_isWidgetModal(Widget w); -extern void awt_shellPoppedUp(Widget shell, XtPointer c, XtPointer d); -extern void awt_shellPoppedDown(Widget shell, XtPointer c, XtPointer d); -#endif //NOMODALFIX - -static jclass inputMethodWindowClass = NULL; - -static int32_t globalTopGuess = 0; -static int32_t globalLeftGuess = 0; -static int32_t globalBottomGuess = 0; -static int32_t globalRightGuess = 0; - - -// Atom used for otlogenniy top-level disposal -static Atom _XA_JAVA_DISPOSE_PROPERTY_ATOM = 0; - -/* - * Fix for bug 4141361 - * - * We keep a linked list of the FrameData information for - * every top level window. - */ -struct FrameDataList { - struct FrameData* wdata; - struct FrameDataList* next; -}; - -static struct FrameDataList* allTopLevel = NULL; - -extern void checkNewXineramaScreen(JNIEnv* env, jobject peer, - struct FrameData* wdata, - int32_t newX, int32_t newY, - int32_t newWidth, int32_t newHeight); - -// Returns false if this Window is non-focusable -// or its nearest decorated parent is non-focusable. -Boolean isFocusableWindowByPeer(JNIEnv * env, jobject peer) { - jobject target, decoratedParent; - struct FrameData *wdata; - Boolean focusable; - - wdata = (struct FrameData *)JNU_GetLongFieldAsPtr(env, peer, mComponentPeerIDs.pData); - DASSERT(wdata != NULL); - - target = (*env)->GetObjectField(env, peer, mComponentPeerIDs.target); - DASSERT(target != NULL); - - decoratedParent = getOwningFrameOrDialog(target, env); - (*env)->DeleteLocalRef(env, target); - - if (decoratedParent == NULL) { - return wdata->isFocusableWindow; - } else { - jobject parentPeer = (*env)->GetObjectField(env, decoratedParent, componentIDs.peer); - DASSERT(parentPeer != NULL); - focusable = wdata->isFocusableWindow && isFocusableWindowByPeer(env, parentPeer); - - (*env)->DeleteLocalRef(env, decoratedParent); - (*env)->DeleteLocalRef(env, parentPeer); - } - return focusable; -} - -// Returns false if this shell's Java Window is non-focusable -// or its nearest decorated parent is non-focusable. -// Returns true otherwise or if any of parameters is NULL -Boolean isFocusableWindowByShell(JNIEnv* env, Widget shell) { - Widget toplevel; - jobject peer; - Boolean focusable; - - DASSERT(shell != NULL && XtIsShell(shell)); - if (shell == NULL) return True; - if (!XtIsShell(shell)) return True; - - toplevel = findTopLevelByShell(shell); - if (toplevel == NULL) { - return True; - } - peer = findPeer(&toplevel); - DASSERT(peer != NULL); - - if (env == NULL) { - env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - } - return isFocusableWindowByPeer(env, peer); -} - - -// Returns Shell widget - the parent of this child -Widget getShellWidget(Widget child) { - - while (child != NULL && !XtIsShell(child)) { - child = XtParent(child); - } - return child; -} - -// Returns false if the parent shell of this widget is non-focusable Java Window. -// Returns false otherwise. -// Doesn't accept NULL parameters. -Boolean isFocusableComponentTopLevelByWidget(JNIEnv * env, Widget child) { - Widget shell = NULL; - shell = getShellWidget(child); - DASSERT(shell); - return isFocusableWindowByShell(env, shell); -} - - -/* - * Add a new element into the top level window list - */ -void addTopLevel(struct FrameData* wdata) { - struct FrameDataList* newNode; - newNode = (struct FrameDataList*) - malloc(sizeof(struct FrameDataList)); - newNode->wdata = wdata; - newNode->next = allTopLevel; - allTopLevel = newNode; -} - -/* - * Remove an element from the top level window list - * (recursive) - */ -Boolean removeTopLevelR(struct FrameDataList** ptr, - struct FrameData* wdata) { - struct FrameDataList* node = *ptr; - if (node == NULL) { - return False; - } - if (node->wdata == wdata) { - *ptr = node->next; - free(node); - return True; - } - return removeTopLevelR(&(node->next), wdata); -} - -Boolean removeTopLevel(struct FrameData* wdata) { - return removeTopLevelR(&allTopLevel, wdata); -} - -/* - * Return the Widget ID of the top level window underneath the - * mouse pointer. - */ -Widget awt_GetWidgetAtPointer() { - struct FrameDataList* ptr = allTopLevel; - Window rootWindow, childWindow, mainWindow; - int32_t xw, yw, xr, yr; - uint32_t keys; - while (ptr != NULL) { - mainWindow = XtWindow(ptr->wdata->mainWindow); - XQueryPointer(awt_display, mainWindow, - &rootWindow, &childWindow, &xr, &yr, &xw, &yw, &keys); - if (childWindow != None) { - return ptr->wdata->winData.comp.widget; - } - ptr = ptr->next; - } - return NULL; -} - -Widget findFocusProxy(Widget widget) { - struct FrameDataList* ptr = allTopLevel; - for (ptr = allTopLevel; ptr != NULL; ptr = ptr->next) { - if (ptr->wdata->winData.comp.widget == widget) { - return ptr->wdata->focusProxy; - } - } - return NULL; -} - -Widget findTopLevelByShell(Widget widget) { - struct FrameDataList* ptr; - for (ptr = allTopLevel; ptr != NULL; ptr = ptr->next) { - if (ptr->wdata->winData.shell == widget) { - return ptr->wdata->winData.comp.widget; - } - } - return NULL; -} - -void -awt_Frame_guessInsets(struct FrameData *wdata) -{ - if (wdata->decor == AWT_NO_DECOR ) { - wdata->top = wdata->topGuess = 0; - wdata->left = wdata->leftGuess = 0; - wdata->bottom = wdata->bottomGuess = 0; - wdata->right = wdata->rightGuess = 0; - return; - } - - if (globalTopGuess == 0) { - char *insets_env; - - if (wdata->top >= 0) { - /* insets were set on wdata by System Properties */ - globalTopGuess = wdata->top; - globalLeftGuess = wdata->left; - globalBottomGuess = wdata->bottom; - globalRightGuess = wdata->right; - } - else switch (awt_wm_getRunningWM()) { - case ENLIGHTEN_WM: - globalTopGuess = 19; - globalLeftGuess = 4; - globalBottomGuess = 4; - globalRightGuess = 4; - break; - - case CDE_WM: - globalTopGuess = 28; - globalLeftGuess = 6; - globalBottomGuess = 6; - globalRightGuess = 6; - break; - - case MOTIF_WM: - case OPENLOOK_WM: - default: - globalTopGuess = 25; - globalLeftGuess = 5; - globalBottomGuess = 5; - globalRightGuess = 5; - break; - } - - if ((insets_env = getenv("AWT_INSETS")) != NULL) { - int guess = atoi(insets_env); - globalTopGuess = (guess & 0xff00) >> 8; - globalLeftGuess = guess & 0x00ff; - globalBottomGuess = wdata->leftGuess; - globalRightGuess = wdata->leftGuess; - } - - /* don't allow bizarly large insets */ - if ((globalTopGuess > 64) || (globalTopGuess < 0)) - globalTopGuess = 28; - if ((globalLeftGuess > 32) || (globalLeftGuess < 0)) - globalLeftGuess = 6; - if ((globalBottomGuess > 32) || (globalBottomGuess < 0)) - globalBottomGuess = 6; - if ((globalRightGuess > 32) || (globalRightGuess < 0)) - globalRightGuess = 6; - } - - wdata->top = wdata->topGuess = globalTopGuess; - wdata->left = wdata->leftGuess = globalLeftGuess; - wdata->bottom = wdata->bottomGuess = globalBottomGuess; - wdata->right = wdata->rightGuess = globalRightGuess; -} - -/* - * To keep input method windows floating, maintain a list of all - * input method windows here. When some top level window gets - * activated, moved, or resized, these input method windows need - * to be brought on top. - */ -static struct FrameDataList* allInputMethodWindow = NULL; - -/* - * Add a new element into the input method window list - */ -void addInputMethodWindow(struct FrameData* wdata) { - struct FrameDataList* newNode; - newNode = (struct FrameDataList*) - malloc(sizeof(struct FrameDataList)); - newNode->wdata = wdata; - newNode->next = allInputMethodWindow; - allInputMethodWindow = newNode; -} - -/* - * Remove an element from the top level window list - * (recursive) - */ -Boolean removeInputMethodWindowR(struct FrameDataList** ptr, - struct FrameData* wdata) { - struct FrameDataList* node = *ptr; - if (node == NULL) { - return False; - } - if (node->wdata == wdata) { - *ptr = node->next; - free(node); - return True; - } - return removeInputMethodWindowR(&(node->next), wdata); -} - -Boolean removeInputMethodWindow(struct FrameData* wdata) { - return removeInputMethodWindowR(&allInputMethodWindow, wdata); -} - -/* - * Raise input method windows - */ -void raiseInputMethodWindow(struct FrameData* wdata) { - struct FrameDataList* node = allInputMethodWindow; - - if (wdata->isInputMethodWindow) { - return; - } - - while (node != NULL) { - XRaiseWindow(awt_display, XtWindow(node->wdata->winData.shell)); - node = node->next; - } -} - -/* fieldIDs for Frame fields that may be accessed from C */ -static struct FrameIDs { - jfieldID resizable; - jfieldID state; -} frameIDs; - -/* - * Class: java_awt_Frame - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for Frame.java - to initialize the fieldIDs for fields that may be accessed from C */ -JNIEXPORT void JNICALL -Java_java_awt_Frame_initIDs - (JNIEnv *env, jclass cls) -{ - frameIDs.resizable = (*env)->GetFieldID(env, cls, "resizable", "Z"); - frameIDs.state = (*env)->GetFieldID(env, cls, "state", "I"); -} - -/* ******* */ -/* Dialogs */ -/* ******* */ -/* No longer have a need for unique fields for query */ -static struct DialogIDs { - jfieldID modal; - jfieldID resizable; -} dialogIDs; - -JNIEXPORT void JNICALL -Java_java_awt_Dialog_initIDs - (JNIEnv *env, jclass cls) -{ -#if 0 - dialogIDs.modal = (*env)->GetFieldID(env, cls, "modal", "Z"); - dialogIDs.resizable = (*env)->GetFieldID(env, cls, "resizable", "Z"); -#endif -} - -/* ******* */ -/* Windows */ -/* ******* */ - -JNIEXPORT void JNICALL -Java_java_awt_Window_initIDs - (JNIEnv *env, jclass cls) -{ - windowIDs.warningString = (*env)->GetFieldID(env, cls, "warningString", - "Ljava/lang/String;"); - windowIDs.resetGCMID = (*env)->GetMethodID(env, cls, "resetGC", - "()V"); - - windowIDs.locationByPlatform = (*env)->GetFieldID(env, cls, "locationByPlatform", - "Z"); - windowIDs.isAutoRequestFocus = (*env)->GetFieldID(env, cls, "autoRequestFocus", "Z"); - - DASSERT(windowIDs.resetGCMID); -} - -/* - * Class: sun_motif_awt_WindowAttributes - * Method: initIDs - * Signature: ()V - */ - -static struct MWindowAttributeIDs { - jfieldID nativeDecor; - jfieldID initialFocus; - jfieldID isResizable; - jfieldID initialState; - jfieldID visibilityState; - jfieldID decorations; -} mWindowAttributeIDs; - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowAttributes_initIDs - (JNIEnv *env, jclass cls) -{ - mWindowAttributeIDs.nativeDecor = - (*env)->GetFieldID(env, cls, "nativeDecor", "Z"); - mWindowAttributeIDs.initialFocus = - (*env)->GetFieldID(env, cls, "initialFocus", "Z"); - mWindowAttributeIDs.isResizable = - (*env)->GetFieldID(env, cls, "isResizable", "Z"); - mWindowAttributeIDs.initialState = - (*env)->GetFieldID(env, cls, "initialState", "I"); - mWindowAttributeIDs.visibilityState = - (*env)->GetFieldID(env, cls, "visibilityState", "I"); - mWindowAttributeIDs.decorations = - (*env)->GetFieldID(env, cls, "decorations", "I"); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: initIDs - * Signature: ()V - */ - -/* This function gets called from the static initializer for MWindowPeer.java - to initialize the fieldIDs for fields that may be accessed from C */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_initIDs - (JNIEnv *env, jclass cls) -{ - mWindowPeerIDs.insets = - (*env)->GetFieldID(env, cls, "insets", "Ljava/awt/Insets;"); - mWindowPeerIDs.winAttr = - (*env)->GetFieldID( env, - cls, - "winAttr", - "Lsun/awt/motif/MWindowAttributes;" - ); - mWindowPeerIDs.iconWidth = - (*env)->GetFieldID(env, cls, "iconWidth", "I"); - mWindowPeerIDs.iconHeight = - (*env)->GetFieldID(env, cls, "iconHeight", "I"); - mWindowPeerIDs.handleWindowFocusOut = - (*env)->GetMethodID(env, - cls, - "handleWindowFocusOut", - "(Ljava/awt/Window;)V"); - mWindowPeerIDs.handleWindowFocusIn = - (*env)->GetMethodID(env, - cls, - "handleWindowFocusIn", - "()V"); - mWindowPeerIDs.handleIconify = - (*env)->GetMethodID(env, - cls, - "handleIconify", - "()V"); - mWindowPeerIDs.handleDeiconify = - (*env)->GetMethodID(env, - cls, - "handleDeiconify", - "()V"); - mWindowPeerIDs.handleStateChange = - (*env)->GetMethodID(env, - cls, - "handleStateChange", - "(II)V"); - - mWindowPeerIDs.draggedToScreenMID = (*env)->GetMethodID(env, cls, - "draggedToNewScreen", - "(I)V"); - DASSERT(mWindowPeerIDs.draggedToScreenMID); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: wrapInSequenced - * Signature: (Ljava/awt/AWTEvent;)Ljava/awt/SequencedEvent; - */ - -/* This method gets called from MWindowPeer to wrap a FocusEvent in - a SequencedEvent. We have to do this in native code, because we - don't want to make SequencedEvent a public class. */ - -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_MWindowPeer_wrapInSequenced - (JNIEnv *env, jobject this, jobject awtevent) -{ - jobject global = awt_canvas_wrapInSequenced(awtevent); - jobject local = (*env)->NewLocalRef(env, global); - (*env)->DeleteGlobalRef(env, global); - return local; -} - -extern jobject findTopLevelOpposite(); - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: findOpposite - * Signature: (Ljava/awt/AWTEvent;)Ljava/awt/Window; - */ - -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_MWindowPeer_findOpposite - (JNIEnv *env, jobject this, jint eventType) -{ -#ifdef HEADLESS - return NULL; -#else - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - return NULL; - } - - return findTopLevelOpposite(env, eventType); -#endif -} - -/* changeInsets() sets target's insets equal to X/Motif values. */ - -static void -awtJNI_ChangeInsets(JNIEnv * env, jobject this, struct FrameData *wdata) -{ - jobject insets; - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) - return; - - insets = (*env)->GetObjectField(env, this, mWindowPeerIDs.insets); - - if (JNU_IsNull(env, insets)) { - return; - } - - (*env)->SetIntField(env, insets, insetsIDs.top, wdata->top); - (*env)->SetIntField(env, insets, insetsIDs.left, wdata->left); - (*env)->SetIntField(env, insets, insetsIDs.bottom, wdata->bottom); - (*env)->SetIntField(env, insets, insetsIDs.right, wdata->right); - - /* Fix for 4106068: don't do it, rely on the window */ - /* manager maximizing policy instead */ -#if 0 - /* when the insets get set, make sure we set the proper */ - /* max window size (since it's dependent on inset size) */ - if (wdata->isResizable) { - int32_t screenWidth = XWidthOfScreen( XDefaultScreenOfDisplay(awt_display)); - int32_t screenHeight= XHeightOfScreen(XDefaultScreenOfDisplay(awt_display)); - XtVaSetValues(wdata->winData.shell, - XmNmaxWidth, screenWidth - (wdata->left + wdata->right), - XmNmaxHeight, screenHeight - (wdata->top + wdata->bottom), - NULL); - } -#endif - (*env)->DeleteLocalRef(env, insets); -} - - -/* setMbAndWwHeightAndOffsets() attempts to establish the heights - of frame's menu bar and warning window (if present in frame). - setMbAndWwHeightAndOffsets() also adjusts appropriately the - X/Motif offsets and calls changeInsets() to set target insets. - A warning window, if present, is established during ...create(). - wdata->warningWindow is set there, wdata->wwHeight is set here. - Routine pSetMenuBar() sets value of the wdata->menuBar field. - This routine reads that value. If it is not null, a menubar - has been added. In this case, calculate the current height - of the menu bar. This may be a partial (incomplete) menubar - because ths routine may be called before the X/Motif menubar - is completely realized. In this case, the menubar height may - be adjusted incrementally. This routine may be called from - ...pSetMenuBar(), innerCanvasEH(), and ...pReshape(). It is - designed to (eventually) obtain the correct menubar height. - On the other hand, if wdata->menuBar is NULL and the stored - menubar height is not zero, then we subtract off the height. */ - -static void -awtJNI_setMbAndWwHeightAndOffsets(JNIEnv * env, - jobject this, - struct FrameData *wdata ) -{ - Dimension warningHeight, /* Motif warning window height */ - labelHeight; /* Motif warning label's height */ - - WidgetList warningChildrenWL; /* warning children widgets */ - - Dimension menuBarWidth, /* Motif menubar width */ - menuBarHeight, /* Motif menubar height */ - menuBarBorderSize, /* Motif menubar border size */ - marginHeight, /* Motif menubar margin height */ - menuHeight, /* Motif menubar's menu height */ - menuBorderSize, /* Motif menu border size */ - actualHeight; /* height: menu+margins+borders */ - - WidgetList menuBarChildrenWL; /* menubar children widgets */ - Cardinal numberChildren; /* number of menubar children */ - -#ifdef _pauly_debug - fprintf(stdout," ++ setMenuBar\n"); - fflush(stdout); -#endif /* _pauly_debug */ - - /* If warning window height not yet known, try to get it now. - It will be added to top or bottom (iff NETSCAPE) offset. */ - if (wdata->warningWindow != NULL) { - XtVaGetValues(wdata->warningWindow, - XmNheight, &warningHeight, - XmNchildren, &warningChildrenWL, - XmNnumChildren, &numberChildren, - NULL); - - /* We may be doing this before warning window is realized ! So, - check for a child label in the warning. If its height is not - yet accounted for in the warning height, then use it here. */ - if (numberChildren != 0) { - XtVaGetValues(warningChildrenWL[0], - XmNheight, &labelHeight, - NULL); -#ifdef _pauly_debug - fprintf(stdout," setMenuBar.... warning label found with height: %d\n", labelHeight); - fflush(stdout); -#endif /* _pauly_debug */ - if (warningHeight < labelHeight) { -#ifdef _pauly_debug - fprintf(stdout," setMenuBar.... !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); - fflush(stdout); -#endif /* _pauly_debug */ - warningHeight = labelHeight; - } - } - - if (wdata->wwHeight < warningHeight) { -#ifdef _pauly_debug - fprintf(stdout, " setMenuBar.... adding warning height: %d\n", warningHeight); - fflush(stdout); -#endif /* _pauly_debug */ -#ifdef NETSCAPE - wdata->bottom += (warningHeight - wdata->wwHeight); -#else - wdata->top += (warningHeight - wdata->wwHeight); -#endif /* NETSCAPE */ - awtJNI_ChangeInsets(env, this, wdata); - wdata->wwHeight = warningHeight; - } - } - - /* Now we adjust offsets for an added or removed menu bar */ - if (wdata->menuBar != NULL) { -#ifdef _pauly_debug - fprintf(stdout," setMenuBar. menu bar: %x\n", wdata->menuBar); - fflush(stdout); -#endif /* _pauly_debug */ - XtVaGetValues(wdata->menuBar, - XmNwidth, &menuBarWidth, - XmNheight, &menuBarHeight, - XmNchildren, &menuBarChildrenWL, - XmNnumChildren, &numberChildren, - XmNborderWidth, &menuBarBorderSize, - XmNmarginHeight, &marginHeight, - NULL); - - /* We may be doing this before menu bar is realized ! Hence, - check for a menu in the menu bar. If its height is not yet - accounted for in the menu bar height, then add it in here. */ - if (numberChildren != 0) { - XtVaGetValues(menuBarChildrenWL[0], - XmNheight, &menuHeight, - XmNborderWidth, &menuBorderSize, - NULL); -#ifdef _pauly_debug - fprintf(stdout," setMenuBar.... menu found with height: %d, border: %d, margin: %d, bar border: %d\n", menuHeight, menuBorderSize, marginHeight, menuBarBorderSize); - fflush(stdout); -#endif /* _pauly_debug */ - /* Calculate real height of menu bar by adding height of its - child menu and borders, margins, and the menu bar borders*/ - actualHeight = menuHeight + (2 * menuBorderSize) + - (2 * marginHeight) + (2 * menuBarBorderSize); -#ifdef __linux__ -#ifdef _pauly_debug - fprintf(stdout," actual height: %d mb height %d\n", actualHeight, menuBarHeight); - fflush(stdout); -#endif /* _pauly_debug */ -#endif - if (menuBarHeight < actualHeight) { -#ifdef _pauly_debug -fprintf(stdout," setMenuBar.... ****************************************\n"); -fflush(stdout); -#endif /* _pauly_debug */ - menuBarHeight = actualHeight; - } - } - - if (wdata->mbHeight < menuBarHeight) { - /* Adjust the (partially) added menu bar height, top offset.*/ -#ifdef _pauly_debug - fprintf(stdout, " setMenuBar.... added menuBar height: %d\n", menuBarHeight); - fflush(stdout); -#endif /* _pauly_debug */ - wdata->top += (menuBarHeight - wdata->mbHeight); - awtJNI_ChangeInsets(env, this, wdata); - wdata->mbHeight = menuBarHeight; - } - } else if ((wdata->menuBar == NULL) && (wdata->mbHeight > 0)) { - /* A menu bar has been removed; subtract height from top offset.*/ - wdata->top -= wdata->mbHeight; -#ifdef _pauly_debug - fprintf(stdout, " setMenuBar.... removed menuBar height: %d\n", wdata->mbHeight); - fflush(stdout); -#endif /* _pauly_debug */ - awtJNI_ChangeInsets(env, this, wdata); - wdata->mbHeight = 0; - } -} - - -/* outerCanvasResizeCB() is Motif resize callback for outer/child canvas. - It reads width, height of Motif widget, sets java target accordingly, - and then calls handleResize() to affect any changes. - This call is only done for a shell resize or inner/parent resize; - i.e., it may not be done for a ...pReshape() to avoid doing a loop. - - client_data is MWindowPeer instance -*/ -static void -outerCanvasResizeCB(Widget wd, XtPointer client_data, XtPointer call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject target; - struct FrameData *wdata; - Position screenX; /* x position of the canvas, screen */ - Position screenY; /* y position of the canvas, screen */ - Dimension width; /* width of the canvas, target */ - Dimension height; /* height of the canvas, target */ - jint oldWidth; - jint oldHeight; - -#ifdef _pauly_debug - fprintf(stdout," ++ WindowResize.\n"); - fflush(stdout); -#endif /* _pauly_debug */ - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, (jobject) client_data, - mComponentPeerIDs.pData); - if (wdata == NULL) { - return; - } - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) - return; - - target = (*env)->GetObjectField(env, (jobject) client_data, - mComponentPeerIDs.target); - XtVaGetValues(wd, - XmNwidth, &width, - XmNheight, &height, - NULL); -#ifdef _pauly_debug - fprintf(stdout," outerCanvasResizeCB. width: %d, height: %d\n", width, height); - fflush(stdout); -#endif /* _pauly_debug */ - - - XtTranslateCoords(wd, 0, 0, &screenX, &screenY); - - if ((wdata->shellResized) || (wdata->canvasResized)) { -#ifdef _pauly_debug - fprintf(stdout," outerCanvasResizeCB\n"); - fflush(stdout); -#endif /* _pauly_debug */ - wdata->shellResized = False; - wdata->canvasResized = False; - /* - ** if you are not yet reparented, don't compute the size based on the - ** widgets, as the window manager shell containg the insets is not yet - ** there. Use the size the application has set. - ** If not reparented, we got here because the application set the size, - ** so just send them Component.RESIZED event with the size they set. - ** - ** If the reparenting causes a resize ( only when inset guess is wrong ) ** the new size will be sent in a Component.RESIZED event at that time. - */ - if (wdata->reparented) - { - (*env)->SetIntField(env, target, componentIDs.x, (jint) screenX); - (*env)->SetIntField(env, target, componentIDs.y, (jint) screenY); - } - - oldWidth = (*env)->GetIntField(env, target, componentIDs.width); - oldHeight = (*env)->GetIntField(env, target, componentIDs.height); - - if (oldWidth != width || oldHeight != height || wdata->need_reshape) - { - wdata->need_reshape = False; - (*env)->SetIntField(env, target, componentIDs.width, (jint)width); - (*env)->SetIntField(env, target, componentIDs.height, - (jint)height); - - /* only do this for Windows, not Canvases, btw */ - checkNewXineramaScreen(env, client_data, wdata, screenX, screenY, width, height); - - JNU_CallMethodByName(env, NULL, (jobject) client_data, - "handleResize", "(II)V", width, height); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - } - - (*env)->DeleteLocalRef(env, target); - -#ifdef _pauly_debug - fprintf(stdout," WindowResize. Done.\n"); - fflush(stdout); -#endif /* _pauly_debug */ - -} /* outerCanvasResizeCB() */ - -static void reconfigureOuterCanvas ( JNIEnv *env, jobject target, - jobject this, struct FrameData *wdata ) -{ - Dimension innerDAWidth, /* width of inner Motif canvas */ - innerDAHeight, /* height of inner Motif canvas */ - outerDAWidth, /* width of outer Motif canvas */ - outerDAHeight; /* height of outer Motif canvas */ - int32_t targetWidth, /* java target object's width */ - targetHeight; /* java target's object height */ - Dimension width; /* width of the canvas, target */ - Dimension height; /* height of the canvas, target */ - - - Position innerX, /* x loc. of inner Motif canvas */ - innerY, /* y loc. of inner Motif canvas */ - x, y; - - /* canvasW is (visible) inner/parent drawing area (canvas) widget */ - XtVaGetValues(XtParent(wdata->winData.comp.widget), - XmNwidth, &innerDAWidth, - XmNheight, &innerDAHeight, - XmNx, &innerX, - XmNy, &innerY, - NULL); - - /* This resize may be due to the insertion or removal of a menu bar. - If so, we appropriately adjust the top offset in wdata, insets. */ - awtJNI_setMbAndWwHeightAndOffsets(env, this, wdata); - - outerDAWidth = innerDAWidth + wdata->left + wdata->right; - outerDAHeight = innerDAHeight + wdata->top + wdata->bottom; - - /* If it's a menu bar reset, do not do resize of outer/child canvas. - (Another thread problem; we arrest this now before damage done.) */ - if (wdata->menuBarReset) - { - targetWidth = (*env)->GetIntField(env, target, componentIDs.width); - targetHeight = (*env)->GetIntField(env, target, componentIDs.height); - if ((outerDAWidth != targetWidth) || (outerDAHeight != targetHeight)) - { - return; - } - } - - wdata->canvasResized = True; - - /* The outer/child drawing area (canvas) needs to be configured too. - If its size changes, its resize callback will thereby be invoked.*/ - x = -wdata->left; - y = -wdata->top; - width = innerDAWidth + wdata->left + wdata->right; - height = innerDAHeight + wdata->top + wdata->bottom; - - XtConfigureWidget(wdata->winData.comp.widget, x, y, width, height, 0 ); -} - - - -/* innerCanvasEH() is event handler for inner/parent canvas. It handles - map and configure notify events. It reads width and height, adjusts - for menubar insertion / removal and configures outer/child canvas. */ - -static void -innerCanvasEH(Widget canvasW, XtPointer client_data, XEvent *event, - Boolean* continueToDispatch) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject) client_data; - jobject target; - struct FrameData *wdata; - - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL) { - return; - } - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) - return; - - target = (*env)->GetObjectField(env, (jobject) client_data, - mComponentPeerIDs.target); - - /* While inside ...pSetMenuBar(), don't react to incomplete resizing - events supplied by Xt toolkit. Wait for completion of the routine. */ - - - /* For a map or resize, we need to check for the addition or deletion - of a menu bar to the form which is the of this drawing area (canvas). - We also must then configure the outer/child canvas appropriately. */ - - if ( (event->xany.type == MapNotify) || - (event->xany.type == ConfigureNotify) ) - { - reconfigureOuterCanvas( env, target, this, wdata ); - } - - (*env)->DeleteLocalRef(env, target); - -} - -/* syncTopLevelPos() is necessary to insure that the window manager has in - * fact moved us to our final position relative to the reParented WM window. - * We have noted a timing window which our shell has not been moved so we - * screw up the insets thinking they are 0,0. Wait (for a limited period of - * time to let the WM hava a chance to move us - */ -void syncTopLevelPos( Display *d, Window w, XWindowAttributes *winAttr ) -{ - int32_t i = 0; - memset(winAttr, 0, sizeof(*winAttr)); - - do { - if (!XGetWindowAttributes(d, w, winAttr)) { - memset(winAttr, 0, sizeof(*winAttr)); - break; - } - /* Sometimes we get here before the WM has updated the - ** window data struct with the correct position. Loop - ** until we get a non-zero position. - */ - if ((winAttr->x != 0) || (winAttr->y != 0)) { - break; - } - else { - /* What we really want here is to sync with the WM, - ** but there's no explicit way to do this, so we - ** call XSync for a delay. - */ - XSync(d, False); - } - } while (i++ < 50); -} - -typedef struct FocusOutInfo_str { - XEvent * eventOut; - Window inWin; - Window inChild; - Widget defChild; - jobject childComp; -} FocusOutInfo_t; - -#define IsCanvasTypeWidget(w) \ - (XtIsSubclass(w, xmDrawingAreaWidgetClass) ||\ - XtIsSubclass(w, vDrawingAreaClass)) - -int isTopLevelPartWidget(Widget w) { - if (XtIsShell(w)) { - return TRUE; - } - if (XtIsSubclass(w, xmFormWidgetClass)) { - return TRUE; - } - if (IsCanvasTypeWidget(w)) { - Widget w1 = XtParent(w); - if (w1 != NULL) { - if (XtIsSubclass(w1, xmFormWidgetClass)) { - return TRUE; - } - if (IsCanvasTypeWidget(w1)) { - Widget w2 = XtParent(w1); - if (w2 != NULL) { - if (XtIsSubclass(w2, xmFormWidgetClass)) { - return TRUE; - } - } - } - - } - } - return FALSE; -} - -void -shellFocusEH(Widget w, XtPointer data, XEvent *event, Boolean *continueToDispatch) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject) data; - jobject target; - struct FrameData *wdata; - - /* Any event handlers which take peer instance pointers as - * client_data should check to ensure the widget has not been - * marked as destroyed as a result of a dispose() call on the peer - * (which can result in the peer instance pointer already haven - * been gc'd by the time this event is processed) - */ - if (w->core.being_destroyed) { - return; - } - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL) { - return; - } - - switch (event->xany.type) { - case FocusOut: - // Will be handled by proxy automaticall since he is focus owner - break; - case FocusIn: - // Forward focus event to the proxy - XSetInputFocus(awt_display, XtWindow(wdata->focusProxy), RevertToParent, CurrentTime); - break; - } -} - -/** - * Fix for Alt-Tab problem. - * See coments on use semantics below. - */ -Boolean skipNextNotifyWhileGrabbed = False; -Boolean skipNextFocusIn = False; - -Boolean focusOnMapNotify = False; - -/* shellEH() is event handler for the Motif shell widget. It handles - focus change, map notify, configure notify events for the shell. - Please see internal comments pertaining to these specific events. - - data is MWindowPeer instance pointer -*/ -void -shellEH(Widget w, XtPointer data, XEvent *event, Boolean *continueToDispatch) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject) data; - jobject target; - struct FrameData *wdata; - int32_t setTargetX, - setTargetY, - getTargetX, - getTargetY; - /* Changed long to int for 64-bit */ - int32_t wwHeight; /* height of any warning window present */ - int32_t topAdjust; /* adjust top offset for menu, warning */ - jclass clazz; - int32_t x, y; - int32_t width, height; - enum wmgr_t runningWM; - jobject winAttrObj; - static jobject windowClass = NULL; - /* Any event handlers which take peer instance pointers as - * client_data should check to ensure the widget has not been - * marked as destroyed as a result of a dispose() call on the peer - * (which can result in the peer instance pointer already haven - * been gc'd by the time this event is processed) - */ - if (w->core.being_destroyed) { - return; - } - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL) { - return; - } - - switch (event->xany.type) { - - case FocusOut: { - int32_t res = 0; - int revert_to = 0; - Widget defChild = NULL; - Window focusOwner = None; - jobject oppositeWindow = NULL; - Widget oppositeShell = NULL; - XEvent inEvent; - Widget shell = NULL; -#ifdef DEBUG_FOCUS - fprintf(stderr, "Focusout on proxy; window = %x, mode %d, detail %d\n", - event->xfocus.window, event->xfocus.mode, event->xfocus.detail); -#endif - shell = wdata->winData.shell; - - if ((*env)->EnsureLocalCapacity(env, 3) < 0) { - break; - } - - /** - * Fix for Alt-Tab problem. We should process NotifyWhileGrabbed events - * only if they are due to the switch between top-levels. - * skipNextNotifyWhileGrabbed is set from Menu and PopupMenu code - * to prevent generation of focus events when user interact with these - * widget. - */ - if (event->xfocus.mode == NotifyWhileGrabbed) { - if (skipNextNotifyWhileGrabbed) { - skipNextNotifyWhileGrabbed = False; - break; - } - } else if (event->xfocus.mode != NotifyNormal) break; - - /** - * Fix for Alt-Tab problem. - * skipNextFocusIn is set in Choice code to avoid processing of - * next focus-in or focus-out generated by Choice as it is a fake - * event. - */ - if (skipNextFocusIn && event->xfocus.detail == NotifyPointer) { - break; - } - - XGetInputFocus( awt_display, &focusOwner, &revert_to); - - if (focusOwner != None) { - Widget inWidget = NULL; - jobject wpeer = NULL; - inWidget = XtWindowToWidget(awt_display, focusOwner); - if (inWidget != NULL && inWidget != shell) { - oppositeShell = getShellWidget(inWidget); - wpeer = findPeer(&inWidget); - if (wpeer == NULL) { - inWidget = findTopLevelByShell(inWidget); - if (inWidget != NULL) { - wpeer = findPeer(&inWidget); - } - } - if (wpeer != NULL) { - jobject peerComp = - (*env)->GetObjectField(env, - wpeer, - mComponentPeerIDs.target); - if (peerComp != NULL) { - // Check that peerComp is top-level - - // load class - if (windowClass == NULL) { - jobject localWindowClass = (*env)->FindClass(env, "java/awt/Window"); - windowClass = (*env)->NewGlobalRef(env, localWindowClass); - (*env)->DeleteLocalRef(env, localWindowClass); - } - if ((*env)->IsInstanceOf(env, peerComp, windowClass)) { - oppositeWindow = peerComp; - } else { // Opposite object is not Window - there is no opposite window. - (*env)->DeleteLocalRef(env, peerComp); - peerComp = NULL; - oppositeShell = NULL; - } - } - } - } - } else { - // If there is no opposite shell but we have active popup - this popup is actually - // the oppposite. This should mean that this focus out is due to popup - and thus - // should be skipped. Fix for 4478780. - if (skipNextNotifyWhileGrabbed) { - break; - } - } - - // If current window is not focusable and opposite window is not focusable - do nothing - // If current window is focusable and opposite is not - do not clear focus variables like - // focus didn't leave this window(but it will in terms of X). When we later switch to either - // - back to this window: variables are already here - // - another focusable window: variables point to focusable window and "focus lost" events - // will be generated for it - // - non-java window: variables point to focusable window and "focus lost" events - // will be generated for it, not for non-focusable. - // If current window is non-focusable and opposite is focusable then do not generate anything - // as if we didn't leave previous focusable window so Java events will generated for it. - // - // Fix for 6547951. - // Also do cleaning when switching to non-java window (opposite is null). - if (isFocusableWindowByShell(env, shell) && shell != oppositeShell && - ((oppositeShell != NULL && isFocusableWindowByShell(env, oppositeShell)) || - oppositeShell == NULL)) - { - // The necessary FOCUS_LOST event will be generated by DKFM. - // So we need to process focus list like we received FocusOut - // for the desired component - shell's current focus widget - defChild = XmGetFocusWidget(shell); - if (defChild != NULL) { - jobject peer = findPeer(&defChild); - if (peer == NULL) { - defChild = findTopLevelByShell(defChild); - if (defChild != NULL) { - peer = findPeer(&defChild); - } - } - if (peer != NULL) { - jobject comp = (*env)->GetObjectField(env, peer, mComponentPeerIDs.target); - if (focusList != NULL) { - jobject last = (*env)->NewLocalRef(env, focusList->requestor); - if ((*env)->IsSameObject(env, comp, last)) { - FocusListElt * temp = focusList; - forGained = focusList->requestor; - focusList = focusList->next; - free(temp); - if (focusList == NULL) { - focusListEnd = NULL; - } - } - if (!JNU_IsNull(env, last)) { - (*env)->DeleteLocalRef(env, last); - } - } - (*env)->DeleteLocalRef(env, comp); - } - } - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - processTree(defChild, findWindowsProxy(target, env), False); - XtSetKeyboardFocus(shell, NULL); - (*env)->DeleteLocalRef(env, target); - } -#ifndef NOMODALFIX - if (!awt_isModal() || awt_isWidgetModal(shell)) { -#endif //NOMODALFIX - if ( oppositeShell != NULL - && isFocusableWindowByShell(env, oppositeShell) - && isFocusableWindowByShell(env, shell) - || (oppositeShell == NULL)) - { - /* - * Fix for 5095117. - * Check if current native focused window is the same as source. - * Sometimes it is not - we must not however clean reference to - * actual native focused window. - */ - jobject currentFocusedWindow = awt_canvas_getFocusedWindowPeer(); - if ((*env)->IsSameObject(env, this, currentFocusedWindow)) { - awt_canvas_setFocusedWindowPeer(NULL); - } - (*env)->DeleteLocalRef(env, currentFocusedWindow); - - JNU_CallMethodByName(env, NULL, this, "handleWindowFocusOut", "(Ljava/awt/Window;)V", - oppositeWindow); - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } -#ifndef NOMODALFIX - } -#endif //NOMODALFIX - if (oppositeWindow != NULL) { - (*env)->DeleteLocalRef(env, oppositeWindow); - } - - break; - } /* FocusOut */ - - case FocusIn: { - Widget shell = wdata->winData.shell; -#ifdef DEBUG_FOCUS - fprintf(stderr, "FocusIn on proxy; window = %x, mode %d, detail %d\n", event->xfocus.window, - event->xfocus.mode, event->xfocus.detail); -#endif - if (/* event->xfocus.mode == NotifyNormal */ 1) { - - /** - * Fix for Alt-Tab problem. We should process NotifyWhileGrabbed events to detect - * switch between top-levels using alt-tab, but avoid processing these type of event - * when they are originated from other sources. - */ - if (event->xfocus.mode == NotifyWhileGrabbed) { - /** - * skipNextNotifyWhileGrabbed is set from Menu and PopupMenu code to - * skip next focus-in event with NotifyWhileGrabbed as it is generated - * in result of closing of the Menu's shell. - * Event will also have NotifyInferior if uses clicked on menu bar in the - * space where there is not menu items. - */ - if (skipNextNotifyWhileGrabbed || event->xfocus.detail == NotifyInferior) { - skipNextNotifyWhileGrabbed = False; - break; - } - } else if (event->xfocus.mode != NotifyNormal) { - break; - } - - /** - * Fix for Alt-Tab problem. - * skipNextFocusIn is set from Choice code to avoid processing next focus-in - * as it is a fake event. - */ - if (skipNextFocusIn == True) { - /** - * There could be the set of fake events, the last one - * will have detail == NotifyPointer - */ - if (event->xfocus.detail != NotifyPointer) { - skipNextFocusIn = False; - } - break; - } -#ifndef NOMODALFIX - if (!awt_isModal() || awt_isWidgetModal(shell)) { -#endif //NOMODALFIX - if (isFocusableWindowByShell(env, shell)) { - jobject currentFocusedWindow = awt_canvas_getFocusedWindowPeer(); - // Check if focus variables already point to this window. If so, - // it means there were transfer to non-focusable window and now we - // are back to origianl focusable window. No need to generate Java events - // in this case. - if (!(*env)->IsSameObject(env, this, currentFocusedWindow)) { - awt_canvas_setFocusedWindowPeer(this); - awt_canvas_setFocusOwnerPeer(this); - - /* - * Fix for 6465038. - * Restore focus on the toplevel widget if it's broken. - */ - Widget widgetToFocus = getFocusWidget(findTopLevelByShell(shell)); - Widget currentOwner = XmGetFocusWidget(shell); - - if (widgetToFocus != currentOwner) { -#ifdef DEBUG_FOCUS - fprintf(stderr, "Wrong Xm focus; resetting Xm focus from %x to toplevel %x...\n", - currentOwner != NULL ? XtWindow(currentOwner) : 0, - widgetToFocus != NULL ? XtWindow(widgetToFocus) : 0); -#endif - if ( !XmProcessTraversal(widgetToFocus, XmTRAVERSE_CURRENT) ) { - XtSetKeyboardFocus(shell, widgetToFocus); - } -#ifdef DEBUG_FOCUS - Widget _w = XmGetFocusWidget(shell); - fprintf(stderr, " ...focus resulted on window %x\n", _w != NULL ? XtWindow(_w) : 0); -#endif - } - - JNU_CallMethodByName(env, NULL, this, "handleWindowFocusIn", "()V"); - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - (*env)->DeleteLocalRef(env, currentFocusedWindow); - } -#ifndef NOMODALFIX - } -#endif //NOMODALFIX - } - raiseInputMethodWindow(wdata); - break; - } /* FocusIn */ - - case VisibilityNotify: { - winAttrObj = (*env)->GetObjectField(env, this, mWindowPeerIDs.winAttr); - (*env)->SetIntField(env, winAttrObj, - mWindowAttributeIDs.visibilityState, - event->xvisibility.state); - if (event->xvisibility.state == VisibilityUnobscured) { - raiseInputMethodWindow(wdata); - } - break; - } /* VisibilityNotify */ - - case MapNotify: { - /* Your body seems to unfade */ - if (wdata->initialFocus == False) { - XtVaSetValues(wdata->winData.shell, XmNinput, True, NULL); - - // We have to to evidently move the window to the front here. - Window shellWindow; - if ((shellWindow = XtWindow(wdata->winData.shell)) != None) { - XRaiseWindow(awt_display, shellWindow); - } - } - if (awt_wm_isStateNetHidden(XtWindow(wdata->winData.shell))) { - focusOnMapNotify = True; - } - /* - * TODO: perhaps we need this putback only for simple Window. - * For Frame/Dialog XmNinput==True would be enough. The native - * system will focus it itself. - */ - if (wdata->isFocusableWindow && focusOnMapNotify) { - XEvent ev; - memset(&ev, 0, sizeof(ev)); - - ev.type = FocusIn; - ev.xany.send_event = True; - ev.xany.display = awt_display; - ev.xfocus.mode = NotifyNormal; - ev.xfocus.detail = NotifyNonlinear; - ev.xfocus.window = XtWindow(wdata->winData.shell); - awt_put_back_event(env, &ev); - } - focusOnMapNotify = False; - - break; - } - - case UnmapNotify: { - /* Gee! All of a sudden, you can't see yourself */ - if (wdata->initialFocus == False) { - XtVaSetValues(wdata->winData.shell, XmNinput, False, NULL); - } - if (awt_wm_isStateNetHidden(XtWindow(wdata->winData.shell))) { - focusOnMapNotify = True; - } - break; - } - - case DestroyNotify: { /* Foul play! ICCCM forbids WM to do this! */ - /* Your window is killed by the WM */ - JNU_CallMethodByName(env, NULL, this, "handleDestroy", "()V"); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - break; - } - - case PropertyNotify: { - jint state, old_state, changed; - - /* - * Let's see if this is a window state protocol message, and - * if it is - decode a new state in terms of java constants. - */ - if (!awt_wm_isStateChange(wdata, (XPropertyEvent *)event, &state)) { - /* Pakka Pakka seems not interested */ - break; - } - - changed = wdata->state ^ state; - if (changed == 0) { - /* You feel dizzy for a moment, but nothing happens... */ - DTRACE_PRINTLN("TL: >>> state unchanged"); - break; - } - - old_state = wdata->state; - wdata->state = state; - -#ifdef DEBUG - DTRACE_PRINT("TL: >>> State Changed:"); - if (changed & java_awt_Frame_ICONIFIED) { - if (state & java_awt_Frame_ICONIFIED) { - DTRACE_PRINT(" ICON"); - } else { - DTRACE_PRINT(" !icon"); - } - } - if (changed & java_awt_Frame_MAXIMIZED_VERT) { - if (state & java_awt_Frame_MAXIMIZED_VERT) { - DTRACE_PRINT(" MAX_VERT"); - } else { - DTRACE_PRINT(" !max_vert"); - } - } - if (changed & java_awt_Frame_MAXIMIZED_HORIZ) { - if (state & java_awt_Frame_MAXIMIZED_HORIZ) { - DTRACE_PRINT(" MAX_HORIZ"); - } else { - DTRACE_PRINT(" !max_horiz"); - } - } - DTRACE_PRINTLN(""); -#endif - - if (changed & java_awt_Frame_ICONIFIED) { - /* Generate window de/iconified event for old clients */ - if (state & java_awt_Frame_ICONIFIED) { - DTRACE_PRINTLN("TL: ... handleIconify"); - JNU_CallMethodByName(env, NULL, - this, "handleIconify", "()V"); - } - else { - DTRACE_PRINTLN("TL: ... handleDeiconify"); - JNU_CallMethodByName(env, NULL, - this, "handleDeiconify", "()V"); - } - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - - DTRACE_PRINTLN("TL: ... handleStateChange"); - JNU_CallMethodByName(env, NULL, - this, "handleStateChange", "(II)V", - old_state, state); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - break; - } /* PropertyNotify */ - - case ReparentNotify: { - Window root = RootWindowOfScreen(XtScreen(wdata->winData.shell)); - -#ifdef DEBUG - DTRACE_PRINT2("TL: ReparentNotify(0x%x/0x%x) to ", - wdata->winData.shell, XtWindow(wdata->winData.shell)); - if (event->xreparent.parent == root) { - DTRACE_PRINTLN("root"); - } else { - DTRACE_PRINTLN1("window 0x%x", event->xreparent.parent); - } -#endif - - if (wdata->winData.flags & W_IS_EMBEDDED) { - DTRACE_PRINTLN("TL: embedded frame - nothing to do"); - break; - } - -#ifdef __linux__ - if (!wdata->fixInsets) { - DTRACE_PRINTLN("TL: insets already fixed"); - break; - } - else { - wdata->fixInsets = False; - } -#endif - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) - break; - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - x = (*env)->GetIntField(env, target, componentIDs.x); - y = (*env)->GetIntField(env, target, componentIDs.y); - width = (*env)->GetIntField(env, target, componentIDs.width); - height = (*env)->GetIntField(env, target, componentIDs.height); - - /* The insets were literally hardcoded in the MWindowPeer. - But they are dependent upon both the window manager (WM) - and the hardware display. So, these are usually wrong. - This leads to problems with shell positioning and size. - Furthermore, there is not a published interface or way - to obtain from any given window manager the dimensions - of its decoration windows (i.e., borders and title bar). - So, given this problem in design, we must workaround. - N.B. (0) This works. But there is one functional caveat: - the frame.insets() function will usually return - the wrong values until AFTER the frame is shown. - It always did this before; it's just that now, - the values will become correct after rendering, - whereas before the values were never corrected. - (I believe this unavoidable given this design.) - (1) Note that we must/have to do this exactly once. - (2) The hardcoded values of ...create() (25,5) - are also utilized here and must be consistent. - This of course could be reworked as desired. - (3) Assume top border (title bar) is one width, - and other three borders are another width. - This, however, could be easily reworked below. */ - - /* - * The above comment is no longer completely true. - * The insets are no longer hardcoded but are retrieved from - * guessInsets(), either from a per-window manager default, - * set in the awt.properties file, or overwritten by the - * actual values determined from a previous frames - * reparenting. - */ - - if (wdata->decor == AWT_NO_DECOR) { - if (!wdata->isResizable && !wdata->isFixedSizeSet) { - reshape(env, this, wdata, x, y, width, height, False); - if (wdata->warningWindow != NULL) - awtJNI_ChangeInsets(env, this, wdata); - } - } - else if (event->xreparent.parent == root) { - wdata->reparented = False; - wdata->configure_seen = False; - - /* - * We can be repareted to root for two reasons: - * . setVisible(false) - * . WM exited - */ - if (wdata->isShowing) { /* WM exited */ - /* Work around 4775545 */ - awt_wm_unshadeKludge(wdata); - } - } - else { /* reparented to WM frame, figure out our insets */ - XWindowAttributes winAttr, actualAttr; - int32_t correctWMTop = -1; - int32_t correctWMLeft = -1; - int32_t correctWMBottom; - int32_t correctWMRight; - int32_t topCorrection; - int32_t leftCorrection; - int32_t bottomCorrection = 0; - int32_t rightCorrection = 0; - int32_t screenX, screenY; - int32_t i; - int32_t actualWidth, actualHeight; - int32_t t, l, b, r; - Window containerWindow; - - /* Dummies for XQueryTree */ - Window ignore_Window, *ignore_WindowPtr; - uint32_t ignore_uint; - - Boolean setXY = True; - XSizeHints* hints = XAllocSizeHints(); - - wdata->reparented = True; - - if (hints != NULL) { - long ignore = 0; - XGetWMNormalHints(awt_display, XtWindow(wdata->winData.shell), - hints, &ignore); - setXY = (hints->flags & (USPosition|PPosition)) != 0; - XFree(hints); - } - - /* - * Unfortunately the concept of "insets" borrowed to AWT - * from Win32 is *absolutely*, *unbelievably* foreign to - * X11. Few WMs provide the size of frame decor - * (i.e. insets) in a property they set on the client - * window, so we check if we can get away with just - * peeking at it. [Future versions of wm-spec might add a - * standardized hint for this]. - * - * Otherwise we do some special casing. Actually the - * fallback code ("default" case) seems to cover most of - * the existing WMs (modulo Reparent/Configure order - * perhaps?). - * - * Fallback code tries to account for the two most common cases: - * - * . single reparenting - * parent window is the WM frame - * [twm, olwm, sawfish] - * - * . double reparenting - * parent is a lining exactly the size of the client - * grandpa is the WM frame - * [mwm, e!, kwin, fvwm2 ... ] - */ - - if (awt_wm_getInsetsFromProp(event->xreparent.window, - &t, &l, &b, &r)) - { - correctWMTop = t; - correctWMLeft = l; - correctWMBottom = b; - correctWMRight = r; - setXY = False; - } - else - switch (awt_wm_getRunningWM()) { - - /* should've been done in awt_wm_getInsetsFromProp */ - case ENLIGHTEN_WM: { - DTRACE_PRINTLN("TL: hmm, E! insets should have been read" - " from _E_FRAME_SIZE"); - /* enlightenment does double reparenting */ - syncTopLevelPos(XtDisplay(wdata->winData.shell), - event->xreparent.parent, &winAttr); - - XQueryTree(XtDisplay(wdata->winData.shell), - event->xreparent.parent, - &ignore_Window, - &containerWindow, /* actual WM frame */ - &ignore_WindowPtr, - &ignore_uint); - if (ignore_WindowPtr) - XFree(ignore_WindowPtr); - - correctWMLeft = winAttr.x; - correctWMTop = winAttr.y; - - /* - * Now get the actual dimensions of the parent window - * resolve the difference. We can't rely on the left - * to be equal to right or bottom... Enlightment - * breaks that assumption. - */ - XGetWindowAttributes(XtDisplay(wdata->winData.shell), - containerWindow, &actualAttr); - correctWMRight = actualAttr.width - - (winAttr.width + correctWMLeft); - correctWMBottom = actualAttr.height - - (winAttr.height + correctWMTop) ; - break; - } - - case ICE_WM: - case KDE2_WM: /* should've been done in awt_wm_getInsetsFromProp */ - case CDE_WM: - case MOTIF_WM: { - /* these are double reparenting too */ - syncTopLevelPos(XtDisplay(wdata->winData.shell), - event->xreparent.parent, &winAttr); - - correctWMTop = winAttr.y; - correctWMLeft = winAttr.x; - correctWMRight = correctWMLeft; - correctWMBottom = correctWMLeft; - - XTranslateCoordinates(awt_display, event->xreparent.window, - root, 0,0, &screenX, &screenY, - &containerWindow); - - if ((screenX != x + wdata->leftGuess) - || (screenY != y + wdata->topGuess)) - { - /* - * looks like the window manager has placed us somewhere - * other than where we asked for, lets respect the window - * and go where he put us, not where we tried to put us - */ - x = screenX - correctWMLeft; - y = screenY - correctWMTop; - } - break; - } - - case SAWFISH_WM: - case OPENLOOK_WM: { - /* single reparenting */ - syncTopLevelPos(XtDisplay(wdata->winData.shell), - event->xreparent.window, &winAttr); - - correctWMTop = winAttr.y; - correctWMLeft = winAttr.x; - correctWMRight = correctWMLeft; - correctWMBottom = correctWMLeft; - break; - } - - case OTHER_WM: - default: { /* this is very similar to the E! case above */ - Display *dpy = event->xreparent.display; - Window w = event->xreparent.window; - Window parent = event->xreparent.parent; - XWindowAttributes wattr, pattr; - - XGetWindowAttributes(dpy, w, &wattr); - XGetWindowAttributes(dpy, parent, &pattr); - - DTRACE_PRINTLN5("TL: window attr +%d+%d+%dx%d (%d)", - wattr.x, wattr.y, wattr.width, wattr.height, - wattr.border_width); - DTRACE_PRINTLN5("TL: parent attr +%d+%d+%dx%d (%d)", - pattr.x, pattr.y, pattr.width, pattr.height, - pattr.border_width); - - /* - * Check for double-reparenting WM. - * - * If the parent is exactly the same size as the - * top-level assume taht it's the "lining" window and - * that the grandparent is the actual frame (NB: we - * have already handled undecorated windows). - * - * XXX: what about timing issues that syncTopLevelPos - * is supposed to work around? - */ - if (wattr.x == 0 && wattr.y == 0 - && wattr.width + 2*wattr.border_width == pattr.width - && wattr.height + 2*wattr.border_width == pattr.height) - { - Window ignore_root, grandparent, *children; - unsigned int ignore_nchildren; - - DTRACE_PRINTLN("TL: double reparenting WM detected"); - XQueryTree(dpy, parent, - &ignore_root, - &grandparent, - &children, - &ignore_nchildren); - if (children) - XFree(children); - - /* take lining window into account */ - wattr.x = pattr.x; - wattr.y = pattr.y; - wattr.border_width += pattr.border_width; - - parent = grandparent; - XGetWindowAttributes(dpy, parent, &pattr); - DTRACE_PRINTLN5("TL: window attr +%d+%d+%dx%d (%d)", - wattr.x, wattr.y, - wattr.width, wattr.height, - wattr.border_width); - DTRACE_PRINTLN5("TL: parent attr +%d+%d+%dx%d (%d)", - pattr.x, pattr.y, - pattr.width, pattr.height, - pattr.border_width); - } - - /* - * XXX: To be absolutely correct, we'd need to take - * parent's border-width into account too, but the - * rest of the code is happily unaware about border - * widths and inner/outer distinction, so for the time - * being, just ignore it. - */ - correctWMTop = wattr.y + wattr.border_width; - correctWMLeft = wattr.x + wattr.border_width; - correctWMBottom = pattr.height - - (wattr.y + wattr.height + 2*wattr.border_width); - correctWMRight = pattr.width - - (wattr.x + wattr.width + 2*wattr.border_width); - DTRACE_PRINTLN4("TL: insets = top %d, left %d, bottom %d, right %d", - correctWMTop, correctWMLeft, - correctWMBottom, correctWMRight); - break; - } /* default */ - - } /* switch (runningWM) */ - - - /* - * Ok, now see if we need adjust window size because - * initial insets were wrong (most likely they were). - */ - topCorrection = correctWMTop - wdata->topGuess; - leftCorrection = correctWMLeft - wdata->leftGuess; - bottomCorrection = correctWMBottom - wdata->bottomGuess; - rightCorrection = correctWMRight - wdata->rightGuess; - - DTRACE_PRINTLN3("TL: top: computed=%d, guess=%d, correction=%d", - correctWMTop, wdata->topGuess, topCorrection); - DTRACE_PRINTLN3("TL: left: computed=%d, guess=%d, correction=%d", - correctWMLeft, wdata->leftGuess, leftCorrection); - DTRACE_PRINTLN3("TL: bottom: computed=%d, guess=%d, correction=%d", - correctWMBottom, wdata->bottomGuess, bottomCorrection); - DTRACE_PRINTLN3("TL: right: computed=%d, guess=%d, correction=%d", - correctWMRight, wdata->rightGuess, rightCorrection); - - if (topCorrection != 0 || leftCorrection != 0 - || bottomCorrection != 0 || rightCorrection != 0) - { - jboolean isPacked; - - DTRACE_PRINTLN("TL: insets need correction"); - wdata->need_reshape = True; - - globalTopGuess = correctWMTop; - globalLeftGuess = correctWMLeft; - globalBottomGuess = correctWMBottom; - globalRightGuess = correctWMRight; - - /* guesses are for WM decor *only* */ - wdata->topGuess = correctWMTop; - wdata->leftGuess = correctWMLeft; - wdata->bottomGuess = correctWMBottom; - wdata->rightGuess = correctWMRight; - - /* - * Actual insets account for menubar/warning label, - * so we can't assign directly but must adjust them. - */ - wdata->top += topCorrection; - wdata->left += leftCorrection; - wdata->bottom += bottomCorrection; - wdata->right += rightCorrection; - - awtJNI_ChangeInsets(env, this, wdata); - - /* - * If this window has been sized by a pack() we need - * to keep the interior geometry intact. Since pack() - * computed width and height with wrong insets, we - * must adjust the target dimensions appropriately. - */ - isPacked = (*env)->GetBooleanField(env, target, - componentIDs.isPacked); - if (isPacked) { - int32_t correctTargetW; - int32_t correctTargetH; - - DTRACE_PRINTLN("TL: window is packed, " - "adjusting size to preserve layout"); - - correctTargetW = width + (leftCorrection + rightCorrection); - correctTargetH = height +(topCorrection + bottomCorrection); - - (*env)->SetIntField(env, target, componentIDs.width, - (jint) correctTargetW); - (*env)->SetIntField(env, target, componentIDs.height, - (jint) correctTargetH); - /* - ** Normally you only reconfigure the outerCanvas due to - ** handling the ReconfigureNotify on the innerCanvas. - ** However, in this case the innerCanvas may not have - ** changed, but outterCanvas may still need to, since the - ** insets have changed. - */ - reshape(env, this, wdata, x, y, - correctTargetW, correctTargetH, setXY); - reconfigureOuterCanvas(env, target, this, wdata); - } else { - reshape(env, this, wdata, x, y, width, height, setXY); - JNU_CallMethodByName(env, NULL, this, - "handleResize", "(II)V", width, height); - } - } -/* NEW for dialog */ /* XXX: what this comment is supposed to mean? */ - else { - wdata->need_reshape = False; - /* fix for 4976337 - son@sparc.spb.su */ - /* we should find better fix later if needed */ - if (wdata->isResizable || !wdata->isFixedSizeSet) { - reshape(env, this, wdata, x, y, width, height, setXY); - } - } - } - (*env)->DeleteLocalRef(env, target); - break; - } /* ReparentNotify */ - - case ConfigureNotify: { - DTRACE_PRINTLN2("TL: ConfigureNotify(0x%x/0x%x)", - wdata->winData.shell, XtWindow(wdata->winData.shell)); - - /* - * Some window managers configure before we are reparented and - * the send event flag is set! ugh... (Enlighetenment for one, - * possibly MWM as well). If we haven't been reparented yet - * this is just the WM shuffling us into position. Ignore - * it!!!! or we wind up in a bogus location. - */ - runningWM = awt_wm_getRunningWM(); - if (!wdata->reparented && wdata->isShowing && - runningWM != NO_WM && wdata->decor != AWT_NO_DECOR) { - break; - } - - /* - * Notice that we have seen a ConfigureNotify after being - * reparented. We should really check for it being a - * synthetic event, but metacity doesn't send one. - */ - if (wdata->reparented) - wdata->configure_seen = 1; - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - break; - } - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - /* - * We can detect the difference between a move and a resize by - * checking the send_event flag on the event; if it's true, - * then it's indeed a move, if it's false, then this is a - * resize and we do not want to process it as a "move" (for - * resizes the x,y values are misleadingly set to 0,0 and so - * just checking for an x,y delta won't work). - */ - - getTargetX = (*env)->GetIntField(env, target, componentIDs.x); - getTargetY = (*env)->GetIntField(env, target, componentIDs.y); - - DTRACE_PRINTLN2("TL: target thinks (%d, %d)", - getTargetX, getTargetY); - DTRACE_PRINTLN3("TL: event is (%d, %d)%s", - event->xconfigure.x, event->xconfigure.y, - (event->xconfigure.send_event ? " synthetic" : "")); - - /* - * N.B. The wdata top offset is the offset from the outside of - * the entire (bordered window) to the inner/parent drawing - * area (canvas), NOT to the shell. Thus, if a menubar is - * present and/or a warning window at the top (not NETSCAPE), - * the top offset will also include space for these. In order - * to position the abstract java window relative to the shell, - * we must add back in the appropriate space for these when we - * subtract off the wdata top field. - */ -#ifdef NETSCAPE - wwHeight = 0; -#else /* NETSCAPE */ - if (wdata->warningWindow != NULL) - wwHeight = wdata->wwHeight; - else - wwHeight = 0; -#endif /* NETSCAPE */ - topAdjust = wdata->mbHeight + wwHeight; - - /* - * Coordinates in Component.setLocation() are treated as the - * upper-left corner of the outer shell. The x and y in the - * ConfigureNotify event, however, are the upper-left corner - * of the inset CLIENT window. Therefore, the coordinates - * from the event are massaged using the inset values in order - * to determine if the top-level shell has moved. In the - * event of a user- generated move event (i.e. dragging the - * window itself), these coordinates are written back into the - * Window object. - * - * Neat X/CDE/Native bug: - * If an attempt is made to move the shell in the y direction - * by an amount equal to the top inset, the Window isn't - * moved. This can be seen here by examining event->xconfigure.y - * before and after such a request is made: the value remains - * unchanged. This wrecks a little havoc here, as the x and y - * in the Component have already been set to the new location - * (in Component.reshape()), but the Window doesn't end up in - * the new location. What's more, if a second request is - * made, the window will be relocated by TWICE the requested - * amount, sort of "catching up" it would seem. - * - * For a test case of this, see bug 4234645. - */ - setTargetX = event->xconfigure.x - wdata->left; - setTargetY = event->xconfigure.y - wdata->top + topAdjust; - - width = (*env)->GetIntField(env, target, componentIDs.width); - height = (*env)->GetIntField(env, target, componentIDs.height); - checkNewXineramaScreen(env, this, wdata, setTargetX, setTargetY, - width, height); - - if ((getTargetX != setTargetX || getTargetY != setTargetY) - && (event->xconfigure.send_event || runningWM == NO_WM)) - { - (*env)->SetIntField(env, target, componentIDs.x, (jint)setTargetX); - (*env)->SetIntField(env, target, componentIDs.y, (jint)setTargetY); -#ifdef _pauly_debug - fprintf(stdout, " ++ shell move. Xevent x,y: %d, %d.\n", - event->xconfigure.x, event->xconfigure.y); - fprintf(stdout, " shell move. left: %d, top: %d, but offset: %d\n", wdata->left, wdata->top, topAdjust); - fprintf(stdout," shell move. target x: %d, target y: %d\n", setTargetX, setTargetY); - fprintf(stdout," shell move. ww height: %d\n", wwHeight); - fflush(stdout); -#endif /* _pauly_debug */ - - DTRACE_PRINTLN2("TL: handleMoved(%d, %d)", - setTargetX, setTargetY); - JNU_CallMethodByName(env, NULL, - this, "handleMoved", "(II)V", - setTargetX, setTargetY); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - else if (event->xconfigure.send_event == False) { -#ifdef _pauly_debug - fprintf(stdout, - " ++ shell resize. Xevent x,y,w,h: %d, %d, %d, %d.\n", - event->xconfigure.x, event->xconfigure.y, - event->xconfigure.width, event->xconfigure.height); - fflush(stdout); -#endif /* _pauly_debug */ - - wdata->shellResized = True; - } - - - (*env)->DeleteLocalRef(env, target); - raiseInputMethodWindow(wdata); -#ifdef __linux__ - adjustStatusWindow(wdata->winData.shell); -#endif - break; - } /* ConfigureNotify */ - - default: - break; - } -} - - -static void -Frame_quit(Widget w, - XtPointer client_data, - XtPointer call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - JNU_CallMethodByName(env, NULL, (jobject) client_data, "handleQuit", "()V"); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - - -static void -setDeleteCallback(jobject this, struct FrameData *wdata) -{ - Atom xa_WM_DELETE_WINDOW; - Atom xa_WM_TAKE_FOCUS; - Atom xa_WM_PROTOCOLS; - - XtVaSetValues(wdata->winData.shell, - XmNdeleteResponse, XmDO_NOTHING, - NULL); - xa_WM_DELETE_WINDOW = XmInternAtom(XtDisplay(wdata->winData.shell), - "WM_DELETE_WINDOW", False); - xa_WM_TAKE_FOCUS = XmInternAtom(XtDisplay(wdata->winData.shell), - "WM_TAKE_FOCUS", False); - xa_WM_PROTOCOLS = XmInternAtom(XtDisplay(wdata->winData.shell), - "WM_PROTOCOLS", False); - - XmAddProtocolCallback(wdata->winData.shell, - xa_WM_PROTOCOLS, - xa_WM_DELETE_WINDOW, - Frame_quit, (XtPointer) this); -} - - -extern AwtGraphicsConfigDataPtr -copyGraphicsConfigToPeer(JNIEnv *env, jobject this); - -extern AwtGraphicsConfigDataPtr -getGraphicsConfigFromComponentPeer(JNIEnv *env, jobject this); - -// Returns true if this shell has some transient shell chidlren -// which are either Dialogs or Windows. -// Returns false otherwise. -Boolean hasTransientChildren(Widget shell) { - int childIndex; - - // Enumerate through the popups - for (childIndex = 0; childIndex < shell->core.num_popups; childIndex++) { - Widget childShell = shell->core.popup_list[childIndex]; - // Find all transient shell which are either Dialog or Window - if (XtIsTransientShell(childShell)) { - Widget toplevel = findTopLevelByShell(childShell); - if (toplevel != NULL) { - // It is Dialog or Window - return true. - return True; - } - } - } - return False; -} - -extern Widget grabbed_widget; -/** - * Disposes top-level component and its widgets - */ -static -void disposeTopLevel(JNIEnv * env, jobject this) { - - struct FrameData *wdata; - Widget parentShell; - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || wdata->mainWindow == NULL - || wdata->winData.shell == NULL) - { - /* do nothing */ - return; - } - - // Save parent shell for later disposal. - parentShell = XtParent(wdata->winData.shell); - - removeTopLevel(wdata); - if (wdata->isInputMethodWindow) { - removeInputMethodWindow(wdata); - } - - XtRemoveEventHandler(wdata->focusProxy, FocusChangeMask, - False, shellEH, this); - XtUnmanageChild(wdata->focusProxy); - awt_util_consumeAllXEvents(wdata->focusProxy); - awt_util_cleanupBeforeDestroyWidget(wdata->focusProxy); - XtDestroyWidget(wdata->focusProxy); - - XtUnmanageChild(wdata->winData.comp.widget); - awt_delWidget(wdata->winData.comp.widget); - awt_util_consumeAllXEvents(wdata->winData.comp.widget); - awt_util_cleanupBeforeDestroyWidget(wdata->winData.comp.widget); - XtDestroyWidget(wdata->winData.comp.widget); - - XtUnmanageChild(wdata->mainWindow); - awt_util_consumeAllXEvents(wdata->mainWindow); - awt_util_consumeAllXEvents(wdata->winData.shell); - XtDestroyWidget(wdata->mainWindow); - XtDestroyWidget(wdata->winData.shell); - if (wdata->iconPixmap) { - XFreePixmap(awt_display, wdata->iconPixmap); - } - - if (grabbed_widget == wdata->winData.shell) { - XUngrabPointer(awt_display, CurrentTime); - XUngrabKeyboard(awt_display, CurrentTime); - grabbed_widget = NULL; - } - - free((void *) wdata); - - (*env)->SetLongField(env, this, mComponentPeerIDs.pData, 0); - awtJNI_DeleteGlobalRef(env, this); - - // Check if parent shell was scheduled for disposal. - // If it doesn't have window then we have to dispose it - // by ourselves right now. - // We can dispose shell only if it doesn't have "transient" children. - { - struct FrameData *pdata; - struct WidgetInfo* winfo; - Widget toplevel = findTopLevelByShell(parentShell); - if (toplevel == NULL) { - // Has already been deleted or it is top shell - return; - } - winfo = findWidgetInfo(toplevel); - DASSERT(winfo != NULL); - if (winfo == NULL) { - // Huh - has already been deleted? - return; - } - pdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, winfo->peer, mComponentPeerIDs.pData); - DASSERT(pdata != NULL); - if (pdata == NULL) { - // Huh - has already been deleted? - return; - } - // 1) scheduled 2) no children 3) no window - if (pdata->isDisposeScheduled - && !hasTransientChildren(parentShell) - && XtWindow(parentShell) == None) - { - disposeTopLevel(env, winfo->peer); - } - } -} - - -/** - * Property change listener. Listens to _XA_JAVA_DISPOSE_PROPERTY_ATOM, - * disposes the top-level when this property has been changed. - */ -static void -shellDisposeNotifyHandler(Widget w, XtPointer client_data, - XEvent* event, Boolean* continue_to_dispatch) { - struct FrameData *wdata; - - *continue_to_dispatch = True; - - if (event->type == PropertyNotify && - event->xproperty.atom == _XA_JAVA_DISPOSE_PROPERTY_ATOM) - { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, (jobject)client_data, - mComponentPeerIDs.pData); - if (wdata != NULL && wdata->isDisposeScheduled) { - disposeTopLevel(env, (jobject)client_data); - - // We've disposed top-level, no more actions on it - *continue_to_dispatch = False; - } - } -} - -/** - * Schedules top-level for later dispose - when all events - * on it will be processed. - */ -static -void scheduleDispose(JNIEnv * env, jobject peer) { - - struct FrameData *wdata; - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, peer, mComponentPeerIDs.pData); - - if (wdata->isDisposeScheduled) { - return; - } - - wdata->isDisposeScheduled = True; - if (XtWindow(wdata->winData.shell) != None) { - XChangeProperty(awt_display, XtWindow(wdata->winData.shell), - _XA_JAVA_DISPOSE_PROPERTY_ATOM, XA_ATOM, 32, PropModeAppend, - (unsigned char *)"", 0); - XFlush(awt_display); - XSync(awt_display, False); - } else { - // If this top-level has children which are still visible then - // their disposal could have been scheduled. We shouldn't allow this widget -// to destroy its children top-levels. For this purpose we postpone the disposal - // of this toplevel until after all its children are disposed. - if (!hasTransientChildren(wdata->winData.shell)) { - disposeTopLevel(env, peer); - } - } -} - - -/* sun_awt_motif_MWindowPeer_pCreate() is native (X/Motif) create routine */ -static char* focusProxyName = "FocusProxy"; - -Widget createFocusProxy(jobject globalRef, Widget parent) { - Widget proxy; -#define MAX_ARGC 20 - Arg args[MAX_ARGC]; - int32_t argc; - - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - if (parent == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return NULL; - } - argc = 0; - XtSetArg(args[argc], XmNwidth, 1); - argc++; - XtSetArg(args[argc], XmNheight, 1); - argc++; - XtSetArg(args[argc], XmNx, -1); - argc++; - XtSetArg(args[argc], XmNy, -1); - argc++; - XtSetArg(args[argc], XmNmarginWidth, 0); - argc++; - XtSetArg(args[argc], XmNmarginHeight, 0); - argc++; - XtSetArg(args[argc], XmNspacing, 0); - argc++; - XtSetArg(args[argc], XmNresizePolicy, XmRESIZE_NONE); - argc++; - - DASSERT(!(argc > MAX_ARGC)); - proxy = XmCreateDrawingArea(parent, focusProxyName, args, argc); - XtAddEventHandler(proxy, - FocusChangeMask, - False, shellEH, globalRef); - XtManageChild(proxy); -#undef MAX_ARGC - return proxy; -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pCreate - * Signature: (Lsun/awt/motif/MComponentPeer;Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_pCreate(JNIEnv *env, jobject this, - jobject parent, jstring target_class_name, jboolean isFocusableWindow) -{ -#define MAX_ARGC 50 - Arg args[MAX_ARGC]; - int32_t argc; - struct FrameData *wdata; - struct FrameData *pdata = NULL; - char *shell_name = NULL; - WidgetClass shell_class; - Widget parent_widget; - jobject target; - jobject insets; - jobject winAttr; - jstring warningString; - jboolean resizable; - jboolean isModal; - jboolean initialFocus; - jint state; - jclass clazz; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - - uint32_t runningWM; /* the running Window Manager */ - Widget innerCanvasW; /* form's child, parent of the - outer canvas (drawing area) */ - Position x,y; - Dimension w,h; - AwtGraphicsConfigDataPtr adata; - AwtGraphicsConfigDataPtr defConfig; - jobject gd = NULL; - jobject gc = NULL; - char *cname = NULL; - jstring jname; - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if (JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "null target"); - AWT_UNLOCK(); - return; - } - - wdata = ZALLOC(FrameData); - JNU_SetLongFieldFromPtr(env, this, mComponentPeerIDs.pData, wdata); - if (wdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - - adata = copyGraphicsConfigToPeer(env, this); - defConfig = getDefaultConfig(adata->awt_visInfo.screen); - - - /* Retrieve the specified characteristics for this window */ - winAttr = (*env)->GetObjectField(env, this, mWindowPeerIDs.winAttr); - resizable = (*env)->GetBooleanField( env, - winAttr, - mWindowAttributeIDs.isResizable); - state = (*env)->GetIntField( env, - winAttr, - mWindowAttributeIDs.initialState); - initialFocus = (*env)->GetBooleanField( env, - winAttr, - mWindowAttributeIDs.initialFocus); - - /* As of today decor is either on or off... except the InputMethodWindow */ - if ((*env)->GetBooleanField(env, winAttr, mWindowAttributeIDs.nativeDecor)) { - wdata->decor = (*env)->GetIntField(env, winAttr, mWindowAttributeIDs.decorations); - } else { - wdata->decor = AWT_NO_DECOR; - } - - insets = (*env)->GetObjectField(env, this, mWindowPeerIDs.insets); - - /* The insets will be corrected upon the reparent - event in shellEH(). For now, use bogus values. */ - wdata->top = (*env)->GetIntField(env, insets, insetsIDs.top); - wdata->left = (*env)->GetIntField(env, insets, insetsIDs.left); - wdata->bottom = (*env)->GetIntField(env, insets, insetsIDs.bottom); - wdata->right = (*env)->GetIntField(env, insets, insetsIDs.right); - awt_Frame_guessInsets(wdata); - awtJNI_ChangeInsets(env, this, wdata); - wdata->reparented = False; - wdata->configure_seen = False; - x = (*env)->GetIntField(env, target, componentIDs.x) + wdata->left; - y = (*env)->GetIntField(env, target, componentIDs.y) + wdata->top; - - w = (*env)->GetIntField(env, target, componentIDs.width) - - (wdata->left + wdata->right); - h = (*env)->GetIntField(env, target, componentIDs.height) - - (wdata->top + wdata->bottom); - if (w < 0) w = 0; - if (h < 0) h = 0; - - DTRACE_PRINTLN1("TL: pCreate: state = 0x%X", state); - - wdata->isModal = 0; - wdata->initialFocus = (Boolean)initialFocus; - wdata->isShowing = False; - wdata->shellResized = False; - wdata->canvasResized = False; - wdata->menuBarReset = False; - wdata->need_reshape = False; - wdata->focusProxy = NULL; -#ifdef __linux__ - wdata->fixInsets = True; -#endif - wdata->state = state; - - /* initialize screen to screen number in GraphicsConfig's device */ - /* can the Window's GC ever be null? */ - gc = (*env)->GetObjectField(env, target, componentIDs.graphicsConfig); - DASSERT(gc); - - gd = (*env)->GetObjectField(env, gc, x11GraphicsConfigIDs.screen); - DASSERT(gd); - - wdata->screenNum = (*env)->GetIntField(env, gd, x11GraphicsDeviceIDs.screen); - - wdata->isFocusableWindow = (Boolean)isFocusableWindow; - - /* - * Create a top-level shell widget. - */ - argc = 0; - XtSetArg(args[argc], XmNsaveUnder, False); argc++; - if (resizable) { - XtSetArg(args[argc], XmNallowShellResize, True); argc++; - } else { - XtSetArg(args[argc], XmNallowShellResize, False); argc++; - } - XtSetArg(args[argc], XmNvisual, defConfig->awt_visInfo.visual); argc++; - XtSetArg(args[argc], XmNcolormap, defConfig->awt_cmap); argc++; - XtSetArg(args[argc], XmNdepth, defConfig->awt_depth); argc++; - XtSetArg(args[argc], XmNmappedWhenManaged, False); argc++; - XtSetArg(args[argc], XmNx, x); argc++; - XtSetArg(args[argc], XmNy, y); argc++; - XtSetArg(args[argc], XmNwidth, w); argc++; - XtSetArg(args[argc], XmNheight, h); argc++; - - XtSetArg(args[argc], XmNbuttonFontList, getMotifFontList()); argc++; - XtSetArg(args[argc], XmNlabelFontList, getMotifFontList()); argc++; - XtSetArg(args[argc], XmNtextFontList, getMotifFontList()); argc++; - - XtSetArg(args[argc], XmNmwmDecorations, wdata->decor); argc++; - XtSetArg(args[argc], XmNscreen, - ScreenOfDisplay(awt_display, defConfig->awt_visInfo.screen)); argc++; - - if (wdata->initialFocus == False || !isFocusableWindowByPeer(env, this)) { - XtSetArg(args[argc], XmNinput, False); argc++; - } - - if (wdata->decor == AWT_NO_DECOR) { - /* this is heinous but it can not be avoided for now. - ** this is the only known way to eliminate all decorations - ** for openlook, which btw, is a bug as ol theoretically - ** supports MWM_HINTS - */ -#ifndef DO_FULL_DECOR - if (awt_wm_getRunningWM() == OPENLOOK_WM) { - XtSetArg(args[argc], XmNoverrideRedirect, True); - argc++; - } -#endif - } - - /* 4334958: Widget name is set to the Java class name */ - shell_name = - (char *)JNU_GetStringPlatformChars(env, target_class_name, NULL); - - if (parent) { - pdata = (struct FrameData *) - (*env)->GetLongField(env, parent, mComponentPeerIDs.pData); - } - - /* Parenting tells us whether we wish to be transient or not */ - if (pdata == NULL) { - if (!shell_name) - shell_name = "AWTapp"; - shell_class = topLevelShellWidgetClass; - parent_widget = awt_root_shell; - } - else { - if (!shell_name) - shell_name = "AWTdialog"; - shell_class = transientShellWidgetClass; - parent_widget = pdata->winData.shell; - XtSetArg(args[argc], XmNtransient, True); argc++; - XtSetArg(args[argc], XmNtransientFor, parent_widget); argc++; - - /* Fix Forte Menu Bug. If Window name is "###overrideRedirect###", - * then set XmNoverrideRedirect to prevent Menus from getting focus. - * In JDK 1.2.2 we created Windows as xmMenuShellWidgetClass, - * so we did not need to do this. Swing DefaultPopupFactory's - * createHeavyWeightPopup sets Window name to "###overrideRedirect###". - */ - /** - * Fix for 4476629. Allow Swing to create heavyweight popups which will - * not steal focus from Frame. - */ - jname = (*env)->GetObjectField(env, target, componentIDs.name); - if (!JNU_IsNull(env, jname)) { - cname = (char *)JNU_GetStringPlatformChars(env, jname, NULL); - } - if ( (cname != NULL && strcmp(cname, "###overrideRedirect###") == 0) - || (!isFrameOrDialog(target, env) - && !isFocusableWindowByPeer(env, this) - ) - ) - { /* mbron */ - XtSetArg(args[argc], XmNoverrideRedirect, True); - argc++; - } - if (cname) { - JNU_ReleaseStringPlatformChars(env, jname, (const char *) cname); - } - (*env)->DeleteLocalRef(env, jname); - } - DASSERT(!(argc > MAX_ARGC)); - wdata->winData.shell = XtCreatePopupShell(shell_name, shell_class, - parent_widget, args, argc); - if (shell_name) { - JNU_ReleaseStringPlatformChars(env, target_class_name, shell_name); - } - -#ifdef DEBUG - /* Participate in EditRes protocol to facilitate debugging */ - XtAddEventHandler(wdata->winData.shell, (EventMask)0, True, - _XEditResCheckMessages, NULL); -#endif - - setDeleteCallback(globalRef, wdata); - - /* Establish resizability. For the case of not resizable, do not - yet set a fixed size here; we must wait until in the routine - sun_awt_motif_MWindowPeer_pReshape() after insets have been fixed. - This is because correction of the insets may affect shell size. - (See comments in shellEH() concerning correction of the insets. */ - /* - * Fix for BugTraq ID 4313607. - * Initial resizability will be set later in MWindowPeer_setResizable() - * called from init(). - */ - wdata->isResizable = True; - wdata->isFixedSizeSet = False; - - XtAddEventHandler(wdata->winData.shell, - (StructureNotifyMask | PropertyChangeMask - | VisibilityChangeMask), - False, shellEH, globalRef); - - XtAddEventHandler(wdata->winData.shell, - FocusChangeMask, - False, shellFocusEH, globalRef); - - - /** - * Installing property change handler for DISPOSE property. - * This property will be changed when we need to dispose the whole - * top-level. The nature of PropertyNotify will guarantee that it is - * the latest event on the top-level so we can freely dispose it. - */ - wdata->isDisposeScheduled = False; - if (_XA_JAVA_DISPOSE_PROPERTY_ATOM == 0) { - _XA_JAVA_DISPOSE_PROPERTY_ATOM = XInternAtom(awt_display, "_SUNW_JAVA_AWT_DISPOSE", False); - } - XtAddEventHandler(wdata->winData.shell, PropertyChangeMask, False, - shellDisposeNotifyHandler, globalRef); - - /* - * Create "main" form. - */ - argc = 0; - XtSetArg(args[argc], XmNmarginWidth, 0); argc++; - XtSetArg(args[argc], XmNmarginHeight, 0); argc++; - XtSetArg(args[argc], XmNhorizontalSpacing, 0); argc++; - XtSetArg(args[argc], XmNverticalSpacing, 0); argc++; - XtSetArg(args[argc], XmNresizePolicy, XmRESIZE_NONE); argc++; - - XtSetArg(args[argc], XmNbuttonFontList, getMotifFontList()); argc++; - XtSetArg(args[argc], XmNlabelFontList, getMotifFontList()); argc++; - XtSetArg(args[argc], XmNtextFontList, getMotifFontList()); argc++; - - DASSERT(!(argc > MAX_ARGC)); - wdata->mainWindow = XmCreateForm(wdata->winData.shell, "main", args, argc); - - /* The widget returned by awt_canvas_create is a drawing area - (i.e., canvas) which is the child of another drawing area - parent widget. The parent is the drawing area within the - form just created. The child is an drawing area layer over - the entire frame window, including the form, any menu bar - and warning windows present, and also window manager stuff. - The top, bottom, left, and right fields in wdata maintain - the respective offsets between these two drawing areas. */ - - wdata->winData.comp.widget = awt_canvas_create((XtPointer)globalRef, - wdata->mainWindow, - "frame_", - -1, - -1, - True, - wdata, - adata); - XtAddCallback(wdata->winData.comp.widget, - XmNresizeCallback, outerCanvasResizeCB, - globalRef); - - innerCanvasW = XtParent(wdata->winData.comp.widget); - XtVaSetValues(innerCanvasW, - XmNleftAttachment, XmATTACH_FORM, - XmNrightAttachment, XmATTACH_FORM, - NULL); - - XtAddEventHandler(innerCanvasW, StructureNotifyMask, FALSE, - innerCanvasEH, globalRef); - - wdata->focusProxy = createFocusProxy((XtPointer)globalRef, - wdata->mainWindow); - - /* No menu bar initially */ - wdata->menuBar = NULL; - wdata->mbHeight = 0; - - /* If a warning window (string) is needed, establish it now.*/ - warningString = - (*env)->GetObjectField(env, target, windowIDs.warningString); - if (!JNU_IsNull(env, warningString) ) { - char *wString; - /* Insert a warning window. It's height can't be set yet; - it will later be set in setMbAndWwHeightAndOffsets().*/ - wString = (char *) JNU_GetStringPlatformChars(env, warningString, NULL); - wdata->warningWindow = awt_util_createWarningWindow(wdata->mainWindow, wString); - JNU_ReleaseStringPlatformChars(env, warningString, (const char *) wString); - - wdata->wwHeight = 0; - XtVaSetValues(wdata->warningWindow, - XmNleftAttachment, XmATTACH_FORM, - XmNrightAttachment, XmATTACH_FORM, - NULL); - -#ifdef NETSCAPE - /* For NETSCAPE, warning window is at bottom of the form*/ - XtVaSetValues(innerCanvasW, - XmNtopAttachment, XmATTACH_FORM, - NULL); - XtVaSetValues(wdata->warningWindow, - XmNtopAttachment, XmATTACH_WIDGET, - XmNtopWidget, innerCanvasW, - XmNbottomAttachment, XmATTACH_FORM, - NULL); -#else /* NETSCAPE */ - /* Otherwise (not NETSCAPE), warning is at top of form */ - XtVaSetValues(wdata->warningWindow, - XmNtopAttachment, XmATTACH_FORM, - NULL); - XtVaSetValues(innerCanvasW, - XmNtopAttachment, XmATTACH_WIDGET, - XmNtopWidget, wdata->warningWindow, - XmNbottomAttachment, XmATTACH_FORM, - NULL); -#endif /* NETSCAPE */ - - } else { - /* No warning window present */ - XtVaSetValues(innerCanvasW, - XmNtopAttachment, XmATTACH_FORM, - XmNbottomAttachment, XmATTACH_FORM, - NULL); - wdata->warningWindow = NULL; - wdata->wwHeight = 0; - } - - awt_util_show(wdata->winData.comp.widget); - - AWT_FLUSH_UNLOCK(); - - addTopLevel(wdata); - - /* Check whether this is an instance of InputMethodWindow or not */ - if (inputMethodWindowClass == NULL) { - jclass localClass = (*env)->FindClass(env, "sun/awt/im/InputMethodWindow"); - inputMethodWindowClass = (jclass)(*env)->NewGlobalRef(env, localClass); - (*env)->DeleteLocalRef(env, localClass); - } - if ((*env)->IsInstanceOf(env, target, inputMethodWindowClass)) { - wdata->isInputMethodWindow = True; - addInputMethodWindow(wdata); - } -} /* MWindowPeer_pCreate() */ - - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pSetTitle - * Signature: (Ljava/lang/String;)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_pSetTitle(JNIEnv *env, jobject this, - jstring title) -{ - char *ctitle; - char *empty_string = " "; - struct FrameData *wdata; - XTextProperty text_prop; - char *c[1]; - int32_t conv_result; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "null wdata or shell"); - AWT_UNLOCK(); - return; - } - - /* TODO: uwe: set _NET_WM_NAME property to utf-8 name */ - - ctitle = (JNU_IsNull(env, title)) ? empty_string - : (char *) JNU_GetStringPlatformChars(env, title, NULL); - - if (strcmp(ctitle, "") == 0) - ctitle = empty_string; - - c[0] = ctitle; - - /* need to convert ctitle to CompoundText */ - conv_result = XmbTextListToTextProperty(awt_display, c, 1, - XStdICCTextStyle, - &text_prop); - - /* - * XmbTextListToTextProperty returns value that is greater - * than Success if the supplied text is not fully convertible - * to specified encoding. In this case, the return value is - * the number of inconvertible characters. But convertibility - * is guaranteed for XCompoundTextStyle, so it will actually - * never be greater than Success. Errors handled below are - * represented by values that are lower than Success. - */ - if (conv_result >= Success) { - XtVaSetValues(wdata->winData.shell, - XmNtitle, text_prop.value, - XmNtitleEncoding, text_prop.encoding, - XmNiconName, text_prop.value, - XmNiconNameEncoding, text_prop.encoding, - XmNname, ctitle, - NULL); - } - - if (ctitle != empty_string) - JNU_ReleaseStringPlatformChars(env, title, (const char *) ctitle); - - if (conv_result == XNoMemory) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - if (conv_result == XLocaleNotSupported) { - JNU_ThrowInternalError(env, "Current locale is not supported"); - AWT_UNLOCK(); - return; - } - - XFree(text_prop.value); - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pToFront - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_pToFront(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - jobject target; - Window shellWindow; - Boolean autoRequestFocus; - Boolean isModal = FALSE; - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL - || wdata->winData.comp.widget == NULL - || wdata->winData.shell == NULL - || wdata->mainWindow == NULL - || JNU_IsNull(env, target)) - { - JNU_ThrowNullPointerException(env, "null widget/target data"); - AWT_UNLOCK(); - return; - } - - if ((shellWindow = XtWindow(wdata->winData.shell)) != None) { - XRaiseWindow(awt_display, shellWindow); - - autoRequestFocus = (*env)->GetBooleanField(env, target, windowIDs.isAutoRequestFocus); - - if (isDialog(target, env)) { - isModal = (*env)->GetBooleanField(env, target, dialogIDs.modal); - } - - // In contrast to XToolkit/WToolkit modal dialog can be unfocused. - // So we should also ask for modality in addition to 'autoRequestFocus'. - if (wdata->isFocusableWindow && (autoRequestFocus || isModal)) { - XSetInputFocus(awt_display, XtWindow(wdata->focusProxy), RevertToPointerRoot, CurrentTime); - } - } - - (*env)->DeleteLocalRef(env, target); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pShow - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_pShow(JNIEnv *env, jobject this) -{ - Java_sun_awt_motif_MWindowPeer_pShowModal(env, this, JNI_FALSE); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pShowModal - * Signature: (Z)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_pShowModal(JNIEnv *env, jobject this, - jboolean isModal) -{ - struct FrameData *wdata; - Boolean iconic; - jobject target; - Boolean locationByPlatform; - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL - || wdata->winData.comp.widget == NULL - || wdata->winData.shell == NULL - || wdata->mainWindow == NULL - || (wdata->winData.flags & W_IS_EMBEDDED) - || JNU_IsNull(env, target)) - { - JNU_ThrowNullPointerException(env, "null widget/target data"); - AWT_UNLOCK(); - return; - } - - DTRACE_PRINTLN2("TL: pShowModal(modal = %s) state = 0x%X", - isModal ? "true" : "false", - wdata->state); - - wdata->isModal = isModal; - - /* - * A workaround for bug 4062589 that is really a motif problem - * (see bug 4064803). Before popping up a modal dialog, if a - * pulldown menu has the input focus (i.e. user has pulled the - * menu down), we send a fake click event and make sure the click - * event is processed. With this simulation of user clicking, X - * server will not get confused about the modality and a - * subsequent click on the popup modal dialog will not cause - * system lockup. - */ - if (wdata->isModal && awt_util_focusIsOnMenu(awt_display) - && awt_util_sendButtonClick(awt_display, InputFocus)) - { - for (;;) { - XEvent ev; - XtAppPeekEvent(awt_appContext, &ev); - if ((ev.type == ButtonRelease) - && (*(XButtonEvent *)&ev).send_event) - { - XtAppProcessEvent(awt_appContext, XtIMAll); - break; - } else { - XtAppProcessEvent(awt_appContext, XtIMAll); - } - } - } - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - // 4488209: kdm@sparc.spb.su - // wdata->isShowing is True when toFront calls pShow. - // We do not need to do some things if wdata->isShowing is True. - if (!wdata->isShowing) { - XtVaSetValues(wdata->winData.comp.widget, - XmNx, -(wdata->left), - XmNy, -(wdata->top), - NULL); - - /* But see below! */ - iconic = (wdata->state & java_awt_Frame_ICONIFIED) ? True : False; - XtVaSetValues(wdata->winData.shell, - XmNinitialState, iconic ? IconicState : NormalState, - NULL); - - if (wdata->menuBar != NULL) { - awt_util_show(wdata->menuBar); - } - XtManageChild(wdata->mainWindow); - XtRealizeWidget(wdata->winData.shell); /* but not map it yet */ - -/* fprintf(stderr, "*** proxy window %x\n", XtWindow(wdata->focusProxy)); */ - XStoreName(awt_display, XtWindow(wdata->focusProxy), "FocusProxy"); - /* - * Maximization and other stuff that requires a live Window to set - * properties on to communicate with WM. - */ - awt_wm_setExtendedState(wdata, wdata->state); - awt_wm_setShellDecor(wdata, wdata->isResizable); - - if (wdata->isModal) { - removePopupMenus(); -#ifndef NOMODALFIX - /* - * Fix for 4078176 Modal dialogs don't act modal - * if addNotify() is called before setModal(true). - * Moved from Java_sun_awt_motif_MDialogPeer_create. - */ - if (!wdata->callbacksAdded) { - XtAddCallback(wdata->winData.shell, - XtNpopupCallback, awt_shellPoppedUp, - NULL); - XtAddCallback(wdata->winData.shell, - XtNpopdownCallback, awt_shellPoppedDown, - NULL); - wdata->callbacksAdded = True; - } -#endif /* !NOMODALFIX */ - /* - * Set modality on the Shell, not the BB. The BB expects that - * its parent is an xmDialogShell, which as the result of - * coalescing is now a transientShell... This has resulted in - * a warning message generated under fvwm. The shells are - * virtually identical and a review of Motif src suggests that - * setting dialog style on BB is a convenience not functional - * for BB so set Modality on shell, not the BB(form) widget. - */ - XtVaSetValues(wdata->winData.shell, - XmNmwmInputMode, MWM_INPUT_FULL_APPLICATION_MODAL, - NULL); - XtManageChild(wdata->winData.comp.widget); - } - else { /* not modal */ - XtVaSetValues(wdata->winData.shell, - XmNmwmInputMode, MWM_INPUT_MODELESS, NULL); - XtManageChild(wdata->winData.comp.widget); - XtSetMappedWhenManaged(wdata->winData.shell, True); - } - if (wdata->isResizable) { - /* REMINDER: uwe: will need to revisit for setExtendedStateBounds */ - awt_wm_removeSizeHints(wdata->winData.shell, PMinSize|PMaxSize); - } - locationByPlatform = - (*env)->GetBooleanField(env, target, windowIDs.locationByPlatform); - if (locationByPlatform) { - awt_wm_removeSizeHints(wdata->winData.shell, USPosition|PPosition); - } - } - - /* - * 4261047: always pop up with XtGrabNone. Motif notices the - * modal input mode and perform the grab for us, doing its - * internal book-keeping as well. - */ - XtPopup(wdata->winData.shell, XtGrabNone); - wdata->isShowing = True; - - wdata->initialFocus = (*env)->GetBooleanField(env, target, windowIDs.isAutoRequestFocus); - - if (wdata->isFocusableWindow) { - if (wdata->initialFocus || wdata->isModal) { - focusOnMapNotify = True; - } else { - XtVaSetValues(wdata->winData.shell, XmNinput, False, NULL); - } - } - - (*env)->DeleteLocalRef(env, target); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: getState - * Signature: ()I - */ -JNIEXPORT jint JNICALL -Java_sun_awt_motif_MWindowPeer_getState(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - jint state; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL || wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return java_awt_Frame_NORMAL; - } - - state = wdata->state; - - AWT_FLUSH_UNLOCK(); - return state; -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: setState - * Signature: (I)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_setState(JNIEnv *env, jobject this, - jint state) -{ - struct FrameData *wdata; - Widget shell; - Window shell_win; - jint changed; - Boolean changeIconic, iconic; - - AWT_LOCK(); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL || wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - shell = wdata->winData.shell; - shell_win = XtWindow(shell); - - DTRACE_PRINTLN4("TL: setState(0x%x/0x%x, 0x%X -> 0x%X)", - shell, shell_win, - wdata->state, state); - - if (!wdata->isShowing) { - /* - * Not showing, so just record requested state; pShow will set - * initial state hints/properties appropriately before poping - * us up again. - */ - DTRACE_PRINTLN("TL: NOT showing (just record the new state)"); - wdata->state = state; - AWT_UNLOCK(); - return; - } - - /* - * Request the state transition from WM here and do java upcalls - * in shell event handler when WM actually changes our state. - */ - changed = wdata->state ^ state; - - changeIconic = changed & java_awt_Frame_ICONIFIED; - iconic = (state & java_awt_Frame_ICONIFIED) ? True : False; - - if (changeIconic && iconic) { - DTRACE_PRINTLN("TL: set iconic = True"); - XIconifyWindow(XtDisplay(shell), shell_win, - XScreenNumberOfScreen(XtScreen(shell))); - } - - /* - * If a change in both iconic and extended states requested, do - * changes to extended state when we are in iconic state. - */ - if ((changed & ~java_awt_Frame_ICONIFIED) != 0) { - awt_wm_setExtendedState(wdata, state); - } - - if (changeIconic && !iconic) { - DTRACE_PRINTLN("TL: set iconic = False"); - XMapWindow(XtDisplay(shell), shell_win); - } - - AWT_FLUSH_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pHide - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_pHide(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - - AWT_LOCK(); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL - || wdata->winData.comp.widget == NULL - || wdata->winData.shell == NULL) - { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - /** - * Disable proxy mechanism when Window's shell is being hidden - */ - clearFocusPath(wdata->winData.shell); - - wdata->isShowing = False; /* ignore window state events */ - - if (XtIsRealized(wdata->winData.shell)) { - /* XXX: uwe: this is bogus */ - /* - * Make sure we withdraw a window in an unmaximized state, or - * we'll lose out normal bounds (pShow will take care of - * hinting maximization, so when the window is shown again it - * will be correctly shown maximized). - */ - if (wdata->state & java_awt_Frame_MAXIMIZED_BOTH) { - awt_wm_setExtendedState(wdata, - wdata->state & ~java_awt_Frame_MAXIMIZED_BOTH); - } - XtUnmanageChild(wdata->winData.comp.widget); - XtPopdown(wdata->winData.shell); - } - - AWT_FLUSH_UNLOCK(); -} - - -/* sun_awt_motif_MWindowPeer_pReshape() is native (X/Motif) routine that - is called to effect a reposition and / or resize of the target frame. - The parameters x,y,w,h specify target's x, y position, width, height.*/ - -/* - * This functionality is invoked from both java and native code, and - * we only want to lock when invoking it from java, so wrap the native - * method version with the locking. - */ - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pReshape - * Signature: (IIII)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_pReshape(JNIEnv *env, jobject this, - jint x, jint y, jint w, jint h) -{ - struct FrameData *wdata; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - // See if our new location is on a new screen - if (wdata->reparented) { - checkNewXineramaScreen(env, this, wdata, x, y, w, h); - } - - /** - * Fix for 4652685. - * Avoid setting position for embedded frames, since this conflicts with the - * fix for 4419207. We assume that the embedded frame never changes its - * position relative to the parent. - */ - if (wdata->winData.flags & W_IS_EMBEDDED) { - x = 0; - y = 0; - } - - reshape(env, this, wdata, x, y, w, h, True); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MEmbeddedFramePeer - * Method: pReshapePrivate - * Signature: (IIII)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MEmbeddedFramePeer_pReshapePrivate(JNIEnv *env, jobject this, - jint x, jint y, jint w, jint h) -{ - struct FrameData *wdata; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - reshape(env, this, wdata, x, y, w, h, True); - - AWT_FLUSH_UNLOCK(); -} - -static void -reshape(JNIEnv *env, jobject this, struct FrameData *wdata, - jint x, jint y, jint w, jint h, Boolean setXY) -{ - int32_t topAdjust, /* top adjustment of offset */ - bottomAdjust; /* bottom adjustment of offset */ - int32_t width, /* of X/Motif shell and form */ - height; /* of X/Motif shell and form */ - int32_t w1, h1; - enum wmgr_t wm; /* window manager */ - XWindowAttributes winAttr; - - DTRACE_PRINTLN7("TL: reshape(0x%x/0x%x,\n"/**/ - "TL: x = %d, y = %d, w = %d, h = %d, %s)", - wdata->winData.shell, XtWindow(wdata->winData.shell), - x, y, w, h, - setXY ? "setXY" : "false"); - - wm = awt_wm_getRunningWM(); - - /* Make adjustments in case of a dynamically added/removed menu bar */ - awtJNI_setMbAndWwHeightAndOffsets(env, this, wdata); - -#ifdef _pauly_debug - fprintf(stdout," reshape. offsets - top: %d, bottom: %d, left: %d, right: %d\n", - wdata->top, wdata->bottom, wdata->left, wdata->right); - fflush(stdout); -#endif /* _pauly_debug */ - - /* The abstract java (target) position coordinates (x,y) - are for the bordered window. Eventually(!), the Motif - (shell) coordinates (XmNx, XmNy) will exclude borders. - (This is true only AFTER shell is massaged by the WM.) */ - - /* The abstract java (target) width and height includes any WM - borders. But the Motif width and height excludes WM borders. - The wdata top and bottom fields may include space for menu bar, - warning window, etc. We must adjust by these values for shell. */ - topAdjust = 0; - bottomAdjust = 0; - /* Surprise - do not(!) check for nonNull MenuBar because that can - occur separately (in ...pSetMenubar()) from calculation of the - menu bar height and offsets (in setMbAndWwHeightAndOffsets()). - In any event, the offsets and wdata mbHeight field should jive. */ - topAdjust += wdata->mbHeight; - if (wdata->warningWindow != NULL) { -#ifdef NETSCAPE - bottomAdjust += wdata->wwHeight; -#else /* NETSCAPE */ - topAdjust += wdata->wwHeight; -#endif /* NETSCAPE */ - } - if (wdata->hasTextComponentNative) { - bottomAdjust += wdata->imHeight; - } -#ifdef _pauly_debug - fprintf(stdout," reshape. adjustments - top: %d, bottom: %d\n", topAdjust, bottomAdjust); - fflush(stdout); -#endif /* _pauly_debug */ - - width = w - (wdata->left + wdata->right); - height = h - (wdata->top + wdata->bottom) + (topAdjust + bottomAdjust); - - /* - * Shell size. - * 4033151. If nonpositive size specified (e.g., if no size - * given), establish minimum allowable size. Note: Motif shell - * can not be sized 0. - */ - w1 = (width > 0) ? width : 1; - h1 = (height > 0) ? height : 1; - - if (awt_wm_configureGravityBuggy() /* WM ignores window gravity */ - && wdata->reparented && wdata->isShowing) - { - /* - * Buggy WM places client window at (x,y) ignoring the window - * gravity. All our windows are NorthWestGravity, so adjust - * (x,y) by insets appropriately. - */ - x += wdata->left; - y += wdata->top; - DTRACE_PRINTLN2("TL: work around WM gravity bug: x += %d, y += %d", - wdata->left, wdata->top); - } - - if (wdata->imRemove) { - XtVaSetValues(XtParent(wdata->winData.comp.widget), - XmNheight, (((h - (wdata->top + wdata->bottom)) > 0) ? - (h - (wdata->top + wdata->bottom)) : 1), - NULL); - wdata->imRemove = False; - } - -#if 0 /* XXX: this screws insets calculation under KDE2 in the case of - negative x, y */ - /* - * Without these checks, kwm places windows slightly off the screen, - * when there is a window underneath at (0,0) and empty space below, - * but not to the right. - */ - if (x < 0) x = 0; - if (y < 0) y = 0; -#endif - if ((wdata->winData.flags & W_IS_EMBEDDED) == 0) { - if ((wm == MOTIF_WM) || (wm == CDE_WM)) { - /* - * By default MWM has "usePPosition: nonzero" and so ignores - * windows with PPosition (0,0). Work around (should we???). - */ - if ((x == 0) && (y == 0)) { - x = y = 1; - } - } - } - - if ( wdata->decor == AWT_NO_DECOR ) { - if (setXY) - XtConfigureWidget(wdata->winData.shell, x, y, w1, h1, 0 ); - else - XtResizeWidget(wdata->winData.shell, w1, h1, 0); - } - else { - /* - * 5006248, workaround for OpenLook WM. - * Thread gets stuck at XtVaSetValues call awaiting for first - * ConfigureNotify to come. For OpenLook it looks like a showstopper. - * We put dummy ConfigureNotify to satisfy the requirements. - */ - if (awt_wm_getRunningWM() == OPENLOOK_WM) { - XEvent xev; - xev.xconfigure.type = ConfigureNotify; - xev.xconfigure.display = awt_display; - xev.xconfigure.window = XtWindow(wdata->winData.shell); - xev.xconfigure.event = xev.xconfigure.window; - xev.xconfigure.x = x; - xev.xconfigure.y = y; - xev.xconfigure.height = h1; - xev.xconfigure.width = w1; - xev.xconfigure.serial = NextRequest(awt_display) + 1; // see isMine() Xt inner function code. - - XPutBackEvent(awt_display, &xev); - } - - if (wdata->isResizable) { - XtVaSetValues(wdata->winData.shell, - XmNwidth, w1, - XmNheight, h1, - NULL); - } - else { - /* - * Fix for BugTraq ID 4313607 - call awt_wm_setShellNotResizable - * regardless of wdata->isFixedSizeSet and wdata->reparented values. - */ - DTRACE_PRINTLN("TL: set fixed size from reshape"); - awt_wm_setShellNotResizable(wdata, w1, h1, True); - if (wdata->reparented && (w1 > 0) && (h1 > 0)) { - wdata->isFixedSizeSet = True; - } - } - if (setXY) - XtVaSetValues(wdata->winData.shell, - XmNx, x, - XmNy, y, - NULL); - } - /* inner/parent drawing area (parent is form) */ - h1 = h - (wdata->top + wdata->bottom); - h1 = ( h1 > 0 ) ? h1 : 1; -#if 0 - XtConfigureWidget(XtParent(wdata->winData.comp.widget), - 0, topAdjust, w1, h1, 0 ); -#else - XtVaSetValues(XtParent(wdata->winData.comp.widget), - XmNx, 0, - XmNy, topAdjust, - XmNwidth, w1, - XmNheight, h1, - NULL); -#endif - -#ifdef _pauly_debug - fprintf(stdout," reshape. setting inner canvas to: %d,%d,%d,%d\n", - 0, topAdjust, w1, h1 ); - fflush(stdout); -#endif /* _pauly_debug */ - - wdata->menuBarReset = False; - - /* DTRACE_PRINTLN("TL: reshape -> returning"); */ - return; -} - -/* - * Class: sun_awt_motif_MEmbeddedFramePeer - * Method: getBoundsPrivate - * Signature: ()Ljava/awt/Rectangle - */ -JNIEXPORT jobject JNICALL Java_sun_awt_motif_MEmbeddedFramePeer_getBoundsPrivate - (JNIEnv * env, jobject this) -{ - jobject bounds = NULL; - struct FrameData *cdata; - XWindowAttributes attr; - - AWT_LOCK(); - - cdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (cdata == NULL || cdata->mainWindow == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return NULL; - } - if (!XtIsRealized(cdata->mainWindow) || !XtIsRealized(cdata->winData.shell)) { - JNU_ThrowInternalError(env, "widget not visible on screen"); - AWT_UNLOCK(); - return NULL; - } - - memset(&attr, 0, sizeof(XWindowAttributes)); - XGetWindowAttributes(awt_display, XtWindow(cdata->winData.shell), &attr); - - bounds = JNU_NewObjectByName(env, "java/awt/Rectangle", "(IIII)V", - (jint)attr.x, (jint)attr.y, (jint)attr.width, (jint)attr.height); - if (((*env)->ExceptionOccurred(env)) || JNU_IsNull(env, bounds)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return NULL; - } - - AWT_UNLOCK(); - - return bounds; -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pDispose - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_pDispose -(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - - AWT_LOCK(); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL || wdata->mainWindow == NULL || wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (wdata->winData.flags & W_IS_EMBEDDED) { - awt_util_delEmbeddedFrame(wdata->winData.shell); - deinstall_xembed(wdata); - } - scheduleDispose(env, this); - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MFramePeer - * Method: pGetIconSize - * Signature: (II)Z - */ -JNIEXPORT jboolean JNICALL Java_sun_awt_motif_MFramePeer_pGetIconSize -(JNIEnv *env, jobject this, jint widthHint, jint heightHint) -{ - struct FrameData *wdata; - uint32_t width, height, border_width, depth; - Window win; - int32_t x, y; - uint32_t mask; - XSetWindowAttributes attrs; - uint32_t saveWidth = 0; - uint32_t saveHeight = 0; - uint32_t dist = 0xffffffff; - int32_t diff = 0; - int32_t closestWidth; - int32_t closestHeight; - int32_t newDist; - int32_t found = 0; - AwtGraphicsConfigDataPtr adata; - - AWT_LOCK(); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return FALSE; - } - XtVaGetValues(wdata->winData.shell, - XmNiconWindow, &win, - NULL); - if (!win) { - int32_t count; - int32_t i; - XIconSize *sizeList; - - adata = getGraphicsConfigFromComponentPeer(env, this); - - if (!XGetIconSizes(awt_display, - RootWindow(awt_display, adata->awt_visInfo.screen), - &sizeList, &count)) { - /* No icon sizes so can't set it -- Should we throw an exception?*/ - /* [jk] I don't think so: simply fall back to 16x16 */ - saveWidth = saveHeight = 16; - goto top; - } - for (i=0; i < count; i++) { - if (widthHint >= sizeList[i].min_width && - widthHint <= sizeList[i].max_width && - heightHint >= sizeList[i].min_height && - heightHint <= sizeList[i].max_height) { - found = 1; - if ((((widthHint-sizeList[i].min_width) - % sizeList[i].width_inc) == 0) && - (((heightHint-sizeList[i].min_height) - % sizeList[i].height_inc) ==0)) { - /* Found an exact match */ - saveWidth = widthHint; - saveHeight = heightHint; - dist = 0; - break; - } - diff = widthHint - sizeList[i].min_width; - if (diff == 0) { - closestWidth = widthHint; - } else { - diff = diff%sizeList[i].width_inc; - closestWidth = widthHint - diff; - } - diff = heightHint - sizeList[i].min_height; - if (diff == 0) { - closestHeight = heightHint; - } else { - diff = diff%sizeList[i].height_inc; - closestHeight = heightHint - diff; - } - newDist = closestWidth*closestWidth + - closestHeight*closestHeight; - if (dist > newDist) { - saveWidth = closestWidth; - saveHeight = closestHeight; - dist = newDist; - } - } - } - - if (!found) { -#if 1 - /* [sbb] this code should work better than the original Solaris - code */ - if (widthHint >= sizeList[0].max_width || - heightHint >= sizeList[0].max_height) { - /* determine which way to scale */ - int32_t wdiff = widthHint - sizeList[0].max_width; - int32_t hdiff = heightHint - sizeList[0].max_height; - if (wdiff >= hdiff) { /* need to scale width more */ - saveWidth = sizeList[0].max_width; - saveHeight = (int32_t)(((double)sizeList[0].max_width/widthHint) * - heightHint); - } else { - saveWidth = (int32_t)(((double)sizeList[0].max_height/heightHint) * - widthHint); - saveHeight = sizeList[0].max_height; - } - } else if (widthHint < sizeList[0].min_width || - heightHint < sizeList[0].min_height) { - saveWidth = (sizeList[0].min_width+sizeList[0].max_width)/2; - saveHeight = (sizeList[0].min_height+sizeList[0].max_height)/2; - } else { /* it fits within the right size */ - saveWidth = widthHint; - saveHeight = heightHint; - } - -#else /* XXX: old Solaris code */ - /* REMIND: Aspect ratio */ - if (widthHint >= sizeList[0].max_width && - heightHint >= sizeList[0].max_height) { - saveWidth = sizeList[0].max_width; - saveHeight = sizeList[0].max_height; - } else if (widthHint >= sizeList[0].min_width && - heightHint >= sizeList[0].min_height) { - saveWidth = sizeList[0].min_width; - saveHeight = sizeList[0].min_height; - } else { - saveWidth = (sizeList[0].min_width+sizeList[0].max_width)/2; - saveHeight = (sizeList[0].min_height+sizeList[0].max_height)/2; - } -#endif - } - free((void *) sizeList); - } else { - Window root; - if (XGetGeometry(awt_display, - win, - &root, - &x, - &y, - (uint32_t *)&saveWidth, - (uint32_t *)&saveHeight, - (uint32_t *)&border_width, - (uint32_t *)&depth)) { - } - } - - top: - (*env)->SetIntField(env, this, mWindowPeerIDs.iconWidth, (jint)saveWidth); - (*env)->SetIntField(env, this, mWindowPeerIDs.iconHeight, (jint)saveHeight); - - AWT_UNLOCK(); - return TRUE; -} - -/* - * Class: sun_awt_motif_MFramePeer - * Method: pSetIconImage - * Signature: ([B[I[SII)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MFramePeer_pSetIconImage___3B_3I_3SII -(JNIEnv *env, jobject this, - jbyteArray jbyteData, jintArray jintData, jshortArray jushortData, - jint iconWidth, jint iconHeight) -{ - struct FrameData *wdata; - Window win; - GC gc; - int32_t x, y; - XImage *dst; - uint32_t mask; - XSetWindowAttributes attrs; - jobject jbuf = NULL; - void *buf = NULL; - int32_t len = 0; - int32_t bpp, slp, bpsl; - AwtGraphicsConfigDataPtr adata; - - if (JNU_IsNull(env, jbyteData)) { - if (JNU_IsNull(env, jintData)) { - if (JNU_IsNull(env, jushortData)) { - /* [jk] Don't throw an exception here, it breaks - * programs that run correctly on Windows - * JNU_ThrowNullPointerException(env, "NullPointerException"); - */ - return; - } else { - jbuf = jushortData; - } - } else { - jbuf = jintData; - } - } else { - jbuf = jbyteData; - len = (*env)->GetArrayLength(env, jbyteData); - } - AWT_LOCK(); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - /* REMIND: Need to figure out how to display image on a pixmap */ - - if (wdata == NULL || wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - adata = getGraphicsConfigFromComponentPeer(env, this); - - /* [jk] we need a new pixmap everytime: - * Test case: src/share/test/awt/FrameTest.html Look at the icon, - * select Operations/Change IconImage, you should see a different - * icon now. - */ - if (wdata->iconPixmap) { - XFreePixmap(awt_display, wdata->iconPixmap); - wdata->iconPixmap = None; - } - - if (wdata->iconPixmap == None) { - if ((wdata->iconPixmap = - XCreatePixmap(awt_display, - RootWindow(awt_display, adata->awt_visInfo.screen), - iconWidth, iconHeight, - adata->awtImage->Depth)) == None) { - /* REMIND: How to warn that there was a problem? */ - AWT_UNLOCK(); - return; - } - wdata->iconWidth = iconWidth; - wdata->iconHeight = iconHeight; - } - - buf = (void *) (*env)->GetPrimitiveArrayCritical(env, jbuf, NULL); - if (jbyteData != NULL) { - int32_t i; - unsigned char *ubuf = (unsigned char *) buf; - /* Need to map from ICM lut to cmap */ - for (i=0; i < len; i++) { - ubuf[i] = (ubuf[i] >= adata->color_data->awt_numICMcolors) - ? 0 - : adata->color_data->awt_icmLUT2Colors[ubuf[i]]; - } - } - - bpp = adata->awtImage->wsImageFormat.bits_per_pixel; - slp = adata->awtImage->wsImageFormat.scanline_pad; - bpsl = paddedwidth(iconWidth * bpp, slp) >> 3; - if (((bpsl << 3) / bpp) < iconWidth) { - (*env)->ReleasePrimitiveArrayCritical(env, jbuf, buf, JNI_ABORT); - AWT_UNLOCK(); - return; - } - dst = XCreateImage(awt_display, adata->awt_visInfo.visual, - adata->awtImage->Depth, ZPixmap, 0, - buf, iconWidth, iconHeight, 32, bpsl); - if (dst == NULL) { - /* REMIND: How to warn that there was a problem? */ - (*env)->ReleasePrimitiveArrayCritical(env, jbuf, buf, JNI_ABORT); - AWT_UNLOCK(); - return; - } - - if ((gc = XCreateGC(awt_display, wdata->iconPixmap, 0, 0)) == NULL) { - XDestroyImage (dst); - (*env)->ReleasePrimitiveArrayCritical(env, jbuf, buf, JNI_ABORT); - AWT_UNLOCK(); - return; - } - - XPutImage(awt_display, wdata->iconPixmap, gc, dst, - 0, 0, 0, 0, iconWidth, iconHeight); - (*env)->ReleasePrimitiveArrayCritical(env, jbuf, buf, JNI_ABORT); - dst->data=NULL; - XDestroyImage(dst); - XFreeGC(awt_display, gc); - - XtVaGetValues(wdata->winData.shell, - XmNiconWindow, &win, - NULL); - if (!win) { - mask = CWBorderPixel | CWColormap | CWBackPixmap; - attrs.border_pixel = awt_defaultFg; - attrs.colormap = adata->awt_cmap; - attrs.background_pixmap = wdata->iconPixmap; - if (!(win = XCreateWindow(awt_display, - RootWindow(awt_display, - adata->awt_visInfo.screen), - 0, 0, iconWidth, iconHeight, - (uint32_t) 0, - adata->awtImage->Depth, - InputOutput, - adata->awt_visInfo.visual, - mask, &attrs))) { - /* Still can't create the window so try setting iconPixmap */ - XtVaSetValues(wdata->winData.shell, - XmNiconPixmap, wdata->iconPixmap, - NULL); - AWT_FLUSH_UNLOCK(); - return; - } - } - - XtVaSetValues(wdata->winData.shell, - XmNiconPixmap, wdata->iconPixmap, - XmNiconWindow, win, - NULL); - - XSetWindowBackgroundPixmap(awt_display, win, wdata->iconPixmap); - XClearWindow(awt_display, win); - AWT_FLUSH_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: setResizable - * Signature: (Z)V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_setResizable(JNIEnv *env, jobject this, - jboolean resizable) -{ - struct FrameData *wdata; - jobject target; - int32_t targetWidth, - targetHeight; - int32_t width, /* fixed width if not resizable */ - height; /* fixed height if not resizable*/ - int32_t verticalAdjust; /* menubar, warning window, etc.*/ - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - return; - } - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL - || wdata->winData.comp.widget == NULL - || wdata->winData.shell == NULL - || JNU_IsNull(env, target)) - { - JNU_ThrowNullPointerException(env, "NullPointerException"); - if (!JNU_IsNull(env, target)) - (*env)->DeleteLocalRef(env, target); - AWT_UNLOCK(); - return; - } - - DTRACE_PRINTLN3("TL: setResizable(0x%x/0x%x, %s)", - wdata->winData.shell, XtWindow(wdata->winData.shell), - resizable ? "true" : "false"); - - if ((!wdata->isResizable) && (resizable)) { - awt_wm_setShellResizable(wdata); - wdata->isFixedSizeSet = False; - } - else if ((wdata->isResizable) && (!resizable)) { - /* - * To calculate fixed window width, height, we must subtract - * off the window manager borders as stored in the wdata - * structure. But note that the wdata top and bottom fields - * may include space for warning window, menubar, IM status; - * this IS part of shell. - */ - verticalAdjust = wdata->mbHeight; - if (wdata->warningWindow != NULL) { - verticalAdjust += wdata->wwHeight; - } - if (wdata->hasTextComponentNative) { - verticalAdjust += wdata->imHeight; - } - - targetWidth = (*env)->GetIntField(env, target, componentIDs.width); - targetHeight = (*env)->GetIntField(env, target, componentIDs.height); - width = targetWidth - (wdata->left + wdata->right); - height = targetHeight - (wdata->top + wdata->bottom) + verticalAdjust; -#ifdef __linux__ - width = (width > 0) ? width : 1; - height = (height > 0) ? height : 1; -#endif - DTRACE_PRINTLN2("TL: setting fixed size %ld x %ld", width, height); - awt_wm_setShellNotResizable(wdata, width, height, False); - if ((width > 0) && (height > 0)) { - wdata->isFixedSizeSet = True; - } - } - - wdata->isResizable = (Boolean)resizable; - - (*env)->DeleteLocalRef(env, target); - AWT_FLUSH_UNLOCK(); -} - - -/* sun_awt_motif_MWindowPeer_pSetMenuBar() is native (X/Motif) routine - which handles insertion or deletion of a menubar from this frame. */ - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: pSetMenuBar - * Signature: (Lsun/awt/motif/MMenuBarPeer;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_pSetMenuBar -(JNIEnv *env, jobject this, jobject mb) -{ - struct FrameData *wdata; - struct ComponentData *mdata; - jobject target; - Widget innerCanvasW; /* Motif inner canvas */ -#ifdef _pauly_debug - Dimension mbHeight; /* Motif menubar height */ -#endif /* _pauly_debug */ - -#ifdef _pauly_debug - fprintf(stdout," ++ ...pSetMenuBar.\n"); - fflush(stdout); -#endif /* _pauly_debug */ - - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - return; - } - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (JNU_IsNull(env, target) || wdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - if (!JNU_IsNull(env, target)) { - (*env)->DeleteLocalRef(env, target); - } - AWT_UNLOCK(); - return; - } - - if (mb == NULL) { -#ifdef _pauly_debug - fprintf(stdout," ...pSetMenuBar. mb is null.\n"); - fflush(stdout); -#endif /* _pauly_debug */ - if (wdata->menuBar != NULL) { - /* Redo attachments of other form widgets appropriately now */ - innerCanvasW = XtParent(wdata->winData.comp.widget); - - if (wdata->warningWindow == NULL) { - /* no warning window: canvas is now attached to form */ - XtVaSetValues(innerCanvasW, - XmNtopAttachment, XmATTACH_FORM, - NULL); - } else { - /* warning window present - conditional on #define NETSCAPE: - if NETSCAPE, warning window is at bottom, so canvas is - attached to the form (as above); otherwise (not NETSCAPE), - warning window itself is instead attached to form. */ -#ifdef NETSCAPE - XtVaSetValues(innerCanvasW, - XmNtopAttachment, XmATTACH_FORM, - NULL); -#else /* NETSCAPE */ - XtVaSetValues(wdata->warningWindow, - XmNtopAttachment, XmATTACH_FORM, - NULL); -#endif /* NETSCAPE */ - } - - wdata->menuBarReset = True; - } - wdata->menuBar = NULL; - awtJNI_setMbAndWwHeightAndOffsets(env, this, wdata); - (*env)->DeleteLocalRef(env, target); - AWT_FLUSH_UNLOCK(); -#ifdef _pauly_debug - fprintf(stdout," ...pSetMenuBar. Done.\n"); - fflush(stdout); -#endif /* _pauly_debug */ - return; - } - - mdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, mb, mMenuBarPeerIDs.pData); - if (mdata == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - (*env)->DeleteLocalRef(env, target); - AWT_UNLOCK(); - return; - } - - /* OK - insert the new menu bar into the form (at the top). - Redo the attachments of other form widgets appropriately.*/ - - if (wdata->menuBar == NULL) - wdata->menuBarReset = True; - wdata->menuBar = mdata->widget; - -#ifdef _pauly_debug - XtVaGetValues(mdata->widget, XmNheight, &mbHeight, NULL); - fprintf(stdout," ...pSetMenuBar. new menu bar (widget %x, parent: %x) - menu bar height: %d\n", wdata->menuBar, XtParent(wdata->menuBar), mbHeight); - fflush(stdout); -#endif /* _pauly_debug */ - - XtVaSetValues(mdata->widget, - XmNtopAttachment, XmATTACH_FORM, - XmNleftAttachment, XmATTACH_FORM, - XmNrightAttachment, XmATTACH_FORM, - NULL); - - innerCanvasW = XtParent(wdata->winData.comp.widget); - - if (wdata->warningWindow == NULL) { - /* no warning window: menu bar at top, canvas attached to it */ - XtVaSetValues(innerCanvasW, - XmNtopAttachment, XmATTACH_WIDGET, - XmNtopWidget, mdata->widget, - NULL); - } else { - /* warning window present - conditional on #define NETSCAPE: - if NETSCAPE, warning window is at bottom, so canvas is - attached to menu bar (as above); otherwise (not NETSCAPE), - the warning window is attached just below the menu bar. */ -#ifdef NETSCAPE - XtVaSetValues(innerCanvasW, - XmNtopAttachment, XmATTACH_WIDGET, - XmNtopWidget, mdata->widget, - NULL); -#else /* NETSCAPE */ - XtVaSetValues(wdata->warningWindow, - XmNtopAttachment, XmATTACH_WIDGET, - XmNtopWidget, mdata->widget, - NULL); -#endif /* NETSCAPE */ - } - - XtManageChild(mdata->widget); - XtMapWidget(mdata->widget); - XSync(awt_display, False); - awtJNI_setMbAndWwHeightAndOffsets(env, this, wdata); - -#ifdef _pauly_debug - XtVaGetValues(mdata->widget, XmNheight, &mbHeight, NULL); - fprintf(stdout," ...pSetMenuBar. with menu bar: menu bar height: %d, top offset: %d, bottom offset: %d\n", mbHeight, wdata->top, wdata->bottom); - fflush(stdout); -#endif /* _pauly_debug */ - - (*env)->DeleteLocalRef(env, target); - - AWT_FLUSH_UNLOCK(); - -#ifdef _pauly_debug - fprintf(stdout," ...pSetMenuBar. Done\n"); - fflush(stdout); -#endif /* _pauly_debug */ -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: toBack - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_toBack -(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (XtWindow(wdata->winData.shell) != 0) { - XLowerWindow(awt_display, XtWindow(wdata->winData.shell)); - } - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: updateAlwaysOnTop - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_updateAlwaysOnTop -(JNIEnv *env, jobject this, jboolean isOnTop) -{ - struct FrameData *wdata; - AWT_LOCK(); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - awt_wm_updateAlwaysOnTop(wdata, isOnTop); - AWT_FLUSH_UNLOCK(); -} - -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_addTextComponentNative -(JNIEnv *env, jobject this, jobject tc) -{ - struct FrameData *wdata; - jobject target; - - if (JNU_IsNull(env, this)) { - return; - } - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || - wdata->winData.comp.widget==NULL || - wdata->winData.shell==NULL || - JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if ( !wdata->hasTextComponentNative) { - wdata->hasTextComponentNative = True; - wdata->imHeight = awt_motif_getIMStatusHeight(wdata->winData.shell, tc); - wdata->bottom += wdata->imHeight; - awtJNI_ChangeInsets(env, this, wdata); - reshape(env, this, wdata, - (*env)->GetIntField(env, target, componentIDs.x), - (*env)->GetIntField(env, target, componentIDs.y), - (*env)->GetIntField(env, target, componentIDs.width), - (*env)->GetIntField(env, target, componentIDs.height), - True); - } - AWT_UNLOCK(); -} - -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_removeTextComponentNative -(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - jobject target; - - if (JNU_IsNull(env, this)) { - return; - } - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || - wdata->winData.comp.widget== NULL || - wdata->winData.shell== NULL || - JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - if (!wdata->hasTextComponentNative) { - AWT_UNLOCK(); - return; - } - - wdata->bottom -= wdata->imHeight; - awtJNI_ChangeInsets(env, this, wdata); - wdata->imRemove = True; - reshape(env, this, wdata, - (*env)->GetIntField(env, target, componentIDs.x), - (*env)->GetIntField(env, target, componentIDs.y), - (*env)->GetIntField(env, target, componentIDs.width), - (*env)->GetIntField(env, target, componentIDs.height), - True); - - wdata->hasTextComponentNative = False; - wdata->imHeight = 0; - - AWT_UNLOCK(); -} /* ...removeTextComponentPeer() */ - -static Atom java_protocol = None; -static Atom motif_wm_msgs = None; - -static void im_callback(Widget shell, XtPointer client_data, XtPointer call_data) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - JNU_CallMethodByName(env, NULL, - (jobject)client_data, - "notifyIMMOptionChange", - "()V"); -} - -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_pSetIMMOption -(JNIEnv *env, jobject this, jstring option) -{ - char *coption; - char *empty = "InputMethod"; - char *menuItem; - jobject globalRef; - struct FrameData *wdata; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL || wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - globalRef = (jobject)JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.jniGlobalRef); - coption = (JNU_IsNull(env, option)) ? empty : (char *) JNU_GetStringPlatformChars(env, option, NULL); - if (java_protocol == None || motif_wm_msgs == None) { - java_protocol = XmInternAtom(awt_display, "_JAVA_IM_MSG", False); - motif_wm_msgs = XmInternAtom(awt_display, "_MOTIF_WM_MESSAGES", False); - } - XmAddProtocols (wdata->winData.shell, motif_wm_msgs, &java_protocol, 1); - XmAddProtocolCallback(wdata->winData.shell, motif_wm_msgs, java_protocol, im_callback, (XtPointer)globalRef); - - if ((menuItem = awt_util_makeWMMenuItem(coption, java_protocol))) { - XtVaSetValues(wdata->winData.shell, - XmNmwmMenu, - menuItem, - NULL); - free(menuItem); - } - if (coption != empty) - JNU_ReleaseStringPlatformChars(env, option, (const char *) coption); - AWT_FLUSH_UNLOCK(); -} - - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MEmbeddedFramePeer_synthesizeFocusInOut(JNIEnv *env, jobject this, - jboolean b) -{ - EmbeddedFrame *ef; - Boolean dummy; - - AWT_LOCK(); - ef = theEmbeddedFrameList; - while (ef != NULL) { - if ((*env)->IsSameObject(env, ef->javaRef, this)) { - XFocusChangeEvent xev; - xev.display = awt_display; - xev.serial = 0; - xev.type = b ? FocusIn : FocusOut; - xev.send_event = False; - xev.window = XtWindow(ef->embeddedFrame); - xev.mode = NotifyNormal; - xev.detail = NotifyNonlinear; - shellEH(ef->embeddedFrame, this, (XEvent*)&xev, &dummy); - break; - } - ef = ef->next; - } - AWT_UNLOCK(); -} - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MEmbeddedFramePeer_traverseOut(JNIEnv *env, jobject this, jboolean direction) -{ - struct FrameData *wdata; - - if (JNU_IsNull(env, this)) { - return; - } - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || - wdata->winData.comp.widget== NULL || - wdata->winData.shell== NULL) - { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - xembed_traverse_out(wdata, direction); - AWT_UNLOCK(); -} - - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MEmbeddedFramePeer_NEFcreate(JNIEnv *env, jobject this, - jobject parent, jlong handle) -{ -#undef MAX_ARGC -#define MAX_ARGC 40 - Arg args[MAX_ARGC]; - int32_t argc; - struct FrameData *wdata; - jobject target; - jstring warningString; - jboolean resizable; - jobject globalRef = awtJNI_CreateAndSetGlobalRef(env, this); - Widget innerCanvasW; /* form's child, parent of the outer canvas - drawing area */ - AwtGraphicsConfigDataPtr adata; - AwtGraphicsConfigDataPtr defConfig; - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - if (JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - wdata = ZALLOC(FrameData); - JNU_SetLongFieldFromPtr(env, this, mComponentPeerIDs.pData, wdata); - if (wdata == NULL) { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - AWT_UNLOCK(); - return; - } - - adata = getGraphicsConfigFromComponentPeer(env, this); - defConfig = getDefaultConfig(adata->awt_visInfo.screen); - - /* A variation on Netscape's hack for embedded frames: the client area - * of the browser is a Java Frame for parenting purposes, but really a - * Motif child window - */ - wdata->winData.flags |= W_IS_EMBEDDED; - - wdata->top = 0; - wdata->left = 0; - wdata->bottom = 0; - wdata->right = 0; - awtJNI_ChangeInsets(env, this, wdata); - - - wdata->isModal = 0; - wdata->isShowing = False; - wdata->shellResized = False; - wdata->canvasResized = False; - wdata->menuBarReset = False; - - resizable = (*env)->GetBooleanField(env, target, frameIDs.resizable); - - wdata->winData.shell = (Widget)handle; - awt_util_addEmbeddedFrame(wdata->winData.shell, globalRef); - - install_xembed((Widget)handle, wdata); - - setDeleteCallback(globalRef, wdata); - /* Establish resizability. For the case of not resizable, do not - yet set a fixed size here; we must wait until in the routine - sun_awt_motif_MWindowPeer_pReshape() after insets have been fixed. - This is because correction of the insets may affect shell size. - (See comments in shellEH() concerning correction of the insets. */ - /* - * Fix for BugTraq ID 4313607. - * Initial resizability will be set later in MWindowPeer_setResizable() - * called from init(). But the real changes will be made only if the new - * and old resizability values are different at that point, so we - * initialize isResizable with inverse value here to get the job done. - */ - wdata->isResizable = !resizable; - wdata->isFixedSizeSet = False; -#if 0 - if (resizable) { - awt_wm_setShellResizable(wdata); - } -#endif - - XtAddEventHandler(wdata->winData.shell, StructureNotifyMask | FocusChangeMask, - FALSE, (XtEventHandler)shellEH, globalRef); - - - argc = 0; - XtSetArg(args[argc], XmNvisual, defConfig->awt_visInfo.visual); argc++; - XtSetArg(args[argc], XmNcolormap, defConfig->awt_cmap); argc++; - XtSetArg(args[argc], XmNdepth, defConfig->awt_depth); argc++; - XtSetArg(args[argc], XmNmarginWidth, 0); argc++; - XtSetArg(args[argc], XmNmarginHeight, 0); argc++; - XtSetArg(args[argc], XmNhorizontalSpacing, 0); argc++; - XtSetArg(args[argc], XmNverticalSpacing, 0); argc++; - XtSetArg(args[argc], XmNscreen, - ScreenOfDisplay(awt_display, defConfig->awt_visInfo.screen)); argc++; - - - XtSetArg(args[argc], XmNresizePolicy, XmRESIZE_NONE); argc++; - - DASSERT(!(argc > MAX_ARGC)); - wdata->mainWindow = XmCreateForm(wdata->winData.shell, "main", args, argc); - - /* The widget returned by awt_canvas_create is a drawing area - (i.e., canvas) which is the child of another drawing area - parent widget. The parent is the drawing area within the - form just created. The child is an drawing area layer over - the entire frame window, including the form, any menu bar - and warning windows present, and also window manager stuff. - The top, bottom, left, and right fields in wdata maintain - the respective offsets between these two drawing areas. */ - - wdata->winData.comp.widget = awt_canvas_create((XtPointer)globalRef, - wdata->mainWindow, - "frame_", - -1, - -1, - True, - wdata, - defConfig); - - XtAddCallback(wdata->winData.comp.widget, - XmNresizeCallback, - outerCanvasResizeCB, - globalRef); - - - innerCanvasW = XtParent(wdata->winData.comp.widget); - XtVaSetValues(innerCanvasW, - XmNleftAttachment, XmATTACH_FORM, - XmNrightAttachment, XmATTACH_FORM, - NULL); - - - XtAddEventHandler(innerCanvasW, StructureNotifyMask, FALSE, - (XtEventHandler)innerCanvasEH, globalRef); - - /* No menu bar initially */ - wdata->menuBar = NULL; - wdata->mbHeight = 0; - - /* If a warning window (string) is needed, establish it now.*/ - warningString = - (*env)->GetObjectField(env, target, windowIDs.warningString); - - /* No warning window present */ - XtVaSetValues(innerCanvasW, - XmNtopAttachment, XmATTACH_FORM, - XmNbottomAttachment, XmATTACH_FORM, - NULL); - wdata->warningWindow = NULL; - wdata->wwHeight = 0; - - - awt_util_show(wdata->winData.comp.widget); - - AWT_FLUSH_UNLOCK(); -} /* MEmbeddedFramePeer_NEFcreate() */ - - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MEmbeddedFramePeer_pShowImpl(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL || - wdata->mainWindow == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - XtVaSetValues(wdata->winData.comp.widget, - XmNx, -(wdata->left), - XmNy, -(wdata->top), NULL); - - if (wdata->menuBar != 0) { - awt_util_show(wdata->menuBar); - } - - XtManageChild(wdata->mainWindow); - if (XtWindow(wdata->winData.shell) == None) { - XtRealizeWidget(wdata->winData.shell); - } - XtManageChild(wdata->winData.comp.widget); - XtSetMappedWhenManaged(wdata->winData.shell, True); - XtPopup(wdata->winData.shell, XtGrabNone); - wdata->isShowing = True; - - AWT_FLUSH_UNLOCK(); -} - -/* - * Create a local managed widget inside a given X window. - * We allocate a top-level shell and then reparent it into the - * given window id. - * - * This is used to take the X11 window ID that has been passed - * to us by our parent Navigator plugin and return a widget - * that can be used as the base for our Java EmbeddeFrame. - * - * Note that the ordering of the various calls is tricky here as - * we have to cope with the variations between 1.1.3, 1.1.6, - * and 1.2. - */ -JNIEXPORT jlong JNICALL -Java_sun_awt_motif_MEmbeddedFrame_getWidget( - JNIEnv *env, jclass clz, jlong winid) -{ - Arg args[40]; - int argc; - Widget w; - Window child, parent; - Visual *visual; - Colormap cmap; - int depth; - int ncolors; - - /* - * Create a top-level shell. Note that we need to use the - * AWT's own awt_display to initialize the widget. If we - * try to create a second X11 display connection the Java - * runtimes get very confused. - */ - AWT_LOCK(); - - argc = 0; - XtSetArg(args[argc], XtNsaveUnder, False); argc++; - XtSetArg(args[argc], XtNallowShellResize, False); argc++; - - /* the awt initialization should be done by now (awt_GraphicsEnv.c) */ - - getAwtData(&depth,&cmap,&visual,&ncolors,NULL); - - XtSetArg(args[argc], XtNvisual, visual); argc++; - XtSetArg(args[argc], XtNdepth, depth); argc++; - XtSetArg(args[argc], XtNcolormap, cmap); argc++; - - XtSetArg(args[argc], XtNwidth, 1); argc++; - XtSetArg(args[argc], XtNheight, 1); argc++; - /* The shell has to have relative coords of O,0? */ - XtSetArg(args[argc], XtNx, 0); argc++; - XtSetArg(args[argc], XtNy, 0); argc++; - - /* The shell widget starts out as a top level widget. - * Without intervention, it will be managed by the window - * manager and will be its own widow. So, until it is reparented, - * we don't map it. - */ - XtSetArg(args[argc], XtNmappedWhenManaged, False); argc++; - - w = XtAppCreateShell("AWTapp","XApplication", - vendorShellWidgetClass, - awt_display, - args, - argc); - XtRealizeWidget(w); - - /* - * Now reparent our new Widget into our Navigator window - */ - parent = (Window) winid; - child = XtWindow(w); - XReparentWindow(awt_display, child, parent, 0, 0); - XFlush(awt_display); - XSync(awt_display, False); - XtVaSetValues(w, XtNx, 0, XtNy, 0, NULL); - XFlush(awt_display); - XSync(awt_display, False); - - AWT_UNLOCK(); - - return (jlong)w; -} - -/* - * Make sure the given widget is mapped. - * - * This isn't necessary on JDK 1.1.5 but is needed on JDK 1.1.4 - */ -JNIEXPORT jint JNICALL -Java_sun_awt_motif_MEmbeddedFrame_mapWidget(JNIEnv *env, jclass clz, jlong widget) -{ - Widget w = (Widget)widget; - /* - * this is what JDK 1.1.5 does in MFramePeer.pShow. - */ - AWT_LOCK(); - XtSetMappedWhenManaged(w, True); - XtPopup(w, XtGrabNone); - AWT_UNLOCK(); - return (jint) 1; -} - - -JNIEXPORT jboolean JNICALL -Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedActive(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - Boolean res; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL || - wdata->mainWindow == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return False; - } - - res = isXEmbedActive(wdata); - AWT_UNLOCK(); - return res; - -} - -JNIEXPORT jboolean JNICALL -Java_sun_awt_motif_MEmbeddedFramePeer_isXEmbedApplicationActive(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - Boolean res; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL || - wdata->mainWindow == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return False; - } - - res = isXEmbedApplicationActive(wdata); - AWT_UNLOCK(); - return res; - -} - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MEmbeddedFramePeer_requestXEmbedFocus(JNIEnv *env, jobject this) -{ - struct FrameData *wdata; - - AWT_LOCK(); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL || - wdata->mainWindow == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - requestXEmbedFocus(wdata); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: setSaveUnder - * Signature: (Z)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_setSaveUnder -(JNIEnv *env, jobject this, jboolean state) -{ - struct FrameData *wdata; - jobject target; - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL || - JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - if (!JNU_IsNull(env, target)) - (*env)->DeleteLocalRef(env, target); - AWT_UNLOCK(); - return; - } - - XtVaSetValues(wdata->winData.shell, XmNsaveUnder, state, NULL); - - AWT_FLUSH_UNLOCK(); -} - - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: setFocusableWindow - * Signature: (Z)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_setFocusableWindow -(JNIEnv *env, jobject this, jboolean isFocusableWindow) -{ - struct FrameData *wdata; - jobject target; - - AWT_LOCK(); - - target = (*env)->GetObjectField(env, this, mComponentPeerIDs.target); - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || - wdata->winData.comp.widget == NULL || - wdata->winData.shell == NULL || - JNU_IsNull(env, target)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - if (!JNU_IsNull(env, target)) - (*env)->DeleteLocalRef(env, target); - AWT_UNLOCK(); - return; - } - - wdata->isFocusableWindow = isFocusableWindow; - - AWT_FLUSH_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: resetTargetGC - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MWindowPeer_resetTargetGC - (JNIEnv * env, jobject this, jobject target) -{ - (*env)->CallVoidMethod(env, target, windowIDs.resetGCMID); -} - - -/* - * Old, compatibility, backdoor for DT. This is a different - * implementation. It keeps the signature, but acts on - * awt_root_shell, not the frame passed as an argument. Note, that - * the code that uses the old backdoor doesn't work correctly with - * gnome session proxy that checks for WM_COMMAND when the window is - * firts mapped, because DT code calls this old backdoor *after* the - * frame is shown or it would get NPE with old AWT (previous - * implementation of this backdoor) otherwise. Old style session - * managers (e.g. CDE) that check WM_COMMAND only during session - * checkpoint should work fine, though. - * - * NB: The function name looks deceptively like a JNI native method - * name. It's not! It's just a plain function. - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_XsessionWMcommand(JNIEnv *env, jobject this, - jobject frame, jstring jcommand) -{ - const char *command; - XTextProperty text_prop; - char *c[1]; - int32_t status; - - AWT_LOCK(); - - if (awt_root_shell == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - if (XtWindow(awt_root_shell) == None) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - /* need to convert ctitle to CompoundText */ - command = (char *) JNU_GetStringPlatformChars(env, jcommand, NULL); - c[0] = (char *)command; - status = XmbTextListToTextProperty(awt_display, c, 1, - XStdICCTextStyle, &text_prop); - - if (status == Success || status > 0) { - XSetTextProperty(awt_display, XtWindow(awt_root_shell), - &text_prop, XA_WM_COMMAND); - if (text_prop.value != NULL) - XFree(text_prop.value); - } - - JNU_ReleaseStringPlatformChars(env, jcommand, command); - - AWT_UNLOCK(); - return; -} - - -/* - * New DT backdoor to set WM_COMMAND. New code should use this - * backdoor and call it *before* the first frame is shown so that - * gnome session proxy can correctly handle it. - * - * NB: The function name looks deceptively like a JNI native method - * name. It's not! It's just a plain function. - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_XsessionWMcommand_New(JNIEnv *env, jobjectArray jargv) -{ - static const char empty[] = ""; - - int argc; - const char **cargv; - XTextProperty text_prop; - int status; - int i; - - AWT_LOCK(); - - if (awt_root_shell == NULL) { - JNU_ThrowNullPointerException(env, "AWT root shell"); - AWT_UNLOCK(); - return; - } - - if (XtWindow(awt_root_shell) == None) { - JNU_ThrowNullPointerException(env, "AWT root shell is unrealized"); - AWT_UNLOCK(); - return; - } - - argc = (int)(*env)->GetArrayLength(env, jargv); - if (argc == 0) { - /* nothing to do */ - AWT_UNLOCK(); - return; - } - - /* array of C strings */ - cargv = (const char **)calloc(argc, sizeof(char *)); - if (cargv == NULL) { - JNU_ThrowOutOfMemoryError(env, "Unable to allocate cargv"); - AWT_UNLOCK(); - return; - } - - /* fill C array with platform chars of java strings */ - for (i = 0; i < argc; ++i) { - jstring js; - const char *cs; - - cs = NULL; - js = (*env)->GetObjectArrayElement(env, jargv, i); - if (js != NULL) { - cs = JNU_GetStringPlatformChars(env, js, NULL); - } - if (cs == NULL) { - cs = empty; - } - - cargv[i] = cs; - (*env)->DeleteLocalRef(env, js); - } - - /* grr, X prototype doesn't declare cargv as const, thought it really is */ - status = XmbTextListToTextProperty(awt_display, (char **)cargv, argc, - XStdICCTextStyle, &text_prop); - if (status < 0) { - switch (status) { - case XNoMemory: - JNU_ThrowOutOfMemoryError(env, - "XmbTextListToTextProperty: XNoMemory"); - break; - case XLocaleNotSupported: - JNU_ThrowInternalError(env, - "XmbTextListToTextProperty: XLocaleNotSupported"); - break; - case XConverterNotFound: - JNU_ThrowNullPointerException(env, - "XmbTextListToTextProperty: XConverterNotFound"); - break; - default: - JNU_ThrowInternalError(env, - "XmbTextListToTextProperty: unknown error"); - } - } else { - /* - * status == Success (i.e. 0) or - * status > 0 - a number of unconvertible characters - * (cannot happen for XStdICCTextStyle). - */ - XSetTextProperty(awt_display, XtWindow(awt_root_shell), - &text_prop, XA_WM_COMMAND); - } - - /* release platform chars */ - for (i = 0; i < argc; ++i) { - jstring js; - - if (cargv[i] == empty) - continue; - - js = (*env)->GetObjectArrayElement(env, jargv, i); - JNU_ReleaseStringPlatformChars(env, js, cargv[i]); - (*env)->DeleteLocalRef(env, js); - } - if (text_prop.value != NULL) - XFree(text_prop.value); - - AWT_UNLOCK(); - return; -} - -/* - * Class: java_awt_TrayIcon - * Method: initIDs - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_java_awt_TrayIcon_initIDs(JNIEnv *env , jclass clazz) -{ -} diff --git a/jdk/src/solaris/native/sun/awt/awt_XmDnD.c b/jdk/src/solaris/native/sun/awt/awt_XmDnD.c deleted file mode 100644 index 602af7a2df5..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_XmDnD.c +++ /dev/null @@ -1,2282 +0,0 @@ -/* - * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include -#include - -#include "jvm.h" -#include "jni.h" -#include "jni_util.h" -#include "jlong.h" - -#include "awt_DataTransferer.h" -#include "awt_XmDnD.h" - -#include "awt_p.h" - -#include "java_awt_Cursor.h" -#include "java_awt_dnd_DnDConstants.h" -#include "java_awt_event_MouseEvent.h" -#include "sun_awt_dnd_SunDragSourceContextPeer.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "sun_awt_motif_MDragSourceContextPeer.h" -#include "sun_awt_motif_MDropTargetContextPeer.h" - -#include -#include -/* - * Fix for 4285634. - * Include the private Motif header to enable access to lastEventState. - */ -#include - -#include "awt_Component.h" -#include "awt_Cursor.h" -#include "awt_AWTEvent.h" - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct CursorIDs cursorIDs; -extern struct ContainerIDs containerIDs; - -/* globals */ - - -/* forwards */ - -static void awt_XmDropProc(Widget, XtPointer, XmDropProcCallbackStruct*); -static void awt_XmDragProc(Widget, XtPointer, XmDragProcCallbackStruct*); - -static void awt_XmTransferProc(Widget, XtPointer, Atom*, Atom*, XtPointer, - unsigned long*, int32_t*); - -/* for XmDragContext callbacks etc ... */ -static void awt_XmDragEnterProc(Widget, XtPointer, - XmDropSiteEnterCallbackStruct*); -static void awt_XmDragMotionProc(Widget, XtPointer, - XmDragMotionCallbackStruct*); -static void awt_XmDragLeaveProc(Widget, XtPointer, - XmDropSiteLeaveCallbackStruct*); -static void awt_XmDropOperationChangedProc(Widget, XtPointer, - XmDropStartCallbackStruct*); -static void awt_XmDropFinishProc(Widget, XtPointer, - XmDropFinishCallbackStruct*); - -static unsigned char DnDConstantsToXm(jint operations); -static jint XmToDnDConstants(unsigned char operations); -static unsigned char selectOperation(unsigned char operations); - -static void flush_cache(JNIEnv* env); -static void cacheDropDone(Boolean dropDone); -static Boolean isDropDone(); - -static void setCursor(JNIEnv* env, Display* d, jobject c, jint type, Time t); - -static Atom MOTIF_DROP_ATOM = None; - -/* in canvas.c */ -extern jint getModifiers(uint32_t state, jint button, jint keyCode); - -/** - * static cache of DropTarget related info. - */ - -static struct { - Widget w; /* if NULL, cache invalid */ - - jobject peer; - jobject component; - - jobject dtcpeer; - - Widget dt; - - jlongArray targets; - Cardinal nTargets; - - Boolean dropDone; - int32_t transfersPending; - Widget transfer; - - jint dropAction; /* used only on JVM transfers */ - - Boolean flushPending; - - Window win; - uint32_t state; -} _cache; - -uint32_t -buttonToMask(uint32_t button) { - switch (button) { - case Button1: - return Button1Mask; - case Button2: - return Button2Mask; - case Button3: - return Button3Mask; - case Button4: - return Button4Mask; - case Button5: - return Button5Mask; - default: - return 0; - } -} - -/* Fix for 4215643: extract the values cached on drag start and send - ButtonRelease event to the window which originated the drag */ - -void -dragsource_track_release(Widget w, XtPointer client_data, - XEvent * event, Boolean * cont) -{ - DASSERT (event != NULL); - - if (_cache.win != None && - (buttonToMask(event->xbutton.button) & _cache.state)) { - - JNIEnv *env = (JNIEnv *) JNU_GetEnv(jvm, JNI_VERSION_1_2); - Window win = event->xbutton.window; - event->xbutton.window = _cache.win; - awt_put_back_event(env, event); - event->xbutton.window = win; - _cache.win = None; - _cache.state = 0; - XtRemoveEventHandler(w, ButtonReleaseMask, False, - dragsource_track_release, NULL); - } -} - -static void -cancel_drag(XtPointer client_data, XtIntervalId* id) { - Time time = awt_util_getCurrentServerTime(); - Widget dc = XmGetDragContext(awt_root_shell, time); - - if (dc != NULL) { - Boolean sourceIsExternal = True; - XtVaGetValues(dc, XmNsourceIsExternal, &sourceIsExternal, NULL); - if (!sourceIsExternal) { - XEvent xevent; - XmDragCancel(dc); - - /* - * When running the internal drag-and-drop event loop - * (see DragC.c:InitiatorMainLoop) Motif DnD uses XtAppNextEvent, - * that processes all timer callbacks and then returns the next X - * event from the queue. Motif DnD doesn't check if the drag - * operation is cancelled after XtAppNextEvent returns and processes - * the returned event. When the drag operation is cancelled the - * XmDragContext widget is destroyed and Motif will crash if the new - * event is dispatched to the destroyed XmDragContext. - * We cancel the drag operation in the timer callback, so we putback - * a dummy X event. This event will be returned from XtAppNextEvent - * and Motif DnD will safely exit from the internal event loop. - */ - xevent.type = LASTEvent; - xevent.xany.send_event = True; - xevent.xany.display = awt_display; - xevent.xany.window = XtWindow(awt_root_shell); - XPutBackEvent(awt_display, &xevent); - } - } -} - -#define DONT_CARE -1 - -static void -awt_popupCallback(Widget shell, XtPointer closure, XtPointer call_data) { - XtGrabKind grab_kind = XtGrabNone; - - if (call_data != NULL) { - grab_kind = *((XtGrabKind*)call_data); - } - - if (XmIsVendorShell(shell)) { - int input_mode; - XtVaGetValues(shell, XmNmwmInputMode, &input_mode, NULL); - switch (input_mode) { - case DONT_CARE: - case MWM_INPUT_MODELESS: - grab_kind = XtGrabNonexclusive; break; - case MWM_INPUT_PRIMARY_APPLICATION_MODAL: - case MWM_INPUT_SYSTEM_MODAL: - case MWM_INPUT_FULL_APPLICATION_MODAL: - grab_kind = XtGrabExclusive; break; - } - } - - if (grab_kind == XtGrabExclusive) { - /* - * We should cancel the drag on the toolkit thread. Otherwise, it can be - * called while the toolkit thread is waiting inside some drag callback. - * In this case Motif will crash when the drag callback returns. - */ - XtAppAddTimeOut(awt_appContext, 0L, cancel_drag, NULL); - } -} - -static XtInitProc xt_shell_initialize = NULL; - -static void -awt_ShellInitialize(Widget req, Widget new, ArgList args, Cardinal *num_args) { - XtAddCallback(new, XtNpopupCallback, awt_popupCallback, NULL); - (*xt_shell_initialize)(req, new, args, num_args); -} - -/* - * Fix for 4484572. - * Modify the 'initialize' routine for all ShellWidget instances, so that it - * will install an XtNpopupCallback that cancels the current drag operation. - * It is needed, since AWT doesn't have full control over all ShellWidget - * instances (e.g. XmPopupMenu internally creates and popups an XmMenuShell). - */ -static void -awt_set_ShellInitialize() { - static Boolean inited = False; - - DASSERT(!inited); - if (inited) { - return; - } - - xt_shell_initialize = shellWidgetClass->core_class.initialize; - shellWidgetClass->core_class.initialize = (XtInitProc)awt_ShellInitialize; - inited = True; -} - -/** - * global function to initialize this client as a Dynamic-only app. - * - * gets called once during toolkit initialization. - */ - -void awt_initialize_Xm_DnD(Display* dpy) { - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jclass clazz; - - XtVaSetValues(XmGetXmDisplay(dpy), - XmNdragInitiatorProtocolStyle, XmDRAG_DYNAMIC, - XmNdragReceiverProtocolStyle, XmDRAG_DYNAMIC, - NULL - ); - - MOTIF_DROP_ATOM = XInternAtom(dpy, _XA_MOTIF_DROP, False); - if (XSaveContext(dpy, MOTIF_DROP_ATOM, awt_convertDataContext, - (XPointer)NULL) == XCNOMEM) { - JNU_ThrowInternalError(env, ""); - return; - } - - /* No drop in progress. */ - cacheDropDone(True); - - /* - * Fix for BugTraq ID 4407057. - * Have to disable Motif default drag support, since it doesn't work - * reliably with our event dispatch mechanism. To do this we allow a drag - * operation only if it is registered on the awt_root_shell. - */ - awt_motif_enableSingleDragInitiator(awt_root_shell); - - awt_set_ShellInitialize(); - - /* - * load the Cursor stuff - */ - - clazz = (*env)->FindClass(env, "sun/awt/motif/MCustomCursor"); - - if (!JNU_IsNull(env, ((*env)->ExceptionOccurred(env)))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } -} - -typedef struct DSInfoRec { - Widget widget; - - Pixmap animation_mask; - Pixmap animation_pixmap; - int32_t animation_pixmap_depth; - unsigned char animation_style; - XtPointer client_data; - XtCallbackProc drag_proc; - XtCallbackProc drop_proc; - XRectangle *drop_rectangles; - unsigned char drop_site_activity; - unsigned char drop_site_operations; - unsigned char drop_site_type; - Atom *import_targets; - Cardinal num_drop_rectangles; - Cardinal num_import_targets; - - struct DSInfoRec* next; -} DSInfoRec, * DSInfoPtr; - -#define ARG_COUNT 14 - -/* - * Allocates DSInfoRect structure, retrieves all attributes of a Motif drop site - * registered on the specified widget and puts them into the allocated storage. - * The caller should free the storage after use. - */ -DSInfoPtr get_drop_site_info(Widget w) { - Arg arglist[ARG_COUNT]; - Cardinal argcount = 0; - DSInfoPtr info = ZALLOC(DSInfoRec); - - if (info == NULL) { - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - return NULL; - } - - XtSetArg(arglist[argcount], XmNanimationMask, - (XtArgVal)&info->animation_mask); argcount++; - XtSetArg(arglist[argcount], XmNanimationPixmap, - (XtArgVal)&info->animation_pixmap); argcount++; - XtSetArg(arglist[argcount], XmNanimationPixmapDepth, - (XtArgVal)&info->animation_pixmap_depth); argcount++; - XtSetArg(arglist[argcount], XmNanimationStyle, - (XtArgVal)&info->animation_style); argcount++; - XtSetArg(arglist[argcount], XmNclientData, - (XtArgVal)&info->client_data); argcount++; - XtSetArg(arglist[argcount], XmNdragProc, - (XtArgVal)&info->drag_proc); argcount++; - XtSetArg(arglist[argcount], XmNdropProc, - (XtArgVal)&info->drop_proc); argcount++; - XtSetArg(arglist[argcount], XmNdropSiteActivity, - (XtArgVal)&info->drop_site_activity); argcount++; - XtSetArg(arglist[argcount], XmNdropSiteOperations, - (XtArgVal)&info->drop_site_operations); argcount++; - XtSetArg(arglist[argcount], XmNdropSiteType, - (XtArgVal)&info->drop_site_type); argcount++; - XtSetArg(arglist[argcount], XmNnumDropRectangles, - (XtArgVal)&info->num_drop_rectangles); argcount++; - XtSetArg(arglist[argcount], XmNnumImportTargets, - (XtArgVal)&info->num_import_targets); argcount++; - DASSERT(argcount == ARG_COUNT - 2); - - XmDropSiteRetrieve(w, arglist, argcount); - - if (info->num_import_targets > 0) { - Atom *targets = NULL; - - info->import_targets = malloc(info->num_import_targets * sizeof(Atom)); - - if (info->import_targets == NULL) { - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - free(info); - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - return NULL; - } - - XtSetArg(arglist[0], XmNimportTargets, (XtArgVal)&targets); - XmDropSiteRetrieve(w, arglist, 1); - - memcpy(info->import_targets, targets, - info->num_import_targets * sizeof(Atom)); - } - - if (info->drop_site_type == XmDROP_SITE_SIMPLE && info->num_drop_rectangles > 0) { - XRectangle *rectangles = NULL; - info->drop_rectangles = - malloc(info->num_drop_rectangles * sizeof(XRectangle)); - - if (info->drop_rectangles == NULL) { - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - if (info->import_targets != NULL) { - free(info->import_targets); - } - free(info); - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - return NULL; - } - - XtSetArg(arglist[0], XmNdropRectangles, (XtArgVal)&rectangles); - XmDropSiteRetrieve(w, arglist, 1); - - memcpy(info->drop_rectangles, rectangles, - info->num_drop_rectangles * sizeof(XRectangle)); - } else /* if (info->drop_site_type == XmDROP_SITE_COMPOSITE) */ { - info->num_drop_rectangles = 1; - info->drop_rectangles = NULL; - } - - info->widget = w; - return info; -} - -/* - * Registers a Motif drop site on a widget given the information - * in the passed DSInfoRec structure. - */ -void restore_drop_site(DSInfoPtr info) { - Arg arglist[ARG_COUNT]; - Cardinal argcount = 0; - - if (info->drop_site_type == XmDROP_SITE_COMPOSITE) { - info->num_drop_rectangles = 1; - info->drop_rectangles = NULL; - } - - XtSetArg(arglist[argcount], XmNanimationMask, - (XtArgVal)info->animation_mask); argcount++; - XtSetArg(arglist[argcount], XmNanimationPixmap, - (XtArgVal)info->animation_pixmap); argcount++; - XtSetArg(arglist[argcount], XmNanimationPixmapDepth, - (XtArgVal)info->animation_pixmap_depth); argcount++; - XtSetArg(arglist[argcount], XmNanimationStyle, - (XtArgVal)info->animation_style); argcount++; - XtSetArg(arglist[argcount], XmNclientData, - (XtArgVal)info->client_data); argcount++; - XtSetArg(arglist[argcount], XmNdragProc, - (XtArgVal)info->drag_proc); argcount++; - XtSetArg(arglist[argcount], XmNdropProc, - (XtArgVal)info->drop_proc); argcount++; - XtSetArg(arglist[argcount], XmNdropRectangles, - (XtArgVal)info->drop_rectangles); argcount++; - XtSetArg(arglist[argcount], XmNdropSiteActivity, - (XtArgVal)info->drop_site_activity); argcount++; - XtSetArg(arglist[argcount], XmNdropSiteOperations, - (XtArgVal)info->drop_site_operations); argcount++; - XtSetArg(arglist[argcount], XmNdropSiteType, - (XtArgVal)info->drop_site_type); argcount++; - XtSetArg(arglist[argcount], XmNimportTargets, - (XtArgVal)info->import_targets); argcount++; - XtSetArg(arglist[argcount], XmNnumDropRectangles, - (XtArgVal)info->num_drop_rectangles); argcount++; - XtSetArg(arglist[argcount], XmNnumImportTargets, - (XtArgVal)info->num_import_targets); argcount++; - DASSERT(argcount == ARG_COUNT); - - XmDropSiteUnregister(info->widget); - XmDropSiteRegister(info->widget, arglist, argcount); - XmDropSiteConfigureStackingOrder(info->widget, (Widget)NULL, XmABOVE); -} - -#undef ARG_COUNT - -/* - * This routine ensures that hierarchy of Motif drop sites is not broken - * when a new drop site is registered or an existing drop site is - * unregistered. It unregisters all drop sites registered on the descendants of - * the specified widget, then registers or unregisters a Motif drop site on the - * root widget depending on the value of registerNewSite. After that the routine - * restores all the drop sites on the descendants. - * The routine recursively traverses through the hierarchy of descendant Motif - * drop sites and stores the info for all drop sites in a list. Then this list - * is used to restore all descendant drop sites. - * @param w current widget in the hierarchy traversal - * @param top root widget of the traversed hierarchy - the one to be inserted or - * removed - * @param list a list of DSInfoRec structures which keep drop site info for - * child drop sites - * @param registerNewSite if True a new Motif drop site should be registered on - * the root widget. If False an existing drop site of the root widget - * should be unregistered. - * @param isDropSite if True the widget being currently traversed has an - * associated Motif drop site. - */ -static DSInfoPtr -update_drop_site_hierarchy(Widget w, Widget top, DSInfoPtr list, - Boolean registerNewSite, Boolean isDropSite) { - - Widget parent = NULL; - Widget *children = NULL; - Cardinal num_children = 0; - - if (w == NULL || !XtIsObject(w) || w->core.being_destroyed) { - return NULL; - } - - /* Get the child drop sites of the widget.*/ - if (XmDropSiteQueryStackingOrder(w, &parent, &children, - &num_children) == 0) { - /* - * The widget is declared to be a drop site, but the query fails. - * The drop site must be corrupted. Truncate traversal. - */ - if (isDropSite) { - return NULL; - } - } else { - /* The query succeded, so the widget is definitely a drop site. */ - isDropSite = True; - } - - /* Traverse descendants of the widget, if it is composite. */ - if (XtIsComposite(w)) { - Cardinal i = 0; - - /* If it is not a drop site, check all its children. */ - if (!isDropSite) { - XtVaGetValues(w, XmNchildren, &children, - XmNnumChildren, &num_children, NULL); - } - - for (i = 0; i < num_children; i++) { - list = update_drop_site_hierarchy(children[i], top, list, - registerNewSite, isDropSite); - } - } - - /* The storage allocated by XmDropSiteQueryStackingOrder must be freed.*/ - if (isDropSite && children != NULL) { - XtFree((void*)children); - } - - if (w != top) { - if (isDropSite) { - /* Prepend drop site info to the list and unregister a drop site.*/ - DSInfoPtr info = get_drop_site_info(w); - - if (info != NULL) { - info->next = list; - list = info; - } - XmDropSiteUnregister(w); - } - } else { - /* Traversal is complete.*/ - DSInfoPtr info = list; - - if (isDropSite) { - XmDropSiteUnregister(w); - } - - if (registerNewSite) { - Arg args[10]; - unsigned int nargs = 0; - -#define SetArg(n, v) args[nargs].name = n; args[nargs++].value = (XtArgVal)(v); - - SetArg(XmNanimationStyle, XmDRAG_UNDER_NONE); - SetArg(XmNdragProc, awt_XmDragProc); - SetArg(XmNdropProc, awt_XmDropProc); - SetArg(XmNdropSiteActivity, XmDROP_SITE_ACTIVE); - - SetArg(XmNdropSiteOperations, - XmDROP_LINK | XmDROP_MOVE | XmDROP_COPY); - - SetArg(XmNimportTargets, NULL); - SetArg(XmNnumImportTargets, 0); - - SetArg(XmNdropSiteType, XmDROP_SITE_COMPOSITE); - SetArg(XmNdropRectangles, (XRectangle*)NULL); -#undef SetArg - - XmDropSiteRegister(w, args, nargs); - XmDropSiteConfigureStackingOrder(w, (Widget)NULL, XmABOVE); - } - - /* Go through the list and restore all child drop sites.*/ - while (info != NULL) { - restore_drop_site(info); - - info = info->next; - list->next = NULL; - if (list->import_targets != NULL) { - free(list->import_targets); - } - if (list->drop_rectangles != NULL) { - free(list->drop_rectangles); - } - free(list); - list = info; - } - } - return list; -} - -void -register_drop_site(Widget w) { - update_drop_site_hierarchy(w, w, NULL, True, False); -} - -void -unregister_drop_site(Widget w) { - update_drop_site_hierarchy(w, w, NULL, False, True); -} - -DECLARE_JAVA_CLASS(dSCClazz, "sun/awt/motif/MDragSourceContextPeer") -DECLARE_JAVA_CLASS(dTCClazz, "sun/awt/motif/MDropTargetContextPeer") - -static void -call_dSCenter(JNIEnv* env, jobject this, jint targetActions, - jint modifiers, jint x, jint y) { - DECLARE_VOID_JAVA_METHOD(dSCenter, dSCClazz, "dragEnter", "(IIII)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dSCenter, targetActions, modifiers, x, y); -} - -static void -call_dSCmotion(JNIEnv* env, jobject this, jint targetActions, - jint modifiers, jint x, jint y) { - DECLARE_VOID_JAVA_METHOD(dSCmotion, dSCClazz, "dragMotion", "(IIII)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dSCmotion, targetActions, - modifiers, x, y); -} - -static void -call_dSCchanged(JNIEnv* env, jobject this, jint targetActions, - jint modifiers, jint x, jint y) { - DECLARE_VOID_JAVA_METHOD(dSCchanged, dSCClazz, "operationChanged", - "(IIII)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dSCchanged, targetActions, - modifiers, x, y); -} - -static void -call_dSCmouseMoved(JNIEnv* env, jobject this, jint targetActions, - jint modifiers, jint x, jint y) { - DECLARE_VOID_JAVA_METHOD(dSCmouseMoved, dSCClazz, "dragMouseMoved", - "(IIII)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dSCmouseMoved, targetActions, - modifiers, x, y); -} - -static void -call_dSCexit(JNIEnv* env, jobject this, jint x, jint y) { - DECLARE_VOID_JAVA_METHOD(dSCexit, dSCClazz, "dragExit", "(II)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dSCexit, x, y); -} - -static void -call_dSCddfinished(JNIEnv* env, jobject this, jboolean success, - jint operations, jint x, jint y) { - DECLARE_VOID_JAVA_METHOD(dSCddfinished, dSCClazz, "dragDropFinished", - "(ZIII)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dSCddfinished, success, operations, x, y); -} - -static jobject -call_dTCcreate(JNIEnv* env) { - DECLARE_STATIC_OBJECT_JAVA_METHOD(dTCcreate, dTCClazz, - "createMDropTargetContextPeer", - "()Lsun/awt/motif/MDropTargetContextPeer;"); - return (*env)->CallStaticObjectMethod(env, clazz, dTCcreate); -} - -static jint -call_dTCenter(JNIEnv* env, jobject this, jobject component, jint x, jint y, - jint dropAction, jint actions, jlongArray formats, - jlong nativeCtxt) { - DECLARE_JINT_JAVA_METHOD(dTCenter, dTCClazz, "handleEnterMessage", - "(Ljava/awt/Component;IIII[JJ)I"); - DASSERT(!JNU_IsNull(env, this)); - return (*env)->CallIntMethod(env, this, dTCenter, component, x, y, dropAction, - actions, formats, nativeCtxt); -} - -static void -call_dTCexit(JNIEnv* env, jobject this, jobject component, jlong nativeCtxt) { - DECLARE_VOID_JAVA_METHOD(dTCexit, dTCClazz, "handleExitMessage", - "(Ljava/awt/Component;J)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dTCexit, component, nativeCtxt); -} - -static jint -call_dTCmotion(JNIEnv* env, jobject this, jobject component, jint x, jint y, - jint dropAction, jint actions, jlongArray formats, - jlong nativeCtxt) { - DECLARE_JINT_JAVA_METHOD(dTCmotion, dTCClazz, "handleMotionMessage", - "(Ljava/awt/Component;IIII[JJ)I"); - DASSERT(!JNU_IsNull(env, this)); - return (*env)->CallIntMethod(env, this, dTCmotion, component, x, y, - dropAction, actions, formats, nativeCtxt); -} - -static void -call_dTCdrop(JNIEnv* env, jobject this, jobject component, jint x, jint y, - jint dropAction, jint actions, jlongArray formats, - jlong nativeCtxt) { - DECLARE_VOID_JAVA_METHOD(dTCdrop, dTCClazz, "handleDropMessage", - "(Ljava/awt/Component;IIII[JJ)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dTCdrop, component, x, y, - dropAction, actions, formats, nativeCtxt); -} - -static void -call_dTCnewData(JNIEnv* env, jobject this, jlong format, jobject type, - jbyteArray data) { - DECLARE_VOID_JAVA_METHOD(dTCnewData, dTCClazz, "newData", - "(JLjava/lang/String;[B)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dTCnewData, format, type, data); -} - -static void -call_dTCtxFailed(JNIEnv* env, jobject this, jlong format) { - DECLARE_VOID_JAVA_METHOD(dTCtxFailed, dTCClazz, "transferFailed", "(J)V"); - DASSERT(!JNU_IsNull(env, this)); - (*env)->CallVoidMethod(env, this, dTCtxFailed, format); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: addNativeDropTarget - * Signature: (Ljava/awt/dnd/DropTarget;)V - */ - -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_addNativeDropTarget - (JNIEnv *env, jobject this, jobject droptarget) -{ - struct ComponentData* cdata = (struct ComponentData *)NULL; - DropSitePtr dropsite = (DropSitePtr)NULL; - - if (JNU_IsNull(env, droptarget)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - - AWT_LOCK(); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - /* introduce a new Component as a root of a set of DropTargets */ - - if ((dropsite = cdata->dsi) == (DropSitePtr)NULL) { - dropsite = cdata->dsi = (DropSitePtr)ZALLOC(DropSiteInfo); - - if (dropsite == (DropSitePtr)NULL) { - JNU_ThrowOutOfMemoryError (env, "OutOfMemoryError"); - AWT_UNLOCK (); - return; - } - - dropsite->component = (*env)->NewGlobalRef - (env, (*env)->GetObjectField(env, this, - mComponentPeerIDs.target)); - dropsite->isComposite = True; - - /* - * Fix for Bug Id 4389284. - * Revalidate drop site hierarchy so that this drop site doesn't obscure - * drop sites that are already registered on its children. - */ - register_drop_site(cdata->widget); - } - - dropsite->dsCnt++; - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MComponentPeer - * Method: removeNativeDropTarget - * Signature: (Ljava/awt/dnd/DropTarget;)V - */ - -JNIEXPORT void JNICALL Java_sun_awt_motif_MComponentPeer_removeNativeDropTarget - (JNIEnv *env, jobject this, jobject droptarget) -{ - struct ComponentData* cdata; - DropSitePtr dropsite; - - if (JNU_IsNull(env, droptarget)) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return; - } - - AWT_LOCK(); - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (cdata == NULL || cdata->widget == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - if ((dropsite = cdata->dsi) == (DropSitePtr)NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - AWT_UNLOCK(); - return; - } - - dropsite->dsCnt--; - if (dropsite->dsCnt == 0) { - /* - * Fix for Bug Id 4411368. - * Revalidate drop site hierarchy to prevent crash when a composite drop - * site is unregistered before its child drop sites. - */ - unregister_drop_site(cdata->widget); - - (*env)->DeleteGlobalRef(env, dropsite->component); - - free((void *)(cdata->dsi)); - cdata->dsi = (DropSitePtr)NULL; - } - - AWT_UNLOCK(); -} - -/** - * - */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MDragSourceContextPeer_setNativeCursor(JNIEnv *env, - jobject this, - jlong nativeCtxt, - jobject cursor, - jint type) { - /* - * NOTE: no need to synchronize on awt_lock here, since we should have - * already acquired it in MDragSourceContextPeer.setCursor(). - */ - setCursor(env, awt_display, cursor, type, CurrentTime); -} - -/** - * - */ - -JNIEXPORT jlong JNICALL -Java_sun_awt_motif_MDropTargetContextPeer_startTransfer(JNIEnv *env, - jobject this, - jlong dragContextVal, - jlong atom) { - XmDropTransferEntryRec trec; - Widget dropTransfer; - Arg args[3]; - Cardinal nargs = 0; - jboolean isCopy; - Widget dragContext = (Widget)jlong_to_ptr(dragContextVal); - - AWT_LOCK(); - - trec.target = (Atom) atom; - trec.client_data = (XtPointer)trec.target; - - -#define SetArg(n, v) args[nargs].name = n; args[nargs++].value = (XtArgVal)(v); - - SetArg(XmNdropTransfers, &trec); - SetArg(XmNnumDropTransfers, 1 ); - SetArg(XmNtransferProc, awt_XmTransferProc); - -#undef SetArg - - _cache.transfer = dropTransfer = - XmDropTransferStart(dragContext, args, nargs); - - _cache.transfersPending++; - - AWT_NOTIFY_ALL(); - AWT_UNLOCK(); - - return ptr_to_jlong(dropTransfer); -} - -/** - * - */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MDropTargetContextPeer_addTransfer(JNIEnv *env, - jobject this, - jlong dropTransferVal, - jlong atom) { - XmDropTransferEntryRec trec; - jboolean isCopy; - Widget dropTransfer=(Widget)jlong_to_ptr(dropTransferVal); - trec.target = (Atom)atom; - trec.client_data = (XtPointer)trec.target; - - AWT_LOCK(); - - XmDropTransferAdd(dropTransfer, &trec, 1); - - _cache.transfersPending++; - - AWT_NOTIFY_ALL(); - AWT_UNLOCK(); -} - -/** - * - */ - -JNIEXPORT void JNICALL Java_sun_awt_motif_MDropTargetContextPeer_dropDone - (JNIEnv *env, jobject this, jlong dragContextVal, jlong dropTransferVal, - jboolean isLocal, jboolean success, jint dropAction) -{ - Widget dropTransfer = (Widget)jlong_to_ptr(dropTransferVal); - Widget dragContext = (Widget)jlong_to_ptr(dragContextVal); - - AWT_LOCK(); - - if (_cache.w == (Widget)NULL) { - AWT_UNLOCK(); - return; - } - - if (!isDropDone()) { - if (dropTransfer != (jlong)NULL) { - XtVaSetValues(dropTransfer, - XmNtransferStatus, - success == JNI_TRUE - ? XmTRANSFER_SUCCESS : XmTRANSFER_FAILURE, - NULL - ); - } else { - /* - * start a transfer that notifies failure - * this causes src side callbacks to be processed. - * However, you cannot pass an a success, so the workaround is - * to set _cache.transferSuccess to the proper value and read it - * on the other side. - */ - - - Arg arg; - - /* - * this is the workaround code - */ - _cache.transfer = NULL; - _cache.dropAction = dropAction; - - /* - * End workaround code - */ - - arg.name = XmNtransferStatus; - arg.value = (XtArgVal)(success == JNI_TRUE ? XmTRANSFER_SUCCESS - : XmTRANSFER_FAILURE - ); - - XmDropTransferStart(dragContext, &arg, 1); - } - - /* - * bugid# 4146717 - * - * If this is a local tx, then we never exec the awt_XmTransferProc, - * thus we need to flush the cache here as it is our only chance, - * otherwise we leave a mess for the next operation to fail on .... - * - */ - - if (isLocal == JNI_TRUE) - flush_cache(env); /* flush now, last chance */ - else - _cache.flushPending = True; /* flush pending in transfer proc */ - } - - cacheDropDone(True); - - AWT_NOTIFY_ALL(); - AWT_UNLOCK(); -} - - -static Boolean exitIdleProc = False; -static int32_t x_root = -1, y_root = -1; - -extern void waitForEvents(JNIEnv *env, int32_t fdXPipe, int32_t fdAWTPipe); - -static jint convertModifiers(uint32_t modifiers) { - return getModifiers(modifiers, 0, 0); -} - -static void -checkMouseMoved(XtPointer client_data) { - Window rootWindow, childWindow; - int32_t xw, yw, xr, yr; - uint32_t modifiers; - - /* - * When dragging over the root window XmNdragMotionCallback is not called - * (Motif feature). - * Since there is no legal way to receive MotionNotify events during drag - * we have to query for mouse position periodically. - */ - if (XQueryPointer(awt_display, XDefaultRootWindow(awt_display), - &rootWindow, &childWindow, - &xr, &yr, &xw, &yw, &modifiers) && - childWindow == None && (xr != x_root || yr != y_root)) { - - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject)client_data; - - call_dSCmouseMoved(env, this, XmDROP_NOOP, convertModifiers(modifiers), - xr, yr); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - x_root = xr; - y_root = yr; - } -} - -static void IdleProc(XtPointer client_data, XtIntervalId* id) { - if (!exitIdleProc) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - /* The pipe where X events arrive */ - int32_t fdXPipe = ConnectionNumber(awt_display) ; - - /* - * Motif DnD internal event loop doesn't process the events - * from the AWT putback event queue. So we pass -1 instead - * of the AWT read pipe descriptor to disable checking of - * the putback event queue. - */ - waitForEvents(env, fdXPipe, -1); - - checkMouseMoved(client_data); - /* Reschedule the timer callback */ - XtAppAddTimeOut(awt_appContext, AWT_DND_POLL_INTERVAL / 10, - IdleProc, client_data); - } -} - -static void RemoveIdleProc(Widget w, - XtPointer client_data, - XmDropFinishCallbackStruct* cbstruct) { - exitIdleProc = True; -} - -/** - * - */ - -JNIEXPORT jlong JNICALL -Java_sun_awt_motif_MDragSourceContextPeer_startDrag(JNIEnv *env, - jobject this, - jobject component, - jobject transferable, - jobject trigger, - jobject cursor, - jint ctype, - jint actions, - jlongArray formats, - jobject formatMap) { - Arg args[32]; - Cardinal nargs = 0; - jobject dscp = (*env)->NewGlobalRef(env, this); - jbyteArray bdata = - (jbyteArray)(*env)->GetObjectField(env, trigger, awtEventIDs.bdata); - Atom* targets = NULL; - jlong* jTargets; - jsize nTargets; - Widget dc; - XtCallbackRec dsecbr[2]; - XtCallbackRec dmcbr[2]; - XtCallbackRec occbr[2]; - XtCallbackRec dslcbr[2]; - XtCallbackRec dscbr[2]; - XtCallbackRec ddfcbr[2]; - XEvent* xevent; - unsigned char xmActions = DnDConstantsToXm(actions); - jboolean isCopy=JNI_TRUE; - awt_convertDataCallbackStruct* structPtr; - -#ifndef _LP64 /* Atom and jlong are different sizes in the 32-bit build */ - jsize i; - jlong* saveJTargets; - Atom* saveTargets; -#endif - - if (xmActions == XmDROP_NOOP) { - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Invalid source actions."); - return ptr_to_jlong(NULL); - } - - if (JNU_IsNull(env, formats)) { - JNU_ThrowNullPointerException(env, "formats"); - return ptr_to_jlong(NULL); - } - - if (JNU_IsNull(env, bdata)) { - JNU_ThrowNullPointerException(env, - "null native data for trigger event"); - return ptr_to_jlong(NULL); - } - - nTargets = (*env)->GetArrayLength(env, formats); - - /* - * In debug build GetLongArrayElements aborts with assertion on an empty - * array. - */ - if (nTargets > 0) { - jTargets = (*env)->GetLongArrayElements(env, formats, &isCopy); - if (!JNU_IsNull(env, ((*env)->ExceptionOccurred(env)))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - if (jTargets != NULL) { - targets = (Atom *)malloc(nTargets * sizeof(Atom)); - if (targets != NULL) { -#ifdef _LP64 - memcpy(targets, jTargets, nTargets * sizeof(Atom)); -#else - saveJTargets = jTargets; - saveTargets = targets; - for (i = 0; i < nTargets; i++, targets++, jTargets++) { - *targets = (Atom)*jTargets; - } - jTargets = saveJTargets; - targets = saveTargets; -#endif - } - (*env)->ReleaseLongArrayElements(env, formats, jTargets, JNI_ABORT); - } - } - if (targets == NULL) { - nTargets = 0; - } - -#define SetCB(cbr, cb, cl) cbr[0].callback = (XtCallbackProc)cb; cbr[0].closure = (XtPointer)cl; cbr[1].callback = (XtCallbackProc)NULL; cbr[1].closure = (XtPointer)NULL - -#define SetArg(n, v) args[nargs].name = n; args[nargs++].value = (XtArgVal)(v); - - SetCB(dsecbr, awt_XmDragEnterProc, dscp); - SetCB(dmcbr, awt_XmDragMotionProc, dscp); - SetCB(occbr, awt_XmDropOperationChangedProc, dscp); - SetCB(dslcbr, awt_XmDragLeaveProc, dscp); - SetCB(ddfcbr, awt_XmDropFinishProc, dscp); - - SetArg(XmNblendModel, XmBLEND_NONE ); - SetArg(XmNdragOperations, xmActions ); - /* No incremental transfer */ - SetArg(XmNconvertProc, awt_convertData ); - SetArg(XmNdropSiteEnterCallback, dsecbr ); - SetArg(XmNdragMotionCallback, dmcbr ); - SetArg(XmNoperationChangedCallback, occbr ); - SetArg(XmNdropSiteLeaveCallback, dslcbr ); - SetArg(XmNdropFinishCallback, ddfcbr ); - SetArg(XmNexportTargets, targets ); - SetArg(XmNnumExportTargets, (Cardinal)nTargets ); - - { - jsize len = (*env)->GetArrayLength(env, bdata); - if (len <= 0) { - free(targets); - return ptr_to_jlong(NULL); - } - - xevent = calloc(1, len); - - if (xevent == NULL) { - free(targets); - JNU_ThrowOutOfMemoryError(env, ""); - return ptr_to_jlong(NULL); - } - - (*env)->GetByteArrayRegion(env, bdata, 0, len, (jbyte *)xevent); - - DASSERT(JNU_IsNull(env, (*env)->ExceptionOccurred(env))); - } - - if (xevent->type != ButtonPress && - xevent->type != ButtonRelease && - xevent->type != KeyRelease && - xevent->type != KeyPress && - xevent->type != MotionNotify) { - - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "A drag can only be initiated in response to an InputEvent."); - free(xevent); - free(targets); - return ptr_to_jlong(NULL); - } - - /* This call causes an UnsatisfiedLinkError on Linux. - * This function is a no-op for Motif 2.1. - * Since Linux only links against Motif 2.1, we can safely remove - * this function altogether from the Linux build. - * bchristi 1/22/2001 - */ - -#ifdef __solaris__ - awt_motif_adjustDragTriggerEvent(xevent); -#endif - - AWT_LOCK(); - - /* - * Fix for BugTraq ID 4357905. - * Drop is processed asynchronously on the event dispatch thread. - * Reject all drag attempts until the current drop is done. - */ - if (!isDropDone()) { - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Drop transfer in progress."); - free(xevent); - free(targets); - AWT_UNLOCK(); - return ptr_to_jlong(NULL); - } - - if (XFindContext(awt_display, MOTIF_DROP_ATOM, awt_convertDataContext, - (XPointer*)&structPtr) == XCNOMEM || structPtr != NULL) { - free(xevent); - free(targets); - AWT_UNLOCK(); - return ptr_to_jlong(NULL); - } - - structPtr = calloc(1, sizeof(awt_convertDataCallbackStruct)); - if (structPtr == NULL) { - free(xevent); - free(targets); - JNU_ThrowOutOfMemoryError(env, ""); - AWT_UNLOCK(); - return ptr_to_jlong(NULL); - } - - structPtr->source = (*env)->NewGlobalRef(env, component); - structPtr->transferable = (*env)->NewGlobalRef(env, transferable); - structPtr->formatMap = (*env)->NewGlobalRef(env, formatMap); - structPtr->formats = (*env)->NewGlobalRef(env, formats); - - if (XSaveContext(awt_display, MOTIF_DROP_ATOM, awt_convertDataContext, - (XPointer)structPtr) == XCNOMEM) { - free(structPtr); - free(xevent); - free(targets); - AWT_UNLOCK(); - return ptr_to_jlong(NULL); - } - - dc = XmDragStart(awt_root_shell, xevent, args, nargs); - - /* Fix for 4215643: remember the window corresponding to the drag source - and the button mask after the event which triggered drag start */ - - if (xevent->type == ButtonPress || xevent->type == MotionNotify) { - _cache.win = xevent->xbutton.window; - if (xevent->type == ButtonPress) { - _cache.state = buttonToMask(xevent->xbutton.button); - } else { - _cache.state = xevent->xmotion.state & (Button1Mask | Button2Mask); - } - XtAddEventHandler(dc, ButtonReleaseMask, False, - dragsource_track_release, NULL); - } - - free(targets); - - if (dc != (Widget)NULL) { - setCursor(env, awt_display, cursor, ctype, xevent->xbutton.time); - } - - free(xevent); - - /* - * With the new synchronization model we don't release awt_lock - * in the DragContext callbacks. During drag-n-drop operation - * the events processing is performed not by our awt_MToolkit_loop, - * but by internal Motif InitiatorMainLoop, which returns only - * when the operation is completed. So our polling mechanism doesn't - * have a chance to execute and even if there are no events in - * the queue AWT_LOCK will still be held by the Toolkit thread - * and so other threads will likely be blocked on it. - * - * The solution is to schedule a timer callback which checks - * for events and if the queue is empty releases AWT_LOCK and polls - * the X pipe for some time, then acquires AWT_LOCK back again - * and reschedules itself. - */ - if (dc != NULL) { - exitIdleProc = False; - XtAddCallback(dc, XmNdragDropFinishCallback, - (XtCallbackProc)RemoveIdleProc, NULL); - XtAppAddTimeOut(awt_appContext, AWT_DND_POLL_INTERVAL / 10, - IdleProc, (XtPointer)dscp); - } - - AWT_UNLOCK(); - - return ptr_to_jlong(dc); - -#undef SetArg -#undef SetCB -} - -/*****************************************************************************/ - -/** - * - */ - -static void setCursor(JNIEnv* env, Display* dpy, jobject cursor, jint type, - Time time) -{ - Cursor xcursor = None; - - if (JNU_IsNull(env, cursor)) return; - - XChangeActivePointerGrab(dpy, - ButtonPressMask | - ButtonMotionMask | - ButtonReleaseMask | - EnterWindowMask | - LeaveWindowMask, - getCursor(env, cursor), - time - ); - - XSync(dpy, False); -} - -/** - * Update the cached targets for this widget - */ - -static Boolean updateCachedTargets(JNIEnv* env, Widget dt) { - Atom* targets = (Atom*)NULL; - Cardinal nTargets = (Cardinal)0; - Arg args[2]; - - /* - * Get the targets for this component - */ - args[0].name = XmNexportTargets; args[0].value = (XtArgVal)&targets; - args[1].name = XmNnumExportTargets; args[1].value = (XtArgVal)&nTargets; - XtGetValues(_cache.dt = dt, args, 2); - - /* - * Free the previous targets if there were any - */ - if (!JNU_IsNull(env, _cache.targets)) { - (*env)->DeleteGlobalRef(env, _cache.targets); - _cache.targets = (jlongArray)NULL; - } - - _cache.nTargets = nTargets; - - /* - * If the widget has targets (atoms) then copy them to the cache - */ - if (nTargets > 0) { - jboolean isCopy; - jlong* jTargets; - -#ifndef _LP64 /* Atom and jlong are different sizes in the 32-bit build */ - jlong* saveJTargets; - Cardinal i; -#endif - - _cache.targets = (*env)->NewLongArray(env, nTargets); - if (_cache.targets == NULL) { - _cache.nTargets = 0; - return False; - } - - _cache.targets = (*env)->NewGlobalRef(env, _cache.targets); - if (_cache.targets == NULL) { - _cache.nTargets = 0; - return False; - } - - jTargets = (*env)->GetLongArrayElements(env, _cache.targets, &isCopy); - if (jTargets == NULL) { - (*env)->DeleteGlobalRef(env, _cache.targets); - _cache.targets = NULL; - _cache.nTargets = 0; - return False; - } - -#ifdef _LP64 - memcpy(jTargets, targets, nTargets * sizeof(Atom)); -#else - saveJTargets = jTargets; - for (i = 0; i < nTargets; i++, jTargets++, targets++) { - *jTargets = (*targets & 0xFFFFFFFFLU); - } - jTargets = saveJTargets; -#endif - - (*env)->ReleaseLongArrayElements(env, _cache.targets, jTargets, 0); - return True; - } - - return False; -} - - -/** - * - */ - -static void flush_cache(JNIEnv* env) { - _cache.w = (Widget)NULL; - _cache.dt = (Widget)NULL; - - (*env)->DeleteGlobalRef(env, _cache.peer); - _cache.peer = (jobject)NULL; - - (*env)->DeleteGlobalRef(env, _cache.component); - _cache.component = (jobject)NULL; - - if (_cache.dtcpeer != (jobject)NULL) { - (*env)->DeleteGlobalRef(env, _cache.dtcpeer); - - _cache.dtcpeer = (jobject)NULL; - } - - _cache.nTargets = (Cardinal)0; - if (_cache.targets != (jlongArray)NULL) { - (*env)->DeleteGlobalRef(env, _cache.targets); - _cache.targets = (jlongArray)NULL; - } - - _cache.transfersPending = 0; - _cache.flushPending = False; - _cache.transfer = (Widget)NULL; - cacheDropDone(True); -} - -/** - * - */ - -static void update_cache(JNIEnv* env, Widget w, Widget dt) { - if(w != _cache.w) { - struct ComponentData* cdata = (struct ComponentData *)NULL; - Arg args[1] = - {{ XmNuserData, (XtArgVal)&_cache.peer}}; - - flush_cache(env); - - if (w == (Widget)NULL) return; - - XtGetValues(w, args, 1); - - if (JNU_IsNull(env, _cache.peer)) { - _cache.w = NULL; - - return; - } - - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, _cache.peer, mComponentPeerIDs.pData); - - if (cdata == NULL || - cdata->widget != w || - cdata->dsi == (DropSitePtr)NULL) { - _cache.w = NULL; - - return; - } - - _cache.w = w; - _cache.component = (*env)->NewGlobalRef(env, cdata->dsi->component); - _cache.peer = (*env)->NewGlobalRef(env, _cache.peer); - /* SECURITY: OK to call this on privileged thread - peer is secure */ - { - jobject dtcpeer = call_dTCcreate(env); - if (!JNU_IsNull(env, dtcpeer)) { - _cache.dtcpeer = (*env)->NewGlobalRef(env, dtcpeer); - (*env)->DeleteLocalRef(env, dtcpeer); - } else { - _cache.dtcpeer = NULL; - } - } - - _cache.transfersPending = 0; - cacheDropDone(True); - } - - if (_cache.w != (Widget)NULL) updateCachedTargets(env, dt); -} - - -/** - * - */ - -static void -cacheDropDone(Boolean dropDone) { - _cache.dropDone = dropDone; -} - -static Boolean -isDropDone() { - return _cache.dropDone; -} - -/** - * - */ - -static jint XmToDnDConstants(unsigned char operations) { - jint src = java_awt_dnd_DnDConstants_ACTION_NONE; - - if (operations & XmDROP_MOVE) src |= java_awt_dnd_DnDConstants_ACTION_MOVE; - if (operations & XmDROP_COPY) src |= java_awt_dnd_DnDConstants_ACTION_COPY; - if (operations & XmDROP_LINK) src |= java_awt_dnd_DnDConstants_ACTION_LINK; - - return src; -} - -static unsigned char selectOperation(unsigned char operations) { - if (operations & XmDROP_MOVE) return XmDROP_MOVE; - if (operations & XmDROP_COPY) return XmDROP_COPY; - if (operations & XmDROP_LINK) return XmDROP_LINK; - - return XmDROP_NOOP; -} - -/** - * - */ - -static unsigned char DnDConstantsToXm(jint actions) { - unsigned char ret = XmDROP_NOOP; - - if (actions & java_awt_dnd_DnDConstants_ACTION_COPY) ret |= XmDROP_COPY; - if (actions & java_awt_dnd_DnDConstants_ACTION_MOVE) ret |= XmDROP_MOVE; - if (actions & java_awt_dnd_DnDConstants_ACTION_LINK) ret |= XmDROP_LINK; - - return ret; -} - -/** - * - */ - -typedef struct DragExitProcStruct { - XtIntervalId timerId; - jobject dtcpeer; /* global reference */ - jobject component; /* global reference */ - jlong dragContext; /* pointer */ -} DragExitProcStruct; - -static DragExitProcStruct pending_drag_exit_data = - { (XtIntervalId)0, NULL, NULL, (jlong)0 }; - -static void drag_exit_proc(XtPointer client_data, XtIntervalId* id) { - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - DASSERT(!JNU_IsNull(env, pending_drag_exit_data.dtcpeer)); - DASSERT(!JNU_IsNull(env, pending_drag_exit_data.component)); - DASSERT(pending_drag_exit_data.dragContext != NULL); - - if (pending_drag_exit_data.timerId != (XtIntervalId)0) { - if (id == NULL) { - XtRemoveTimeOut(pending_drag_exit_data.timerId); - } - if (id == NULL || pending_drag_exit_data.timerId == *id) { - - /* SECURITY: OK to call this on privileged thread - - peer is secure */ - call_dTCexit(env, pending_drag_exit_data.dtcpeer, - pending_drag_exit_data.component, - pending_drag_exit_data.dragContext); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - } - - /* cleanup */ - (*env)->DeleteGlobalRef(env, pending_drag_exit_data.dtcpeer); - (*env)->DeleteGlobalRef(env, pending_drag_exit_data.component); - - memset(&pending_drag_exit_data, 0, sizeof(DragExitProcStruct)); -} - -static void awt_XmDragProc(Widget w, XtPointer closure, - XmDragProcCallbackStruct* cbstruct) -{ - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject component = (jobject)NULL; - jint src = java_awt_dnd_DnDConstants_ACTION_NONE; - jint usrAction = java_awt_dnd_DnDConstants_ACTION_NONE; - jint ret = java_awt_dnd_DnDConstants_ACTION_NONE; - unsigned char srcOps = XmDROP_NOOP; - - /* - * Fix for BugTraq ID 4395290. - * We should dispatch any pending java upcall right now - * to keep the order of upcalls. - */ - if (pending_drag_exit_data.timerId != (XtIntervalId)0) { - drag_exit_proc(NULL, NULL); - } - - /* - * Fix for BugTraq ID 4357905. - * Drop is processed asynchronously on the event dispatch thread. - * We reject other drop attempts to protect the SunDTCP context - * from being overwritten by an upcall before the drop is done. - */ - if (!isDropDone()) { - cbstruct->operation = XmDROP_NOOP; - cbstruct->dropSiteStatus = XmINVALID_DROP_SITE; - return; - } - - if (cbstruct->dragContext == NULL) { - cbstruct->operation = XmDROP_NOOP; - cbstruct->dropSiteStatus = XmINVALID_DROP_SITE; - return; - } - - (*env)->PushLocalFrame(env, 0); - - /* - * Fix for BugTraq ID 4285634. - * If some modifier keys are pressed the Motif toolkit initializes - * cbstruct->operations this field to the bitwise AND of the - * XmDragOperations resource of the XmDragContext for this drag operation - * and the drop action corresponding to the current modifiers state. - * We need to determine the drag operations supported by the drag source, so - * we have to get XmNdragOperations value of the XmDragSource. - */ - XtVaGetValues(cbstruct->dragContext, XmNdragOperations, &srcOps, NULL); - src = XmToDnDConstants(srcOps); - usrAction = XmToDnDConstants(selectOperation(cbstruct->operations)); - - update_cache(env, w, cbstruct->dragContext); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - flush_cache(env); - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - goto wayout; - } - - switch (cbstruct->reason) { - case XmCR_DROP_SITE_ENTER_MESSAGE: { - - /* SECURITY: OK to call this on privileged thread - - peer is secure */ - ret = call_dTCenter(env, _cache.dtcpeer, _cache.component, - cbstruct->x, cbstruct->y, - usrAction, src, - _cache.targets,ptr_to_jlong(cbstruct->dragContext)); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - flush_cache(env); - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - break; - - case XmCR_DROP_SITE_LEAVE_MESSAGE: { - - DASSERT(pending_drag_exit_data.timerId == (XtIntervalId)0); - DASSERT(JNU_IsNull(env, pending_drag_exit_data.dtcpeer)); - DASSERT(JNU_IsNull(env, pending_drag_exit_data.component)); - DASSERT(pending_drag_exit_data.dragContext == (jlong)0); - - DASSERT(!JNU_IsNull(env, _cache.dtcpeer)); - DASSERT(!JNU_IsNull(env, _cache.component)); - DASSERT(cbstruct->dragContext != NULL); - - pending_drag_exit_data.dtcpeer = - (*env)->NewGlobalRef(env, _cache.dtcpeer); - pending_drag_exit_data.component = - (*env)->NewGlobalRef(env, _cache.component); - pending_drag_exit_data.dragContext = - ptr_to_jlong(cbstruct->dragContext); - - /* - * Fix for BugTraq ID 4395290. - * Postpone upcall to java, so that we can abort it in case - * if drop immediatelly follows. - */ - if (!JNU_IsNull(env, pending_drag_exit_data.dtcpeer) && - !JNU_IsNull(env, pending_drag_exit_data.component)) { - pending_drag_exit_data.timerId = - XtAppAddTimeOut(awt_appContext, 0, drag_exit_proc, NULL); - DASSERT(pending_drag_exit_data.timerId != (XtIntervalId)0); - } else { - JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError"); - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - if (!JNU_IsNull(env, pending_drag_exit_data.dtcpeer)) { - (*env)->DeleteGlobalRef(env, pending_drag_exit_data.dtcpeer); - } - if (!JNU_IsNull(env, pending_drag_exit_data.component)) { - (*env)->DeleteGlobalRef(env, pending_drag_exit_data.component); - } - memset(&pending_drag_exit_data, 0, sizeof(DragExitProcStruct)); - } - - ret = java_awt_dnd_DnDConstants_ACTION_NONE; - - /* now cleanup */ - - flush_cache(env); - } - break; - - case XmCR_DROP_SITE_MOTION_MESSAGE: { - - /* SECURITY: OK to call this on privileged thread - - peer is secure */ - ret = call_dTCmotion(env, _cache.dtcpeer, _cache.component, - cbstruct->x, cbstruct->y, - usrAction, src, - _cache.targets, - ptr_to_jlong(cbstruct->dragContext)); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - flush_cache(env); - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - } - break; - - case XmCR_OPERATION_CHANGED: { - - /* SECURITY: OK to call this on privileged thread - - peer is secure */ - ret = call_dTCmotion(env, _cache.dtcpeer, _cache.component, - cbstruct->x, cbstruct->y, - usrAction, src, - _cache.targets, - ptr_to_jlong(cbstruct->dragContext)); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - flush_cache(env); - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - } - break; - - default: break; - } - - wayout: - - /* - * Fix for BugTraq ID 4285634. - * If some modifier keys are pressed the Motif toolkit initializes - * cbstruct->operations this field to the bitwise AND of the - * XmDragOperations resource of the XmDragContext for this drag operation - * and the drop action corresponding to the current modifiers state. - * We should allow the drop target to select a drop action independent of - * the current modifiers state. - */ - cbstruct->operation = DnDConstantsToXm(ret); - - if (cbstruct->reason != XmCR_DROP_SITE_LEAVE_MESSAGE) { - Arg arg; - arg.name = XmNdropSiteOperations; - arg.value = (XtArgVal)cbstruct->operation; - - XmDropSiteUpdate(w, &arg, 1); - } - - if (ret != java_awt_dnd_DnDConstants_ACTION_NONE) { - cbstruct->dropSiteStatus = XmVALID_DROP_SITE; - } else { - cbstruct->dropSiteStatus = XmINVALID_DROP_SITE; - } - - (*env)->PopLocalFrame(env, NULL); -} - -static void drop_failure_cleanup(JNIEnv* env, Widget dragContext) { - Arg arg; - - DASSERT(dragContext != NULL); - _cache.transfer = NULL; - _cache.dropAction = XmDROP_NOOP; - - arg.name = XmNtransferStatus; - arg.value = (XtArgVal)XmTRANSFER_FAILURE; - XmDropTransferStart(dragContext, &arg, 1); - - /* Flush here, since awt_XmTransferProc won't be called. */ - flush_cache(env); -} - -/** - * - */ - -static void awt_XmDropProc(Widget w, XtPointer closure, - XmDropProcCallbackStruct* cbstruct) -{ - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jint src = java_awt_dnd_DnDConstants_ACTION_NONE; - unsigned char operation = selectOperation(cbstruct->operations); - unsigned char srcOps = XmDROP_NOOP; - unsigned char dstOps = XmDROP_NOOP; - Arg arg; - Boolean sourceIsExternal = False; - - arg.name = XmNdropSiteOperations; - arg.value = (XtArgVal)&dstOps; - XmDropSiteRetrieve(w, &arg, 1); - arg.value = (XtArgVal)(XmDROP_COPY | XmDROP_MOVE | XmDROP_LINK); - XmDropSiteUpdate(w, &arg, 1); - - /* - * Fix for BugTraq ID 4357905. - * Drop is processed asynchronously on the event dispatch thread. - * We reject other drop attempts to protect the SunDTCP context - * from being overwritten by an upcall before the drop is done. - */ - if (!isDropDone()) { - return; - } - - if (cbstruct->dragContext == NULL) { - cbstruct->operation = XmDROP_NOOP; - cbstruct->dropSiteStatus = XmINVALID_DROP_SITE; - return; - } - - /* - * Fix for BugTraq ID 4492640. - * Because of the Motif bug #4528191 XmNdragOperations resource is always - * equal to XmDROP_MOVE | XmDROP_COPY when the drag source is external. - * The workaround for this bug is to assume that an external drag source - * supports all drop actions. - */ - XtVaGetValues(cbstruct->dragContext, - XmNsourceIsExternal, &sourceIsExternal, NULL); - - if (sourceIsExternal) { - srcOps = XmDROP_LINK | XmDROP_MOVE | XmDROP_COPY; - } else { - /* - * Fix for BugTraq ID 4285634. - * If some modifier keys are pressed the Motif toolkit initializes - * cbstruct->operations to the bitwise AND of the - * XmDragOperations resource of the XmDragContext for this drag operation - * and the drop action corresponding to the current modifiers state. - * We need to determine the drag operations supported by the drag source, so - * we have to get XmNdragOperations value of the XmDragSource. - */ - XtVaGetValues(cbstruct->dragContext, XmNdragOperations, &srcOps, NULL); - } - - src = XmToDnDConstants(srcOps); - - if ((srcOps & dstOps) == 0) { - cbstruct->operation = XmDROP_NOOP; - cbstruct->dropSiteStatus = XmINVALID_DROP_SITE; - drop_failure_cleanup(env, cbstruct->dragContext); - return; - } - - (*env)->PushLocalFrame(env, 0); - - update_cache(env, w, cbstruct->dragContext); - - cacheDropDone(False); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - (*env)->PopLocalFrame(env, NULL); - drop_failure_cleanup(env, cbstruct->dragContext); - return; - } - - /* - * Fix for BugTraq ID 4395290. - * Abort a pending upcall to dragExit. - */ - pending_drag_exit_data.timerId = (XtIntervalId)0; - - /* SECURITY: OK to call this on privileged thread - peer is secure */ - call_dTCdrop(env, _cache.dtcpeer, _cache.component, - cbstruct->x, cbstruct->y, - XmToDnDConstants(operation), src, _cache.targets, - ptr_to_jlong(cbstruct->dragContext)); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - flush_cache(env); - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - (*env)->PopLocalFrame(env, NULL); -} - -/** - * - */ - -static void awt_XmTransferProc(Widget w, XtPointer closure, Atom* selection, - Atom* type, XtPointer value, - unsigned long* length, int32_t* format) -{ - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - Atom req = (Atom)closure; - Display* dpy = XtDisplayOfObject(w); - jobject tName = NULL; - - /* - * Note: this method is only called to transfer data between clients - * in different JVM's or native apps. For Intra-JVM transfers the peer - * code shares the sources Transferable with the destination. - */ - - if (_cache.w == (Widget)NULL || _cache.transfer != w) { - if (value != NULL) { - XtFree(value); - value = NULL; - } - /* we have already cleaned up ... */ - return; - } - - (*env)->PushLocalFrame(env, 0); - - if (*type == None || *type == XT_CONVERT_FAIL) { - /* SECURITY: OK to call this on privileged thread - peer is secure - */ - call_dTCtxFailed(env, _cache.dtcpeer, (jlong)req); - } else { - switch (*format) { - case 8: - case 16: - case 32: { - jsize size = (*length <= INT_MAX) ? (jsize)*length : INT_MAX; - jbyteArray arry = (*env)->NewByteArray(env, size); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - - /* SECURITY: OK to call this on privileged thread - - peer is secure */ - call_dTCtxFailed(env, _cache.dtcpeer, (jlong)req); - - goto wayout; - } - - (*env)->SetByteArrayRegion(env, arry, 0, size, (jbyte*)value); - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - - /* SECURITY: OK to call this on privileged thread - - peer is secure */ - call_dTCtxFailed(env, _cache.dtcpeer, (jlong)req); - goto wayout; - } - - arry = (*env)->NewGlobalRef(env, arry); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - { - char* tn = XGetAtomName(dpy, *type); - - tName = (*env)->NewStringUTF(env, (const char *)tn); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - XFree((void *)tn); - } - - /* SECURITY: OK to call this on privileged thread - peer is - secure */ - call_dTCnewData(env, _cache.dtcpeer, (jlong)req, tName, arry); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - - default: - break; - } - } - - wayout: - if (value != NULL) { - XtFree(value); - value = NULL; - } - - _cache.transfersPending--; - while (_cache.transfersPending == 0 && !isDropDone()) { - AWT_WAIT(0); - } - - if (isDropDone() && _cache.flushPending) { - flush_cache(env); - } - - (*env)->PopLocalFrame(env, NULL); -} - -/** - * - */ - -static void awt_XmDragEnterProc(Widget w, XtPointer closure, - XmDropSiteEnterCallbackStruct* cbstruct) -{ - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject)closure; - - /* This should only be valid, but Im leaving this part of the old code */ - jboolean valid = cbstruct->dropSiteStatus == XmVALID_DROP_SITE - ? JNI_TRUE : JNI_FALSE; - - if (valid == JNI_TRUE) { - /* - * Workaround for Motif bug id #4457656. - * Pointer coordinates passed in cbstruct are incorrect. - * We have to make a round-trip query. - */ - Window rootWindow, childWindow; - int32_t xw, yw, xr, yr; - uint32_t modifiers; - - XQueryPointer(awt_display, XtWindow(w), - &rootWindow, &childWindow, &xr, &yr, &xw, &yw, &modifiers); - - (*env)->PushLocalFrame(env, 0); - - /* SECURITY: OK to call this on privileged thread - peer is secure */ - call_dSCenter(env, this, XmToDnDConstants(cbstruct->operation), - convertModifiers(modifiers), xr, yr); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - (*env)->PopLocalFrame(env, NULL); - } -} - -/** - * - */ - -static void awt_XmDragMotionProc(Widget w, XtPointer closure, - XmDragMotionCallbackStruct* cbstruct) -{ - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject)closure; - - /* This should only be valid, but Im leaving this part of the old code */ - jboolean valid = cbstruct->dropSiteStatus == XmVALID_DROP_SITE - ? JNI_TRUE : JNI_FALSE; - Window rootWindow, childWindow; - int32_t xw, yw, xr, yr; - uint32_t modifiers; - - XQueryPointer(awt_display, XtWindow(w), - &rootWindow, &childWindow, &xr, &yr, &xw, &yw, &modifiers); - /* - * Fix for 4285634. - * Use the cached modifiers state, since the directly queried state can - * differ from the one associated with this dnd notification. - */ - modifiers = ((XmDragContext)w)->drag.lastEventState; - if (xr != x_root || yr != y_root) { - call_dSCmouseMoved(env, this, XmToDnDConstants(cbstruct->operation), - convertModifiers(modifiers), xr, yr); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - x_root = xr; - y_root = yr; - } - - if (valid == JNI_TRUE) { - - (*env)->PushLocalFrame(env, 0); - - /* SECURITY: OK to call this on privileged thread - peer is secure */ - call_dSCmotion(env, this, XmToDnDConstants(cbstruct->operation), - convertModifiers(modifiers), xr, yr); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - (*env)->PopLocalFrame(env, NULL); - } else { - (*env)->PushLocalFrame(env, 0); - - /* SECURITY: OK to call this on privileged thread - peer is secure */ - call_dSCexit(env, this, xr, yr); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - (*env)->PopLocalFrame(env, NULL); - } -} - -/** - * - */ - -static void awt_XmDragLeaveProc(Widget w, XtPointer closure, - XmDropSiteLeaveCallbackStruct* cbstruct) -{ - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject)closure; - Window rootWindow, childWindow; - int32_t xw, yw, xr, yr; - uint32_t modifiers; - - XQueryPointer(XtDisplay(w), XtWindow(w), - &rootWindow, &childWindow, &xr, &yr, &xw, &yw, &modifiers); - - (*env)->PushLocalFrame(env, 0); - - /* SECURITY: OK to call this on privileged thread - peer is secure */ - call_dSCexit(env, this, xr, yr); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - (*env)->PopLocalFrame(env, NULL); -} - -/** - * - */ - -static void awt_XmDropOperationChangedProc(Widget w, XtPointer closure, - XmDropStartCallbackStruct* cbstruct) -{ - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject)closure; - Window rootWindow, childWindow; - int32_t xw, yw, xr, yr; - uint32_t modifiers; - - XQueryPointer(XtDisplay(w), XtWindow(w), - &rootWindow, &childWindow, &xr, &yr, &xw, &yw, &modifiers); - - (*env)->PushLocalFrame(env, 0); - - - /* SECURITY: OK to call this on privileged thread - peer is secure */ - call_dSCchanged(env, this, XmToDnDConstants(cbstruct->operation), - convertModifiers(modifiers), xr, yr); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - (*env)->PopLocalFrame(env, NULL); -} - -/** - * - */ - -static void awt_XmDropFinishProc(Widget w, XtPointer closure, - XmDropFinishCallbackStruct* cbstruct) -{ - JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject this = (jobject)closure; - unsigned char completionStatus = cbstruct->completionStatus; - jint dropAction = XmToDnDConstants(cbstruct->operation); - Window rootWindow, childWindow; - int32_t xw, yw, xr, yr; - uint32_t modifiers; - - XQueryPointer(XtDisplay(w), XtWindow(w), - &rootWindow, &childWindow, &xr, &yr, &xw, &yw, &modifiers); - - /* cleanup */ - - if (_cache.transfer == NULL) { - dropAction = _cache.dropAction; - } - - _cache.dropAction = java_awt_dnd_DnDConstants_ACTION_NONE; - _cache.win = None; - _cache.state = 0; - XtRemoveEventHandler(w, ButtonReleaseMask, False, - dragsource_track_release, NULL); - - /* SECURITY: OK to call this on privileged thread - peer is secure */ - call_dSCddfinished(env, this, completionStatus, dropAction, xr, yr); - - if (!JNU_IsNull(env, (*env)->ExceptionOccurred(env))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - - awt_cleanupConvertDataContext(env, MOTIF_DROP_ATOM); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_XmDnD.h b/jdk/src/solaris/native/sun/awt/awt_XmDnD.h deleted file mode 100644 index c2650e34086..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_XmDnD.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 1997-2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#include -#include -#include -#include - -/** - * - */ - -typedef struct DropSiteInfo { - Widget tlw; - - jobject component; - Boolean isComposite; - uint32_t dsCnt; -} DropSiteInfo; diff --git a/jdk/src/solaris/native/sun/awt/awt_dnd.c b/jdk/src/solaris/native/sun/awt/awt_dnd.c deleted file mode 100644 index 1b5c9d49ce4..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_dnd.c +++ /dev/null @@ -1,887 +0,0 @@ -/* - * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_dnd.h" - -#include "awt_p.h" - -#include "java_awt_dnd_DnDConstants.h" - -/* Shared atoms */ - -Atom XA_WM_STATE; -Atom XA_DELETE; - -/* XDnD atoms */ - -Atom XA_XdndAware; -Atom XA_XdndProxy; - -Atom XA_XdndEnter; -Atom XA_XdndPosition; -Atom XA_XdndLeave; -Atom XA_XdndDrop; -Atom XA_XdndStatus; -Atom XA_XdndFinished; - -Atom XA_XdndTypeList; -Atom XA_XdndSelection; - -Atom XA_XdndActionCopy; -Atom XA_XdndActionMove; -Atom XA_XdndActionLink; -Atom XA_XdndActionAsk; -Atom XA_XdndActionPrivate; -Atom XA_XdndActionList; - -/* Motif DnD atoms */ - -Atom _XA_MOTIF_DRAG_WINDOW; -Atom _XA_MOTIF_DRAG_TARGETS; -Atom _XA_MOTIF_DRAG_INITIATOR_INFO; -Atom _XA_MOTIF_DRAG_RECEIVER_INFO; -Atom _XA_MOTIF_DRAG_AND_DROP_MESSAGE; -Atom _XA_MOTIF_ATOM_0; -Atom XA_XmTRANSFER_SUCCESS; -Atom XA_XmTRANSFER_FAILURE; - -unsigned char MOTIF_BYTE_ORDER = 0; - -static Window awt_root_window = None; - -static Boolean -init_atoms(Display* display) { - struct atominit { - Atom *atomptr; - const char *name; - }; - - /* Add new atoms to this list */ - static struct atominit atom_list[] = { - /* Shared atoms */ - { &XA_WM_STATE, "WM_STATE" }, - { &XA_DELETE, "DELETE" }, - - /* XDnD atoms */ - { &XA_XdndAware, "XdndAware" }, - { &XA_XdndProxy, "XdndProxy" }, - { &XA_XdndEnter, "XdndEnter" }, - { &XA_XdndPosition, "XdndPosition" }, - { &XA_XdndLeave, "XdndLeave" }, - { &XA_XdndDrop, "XdndDrop" }, - { &XA_XdndStatus, "XdndStatus" }, - { &XA_XdndFinished, "XdndFinished" }, - { &XA_XdndTypeList, "XdndTypeList" }, - { &XA_XdndSelection, "XdndSelection" }, - { &XA_XdndActionCopy, "XdndActionCopy" }, - { &XA_XdndActionMove, "XdndActionMove" }, - { &XA_XdndActionLink, "XdndActionLink" }, - { &XA_XdndActionAsk, "XdndActionAsk" }, - { &XA_XdndActionPrivate, "XdndActionPrivate" }, - { &XA_XdndActionList, "XdndActionList" }, - - /* Motif DnD atoms */ - { &_XA_MOTIF_DRAG_WINDOW, "_MOTIF_DRAG_WINDOW" }, - { &_XA_MOTIF_DRAG_TARGETS, "_MOTIF_DRAG_TARGETS" }, - { &_XA_MOTIF_DRAG_INITIATOR_INFO, "_MOTIF_DRAG_INITIATOR_INFO" }, - { &_XA_MOTIF_DRAG_RECEIVER_INFO, "_MOTIF_DRAG_RECEIVER_INFO" }, - { &_XA_MOTIF_DRAG_AND_DROP_MESSAGE, "_MOTIF_DRAG_AND_DROP_MESSAGE" }, - { &_XA_MOTIF_ATOM_0, "_MOTIF_ATOM_0" }, - { &XA_XmTRANSFER_SUCCESS, "XmTRANSFER_SUCCESS" }, - { &XA_XmTRANSFER_FAILURE, "XmTRANSFER_FAILURE" } - }; - -#define ATOM_LIST_LENGTH (sizeof(atom_list)/sizeof(atom_list[0])) - - const char *names[ATOM_LIST_LENGTH]; - Atom atoms[ATOM_LIST_LENGTH]; - Status status; - size_t i; - - /* Fill the array of atom names */ - for (i = 0; i < ATOM_LIST_LENGTH; ++i) { - names[i] = atom_list[i].name; - } - - DTRACE_PRINT2("%s:%d initializing atoms ... ", __FILE__, __LINE__); - - status = XInternAtoms(awt_display, (char**)names, ATOM_LIST_LENGTH, - False, atoms); - if (status == 0) { - DTRACE_PRINTLN("failed"); - return False; - } - - /* Store returned atoms into corresponding global variables */ - DTRACE_PRINTLN("ok"); - for (i = 0; i < ATOM_LIST_LENGTH; ++i) { - *atom_list[i].atomptr = atoms[i]; - } - - return True; -#undef ATOM_LIST_LENGTH -} - -/* - * NOTE: must be called after awt_root_shell is created and realized. - */ -Boolean -awt_dnd_init(Display* display) { - static Boolean inited = False; - - if (!inited) { - Boolean atoms_inited = False; - Boolean ds_inited = False; - unsigned int value = 1; - MOTIF_BYTE_ORDER = (*((char*)&value) != 0) ? 'l' : 'B'; - - /* NOTE: init_atoms() should be called before the rest of initialization - so that atoms can be used. */ - inited = init_atoms(display); - - if (inited) { - if (XtIsRealized(awt_root_shell)) { - awt_root_window = XtWindow(awt_root_shell); - } else { - inited = False; - } - } - - inited = inited && awt_dnd_ds_init(display); - } - - return inited; -} - -/* - * Returns a window of awt_root_shell. - */ -Window -get_awt_root_window() { - return awt_root_window; -} - -static unsigned char local_xerror_code = Success; - -static int -xerror_handler(Display *dpy, XErrorEvent *err) { - local_xerror_code = err->error_code; - return 0; -} - -/**************** checked_X* wrappers *****************************************/ -#undef NO_SYNC -#undef SYNC_TRACE - -unsigned char -checked_XChangeProperty(Display* display, Window w, Atom property, Atom type, - int format, int mode, unsigned char* data, - int nelements) { - XErrorHandler xerror_saved_handler; - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 1\n"); -#endif -#endif - local_xerror_code = Success; - xerror_saved_handler = XSetErrorHandler(xerror_handler); - - XChangeProperty(display, w, property, type, format, mode, data, nelements); - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 2\n"); -#endif -#endif - XSetErrorHandler(xerror_saved_handler); - - return local_xerror_code; -} - -unsigned char -checked_XGetWindowProperty(Display* display, Window w, Atom property, long long_offset, - long long_length, Bool delete, Atom req_type, - Atom* actual_type_return, int* actual_format_return, - unsigned long* nitems_return, unsigned long* bytes_after_return, - unsigned char** prop_return) { - - XErrorHandler xerror_saved_handler; - int ret_val = Success; - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 3\n"); -#endif -#endif - local_xerror_code = Success; - xerror_saved_handler = XSetErrorHandler(xerror_handler); - - ret_val = XGetWindowProperty(display, w, property, long_offset, long_length, - delete, req_type, actual_type_return, - actual_format_return, nitems_return, - bytes_after_return, prop_return); - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 4\n"); -#endif -#endif - XSetErrorHandler(xerror_saved_handler); - - return ret_val != Success ? local_xerror_code : Success; -} - -unsigned char -checked_XSendEvent(Display* display, Window w, Bool propagate, long event_mask, - XEvent* event_send) { - - XErrorHandler xerror_saved_handler; - Status ret_val = 0; - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 5\n"); -#endif -#endif - local_xerror_code = Success; - xerror_saved_handler = XSetErrorHandler(xerror_handler); - - ret_val = XSendEvent(display, w, propagate, event_mask, event_send); - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 6\n"); -#endif -#endif - XSetErrorHandler(xerror_saved_handler); - - return ret_val == 0 ? local_xerror_code : Success; -} - -/* - * NOTE: returns Success even if the two windows aren't on the same screen. - */ -unsigned char -checked_XTranslateCoordinates(Display* display, Window src_w, Window dest_w, - int src_x, int src_y, int* dest_x_return, - int* dest_y_return, Window* child_return) { - - XErrorHandler xerror_saved_handler; - Bool ret_val = True; - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 7\n"); -#endif -#endif - local_xerror_code = Success; - xerror_saved_handler = XSetErrorHandler(xerror_handler); - - ret_val = XTranslateCoordinates(display, src_w, dest_w, src_x, src_y, - dest_x_return, dest_y_return, child_return); - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 8\n"); -#endif -#endif - XSetErrorHandler(xerror_saved_handler); - - return local_xerror_code; -} - -unsigned char -checked_XSelectInput(Display* display, Window w, long event_mask) { - XErrorHandler xerror_saved_handler; - Bool ret_val = True; - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 7\n"); -#endif -#endif - local_xerror_code = Success; - xerror_saved_handler = XSetErrorHandler(xerror_handler); - - XSelectInput(display, w, event_mask); - -#ifndef NO_SYNC - XSync(display, False); -#ifdef SYNC_TRACE - fprintf(stderr,"XSync 8\n"); -#endif -#endif - XSetErrorHandler(xerror_saved_handler); - - return local_xerror_code; -} -/******************************************************************************/ - -jint -xdnd_to_java_action(Atom action) { - if (action == XA_XdndActionCopy) { - return java_awt_dnd_DnDConstants_ACTION_COPY; - } else if (action == XA_XdndActionMove) { - return java_awt_dnd_DnDConstants_ACTION_MOVE; - } else if (action == XA_XdndActionLink) { - return java_awt_dnd_DnDConstants_ACTION_LINK; - } else if (action == None) { - return java_awt_dnd_DnDConstants_ACTION_NONE; - } else { - /* XdndActionCopy is the default. */ - return java_awt_dnd_DnDConstants_ACTION_COPY; - } -} - -Atom -java_to_xdnd_action(jint action) { - switch (action) { - case java_awt_dnd_DnDConstants_ACTION_COPY: return XA_XdndActionCopy; - case java_awt_dnd_DnDConstants_ACTION_MOVE: return XA_XdndActionMove; - case java_awt_dnd_DnDConstants_ACTION_LINK: return XA_XdndActionLink; - default: return None; - } -} - -void -write_card8(void** p, CARD8 value) { - CARD8** card8_pp = (CARD8**)p; - **card8_pp = value; - (*card8_pp)++; -} - -void -write_card16(void** p, CARD16 value) { - CARD16** card16_pp = (CARD16**)p; - **card16_pp = value; - (*card16_pp)++; -} - -void -write_card32(void** p, CARD32 value) { - CARD32** card32_pp = (CARD32**)p; - **card32_pp = value; - (*card32_pp)++; -} - -CARD8 -read_card8(char* data, size_t offset) { - return *((CARD8*)(data + offset)); -} - -CARD16 -read_card16(char* data, size_t offset, char byte_order) { - CARD16 card16 = *((CARD16*)(data + offset)); - - if (byte_order != MOTIF_BYTE_ORDER) { - SWAP2BYTES(card16); - } - - return card16; -} - -CARD32 -read_card32(char* data, size_t offset, char byte_order) { - CARD32 card32 = *((CARD32*)(data + offset)); - - if (byte_order != MOTIF_BYTE_ORDER) { - SWAP4BYTES(card32); - } - - return card32; -} - -static Window -read_motif_window(Display* dpy) { - Window root_window = DefaultRootWindow(dpy); - Window motif_window = None; - - unsigned char ret; - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - - ret = checked_XGetWindowProperty(dpy, root_window, _XA_MOTIF_DRAG_WINDOW, - 0, 0xFFFF, False, AnyPropertyType, &type, - &format, &nitems, &after, &data); - - if (ret != Success) { - DTRACE_PRINTLN2("%s:%d Failed to read _MOTIF_DRAG_WINDOW.", - __FILE__, __LINE__); - return None; - } - - - if (type == XA_WINDOW && format == 32 && nitems == 1) { - motif_window = *((Window*)data); - } - - XFree ((char *)data); - - return motif_window; -} - -static Window -create_motif_window(Display* dpy) { - Window root_window = DefaultRootWindow(dpy); - Window motif_window = None; - Display* display = NULL; - XSetWindowAttributes swa; - - display = XOpenDisplay(XDisplayString(dpy)); - if (display == NULL) { - return None; - } - - XGrabServer(display); - - XSetCloseDownMode(display, RetainPermanent); - - swa.override_redirect = True; - swa.event_mask = PropertyChangeMask; - motif_window = XCreateWindow(display, root_window, - -10, -10, 1, 1, 0, 0, - InputOnly, CopyFromParent, - (CWOverrideRedirect|CWEventMask), - &swa); - XMapWindow(display, motif_window); - - XChangeProperty(display, root_window, _XA_MOTIF_DRAG_WINDOW, XA_WINDOW, 32, - PropModeReplace, (unsigned char *)&motif_window, 1); - - XUngrabServer(display); - - XCloseDisplay(display); - - return motif_window; -} - -Window -get_motif_window(Display* dpy) { - /* - * Note: it is unsafe to cache the motif drag window handle, as another - * client can change the _MOTIF_DRAG_WINDOW property on the root, the handle - * becomes out-of-sync and all subsequent drag operations will fail. - */ - Window motif_window = read_motif_window(dpy); - if (motif_window == None) { - motif_window = create_motif_window(dpy); - } - - return motif_window; -} - -typedef struct { - CARD16 num_targets; - Atom* targets; -} TargetsTableEntry; - -typedef struct { - CARD16 num_entries; - TargetsTableEntry* entries; -} TargetsTable; - -typedef struct { - CARD8 byte_order; - CARD8 protocol_version; - CARD16 num_entries B16; - CARD32 heap_offset B32; -} TargetsPropertyRec; - -static TargetsTable* -get_target_list_table(Display* dpy) { - Window motif_window = get_motif_window(dpy); - TargetsTable* targets_table = NULL; - TargetsPropertyRec* targets_property_rec_ptr; - char* bufptr; - - unsigned char ret; - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - unsigned int i, j; - - ret = checked_XGetWindowProperty(dpy, motif_window, _XA_MOTIF_DRAG_TARGETS, - 0L, 100000L, False, _XA_MOTIF_DRAG_TARGETS, - &type, &format, &nitems, &after, - (unsigned char**)&targets_property_rec_ptr); - - if (ret != Success || type != _XA_MOTIF_DRAG_TARGETS || - targets_property_rec_ptr == NULL) { - - DTRACE_PRINT2("%s:%d Cannot read _XA_MOTIF_DRAG_TARGETS", __FILE__, __LINE__); - return NULL; - } - - if (targets_property_rec_ptr->protocol_version != - MOTIF_DND_PROTOCOL_VERSION) { - DTRACE_PRINT2("%s:%d incorrect protocol version", __FILE__, __LINE__); - return NULL; - } - - if (targets_property_rec_ptr->byte_order != MOTIF_BYTE_ORDER) { - SWAP2BYTES(targets_property_rec_ptr->num_entries); - SWAP4BYTES(targets_property_rec_ptr->heap_offset); - } - - targets_table = (TargetsTable*)malloc(sizeof(TargetsTable)); - if (targets_table == NULL) { - DTRACE_PRINT2("%s:%d malloc failed", __FILE__, __LINE__); - return NULL; - } - targets_table->num_entries = targets_property_rec_ptr->num_entries; - targets_table->entries = - (TargetsTableEntry*)malloc(sizeof(TargetsTableEntry) * - targets_property_rec_ptr->num_entries); - if (targets_table->entries == NULL) { - DTRACE_PRINT2("%s:%d malloc failed", __FILE__, __LINE__); - free(targets_table); - return NULL; - } - - bufptr = (char *)targets_property_rec_ptr + sizeof(TargetsPropertyRec); - for (i = 0; i < targets_table->num_entries; i++) { - CARD16 num_targets; - Atom* targets; - memcpy(&num_targets, bufptr, 2 ); - bufptr += 2; - if (targets_property_rec_ptr->byte_order != MOTIF_BYTE_ORDER) { - SWAP2BYTES(num_targets); - } - - targets = (Atom*)malloc(sizeof(Atom) * num_targets); - if (targets == NULL) { - DTRACE_PRINT2("%s:%d malloc failed", __FILE__, __LINE__); - free(targets_table->entries); - free(targets_table); - return NULL; - } - for (j = 0; j < num_targets; j++) { - CARD32 target; - memcpy(&target, bufptr, 4 ); - bufptr += 4; - if (targets_property_rec_ptr->byte_order != MOTIF_BYTE_ORDER) { - SWAP4BYTES(target); - } - targets[j] = (Atom)target; - } - - targets_table->entries[i].num_targets = num_targets; - targets_table->entries[i].targets = targets; - } - - free(targets_property_rec_ptr); - - return targets_table; -} - -static void -put_target_list_table(Display* dpy, TargetsTable* table) { - Window motif_window = get_motif_window(dpy); - TargetsPropertyRec* targets_property_rec_ptr; - size_t table_size = sizeof(TargetsPropertyRec); - unsigned char ret; - int i, j; - char* buf; - - for (i = 0; i < table->num_entries; i++) { - table_size += table->entries[i].num_targets * sizeof(Atom) + 2; - } - - targets_property_rec_ptr = (TargetsPropertyRec*)malloc(table_size); - if (targets_property_rec_ptr == NULL) { - DTRACE_PRINT2("%s:%d malloc failed", __FILE__, __LINE__); - return; - } - targets_property_rec_ptr->byte_order = MOTIF_BYTE_ORDER; - targets_property_rec_ptr->protocol_version = MOTIF_DND_PROTOCOL_VERSION; - targets_property_rec_ptr->num_entries = table->num_entries; - targets_property_rec_ptr->heap_offset = table_size; - - buf = (char*)targets_property_rec_ptr + sizeof(TargetsPropertyRec); - - for (i = 0; i < table->num_entries; i++) { - CARD16 num_targets = table->entries[i].num_targets; - memcpy(buf, &num_targets, 2); - buf += 2; - - for (j = 0; j < num_targets; j++) { - CARD32 target = table->entries[i].targets[j]; - memcpy(buf, &target, 4); - buf += 4; - } - } - - ret = checked_XChangeProperty(dpy, motif_window, _XA_MOTIF_DRAG_TARGETS, - _XA_MOTIF_DRAG_TARGETS, 8, PropModeReplace, - (unsigned char*)targets_property_rec_ptr, - (int)table_size); - - if (ret != Success) { - DTRACE_PRINT2("%s:%d XChangeProperty failed", __FILE__, __LINE__); - } - - XtFree((char*)targets_property_rec_ptr); -} - -static int -_compare(const void* p1, const void* p2) { - long diff = *(Atom*)p1 - *(Atom*)p2; - - if (diff > 0) { - return 1; - } else if (diff < 0) { - return -1; - } else { - return 0; - } -} - -/* - * Returns the index for the specified target list or -1 on failure. - */ -int -get_index_for_target_list(Display* dpy, Atom* targets, unsigned int num_targets) { - TargetsTable* targets_table = NULL; - Atom* sorted_targets = NULL; - int i, j; - int ret = -1; - - if (targets == NULL && num_targets > 0) { - DTRACE_PRINT4("%s:%d targets=%X num_targets=%d", - __FILE__, __LINE__, targets, num_targets); - return -1; - } - - if (num_targets > 0) { - sorted_targets = (Atom*)malloc(sizeof(Atom) * num_targets); - if (sorted_targets == NULL) { - DTRACE_PRINT2("%s:%d malloc failed.", __FILE__, __LINE__); - return -1; - } - - memcpy(sorted_targets, targets, sizeof(Atom) * num_targets); - qsort ((void *)sorted_targets, (size_t)num_targets, (size_t)sizeof(Atom), - _compare); - } - - XGrabServer(dpy); - targets_table = get_target_list_table(dpy); - - if (targets_table != NULL) { - for (i = 0; i < targets_table->num_entries; i++) { - TargetsTableEntry* entry_ptr = &targets_table->entries[i]; - Boolean equals = True; - if (num_targets == entry_ptr->num_targets) { - for (j = 0; j < entry_ptr->num_targets; j++) { - if (sorted_targets[j] != entry_ptr->targets[j]) { - equals = False; - break; - } - } - } else { - equals = False; - } - - if (equals) { - XUngrabServer(dpy); - /* Workaround for bug 5039226 */ - XSync(dpy, False); - free((char*)sorted_targets); - return i; - } - } - } else { - targets_table = (TargetsTable*)malloc(sizeof(TargetsTable)); - targets_table->num_entries = 0; - targets_table->entries = NULL; - } - - /* Index not found - expand the table. */ - targets_table->entries = - (TargetsTableEntry*)realloc((char*)targets_table->entries, - sizeof(TargetsTableEntry) * - (targets_table->num_entries + 1)); - if (targets_table->entries == NULL) { - DTRACE_PRINT2("%s:%d realloc failed.", __FILE__, __LINE__); - XUngrabServer(dpy); - /* Workaround for bug 5039226 */ - XSync(dpy, False); - free((char*)sorted_targets); - return -1; - } - - /* Fill in the new entry */ - { - TargetsTableEntry* new_entry = - &targets_table->entries[targets_table->num_entries]; - - new_entry->num_targets = num_targets; - if (num_targets > 0) { - new_entry->targets = (Atom*)malloc(sizeof(Atom) * num_targets); - if (new_entry->targets == NULL) { - DTRACE_PRINT2("%s:%d malloc failed.", __FILE__, __LINE__); - XUngrabServer(dpy); - /* Workaround for bug 5039226 */ - XSync(dpy, False); - free((char*)sorted_targets); - return -1; - } - memcpy(new_entry->targets, sorted_targets, - sizeof(Atom) * num_targets); - } else { - new_entry->targets = NULL; - } - } - - targets_table->num_entries++; - - put_target_list_table(dpy, targets_table); - - XUngrabServer(dpy); - /* Workaround for bug 5039226 */ - XSync(dpy, False); - - ret = targets_table->num_entries - 1; - - free((char*)sorted_targets); - - for (i = 0; i < targets_table->num_entries; i++) { - free((char*)targets_table->entries[i].targets); - } - - free((char*)targets_table->entries); - free((char*)targets_table); - return ret; -} - -/* - * Retrieves the target list for the specified index. - * Stores the number of targets in the list to 'num_targets' and the targets - * to 'targets'. On failure stores 0 and NULL respectively. - * The caller should free the allocated array when done with it. - */ -void -get_target_list_for_index(Display* dpy, int index, Atom** targets, unsigned int* num_targets) { - TargetsTable* table = get_target_list_table(dpy); - TargetsTableEntry* entry = NULL; - - if (table == NULL) { - DTRACE_PRINT2("%s:%d No target table.", __FILE__, __LINE__); - *targets = NULL; - *num_targets = 0; - return; - } - - if (table->num_entries <= index) { - DTRACE_PRINT4("%s:%d index out of bounds idx=%d entries=%d", - __FILE__, __LINE__, index, table->num_entries); - *targets = NULL; - *num_targets = 0; - return; - } - - entry = &table->entries[index]; - - *targets = (Atom*)malloc(entry->num_targets * sizeof(Atom)); - - if (*targets == NULL) { - DTRACE_PRINT2("%s:%d malloc failed.", __FILE__, __LINE__); - *num_targets = 0; - return; - } - - memcpy(*targets, entry->targets, entry->num_targets * sizeof(Atom)); - *num_targets = entry->num_targets; -} - -jint -motif_to_java_actions(unsigned char motif_action) { - jint java_action = java_awt_dnd_DnDConstants_ACTION_NONE; - - if (motif_action & MOTIF_DND_COPY) { - java_action |= java_awt_dnd_DnDConstants_ACTION_COPY; - } - - if (motif_action & MOTIF_DND_MOVE) { - java_action |= java_awt_dnd_DnDConstants_ACTION_MOVE; - } - - if (motif_action & MOTIF_DND_LINK) { - java_action |= java_awt_dnd_DnDConstants_ACTION_LINK; - } - - return java_action; -} - -unsigned char -java_to_motif_actions(jint java_action) { - unsigned char motif_action = MOTIF_DND_NOOP; - - if (java_action & java_awt_dnd_DnDConstants_ACTION_COPY) { - motif_action |= MOTIF_DND_COPY; - } - - if (java_action & java_awt_dnd_DnDConstants_ACTION_MOVE) { - motif_action |= MOTIF_DND_MOVE; - } - - if (java_action & java_awt_dnd_DnDConstants_ACTION_LINK) { - motif_action |= MOTIF_DND_LINK; - } - - return motif_action; -} - -Boolean -awt_dnd_process_event(XEvent* event) { - Boolean ret = awt_dnd_ds_process_event(event) || - awt_dnd_dt_process_event(event); - - /* Extract the event from the queue if it is processed. */ - if (ret) { - XNextEvent(event->xany.display, event); - } - - return ret; -} diff --git a/jdk/src/solaris/native/sun/awt/awt_dnd.h b/jdk/src/solaris/native/sun/awt/awt_dnd.h deleted file mode 100644 index 5e2f3e437da..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_dnd.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include - -#include "awt_p.h" - -/* For definition of MComponentPeerIDs */ -#include "awt_Component.h" - -extern struct MComponentPeerIDs mComponentPeerIDs; - -/* DnD protocols */ - -typedef enum { - NO_PROTOCOL, - XDND_PROTOCOL, - MOTIF_DND_PROTOCOL -} Protocol; - -/* XDnD constants */ - -#define XDND_PROTOCOL_VERSION 5 -/* XDnD compliance only requires supporting version 3 and up. */ -#define XDND_MIN_PROTOCOL_VERSION 3 - -#define XDND_PROTOCOL_MASK 0xFF000000 -#define XDND_PROTOCOL_SHIFT 24 -#define XDND_DATA_TYPES_BIT 0x1 -#define XDND_ACCEPT_DROP_FLAG 0x1 - -/* Motif DnD constants */ - -#define MOTIF_DND_PROTOCOL_VERSION 0 - -/* Suuported protocol styles */ -#define MOTIF_PREFER_PREREGISTER_STYLE 2 -#define MOTIF_PREFER_DYNAMIC_STYLE 4 -#define MOTIF_DYNAMIC_STYLE 5 -#define MOTIF_PREFER_RECEIVER_STYLE 6 - -#define MOTIF_MESSAGE_REASON_MASK 0x7F -#define MOTIF_MESSAGE_SENDER_MASK 0x80 -#define MOTIF_MESSAGE_FROM_RECEIVER 0x80 -#define MOTIF_MESSAGE_FROM_INITIATOR 0 - -/* Info structure sizes */ -#define MOTIF_INITIATOR_INFO_SIZE 8 -#define MOTIF_RECEIVER_INFO_SIZE 16 - -/* Message flags masks and shifts */ -#define MOTIF_DND_ACTION_MASK 0x000F -#define MOTIF_DND_ACTION_SHIFT 0 -#define MOTIF_DND_STATUS_MASK 0x00F0 -#define MOTIF_DND_STATUS_SHIFT 4 -#define MOTIF_DND_ACTIONS_MASK 0x0F00 -#define MOTIF_DND_ACTIONS_SHIFT 8 - -/* message type constants */ -#define TOP_LEVEL_ENTER 0 -#define TOP_LEVEL_LEAVE 1 -#define DRAG_MOTION 2 -#define DROP_SITE_ENTER 3 -#define DROP_SITE_LEAVE 4 -#define DROP_START 5 -#define DROP_FINISH 6 -#define DRAG_DROP_FINISH 7 -#define OPERATION_CHANGED 8 - -/* drop action constants */ -#define MOTIF_DND_NOOP 0L -#define MOTIF_DND_MOVE (1L << 0) -#define MOTIF_DND_COPY (1L << 1) -#define MOTIF_DND_LINK (1L << 2) - -/* drop site status constants */ -#define MOTIF_NO_DROP_SITE 1 -#define MOTIF_INVALID_DROP_SITE 2 -#define MOTIF_VALID_DROP_SITE 3 - -/* Shared atoms */ - -extern Atom XA_WM_STATE; -extern Atom XA_DELETE; - -/* XDnD atoms */ - -extern Atom XA_XdndAware; -extern Atom XA_XdndProxy; - -extern Atom XA_XdndEnter; -extern Atom XA_XdndPosition; -extern Atom XA_XdndLeave; -extern Atom XA_XdndDrop; -extern Atom XA_XdndStatus; -extern Atom XA_XdndFinished; - -extern Atom XA_XdndTypeList; -extern Atom XA_XdndSelection; - -extern Atom XA_XdndActionCopy; -extern Atom XA_XdndActionMove; -extern Atom XA_XdndActionLink; -extern Atom XA_XdndActionAsk; -extern Atom XA_XdndActionPrivate; -extern Atom XA_XdndActionList; - -/* Motif DnD atoms */ - -extern Atom _XA_MOTIF_DRAG_WINDOW; -extern Atom _XA_MOTIF_DRAG_TARGETS; -extern Atom _XA_MOTIF_DRAG_INITIATOR_INFO; -extern Atom _XA_MOTIF_DRAG_RECEIVER_INFO; -extern Atom _XA_MOTIF_DRAG_AND_DROP_MESSAGE; -extern Atom XA_XmTRANSFER_SUCCESS; -extern Atom XA_XmTRANSFER_FAILURE; -extern Atom _XA_MOTIF_ATOM_0; - -extern unsigned char MOTIF_BYTE_ORDER; - -/* Motif DnD macros */ - -#define SWAP4BYTES(l) {\ - struct {\ - unsigned t :32;\ - } bit32;\ - char n, *tp = (char *) &bit32;\ - bit32.t = l;\ - n = tp[0]; tp[0] = tp[3]; tp[3] = n;\ - n = tp[1]; tp[1] = tp[2]; tp[2] = n;\ - l = bit32.t;\ -} - -#define SWAP2BYTES(s) {\ - struct {\ - unsigned t :16;\ - } bit16;\ - char n, *tp = (char *) &bit16;\ - bit16.t = s;\ - n = tp[0]; tp[0] = tp[1]; tp[1] = n;\ - s = bit16.t;\ -} - -typedef struct DropSiteInfo { - Widget tlw; - jobject component; - Boolean isComposite; - uint32_t dsCnt; -} DropSiteInfo; - -Boolean awt_dnd_init(Display* display); -Boolean awt_dnd_ds_init(Display* display); - -Window get_awt_root_window(); - -/**************** checked_X* wrappers *****************************************/ -unsigned char -checked_XChangeProperty(Display* display, Window w, Atom property, Atom type, - int format, int mode, unsigned char* data, - int nelements); - -unsigned char -checked_XGetWindowProperty(Display* display, Window w, Atom property, - long long_offset, long long_length, Bool delete, - Atom req_type, Atom* actual_type_return, - int* actual_format_return, - unsigned long* nitems_return, - unsigned long* bytes_after_return, - unsigned char** prop_return); - -unsigned char -checked_XSendEvent(Display* display, Window w, Bool propagate, long event_mask, - XEvent* event_send); - -unsigned char -checked_XTranslateCoordinates(Display* display, Window src_w, Window dest_w, - int src_x, int src_y, int* dest_x_return, - int* dest_y_return, Window* child_return); - -unsigned char -checked_XSelectInput(Display* display, Window w, long event_mask); -/******************************************************************************/ - -jint xdnd_to_java_action(Atom action); -Atom java_to_xdnd_action(jint action); - -jint motif_to_java_actions(unsigned char action); -unsigned char java_to_motif_actions(jint action); - -void write_card8(void** p, CARD8 value); -void write_card16(void** p, CARD16 value); -void write_card32(void** p, CARD32 value); - -CARD8 read_card8(char* data, size_t offset); -CARD16 read_card16(char* data, size_t offset, char byte_order); -CARD32 read_card32(char* data, size_t offset, char byte_order); - -Window get_motif_window(Display* dpy); - -/*************************** TARGET LIST SUPPORT ***************************************/ - -int get_index_for_target_list(Display* dpy, Atom* targets, unsigned int num_targets); -void get_target_list_for_index(Display* dpy, int index, Atom** targets, unsigned - int* num_targets); - -/***************************************************************************************/ - -Boolean awt_dnd_process_event(XEvent* event); -Boolean awt_dnd_ds_process_event(XEvent* event); -Boolean awt_dnd_dt_process_event(XEvent* event); - -Window awt_dnd_ds_get_source_window(); - -/**************************** XEmbed server DnD support ***********************/ -void set_proxy_mode_source_window(Window window); -/******************************************************************************/ diff --git a/jdk/src/solaris/native/sun/awt/awt_dnd_ds.c b/jdk/src/solaris/native/sun/awt/awt_dnd_ds.c deleted file mode 100644 index 4edc454df82..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_dnd_ds.c +++ /dev/null @@ -1,1796 +0,0 @@ -/* - * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_dnd.h" - -/* Declares getCursor(JNIEnv, jobject) */ -#include "awt_Cursor.h" - -/* Define java constants */ -#include "java_awt_dnd_DnDConstants.h" -#include "sun_awt_dnd_SunDragSourceContextPeer.h" - -/* Define DECLARE_* macros */ -#include "awt_DataTransferer.h" - -#define GRAB_EVENT_MASK \ - (ButtonPressMask | ButtonMotionMask | ButtonReleaseMask) - -/* Events selected on the root window during drag. */ -#define ROOT_EVENT_MASK \ - (ButtonMotionMask | KeyPressMask | KeyReleaseMask) - -/* Events selected on registered receiver windows during drag. */ -#define RECEIVER_EVENT_MASK \ - (StructureNotifyMask) - - -/* in canvas.c */ -extern jint getModifiers(uint32_t state, jint button, jint keyCode); - -typedef struct { - CARD8 byte_order; - CARD8 protocol_version; - CARD16 index; - CARD32 selection_atom; -} InitiatorInfo; - -typedef enum { - /* - * Communicate with receivers of both protocols. - * If the receiver supports both protocols, - * choose Motif DnD for communication. - */ - DS_POLICY_PREFER_MOTIF, - /* - * Communicate with receivers of both protocols. - * If the receiver supports both protocols, - * choose XDnD for communication. [default] - */ - DS_POLICY_PREFER_XDND, - /* Communicate only with Motif DnD receivers. */ - DS_POLICY_ONLY_MOTIF, - /* Communicate only with XDnD receivers. */ - DS_POLICY_ONLY_XDND -} DragSourcePolicy; - - -/* The drag source policy. */ -static DragSourcePolicy drag_source_policy = DS_POLICY_PREFER_XDND; - -static Boolean dnd_in_progress = False; -static Boolean drag_in_progress = False; -static jobject source_peer = NULL; -static Atom* data_types = NULL; -static unsigned int data_types_count = 0; -static Window drag_root_window = None; -static EventMask your_root_event_mask = NoEventMask; -static Time latest_time_stamp = CurrentTime; - -/* The child of the root which is currently under the mouse. */ -static Window target_root_subwindow = None; - -static Window target_window = None; -static long target_window_mask = 0; -static Window target_proxy_window = None; -static Protocol target_protocol = NO_PROTOCOL; -static unsigned int target_protocol_version = 0; -/* - * The server time when the pointer entered the current target - - * needed on Motif DnD to filter out messages from the previous - * target. - * It is updated whenever the target_window is updated. - * If the target_window is set to non-None, it is set to the time stamp - * of the X event that trigger the update. Otherwise, it is set to CurrentTime. - */ -static Time target_enter_server_time = CurrentTime; - -static int x_root = 0; -static int y_root = 0; -static unsigned int event_state = 0; - -static jint source_action = java_awt_dnd_DnDConstants_ACTION_NONE; -static jint source_actions = java_awt_dnd_DnDConstants_ACTION_NONE; -static jint target_action = java_awt_dnd_DnDConstants_ACTION_NONE; - -/* Forward declarations */ -static void cleanup_drag(Display* dpy, Time time); -static Boolean process_proxy_mode_event(XEvent* xev); - -/**************************** XEmbed server DnD support ***********************/ -static Window proxy_mode_source_window = None; -/******************************************************************************/ - -/**************************** JNI stuff ***************************************/ - -DECLARE_JAVA_CLASS(dscp_clazz, "sun/awt/dnd/SunDragSourceContextPeer") - -static void -ds_postDragSourceDragEvent(JNIEnv* env, jint targetAction, unsigned int state, - int x, int y, jint dispatch_type) { - DECLARE_VOID_JAVA_METHOD(dscp_postDragSourceDragEvent, dscp_clazz, - "postDragSourceDragEvent", "(IIIII)V"); - - DASSERT(!JNU_IsNull(env, source_peer)); - if (JNU_IsNull(env, source_peer)) { - return; - } - - (*env)->CallVoidMethod(env, source_peer, dscp_postDragSourceDragEvent, - targetAction, getModifiers(state, 0, 0), x, y, - dispatch_type); -} - -static jint -ds_convertModifiersToDropAction(JNIEnv* env, unsigned int state) { - jint action; - DECLARE_STATIC_JINT_JAVA_METHOD(dscp_convertModifiersToDropAction, dscp_clazz, - "convertModifiersToDropAction", "(II)I"); - action = (*env)->CallStaticIntMethod(env, clazz, dscp_convertModifiersToDropAction, - getModifiers(state, 0, 0), source_actions); - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - return java_awt_dnd_DnDConstants_ACTION_NONE; - } - return action; -} - -static void -ds_postDragSourceEvent(JNIEnv* env, int x, int y) { - DECLARE_VOID_JAVA_METHOD(dscp_dragExit, dscp_clazz, - "dragExit", "(II)V"); - - DASSERT(!JNU_IsNull(env, source_peer)); - if (JNU_IsNull(env, source_peer)) { - return; - } - - (*env)->CallVoidMethod(env, source_peer, dscp_dragExit, x, y); -} - -static void -ds_postDragSourceDropEvent(JNIEnv* env, jboolean success, jint targetAction, - int x, int y) { - DECLARE_VOID_JAVA_METHOD(dscp_dragDropFinished, dscp_clazz, - "dragDropFinished", "(ZIII)V"); - - DASSERT(!JNU_IsNull(env, source_peer)); - if (JNU_IsNull(env, source_peer)) { - return; - } - - (*env)->CallVoidMethod(env, source_peer, dscp_dragDropFinished, - success, targetAction, x, y); -} - -/******************************************************************************/ - -static void -cancel_drag(XtPointer client_data, XtIntervalId* id) { - Time time_stamp = awt_util_getCurrentServerTime(); - - cleanup_drag(awt_display, time_stamp); -} - -#define DONT_CARE -1 - -static void -awt_popupCallback(Widget shell, XtPointer closure, XtPointer call_data) { - XtGrabKind grab_kind = XtGrabNone; - - if (call_data != NULL) { - grab_kind = *((XtGrabKind*)call_data); - } - - if (XmIsVendorShell(shell)) { - int input_mode; - XtVaGetValues(shell, XmNmwmInputMode, &input_mode, NULL); - switch (input_mode) { - case DONT_CARE: - case MWM_INPUT_MODELESS: - grab_kind = XtGrabNonexclusive; break; - case MWM_INPUT_PRIMARY_APPLICATION_MODAL: - case MWM_INPUT_SYSTEM_MODAL: - case MWM_INPUT_FULL_APPLICATION_MODAL: - grab_kind = XtGrabExclusive; break; - } - } - - if (grab_kind == XtGrabExclusive) { - /* - * We should cancel the drag on the toolkit thread. Otherwise, it can be - * called while the toolkit thread is waiting inside some drag callback. - * In this case Motif will crash when the drag callback returns. - */ - XtAppAddTimeOut(awt_appContext, 0L, cancel_drag, NULL); - } -} - -static XtInitProc xt_shell_initialize = NULL; - -static void -awt_ShellInitialize(Widget req, Widget new, ArgList args, Cardinal *num_args) { - XtAddCallback(new, XtNpopupCallback, awt_popupCallback, NULL); - (*xt_shell_initialize)(req, new, args, num_args); -} - -/* - * Fix for 4484572 (copied from awt_XmDnD.c). - * Modify the 'initialize' routine for all ShellWidget instances, so that it - * will install an XtNpopupCallback that cancels the current drag operation. - * It is needed, since AWT doesn't have full control over all ShellWidget - * instances (e.g. XmPopupMenu internally creates and popups an XmMenuShell). - */ -static void -awt_set_ShellInitialize() { - static Boolean inited = False; - - DASSERT(!inited); - if (inited) { - return; - } - - xt_shell_initialize = shellWidgetClass->core_class.initialize; - shellWidgetClass->core_class.initialize = (XtInitProc)awt_ShellInitialize; - inited = True; -} - -/* - * Returns True if initialization completes successfully. - */ -Boolean -awt_dnd_ds_init(Display* display) { - if (XSaveContext(display, XA_XdndSelection, awt_convertDataContext, - (XPointer)NULL) == XCNOMEM) { - return False; - } - - if (XSaveContext(display, _XA_MOTIF_ATOM_0, awt_convertDataContext, - (XPointer)NULL) == XCNOMEM) { - return False; - } - - { - char *ev = getenv("_JAVA_DRAG_SOURCE_POLICY"); - - /* By default XDnD protocol is preferred. */ - drag_source_policy = DS_POLICY_PREFER_XDND; - - if (ev != NULL) { - if (strcmp(ev, "PREFER_XDND") == 0) { - drag_source_policy = DS_POLICY_PREFER_XDND; - } else if (strcmp(ev, "PREFER_MOTIF") == 0) { - drag_source_policy = DS_POLICY_PREFER_MOTIF; - } else if (strcmp(ev, "ONLY_MOTIF") == 0) { - drag_source_policy = DS_POLICY_ONLY_MOTIF; - } else if (strcmp(ev, "ONLY_XDND") == 0) { - drag_source_policy = DS_POLICY_ONLY_XDND; - } - } - } - - awt_set_ShellInitialize(); - - return True; -} - -/* - * Returns a handle of the window used as a drag source. - */ -Window -awt_dnd_ds_get_source_window() { - return get_awt_root_window(); -} - -/* - * Returns True if a drag operation initiated by this client - * is still in progress. - */ -Boolean -awt_dnd_ds_in_progress() { - return dnd_in_progress; -} - -static void -ds_send_event_to_target(XClientMessageEvent* xclient) { - /* Shortcut if the source is in the same JVM. */ - if (XtWindowToWidget(xclient->display, target_proxy_window) != NULL) { - awt_dnd_dt_process_event((XEvent*)xclient); - } else { - XSendEvent(xclient->display, target_proxy_window, False, NoEventMask, - (XEvent*)xclient); - } -} - -static void -xdnd_send_enter(Display* dpy, Time time) { - XClientMessageEvent enter; - - enter.display = dpy; - enter.type = ClientMessage; - enter.window = target_window; - enter.format = 32; - enter.message_type = XA_XdndEnter; - enter.data.l[0] = awt_dnd_ds_get_source_window(); - enter.data.l[1] = target_protocol_version << XDND_PROTOCOL_SHIFT; - enter.data.l[1] |= data_types_count > 3 ? XDND_DATA_TYPES_BIT : 0; - enter.data.l[2] = data_types_count > 0 ? data_types[0] : None; - enter.data.l[3] = data_types_count > 1 ? data_types[1] : None; - enter.data.l[4] = data_types_count > 2 ? data_types[2] : None; - - ds_send_event_to_target(&enter); -} - -static void -motif_send_enter(Display* dpy, Time time) { - XClientMessageEvent enter; - - enter.display = dpy; - enter.type = ClientMessage; - enter.window = target_window; - enter.format = 8; - enter.message_type = _XA_MOTIF_DRAG_AND_DROP_MESSAGE; - - { - void* p = &enter.data.b[0]; - int flags = 0; - - flags |= java_to_motif_actions(source_action) << MOTIF_DND_ACTION_SHIFT; - flags |= java_to_motif_actions(source_actions) << MOTIF_DND_ACTIONS_SHIFT; - - write_card8(&p, TOP_LEVEL_ENTER | MOTIF_MESSAGE_FROM_INITIATOR); - write_card8(&p, MOTIF_BYTE_ORDER); - write_card16(&p, flags); - write_card32(&p, time); - write_card32(&p, awt_dnd_ds_get_source_window()); - write_card32(&p, _XA_MOTIF_ATOM_0); - } - - ds_send_event_to_target(&enter); -} - -static void -send_enter(Display* dpy, Time time) { - switch (target_protocol) { - case XDND_PROTOCOL: - xdnd_send_enter(dpy, time); - break; - case MOTIF_DND_PROTOCOL: - motif_send_enter(dpy, time); - break; - case NO_PROTOCOL: - default: - DTRACE_PRINTLN2("%s:%d send_enter: unknown DnD protocol.", __FILE__, __LINE__); - break; - } -} - -static void -xdnd_send_move(XMotionEvent* event) { - XClientMessageEvent move; - - move.display = event->display; - move.type = ClientMessage; - move.window = target_window; - move.format = 32; - move.message_type = XA_XdndPosition; - move.data.l[0] = awt_dnd_ds_get_source_window(); - move.data.l[1] = 0; /* flags */ - move.data.l[2] = event->x_root << 16 | event->y_root; - move.data.l[3] = event->time; - move.data.l[4] = java_to_xdnd_action(source_action); - - ds_send_event_to_target(&move); -} - -static void -motif_send_move(XMotionEvent* event) { - XClientMessageEvent move; - - move.display = event->display; - move.type = ClientMessage; - move.window = target_window; - move.format = 8; - move.message_type = _XA_MOTIF_DRAG_AND_DROP_MESSAGE; - - { - void* p = move.data.b; - int flags = 0; - - flags |= java_to_motif_actions(source_action) << MOTIF_DND_ACTION_SHIFT; - flags |= java_to_motif_actions(source_actions) << MOTIF_DND_ACTIONS_SHIFT; - - write_card8(&p, DRAG_MOTION | MOTIF_MESSAGE_FROM_INITIATOR); - write_card8(&p, MOTIF_BYTE_ORDER); - write_card16(&p, flags); - write_card32(&p, event->time); - write_card16(&p, event->x_root); - write_card16(&p, event->y_root); - } - - ds_send_event_to_target(&move); -} - -static void -send_move(XMotionEvent* event) { - switch (target_protocol) { - case XDND_PROTOCOL: - xdnd_send_move(event); - break; - case MOTIF_DND_PROTOCOL: - motif_send_move(event); - break; - case NO_PROTOCOL: - default: - DTRACE_PRINTLN2("%s:%d send_move: unknown DnD protocol.", __FILE__, __LINE__); - break; - } -} - -static void -xdnd_send_leave(Display* dpy, Time time) { - XClientMessageEvent leave; - - leave.display = dpy; - leave.type = ClientMessage; - leave.window = target_window; - leave.format = 32; - leave.message_type = XA_XdndLeave; - leave.data.l[0] = awt_dnd_ds_get_source_window(); - leave.data.l[1] = 0; - leave.data.l[2] = 0; - leave.data.l[3] = 0; - leave.data.l[4] = 0; - - ds_send_event_to_target(&leave); -} - -static void -motif_send_leave(Display* dpy, Time time) { - XClientMessageEvent leave; - - leave.display = dpy; - leave.type = ClientMessage; - leave.window = target_window; - leave.format = 8; - leave.message_type = _XA_MOTIF_DRAG_AND_DROP_MESSAGE; - - { - void* p = &leave.data.b[0]; - - write_card8(&p, TOP_LEVEL_LEAVE | MOTIF_MESSAGE_FROM_INITIATOR); - write_card8(&p, MOTIF_BYTE_ORDER); - write_card16(&p, 0); - write_card32(&p, time); - write_card32(&p, awt_dnd_ds_get_source_window()); - } - - ds_send_event_to_target(&leave); -} - -static void -send_leave(Display* dpy, Time time) { - switch (target_protocol) { - case XDND_PROTOCOL: - xdnd_send_leave(dpy, time); - break; - case MOTIF_DND_PROTOCOL: - motif_send_leave(dpy, time); - break; - case NO_PROTOCOL: - default: - DTRACE_PRINTLN2("%s:%d send_leave: unknown DnD protocol.", __FILE__, __LINE__); - break; - } -} - - -static void -xdnd_send_drop(XButtonEvent* event) { - XClientMessageEvent drop; - - drop.display = event->display; - drop.type = ClientMessage; - drop.window = target_window; - drop.format = 32; - drop.message_type = XA_XdndDrop; - drop.data.l[0] = awt_dnd_ds_get_source_window(); - drop.data.l[1] = 0; /* flags */ - drop.data.l[2] = event->time; /* ### */ - drop.data.l[3] = 0; - drop.data.l[4] = 0; - - ds_send_event_to_target(&drop); -} - -static void -motif_send_drop(XButtonEvent* event) { - XClientMessageEvent drop; - - /* - * Motif drop sites expect TOP_LEVEL_LEAVE before DROP_START. - */ - motif_send_leave(event->display, event->time); - - drop.display = event->display; - drop.type = ClientMessage; - drop.window = target_window; - drop.format = 8; - drop.message_type = _XA_MOTIF_DRAG_AND_DROP_MESSAGE; - - { - void* p = &drop.data.b[0]; - int flags = 0; - - flags |= java_to_motif_actions(source_action) << MOTIF_DND_ACTION_SHIFT; - flags |= java_to_motif_actions(source_actions) << MOTIF_DND_ACTIONS_SHIFT; - - write_card8(&p, DROP_START | MOTIF_MESSAGE_FROM_INITIATOR); - write_card8(&p, MOTIF_BYTE_ORDER); - write_card16(&p, flags); - write_card32(&p, event->time); - write_card16(&p, event->x_root); - write_card16(&p, event->y_root); - write_card32(&p, _XA_MOTIF_ATOM_0); - write_card32(&p, awt_dnd_ds_get_source_window()); - } - - ds_send_event_to_target(&drop); -} - -static void -send_drop(XButtonEvent* event) { - switch (target_protocol) { - case XDND_PROTOCOL: - xdnd_send_drop(event); - break; - case MOTIF_DND_PROTOCOL: - motif_send_drop(event); - break; - case NO_PROTOCOL: - default: - DTRACE_PRINTLN2("%s:%d send_drop: unknown DnD protocol.", __FILE__, __LINE__); - break; - } -} - -static void -remove_dnd_grab(Display* dpy, Time time) { - XUngrabPointer(dpy, time); - XUngrabKeyboard(dpy, time); - - /* Restore the root event mask if it was changed. */ - if ((your_root_event_mask | ROOT_EVENT_MASK) != your_root_event_mask && - drag_root_window != None) { - - XSelectInput(dpy, drag_root_window, your_root_event_mask); - - drag_root_window = None; - your_root_event_mask = NoEventMask; - } -} - -static void -cleanup_target_info(Display* dpy) { - target_root_subwindow = None; - - target_window = None; - target_proxy_window = None; - target_protocol = NO_PROTOCOL; - target_protocol_version = 0; - target_enter_server_time = CurrentTime; - target_action = java_awt_dnd_DnDConstants_ACTION_NONE; -} - -static void -cleanup_drag(Display* dpy, Time time) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - - if (dnd_in_progress) { - if (target_window != None) { - send_leave(dpy, time); - } - - if (target_action != java_awt_dnd_DnDConstants_ACTION_NONE) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - ds_postDragSourceEvent(env, x_root, y_root); - } - - ds_postDragSourceDropEvent(env, JNI_FALSE, - java_awt_dnd_DnDConstants_ACTION_NONE, - x_root, y_root); - } - - /* Cleanup the global state */ - dnd_in_progress = False; - drag_in_progress = False; - data_types_count = 0; - if (data_types != NULL) { - free(data_types); - data_types = NULL; - } - if (!JNU_IsNull(env, source_peer)) { - (*env)->DeleteGlobalRef(env, source_peer); - source_peer = NULL; - } - - cleanup_target_info(dpy); - - remove_dnd_grab(dpy, time); - - XDeleteProperty(awt_display, awt_dnd_ds_get_source_window(), _XA_MOTIF_ATOM_0); - XDeleteProperty(awt_display, awt_dnd_ds_get_source_window(), XA_XdndTypeList); - XDeleteProperty(awt_display, awt_dnd_ds_get_source_window(), XA_XdndActionList); - XtDisownSelection(awt_root_shell, _XA_MOTIF_ATOM_0, time); - XtDisownSelection(awt_root_shell, XA_XdndSelection, time); - - awt_cleanupConvertDataContext(env, _XA_MOTIF_ATOM_0); - awt_cleanupConvertDataContext(env, XA_XdndSelection); -} - -static void -process_drop(XButtonEvent* event) { - unsigned char ret; - XWindowAttributes xwa; - - DASSERT(target_window != None); - - XGetWindowAttributes(event->display, target_window, &xwa); - - target_window_mask = xwa.your_event_mask; - - /* Select for DestoyNotify to cleanup if the target crashes. */ - ret = checked_XSelectInput(event->display, target_window, - (target_window_mask | StructureNotifyMask)); - - if (ret == Success) { - send_drop(event); - } else { - DTRACE_PRINTLN2("%s:%d drop rejected - invalid window.", - __FILE__, __LINE__); - cleanup_drag(event->display, event->time); - } -} - -static Window -find_client_window(Display* dpy, Window window) { - Window root, parent, *children; - unsigned int nchildren, idx; - - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - Status ret; - - if (XGetWindowProperty(dpy, window, XA_WM_STATE, 0, 0, False, - AnyPropertyType, &type, &format, &nitems, - &after, &data) == Success) { - XFree(data); - } - - if (type != None) { - return window; - } - - if (!XQueryTree(dpy, window, &root, &parent, &children, &nchildren)) { - return None; - } - - if (children == NULL) { - return None; - } - - for (idx = 0; idx < nchildren; idx++) { - Window win = find_client_window(dpy, children[idx]); - if (win != None) { - XFree(children); - return win; - } - } - - XFree(children); - return None; -} - -static void -do_update_target_window(Display* dpy, Window subwindow, Time time) { - Window client_window = None; - Window proxy_window = None; - Protocol protocol = NO_PROTOCOL; - unsigned int protocol_version = 0; - Boolean is_receiver = False; - - client_window = find_client_window(dpy, subwindow); - - if (client_window != None) { - /* Request status */ - int status; - - /* Returns of XGetWindowProperty */ - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - - /* - * No need for checked_XGetWindowProperty, since we check the returned - * property type anyway. - */ - if (drag_source_policy != DS_POLICY_ONLY_XDND) { - - data = NULL; - status = XGetWindowProperty(dpy, client_window, - _XA_MOTIF_DRAG_RECEIVER_INFO, - 0, 0xFFFF, False, AnyPropertyType, - &type, &format, &nitems, &after, &data); - - if (status == Success && data != NULL && type != None && format == 8 - && nitems >= MOTIF_RECEIVER_INFO_SIZE) { - unsigned char byte_order = read_card8((char*)data, 0); - unsigned char drag_protocol_style = read_card8((char*)data, 2); - - switch (drag_protocol_style) { - case MOTIF_PREFER_PREREGISTER_STYLE : - case MOTIF_PREFER_DYNAMIC_STYLE : - case MOTIF_DYNAMIC_STYLE : - case MOTIF_PREFER_RECEIVER_STYLE : - proxy_window = read_card32((char*)data, 4, byte_order); - protocol = MOTIF_DND_PROTOCOL; - protocol_version = read_card8((char*)data, 1); - is_receiver = True; - break; - default: - DTRACE_PRINTLN3("%s:%d unsupported protocol style (%d).", - __FILE__, __LINE__, (int)drag_protocol_style); - } - } - - if (status == Success) { - XFree(data); - data = NULL; - } - } - - if (drag_source_policy != DS_POLICY_ONLY_MOTIF && - (drag_source_policy != DS_POLICY_PREFER_MOTIF || !is_receiver)) { - - data = NULL; - status = XGetWindowProperty(dpy, client_window, XA_XdndAware, 0, 1, - False, AnyPropertyType, &type, &format, - &nitems, &after, &data); - - if (status == Success && data != NULL && type == XA_ATOM) { - unsigned int target_version = *((unsigned int*)data); - - if (target_version >= XDND_MIN_PROTOCOL_VERSION) { - proxy_window = None; - protocol = XDND_PROTOCOL; - protocol_version = target_version < XDND_PROTOCOL_VERSION ? - target_version : XDND_PROTOCOL_VERSION; - is_receiver = True; - } - } - - /* Retrieve the proxy window handle and check if it is valid. */ - if (protocol == XDND_PROTOCOL) { - if (status == Success) { - XFree(data); - } - - data = NULL; - status = XGetWindowProperty(dpy, client_window, XA_XdndProxy, 0, - 1, False, XA_WINDOW, &type, &format, - &nitems, &after, &data); - - if (status == Success && data != NULL && type == XA_WINDOW) { - proxy_window = *((Window*)data); - } - - if (proxy_window != None) { - if (status == Success) { - XFree(data); - } - - data = NULL; - status = XGetWindowProperty(dpy, proxy_window, XA_XdndProxy, - 0, 1, False, XA_WINDOW, &type, - &format, &nitems, &after, &data); - - if (status != Success || data == NULL || type != XA_WINDOW || - *((Window*)data) != proxy_window) { - proxy_window = None; - } else { - if (status == Success) { - XFree(data); - } - - data = NULL; - status = XGetWindowProperty(dpy, proxy_window, - XA_XdndAware, 0, 1, False, - AnyPropertyType, &type, - &format, &nitems, &after, - &data); - - if (status != Success || data == NULL || type != XA_ATOM) { - proxy_window = None; - } - } - } - } - - XFree(data); - } - - if (proxy_window == None) { - proxy_window = client_window; - } - } - - if (is_receiver) { - target_window = client_window; - target_proxy_window = proxy_window; - target_protocol = protocol; - target_protocol_version = protocol_version; - } else { - target_window = None; - target_proxy_window = None; - target_protocol = NO_PROTOCOL; - target_protocol_version = 0; - } - - target_action = java_awt_dnd_DnDConstants_ACTION_NONE; - - if (target_window != None) { - target_enter_server_time = time; - } else { - target_enter_server_time = CurrentTime; - } - - target_root_subwindow = subwindow; -} - -static void -update_target_window(XMotionEvent* event) { - Display* dpy = event->display; - int x = event->x_root; - int y = event->x_root; - Time time = event->time; - Window subwindow = event->subwindow; - - /* - * If this event had occurred before the pointer was grabbed, - * query the server for the current root subwindow. - */ - if (event->window != event->root) { - int xw, yw, xr, yr; - unsigned int modifiers; - XQueryPointer(dpy, event->root, &event->root, &subwindow, - &xr, &yr, &xw, &yw, &modifiers); - } - - if (target_root_subwindow != subwindow) { - if (target_window != None) { - send_leave(dpy, time); - - /* - * Neither Motif DnD nor XDnD provide a mean for the target - * to notify the source that the pointer exits the drop site - * that occupies the whole top level. - * We detect this situation and post dragExit. - */ - if (target_action != java_awt_dnd_DnDConstants_ACTION_NONE) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - ds_postDragSourceEvent(env, x, y); - } - } - - /* Update the global state. */ - do_update_target_window(dpy, subwindow, time); - - if (target_window != None) { - send_enter(dpy, time); - } - } -} - -/* - * Updates the source action based on the specified event state. - * Returns True if source action changed, False otherwise. - */ -static Boolean -update_source_action(unsigned int state) { - JNIEnv* env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - jint action = ds_convertModifiersToDropAction(env, state); - if (source_action == action) { - return False; - } - source_action = action; - return True; -} - -static void -handle_mouse_move(XMotionEvent* event) { - if (!drag_in_progress) { - return; - } - - if (x_root != event->x_root || y_root != event->y_root) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - ds_postDragSourceDragEvent(env, target_action, event->state, - event->x_root, event->y_root, - sun_awt_dnd_SunDragSourceContextPeer_DISPATCH_MOUSE_MOVED); - - x_root = event->x_root; - y_root = event->y_root; - } - - if (event_state != event->state) { - if (update_source_action(event->state) && target_window != None) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - ds_postDragSourceDragEvent(env, target_action, event->state, - event->x_root, event->y_root, - sun_awt_dnd_SunDragSourceContextPeer_DISPATCH_CHANGED); - } - event_state = event->state; - } - - update_target_window(event); - - if (target_window != None) { - send_move(event); - } -} - -static Boolean -handle_xdnd_status(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - long* event_data = event->data.l; - Window target_win = None; - jint action = java_awt_dnd_DnDConstants_ACTION_NONE; - - DTRACE_PRINTLN4("%s:%d XdndStatus target_window=%ld target_protocol=%d.", - __FILE__, __LINE__, target_window, target_protocol); - - if (target_protocol != XDND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d XdndStatus rejected - invalid state.", - __FILE__, __LINE__); - return True; - } - - target_win = event_data[0]; - - /* Ignore XDnD messages from all other windows. */ - if (target_window != target_win) { - DTRACE_PRINTLN4("%s:%d XdndStatus rejected - invalid target window cur=%ld this=%ld.", - __FILE__, __LINE__, target_window, target_win); - return True; - } - - if (event_data[1] & XDND_ACCEPT_DROP_FLAG) { - /* This feature is new in XDnD version 2, but we can use it as XDnD - compliance only requires supporting version 3 and up. */ - action = xdnd_to_java_action(event_data[4]); - } - - if (action == java_awt_dnd_DnDConstants_ACTION_NONE && - target_action != java_awt_dnd_DnDConstants_ACTION_NONE) { - ds_postDragSourceEvent(env, x_root, y_root); - } else if (action != java_awt_dnd_DnDConstants_ACTION_NONE) { - jint type = 0; - - if (target_action == java_awt_dnd_DnDConstants_ACTION_NONE) { - type = sun_awt_dnd_SunDragSourceContextPeer_DISPATCH_ENTER; - } else { - type = sun_awt_dnd_SunDragSourceContextPeer_DISPATCH_MOTION; - } - - ds_postDragSourceDragEvent(env, action, event_state, - x_root, y_root, type); - } - - target_action = action; - - return True; -} - -static Boolean -handle_xdnd_finished(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - long* event_data = event->data.l; - Window target_win = None; - jboolean success = JNI_TRUE; - jint action = java_awt_dnd_DnDConstants_ACTION_NONE; - - if (target_protocol != XDND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d XdndStatus rejected - invalid state.", - __FILE__, __LINE__); - return True; - } - - target_win = event_data[0]; - - /* Ignore XDnD messages from all other windows. */ - if (target_window != target_win) { - DTRACE_PRINTLN4("%s:%d XdndStatus rejected - invalid target window cur=%ld this=%ld.", - __FILE__, __LINE__, target_window, target_win); - return True; - } - - if (target_protocol_version >= 5) { - success = (event_data[1] & XDND_ACCEPT_DROP_FLAG) != 0 ? - JNI_TRUE : JNI_FALSE; - action = xdnd_to_java_action(event_data[2]); - } else { - /* Assume that the drop was successful and the performed drop action is - the drop action accepted with the latest XdndStatus message. */ - success = JNI_TRUE; - action = target_action; - } - - ds_postDragSourceDropEvent(env, success, action, x_root, y_root); - - dnd_in_progress = False; - - XSelectInput(event->display, target_win, target_window_mask); - - cleanup_drag(event->display, CurrentTime); - - return True; -} - -static Boolean -handle_motif_client_message(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - int reason = (int)(event->data.b[0] & MOTIF_MESSAGE_REASON_MASK); - int origin = (int)(event->data.b[0] & MOTIF_MESSAGE_SENDER_MASK); - unsigned char byte_order = event->data.b[1]; - jint action = java_awt_dnd_DnDConstants_ACTION_NONE; - Time time = CurrentTime; - int x = 0, y = 0; - - /* Only receiver messages should be handled. */ - if (origin != MOTIF_MESSAGE_FROM_RECEIVER) { - return False; - } - - if (target_protocol != MOTIF_DND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d _MOTIF_DRAG_AND_DROP_MESSAGE rejected - invalid state.", - __FILE__, __LINE__); - return True; - } - - switch (reason) { - case DROP_SITE_ENTER: - case DROP_SITE_LEAVE: - case DRAG_MOTION: - case OPERATION_CHANGED: - break; - default: - return False; - } - - time = read_card32(event->data.b, 4, byte_order); - - /* Discard events from the previous receiver. */ - if (target_enter_server_time == CurrentTime || - time < target_enter_server_time) { - DTRACE_PRINTLN2("%s:%d _MOTIF_DRAG_AND_DROP_MESSAGE rejected - invalid time.", - __FILE__, __LINE__); - return True; - } - - if (reason != DROP_SITE_LEAVE) { - CARD16 flags = read_card16(event->data.b, 2, byte_order); - unsigned char status = (flags & MOTIF_DND_STATUS_MASK) >> - MOTIF_DND_STATUS_SHIFT; - unsigned char motif_action = (flags & MOTIF_DND_ACTION_MASK) >> - MOTIF_DND_ACTION_SHIFT; - - if (status == MOTIF_VALID_DROP_SITE) { - action = motif_to_java_actions(motif_action); - } else { - action = java_awt_dnd_DnDConstants_ACTION_NONE; - } - - x = read_card16(event->data.b, 8, byte_order); - y = read_card16(event->data.b, 10, byte_order); - } - - /* - * We should derive the type of java event to post not from the message - * reason, but from the combination of the current and previous target - * actions: - * Even if the reason is DROP_SITE_LEAVE we shouldn't post dragExit - * if the drag was rejected earlier. - * Even if the reason is DROP_SITE_ENTER we shouldn't post dragEnter - * if the drag is not accepted. - */ - if (target_action != java_awt_dnd_DnDConstants_ACTION_NONE && - action == java_awt_dnd_DnDConstants_ACTION_NONE) { - - ds_postDragSourceEvent(env, x, y); - } else if (action != java_awt_dnd_DnDConstants_ACTION_NONE) { - jint type = 0; - - if (target_action == java_awt_dnd_DnDConstants_ACTION_NONE) { - type = sun_awt_dnd_SunDragSourceContextPeer_DISPATCH_ENTER; - } else { - type = sun_awt_dnd_SunDragSourceContextPeer_DISPATCH_MOTION; - } - - ds_postDragSourceDragEvent(env, action, event_state, x, y, type); - } - - target_action = action; - - return True; -} - -/* - * Handles client messages. - * Returns True if the event is processed, False otherwise. - */ -static Boolean -handle_client_message(XClientMessageEvent* event) { - if (event->message_type == XA_XdndStatus) { - return handle_xdnd_status(event); - } else if (event->message_type == XA_XdndFinished) { - return handle_xdnd_finished(event); - } else if (event->message_type == _XA_MOTIF_DRAG_AND_DROP_MESSAGE) { - return handle_motif_client_message(event); - } - return False; -} - -/* - * Similar to XtLastTimestampProcessed(). We cannot use Xt time stamp, as it is - * updated in XtDispatchEvent that may not be called if a java event is - * consumed. This can make Xt time stamp out-of-date and cause XGrab* failures - * with GrabInvalidTime reason. - */ -static Time -get_latest_time_stamp() { - return latest_time_stamp; -} - -static void -update_latest_time_stamp(XEvent* event) { - Time time = latest_time_stamp; - - switch (event->type) { - case KeyPress: - case KeyRelease: time = event->xkey.time; break; - case ButtonPress: - case ButtonRelease: time = event->xbutton.time; break; - case MotionNotify: time = event->xmotion.time; break; - case EnterNotify: - case LeaveNotify: time = event->xcrossing.time; break; - case PropertyNotify: time = event->xproperty.time; break; - case SelectionClear: time = event->xselectionclear.time; break; - } - - latest_time_stamp = time; -} - -Boolean -awt_dnd_ds_process_event(XEvent* event) { - Display* dpy = event->xany.display; - - update_latest_time_stamp(event); - - if (process_proxy_mode_event(event)) { - return True; - } - - if (!dnd_in_progress) { - return False; - } - - /* Process drag and drop messages. */ - switch (event->type) { - case ClientMessage: - return handle_client_message(&event->xclient); - case DestroyNotify: - /* Target crashed during drop processing - cleanup. */ - if (!drag_in_progress && - event->xdestroywindow.window == target_window) { - cleanup_drag(dpy, CurrentTime); - return True; - } - /* Pass along */ - return False; - } - - if (!drag_in_progress) { - return False; - } - - /* Process drag-only messages. */ - switch (event->type) { - case KeyRelease: - case KeyPress: { - KeySym keysym = XKeycodeToKeysym(dpy, event->xkey.keycode, 0); - switch (keysym) { - case XK_Escape: { - if (keysym == XK_Escape) { - remove_dnd_grab(dpy, event->xkey.time); - cleanup_drag(dpy, event->xkey.time); - } - break; - } - case XK_Control_R: - case XK_Control_L: - case XK_Shift_R: - case XK_Shift_L: { - Window subwindow; - int xw, yw, xr, yr; - unsigned int modifiers; - XQueryPointer(event->xkey.display, event->xkey.root, &event->xkey.root, &subwindow, - &xr, &yr, &xw, &yw, &modifiers); - event->xkey.state = modifiers; - //It's safe to use key event as motion event since we use only their common fields. - handle_mouse_move(&event->xmotion); - break; - } - } - return True; - } - case ButtonPress: - return True; - case MotionNotify: - handle_mouse_move(&event->xmotion); - return True; - case ButtonRelease: - /* - * On some X servers it could happen that ButtonRelease coordinates - * differ from the latest MotionNotify coordinates, so we need to - * process it as a mouse motion. - * MotionNotify differs from ButtonRelease only in is_hint member, but - * we never use it, so it is safe to cast to MotionNotify. - */ - handle_mouse_move(&event->xmotion); - if (event->xbutton.button == Button1 || event->xbutton.button == Button2) { - // drag is initiated with Button1 or Button2 pressed and - // ended on release of either of these buttons (as the same - // behavior was with our old Motif DnD-based implementation) - remove_dnd_grab(dpy, event->xbutton.time); - drag_in_progress = False; - if (target_window != None && target_action != java_awt_dnd_DnDConstants_ACTION_NONE) { - /* - * ACTION_NONE indicates that either the drop target rejects the - * drop or it haven't responded yet. The latter could happen in - * case of fast drag, slow target-server connection or slow - * drag notifications processing on the target side. - */ - process_drop(&event->xbutton); - } else { - cleanup_drag(dpy, event->xbutton.time); - } - } - return True; - default: - return False; - } -} - -static Boolean -motif_convert_proc(Widget w, Atom* selection, Atom* target, Atom* type, - XtPointer* value, unsigned long* length, int32_t* format) { - - if (*target == XA_XmTRANSFER_SUCCESS || - *target == XA_XmTRANSFER_FAILURE) { - - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - jboolean success = - (*target == XA_XmTRANSFER_SUCCESS) ? JNI_TRUE : JNI_FALSE; - - ds_postDragSourceDropEvent(env, success, target_action, - x_root, y_root); - - dnd_in_progress = False; - - XSelectInput(XtDisplay(w), target_window, target_window_mask); - - cleanup_drag(XtDisplay(w), CurrentTime); - - *type = *target; - *length = 0; - *format = 32; - *value = NULL; - - return True; - } else { - return awt_convertData(w, selection, target, type, value, length, - format); - } -} - -static Boolean -set_convert_data_context(JNIEnv* env, Display* dpy, XID xid, jobject component, - jobject transferable, jobject formatMap, - jlongArray formats) { - awt_convertDataCallbackStruct* structPtr = NULL; - - if (XFindContext(awt_display, xid, awt_convertDataContext, - (XPointer*)&structPtr) == XCNOMEM || structPtr != NULL) { - return False; - } - - structPtr = calloc(1, sizeof(awt_convertDataCallbackStruct)); - if (structPtr == NULL) { - return False; - } - - structPtr->source = (*env)->NewGlobalRef(env, component); - structPtr->transferable = (*env)->NewGlobalRef(env, transferable); - structPtr->formatMap = (*env)->NewGlobalRef(env, formatMap); - structPtr->formats = (*env)->NewGlobalRef(env, formats); - - if (JNU_IsNull(env, structPtr->source) || - JNU_IsNull(env, structPtr->transferable) || - JNU_IsNull(env, structPtr->formatMap) || - JNU_IsNull(env, structPtr->formats)) { - - if (!JNU_IsNull(env, structPtr->source)) { - (*env)->DeleteGlobalRef(env, structPtr->source); - } - if (!JNU_IsNull(env, structPtr->transferable)) { - (*env)->DeleteGlobalRef(env, structPtr->transferable); - } - if (!JNU_IsNull(env, structPtr->formatMap)) { - (*env)->DeleteGlobalRef(env, structPtr->formatMap); - } - if (!JNU_IsNull(env, structPtr->formats)) { - (*env)->DeleteGlobalRef(env, structPtr->formats); - } - free(structPtr); - return False; - } - - if (XSaveContext(dpy, xid, awt_convertDataContext, - (XPointer)structPtr) == XCNOMEM) { - free(structPtr); - return False; - } - - return True; -} - -/* - * Convenience routine. Constructs an appropriate exception message based on the - * specified prefix and the return code of XGrab* function and throws an - * InvalidDnDOperationException with the constructed message. - */ -static void -throw_grab_failure_exception(JNIEnv* env, int ret_code, char* msg_prefix) { - char msg[200]; - char* msg_cause = ""; - - switch (ret_code) { - case GrabNotViewable: msg_cause = "not viewable"; break; - case AlreadyGrabbed: msg_cause = "already grabbed"; break; - case GrabInvalidTime: msg_cause = "invalid time"; break; - case GrabFrozen: msg_cause = "grab frozen"; break; - default: msg_cause = "unknown failure"; break; - } - - sprintf(msg, "%s: %s.", msg_prefix, msg_cause); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - msg); -} - -/* - * Sets the proxy mode source window - the source window which the drag - * notifications from an XEmbed client should be forwarded to. - * If the window is not None and there is a drag operation in progress, - * throws InvalidDnDOperationException and doesn't change - * proxy_mode_source_window. - * The caller mush hold AWT_LOCK. - */ -void -set_proxy_mode_source_window(Window window) { - if (window != None && dnd_in_progress) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Drag and drop is already in progress."); - return; - } - - proxy_mode_source_window = window; -} - -/* - * Checks if the event is a drag notification from an XEmbed client. - * If it is, forwards this event back to the current source and returns True. - * Otherwise, returns False. - * Currently only XDnD protocol notifications are recognized. - * The caller must hold AWT_LOCK. - */ -static Boolean -process_proxy_mode_event(XEvent* event) { - if (proxy_mode_source_window == None) { - return False; - } - - if (event->type == ClientMessage) { - XClientMessageEvent* xclient = &event->xclient; - if (xclient->message_type == XA_XdndStatus || - xclient->message_type == XA_XdndFinished) { - Window source = proxy_mode_source_window; - - xclient->data.l[0] = xclient->window; - xclient->window = source; - - XSendEvent(xclient->display, source, False, NoEventMask, - (XEvent*)xclient); - - if (xclient->message_type == XA_XdndFinished) { - proxy_mode_source_window = None; - } - - return True; - } - } - - return False; -} - -/* - * Class: sun_awt_motif_X11DragSourceContextPeer - * Method: startDrag - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_X11DragSourceContextPeer_startDrag(JNIEnv *env, - jobject this, - jobject component, - jobject wpeer, - jobject transferable, - jobject trigger, - jobject cursor, - jint ctype, - jint actions, - jlongArray formats, - jobject formatMap) { - Time time_stamp = CurrentTime; - Cursor xcursor = None; - Window root_window = None; - Atom* targets = NULL; - jsize num_targets = 0; - - AWT_LOCK(); - - if (dnd_in_progress) { - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Drag and drop is already in progress."); - AWT_UNLOCK(); - return; - } - - if (proxy_mode_source_window != None) { - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Proxy drag is in progress."); - AWT_UNLOCK(); - return; - } - - if (!awt_dnd_init(awt_display)) { - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "DnD subsystem initialization failed."); - AWT_UNLOCK(); - return; - } - - if (!JNU_IsNull(env, cursor)) { - xcursor = getCursor(env, cursor); - - if (xcursor == None) { - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Invalid drag cursor"); - AWT_UNLOCK(); - } - } - - /* Determine the root window for the drag operation. */ - { - struct FrameData* wdata = (struct FrameData*) - JNU_GetLongFieldAsPtr(env, wpeer, mComponentPeerIDs.pData); - - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "Null component data"); - AWT_UNLOCK(); - return; - } - - if (wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "Null shell widget"); - AWT_UNLOCK(); - return; - } - - root_window = RootWindowOfScreen(XtScreen(wdata->winData.shell)); - - if (root_window == None) { - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot get the root window for the drag operation."); - AWT_UNLOCK(); - return; - } - } - - time_stamp = get_latest_time_stamp(); - - /* Extract the targets from java array. */ - { - targets = NULL; - num_targets = (*env)->GetArrayLength(env, formats); - - /* - * In debug build GetLongArrayElements aborts with assertion on an empty - * array. - */ - if (num_targets > 0) { - jboolean isCopy = JNI_TRUE; - jlong* java_targets = (*env)->GetLongArrayElements(env, formats, - &isCopy); - - if ((*env)->ExceptionCheck(env) == JNI_TRUE) { - AWT_UNLOCK(); - return; - } - - if (java_targets != NULL) { - targets = (Atom*)malloc(num_targets * sizeof(Atom)); - if (targets != NULL) { -#ifdef _LP64 - memcpy(targets, java_targets, num_targets * sizeof(Atom)); -#else - jsize i; - - for (i = 0; i < num_targets; i++) { - targets[i] = (Atom)java_targets[i]; - } -#endif - } - (*env)->ReleaseLongArrayElements(env, formats, java_targets, - JNI_ABORT); - } - } - if (targets == NULL) { - num_targets = 0; - } - } - - /* Write the XDnD initiator info on the awt_root_shell. */ - { - unsigned char ret; - Atom action_atoms[3]; - unsigned int action_count = 0; - - if (actions & java_awt_dnd_DnDConstants_ACTION_COPY) { - action_atoms[action_count] = XA_XdndActionCopy; - action_count++; - } - if (actions & java_awt_dnd_DnDConstants_ACTION_MOVE) { - action_atoms[action_count] = XA_XdndActionMove; - action_count++; - } - if (actions & java_awt_dnd_DnDConstants_ACTION_LINK) { - action_atoms[action_count] = XA_XdndActionLink; - action_count++; - } - - ret = checked_XChangeProperty(awt_display, awt_dnd_ds_get_source_window(), - XA_XdndActionList, XA_ATOM, 32, - PropModeReplace, (unsigned char*)action_atoms, - action_count * sizeof(Atom)); - - if (ret != Success) { - cleanup_drag(awt_display, time_stamp); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot write XdndActionList property"); - AWT_UNLOCK(); - return; - } - - ret = checked_XChangeProperty(awt_display, awt_dnd_ds_get_source_window(), - XA_XdndTypeList, XA_ATOM, 32, - PropModeReplace, (unsigned char*)targets, - num_targets); - - if (ret != Success) { - cleanup_drag(awt_display, time_stamp); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot write XdndTypeList property"); - AWT_UNLOCK(); - return; - } - } - - /* Write the Motif DnD initiator info on the awt_root_shell. */ - { - InitiatorInfo info; - unsigned char ret; - int target_list_index = - get_index_for_target_list(awt_display, targets, num_targets); - - if (target_list_index == -1) { - cleanup_drag(awt_display, time_stamp); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot determine the target list index."); - AWT_UNLOCK(); - return; - } - - info.byte_order = MOTIF_BYTE_ORDER; - info.protocol_version = MOTIF_DND_PROTOCOL_VERSION; - info.index = target_list_index; - info.selection_atom = _XA_MOTIF_ATOM_0; - - ret = checked_XChangeProperty(awt_display, awt_dnd_ds_get_source_window(), - _XA_MOTIF_ATOM_0, - _XA_MOTIF_DRAG_INITIATOR_INFO, 8, - PropModeReplace, (unsigned char*)&info, - sizeof(InitiatorInfo)); - - if (ret != Success) { - cleanup_drag(awt_display, time_stamp); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot write the Motif DnD initiator info"); - AWT_UNLOCK(); - return; - } - } - - /* Acquire XDnD selection ownership. */ - if (XtOwnSelection(awt_root_shell, XA_XdndSelection, time_stamp, - awt_convertData, NULL, NULL) != True) { - cleanup_drag(awt_display, time_stamp); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot acquire XdndSelection ownership."); - AWT_UNLOCK(); - return; - } - - /* Acquire Motif DnD selection ownership. */ - if (XtOwnSelection(awt_root_shell, _XA_MOTIF_ATOM_0, time_stamp, - motif_convert_proc, NULL, NULL) != True) { - cleanup_drag(awt_display, time_stamp); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot acquire Motif DnD selection ownership."); - AWT_UNLOCK(); - return; - } - - /* - * Store the information needed to convert data for both selections - * in awt_convertDataContext. - */ - { - if (!set_convert_data_context(env, awt_display, XA_XdndSelection, - component, transferable, formatMap, - formats)) { - cleanup_drag(awt_display, time_stamp); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot save context for XDnD selection data conversion."); - AWT_UNLOCK(); - return; - } - - if (!set_convert_data_context(env, awt_display, _XA_MOTIF_ATOM_0, - component, transferable, formatMap, - formats)) { - cleanup_drag(awt_display, time_stamp); - JNU_ThrowByName(env, "java/awt/dnd/InvalidDnDOperationException", - "Cannot save context for Motif DnD selection data conversion."); - AWT_UNLOCK(); - return; - } - } - - /* Install X grabs. */ - { - XWindowAttributes xwa; - int ret; - - XGetWindowAttributes(awt_display, root_window, &xwa); - - your_root_event_mask = xwa.your_event_mask; - - XSelectInput(awt_display, root_window, - your_root_event_mask | ROOT_EVENT_MASK); - - ret = XGrabPointer(awt_display, - root_window, - False, - GRAB_EVENT_MASK, - GrabModeAsync, - GrabModeAsync, - None, - xcursor, - time_stamp); - - if (ret != GrabSuccess) { - cleanup_drag(awt_display, time_stamp); - throw_grab_failure_exception(env, ret, "Cannot grab pointer"); - AWT_UNLOCK(); - return; - } - - ret = XGrabKeyboard(awt_display, - root_window, - False, - GrabModeAsync, - GrabModeAsync, - time_stamp); - - if (ret != GrabSuccess) { - cleanup_drag(awt_display, time_stamp); - throw_grab_failure_exception(env, ret, "Cannot grab keyboard"); - AWT_UNLOCK(); - return; - } - } - - /* Update the global state. */ - source_peer = (*env)->NewGlobalRef(env, this); - dnd_in_progress = True; - drag_in_progress = True; - data_types = targets; - data_types_count = num_targets; - source_actions = actions; - drag_root_window = root_window; - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_X11DragSourceContextPeer - * Method: setNativeCursor - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_sun_awt_motif_X11DragSourceContextPeer_setNativeCursor(JNIEnv *env, - jobject this, - jlong nativeCtxt, - jobject cursor, - jint type) { - if (JNU_IsNull(env, cursor)) { - return; - } - - XChangeActivePointerGrab(awt_display, - GRAB_EVENT_MASK, - getCursor(env, cursor), - CurrentTime); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_dnd_dt.c b/jdk/src/solaris/native/sun/awt/awt_dnd_dt.c deleted file mode 100644 index 7b76f81195e..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_dnd_dt.c +++ /dev/null @@ -1,3700 +0,0 @@ -/* - * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_dnd.h" - -#include "jlong.h" - -#include "awt_DataTransferer.h" -#include "awt_MToolkit.h" - -#include "java_awt_dnd_DnDConstants.h" -#include "java_awt_event_MouseEvent.h" - -#include "sun_awt_motif_MComponentPeer.h" -#include "awt_xembed.h" - -#define DT_INITIAL_STATE 0 -#define DT_ENTERED_STATE 1 -#define DT_OVER_STATE 2 - -extern struct ComponentIDs componentIDs; -extern struct MComponentPeerIDs mComponentPeerIDs; - -/**************************** XEmbed server DnD support ***********************/ -extern void -set_xembed_drop_target(JNIEnv* env, jobject server); -extern void -remove_xembed_drop_target(JNIEnv* env, jobject server); -extern Boolean -is_xembed_client(Window window); - -DECLARE_JAVA_CLASS(MEmbedCanvasPeerClass, "sun/awt/motif/MEmbedCanvasPeer"); -/******************************************************************************/ - -typedef enum { - EventSuccess, /* Event is successfully processed. */ - EventFailure /* Failed to process the event. */ -} EventStatus; - -typedef enum { - EnterEvent, /* XdndEnter, TOP_LEVEL_ENTER */ - MotionEvent, /* XdndPosition, DRAG_MOTION, OPERATION_CHANGED */ - LeaveEvent, /* XdndLeave, TOP_LEVEL_LEAVE */ - DropEvent, /* XdndDrop, DROP_START */ - UnknownEvent -} EventType; - -static Protocol source_protocol = NO_PROTOCOL; -static unsigned int source_protocol_version = 0; -static Window source_window = None; -static Atom source_atom = None; -static long source_window_mask = None; -static jint source_actions = java_awt_dnd_DnDConstants_ACTION_NONE; -/* - * According to XDnD protocol, XdndActionList is optional. - * In case if XdndActionList is not set on the source, the list of drop actions - * supported by the source is constructed as follows: - * - "copy" is always included; - * - "move" is included if at least one XdndPosition message received - * after the latest XdndEnter passed XdndActionMove in data.l[4]; - * - "link" is included if at least one XdndPosition message received - * after the latest XdndEnter passed XdndActionLink in data.l[4]. - * We use a boolean flag to signal that we are building the list of drop actions - * supported by the source. - */ -static Boolean track_source_actions = False; -static jint user_action = java_awt_dnd_DnDConstants_ACTION_NONE; -static jlongArray source_data_types = NULL; -static Atom* source_data_types_native = NULL; -static unsigned int source_data_types_count = 0; -static int source_x = 0; -static int source_y = 0; -static jobject target_component = NULL; -/* - * The Motif DnD protocol prescribes that DROP_START message should always be - * preceeded with TOP_LEVEL_LEAVE message. We need to cleanup on TOP_LEVEL_LEAVE - * message, but DROP_START wouldn't be processed properly. - * To resolve this issue we postpone cleanup using a boolean flag this flag is - * set when we receive the TOP_LEVEL_LEAVE message and cleared when the next - * client message arrives if that message is not DROP_START. If that message is - * a DROP_START message, the flag is cleared after the DROP_START is processed. - */ -static Boolean motif_top_level_leave_postponed = False; -/* - * We store a postponed TOP_LEVEL_LEAVE message here. - */ -static XClientMessageEvent motif_top_level_leave_postponed_event; - -/* Forward declarations */ -static Window get_root_for_window(Window window); -static Window get_outer_canvas_for_window(Window window); -static Boolean register_drop_site(Widget outer_canvas, XtPointer componentRef); -static Boolean is_xdnd_drag_message_type(unsigned long message_type); -static Boolean register_xdnd_drop_site(Display* dpy, Window toplevel, - Window window); - -/**************************** JNI stuff ***************************************/ - -DECLARE_JAVA_CLASS(dtcp_clazz, "sun/awt/motif/X11DropTargetContextPeer") - -static void -dt_postDropTargetEvent(JNIEnv* env, jobject component, int x, int y, - jint dropAction, jint event_id, - XClientMessageEvent* event) { - DECLARE_STATIC_VOID_JAVA_METHOD(dtcp_postDropTargetEventToPeer, dtcp_clazz, - "postDropTargetEventToPeer", - "(Ljava/awt/Component;IIII[JJI)V"); - - { - void* copy = NULL; - - if (event != NULL) { - /* - * For XDnD messages we append the information from the latest - * XdndEnter to the context. It is done to be able to reconstruct - * XdndEnter for an XEmbed client. - */ - Boolean isXDnDMessage = - is_xdnd_drag_message_type(event->message_type); - - if (isXDnDMessage) { - copy = malloc(sizeof(XClientMessageEvent) + - 4 * sizeof(long)); - } else { - copy = malloc(sizeof(XClientMessageEvent)); - } - - if (copy == NULL) { - DTRACE_PRINTLN2("%s:%d malloc failed.", __FILE__, __LINE__); - return; - } - - memcpy(copy, event, sizeof(XClientMessageEvent)); - - if (isXDnDMessage) { - size_t msgSize = sizeof(XClientMessageEvent); - long data1 = source_protocol_version << XDND_PROTOCOL_SHIFT; - long * appended_data; - if (source_data_types_native != NULL && - source_data_types_count > 3) { - - data1 |= XDND_DATA_TYPES_BIT; - } - - appended_data = (long*)((char*)copy + msgSize); - appended_data[0] = data1; - appended_data[1] = source_data_types_count > 0 ? - source_data_types_native[0] : 0; - appended_data[2] = source_data_types_count > 1 ? - source_data_types_native[1] : 0; - appended_data[3] = source_data_types_count > 2 ? - source_data_types_native[2] : 0; - } - } - - DASSERT(!JNU_IsNull(env, component)); - - (*env)->CallStaticVoidMethod(env, clazz, dtcp_postDropTargetEventToPeer, - component, x, y, dropAction, - source_actions, source_data_types, - ptr_to_jlong(copy), event_id); - } -} - -/******************************************************************************/ - -/********************* Embedded drop site list support ************************/ - -struct EmbeddedDropSiteListEntryRec; - -typedef struct EmbeddedDropSiteListEntryRec EmbeddedDropSiteListEntry; - -struct EmbeddedDropSiteListEntryRec { - Window toplevel; - Window root; - /* - * We select for PropertyNotify events on the toplevel, so we need to - * restore the event mask when we are done with this toplevel. - */ - long event_mask; - unsigned int embedded_sites_count; - Window* embedded_sites; - EmbeddedDropSiteListEntry* next; -}; - -static EmbeddedDropSiteListEntry* embedded_drop_site_list = NULL; - -struct EmbeddedDropSiteProtocolListEntryRec; - -typedef struct EmbeddedDropSiteProtocolListEntryRec EmbeddedDropSiteProtocolListEntry; - -struct EmbeddedDropSiteProtocolListEntryRec { - Window window; - Window proxy; - /* - * We override the XdndAware property on the toplevel, so we should keep its - * original contents - the XDnD protocol version supported by the browser. - * This is needed to adjust XDnD messages forwarded to the browser. - */ - unsigned int protocol_version; - /* True if the toplevel was already registered as a drag receiver and - we just changed the proxy. False, otherwise */ - Boolean overriden; - EmbeddedDropSiteProtocolListEntry* next; -}; - -static EmbeddedDropSiteProtocolListEntry* embedded_motif_protocol_list = NULL; -static EmbeddedDropSiteProtocolListEntry* embedded_xdnd_protocol_list = NULL; - -typedef enum { - RegFailure, /* Proxy registration failed */ - RegSuccess, /* The new drop site is registered with the new proxy */ - RegOverride, /* The new proxy is set for the existing drop site */ - RegAlreadyRegistered /* This proxy is already set for this drop site */ -} ProxyRegistrationStatus; - -/* Forward declarations. */ -static EmbeddedDropSiteProtocolListEntry* -get_xdnd_protocol_entry_for_toplevel(Window toplevel); -static EmbeddedDropSiteProtocolListEntry* -get_motif_protocol_entry_for_toplevel(Window toplevel); -static void remove_xdnd_protocol_entry_for_toplevel(Window toplevel); -static void remove_motif_protocol_entry_for_toplevel(Window toplevel); - -/* - * Registers the toplevel as a Motif drag receiver if it is not registered yet, - * sets the specified new_proxy for it and returns the previous proxy in old_proxy. - * Does nothing if the new_proxy is already set as a proxy for this toplevel. - * Returns the completion status. - */ -static ProxyRegistrationStatus -set_motif_proxy(Display* dpy, Window toplevel, Window new_proxy, Window *old_proxy) { - Boolean override = False; - - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char* data; - unsigned char ret; - - DASSERT(old_proxy != NULL); - - *old_proxy = None; - - data = NULL; - ret = checked_XGetWindowProperty(dpy, toplevel, - _XA_MOTIF_DRAG_RECEIVER_INFO, 0, 0xFFFF, - False, AnyPropertyType, &type, &format, - &nitems, &after, &data); - - /* Check if toplevel is a valid window. */ - if (ret != Success) { - return RegFailure; - } - - if (ret == Success && data != NULL && type != None && format == 8 - && nitems >= MOTIF_RECEIVER_INFO_SIZE) { - unsigned char byte_order = read_card8((char*)data, 0); - void* p = (char*)data + 4; - - /* Browser and plugin have different byte orders - report failure for now. */ - if (MOTIF_BYTE_ORDER != byte_order) { - XFree(data); - return RegFailure; - } - - *old_proxy = read_card32((char*)data, 4, byte_order); - - /* If the proxy is already set to the specified window - return. */ - if (*old_proxy == new_proxy) { - XFree(data); - return RegAlreadyRegistered; - } - - /* replace the proxy window */ - write_card32(&p, new_proxy); - - override = True; - } else { - void* p; - - if (ret == Success) { - XFree(data); - data = NULL; - } - - data = malloc(MOTIF_RECEIVER_INFO_SIZE); - - if (data == NULL) { - DTRACE_PRINTLN2("%s:%d malloc failed.", __FILE__, __LINE__); - return RegFailure; - } - - p = data; - - write_card8(&p, MOTIF_BYTE_ORDER); - write_card8(&p, MOTIF_DND_PROTOCOL_VERSION); /* protocol version */ - write_card8(&p, MOTIF_DYNAMIC_STYLE); /* protocol style */ - write_card8(&p, 0); /* pad */ - write_card32(&p, new_proxy); /* proxy window */ - write_card16(&p, 0); /* num_drop_sites */ - write_card16(&p, 0); /* pad */ - write_card32(&p, MOTIF_RECEIVER_INFO_SIZE); - } - - ret = checked_XChangeProperty(dpy, toplevel, - _XA_MOTIF_DRAG_RECEIVER_INFO, - _XA_MOTIF_DRAG_RECEIVER_INFO, 8, - PropModeReplace, (unsigned char*)data, - MOTIF_RECEIVER_INFO_SIZE); - - if (data != NULL) { - XFree(data); - data = NULL; - } - - if (ret == Success) { - if (override) { - return RegOverride; - } else { - return RegSuccess; - } - } else { - return RegFailure; - } -} - -/* - * Registers the toplevel as a XDnD drag receiver if it is not registered yet, - * sets the specified new_proxy for it and returns the previous proxy in - * old_proxy and the original XDnD protocol version in old_version. - * Does nothing if the new_proxy is already set as a proxy for this toplevel. - * Returns the completion status. - */ -static ProxyRegistrationStatus -set_xdnd_proxy(Display* dpy, Window toplevel, Window new_proxy, - Window* old_proxy, unsigned int* old_version) { - Atom version_atom = XDND_PROTOCOL_VERSION; - Window xdnd_proxy = None; - Boolean override = False; - - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char* data; - unsigned char ret; - - DASSERT(old_proxy != NULL); - - *old_proxy = None; - - data = NULL; - ret = checked_XGetWindowProperty(dpy, toplevel, XA_XdndAware, 0, 1, - False, AnyPropertyType, &type, &format, - &nitems, &after, &data); - - if (ret != Success) { - return RegFailure; - } - - if (ret == Success && data != NULL && type == XA_ATOM) { - unsigned int protocol_version = *((unsigned int*)data); - - override = True; - *old_version = protocol_version; - - /* XdndProxy is not supported for prior to XDnD version 4 */ - if (protocol_version >= 4) { - int status; - - XFree(data); - - data = NULL; - status = XGetWindowProperty(dpy, toplevel, XA_XdndProxy, 0, 1, - False, XA_WINDOW, &type, &format, - &nitems, &after, &data); - - if (status == Success && data != NULL && type == XA_WINDOW) { - xdnd_proxy = *((Window*)data); - - if (xdnd_proxy != None) { - XFree(data); - - data = NULL; - status = XGetWindowProperty(dpy, xdnd_proxy, XA_XdndProxy, - 0, 1, False, XA_WINDOW, &type, - &format, &nitems, &after, &data); - - if (status != Success || data == NULL || type != XA_WINDOW || - *((Window*)data) != xdnd_proxy) { - /* Ignore invalid proxy. */ - xdnd_proxy = None; - } - } - - if (xdnd_proxy != None) { - XFree(data); - - data = NULL; - status = XGetWindowProperty(dpy, xdnd_proxy, XA_XdndAware, - 0, 1, False, AnyPropertyType, - &type, &format, &nitems, &after, - &data); - - if (status == Success && data != NULL && type == XA_ATOM) { - unsigned int proxy_version = *((unsigned int*)data); - - if (proxy_version != protocol_version) { - /* Ignore invalid proxy. */ - xdnd_proxy = None; - } - } else { - /* Ignore invalid proxy. */ - xdnd_proxy = None; - } - } - } - - *old_proxy = xdnd_proxy; - } - } - - XFree(data); - - /* If the proxy is already set to the specified window - return. */ - if (xdnd_proxy == new_proxy) { - return RegAlreadyRegistered; - } - - /* The proxy window must have the XdndAware set, as XDnD protocol prescribes - to check the proxy window for XdndAware. */ - ret = checked_XChangeProperty(dpy, new_proxy, XA_XdndAware, XA_ATOM, 32, - PropModeReplace, - (unsigned char*)&version_atom, 1); - - if (ret != Success) { - return RegFailure; - } - - /* The proxy window must have the XdndProxy set to point to itself. */ - ret = checked_XChangeProperty(dpy, new_proxy, XA_XdndProxy, XA_WINDOW, 32, - PropModeReplace, - (unsigned char*)&new_proxy, 1); - - if (ret != Success) { - return RegFailure; - } - - ret = checked_XChangeProperty(dpy, toplevel, XA_XdndAware, XA_ATOM, 32, - PropModeReplace, - (unsigned char*)&version_atom, 1); - - if (ret != Success) { - return RegFailure; - } - - ret = checked_XChangeProperty(dpy, toplevel, XA_XdndProxy, XA_WINDOW, 32, - PropModeReplace, - (unsigned char*)&new_proxy, 1); - - if (ret == Success) { - if (override) { - return RegOverride; - } else { - return RegSuccess; - } - } else { - return RegFailure; - } -} - -/* - * 'toplevel' is the browser toplevel window. To register a drop site on the - * plugin window we set the proxy for the browser toplevel window to point to - * the awt_root_shell window. - * - * We assume that only one JVM per browser instance is possible. This - * assumption is true with the current plugin implementation - it creates a - * single JVM for all plugin instances created by the given plugin factory. - * - * When a client message event for the browser toplevel window is received, we - * will iterate over drop sites registered with this toplevel and determine if - * the mouse pointer is currently over one of them (there could be several - * plugin windows in one browser window - for example if an HTML page contains - * frames and several frames contain a plugin object). - * - * If the pointer is not over any of the plugin drop sites the client message - * will be resent to the browser, otherwise it will be processed normally. - */ -static EmbeddedDropSiteListEntry* -awt_dnd_dt_init_proxy(Display* dpy, Window root, Window toplevel, Window window) { - Window awt_root_window = get_awt_root_window(); - Window motif_proxy = None; - Boolean motif_override = False; - unsigned long event_mask = 0; - - if (awt_root_window == None) { - return NULL; - } - - /* Grab server, since we are working with the window that belongs to - another client. REMIND: ungrab when done!!! */ - XGrabServer(dpy); - - { - ProxyRegistrationStatus motif_status = RegFailure; - - motif_status = set_motif_proxy(dpy, toplevel, awt_root_window, &motif_proxy); - - switch (motif_status) { - case RegFailure: - case RegAlreadyRegistered: - XUngrabServer(dpy); - /* Workaround for bug 5039226 */ - XSync(dpy, False); - return NULL; - case RegOverride: - motif_override = True; - break; - case RegSuccess: - motif_override = False; - break; - default: - DASSERT(False); - } - - - } - - { - XWindowAttributes xwa; - XGetWindowAttributes(dpy, toplevel, &xwa); - event_mask = xwa.your_event_mask; - if ((event_mask & PropertyChangeMask) == 0) { - XSelectInput(dpy, toplevel, event_mask | PropertyChangeMask); - } - } - - XUngrabServer(dpy); - /* Workaround for bug 5039226 */ - XSync(dpy, False); - - /* Add protocol specific entries for the toplevel. */ - { - EmbeddedDropSiteProtocolListEntry* motif_entry = NULL; - - motif_entry = malloc(sizeof(EmbeddedDropSiteProtocolListEntry)); - - if (motif_entry == NULL) { - return NULL; - } - - motif_entry->window = toplevel; - motif_entry->proxy = motif_proxy; - motif_entry->protocol_version = 0; - motif_entry->overriden = motif_override; - motif_entry->next = embedded_motif_protocol_list; - embedded_motif_protocol_list = motif_entry; - } - - { - EmbeddedDropSiteListEntry* entry = NULL; - Window* sites = NULL; - - entry = malloc(sizeof(EmbeddedDropSiteListEntry)); - - if (entry == NULL) { - return NULL; - } - - sites = malloc(sizeof(Window)); - - if (sites == NULL) { - free(entry); - return NULL; - } - - sites[0] = window; - - entry->toplevel = toplevel; - entry->root = root; - entry->event_mask = event_mask; - entry->embedded_sites_count = 1; - entry->embedded_sites = sites; - entry->next = NULL; - - return entry; - } -} - -static void -register_xdnd_embedder(Display* dpy, EmbeddedDropSiteListEntry* entry, long window) { - Window awt_root_window = get_awt_root_window(); - Window toplevel = entry->toplevel; - Window xdnd_proxy = None; - unsigned int xdnd_protocol_version = 0; - Boolean xdnd_override = False; - Boolean register_xdnd = True; - Boolean motif_overriden = False; - - EmbeddedDropSiteProtocolListEntry* motif_entry = embedded_motif_protocol_list; - while (motif_entry != NULL) { - if (motif_entry->window == toplevel) { - motif_overriden = motif_entry->overriden; - break; - } - motif_entry = motif_entry->next; - } - - /* - * First check if the window is an XEmbed client. - * In this case we don't have to setup a proxy on the toplevel, - * instead we register the XDnD drop site on the embedded window. - */ - if (isXEmbedActiveByWindow(window)) { - register_xdnd_drop_site(dpy, toplevel, window); - return; - } - - /* - * By default, we register a drop site that supports both dnd - * protocols. This approach is not appropriate in plugin - * scenario if the browser doesn't support XDnD. If we forcibly set - * XdndAware on the browser toplevel, any drag source that supports both - * protocols and prefers XDnD will be unable to drop anything on the - * browser. - * The solution for this problem is not to register XDnD drop site - * if the browser supports only Motif DnD. - */ - if (motif_overriden) { - int status; - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char* data; - - data = NULL; - status = XGetWindowProperty(dpy, toplevel, XA_XdndAware, 0, 1, - False, AnyPropertyType, &type, &format, - &nitems, &after, &data); - - XFree(data); - data = NULL; - - if (type != XA_ATOM) { - register_xdnd = False; - } - } - - if (register_xdnd) { - ProxyRegistrationStatus xdnd_status; - /* Grab server, since we are working with the window that belongs to - another client. REMIND: ungrab when done!!! */ - XGrabServer(dpy); - - xdnd_status = - set_xdnd_proxy(dpy, toplevel, awt_root_window, &xdnd_proxy, - &xdnd_protocol_version); - - XUngrabServer(dpy); - - switch (xdnd_status) { - case RegFailure: - case RegAlreadyRegistered: - return; - case RegOverride: - xdnd_override = True; - break; - case RegSuccess: - xdnd_override = False; - break; - default: - DASSERT(False); - } - - { - EmbeddedDropSiteProtocolListEntry* xdnd_entry = NULL; - - xdnd_entry = malloc(sizeof(EmbeddedDropSiteProtocolListEntry)); - - if (xdnd_entry == NULL) { - return; - } - - xdnd_entry->window = toplevel; - xdnd_entry->proxy = xdnd_proxy; - xdnd_entry->protocol_version = xdnd_protocol_version; - xdnd_entry->overriden = xdnd_override; - xdnd_entry->next = embedded_xdnd_protocol_list; - embedded_xdnd_protocol_list = xdnd_entry; - } - } -} - -/* - * If embedded_drop_site_list already contains an entry with the specified - * 'toplevel', the method registers the specified 'window' as an embedded drop - * site for this 'toplevel' and returns True. - * Otherwise, it checks if the 'toplevel' is a registered drop site for adds - * (window, component) pair to the list and returns True - * if completes successfully. - */ -static Boolean -add_to_embedded_drop_site_list(Display* dpy, Window root, Window toplevel, - Window window) { - EmbeddedDropSiteListEntry* entry = embedded_drop_site_list; - - while (entry != NULL) { - if (entry->toplevel == toplevel) { - void* p = realloc(entry->embedded_sites, - sizeof(Window) * - (entry->embedded_sites_count + 1)); - if (p == NULL) { - return False; - } - entry->embedded_sites = p; - entry->embedded_sites[entry->embedded_sites_count++] = window; - - register_xdnd_embedder(dpy, entry, window); - - return True; - } - entry = entry->next; - } - - entry = awt_dnd_dt_init_proxy(dpy, root, toplevel, window); - - if (entry == NULL) { - return False; - } - - register_xdnd_embedder(dpy, entry, window); - - entry->next = embedded_drop_site_list; - embedded_drop_site_list = entry; - - return True; -} - -/* - * Removes the window from the list of embedded drop sites for the toplevel. - * Returns True if the window was successfully removed, False otherwise. - */ -static Boolean -remove_from_embedded_drop_site_list(Display* dpy, Window toplevel, Window window) { - EmbeddedDropSiteListEntry* entry = embedded_drop_site_list; - EmbeddedDropSiteListEntry* prev = NULL; - - while (entry != NULL) { - if (entry->toplevel == toplevel) { - unsigned int idx; - - for (idx = 0; idx < entry->embedded_sites_count; idx++) { - if (entry->embedded_sites[idx] == window) { - int tail = entry->embedded_sites_count - idx - 1; - if (tail > 0) { - memmove(entry->embedded_sites + idx, - entry->embedded_sites + idx + 1, - tail * sizeof(Window)); - } - entry->embedded_sites_count--; - - /* If the list of embedded drop sites for this toplevel - becomes empty - restore the original proxies and remove - the entry. */ - if (entry->embedded_sites_count == 0) { - Widget w = XtWindowToWidget(dpy, toplevel); - - if (w != NULL) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - Widget copy = w; - jobject peer = findPeer(&w); - - if (!JNU_IsNull(env, peer) && - (*env)->IsInstanceOf(env, peer, - get_MEmbedCanvasPeerClass(env)) == JNI_TRUE) { - remove_xembed_drop_target(env, peer); - } - } else { - EmbeddedDropSiteProtocolListEntry* xdnd_entry = - get_xdnd_protocol_entry_for_toplevel(toplevel); - EmbeddedDropSiteProtocolListEntry* motif_entry = - get_motif_protocol_entry_for_toplevel(toplevel); - - if (xdnd_entry != NULL) { - if (xdnd_entry->overriden == True) { - XChangeProperty(dpy, toplevel, XA_XdndAware, - XA_ATOM, 32, - PropModeReplace, - (unsigned char*)&xdnd_entry->protocol_version, - 1); - - XChangeProperty(dpy, toplevel, XA_XdndProxy, - XA_WINDOW, 32, - PropModeReplace, - (unsigned char*)&xdnd_entry->proxy, 1); - } else { - XDeleteProperty(dpy, toplevel, XA_XdndAware); - XDeleteProperty(dpy, toplevel, XA_XdndProxy); - } - remove_xdnd_protocol_entry_for_toplevel(toplevel); - } - - if (motif_entry != NULL) { - if (motif_entry->overriden == True) { - /* Request status */ - int status; - - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char* data; - - data = NULL; - status = XGetWindowProperty(dpy, toplevel, - _XA_MOTIF_DRAG_RECEIVER_INFO, 0, 0xFFFF, - False, AnyPropertyType, &type, &format, - &nitems, &after, &data); - - if (status == Success && data != NULL && type != None && - format == 8 && nitems >= MOTIF_RECEIVER_INFO_SIZE) { - unsigned char byte_order = read_card8((char*)data, 0); - void* p = (char*)data + 4; - - DASSERT(MOTIF_BYTE_ORDER == byte_order); - - if (MOTIF_BYTE_ORDER == byte_order) { - /* restore the original proxy window */ - write_card32(&p, motif_entry->proxy); - - XChangeProperty(dpy, toplevel, - _XA_MOTIF_DRAG_RECEIVER_INFO, - _XA_MOTIF_DRAG_RECEIVER_INFO, 8, - PropModeReplace, - (unsigned char*)data, - MOTIF_RECEIVER_INFO_SIZE); - } - } - - if (status == Success) { - XFree(data); - } - } else { - XDeleteProperty(dpy, toplevel, _XA_MOTIF_DRAG_RECEIVER_INFO); - } - - remove_motif_protocol_entry_for_toplevel(toplevel); - } - - if ((entry->event_mask & PropertyChangeMask) == 0) { - XSelectInput(dpy, toplevel, entry->event_mask); - } - } - - if (prev == NULL) { - embedded_drop_site_list = entry->next; - } else { - prev->next = entry->next; - } - - free(entry); - } - return True; - } - } - return False; - } - prev = entry; - entry = entry->next; - } - return False; -} - -static EmbeddedDropSiteListEntry* -get_entry_for_toplevel(Window toplevel) { - EmbeddedDropSiteListEntry* entry = embedded_drop_site_list; - - while (entry != NULL) { - if (entry->toplevel == toplevel) { - return entry; - } - entry = entry->next; - } - return NULL; -} - -static EmbeddedDropSiteProtocolListEntry* -get_motif_protocol_entry_for_toplevel(Window toplevel) { - EmbeddedDropSiteProtocolListEntry* entry = embedded_motif_protocol_list; - - while (entry != NULL) { - if (entry->window == toplevel) { - return entry; - } - entry = entry->next; - } - return NULL; -} - -static EmbeddedDropSiteProtocolListEntry* -get_xdnd_protocol_entry_for_toplevel(Window toplevel) { - EmbeddedDropSiteProtocolListEntry* entry = embedded_xdnd_protocol_list; - - while (entry != NULL) { - if (entry->window == toplevel) { - return entry; - } - entry = entry->next; - } - return NULL; -} - -static void -remove_motif_protocol_entry_for_toplevel(Window toplevel) { - EmbeddedDropSiteProtocolListEntry* entry = embedded_motif_protocol_list; - EmbeddedDropSiteProtocolListEntry* prev_entry = NULL; - - while (entry != NULL) { - if (entry->window == toplevel) { - if (prev_entry != NULL) { - prev_entry->next = entry->next; - } else { - embedded_motif_protocol_list = entry->next; - } - free(entry); - } - entry = entry->next; - prev_entry = entry; - } -} - -static void -remove_xdnd_protocol_entry_for_toplevel(Window toplevel) { - EmbeddedDropSiteProtocolListEntry* entry = embedded_xdnd_protocol_list; - EmbeddedDropSiteProtocolListEntry* prev_entry = NULL; - - while (entry != NULL) { - if (entry->window == toplevel) { - if (prev_entry != NULL) { - prev_entry->next = entry->next; - } else { - embedded_xdnd_protocol_list = entry->next; - } - free(entry); - } - entry = entry->next; - } -} - -static Boolean -is_embedding_toplevel(Window toplevel) { - return get_entry_for_toplevel(toplevel) != NULL; -} - -static Window -get_embedded_window(Display* dpy, Window toplevel, int x, int y) { - EmbeddedDropSiteListEntry* entry = get_entry_for_toplevel(toplevel); - - if (entry != NULL) { - unsigned int idx; - - for (idx = 0; idx < entry->embedded_sites_count; idx++) { - Window site = entry->embedded_sites[idx]; - Window child = None; - int x_return, y_return; - - if (XTranslateCoordinates(dpy, entry->root, site, x, y, - &x_return, &y_return, &child)) { - if (x_return >= 0 && y_return >= 0) { - XWindowAttributes xwa; - XGetWindowAttributes(dpy, site, &xwa); - if (xwa.map_state != IsUnmapped && - x_return < xwa.width && y_return < xwa.height) { - return site; - } - } - } - } - } - - return None; -} - -/* - * If the toplevel is not an embedding toplevel does nothing and returns False. - * Otherwise, sets xdnd_proxy for the specified toplevel to the 'proxy_window', - * xdnd_protocol_version to 'version', xdnd_override to 'override', returns True. - */ -static Boolean -set_xdnd_proxy_for_toplevel(Window toplevel, Window proxy_window, - unsigned int version, Boolean override) { - EmbeddedDropSiteProtocolListEntry* entry = - get_xdnd_protocol_entry_for_toplevel(toplevel); - - if (entry == NULL) { - return False; - } - - entry->proxy = proxy_window; - entry->protocol_version = version; - entry->overriden = override; - - return True; -} - -/* - * If the toplevel is not an embedding toplevel does nothing and returns False. - * Otherwise, sets motif_proxy for the specified toplevel to the proxy_window, - * motif_override to 'override' and returns True. - */ -static Boolean -set_motif_proxy_for_toplevel(Window toplevel, Window proxy_window, Boolean override) { - EmbeddedDropSiteProtocolListEntry* entry = - get_motif_protocol_entry_for_toplevel(toplevel); - - if (entry == NULL) { - return False; - } - - entry->proxy = proxy_window; - entry->overriden = override; - - return True; -} - -/* - * Forwards a drag notification to the embedding toplevel modifying the event - * to match the protocol version supported by the toplevel. - * Returns True if the event is sent, False otherwise. - */ -static Boolean -forward_client_message_to_toplevel(Window toplevel, XClientMessageEvent* event) { - EmbeddedDropSiteProtocolListEntry* protocol_entry = NULL; - Window proxy = None; - - if (event->message_type == _XA_MOTIF_DRAG_AND_DROP_MESSAGE) { - protocol_entry = get_motif_protocol_entry_for_toplevel(toplevel); - } else { - /* Assume XDnD */ - protocol_entry = get_xdnd_protocol_entry_for_toplevel(toplevel); - if (protocol_entry != NULL) { - /* Adjust the event to match the XDnD protocol version. */ - unsigned int version = protocol_entry->protocol_version; - if (event->message_type == XA_XdndEnter) { - unsigned int min_version = source_protocol_version < version ? - source_protocol_version : version; - event->data.l[1] = min_version << XDND_PROTOCOL_SHIFT; - event->data.l[1] |= source_data_types_count > 3 ? XDND_DATA_TYPES_BIT : 0; - } - } - } - - if (protocol_entry == NULL) { - return False; - } - - if (!protocol_entry->overriden) { - return False; - } - proxy = protocol_entry->proxy; - - if (proxy == None) { - proxy = toplevel; - } - - event->window = toplevel; - - XSendEvent(event->display, proxy, False, NoEventMask, (XEvent*)event); - - return True; -} - -/******************************************************************************/ - -/********************* Drop site list support *********************************/ - -struct DropSiteListEntryRec; - -typedef struct DropSiteListEntryRec DropSiteListEntry; - -struct DropSiteListEntryRec { - Window window; - Window root; - /* - * The closest to the root ancestor with WM_STATE property set. - * Normally toplevel == window. - * In plugin scenario toplevel is the browser toplevel window. - */ - Window toplevel; - /* - * Java top-level position is the outer canvas position, not the shell - * window position. We need to keep the outer canvas ID (and the root ID) to - * translate from mouse position root coordinates to the Java component - * coordinates. - */ - Window outer_canvas; - jobject component; - DropSiteListEntry* next; -}; - -static DropSiteListEntry* drop_site_list = NULL; - -/* - * If drop_site_list already contains an entry with the same window, - * does nothing and returns False. - * Otherwise, adds a new entry the list and returns True - * if completes successfully. - */ -static Boolean -add_to_drop_site_list(Window window, Window root, Window toplevel, - Window outer_canvas, jobject component) { - DropSiteListEntry* entry = drop_site_list; - - while (entry != NULL) { - if (entry->window == window) { - return False; - } - entry = entry->next; - } - - entry = malloc(sizeof(DropSiteListEntry)); - - if (entry == NULL) { - return False; - } - - entry->window = window; - entry->root = root; - entry->toplevel = toplevel; - entry->outer_canvas = outer_canvas; - entry->component = component; - entry->next = drop_site_list; - drop_site_list = entry; - - return True; -} - -/* - * Returns True if the list entry for the specified window has been successfully - * removed from the list. Otherwise, returns False. - */ -static Boolean -remove_from_drop_site_list(Window window) { - DropSiteListEntry* entry = drop_site_list; - DropSiteListEntry* prev = NULL; - - while (entry != NULL) { - if (entry->window == window) { - if (prev != NULL) { - prev->next = entry->next; - } else { - drop_site_list = entry->next; - } - free(entry); - return True; - } - prev = entry; - entry = entry->next; - } - - return False; -} - -static jobject -get_component_for_window(Window window) { - DropSiteListEntry* entry = drop_site_list; - - while (entry != NULL) { - if (entry->window == window) { - return entry->component; - } - entry = entry->next; - } - - return NULL; -} - -static Window -get_root_for_window(Window window) { - DropSiteListEntry* entry = drop_site_list; - - while (entry != NULL) { - if (entry->window == window) { - return entry->root; - } - entry = entry->next; - } - - return None; -} - -static Window -get_toplevel_for_window(Window window) { - DropSiteListEntry* entry = drop_site_list; - - while (entry != NULL) { - if (entry->window == window) { - return entry->toplevel; - } - entry = entry->next; - } - - return None; -} - -static Window -get_outer_canvas_for_window(Window window) { - DropSiteListEntry* entry = drop_site_list; - - while (entry != NULL) { - if (entry->window == window) { - return entry->outer_canvas; - } - entry = entry->next; - } - - return None; -} -/******************************************************************************/ - -/******************* Delayed drop site registration stuff *********************/ -struct DelayedRegistrationEntryRec; - -typedef struct DelayedRegistrationEntryRec DelayedRegistrationEntry; - -struct DelayedRegistrationEntryRec { - Widget outer_canvas; - jobject component; - XtIntervalId timer; - DelayedRegistrationEntry* next; -}; - -static DelayedRegistrationEntry* delayed_registration_list = NULL; - -static const int DELAYED_REGISTRATION_PERIOD = 500; - -/* Timer callback. */ -static void -register_drop_site_later(XtPointer client_data, XtIntervalId* id); - -/* - * Enqueues the specified widget and component for delayed drop site - * registration. If this widget has already been registered, does nothing and - * returns False. Otherwise, schedules a timer callback that will repeatedly - * attempt to register the drop site until the registration succeeds. - * To remove this widget from the queue of delayed registration call - * remove_delayed_registration_entry(). - * - * The caller must own AWT_LOCK. - */ -static Boolean -add_delayed_registration_entry(Widget outer_canvas, XtPointer componentRef) { - DelayedRegistrationEntry* entry = delayed_registration_list; - - if (outer_canvas == NULL || componentRef == NULL) { - return False; - } - - while (entry != NULL && entry->outer_canvas != outer_canvas) { - entry = entry->next; - } - - if (entry != NULL) { - return False; - } - - entry = malloc(sizeof(DelayedRegistrationEntry)); - - if (entry == NULL) { - return False; - } - - entry->outer_canvas = outer_canvas; - entry->component = componentRef; - entry->timer = XtAppAddTimeOut(awt_appContext, DELAYED_REGISTRATION_PERIOD, - register_drop_site_later, entry); - entry->next = delayed_registration_list; - delayed_registration_list = entry; - - return True; -} - -/* - * Unregisters the timer callback and removes this widget from the queue of - * delayed drop site registration. - * - * The caller must own AWT_LOCK. - */ -static Boolean -remove_delayed_registration_entry(Widget outer_canvas) { - DelayedRegistrationEntry* entry = delayed_registration_list; - DelayedRegistrationEntry* prev = NULL; - - if (outer_canvas == NULL) { - return False; - } - - while (entry != NULL && entry->outer_canvas != outer_canvas) { - prev = entry; - entry = entry->next; - } - - if (entry == NULL) { - return False; - } - - if (prev != NULL) { - prev->next = entry->next; - } else { - delayed_registration_list = entry->next; - } - - if (entry->timer) { - XtRemoveTimeOut(entry->timer); - entry->timer = (XtIntervalId)0; - } - - free(entry); - - return True; -} - -static void -register_drop_site_later(XtPointer client_data, XtIntervalId* id) { - DelayedRegistrationEntry* entry = (DelayedRegistrationEntry*)client_data; - - if (XtIsRealized(entry->outer_canvas) && - register_drop_site(entry->outer_canvas, entry->component)) { - remove_delayed_registration_entry(entry->outer_canvas); - } else { - entry->timer = XtAppAddTimeOut(awt_appContext, DELAYED_REGISTRATION_PERIOD, - register_drop_site_later, entry); - } -} -/******************************************************************************/ - -static void -awt_dnd_cleanup() { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - - if (!JNU_IsNull(env, target_component)) { - /* Trigger dragExit */ - /* - * Note: we pass NULL native context. This indicates that response - * shouldn't be sent to the source. - */ - dt_postDropTargetEvent(env, target_component, 0, 0, - java_awt_dnd_DnDConstants_ACTION_NONE, - java_awt_event_MouseEvent_MOUSE_EXITED, - NULL); - } - - if (motif_top_level_leave_postponed) { - XClientMessageEvent* leave = &motif_top_level_leave_postponed_event; - if (leave->type == ClientMessage) { - Window win = leave->window; - if (is_embedding_toplevel(win)) { - forward_client_message_to_toplevel(win, leave); - } - } - } - - if (source_window != None) { - XSelectInput(awt_display, source_window, source_window_mask); - } - - source_protocol = NO_PROTOCOL; - source_protocol_version = 0; - source_window = None; - source_atom = None; - source_window_mask = 0; - source_actions = java_awt_dnd_DnDConstants_ACTION_NONE; - track_source_actions = False; - (*env)->DeleteGlobalRef(env, source_data_types); - source_data_types = NULL; - if (source_data_types_native != NULL) { - free(source_data_types_native); - source_data_types_native = NULL; - } - source_data_types_count = 0; - source_x = 0; - source_y = 0; - target_component = NULL; - motif_top_level_leave_postponed = False; - memset(&motif_top_level_leave_postponed_event, 0, - sizeof(XClientMessageEvent)); -} - -static jlongArray -get_data_types_array(JNIEnv* env, Atom* types, unsigned int types_count) { - jlongArray array = NULL; - jboolean isCopy; - jlong* jTargets; -#ifndef _LP64 /* Atom and jlong are different sizes in the 32-bit build */ - unsigned int i; -#endif - - if ((*env)->PushLocalFrame(env, 1) < 0) { - return NULL; - } - - array = (*env)->NewLongArray(env, types_count); - - if (JNU_IsNull(env, array)) { - return NULL; - } - - if (types_count == 0) { - return array; - } - - jTargets = (*env)->GetLongArrayElements(env, array, &isCopy); - if (jTargets == NULL) { - (*env)->PopLocalFrame(env, NULL); - return NULL; - } - -#ifdef _LP64 - memcpy(jTargets, types, types_count * sizeof(Atom)); -#else - for (i = 0; i < types_count; i++) { - jTargets[i] = (types[i] & 0xFFFFFFFFLU); - } -#endif - - (*env)->ReleaseLongArrayElements(env, array, jTargets, 0); - - array = (*env)->NewGlobalRef(env, array); - - (*env)->PopLocalFrame(env, NULL); - - return array; -} - -static Boolean -is_xdnd_drag_message_type(unsigned long message_type) { - return message_type == XA_XdndEnter || - message_type == XA_XdndPosition || - message_type == XA_XdndLeave || - message_type == XA_XdndDrop ? True : False; -} - -/* - * Returns EventConsume if the event should be consumed, - * EventPassAlong otherwise. - */ -static EventStatus -handle_xdnd_enter(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - Display* dpy = event->display; - long* event_data = event->data.l; - Window source_win = None; - long source_win_mask = 0; - unsigned int protocol_version = 0; - unsigned int data_types_count = 0; - Atom* data_types = NULL; - jlongArray java_data_types = NULL; - jint actions = java_awt_dnd_DnDConstants_ACTION_NONE; - Boolean track = False; - - DTRACE_PRINTLN5("%s:%d XdndEnter comp=%X src_win=%ld protocol=%d.", - __FILE__, __LINE__, - target_component, source_window, source_protocol); - - if (!JNU_IsNull(env, target_component) || source_window != None || - source_protocol != NO_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - invalid state.", - __FILE__, __LINE__); - return EventFailure; - } - - /* - * NOTE: the component can be NULL if the event was sent to the embedding - * toplevel. - */ - if (JNU_IsNull(env, get_component_for_window(event->window)) && - !is_embedding_toplevel(event->window)) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - window is not a registered drop site.", - __FILE__, __LINE__); - return EventFailure; - } - - protocol_version = - (event_data[1] & XDND_PROTOCOL_MASK) >> XDND_PROTOCOL_SHIFT; - - /* XDnD compliance only requires supporting version 3 and up. */ - if (protocol_version < XDND_MIN_PROTOCOL_VERSION) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - invalid protocol version.", - __FILE__, __LINE__); - return EventFailure; - } - - /* Ignore the source if the protocol version is higher than we support. */ - if (protocol_version > XDND_PROTOCOL_VERSION) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - invalid protocol version.", - __FILE__, __LINE__); - return EventFailure; - } - - source_win = event_data[0]; - - /* Extract the list of supported actions. */ - if (protocol_version < 2) { - /* Prior to XDnD version 2 only COPY action was supported. */ - actions = java_awt_dnd_DnDConstants_ACTION_COPY; - } else { - unsigned char ret; - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - - data = NULL; - ret = checked_XGetWindowProperty(dpy, source_win, XA_XdndActionList, - 0, 0xFFFF, False, XA_ATOM, &type, - &format, &nitems, &after, &data); - - /* Ignore the source if the window is destroyed. */ - if (ret == BadWindow) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - invalid window.", - __FILE__, __LINE__); - return EventFailure; - } - - if (ret == Success) { - if (type == XA_ATOM && format == 32) { - unsigned int i; - Atom* action_atoms = (Atom*)data; - - for (i = 0; i < nitems; i++) { - actions |= xdnd_to_java_action(action_atoms[i]); - } - } - - /* - * According to XDnD protocol, XdndActionList is optional. - * If XdndActionList is not set we try to guess which actions are - * supported. - */ - if (type == None) { - actions = java_awt_dnd_DnDConstants_ACTION_COPY; - track = True; - } - - XFree(data); - } - } - - /* Extract the available data types. */ - if (event_data[1] & XDND_DATA_TYPES_BIT) { - unsigned char ret; - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - - data = NULL; - ret = checked_XGetWindowProperty(dpy, source_win, XA_XdndTypeList, - 0, 0xFFFF, False, XA_ATOM, &type, - &format, &nitems, &after, &data); - - /* Ignore the source if the window is destroyed. */ - if (ret == BadWindow) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - invalid window.", - __FILE__, __LINE__); - return EventFailure; - } - - if (ret == Success) { - if (type == XA_ATOM && format == 32 && nitems > 0) { - data_types_count = nitems; - data_types = (Atom*)malloc(data_types_count * sizeof(Atom)); - - if (data_types == NULL) { - XFree(data); - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - malloc fails.", - __FILE__, __LINE__); - return EventFailure; - } - - memcpy((void *)data_types, (void *)data, - data_types_count * sizeof(Atom)); - } - - XFree(data); - } - } else { - int i; - data_types = (Atom*)malloc(3 * sizeof (Atom)); - if (data_types == NULL) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - malloc fails.", - __FILE__, __LINE__); - return EventFailure; - } - for (i = 0; i < 3; i++) { - Atom j; - if ((j = event_data[2 + i]) != None) { - data_types[data_types_count++] = j; - } - } - } - - java_data_types = get_data_types_array(env, data_types, data_types_count); - - if (JNU_IsNull(env, java_data_types)) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - cannot create types array.", - __FILE__, __LINE__); - free((char*)data_types); - return EventFailure; - } - - /* - * Select for StructureNotifyMask to receive DestroyNotify in case of source - * crash. - */ - { - unsigned char ret; - XWindowAttributes xwa; - - XGetWindowAttributes(dpy, source_win, &xwa); - - source_win_mask = xwa.your_event_mask; - - ret = checked_XSelectInput(dpy, source_win, - (source_win_mask | StructureNotifyMask)); - - if (ret == BadWindow) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - invalid window.", - __FILE__, __LINE__); - free((char*)data_types); - (*env)->DeleteGlobalRef(env, java_data_types); - return EventFailure; - } - } - - /* Update the global state. */ - source_protocol = XDND_PROTOCOL; - source_protocol_version = protocol_version; - source_window = source_win; - source_window_mask = source_win_mask; - source_actions = actions; - track_source_actions = track; - source_data_types = java_data_types; - source_data_types_native = data_types; - source_data_types_count = data_types_count; - - DTRACE_PRINTLN5("%s:%d XdndEnter handled src_win=%ld protocol=%d fmt=%d.", - __FILE__, __LINE__, - source_window, source_protocol, data_types_count); - - return EventSuccess; -} - -/* - * Returns EventConsume if the event should be consumed, - * EventPassAlong otherwise. - */ -static EventStatus -handle_xdnd_position(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - long* event_data = event->data.l; - Window source_win = None; - Time time_stamp = CurrentTime; - Atom action_atom = None; - jint action = java_awt_dnd_DnDConstants_ACTION_NONE; - int x = 0; - int y = 0; - jint java_event_id = 0; - jobject component = NULL; - Window receiver = None; - - DTRACE_PRINTLN5("%s:%d XdndPosition comp=%X src_win=%ld protocol=%d.", - __FILE__, __LINE__, - target_component, source_window, source_protocol); - - if (source_protocol != XDND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d XdndPosition rejected - invalid state.", - __FILE__, __LINE__); - return EventFailure; - } - - source_win = event_data[0]; - - /* Ignore XDnD messages from all other windows. */ - if (source_window != source_win) { - DTRACE_PRINTLN4("%s:%d XdndPosition rejected - invalid source window cur=%ld this=%ld.", - __FILE__, __LINE__, source_window, source_win); - return EventFailure; - } - - x = event_data[2] >> 16; - y = event_data[2] & 0xFFFF; - - component = get_component_for_window(event->window); - - if (JNU_IsNull(env, component)) { - /* - * The window must be the embedding toplevel, since otherwise we would reject the - * XdndEnter and never get to this point. - */ - DASSERT(is_embedding_toplevel(event->window)); - - receiver = get_embedded_window(event->display, event->window, x, y); - - if (receiver != None) { - component = get_component_for_window(receiver); - } - } else { - receiver = event->window; - } - - /* Translate mouse position from root coordinates - to the target window coordinates. */ - if (receiver != None) { - Window child = None; - XTranslateCoordinates(event->display, - get_root_for_window(receiver), - get_outer_canvas_for_window(receiver), - x, y, &x, &y, &child); - } - - /* Time stamp - new in XDnD version 1. */ - if (source_protocol_version > 0) { - time_stamp = event_data[3]; - } - - /* User action - new in XDnD version 1. */ - if (source_protocol_version > 1) { - action_atom = event_data[4]; - } else { - /* The default action is XdndActionCopy */ - action_atom = XA_XdndActionCopy; - } - - action = xdnd_to_java_action(action_atom); - - if (track_source_actions) { - source_actions |= action; - } - - if (JNU_IsNull(env, component)) { - if (!JNU_IsNull(env, target_component)) { - dt_postDropTargetEvent(env, target_component, x, y, - java_awt_dnd_DnDConstants_ACTION_NONE, - java_awt_event_MouseEvent_MOUSE_EXITED, - NULL); - } - } else { - if (JNU_IsNull(env, target_component)) { - java_event_id = java_awt_event_MouseEvent_MOUSE_ENTERED; - } else { - java_event_id = java_awt_event_MouseEvent_MOUSE_DRAGGED; - } - - dt_postDropTargetEvent(env, component, x, y, action, - java_event_id, event); - } - - user_action = action; - source_x = x; - source_y = y; - target_component = component; - - return EventSuccess; -} - -/* - * Returns EventConsume if the event should be consumed, - * EventPassAlong otherwise. - */ -static EventStatus -handle_xdnd_leave(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - long* event_data = event->data.l; - Window source_win = None; - - if (source_protocol != XDND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d XdndLeave rejected - invalid state.", - __FILE__, __LINE__); - return EventFailure; - } - - source_win = event_data[0]; - - /* Ignore XDnD messages from all other windows. */ - if (source_window != source_win) { - DTRACE_PRINTLN4("%s:%d XdndLeave rejected - invalid source window cur=%ld this=%ld.", - __FILE__, __LINE__, source_window, source_win); - return EventFailure; - } - - awt_dnd_cleanup(); - - return EventSuccess; -} - -/* - * Returns EventConsume if the event should be consumed, - * EventPassAlong otherwise. - */ -static EventStatus -handle_xdnd_drop(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - long* event_data = event->data.l; - Window source_win = None; - - DTRACE_PRINTLN5("%s:%d XdndDrop comp=%X src_win=%ld protocol=%d.", - __FILE__, __LINE__, - target_component, source_window, source_protocol); - - if (source_protocol != XDND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d XdndDrop rejected - invalid state.", - __FILE__, __LINE__); - return EventFailure; - } - - source_win = event_data[0]; - - /* Ignore XDnD messages from all other windows. */ - if (source_window != source_win) { - DTRACE_PRINTLN4("%s:%d XdndDrop rejected - invalid source window cur=%ld this=%ld.", - __FILE__, __LINE__, source_window, source_win); - return EventFailure; - } - - if (!JNU_IsNull(env, target_component)) { - dt_postDropTargetEvent(env, target_component, source_x, source_y, user_action, - java_awt_event_MouseEvent_MOUSE_RELEASED, event); - } - - return EventSuccess; -} - -/* - * Returns EventPassAlong if the event should be passed to the original proxy. - * TOP_LEVEL_ENTER should be passed to the original proxy only if the event is - * invalid. - */ -static EventStatus -handle_motif_top_level_enter(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - Display* dpy = event->display; - char* event_data = event->data.b; - unsigned char event_byte_order = 0; - Window source_win = None; - long source_win_mask = 0; - unsigned int protocol_version = MOTIF_DND_PROTOCOL_VERSION; - Atom property_atom = None; - unsigned int data_types_count = 0; - Atom* data_types = NULL; - jlongArray java_data_types = NULL; - - DTRACE_PRINTLN5("%s:%d TOP_LEVEL_ENTER comp=%X src_win=%ld protocol=%d.", - __FILE__, __LINE__, - target_component, source_window, source_protocol); - - if (!JNU_IsNull(env, target_component) || source_window != None || - source_protocol != NO_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d TOP_LEVEL_ENTER rejected - invalid state.", - __FILE__, __LINE__); - return EventFailure; - } - - if (JNU_IsNull(env, get_component_for_window(event->window)) && - !is_embedding_toplevel(event->window)) { - DTRACE_PRINTLN2("%s:%d TOP_LEVEL_ENTER rejected - window is not a registered drop site.", - __FILE__, __LINE__); - return EventFailure; - } - - event_byte_order = read_card8(event_data, 1); - source_win = read_card32(event_data, 8, event_byte_order); - property_atom = read_card32(event_data, 12, event_byte_order); - - /* Extract the available data types. */ - { - unsigned char ret; - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - - data = NULL; - ret = checked_XGetWindowProperty(dpy, source_win, property_atom, 0, - 0xFFFF, False, - _XA_MOTIF_DRAG_INITIATOR_INFO, &type, - &format, &nitems, &after, &data); - - /* Ignore the source if the window is destroyed. */ - if (ret == BadWindow) { - DTRACE_PRINTLN2("%s:%d TOP_LEVEL_ENTER rejected - invalid window.", - __FILE__, __LINE__); - return EventFailure; - } - - if (ret == BadAtom) { - DTRACE_PRINTLN2("%s:%d TOP_LEVEL_ENTER rejected - invalid property atom.", - __FILE__, __LINE__); - return EventFailure; - } - - if (ret == Success) { - if (type == _XA_MOTIF_DRAG_INITIATOR_INFO && format == 8 && - nitems == MOTIF_INITIATOR_INFO_SIZE) { - unsigned char property_byte_order = read_card8((char*)data, 0); - int index = read_card16((char*)data, 2, property_byte_order); - - protocol_version = read_card8((char*)data, 1); - - if (protocol_version > MOTIF_DND_PROTOCOL_VERSION) { - DTRACE_PRINTLN3("%s:%d TOP_LEVEL_ENTER rejected - invalid protocol version: %d.", - __FILE__, __LINE__, protocol_version); - XFree(data); - return EventFailure; - } - - get_target_list_for_index(dpy, index, &data_types, &data_types_count); - } - - XFree(data); - } - } - - java_data_types = get_data_types_array(env, data_types, data_types_count); - - if (JNU_IsNull(env, java_data_types)) { - DTRACE_PRINTLN2("%s:%d TOP_LEVEL_ENTER rejected - cannot create types array.", - __FILE__, __LINE__); - free((char*)data_types); - return EventFailure; - } - - /* - * Select for StructureNotifyMask to receive DestroyNotify in case of source - * crash. - */ - { - unsigned char ret; - XWindowAttributes xwa; - - XGetWindowAttributes(dpy, source_win, &xwa); - - source_win_mask = xwa.your_event_mask; - - ret = checked_XSelectInput(dpy, source_win, - (source_win_mask | StructureNotifyMask)); - - if (ret == BadWindow) { - DTRACE_PRINTLN2("%s:%d XdndEnter rejected - invalid window.", - __FILE__, __LINE__); - free((char*)data_types); - (*env)->DeleteGlobalRef(env, java_data_types); - return EventFailure; - } - } - - source_protocol = MOTIF_DND_PROTOCOL; - source_protocol_version = protocol_version; - source_window = source_win; - source_atom = property_atom; - source_window_mask = source_win_mask; - /* - * TOP_LEVEL_ENTER doesn't communicate the list of supported actions - * They are provided in DRAG_MOTION. - */ - source_actions = java_awt_dnd_DnDConstants_ACTION_NONE; - track_source_actions = False; - source_data_types = java_data_types; - source_data_types_native = data_types; - source_data_types_count = data_types_count; - DTRACE_PRINTLN6("%s:%d TOP_LEVEL_ENTER comp=%d src_win=%ld protocol=%d fmt=%d.", - __FILE__, __LINE__, - target_component, source_window, source_protocol, data_types_count); - - return EventSuccess; -} - -/* - * Returns EventPassAlong if the event should be passed to the original proxy. - * DRAG_MOTION event shouldn't be passed to the original proxy only if it is - * a valid event and the mouse coordinates passed in it specify the point over - * a Java component in this JVM. - */ -static EventStatus -handle_motif_drag_motion(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - char* event_data = event->data.b; - unsigned char event_reason = 0; - unsigned char event_byte_order = 0; - Window source_win = None; - CARD16 flags = 0; - unsigned char motif_action = 0; - unsigned char motif_actions = 0; - jint java_action = java_awt_dnd_DnDConstants_ACTION_NONE; - jint java_actions = java_awt_dnd_DnDConstants_ACTION_NONE; - int x = 0; - int y = 0; - jint java_event_id = 0; - jobject component = NULL; - - DTRACE_PRINTLN5("%s:%d DRAG_MOTION comp=%X src_win=%ld protocol=%d.", - __FILE__, __LINE__, - target_component, source_window, source_protocol); - - if (source_protocol != MOTIF_DND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d DRAG_MOTION rejected - invalid state.", - __FILE__, __LINE__); - return EventFailure; - } - - event_reason = read_card8(event_data, 0) & MOTIF_MESSAGE_REASON_MASK; - event_byte_order = read_card8(event_data, 1); - - flags = read_card16(event_data, 2, event_byte_order); - - motif_action = (flags & MOTIF_DND_ACTION_MASK) >> MOTIF_DND_ACTION_SHIFT; - motif_actions = (flags & MOTIF_DND_ACTIONS_MASK) >> MOTIF_DND_ACTIONS_SHIFT; - - java_action = motif_to_java_actions(motif_action); - java_actions = motif_to_java_actions(motif_actions); - - /* Append source window id to the event data, so that we can send the - response properly. */ - { - Window win = source_window; - void* p = &event->data.b[12]; - if (event_byte_order != MOTIF_BYTE_ORDER) { - SWAP4BYTES(win); - } - write_card32(&p, (CARD32)win); - } - - component = get_component_for_window(event->window); - - if (event_reason == OPERATION_CHANGED) { - /* OPERATION_CHANGED event doesn't provide coordinates, so we use - previously stored position and component ref. */ - x = source_x; - y = source_y; - - if (JNU_IsNull(env, component)) { - component = target_component; - } - } else { - Window receiver = None; - - x = read_card16(event_data, 8, event_byte_order); - y = read_card16(event_data, 10, event_byte_order); - - if (JNU_IsNull(env, component)) { - /* - * The window must be the embedding toplevel, since otherwise we - * would reject the TOP_LEVEL_ENTER and never get to this point. - */ - DASSERT(is_embedding_toplevel(event->window)); - - receiver = get_embedded_window(event->display, event->window, x, y); - - if (receiver != None) { - component = get_component_for_window(receiver); - } - } else { - receiver = event->window; - } - - /* Translate mouse position from root coordinates - to the target window coordinates. */ - if (receiver != None) { - Window child = None; - XTranslateCoordinates(event->display, - get_root_for_window(receiver), - get_outer_canvas_for_window(receiver), - x, y, &x, &y, &child); - } - } - - if (JNU_IsNull(env, component)) { - if (!JNU_IsNull(env, target_component)) { - /* Triggers dragExit */ - dt_postDropTargetEvent(env, target_component, x, y, - java_awt_dnd_DnDConstants_ACTION_NONE, - java_awt_event_MouseEvent_MOUSE_EXITED, - NULL); - } - } else { - if (JNU_IsNull(env, target_component)) { - /* Triggers dragEnter */ - java_event_id = java_awt_event_MouseEvent_MOUSE_ENTERED; - } else { - /* Triggers dragOver */ - java_event_id = java_awt_event_MouseEvent_MOUSE_DRAGGED; - } - - dt_postDropTargetEvent(env, component, x, y, java_action, java_event_id, - event); - } - - source_actions = java_actions; - track_source_actions = False; - user_action = java_action; - source_x = x; - source_y = y; - target_component = component; - - return EventSuccess; -} - -/* - * Returns EventPassAlong if the event should be passed to the original proxy. - * TOP_LEVEL_LEAVE should be passed to the original proxy only if the event - * is invalid. - */ -static EventStatus -handle_motif_top_level_leave(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - char* event_data = event->data.b; - unsigned char event_byte_order = 0; - Window source_win = None; - - DTRACE_PRINTLN5("%s:%d TOP_LEVEL_LEAVE comp=%X src_win=%ld protocol=%d.", - __FILE__, __LINE__, - target_component, source_window, source_protocol); - - if (source_protocol != MOTIF_DND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d TOP_LEVEL_LEAVE rejected - invalid state.", - __FILE__, __LINE__); - return EventFailure; - } - - event_byte_order = read_card8(event_data, 1); - source_win = read_card32(event_data, 8, event_byte_order); - - /* Ignore Motif DnD messages from all other windows. */ - if (source_window != source_win) { - DTRACE_PRINTLN4("%s:%d TOP_LEVEL_LEAVE rejected - invalid source window cur=%ld this=%ld.", - __FILE__, __LINE__, source_window, source_win); - return EventFailure; - } - - /* - * Postpone upcall to java, so that we can abort it in case - * if drop immediatelly follows (see BugTraq ID 4395290). - * Send a dummy ClientMessage event to guarantee that a postponed java - * upcall will be processed. - */ - motif_top_level_leave_postponed = True; - { - XClientMessageEvent dummy; - Window proxy; - - dummy.display = event->display; - dummy.type = ClientMessage; - dummy.window = event->window; - dummy.format = 32; - dummy.message_type = None; - - /* - * If this is an embedded drop site, the event should go to the - * awt_root_window as this is a proxy for all embedded drop sites. - * Otherwise the event should go to the event->window, as we don't use - * proxies for normal drop sites. - */ - if (is_embedding_toplevel(event->window)) { - proxy = get_awt_root_window(); - } else { - proxy = event->window; - } - - XSendEvent(event->display, proxy, False, NoEventMask, - (XEvent*)&dummy); - } - - return EventSuccess; -} - -/* - * Returns EventPassAlong if the event should be passed to the original proxy. - * DROP_START event shouldn't be passed to the original proxy only if it is - * a valid event and the mouse coordinates passed in it specify the point over - * a Java component in this JVM. - */ -static EventStatus -handle_motif_drop_start(XClientMessageEvent* event) { - JNIEnv *env = (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_4); - char* event_data = event->data.b; - unsigned char event_byte_order = 0; - Window source_win = None; - Atom property_atom = None; - CARD16 flags = 0; - unsigned char motif_action = 0; - unsigned char motif_actions = 0; - jint java_action = java_awt_dnd_DnDConstants_ACTION_NONE; - jint java_actions = java_awt_dnd_DnDConstants_ACTION_NONE; - int x = 0; - int y = 0; - jobject component = NULL; - Window receiver = None; - - DTRACE_PRINTLN5("%s:%d DROP_START comp=%X src_win=%ld protocol=%d.", - __FILE__, __LINE__, - target_component, source_window, source_protocol); - - if (source_protocol != MOTIF_DND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d DROP_START rejected - invalid state.", - __FILE__, __LINE__); - return EventFailure; - } - - event_byte_order = read_card8(event_data, 1); - source_win = read_card32(event_data, 16, event_byte_order); - - /* Ignore Motif DnD messages from all other windows. */ - if (source_window != source_win) { - DTRACE_PRINTLN4("%s:%d DROP_START rejected - invalid source window cur=%ld this=%ld.", - __FILE__, __LINE__, source_window, source_win); - return EventFailure; - } - - property_atom = read_card32(event_data, 12, event_byte_order); - - flags = read_card16(event_data, 2, event_byte_order); - - motif_action = (flags & MOTIF_DND_ACTION_MASK) >> MOTIF_DND_ACTION_SHIFT; - motif_actions = (flags & MOTIF_DND_ACTIONS_MASK) >> MOTIF_DND_ACTIONS_SHIFT; - - java_action = motif_to_java_actions(motif_action); - java_actions = motif_to_java_actions(motif_actions); - - x = read_card16(event_data, 8, event_byte_order); - y = read_card16(event_data, 10, event_byte_order); - - source_actions = java_actions; - - component = get_component_for_window(event->window); - - if (JNU_IsNull(env, component)) { - /* - * The window must be the embedding toplevel, since otherwise we would reject the - * TOP_LEVEL_ENTER and never get to this point. - */ - DASSERT(is_embedding_toplevel(event->window)); - - receiver = get_embedded_window(event->display, event->window, x, y); - - if (receiver != None) { - component = get_component_for_window(receiver); - } - } else { - receiver = event->window; - } - - /* Translate mouse position from root coordinates - to the target window coordinates. */ - if (receiver != None) { - Window child = None; - XTranslateCoordinates(event->display, - get_root_for_window(receiver), - get_outer_canvas_for_window(receiver), - x, y, &x, &y, &child); - } - - if (JNU_IsNull(env, component)) { - if (!JNU_IsNull(env, target_component)) { - /* Triggers dragExit */ - dt_postDropTargetEvent(env, target_component, x, y, - java_awt_dnd_DnDConstants_ACTION_NONE, - java_awt_event_MouseEvent_MOUSE_EXITED, - NULL); - } - } else { - dt_postDropTargetEvent(env, component, x, y, java_action, - java_awt_event_MouseEvent_MOUSE_RELEASED, - event); - } - - return EventSuccess; -} - -static void -send_enter_message_to_toplevel(Window toplevel, XClientMessageEvent* xclient) { - XClientMessageEvent enter; - - if (source_protocol == XDND_PROTOCOL) { - enter.display = xclient->display; - enter.type = ClientMessage; - enter.window = toplevel; - enter.format = 32; - enter.message_type = XA_XdndEnter; - enter.data.l[0] = xclient->data.l[0]; /* XID of the source window */ - enter.data.l[1] = source_protocol_version << XDND_PROTOCOL_SHIFT; - enter.data.l[1] |= source_data_types_count > 3 ? XDND_DATA_TYPES_BIT : 0; - enter.data.l[2] = - source_data_types_count > 0 ? source_data_types_native[0] : None; - enter.data.l[3] = - source_data_types_count > 1 ? source_data_types_native[1] : None; - enter.data.l[4] = - source_data_types_count > 2 ? source_data_types_native[2] : None; - } else if (source_protocol == MOTIF_DND_PROTOCOL) { - int reason = (int)(xclient->data.b[0] & MOTIF_MESSAGE_REASON_MASK); - unsigned char byte_order = xclient->data.b[1]; - - enter.display = xclient->display; - enter.type = ClientMessage; - enter.window = toplevel; - enter.format = 8; - enter.message_type = _XA_MOTIF_DRAG_AND_DROP_MESSAGE; - - { - void* p = &enter.data.b[0]; - int flags = 0; - - flags |= java_to_motif_actions(user_action) << MOTIF_DND_ACTION_SHIFT; - flags |= java_to_motif_actions(source_actions) << MOTIF_DND_ACTIONS_SHIFT; - - write_card8(&p, TOP_LEVEL_ENTER | MOTIF_MESSAGE_FROM_INITIATOR); - write_card8(&p, byte_order); - write_card16(&p, flags); - { - Time time_stamp = read_card32(xclient->data.b, 4, byte_order); - Window src_window = source_window; - Atom motif_atom = _XA_MOTIF_ATOM_0; - - if (byte_order != MOTIF_BYTE_ORDER) { - SWAP4BYTES(time_stamp); - SWAP4BYTES(src_window); - SWAP4BYTES(motif_atom); - } - write_card32(&p, time_stamp); - write_card32(&p, src_window); - write_card32(&p, motif_atom); - } - } - } else { - return; - } - - forward_client_message_to_toplevel(toplevel, &enter); -} - -static void -send_leave_message_to_toplevel(Window toplevel, XClientMessageEvent* xclient) { - XClientMessageEvent leave; - - if (source_protocol == XDND_PROTOCOL) { - leave.display = xclient->display; - leave.type = ClientMessage; - leave.window = toplevel; - leave.format = 32; - leave.message_type = XA_XdndLeave; - leave.data.l[0] = xclient->data.l[0]; /* XID of the source window */ - leave.data.l[1] = 0; /* flags */ - } else if (source_protocol == MOTIF_DND_PROTOCOL) { - int reason = (int)(xclient->data.b[0] & MOTIF_MESSAGE_REASON_MASK); - unsigned char byte_order = xclient->data.b[1]; - - leave.display = xclient->display; - leave.type = ClientMessage; - leave.window = toplevel; - leave.format = 8; - leave.message_type = _XA_MOTIF_DRAG_AND_DROP_MESSAGE; - - { - void* p = &leave.data.b[0]; - int flags = 0; - - write_card8(&p, TOP_LEVEL_LEAVE | MOTIF_MESSAGE_FROM_INITIATOR); - write_card8(&p, byte_order); - - { - Time time_stamp = read_card32(xclient->data.b, 4, byte_order); - Window src_window = source_window; - - if (byte_order != MOTIF_BYTE_ORDER) { - SWAP4BYTES(time_stamp); - SWAP4BYTES(src_window); - } - write_card32(&p, time_stamp); - write_card32(&p, src_window); - } - } - } else { - return; - } - - forward_client_message_to_toplevel(toplevel, &leave); -} - -static void -post_process_client_message(XClientMessageEvent* xclient, EventStatus status, - EventType type) { - Window win = xclient->window; - Boolean postponed_leave = motif_top_level_leave_postponed; - - motif_top_level_leave_postponed = False; - - if (is_embedding_toplevel(win)) { - Boolean server_grabbed = False; - - if (postponed_leave) { - XClientMessageEvent* leave = &motif_top_level_leave_postponed_event; - DASSERT(leave->type == ClientMessage && type == DropEvent); - /* Grab the server to ensure that no event is sent between - the TOP_LEVEL_LEAVE and the next message. */ - XGrabServer(awt_display); - forward_client_message_to_toplevel(leave->window, leave); - memset(&motif_top_level_leave_postponed_event, 0, - sizeof(XClientMessageEvent)); - } - - /* - * This code forwards drag notifications to the browser according to the - * following rules: - * - the messages that we failed to process are always forwarded to the - * browser; - * - MotionEvents and DropEvents are forwarded if and only if the drag - * is not over a plugin window; - * - XDnD: EnterEvents and LeaveEvents are never forwarded, instead, we - * send synthesized EnterEvents or LeaveEvents when the drag - * respectively exits or enters plugin windows; - * - Motif DnD: EnterEvents and LeaveEvents are always forwarded. - * Synthetic EnterEvents and LeaveEvents are needed, because the XDnD drop - * site implemented Netscape 6.2 has a nice feature: when it receives - * the first XdndPosition it continuously sends XdndStatus messages to - * the source (every 100ms) until the drag terminates or leaves the drop - * site. When the mouse is dragged over plugin window embedded in the - * browser frame, these XdndStatus messages are mixed with the XdndStatus - * messages sent from the plugin. - * For Motif DnD, synthetic events cause Motif warnings being displayed, - * so these events are always forwarded. However, Motif DnD drop site in - * Netscape 6.2 is implemented in the same way, so there could be similar - * problems if the drag source choose Motif DnD for communication. - */ - switch (status) { - case EventFailure: - forward_client_message_to_toplevel(win, xclient); - break; - case EventSuccess: - { - /* True iff the previous notification was MotionEvent and it was - forwarded to the browser. */ - static Boolean motion_passed_along = False; - - Boolean motif_protocol = - xclient->message_type == _XA_MOTIF_DRAG_AND_DROP_MESSAGE; - - switch (type) { - case MotionEvent: - if (JNU_IsNull(env, target_component)) { - if (!motion_passed_along && !motif_protocol) { - send_enter_message_to_toplevel(win, xclient); - } - forward_client_message_to_toplevel(win, xclient); - motion_passed_along = True; - } else { - if (motion_passed_along && !motif_protocol) { - send_leave_message_to_toplevel(win, xclient); - } - motion_passed_along = False; - } - break; - case DropEvent: - if (JNU_IsNull(env, target_component)) { - forward_client_message_to_toplevel(win, xclient); - /* The last chance to cleanup. */ - awt_dnd_cleanup(); - } - motion_passed_along = False; - break; - case EnterEvent: - case LeaveEvent: - if (motif_protocol) { - forward_client_message_to_toplevel(win, xclient); - } - motion_passed_along = False; - break; - } - } - } - - if (postponed_leave) { - XUngrabServer(awt_display); - } - } -} - -/* - * Returns True if the event is processed and shouldn't be passed along to Java. - * Otherwise, return False. - */ -Boolean -awt_dnd_dt_process_event(XEvent* event) { - Display* dpy = event->xany.display; - EventStatus status = EventFailure; - EventType type = UnknownEvent; - - if (event->type == DestroyNotify) { - if (event->xany.window == source_window) { - awt_dnd_cleanup(); - } - /* pass along */ - return False; - } - - if (event->type == PropertyNotify) { - if (is_embedding_toplevel(event->xany.window)) { - Atom atom = event->xproperty.atom; - /* - * If some other client replaced the XDnD or Motif DnD proxy with - * another window we set the proxy back to the awt_root_window - * and update the entry in the embedded_drop_site_list. - * This code is needed, as for example Netscape 4.7 resets the proxy - * when the browser shell is resized. - */ - if (atom == _XA_MOTIF_DRAG_RECEIVER_INFO) { - Window prev_motif_proxy; - ProxyRegistrationStatus status; - status = set_motif_proxy(event->xany.display, event->xany.window, - get_awt_root_window(), &prev_motif_proxy); - if (status != RegFailure && status != RegAlreadyRegistered) { - set_motif_proxy_for_toplevel(event->xany.window, - prev_motif_proxy, - status == RegOverride); - } - } - - if (atom == XA_XdndAware || atom == XA_XdndProxy) { - Window prev_xdnd_proxy; - unsigned int prev_protocol_version; - ProxyRegistrationStatus status; - status = set_xdnd_proxy(event->xany.display, event->xany.window, - get_awt_root_window(), &prev_xdnd_proxy, - &prev_protocol_version); - if (status != RegFailure && status != RegAlreadyRegistered) { - set_xdnd_proxy_for_toplevel(event->xany.window, - prev_xdnd_proxy, - prev_protocol_version, - status == RegOverride); - } - } - } - /* pass along */ - return False; - } - - if (event->type != ClientMessage) { - return False; - } - - if (get_component_for_window(event->xany.window) == NULL && - !is_embedding_toplevel(event->xany.window)) { - return False; - } - - if (motif_top_level_leave_postponed) { - /* Sanity check. */ - if (source_protocol != MOTIF_DND_PROTOCOL) { - DTRACE_PRINTLN2("%s:%d TOP_LEVEL_LEAVE rejected - invalid state.", - __FILE__, __LINE__); - awt_dnd_cleanup(); - } else if (event->xclient.message_type == - _XA_MOTIF_DRAG_AND_DROP_MESSAGE) { - unsigned char first_byte = event->xclient.data.b[0]; - unsigned char reason = first_byte & MOTIF_MESSAGE_REASON_MASK; - unsigned char origin = first_byte & MOTIF_MESSAGE_SENDER_MASK; - - if (origin == MOTIF_MESSAGE_FROM_INITIATOR && - reason != DROP_START) { - awt_dnd_cleanup(); - } - } else { - awt_dnd_cleanup(); - } - } - - if (event->xclient.message_type == XA_XdndEnter) { - status = handle_xdnd_enter(&event->xclient); - type = EnterEvent; - } else if (event->xclient.message_type == XA_XdndPosition) { - status = handle_xdnd_position(&event->xclient); - type = MotionEvent; - } else if (event->xclient.message_type == XA_XdndLeave) { - status = handle_xdnd_leave(&event->xclient); - type = LeaveEvent; - } else if (event->xclient.message_type == XA_XdndDrop) { - status = handle_xdnd_drop(&event->xclient); - type = DropEvent; - } else if (event->xclient.message_type == _XA_MOTIF_DRAG_AND_DROP_MESSAGE) { - unsigned char reason = event->xclient.data.b[0] & MOTIF_MESSAGE_REASON_MASK; - unsigned char origin = event->xclient.data.b[0] & MOTIF_MESSAGE_SENDER_MASK; - - /* Only initiator messages should be handled. */ - if (origin == MOTIF_MESSAGE_FROM_INITIATOR) { - switch (reason) { - case DRAG_MOTION: - case OPERATION_CHANGED: - status = handle_motif_drag_motion(&event->xclient); - type = MotionEvent; - break; - case TOP_LEVEL_ENTER: - status = handle_motif_top_level_enter(&event->xclient); - type = EnterEvent; - break; - case TOP_LEVEL_LEAVE: - status = handle_motif_top_level_leave(&event->xclient); - type = LeaveEvent; - break; - case DROP_START: - status = handle_motif_drop_start(&event->xclient); - type = DropEvent; - break; - } - } - } else { - /* Unknown message type. */ - return False; - } - - /* - * We need to handle a special case here: Motif DnD protocol prescribed that - * DROP_START message should always be preceeded with TOP_LEVEL_LEAVE - * message. We need to cleanup on TOP_LEVEL_LEAVE message, but DROP_START - * wouldn't be processed properly. Instead we postpone the cleanup and - * send a dummy client message to ourselves. If dummy arrives first we do a - * normal cleanup. If DROP_START arrives before the dummy we discard delayed - * cleanup. - * In case of forwarding events from an embedded Java app to an embedding - * Java app it could happen that the embedding app receives the dummy before - * the DROP_START message arrives from the embedding app. In this case the - * drop operation on the embedding app fails to complete. - * To resolve this problem we postpone forwarding of TOP_LEVEL_LEAVE message - * until the next client message is about to be forwarded. - */ - if (motif_top_level_leave_postponed && type == LeaveEvent) { - /* motif_top_level_leave_postponed can be set only if the latest client - message has been processed successfully. */ - DASSERT(status == EventSuccess); - memcpy(&motif_top_level_leave_postponed_event, &event->xclient, - sizeof(XClientMessageEvent)); - } else { - post_process_client_message(&event->xclient, status, type); - } - - return True; -} - -static Boolean -register_xdnd_drop_site(Display* dpy, Window toplevel, Window window) { - unsigned char ret; - Atom version_atom = XDND_PROTOCOL_VERSION; - - ret = checked_XChangeProperty(dpy, window, XA_XdndAware, XA_ATOM, 32, - PropModeReplace, - (unsigned char*)&version_atom, 1); - - return (ret == Success); -} - -static Boolean -register_motif_drop_site(Display* dpy, Window toplevel, Window window) { - unsigned char status; - size_t data_size = MOTIF_RECEIVER_INFO_SIZE; - char* data = malloc(data_size); - void* p = data; - - if (data == NULL) { - DTRACE_PRINTLN2("%s:%d malloc failed.", __FILE__, __LINE__); - return False; - } - - write_card8(&p, MOTIF_BYTE_ORDER); - write_card8(&p, MOTIF_DND_PROTOCOL_VERSION); /* protocol version */ - write_card8(&p, MOTIF_DYNAMIC_STYLE); /* protocol style */ - write_card8(&p, 0); /* pad */ - write_card32(&p, window); /* proxy window */ - write_card16(&p, 0); /* num_drop_sites */ - write_card16(&p, 0); /* pad */ - write_card32(&p, data_size); - - status = checked_XChangeProperty(dpy, window, _XA_MOTIF_DRAG_RECEIVER_INFO, - _XA_MOTIF_DRAG_RECEIVER_INFO, 8, PropModeReplace, - (unsigned char*)data, data_size); - - free(data); - - return (status == Success); -} - -static Window -find_toplevel_window(Display* dpy, Window window) { - Window ret = None; - Window root = None; - Window parent = None; - Window *children; - unsigned int nchildren; - - int status; - - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - - /* Traverse the ancestor tree from window up to the root and find - the top-level client window nearest to the root. */ - do { - type = None; - - data = NULL; - status = XGetWindowProperty(dpy, window, XA_WM_STATE, 0, 0, False, - AnyPropertyType, &type, &format, &nitems, - &after, &data); - - if (status == Success) { - XFree(data); - } - - if (type != None) { - ret = window; - } - - if (!XQueryTree(dpy, window, &root, &parent, &children, &nchildren)) { - return None; - } - - XFree(children); - - window = parent; - } while (window != root); - - return ret; -} - -static Boolean -register_drop_site(Widget outer_canvas, XtPointer componentRef) { - Display* dpy = XtDisplay(outer_canvas); - Widget shell = NULL; - /* Shell window. */ - Window window = None; - Window root = None; - Window toplevel = None; - - for (shell = outer_canvas; shell != NULL && !XtIsShell(shell); - shell = XtParent(shell)); - - if (shell == NULL || !XtIsRealized(shell)) { - DTRACE_PRINTLN2("%s:%d Cannot find a realized shell for the widget.", - __FILE__, __LINE__); - return False; - } - - window = XtWindow(shell); - - if (!awt_dnd_init(dpy)) { - DTRACE_PRINTLN2("%s:%d Fail to initialize.", __FILE__, __LINE__); - return False; - } - - { - XWindowAttributes xwa; - - if (!XGetWindowAttributes(dpy, window, &xwa)) { - DTRACE_PRINTLN2("%s:%d XGetWindowAttributes failed.", __FILE__, __LINE__); - return False; - } - - root = xwa.root; - - if (root == None) { - DTRACE_PRINTLN2("%s:%d Bad root.", __FILE__, __LINE__); - return False; - } - } - - toplevel = find_toplevel_window(dpy, window); - - /* - * No window with WM_STATE property is found. - * Since the window can be a plugin window reparented to the browser - * toplevel, we cannot determine which window will eventually have WM_STATE - * property set. So we schedule a timer callback that will periodically - * attempt to find an ancestor with WM_STATE and register the drop site - * appropriately. - */ - if (toplevel == None) { - add_delayed_registration_entry(outer_canvas, componentRef); - return False; - } - - if (toplevel == window) { - Boolean xdnd_registered = False; - Boolean motif_registered = False; - - xdnd_registered = register_xdnd_drop_site(dpy, toplevel, window); - - motif_registered = register_motif_drop_site(dpy, toplevel, window); - - if (!xdnd_registered && !motif_registered) { - DTRACE_PRINTLN2("%s:%d Failed to register.", __FILE__, __LINE__); - return False; - } - } else { - if (!add_to_embedded_drop_site_list(dpy, root, toplevel, window)) { - DTRACE_PRINTLN2("%s:%d Failed to init proxy.", __FILE__, __LINE__); - return False; - } - } - - /* There is no need to update the window for the component later, since the - window is destroyed only when the component is disposed in which case the - drop site will be unregistered as well. */ - if (add_to_drop_site_list(window, root, toplevel, XtWindow(outer_canvas), - (jobject)componentRef)) { - DTRACE_PRINTLN2("%s:%d Drop site registered.", __FILE__, __LINE__); - return True; - } else { - DTRACE_PRINTLN2("%s:%d Failed to register.", __FILE__, __LINE__); - return False; - } -} - -static void -register_drop_site_when_realized(Widget outer_canvas, XtPointer client_data, - XEvent *event, Boolean *dontSwallow) { - if (XtIsRealized(outer_canvas)) { - XtRemoveEventHandler(outer_canvas, StructureNotifyMask, False, - register_drop_site_when_realized, client_data); - - register_drop_site(outer_canvas, client_data); - } -} - -/* - * Registers the top-level Window that contains the specified widget as a drop - * site that supports XDnD and Motif DnD protocols. - * If the registration fails for some reason, adds an event handler that will - * attempt to register the drop site later. - * - * Returns True if the drop site is registered successfully. - */ -static Boolean -awt_dnd_register_drop_site(Widget outer_canvas, XtPointer componentRef) { - if (XtIsRealized(outer_canvas)) { - return register_drop_site(outer_canvas, componentRef); - } else { - XtAddEventHandler(outer_canvas, StructureNotifyMask, False, - register_drop_site_when_realized, - componentRef); - - DTRACE_PRINTLN2("%s:%d Unrealized shell. Register later.", - __FILE__, __LINE__); - - return True; - } -} - -/* - * Unregisters the drop site associated with the top-level Window that contains - * the specified widget . - * - * Returns True if completes successfully, False otherwise. - */ -static Boolean -awt_dnd_unregister_drop_site(Widget outer_canvas, XtPointer componentRef) { - Widget shell = NULL; - - XtRemoveEventHandler(outer_canvas, StructureNotifyMask, False, - register_drop_site_when_realized, componentRef); - - remove_delayed_registration_entry(outer_canvas); - - for (shell = outer_canvas; shell != NULL && !XtIsShell(shell); - shell = XtParent(shell)); - - if (shell != NULL && XtIsShell(shell) && XtIsRealized(shell)) { - Window win = XtWindow(shell); - Window toplevel = get_toplevel_for_window(win); - /* - * Cleanup the global state if this drop site participate in the current - * drag operation. Particularly, this allows to delete global ref to the - * component safely. - */ - if (get_component_for_window(win) == target_component) { - awt_dnd_cleanup(); - } - if (toplevel != win) { - remove_from_embedded_drop_site_list(awt_display, toplevel, win); - } - return remove_from_drop_site_list(win); - } - - return True; -} - -/**************************** XEmbed server DnD support ***********************/ - -/* - * - * - */ -Boolean -register_xembed_drop_site(JNIEnv* env, Display* dpy, jobject server, - Window serverHandle, Window clientHandle) { - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char* data; - unsigned char ret; - unsigned int protocol_version; - - Window xdnd_proxy = None; - unsigned int xdnd_protocol_version = 0; - Boolean xdnd_override = False; - - if (!awt_dnd_init(dpy)) { - DTRACE_PRINTLN2("%s:%d Fail to initialize.", __FILE__, __LINE__); - return False; - } - - /* Get the XDnD protocol version and XDnD proxy of the XEmbed client. */ - data = NULL; - ret = checked_XGetWindowProperty(dpy, clientHandle, XA_XdndAware, 0, 1, - False, AnyPropertyType, &type, &format, - &nitems, &after, &data); - - /* XEmbed client doesn't have an associated XDnD drop site - - do nothing and return True to indicate success. */ - if (ret != Success || data == NULL || nitems == 0 || type != XA_ATOM) { - XFree(data); - return False; - } - - protocol_version = *((unsigned int*)data); - - XFree(data); - - if (protocol_version < XDND_MIN_PROTOCOL_VERSION) { - return False; - } - - xdnd_protocol_version = protocol_version; - - /* XdndProxy is not supported prior to XDnD version 4 */ - if (protocol_version >= 4) { - int status; - - data = NULL; - status = XGetWindowProperty(dpy, clientHandle, XA_XdndProxy, 0, 1, - False, XA_WINDOW, &type, &format, - &nitems, &after, &data); - - if (status == Success && data != NULL && type == XA_WINDOW) { - xdnd_proxy = *((Window*)data); - - if (xdnd_proxy != None) { - XFree(data); - - data = NULL; - status = XGetWindowProperty(dpy, xdnd_proxy, XA_XdndProxy, - 0, 1, False, XA_WINDOW, &type, - &format, &nitems, &after, - &data); - - if (status != Success || data == NULL || type != XA_WINDOW || - *((Window*)data) != xdnd_proxy) { - /* Ignore invalid proxy. */ - xdnd_proxy = None; - } - } - - if (xdnd_proxy != None) { - XFree(data); - - data = NULL; - status = XGetWindowProperty(dpy, xdnd_proxy, XA_XdndAware, 0, 1, - False, AnyPropertyType, &type, - &format, &nitems, &after, &data); - - if (status == Success && data != NULL && type == XA_ATOM) { - unsigned int proxy_version = *((unsigned int*)data); - - if (proxy_version != protocol_version) { - /* Ignore invalid proxy. */ - xdnd_proxy = None; - } - } else { - /* Ignore invalid proxy. */ - xdnd_proxy = None; - } - } - } - - XFree(data); - } - - set_xembed_drop_target(env, server); - - /* Add protocol specific entries for the embedded window. */ - /* Only XDnD protocol is supported for XEmbed clients. */ - { - EmbeddedDropSiteProtocolListEntry* xdnd_entry = NULL; - - xdnd_entry = malloc(sizeof(EmbeddedDropSiteProtocolListEntry)); - - if (xdnd_entry == NULL) { - return False; - } - - xdnd_entry->window = clientHandle; - xdnd_entry->proxy = xdnd_proxy; - xdnd_entry->protocol_version = xdnd_protocol_version; - xdnd_entry->overriden = True; - xdnd_entry->next = embedded_xdnd_protocol_list; - embedded_xdnd_protocol_list = xdnd_entry; - } - - { - EmbeddedDropSiteListEntry* entry = NULL; - Window* sites = NULL; - - entry = malloc(sizeof(EmbeddedDropSiteListEntry)); - - if (entry == NULL) { - return False; - } - - sites = malloc(sizeof(Window)); - - if (sites == NULL) { - free(entry); - return False; - } - - sites[0] = clientHandle; - - entry->toplevel = serverHandle; - entry->root = None; - entry->event_mask = 0; - entry->embedded_sites_count = 1; - entry->embedded_sites = sites; - entry->next = embedded_drop_site_list; - embedded_drop_site_list = entry; - } - - return True; -} - -Boolean -unregister_xembed_drop_site(JNIEnv* env, Display* dpy, jobject server, - Window serverHandle, Window clientHandle) { - remove_from_embedded_drop_site_list(dpy, serverHandle, clientHandle); - return True; -} - -void -forward_event_to_embedded(Window embedded, jlong ctxt, jint eventID) { - static XClientMessageEvent* prevMessage = NULL; - static Boolean overXEmbedClient = False; - - XClientMessageEvent* xclient = - (XClientMessageEvent*)jlong_to_ptr(ctxt); - - if (xclient == NULL && prevMessage == NULL) { - return; - } - - if (xclient != NULL) { - /* - * NOTE: this check guarantees that prevMessage will always be an XDnD - * drag message. - */ - if (!is_xdnd_drag_message_type(xclient->message_type)) { - return; - } - - if (!overXEmbedClient) { - long* appended_data = jlong_to_ptr(ctxt) + - sizeof(XClientMessageEvent); - - /* Copy XdndTypeList from source to proxy. */ - if ((appended_data[0] & XDND_DATA_TYPES_BIT) != 0) { - unsigned char ret; - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - - data = NULL; - ret = checked_XGetWindowProperty(xclient->display, - xclient->data.l[0], - XA_XdndTypeList, 0, 0xFFFF, - False, XA_ATOM, &type, &format, - &nitems, &after, &data); - - /* Ignore the source if the window is destroyed. */ - if (ret == BadWindow) { - return; - } - - if (ret == Success) { - if (type == XA_ATOM && format == 32) { - ret = checked_XChangeProperty(xclient->display, - xclient->window, - XA_XdndTypeList, XA_ATOM, - 32, PropModeReplace, data, - nitems); - } - - XFree(data); - } - } - - set_proxy_mode_source_window(xclient->data.l[0]); - - { - XClientMessageEvent enter; - enter.display = xclient->display; - enter.type = ClientMessage; - enter.window = embedded; - enter.format = 32; - enter.message_type = XA_XdndEnter; - - enter.data.l[0] = xclient->window; /* XID of the source window */ - enter.data.l[1] = appended_data[0]; - enter.data.l[2] = appended_data[1]; - enter.data.l[3] = appended_data[2]; - enter.data.l[4] = appended_data[3]; - - forward_client_message_to_toplevel(embedded, &enter); - } - - overXEmbedClient = True; - } - - /* Make a copy of the original event, since we are going to modify the - event while it still can be referenced from other Java events. */ - { - XClientMessageEvent copy; - memcpy(©, xclient, sizeof(XClientMessageEvent)); - copy.data.l[0] = xclient->window; - - forward_client_message_to_toplevel(embedded, ©); - } - } - - if (eventID == java_awt_event_MouseEvent_MOUSE_EXITED) { - if (overXEmbedClient) { - if (xclient != NULL || prevMessage != NULL) { - /* Last chance to send XdndLeave to the XEmbed client. */ - XClientMessageEvent leave; - - leave.display = xclient != NULL ? - xclient->display : prevMessage->display; - leave.type = ClientMessage; - leave.window = embedded; - leave.format = 32; - leave.message_type = XA_XdndLeave; - leave.data.l[0] = xclient != NULL ? - xclient->window : prevMessage->window; /* XID of the source window */ - leave.data.l[1] = 0; /* flags */ - - forward_client_message_to_toplevel(embedded, &leave); - } - overXEmbedClient = False; - } - } - - if (eventID == java_awt_event_MouseEvent_MOUSE_RELEASED) { - overXEmbedClient = False; - awt_dnd_cleanup(); - } - - if (prevMessage != 0) { - free(prevMessage); - prevMessage = 0; - } - - if (xclient != 0 && overXEmbedClient) { - prevMessage = malloc(sizeof(XClientMessageEvent)); - - memcpy(prevMessage, xclient, sizeof(XClientMessageEvent)); - } -} - -/******************************************************************************/ - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: registerX11DropTarget - * Signature: (Ljava/awt/Component;)V - */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_registerX11DropTarget(JNIEnv *env, jobject this, - jobject target) { - struct FrameData* wdata = NULL; - DropSitePtr dsi = NULL; - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL || wdata->winData.comp.widget == NULL) { - JNU_ThrowNullPointerException(env, "NULL component data"); - return; - } - - if (wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "Null shell widget"); - return; - } - - DASSERT(wdata->winData.comp.dsi == NULL); - - dsi = (DropSitePtr)calloc(1, sizeof(struct DropSiteInfo)); - - if (dsi == NULL) { - JNU_ThrowOutOfMemoryError(env, ""); - return; - } - - dsi->component = (*env)->NewGlobalRef(env, target); - dsi->isComposite = False; - - wdata->winData.comp.dsi = dsi; - - AWT_LOCK(); - - awt_dnd_register_drop_site(wdata->winData.comp.widget, - dsi->component); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MWindowPeer - * Method: unregisterX11DropTarget - * Signature: (Ljava/awt/Component;)V - */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_MWindowPeer_unregisterX11DropTarget(JNIEnv *env, - jobject this, - jobject target) { - struct FrameData* wdata = NULL; - DropSitePtr dsi = NULL; - - wdata = (struct FrameData *) - JNU_GetLongFieldAsPtr(env, this, mComponentPeerIDs.pData); - - if (wdata == NULL) { - JNU_ThrowNullPointerException(env, "Null component data"); - return; - } - - if (wdata->winData.shell == NULL) { - JNU_ThrowNullPointerException(env, "Null shell widget"); - return; - } - - dsi = wdata->winData.comp.dsi; - - if (dsi == NULL) { - JNU_ThrowNullPointerException(env, "Null DropSiteInfo"); - return; - } - - AWT_LOCK(); - - awt_dnd_unregister_drop_site(wdata->winData.comp.widget, dsi->component); - - AWT_UNLOCK(); - - wdata->winData.comp.dsi = NULL; - - (*env)->DeleteGlobalRef(env, dsi->component); - - free(dsi); -} - -static void -dt_send_event_to_source(XClientMessageEvent* xclient) { - /* Shortcut if the source is in the same JVM. */ - if (xclient->window == awt_dnd_ds_get_source_window()) { - awt_dnd_ds_process_event((XEvent*)xclient); - } else { - unsigned char ret; - - ret = checked_XSendEvent(xclient->display, xclient->window, False, - NoEventMask, (XEvent*)xclient); - - if (ret == BadWindow) { - DTRACE_PRINTLN2("%s:%d XSendEvent - invalid window.", - __FILE__, __LINE__); - - /* Cleanup if we are still communicating with this window. */ - if (source_window == xclient->window) { - awt_dnd_cleanup(); - } - } - } -} - -static void -dt_send_response(XClientMessageEvent* xclient, jint eventID, jint action) { - Display* dpy = xclient->display; - XClientMessageEvent response; - - if (xclient->message_type == XA_XdndPosition) { - long* event_data = xclient->data.l; - - if (eventID == java_awt_event_MouseEvent_MOUSE_EXITED) { - action = java_awt_dnd_DnDConstants_ACTION_NONE; - } - - response.display = dpy; - response.type = ClientMessage; - response.window = event_data[0]; - response.format = 32; - response.message_type = XA_XdndStatus; - /* target window */ - response.data.l[0] = xclient->window; - /* flags */ - response.data.l[1] = 0; - if (action != java_awt_dnd_DnDConstants_ACTION_NONE) { - response.data.l[1] |= XDND_ACCEPT_DROP_FLAG; - } - /* specify an empty rectangle */ - response.data.l[2] = 0; /* x, y */ - response.data.l[3] = 0; /* w, h */ - /* action accepted by the target */ - response.data.l[4] = java_to_xdnd_action(action); - } else if (xclient->message_type == _XA_MOTIF_DRAG_AND_DROP_MESSAGE) { - int reason = (int)(xclient->data.b[0] & MOTIF_MESSAGE_REASON_MASK); - int origin = (int)(xclient->data.b[0] & MOTIF_MESSAGE_SENDER_MASK); - unsigned char byte_order = xclient->data.b[1]; - CARD16 response_flags = 0; - CARD8 response_reason = 0; - void* p = &response.data.b; - - /* Only initiator messages should be handled. */ - if (origin != MOTIF_MESSAGE_FROM_INITIATOR) { - DTRACE_PRINTLN2("%s:%d Receiver message.", __FILE__, __LINE__); - return; - } - - switch (reason) { - case DRAG_MOTION: - switch (eventID) { - case java_awt_event_MouseEvent_MOUSE_ENTERED: - response_reason = DROP_SITE_ENTER; - break; - case java_awt_event_MouseEvent_MOUSE_DRAGGED: - response_reason = DRAG_MOTION; - break; - case java_awt_event_MouseEvent_MOUSE_EXITED: - response_reason = DROP_SITE_LEAVE; - break; - } - } - - response.display = dpy; - response.type = ClientMessage; - response.window = read_card32(xclient->data.b, 12, byte_order); - response.format = 8; - response.message_type = _XA_MOTIF_DRAG_AND_DROP_MESSAGE; - - write_card8(&p, response_reason | MOTIF_MESSAGE_FROM_RECEIVER); - write_card8(&p, MOTIF_BYTE_ORDER); - - if (response_reason != DROP_SITE_LEAVE) { - CARD16 flags = read_card16(xclient->data.b, 2, byte_order); - unsigned char drop_site_status = - (action == java_awt_dnd_DnDConstants_ACTION_NONE) ? - MOTIF_INVALID_DROP_SITE : MOTIF_VALID_DROP_SITE; - - /* Clear action and drop site status bits. */ - response_flags = - flags & ~MOTIF_DND_ACTION_MASK & ~MOTIF_DND_STATUS_MASK; - - /* Fill in new action and drop site status. */ - response_flags |= - java_to_motif_actions(action) << MOTIF_DND_ACTION_SHIFT; - response_flags |= - drop_site_status << MOTIF_DND_STATUS_SHIFT; - } else { - response_flags = 0; - } - - write_card16(&p, response_flags); - - /* Write time stamp. */ - write_card32(&p, read_card32(xclient->data.b, 4, byte_order)); - - /* Write coordinates. */ - if (response_reason != DROP_SITE_LEAVE) { - write_card16(&p, read_card16(xclient->data.b, 8, byte_order)); - write_card16(&p, read_card16(xclient->data.b, 10, byte_order)); - } else { - write_card16(&p, 0); - write_card16(&p, 0); - } - } else { - return; - } - - dt_send_event_to_source(&response); -} - -static void -dummy_selection_callback(Widget w, XtPointer client_data, Atom* selection, - Atom* type, XtPointer value, unsigned long *length, - int32_t *format) { - /* The selection callback is responsible for freeing the data. */ - if (value != NULL) { - XtFree(value); - value = NULL; - } -} - -static void -dt_notify_drop_done(JNIEnv* env, XClientMessageEvent* xclient, jboolean success, - jint action) { - if (xclient->message_type == XA_XdndDrop) { - Display* dpy = xclient->display; - XClientMessageEvent finished; - long* event_data = xclient->data.l; - - /* - * The XDnD protocol recommends that the target requests the special - * target DELETE in case if the drop action is XdndActionMove. - */ - if (action == java_awt_dnd_DnDConstants_ACTION_MOVE && - success == JNI_TRUE) { - - Time time_stamp = event_data[2]; - - XtGetSelectionValue(awt_root_shell, XA_XdndSelection, XA_DELETE, - dummy_selection_callback, NULL, time_stamp); - } - - finished.display = dpy; - finished.type = ClientMessage; - finished.window = event_data[0]; - finished.format = 32; - finished.message_type = XA_XdndFinished; - finished.data.l[0] = xclient->window; - finished.data.l[1] = 0; /* flags */ - finished.data.l[2] = None; - if (source_protocol_version >= 5) { - if (success == JNI_TRUE) { - finished.data.l[1] |= XDND_ACCEPT_DROP_FLAG; - } - finished.data.l[2] = java_to_xdnd_action(action); - } - - dt_send_event_to_source(&finished); - } else if (xclient->message_type == _XA_MOTIF_DRAG_AND_DROP_MESSAGE) { - char* event_data = xclient->data.b; - unsigned char event_byte_order = read_card8(event_data, 1); - unsigned char first_byte = read_card8(event_data, 0); - unsigned char reason = first_byte & MOTIF_MESSAGE_REASON_MASK; - unsigned char origin = first_byte & MOTIF_MESSAGE_SENDER_MASK; - Atom selection = None; - Time time_stamp = CurrentTime; - Atom status_atom = None; - - if (origin != MOTIF_MESSAGE_FROM_INITIATOR) { - DTRACE_PRINTLN2("%s:%d Invalid origin.", __FILE__, __LINE__); - return; - } - - if (reason != DROP_START) { - DTRACE_PRINTLN2("%s:%d Invalid reason.", __FILE__, __LINE__); - return; - } - - selection = read_card32(event_data, 12, event_byte_order); - time_stamp = read_card32(event_data, 4, event_byte_order); - - if (success == JNI_TRUE) { - status_atom = XA_XmTRANSFER_SUCCESS; - } else { - status_atom = XA_XmTRANSFER_FAILURE; - } - - /* - * This is just the way to communicate the drop completion status back - * to the initiator as prescribed by the Motif DnD protocol. - */ - XtGetSelectionValue(awt_root_shell, selection, status_atom, - dummy_selection_callback, NULL, time_stamp); - } - - /* - * Flush the buffer to guarantee that the drop completion event is sent - * to the source before the method returns. - */ - XFlush(awt_display); - - /* Trick to prevent awt_dnd_cleanup() from posting dragExit */ - target_component = NULL; - /* Cannot do cleanup before the drop finishes as we need source protocol - version to send XdndFinished message. */ - awt_dnd_cleanup(); -} - -/* - * Class: sun_awt_motif_X11DropTargetContextPeer - * Method: sendResponse - * Signature: (IIJZ)V - */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_X11DropTargetContextPeer_sendResponse(JNIEnv *env, - jobject this, - jint eventID, - jint action, - jlong nativeCtxt, - jboolean dispatcherDone, - jboolean consumed) { - XClientMessageEvent* xclient = - (XClientMessageEvent*)jlong_to_ptr(nativeCtxt); - - AWT_LOCK(); - - if (consumed == JNI_FALSE) { - dt_send_response(xclient, eventID, action); - } - - /* - * Free the native context only if all copies of the original event are - * processed. - */ - if (dispatcherDone == JNI_TRUE) { - XtFree((char*)xclient); - } - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_X11DropTargetContextPeer - * Method: dropDone - * Signature: (JZI)V - */ - -JNIEXPORT void JNICALL -Java_sun_awt_motif_X11DropTargetContextPeer_dropDone(JNIEnv *env, - jobject this, - jlong nativeCtxt, - jboolean success, - jint action) { - XClientMessageEvent* xclient = - (XClientMessageEvent*)jlong_to_ptr(nativeCtxt); - - AWT_LOCK(); - - dt_notify_drop_done(env, xclient, success, action); - - XtFree((char*)xclient); - - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_X11DropTargetContextPeer - * Method: getData - * Signature: (IJ)Ljava/lang/Object; - */ - -JNIEXPORT jobject JNICALL -Java_sun_awt_motif_X11DropTargetContextPeer_getData(JNIEnv *env, - jobject this, - jlong nativeCtxt, - jlong formatAtom) { - XClientMessageEvent* xclient = - (XClientMessageEvent*)jlong_to_ptr(nativeCtxt); - - Atom selection = None; - Time time_stamp = CurrentTime; - Atom target = (Atom)formatAtom; - - if (xclient->message_type == XA_XdndDrop || - xclient->message_type == XA_XdndPosition) { - Display* dpy = xclient->display; - Window source_win = xclient->data.l[0]; - Atom protocol_version = 0; - - int status; - - Atom type; - int format; - unsigned long nitems; - unsigned long after; - unsigned char *data; - - AWT_LOCK(); - - data = NULL; - status = XGetWindowProperty(dpy, source_win, XA_XdndAware, 0, 0xFFFF, - False, XA_ATOM, &type, &format, &nitems, - &after, &data); - - if (status == Success && data != NULL && type == XA_ATOM && format == 32 - && nitems > 0) { - protocol_version = (protocol_version > XDND_PROTOCOL_VERSION) ? - XDND_PROTOCOL_VERSION : protocol_version; - - if (protocol_version > 0) { - if (xclient->message_type == XA_XdndDrop) { - time_stamp = xclient->data.l[2]; - } else if (xclient->message_type == XA_XdndPosition) { - time_stamp = xclient->data.l[3]; - } - } - } - - if (status == Success) { - XFree(data); - data = NULL; - } - - AWT_FLUSH_UNLOCK(); - - selection = XA_XdndSelection; - if (time_stamp == CurrentTime) { - time_stamp = awt_util_getCurrentServerTime(); - } - - } else if (xclient->message_type == _XA_MOTIF_DRAG_AND_DROP_MESSAGE) { - char* event_data = xclient->data.b; - unsigned char event_byte_order = read_card8(event_data, 1); - unsigned char first_byte = read_card8(event_data, 0); - unsigned char reason = first_byte & MOTIF_MESSAGE_REASON_MASK; - unsigned char origin = first_byte & MOTIF_MESSAGE_SENDER_MASK; - - if (origin != MOTIF_MESSAGE_FROM_INITIATOR) { - DTRACE_PRINTLN2("%s:%d Invalid origin.", __FILE__, __LINE__); - return NULL; - } - - switch (reason) { - case DROP_START: - selection = read_card32(event_data, 12, event_byte_order); - break; - case DRAG_MOTION: - case OPERATION_CHANGED: - selection = source_atom; - break; - default: - DTRACE_PRINTLN2("%s:%d Invalid reason.", __FILE__, __LINE__); - return NULL; - } - - if (selection == None) { - return NULL; - } - - time_stamp = read_card32(event_data, 4, event_byte_order); - } else { - return NULL; - } - - return get_selection_data(env, selection, target, time_stamp); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_motif.c b/jdk/src/solaris/native/sun/awt/awt_motif.c deleted file mode 100644 index 818e3e17fcc..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_motif.c +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2000-2002 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_motif.h" - -#include - -/* Common routines required for both Motif 2.1 and Motif 1.2 */ -#include - -/* Remove the ScrollBar widget's continuous scrolling timeout handler - on a ButtonRelease to prevent the continuous scrolling that would - occur if a timeout expired after the ButtonRelease. -*/ -/* - * Note: RFE:4263104 is filed when the API is available these needs to removed - */ -void -awt_motif_Scrollbar_ButtonReleaseHandler(Widget w, - XtPointer data, - XEvent *event, - Boolean *cont) -{ - /* Remove the timeout handler. */ -#define END_TIMER (1<<2) - XmScrollBarWidget sbw = (XmScrollBarWidget) w; - if (sbw->scrollBar.timer != NULL) { - XtRemoveTimeOut( sbw->scrollBar.timer ); - sbw->scrollBar.timer = (XtIntervalId)NULL; - sbw->scrollBar.flags |= END_TIMER; - } -} diff --git a/jdk/src/solaris/native/sun/awt/awt_motif12.c b/jdk/src/solaris/native/sun/awt/awt_motif12.c deleted file mode 100644 index fc3d90ed995..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_motif12.c +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#if MOTIF_VERSION!=1 - #error This file should only be compiled with motif 1.2 -#endif - -#include "awt_motif.h" -#include -#include -#include "debug_util.h" -#include "awt.h" - -/* - * awt_motif_getIMStatusHeight is a cut and paste of the ImGetGeo() function - * found in CDE Motif's Xm/XmIm.c. It returns the height of the Input Method - * Status region attached to the given VendorShell. This is needed in order - * to calculate geometry for Frames and Dialogs that contain TextField or - * TextArea widgets. - * - * BCB: Copying this function out of the Motif source is a horrible - * hack. Unfortunately, Motif tries to hide the existence of the IM Status - * region from us so it does not provide any public way to get this info. - * Clearly a better long term solution needs to be found. - */ - -typedef struct _XmICStruct { - struct _XmICStruct *next; - Widget icw; - Window focus_window; - XtArgVal foreground; - XtArgVal background; - XtArgVal background_pixmap; - XtArgVal font_list; - XtArgVal line_space; - int32_t status_width; - int32_t status_height; - int32_t preedit_width; - int32_t preedit_height; - Boolean has_focus; - Boolean need_reset; -} XmICStruct; - -typedef struct { - Widget im_widget; - XIMStyle input_style; - XIC xic; - int32_t status_width; - int32_t status_height; - int32_t preedit_width; - int32_t preedit_height; - XmICStruct *iclist; - XmICStruct *current; -} XmImInfo; - -static XFontSet extract_fontset(XmFontList); -static XmICStruct *get_iclist(Widget); - -#define MAXARGS 10 -static Arg xic_vlist[MAXARGS]; -static Arg status_vlist[MAXARGS]; -static Arg preedit_vlist[MAXARGS]; - -#define NO_ARG_VAL -1 -#define SEPARATOR_HEIGHT 2 - - -#ifdef MOTIF_2_1_HACK -/* To shut up warning messages from "cc -v" - * Copied from Solaris 2.6 /usr/dt/include/Xm/BaseClassP.h and not - * there in Solaris 7. - */ -#if defined(__SunOS_5_7) || defined(__SunOS_5_8) -extern XmWidgetExtData _XmGetWidgetExtData(Widget, unsigned char); -#endif - -#else - -/* - The following defines are to make the XmImGetXIC to compile on systems - lower than SunOS 5.7, so therefore the following is a copy of the - defines on SunOS 5.7/Motif2.1 header files. -*/ -/*#if defined (__SunOS_5_5_1) || defined (__SunOS_5_6)*/ -#define XmPER_SHELL 0 - -extern XIC XmImGetXIC( - Widget w, - unsigned int input_policy, - ArgList args, - Cardinal num_args) ; -#endif - -static XmICStruct * -get_iclist(Widget w) -{ - Widget p; - XmVendorShellExtObject ve; - XmWidgetExtData extData; - XmImInfo *im_info; - - p = w; - while (!XtIsShell(p)) - p = XtParent(p); - - extData = (XmWidgetExtData)_XmGetWidgetExtData((Widget) p, XmSHELL_EXTENSION); - if (extData == NULL) - return NULL; - - ve = (XmVendorShellExtObject) extData->widget; - if ((im_info = (XmImInfo *) ve->vendor.im_info) == NULL) - return NULL; - else - return im_info->iclist; -} - -int32_t -awt_motif_getIMStatusHeight(Widget vw, jobject tc) -{ - XmICStruct *icp; - XmVendorShellExtObject ve; - XmWidgetExtData extData; - XmImInfo *im_info; - int32_t width = 0; - int32_t height = 0; - XRectangle rect; - XRectangle *rp; - int32_t old_height; - Arg args[1]; - int32_t base_height; - XFontSet fs; - XFontSet fss = NULL; - XFontSet fsp = NULL; - - extData = (XmWidgetExtData)_XmGetWidgetExtData((Widget) vw, XmSHELL_EXTENSION); - ve = (XmVendorShellExtObject) extData->widget; - - if ((icp = get_iclist(vw)) == NULL) { - ve->vendor.im_height = 0; - return 0; - } - im_info = (XmImInfo *) ve->vendor.im_info; - if (im_info->xic == NULL) { - ve->vendor.im_height = 0; - return 0; - } - status_vlist[0].name = XNFontSet; - status_vlist[1].name = NULL; - preedit_vlist[0].name = XNFontSet; - preedit_vlist[1].name = NULL; - - xic_vlist[0].name = XNAreaNeeded; - xic_vlist[1].name = NULL; - - im_info->status_width = 0; - im_info->status_height = 0; - im_info->preedit_width = 0; - im_info->preedit_height = 0; - for (; icp != NULL; icp = icp->next) { - if (im_info->input_style & XIMStatusArea) { - if (icp->status_height == 0) { - char *ret; - - if (icp->font_list == NO_ARG_VAL || - (fss = extract_fontset((XmFontList) icp->font_list)) == NULL) - continue; - - status_vlist[0].value = (XtArgVal) fss; - XSetICValues(im_info->xic, - XNStatusAttributes, &status_vlist[0], - NULL); - - xic_vlist[0].value = (XtArgVal) & rp; - ret = XGetICValues(im_info->xic, - XNStatusAttributes, &xic_vlist[0], - NULL); - - if (ret) { - /* Cannot obtain XIC value. IM server may be gone. */ - ve->vendor.im_height = 0; - return 0; - } else { - icp->status_width = rp->width; - icp->status_height = rp->height; - XFree(rp); - } - } - if (icp->status_width > im_info->status_width) - im_info->status_width = icp->status_width; - if (icp->status_height > im_info->status_height) - im_info->status_height = icp->status_height; - } - if (im_info->input_style & XIMPreeditArea) { - if (icp->preedit_height == 0) { - if (icp->font_list == NO_ARG_VAL || - (fsp = extract_fontset((XmFontList) icp->font_list)) == NULL) - continue; - - preedit_vlist[0].value = (XtArgVal) fsp; - XSetICValues(im_info->xic, - XNPreeditAttributes, &preedit_vlist[0], - NULL); - - xic_vlist[0].value = (XtArgVal) & rp; - XGetICValues(im_info->xic, - XNPreeditAttributes, &xic_vlist[0], - NULL); - - icp->preedit_width = rp->width; - icp->preedit_height = rp->height; - XFree(rp); - } - if (icp->preedit_width > im_info->preedit_width) - im_info->preedit_width = icp->preedit_width; - if (icp->preedit_height > im_info->preedit_height) - im_info->preedit_height = icp->preedit_height; - } - } - - if (im_info->current != NULL && (fss != NULL || fsp != NULL)) { - if (im_info->current->font_list != NO_ARG_VAL && - (fs = extract_fontset((XmFontList) im_info->current->font_list)) - != NULL) { - if (fss != NULL) - status_vlist[0].value = (XtArgVal) fs; - else - status_vlist[0].name = NULL; - if (fsp != NULL) - preedit_vlist[0].value = (XtArgVal) fs; - else - preedit_vlist[0].name = NULL; - XSetICValues(im_info->xic, - XNStatusAttributes, &status_vlist[0], - XNPreeditAttributes, &preedit_vlist[0], - NULL); - } - } - if (im_info->status_height > im_info->preedit_height) - height = im_info->status_height; - else - height = im_info->preedit_height; - old_height = ve->vendor.im_height; - if (height) - height += SEPARATOR_HEIGHT; - - ve->vendor.im_height = height; - - XtSetArg(args[0], XtNbaseHeight, &base_height); - XtGetValues(vw, args, 1); - if (base_height < 0) - base_height = 0; - XtSetArg(args[0], XtNbaseHeight, base_height); - XtSetValues(vw, args, 1); - return height; -} -static XRectangle geometryRect; -XVaNestedList awt_motif_getXICStatusAreaList(Widget w, jobject tc) -{ - Widget p; - XmVendorShellExtObject ve; - XmWidgetExtData extData; - XmImInfo *im_info; - XmICStruct *icp; - - XVaNestedList list = NULL; - XRectangle *ssgeometry = &geometryRect; - Pixel bg; - Pixel fg; - Pixmap bpm; - Dimension height,width; - Position x,y; - - p = w; - while (!XtIsShell(p)){ - p = XtParent(p); - } - - XtVaGetValues(p, - XmNx, &x, - XmNy, &y, - XmNwidth, &width, - XmNheight, &height, - NULL); - - extData = (XmWidgetExtData)_XmGetWidgetExtData((Widget) p, XmSHELL_EXTENSION); - if (extData == NULL) { - return NULL; - } - - ve = (XmVendorShellExtObject) extData->widget; - if ((im_info = (XmImInfo *) ve->vendor.im_info) == NULL) { - return NULL; - } else - icp = im_info->iclist; - - - if (icp) { - /* - * We hava at least a textfield/textarea in the frame, use the - * first one. - */ - ssgeometry->x = 0; - ssgeometry->y = height - icp->status_height; - ssgeometry->width = icp->status_width; - ssgeometry->height = icp->status_height; - - /* - * use motif TextComponent's resource - */ - fg = icp->foreground; - bg = icp->background; - bpm = icp->background_pixmap; - - list = XVaCreateNestedList(0, - XNFontSet, extract_fontset((XmFontList)icp->font_list), - XNArea, ssgeometry, - XNBackground, bg, - XNForeground, fg, - XNBackgroundPixmap, bpm, - NULL); - } - return list ; -} - -static XFontSet -extract_fontset(XmFontList fl) -{ - XmFontContext context; - XmFontListEntry next_entry; - XmFontType type_return; - XtPointer tmp_font; - XFontSet first_fs = NULL; - char *font_tag; - - if (!XmFontListInitFontContext(&context, fl)) - return NULL; - - do { - next_entry = XmFontListNextEntry(context); - if (next_entry) { - tmp_font = XmFontListEntryGetFont(next_entry, &type_return); - if (type_return == XmFONT_IS_FONTSET) { - font_tag = XmFontListEntryGetTag(next_entry); - if (!strcmp(font_tag, XmFONTLIST_DEFAULT_TAG)) { - XmFontListFreeFontContext(context); - XtFree(font_tag); - return (XFontSet) tmp_font; - } - XtFree(font_tag); - if (first_fs == NULL) - first_fs = (XFontSet) tmp_font; - } - } - } while (next_entry); - - XmFontListFreeFontContext(context); - return first_fs; -} - -/* - * Motif 1.2 requires that an X event passed to XmDragStart is of - * ButtonPress type. In Motif 2.1 the restriction is relaxed to allow - * ButtonPress, ButtonRelease, KeyRelease, KeyPress, MotionNotify events - * as drag initiators. Actually the code in Motif 1.2 works okay for these - * events as well, since it uses only the fields that have the same values - * in all five event types. To bypass the initial sanity check in - * XmDragStart we forcibly change event type to ButtonPress. - * - * This function causes an UnsatisfiedLinkError on Linux. - * Since Linux only links against Motif 2.1, we can safely remove - * this function altogether from the Linux build. - * bchristi 1/22/2001 - */ - -#ifdef __solaris__ -void -awt_motif_adjustDragTriggerEvent(XEvent* xevent) { - xevent->type = ButtonPress; -} -#endif /* __solaris__ */ - -static XmDragStartProc do_drag_start = NULL; -static Widget drag_initiator = NULL; - -static void -CheckedDragStart(XmDragContext dc, Widget src, XEvent *event) { - DASSERT(do_drag_start != NULL); - DASSERT(drag_initiator != NULL); - /* - * Fix for BugTraq ID 4407057. - * Enable the drag operation only if it is registered on the specific widget. - * We use this check to disable Motif default drag support. - */ - if (src == drag_initiator) { - do_drag_start(dc, src, event); - } else { - /* - * This is the last chance to destroy the XmDragContext widget. - * NOTE: We rely on the fact that Motif 1.2 never uses the pointer - * to XmDragContext object returned from XmDragStart. - */ - XtDestroyWidget(dc); - } -} - -void -awt_motif_enableSingleDragInitiator(Widget w) { - DASSERT(drag_initiator == NULL && do_drag_start == NULL && w != NULL); - drag_initiator = w; - do_drag_start = xmDragContextClassRec.drag_class.start; - DASSERT(do_drag_start != NULL); - xmDragContextClassRec.drag_class.start = (XmDragStartProc)CheckedDragStart; -} diff --git a/jdk/src/solaris/native/sun/awt/awt_motif21.c b/jdk/src/solaris/native/sun/awt/awt_motif21.c deleted file mode 100644 index 3bd95f97aef..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_motif21.c +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#if MOTIF_VERSION!=2 - #error This file should only be compiled with motif 2.1 -#endif - -#include "awt_motif.h" -#include -#include "awt.h" -#include "awt_p.h" -#include "awt_Component.h" - -#define XmPER_SHELL 0 -extern int32_t _XmImGetGeo( - Widget vw) ; - -#define MAXARGS 10 -static Arg xic_vlist[MAXARGS]; - -#define SEPARATOR_HEIGHT 2 -#define MTEXTAREAPEER_CLASS_NAME "sun/awt/motif/MTextAreaPeer" -extern struct MComponentPeerIDs mComponentPeerIDs; -static jobject mTextAreaClass = NULL; - -/* - * Get the Motif text widget from the text component peer. XmImGetXIC() - * function should be issued on Motif text widgets. - */ -static Widget getTextWidget(jobject tc) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - if (mTextAreaClass == NULL) { - jclass localClass = (*env)->FindClass(env, MTEXTAREAPEER_CLASS_NAME); - mTextAreaClass = (jclass)(*env)->NewGlobalRef(env, localClass); - (*env)->DeleteLocalRef(env, localClass); - } - - if ((*env)->IsInstanceOf(env, tc, mTextAreaClass)) { - struct TextAreaData * tdata = (struct TextAreaData *) - JNU_GetLongFieldAsPtr(env, tc, mComponentPeerIDs.pData); - return tdata->txt; - } else { - struct ComponentData * tdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, tc, mComponentPeerIDs.pData); - return tdata->widget; - } -} - -/* get_im_height: returns height of the input method status area in pixels. - * - * This function assumes that if any XIM related information cannot be - * queried then the app must not have an input method status area in the - * current locale and returns zero as the status area height - */ -int32_t -awt_motif_getIMStatusHeight(Widget w, jobject tc) -{ - XIC xic = NULL; - XRectangle *im_rect=NULL; - int32_t im_height = 0; - char *ret; - - xic = XmImGetXIC(getTextWidget(tc), XmPER_SHELL, NULL, 0); - - if(xic != NULL) { - /* finally query the server for the status area geometry */ - xic_vlist[0].name = XNArea; - xic_vlist[0].value = (XtArgVal)&im_rect; - xic_vlist[1].name = NULL; - ret=XGetICValues(xic, XNStatusAttributes, &xic_vlist[0], NULL); - if (ret == NULL && im_rect != NULL) { - im_height = im_rect->height; - if (im_height > 0) { - im_height += SEPARATOR_HEIGHT; - } - XFree(im_rect); - } else { - im_height = 0; - } - } - - if (im_height == 0) { - im_height = _XmImGetGeo(w); - } - -#if defined(DEBUG) - jio_fprintf(stderr,"awt_motif_getIMStatusHeight: Height = %d",im_height); -#endif - return im_height; -} - - -static XRectangle geomRect; -static Pixmap bpm; -XVaNestedList awt_motif_getXICStatusAreaList(Widget w, jobject tc) -{ - XIC xic; - - XRectangle *im_rect; - XFontSet *im_font; - - Pixel bg ; - Pixel fg ; - Dimension height, width ; - Position x,y ; - - XVaNestedList list = NULL; - - char *ret; - Widget p=w; - - while (!XtIsShell(p)) { - p = XtParent(p); - } - - XtVaGetValues(p, - XmNx, &x, - XmNy, &y, - XmNwidth, &width, - XmNheight, &height, - XmNbackgroundPixmap, &bpm, - NULL); - - - - xic = XmImGetXIC(getTextWidget(tc), XmPER_SHELL, NULL, 0); - if(xic == NULL) - { -#if defined DEBUG - jio_fprintf(stderr,"Could not get XIC"); -#endif - return list ; - } - - /* finally query the server for the required attributes area geometry */ - xic_vlist[0].name = XNFontSet ; - xic_vlist[0].value = (XtArgVal) &im_font ; - xic_vlist[1].name = XNArea; - xic_vlist[1].value = (XtArgVal) &im_rect; - xic_vlist[2].name = XNBackground ; - xic_vlist[2].value = (XtArgVal) &bg ; - xic_vlist[3].name = XNForeground ; - xic_vlist[3].value = (XtArgVal) &fg ; - xic_vlist[4].name = NULL; - - - if(ret=XGetICValues(xic, XNStatusAttributes, &xic_vlist[0], NULL)) - { - return list ; - } else { - geomRect.x = 0 ; - geomRect.y = height - im_rect->height ; - geomRect.width = im_rect->width ; - geomRect.height = im_rect->height ; - XFree(im_rect) ; - - list = XVaCreateNestedList(0 , - XNFontSet, im_font , - XNArea, &geomRect , - XNBackground, bg , - XNForeground, fg , - XNBackgroundPixmap, &bpm , - NULL ); - } -#if defined(DEBUG) - jio_fprintf(stderr,"awt_motif_getXICStatusAreaList:\n"); - jio_fprintf(stderr,"XNArea:x=%d,y=%d,width=%d,height=%d\n", \ - geomRect.x,geomRect.y,geomRect.width,geomRect.height); - jio_fprintf(stderr,"XNBackground=0x%x\n",bg); - jio_fprintf(stderr,"XNForeground=0x%x\n",fg); - jio_fprintf(stderr,"XNBackgroundPixmap=0x%x\n",bpm); -#endif - return list ; - -} - - /* This function causes an UnsatisfiedLinkError on Linux. - * Since Linux only links against Motif 2.1 and under 2.1 this function - * is a no-op, we can safely remove - * this function altogether from the Linux build. - * bchristi 1/22/2001 - */ - -#ifdef __solaris__ -void -awt_motif_adjustDragTriggerEvent(XEvent* xevent) { - /* Do nothing. In Motif 2.1 the sanity check is corrected - to allow any imput event as a drag trigger event. */ -} -#endif /* __solaris__ */ - -static void -CheckDragInitiator(Widget w, XtPointer client_data, - XmDragStartCallbackStruct* cbstruct) { - Widget drag_initiator = (Widget)client_data; - /* - * Fix for BugTraq ID 4407057. - * Enable the drag operation only if it is registered on the specific - * widget. We use this check to disable Motif default drag support. - */ - if (drag_initiator != cbstruct->widget) { - cbstruct->doit = False; - } -} - -void -awt_motif_enableSingleDragInitiator(Widget w) { - XtAddCallback(XmGetXmDisplay(XtDisplay(w)), - XmNdragStartCallback, (XtCallbackProc)CheckDragInitiator, - (XtPointer)w); -} diff --git a/jdk/src/solaris/native/sun/awt/awt_p.h b/jdk/src/solaris/native/sun/awt/awt_p.h index eb7bc55a27d..fb4f513f79f 100644 --- a/jdk/src/solaris/native/sun/awt/awt_p.h +++ b/jdk/src/solaris/native/sun/awt/awt_p.h @@ -79,7 +79,7 @@ #ifndef XAWT #include "GLXGraphicsConfig.h" -#include +//#include #endif #ifndef HEADLESS diff --git a/jdk/src/solaris/native/sun/awt/awt_xembed.c b/jdk/src/solaris/native/sun/awt/awt_xembed.c deleted file mode 100644 index 86bfae68f66..00000000000 --- a/jdk/src/solaris/native/sun/awt/awt_xembed.c +++ /dev/null @@ -1,430 +0,0 @@ -/* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" - -#include -#include -#include -#include - -/* JNI headers */ -#include "java_awt_Frame.h" /* for frame state constants */ - -#include "awt_wm.h" -#include "awt_util.h" /* for X11 error handling macros */ -#include "awt_xembed.h" -#include "awt_MToolkit.h" -#include "awt_DataTransferer.h" /* for DECLARE_XXX macros */ - -#ifdef DOTRACE -#define MTRACE(param) fprintf(myerr, param) -#define MTRACEP1(format, p1) fprintf(myerr, format, p1) -#define MTRACEP2(format, p1, p2) fprintf(myerr, format, p1, p2) -#define MTRACEP3(format, p1, p2, p3) fprintf(myerr, format, p1, p2, p3) -#define MTRACEP4(format, p1, p2, p3, p4) fprintf(myerr, format, p1, p2, p3, p4) -#define MTRACEP5(format, p1, p2, p3, p4, p5) fprintf(myerr, format, p1, p2, p3, p4, p5) -#define MTRACEP6(format, p1, p2, p3, p4, p5, p6) fprintf(myerr, format, p1, p2, p3, p4, p5, p6) -#define MTRACEP7(format, p1, p2, p3, p4, p5, p6, p7) fprintf(myerr, format, p1, p2, p3, p4, p5, p6, p7) -#else -#define MTRACE(param) -#define MTRACEP1(format, p1) -#define MTRACEP2(format, p1, p2) -#define MTRACEP3(format, p1, p2, p3) -#define MTRACEP4(format, p1, p2, p3, p4) -#define MTRACEP5(format, p1, p2, p3, p4, p5) -#define MTRACEP6(format, p1, p2, p3, p4, p5, p6) -#define MTRACEP7(format, p1, p2, p3, p4, p5, p6, p7) -#endif - -#ifdef DOTRACE -static FILE* myerr; -#endif - -static Window getParent(Window window); -static Window getEmbedder(Window client); -static jmethodID handleFocusInMID; - -const char * error_msg = "UNKNOWN XEMBED MESSAGE"; - -const char * xembed_strs[] = { - "EMBEDDED_NOTIFY", - "WINDOW_ACTIVATE", - "WINDOW_DEACTIVATE", - "REQUEST_FOCUS", - "FOCUS_IN", - "FOCUS_OUT", - "FOCUS_NEXT", - "FOCUS_PREV" , - "GRAB_KEY", - "UNGRAB_KEY", - "MODALITY_ON" , - "MODALITY_OFF", - "REGISTER_ACCELERATOR", - "UNREGISTER_ACCELERATOR", - "ACTIVATE_ACCELERATOR" -}; - -const char * -msg_to_str(int msg) { - if (msg >= 0 && msg <= XEMBED_LAST_MSG) { - return xembed_strs[msg]; - } else { - return error_msg; - } -} - -DECLARE_JAVA_CLASS(MEmbeddedFramePeerClass, "sun/awt/motif/MEmbeddedFramePeer"); - -typedef struct _xembed_info { - CARD32 version; - CARD32 flags; -} xembed_info; - -typedef struct _xembed_data { - struct FrameData * wdata; // pointer to EmbeddedFrame wdata - Window client; // pointer to plugin intermediate widget, XEmbed client - Boolean active; // whether xembed is active for this client - Boolean applicationActive; // whether the embedding application is active - Window embedder; // Window ID of the embedder - struct _xembed_data * next; -} xembed_data, * pxembed_data; - -static pxembed_data xembed_list = NULL; - -static pxembed_data -getData(Window client) { - pxembed_data temp = xembed_list; - while (temp != NULL) { - if (temp->client == client) { - return temp; - } - temp = temp->next; - } - return NULL; -} - -static pxembed_data -getDataByFrame(struct FrameData* wdata) { - pxembed_data temp = xembed_list; - while (temp != NULL) { - if (temp->wdata == wdata) { - return temp; - } - temp = temp->next; - } - return NULL; -} - -static pxembed_data -addData(Window client) { - xembed_data * data = malloc(sizeof(xembed_data)); - memset(data, 0, sizeof(xembed_data)); - data->client = client; - data->next = xembed_list; - xembed_list = data; - return data; -} - -static void -removeData(Window client) { - pxembed_data * temp = &xembed_list; - while (*temp != NULL) { - if ((*temp)->client == client) { - xembed_data * data = *temp; - *temp = (*temp)->next; - free(data); - return; - } - temp = &(*temp)->next; - } -} - -static Atom XA_XEmbedInfo; -static Atom XA_XEmbed; - -void -init_xembed() { - XA_XEmbedInfo = XInternAtom(awt_display, "_XEMBED_INFO", False); - XA_XEmbed = XInternAtom(awt_display, "_XEMBED", False); -#ifdef DOTRACE - myerr = fopen("xembedclient.log","w"); -#endif -} - -static Time -getCurrentServerTime() { - return awt_util_getCurrentServerTime(); -} - - -void -sendMessageHelper(Window window, int message, long detail, - long data1, long data2) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - XEvent ev; - XClientMessageEvent * req = (XClientMessageEvent*)&ev; - memset(&ev, 0, sizeof(ev)); - - req->type = ClientMessage; - req->window = window; - req->message_type = XA_XEmbed; - req->format = 32; - req->data.l[0] = getCurrentServerTime(); - req->data.l[1] = message; - req->data.l[2] = detail; - req->data.l[3] = data1; - req->data.l[4] = data2; - AWT_LOCK(); - XSendEvent(awt_display, window, False, NoEventMask, &ev); - AWT_UNLOCK(); -} - -void -sendMessage(Window window, int message) { - sendMessageHelper(window, message, 0, 0, 0); -} - - -static Window -getParent(Window window) { - Window root, parent = None, *children = NULL; - unsigned int count; - XQueryTree(awt_display, window, &root, &parent, &children, &count); - if (children != NULL) { - XFree(children); - } - return parent; -} - -static Window -getEmbedder(Window client) { - return getParent(client); -} - - -static void -handleFocusIn(struct FrameData* wdata, int detail) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - struct WidgetInfo* winfo; - MTRACE("HandleFocusIn\n"); - winfo = findWidgetInfo(wdata->winData.comp.widget); - if (winfo != NULL) { - jobject peer = winfo->peer; - if (handleFocusInMID == NULL) { - jclass clazz = (*env)->FindClass(env, "sun/awt/motif/MEmbeddedFramePeer"); - DASSERT(clazz != NULL); - handleFocusInMID = (*env)->GetMethodID(env, clazz, "handleFocusIn", "(I)V"); - DASSERT(handleFocusInMID != NULL); - if (clazz != NULL) { - (*env)->DeleteLocalRef(env, clazz); - } - } - if (handleFocusInMID != NULL) { - (*env)->CallVoidMethod(env, peer, handleFocusInMID, (jint)detail); - } - } -} - -static void -genWindowFocus(struct FrameData *wdata, Boolean gain) { - XEvent ev; - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - memset(&ev, 0, sizeof(ev)); - - ev.type = (gain?FocusIn:FocusOut); - ev.xany.send_event = True; - ev.xany.display = awt_display; - ev.xfocus.mode = NotifyNormal; - ev.xfocus.detail = NotifyNonlinear; - ev.xfocus.window = XtWindow(wdata->winData.shell); - awt_put_back_event(env, &ev); -} - -extern Boolean skipNextFocusIn; - -static void -callNotifyStarted(JNIEnv* env, jobject peer) { - DECLARE_VOID_JAVA_METHOD(notifyStartedMID, MEmbeddedFramePeerClass, - "notifyStarted", "()V"); - - (*env)->CallVoidMethod(env, peer, notifyStartedMID); -} - -void -xembed_eventHandler(XEvent *event) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - struct FrameData *wdata; - xembed_data * data; - - data = getData(event->xany.window); - if (data == NULL) { - MTRACEP1("No XEMBED client registered for this window %x\n", event->xany.window); - if (event->xany.type == ClientMessage) { - MTRACEP7("Unprocessed handleClientMessage: type=%d 0=%ld 1=%ld(%s) 2=%ld 3=%ld 4=%ld\n", - event->xclient.message_type, event->xclient.data.l[0], - event->xclient.data.l[1], msg_to_str(event->xclient.data.l[1]), - event->xclient.data.l[2], - event->xclient.data.l[3], event->xclient.data.l[4]); - } - return; - } - - wdata = data->wdata; - - if (event->xany.type == ClientMessage) { - MTRACEP6("handleClientMessage: type=%d 0=%ld 1=%ld 2=%ld 3=%ld 4=%ld\n", - event->xclient.message_type, event->xclient.data.l[0], - event->xclient.data.l[1], event->xclient.data.l[2], - event->xclient.data.l[3], event->xclient.data.l[4]); - // Probably a message from embedder - if (event->xclient.message_type == XA_XEmbed) { - // XEmbed message, data[1] contains message - switch ((int)event->xclient.data.l[1]) { - case XEMBED_EMBEDDED_NOTIFY: - MTRACE("EMBEDDED_NOTIFY\n"); - data->active = True; - data->embedder = getEmbedder(data->client); - // If Frame has not been reparented already we should "reparent" - // it manually - if (!(wdata->reparented)) { - wdata->reparented = True; - // in XAWT we also update WM_NORMAL_HINTS here. - } - { - struct WidgetInfo* winfo = - findWidgetInfo(wdata->winData.comp.widget); - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_4); - if (winfo != NULL) { - callNotifyStarted(env, winfo->peer); - } - } - MTRACE("Embedded notify in client\n"); - break; - case XEMBED_WINDOW_DEACTIVATE: - MTRACE("DEACTIVATE\n"); - data->applicationActive = False; - break; - case XEMBED_WINDOW_ACTIVATE: - MTRACE("ACTIVATE\n"); - data->applicationActive = True; - break; - case XEMBED_FOCUS_IN: - MTRACE("FOCUS IN\n"); - skipNextFocusIn = False; - handleFocusIn(wdata, (int)(event->xclient.data.l[2])); - genWindowFocus(wdata, True); - break; - case XEMBED_FOCUS_OUT: - MTRACE("FOCUS OUT\n"); - genWindowFocus(wdata, False); - break; - } - } - } else if (event->xany.type == ReparentNotify) { - data->embedder = event->xreparent.parent; - } -} - -void -notify_ready(Window client) { - sendMessage(getEmbedder(client), _SUN_XEMBED_START); -} - -void -install_xembed(Widget client_widget, struct FrameData* wdata) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - xembed_info info = {XEMBED_VERSION, XEMBED_MAPPED}; - Window client = XtWindow(client_widget); - xembed_data * data; - - AWT_LOCK(); - data = addData(client); - data->wdata = wdata; - - // Install event handler for messages from embedder - XSelectInput(awt_display, client, StructureNotifyMask); - - // Install XEMBED_INFO information - XChangeProperty(awt_display, client, XA_XEmbedInfo, - XA_XEmbedInfo, 32, PropModeReplace, - (unsigned char*)&info, 2); - MTRACE("Installing xembed\n"); - - notify_ready(client); - - AWT_UNLOCK(); -} - -void -deinstall_xembed(struct FrameData* wdata) { - xembed_data * data = getDataByFrame(wdata); - - if (data != NULL) { - removeData(data->client); - } -} - -void -requestXEmbedFocus(struct FrameData * wdata) { - xembed_data * data = getDataByFrame(wdata); - - if (data != NULL) { - if (data->active && data->applicationActive) { - sendMessage(data->embedder, XEMBED_REQUEST_FOCUS); - } - } -} - -Boolean -isXEmbedActive(struct FrameData * wdata) { - xembed_data * data = getDataByFrame(wdata); - return (data != NULL && data->active); -} - -Boolean -isXEmbedActiveByWindow(Window client) { - xembed_data * data = getData(client); - return (data != NULL && data->active); -} - - -Boolean -isXEmbedApplicationActive(struct FrameData * wdata) { - xembed_data * data = getDataByFrame(wdata); - return (data != NULL && data->applicationActive); -} - -void -xembed_traverse_out(struct FrameData * wdata, jboolean direction) { - xembed_data * data = getDataByFrame(wdata); - sendMessage(data->embedder, (direction == JNI_TRUE)?XEMBED_FOCUS_NEXT:XEMBED_FOCUS_PREV); -} diff --git a/jdk/src/solaris/native/sun/awt/canvas.c b/jdk/src/solaris/native/sun/awt/canvas.c deleted file mode 100644 index 1a2f7dd4164..00000000000 --- a/jdk/src/solaris/native/sun/awt/canvas.c +++ /dev/null @@ -1,3227 +0,0 @@ -/* - * Copyright 1995-2005 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include /* timeval */ - -#define XK_KATAKANA -#include /* standard X keysyms */ -#include /* DEC vendor-specific */ -#include /* Sun vendor-specific */ -#include /* Apollo (HP) vendor-specific */ -/* - * #include HP vendor-specific - * I checked HPkeysym.h into the workspace because it ships - * with X11R6.4.2 (and later) but not with X11R6.4.1. - * So, it ought to ship with Solaris 9, but not Solaris 8. - * Same deal for Linux - newer versions of XFree have it. - * - * Note: this is mainly done for the hp keysyms; it does NOT - * give us the osf keysyms that are also defined in HPkeysym.h. - * This is because we are already getting /Xm/VirtKeys.h - * from awt_p.h <- /Xm/Xm.h <- /Xm/VirtKeys.h, and VirtKeys.h - * #defines _OSF_Keysyms before we get here. We are - * missing a couple of osf keysyms because of this, - * so I have #defined them below. - */ -#include "HPkeysym.h" /* HP vendor-specific */ - -#include -#include -#include "java_awt_Frame.h" -#include "java_awt_Component.h" -#include "java_awt_AWTEvent.h" -#include "java_awt_event_KeyEvent.h" -#include "java_awt_event_FocusEvent.h" -#include "java_awt_event_MouseEvent.h" -#include "java_awt_event_MouseWheelEvent.h" -#include "java_awt_event_InputEvent.h" -#include "java_awt_event_WindowEvent.h" -#include "sun_awt_motif_MComponentPeer.h" -#include "color.h" -#include "canvas.h" -#include "awt_Cursor.h" -#include "VDrawingArea.h" -#include "XDrawingArea.h" -#include "awt_Component.h" -#include "awt_AWTEvent.h" -#include "awt_Event.h" -#include "awt_KeyboardFocusManager.h" -#include "awt_MToolkit.h" -#include "awt_TopLevel.h" -#include "awt_util.h" - -#include -#include -#include -#include - -#ifdef NDEBUG /* NDEBUG overrides DEBUG */ -#undef DEBUG -#endif - -/* - * Two osf keys are not defined in standard keysym.h, - * /Xm/VirtKeys.h, or HPkeysym.h, so I added them below. - * I found them in /usr/openwin/lib/X11/XKeysymDB - */ -#ifndef osfXK_Prior -#define osfXK_Prior 0x1004FF55 -#endif -#ifndef osfXK_Next -#define osfXK_Next 0x1004FF56 -#endif -/* - * osfXK_Escape is defined in HPkeysym.h, but not in - * /Xm/VirtKeys.h, so I added it below. It is also in - * /usr/openwin/lib/X11/XKeysymDB - * Note: it is in /Xm/VirtKeys.h in the AWT motif workspace, - * but not in /usr/local/Motif/include/Xm/VirtKeys.h - * on the Solaris 7, 8, or 9 machines I tried. - */ -#ifndef osfXK_Escape -#define osfXK_Escape 0x1004FF1B -#endif - -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct AWTEventIDs awtEventIDs; -extern struct KeyEventIDs keyEventIDs; -extern struct InputEventIDs inputEventIDs; -extern struct ComponentIDs componentIDs; -extern struct KeyboardFocusManagerIDs keyboardFocusManagerIDs; - -#ifdef DEBUG -static Boolean debugKeys = False; -#endif - -jint awt_multiclick_smudge = 4; - -extern Widget drag_source; - -Widget prevWidget = NULL; /* for bug fix 4017222 */ - -FocusListElt *focusList = NULL, *focusListEnd = NULL; - -jweak forGained = NULL; - -extern Boolean scrollBugWorkAround; -extern jobject currentX11InputMethodInstance; -extern Window currentFocusWindow; -extern Boolean awt_x11inputmethod_lookupString(XKeyPressedEvent *, KeySym *); -Boolean awt_UseType4Patch = True; -Boolean awt_ServerDetected = False; -Boolean awt_IsXsun = False; -Boolean awt_UseXKB = False; - -void awt_post_java_key_event(XtPointer client_data, jint id, - XEvent *xevent, Time when, jint keycode, - jchar keychar, jint modifiers, - jint keyLocation, XEvent *anEvent); -void awt_post_java_focus_event(XtPointer client_data, jint id, jobject cause, - XEvent *event); -void awt_post_java_mouse_event(XtPointer client_data, jint id, - XEvent *event, Time when, jint modifiers, - jint x, jint y, - jint xAbs, jint yAbs, - jint clickcount, Boolean popuptrigger, - jint wheelAmt, jint button); - -typedef struct KEYMAP_ENTRY { - jint awtKey; - KeySym x11Key; - Boolean mapsToUnicodeChar; - jint keyLocation; -} KeymapEntry; - -/* NB: XK_R? keysyms are for Type 4 keyboards. - * The corresponding XK_F? keysyms are for Type 5 - * - * Note: this table must be kept in sorted order, since it is traversed - * according to both Java keycode and X keysym. There are a number of - * keycodes that map to more than one corresponding keysym, and we need - * to choose the right one. Unfortunately, there are some keysyms that - * can map to more than one keycode, depending on what kind of keyboard - * is in use (e.g. F11 and F12). - */ - -KeymapEntry keymapTable[] = -{ - {java_awt_event_KeyEvent_VK_A, XK_a, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_B, XK_b, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_C, XK_c, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_D, XK_d, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_E, XK_e, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F, XK_f, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_G, XK_g, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_H, XK_h, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_I, XK_i, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_J, XK_j, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_K, XK_k, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_L, XK_l, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_M, XK_m, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_N, XK_n, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_O, XK_o, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_P, XK_p, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_Q, XK_q, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_R, XK_r, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_S, XK_s, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_T, XK_t, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_U, XK_u, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_V, XK_v, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_W, XK_w, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_X, XK_x, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_Y, XK_y, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_Z, XK_z, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* TTY Function keys */ - {java_awt_event_KeyEvent_VK_BACK_SPACE, XK_BackSpace, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_TAB, XK_Tab, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CLEAR, XK_Clear, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_ENTER, XK_Return, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_ENTER, XK_Linefeed, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAUSE, XK_Pause, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAUSE, XK_F21, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAUSE, XK_R1, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_SCROLL_LOCK, XK_Scroll_Lock, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_SCROLL_LOCK, XK_F23, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_SCROLL_LOCK, XK_R3, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_ESCAPE, XK_Escape, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Other vendor-specific versions of TTY Function keys */ - {java_awt_event_KeyEvent_VK_BACK_SPACE, osfXK_BackSpace, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CLEAR, osfXK_Clear, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_ESCAPE, osfXK_Escape, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Modifier keys */ - {java_awt_event_KeyEvent_VK_SHIFT, XK_Shift_L, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_LEFT}, - {java_awt_event_KeyEvent_VK_SHIFT, XK_Shift_R, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_RIGHT}, - {java_awt_event_KeyEvent_VK_CONTROL, XK_Control_L, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_LEFT}, - {java_awt_event_KeyEvent_VK_CONTROL, XK_Control_R, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_RIGHT}, - {java_awt_event_KeyEvent_VK_ALT, XK_Alt_L, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_LEFT}, - {java_awt_event_KeyEvent_VK_ALT, XK_Alt_R, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_RIGHT}, - {java_awt_event_KeyEvent_VK_META, XK_Meta_L, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_LEFT}, - {java_awt_event_KeyEvent_VK_META, XK_Meta_R, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_RIGHT}, - {java_awt_event_KeyEvent_VK_CAPS_LOCK, XK_Caps_Lock, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Misc Functions */ - {java_awt_event_KeyEvent_VK_PRINTSCREEN, XK_Print, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PRINTSCREEN, XK_F22, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PRINTSCREEN, XK_R2, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CANCEL, XK_Cancel, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_HELP, XK_Help, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_NUM_LOCK, XK_Num_Lock, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - - /* Other vendor-specific versions of Misc Functions */ - {java_awt_event_KeyEvent_VK_CANCEL, osfXK_Cancel, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_HELP, osfXK_Help, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Rectangular Navigation Block */ - {java_awt_event_KeyEvent_VK_HOME, XK_Home, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_HOME, XK_R7, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_UP, XK_Page_Up, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_UP, XK_Prior, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_UP, XK_R9, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_DOWN, XK_Page_Down, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_DOWN, XK_Next, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_DOWN, XK_R15, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_END, XK_End, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_END, XK_R13, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_INSERT, XK_Insert, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DELETE, XK_Delete, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Keypad equivalents of Rectangular Navigation Block */ - {java_awt_event_KeyEvent_VK_HOME, XK_KP_Home, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_PAGE_UP, XK_KP_Page_Up, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_PAGE_UP, XK_KP_Prior, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_PAGE_DOWN, XK_KP_Page_Down, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_PAGE_DOWN, XK_KP_Next, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_END, XK_KP_End, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_INSERT, XK_KP_Insert, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_DELETE, XK_KP_Delete, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - - /* Other vendor-specific Rectangular Navigation Block */ - {java_awt_event_KeyEvent_VK_PAGE_UP, osfXK_PageUp, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_UP, osfXK_Prior, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_DOWN, osfXK_PageDown, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PAGE_DOWN, osfXK_Next, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_END, osfXK_EndLine, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_INSERT, osfXK_Insert, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DELETE, osfXK_Delete, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Triangular Navigation Block */ - {java_awt_event_KeyEvent_VK_LEFT, XK_Left, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_UP, XK_Up, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_RIGHT, XK_Right, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DOWN, XK_Down, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Keypad equivalents of Triangular Navigation Block */ - {java_awt_event_KeyEvent_VK_KP_LEFT, XK_KP_Left, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_KP_UP, XK_KP_Up, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_KP_RIGHT, XK_KP_Right, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_KP_DOWN, XK_KP_Down, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - - /* Other vendor-specific Triangular Navigation Block */ - {java_awt_event_KeyEvent_VK_LEFT, osfXK_Left, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_UP, osfXK_Up, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_RIGHT, osfXK_Right, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DOWN, osfXK_Down, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Remaining Cursor control & motion */ - {java_awt_event_KeyEvent_VK_BEGIN, XK_Begin, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_BEGIN, XK_KP_Begin, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - - {java_awt_event_KeyEvent_VK_0, XK_0, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_1, XK_1, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_2, XK_2, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_3, XK_3, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_4, XK_4, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_5, XK_5, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_6, XK_6, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_7, XK_7, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_8, XK_8, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_9, XK_9, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - {java_awt_event_KeyEvent_VK_SPACE, XK_space, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_EXCLAMATION_MARK, XK_exclam, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_QUOTEDBL, XK_quotedbl, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_NUMBER_SIGN, XK_numbersign, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DOLLAR, XK_dollar, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_AMPERSAND, XK_ampersand, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_QUOTE, XK_apostrophe, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_LEFT_PARENTHESIS, XK_parenleft, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_RIGHT_PARENTHESIS, XK_parenright, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_ASTERISK, XK_asterisk, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PLUS, XK_plus, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_COMMA, XK_comma, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_MINUS, XK_minus, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PERIOD, XK_period, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_SLASH, XK_slash, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - {java_awt_event_KeyEvent_VK_COLON, XK_colon, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_SEMICOLON, XK_semicolon, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_LESS, XK_less, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_EQUALS, XK_equal, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_GREATER, XK_greater, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - {java_awt_event_KeyEvent_VK_AT, XK_at, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - {java_awt_event_KeyEvent_VK_OPEN_BRACKET, XK_bracketleft, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_BACK_SLASH, XK_backslash, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CLOSE_BRACKET, XK_bracketright, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CIRCUMFLEX, XK_asciicircum, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_UNDERSCORE, XK_underscore, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_BACK_QUOTE, XK_grave, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - {java_awt_event_KeyEvent_VK_BRACELEFT, XK_braceleft, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_BRACERIGHT, XK_braceright, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - {java_awt_event_KeyEvent_VK_INVERTED_EXCLAMATION_MARK, XK_exclamdown, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Remaining Numeric Keypad Keys */ - {java_awt_event_KeyEvent_VK_NUMPAD0, XK_KP_0, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD1, XK_KP_1, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD2, XK_KP_2, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD3, XK_KP_3, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD4, XK_KP_4, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD5, XK_KP_5, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD6, XK_KP_6, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD7, XK_KP_7, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD8, XK_KP_8, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_NUMPAD9, XK_KP_9, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_SPACE, XK_KP_Space, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_TAB, XK_KP_Tab, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_ENTER, XK_KP_Enter, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_EQUALS, XK_KP_Equal, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_EQUALS, XK_R4, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_MULTIPLY, XK_KP_Multiply, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_MULTIPLY, XK_F26, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_MULTIPLY, XK_R6, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_ADD, XK_KP_Add, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_SEPARATOR, XK_KP_Separator, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_SUBTRACT, XK_KP_Subtract, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_SUBTRACT, XK_F24, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_DECIMAL, XK_KP_Decimal, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_DIVIDE, XK_KP_Divide, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_DIVIDE, XK_F25, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - {java_awt_event_KeyEvent_VK_DIVIDE, XK_R5, TRUE, java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD}, - - /* Function Keys */ - {java_awt_event_KeyEvent_VK_F1, XK_F1, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F2, XK_F2, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F3, XK_F3, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F4, XK_F4, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F5, XK_F5, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F6, XK_F6, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F7, XK_F7, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F8, XK_F8, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F9, XK_F9, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F10, XK_F10, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F11, XK_F11, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F12, XK_F12, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Sun vendor-specific version of F11 and F12 */ - {java_awt_event_KeyEvent_VK_F11, SunXK_F36, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_F12, SunXK_F37, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* X11 keysym names for input method related keys don't always - * match keytop engravings or Java virtual key names, so here we - * only map constants that we've found on real keyboards. - */ - /* Type 5c Japanese keyboard: kakutei */ - {java_awt_event_KeyEvent_VK_ACCEPT, XK_Execute, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - /* Type 5c Japanese keyboard: henkan */ - {java_awt_event_KeyEvent_VK_CONVERT, XK_Kanji, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - /* Type 5c Japanese keyboard: nihongo */ - {java_awt_event_KeyEvent_VK_INPUT_METHOD_ON_OFF, XK_Henkan_Mode, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - /* VK_KANA_LOCK is handled separately because it generates the - * same keysym as ALT_GRAPH in spite of its different behavior. - */ - - {java_awt_event_KeyEvent_VK_COMPOSE, XK_Multi_key, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_ALT_GRAPH, XK_Mode_switch, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Editing block */ - {java_awt_event_KeyEvent_VK_AGAIN, XK_Redo, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_AGAIN, XK_L2, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_UNDO, XK_Undo, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_UNDO, XK_L4, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_COPY, XK_L6, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PASTE, XK_L8, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CUT, XK_L10, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_FIND, XK_Find, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_FIND, XK_L9, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PROPS, XK_L3, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_STOP, XK_L1, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Sun vendor-specific versions for editing block */ - {java_awt_event_KeyEvent_VK_AGAIN, SunXK_Again, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_UNDO, SunXK_Undo, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_COPY, SunXK_Copy, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PASTE, SunXK_Paste, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CUT, SunXK_Cut, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_FIND, SunXK_Find, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PROPS, SunXK_Props, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_STOP, SunXK_Stop, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Apollo (HP) vendor-specific versions for editing block */ - {java_awt_event_KeyEvent_VK_COPY, apXK_Copy, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CUT, apXK_Cut, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PASTE, apXK_Paste, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Other vendor-specific versions for editing block */ - {java_awt_event_KeyEvent_VK_COPY, osfXK_Copy, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_CUT, osfXK_Cut, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_PASTE, osfXK_Paste, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_UNDO, osfXK_Undo, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Dead key mappings (for European keyboards) */ - {java_awt_event_KeyEvent_VK_DEAD_GRAVE, XK_dead_grave, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_ACUTE, XK_dead_acute, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_CIRCUMFLEX, XK_dead_circumflex, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_TILDE, XK_dead_tilde, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_MACRON, XK_dead_macron, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_BREVE, XK_dead_breve, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_ABOVEDOT, XK_dead_abovedot, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_DIAERESIS, XK_dead_diaeresis, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_ABOVERING, XK_dead_abovering, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_DOUBLEACUTE, XK_dead_doubleacute, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_CARON, XK_dead_caron, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_CEDILLA, XK_dead_cedilla, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_OGONEK, XK_dead_ogonek, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_IOTA, XK_dead_iota, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_VOICED_SOUND, XK_dead_voiced_sound, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_SEMIVOICED_SOUND, XK_dead_semivoiced_sound, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Sun vendor-specific dead key mappings (for European keyboards) */ - {java_awt_event_KeyEvent_VK_DEAD_GRAVE, SunXK_FA_Grave, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_CIRCUMFLEX, SunXK_FA_Circum, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_TILDE, SunXK_FA_Tilde, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_ACUTE, SunXK_FA_Acute, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_DIAERESIS, SunXK_FA_Diaeresis, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_CEDILLA, SunXK_FA_Cedilla, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* DEC vendor-specific dead key mappings (for European keyboards) */ - {java_awt_event_KeyEvent_VK_DEAD_ABOVERING, DXK_ring_accent, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_CIRCUMFLEX, DXK_circumflex_accent, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_CEDILLA, DXK_cedilla_accent, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_ACUTE, DXK_acute_accent, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_GRAVE, DXK_grave_accent, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_TILDE, DXK_tilde, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_DIAERESIS, DXK_diaeresis, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - /* Other vendor-specific dead key mappings (for European keyboards) */ - {java_awt_event_KeyEvent_VK_DEAD_ACUTE, hpXK_mute_acute, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_GRAVE, hpXK_mute_grave, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_CIRCUMFLEX, hpXK_mute_asciicircum, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_DIAERESIS, hpXK_mute_diaeresis, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - {java_awt_event_KeyEvent_VK_DEAD_TILDE, hpXK_mute_asciitilde, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_STANDARD}, - - {java_awt_event_KeyEvent_VK_UNDEFINED, NoSymbol, FALSE, java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN} -}; - -static Boolean -keyboardHasKanaLockKey() -{ - static Boolean haveResult = FALSE; - static Boolean result = FALSE; - - int32_t minKeyCode, maxKeyCode, keySymsPerKeyCode; - KeySym *keySyms, *keySymsStart, keySym; - int32_t i; - int32_t kanaCount = 0; - - // Solaris doesn't let you swap keyboards without rebooting, - // so there's no need to check for the kana lock key more than once. - if (haveResult) { - return result; - } - - // There's no direct way to determine whether the keyboard has - // a kana lock key. From available keyboard mapping tables, it looks - // like only keyboards with the kana lock key can produce keysyms - // for kana characters. So, as an indirect test, we check for those. - - XDisplayKeycodes(awt_display, &minKeyCode, &maxKeyCode); - keySyms = XGetKeyboardMapping(awt_display, minKeyCode, maxKeyCode - minKeyCode + 1, &keySymsPerKeyCode); - keySymsStart = keySyms; - for (i = 0; i < (maxKeyCode - minKeyCode + 1) * keySymsPerKeyCode; i++) { - keySym = *keySyms++; - if ((keySym & 0xff00) == 0x0400) { - kanaCount++; - } - } - XFree(keySymsStart); - - // use a (somewhat arbitrary) minimum so we don't get confused by a stray function key - result = kanaCount > 10; - haveResult = TRUE; - return result; -} - -void -keysymToAWTKeyCode(KeySym x11Key, jint *keycode, Boolean *mapsToUnicodeChar, - jint *keyLocation) -{ - int32_t i; - - // Solaris uses XK_Mode_switch for both the non-locking AltGraph - // and the locking Kana key, but we want to keep them separate for - // KeyEvent. - if (x11Key == XK_Mode_switch && keyboardHasKanaLockKey()) { - *keycode = java_awt_event_KeyEvent_VK_KANA_LOCK; - *mapsToUnicodeChar = FALSE; - *keyLocation = java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN; - return; - } - - for (i = 0; - keymapTable[i].awtKey != java_awt_event_KeyEvent_VK_UNDEFINED; - i++) { - if (keymapTable[i].x11Key == x11Key) { - *keycode = keymapTable[i].awtKey; - *mapsToUnicodeChar = keymapTable[i].mapsToUnicodeChar; - *keyLocation = keymapTable[i].keyLocation; - return; - } - } - - *keycode = java_awt_event_KeyEvent_VK_UNDEFINED; - *mapsToUnicodeChar = FALSE; - *keyLocation = java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN; - - DTRACE_PRINTLN1("keysymToAWTKeyCode: no key mapping found: keysym = %x", x11Key); -} - -KeySym -awt_getX11KeySym(jint awtKey) -{ - int32_t i; - - if (awtKey == java_awt_event_KeyEvent_VK_KANA_LOCK && keyboardHasKanaLockKey()) { - return XK_Mode_switch; - } - - for (i = 0; keymapTable[i].awtKey != 0; i++) { - if (keymapTable[i].awtKey == awtKey) { - return keymapTable[i].x11Key; - } - } - - DTRACE_PRINTLN1("awt_getX11KeySym: no key mapping found: awtKey = %x", awtKey); - return NoSymbol; -} - - -typedef struct COLLAPSE_INFO { - Window win; - DamageRect *r; -} CollapseInfo; - -static void -expandDamageRect(DamageRect * drect, XEvent * xev, Boolean debug, char *str) -{ - int32_t x1 = xev->xexpose.x; - int32_t y1 = xev->xexpose.y; - int32_t x2 = x1 + xev->xexpose.width; - int32_t y2 = y1 + xev->xexpose.height; - - /* - if (debug) { - printf(" %s: collapsing (%d,%d %dx%d) into (%d,%d %dx%d) ->>", - str, x1, y1, xev->xexpose.width, xev->xexpose.height, - drect->x1, drect->y1, drect->x2 - drect->x1, drect->y2 - drect->y1); - } - */ - - drect->x1 = MIN(x1, drect->x1); - drect->y1 = MIN(y1, drect->y1); - drect->x2 = MAX(x2, drect->x2); - drect->y2 = MAX(y2, drect->y2); - - /* - if (debug) { - printf("(%d,%d %dx%d) %s\n", - drect->x1, drect->y1, drect->x2 - drect->x1, drect->y2 - drect->y1); - } - */ - -} - -static Bool -checkForExpose(Display * dpy, XEvent * evt, XPointer client_data) -{ - CollapseInfo *cinfo = (CollapseInfo *) client_data; - - if ((evt->type == Expose && evt->xexpose.window == cinfo->win && - INTERSECTS(cinfo->r->x1, cinfo->r->x2, cinfo->r->y1, cinfo->r->y2, - evt->xexpose.x, - evt->xexpose.x + evt->xexpose.width, - evt->xexpose.y, - evt->xexpose.y + evt->xexpose.height)) || - (evt->type == GraphicsExpose && evt->xgraphicsexpose.drawable == cinfo->win && - INTERSECTS(cinfo->r->x1, cinfo->r->x2, cinfo->r->y1, cinfo->r->y2, - evt->xgraphicsexpose.x, - evt->xgraphicsexpose.x + evt->xgraphicsexpose.width, - evt->xgraphicsexpose.y, - evt->xgraphicsexpose.y + evt->xgraphicsexpose.height))) { - - return True; - } - return False; -} - -/* - * javaObject is an MComponentPeer instance - */ -static void -HandleExposeEvent(Widget w, jobject javaObject, XEvent * event) -{ - jobject target; - jint wdth, hght; - - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - switch (event->type) { - case Expose: - case GraphicsExpose: - { - struct ComponentData *cdata; - Boolean debug = FALSE; - jint drawState; - - /* Set the draw state */ - drawState = (*env)->GetIntField(env, javaObject, - mComponentPeerIDs.drawState); - (*env)->SetIntField(env, javaObject, mComponentPeerIDs.drawState, - drawState | JAWT_LOCK_CLIP_CHANGED); - cdata = (struct ComponentData *) - JNU_GetLongFieldAsPtr(env, javaObject, mComponentPeerIDs.pData); - if (JNU_IsNull(env, javaObject) || (cdata == NULL)) { - return; - } - if (event->xexpose.send_event) { - if (cdata->repaintPending & RepaintPending_REPAINT) { - cdata->repaintPending &= ~RepaintPending_REPAINT; - - JNU_CallMethodByName(env, - NULL, - javaObject, - "handleRepaint", - "(IIII)V", - (jint) cdata->repaintRect.x1, - (jint) cdata->repaintRect.y1, - (jint) cdata->repaintRect.x2 - - cdata->repaintRect.x1, - (jint) cdata->repaintRect.y2 - - cdata->repaintRect.y1); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - return; - } - if ((cdata->repaintPending & RepaintPending_EXPOSE) == 0) { - cdata->exposeRect.x1 = event->xexpose.x; - cdata->exposeRect.y1 = event->xexpose.y; - cdata->exposeRect.x2 = cdata->exposeRect.x1 + event->xexpose.width; - cdata->exposeRect.y2 = cdata->exposeRect.y1 + event->xexpose.height; - cdata->repaintPending |= RepaintPending_EXPOSE; - } else { - expandDamageRect(&(cdata->exposeRect), event, debug, "1"); - } - - /* Only post Expose/Repaint if we know others arn't following - * directly in the queue. - */ - if (event->xexpose.count == 0) { - int32_t count = 0; - CollapseInfo cinfo; - - cinfo.win = XtWindow(w); - cinfo.r = &(cdata->exposeRect); - - /* Do a little more inspecting and collapse further if there - * are additional expose events pending on this window where - * the damage rects intersect with the current exposeRect. - */ - while (TRUE) { - XEvent xev; - - if (XCheckIfEvent(XtDisplay(w), &xev - ,checkForExpose, (XtPointer) & cinfo)) { - count = xev.xexpose.count; - expandDamageRect(&(cdata->exposeRect), &xev, debug, "2"); - - } else { - /* XCheckIfEvent Failed. */ - break; - } - } - - cdata->repaintPending &= ~RepaintPending_EXPOSE; - - /* Fix for bugtraq id 4262108. Paint events should not be - * delivered to components that have one of their - * dimensions equal to zero. - */ - - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - return; - } - - target = (*env)->GetObjectField(env, javaObject, - mComponentPeerIDs.target); - wdth = (*env)->GetIntField(env, target, componentIDs.width); - hght = (*env)->GetIntField(env, target, componentIDs.height); - (*env)->DeleteLocalRef(env, target); - - if ( wdth != 0 && hght != 0) { - JNU_CallMethodByName(env, - NULL, - javaObject, - "handleExpose", - "(IIII)V", - (jint) cdata->exposeRect.x1, - (jint) cdata->exposeRect.y1, - (jint) cdata->exposeRect.x2 - - cdata->exposeRect.x1, - (jint) cdata->exposeRect.y2 - - cdata->exposeRect.y1); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - } - } - } - break; - - default: - jio_fprintf(stderr, "Got event %d in HandleExposeEvent!\n", event->type); - } -} - -/* We always store and return JNI GlobalRefs. */ -static jweak focusOwnerPeer = NULL; -static jweak focusedWindowPeer = NULL; - -/* - * This function should only be called under the - * protection of AWT_LOCK(). Otherwise, multithreaded access - * can corrupt the value of focusOwnerPeer variable. - * This function returns LocalRef, result should be deleted - * explicitly if called on a thread that never returns to - * Java. - */ -jobject -awt_canvas_getFocusOwnerPeer() { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject res; - AWT_LOCK(); - res = (*env)->NewLocalRef(env, focusOwnerPeer); - AWT_UNLOCK(); - return res; -} - -/* - * This function should only be called under the - * protection of AWT_LOCK(). Otherwise, multithreaded access - * can corrupt the value of focusedWindowPeer variable. - * This function returns LocalRef, result should be deleted - * explicitly if called on a thread that never returns to - * Java. - */ -jobject -awt_canvas_getFocusedWindowPeer() { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject res; - AWT_LOCK(); - res = (*env)->NewLocalRef(env, focusedWindowPeer); - AWT_UNLOCK(); - return res; -} - -/* - * Only call this function under AWT_LOCK(). Otherwise, multithreaded - * access can corrupt the value of focusOwnerPeer variable. - */ -void -awt_canvas_setFocusOwnerPeer(jobject peer) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - AWT_LOCK(); - if (focusOwnerPeer != NULL) { - (*env)->DeleteWeakGlobalRef(env, focusOwnerPeer); - } - focusOwnerPeer = (peer != NULL) - ? (*env)->NewWeakGlobalRef(env, peer) : NULL; - AWT_UNLOCK(); -} - -/* - * Only call this function under AWT_LOCK(). Otherwise, multithreaded - * access can corrupt the value of focusedWindowPeer variable. - */ -void -awt_canvas_setFocusedWindowPeer(jobject peer) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - AWT_LOCK(); - if (focusedWindowPeer != NULL) { - (*env)->DeleteWeakGlobalRef(env, focusedWindowPeer); - } - focusedWindowPeer = (peer != NULL) - ? (*env)->NewWeakGlobalRef(env, peer) : NULL; - AWT_UNLOCK(); -} - -void callFocusCallback(jobject focusPeer, int focus_type, jobject cause) { - awt_post_java_focus_event(focusPeer, - focus_type, - cause, - NULL); - awt_canvas_setFocusOwnerPeer(focusPeer); -} - - -void -handleFocusEvent(Widget w, - XFocusChangeEvent * fevent, - XtPointer client_data, - Boolean * cont, - Boolean passEvent, - jobject cause) -{ - if (fevent->type == FocusIn) { - if (fevent->mode == NotifyNormal && - fevent->detail != NotifyPointer && fevent->detail != NotifyVirtual) - { -#ifdef DEBUG_FOCUS - printf("window = %d, mode = %d, detail = %d\n", fevent->window, fevent->mode, fevent->detail); - printf("----posting java FOCUS GAINED on window %d, pass = %d\n", XtWindow(w), passEvent); -#endif - awt_post_java_focus_event(client_data, - java_awt_event_FocusEvent_FOCUS_GAINED, - cause, - NULL); - awt_canvas_setFocusOwnerPeer(client_data); - } - } else { - /* FocusOut */ - if (fevent->mode == NotifyNormal && - fevent->detail != NotifyPointer && fevent->detail != NotifyVirtual) - { -#ifdef DEBUG_FOCUS - printf("window = %d, mode = %d, detail = %d\n", fevent->window, fevent->mode, fevent->detail); - printf("----posting java FOCUS LOST on window %d, pass = %d, temp = %d\n", XtWindow(w), passEvent, temp); -#endif - awt_post_java_focus_event(client_data, - java_awt_event_FocusEvent_FOCUS_LOST, - cause, - NULL); - awt_canvas_setFocusOwnerPeer(NULL); - } - } - *cont = TRUE; -} - -void callFocusHandler(Widget w, int eventType, jobject cause) { - jobject peer = NULL; - XFocusChangeEvent event; - Boolean cont; - JNIEnv *env = (JNIEnv *) JNU_GetEnv(jvm, JNI_VERSION_1_2); - - if (w == NULL) { - return; - } - - peer = findPeer(&w); - if (peer == NULL) { - w = findTopLevelByShell(w); - if (w != NULL) { - peer = findPeer(&w); - } - } - if (peer == NULL) { - return; - } - memset(&event, 0, sizeof(event)); - event.type = eventType; - event.mode = NotifyNormal; - event.detail = NotifyAncestor; - event.window = XtWindow(w); - cont = FALSE; - handleFocusEvent(w, &event, (XtPointer)peer, &cont, TRUE, cause); -} - -/** - * Copy XEvent to jbyteArray and save it in AWTEvent - */ -void -awt_copyXEventToAWTEvent(JNIEnv *env, XEvent * xev, jobject jevent) -{ - jbyteArray bdata; - if (xev != NULL) { - if ((*env)->EnsureLocalCapacity(env, 1) < 0) { - return; - } - bdata = (*env)->NewByteArray(env, sizeof(XEvent)); - if (bdata != NULL) { - (*env)->SetByteArrayRegion(env, bdata, 0, sizeof(XEvent), - (jbyte *)xev); - (*env)->SetObjectField(env, jevent, awtEventIDs.bdata, bdata); - (*env)->DeleteLocalRef(env, bdata); - } - } -} - -/* Returns new modifiers set like ???_DOWN_MASK for keyboard and mouse after the event. - * The modifiers on a Java key event reflect the state of the modifier keys - * immediately AFTER the key press or release. This usually doesn't require - * us to change the modifiers: the exception is when the key pressed or - * released is a modifier key. Since the state of an XEvent represents - * the modifiers BEFORE the event, we change the modifiers according to - * the button and keycode. - */ -jint -getModifiers(uint32_t state, jint button, jint keyCode) -{ - jint modifiers = 0; - - if (((state & ShiftMask) != 0) ^ (keyCode == java_awt_event_KeyEvent_VK_SHIFT)) - { - modifiers |= java_awt_event_InputEvent_SHIFT_DOWN_MASK; - } - if (((state & ControlMask) != 0) ^ (keyCode == java_awt_event_KeyEvent_VK_CONTROL)) - { - modifiers |= java_awt_event_InputEvent_CTRL_DOWN_MASK; - } - if (((state & awt_MetaMask) != 0) ^ (keyCode == java_awt_event_KeyEvent_VK_META)) - { - modifiers |= java_awt_event_InputEvent_META_DOWN_MASK; - } - if (((state & awt_AltMask) != 0) ^ (keyCode == java_awt_event_KeyEvent_VK_ALT)) - { - modifiers |= java_awt_event_InputEvent_ALT_DOWN_MASK; - } - if (((state & awt_ModeSwitchMask) != 0) ^ (keyCode == java_awt_event_KeyEvent_VK_ALT_GRAPH)) - { - modifiers |= java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK; - } - if (((state & Button1Mask) != 0) ^ (button == java_awt_event_MouseEvent_BUTTON1)) { - modifiers |= java_awt_event_InputEvent_BUTTON1_DOWN_MASK; - } - if (((state & Button2Mask) != 0) ^ (button == java_awt_event_MouseEvent_BUTTON2)) { - modifiers |= java_awt_event_InputEvent_BUTTON2_DOWN_MASK; - } - if (((state & Button3Mask) != 0) ^ (button == java_awt_event_MouseEvent_BUTTON3)) { - modifiers |= java_awt_event_InputEvent_BUTTON3_DOWN_MASK; - } - return modifiers; -} - -/* Returns which mouse button has changed state - */ -jint -getButton(uint32_t button) -{ - switch (button) { - case Button1: - return java_awt_event_MouseEvent_BUTTON1; - case Button2: - return java_awt_event_MouseEvent_BUTTON2; - case Button3: - return java_awt_event_MouseEvent_BUTTON3; - } - return java_awt_event_MouseEvent_NOBUTTON; -} - - -/* This function changes the state of the native XEvent AFTER - * the corresponding Java event has been processed. The XEvent - * needs to be modified before it is dispatched to the native widget. - */ -void -awt_modify_KeyEvent(JNIEnv *env, XEvent *xevent, jobject jevent) -{ - jint keyCode; - jchar keyChar; - jint modifiers; - KeySym keysym = (KeySym) java_awt_event_KeyEvent_CHAR_UNDEFINED; - - if (xevent->type != KeyPress && xevent->type != KeyRelease) { - return; - } - - keyCode = (*env)->GetIntField(env, jevent, keyEventIDs.keyCode); - keyChar = (*env)->GetCharField(env, jevent, keyEventIDs.keyChar); - modifiers = (*env)->GetIntField(env, jevent, inputEventIDs.modifiers); - - switch (keyCode) { - case java_awt_event_KeyEvent_VK_MULTIPLY: - case java_awt_event_KeyEvent_VK_SUBTRACT: - case java_awt_event_KeyEvent_VK_DIVIDE: - /* Bugid 4103229: Change the X event so these three Numpad - * keys work with the NumLock off. For some reason, Motif - * widgets ignore the events produced by these three keys - * unless the NumLock is on. It also ignores them if some - * other modifiers are set. Turn off ALL modifiers, then - * turn NumLock mask on in the X event. - */ - xevent->xkey.state = awt_NumLockMask; - return; - case java_awt_event_KeyEvent_VK_ENTER: - case java_awt_event_KeyEvent_VK_BACK_SPACE: - case java_awt_event_KeyEvent_VK_TAB: - case java_awt_event_KeyEvent_VK_ESCAPE: - case java_awt_event_KeyEvent_VK_ADD: - case java_awt_event_KeyEvent_VK_DECIMAL: - case java_awt_event_KeyEvent_VK_NUMPAD0: - case java_awt_event_KeyEvent_VK_NUMPAD1: - case java_awt_event_KeyEvent_VK_NUMPAD2: - case java_awt_event_KeyEvent_VK_NUMPAD3: - case java_awt_event_KeyEvent_VK_NUMPAD4: - case java_awt_event_KeyEvent_VK_NUMPAD5: - case java_awt_event_KeyEvent_VK_NUMPAD6: - case java_awt_event_KeyEvent_VK_NUMPAD7: - case java_awt_event_KeyEvent_VK_NUMPAD8: - case java_awt_event_KeyEvent_VK_NUMPAD9: - keysym = awt_getX11KeySym(keyCode); - break; - case java_awt_event_KeyEvent_VK_DELETE: - /* For some reason XKeysymToKeycode returns incorrect value for - * Delete, so we don't want to modify the original event - */ - break; - default: - if (keyChar < (KeySym) 256) { - keysym = (KeySym) keyChar; - } else { - keysym = awt_getX11KeySym(keyCode); - } - break; - } - - if (keysym < (KeySym) 256) { - if (modifiers & java_awt_event_InputEvent_CTRL_MASK) { - switch (keysym + 64) { - case '[': - case ']': - case '\\': - case '_': - keysym += 64; - break; - default: - if (isalpha((int32_t)(keysym + 'a' - 1))) { - keysym += ('a' - 1); - } - break; - } - } - /* - * 0xff61 is Unicode value of first XK_kana_fullstop. - * We need X Keysym to Unicode map in post1.1 release - * to support more international keyboards. - */ - if (keysym >= (KeySym) 0xff61 && keysym <= (KeySym) 0xff9f) { - keysym = keysym - 0xff61 + XK_kana_fullstop; - } - xevent->xkey.keycode = XKeysymToKeycode(awt_display, keysym); - } - - if (keysym >= 'A' && keysym <= 'Z') { - xevent->xkey.state |= ShiftMask; - } - if (modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK) { - xevent->xkey.state |= ShiftMask; - } - if (modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK) { - xevent->xkey.state |= ControlMask; - } - if (modifiers & java_awt_event_InputEvent_META_DOWN_MASK) { - xevent->xkey.state |= awt_MetaMask; - } - if (modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK) { - xevent->xkey.state |= awt_AltMask; - } - if (modifiers & java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK) { - xevent->xkey.state |= awt_ModeSwitchMask; - } - if (modifiers & java_awt_event_InputEvent_BUTTON1_DOWN_MASK) { - xevent->xkey.state |= Button1Mask; - } - if (modifiers & java_awt_event_InputEvent_BUTTON2_DOWN_MASK) { - xevent->xkey.state |= Button2Mask; - } - if (modifiers & java_awt_event_InputEvent_BUTTON3_DOWN_MASK) { - xevent->xkey.state |= Button3Mask; - } -} - - -/* Called from handleKeyEvent. The purpose of this function is - * to check for a list of vendor-specific keysyms, most of which - * have values greater than 0xFFFF. Most of these keys don't map - * to unicode characters, but some do. - * - * For keys that don't map to unicode characters, the keysym - * is irrelevant at this point. We set the keysym to zero - * to ensure that the switch statement immediately below - * this function call (in adjustKeySym) won't incorrectly act - * on them after the high bits are stripped off. - * - * For keys that do map to unicode characters, we change the keysym - * to the equivalent that is < 0xFFFF - */ -static void -handleVendorKeySyms(XEvent *event, KeySym *keysym) -{ - KeySym originalKeysym = *keysym; - - switch (*keysym) { - /* Apollo (HP) vendor-specific from */ - case apXK_Copy: - case apXK_Cut: - case apXK_Paste: - /* DEC vendor-specific from */ - case DXK_ring_accent: /* syn usldead_ring */ - case DXK_circumflex_accent: - case DXK_cedilla_accent: /* syn usldead_cedilla */ - case DXK_acute_accent: - case DXK_grave_accent: - case DXK_tilde: - case DXK_diaeresis: - /* Sun vendor-specific from */ - case SunXK_FA_Grave: - case SunXK_FA_Circum: - case SunXK_FA_Tilde: - case SunXK_FA_Acute: - case SunXK_FA_Diaeresis: - case SunXK_FA_Cedilla: - case SunXK_F36: /* Labeled F11 */ - case SunXK_F37: /* Labeled F12 */ - case SunXK_Props: - case SunXK_Copy: - case SunXK_Open: - case SunXK_Paste: - case SunXK_Cut: - /* Other vendor-specific from HPkeysym.h */ - case hpXK_mute_acute: /* syn usldead_acute */ - case hpXK_mute_grave: /* syn usldead_grave */ - case hpXK_mute_asciicircum: /* syn usldead_asciicircum */ - case hpXK_mute_diaeresis: /* syn usldead_diaeresis */ - case hpXK_mute_asciitilde: /* syn usldead_asciitilde */ - case osfXK_Copy: - case osfXK_Cut: - case osfXK_Paste: - case osfXK_PageUp: - case osfXK_PageDown: - case osfXK_EndLine: - case osfXK_Clear: - case osfXK_Left: - case osfXK_Up: - case osfXK_Right: - case osfXK_Down: - case osfXK_Prior: - case osfXK_Next: - case osfXK_Insert: - case osfXK_Undo: - case osfXK_Help: - *keysym = 0; - break; - /* - * The rest DO map to unicode characters, so translate them - */ - case osfXK_BackSpace: - *keysym = XK_BackSpace; - break; - case osfXK_Escape: - *keysym = XK_Escape; - break; - case osfXK_Cancel: - *keysym = XK_Cancel; - break; - case osfXK_Delete: - *keysym = XK_Delete; - break; - default: - break; - } - - if (originalKeysym != *keysym) { - DTRACE_PRINTLN2("In handleVendorKeySyms: originalKeysym=%x, keysym=%x", - originalKeysym, *keysym); - } -} - -/* Called from handleKeyEvent. - * The purpose of this function is to adjust the keysym and XEvent - * keycode for a key event. This is basically a conglomeration of - * bugfixes that require these adjustments. - */ -static void -adjustKeySym(XEvent *event, KeySym *keysym) -{ - KeySym originalKeysym = *keysym; - - /* We have seen bits set in the high two bytes on Linux, - * which prevents this switch statement from executing - * correctly. Strip off the high order bits. - */ - *keysym &= 0x0000FFFF; - - switch (*keysym) { - case XK_Return: - *keysym = XK_Linefeed; /* fall thru */ - case XK_BackSpace: - case XK_Tab: - case XK_Linefeed: - case XK_Escape: - case XK_Delete: - /* strip off highorder bits defined in keysymdef.h - * I think doing this converts them to values that - * we can cast to jchars and use as java keychars. - * If so, it's really a hack. - */ - *keysym &= 0x007F; - break; - case XK_Cancel: - *keysym = 0x0018; /* the unicode char for Cancel */ - break; - case XK_KP_Decimal: - *keysym = '.'; - break; - case XK_KP_Add: - *keysym = '+'; - break; - case XK_F24: /* NumLock off */ - case XK_KP_Subtract: /* NumLock on */ - *keysym = '-'; - break; - case XK_F25: /* NumLock off */ - case XK_KP_Divide: /* NumLock on */ - *keysym = '/'; - break; - case XK_F26: /* NumLock off */ - case XK_KP_Multiply: /* NumLock on */ - *keysym = '*'; - break; - case XK_KP_Equal: - *keysym = '='; - break; - case XK_KP_0: - *keysym = '0'; - break; - case XK_KP_1: - *keysym = '1'; - break; - case XK_KP_2: - *keysym = '2'; - break; - case XK_KP_3: - *keysym = '3'; - break; - case XK_KP_4: - *keysym = '4'; - break; - case XK_KP_5: - *keysym = '5'; - break; - case XK_KP_6: - *keysym = '6'; - break; - case XK_KP_7: - *keysym = '7'; - break; - case XK_KP_8: - *keysym = '8'; - break; - case XK_KP_9: - *keysym = '9'; - break; - case XK_KP_Left: /* Bug 4350175 */ - *keysym = XK_Left; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Up: - *keysym = XK_Up; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Right: - *keysym = XK_Right; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Down: - *keysym = XK_Down; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Home: - *keysym = XK_Home; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_End: - *keysym = XK_End; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Page_Up: - *keysym = XK_Page_Up; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Page_Down: - *keysym = XK_Page_Down; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Begin: - *keysym = XK_Begin; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Insert: - *keysym = XK_Insert; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - break; - case XK_KP_Delete: - *keysym = XK_Delete; - event->xkey.keycode = XKeysymToKeycode(awt_display, *keysym); - *keysym &= 0x007F; - break; - case XK_KP_Enter: - *keysym = XK_Linefeed; - event->xkey.keycode = XKeysymToKeycode(awt_display, XK_Return); - *keysym &= 0x007F; - break; - default: - break; - } - - if (originalKeysym != *keysym) { - DTRACE_PRINTLN2("In adjustKeySym: originalKeysym=%x, keysym=%x", - originalKeysym, *keysym); - } -} - -/* - * What a sniffer sez? - * Xsun and Xorg if NumLock is on do two thing different: - * keep Keypad key in different places of keysyms array and - * ignore/obey "ModLock is ShiftLock", so we should choose. - * People say, it's right to use behavior and not Vendor tags to decide. - * Maybe. But why these tags were invented, then? - * TODO: use behavior, not tags. Maybe. - */ -static Boolean -isXsunServer(XEvent *event) { - if( awt_ServerDetected ) return awt_IsXsun; - if( strncmp( ServerVendor( event->xkey.display ), "Sun Microsystems, Inc.", 32) ) { - awt_ServerDetected = True; - awt_IsXsun = False; - return False; - } - // Now, it's Sun. It still may be Xorg though, eg on Solaris 10, x86. - // Today (2005), VendorRelease of Xorg is a Big Number unlike Xsun. - if( VendorRelease( event->xkey.display ) > 10000 ) { - awt_ServerDetected = True; - awt_IsXsun = False; - return False; - } - awt_ServerDetected = True; - awt_IsXsun = True; - return True; -} -static Boolean -isKPevent(XEvent *event) -{ - /* - Xlib manual, ch 12.7 says, as a first rule for choice of keysym: - The numlock modifier is on and the second KeySym is a keypad KeySym. In this case, - if the Shift modifier is on, or if the Lock modifier is on and is interpreted as ShiftLock, - then the first KeySym is used, otherwise the second KeySym is used. - - However, Xsun server does ignore ShiftLock and always takes 3-rd element from an array. - - So, is it a keypad keysym? - */ - jint mods = getModifiers(event->xkey.state, 0, event->xkey.keycode); - Boolean bsun = isXsunServer( event ); - - return IsKeypadKey( XKeycodeToKeysym(event->xkey.display, event->xkey.keycode,(bsun && !awt_UseXKB ? 2 : 1) ) ); -} -/* - * In a next redesign, get rid of this code altogether. - * - */ -static void -handleKeyEventWithNumLockMask_New(XEvent *event, KeySym *keysym) -{ - KeySym originalKeysym = *keysym; - if( !isKPevent( event ) ) { - return; - } - if( isXsunServer( event ) && !awt_UseXKB ) { - if( (event->xkey.state & ShiftMask) ) { // shift modifier is on - *keysym = XKeycodeToKeysym(event->xkey.display, - event->xkey.keycode, 3); - }else { - *keysym = XKeycodeToKeysym(event->xkey.display, - event->xkey.keycode, 2); - } - } else { - if( (event->xkey.state & ShiftMask) || // shift modifier is on - ((event->xkey.state & LockMask) && // lock modifier is on - (awt_ModLockIsShiftLock)) ) { // it is interpreted as ShiftLock - *keysym = XKeycodeToKeysym(event->xkey.display, - event->xkey.keycode, 0); - }else{ - *keysym = XKeycodeToKeysym(event->xkey.display, - event->xkey.keycode, 1); - } - } -} - -/* Called from handleKeyEvent. - * The purpose of this function is to make some adjustments to keysyms - * that have been found to be necessary when the NumLock mask is set. - * They come from various bug fixes and rearchitectures. - * This function is meant to be called when - * (event->xkey.state & awt_NumLockMask) is TRUE. - */ -static void -handleKeyEventWithNumLockMask(XEvent *event, KeySym *keysym) -{ - KeySym originalKeysym = *keysym; - -#ifndef __linux__ - /* The following code on Linux will cause the keypad keys - * not to echo on JTextField when the NumLock is on. The - * keysyms will be 0, because the last parameter 2 is not defined. - * See Xlib Programming Manual, O'Reilly & Associates, Section - * 9.1.5 "Other Keyboard-handling Routines", "The meaning of - * the keysym list beyond the first two (unmodified, Shift or - * Shift Lock) is not defined." - */ - - /* Translate again with NumLock as modifier. */ - /* ECH - I wonder why we think that NumLock corresponds to 2? - * On Linux, we've seen xmodmap -pm yield mod2 as NumLock, - * but I don't know that it will be for every configuration. - * Perhaps using the index (modn in awt_MToolkit.c:setup_modifier_map) - * would be more correct. - */ - *keysym = XKeycodeToKeysym(event->xkey.display, - event->xkey.keycode, 2); - if (originalKeysym != *keysym) { - DTRACE_PRINTLN3("%s=%x, keysym=%x", - "In handleKeyEventWithNumLockMask ifndef linux: originalKeysym", - originalKeysym, *keysym); - } -#endif - - /* Note: the XK_R? key assignments are for Type 4 kbds */ - switch (*keysym) { - case XK_R13: - *keysym = XK_KP_1; - break; - case XK_R14: - *keysym = XK_KP_2; - break; - case XK_R15: - *keysym = XK_KP_3; - break; - case XK_R10: - *keysym = XK_KP_4; - break; - case XK_R11: - *keysym = XK_KP_5; - break; - case XK_R12: - *keysym = XK_KP_6; - break; - case XK_R7: - *keysym = XK_KP_7; - break; - case XK_R8: - *keysym = XK_KP_8; - break; - case XK_R9: - *keysym = XK_KP_9; - break; - case XK_KP_Insert: - *keysym = XK_KP_0; - break; - case XK_KP_Delete: - *keysym = XK_KP_Decimal; - break; - case XK_R4: - *keysym = XK_KP_Equal; /* Type 4 kbd */ - break; - case XK_R5: - *keysym = XK_KP_Divide; - break; - case XK_R6: - *keysym = XK_KP_Multiply; - break; - /* - * Need the following keysym changes for Linux key releases. - * Sometimes the modifier state gets messed up, so we get a - * KP_Left when we should get a KP_4, for example. - * XK_KP_Insert and XK_KP_Delete were already handled above. - */ - case XK_KP_Left: - *keysym = XK_KP_4; - break; - case XK_KP_Up: - *keysym = XK_KP_8; - break; - case XK_KP_Right: - *keysym = XK_KP_6; - break; - case XK_KP_Down: - *keysym = XK_KP_2; - break; - case XK_KP_Home: - *keysym = XK_KP_7; - break; - case XK_KP_End: - *keysym = XK_KP_1; - break; - case XK_KP_Page_Up: - *keysym = XK_KP_9; - break; - case XK_KP_Page_Down: - *keysym = XK_KP_3; - break; - case XK_KP_Begin: - *keysym = XK_KP_5; - break; - default: - break; - } - - if (originalKeysym != *keysym) { - DTRACE_PRINTLN2("In handleKeyEventWithNumLockMask: originalKeysym=%x, keysym=%x", - originalKeysym, *keysym); - } -} - -static void -handleKeyEvent(jint keyEventId, - XEvent *event, - XtPointer *client_data, - Boolean *cont, - Boolean passEvent) -{ - KeySym keysym = NoSymbol; - jint keycode = java_awt_event_KeyEvent_VK_UNDEFINED; - Modifiers mods = 0; - Boolean mapsToUnicodeChar = FALSE; - jint keyLocation = java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN; - jint modifiers = 0; - - DTRACE_PRINTLN4("\nEntered handleKeyEvent: type=%d, xkeycode=%x, xstate=%x, keysym=%x", - event->type, event->xkey.keycode, event->xkey.state, keysym); - - if (currentX11InputMethodInstance != NULL - && keyEventId == java_awt_event_KeyEvent_KEY_PRESSED - && event->xkey.window == currentFocusWindow) - { - /* invokes XmbLookupString to get a committed string or keysym if any. */ - if (awt_x11inputmethod_lookupString((XKeyPressedEvent*)event, &keysym)) { - *cont = FALSE; - return; - } - } - - /* Ignore the keysym found immediately above in - * awt_x11inputmethod_lookupString; the methodology in that function - * sometimes returns incorrect results. - * - * Get keysym without taking modifiers into account first. - * This keysym is not necessarily for the character that was typed: - * it is for the primary layer. So, if $ were typed by pressing - * shift-4, this call should give us 4, not $ - * - * We only want this keysym so we can use it to index into the - * keymapTable to get the Java keycode associated with the - * primary layer key that was pressed. - */ - keysym = XKeycodeToKeysym(event->xkey.display, event->xkey.keycode, 0); - - /* Linux: Sometimes the keysym returned is uppercase when CapsLock is - * on and LockMask is not set in event->xkey.state. - */ - if (keysym >= (KeySym) 'A' && keysym <= (KeySym) 'Z') { - event->xkey.state |= LockMask; - keysym = (KeySym) tolower((int32_t) keysym); - } - - DTRACE_PRINTLN4("In handleKeyEvent: type=%d, xkeycode=%x, xstate=%x, keysym=%x", - event->type, event->xkey.keycode, event->xkey.state, keysym); - - if (keysym == NoSymbol) { - *cont = TRUE; - return; - } - - if (keysym < (KeySym) 256) { - keysymToAWTKeyCode(keysym, &keycode, &mapsToUnicodeChar, &keyLocation); - - /* Now get real keysym which looks at modifiers - * XtGetActionKeySym() returns wrong value with Kana Lock, - * so use XtTranslateKeycode(). - */ - XtTranslateKeycode(event->xkey.display, (KeyCode) event->xkey.keycode, - event->xkey.state, &mods, &keysym); - DTRACE_PRINTLN6("%s: type=%d, xkeycode=%x, xstate=%x, keysym=%x, xmods=%d", - "In handleKeyEvent keysym<256 ", event->type, event->xkey.keycode, - event->xkey.state, keysym, mods); - - /* Linux: With caps lock on, chars echo lowercase. */ - if ((event->xkey.state & LockMask) && - (keysym >= (KeySym) 'a' && keysym <= (KeySym) 'z')) - { - keysym = (KeySym) toupper((int32_t) keysym); - } - - if ((event->xkey.state & ControlMask)) { - switch (keysym) { - case '[': - case ']': - case '\\': - case '_': - keysym -= 64; - break; - default: - if (isalpha((int32_t) keysym)) { - keysym = (KeySym) tolower((int32_t) keysym) - 'a' + 1; - } - break; - } - } - - if (keysym >= (KeySym) XK_kana_fullstop && - keysym <= (KeySym) XK_semivoicedsound) { - /* - * 0xff61 is Unicode value of first XK_kana_fullstop. - * We need X Keysym to Unicode map in post1.1 release - * to support more intenational keyboard. - */ - keysym = keysym - XK_kana_fullstop + 0xff61; - } - - modifiers = getModifiers(event->xkey.state, 0, keycode); - DTRACE_PRINTLN6("%s: type=%d, xkeycode=%x, xstate=%x, keysym=%x, AWTmodifiers=%d", - "In handleKeyEvent keysym<256 ", event->type, event->xkey.keycode, - event->xkey.state, keysym, modifiers); - - awt_post_java_key_event(client_data, - keyEventId, - (passEvent == TRUE) ? event : NULL, - event->xkey.time, - keycode, - (jchar) keysym, - modifiers, - keyLocation, - event); - - if (keyEventId == java_awt_event_KeyEvent_KEY_PRESSED) { - awt_post_java_key_event(client_data, - java_awt_event_KeyEvent_KEY_TYPED, - NULL, - event->xkey.time, - java_awt_event_KeyEvent_VK_UNDEFINED, - (jchar) keysym, - modifiers, - java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, - event); - - } - } else { - if (event->xkey.state & awt_NumLockMask) { - if( awt_UseType4Patch ) { - handleKeyEventWithNumLockMask(event, &keysym); - }else{ - handleKeyEventWithNumLockMask_New(event, &keysym); - } - } - - if (keysym == XK_ISO_Left_Tab) { - keysym = XK_Tab; - } - - /* The keysym here does not consider modifiers, so these results - * are relevant to the KEY_PRESSED event only, not the KEY_TYPED - */ - keysymToAWTKeyCode(keysym, &keycode, &mapsToUnicodeChar, &keyLocation); - DTRACE_PRINTLN3("In handleKeyEvent: keysym=%x, AWTkeycode=%x, mapsToUnicodeChar=%d", - keysym, keycode, mapsToUnicodeChar); - - if (keycode == java_awt_event_KeyEvent_VK_UNDEFINED) { - *cont = TRUE; - return; - } - - /* Need to take care of keysyms > 0xFFFF here - * Most of these keys don't map to unicode characters, but some do. - * - * For keys that don't map to unicode characters, the keysym - * is irrelevant at this point. We set the keysym to zero - * to ensure that the switch statement immediately below - * this function call (in adjustKeySym) won't incorrectly act - * on them after the high bits are stripped off. - * - * For keys that do map to unicode characters, we change the keysym - * to the equivalent that is < 0xFFFF - */ - handleVendorKeySyms(event, &keysym); - - /* This function is a conglomeration of bug fixes that adjust - * the keysym and XEvent keycode for this key event. - */ - adjustKeySym(event, &keysym); - - modifiers = getModifiers(event->xkey.state, 0, keycode); - - DTRACE_PRINTLN6("%s: type=%d, xkeycode=%x, xstate=%x, keysym=%x, xmods=%d", - "In handleKeyEvent keysym>=256 ", event->type, event->xkey.keycode, - event->xkey.state, keysym, mods); - DTRACE_PRINTLN2(" AWTkeycode=%x, AWTmodifiers=%d", - keycode, modifiers); - - awt_post_java_key_event(client_data, - keyEventId, - (passEvent == TRUE) ? event : NULL, - event->xkey.time, - keycode, - (jchar) (mapsToUnicodeChar ? keysym : - java_awt_event_KeyEvent_CHAR_UNDEFINED), - modifiers, - keyLocation, - event); - - /* If this was a keyPressed event, we may need to post a - * keyTyped event, too. Otherwise, return. - */ - if (keyEventId == java_awt_event_KeyEvent_KEY_RELEASED) { - return; - } - DTRACE_PRINTLN("This is a keyPressed event"); - - /* XtTranslateKeycode seems to return slightly bogus values for the - * Escape key (keysym==1004ff69==osfXK_Cancel, xmods=2) on Solaris, - * so we just create the KEY_TYPED as a special case for Escape here. - * (Linux works fine, and this was also okay running under VNC.) - */ - if (keycode == java_awt_event_KeyEvent_VK_ESCAPE) { - awt_post_java_key_event(client_data, - java_awt_event_KeyEvent_KEY_TYPED, - NULL, - event->xkey.time, - java_awt_event_KeyEvent_VK_UNDEFINED, - (jchar) keysym, - modifiers, - java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, - event); - - DTRACE_PRINTLN("Posted a keyTyped event for VK_ESCAPE"); - return; - } - - /* Now get real keysym which looks at modifiers for keyTyped event. - * XtGetActionKeySym() returns wrong value with Kana Lock, - * so use XtTranslateKeycode(). - */ - XtTranslateKeycode(event->xkey.display, (KeyCode) event->xkey.keycode, - event->xkey.state, &mods, &keysym); - DTRACE_PRINTLN6("%s: type=%d, xkeycode=%x, xstate=%x, keysym=%x, xmods=%d", - "In handleKeyEvent keysym>=256 ", event->type, event->xkey.keycode, - event->xkey.state, keysym, mods); - - if (keysym == NoSymbol) { - return; - } - - if (event->xkey.state & awt_NumLockMask) { - if( awt_UseType4Patch ) { - handleKeyEventWithNumLockMask(event, &keysym); - }else{ - handleKeyEventWithNumLockMask_New(event, &keysym); - } - } - - if (keysym == XK_ISO_Left_Tab) { - keysym = XK_Tab; - } - - /* Map the real keysym to a Java keycode */ - keysymToAWTKeyCode(keysym, &keycode, &mapsToUnicodeChar, &keyLocation); - DTRACE_PRINTLN3("In handleKeyEvent: keysym=%x, AWTkeycode=%x, mapsToUnicodeChar=%d", - keysym, keycode, mapsToUnicodeChar); - - /* If it doesn't map to a Unicode character, don't post a keyTyped event */ - if (!mapsToUnicodeChar) { - return; - } - - handleVendorKeySyms(event, &keysym); - adjustKeySym(event, &keysym); - DTRACE_PRINT4("In handleKeyEvent: type=%d, xkeycode=%x, xstate=%x, keysym=%x", - event->type, event->xkey.keycode, event->xkey.state, keysym); - DTRACE_PRINTLN2(", AWTkeycode=%x, AWTmodifiers=%d", keycode, modifiers); - - awt_post_java_key_event(client_data, - java_awt_event_KeyEvent_KEY_TYPED, - NULL, - event->xkey.time, - java_awt_event_KeyEvent_VK_UNDEFINED, - (jchar) keysym, - modifiers, - java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, - event); - } -} - - -static void -translateXY(Widget w, jint *xp, jint *yp) -{ - Position wx, wy; - - XtVaGetValues(w, XmNx, &wx, XmNy, &wy, NULL); - *xp += wx; - *yp += wy; -} - - -/* - * Part fix for bug id 4017222. Return the root widget of the Widget parameter. - */ -Widget -getRootWidget(Widget w) { - if(!w) return NULL; - - if(XtParent(w)) - return getRootWidget(XtParent(w)); - else - return w; -} - -#define ABS(x) ((x) < 0 ? -(x) : (x)) - -/* This proc is the major AWT engine for processing X events - * for Java components and is the proc responsible for taking - * X events and posting their corresponding Java event to the - * AWT EventQueue. It is set up to be called both from an Xt - * event handler and directly from MToolkit.c:shouldDispatchToWidget(). - * For the latter case, the "passEvent" parameter will be true, - * which means that the event is being posted on the Java queue - * BEFORE it is being passed to Xt and so a copy of the X event - * must be stored within the Java event structure so it can be - * dispatched to Xt later on. - */ -void -awt_canvas_handleEvent(Widget w, XtPointer client_data, - XEvent * event, struct WidgetInfo *winfo, - Boolean * cont, Boolean passEvent) -{ - static jint clickCount = 1; - static XtPointer lastPeer = NULL; - static Time lastTime = 0; - static jint lastx = 0; - static jint lasty = 0; - static int32_t rbutton = 0; - static int32_t lastButton = 0; - Boolean popupTrigger; - jint x, y; - jint modifiers = 0; - jint button = java_awt_event_MouseEvent_NOBUTTON; - uint32_t fullRelease = 0; - WidgetClass wclass = NULL; - - /* Any event handlers which take peer instance pointers as - * client_data should check to ensure the widget has not been - * marked as destroyed as a result of a dispose() call on the peer - * (which can result in the peer instance pointer already haven - * been gc'd by the time this event is processed) - */ - if (w->core.being_destroyed) { - return; - } - *cont = FALSE; - - switch (event->type) { - case SelectionClear: - case SelectionNotify: - case SelectionRequest: - *cont = TRUE; - break; - case GraphicsExpose: - case Expose: - HandleExposeEvent(w, (jobject) client_data, event); - break; - case FocusIn: - case FocusOut: - *cont = TRUE; - updateCursor(client_data, CACHE_UPDATE); // 4840883 - // We no longer listen to the Motif focus notifications. - // Instead we call focus callbacks in the times we think - // appropriate trying to simulate correct Motif widget system - // behavior. - break; - case ButtonPress: - x = (jint) event->xbutton.x; - y = (jint) event->xbutton.y; - - if (lastPeer == client_data && - lastButton == event->xbutton.button && - (event->xbutton.time - lastTime) <= (Time) awt_multiclick_time) { - clickCount++; - } else { - clickCount = 1; - lastPeer = client_data; - lastButton = event->xbutton.button; - lastx = x; - lasty = y; - } - lastTime = event->xbutton.time; - - /* On MouseEvent.MOUSE_PRESSED, RELEASED and CLICKED only new modifiers and - * modifier for changed mouse button are set. - */ - button = getButton(event->xbutton.button); - modifiers = getModifiers(event->xbutton.state, button, 0); - - - /* If the widget is a subwidget on a component we need to - * translate the x,y into the coordinate space of the component. - */ - if (winfo != NULL && winfo->widget != winfo->origin) { - translateXY(winfo->widget, &x, &y); - } - - if (XtIsSubclass(w, xmScrollBarWidgetClass) && findWidgetInfo(w) != NULL) { - passEvent = FALSE; - *cont = TRUE; - } - - /* Mouse wheel events come in as button 4 (wheel up) and - * button 5 (wheel down). - */ - if (lastButton == 4 || lastButton == 5) { - *cont = FALSE; - awt_post_java_mouse_event(client_data, - java_awt_event_MouseEvent_MOUSE_WHEEL, - (passEvent == TRUE) ? event : NULL, - event->xbutton.time, - modifiers, - x, y, - (jint) (event->xbutton.x_root), - (jint) (event->xbutton.y_root), - clickCount, - False, - lastButton == 4 ? -1 : 1, - java_awt_event_MouseEvent_NOBUTTON); - /* we're done with this event */ - break; - } - - /* (4168006) Find out out how many buttons we have - * If this is a two button system Right == 2 - * If this is a three button system Right == 3 - */ - if ( rbutton == 0 ) { - unsigned char map[5]; - rbutton = XGetPointerMapping ( awt_display, map, 3 ); - } - - if (event->xbutton.button == rbutton || event->xbutton.button > 2) { - popupTrigger = True; - } else { - popupTrigger = False; - } - - awt_post_java_mouse_event(client_data, - java_awt_event_MouseEvent_MOUSE_PRESSED, - (passEvent == TRUE) ? event : NULL, - event->xbutton.time, - modifiers, - x, y, - (jint) (event->xbutton.x_root), - (jint) (event->xbutton.y_root), - clickCount, - popupTrigger, 0, - button); - - drag_source = w; - - break; - case ButtonRelease: - if (XtIsSubclass(w, xmScrollBarWidgetClass) && findWidgetInfo(w) != NULL) { - passEvent = FALSE; - *cont = TRUE; - } - - /* - * For button 4 & 5 (mouse wheel) we can simply ignore this event. - * We dispatch the wheel on the ButtonPress. - */ - if (event->xbutton.button == 4 || - event->xbutton.button == 5) { - break; - } - - prevWidget = NULL; - x = (jint) event->xbutton.x; - y = (jint) event->xbutton.y; - /* On MouseEvent.MOUSE_PRESSED, RELEASED and CLICKED only new modifiers and - * modifier for changed mouse button are set. - */ - button = getButton(event->xbutton.button); - modifiers = getModifiers(event->xbutton.state, button, 0); - - fullRelease = - ((event->xbutton.state & Button1Mask) && - !(event->xbutton.state & Button2Mask) && - !(event->xbutton.state & Button3Mask) && - (event->xbutton.button == Button1)) || - (!(event->xbutton.state & Button1Mask) && - (event->xbutton.state & Button2Mask) && - !(event->xbutton.state & Button3Mask) && - (event->xbutton.button == Button2)) || - (!(event->xbutton.state & Button1Mask) && - !(event->xbutton.state & Button2Mask) && - (event->xbutton.state & Button3Mask) && - (event->xbutton.button == Button3)); - - /* If the widget is a subwidget on a component we need to - * translate the x,y into the coordinate space of the component. - */ - if (winfo != NULL && winfo->widget != winfo->origin) { - translateXY(winfo->widget, &x, &y); - } - drag_source = NULL; - awt_post_java_mouse_event(client_data, - java_awt_event_MouseEvent_MOUSE_RELEASED, - (passEvent == TRUE) ? event : NULL, - event->xbutton.time, - modifiers, - x, y, - (jint) (event->xbutton.x_root), - (jint) (event->xbutton.y_root), - clickCount, - FALSE, 0, - button); - - if (lastPeer == client_data) { - awt_post_java_mouse_event(client_data, - java_awt_event_MouseEvent_MOUSE_CLICKED, - NULL, - event->xbutton.time, - modifiers, - x, y, - (jint) (event->xbutton.x_root), - (jint) (event->xbutton.y_root), - clickCount, - FALSE, 0, - button); - } - - if (fullRelease) { - updateCursor(client_data, UPDATE_ONLY); - } - - break; - case MotionNotify: - if (XtIsSubclass(w, xmScrollBarWidgetClass) && findWidgetInfo(w) != NULL) { - passEvent = FALSE; - *cont = TRUE; - } - - x = (jint) event->xmotion.x; - y = (jint) event->xmotion.y; - - /* If a motion comes in while a multi-click is pending, - * allow a smudge factor so that moving the mouse by a small - * amount does not wipe out the multi-click state variables. - */ - if (!(lastPeer == client_data && - ((event->xmotion.time - lastTime) <= (Time) awt_multiclick_time) && - (ABS(lastx - x) < awt_multiclick_smudge && - ABS(lasty - y) < awt_multiclick_smudge))) { - clickCount = (jint) 0; - lastTime = (Time) 0; - lastPeer = NULL; - lastx = (jint) 0; - lasty = (jint) 0; - } - /* On other MouseEvent only new modifiers and - * old mouse modifiers are set. - */ - modifiers = getModifiers(event->xmotion.state, 0, 0); - - /* If the widget is a subwidget on a component we need to - * translate the x,y into the coordinate space of the component. - */ - if (winfo != NULL && winfo->widget != winfo->origin) { - translateXY(winfo->widget, &x, &y); - } - if (event->xmotion.state & (Button1Mask | Button2Mask | Button3Mask)) { - if (!clickCount) { - - /* - Fix for bug id 4017222. A button is down, so EnterNotify and - LeaveNotify events are only being sent to this widget. If - the pointer has moved over a new widget, manually generate - MouseEnter and MouseExit and send them to the right widgets. - */ - - extern Widget awt_WidgetAtXY(Widget root, Position x, Position y); - extern Widget awt_GetWidgetAtPointer(); - Widget currentWidget=NULL, topLevelW; - Position wx=0, wy=0; - - XtTranslateCoords(w, (int32_t) x, (int32_t) y, &wx, &wy); - /* Get the top level widget underneath the mouse pointer */ - currentWidget = awt_GetWidgetAtPointer(); - /* Get the exact widget at the current XY from the top level */ - currentWidget = awt_WidgetAtXY(currentWidget, wx, wy); - if ((prevWidget != NULL) && (prevWidget != w) && - (currentWidget != prevWidget) && awt_isAwtWidget(prevWidget) && - !prevWidget->core.being_destroyed) { - XtPointer userData=NULL; - XtVaGetValues(prevWidget, XmNuserData, &userData, NULL); - if (userData) { - awt_post_java_mouse_event(userData, - java_awt_event_MouseEvent_MOUSE_EXITED, - (passEvent==TRUE) ? event : NULL, - event->xmotion.time, - modifiers, - x, y, - (jint) (event->xmotion.x_root), - (jint) (event->xmotion.y_root), - clickCount, - FALSE, 0, - java_awt_event_MouseEvent_NOBUTTON); - } - } - - if ((currentWidget != NULL) && (currentWidget != w) && - (currentWidget != prevWidget) && awt_isAwtWidget(currentWidget)) { - XtPointer userData=NULL; - XtVaGetValues(currentWidget, XmNuserData, &userData, NULL); - if (userData) { - awt_post_java_mouse_event(userData, - java_awt_event_MouseEvent_MOUSE_ENTERED, - (passEvent==TRUE) ? event : NULL, - event->xmotion.time, - modifiers, - x, y, - (jint) (event->xmotion.x_root), - (jint) (event->xmotion.y_root), - clickCount, - FALSE, 0, - java_awt_event_MouseEvent_NOBUTTON); - } - - updateCursor(userData, CACHE_ONLY); - awt_util_setCursor(currentWidget, None); - } - - prevWidget = currentWidget; - /* end 4017222 */ - - - awt_post_java_mouse_event(client_data, - java_awt_event_MouseEvent_MOUSE_DRAGGED, - (passEvent == TRUE) ? event : NULL, - event->xmotion.time, - modifiers, - x, y, - (jint) (event->xmotion.x_root), - (jint) (event->xmotion.y_root), - clickCount, - FALSE, 0, - java_awt_event_MouseEvent_NOBUTTON); - - } - } else { - - awt_post_java_mouse_event(client_data, - java_awt_event_MouseEvent_MOUSE_MOVED, - (passEvent == TRUE) ? event : NULL, - event->xmotion.time, - modifiers, - x, y, - (jint) (event->xmotion.x_root), - (jint) (event->xmotion.y_root), - clickCount, - FALSE, 0, - java_awt_event_MouseEvent_NOBUTTON); - } - break; - case KeyPress: - handleKeyEvent(java_awt_event_KeyEvent_KEY_PRESSED, - event, client_data, cont, TRUE); - break; - case KeyRelease: - handleKeyEvent(java_awt_event_KeyEvent_KEY_RELEASED, - event, client_data, cont, TRUE); - break; - case EnterNotify: - case LeaveNotify: -/* - printf("----->%s on %s(%x):mode=%d detail = %d\n", - event->type == EnterNotify?"EnterNotify":"LeaveNotify", - XtName(w), w, - ((XCrossingEvent*)event)->mode, ((XCrossingEvent*)event)->detail); -*/ - if (event->xcrossing.mode != NotifyNormal || - ((event->xcrossing.detail == NotifyVirtual || - event->xcrossing.detail == NotifyNonlinearVirtual) && - !XtIsSubclass(w, xmScrolledWindowWidgetClass))) { - *cont = TRUE; - return; - } - - /* fix for 4454304. - * We should not post MOUSE_ENTERED and MOUSE_EXITED events - * if the mouse pointer is in the place between component - * and its scrollbars. - * kdm@sparc.spb.su - */ - if (winfo != NULL && winfo->widget != NULL) { - wclass = XtClass(winfo->widget); - if (event->xcrossing.subwindow == NULL - && event->xcrossing.detail == NotifyInferior - && (wclass == xmTextWidgetClass - || wclass == xmListWidgetClass)) { - *cont = TRUE; - return; - } - } - - clickCount = (jint) 0; - lastTime = (Time) 0; - lastPeer = NULL; - - /* On other MouseEvent only new modifiers and - * old mouse modifiers are set. - */ - modifiers = getModifiers(event->xcrossing.state, 0, 0); - - switch (event->type) { - case EnterNotify: - awt_post_java_mouse_event(client_data, - java_awt_event_MouseEvent_MOUSE_ENTERED, - (passEvent == TRUE) ? event : NULL, - event->xcrossing.time, - modifiers, - (jint) (event->xcrossing.x), - (jint) (event->xcrossing.y), - (jint) (event->xcrossing.x_root), - (jint) (event->xcrossing.y_root), - clickCount, - FALSE, 0, - java_awt_event_MouseEvent_NOBUTTON); - if (!(event->xcrossing.state - & (Button1Mask | Button2Mask | Button3Mask))) { - updateCursor(client_data, CACHE_UPDATE); - } - - break; - case LeaveNotify: - awt_post_java_mouse_event(client_data, - java_awt_event_MouseEvent_MOUSE_EXITED, - (passEvent == TRUE) ? event : NULL, - event->xcrossing.time, - modifiers, - (jint) (event->xcrossing.x), - (jint) (event->xcrossing.y), - (jint) (event->xcrossing.x_root), - (jint) (event->xcrossing.y_root), - clickCount, - FALSE, 0, - java_awt_event_MouseEvent_NOBUTTON); - break; - } - break; - - default: - break; - } -} - -/* - * client_data is MComponentPeer subclass - */ -void -awt_canvas_event_handler(Widget w, XtPointer client_data, - XEvent * event, Boolean * cont) -{ - awt_canvas_handleEvent(w, client_data, event, NULL, cont, FALSE); -} - -void -awt_canvas_reconfigure(struct FrameData *wdata) -{ - Dimension w, h; - - if (wdata->winData.comp.widget == NULL || - XtParent(wdata->winData.comp.widget) == NULL) { - return; - } - XtVaGetValues(XtParent(wdata->winData.comp.widget), XmNwidth, &w, XmNheight, &h, NULL); - XtConfigureWidget(wdata->winData.comp.widget, - -(wdata->left), - -(wdata->top), - w + (wdata->left + wdata->right), - h + (wdata->top + wdata->bottom), - 0); -} - -static void -Wrap_event_handler(Widget widget, - XtPointer client_data, - XmDrawingAreaCallbackStruct * call_data) -{ - awt_canvas_reconfigure((struct FrameData *) client_data); -} - - -Widget -awt_canvas_create(XtPointer this, - Widget parent, - char *base, - int32_t width, - int32_t height, - Boolean parentIsFrame, - struct FrameData *wdata, - AwtGraphicsConfigDataPtr awtData) -{ - Widget newCanvas; - Widget wrap; -#define MAX_ARGC 20 - Arg args[MAX_ARGC]; - int32_t argc; - char name[128]; - static XtTranslations translationKeyDown = NULL; - - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - - if (parent == NULL) { - JNU_ThrowNullPointerException(env, "NullPointerException"); - return NULL; - } - if (width == 0) { - width = 1; - } - if (height == 0) { - height = 1; - } - - if (wdata != NULL) { - argc = 0; - if (!parentIsFrame) - { - XtSetArg(args[argc], XmNwidth, width); - argc++; - XtSetArg(args[argc], XmNheight, height); - argc++; - } - XtSetArg(args[argc], XmNmarginWidth, 0); - argc++; - XtSetArg(args[argc], XmNmarginHeight, 0); - argc++; - XtSetArg(args[argc], XmNspacing, 0); - argc++; - XtSetArg(args[argc], XmNresizePolicy, XmRESIZE_NONE); - argc++; - /* check for overflowing name? */ - strcpy(name, base); - strcat(name, "wrap"); - - DASSERT(!(argc > MAX_ARGC)); - wrap = XmCreateDrawingArea(parent, name, args, argc); - if (!parentIsFrame) - { - /* Fixing bugs in frame module (awt_Frame.c). It will now - provide the resize handling for this inner/parent canvas.*/ - XtAddCallback(wrap, XmNresizeCallback, - (XtCallbackProc) Wrap_event_handler, wdata); - } - XtManageChild(wrap); - } else { - wrap = parent; - } - - /* check for overflowing name? */ - strcpy(name, base); - strcat(name, "canvas"); - - argc = 0; - XtSetArg(args[argc], XmNspacing, 0); - argc++; - if (!parentIsFrame) - { - XtSetArg(args[argc], XmNwidth, width); - argc++; - XtSetArg(args[argc], XmNheight, height); - argc++; - } - XtSetArg(args[argc], XmNmarginHeight, 0); - argc++; - XtSetArg(args[argc], XmNmarginWidth, 0); - argc++; - XtSetArg(args[argc], XmNresizePolicy, XmRESIZE_NONE); - argc++; - XtSetArg(args[argc], XmNuserData, this); - argc++; - /* Fixed 4059430, 3/11/98, robi.khan@eng - * install insert proc callback so components are ordered correctly - * when added directly to frame/dialogs/windows - */ - XtSetArg(args[argc], XmNinsertPosition, (XtPointer) awt_util_insertCallback); - argc++; - - if (awtData != getDefaultConfig(awtData->awt_visInfo.screen)) { - XtSetArg (args[argc], XtNvisual, awtData->awt_visInfo.visual); argc++; - XtSetArg (args[argc], XmNdepth, awtData->awt_depth); argc++; - XtSetArg (args[argc], XmNscreen, - ScreenOfDisplay(awt_display, - awtData->awt_visInfo.screen)); argc++; - - if (awtData->awt_cmap == None) { - awtJNI_CreateColorData (env, awtData, 1); - } - - XtSetArg (args[argc], XmNcolormap, awtData->awt_cmap); argc++; - - DASSERT(!(argc > MAX_ARGC)); - newCanvas = XtCreateWidget(name, vDrawingAreaClass, wrap, - args, argc); - - } else { - newCanvas = XtCreateWidget(name, xDrawingAreaClass, - wrap, args, argc); - } - - XtSetMappedWhenManaged(newCanvas, False); - XtManageChild(newCanvas); -/* - XXX: causes problems on 2.5 - if (!scrollBugWorkAround) { - awt_setWidgetGravity(newCanvas, StaticGravity); - } -*/ - /* Fixed 4250354 7/28/99 ssi@sparc.spb.su - * XtParseTranslationTable leaks in old ver of Xtoolkit - * and result should be deletetd in any case - * - * XtOverrideTranslations(newCanvas, - * XtParseTranslationTable(":DrawingAreaInput()")); - */ - if (NULL==translationKeyDown) - translationKeyDown=XtParseTranslationTable(":DrawingAreaInput()"); - XtOverrideTranslations(newCanvas,translationKeyDown); - - XtSetSensitive(newCanvas, True); - - return newCanvas; -} - -static void -messWithGravity(Widget w, int32_t gravity) -{ - extern void awt_changeAttributes(Display * dpy, Widget w, - unsigned long mask, - XSetWindowAttributes * xattr); - XSetWindowAttributes xattr; - - xattr.bit_gravity = gravity; - xattr.win_gravity = gravity; - - awt_changeAttributes(XtDisplay(w), w, (CWBitGravity | CWWinGravity), &xattr); - -} - -struct MoveRecord { - long dx; - long dy; -}; - -void -moveWidget(Widget w, void *data) -{ - struct MoveRecord *rec = (struct MoveRecord *) data; - - if (XtIsRealized(w) && XmIsRowColumn(w)) { - w->core.x -= rec->dx; - w->core.y -= rec->dy; - } -} - -#if 0 -/* Scroll entire contents of window by dx and dy. Currently only - dy is supported. A negative dy means scroll backwards, i.e., - contents in window move down. */ -void -awt_canvas_scroll(XtPointer this, - struct CanvasData *wdata, - long dx, - long dy) -{ - - Window win; - XWindowChanges xchgs; - Window root; - int x, y; - unsigned int width, height, junk; - Display *dpy; - struct MoveRecord mrec; - - mrec.dx = dx; - mrec.dy = dy; - - dpy = XtDisplay(wdata->comp.widget); - win = XtWindow(wdata->comp.widget); - - /* REMIND: consider getting rid of this! */ - XGetGeometry(awt_display, - win, - &root, - &x, - &y, - &width, - &height, - &junk, - &junk); - - /* we need to actually update the coordinates for manager widgets, */ - /* otherwise the parent won't pass down events to them properly */ - /* after scrolling... */ - awt_util_mapChildren(wdata->comp.widget, moveWidget, 0, &mrec); - - if (dx < 0) { - /* scrolling backward */ - - if (scrollBugWorkAround) { - messWithGravity(wdata->comp.widget, NorthWestGravity); - } - xchgs.x = x + dx; - xchgs.y = y; - xchgs.width = width - dx; - xchgs.height = height; - XConfigureWindow(awt_display, - win, - CWX | CWY | CWWidth | CWHeight, - &xchgs); - - if (scrollBugWorkAround) { - messWithGravity(wdata->comp.widget, NorthWestGravity); - } - xchgs.x = x; - xchgs.y = y; - XConfigureWindow(awt_display, - win, - CWX | CWY, - &xchgs); - - xchgs.width = width; - xchgs.height = height; - XConfigureWindow(awt_display, - win, - CWWidth | CWHeight, - &xchgs); - } else { - /* forward scrolling */ - - /* make window a little taller */ - xchgs.width = width + dx; - xchgs.height = height; - XConfigureWindow(awt_display, - win, - CWWidth | CWHeight, - &xchgs); - - if (scrollBugWorkAround) { - messWithGravity(wdata->comp.widget, NorthEastGravity); - } - /* move window by amount we're scrolling */ - xchgs.x = x - dx; - xchgs.y = y; - XConfigureWindow(awt_display, - win, - CWX | CWY, - &xchgs); - - if (scrollBugWorkAround) { - messWithGravity(wdata->comp.widget, NorthWestGravity); - } - /* resize to original size */ - xchgs.x = x; - xchgs.y = y; - xchgs.width = width; - xchgs.height = height; - XConfigureWindow(awt_display, - win, - CWX | CWY | CWWidth | CWHeight, - &xchgs); - } - /* Because of the weird way we're scrolling this window, - we have to eat all the exposure events that result from - scrolling forward, and translate them up by the amount we're - scrolling by. - - Rather than just eating all the exposures and having the - java code fill in what it knows is exposed, we do it this - way. The reason is that there might be some other exposure - events caused by overlapping windows on top of us that we - also need to deal with. */ - { - XRectangle rect; - - rect.x = -1; - eatAllExposures(dpy, win, &rect); - if (rect.x != -1) { /* we got at least one expose event */ - if (dx > 0) { - rect.x -= dx; - rect.width += dx; - } -/* - printf("EXPOSE (%d): %d, %d, %d, %d\n", - dy, rect.x, rect.y, rect.width, rect.height); -*/ - callJavaExpose(this, &rect); - XSync(awt_display, False); - } - } - if (dy < 0) { - /* scrolling backward */ - - if (scrollBugWorkAround) { - messWithGravity(wdata->comp.widget, SouthGravity); - } - xchgs.x = x; - xchgs.y = y + dy; - xchgs.width = width; - xchgs.height = height - dy; - XConfigureWindow(awt_display, - win, - CWX | CWY | CWWidth | CWHeight, - &xchgs); - - if (scrollBugWorkAround) { - messWithGravity(wdata->comp.widget, NorthWestGravity); - } - xchgs.x = x; - xchgs.y = y; - XConfigureWindow(awt_display, - win, - CWX | CWY, - &xchgs); - - xchgs.width = width; - xchgs.height = height; - XConfigureWindow(awt_display, - win, - CWWidth | CWHeight, - &xchgs); - } else { - /* forward scrolling */ - - /* make window a little taller */ - xchgs.width = width; - xchgs.height = height + dy; - XConfigureWindow(awt_display, - win, - CWWidth | CWHeight, - &xchgs); - - /* move window by amount we're scrolling */ - xchgs.x = x; - xchgs.y = y - dy; - XConfigureWindow(awt_display, - win, - CWX | CWY, - &xchgs); - - if (scrollBugWorkAround) { - messWithGravity(wdata->comp.widget, SouthGravity); - } - /* resize to original size */ - xchgs.x = x; - xchgs.y = y; - xchgs.width = width; - xchgs.height = height; - XConfigureWindow(awt_display, - win, - CWX | CWY | CWWidth | CWHeight, - &xchgs); - if (scrollBugWorkAround) { - messWithGravity(wdata->comp.widget, NorthWestGravity); - } - } - /* Because of the weird way we're scrolling this window, - we have to eat all the exposure events that result from - scrolling forward, and translate them up by the amount we're - scrolling by. - - Rather than just eating all the exposures and having the - java code fill in what it knows is exposed, we do it this - way. The reason is that there might be some other exposure - events caused by overlapping windows on top of us that we - also need to deal with. */ - { - XRectangle rect; - - rect.x = -1; - eatAllExposures(dpy, win, &rect); - if (rect.x != -1) { /* we got at least one expose event */ - if (dy > 0) { - rect.y -= dy; - rect.height += dy; - } - if (dx > 0) { - rect.x -= dx; - rect.width += dx; - } -/* - printf("EXPOSE (%d): %d, %d, %d, %d\n", - dy, rect.x, rect.y, rect.width, rect.height); -*/ - callJavaExpose(this, &rect); - XSync(awt_display, False); - } - } -} -#endif - -extern Window focusProxyWindow; -/* - * client_data is MComponentPeer instance - */ -void -awt_post_java_key_event(XtPointer client_data, jint id, XEvent *event, - Time when, jint keycode, jchar keychar, jint modifiers, jint keyLocation, XEvent *anEvent) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject peer = (jobject) client_data; - jobject target; - static jclass classKeyEvent = NULL; - static jmethodID mid = NULL; - char *clsName = "java/awt/event/KeyEvent"; - jobject hEvent; - jlong jWhen; - Boolean isProxyActive = (focusProxyWindow != None); - - if (anEvent != NULL && anEvent->xany.send_event == 2){ - isProxyActive = False; - if (event != NULL) { - event->xany.send_event = 0; - } - } - if ((*env)->PushLocalFrame(env, 16) < 0) - return; - - target = (*env)->GetObjectField(env, peer, mComponentPeerIDs.target); - - if (classKeyEvent == NULL) { - jobject sysClass; - - sysClass = (*env)->FindClass(env, clsName); - if (sysClass != NULL) { - /* Make this class 'sticky', we don't want it GC'd */ - classKeyEvent = (*env)->NewGlobalRef(env, sysClass); - mid = (*env)->GetMethodID(env, classKeyEvent, "", - "(Ljava/awt/Component;IJIICIZ)V"); - } - if (JNU_IsNull(env, classKeyEvent) || mid == NULL) { - JNU_ThrowClassNotFoundException(env, clsName); - (*env)->PopLocalFrame(env, 0); - return; - } - } - - jWhen = awt_util_nowMillisUTC_offset(when); /* convert Time to UTC */ - - hEvent = (*env)->NewObject(env, classKeyEvent, mid, - target, id, jWhen, modifiers, - keycode, keychar, keyLocation, - isProxyActive?JNI_TRUE:JNI_FALSE); - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - if (JNU_IsNull(env, hEvent)) { - JNU_ThrowNullPointerException(env, "NullPointerException: constructor failed."); - (*env)->PopLocalFrame(env, 0); - return; - } - awt_copyXEventToAWTEvent(env, event, hEvent); - #ifdef DEBUG - if (debugKeys) { - jio_fprintf(stderr, "native posting event id:%d keychar:%c\n", (int)id, (char)keychar); - } - #endif - JNU_CallMethodByName(env, NULL, peer, - "postEvent", "(Ljava/awt/AWTEvent;)V", hEvent); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - (*env)->PopLocalFrame(env, 0); -} /* awt_post_java_key_event() */ - -/* - * Note: this routine returns a global reference which should be deleted - * after use. - */ -jobject -awt_canvas_wrapInSequenced(jobject awtevent) { - static jclass classSequencedEvent = NULL; - static jmethodID mid = NULL; - jobject wrapperEventLocal = NULL; - jobject wrapperEvent = NULL; - - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - - if ((*env)->PushLocalFrame(env, 5) < 0) - return NULL; - - if (classSequencedEvent == NULL) { - jobject sysClass = (*env)->FindClass(env, "java/awt/SequencedEvent"); - if (sysClass != NULL) { - /* Make this class 'sticky', we don't want it GC'd */ - classSequencedEvent = (*env)->NewGlobalRef(env, sysClass); - if (mid == NULL) { - mid = (*env)->GetMethodID(env, classSequencedEvent - ,"" - ,"(Ljava/awt/AWTEvent;)V"); - } - } - if (JNU_IsNull(env, classSequencedEvent) || mid == NULL) { - JNU_ThrowClassNotFoundException(env, "java/awt/SequencedEvent"); - (*env)->PopLocalFrame(env, 0); - return NULL; - } - } - wrapperEventLocal = (*env)->NewObject(env, classSequencedEvent, mid, awtevent); - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - if (JNU_IsNull(env, wrapperEventLocal)) { - JNU_ThrowNullPointerException(env, "constructor failed."); - (*env)->PopLocalFrame(env, 0); - return NULL; - } - wrapperEvent = (*env)->NewGlobalRef(env, wrapperEventLocal); - if (!JNU_IsNull(env, ((*env)->ExceptionOccurred(env)))) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - (*env)->PopLocalFrame(env, 0); - return NULL; - } - if (JNU_IsNull(env, wrapperEvent)) { - JNU_ThrowNullPointerException(env, "NewGlobalRef failed."); - (*env)->PopLocalFrame(env, 0); - return NULL; - } - - (*env)->PopLocalFrame(env, 0); - return wrapperEvent; -} - -jobject -findTopLevelOpposite(JNIEnv *env, jint eventType) -{ - jobject target, peer, opposite; - - if ((*env)->EnsureLocalCapacity(env, 2) < 0) { - return NULL; - } - - /* 4462056: Get a usable handle for a weakly referenced object */ - target = (*env)->NewLocalRef(env, - (eventType == java_awt_event_WindowEvent_WINDOW_GAINED_FOCUS) - ? forGained - : focusList->requestor); - if (target == NULL) { - return NULL; - } - - peer = (*env)->GetObjectField(env, target, componentIDs.peer); - (*env)->DeleteLocalRef(env, target); - if (peer == NULL) { - return NULL; - } - - opposite = findTopLevel(peer, env); - (*env)->DeleteLocalRef(env, peer); - - return opposite; -} - -void -cleanFocusList(JNIEnv *env){ - - while(focusList) { - FocusListElt *tmp = focusList->next; - (*env)->DeleteWeakGlobalRef(env, focusList->requestor); - free(focusList); - focusList = tmp; - } - focusListEnd = NULL; -} - -static jweak -computeOpposite(jint id, jobject target) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject top; - jboolean isSameObject; - - if (focusList == NULL) { - return NULL; - } - - /* 4462056: Get a usable handle for a weakly referenced object */ - top = (*env)->NewLocalRef(env, focusList->requestor); - if (top == NULL) { - /* weakly referenced component was deleted -- clean up focus list */ - cleanFocusList(env); - return NULL; - } - - isSameObject = (*env)->IsSameObject(env, target, top); - (*env)->DeleteLocalRef(env, top); - - if (isSameObject) { - if (id == java_awt_event_FocusEvent_FOCUS_GAINED) { - return forGained; - } else { /* focus lost */ - FocusListElt *tmp = focusList->next; - (*env)->DeleteWeakGlobalRef(env, forGained); - forGained = focusList->requestor; - free(focusList); - focusList = tmp; - - if (focusList == NULL) { - focusListEnd = NULL; - return NULL; - } - return focusList->requestor; - } - } else { /* target does not match top of list */ - /* be gentle with focus lost for now... */ - if (id == java_awt_event_FocusEvent_FOCUS_LOST) { - (*env)->DeleteWeakGlobalRef(env, forGained); - forGained = (*env)->NewWeakGlobalRef(env, target); - return NULL; - } - - cleanFocusList(env); - return NULL; - } -} - - -/* - * client_data is MComponentPeer instance - */ -void -awt_post_java_focus_event(XtPointer client_data, - jint id, jobject cause, - XEvent* event) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject peer = (jobject) client_data; - jobject target; - jobject opposite; - static jclass classFocusEvent = NULL; - static jmethodID mid = NULL; - char *clsName = "sun/awt/CausedFocusEvent"; - jobject hEvent; - - if ((*env)->PushLocalFrame(env, 16) < 0) - return; - - target = (*env)->GetObjectField(env, peer, mComponentPeerIDs.target); - - opposite = (*env)->NewLocalRef(env, computeOpposite(id, target)); - - if (classFocusEvent == NULL) { - jobject sysClass; - - sysClass = (*env)->FindClass(env, clsName); - if (sysClass != NULL) { - /* Make this class 'sticky', we don't want it GC'd */ - classFocusEvent = (*env)->NewGlobalRef(env, sysClass); - mid = (*env)->GetMethodID(env, classFocusEvent - ,"" - ,"(Ljava/awt/Component;IZLjava/awt/Component;Lsun/awt/CausedFocusEvent$Cause;)V"); - } - if (JNU_IsNull(env, classFocusEvent) || mid == 0) { - JNU_ThrowClassNotFoundException(env, clsName); - (*env)->PopLocalFrame(env, 0); - return; - } - } - hEvent = (*env)->NewObject(env, classFocusEvent, mid, - target, id, JNI_FALSE, opposite, cause); - (*env)->DeleteLocalRef(env, opposite); - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - if (JNU_IsNull(env, hEvent)) { - JNU_ThrowNullPointerException(env, "NullPointerException: constructor failed."); - (*env)->PopLocalFrame(env, 0); - return; - } - awt_copyXEventToAWTEvent(env, event, hEvent); - { - jobject awtEvent = awt_canvas_wrapInSequenced(hEvent); - JNU_CallMethodByName(env, NULL, peer, - "postEvent", "(Ljava/awt/AWTEvent;)V", - awtEvent); - (*env)->DeleteGlobalRef(env, awtEvent); - } - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - (*env)->PopLocalFrame(env, 0); -} - - -void -awt_canvas_addToFocusListDefault(jobject target) { - awt_canvas_addToFocusListWithDuplicates(target, JNI_FALSE); -} - -void -awt_canvas_addToFocusListWithDuplicates(jobject target, jboolean acceptDuplicates) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jboolean isSameObject; - - if (focusListEnd) { - jobject localRef = (*env)->NewLocalRef(env, focusListEnd->requestor); - - if (localRef == NULL) { - isSameObject = JNI_FALSE; - } else { - isSameObject = (*env)->IsSameObject(env, target, localRef); - (*env)->DeleteLocalRef(env, localRef); - } - - if (isSameObject && !acceptDuplicates) { - return; - } - - focusListEnd->next = malloc(sizeof(FocusListElt)); - focusListEnd = focusListEnd->next; - } else { - jobject l_focusOwnerPeer = awt_canvas_getFocusOwnerPeer(); - if (l_focusOwnerPeer == NULL) { - isSameObject = JNI_FALSE; - } else { - jobject l_focusOwner = - (*env)->GetObjectField(env, l_focusOwnerPeer, - mComponentPeerIDs.target); - isSameObject = - (*env)->IsSameObject(env, target, l_focusOwner); - (*env)->DeleteLocalRef(env, l_focusOwner); - (*env)->DeleteLocalRef(env, l_focusOwnerPeer); - } - - if (isSameObject && !acceptDuplicates) { - return; - } - - focusList = focusListEnd = malloc(sizeof(FocusListElt)); - } - - focusListEnd->requestor = (*env)->NewWeakGlobalRef(env, target); - focusListEnd->next = NULL; -} - -/* - * client_data is MComponentPeer instance - */ -void -awt_post_java_mouse_event(XtPointer client_data, jint id, XEvent* event, - Time when, jint modifiers, jint x, jint y, - jint xAbs, jint yAbs, - jint clickcount, - Boolean popuptrigger, - jint wheelAmt, jint button) -{ - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - jobject peer = (jobject) client_data; - jobject target; - - static jclass classMouseEvent = NULL; - static jclass classMouseWheelEvent = NULL; - - static jmethodID mid = NULL; - static jmethodID wheelmid = NULL; - - char *clsName = "java/awt/event/MouseEvent"; - char *wheelClsName = "java/awt/event/MouseWheelEvent"; - - jobject hEvent; - jobject sysClass; - jlong jWhen; - - if ((*env)->PushLocalFrame(env, 16) < 0) - return; - - target = (*env)->GetObjectField(env, peer, mComponentPeerIDs.target); - - if (classMouseEvent == NULL) { - sysClass = (*env)->FindClass(env, clsName); - if (sysClass != NULL) { - /* Make this class 'sticky', we don't want it GC'd */ - classMouseEvent = (*env)->NewGlobalRef(env, sysClass); - mid = (*env)->GetMethodID(env, classMouseEvent - ,"" - ,"(Ljava/awt/Component;IJIIIIIIZI)V"); - } - if (JNU_IsNull(env, classMouseEvent) || mid == 0) { - JNU_ThrowClassNotFoundException(env, clsName); - (*env)->PopLocalFrame(env, 0); - return; - } - } - - if (id == java_awt_event_MouseEvent_MOUSE_WHEEL && - classMouseWheelEvent == NULL) { - sysClass = (*env)->FindClass(env, wheelClsName); - if (sysClass != NULL) { - /* Make this class 'sticky', we don't want it GC'd */ - classMouseWheelEvent = (*env)->NewGlobalRef(env, sysClass); - wheelmid = (*env)->GetMethodID(env, classMouseWheelEvent, - "", - "(Ljava/awt/Component;IJIIIIIIZIII)V"); - } - if (JNU_IsNull(env, classMouseWheelEvent) || wheelmid == 0) { - JNU_ThrowClassNotFoundException(env, wheelClsName); - (*env)->PopLocalFrame(env, 0); - return; - } - } - - jWhen = awt_util_nowMillisUTC_offset(when); /* convert Time to UTC */ - - if (id == java_awt_event_MouseEvent_MOUSE_WHEEL) { - hEvent = (*env)->NewObject(env, classMouseWheelEvent, wheelmid, - target, id, jWhen, modifiers, - x, y, - xAbs, yAbs, - clickcount, popuptrigger, - /* Linux has no API for setting how a Component - * should scroll in response to the mouse wheel, - * so we have to make up our own. - * The default behavior on Windows is 3 lines of - * text, so we use that to match. - */ - java_awt_event_MouseWheelEvent_WHEEL_UNIT_SCROLL, - 3, - wheelAmt); - } - else { - hEvent = (*env)->NewObject(env, classMouseEvent, mid, - target, id, jWhen, modifiers, - x, y, - xAbs, yAbs, - clickcount, popuptrigger, button); - } - - - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - if (JNU_IsNull(env, hEvent)) { - JNU_ThrowNullPointerException(env, "NullPointerException: constructor failed."); - (*env)->PopLocalFrame(env, 0); - return; - } - awt_copyXEventToAWTEvent(env, event, hEvent); - JNU_CallMethodByName(env, NULL, peer, - "postEvent", "(Ljava/awt/AWTEvent;)V", hEvent); - if ((*env)->ExceptionOccurred(env)) { - (*env)->ExceptionDescribe(env); - (*env)->ExceptionClear(env); - } - (*env)->PopLocalFrame(env, 0); -} diff --git a/jdk/src/solaris/native/sun/awt/cursor.c b/jdk/src/solaris/native/sun/awt/cursor.c deleted file mode 100644 index f93c15e295a..00000000000 --- a/jdk/src/solaris/native/sun/awt/cursor.c +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -#ifdef HEADLESS - #error This file should not be included in headless library -#endif - -#include "awt_p.h" -#include "java_awt_Cursor.h" -#include "awt_Cursor.h" -#include "sun_awt_motif_MCustomCursor.h" - -#include "jni.h" -#include "jni_util.h" - -extern struct CursorIDs cursorIDs; -static jfieldID widthID; -static jfieldID heightID; - -/* - * Class: sun_awt_motif_MCustomCursor - * Method: cacheInit - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCustomCursor_cacheInit - (JNIEnv *env, jclass cls) -{ - jclass clsDimension = (*env)->FindClass(env, "java/awt/Dimension"); - widthID = (*env)->GetFieldID(env, clsDimension, "width", "I"); - heightID = (*env)->GetFieldID(env, clsDimension, "height", "I"); -} - -/* - * Class: sun_awt_motif_MCustomCursor - * Method: queryBestCursor - * Signature: (Ljava/awt/Dimension;)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCustomCursor_queryBestCursor - (JNIEnv *env, jclass cls, jobject dimension) -{ - Window root; - uint32_t width, height; - - AWT_LOCK(); - root = RootWindow(awt_display, DefaultScreen(awt_display)); - XQueryBestCursor(awt_display, root, - (*env)->GetIntField(env, dimension, widthID), - (*env)->GetIntField(env, dimension, heightID), - &width, &height); - (*env)->SetIntField(env, dimension, widthID, (int32_t) width); - (*env)->SetIntField(env, dimension, heightID, (int32_t) height); - AWT_UNLOCK(); -} - -/* - * Class: sun_awt_motif_MCustomCursor - * Method: createCursor - * Signature: ([B[BIIII)V - */ -JNIEXPORT void JNICALL Java_sun_awt_motif_MCustomCursor_createCursor - (JNIEnv *env , jobject this, jbyteArray xorMask, jbyteArray andMask, - jint width, jint height, jint fc, jint bc, jint xHotSpot, jint yHotSpot) -{ - Cursor cursor; - char *sourceBits, *maskBits; - Window root; - Pixmap source, mask; - XColor fcolor, bcolor; - AwtGraphicsConfigDataPtr defaultConfig = - getDefaultConfig(DefaultScreen(awt_display)); - - AWT_LOCK(); - - root = RootWindow(awt_display, DefaultScreen(awt_display)); - fcolor.flags = DoRed | DoGreen | DoBlue; - fcolor.red = ((fc >> 16) & 0x000000ff) << 8; - fcolor.green = ((fc >> 8) & 0x000000ff) << 8; - fcolor.blue = ((fc >> 0) & 0x000000ff) << 8; - XAllocColor(awt_display, defaultConfig->awt_cmap, &fcolor); - bcolor.flags = DoRed | DoGreen | DoBlue; - bcolor.red = ((bc >> 16) & 0x000000ff) << 8; - bcolor.green = ((bc >> 8) & 0x000000ff) << 8; - bcolor.blue = ((bc >> 0) & 0x000000ff) << 8; - XAllocColor(awt_display, defaultConfig->awt_cmap, &bcolor); - - /* Create source pixmap. */ - sourceBits = (char *)(*env)->GetPrimitiveArrayCritical(env, xorMask, NULL); - source = XCreateBitmapFromData(awt_display, root, sourceBits, - width, height); - - /* Create mask pixmap */ - maskBits = (char *)(*env)->GetPrimitiveArrayCritical(env, andMask, NULL); - mask = XCreateBitmapFromData(awt_display, root, maskBits, - width, height); - - /* Create cursor */ - cursor = XCreatePixmapCursor(awt_display, source, mask, &fcolor, &bcolor, - xHotSpot, yHotSpot); - - /* Free resources */ - XFreePixmap(awt_display, source); - XFreePixmap(awt_display, mask); - - (*env)->ReleasePrimitiveArrayCritical(env, xorMask, sourceBits, JNI_ABORT); - (*env)->ReleasePrimitiveArrayCritical(env, andMask, maskBits, JNI_ABORT); - - JNU_SetLongFieldFromPtr(env, this, cursorIDs.pData, cursor); - - AWT_FLUSH_UNLOCK(); -} diff --git a/jdk/src/solaris/native/sun/awt/initIDs.c b/jdk/src/solaris/native/sun/awt/initIDs.c index f026d9ae727..1eb03b1c52f 100644 --- a/jdk/src/solaris/native/sun/awt/initIDs.c +++ b/jdk/src/solaris/native/sun/awt/initIDs.c @@ -26,7 +26,7 @@ #include "java_awt_Color.h" #include "java_awt_Dimension.h" #include "java_awt_MenuBar.h" -#include "java_awt_Label.h" +//#include "java_awt_Label.h" #include "java_awt_FontMetrics.h" #include "java_awt_event_MouseEvent.h" #include "java_awt_Rectangle.h" diff --git a/jdk/src/solaris/native/sun/awt/multi_font.c b/jdk/src/solaris/native/sun/awt/multi_font.c index aad6bfec992..3d321bbb5fb 100644 --- a/jdk/src/solaris/native/sun/awt/multi_font.c +++ b/jdk/src/solaris/native/sun/awt/multi_font.c @@ -52,8 +52,8 @@ extern XFontStruct *loadFont(Display *, char *, int32_t); extern struct FontIDs fontIDs; -extern struct MComponentPeerIDs mComponentPeerIDs; -extern struct MMenuItemPeerIDs mMenuItemPeerIDs; +//extern struct MComponentPeerIDs mComponentPeerIDs; +//extern struct MMenuItemPeerIDs mMenuItemPeerIDs; extern struct PlatformFontIDs platformFontIDs; extern struct MFontPeerIDs mFontPeerIDs; @@ -151,8 +151,8 @@ awtJNI_DeleteGlobalMenuRef(JNIEnv * env, jobject this) struct gRefStruct *temp; gRef = (jobject) - JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.jniGlobalRef); - JNU_SetLongFieldFromPtr(env, this, mMenuItemPeerIDs.jniGlobalRef, NULL); + //JNU_GetLongFieldAsPtr(env, this, mMenuItemPeerIDs.jniGlobalRef); + //JNU_SetLongFieldFromPtr(env, this, mMenuItemPeerIDs.jniGlobalRef, NULL); /* * Verra handy for tracking down race conditions. If you From 9e5e0e9d44c45eaa837382f1205346595ffe5594 Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Thu, 19 Jun 2008 16:09:22 +0400 Subject: [PATCH 007/325] 6694792: Syntax error in java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_2.java Reviewed-by: yan --- .../MouseEvent/SpuriousExitEnter/SpuriousExitEnter_2.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/test/java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_2.java b/jdk/test/java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_2.java index 45f57c57621..a003c53df99 100644 --- a/jdk/test/java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_2.java +++ b/jdk/test/java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright (c) 2007-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -100,7 +100,7 @@ public class SpuriousExitEnter_2 { Sysout.printInstructions( instructions ); Sysout.enableNumbering(true); - MouseAdapter enterExitAdapter = new MouseAdapter { + MouseAdapter enterExitAdapter = new MouseAdapter() { public void mouseEntered(MouseEvent e){ Sysout.println("Entered on " + e.getSource().getClass().getName()); } From 7690c18be2a1fb727805ef0e520ba992b040268a Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 19 Jun 2008 18:03:43 +0400 Subject: [PATCH 008/325] 4114658: DOC: Unspecified behaviour for java.beans.PropertyEditorSupport Reviewed-by: peterz, loneid --- .../classes/java/beans/PropertyEditor.java | 17 ++++++------ .../java/beans/PropertyEditorSupport.java | 26 ++++++++++++++----- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/jdk/src/share/classes/java/beans/PropertyEditor.java b/jdk/src/share/classes/java/beans/PropertyEditor.java index b6ddf415354..965775898a8 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditor.java +++ b/jdk/src/share/classes/java/beans/PropertyEditor.java @@ -204,20 +204,21 @@ public interface PropertyEditor { //---------------------------------------------------------------------- /** - * Register a listener for the PropertyChange event. When a - * PropertyEditor changes its value it should fire a PropertyChange - * event on all registered PropertyChangeListeners, specifying the - * null value for the property name and itself as the source. + * Adds a listener for the value change. + * When the property editor changes its value + * it should fire a {@link PropertyChangeEvent} + * on all registered {@link PropertyChangeListener}s, + * specifying the {@code null} value for the property name + * and itself as the source. * - * @param listener An object to be invoked when a PropertyChange - * event is fired. + * @param listener the {@link PropertyChangeListener} to add */ void addPropertyChangeListener(PropertyChangeListener listener); /** - * Remove a listener for the PropertyChange event. + * Removes a listener for the value change. * - * @param listener The PropertyChange listener to be removed. + * @param listener the {@link PropertyChangeListener} to remove */ void removePropertyChangeListener(PropertyChangeListener listener); diff --git a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java index 12f07c06bb1..57fddf04365 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java @@ -233,11 +233,20 @@ public class PropertyEditorSupport implements PropertyEditor { //---------------------------------------------------------------------- /** - * Register a listener for the PropertyChange event. The class will - * fire a PropertyChange value whenever the value is updated. + * Adds a listener for the value change. + * When the property editor changes its value + * it should fire a {@link PropertyChangeEvent} + * on all registered {@link PropertyChangeListener}s, + * specifying the {@code null} value for the property name. + * If the source property is set, + * it should be used as the source of the event. + *

+ * The same listener object may be added more than once, + * and will be called as many times as it is added. + * If {@code listener} is {@code null}, + * no exception is thrown and no action is taken. * - * @param listener An object to be invoked when a PropertyChange - * event is fired. + * @param listener the {@link PropertyChangeListener} to add */ public synchronized void addPropertyChangeListener( PropertyChangeListener listener) { @@ -248,9 +257,14 @@ public class PropertyEditorSupport implements PropertyEditor { } /** - * Remove a listener for the PropertyChange event. + * Removes a listener for the value change. + *

+ * If the same listener was added more than once, + * it will be notified one less time after being removed. + * If {@code listener} is {@code null}, or was never added, + * no exception is thrown and no action is taken. * - * @param listener The PropertyChange listener to be removed. + * @param listener the {@link PropertyChangeListener} to remove */ public synchronized void removePropertyChangeListener( PropertyChangeListener listener) { From 6aa1d81c2f4d97f1a615e8da721c88779e3b54ff Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Mon, 23 Jun 2008 14:42:53 +0400 Subject: [PATCH 009/325] 6682536: java\awt\FullScreen\NonfocusableFrameFullScreenTest\NonfocusableFrameFullScreenTest.java fails Always-on-top property should be restored on exiting full-screen. Reviewed-by: tdv --- .../windows/native/sun/windows/awt_Win32GraphicsDevice.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/jdk/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp b/jdk/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp index ff144bc61a0..6d59689cb0f 100644 --- a/jdk/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp @@ -1107,6 +1107,10 @@ Java_sun_awt_Win32GraphicsDevice_exitFullScreenExclusive( } } } else { + jobject target = env->GetObjectField(windowPeer, AwtObject::targetID); + jboolean alwaysOnTop = JNU_GetFieldByName(env, NULL, target, "alwaysOnTop", "Z").z; + env->DeleteLocalRef(target); + if (!::SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOOWNERZORDER|SWP_NOSIZE)) { @@ -1114,6 +1118,9 @@ Java_sun_awt_Win32GraphicsDevice_exitFullScreenExclusive( "Error %d unsetting topmost attribute to fs window", ::GetLastError()); } + + // We should restore alwaysOnTop state as it's anyway dropped here + Java_sun_awt_windows_WWindowPeer_setAlwaysOnTopNative(env, windowPeer, alwaysOnTop); } CATCH_BAD_ALLOC; From 3a96c0f73d3b7ab8e6d3cf8df50e39a2502bee25 Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Mon, 23 Jun 2008 16:03:25 +0400 Subject: [PATCH 010/325] 6704896: FD_SET usage can cause stack corruption (sol) Using poll() instead of select() Reviewed-by: yan, denis --- .../sun/awt/splashscreen/splashscreen_sys.c | 35 ++++++++----------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c b/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c index bcbc98393af..012b38e3c59 100644 --- a/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c +++ b/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c @@ -40,6 +40,7 @@ #include #include #include +#include static Bool shapeSupported; static int shapeEventBase, shapeErrorBase; @@ -534,40 +535,34 @@ void SplashEventLoop(Splash * splash) { /* Different from win32 implementation - this loop - uses select timeouts instead of a timer */ + uses poll timeouts instead of a timer */ /* we should have splash _locked_ on entry!!! */ int xconn = XConnectionNumber(splash->display); while (1) { + struct pollfd pfd[2]; + int timeout = -1; int ctl = splash->controlpipe[0]; - fd_set fds[2]; - int n = 0; - struct timeval tv, *ptv; int rc; - int time; int pipes_empty; - FD_ZERO(fds); - FD_SET(xconn, fds); - if (xconn+1 > n) - n = xconn+1; - FD_SET(ctl, fds); - if (ctl+1 > n) - n = ctl+1; + pfd[0].fd = xconn; + pfd[0].events = POLLIN | POLLPRI; + + pfd[1].fd = ctl; + pfd[1].events = POLLIN | POLLPRI; + errno = 0; if (splash->isVisible>0 && SplashIsStillLooping(splash)) { - time = splash->time + splash->frames[splash->currentFrame].delay + timeout = splash->time + splash->frames[splash->currentFrame].delay - SplashTime(); - if (time < 0) - time = 0; - msec2timeval(time, &tv); - ptv = &tv; - } else { - ptv = NULL; + if (timeout < 0) { + timeout = 0; + } } SplashUnlock(splash); - rc = select(n, fds, NULL, NULL, ptv); + rc = poll(pfd, 2, timeout); SplashLock(splash); if (splash->isVisible>0 && SplashTime() >= splash->time + splash->frames[splash->currentFrame].delay) { From 762ea5875b8d38a67aa2e524b4756fdfb02c115e Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Mon, 23 Jun 2008 15:21:37 -0400 Subject: [PATCH 011/325] 6623943: javax.swing.TimerQueue's thread occasionally fails to start Reviewed-by: alexp --- .../share/classes/javax/swing/JApplet.java | 5 +- .../share/classes/javax/swing/TimerQueue.java | 67 ++++++++++--------- 2 files changed, 35 insertions(+), 37 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/JApplet.java b/jdk/src/share/classes/javax/swing/JApplet.java index b9b5b2506b9..47f792a942d 100644 --- a/jdk/src/share/classes/javax/swing/JApplet.java +++ b/jdk/src/share/classes/javax/swing/JApplet.java @@ -131,10 +131,7 @@ public class JApplet extends Applet implements Accessible, // Check the timerQ and restart if necessary. TimerQueue q = TimerQueue.sharedInstance(); if(q != null) { - synchronized(q) { - if(!q.running) - q.start(); - } + q.startIfNeeded(); } /* Workaround for bug 4155072. The shared double buffer image diff --git a/jdk/src/share/classes/javax/swing/TimerQueue.java b/jdk/src/share/classes/javax/swing/TimerQueue.java index 2121939011f..1f694d1c820 100644 --- a/jdk/src/share/classes/javax/swing/TimerQueue.java +++ b/jdk/src/share/classes/javax/swing/TimerQueue.java @@ -31,6 +31,7 @@ package javax.swing; import java.util.*; import java.util.concurrent.*; +import java.util.concurrent.locks.*; import java.util.concurrent.atomic.AtomicLong; import sun.awt.AppContext; @@ -52,7 +53,8 @@ class TimerQueue implements Runnable new StringBuffer("TimerQueue.expiredTimersKey"); private final DelayQueue queue; - volatile boolean running; + private volatile boolean running; + private final Lock runningLock; /* Lock object used in place of class object for synchronization. * (4187686) @@ -69,7 +71,8 @@ class TimerQueue implements Runnable super(); queue = new DelayQueue(); // Now start the TimerQueue thread. - start(); + runningLock = new ReentrantLock(); + startIfNeeded(); } @@ -87,33 +90,30 @@ class TimerQueue implements Runnable } - synchronized void start() { - if (running) { - throw new RuntimeException("Can't start a TimerQueue " + - "that is already running"); - } - else { - final ThreadGroup threadGroup = - AppContext.getAppContext().getThreadGroup(); - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - Thread timerThread = new Thread(threadGroup, TimerQueue.this, - "TimerQueue"); - timerThread.setDaemon(true); - timerThread.setPriority(Thread.NORM_PRIORITY); - timerThread.start(); - return null; - } - }); - running = true; + void startIfNeeded() { + if (! running) { + runningLock.lock(); + try { + final ThreadGroup threadGroup = + AppContext.getAppContext().getThreadGroup(); + java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Object run() { + Thread timerThread = new Thread(threadGroup, TimerQueue.this, + "TimerQueue"); + timerThread.setDaemon(true); + timerThread.setPriority(Thread.NORM_PRIORITY); + timerThread.start(); + return null; + } + }); + running = true; + } finally { + runningLock.unlock(); + } } } - synchronized void stop() { - running = false; - } - void addTimer(Timer timer, long delayMillis) { timer.getLock().lock(); try { @@ -164,6 +164,7 @@ class TimerQueue implements Runnable public void run() { + runningLock.lock(); try { while (running) { try { @@ -195,14 +196,14 @@ class TimerQueue implements Runnable } } catch (ThreadDeath td) { - synchronized (this) { - running = false; - // Mark all the timers we contain as not being queued. - for (DelayedTimer delayedTimer : queue) { - delayedTimer.getTimer().cancelEvent(); - } - throw td; + // Mark all the timers we contain as not being queued. + for (DelayedTimer delayedTimer : queue) { + delayedTimer.getTimer().cancelEvent(); } + throw td; + } finally { + running = false; + runningLock.unlock(); } } From 86ac930e557df1de5b207464c44473e6b0f5b83c Mon Sep 17 00:00:00 2001 From: Dmitry Cherepanov Date: Thu, 26 Jun 2008 14:23:25 +0400 Subject: [PATCH 012/325] 6581899: JTextField & JTextArea - Poor performance with JRE 1.5.0_08 Acquire the first|last components only when the key is a traversal key Reviewed-by: ant --- .../share/classes/sun/awt/EmbeddedFrame.java | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/jdk/src/share/classes/sun/awt/EmbeddedFrame.java b/jdk/src/share/classes/sun/awt/EmbeddedFrame.java index 63a12b7f83a..d7450bebe1d 100644 --- a/jdk/src/share/classes/sun/awt/EmbeddedFrame.java +++ b/jdk/src/share/classes/sun/awt/EmbeddedFrame.java @@ -257,21 +257,27 @@ public abstract class EmbeddedFrame extends Frame Set toTest; Component currentFocused = e.getComponent(); - Component last = getFocusTraversalPolicy().getLastComponent(this); toTest = getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); - if (toTest.contains(stroke) && (currentFocused == last || last == null)) { - if (traverseOut(FORWARD)) { - e.consume(); - return true; + if (toTest.contains(stroke)) { + // 6581899: performance improvement for SortingFocusTraversalPolicy + Component last = getFocusTraversalPolicy().getLastComponent(this); + if (currentFocused == last || last == null) { + if (traverseOut(FORWARD)) { + e.consume(); + return true; + } } } - Component first = getFocusTraversalPolicy().getFirstComponent(this); toTest = getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); - if (toTest.contains(stroke) && (currentFocused == first || first == null)) { - if (traverseOut(BACKWARD)) { - e.consume(); - return true; + if (toTest.contains(stroke)) { + // 6581899: performance improvement for SortingFocusTraversalPolicy + Component first = getFocusTraversalPolicy().getFirstComponent(this); + if (currentFocused == first || first == null) { + if (traverseOut(BACKWARD)) { + e.consume(); + return true; + } } } return false; From 9d7b3f41e04e5a8d75d948e22b79c49b45fde494 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 26 Jun 2008 15:11:04 +0400 Subject: [PATCH 013/325] 6718964: Swing border tests should be open source Reviewed-by: peterz --- jdk/test/javax/swing/border/Test4120351.java | 43 ++++++++++++ jdk/test/javax/swing/border/Test4124729.java | 38 ++++++++++ jdk/test/javax/swing/border/Test4243289.html | 9 +++ jdk/test/javax/swing/border/Test4243289.java | 52 ++++++++++++++ jdk/test/javax/swing/border/Test4247606.html | 10 +++ jdk/test/javax/swing/border/Test4247606.java | 62 +++++++++++++++++ jdk/test/javax/swing/border/Test4252164.html | 10 +++ jdk/test/javax/swing/border/Test4252164.java | 73 ++++++++++++++++++++ jdk/test/javax/swing/border/Test6461042.java | 57 +++++++++++++++ 9 files changed, 354 insertions(+) create mode 100644 jdk/test/javax/swing/border/Test4120351.java create mode 100644 jdk/test/javax/swing/border/Test4124729.java create mode 100644 jdk/test/javax/swing/border/Test4243289.html create mode 100644 jdk/test/javax/swing/border/Test4243289.java create mode 100644 jdk/test/javax/swing/border/Test4247606.html create mode 100644 jdk/test/javax/swing/border/Test4247606.java create mode 100644 jdk/test/javax/swing/border/Test4252164.html create mode 100644 jdk/test/javax/swing/border/Test4252164.java create mode 100644 jdk/test/javax/swing/border/Test6461042.java diff --git a/jdk/test/javax/swing/border/Test4120351.java b/jdk/test/javax/swing/border/Test4120351.java new file mode 100644 index 00000000000..1253e638a0e --- /dev/null +++ b/jdk/test/javax/swing/border/Test4120351.java @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4120351 + * @summary Tests that the methods createEtchedBorder(int type) and + * createEtchedBorder(int type, Color highlight, Color shadows) are added + * @author Andrey Pikalev + */ + +import java.awt.Color; +import javax.swing.BorderFactory; +import javax.swing.border.EtchedBorder; + +public class Test4120351 { + public static void main(String[] args) { + BorderFactory.createEtchedBorder(EtchedBorder.RAISED); + BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); + BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.BLACK, Color.WHITE); + BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.WHITE, Color.BLACK); + } +} diff --git a/jdk/test/javax/swing/border/Test4124729.java b/jdk/test/javax/swing/border/Test4124729.java new file mode 100644 index 00000000000..d48ce9d1d5f --- /dev/null +++ b/jdk/test/javax/swing/border/Test4124729.java @@ -0,0 +1,38 @@ +/* + * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4124729 + * @summary Test that constrtructor LineBorder(?,?,?) is public + * @author Andrey Pikalev + */ + +import java.awt.Color; +import javax.swing.border.LineBorder; + +public class Test4124729 { + public static void main(String[] args) { + new LineBorder(Color.BLUE, 3, true); + } +} diff --git a/jdk/test/javax/swing/border/Test4243289.html b/jdk/test/javax/swing/border/Test4243289.html new file mode 100644 index 00000000000..9133d99c582 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4243289.html @@ -0,0 +1,9 @@ + + +When applet starts, you'll see a panel with a TitledBorder with title "Panel Title". +If this title is overstriken with the border line, test fails, otherwise it passes. + + + + + diff --git a/jdk/test/javax/swing/border/Test4243289.java b/jdk/test/javax/swing/border/Test4243289.java new file mode 100644 index 00000000000..1c462a85973 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4243289.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4243289 + * @summary Tests that TitledBorder do not draw line through its caption + * @author Peter Zhelezniakov + * @run applet/manual=yesno Test4243289.html + */ + +import java.awt.Font; +import javax.swing.BorderFactory; +import javax.swing.JApplet; +import javax.swing.JPanel; +import javax.swing.border.TitledBorder; + +public class Test4243289 extends JApplet { + public void init() { + Font font = new Font("Dialog", Font.PLAIN, 12); // NON-NLS: the font name + TitledBorder border = BorderFactory.createTitledBorder( + BorderFactory.createEtchedBorder(), + "Panel Title", // NON-NLS: the title of the border + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, + font); + + JPanel panel = new JPanel(); + panel.setBorder(border); + getContentPane().add(panel); + } +} diff --git a/jdk/test/javax/swing/border/Test4247606.html b/jdk/test/javax/swing/border/Test4247606.html new file mode 100644 index 00000000000..d501ab221d6 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4247606.html @@ -0,0 +1,10 @@ + + +If the button do not fit into the titled border bounds +and cover the bottom border's line then test fails. +Otherwise test passes. + + + + + diff --git a/jdk/test/javax/swing/border/Test4247606.java b/jdk/test/javax/swing/border/Test4247606.java new file mode 100644 index 00000000000..b598d4a1b9e --- /dev/null +++ b/jdk/test/javax/swing/border/Test4247606.java @@ -0,0 +1,62 @@ +/* + * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4247606 + * @summary BorderedPane appears wrong with Title Position Below Bottom + * @author Andrey Pikalev + * @run applet/manual=yesno Test4247606.html + */ + +import java.awt.BorderLayout; +import java.awt.Color; +import javax.swing.BorderFactory; +import javax.swing.JApplet; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.border.Border; +import javax.swing.border.TitledBorder; + +public class Test4247606 extends JApplet { + public void init() { + JButton button = new JButton("Button"); // NON-NLS: the button text + button.setBorder(BorderFactory.createLineBorder(Color.red, 1)); + + TitledBorder border = new TitledBorder("Bordered Pane"); // NON-NLS: the panel title + border.setTitlePosition(TitledBorder.BELOW_BOTTOM); + + JPanel panel = create(button, border); + panel.setBackground(Color.green); + + getContentPane().add(create(panel, BorderFactory.createEmptyBorder(10, 10, 10, 10))); + } + + private static JPanel create(JComponent component, Border border) { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(border); + panel.add(component); + return panel; + } +} diff --git a/jdk/test/javax/swing/border/Test4252164.html b/jdk/test/javax/swing/border/Test4252164.html new file mode 100644 index 00000000000..eb436c53fe3 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4252164.html @@ -0,0 +1,10 @@ + + +Please, ensure that rounded border is filled completely. +It should not contain white points inside. +Use Mouse Wheel to change thickness of the border. + + + + + diff --git a/jdk/test/javax/swing/border/Test4252164.java b/jdk/test/javax/swing/border/Test4252164.java new file mode 100644 index 00000000000..a39193fc6f9 --- /dev/null +++ b/jdk/test/javax/swing/border/Test4252164.java @@ -0,0 +1,73 @@ +/* + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4252164 + * @summary Tests rounded LineBorder for components + * @author Sergey Malenkov + * @run applet/manual=yesno Test4252164.html + */ + +import java.awt.Color; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import javax.swing.JApplet; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.border.LineBorder; + +public class Test4252164 extends JApplet implements MouseWheelListener { + private int thickness; + private JLabel rounded; + private JLabel straight; + + public void mouseWheelMoved(MouseWheelEvent event) { + update(event.getWheelRotation()); + } + + public void init() { + add(createUI()); + addMouseWheelListener(this); + } + + private JPanel createUI() { + this.rounded = new JLabel("ROUNDED"); // NON-NLS: the label for rounded border + this.straight = new JLabel("STRAIGHT"); // NON-NLS: the label for straight border + + JPanel panel = new JPanel(); + panel.add(this.rounded); + panel.add(this.straight); + + update(10); + + return panel; + } + + private void update(int thickness) { + this.thickness += thickness; + + this.rounded.setBorder(new LineBorder(Color.RED, this.thickness, true)); + this.straight.setBorder(new LineBorder(Color.RED, this.thickness, false)); + } +} diff --git a/jdk/test/javax/swing/border/Test6461042.java b/jdk/test/javax/swing/border/Test6461042.java new file mode 100644 index 00000000000..3224b1db83e --- /dev/null +++ b/jdk/test/javax/swing/border/Test6461042.java @@ -0,0 +1,57 @@ +/* + * Copyright 2006-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6461042 + * @summary Tests that toString() doesn't cause StackOverflowException + * when a JComponent is its own border + * @author Shannon Hickey + */ + +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Insets; +import javax.swing.JComponent; +import javax.swing.border.Border; + +public class Test6461042 extends JComponent implements Border { + public static void main(String[] args) { + new Test6461042().toString(); + } + + public Test6461042() { + setBorder(this); + } + + public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { + } + + public Insets getBorderInsets(Component c) { + return null; + } + + public boolean isBorderOpaque() { + return false; + } +} From ef9b3891fc4b83e611765fbc187e6ceb8510cb57 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 26 Jun 2008 15:39:12 +0400 Subject: [PATCH 014/325] 6718965: Swing color chooser tests should be open source Reviewed-by: peterz --- .../swing/JColorChooser/Test4165217.java | 78 +++++++++++++++ .../swing/JColorChooser/Test4177735.java | 95 +++++++++++++++++++ .../swing/JColorChooser/Test4193384.java | 70 ++++++++++++++ .../swing/JColorChooser/Test4234761.java | 60 ++++++++++++ .../swing/JColorChooser/Test4380468.html | 17 ++++ .../swing/JColorChooser/Test4380468.java | 40 ++++++++ .../swing/JColorChooser/Test4461329.java | 46 +++++++++ .../swing/JColorChooser/Test4711996.java | 41 ++++++++ .../swing/JColorChooser/Test4759306.html | 8 ++ .../swing/JColorChooser/Test4759306.java | 42 ++++++++ .../swing/JColorChooser/Test4759934.html | 14 +++ .../swing/JColorChooser/Test4759934.java | 80 ++++++++++++++++ .../swing/JColorChooser/Test4887836.html | 9 ++ .../swing/JColorChooser/Test4887836.java | 43 +++++++++ 14 files changed, 643 insertions(+) create mode 100644 jdk/test/javax/swing/JColorChooser/Test4165217.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4177735.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4193384.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4234761.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4380468.html create mode 100644 jdk/test/javax/swing/JColorChooser/Test4380468.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4461329.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4711996.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4759306.html create mode 100644 jdk/test/javax/swing/JColorChooser/Test4759306.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4759934.html create mode 100644 jdk/test/javax/swing/JColorChooser/Test4759934.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test4887836.html create mode 100644 jdk/test/javax/swing/JColorChooser/Test4887836.java diff --git a/jdk/test/javax/swing/JColorChooser/Test4165217.java b/jdk/test/javax/swing/JColorChooser/Test4165217.java new file mode 100644 index 00000000000..59a80e89848 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4165217.java @@ -0,0 +1,78 @@ +/* + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4165217 + * @summary Tests JColorChooser serialization + * @author Ilya Boyandin + */ + +import java.awt.Color; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Random; +import javax.swing.JColorChooser; + +public class Test4165217 { + public static void main(String[] args) { + JColorChooser chooser = new JColorChooser(); + chooser.setColor(new Color(new Random().nextInt())); + + Color before = chooser.getColor(); + Color after = copy(chooser).getColor(); + + if (!after.equals(before)) { + throw new Error("color is changed after serialization"); + } + } + + private static JColorChooser copy(JColorChooser chooser) { + try { + return (JColorChooser) deserialize(serialize(chooser)); + } + catch (ClassNotFoundException exception) { + throw new Error("unexpected exception during class creation", exception); + } + catch (IOException exception) { + throw new Error("unexpected exception during serialization", exception); + } + } + + private static byte[] serialize(Object object) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(object); + oos.flush(); + return baos.toByteArray(); + } + + private static Object deserialize(byte[] array) throws IOException, ClassNotFoundException { + ByteArrayInputStream bais = new ByteArrayInputStream(array); + ObjectInputStream ois = new ObjectInputStream(bais); + return ois.readObject(); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4177735.java b/jdk/test/javax/swing/JColorChooser/Test4177735.java new file mode 100644 index 00000000000..b8b2d93f47e --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4177735.java @@ -0,0 +1,95 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4177735 + * @summary Tests that JColorChooser leaves no threads when disposed + * @author Shannon Hickey + */ + +import java.awt.Point; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.SwingUtilities; +import javax.swing.colorchooser.AbstractColorChooserPanel; + +public class Test4177735 implements Runnable { + private static final long DELAY = 1000L; + + public static void main(String[] args) throws Exception { + JColorChooser chooser = new JColorChooser(); + AbstractColorChooserPanel[] panels = chooser.getChooserPanels(); + chooser.setChooserPanels(new AbstractColorChooserPanel[] { panels[1] }); + + JDialog dialog = show(chooser); + pause(DELAY); + + dialog.dispose(); + pause(DELAY); + + Test4177735 test = new Test4177735(); + SwingUtilities.invokeAndWait(test); + if (test.count != 0) { + throw new Error("JColorChooser leaves " + test.count + " threads running"); + } + } + + static JDialog show(JColorChooser chooser) { + JDialog dialog = JColorChooser.createDialog(null, null, false, chooser, null, null); + dialog.setVisible(true); + // block till displayed + Point point = null; + while (point == null) { + try { + point = dialog.getLocationOnScreen(); + } + catch (IllegalStateException exception) { + pause(DELAY); + } + } + return dialog; + } + + private static void pause(long delay) { + try { + Thread.sleep(delay); + } + catch (InterruptedException exception) { + } + } + + private int count; + + public void run() { + ThreadGroup group = Thread.currentThread().getThreadGroup(); + Thread[] threads = new Thread[group.activeCount()]; + int count = group.enumerate(threads, false); + for (int i = 0; i < count; i++) { + String name = threads[i].getName(); + if ("SyntheticImageGenerator".equals(name)) { // NON-NLS: thread name + this.count++; + } + } + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4193384.java b/jdk/test/javax/swing/JColorChooser/Test4193384.java new file mode 100644 index 00000000000..e9ed74728a4 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4193384.java @@ -0,0 +1,70 @@ +/* + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4193384 4200976 + * @summary Tests the color conversions and the preview panel foreground color + * @author Mark Davidson + */ + +import java.awt.Color; +import javax.swing.JColorChooser; +import javax.swing.JLabel; + +public class Test4193384 { + public static void main(String[] args) { + test(new Color[] { + new Color(11, 12, 13), + new Color(204, 0, 204), + new Color(0, 51, 51) + }); + } + + private static void test(Color[] colors) { + JLabel label = new JLabel("Preview Panel"); // NON-NLS: simple label + + JColorChooser chooser = new JColorChooser(); + chooser.setPreviewPanel(label); + + float[] hsb = new float[3]; + for (int i = 0; i < colors.length; i++) { + Color color = colors[i]; + // Make sure sure that there wasn't a regression + // in java.awt.Color and the conversion methods + Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsb); + if (!color.equals(Color.getHSBColor(hsb[0], hsb[1], hsb[2]))) { + throw new Error("color conversion is failed"); + } + // 4193384 regression test + if (!color.equals(new JColorChooser(color).getColor())) { + throw new Error("constructor sets incorrect initial color"); + } + // 4200976 regression test + chooser.setColor(color); + if (!color.equals(label.getForeground())) { + throw new Error("a custom preview panel doesn't handle colors"); + } + } + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4234761.java b/jdk/test/javax/swing/JColorChooser/Test4234761.java new file mode 100644 index 00000000000..aa3d972a642 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4234761.java @@ -0,0 +1,60 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4234761 + * @summary RGB values sholdn't be changed in transition to HSB tab + * @author Oleg Mokhovikov + */ + +import java.awt.Color; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.JTabbedPane; + +public class Test4234761 implements PropertyChangeListener { + private static final Color COLOR = new Color(51, 51, 51); + + public static void main(String[] args) { + JColorChooser chooser = new JColorChooser(COLOR); + JDialog dialog = Test4177735.show(chooser); + + PropertyChangeListener listener = new Test4234761(); + chooser.addPropertyChangeListener("color", listener); // NON-NLS: property name + + JTabbedPane tabbedPane = (JTabbedPane) chooser.getComponent(0); + tabbedPane.setSelectedIndex(1); // HSB tab index + + if (!chooser.getColor().equals(COLOR)) { + listener.propertyChange(null); + } + dialog.dispose(); + } + + public void propertyChange(PropertyChangeEvent event) { + throw new Error("RGB value is changed after transition to HSB tab"); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4380468.html b/jdk/test/javax/swing/JColorChooser/Test4380468.html new file mode 100644 index 00000000000..fbbba0d2e64 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4380468.html @@ -0,0 +1,17 @@ + + +1. Click the HSB tab at the ColorChooser. +2. Click in the lower left corner of the gradient palette + in order to select a color such that all three RGB values + are single digit colors (such as 0, 0, 0 or 5, 3, 1). +3. Click another tab, then click back to the HSB tab. +4. Now click the lighter colors that should have + 2 and 3 digit RGB values (in the upper right corner). + +If all digits of each RGB value are shown then test passes. +If only the last digit of their values are shown then test fails. + + + + + diff --git a/jdk/test/javax/swing/JColorChooser/Test4380468.java b/jdk/test/javax/swing/JColorChooser/Test4380468.java new file mode 100644 index 00000000000..7e903317121 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4380468.java @@ -0,0 +1,40 @@ +/* + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4380468 + * @summary JColorChooser's HSB panel should display all RGB digits + * @author Andrey Pikalev + * @run applet/manual=yesno Test4380468.html + */ + +import java.awt.Color; +import javax.swing.JApplet; +import javax.swing.JColorChooser; + +public class Test4380468 extends JApplet { + public void init() { + add(new JColorChooser(Color.GREEN)); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4461329.java b/jdk/test/javax/swing/JColorChooser/Test4461329.java new file mode 100644 index 00000000000..2f23bc1ec6c --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4461329.java @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4461329 + * @summary Tests getPreviewPanel() and setPreviewPanel() methods + * @author Leif Samuelsson + */ + +import javax.swing.JButton; +import javax.swing.JColorChooser; + +public class Test4461329 { + public static void main(String[] args) { + JColorChooser chooser = new JColorChooser(); + if (null == chooser.getPreviewPanel()) { + throw new Error("Failed: getPreviewPanel() returned null"); + } + JButton button = new JButton("Color"); // NON-NLS: simple label + chooser.setPreviewPanel(button); + if (button != chooser.getPreviewPanel()) { + throw new Error("Failed in setPreviewPanel()"); + } + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4711996.java b/jdk/test/javax/swing/JColorChooser/Test4711996.java new file mode 100644 index 00000000000..fb6007712cf --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4711996.java @@ -0,0 +1,41 @@ +/* + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4711996 + * @summary Checks if IllegalArgumentException is thrown when updating JColorChooserUI + * @author Konstantin Eremin + */ + +import javax.swing.JColorChooser; +import javax.swing.colorchooser.AbstractColorChooserPanel; + +public class Test4711996 { + public static void main(String[] args) { + JColorChooser chooser = new JColorChooser(); + AbstractColorChooserPanel[] panels = chooser.getChooserPanels(); + chooser.removeChooserPanel(panels[0]); + chooser.updateUI(); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4759306.html b/jdk/test/javax/swing/JColorChooser/Test4759306.html new file mode 100644 index 00000000000..8a4d53f00e9 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4759306.html @@ -0,0 +1,8 @@ + + +If you see the preview panel, then test failed, otherwise it passed. + + + + + diff --git a/jdk/test/javax/swing/JColorChooser/Test4759306.java b/jdk/test/javax/swing/JColorChooser/Test4759306.java new file mode 100644 index 00000000000..726ed798f0e --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4759306.java @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4759306 + * @summary Checks if JColorChooser.setPreviewPanel removes the old one + * @author Konstantin Eremin + @run applet/manual=yesno Test4759306.html + */ + +import javax.swing.JApplet; +import javax.swing.JColorChooser; +import javax.swing.JPanel; + +public class Test4759306 extends JApplet { + public void init() { + JColorChooser chooser = new JColorChooser(); + chooser.setPreviewPanel(new JPanel()); + getContentPane().add(chooser); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4759934.html b/jdk/test/javax/swing/JColorChooser/Test4759934.html new file mode 100644 index 00000000000..0441b67ac66 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4759934.html @@ -0,0 +1,14 @@ + + +1. Press button "Show Dialog" at the frame "Test" and + the dialog with button "Show ColorChooser" should appears. +2. Press button "Show ColorChooser" at the dialog "Dialog" and + the colorchooser should appears. +3. Press the button "Cancel" of colorchooser. + If the focus will come to the frame "Test" then test fails. + If the focus will come to the dialog "Dialog" then test passes. + + + + + diff --git a/jdk/test/javax/swing/JColorChooser/Test4759934.java b/jdk/test/javax/swing/JColorChooser/Test4759934.java new file mode 100644 index 00000000000..27137726ea0 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4759934.java @@ -0,0 +1,80 @@ +/* + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4759934 + * @summary Tests windows activation problem + * @author Andrey Pikalev + * @run applet/manual=yesno Test4759934.html + */ + +import java.awt.Color; +import java.awt.Component; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JApplet; +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.JFrame; + +public class Test4759934 extends JApplet implements ActionListener { + private static final String CMD_DIALOG = "Show Dialog"; // NON-NLS: first button + private static final String CMD_CHOOSER = "Show ColorChooser"; // NON-NLS: second button + + private final JFrame frame = new JFrame("Test"); // NON-NLS: frame title + + public void init() { + show(this.frame, CMD_DIALOG); + } + + public void actionPerformed(ActionEvent event) { + String command = event.getActionCommand(); + if (CMD_DIALOG.equals(command)) { + JDialog dialog = new JDialog(this.frame, "Dialog"); // NON-NLS: dialog title + dialog.setLocation(200, 0); + show(dialog, CMD_CHOOSER); + } + else if (CMD_CHOOSER.equals(command)) { + Object source = event.getSource(); + Component component = (source instanceof Component) + ? (Component) source + : null; + + JColorChooser.showDialog(component, "ColorChooser", Color.BLUE); // NON-NLS: title + } + } + + private void show(Window window, String command) { + JButton button = new JButton(command); + button.setActionCommand(command); + button.addActionListener(this); + button.setFont(button.getFont().deriveFont(64.0f)); + + window.add(button); + window.pack(); + window.setVisible(true); + } +} diff --git a/jdk/test/javax/swing/JColorChooser/Test4887836.html b/jdk/test/javax/swing/JColorChooser/Test4887836.html new file mode 100644 index 00000000000..324d5afe368 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4887836.html @@ -0,0 +1,9 @@ + + +If you do not see white area under swatches, +then test passed, otherwise it failed. + + + + + diff --git a/jdk/test/javax/swing/JColorChooser/Test4887836.java b/jdk/test/javax/swing/JColorChooser/Test4887836.java new file mode 100644 index 00000000000..3c6bb3832de --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test4887836.java @@ -0,0 +1,43 @@ +/* + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4887836 + * @summary Checks if no tooltip modification when no KeyStroke modifier + * @author Konstantin Eremin + * @run applet/manual=yesno Test4887836.html + */ + +import java.awt.Color; +import java.awt.Font; +import javax.swing.JApplet; +import javax.swing.JColorChooser; +import javax.swing.UIManager; + +public class Test4887836 extends JApplet { + public void init() { + UIManager.put("Label.font", new Font("Perpetua", 0, 36)); // NON-NLS: property and font names + add(new JColorChooser(Color.LIGHT_GRAY)); + } +} From 19fc7593d1504862e6d813750578d0d1f46587a7 Mon Sep 17 00:00:00 2001 From: Jean-Christophe Collet Date: Tue, 1 Jul 2008 13:29:36 +0200 Subject: [PATCH 015/325] 6713809: FTP fails from multi-homed system Binds the data socket to the same address as the control socket Reviewed-by: michaelm --- jdk/src/share/classes/sun/net/ftp/FtpClient.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/sun/net/ftp/FtpClient.java b/jdk/src/share/classes/sun/net/ftp/FtpClient.java index 9a7c99d517d..a93489f4b60 100644 --- a/jdk/src/share/classes/sun/net/ftp/FtpClient.java +++ b/jdk/src/share/classes/sun/net/ftp/FtpClient.java @@ -352,6 +352,9 @@ public class FtpClient extends TransferProtocolClient { s = new Socket(Proxy.NO_PROXY); } else s = new Socket(); + // Bind the socket to the same address as the control channel. This + // is needed in case of multi-homed systems. + s.bind(new InetSocketAddress(serverSocket.getLocalAddress(),0)); if (connectTimeout >= 0) { s.connect(dest, connectTimeout); } else { @@ -417,8 +420,10 @@ public class FtpClient extends TransferProtocolClient { // since we can't accept a connection through SOCKS (yet) // throw an exception throw new FtpProtocolException("Passive mode failed"); - } else - portSocket = new ServerSocket(0, 1); + } + // Bind the ServerSocket to the same address as the control channel + // This is needed for multi-homed systems + portSocket = new ServerSocket(0, 1, serverSocket.getLocalAddress()); try { myAddress = portSocket.getInetAddress(); if (myAddress.isAnyLocalAddress()) From 3fce795f6c2f6f7562445e89abe2e7c11db432b4 Mon Sep 17 00:00:00 2001 From: Jean-Christophe Collet Date: Tue, 1 Jul 2008 13:38:59 +0200 Subject: [PATCH 016/325] 6656849: NullPointerException thrown while de-serializing IPV6 Address Check for existence of interface name earlier in code Reviewed-by: michaelm --- .../share/classes/java/net/Inet6Address.java | 60 +++++++++++------- .../net/Inet6Address/serialize/Readme.txt | 6 ++ .../net/Inet6Address/serialize/Serialize.java | 22 +++++-- .../Inet6Address/serialize/serial-bge0.ser | Bin 0 -> 266 bytes 4 files changed, 57 insertions(+), 31 deletions(-) create mode 100644 jdk/test/java/net/Inet6Address/serialize/Readme.txt create mode 100644 jdk/test/java/net/Inet6Address/serialize/serial-bge0.ser diff --git a/jdk/src/share/classes/java/net/Inet6Address.java b/jdk/src/share/classes/java/net/Inet6Address.java index 299d55e5f06..0778f5a02fe 100644 --- a/jdk/src/share/classes/java/net/Inet6Address.java +++ b/jdk/src/share/classes/java/net/Inet6Address.java @@ -25,12 +25,9 @@ package java.net; -import java.security.AccessController; import java.io.ObjectInputStream; import java.io.IOException; -import java.io.ObjectStreamException; import java.io.InvalidObjectException; -import sun.security.action.*; import java.util.Enumeration; /** @@ -358,13 +355,13 @@ class Inet6Address extends InetAddress { } private int deriveNumericScope (NetworkInterface ifc) throws UnknownHostException { - Enumeration addresses = ifc.getInetAddresses(); + Enumeration addresses = ifc.getInetAddresses(); while (addresses.hasMoreElements()) { - InetAddress address = (InetAddress)addresses.nextElement(); - if (!(address instanceof Inet6Address)) { + InetAddress addr = addresses.nextElement(); + if (!(addr instanceof Inet6Address)) { continue; } - Inet6Address ia6_addr = (Inet6Address)address; + Inet6Address ia6_addr = (Inet6Address)addr; /* check if site or link local prefixes match */ if (!differentLocalAddressTypes(ia6_addr)){ /* type not the same, so carry on searching */ @@ -377,22 +374,22 @@ class Inet6Address extends InetAddress { } private int deriveNumericScope (String ifname) throws UnknownHostException { - Enumeration en; + Enumeration en; try { en = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { throw new UnknownHostException ("could not enumerate local network interfaces"); } while (en.hasMoreElements()) { - NetworkInterface ifc = (NetworkInterface)en.nextElement(); + NetworkInterface ifc = en.nextElement(); if (ifc.getName().equals (ifname)) { Enumeration addresses = ifc.getInetAddresses(); while (addresses.hasMoreElements()) { - InetAddress address = (InetAddress)addresses.nextElement(); - if (!(address instanceof Inet6Address)) { + InetAddress addr = (InetAddress)addresses.nextElement(); + if (!(addr instanceof Inet6Address)) { continue; } - Inet6Address ia6_addr = (Inet6Address)address; + Inet6Address ia6_addr = (Inet6Address)addr; /* check if site or link local prefixes match */ if (!differentLocalAddressTypes(ia6_addr)){ /* type not the same, so carry on searching */ @@ -420,21 +417,22 @@ class Inet6Address extends InetAddress { if (ifname != null && !"".equals (ifname)) { try { scope_ifname = NetworkInterface.getByName(ifname); - try { - scope_id = deriveNumericScope (scope_ifname); - } catch (UnknownHostException e) { - // should not happen - assert false; + if (scope_ifname == null) { + /* the interface does not exist on this system, so we clear + * the scope information completely */ + scope_id_set = false; + scope_ifname_set = false; + scope_id = 0; + } else { + try { + scope_id = deriveNumericScope (scope_ifname); + } catch (UnknownHostException e) { + // should not happen + assert false; + } } } catch (SocketException e) {} - if (scope_ifname == null) { - /* the interface does not exist on this system, so we clear - * the scope information completely */ - scope_id_set = false; - scope_ifname_set = false; - scope_id = 0; - } } /* if ifname was not supplied, then the numeric info is used */ @@ -460,6 +458,7 @@ class Inet6Address extends InetAddress { * an IP multicast address * @since JDK1.1 */ + @Override public boolean isMulticastAddress() { return ((ipaddress[0] & 0xff) == 0xff); } @@ -470,6 +469,7 @@ class Inet6Address extends InetAddress { * a wildcard address. * @since 1.4 */ + @Override public boolean isAnyLocalAddress() { byte test = 0x00; for (int i = 0; i < INADDRSZ; i++) { @@ -485,6 +485,7 @@ class Inet6Address extends InetAddress { * a loopback address; or false otherwise. * @since 1.4 */ + @Override public boolean isLoopbackAddress() { byte test = 0x00; for (int i = 0; i < 15; i++) { @@ -500,6 +501,7 @@ class Inet6Address extends InetAddress { * a link local address; or false if address is not a link local unicast address. * @since 1.4 */ + @Override public boolean isLinkLocalAddress() { return ((ipaddress[0] & 0xff) == 0xfe && (ipaddress[1] & 0xc0) == 0x80); @@ -512,6 +514,7 @@ class Inet6Address extends InetAddress { * a site local address; or false if address is not a site local unicast address. * @since 1.4 */ + @Override public boolean isSiteLocalAddress() { return ((ipaddress[0] & 0xff) == 0xfe && (ipaddress[1] & 0xc0) == 0xc0); @@ -525,6 +528,7 @@ class Inet6Address extends InetAddress { * of global scope or it is not a multicast address * @since 1.4 */ + @Override public boolean isMCGlobal() { return ((ipaddress[0] & 0xff) == 0xff && (ipaddress[1] & 0x0f) == 0x0e); @@ -538,6 +542,7 @@ class Inet6Address extends InetAddress { * of node-local scope or it is not a multicast address * @since 1.4 */ + @Override public boolean isMCNodeLocal() { return ((ipaddress[0] & 0xff) == 0xff && (ipaddress[1] & 0x0f) == 0x01); @@ -551,6 +556,7 @@ class Inet6Address extends InetAddress { * of link-local scope or it is not a multicast address * @since 1.4 */ + @Override public boolean isMCLinkLocal() { return ((ipaddress[0] & 0xff) == 0xff && (ipaddress[1] & 0x0f) == 0x02); @@ -564,6 +570,7 @@ class Inet6Address extends InetAddress { * of site-local scope or it is not a multicast address * @since 1.4 */ + @Override public boolean isMCSiteLocal() { return ((ipaddress[0] & 0xff) == 0xff && (ipaddress[1] & 0x0f) == 0x05); @@ -578,6 +585,7 @@ class Inet6Address extends InetAddress { * or it is not a multicast address * @since 1.4 */ + @Override public boolean isMCOrgLocal() { return ((ipaddress[0] & 0xff) == 0xff && (ipaddress[1] & 0x0f) == 0x08); @@ -590,6 +598,7 @@ class Inet6Address extends InetAddress { * * @return the raw IP address of this object. */ + @Override public byte[] getAddress() { return ipaddress.clone(); } @@ -624,6 +633,7 @@ class Inet6Address extends InetAddress { * * @return the raw IP address in a string format. */ + @Override public String getHostAddress() { String s = numericToTextFormat(ipaddress); if (scope_ifname_set) { /* must check this first */ @@ -639,6 +649,7 @@ class Inet6Address extends InetAddress { * * @return a hash code value for this IP address. */ + @Override public int hashCode() { if (ipaddress != null) { @@ -677,6 +688,7 @@ class Inet6Address extends InetAddress { * false otherwise. * @see java.net.InetAddress#getAddress() */ + @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Inet6Address)) diff --git a/jdk/test/java/net/Inet6Address/serialize/Readme.txt b/jdk/test/java/net/Inet6Address/serialize/Readme.txt new file mode 100644 index 00000000000..4335bbd206f --- /dev/null +++ b/jdk/test/java/net/Inet6Address/serialize/Readme.txt @@ -0,0 +1,6 @@ +This test uses 2 binary data files that were each created by serializing an Inet6Address instance. +In both cases this has to do with the tricky issue of scopes in serialized addresses. + +serial1.4.2.ser: Was created by serializing an Inet6Address (::1) with J2SE 1.4.2 and is used to check for backward compatibility. + +serial-bge0.ser: Was created on a Sparc workstation because it has an uncommon interface name ('bge0') which is useful for the test. diff --git a/jdk/test/java/net/Inet6Address/serialize/Serialize.java b/jdk/test/java/net/Inet6Address/serialize/Serialize.java index d97149b79a1..17b5500576c 100644 --- a/jdk/test/java/net/Inet6Address/serialize/Serialize.java +++ b/jdk/test/java/net/Inet6Address/serialize/Serialize.java @@ -24,7 +24,9 @@ /** * @test * @bug 4921029 + * @bug 6656849 * @summary java.net.Inet6Address fails to be serialized with IPv6 support + * @summary NullPointerException thrown while de-serializing IPV6 Address. */ import java.net.*; @@ -76,11 +78,20 @@ public class Serialize { System.out.println(nobj); - // create an address with an unlikely numeric scope_id - if (!test ((Inet6Address)InetAddress.getByName ("fe80::1%99"))) { - throw new RuntimeException ("test failed on fe80::1%99"); - } + // create an address with an unlikely numeric scope_id + if (!test ((Inet6Address)InetAddress.getByName ("fe80::1%99"))) { + throw new RuntimeException ("test failed on fe80::1%99"); + } + // Deserialize an Inet6 address with a named interface + file = new File (System.getProperty("test.src"), "serial-bge0.ser"); + ois = new ObjectInputStream(new FileInputStream(file)); + try { + nobj = (Inet6Address) ois.readObject(); + } catch (NullPointerException e) { + throw new RuntimeException("6656849 Not fixed: NullPointer when deserializing"); + } + System.out.println(nobj); System.out.println("All tests passed"); } @@ -97,8 +108,5 @@ public class Serialize { } else { return false; } - - } - } diff --git a/jdk/test/java/net/Inet6Address/serialize/serial-bge0.ser b/jdk/test/java/net/Inet6Address/serialize/serial-bge0.ser new file mode 100644 index 0000000000000000000000000000000000000000..4382d7d1e8fb56bdcba2d44c6f5b67931cf16f9b GIT binary patch literal 266 zcmZ4UmVvdnh(R Date: Wed, 2 Jul 2008 18:17:56 +0400 Subject: [PATCH 017/325] 6618401: Input method cannot be selected from System menu Lock.wait() added in sun.awt.im.InputMethodManager.showInputMethodMenuOnRequesterEDT() Reviewed-by: alexp --- jdk/src/share/classes/sun/awt/im/InputMethodManager.java | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/src/share/classes/sun/awt/im/InputMethodManager.java b/jdk/src/share/classes/sun/awt/im/InputMethodManager.java index f95b13c63ab..caba8d6a152 100644 --- a/jdk/src/share/classes/sun/awt/im/InputMethodManager.java +++ b/jdk/src/share/classes/sun/awt/im/InputMethodManager.java @@ -358,6 +358,7 @@ class ExecutableInputMethodManager extends InputMethodManager AppContext requesterAppContext = SunToolkit.targetToAppContext(requester); synchronized (lock) { SunToolkit.postEvent(requesterAppContext, event); + lock.wait(); } Throwable eventThrowable = event.getThrowable(); From 696e17c0ba6b44d02c806a89ff537f09f4b7f925 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 3 Jul 2008 18:02:47 -0700 Subject: [PATCH 018/325] 6684714: Optimize EA Connection Graph build performance Switch on EA by default, optimize Connection Graph construction Reviewed-by: rasbold, never --- hotspot/src/share/vm/compiler/oopMap.cpp | 21 +- hotspot/src/share/vm/compiler/oopMap.hpp | 8 +- hotspot/src/share/vm/opto/bytecodeInfo.cpp | 2 +- hotspot/src/share/vm/opto/c2_globals.hpp | 2 +- hotspot/src/share/vm/opto/compile.cpp | 16 +- hotspot/src/share/vm/opto/escape.cpp | 474 +++++++++++---------- hotspot/src/share/vm/opto/escape.hpp | 52 ++- 7 files changed, 290 insertions(+), 285 deletions(-) diff --git a/hotspot/src/share/vm/compiler/oopMap.cpp b/hotspot/src/share/vm/compiler/oopMap.cpp index 2984d647ea8..78bef1836c8 100644 --- a/hotspot/src/share/vm/compiler/oopMap.cpp +++ b/hotspot/src/share/vm/compiler/oopMap.cpp @@ -188,10 +188,6 @@ void OopMap::set_derived_oop(VMReg reg, VMReg derived_from_local_register ) { } } -void OopMap::set_stack_obj(VMReg reg) { - set_xxx(reg, OopMapValue::stack_obj, VMRegImpl::Bad()); -} - // OopMapSet OopMapSet::OopMapSet() { @@ -399,8 +395,7 @@ void OopMapSet::all_do(const frame *fr, const RegisterMap *reg_map, if ( loc != NULL ) { if ( omv.type() == OopMapValue::oop_value ) { #ifdef ASSERT - if (COMPILER2_PRESENT(!DoEscapeAnalysis &&) - (((uintptr_t)loc & (sizeof(*loc)-1)) != 0) || + if ((((uintptr_t)loc & (sizeof(*loc)-1)) != 0) || !Universe::heap()->is_in_or_null(*loc)) { tty->print_cr("# Found non oop pointer. Dumping state at failure"); // try to dump out some helpful debugging information @@ -431,17 +426,6 @@ void OopMapSet::all_do(const frame *fr, const RegisterMap *reg_map, } } } - -#ifdef COMPILER2 - if (DoEscapeAnalysis) { - for (OopMapStream oms(map, OopMapValue::stack_obj); !oms.is_done(); oms.next()) { - omv = oms.current(); - assert(omv.is_stack_loc(), "should refer to stack location"); - oop loc = (oop) fr->oopmapreg_to_location(omv.reg(),reg_map); - oop_fn->do_oop(&loc); - } - } -#endif // COMPILER2 } @@ -540,9 +524,6 @@ void print_register_type(OopMapValue::oop_types x, VMReg optional, st->print("Derived_oop_" ); optional->print_on(st); break; - case OopMapValue::stack_obj: - st->print("Stack"); - break; default: ShouldNotReachHere(); } diff --git a/hotspot/src/share/vm/compiler/oopMap.hpp b/hotspot/src/share/vm/compiler/oopMap.hpp index ac05d570c04..bce97de176c 100644 --- a/hotspot/src/share/vm/compiler/oopMap.hpp +++ b/hotspot/src/share/vm/compiler/oopMap.hpp @@ -46,7 +46,7 @@ private: public: // Constants - enum { type_bits = 6, + enum { type_bits = 5, register_bits = BitsPerShort - type_bits }; enum { type_shift = 0, @@ -63,8 +63,7 @@ public: value_value = 2, narrowoop_value = 4, callee_saved_value = 8, - derived_oop_value= 16, - stack_obj = 32 }; + derived_oop_value= 16 }; // Constructors OopMapValue () { set_value(0); set_content_reg(VMRegImpl::Bad()); } @@ -93,14 +92,12 @@ public: bool is_narrowoop() { return mask_bits(value(), type_mask_in_place) == narrowoop_value; } bool is_callee_saved() { return mask_bits(value(), type_mask_in_place) == callee_saved_value; } bool is_derived_oop() { return mask_bits(value(), type_mask_in_place) == derived_oop_value; } - bool is_stack_obj() { return mask_bits(value(), type_mask_in_place) == stack_obj; } void set_oop() { set_value((value() & register_mask_in_place) | oop_value); } void set_value() { set_value((value() & register_mask_in_place) | value_value); } void set_narrowoop() { set_value((value() & register_mask_in_place) | narrowoop_value); } void set_callee_saved() { set_value((value() & register_mask_in_place) | callee_saved_value); } void set_derived_oop() { set_value((value() & register_mask_in_place) | derived_oop_value); } - void set_stack_obj() { set_value((value() & register_mask_in_place) | stack_obj); } VMReg reg() const { return VMRegImpl::as_VMReg(mask_bits(value(), register_mask_in_place) >> register_shift); } oop_types type() const { return (oop_types)mask_bits(value(), type_mask_in_place); } @@ -180,7 +177,6 @@ class OopMap: public ResourceObj { void set_dead ( VMReg local); void set_callee_saved( VMReg local, VMReg caller_machine_register ); void set_derived_oop ( VMReg local, VMReg derived_from_local_register ); - void set_stack_obj( VMReg local); void set_xxx(VMReg reg, OopMapValue::oop_types x, VMReg optional); int heap_size() const; diff --git a/hotspot/src/share/vm/opto/bytecodeInfo.cpp b/hotspot/src/share/vm/opto/bytecodeInfo.cpp index 1b12ee877ad..b1fe31aed2e 100644 --- a/hotspot/src/share/vm/opto/bytecodeInfo.cpp +++ b/hotspot/src/share/vm/opto/bytecodeInfo.cpp @@ -83,7 +83,7 @@ static bool is_init_with_ea(ciMethod* callee_method, ciMethod* caller_method, Compile* C) { // True when EA is ON and a java constructor is called or // a super constructor is called from an inlined java constructor. - return DoEscapeAnalysis && EliminateAllocations && + return C->do_escape_analysis() && EliminateAllocations && ( callee_method->is_initializer() || (caller_method->is_initializer() && caller_method != C->method() && diff --git a/hotspot/src/share/vm/opto/c2_globals.hpp b/hotspot/src/share/vm/opto/c2_globals.hpp index 691914e2b0a..7cdf24bdc23 100644 --- a/hotspot/src/share/vm/opto/c2_globals.hpp +++ b/hotspot/src/share/vm/opto/c2_globals.hpp @@ -373,7 +373,7 @@ product(intx, AutoBoxCacheMax, 128, \ "Sets max value cached by the java.lang.Integer autobox cache") \ \ - product(bool, DoEscapeAnalysis, false, \ + product(bool, DoEscapeAnalysis, true, \ "Perform escape analysis") \ \ notproduct(bool, PrintEscapeAnalysis, false, \ diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp index 019ca50ae59..f193d5d2d11 100644 --- a/hotspot/src/share/vm/opto/compile.cpp +++ b/hotspot/src/share/vm/opto/compile.cpp @@ -583,18 +583,22 @@ Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr NOT_PRODUCT( verify_graph_edges(); ) // Perform escape analysis - if (_do_escape_analysis) - _congraph = new ConnectionGraph(this); - if (_congraph != NULL) { - NOT_PRODUCT( TracePhase t2("escapeAnalysis", &_t_escapeAnalysis, TimeCompiler); ) - _congraph->compute_escape(); - if (failing()) return; + if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) { + TracePhase t2("escapeAnalysis", &_t_escapeAnalysis, true); + + _congraph = new(comp_arena()) ConnectionGraph(this); + bool has_non_escaping_obj = _congraph->compute_escape(); #ifndef PRODUCT if (PrintEscapeAnalysis) { _congraph->dump(); } #endif + if (!has_non_escaping_obj) { + _congraph = NULL; + } + + if (failing()) return; } // Now optimize Optimize(); diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index ad6c8826270..7fee3d3d44f 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -25,16 +25,6 @@ #include "incls/_precompiled.incl" #include "incls/_escape.cpp.incl" -uint PointsToNode::edge_target(uint e) const { - assert(_edges != NULL && e < (uint)_edges->length(), "valid edge index"); - return (_edges->at(e) >> EdgeShift); -} - -PointsToNode::EdgeType PointsToNode::edge_type(uint e) const { - assert(_edges != NULL && e < (uint)_edges->length(), "valid edge index"); - return (EdgeType) (_edges->at(e) & EdgeMask); -} - void PointsToNode::add_edge(uint targIdx, PointsToNode::EdgeType et) { uint v = (targIdx << EdgeShift) + ((uint) et); if (_edges == NULL) { @@ -87,12 +77,13 @@ void PointsToNode::dump() const { } #endif -ConnectionGraph::ConnectionGraph(Compile * C) : _processed(C->comp_arena()), _node_map(C->comp_arena()) { - _collecting = true; - this->_compile = C; - const PointsToNode &dummy = PointsToNode(); - int sz = C->unique(); - _nodes = new(C->comp_arena()) GrowableArray(C->comp_arena(), sz, sz, dummy); +ConnectionGraph::ConnectionGraph(Compile * C) : + _nodes(C->comp_arena(), C->unique(), C->unique(), PointsToNode()), + _processed(C->comp_arena()), + _collecting(true), + _compile(C), + _node_map(C->comp_arena()) { + _phantom_object = C->top()->_idx; PointsToNode *phn = ptnode_adr(_phantom_object); phn->_node = C->top(); @@ -182,32 +173,36 @@ PointsToNode::EscapeState ConnectionGraph::escape_state(Node *n, PhaseTransform // If we are still collecting or there were no non-escaping allocations // we don't know the answer yet - if (_collecting || !_has_allocations) + if (_collecting) return PointsToNode::UnknownEscape; // if the node was created after the escape computation, return // UnknownEscape - if (idx >= (uint)_nodes->length()) + if (idx >= nodes_size()) return PointsToNode::UnknownEscape; - es = _nodes->at_grow(idx).escape_state(); + es = ptnode_adr(idx)->escape_state(); // if we have already computed a value, return it if (es != PointsToNode::UnknownEscape) return es; + // PointsTo() calls n->uncast() which can return a new ideal node. + if (n->uncast()->_idx >= nodes_size()) + return PointsToNode::UnknownEscape; + // compute max escape state of anything this node could point to VectorSet ptset(Thread::current()->resource_area()); PointsTo(ptset, n, phase); for(VectorSetI i(&ptset); i.test() && es != PointsToNode::GlobalEscape; ++i) { uint pt = i.elem; - PointsToNode::EscapeState pes = _nodes->adr_at(pt)->escape_state(); + PointsToNode::EscapeState pes = ptnode_adr(pt)->escape_state(); if (pes > es) es = pes; } // cache the computed escape state assert(es != PointsToNode::UnknownEscape, "should have computed an escape state"); - _nodes->adr_at(idx)->set_escape_state(es); + ptnode_adr(idx)->set_escape_state(es); return es; } @@ -220,49 +215,51 @@ void ConnectionGraph::PointsTo(VectorSet &ptset, Node * n, PhaseTransform *phase #endif n = n->uncast(); - PointsToNode npt = _nodes->at_grow(n->_idx); + PointsToNode* npt = ptnode_adr(n->_idx); // If we have a JavaObject, return just that object - if (npt.node_type() == PointsToNode::JavaObject) { + if (npt->node_type() == PointsToNode::JavaObject) { ptset.set(n->_idx); return; } #ifdef ASSERT - if (npt._node == NULL) { + if (npt->_node == NULL) { if (orig_n != n) orig_n->dump(); n->dump(); - assert(npt._node != NULL, "unregistered node"); + assert(npt->_node != NULL, "unregistered node"); } #endif worklist.push(n->_idx); while(worklist.length() > 0) { int ni = worklist.pop(); - PointsToNode pn = _nodes->at_grow(ni); - if (!visited.test_set(ni)) { - // ensure that all inputs of a Phi have been processed - assert(!_collecting || !pn._node->is_Phi() || _processed.test(ni),""); + if (visited.test_set(ni)) + continue; - int edges_processed = 0; - for (uint e = 0; e < pn.edge_count(); e++) { - uint etgt = pn.edge_target(e); - PointsToNode::EdgeType et = pn.edge_type(e); - if (et == PointsToNode::PointsToEdge) { - ptset.set(etgt); - edges_processed++; - } else if (et == PointsToNode::DeferredEdge) { - worklist.push(etgt); - edges_processed++; - } else { - assert(false,"neither PointsToEdge or DeferredEdge"); - } - } - if (edges_processed == 0) { - // no deferred or pointsto edges found. Assume the value was set - // outside this method. Add the phantom object to the pointsto set. - ptset.set(_phantom_object); + PointsToNode* pn = ptnode_adr(ni); + // ensure that all inputs of a Phi have been processed + assert(!_collecting || !pn->_node->is_Phi() || _processed.test(ni),""); + + int edges_processed = 0; + uint e_cnt = pn->edge_count(); + for (uint e = 0; e < e_cnt; e++) { + uint etgt = pn->edge_target(e); + PointsToNode::EdgeType et = pn->edge_type(e); + if (et == PointsToNode::PointsToEdge) { + ptset.set(etgt); + edges_processed++; + } else if (et == PointsToNode::DeferredEdge) { + worklist.push(etgt); + edges_processed++; + } else { + assert(false,"neither PointsToEdge or DeferredEdge"); } } + if (edges_processed == 0) { + // no deferred or pointsto edges found. Assume the value was set + // outside this method. Add the phantom object to the pointsto set. + ptset.set(_phantom_object); + } } } @@ -272,11 +269,11 @@ void ConnectionGraph::remove_deferred(uint ni, GrowableArray* deferred_edg deferred_edges->clear(); visited->Clear(); - uint i = 0; + visited->set(ni); PointsToNode *ptn = ptnode_adr(ni); // Mark current edges as visited and move deferred edges to separate array. - while (i < ptn->edge_count()) { + for (uint i = 0; i < ptn->edge_count(); ) { uint t = ptn->edge_target(i); #ifdef ASSERT assert(!visited->test_set(t), "expecting no duplications"); @@ -293,24 +290,23 @@ void ConnectionGraph::remove_deferred(uint ni, GrowableArray* deferred_edg for (int next = 0; next < deferred_edges->length(); ++next) { uint t = deferred_edges->at(next); PointsToNode *ptt = ptnode_adr(t); - for (uint j = 0; j < ptt->edge_count(); j++) { - uint n1 = ptt->edge_target(j); - if (visited->test_set(n1)) + uint e_cnt = ptt->edge_count(); + for (uint e = 0; e < e_cnt; e++) { + uint etgt = ptt->edge_target(e); + if (visited->test_set(etgt)) continue; - switch(ptt->edge_type(j)) { - case PointsToNode::PointsToEdge: - add_pointsto_edge(ni, n1); - if(n1 == _phantom_object) { - // Special case - field set outside (globally escaping). - ptn->set_escape_state(PointsToNode::GlobalEscape); - } - break; - case PointsToNode::DeferredEdge: - deferred_edges->append(n1); - break; - case PointsToNode::FieldEdge: - assert(false, "invalid connection graph"); - break; + + PointsToNode::EdgeType et = ptt->edge_type(e); + if (et == PointsToNode::PointsToEdge) { + add_pointsto_edge(ni, etgt); + if(etgt == _phantom_object) { + // Special case - field set outside (globally escaping). + ptn->set_escape_state(PointsToNode::GlobalEscape); + } + } else if (et == PointsToNode::DeferredEdge) { + deferred_edges->append(etgt); + } else { + assert(false,"invalid connection graph"); } } } @@ -322,15 +318,15 @@ void ConnectionGraph::remove_deferred(uint ni, GrowableArray* deferred_edg // a pointsto edge is added if it is a JavaObject void ConnectionGraph::add_edge_from_fields(uint adr_i, uint to_i, int offs) { - PointsToNode an = _nodes->at_grow(adr_i); - PointsToNode to = _nodes->at_grow(to_i); - bool deferred = (to.node_type() == PointsToNode::LocalVar); + PointsToNode* an = ptnode_adr(adr_i); + PointsToNode* to = ptnode_adr(to_i); + bool deferred = (to->node_type() == PointsToNode::LocalVar); - for (uint fe = 0; fe < an.edge_count(); fe++) { - assert(an.edge_type(fe) == PointsToNode::FieldEdge, "expecting a field edge"); - int fi = an.edge_target(fe); - PointsToNode pf = _nodes->at_grow(fi); - int po = pf.offset(); + for (uint fe = 0; fe < an->edge_count(); fe++) { + assert(an->edge_type(fe) == PointsToNode::FieldEdge, "expecting a field edge"); + int fi = an->edge_target(fe); + PointsToNode* pf = ptnode_adr(fi); + int po = pf->offset(); if (po == offs || po == Type::OffsetBot || offs == Type::OffsetBot) { if (deferred) add_deferred_edge(fi, to_i); @@ -343,13 +339,13 @@ void ConnectionGraph::add_edge_from_fields(uint adr_i, uint to_i, int offs) { // Add a deferred edge from node given by "from_i" to any field of adr_i // whose offset matches "offset". void ConnectionGraph::add_deferred_edge_to_fields(uint from_i, uint adr_i, int offs) { - PointsToNode an = _nodes->at_grow(adr_i); - for (uint fe = 0; fe < an.edge_count(); fe++) { - assert(an.edge_type(fe) == PointsToNode::FieldEdge, "expecting a field edge"); - int fi = an.edge_target(fe); - PointsToNode pf = _nodes->at_grow(fi); - int po = pf.offset(); - if (pf.edge_count() == 0) { + PointsToNode* an = ptnode_adr(adr_i); + for (uint fe = 0; fe < an->edge_count(); fe++) { + assert(an->edge_type(fe) == PointsToNode::FieldEdge, "expecting a field edge"); + int fi = an->edge_target(fe); + PointsToNode* pf = ptnode_adr(fi); + int po = pf->offset(); + if (pf->edge_count() == 0) { // we have not seen any stores to this field, assume it was set outside this method add_pointsto_edge(fi, _phantom_object); } @@ -835,6 +831,11 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) // Phase 1: Process possible allocations from alloc_worklist. // Create instance types for the CheckCastPP for allocations where possible. + // + // (Note: don't forget to change the order of the second AddP node on + // the alloc_worklist if the order of the worklist processing is changed, + // see the comment in find_second_addp().) + // while (alloc_worklist.length() != 0) { Node *n = alloc_worklist.pop(); uint ni = n->_idx; @@ -842,7 +843,7 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) if (n->is_Call()) { CallNode *alloc = n->as_Call(); // copy escape information to call node - PointsToNode* ptn = _nodes->adr_at(alloc->_idx); + PointsToNode* ptn = ptnode_adr(alloc->_idx); PointsToNode::EscapeState es = escape_state(alloc, igvn); // We have an allocation or call which returns a Java object, // see if it is unescaped. @@ -899,7 +900,7 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) // First, put on the worklist all Field edges from Connection Graph // which is more accurate then putting immediate users from Ideal Graph. for (uint e = 0; e < ptn->edge_count(); e++) { - Node *use = _nodes->adr_at(ptn->edge_target(e))->_node; + Node *use = ptnode_adr(ptn->edge_target(e))->_node; assert(ptn->edge_type(e) == PointsToNode::FieldEdge && use->is_AddP(), "only AddP nodes are Field edges in CG"); if (use->outcnt() > 0) { // Don't process dead nodes @@ -1062,7 +1063,7 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) } if (mem != n->in(MemNode::Memory)) { set_map(n->_idx, mem); - _nodes->adr_at(n->_idx)->_node = n; + ptnode_adr(n->_idx)->_node = n; } if (n->is_Load()) { continue; // don't push users @@ -1223,10 +1224,10 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) // Update the memory inputs of MemNodes with the value we computed // in Phase 2. - for (int i = 0; i < _nodes->length(); i++) { + for (uint i = 0; i < nodes_size(); i++) { Node *nmem = get_map(i); if (nmem != NULL) { - Node *n = _nodes->adr_at(i)->_node; + Node *n = ptnode_adr(i)->_node; if (n != NULL && n->is_Mem()) { igvn->hash_delete(n); n->set_req(MemNode::Memory, nmem); @@ -1237,28 +1238,48 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) } } -void ConnectionGraph::compute_escape() { +bool ConnectionGraph::has_candidates(Compile *C) { + // EA brings benefits only when the code has allocations and/or locks which + // are represented by ideal Macro nodes. + int cnt = C->macro_count(); + for( int i=0; i < cnt; i++ ) { + Node *n = C->macro_node(i); + if ( n->is_Allocate() ) + return true; + if( n->is_Lock() ) { + Node* obj = n->as_Lock()->obj_node()->uncast(); + if( !(obj->is_Parm() || obj->is_Con()) ) + return true; + } + } + return false; +} + +bool ConnectionGraph::compute_escape() { + Compile* C = _compile; // 1. Populate Connection Graph (CG) with Ideal nodes. Unique_Node_List worklist_init; - worklist_init.map(_compile->unique(), NULL); // preallocate space + worklist_init.map(C->unique(), NULL); // preallocate space // Initialize worklist - if (_compile->root() != NULL) { - worklist_init.push(_compile->root()); + if (C->root() != NULL) { + worklist_init.push(C->root()); } GrowableArray cg_worklist; - PhaseGVN* igvn = _compile->initial_gvn(); + PhaseGVN* igvn = C->initial_gvn(); bool has_allocations = false; // Push all useful nodes onto CG list and set their type. for( uint next = 0; next < worklist_init.size(); ++next ) { Node* n = worklist_init.at(next); record_for_escape_analysis(n, igvn); - if (n->is_Call() && - _nodes->adr_at(n->_idx)->node_type() == PointsToNode::JavaObject) { + // Only allocations and java static calls results are checked + // for an escape status. See process_call_result() below. + if (n->is_Allocate() || n->is_CallStaticJava() && + ptnode_adr(n->_idx)->node_type() == PointsToNode::JavaObject) { has_allocations = true; } if(n->is_AddP()) @@ -1269,24 +1290,23 @@ void ConnectionGraph::compute_escape() { } } - if (has_allocations) { - _has_allocations = true; - } else { - _has_allocations = false; + if (!has_allocations) { _collecting = false; - return; // Nothing to do. + return false; // Nothing to do. } // 2. First pass to create simple CG edges (doesn't require to walk CG). - for( uint next = 0; next < _delayed_worklist.size(); ++next ) { + uint delayed_size = _delayed_worklist.size(); + for( uint next = 0; next < delayed_size; ++next ) { Node* n = _delayed_worklist.at(next); build_connection_graph(n, igvn); } // 3. Pass to create fields edges (Allocate -F-> AddP). - for( int next = 0; next < cg_worklist.length(); ++next ) { + uint cg_length = cg_worklist.length(); + for( uint next = 0; next < cg_length; ++next ) { int ni = cg_worklist.at(next); - build_connection_graph(_nodes->adr_at(ni)->_node, igvn); + build_connection_graph(ptnode_adr(ni)->_node, igvn); } cg_worklist.clear(); @@ -1294,8 +1314,8 @@ void ConnectionGraph::compute_escape() { // 4. Build Connection Graph which need // to walk the connection graph. - for (uint ni = 0; ni < (uint)_nodes->length(); ni++) { - PointsToNode* ptn = _nodes->adr_at(ni); + for (uint ni = 0; ni < nodes_size(); ni++) { + PointsToNode* ptn = ptnode_adr(ni); Node *n = ptn->_node; if (n != NULL) { // Call, AddP, LoadP, StoreP build_connection_graph(n, igvn); @@ -1305,20 +1325,19 @@ void ConnectionGraph::compute_escape() { } VectorSet ptset(Thread::current()->resource_area()); - GrowableArray alloc_worklist; - GrowableArray worklist; GrowableArray deferred_edges; VectorSet visited(Thread::current()->resource_area()); - // remove deferred edges from the graph and collect - // information we will need for type splitting - for( int next = 0; next < cg_worklist.length(); ++next ) { + // 5. Remove deferred edges from the graph and collect + // information needed for type splitting. + cg_length = cg_worklist.length(); + for( uint next = 0; next < cg_length; ++next ) { int ni = cg_worklist.at(next); - PointsToNode* ptn = _nodes->adr_at(ni); + PointsToNode* ptn = ptnode_adr(ni); PointsToNode::NodeType nt = ptn->node_type(); - Node *n = ptn->_node; if (nt == PointsToNode::LocalVar || nt == PointsToNode::Field) { remove_deferred(ni, &deferred_edges, &visited); + Node *n = ptn->_node; if (n->is_AddP()) { // If this AddP computes an address which may point to more that one // object or more then one field (array's element), nothing the address @@ -1329,116 +1348,123 @@ void ConnectionGraph::compute_escape() { if (ptset.Size() > 1 || (ptset.Size() != 0 && ptn->offset() == Type::OffsetBot)) { for( VectorSetI j(&ptset); j.test(); ++j ) { - uint pt = j.elem; - ptnode_adr(pt)->_scalar_replaceable = false; + ptnode_adr(j.elem)->_scalar_replaceable = false; } } } - } else if (nt == PointsToNode::JavaObject && n->is_Call()) { - // Push call on alloc_worlist (alocations are calls) - // for processing by split_unique_types(). - alloc_worklist.append(n); } } + // 6. Propagate escape states. + GrowableArray worklist; + bool has_non_escaping_obj = false; + // push all GlobalEscape nodes on the worklist - for( int next = 0; next < cg_worklist.length(); ++next ) { + for( uint next = 0; next < cg_length; ++next ) { int nk = cg_worklist.at(next); - if (_nodes->adr_at(nk)->escape_state() == PointsToNode::GlobalEscape) - worklist.append(nk); + if (ptnode_adr(nk)->escape_state() == PointsToNode::GlobalEscape) + worklist.push(nk); } - // mark all node reachable from GlobalEscape nodes + // mark all nodes reachable from GlobalEscape nodes while(worklist.length() > 0) { - PointsToNode n = _nodes->at(worklist.pop()); - for (uint ei = 0; ei < n.edge_count(); ei++) { - uint npi = n.edge_target(ei); + PointsToNode* ptn = ptnode_adr(worklist.pop()); + uint e_cnt = ptn->edge_count(); + for (uint ei = 0; ei < e_cnt; ei++) { + uint npi = ptn->edge_target(ei); PointsToNode *np = ptnode_adr(npi); if (np->escape_state() < PointsToNode::GlobalEscape) { np->set_escape_state(PointsToNode::GlobalEscape); - worklist.append_if_missing(npi); + worklist.push(npi); } } } // push all ArgEscape nodes on the worklist - for( int next = 0; next < cg_worklist.length(); ++next ) { + for( uint next = 0; next < cg_length; ++next ) { int nk = cg_worklist.at(next); - if (_nodes->adr_at(nk)->escape_state() == PointsToNode::ArgEscape) + if (ptnode_adr(nk)->escape_state() == PointsToNode::ArgEscape) worklist.push(nk); } - // mark all node reachable from ArgEscape nodes + // mark all nodes reachable from ArgEscape nodes while(worklist.length() > 0) { - PointsToNode n = _nodes->at(worklist.pop()); - for (uint ei = 0; ei < n.edge_count(); ei++) { - uint npi = n.edge_target(ei); + PointsToNode* ptn = ptnode_adr(worklist.pop()); + if (ptn->node_type() == PointsToNode::JavaObject) + has_non_escaping_obj = true; // Non GlobalEscape + uint e_cnt = ptn->edge_count(); + for (uint ei = 0; ei < e_cnt; ei++) { + uint npi = ptn->edge_target(ei); PointsToNode *np = ptnode_adr(npi); if (np->escape_state() < PointsToNode::ArgEscape) { np->set_escape_state(PointsToNode::ArgEscape); - worklist.append_if_missing(npi); + worklist.push(npi); } } } + GrowableArray alloc_worklist; + // push all NoEscape nodes on the worklist - for( int next = 0; next < cg_worklist.length(); ++next ) { + for( uint next = 0; next < cg_length; ++next ) { int nk = cg_worklist.at(next); - if (_nodes->adr_at(nk)->escape_state() == PointsToNode::NoEscape) + if (ptnode_adr(nk)->escape_state() == PointsToNode::NoEscape) worklist.push(nk); } - // mark all node reachable from NoEscape nodes + // mark all nodes reachable from NoEscape nodes while(worklist.length() > 0) { - PointsToNode n = _nodes->at(worklist.pop()); - for (uint ei = 0; ei < n.edge_count(); ei++) { - uint npi = n.edge_target(ei); + PointsToNode* ptn = ptnode_adr(worklist.pop()); + if (ptn->node_type() == PointsToNode::JavaObject) + has_non_escaping_obj = true; // Non GlobalEscape + Node* n = ptn->_node; + if (n->is_Allocate() && ptn->_scalar_replaceable ) { + // Push scalar replaceable alocations on alloc_worklist + // for processing in split_unique_types(). + alloc_worklist.append(n); + } + uint e_cnt = ptn->edge_count(); + for (uint ei = 0; ei < e_cnt; ei++) { + uint npi = ptn->edge_target(ei); PointsToNode *np = ptnode_adr(npi); if (np->escape_state() < PointsToNode::NoEscape) { np->set_escape_state(PointsToNode::NoEscape); - worklist.append_if_missing(npi); + worklist.push(npi); } } } _collecting = false; + assert(C->unique() == nodes_size(), "there should be no new ideal nodes during ConnectionGraph build"); - has_allocations = false; // Are there scalar replaceable allocations? + bool has_scalar_replaceable_candidates = alloc_worklist.length() > 0; + if ( has_scalar_replaceable_candidates && + C->AliasLevel() >= 3 && EliminateAllocations ) { - for( int next = 0; next < alloc_worklist.length(); ++next ) { - Node* n = alloc_worklist.at(next); - uint ni = n->_idx; - PointsToNode* ptn = _nodes->adr_at(ni); - PointsToNode::EscapeState es = ptn->escape_state(); - if (ptn->escape_state() == PointsToNode::NoEscape && - ptn->_scalar_replaceable) { - has_allocations = true; - break; - } - } - if (!has_allocations) { - return; // Nothing to do. - } - - if(_compile->AliasLevel() >= 3 && EliminateAllocations) { // Now use the escape information to create unique types for - // unescaped objects + // scalar replaceable objects. split_unique_types(alloc_worklist); - if (_compile->failing()) return; + + if (C->failing()) return false; // Clean up after split unique types. ResourceMark rm; - PhaseRemoveUseless pru(_compile->initial_gvn(), _compile->for_igvn()); + PhaseRemoveUseless pru(C->initial_gvn(), C->for_igvn()); + + C->print_method("After Escape Analysis", 2); #ifdef ASSERT - } else if (PrintEscapeAnalysis || PrintEliminateAllocations) { + } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) { tty->print("=== No allocations eliminated for "); - C()->method()->print_short_name(); + C->method()->print_short_name(); if(!EliminateAllocations) { tty->print(" since EliminateAllocations is off ==="); - } else if(_compile->AliasLevel() < 3) { + } else if(!has_scalar_replaceable_candidates) { + tty->print(" since there are no scalar replaceable candidates ==="); + } else if(C->AliasLevel() < 3) { tty->print(" since AliasLevel < 3 ==="); } tty->cr(); #endif } + return has_non_escaping_obj; } void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *phase) { @@ -1538,7 +1564,7 @@ void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *pha } } if (copy_dependencies) - call_analyzer->copy_dependencies(C()->dependencies()); + call_analyzer->copy_dependencies(_compile->dependencies()); break; } } @@ -1561,7 +1587,6 @@ void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *pha for( VectorSetI j(&ptset); j.test(); ++j ) { uint pt = j.elem; set_escape_state(pt, PointsToNode::GlobalEscape); - PointsToNode *ptadr = ptnode_adr(pt); } } } @@ -1569,9 +1594,10 @@ void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *pha } } void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *phase) { - PointsToNode *ptadr = ptnode_adr(resproj->_idx); + CallNode *call = resproj->in(0)->as_Call(); + uint call_idx = call->_idx; + uint resproj_idx = resproj->_idx; - CallNode *call = resproj->in(0)->as_Call(); switch (call->Opcode()) { case Op_Allocate: { @@ -1587,7 +1613,6 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha ciKlass* cik = kt->klass(); ciInstanceKlass* ciik = cik->as_instance_klass(); - PointsToNode *ptadr = ptnode_adr(call->_idx); PointsToNode::EscapeState es; uint edge_to; if (cik->is_subclass_of(_compile->env()->Thread_klass()) || ciik->has_finalizer()) { @@ -1595,25 +1620,24 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha edge_to = _phantom_object; // Could not be worse } else { es = PointsToNode::NoEscape; - edge_to = call->_idx; + edge_to = call_idx; } - set_escape_state(call->_idx, es); - add_pointsto_edge(resproj->_idx, edge_to); - _processed.set(resproj->_idx); + set_escape_state(call_idx, es); + add_pointsto_edge(resproj_idx, edge_to); + _processed.set(resproj_idx); break; } case Op_AllocateArray: { - PointsToNode *ptadr = ptnode_adr(call->_idx); int length = call->in(AllocateNode::ALength)->find_int_con(-1); if (length < 0 || length > EliminateAllocationArraySizeLimit) { // Not scalar replaceable if the length is not constant or too big. - ptadr->_scalar_replaceable = false; + ptnode_adr(call_idx)->_scalar_replaceable = false; } - set_escape_state(call->_idx, PointsToNode::NoEscape); - add_pointsto_edge(resproj->_idx, call->_idx); - _processed.set(resproj->_idx); + set_escape_state(call_idx, PointsToNode::NoEscape); + add_pointsto_edge(resproj_idx, call_idx); + _processed.set(resproj_idx); break; } @@ -1631,19 +1655,17 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha // Note: we use isa_ptr() instead of isa_oopptr() here because the // _multianewarray functions return a TypeRawPtr. if (ret_type == NULL || ret_type->isa_ptr() == NULL) { - _processed.set(resproj->_idx); + _processed.set(resproj_idx); break; // doesn't return a pointer type } ciMethod *meth = call->as_CallJava()->method(); const TypeTuple * d = call->tf()->domain(); if (meth == NULL) { // not a Java method, assume global escape - set_escape_state(call->_idx, PointsToNode::GlobalEscape); - if (resproj != NULL) - add_pointsto_edge(resproj->_idx, _phantom_object); + set_escape_state(call_idx, PointsToNode::GlobalEscape); + add_pointsto_edge(resproj_idx, _phantom_object); } else { BCEscapeAnalyzer *call_analyzer = meth->get_bcea(); - VectorSet ptset(Thread::current()->resource_area()); bool copy_dependencies = false; if (call_analyzer->is_return_allocated()) { @@ -1651,13 +1673,12 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha // update dependency information. // Mark it as NoEscape so that objects referenced by // it's fields will be marked as NoEscape at least. - set_escape_state(call->_idx, PointsToNode::NoEscape); - if (resproj != NULL) - add_pointsto_edge(resproj->_idx, call->_idx); + set_escape_state(call_idx, PointsToNode::NoEscape); + add_pointsto_edge(resproj_idx, call_idx); copy_dependencies = true; - } else if (call_analyzer->is_return_local() && resproj != NULL) { + } else if (call_analyzer->is_return_local()) { // determine whether any arguments are returned - set_escape_state(call->_idx, PointsToNode::NoEscape); + set_escape_state(call_idx, PointsToNode::NoEscape); for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* at = d->field_at(i); @@ -1665,36 +1686,35 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha Node *arg = call->in(i)->uncast(); if (call_analyzer->is_arg_returned(i - TypeFunc::Parms)) { - PointsToNode *arg_esp = _nodes->adr_at(arg->_idx); + PointsToNode *arg_esp = ptnode_adr(arg->_idx); if (arg_esp->node_type() == PointsToNode::UnknownType) done = false; else if (arg_esp->node_type() == PointsToNode::JavaObject) - add_pointsto_edge(resproj->_idx, arg->_idx); + add_pointsto_edge(resproj_idx, arg->_idx); else - add_deferred_edge(resproj->_idx, arg->_idx); + add_deferred_edge(resproj_idx, arg->_idx); arg_esp->_hidden_alias = true; } } } copy_dependencies = true; } else { - set_escape_state(call->_idx, PointsToNode::GlobalEscape); - if (resproj != NULL) - add_pointsto_edge(resproj->_idx, _phantom_object); + set_escape_state(call_idx, PointsToNode::GlobalEscape); + add_pointsto_edge(resproj_idx, _phantom_object); for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* at = d->field_at(i); if (at->isa_oopptr() != NULL) { Node *arg = call->in(i)->uncast(); - PointsToNode *arg_esp = _nodes->adr_at(arg->_idx); + PointsToNode *arg_esp = ptnode_adr(arg->_idx); arg_esp->_hidden_alias = true; } } } if (copy_dependencies) - call_analyzer->copy_dependencies(C()->dependencies()); + call_analyzer->copy_dependencies(_compile->dependencies()); } if (done) - _processed.set(resproj->_idx); + _processed.set(resproj_idx); break; } @@ -1709,13 +1729,11 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha // Note: we use isa_ptr() instead of isa_oopptr() here because the // _multianewarray functions return a TypeRawPtr. if (ret_type->isa_ptr() != NULL) { - PointsToNode *ptadr = ptnode_adr(call->_idx); - set_escape_state(call->_idx, PointsToNode::GlobalEscape); - if (resproj != NULL) - add_pointsto_edge(resproj->_idx, _phantom_object); + set_escape_state(call_idx, PointsToNode::GlobalEscape); + add_pointsto_edge(resproj_idx, _phantom_object); } } - _processed.set(resproj->_idx); + _processed.set(resproj_idx); } } } @@ -1743,7 +1761,7 @@ void ConnectionGraph::record_for_escape_analysis(Node *n, PhaseTransform *phase) // Check if a call returns an object. const TypeTuple *r = n->as_Call()->tf()->range(); - if (r->cnt() > TypeFunc::Parms && + if (n->is_CallStaticJava() && r->cnt() > TypeFunc::Parms && n->as_Call()->proj_out(TypeFunc::Parms) != NULL) { // Note: use isa_ptr() instead of isa_oopptr() here because // the _multianewarray functions return a TypeRawPtr. @@ -1776,7 +1794,7 @@ void ConnectionGraph::record_for_escape_analysis(Node *n, PhaseTransform *phase) { add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false); int ti = n->in(1)->_idx; - PointsToNode::NodeType nt = _nodes->adr_at(ti)->node_type(); + PointsToNode::NodeType nt = ptnode_adr(ti)->node_type(); if (nt == PointsToNode::UnknownType) { _delayed_worklist.push(n); // Process it later. break; @@ -1866,7 +1884,7 @@ void ConnectionGraph::record_for_escape_analysis(Node *n, PhaseTransform *phase) if (in->is_top() || in == n) continue; // ignore top or inputs which go back this node int ti = in->_idx; - PointsToNode::NodeType nt = _nodes->adr_at(ti)->node_type(); + PointsToNode::NodeType nt = ptnode_adr(ti)->node_type(); if (nt == PointsToNode::UnknownType) { break; } else if (nt == PointsToNode::JavaObject) { @@ -1904,7 +1922,7 @@ void ConnectionGraph::record_for_escape_analysis(Node *n, PhaseTransform *phase) // Treat Return value as LocalVar with GlobalEscape escape state. add_node(n, PointsToNode::LocalVar, PointsToNode::GlobalEscape, false); int ti = n->in(TypeFunc::Parms)->_idx; - PointsToNode::NodeType nt = _nodes->adr_at(ti)->node_type(); + PointsToNode::NodeType nt = ptnode_adr(ti)->node_type(); if (nt == PointsToNode::UnknownType) { _delayed_worklist.push(n); // Process it later. break; @@ -1968,17 +1986,17 @@ void ConnectionGraph::record_for_escape_analysis(Node *n, PhaseTransform *phase) } void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) { + uint n_idx = n->_idx; + // Don't set processed bit for AddP, LoadP, StoreP since // they may need more then one pass to process. - if (_processed.test(n->_idx)) + if (_processed.test(n_idx)) return; // No need to redefine node's state. - PointsToNode *ptadr = ptnode_adr(n->_idx); - if (n->is_Call()) { CallNode *call = n->as_Call(); process_call_arguments(call, phase); - _processed.set(n->_idx); + _processed.set(n_idx); return; } @@ -1991,7 +2009,7 @@ void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) { PointsTo(ptset, base, phase); for( VectorSetI i(&ptset); i.test(); ++i ) { uint pt = i.elem; - add_field_edge(pt, n->_idx, address_offset(n, phase)); + add_field_edge(pt, n_idx, address_offset(n, phase)); } break; } @@ -2006,12 +2024,12 @@ void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) { case Op_DecodeN: { int ti = n->in(1)->_idx; - if (_nodes->adr_at(ti)->node_type() == PointsToNode::JavaObject) { - add_pointsto_edge(n->_idx, ti); + if (ptnode_adr(ti)->node_type() == PointsToNode::JavaObject) { + add_pointsto_edge(n_idx, ti); } else { - add_deferred_edge(n->_idx, ti); + add_deferred_edge(n_idx, ti); } - _processed.set(n->_idx); + _processed.set(n_idx); break; } case Op_ConP: @@ -2060,7 +2078,7 @@ void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) { int offset = address_offset(adr, phase); for( VectorSetI i(&ptset); i.test(); ++i ) { uint pt = i.elem; - add_deferred_edge_to_fields(n->_idx, pt, offset); + add_deferred_edge_to_fields(n_idx, pt, offset); } break; } @@ -2083,13 +2101,13 @@ void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) { if (in->is_top() || in == n) continue; // ignore top or inputs which go back this node int ti = in->_idx; - if (_nodes->adr_at(in->_idx)->node_type() == PointsToNode::JavaObject) { - add_pointsto_edge(n->_idx, ti); + if (ptnode_adr(in->_idx)->node_type() == PointsToNode::JavaObject) { + add_pointsto_edge(n_idx, ti); } else { - add_deferred_edge(n->_idx, ti); + add_deferred_edge(n_idx, ti); } } - _processed.set(n->_idx); + _processed.set(n_idx); break; } case Op_Proj: @@ -2097,7 +2115,7 @@ void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) { // we are only interested in the result projection from a call if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() ) { process_call_result(n->as_Proj(), phase); - assert(_processed.test(n->_idx), "all call results should be processed"); + assert(_processed.test(n_idx), "all call results should be processed"); } else { assert(false, "Op_Proj"); } @@ -2112,12 +2130,12 @@ void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) { } #endif int ti = n->in(TypeFunc::Parms)->_idx; - if (_nodes->adr_at(ti)->node_type() == PointsToNode::JavaObject) { - add_pointsto_edge(n->_idx, ti); + if (ptnode_adr(ti)->node_type() == PointsToNode::JavaObject) { + add_pointsto_edge(n_idx, ti); } else { - add_deferred_edge(n->_idx, ti); + add_deferred_edge(n_idx, ti); } - _processed.set(n->_idx); + _processed.set(n_idx); break; } case Op_StoreP: @@ -2162,9 +2180,9 @@ void ConnectionGraph::dump() { PhaseGVN *igvn = _compile->initial_gvn(); bool first = true; - uint size = (uint)_nodes->length(); + uint size = nodes_size(); for (uint ni = 0; ni < size; ni++) { - PointsToNode *ptn = _nodes->adr_at(ni); + PointsToNode *ptn = ptnode_adr(ni); PointsToNode::NodeType ptn_type = ptn->node_type(); if (ptn_type != PointsToNode::JavaObject || ptn->_node == NULL) @@ -2174,7 +2192,7 @@ void ConnectionGraph::dump() { if (first) { tty->cr(); tty->print("======== Connection graph for "); - C()->method()->print_short_name(); + _compile->method()->print_short_name(); tty->cr(); first = false; } @@ -2182,12 +2200,12 @@ void ConnectionGraph::dump() { ptn->dump(); // Print all locals which reference this allocation for (uint li = ni; li < size; li++) { - PointsToNode *ptn_loc = _nodes->adr_at(li); + PointsToNode *ptn_loc = ptnode_adr(li); PointsToNode::NodeType ptn_loc_type = ptn_loc->node_type(); if ( ptn_loc_type == PointsToNode::LocalVar && ptn_loc->_node != NULL && ptn_loc->edge_count() == 1 && ptn_loc->edge_target(0) == ni ) { tty->print("%6d LocalVar [[%d]]", li, ni); - _nodes->adr_at(li)->_node->dump(); + ptnode_adr(li)->_node->dump(); } } if (Verbose) { @@ -2195,7 +2213,7 @@ void ConnectionGraph::dump() { for (uint i = 0; i < ptn->edge_count(); i++) { uint ei = ptn->edge_target(i); tty->print("%6d Field [[%d]]", ei, ni); - _nodes->adr_at(ei)->_node->dump(); + ptnode_adr(ei)->_node->dump(); } } tty->cr(); diff --git a/hotspot/src/share/vm/opto/escape.hpp b/hotspot/src/share/vm/opto/escape.hpp index 1d2c83511e7..5d9259569ef 100644 --- a/hotspot/src/share/vm/opto/escape.hpp +++ b/hotspot/src/share/vm/opto/escape.hpp @@ -178,14 +178,24 @@ public: // count of outgoing edges uint edge_count() const { return (_edges == NULL) ? 0 : _edges->length(); } + // node index of target of outgoing edge "e" - uint edge_target(uint e) const; + uint edge_target(uint e) const { + assert(_edges != NULL, "valid edge index"); + return (_edges->at(e) >> EdgeShift); + } // type of outgoing edge "e" - EdgeType edge_type(uint e) const; + EdgeType edge_type(uint e) const { + assert(_edges != NULL, "valid edge index"); + return (EdgeType) (_edges->at(e) & EdgeMask); + } + // add a edge of the specified type pointing to the specified target void add_edge(uint targIdx, EdgeType et); + // remove an edge of the specified type pointing to the specified target void remove_edge(uint targIdx, EdgeType et); + #ifndef PRODUCT void dump() const; #endif @@ -194,7 +204,7 @@ public: class ConnectionGraph: public ResourceObj { private: - GrowableArray* _nodes; // Connection graph nodes indexed + GrowableArray _nodes; // Connection graph nodes indexed // by ideal node index. Unique_Node_List _delayed_worklist; // Nodes to be processed before @@ -207,9 +217,6 @@ private: // is still being collected. If false, // no new nodes will be processed. - bool _has_allocations; // Indicates whether method has any - // non-escaping allocations. - uint _phantom_object; // Index of globally escaping object // that pointer values loaded from // a field which has not been set @@ -217,14 +224,13 @@ private: Compile * _compile; // Compile object for current compilation - // address of an element in _nodes. Used when the element is to be modified - PointsToNode *ptnode_adr(uint idx) { - if ((uint)_nodes->length() <= idx) { - // expand _nodes array - PointsToNode dummy = _nodes->at_grow(idx); - } - return _nodes->adr_at(idx); + // Address of an element in _nodes. Used when the element is to be modified + PointsToNode *ptnode_adr(uint idx) const { + // There should be no new ideal nodes during ConnectionGraph build, + // growableArray::adr_at() will throw assert otherwise. + return _nodes.adr_at(idx); } + uint nodes_size() const { return _nodes.length(); } // Add node to ConnectionGraph. void add_node(Node *n, PointsToNode::NodeType nt, PointsToNode::EscapeState es, bool done); @@ -307,30 +313,30 @@ private: // Set the escape state of a node void set_escape_state(uint ni, PointsToNode::EscapeState es); - // Get Compile object for current compilation. - Compile *C() const { return _compile; } - public: ConnectionGraph(Compile *C); + // Check for non-escaping candidates + static bool has_candidates(Compile *C); + // Compute the escape information - void compute_escape(); + bool compute_escape(); // escape state of a node PointsToNode::EscapeState escape_state(Node *n, PhaseTransform *phase); // other information we have collected bool is_scalar_replaceable(Node *n) { - if (_collecting) + if (_collecting || (n->_idx >= nodes_size())) return false; - PointsToNode ptn = _nodes->at_grow(n->_idx); - return ptn.escape_state() == PointsToNode::NoEscape && ptn._scalar_replaceable; + PointsToNode* ptn = ptnode_adr(n->_idx); + return ptn->escape_state() == PointsToNode::NoEscape && ptn->_scalar_replaceable; } bool hidden_alias(Node *n) { - if (_collecting) + if (_collecting || (n->_idx >= nodes_size())) return true; - PointsToNode ptn = _nodes->at_grow(n->_idx); - return (ptn.escape_state() != PointsToNode::NoEscape) || ptn._hidden_alias; + PointsToNode* ptn = ptnode_adr(n->_idx); + return (ptn->escape_state() != PointsToNode::NoEscape) || ptn->_hidden_alias; } #ifndef PRODUCT From 1267284a6fc00be6f5a89cbf6feb66e86e9d790b Mon Sep 17 00:00:00 2001 From: Dmitry Cherepanov Date: Mon, 7 Jul 2008 15:36:01 +0400 Subject: [PATCH 019/325] 6582346: javaw launcher does not display MessageBox after change to the resource files Call InitCommonControlsEx to perform UI initialization Reviewed-by: art --- .../windows/native/sun/windows/ComCtl32Util.cpp | 15 +++++++++++++++ jdk/src/windows/native/sun/windows/ComCtl32Util.h | 7 +++++++ 2 files changed, 22 insertions(+) diff --git a/jdk/src/windows/native/sun/windows/ComCtl32Util.cpp b/jdk/src/windows/native/sun/windows/ComCtl32Util.cpp index d9309a6856b..d00ef6e95e8 100644 --- a/jdk/src/windows/native/sun/windows/ComCtl32Util.cpp +++ b/jdk/src/windows/native/sun/windows/ComCtl32Util.cpp @@ -49,6 +49,9 @@ void ComCtl32Util::InitLibraries() { m_bNewSubclassing = (m_lpfnSetWindowSubclass != NULL) && (m_lpfnRemoveWindowSubclass != NULL) && (m_lpfnDefSubclassProc != NULL); + + fn_InitCommonControlsEx = (ComCtl32Util::InitCommonControlsExType)::GetProcAddress(hModComCtl32, "InitCommonControlsEx"); + InitCommonControls(); } } } @@ -108,3 +111,15 @@ LRESULT ComCtl32Util::SharedWindowProc(HWND hwnd, UINT msg, CATCH_BAD_ALLOC_RET(0); } + +void ComCtl32Util::InitCommonControls() +{ + if (fn_InitCommonControlsEx == NULL) { + return; + } + + INITCOMMONCONTROLSEX iccex; + memset(&iccex, 0, sizeof(INITCOMMONCONTROLSEX)); + iccex.dwSize = sizeof(INITCOMMONCONTROLSEX); + fn_InitCommonControlsEx(&iccex); +} diff --git a/jdk/src/windows/native/sun/windows/ComCtl32Util.h b/jdk/src/windows/native/sun/windows/ComCtl32Util.h index b90869ba39e..e410f30760e 100644 --- a/jdk/src/windows/native/sun/windows/ComCtl32Util.h +++ b/jdk/src/windows/native/sun/windows/ComCtl32Util.h @@ -25,6 +25,8 @@ #include "awt_Component.h" +#include + #ifndef _COMCTL32UTIL_H #define _COMCTL32UTIL_H @@ -81,6 +83,11 @@ class ComCtl32Util PFNREMOVEWINDOWSUBCLASS m_lpfnRemoveWindowSubclass; PFNDEFSUBCLASSPROC m_lpfnDefSubclassProc; + typedef BOOL (WINAPI * InitCommonControlsExType)(const LPINITCOMMONCONTROLSEX lpInitCtrls); + InitCommonControlsExType fn_InitCommonControlsEx; + + void InitCommonControls(); + BOOL m_bNewSubclassing; // comctl32.dll version 6 window proc From 29aa2aecb4fc740222c1de39554ed03bf6be94eb Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Mon, 7 Jul 2008 16:09:39 +0400 Subject: [PATCH 020/325] 6693974: Unify EventQueue$EventQueueItem and SunToolkit.$EventQueueItem classes Reviewed-by: volk, art --- jdk/src/share/classes/java/awt/Component.java | 2 +- jdk/src/share/classes/java/awt/EventQueue.java | 18 ++++-------------- jdk/src/share/classes/sun/awt/SunToolkit.java | 9 --------- 3 files changed, 5 insertions(+), 24 deletions(-) diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index 221506d80e1..6a206029cd0 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -5737,7 +5737,7 @@ public abstract class Component implements ImageObserver, MenuContainer, } } - transient EventQueueItem[] eventCache; + transient sun.awt.EventQueueItem[] eventCache; /** * @see #isCoalescingEnabled diff --git a/jdk/src/share/classes/java/awt/EventQueue.java b/jdk/src/share/classes/java/awt/EventQueue.java index 8620c2880f5..f9c26526210 100644 --- a/jdk/src/share/classes/java/awt/EventQueue.java +++ b/jdk/src/share/classes/java/awt/EventQueue.java @@ -42,6 +42,7 @@ import sun.awt.AppContext; import sun.awt.AWTAutoShutdown; import sun.awt.PeerEvent; import sun.awt.SunToolkit; +import sun.awt.EventQueueItem; /** * EventQueue is a platform-independent class @@ -359,7 +360,7 @@ public class EventQueue { entry != null; entry = entry.next) { // Give Component.coalesceEvents a chance - if (entry.event.getSource() == source && entry.id == id) { + if (entry.event.getSource() == source && entry.event.getID() == id) { AWTEvent coalescedEvent = source.coalesceEvents( entry.event, e); if (coalescedEvent != null) { @@ -499,7 +500,7 @@ public class EventQueue { for (EventQueueItem entry = queues[i].head, prev = null; entry != null; prev = entry, entry = entry.next) { - if (entry.id == id) { + if (entry.event.getID() == id) { if (prev == null) { queues[i].head = entry.next; } else { @@ -545,7 +546,7 @@ public class EventQueue { for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { EventQueueItem q = queues[i].head; for (; q != null; q = q.next) { - if (q.id == id) { + if (q.event.getID() == id) { return q.event; } } @@ -1051,14 +1052,3 @@ class Queue { EventQueueItem head; EventQueueItem tail; } - -class EventQueueItem { - AWTEvent event; - int id; - EventQueueItem next; - - EventQueueItem(AWTEvent evt) { - event = evt; - id = evt.getID(); - } -} diff --git a/jdk/src/share/classes/sun/awt/SunToolkit.java b/jdk/src/share/classes/sun/awt/SunToolkit.java index 64b13e923bc..95a6e7815e1 100644 --- a/jdk/src/share/classes/sun/awt/SunToolkit.java +++ b/jdk/src/share/classes/sun/awt/SunToolkit.java @@ -2039,12 +2039,3 @@ class PostEventQueue { SunToolkit.wakeupEventQueue(eventQueue, event.getSource() == AWTAutoShutdown.getInstance()); } } // class PostEventQueue - -class EventQueueItem { - AWTEvent event; - EventQueueItem next; - - EventQueueItem(AWTEvent evt) { - event = evt; - } -} // class EventQueueItem From 1dce7af76f26ab1860a83f60e9f4853e56952d8e Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Mon, 7 Jul 2008 16:56:23 +0400 Subject: [PATCH 021/325] 6647340: Minimized JInternalFrame icons appear in incorrect positions if the main frame is resized Now BasicInternalFrameUI and BasicDesktopIconUI both recalculate frame icon position Reviewed-by: peterz --- .../swing/plaf/basic/BasicDesktopIconUI.java | 12 +- .../plaf/basic/BasicInternalFrameUI.java | 45 ++--- .../swing/plaf/basic/DesktopIconMover.java | 168 ++++++++++++++++++ .../JInternalFrame/6647340/bug6647340.java | 146 +++++++++++++++ 4 files changed, 335 insertions(+), 36 deletions(-) create mode 100644 jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java create mode 100644 jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java index 9aab4dbe17d..5ebb6289440 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,6 +47,7 @@ public class BasicDesktopIconUI extends DesktopIconUI { protected JInternalFrame.JDesktopIcon desktopIcon; protected JInternalFrame frame; + private DesktopIconMover desktopIconMover; /** * The title pane component used in the desktop icon. @@ -127,12 +128,21 @@ public class BasicDesktopIconUI extends DesktopIconUI { mouseInputListener = createMouseInputListener(); desktopIcon.addMouseMotionListener(mouseInputListener); desktopIcon.addMouseListener(mouseInputListener); + getDesktopIconMover().installListeners(); } protected void uninstallListeners() { desktopIcon.removeMouseMotionListener(mouseInputListener); desktopIcon.removeMouseListener(mouseInputListener); mouseInputListener = null; + getDesktopIconMover().uninstallListeners(); + } + + private DesktopIconMover getDesktopIconMover() { + if (desktopIconMover == null) { + desktopIconMover = new DesktopIconMover(desktopIcon); + } + return desktopIconMover; } protected void installDefaults() { diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java index 83b0fd73bd9..86a8f15ddd0 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,6 @@ public class BasicInternalFrameUI extends InternalFrameUI protected MouseInputAdapter borderListener; protected PropertyChangeListener propertyChangeListener; protected LayoutManager internalFrameLayout; - protected ComponentListener componentListener; protected MouseInputListener glassPaneDispatcher; private InternalFrameListener internalFrameListener; @@ -67,9 +66,9 @@ public class BasicInternalFrameUI extends InternalFrameUI protected BasicInternalFrameTitlePane titlePane; // access needs this private static DesktopManager sharedDesktopManager; - private boolean componentListenerAdded = false; private Rectangle parentBounds; + private DesktopIconMover desktopIconMover; private boolean dragging = false; private boolean resizing = false; @@ -210,14 +209,17 @@ public class BasicInternalFrameUI extends InternalFrameUI frame.getGlassPane().addMouseListener(glassPaneDispatcher); frame.getGlassPane().addMouseMotionListener(glassPaneDispatcher); } - componentListener = createComponentListener(); if (frame.getParent() != null) { parentBounds = frame.getParent().getBounds(); } - if ((frame.getParent() != null) && !componentListenerAdded) { - frame.getParent().addComponentListener(componentListener); - componentListenerAdded = true; + getDesktopIconMover().installListeners(); + } + + private DesktopIconMover getDesktopIconMover() { + if (desktopIconMover == null) { + desktopIconMover = new DesktopIconMover(frame); } + return desktopIconMover; } // Provide a FocusListener to listen for a WINDOW_LOST_FOCUS event, @@ -288,11 +290,7 @@ public class BasicInternalFrameUI extends InternalFrameUI * @since 1.3 */ protected void uninstallListeners() { - if ((frame.getParent() != null) && componentListenerAdded) { - frame.getParent().removeComponentListener(componentListener); - componentListenerAdded = false; - } - componentListener = null; + getDesktopIconMover().uninstallListeners(); if (glassPaneDispatcher != null) { frame.getGlassPane().removeMouseListener(glassPaneDispatcher); frame.getGlassPane().removeMouseMotionListener(glassPaneDispatcher); @@ -1230,15 +1228,6 @@ public class BasicInternalFrameUI extends InternalFrameUI } } - // Relocate the icon base on the new parent bounds. - if (icon != null) { - Rectangle iconBounds = icon.getBounds(); - int y = iconBounds.y + - (parentNewBounds.height - parentBounds.height); - icon.setBounds(iconBounds.x, y, - iconBounds.width, iconBounds.height); - } - // Update the new parent bounds for next resize. if (!parentBounds.equals(parentNewBounds)) { parentBounds = parentNewBounds; @@ -1413,10 +1402,6 @@ public class BasicInternalFrameUI extends InternalFrameUI // Cancel a resize in progress if the internal frame // gets a setClosed(true) or dispose(). cancelResize(); - if ((frame.getParent() != null) && componentListenerAdded) { - frame.getParent().removeComponentListener( - componentListener); - } closeFrame(f); } } else if (JInternalFrame.IS_MAXIMUM_PROPERTY == prop) { @@ -1449,16 +1434,6 @@ public class BasicInternalFrameUI extends InternalFrameUI } else { parentBounds = null; } - if ((frame.getParent() != null) && !componentListenerAdded) { - f.getParent().addComponentListener(componentListener); - componentListenerAdded = true; - } else if ((newValue == null) && componentListenerAdded) { - if (f.getParent() != null) { - f.getParent().removeComponentListener( - componentListener); - } - componentListenerAdded = false; - } } else if (JInternalFrame.TITLE_PROPERTY == prop || prop == "closable" || prop == "iconable" || prop == "maximizable") { diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java b/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java new file mode 100644 index 00000000000..deff4f27a5f --- /dev/null +++ b/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java @@ -0,0 +1,168 @@ +/* + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.plaf.basic; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.beans.*; + +/** + * DesktopIconMover is intended to move desktop icon + * when parent window is resized. + */ +class DesktopIconMover implements ComponentListener, PropertyChangeListener { + private Component parent; + private JInternalFrame frame; // if not null, DesktopIconMover(frame) + // constructor was used + private JInternalFrame.JDesktopIcon icon; + private Rectangle parentBounds; + private boolean componentListenerAdded = false; + + public DesktopIconMover(JInternalFrame frame) { + if (frame == null) { + throw new NullPointerException("Frame cannot be null"); + } + this.frame = frame; + this.icon = frame.getDesktopIcon(); + if (icon == null) { + throw new NullPointerException( + "frame.getDesktopIcon() cannot be null"); + } + this.parent = frame.getParent(); + if (this.parent != null) { + parentBounds = this.parent.getBounds(); + } + } + + public DesktopIconMover(JInternalFrame.JDesktopIcon icon) { + if (icon == null) { + throw new NullPointerException("Icon cannot be null"); + } + this.icon = icon; + this.parent = icon.getParent(); + if (this.parent != null) { + parentBounds = this.parent.getBounds(); + } + } + + public void installListeners() { + if (frame != null) { + frame.addPropertyChangeListener(this); + } else { + icon.addPropertyChangeListener(this); + } + addComponentListener(); + } + + public void uninstallListeners() { + if (frame != null) { + frame.removePropertyChangeListener(this); + } else { + icon.removePropertyChangeListener(this); + } + removeComponentListener(); + } + + public void propertyChange(PropertyChangeEvent evt) { + String propName = evt.getPropertyName(); + if ("ancestor".equals(propName)) { + Component newAncestor = (Component) evt.getNewValue(); + + // Remove component listener if parent is changing + Component probablyNewParent = getCurrentParent(); + if ((probablyNewParent != null) && + (!probablyNewParent.equals(parent))) { + removeComponentListener(); + parent = probablyNewParent; + } + + if (newAncestor == null) { + removeComponentListener(); + } else { + addComponentListener(); + } + + // Update parentBounds + if (parent != null) { + parentBounds = parent.getBounds(); + } else { + parentBounds = null; + } + } else if (JInternalFrame.IS_CLOSED_PROPERTY.equals(propName)) { + removeComponentListener(); + } + } + + private void addComponentListener() { + if (!componentListenerAdded && (parent != null)) { + parent.addComponentListener(this); + componentListenerAdded = true; + } + } + + private void removeComponentListener() { + if ((parent != null) && componentListenerAdded) { + parent.removeComponentListener(this); + componentListenerAdded = false; + } + } + + private Component getCurrentParent() { + if (frame != null) { + return frame.getParent(); + } else { + return icon.getParent(); + } + } + + public void componentResized(ComponentEvent e) { + if ((parent == null) || (parentBounds == null)) { + return; + } + + Rectangle parentNewBounds = parent.getBounds(); + if ((parentNewBounds == null) || parentNewBounds.equals(parentBounds)) { + return; + } + + // Move desktop icon only in up-down direction + int newIconY = icon.getLocation().y + + (parentNewBounds.height - parentBounds.height); + icon.setLocation(icon.getLocation().x, newIconY); + + parentBounds = parentNewBounds; + } + + public void componentMoved(ComponentEvent e) { + } + + public void componentShown(ComponentEvent e) { + } + + public void componentHidden(ComponentEvent e) { + } +} diff --git a/jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java b/jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java new file mode 100644 index 00000000000..b4c180140bd --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/6647340/bug6647340.java @@ -0,0 +1,146 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6647340 + * @summary Checks that iconified internal frame follows + * the main frame borders properly. + * @author Mikhail Lapshin + */ + +import sun.awt.SunToolkit; + +import javax.swing.*; +import java.awt.*; +import java.beans.PropertyVetoException; + +public class bug6647340 { + private JFrame frame; + private Point location; + private JInternalFrame jif; + + public static void main(String[] args) throws Exception { + final bug6647340 test = new bug6647340(); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + test.setupUI(); + } + }); + test.test(); + } finally { + if (test.frame != null) { + test.frame.dispose(); + } + } + } + + private void setupUI() { + frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JDesktopPane desktop = new JDesktopPane(); + frame.add(desktop); + + jif = new JInternalFrame("Internal Frame", true, true, true, true); + jif.setBounds(20, 20, 200, 100); + desktop.add(jif); + jif.setVisible(true); + + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + frame.setBounds((screen.width - 400) / 2, (screen.height - 400) / 2, 400, 400); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private void test() throws Exception { + realSync(); + test1(); + realSync(); + check1(); + realSync(); + test2(); + realSync(); + check2(); + } + + private void test1() throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + setIcon(true); + location = jif.getDesktopIcon().getLocation(); + Dimension size = frame.getSize(); + frame.setSize(size.width + 100, size.height + 100); + } + }); + } + + private void test2() throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + setIcon(false); + } + }); + realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + Dimension size = frame.getSize(); + frame.setSize(size.width - 100, size.height - 100); + } + }); + realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + setIcon(true); + } + }); + } + + private void check1() { + if (!jif.getDesktopIcon().getLocation().equals(location)) { + System.out.println("First test passed"); + } else { + throw new RuntimeException("Icon isn't shifted with the frame bounds"); + } + } + + private void check2() { + if (jif.getDesktopIcon().getLocation().equals(location)) { + System.out.println("Second test passed"); + } else { + throw new RuntimeException("Icon isn't located near the frame bottom"); + } + } + + private static void realSync() { + ((SunToolkit) (Toolkit.getDefaultToolkit())).realSync(); + } + + private void setIcon(boolean b) { + try { + jif.setIcon(b); + } catch (PropertyVetoException e) { + e.printStackTrace(); + } + } +} From 5a843be073ff7665ba9edaaf880d5499bf2bacac Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Mon, 7 Jul 2008 17:24:21 +0400 Subject: [PATCH 022/325] 6682046: Mixing code does not always recalculate shapes correctly when resizing components The valid property is now encapsulated in Component. Reviewed-by: art --- jdk/src/share/classes/java/awt/Button.java | 6 +- jdk/src/share/classes/java/awt/Checkbox.java | 6 +- jdk/src/share/classes/java/awt/Choice.java | 22 ++----- jdk/src/share/classes/java/awt/Component.java | 46 ++++++++++----- jdk/src/share/classes/java/awt/Container.java | 58 +++++++++---------- jdk/src/share/classes/java/awt/Dialog.java | 6 +- jdk/src/share/classes/java/awt/Frame.java | 14 ++--- jdk/src/share/classes/java/awt/Label.java | 6 +- jdk/src/share/classes/java/awt/TextField.java | 6 +- 9 files changed, 83 insertions(+), 87 deletions(-) diff --git a/jdk/src/share/classes/java/awt/Button.java b/jdk/src/share/classes/java/awt/Button.java index fcb33ddecc2..8982a60cc83 100644 --- a/jdk/src/share/classes/java/awt/Button.java +++ b/jdk/src/share/classes/java/awt/Button.java @@ -1,5 +1,5 @@ /* - * Copyright 1995-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -213,8 +213,8 @@ public class Button extends Component implements Accessible { } // This could change the preferred size of the Component. - if (testvalid && valid) { - invalidate(); + if (testvalid) { + invalidateIfValid(); } } diff --git a/jdk/src/share/classes/java/awt/Checkbox.java b/jdk/src/share/classes/java/awt/Checkbox.java index e366e54f6cd..7e5599d5ef9 100644 --- a/jdk/src/share/classes/java/awt/Checkbox.java +++ b/jdk/src/share/classes/java/awt/Checkbox.java @@ -1,5 +1,5 @@ /* - * Copyright 1995-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -284,8 +284,8 @@ public class Checkbox extends Component implements ItemSelectable, Accessible { } // This could change the preferred size of the Component. - if (testvalid && valid) { - invalidate(); + if (testvalid) { + invalidateIfValid(); } } diff --git a/jdk/src/share/classes/java/awt/Choice.java b/jdk/src/share/classes/java/awt/Choice.java index 9edb8ac7d8c..ea46b8d772e 100644 --- a/jdk/src/share/classes/java/awt/Choice.java +++ b/jdk/src/share/classes/java/awt/Choice.java @@ -1,5 +1,5 @@ /* - * Copyright 1995-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -207,9 +207,7 @@ public class Choice extends Component implements ItemSelectable, Accessible { } // This could change the preferred size of the Component. - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** @@ -269,9 +267,7 @@ public class Choice extends Component implements ItemSelectable, Accessible { } // This could change the preferred size of the Component. - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** @@ -299,9 +295,7 @@ public class Choice extends Component implements ItemSelectable, Accessible { } // This could change the preferred size of the Component. - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** @@ -323,9 +317,7 @@ public class Choice extends Component implements ItemSelectable, Accessible { } // This could change the preferred size of the Component. - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** @@ -367,9 +359,7 @@ public class Choice extends Component implements ItemSelectable, Accessible { } // This could change the preferred size of the Component. - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index 6a206029cd0..07d6ff966a6 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -346,7 +346,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * @see #validate * @see #invalidate */ - volatile boolean valid = false; + private volatile boolean valid = false; /** * The DropTarget associated with this component. @@ -1714,9 +1714,9 @@ public abstract class Component implements ImageObserver, MenuContainer, // This could change the preferred size of the Component. // Fix for 6213660. Should compare old and new fonts and do not // call invalidate() if they are equal. - if (valid && f != oldFont && (oldFont == null || + if (f != oldFont && (oldFont == null || !oldFont.equals(f))) { - invalidate(); + invalidateIfValid(); } } @@ -1773,9 +1773,7 @@ public abstract class Component implements ImageObserver, MenuContainer, firePropertyChange("locale", oldValue, l); // This could change the preferred size of the Component. - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** @@ -2084,8 +2082,8 @@ public abstract class Component implements ImageObserver, MenuContainer, if (resized) { invalidate(); } - if (parent != null && parent.valid) { - parent.invalidate(); + if (parent != null) { + parent.invalidateIfValid(); } } if (needNotify) { @@ -2654,7 +2652,8 @@ public abstract class Component implements ImageObserver, MenuContainer, public void validate() { synchronized (getTreeLock()) { ComponentPeer peer = this.peer; - if (!valid && peer != null) { + boolean wasValid = isValid(); + if (!wasValid && peer != null) { Font newfont = getFont(); Font oldfont = peerFont; if (newfont != oldfont && (oldfont == null @@ -2665,6 +2664,9 @@ public abstract class Component implements ImageObserver, MenuContainer, peer.layout(); } valid = true; + if (!wasValid) { + mixOnValidating(); + } } } @@ -2693,12 +2695,20 @@ public abstract class Component implements ImageObserver, MenuContainer, if (!isMaximumSizeSet()) { maxSize = null; } - if (parent != null && parent.valid) { - parent.invalidate(); + if (parent != null) { + parent.invalidateIfValid(); } } } + /** Invalidates the component unless it is already invalid. + */ + final void invalidateIfValid() { + if (isValid()) { + invalidate(); + } + } + /** * Creates a graphics context for this component. This method will * return null if this component is currently not @@ -7716,7 +7726,7 @@ public abstract class Component implements ImageObserver, MenuContainer, protected String paramString() { String thisName = getName(); String str = (thisName != null? thisName : "") + "," + x + "," + y + "," + width + "x" + height; - if (!valid) { + if (!isValid()) { str += ",invalid"; } if (!visible) { @@ -8476,9 +8486,7 @@ public abstract class Component implements ImageObserver, MenuContainer, firePropertyChange("componentOrientation", oldValue, o); // This could change the preferred size of the Component. - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** @@ -9328,7 +9336,8 @@ public abstract class Component implements ImageObserver, MenuContainer, */ private boolean areBoundsValid() { Container cont = getContainer(); - return cont == null || cont.isValid() || cont.getLayout() == null; + return cont == null || cont.isValid() + || cont.getLayout() == null; } /** @@ -9599,5 +9608,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } } + void mixOnValidating() { + // This method gets overriden in the Container. Obviously, a plain + // non-container components don't need to handle validation. + } + // ****************** END OF MIXING CODE ******************************** } diff --git a/jdk/src/share/classes/java/awt/Container.java b/jdk/src/share/classes/java/awt/Container.java index febd964265a..c302e4b0edc 100644 --- a/jdk/src/share/classes/java/awt/Container.java +++ b/jdk/src/share/classes/java/awt/Container.java @@ -505,9 +505,7 @@ public class Container extends Component { comp.parent = null; component.remove(index); - if (valid) { - invalidate(); - } + invalidateIfValid(); } else { // We should remove component and then // add it by the newIndex without newIndex decrement if even we shift components to the left @@ -800,9 +798,7 @@ public class Container extends Component { } } - if (valid) { - invalidate(); - } + invalidateIfValid(); if (peer != null) { if (comp.peer == null) { // Remove notify was called or it didn't have peer - create new one comp.addNotify(); @@ -1064,9 +1060,7 @@ public class Container extends Component { comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)); adjustDescendants(comp.countHierarchyMembers()); - if (valid) { - invalidate(); - } + invalidateIfValid(); if (peer != null) { comp.addNotify(); } @@ -1155,9 +1149,7 @@ public class Container extends Component { comp.parent = null; component.remove(index); - if (valid) { - invalidate(); - } + invalidateIfValid(); if (containerListener != null || (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 || Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) { @@ -1249,9 +1241,7 @@ public class Container extends Component { if (peer != null && layoutMgr == null && isVisible()) { updateCursorImmediately(); } - if (valid) { - invalidate(); - } + invalidateIfValid(); } } @@ -1411,9 +1401,7 @@ public class Container extends Component { */ public void setLayout(LayoutManager mgr) { layoutMgr = mgr; - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** @@ -1485,10 +1473,10 @@ public class Container extends Component { */ public void validate() { /* Avoid grabbing lock unless really necessary. */ - if (!valid) { + if (!isValid()) { boolean updateCur = false; synchronized (getTreeLock()) { - if (!valid && peer != null) { + if (!isValid() && peer != null) { ContainerPeer p = null; if (peer instanceof ContainerPeer) { p = (ContainerPeer) peer; @@ -1497,7 +1485,6 @@ public class Container extends Component { p.beginValidate(); } validateTree(); - valid = true; if (p != null) { p.endValidate(); updateCur = isVisible(); @@ -1520,7 +1507,7 @@ public class Container extends Component { * @see #validate */ protected void validateTree() { - if (!valid) { + if (!isValid()) { if (peer instanceof ContainerPeer) { ((ContainerPeer)peer).beginLayout(); } @@ -1529,7 +1516,7 @@ public class Container extends Component { Component comp = component.get(i); if ( (comp instanceof Container) && !(comp instanceof Window) - && !comp.valid) { + && !comp.isValid()) { ((Container)comp).validateTree(); } else { comp.validate(); @@ -1539,7 +1526,7 @@ public class Container extends Component { ((ContainerPeer)peer).endLayout(); } } - valid = true; + super.validate(); } /** @@ -1554,14 +1541,10 @@ public class Container extends Component { ((Container)comp).invalidateTree(); } else { - if (comp.valid) { - comp.invalidate(); - } + comp.invalidateIfValid(); } } - if (valid) { - invalidate(); - } + invalidateIfValid(); } } @@ -4083,6 +4066,21 @@ public class Container extends Component { } } + @Override + void mixOnValidating() { + synchronized (getTreeLock()) { + if (mixingLog.isLoggable(Level.FINE)) { + mixingLog.fine("this = " + this); + } + + if (hasHeavyweightDescendants()) { + recursiveApplyCurrentShape(); + } + + super.mixOnValidating(); + } + } + // ****************** END OF MIXING CODE ******************************** } diff --git a/jdk/src/share/classes/java/awt/Dialog.java b/jdk/src/share/classes/java/awt/Dialog.java index f236f2677d4..2104a64b742 100644 --- a/jdk/src/share/classes/java/awt/Dialog.java +++ b/jdk/src/share/classes/java/awt/Dialog.java @@ -1,5 +1,5 @@ /* - * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1327,8 +1327,8 @@ public class Dialog extends Window { // the insets of the Dialog. If we could, we'd call invalidate() // from the peer, but we need to guarantee that we're not holding // the Dialog lock when we call invalidate(). - if (testvalid && valid) { - invalidate(); + if (testvalid) { + invalidateIfValid(); } } diff --git a/jdk/src/share/classes/java/awt/Frame.java b/jdk/src/share/classes/java/awt/Frame.java index 0e897d43309..290f7f9bb3d 100644 --- a/jdk/src/share/classes/java/awt/Frame.java +++ b/jdk/src/share/classes/java/awt/Frame.java @@ -1,5 +1,5 @@ /* - * Copyright 1995-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -590,9 +590,7 @@ public class Frame extends Window implements MenuContainer { if (peer != null) { mbManagement = true; menuBar.addNotify(); - if (valid) { - invalidate(); - } + invalidateIfValid(); peer.setMenuBar(menuBar); } } @@ -633,8 +631,8 @@ public class Frame extends Window implements MenuContainer { // the insets of the Frame. If we could, we'd call invalidate() // from the peer, but we need to guarantee that we're not holding // the Frame lock when we call invalidate(). - if (testvalid && valid) { - invalidate(); + if (testvalid) { + invalidateIfValid(); } firePropertyChange("resizable", oldResizable, resizable); } @@ -907,9 +905,7 @@ public class Frame extends Window implements MenuContainer { FramePeer peer = (FramePeer)this.peer; if (peer != null) { mbManagement = true; - if (valid) { - invalidate(); - } + invalidateIfValid(); peer.setMenuBar(null); m.removeNotify(); } diff --git a/jdk/src/share/classes/java/awt/Label.java b/jdk/src/share/classes/java/awt/Label.java index 5daf2b88b6f..80f167358c4 100644 --- a/jdk/src/share/classes/java/awt/Label.java +++ b/jdk/src/share/classes/java/awt/Label.java @@ -1,5 +1,5 @@ /* - * Copyright 1995-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -257,8 +257,8 @@ public class Label extends Component implements Accessible { } // This could change the preferred size of the Component. - if (testvalid && valid) { - invalidate(); + if (testvalid) { + invalidateIfValid(); } } diff --git a/jdk/src/share/classes/java/awt/TextField.java b/jdk/src/share/classes/java/awt/TextField.java index fb95d91b894..b2659aa99f0 100644 --- a/jdk/src/share/classes/java/awt/TextField.java +++ b/jdk/src/share/classes/java/awt/TextField.java @@ -1,5 +1,5 @@ /* - * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -296,9 +296,7 @@ public class TextField extends TextComponent { super.setText(t); // This could change the preferred size of the Component. - if (valid) { - invalidate(); - } + invalidateIfValid(); } /** From 2720870af6c94d41a011e538b25def7b3e097dcb Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Mon, 7 Jul 2008 17:39:18 +0400 Subject: [PATCH 023/325] 6723018: Need to push the test for 6682046 Pushed the test Reviewed-by: art --- jdk/test/java/awt/Mixing/Validating.java | 405 +++++++++++++++++++++++ 1 file changed, 405 insertions(+) create mode 100644 jdk/test/java/awt/Mixing/Validating.java diff --git a/jdk/test/java/awt/Mixing/Validating.java b/jdk/test/java/awt/Mixing/Validating.java new file mode 100644 index 00000000000..a103def156b --- /dev/null +++ b/jdk/test/java/awt/Mixing/Validating.java @@ -0,0 +1,405 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + @test + @bug 6682046 + @summary Mixing code does not always recalculate shapes correctly when resizing components + @author anthony.petrov@...: area=awt.mixing + @library ../regtesthelpers + @build Util + @run main Validating +*/ + +/** + * Validating.java + * + * summary: Mixing code does not always recalculate shapes correctly when resizing components + */ + +import java.awt.*; +import java.awt.event.*; +import test.java.awt.regtesthelpers.Util; + +public class Validating +{ + static volatile boolean clickPassed = false; + + private static void init() + { + //*** Create instructions for the user here *** + + String[] instructions = + { + "This is an AUTOMATIC test, simply wait until it is done.", + "The result (passed or failed) will be shown in the", + "message window below." + }; + Sysout.createDialog( ); + Sysout.printInstructions( instructions ); + + if (!Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) { + System.out.println("The test environment does not support maximization. The test cannot be performed."); + pass(); + return; + } + + // Create the frame with a button. + Frame f = new Frame(); + Button b = new Button("ok"); + b.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + clickPassed = true; + } + }); + f.add(b); + // Make the frame maximized + f.setExtendedState(Frame.MAXIMIZED_BOTH); + f.pack(); + f.setVisible(true); + + Robot robot = Util.createRobot(); + robot.setAutoDelay(20); + + Util.waitForIdle(robot); + + // Now let's attempt to click in the middle of the button + // (i.e. in the middle of the window). + // If the button doesn't receive the click, it means that the test + // failed: the shape of the button was not enlarged. + Point heavyLoc = b.getLocationOnScreen(); + robot.mouseMove(heavyLoc.x + b.getWidth() / 2, heavyLoc.y + b.getHeight() / 2); + + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + Util.waitForIdle(robot); + + if (clickPassed) { + pass(); + } else { + fail("The button cannot be clicked."); + } + }//End init() + + + + /***************************************************** + * Standard Test Machinery Section + * DO NOT modify anything in this section -- it's a + * standard chunk of code which has all of the + * synchronisation necessary for the test harness. + * By keeping it the same in all tests, it is easier + * to read and understand someone else's test, as + * well as insuring that all tests behave correctly + * with the test harness. + * There is a section following this for test- + * classes + ******************************************************/ + private static boolean theTestPassed = false; + private static boolean testGeneratedInterrupt = false; + private static String failureMessage = ""; + + private static Thread mainThread = null; + + private static int sleepTime = 300000; + + // Not sure about what happens if multiple of this test are + // instantiated in the same VM. Being static (and using + // static vars), it aint gonna work. Not worrying about + // it for now. + public static void main( String args[] ) throws InterruptedException + { + mainThread = Thread.currentThread(); + try + { + init(); + } + catch( TestPassedException e ) + { + //The test passed, so just return from main and harness will + // interepret this return as a pass + return; + } + //At this point, neither test pass nor test fail has been + // called -- either would have thrown an exception and ended the + // test, so we know we have multiple threads. + + //Test involves other threads, so sleep and wait for them to + // called pass() or fail() + try + { + Thread.sleep( sleepTime ); + //Timed out, so fail the test + throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" ); + } + catch (InterruptedException e) + { + //The test harness may have interrupted the test. If so, rethrow the exception + // so that the harness gets it and deals with it. + if( ! testGeneratedInterrupt ) throw e; + + //reset flag in case hit this code more than once for some reason (just safety) + testGeneratedInterrupt = false; + + if ( theTestPassed == false ) + { + throw new RuntimeException( failureMessage ); + } + } + + }//main + + public static synchronized void setTimeoutTo( int seconds ) + { + sleepTime = seconds * 1000; + } + + public static synchronized void pass() + { + Sysout.println( "The test passed." ); + Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); + //first check if this is executing in main thread + if ( mainThread == Thread.currentThread() ) + { + //Still in the main thread, so set the flag just for kicks, + // and throw a test passed exception which will be caught + // and end the test. + theTestPassed = true; + throw new TestPassedException(); + } + theTestPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + }//pass() + + public static synchronized void fail() + { + //test writer didn't specify why test failed, so give generic + fail( "it just plain failed! :-)" ); + } + + public static synchronized void fail( String whyFailed ) + { + Sysout.println( "The test failed: " + whyFailed ); + Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); + //check if this called from main thread + if ( mainThread == Thread.currentThread() ) + { + //If main thread, fail now 'cause not sleeping + throw new RuntimeException( whyFailed ); + } + theTestPassed = false; + testGeneratedInterrupt = true; + failureMessage = whyFailed; + mainThread.interrupt(); + }//fail() + +}// class Validating + +//This exception is used to exit from any level of call nesting +// when it's determined that the test has passed, and immediately +// end the test. +class TestPassedException extends RuntimeException +{ +} + +//*********** End Standard Test Machinery Section ********** + + +//************ Begin classes defined for the test **************** + +// if want to make listeners, here is the recommended place for them, then instantiate +// them in init() + +/* Example of a class which may be written as part of a test +class NewClass implements anInterface + { + static int newVar = 0; + + public void eventDispatched(AWTEvent e) + { + //Counting events to see if we get enough + eventCount++; + + if( eventCount == 20 ) + { + //got enough events, so pass + + Validating.pass(); + } + else if( tries == 20 ) + { + //tried too many times without getting enough events so fail + + Validating.fail(); + } + + }// eventDispatched() + + }// NewClass class + +*/ + + +//************** End classes defined for the test ******************* + + + + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + System.out.println(messageIn); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class From b4be323f02abd645a977db142d496eb8512e7d90 Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Tue, 8 Jul 2008 11:36:19 +0400 Subject: [PATCH 024/325] 6635663: make/tools/AutoMulti/{AutoMulti,TestALFGenerator}.java still generate files with wrong legal notices Removed unused files Reviewed-by: ohair --- jdk/make/tools/Makefile | 1 - jdk/make/tools/auto_multi/Makefile | 43 -- .../src/build/tools/automulti/AutoMulti.java | 458 ------------------ .../src/build/tools/automulti/README.txt | 36 -- .../tools/automulti/TestALFGenerator.java | 401 --------------- .../tools/automulti/TestALFLookAndFeel.java | 182 ------- 6 files changed, 1121 deletions(-) delete mode 100644 jdk/make/tools/auto_multi/Makefile delete mode 100644 jdk/make/tools/src/build/tools/automulti/AutoMulti.java delete mode 100644 jdk/make/tools/src/build/tools/automulti/README.txt delete mode 100644 jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java delete mode 100644 jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java diff --git a/jdk/make/tools/Makefile b/jdk/make/tools/Makefile index be1c59a7cfa..c396097c086 100644 --- a/jdk/make/tools/Makefile +++ b/jdk/make/tools/Makefile @@ -32,7 +32,6 @@ include $(BUILDDIR)/common/Defs.gmk SUBDIRS = \ addjsum \ - auto_multi \ buildmetaindex \ commentchecker \ compile_font_config \ diff --git a/jdk/make/tools/auto_multi/Makefile b/jdk/make/tools/auto_multi/Makefile deleted file mode 100644 index f5db35099ad..00000000000 --- a/jdk/make/tools/auto_multi/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# -# Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved. -# 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 -# published by the Free Software Foundation. Sun designates this -# particular file as subject to the "Classpath" exception as provided -# by Sun in the LICENSE file that accompanied this code. -# -# 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. -# -# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, -# CA 95054 USA or visit www.sun.com if you need additional information or -# have any questions. -# - -# -# Makefile for building the automulti tool -# - -BUILDDIR = ../.. -PACKAGE = build.tools.automulti -PRODUCT = tools -PROGRAM = automulti -include $(BUILDDIR)/common/Defs.gmk - -BUILDTOOL_SOURCE_ROOT = $(BUILDDIR)/tools/src -BUILDTOOL_MAIN = $(PKGDIR)/AutoMulti.java - -# -# Build tool jar rules. -# -include $(BUILDDIR)/common/BuildToolJar.gmk - diff --git a/jdk/make/tools/src/build/tools/automulti/AutoMulti.java b/jdk/make/tools/src/build/tools/automulti/AutoMulti.java deleted file mode 100644 index a59edc856ca..00000000000 --- a/jdk/make/tools/src/build/tools/automulti/AutoMulti.java +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package build.tools.automulti; - -import java.lang.reflect.*; -import java.util.*; -import java.io.*; - -/** - * Automatically generates the Multiplexing UI classes - * for Swing. - *

- * To use, type 'java AutoMulti ' where - * is the directory containing the source for Swing's UI classes and - * is the package prefix to use before ".swing.plaf.multi". - * For example: - * - *

- * cd TEST
- * ../../../../build/solaris-sparc/bin/java AutoMulti ../../../../src/share/classes/javax/swing/plaf javax
- * 
- * - * AutoMulti will scour the plaf directory for *UI.java files and - * generate Multi*UI.java files that do the multiplexing thing. - *

- * NOTE: This tool depends upon the existence of and on the - * compiled classes from being somewhere in the class path. - * - * @author Willie Walker - */ -public class AutoMulti { - static String importLines; - - /** - * A silly list of parameter names to use. Skips "i" because we use - * it as a 'for' loop counter. If you want to get fancy, please feel - * to change how parameter names are obtained. This will break if - * someone decides to create a UI method that takes more than 8 - * parameters. Which one is a bug (this breaking or having a method - * with more than eight parameters) is a subjective thing. - */ - public static String[] paramNames = {"a","b","c","d","e","f","g","h"}; - - /** - * Removes the package names (e.g., javax.swing) from the name. - */ - public static String unqualifyName(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - String unqualifiedName = null; - while (parser.hasMoreTokens()) { - unqualifiedName = parser.nextToken(); - } - return removeDollars(unqualifiedName); - } - - /** - * Strips the extension from the filename. - */ - public static String stripExtension(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - return parser.nextToken(); - } - - /** - * Adds some spaces. - */ - public static void indent(StringBuffer s, int i) { - while (i > 0) { - s.append(" "); - i--; - } - } - - /** - * Spits out all the beginning stuff. - */ - public static StringBuffer createPreamble(String prefixName) { - StringBuffer s = new StringBuffer(); - s.append("/*\n"); - s.append(" *\n"); - s.append(" * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.\n"); - s.append(" * \n"); - s.append(" * This software is the proprietary information of Sun Microsystems, Inc. \n"); - s.append(" * Use is subject to license terms.\n"); - s.append(" * \n"); - s.append(" */\n"); - s.append("package " + prefixName + ".swing.plaf.multi;\n"); - s.append("\n"); - return s; - } - - /** - * Replaces 'Xxx$Yyy' with "Xxx'. Used by addImport because you - * can't import nested classes directly. - */ - public static String removeNestedClassName(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - sb.setLength(dollarPosition); - return sb.toString(); - } else { // no '$' - return s; - } - } - - /** - * Replaces '$' with ".'. Needed for printing inner class names - * for argument and return types. - */ - public static String removeDollars(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - while (dollarPosition >= 0) { - //XXX: will there ever be more than one '$'? - sb.replace(dollarPosition, dollarPosition+1, "."); - dollarPosition = sb.indexOf("$", dollarPosition); - } - return sb.toString(); - } else { // no $ - return s; - } - } - - /** - * Adds an import line to the String. - */ - public static void addImport(String s, Class theClass) { - if (!theClass.isPrimitive() && (theClass != Object.class)) { - String className = removeNestedClassName(theClass.getName()); - String importLine = new String("import " + className + ";\n"); - if (importLines.indexOf(importLine) == -1) { - importLines += importLine; - } - } - } - - /** - * Spits out the class header information. - */ - public static void addHeader(StringBuffer s, String className) { - s.append("/**\n"); - s.append(" * A multiplexing UI used to combine " + className + "s.\n"); - s.append(" * \n"); - s.append(" *

This file was automatically generated by AutoMulti.\n"); - s.append(" *\n"); - s.append(" * @author Otto Multey\n"); // Get it? I crack myself up. - s.append(" */\n"); - s.append("public class Multi" + className + " extends " + className + " {\n"); - s.append("\n"); - s.append(" /**\n"); - s.append(" * The vector containing the real UIs. This is populated \n"); - s.append(" * in the call to createUI, and can be obtained by calling\n"); - s.append(" * the getUIs method. The first element is guaranteed to be the real UI \n"); - s.append(" * obtained from the default look and feel.\n"); - s.append(" */\n"); - s.append(" protected Vector uis = new Vector();\n"); - s.append("\n"); - s.append("////////////////////\n"); - s.append("// Common UI methods\n"); - s.append("////////////////////\n"); - s.append("\n"); - s.append(" /**\n"); - s.append(" * Returns the list of UIs associated with this multiplexing UI. This \n"); - s.append(" * allows processing of the UIs by an application aware of multiplexing \n"); - s.append(" * UIs on components.\n"); - s.append(" */\n"); - s.append(" public ComponentUI[] getUIs() {\n"); - s.append(" return MultiLookAndFeel.uisToArray(uis);\n"); - s.append(" }\n"); - } - - /** - * Prints out the code for a method. This is pretty specific to the - * Multiplexing UI code, so don't get any fancy ideas. - */ - public static void addMethod(StringBuffer s, Method m, String origName, String className) { - - // Get the method name and the return type. Be a little careful about arrays. - // - String methodName = unqualifyName(m.getName()); - String returnType; - if (!m.getReturnType().isArray()) { - returnType = unqualifyName(m.getReturnType().toString()); - addImport(importLines,m.getReturnType()); - } else { - returnType = unqualifyName(m.getReturnType().getComponentType().toString()) - + "[]"; - addImport(importLines,m.getReturnType().getComponentType()); - } - - // Print the javadoc - // - s.append("\n"); - if (methodName.equals("createUI")) { - s.append(" /**\n"); - s.append(" * Returns a multiplexing UI instance if any of the auxiliary\n"); - s.append(" * LookAndFeels supports this UI. Otherwise, just returns the \n"); - s.append(" * UI object obtained from the default LookAndFeel.\n"); - s.append(" */\n"); - } else if (!returnType.equals("void")) { - s.append(" /**\n"); - s.append(" * Invokes the " + methodName + " method on each UI handled by this object.\n"); - s.append(" * \n"); - s.append(" * @return the value obtained from the first UI, which is\n"); - s.append(" * the UI obtained from the default LookAndFeel\n"); - s.append(" */\n"); - } else { - s.append(" /**\n"); - s.append(" * Invokes the " + methodName - + " method on each UI handled by this object.\n"); - s.append(" */\n"); - } - - // Print the method signature - // - s.append(" public"); - if (Modifier.isStatic(m.getModifiers())) { - s.append(" static"); - } - s.append(" " + returnType); - s.append(" " + methodName); - s.append("("); - - Class[] params = m.getParameterTypes(); - Class temp; - String braces; - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(", "); - } - temp = params[i]; - braces = new String(""); - while (temp.isArray()) { - braces += "[]"; - temp = temp.getComponentType(); - } - s.append(unqualifyName(temp.getName()) + braces + " " + paramNames[i]); - addImport(importLines,temp); - } - s.append(")"); - - // Don't forget about exceptions - // - Class exceptions[] = m.getExceptionTypes(); - String throwsString = new String(""); - - if (exceptions.length > 0) { - s.append("\n"); - indent(s,12); - s.append("throws "); - for (int i = 0; i < exceptions.length; i++) { - if (i > 0) { - s.append(", "); - } - s.append(unqualifyName(exceptions[i].getName())); - addImport(importLines,exceptions[i]); - } - } - s.append(throwsString + " {\n"); - - // Now print out the contents of the method. We do a special thing - // for the createUI method, another thing if the method returns 'void' - // and a third thing if we don't do either of the first two. If - // you want to squash this down, feel free. - // - if (methodName.equals("createUI")) { - indent(s,8); - s.append("ComponentUI mui = new Multi" + origName + "();\n"); - indent(s,8); - s.append("return MultiLookAndFeel.createUIs(mui,\n"); - indent(s,42); - s.append("((Multi" + origName +") mui).uis,\n"); - indent(s,42); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - } else if (!returnType.equals("void")) { - indent(s,8); - s.append(returnType + " returnValue = \n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(0)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("for (int i = 1; i < uis.size(); i++) {\n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(i)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("}\n"); - indent(s,8); - s.append("return returnValue;\n"); - } else { - indent(s,8); - s.append("for (int i = 0; i < uis.size(); i++) {\n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(i)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("}\n"); - } - indent(s,4); - s.append("}\n"); - } - - /** - * Takes a plaf class name (e.g., "MenuUI") and generates the corresponding - * Multiplexing UI Java source code (e.g., "MultiMenuUI.java"). - */ - public static void generateFile(String prefixName, String className) { - try { - FileOutputStream fos; - PrintWriter outFile; - - importLines = new String(); - importLines += new String("import java.util.Vector;\n"); - - StringBuffer body = new StringBuffer(); - Class wee = Class.forName(prefixName + ".swing.plaf." + className); - String weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - while (!weeName.equals("Object")) { - body.append("\n"); - body.append("////////////////////\n"); - body.append("// " + weeName + " methods\n"); - body.append("////////////////////\n"); - Method[] methods = wee.getDeclaredMethods(); - for (int i=0; i < methods.length; i++) { - if (Modifier.isPublic(methods[i].getModifiers())) { - addMethod(body,methods[i],className,weeName); - } - } - wee = wee.getSuperclass(); - weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - } - - fos = new FileOutputStream("Multi" + className + ".java"); - outFile = new PrintWriter(fos); - StringBuffer outText = createPreamble(prefixName); - outText.append(importLines.toString() + "\n"); - addHeader(outText,className); - outText.append(body.toString()); - outText.append("}\n"); - outFile.write(outText.toString()); - outFile.flush(); - outFile.close(); - } catch (Exception e) { - System.err.println(e); - } - } - - /** - * D'Oh! Something bad happened. - */ - public static void usage(String s) throws IOException { - System.err.println("Usage: AutoMulti [com.sun]"); - throw new IllegalArgumentException(s); - } - - /** - * Takes the plaf directory name and generates the multiplexing UI - * source code. - */ - public static void main(String[] args) throws IOException { - - if (args.length < 1) { - usage(""); - } - - String dirName = args[0]; - File dir = new File(dirName); - if (!dir.isDirectory()) { - System.err.println("No such directory: " + dirName); - usage(""); - } - - String prefixName; - if (args.length > 1) { - prefixName = args[1]; - } else { - prefixName = "com.sun.java"; - } - - String plafUIs[] = dir.list(new UIJavaFilter()); - for (int i = 0; i < plafUIs.length; i++) { - generateFile(prefixName,stripExtension(plafUIs[i])); - } - } -} - -/** - * Only accepts file names of the form *UI.java. The one exception - * is not accepting ComponentUI.java because we don't need to generate - * a multiplexing class for it. - */ -class UIJavaFilter implements FilenameFilter { - public boolean accept(File dir, String name) { - if (name.equals("ComponentUI.java")) { - return false; - } else if (name.endsWith("UI.java")) { - return true; - } else { - return false; - } - } -} diff --git a/jdk/make/tools/src/build/tools/automulti/README.txt b/jdk/make/tools/src/build/tools/automulti/README.txt deleted file mode 100644 index b5de5afe910..00000000000 --- a/jdk/make/tools/src/build/tools/automulti/README.txt +++ /dev/null @@ -1,36 +0,0 @@ -AutoMulti is the tool that automatically generates the -Multi*UI classes for the Multiplexing look and feel. -Instructions for using it are in AutoMulti.java. - -TestALFGenerator is a tool (a variation of AutoMulti) -that automatically generates an auxiliary look and -feel that you can use to test the Multiplexing look -and feel. The TestALF look and feel implements every -method by printing the message "In the xxx method of -the TextALFYyyUI class." and, except in the case of -createUI, returning something meaningless (since, -except in the case of createUI, the return value is -ignored). - -TestALFLookAndFeel.java is the only non-auto-generated -file for the TestALF L&F. If you specify a package -argument to TestALFGenerator, you'll have to change -the code in TestALFLookAndFeel.java to reflect the -package name. - -To test any application with the TestALF, make sure the -compiled TestALF classes are in the class path. Then add -this to the /lib/swing.properties file (which -you'll probably have to create): - -swing.auxiliarylaf=TestALFLookAndFeel - -E.g., if you're running SwingSet2 against your solaris -build, then you'd create/edit the swing.properties file -in /build/solaris-sparc/lib. - -Then run any app. You'll see lots of thrilling "In the -Xxxx method of the Yyy class" messages. If you get anything -else (especially an exception), then you've found a bug. -Probably in the default look and feel. - diff --git a/jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java b/jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java deleted file mode 100644 index 9b07dbc4048..00000000000 --- a/jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package build.tools.automulti; - -import java.lang.reflect.*; -import java.util.*; -import java.io.*; - -/** - * Automatically generates an auxiliary look and feel to be - * used for testing the Multiplexing look and feel. - *

- * To use, type 'java TestALFGenerator []' where - * is the directory containing the source for Swing's UI classes. - * is an optional argument that specifies the package - * of the TestALF classes. If it's omitted, the classes are in - * the default package. - * For example: - * - *

- * ../../../../build/solaris-sparc/bin/java TestALFGenerator ../../../../src/share/classes/javax/swing/plaf com.myco.myalaf
- * 
- * - * TestALFGenerator will scour the plaf directory for *UI.java files and - * generate TestALF*UI.java files. - *

- * NOTE: This tool depends upon the existence of and on the - * compiled classes from being somewhere in the class path. - * - * @author Willie Walker - */ -public class TestALFGenerator { - static String importLines; - static String packageName; - static String classPrefix = "TestALF"; - - /** - * A silly list of parameter names to use. Skips "i" because we use - * it as a 'for' loop counter. If you want to get fancy, please feel - * to change how parameter names are obtained. This will break if - * someone decides to create a UI method that takes more than 8 - * parameters. Which one is a bug (this breaking or having a method - * with more than eight parameters) is a subjective thing. - */ - public static String[] paramNames = {"a","b","c","d","e","f","g","h"}; - - /** - * Removes the package names (e.g., javax.swing) from the name. - */ - public static String unqualifyName(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - String unqualifiedName = null; - while (parser.hasMoreTokens()) { - unqualifiedName = parser.nextToken(); - } - return removeDollars(unqualifiedName); - } - - /** - * Strips the extension from the filename. - */ - public static String stripExtension(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - return parser.nextToken(); - } - - /** - * Adds some spaces. - */ - public static void indent(StringBuffer s, int i) { - while (i > 0) { - s.append(" "); - i--; - } - } - - /** - * Spits out all the beginning stuff. - */ - public static StringBuffer createPreamble(String prefixName) { - StringBuffer s = new StringBuffer(); - s.append("/*\n"); - s.append(" *\n"); - s.append(" * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.\n"); - s.append(" * \n"); - s.append(" * This software is the proprietary information of Sun Microsystems, Inc. \n"); - s.append(" * Use is subject to license terms.\n"); - s.append(" * \n"); - s.append(" */\n"); - if (packageName != null) { - s.append("package " + packageName + ";\n"); - s.append("\n"); - } - return s; - } - - /** - * Replaces 'Xxx$Yyy' with "Xxx'. Used by addImport because you - * can't import nested classes directly. - */ - public static String removeNestedClassName(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - sb.setLength(dollarPosition); - return sb.toString(); - } else { // no '$' - return s; - } - } - - /** - * Replaces '$' with ".'. Needed for printing inner class names - * for argument and return types. - */ - public static String removeDollars(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - while (dollarPosition >= 0) { - //XXX: will there ever be more than one '$'? - sb.replace(dollarPosition, dollarPosition+1, "."); - dollarPosition = sb.indexOf("$", dollarPosition); - } - return sb.toString(); - } else { // no $ - return s; - } - } - - /** - * Adds an import line to the String. - */ - public static void addImport(String s, Class theClass) { - if (!theClass.isPrimitive() && (theClass != Object.class)) { - String className = removeNestedClassName(theClass.getName()); - String importLine = new String("import " + className + ";\n"); - if (importLines.indexOf(importLine) == -1) { - importLines += importLine; - } - } - } - - /** - * Spits out the class header information. - */ - public static void addHeader(StringBuffer s, String className) { - s.append("/**\n"); - s.append(" * An auxiliary UI for " + className + "s.\n"); - s.append(" * \n"); - s.append(" *

This file was automatically generated by TestALFGenerator.\n"); - s.append(" *\n"); - s.append(" * @author Otto Multey\n"); // Get it? I crack myself up. - s.append(" */\n"); - s.append("public class " + classPrefix + className + " extends " + className + " {\n"); - s.append("\n"); - } - - /** - * Prints out the code for a method. - */ - public static void addMethod(StringBuffer s, Method m, String origName, String className) { - - // Get the method name and the return type. Be a little careful about arrays. - // - String methodName = unqualifyName(m.getName()); - String returnType; - - if (!m.getReturnType().isArray()) { - returnType = unqualifyName(m.getReturnType().toString()); - addImport(importLines,m.getReturnType()); - } else { - returnType = unqualifyName(m.getReturnType().getComponentType().toString()) - + "[]"; - addImport(importLines,m.getReturnType().getComponentType()); - } - - // Print the javadoc - // - s.append("\n"); - - if (methodName.equals("createUI")) { - s.append(" /**\n"); - s.append(" * Returns a UI object for this component.\n"); - s.append(" */\n"); - } else { - s.append(" /**\n"); - s.append(" * Prints a message saying this method has been invoked.\n"); - s.append(" */\n"); - } - - // Print the method signature - // - s.append(" public"); - if (Modifier.isStatic(m.getModifiers())) { - s.append(" static"); - } - s.append(" " + returnType); - s.append(" " + methodName); - s.append("("); - - Class[] params = m.getParameterTypes(); - Class temp; - String braces; - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(", "); - } - temp = params[i]; - braces = new String(""); - while (temp.isArray()) { - braces += "[]"; - temp = temp.getComponentType(); - } - s.append(unqualifyName(temp.getName()) + braces + " " + paramNames[i]); - addImport(importLines,temp); - } - s.append(")"); - - // Don't forget about exceptions - // - Class exceptions[] = m.getExceptionTypes(); - String throwsString = new String(""); - - if (exceptions.length > 0) { - s.append("\n"); - indent(s,12); - s.append("throws "); - for (int i = 0; i < exceptions.length; i++) { - if (i > 0) { - s.append(", "); - } - s.append(unqualifyName(exceptions[i].getName())); - addImport(importLines,exceptions[i]); - } - } - s.append(throwsString + " {\n"); - - // Now print out the contents of the method. - indent(s,8); - s.append("System.out.println(\"In the " + methodName - + " method of the " - + classPrefix + origName + " class.\");\n"); - if (methodName.equals("createUI")) { - indent(s,8); - s.append("return ui;\n"); - } else { - // If we have to return something, do so. - if (!returnType.equals("void")) { - Class rType = m.getReturnType(); - indent(s,8); - if (!rType.isPrimitive()) { - s.append("return null;\n"); - } else if (rType == Boolean.TYPE) { - s.append("return false;\n"); - } else if (rType == Character.TYPE) { - s.append("return '0';\n"); - } else { // byte, short, int, long, float, or double - s.append("return 0;\n"); - } - } - } - - indent(s,4); - s.append("}\n"); - } - - /** - * Takes a plaf class name (e.g., "MenuUI") and generates the corresponding - * TestALF UI Java source code (e.g., "TestALFMenuUI.java"). - */ - public static void generateFile(String prefixName, String className) { - try { - FileOutputStream fos; - PrintWriter outFile; - - importLines = new String(); - importLines += new String("import java.util.Vector;\n"); - - StringBuffer body = new StringBuffer(); - Class wee = Class.forName(prefixName + ".swing.plaf." + className); - String weeName = unqualifyName(wee.getName()); - String thisClassName = classPrefix + className; - addImport(importLines,wee); - - // Declare and initialize the shared UI object. - body.append("\n"); - body.append("////////////////////\n"); - body.append("// Shared UI object\n"); - body.append("////////////////////\n"); - body.append("private final static " + thisClassName - + " ui = new " + thisClassName + "();\n"); - - while (!weeName.equals("Object")) { - body.append("\n"); - body.append("////////////////////\n"); - body.append("// " + weeName + " methods\n"); - body.append("////////////////////\n"); - Method[] methods = wee.getDeclaredMethods(); - for (int i=0; i < methods.length; i++) { - if (Modifier.isPublic(methods[i].getModifiers())) { - addMethod(body,methods[i],className,weeName); - } - } - wee = wee.getSuperclass(); - weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - } - - fos = new FileOutputStream(classPrefix + className + ".java"); - outFile = new PrintWriter(fos); - StringBuffer outText = createPreamble(prefixName); - outText.append(importLines.toString() + "\n"); - addHeader(outText,className); - outText.append(body.toString()); - outText.append("}\n"); - outFile.write(outText.toString()); - outFile.flush(); - outFile.close(); - } catch (Exception e) { - System.err.println(e); - } - } - - /** - * D'Oh! Something bad happened. - */ - public static void usage(String s) throws IOException { - System.err.println("Usage: java TestALFGenerator []"); - throw new IllegalArgumentException(s); - } - - /** - * Takes the plaf directory name and generates the TestALF UI - * source code. - */ - public static void main(String[] args) throws IOException { - - if (args.length < 1) { - usage(""); - } - - String dirName = args[0]; - File dir = new File(dirName); - if (!dir.isDirectory()) { - System.err.println("No such directory: " + dirName); - usage(""); - } - - if (args.length > 1) { - packageName = args[1]; - } - - String plafUIs[] = dir.list(new UIJavaFilter()); - for (int i = 0; i < plafUIs.length; i++) { - generateFile("javax",stripExtension(plafUIs[i])); - } - } -} - -/** - * Only accepts file names of the form *UI.java. The one exception - * is not accepting ComponentUI.java because we don't need to generate - * a TestALF class for it. - */ -class UIJavaFilter implements FilenameFilter { - public boolean accept(File dir, String name) { - if (name.equals("ComponentUI.java")) { - return false; - } else if (name.endsWith("UI.java")) { - return true; - } else { - return false; - } - } -} diff --git a/jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java b/jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java deleted file mode 100644 index aadab48cac1..00000000000 --- a/jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -//package com.myco.myalaf; //search for myalaf for other refs to package name - - -package build.tools.automulti; - -import java.util.Vector; -import java.lang.reflect.Method; -import javax.swing.*; -import javax.swing.plaf.*; - -/** - *

An auxiliary look and feel used for testing the Multiplexing - * look and feel. - *

- * - * @see UIManager#addAuxiliaryLookAndFeel - * @see javax.swing.plaf.multi - * - * @author Kathy Walrath - * @author Will Walker - */ -public class TestALFLookAndFeel extends LookAndFeel { - -////////////////////////////// -// LookAndFeel methods -////////////////////////////// - - /** - * Returns a string, suitable for use in menus, - * that identifies this look and feel. - * - * @return a string such as "Test Auxiliary Look and Feel" - */ - public String getName() { - return "Test Auxiliary Look and Feel"; - } - - /** - * Returns a string, suitable for use by applications/services, - * that identifies this look and feel. - * - * @return "TestALF" - */ - public String getID() { - return "TestALF"; - } - - /** - * Returns a one-line description of this look and feel. - * - * @return a descriptive string such as "Allows multiple UI instances per component instance" - */ - public String getDescription() { - return "Allows multiple UI instances per component instance"; - } - - /** - * Returns false; - * this look and feel is not native to any platform. - * - * @return false - */ - public boolean isNativeLookAndFeel() { - return false; - } - - /** - * Returns true; - * every platform permits this look and feel. - * - * @return true - */ - public boolean isSupportedLookAndFeel() { - return true; - } - - /** - * Creates, initializes, and returns - * the look and feel specific defaults. - * For this look and feel, - * the defaults consist solely of - * mappings of UI class IDs - * (such as "ButtonUI") - * to ComponentUI class names - * (such as "com.myco.myalaf.MultiButtonUI"). - * - * @return an initialized UIDefaults object - * @see javax.swing.JComponent#getUIClassID - */ - public UIDefaults getDefaults() { - System.out.println("In the TestALFLookAndFeel getDefaults method."); - UIDefaults table = new TestALFUIDefaults(); - //String prefix = "com.myco.myalaf.TestALF"; - String prefix = "TestALF"; - Object[] uiDefaults = { - "ButtonUI", prefix + "ButtonUI", - "CheckBoxMenuItemUI", prefix + "MenuItemUI", - "CheckBoxUI", prefix + "ButtonUI", - "ColorChooserUI", prefix + "ColorChooserUI", - "ComboBoxUI", prefix + "ComboBoxUI", - "DesktopIconUI", prefix + "DesktopIconUI", - "DesktopPaneUI", prefix + "DesktopPaneUI", - "EditorPaneUI", prefix + "TextUI", - "FileChooserUI", prefix + "FileChooserUI", - "FormattedTextFieldUI", prefix + "TextUI", - "InternalFrameUI", prefix + "InternalFrameUI", - "LabelUI", prefix + "LabelUI", - "ListUI", prefix + "ListUI", - "MenuBarUI", prefix + "MenuBarUI", - "MenuItemUI", prefix + "MenuItemUI", - "MenuUI", prefix + "MenuItemUI", - "OptionPaneUI", prefix + "OptionPaneUI", - "PanelUI", prefix + "PanelUI", - "PasswordFieldUI", prefix + "TextUI", - "PopupMenuSeparatorUI", prefix + "SeparatorUI", - "PopupMenuUI", prefix + "PopupMenuUI", - "ProgressBarUI", prefix + "ProgressBarUI", - "RadioButtonMenuItemUI", prefix + "MenuItemUI", - "RadioButtonUI", prefix + "ButtonUI", - "RootPaneUI", prefix + "RootPaneUI", - "ScrollBarUI", prefix + "ScrollBarUI", - "ScrollPaneUI", prefix + "ScrollPaneUI", - "SeparatorUI", prefix + "SeparatorUI", - "SliderUI", prefix + "SliderUI", - "SpinnerUI", prefix + "SpinnerUI", - "SplitPaneUI", prefix + "SplitPaneUI", - "TabbedPaneUI", prefix + "TabbedPaneUI", - "TableHeaderUI", prefix + "TableHeaderUI", - "TableUI", prefix + "TableUI", - "TextAreaUI", prefix + "TextUI", - "TextFieldUI", prefix + "TextUI", - "TextPaneUI", prefix + "TextUI", - "ToggleButtonUI", prefix + "ButtonUI", - "ToolBarSeparatorUI", prefix + "SeparatorUI", - "ToolBarUI", prefix + "ToolBarUI", - "ToolTipUI", prefix + "ToolTipUI", - "TreeUI", prefix + "TreeUI", - "ViewportUI", prefix + "ViewportUI", - }; - - table.putDefaults(uiDefaults); - return table; - } - -} - -/** - * We want the Test auxiliary look and feel to be quiet and fallback - * gracefully if it cannot find a UI. This class overrides the - * getUIError method of UIDefaults, which is the method that - * emits error messages when it cannot find a UI class in the - * LAF. - */ -class TestALFUIDefaults extends UIDefaults { - protected void getUIError(String msg) { - System.err.println("Test auxiliary L&F: " + msg); - } -} From f7cbc30ff9e98bb8f78cfd49dab362f694a0a487 Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Tue, 8 Jul 2008 16:20:14 +0400 Subject: [PATCH 025/325] 6723013: Incomplete push for 6693974 Reviewed-by: art --- .../share/classes/sun/awt/EventQueueItem.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 jdk/src/share/classes/sun/awt/EventQueueItem.java diff --git a/jdk/src/share/classes/sun/awt/EventQueueItem.java b/jdk/src/share/classes/sun/awt/EventQueueItem.java new file mode 100644 index 00000000000..17c871db426 --- /dev/null +++ b/jdk/src/share/classes/sun/awt/EventQueueItem.java @@ -0,0 +1,37 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.awt; + +import java.awt.AWTEvent; + +public class EventQueueItem { + public AWTEvent event; + public EventQueueItem next; + + public EventQueueItem(AWTEvent evt) { + event = evt; + } +} From e2a366414cf30606390865ef7044efa145133348 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Tue, 8 Jul 2008 16:40:38 +0400 Subject: [PATCH 026/325] 4916852: RFE: LTP: BorderLayout Persistence Delegate should use 1.5 API Reviewed-by: peterz, loneid --- .../share/classes/java/beans/MetaData.java | 54 +++++++----- .../XMLEncoder/java_awt_BorderLayout.java | 82 +++++++++++++++++++ .../beans/XMLEncoder/java_awt_Component.java | 58 +++++++++++++ 3 files changed, 172 insertions(+), 22 deletions(-) create mode 100644 jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java create mode 100644 jdk/test/java/beans/XMLEncoder/java_awt_Component.java diff --git a/jdk/src/share/classes/java/beans/MetaData.java b/jdk/src/share/classes/java/beans/MetaData.java index 9bcd505c215..e2cb0326c69 100644 --- a/jdk/src/share/classes/java/beans/MetaData.java +++ b/jdk/src/share/classes/java/beans/MetaData.java @@ -986,14 +986,20 @@ class java_awt_Component_PersistenceDelegate extends DefaultPersistenceDelegate // null to defined values after the Windows are made visible - // special case them for now. if (!(oldInstance instanceof java.awt.Window)) { - String[] fieldNames = new String[]{"background", "foreground", "font"}; - for(int i = 0; i < fieldNames.length; i++) { - String name = fieldNames[i]; - Object oldValue = ReflectionUtils.getPrivateField(oldInstance, java.awt.Component.class, name, out.getExceptionListener()); - Object newValue = (newInstance == null) ? null : ReflectionUtils.getPrivateField(newInstance, java.awt.Component.class, name, out.getExceptionListener()); - if (oldValue != null && !oldValue.equals(newValue)) { - invokeStatement(oldInstance, "set" + NameGenerator.capitalize(name), new Object[]{oldValue}, out); - } + Object oldBackground = c.isBackgroundSet() ? c.getBackground() : null; + Object newBackground = c2.isBackgroundSet() ? c2.getBackground() : null; + if (!MetaData.equals(oldBackground, newBackground)) { + invokeStatement(oldInstance, "setBackground", new Object[] { oldBackground }, out); + } + Object oldForeground = c.isForegroundSet() ? c.getForeground() : null; + Object newForeground = c2.isForegroundSet() ? c2.getForeground() : null; + if (!MetaData.equals(oldForeground, newForeground)) { + invokeStatement(oldInstance, "setForeground", new Object[] { oldForeground }, out); + } + Object oldFont = c.isFontSet() ? c.getFont() : null; + Object newFont = c2.isFontSet() ? c2.getFont() : null; + if (!MetaData.equals(oldFont, newFont)) { + invokeStatement(oldInstance, "setFont", new Object[] { oldFont }, out); } } @@ -1104,26 +1110,30 @@ class java_awt_List_PersistenceDelegate extends DefaultPersistenceDelegate { // BorderLayout class java_awt_BorderLayout_PersistenceDelegate extends DefaultPersistenceDelegate { + private static final String[] CONSTRAINTS = { + BorderLayout.NORTH, + BorderLayout.SOUTH, + BorderLayout.EAST, + BorderLayout.WEST, + BorderLayout.CENTER, + BorderLayout.PAGE_START, + BorderLayout.PAGE_END, + BorderLayout.LINE_START, + BorderLayout.LINE_END, + }; + @Override protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); - String[] locations = {"north", "south", "east", "west", "center"}; - String[] names = {java.awt.BorderLayout.NORTH, java.awt.BorderLayout.SOUTH, - java.awt.BorderLayout.EAST, java.awt.BorderLayout.WEST, - java.awt.BorderLayout.CENTER}; - for(int i = 0; i < locations.length; i++) { - Object oldC = ReflectionUtils.getPrivateField(oldInstance, - java.awt.BorderLayout.class, - locations[i], - out.getExceptionListener()); - Object newC = ReflectionUtils.getPrivateField(newInstance, - java.awt.BorderLayout.class, - locations[i], - out.getExceptionListener()); + BorderLayout oldLayout = (BorderLayout) oldInstance; + BorderLayout newLayout = (BorderLayout) newInstance; + for (String constraints : CONSTRAINTS) { + Object oldC = oldLayout.getLayoutComponent(constraints); + Object newC = newLayout.getLayoutComponent(constraints); // Pending, assume any existing elements are OK. if (oldC != null && newC == null) { invokeStatement(oldInstance, "addLayoutComponent", - new Object[]{oldC, names[i]}, out); + new Object[] { oldC, constraints }, out); } } } diff --git a/jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java b/jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java new file mode 100644 index 00000000000..1eba0c21bac --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/java_awt_BorderLayout.java @@ -0,0 +1,82 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4916852 + * @summary Tests BorderLayout encoding + * @author Sergey Malenkov + */ + +import java.awt.BorderLayout; +import javax.swing.JLabel; + +public final class java_awt_BorderLayout extends AbstractTest { + private static final String[] CONSTRAINTS = { + BorderLayout.NORTH, + BorderLayout.SOUTH, + BorderLayout.EAST, + BorderLayout.WEST, + BorderLayout.CENTER, + BorderLayout.PAGE_START, + BorderLayout.PAGE_END, + BorderLayout.LINE_START, + BorderLayout.LINE_END, + }; + + public static void main(String[] args) { + new java_awt_BorderLayout().test(true); + } + + @Override + protected BorderLayout getObject() { + BorderLayout layout = new BorderLayout(); + update(layout, BorderLayout.EAST); + update(layout, BorderLayout.WEST); + update(layout, BorderLayout.NORTH); + update(layout, BorderLayout.SOUTH); + return layout; + } + + @Override + protected BorderLayout getAnotherObject() { + BorderLayout layout = getObject(); + update(layout, BorderLayout.CENTER); + return layout; + } + + @Override + protected void validate(BorderLayout before, BorderLayout after) { + super.validate(before, after); + + BeanValidator validator = new BeanValidator(); + for (String constraint : CONSTRAINTS) { + validator.validate(before.getLayoutComponent(constraint), + after.getLayoutComponent(constraint)); + } + } + + private static void update(BorderLayout layout, String constraints) { + layout.addLayoutComponent(new JLabel(constraints), constraints); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/java_awt_Component.java b/jdk/test/java/beans/XMLEncoder/java_awt_Component.java new file mode 100644 index 00000000000..a98424a3b7a --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/java_awt_Component.java @@ -0,0 +1,58 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4916852 + * @summary Tests Component encoding (background, foreground and font) + * @author Sergey Malenkov + */ + +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; + +public final class java_awt_Component extends AbstractTest { + public static void main(String[] args) { + new java_awt_Component().test(true); + } + + @Override + protected Component getObject() { + Component component = new MyComponent(); + component.setBackground(Color.WHITE); + component.setFont(new Font(null, Font.BOLD, 5)); + return component; + } + + @Override + protected Component getAnotherObject() { + Component component = new MyComponent(); + component.setForeground(Color.BLACK); + component.setFont(new Font(null, Font.ITALIC, 6)); + return component; + } + + public static final class MyComponent extends Component { + } +} \ No newline at end of file From 9ac27197dfebf5f24f62dbf807d5917070d94f2e Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Wed, 9 Jul 2008 12:03:16 +0800 Subject: [PATCH 027/325] 6480981: keytool should be able to import certificates from remote SSL servers Reviewed-by: vinnie, wetmore --- .../classes/sun/security/tools/KeyTool.java | 129 ++++++++++++++---- .../classes/sun/security/util/Resources.java | 8 +- .../sun/security/tools/keytool/PrintSSL.java | 55 ++++++++ .../sun/security/tools/keytool/printssl.sh | 58 ++++++++ 4 files changed, 218 insertions(+), 32 deletions(-) create mode 100644 jdk/test/sun/security/tools/keytool/PrintSSL.java create mode 100644 jdk/test/sun/security/tools/keytool/printssl.sh diff --git a/jdk/src/share/classes/sun/security/tools/KeyTool.java b/jdk/src/share/classes/sun/security/tools/KeyTool.java index 41cfa2dc9ee..68fb2fa953e 100644 --- a/jdk/src/share/classes/sun/security/tools/KeyTool.java +++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,35 +26,23 @@ package sun.security.tools; import java.io.*; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.security.Key; import java.security.PublicKey; import java.security.PrivateKey; import java.security.Security; import java.security.Signature; -import java.security.SignatureException; import java.security.UnrecoverableEntryException; import java.security.UnrecoverableKeyException; import java.security.Principal; import java.security.Provider; import java.security.Identity; -import java.security.Signer; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.cert.CertificateException; -import java.security.interfaces.DSAParams; -import java.security.interfaces.DSAPrivateKey; -import java.security.interfaces.DSAPublicKey; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; import java.text.Collator; import java.text.MessageFormat; import java.util.*; @@ -62,7 +50,6 @@ import java.lang.reflect.Constructor; import java.net.URL; import java.net.URLClassLoader; -import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import sun.security.util.ObjectIdentifier; import sun.security.pkcs.PKCS10; @@ -72,11 +59,16 @@ import sun.security.provider.SystemIdentity; import sun.security.provider.X509Factory; import sun.security.util.DerOutputStream; import sun.security.util.Password; -import sun.security.util.Resources; import sun.security.util.PathList; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; import sun.security.x509.*; import static java.security.KeyStore.*; @@ -132,6 +124,7 @@ public final class KeyTool { private String ksfname = null; private File ksfile = null; private InputStream ksStream = null; // keystore stream + private String sslserver = null; private KeyStore keyStore = null; private boolean token = false; private boolean nullStream = false; @@ -347,6 +340,9 @@ public final class KeyTool { } else if (collator.compare(flags, "-file") == 0) { if (++i == args.length) errorNeedArgument(flags); filename = args[i]; + } else if (collator.compare(flags, "-sslserver") == 0) { + if (++i == args.length) errorNeedArgument(flags); + sslserver = args[i]; } else if (collator.compare(flags, "-srckeystore") == 0) { if (++i == args.length) errorNeedArgument(flags); srcksfname = args[i]; @@ -924,17 +920,7 @@ public final class KeyTool { doPrintEntries(out); } } else if (command == PRINTCERT) { - InputStream inStream = System.in; - if (filename != null) { - inStream = new FileInputStream(filename); - } - try { - doPrintCert(inStream, out); - } finally { - if (inStream != System.in) { - inStream.close(); - } - } + doPrintCert(out); } else if (command == SELFCERT) { doSelfCert(alias, dname, sigAlgName); kssave = true; @@ -1744,7 +1730,7 @@ public final class KeyTool { * Reads a certificate (or certificate chain) and prints its contents in * a human readbable format. */ - private void doPrintCert(InputStream in, PrintStream out) + private void printCertFromStream(InputStream in, PrintStream out) throws Exception { Collection c = null; @@ -1770,13 +1756,98 @@ public final class KeyTool { Object[] source = {new Integer(i + 1)}; out.println(form.format(source)); } - printX509Cert(x509Cert, out); + if (rfc) dumpCert(x509Cert, out); + else printX509Cert(x509Cert, out); if (i < (certs.length-1)) { out.println(); } } } + private void doPrintCert(final PrintStream out) throws Exception { + if (sslserver != null) { + SSLContext sc = SSLContext.getInstance("SSL"); + final boolean[] certPrinted = new boolean[1]; + sc.init(null, new TrustManager[] { + new X509TrustManager() { + + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + for (int i=0; i 0) { + certPrinted[0] = true; + } + } + } + }, null); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + HttpsURLConnection.setDefaultHostnameVerifier( + new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + // HTTPS instead of raw SSL, so that -Dhttps.proxyHost and + // -Dhttps.proxyPort can be used. Since we only go through + // the handshake process, an HTTPS server is not needed. + // This program should be able to deal with any SSL-based + // network service. + Exception ex = null; + try { + new URL("https://" + sslserver).openConnection().connect(); + } catch (Exception e) { + ex = e; + } + // If the certs are not printed out, we consider it an error even + // if the URL connection is successful. + if (!certPrinted[0]) { + Exception e = new Exception( + rb.getString("No certificate from the SSL server")); + if (ex != null) { + e.initCause(ex); + } + throw e; + } + } else { + InputStream inStream = System.in; + if (filename != null) { + inStream = new FileInputStream(filename); + } + try { + printCertFromStream(inStream, out); + } finally { + if (inStream != System.in) { + inStream.close(); + } + } + } + } /** * Creates a self-signed certificate, and stores it as a single-element * certificate chain. @@ -3127,7 +3198,7 @@ public final class KeyTool { System.err.println(); System.err.println(rb.getString - ("-printcert [-v] [-file ]")); + ("-printcert [-v] [-rfc] [-file | -sslserver ]")); System.err.println(); System.err.println(rb.getString diff --git a/jdk/src/share/classes/sun/security/util/Resources.java b/jdk/src/share/classes/sun/security/util/Resources.java index 7f765ee368b..0f5982183ad 100644 --- a/jdk/src/share/classes/sun/security/util/Resources.java +++ b/jdk/src/share/classes/sun/security/util/Resources.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -386,8 +386,10 @@ public class Resources extends java.util.ListResourceBundle { {"\t [-alias ]", "\t [-alias ]"}, /** rest is same as -certreq starting from -keystore **/ - {"-printcert [-v] [-file ]", - "-printcert [-v] [-file ]"}, + {"-printcert [-v] [-rfc] [-file | -sslserver ]", + "-printcert [-v] [-rfc] [-file | -sslserver ]"}, + {"No certificate from the SSL server", + "No certificate from the SSL server"}, //{"-selfcert [-v] [-protected]", // "-selfcert [-v] [-protected]"}, diff --git a/jdk/test/sun/security/tools/keytool/PrintSSL.java b/jdk/test/sun/security/tools/keytool/PrintSSL.java new file mode 100644 index 00000000000..7e9ce7b9534 --- /dev/null +++ b/jdk/test/sun/security/tools/keytool/PrintSSL.java @@ -0,0 +1,55 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +// Read printssl.sh, this Java program starts an SSL server + +import java.net.ServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSocket; + +public class PrintSSL { + public static void main(String[] args) throws Exception { + System.setProperty("javax.net.ssl.keyStorePassword", "passphrase"); + System.setProperty("javax.net.ssl.keyStore", + System.getProperty("test.src", "./") + "/../../ssl/etc/keystore"); + SSLServerSocketFactory sslssf = + (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); + final ServerSocket server = sslssf.createServerSocket(0); + System.out.println(server.getLocalPort()); + System.out.flush(); + Thread t = new Thread() { + public void run() { + try { + Thread.sleep(30000); + server.close(); + } catch (Exception e) { + ; + } + throw new RuntimeException("Timeout"); + } + }; + t.setDaemon(true); + t.start(); + ((SSLSocket)server.accept()).startHandshake(); + } +} diff --git a/jdk/test/sun/security/tools/keytool/printssl.sh b/jdk/test/sun/security/tools/keytool/printssl.sh new file mode 100644 index 00000000000..9fc19cd9b20 --- /dev/null +++ b/jdk/test/sun/security/tools/keytool/printssl.sh @@ -0,0 +1,58 @@ +# +# Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. +# 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 +# published by the Free Software Foundation. +# +# 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. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + +# @test +# @bug 6480981 +# @summary keytool should be able to import certificates from remote SSL servers + +if [ "${TESTSRC}" = "" ] ; then + TESTSRC="." +fi +if [ "${TESTJAVA}" = "" ] ; then + echo "TESTJAVA not set. Test cannot execute." + echo "FAILED!!!" + exit 1 +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + SunOS | Linux ) + FS="/" + ;; + Windows_* ) + FS="\\" + ;; + * ) + echo "Unrecognized operating system!" + exit 1; + ;; +esac + +${TESTJAVA}${FS}bin${FS}javac -d . ${TESTSRC}${FS}PrintSSL.java || exit 10 +${TESTJAVA}${FS}bin${FS}java -Dtest.src=$TESTSRC PrintSSL | ( read PORT; ${TESTJAVA}${FS}bin${FS}keytool -printcert -sslserver localhost:$PORT ) +status=$? + +rm PrintSSL*.class + +exit $status From 1bdca97b29cf1ccfa27349d1198d07849df1c256 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 9 Jul 2008 15:25:38 +0400 Subject: [PATCH 028/325] 6351692: catch(Throwable) in java.beans.MetaData preventing thread shutdown Reviewed-by: peterz, loneid --- .../share/classes/java/beans/DefaultPersistenceDelegate.java | 2 +- jdk/src/share/classes/java/beans/EventHandler.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java index 6553a517200..5339aba83e4 100644 --- a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java +++ b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java @@ -298,7 +298,7 @@ public class DefaultPersistenceDelegate extends PersistenceDelegate { oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{}); newL = (EventListener[])MethodUtil.invoke(m, newInstance, new Object[]{}); } - catch (Throwable e2) { + catch (Exception e2) { try { Method m = type.getMethod("getListeners", new Class[]{Class.class}); oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{listenerType}); diff --git a/jdk/src/share/classes/java/beans/EventHandler.java b/jdk/src/share/classes/java/beans/EventHandler.java index 9d50dea91d1..43cd76ff383 100644 --- a/jdk/src/share/classes/java/beans/EventHandler.java +++ b/jdk/src/share/classes/java/beans/EventHandler.java @@ -404,7 +404,7 @@ public class EventHandler implements InvocationHandler { Object newTarget = MethodUtil.invoke(getter, target, new Object[]{}); return applyGetters(newTarget, rest); } - catch (Throwable e) { + catch (Exception e) { throw new RuntimeException("Failed to call method: " + first + " on " + target, e); } From 3916f38bd49205164c4f8c68c12cb46ee64204da Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 9 Jul 2008 19:29:07 +0400 Subject: [PATCH 029/325] 4994637: LTP: java.beans.java_util_Map_PersistenceDelegate: ConcurrentModificationException Reviewed-by: peterz, loneid --- .../share/classes/java/beans/MetaData.java | 2 +- .../java/beans/XMLEncoder/Test4994637.java | 58 +++++++++++++++++++ .../beans/XMLEncoder/java_util_HashMap.java | 24 ++++++-- 3 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 jdk/test/java/beans/XMLEncoder/Test4994637.java diff --git a/jdk/src/share/classes/java/beans/MetaData.java b/jdk/src/share/classes/java/beans/MetaData.java index e2cb0326c69..5d8fd697918 100644 --- a/jdk/src/share/classes/java/beans/MetaData.java +++ b/jdk/src/share/classes/java/beans/MetaData.java @@ -650,7 +650,7 @@ class java_util_Map_PersistenceDelegate extends DefaultPersistenceDelegate { // Remove the new elements. // Do this first otherwise we undo the adding work. if (newMap != null) { - for ( Object newKey : newMap.keySet() ) { + for (Object newKey : newMap.keySet().toArray()) { // PENDING: This "key" is not in the right environment. if (!oldMap.containsKey(newKey)) { invokeStatement(oldInstance, "remove", new Object[]{newKey}, out); diff --git a/jdk/test/java/beans/XMLEncoder/Test4994637.java b/jdk/test/java/beans/XMLEncoder/Test4994637.java new file mode 100644 index 00000000000..5476a8100bb --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/Test4994637.java @@ -0,0 +1,58 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4994637 + * @summary Tests custom map encoding + * @author Sergey Malenkov + */ + +import java.util.HashMap; + +public final class Test4994637 extends AbstractTest { + public static void main(String[] args) { + new Test4994637().test(true); + } + + @Override + protected CustomMap getObject() { + return new CustomMap(); + } + + @Override + protected CustomMap getAnotherObject() { + CustomMap map = new CustomMap(); + map.clear(); + map.put(null, "zero"); + return map; + } + + public static final class CustomMap extends HashMap { + public CustomMap() { + put("1", "one"); + put("2", "two"); + put("3", "three"); + } + } +} diff --git a/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java b/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java index 9a9771f80db..d9058003e4d 100644 --- a/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java +++ b/jdk/test/java/beans/XMLEncoder/java_util_HashMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2006-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 4631471 4921212 + * @bug 4631471 4921212 4994637 * @summary Tests HashMap encoding * @author Sergey Malenkov */ @@ -36,10 +36,17 @@ public final class java_util_HashMap extends AbstractTest> { new java_util_HashMap().test(true); } + @Override protected Map getObject() { - return new HashMap(); + Map map = new HashMap(); + map.put(null, null); + map.put("key", "value"); + map.put("key-null", "null-value"); + map.put("way", "remove"); + return map; } + @Override protected Map getAnotherObject() { Map map = new HashMap(); map.put(null, "null-value"); @@ -48,6 +55,7 @@ public final class java_util_HashMap extends AbstractTest> { return map; } + @Override protected void validate(Map before, Map after) { super.validate(before, after); validate(before); @@ -55,10 +63,18 @@ public final class java_util_HashMap extends AbstractTest> { } private static void validate(Map map) { - if (!map.isEmpty()) { + switch (map.size()) { + case 3: validate(map, null, "null-value"); validate(map, "key", "value"); validate(map, "key-null", null); + break; + case 4: + validate(map, null, null); + validate(map, "key", "value"); + validate(map, "key-null", "null-value"); + validate(map, "way", "remove"); + break; } } From 18dbebd14308d8aa9a2c30ffe2f790f7cff46bd7 Mon Sep 17 00:00:00 2001 From: Jon Masamitsu Date: Wed, 9 Jul 2008 15:08:55 -0700 Subject: [PATCH 030/325] 6672698: mangle_unused_area() should not remangle the entire heap at each collection Maintain a high water mark for the allocations in a space and mangle only up to that high water mark. Reviewed-by: ysr, apetrusenko --- .../binaryTreeDictionary.cpp | 11 +- .../compactibleFreeListSpace.cpp | 2 +- .../freeBlockDictionary.hpp | 1 - .../concurrentMarkSweep/freeChunk.hpp | 2 + .../includeDB_gc_concurrentMarkSweep | 2 + .../vm/gc_implementation/includeDB_gc_parNew | 16 +- .../includeDB_gc_parallelScavenge | 21 +- .../vm/gc_implementation/includeDB_gc_shared | 2 + .../parNew/asParNewGeneration.cpp | 35 ++- .../parNew/parNewGeneration.cpp | 16 +- .../parallelScavenge/asPSYoungGen.cpp | 112 +++++++-- .../parallelScavenge/cardTableExtension.cpp | 6 +- .../parallelScavenge/parallelScavengeHeap.cpp | 20 ++ .../parallelScavenge/parallelScavengeHeap.hpp | 6 + .../parallelScavenge/psMarkSweep.cpp | 16 +- .../parallelScavenge/psMarkSweepDecorator.cpp | 4 +- .../parallelScavenge/psOldGen.cpp | 42 +++- .../parallelScavenge/psOldGen.hpp | 4 + .../parallelScavenge/psParallelCompact.cpp | 36 ++- .../parallelScavenge/psParallelCompact.hpp | 93 ++++++++ .../parallelScavenge/psScavenge.cpp | 19 +- .../parallelScavenge/psYoungGen.cpp | 214 +++++++++++++++--- .../parallelScavenge/psYoungGen.hpp | 8 + .../shared/mutableNUMASpace.cpp | 63 ++++-- .../shared/mutableNUMASpace.hpp | 13 +- .../gc_implementation/shared/mutableSpace.cpp | 55 ++++- .../gc_implementation/shared/mutableSpace.hpp | 42 +++- .../shared/spaceDecorator.cpp | 140 ++++++++++++ .../shared/spaceDecorator.hpp | 141 ++++++++++++ hotspot/src/share/vm/includeDB_core | 10 + hotspot/src/share/vm/includeDB_features | 1 + .../src/share/vm/memory/defNewGeneration.cpp | 118 ++++++++-- .../src/share/vm/memory/defNewGeneration.hpp | 15 +- hotspot/src/share/vm/memory/dump.cpp | 2 +- .../src/share/vm/memory/genCollectedHeap.cpp | 29 +++ .../src/share/vm/memory/genCollectedHeap.hpp | 6 + hotspot/src/share/vm/memory/genMarkSweep.cpp | 4 + hotspot/src/share/vm/memory/generation.cpp | 21 +- hotspot/src/share/vm/memory/generation.hpp | 9 + hotspot/src/share/vm/memory/space.cpp | 81 +++++-- hotspot/src/share/vm/memory/space.hpp | 53 ++++- hotspot/src/share/vm/runtime/globals.hpp | 8 +- .../share/vm/utilities/globalDefinitions.hpp | 6 +- 43 files changed, 1299 insertions(+), 206 deletions(-) create mode 100644 hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.cpp create mode 100644 hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.hpp diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/binaryTreeDictionary.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/binaryTreeDictionary.cpp index 91d381d5501..5064f1104b3 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/binaryTreeDictionary.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/binaryTreeDictionary.cpp @@ -71,8 +71,15 @@ TreeList* TreeList::as_TreeList(TreeChunk* tc) { TreeList* TreeList::as_TreeList(HeapWord* addr, size_t size) { TreeChunk* tc = (TreeChunk*) addr; assert(size >= sizeof(TreeChunk), "Chunk is too small for a TreeChunk"); - assert(tc->size() == 0 && tc->prev() == NULL && tc->next() == NULL, - "Space should be clear"); + // The space in the heap will have been mangled initially but + // is not remangled when a free chunk is returned to the free list + // (since it is used to maintain the chunk on the free list). + assert((ZapUnusedHeapArea && + SpaceMangler::is_mangled((HeapWord*) tc->size_addr()) && + SpaceMangler::is_mangled((HeapWord*) tc->prev_addr()) && + SpaceMangler::is_mangled((HeapWord*) tc->next_addr())) || + (tc->size() == 0 && tc->prev() == NULL && tc->next() == NULL), + "Space should be clear or mangled"); tc->setSize(size); tc->linkPrev(NULL); tc->linkNext(NULL); diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp index 245807e7319..a0c86f686f0 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp @@ -54,7 +54,7 @@ CompactibleFreeListSpace::CompactibleFreeListSpace(BlockOffsetSharedArray* bs, _collector(NULL) { _bt.set_space(this); - initialize(mr, true); + initialize(mr, SpaceDecorator::Clear, SpaceDecorator::Mangle); // We have all of "mr", all of which we place in the dictionary // as one big chunk. We'll need to decide here which of several // possible alternative dictionary implementations to use. For diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeBlockDictionary.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeBlockDictionary.hpp index b238c023674..fd0448c1a15 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeBlockDictionary.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeBlockDictionary.hpp @@ -22,7 +22,6 @@ * */ - // A FreeBlockDictionary is an abstract superclass that will allow // a number of alternative implementations in the future. class FreeBlockDictionary: public CHeapObj { diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeChunk.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeChunk.hpp index be2479475a8..e356dc05092 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeChunk.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeChunk.hpp @@ -85,6 +85,8 @@ class FreeChunk VALUE_OBJ_CLASS_SPEC { } debug_only(void* prev_addr() const { return (void*)&_prev; }) + debug_only(void* next_addr() const { return (void*)&_next; }) + debug_only(void* size_addr() const { return (void*)&_size; }) size_t size() const volatile { LP64_ONLY(if (UseCompressedOops) return mark()->get_size(); else ) diff --git a/hotspot/src/share/vm/gc_implementation/includeDB_gc_concurrentMarkSweep b/hotspot/src/share/vm/gc_implementation/includeDB_gc_concurrentMarkSweep index d3e253edc7b..621c3f9b94e 100644 --- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_concurrentMarkSweep +++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_concurrentMarkSweep @@ -28,6 +28,7 @@ binaryTreeDictionary.cpp allocationStats.hpp binaryTreeDictionary.cpp binaryTreeDictionary.hpp binaryTreeDictionary.cpp globals.hpp binaryTreeDictionary.cpp ostream.hpp +binaryTreeDictionary.cpp spaceDecorator.hpp binaryTreeDictionary.hpp freeBlockDictionary.hpp binaryTreeDictionary.hpp freeList.hpp @@ -114,6 +115,7 @@ compactibleFreeListSpace.cpp java.hpp compactibleFreeListSpace.cpp liveRange.hpp compactibleFreeListSpace.cpp oop.inline.hpp compactibleFreeListSpace.cpp resourceArea.hpp +compactibleFreeListSpace.cpp spaceDecorator.hpp compactibleFreeListSpace.cpp universe.inline.hpp compactibleFreeListSpace.cpp vmThread.hpp diff --git a/hotspot/src/share/vm/gc_implementation/includeDB_gc_parNew b/hotspot/src/share/vm/gc_implementation/includeDB_gc_parNew index 7c926792262..e5e5bc17b7c 100644 --- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_parNew +++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_parNew @@ -22,16 +22,17 @@ // // -asParNewGeneration.hpp adaptiveSizePolicy.hpp -asParNewGeneration.hpp parNewGeneration.hpp +asParNewGeneration.hpp adaptiveSizePolicy.hpp +asParNewGeneration.hpp parNewGeneration.hpp -asParNewGeneration.cpp asParNewGeneration.hpp -asParNewGeneration.cpp cmsAdaptiveSizePolicy.hpp +asParNewGeneration.cpp asParNewGeneration.hpp +asParNewGeneration.cpp cmsAdaptiveSizePolicy.hpp asParNewGeneration.cpp cmsGCAdaptivePolicyCounters.hpp -asParNewGeneration.cpp defNewGeneration.inline.hpp -asParNewGeneration.cpp oop.pcgc.inline.hpp -asParNewGeneration.cpp parNewGeneration.hpp +asParNewGeneration.cpp defNewGeneration.inline.hpp +asParNewGeneration.cpp oop.pcgc.inline.hpp +asParNewGeneration.cpp parNewGeneration.hpp asParNewGeneration.cpp referencePolicy.hpp +asParNewGeneration.cpp spaceDecorator.hpp parCardTableModRefBS.cpp allocation.inline.hpp parCardTableModRefBS.cpp cardTableModRefBS.hpp @@ -75,6 +76,7 @@ parNewGeneration.cpp referencePolicy.hpp parNewGeneration.cpp resourceArea.hpp parNewGeneration.cpp sharedHeap.hpp parNewGeneration.cpp space.hpp +parNewGeneration.cpp spaceDecorator.hpp parNewGeneration.cpp workgroup.hpp parNewGeneration.hpp defNewGeneration.hpp diff --git a/hotspot/src/share/vm/gc_implementation/includeDB_gc_parallelScavenge b/hotspot/src/share/vm/gc_implementation/includeDB_gc_parallelScavenge index 8a2a7a6127b..3406c59d91f 100644 --- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_parallelScavenge +++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_parallelScavenge @@ -53,14 +53,15 @@ asPSOldGen.cpp java.hpp asPSOldGen.cpp oop.inline.hpp asPSOldGen.cpp parallelScavengeHeap.hpp asPSOldGen.cpp psMarkSweepDecorator.hpp -asPSOldGen.cpp asPSOldGen.hpp +asPSOldGen.cpp asPSOldGen.hpp asPSYoungGen.hpp generationCounters.hpp asPSYoungGen.hpp mutableSpace.hpp asPSYoungGen.hpp objectStartArray.hpp asPSYoungGen.hpp spaceCounters.hpp asPSYoungGen.hpp psVirtualspace.hpp -asPSYoungGen.hpp psYoungGen.hpp +asPSYoungGen.hpp psYoungGen.hpp +asPSYoungGen.hpp spaceDecorator.hpp asPSYoungGen.cpp gcUtil.hpp asPSYoungGen.cpp java.hpp @@ -68,8 +69,9 @@ asPSYoungGen.cpp oop.inline.hpp asPSYoungGen.cpp parallelScavengeHeap.hpp asPSYoungGen.cpp psMarkSweepDecorator.hpp asPSYoungGen.cpp psScavenge.hpp -asPSYoungGen.cpp asPSYoungGen.hpp -asPSYoungGen.cpp psYoungGen.hpp +asPSYoungGen.cpp asPSYoungGen.hpp +asPSYoungGen.cpp psYoungGen.hpp +asPSYoungGen.cpp spaceDecorator.hpp cardTableExtension.cpp cardTableExtension.hpp cardTableExtension.cpp gcTaskManager.hpp @@ -225,6 +227,7 @@ psMarkSweep.cpp psYoungGen.hpp psMarkSweep.cpp referencePolicy.hpp psMarkSweep.cpp referenceProcessor.hpp psMarkSweep.cpp safepoint.hpp +psMarkSweep.cpp spaceDecorator.hpp psMarkSweep.cpp symbolTable.hpp psMarkSweep.cpp systemDictionary.hpp psMarkSweep.cpp vmThread.hpp @@ -239,6 +242,7 @@ psMarkSweepDecorator.cpp oop.inline.hpp psMarkSweepDecorator.cpp parallelScavengeHeap.hpp psMarkSweepDecorator.cpp psMarkSweep.hpp psMarkSweepDecorator.cpp psMarkSweepDecorator.hpp +psMarkSweepDecorator.cpp spaceDecorator.hpp psMarkSweepDecorator.cpp systemDictionary.hpp psMarkSweepDecorator.hpp mutableSpace.hpp @@ -290,6 +294,7 @@ psOldGen.cpp oop.inline.hpp psOldGen.cpp parallelScavengeHeap.hpp psOldGen.cpp psMarkSweepDecorator.hpp psOldGen.cpp psOldGen.hpp +psOldGen.cpp spaceDecorator.hpp psOldGen.hpp psGenerationCounters.hpp psOldGen.hpp mutableSpace.hpp @@ -351,6 +356,7 @@ psScavenge.cpp psTasks.hpp psScavenge.cpp referencePolicy.hpp psScavenge.cpp referenceProcessor.hpp psScavenge.cpp resourceArea.hpp +psScavenge.cpp spaceDecorator.hpp psScavenge.cpp threadCritical.hpp psScavenge.cpp vmThread.hpp psScavenge.cpp vm_operations.hpp @@ -409,8 +415,8 @@ psVirtualspace.hpp virtualspace.hpp psVirtualspace.cpp os.hpp psVirtualspace.cpp os_.inline.hpp -psVirtualspace.cpp psVirtualspace.hpp -psVirtualspace.cpp virtualspace.hpp +psVirtualspace.cpp psVirtualspace.hpp +psVirtualspace.cpp virtualspace.hpp psYoungGen.cpp gcUtil.hpp psYoungGen.cpp java.hpp @@ -419,7 +425,8 @@ psYoungGen.cpp parallelScavengeHeap.hpp psYoungGen.cpp psMarkSweepDecorator.hpp psYoungGen.cpp psScavenge.hpp psYoungGen.cpp psYoungGen.hpp -psYoungGen.cpp mutableNUMASpace.hpp +psYoungGen.cpp mutableNUMASpace.hpp +psYoungGen.cpp spaceDecorator.hpp psYoungGen.hpp psGenerationCounters.hpp psYoungGen.hpp mutableSpace.hpp diff --git a/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared b/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared index 367fccf4807..7729f5eb830 100644 --- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared +++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared @@ -56,6 +56,7 @@ markSweep.inline.hpp psParallelCompact.hpp mutableNUMASpace.cpp mutableNUMASpace.hpp mutableNUMASpace.cpp oop.inline.hpp mutableNUMASpace.cpp sharedHeap.hpp +mutableNUMASpace.cpp spaceDecorator.hpp mutableNUMASpace.cpp thread_.inline.hpp mutableNUMASpace.hpp mutableSpace.hpp @@ -64,6 +65,7 @@ mutableNUMASpace.hpp gcUtil.hpp mutableSpace.cpp mutableSpace.hpp mutableSpace.cpp oop.inline.hpp mutableSpace.cpp safepoint.hpp +mutableSpace.cpp spaceDecorator.hpp mutableSpace.cpp thread.hpp spaceCounters.cpp resourceArea.hpp diff --git a/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp b/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp index fa4a554b976..abdeb185a93 100644 --- a/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp @@ -162,10 +162,9 @@ bool ASParNewGeneration::resize_generation(size_t eden_size, // Grow the generation size_t change = desired_size - orig_size; assert(change % alignment == 0, "just checking"); - if (!virtual_space()->expand_by(change)) { + if (expand(change)) { return false; // Error if we fail to resize! } - size_changed = true; } else if (desired_size < orig_size) { size_t desired_change = orig_size - desired_size; @@ -222,7 +221,9 @@ void ASParNewGeneration::reset_survivors_after_shrink() { // Was there a shrink of the survivor space? if (new_end < to()->end()) { MemRegion mr(to()->bottom(), new_end); - to()->initialize(mr, false /* clear */); + to()->initialize(mr, + SpaceDecorator::DontClear, + SpaceDecorator::DontMangle); } } } @@ -322,9 +323,7 @@ void ASParNewGeneration::resize_spaces(size_t requested_eden_size, pointer_delta(from_start, eden_start, sizeof(char))); } -// tty->print_cr("eden_size before: " SIZE_FORMAT, eden_size); eden_size = align_size_down(eden_size, alignment); -// tty->print_cr("eden_size after: " SIZE_FORMAT, eden_size); eden_end = eden_start + eden_size; assert(eden_end >= eden_start, "addition overflowed") @@ -501,11 +500,31 @@ void ASParNewGeneration::resize_spaces(size_t requested_eden_size, size_t old_from = from()->capacity(); size_t old_to = to()->capacity(); + // If not clearing the spaces, do some checking to verify that + // the spaces are already mangled. + + // Must check mangling before the spaces are reshaped. Otherwise, + // the bottom or end of one space may have moved into another + // a failure of the check may not correctly indicate which space + // is not properly mangled. + if (ZapUnusedHeapArea) { + HeapWord* limit = (HeapWord*) virtual_space()->high(); + eden()->check_mangled_unused_area(limit); + from()->check_mangled_unused_area(limit); + to()->check_mangled_unused_area(limit); + } + // The call to initialize NULL's the next compaction space - eden()->initialize(edenMR, true); + eden()->initialize(edenMR, + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); eden()->set_next_compaction_space(from()); - to()->initialize(toMR , true); - from()->initialize(fromMR, false); // Note, not cleared! + to()->initialize(toMR , + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); + from()->initialize(fromMR, + SpaceDecorator::DontClear, + SpaceDecorator::DontMangle); assert(from()->top() == old_from_top, "from top changed!"); diff --git a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp index 8beea55ee97..e2f7ef1541c 100644 --- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp @@ -727,7 +727,7 @@ void ParNewGeneration::collect(bool full, SpecializationStats::clear(); age_table()->clear(); - to()->clear(); + to()->clear(SpaceDecorator::Mangle); gch->save_marks(); assert(workers != NULL, "Need parallel worker threads."); @@ -793,8 +793,18 @@ void ParNewGeneration::collect(bool full, } if (!promotion_failed()) { // Swap the survivor spaces. - eden()->clear(); - from()->clear(); + eden()->clear(SpaceDecorator::Mangle); + from()->clear(SpaceDecorator::Mangle); + if (ZapUnusedHeapArea) { + // This is now done here because of the piece-meal mangling which + // can check for valid mangling at intermediate points in the + // collection(s). When a minor collection fails to collect + // sufficient space resizing of the young generation can occur + // an redistribute the spaces in the young generation. Mangle + // here so that unzapped regions don't get distributed to + // other spaces. + to()->mangle_unused_area(); + } swap_spaces(); assert(to()->is_empty(), "to space should be empty now"); diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp index 7ef34bb89bd..d1efec8ff71 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp @@ -170,9 +170,20 @@ bool ASPSYoungGen::resize_generation(size_t eden_size, size_t survivor_size) { if (desired_size > orig_size) { // Grow the generation size_t change = desired_size - orig_size; + HeapWord* prev_low = (HeapWord*) virtual_space()->low(); if (!virtual_space()->expand_by(change)) { return false; } + if (ZapUnusedHeapArea) { + // Mangle newly committed space immediately because it + // can be done here more simply that after the new + // spaces have been computed. + HeapWord* new_low = (HeapWord*) virtual_space()->low(); + assert(new_low < prev_low, "Did not grow"); + + MemRegion mangle_region(new_low, prev_low); + SpaceMangler::mangle_region(mangle_region); + } size_changed = true; } else if (desired_size < orig_size) { size_t desired_change = orig_size - desired_size; @@ -215,8 +226,10 @@ bool ASPSYoungGen::resize_generation(size_t eden_size, size_t survivor_size) { // current implementation does not allow holes between the spaces // _young_generation_boundary has to be reset because it changes. // so additional verification + void ASPSYoungGen::resize_spaces(size_t requested_eden_size, size_t requested_survivor_size) { + assert(UseAdaptiveSizePolicy, "sanity check"); assert(requested_eden_size > 0 && requested_survivor_size > 0, "just checking"); @@ -276,22 +289,42 @@ void ASPSYoungGen::resize_spaces(size_t requested_eden_size, ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); const size_t alignment = heap->intra_heap_alignment(); + const bool maintain_minimum = + (requested_eden_size + 2 * requested_survivor_size) <= min_gen_size(); + bool eden_from_to_order = from_start < to_start; // Check whether from space is below to space - if (from_start < to_start) { + if (eden_from_to_order) { // Eden, from, to + if (PrintAdaptiveSizePolicy && Verbose) { gclog_or_tty->print_cr(" Eden, from, to:"); } // Set eden - // Compute how big eden can be, then adjust end. - // See comment in PSYoungGen::resize_spaces() on - // calculating eden_end. - const size_t eden_size = MIN2(requested_eden_size, - pointer_delta(from_start, - eden_start, - sizeof(char))); + // "requested_eden_size" is a goal for the size of eden + // and may not be attainable. "eden_size" below is + // calculated based on the location of from-space and + // the goal for the size of eden. from-space is + // fixed in place because it contains live data. + // The calculation is done this way to avoid 32bit + // overflow (i.e., eden_start + requested_eden_size + // may too large for representation in 32bits). + size_t eden_size; + if (maintain_minimum) { + // Only make eden larger than the requested size if + // the minimum size of the generation has to be maintained. + // This could be done in general but policy at a higher + // level is determining a requested size for eden and that + // should be honored unless there is a fundamental reason. + eden_size = pointer_delta(from_start, + eden_start, + sizeof(char)); + } else { + eden_size = MIN2(requested_eden_size, + pointer_delta(from_start, eden_start, sizeof(char))); + } + eden_end = eden_start + eden_size; assert(eden_end >= eden_start, "addition overflowed") @@ -371,12 +404,14 @@ void ASPSYoungGen::resize_spaces(size_t requested_eden_size, to_start = MAX2(to_start, eden_start + alignment); // Compute how big eden can be, then adjust end. - // See comment in PSYoungGen::resize_spaces() on - // calculating eden_end. - const size_t eden_size = MIN2(requested_eden_size, - pointer_delta(to_start, - eden_start, - sizeof(char))); + // See comments above on calculating eden_end. + size_t eden_size; + if (maintain_minimum) { + eden_size = pointer_delta(to_start, eden_start, sizeof(char)); + } else { + eden_size = MIN2(requested_eden_size, + pointer_delta(to_start, eden_start, sizeof(char))); + } eden_end = eden_start + eden_size; assert(eden_end >= eden_start, "addition overflowed") @@ -423,9 +458,47 @@ void ASPSYoungGen::resize_spaces(size_t requested_eden_size, size_t old_from = from_space()->capacity_in_bytes(); size_t old_to = to_space()->capacity_in_bytes(); - eden_space()->initialize(edenMR, true); - to_space()->initialize(toMR , true); - from_space()->initialize(fromMR, false); // Note, not cleared! + if (ZapUnusedHeapArea) { + // NUMA is a special case because a numa space is not mangled + // in order to not prematurely bind its address to memory to + // the wrong memory (i.e., don't want the GC thread to first + // touch the memory). The survivor spaces are not numa + // spaces and are mangled. + if (UseNUMA) { + if (eden_from_to_order) { + mangle_survivors(from_space(), fromMR, to_space(), toMR); + } else { + mangle_survivors(to_space(), toMR, from_space(), fromMR); + } + } + + // If not mangling the spaces, do some checking to verify that + // the spaces are already mangled. + // The spaces should be correctly mangled at this point so + // do some checking here. Note that they are not being mangled + // in the calls to initialize(). + // Must check mangling before the spaces are reshaped. Otherwise, + // the bottom or end of one space may have moved into an area + // covered by another space and a failure of the check may + // not correctly indicate which space is not properly mangled. + + HeapWord* limit = (HeapWord*) virtual_space()->high(); + eden_space()->check_mangled_unused_area(limit); + from_space()->check_mangled_unused_area(limit); + to_space()->check_mangled_unused_area(limit); + } + // When an existing space is being initialized, it is not + // mangled because the space has been previously mangled. + eden_space()->initialize(edenMR, + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); + to_space()->initialize(toMR, + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); + from_space()->initialize(fromMR, + SpaceDecorator::DontClear, + SpaceDecorator::DontMangle); + PSScavenge::set_young_generation_boundary(eden_space()->bottom()); assert(from_space()->top() == old_from_top, "from top changed!"); @@ -446,7 +519,6 @@ void ASPSYoungGen::resize_spaces(size_t requested_eden_size, } space_invariants(); } - void ASPSYoungGen::reset_after_change() { assert_locked_or_safepoint(Heap_lock); @@ -458,7 +530,9 @@ void ASPSYoungGen::reset_after_change() { HeapWord* eden_bottom = eden_space()->bottom(); if (new_eden_bottom != eden_bottom) { MemRegion eden_mr(new_eden_bottom, eden_space()->end()); - eden_space()->initialize(eden_mr, true); + eden_space()->initialize(eden_mr, + SpaceDecorator::Clear, + SpaceDecorator::Mangle); PSScavenge::set_young_generation_boundary(eden_space()->bottom()); } MemRegion cmr((HeapWord*)virtual_space()->low(), diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp index 2b2c6f87c51..affd72fc2b1 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp @@ -666,9 +666,9 @@ void CardTableExtension::resize_commit_uncommit(int changed_region, HeapWord* new_end_for_commit = MIN2(cur_committed.end(), _guard_region.start()); - MemRegion new_committed = - MemRegion(new_start_aligned, new_end_for_commit); - if(!new_committed.is_empty()) { + if(new_start_aligned < new_end_for_commit) { + MemRegion new_committed = + MemRegion(new_start_aligned, new_end_for_commit); if (!os::commit_memory((char*)new_committed.start(), new_committed.byte_size())) { vm_exit_out_of_memory(new_committed.byte_size(), diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp index 6fd50b39fc5..85ffd751270 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp @@ -938,3 +938,23 @@ void ParallelScavengeHeap::resize_old_gen(size_t desired_free_space) { // Delegate the resize to the generation. _old_gen->resize(desired_free_space); } + +#ifndef PRODUCT +void ParallelScavengeHeap::record_gen_tops_before_GC() { + if (ZapUnusedHeapArea) { + young_gen()->record_spaces_top(); + old_gen()->record_spaces_top(); + perm_gen()->record_spaces_top(); + } +} + +void ParallelScavengeHeap::gen_mangle_unused_area() { + if (ZapUnusedHeapArea) { + young_gen()->eden_space()->mangle_unused_area(); + young_gen()->to_space()->mangle_unused_area(); + young_gen()->from_space()->mangle_unused_area(); + old_gen()->object_space()->mangle_unused_area(); + perm_gen()->object_space()->mangle_unused_area(); + } +} +#endif diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp index d26eec48882..a4c141840b7 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp @@ -213,6 +213,12 @@ class ParallelScavengeHeap : public CollectedHeap { // Resize the old generation. The reserved space for the // generation may be expanded in preparation for the resize. void resize_old_gen(size_t desired_free_space); + + // Save the tops of the spaces in all generations + void record_gen_tops_before_GC() PRODUCT_RETURN; + + // Mangle the unused parts of all spaces in the heap + void gen_mangle_unused_area() PRODUCT_RETURN; }; inline size_t ParallelScavengeHeap::set_alignment(size_t& var, size_t val) diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp index 3a817a2049e..d42d4fc26df 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp @@ -98,6 +98,9 @@ void PSMarkSweep::invoke_no_policy(bool clear_all_softrefs) { // Increment the invocation count heap->increment_total_collections(true /* full */); + // Save information needed to minimize mangling + heap->record_gen_tops_before_GC(); + // We need to track unique mark sweep invocations as well. _total_invocations++; @@ -188,6 +191,12 @@ void PSMarkSweep::invoke_no_policy(bool clear_all_softrefs) { deallocate_stacks(); + if (ZapUnusedHeapArea) { + // Do a complete mangle (top to end) because the usage for + // scratch does not maintain a top pointer. + young_gen->to_space()->mangle_unused_area_complete(); + } + eden_empty = young_gen->eden_space()->is_empty(); if (!eden_empty) { eden_empty = absorb_live_data_from_eden(size_policy, young_gen, old_gen); @@ -198,7 +207,7 @@ void PSMarkSweep::invoke_no_policy(bool clear_all_softrefs) { Universe::update_heap_info_at_gc(); survivors_empty = young_gen->from_space()->is_empty() && - young_gen->to_space()->is_empty(); + young_gen->to_space()->is_empty(); young_gen_empty = eden_empty && survivors_empty; BarrierSet* bs = heap->barrier_set(); @@ -344,6 +353,11 @@ void PSMarkSweep::invoke_no_policy(bool clear_all_softrefs) { perm_gen->verify_object_start_array(); } + if (ZapUnusedHeapArea) { + old_gen->object_space()->check_mangled_unused_area_complete(); + perm_gen->object_space()->check_mangled_unused_area_complete(); + } + NOT_PRODUCT(ref_processor()->verify_no_references_recorded()); if (PrintHeapAtGC) { diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweepDecorator.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweepDecorator.cpp index cec3a48db1a..c0fa75a8c98 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweepDecorator.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweepDecorator.cpp @@ -438,5 +438,7 @@ void PSMarkSweepDecorator::compact(bool mangle_free_space ) { "should point inside space"); space()->set_top(compaction_top()); - if (mangle_free_space) space()->mangle_unused_area(); + if (mangle_free_space) { + space()->mangle_unused_area(); + } } diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.cpp index f92d291cc4e..89515f945c6 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.cpp @@ -87,6 +87,15 @@ void PSOldGen::initialize_work(const char* perf_data_name, int level) { MemRegion cmr((HeapWord*)virtual_space()->low(), (HeapWord*)virtual_space()->high()); + if (ZapUnusedHeapArea) { + // Mangle newly committed space immediately rather than + // waiting for the initialization of the space even though + // mangling is related to spaces. Doing it here eliminates + // the need to carry along information that a complete mangling + // (bottom to end) needs to be done. + SpaceMangler::mangle_region(cmr); + } + Universe::heap()->barrier_set()->resize_covered_region(cmr); CardTableModRefBS* _ct = (CardTableModRefBS*)Universe::heap()->barrier_set(); @@ -112,7 +121,9 @@ void PSOldGen::initialize_work(const char* perf_data_name, int level) { if (_object_space == NULL) vm_exit_during_initialization("Could not allocate an old gen space"); - object_space()->initialize(cmr, true); + object_space()->initialize(cmr, + SpaceDecorator::Clear, + SpaceDecorator::Mangle); _object_mark_sweep = new PSMarkSweepDecorator(_object_space, start_array(), MarkSweepDeadRatio); @@ -232,6 +243,19 @@ bool PSOldGen::expand_by(size_t bytes) { assert_locked_or_safepoint(Heap_lock); bool result = virtual_space()->expand_by(bytes); if (result) { + if (ZapUnusedHeapArea) { + // We need to mangle the newly expanded area. The memregion spans + // end -> new_end, we assume that top -> end is already mangled. + // Do the mangling before post_resize() is called because + // the space is available for allocation after post_resize(); + HeapWord* const virtual_space_high = (HeapWord*) virtual_space()->high(); + assert(object_space()->end() < virtual_space_high, + "Should be true before post_resize()"); + MemRegion mangle_region(object_space()->end(), virtual_space_high); + // Note that the object space has not yet been updated to + // coincede with the new underlying virtual space. + SpaceMangler::mangle_region(mangle_region); + } post_resize(); if (UsePerfData) { _space_counters->update_capacity(); @@ -348,16 +372,7 @@ void PSOldGen::post_resize() { start_array()->set_covered_region(new_memregion); Universe::heap()->barrier_set()->resize_covered_region(new_memregion); - // Did we expand? HeapWord* const virtual_space_high = (HeapWord*) virtual_space()->high(); - if (object_space()->end() < virtual_space_high) { - // We need to mangle the newly expanded area. The memregion spans - // end -> new_end, we assume that top -> end is already mangled. - // This cannot be safely tested for, as allocation may be taking - // place. - MemRegion mangle_region(object_space()->end(), virtual_space_high); - object_space()->mangle_region(mangle_region); - } // ALWAYS do this last!! object_space()->set_end(virtual_space_high); @@ -462,3 +477,10 @@ void PSOldGen::verify_object_start_array() { VerifyObjectStartArrayClosure check( this, &_start_array ); object_iterate(&check); } + +#ifndef PRODUCT +void PSOldGen::record_spaces_top() { + assert(ZapUnusedHeapArea, "Not mangling unused space"); + object_space()->set_top_for_allocations(); +} +#endif diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.hpp index a7a68bdf68e..7e1d30811e6 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.hpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psOldGen.hpp @@ -185,4 +185,8 @@ class PSOldGen : public CHeapObj { // Printing support virtual const char* name() const { return _name; } + + // Debugging support + // Save the tops of all spaces for later use during mangling. + void record_spaces_top() PRODUCT_RETURN; }; diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp index 8f9ec0e59c3..2b25332ab96 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp @@ -1058,6 +1058,10 @@ void PSParallelCompact::post_compact() ref_processor()->enqueue_discovered_references(NULL); + if (ZapUnusedHeapArea) { + heap->gen_mangle_unused_area(); + } + // Update time of last GC reset_millis_since_last_gc(); } @@ -1959,6 +1963,11 @@ void PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) { PSPermGen* perm_gen = heap->perm_gen(); PSAdaptiveSizePolicy* size_policy = heap->size_policy(); + if (ZapUnusedHeapArea) { + // Save information needed to minimize mangling + heap->record_gen_tops_before_GC(); + } + _print_phases = PrintGCDetails && PrintParallelOldGCPhaseTimes; // Make sure data structures are sane, make the heap parsable, and do other @@ -2127,17 +2136,19 @@ void PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) { size_t max_eden_size = young_gen->max_size() - young_gen->from_space()->capacity_in_bytes() - young_gen->to_space()->capacity_in_bytes(); - size_policy->compute_generation_free_space(young_gen->used_in_bytes(), - young_gen->eden_space()->used_in_bytes(), - old_gen->used_in_bytes(), - perm_gen->used_in_bytes(), - young_gen->eden_space()->capacity_in_bytes(), - old_gen->max_gen_size(), - max_eden_size, - true /* full gc*/, - gc_cause); + size_policy->compute_generation_free_space( + young_gen->used_in_bytes(), + young_gen->eden_space()->used_in_bytes(), + old_gen->used_in_bytes(), + perm_gen->used_in_bytes(), + young_gen->eden_space()->capacity_in_bytes(), + old_gen->max_gen_size(), + max_eden_size, + true /* full gc*/, + gc_cause); - heap->resize_old_gen(size_policy->calculated_old_free_size_in_bytes()); + heap->resize_old_gen( + size_policy->calculated_old_free_size_in_bytes()); // Don't resize the young generation at an major collection. A // desired young generation size may have been calculated but @@ -2210,6 +2221,11 @@ void PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) { perm_gen->verify_object_start_array(); } + if (ZapUnusedHeapArea) { + old_gen->object_space()->check_mangled_unused_area_complete(); + perm_gen->object_space()->check_mangled_unused_area_complete(); + } + NOT_PRODUCT(ref_processor()->verify_no_references_recorded()); collection_exit.update(); diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp index 9566821169b..4b1f8572fa5 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp @@ -716,6 +716,99 @@ class BitBlockUpdateClosure: public ParMarkBitMapClosure { virtual IterationStatus do_addr(HeapWord* addr, size_t words); }; +// The UseParallelOldGC collector is a stop-the-world garbage +// collector that does parts of the collection using parallel threads. +// The collection includes the tenured generation and the young +// generation. The permanent generation is collected at the same +// time as the other two generations but the permanent generation +// is collect by a single GC thread. The permanent generation is +// collected serially because of the requirement that during the +// processing of a klass AAA, any objects reference by AAA must +// already have been processed. This requirement is enforced by +// a left (lower address) to right (higher address) sliding compaction. +// +// There are four phases of the collection. +// +// - marking phase +// - summary phase +// - compacting phase +// - clean up phase +// +// Roughly speaking these phases correspond, respectively, to +// - mark all the live objects +// - calculate the destination of each object at the end of the collection +// - move the objects to their destination +// - update some references and reinitialize some variables +// +// These three phases are invoked in PSParallelCompact::invoke_no_policy(). +// The marking phase is implemented in PSParallelCompact::marking_phase() +// and does a complete marking of the heap. +// The summary phase is implemented in PSParallelCompact::summary_phase(). +// The move and update phase is implemented in PSParallelCompact::compact(). +// +// A space that is being collected is divided into chunks and with +// each chunk is associated an object of type ParallelCompactData. +// Each chunk is of a fixed size and typically will contain more than +// 1 object and may have parts of objects at the front and back of the +// chunk. +// +// chunk -----+---------------------+---------- +// objects covered [ AAA )[ BBB )[ CCC )[ DDD ) +// +// The marking phase does a complete marking of all live objects in the +// heap. The marking also compiles the size of the data for +// all live objects covered by the chunk. This size includes the +// part of any live object spanning onto the chunk (part of AAA +// if it is live) from the front, all live objects contained in the chunk +// (BBB and/or CCC if they are live), and the part of any live objects +// covered by the chunk that extends off the chunk (part of DDD if it is +// live). The marking phase uses multiple GC threads and marking is +// done in a bit array of type ParMarkBitMap. The marking of the +// bit map is done atomically as is the accumulation of the size of the +// live objects covered by a chunk. +// +// The summary phase calculates the total live data to the left of +// each chunk XXX. Based on that total and the bottom of the space, +// it can calculate the starting location of the live data in XXX. +// The summary phase calculates for each chunk XXX quantites such as +// +// - the amount of live data at the beginning of a chunk from an object +// entering the chunk. +// - the location of the first live data on the chunk +// - a count of the number of chunks receiving live data from XXX. +// +// See ParallelCompactData for precise details. The summary phase also +// calculates the dense prefix for the compaction. The dense prefix +// is a portion at the beginning of the space that is not moved. The +// objects in the dense prefix do need to have their object references +// updated. See method summarize_dense_prefix(). +// +// The summary phase is done using 1 GC thread. +// +// The compaction phase moves objects to their new location and updates +// all references in the object. +// +// A current exception is that objects that cross a chunk boundary +// are moved but do not have their references updated. References are +// not updated because it cannot easily be determined if the klass +// pointer KKK for the object AAA has been updated. KKK likely resides +// in a chunk to the left of the chunk containing AAA. These AAA's +// have there references updated at the end in a clean up phase. +// See the method PSParallelCompact::update_deferred_objects(). An +// alternate strategy is being investigated for this deferral of updating. +// +// Compaction is done on a chunk basis. A chunk that is ready to be +// filled is put on a ready list and GC threads take chunk off the list +// and fill them. A chunk is ready to be filled if it +// empty of live objects. Such a chunk may have been initially +// empty (only contained +// dead objects) or may have had all its live objects copied out already. +// A chunk that compacts into itself is also ready for filling. The +// ready list is initially filled with empty chunks and chunks compacting +// into themselves. There is always at least 1 chunk that can be put on +// the ready list. The chunks are atomically added and removed from +// the ready list. +// class PSParallelCompact : AllStatic { public: // Convenient access to type names. diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp index 5f960dc9ece..7d655878206 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp @@ -265,6 +265,11 @@ bool PSScavenge::invoke_no_policy() { young_gen->eden_space()->accumulate_statistics(); } + if (ZapUnusedHeapArea) { + // Save information needed to minimize mangling + heap->record_gen_tops_before_GC(); + } + if (PrintHeapAtGC) { Universe::print_heap_before_gc(); } @@ -315,7 +320,7 @@ bool PSScavenge::invoke_no_policy() { if (!ScavengeWithObjectsInToSpace) { assert(young_gen->to_space()->is_empty(), "Attempt to scavenge with live objects in to_space"); - young_gen->to_space()->clear(); + young_gen->to_space()->clear(SpaceDecorator::Mangle); } else if (ZapUnusedHeapArea) { young_gen->to_space()->mangle_unused_area(); } @@ -437,8 +442,10 @@ bool PSScavenge::invoke_no_policy() { if (!promotion_failure_occurred) { // Swap the survivor spaces. - young_gen->eden_space()->clear(); - young_gen->from_space()->clear(); + + + young_gen->eden_space()->clear(SpaceDecorator::Mangle); + young_gen->from_space()->clear(SpaceDecorator::Mangle); young_gen->swap_spaces(); size_t survived = young_gen->from_space()->used_in_bytes(); @@ -600,6 +607,12 @@ bool PSScavenge::invoke_no_policy() { Universe::print_heap_after_gc(); } + if (ZapUnusedHeapArea) { + young_gen->eden_space()->check_mangled_unused_area_complete(); + young_gen->from_space()->check_mangled_unused_area_complete(); + young_gen->to_space()->check_mangled_unused_area_complete(); + } + scavenge_exit.update(); if (PrintGCTaskTimeStamps) { diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp index b7088556bdc..56a8491f6b0 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp @@ -36,7 +36,7 @@ PSYoungGen::PSYoungGen(size_t initial_size, void PSYoungGen::initialize_virtual_space(ReservedSpace rs, size_t alignment) { assert(_init_gen_size != 0, "Should have a finite size"); _virtual_space = new PSVirtualSpace(rs, alignment); - if (!_virtual_space->expand_by(_init_gen_size)) { + if (!virtual_space()->expand_by(_init_gen_size)) { vm_exit_during_initialization("Could not reserve enough space for " "object heap"); } @@ -49,13 +49,20 @@ void PSYoungGen::initialize(ReservedSpace rs, size_t alignment) { void PSYoungGen::initialize_work() { - _reserved = MemRegion((HeapWord*)_virtual_space->low_boundary(), - (HeapWord*)_virtual_space->high_boundary()); + _reserved = MemRegion((HeapWord*)virtual_space()->low_boundary(), + (HeapWord*)virtual_space()->high_boundary()); - MemRegion cmr((HeapWord*)_virtual_space->low(), - (HeapWord*)_virtual_space->high()); + MemRegion cmr((HeapWord*)virtual_space()->low(), + (HeapWord*)virtual_space()->high()); Universe::heap()->barrier_set()->resize_covered_region(cmr); + if (ZapUnusedHeapArea) { + // Mangle newly committed space immediately because it + // can be done here more simply that after the new + // spaces have been computed. + SpaceMangler::mangle_region(cmr); + } + if (UseNUMA) { _eden_space = new MutableNUMASpace(); } else { @@ -89,7 +96,7 @@ void PSYoungGen::initialize_work() { // Compute maximum space sizes for performance counters ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); size_t alignment = heap->intra_heap_alignment(); - size_t size = _virtual_space->reserved_size(); + size_t size = virtual_space()->reserved_size(); size_t max_survivor_size; size_t max_eden_size; @@ -142,7 +149,7 @@ void PSYoungGen::compute_initial_space_boundaries() { // Compute sizes size_t alignment = heap->intra_heap_alignment(); - size_t size = _virtual_space->committed_size(); + size_t size = virtual_space()->committed_size(); size_t survivor_size = size / InitialSurvivorRatio; survivor_size = align_size_down(survivor_size, alignment); @@ -164,18 +171,18 @@ void PSYoungGen::compute_initial_space_boundaries() { } void PSYoungGen::set_space_boundaries(size_t eden_size, size_t survivor_size) { - assert(eden_size < _virtual_space->committed_size(), "just checking"); + assert(eden_size < virtual_space()->committed_size(), "just checking"); assert(eden_size > 0 && survivor_size > 0, "just checking"); // Initial layout is Eden, to, from. After swapping survivor spaces, // that leaves us with Eden, from, to, which is step one in our two // step resize-with-live-data procedure. - char *eden_start = _virtual_space->low(); + char *eden_start = virtual_space()->low(); char *to_start = eden_start + eden_size; char *from_start = to_start + survivor_size; char *from_end = from_start + survivor_size; - assert(from_end == _virtual_space->high(), "just checking"); + assert(from_end == virtual_space()->high(), "just checking"); assert(is_object_aligned((intptr_t)eden_start), "checking alignment"); assert(is_object_aligned((intptr_t)to_start), "checking alignment"); assert(is_object_aligned((intptr_t)from_start), "checking alignment"); @@ -184,9 +191,9 @@ void PSYoungGen::set_space_boundaries(size_t eden_size, size_t survivor_size) { MemRegion to_mr ((HeapWord*)to_start, (HeapWord*)from_start); MemRegion from_mr((HeapWord*)from_start, (HeapWord*)from_end); - eden_space()->initialize(eden_mr, true); - to_space()->initialize(to_mr , true); - from_space()->initialize(from_mr, true); + eden_space()->initialize(eden_mr, true, ZapUnusedHeapArea); + to_space()->initialize(to_mr , true, ZapUnusedHeapArea); + from_space()->initialize(from_mr, true, ZapUnusedHeapArea); } #ifndef PRODUCT @@ -207,7 +214,7 @@ void PSYoungGen::space_invariants() { char* to_start = (char*)to_space()->bottom(); char* to_end = (char*)to_space()->end(); - guarantee(eden_start >= _virtual_space->low(), "eden bottom"); + guarantee(eden_start >= virtual_space()->low(), "eden bottom"); guarantee(eden_start < eden_end, "eden space consistency"); guarantee(from_start < from_end, "from space consistency"); guarantee(to_start < to_end, "to space consistency"); @@ -217,29 +224,29 @@ void PSYoungGen::space_invariants() { // Eden, from, to guarantee(eden_end <= from_start, "eden/from boundary"); guarantee(from_end <= to_start, "from/to boundary"); - guarantee(to_end <= _virtual_space->high(), "to end"); + guarantee(to_end <= virtual_space()->high(), "to end"); } else { // Eden, to, from guarantee(eden_end <= to_start, "eden/to boundary"); guarantee(to_end <= from_start, "to/from boundary"); - guarantee(from_end <= _virtual_space->high(), "from end"); + guarantee(from_end <= virtual_space()->high(), "from end"); } // More checks that the virtual space is consistent with the spaces - assert(_virtual_space->committed_size() >= + assert(virtual_space()->committed_size() >= (eden_space()->capacity_in_bytes() + to_space()->capacity_in_bytes() + from_space()->capacity_in_bytes()), "Committed size is inconsistent"); - assert(_virtual_space->committed_size() <= _virtual_space->reserved_size(), + assert(virtual_space()->committed_size() <= virtual_space()->reserved_size(), "Space invariant"); char* eden_top = (char*)eden_space()->top(); char* from_top = (char*)from_space()->top(); char* to_top = (char*)to_space()->top(); - assert(eden_top <= _virtual_space->high(), "eden top"); - assert(from_top <= _virtual_space->high(), "from top"); - assert(to_top <= _virtual_space->high(), "to top"); + assert(eden_top <= virtual_space()->high(), "eden top"); + assert(from_top <= virtual_space()->high(), "from top"); + assert(to_top <= virtual_space()->high(), "to top"); - _virtual_space->verify(); + virtual_space()->verify(); } #endif @@ -265,8 +272,8 @@ void PSYoungGen::resize(size_t eden_size, size_t survivor_size) { bool PSYoungGen::resize_generation(size_t eden_size, size_t survivor_size) { - const size_t alignment = _virtual_space->alignment(); - size_t orig_size = _virtual_space->committed_size(); + const size_t alignment = virtual_space()->alignment(); + size_t orig_size = virtual_space()->committed_size(); bool size_changed = false; // There used to be this guarantee there. @@ -288,10 +295,18 @@ bool PSYoungGen::resize_generation(size_t eden_size, size_t survivor_size) { // Grow the generation size_t change = desired_size - orig_size; assert(change % alignment == 0, "just checking"); - if (!_virtual_space->expand_by(change)) { + HeapWord* prev_high = (HeapWord*) virtual_space()->high(); + if (!virtual_space()->expand_by(change)) { return false; // Error if we fail to resize! } - + if (ZapUnusedHeapArea) { + // Mangle newly committed space immediately because it + // can be done here more simply that after the new + // spaces have been computed. + HeapWord* new_high = (HeapWord*) virtual_space()->high(); + MemRegion mangle_region(prev_high, new_high); + SpaceMangler::mangle_region(mangle_region); + } size_changed = true; } else if (desired_size < orig_size) { size_t desired_change = orig_size - desired_size; @@ -321,19 +336,95 @@ bool PSYoungGen::resize_generation(size_t eden_size, size_t survivor_size) { post_resize(); if (Verbose && PrintGC) { - size_t current_size = _virtual_space->committed_size(); + size_t current_size = virtual_space()->committed_size(); gclog_or_tty->print_cr("PSYoung generation size changed: " SIZE_FORMAT "K->" SIZE_FORMAT "K", orig_size/K, current_size/K); } } - guarantee(eden_plus_survivors <= _virtual_space->committed_size() || - _virtual_space->committed_size() == max_size(), "Sanity"); + guarantee(eden_plus_survivors <= virtual_space()->committed_size() || + virtual_space()->committed_size() == max_size(), "Sanity"); return true; } +#ifndef PRODUCT +// In the numa case eden is not mangled so a survivor space +// moving into a region previously occupied by a survivor +// may find an unmangled region. Also in the PS case eden +// to-space and from-space may not touch (i.e., there may be +// gaps between them due to movement while resizing the +// spaces). Those gaps must be mangled. +void PSYoungGen::mangle_survivors(MutableSpace* s1, + MemRegion s1MR, + MutableSpace* s2, + MemRegion s2MR) { + // Check eden and gap between eden and from-space, in deciding + // what to mangle in from-space. Check the gap between from-space + // and to-space when deciding what to mangle. + // + // +--------+ +----+ +---+ + // | eden | |s1 | |s2 | + // +--------+ +----+ +---+ + // +-------+ +-----+ + // |s1MR | |s2MR | + // +-------+ +-----+ + // All of survivor-space is properly mangled so find the + // upper bound on the mangling for any portion above current s1. + HeapWord* delta_end = MIN2(s1->bottom(), s1MR.end()); + MemRegion delta1_left; + if (s1MR.start() < delta_end) { + delta1_left = MemRegion(s1MR.start(), delta_end); + s1->mangle_region(delta1_left); + } + // Find any portion to the right of the current s1. + HeapWord* delta_start = MAX2(s1->end(), s1MR.start()); + MemRegion delta1_right; + if (delta_start < s1MR.end()) { + delta1_right = MemRegion(delta_start, s1MR.end()); + s1->mangle_region(delta1_right); + } + + // Similarly for the second survivor space except that + // any of the new region that overlaps with the current + // region of the first survivor space has already been + // mangled. + delta_end = MIN2(s2->bottom(), s2MR.end()); + delta_start = MAX2(s2MR.start(), s1->end()); + MemRegion delta2_left; + if (s2MR.start() < delta_end) { + delta2_left = MemRegion(s2MR.start(), delta_end); + s2->mangle_region(delta2_left); + } + delta_start = MAX2(s2->end(), s2MR.start()); + MemRegion delta2_right; + if (delta_start < s2MR.end()) { + s2->mangle_region(delta2_right); + } + + if (TraceZapUnusedHeapArea) { + // s1 + gclog_or_tty->print_cr("Current region: [" PTR_FORMAT ", " PTR_FORMAT ") " + "New region: [" PTR_FORMAT ", " PTR_FORMAT ")", + s1->bottom(), s1->end(), s1MR.start(), s1MR.end()); + gclog_or_tty->print_cr(" Mangle before: [" PTR_FORMAT ", " + PTR_FORMAT ") Mangle after: [" PTR_FORMAT ", " PTR_FORMAT ")", + delta1_left.start(), delta1_left.end(), delta1_right.start(), + delta1_right.end()); + + // s2 + gclog_or_tty->print_cr("Current region: [" PTR_FORMAT ", " PTR_FORMAT ") " + "New region: [" PTR_FORMAT ", " PTR_FORMAT ")", + s2->bottom(), s2->end(), s2MR.start(), s2MR.end()); + gclog_or_tty->print_cr(" Mangle before: [" PTR_FORMAT ", " + PTR_FORMAT ") Mangle after: [" PTR_FORMAT ", " PTR_FORMAT ")", + delta2_left.start(), delta2_left.end(), delta2_right.start(), + delta2_right.end()); + } + +} +#endif // NOT PRODUCT void PSYoungGen::resize_spaces(size_t requested_eden_size, size_t requested_survivor_size) { @@ -396,9 +487,11 @@ void PSYoungGen::resize_spaces(size_t requested_eden_size, const bool maintain_minimum = (requested_eden_size + 2 * requested_survivor_size) <= min_gen_size(); + bool eden_from_to_order = from_start < to_start; // Check whether from space is below to space - if (from_start < to_start) { + if (eden_from_to_order) { // Eden, from, to + eden_from_to_order = true; if (PrintAdaptiveSizePolicy && Verbose) { gclog_or_tty->print_cr(" Eden, from, to:"); } @@ -435,7 +528,7 @@ void PSYoungGen::resize_spaces(size_t requested_eden_size, // extra calculations. // First calculate an optimal to-space - to_end = (char*)_virtual_space->high(); + to_end = (char*)virtual_space()->high(); to_start = (char*)pointer_delta(to_end, (char*)requested_survivor_size, sizeof(char)); @@ -491,7 +584,7 @@ void PSYoungGen::resize_spaces(size_t requested_eden_size, // to space as if we were able to resize from space, even though from // space is not modified. // Giving eden priority was tried and gave poorer performance. - to_end = (char*)pointer_delta(_virtual_space->high(), + to_end = (char*)pointer_delta(virtual_space()->high(), (char*)requested_survivor_size, sizeof(char)); to_end = MIN2(to_end, from_start); @@ -560,9 +653,45 @@ void PSYoungGen::resize_spaces(size_t requested_eden_size, size_t old_from = from_space()->capacity_in_bytes(); size_t old_to = to_space()->capacity_in_bytes(); - eden_space()->initialize(edenMR, true); - to_space()->initialize(toMR , true); - from_space()->initialize(fromMR, false); // Note, not cleared! + if (ZapUnusedHeapArea) { + // NUMA is a special case because a numa space is not mangled + // in order to not prematurely bind its address to memory to + // the wrong memory (i.e., don't want the GC thread to first + // touch the memory). The survivor spaces are not numa + // spaces and are mangled. + if (UseNUMA) { + if (eden_from_to_order) { + mangle_survivors(from_space(), fromMR, to_space(), toMR); + } else { + mangle_survivors(to_space(), toMR, from_space(), fromMR); + } + } + + // If not mangling the spaces, do some checking to verify that + // the spaces are already mangled. + // The spaces should be correctly mangled at this point so + // do some checking here. Note that they are not being mangled + // in the calls to initialize(). + // Must check mangling before the spaces are reshaped. Otherwise, + // the bottom or end of one space may have moved into an area + // covered by another space and a failure of the check may + // not correctly indicate which space is not properly mangled. + HeapWord* limit = (HeapWord*) virtual_space()->high(); + eden_space()->check_mangled_unused_area(limit); + from_space()->check_mangled_unused_area(limit); + to_space()->check_mangled_unused_area(limit); + } + // When an existing space is being initialized, it is not + // mangled because the space has been previously mangled. + eden_space()->initialize(edenMR, + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); + to_space()->initialize(toMR, + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); + from_space()->initialize(fromMR, + SpaceDecorator::DontClear, + SpaceDecorator::DontMangle); assert(from_space()->top() == old_from_top, "from top changed!"); @@ -671,7 +800,7 @@ void PSYoungGen::print_on(outputStream* st) const { st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K", capacity_in_bytes()/K, used_in_bytes()/K); } - _virtual_space->print_space_boundaries_on(st); + virtual_space()->print_space_boundaries_on(st); st->print(" eden"); eden_space()->print_on(st); st->print(" from"); from_space()->print_on(st); st->print(" to "); to_space()->print_on(st); @@ -774,7 +903,9 @@ void PSYoungGen::reset_survivors_after_shrink() { // Was there a shrink of the survivor space? if (new_end < space_shrinking->end()) { MemRegion mr(space_shrinking->bottom(), new_end); - space_shrinking->initialize(mr, false /* clear */); + space_shrinking->initialize(mr, + SpaceDecorator::DontClear, + SpaceDecorator::Mangle); } } @@ -809,3 +940,12 @@ void PSYoungGen::verify(bool allow_dirty) { from_space()->verify(allow_dirty); to_space()->verify(allow_dirty); } + +#ifndef PRODUCT +void PSYoungGen::record_spaces_top() { + assert(ZapUnusedHeapArea, "Not mangling unused space"); + eden_space()->set_top_for_allocations(); + from_space()->set_top_for_allocations(); + to_space()->set_top_for_allocations(); +} +#endif diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.hpp index 953d4309f20..4fad1bccffb 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.hpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.hpp @@ -179,4 +179,12 @@ class PSYoungGen : public CHeapObj { // Space boundary invariant checker void space_invariants() PRODUCT_RETURN; + + // Helper for mangling survivor spaces. + void mangle_survivors(MutableSpace* s1, + MemRegion s1MR, + MutableSpace* s2, + MemRegion s2MR) PRODUCT_RETURN; + + void record_spaces_top() PRODUCT_RETURN; }; diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp index ff58cc3a43f..20ca6d3e31f 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp +++ b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp @@ -42,19 +42,31 @@ MutableNUMASpace::~MutableNUMASpace() { delete lgrp_spaces(); } +#ifndef PRODUCT void MutableNUMASpace::mangle_unused_area() { - for (int i = 0; i < lgrp_spaces()->length(); i++) { - LGRPSpace *ls = lgrp_spaces()->at(i); - MutableSpace *s = ls->space(); - if (!os::numa_has_static_binding()) { - HeapWord *top = MAX2((HeapWord*)round_down((intptr_t)s->top(), page_size()), s->bottom()); - if (top < s->end()) { - ls->add_invalid_region(MemRegion(top, s->end())); - } - } - s->mangle_unused_area(); - } + // This method should do nothing. + // It can be called on a numa space during a full compaction. } +void MutableNUMASpace::mangle_unused_area_complete() { + // This method should do nothing. + // It can be called on a numa space during a full compaction. +} +void MutableNUMASpace::mangle_region(MemRegion mr) { + // This method should do nothing because numa spaces are not mangled. +} +void MutableNUMASpace::set_top_for_allocations(HeapWord* v) { + assert(false, "Do not mangle MutableNUMASpace's"); +} +void MutableNUMASpace::set_top_for_allocations() { + // This method should do nothing. +} +void MutableNUMASpace::check_mangled_unused_area(HeapWord* limit) { + // This method should do nothing. +} +void MutableNUMASpace::check_mangled_unused_area_complete() { + // This method should do nothing. +} +#endif // NOT_PRODUCT // There may be unallocated holes in the middle chunks // that should be filled with dead objects to ensure parseability. @@ -243,7 +255,10 @@ void MutableNUMASpace::update() { s->set_end(s->bottom()); s->set_top(s->bottom()); } - initialize(region(), true); + // A NUMA space is never mangled + initialize(region(), + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); } else { bool should_initialize = false; if (!os::numa_has_static_binding()) { @@ -257,7 +272,10 @@ void MutableNUMASpace::update() { if (should_initialize || (UseAdaptiveNUMAChunkSizing && adaptation_cycles() < samples_count())) { - initialize(region(), true); + // A NUMA space is never mangled + initialize(region(), + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); } } @@ -448,14 +466,17 @@ void MutableNUMASpace::merge_regions(MemRegion new_region, MemRegion* intersecti } } -void MutableNUMASpace::initialize(MemRegion mr, bool clear_space) { +void MutableNUMASpace::initialize(MemRegion mr, + bool clear_space, + bool mangle_space) { assert(clear_space, "Reallocation will destory data!"); assert(lgrp_spaces()->length() > 0, "There should be at least one space"); MemRegion old_region = region(), new_region; set_bottom(mr.start()); set_end(mr.end()); - MutableSpace::set_top(bottom()); + // Must always clear the space + clear(SpaceDecorator::DontMangle); // Compute chunk sizes size_t prev_page_size = page_size(); @@ -586,10 +607,8 @@ void MutableNUMASpace::initialize(MemRegion mr, bool clear_space) { bias_region(top_region, ls->lgrp_id()); } - // If we clear the region, we would mangle it in debug. That would cause page - // allocation in a different place. Hence setting the top directly. - s->initialize(new_region, false); - s->set_top(s->bottom()); + // Clear space (set top = bottom) but never mangle. + s->initialize(new_region, SpaceDecorator::Clear, SpaceDecorator::DontMangle); set_adaptation_cycles(samples_count()); } @@ -641,10 +660,12 @@ void MutableNUMASpace::set_top(HeapWord* value) { MutableSpace::set_top(value); } -void MutableNUMASpace::clear() { +void MutableNUMASpace::clear(bool mangle_space) { MutableSpace::set_top(bottom()); for (int i = 0; i < lgrp_spaces()->length(); i++) { - lgrp_spaces()->at(i)->space()->clear(); + // Never mangle NUMA spaces because the mangling will + // bind the memory to a possibly unwanted lgroup. + lgrp_spaces()->at(i)->space()->clear(SpaceDecorator::DontMangle); } } diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp index 6b5dcbbe214..54a01299beb 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp +++ b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp @@ -171,14 +171,21 @@ class MutableNUMASpace : public MutableSpace { MutableNUMASpace(); virtual ~MutableNUMASpace(); // Space initialization. - virtual void initialize(MemRegion mr, bool clear_space); + virtual void initialize(MemRegion mr, bool clear_space, bool mangle_space); // Update space layout if necessary. Do all adaptive resizing job. virtual void update(); // Update allocation rate averages. virtual void accumulate_statistics(); - virtual void clear(); - virtual void mangle_unused_area(); + virtual void clear(bool mangle_space); + virtual void mangle_unused_area() PRODUCT_RETURN; + virtual void mangle_unused_area_complete() PRODUCT_RETURN; + virtual void mangle_region(MemRegion mr) PRODUCT_RETURN; + virtual void check_mangled_unused_area(HeapWord* limit) PRODUCT_RETURN; + virtual void check_mangled_unused_area_complete() PRODUCT_RETURN; + virtual void set_top_for_allocations(HeapWord* v) PRODUCT_RETURN; + virtual void set_top_for_allocations() PRODUCT_RETURN; + virtual void ensure_parsability(); virtual size_t used_in_words() const; virtual size_t free_in_words() const; diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp b/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp index a91247a80d9..a5befabf056 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp +++ b/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.cpp @@ -25,7 +25,17 @@ # include "incls/_precompiled.incl" # include "incls/_mutableSpace.cpp.incl" -void MutableSpace::initialize(MemRegion mr, bool clear_space) { +MutableSpace::MutableSpace(): ImmutableSpace(), _top(NULL) { + _mangler = new MutableSpaceMangler(this); +} + +MutableSpace::~MutableSpace() { + delete _mangler; +} + +void MutableSpace::initialize(MemRegion mr, + bool clear_space, + bool mangle_space) { HeapWord* bottom = mr.start(); HeapWord* end = mr.end(); @@ -34,14 +44,51 @@ void MutableSpace::initialize(MemRegion mr, bool clear_space) { set_bottom(bottom); set_end(end); - if (clear_space) clear(); + if (clear_space) { + clear(mangle_space); + } } -void MutableSpace::clear() { +void MutableSpace::clear(bool mangle_space) { set_top(bottom()); - if (ZapUnusedHeapArea) mangle_unused_area(); + if (ZapUnusedHeapArea && mangle_space) { + mangle_unused_area(); + } } +#ifndef PRODUCT +void MutableSpace::check_mangled_unused_area(HeapWord* limit) { + mangler()->check_mangled_unused_area(limit); +} + +void MutableSpace::check_mangled_unused_area_complete() { + mangler()->check_mangled_unused_area_complete(); +} + +// Mangle only the unused space that has not previously +// been mangled and that has not been allocated since being +// mangled. +void MutableSpace::mangle_unused_area() { + mangler()->mangle_unused_area(); +} + +void MutableSpace::mangle_unused_area_complete() { + mangler()->mangle_unused_area_complete(); +} + +void MutableSpace::mangle_region(MemRegion mr) { + SpaceMangler::mangle_region(mr); +} + +void MutableSpace::set_top_for_allocations(HeapWord* v) { + mangler()->set_top_for_allocations(v); +} + +void MutableSpace::set_top_for_allocations() { + mangler()->set_top_for_allocations(top()); +} +#endif + // This version requires locking. */ HeapWord* MutableSpace::allocate(size_t size) { assert(Heap_lock->owned_by_self() || diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.hpp b/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.hpp index f21930123b9..9c0271245f4 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.hpp +++ b/hotspot/src/share/vm/gc_implementation/shared/mutableSpace.hpp @@ -30,14 +30,23 @@ // Invariant: (ImmutableSpace +) bottom() <= top() <= end() // top() is inclusive and end() is exclusive. +class MutableSpaceMangler; + class MutableSpace: public ImmutableSpace { friend class VMStructs; + + // Helper for mangling unused space in debug builds + MutableSpaceMangler* _mangler; + protected: HeapWord* _top; + MutableSpaceMangler* mangler() { return _mangler; } + public: - virtual ~MutableSpace() {} - MutableSpace() { _top = NULL; } + virtual ~MutableSpace(); + MutableSpace(); + // Accessors HeapWord* top() const { return _top; } virtual void set_top(HeapWord* value) { _top = value; } @@ -52,21 +61,30 @@ class MutableSpace: public ImmutableSpace { MemRegion used_region() { return MemRegion(bottom(), top()); } // Initialization - virtual void initialize(MemRegion mr, bool clear_space); - virtual void clear(); + virtual void initialize(MemRegion mr, + bool clear_space, + bool mangle_space); + virtual void clear(bool mangle_space); + // Does the usual initialization but optionally resets top to bottom. +#if 0 // MANGLE_SPACE + void initialize(MemRegion mr, bool clear_space, bool reset_top); +#endif virtual void update() { } virtual void accumulate_statistics() { } - // Overwrites the unused portion of this space. Note that some collectors - // may use this "scratch" space during collections. - virtual void mangle_unused_area() { - mangle_region(MemRegion(_top, _end)); - } + // Methods used in mangling. See descriptions under SpaceMangler. + virtual void mangle_unused_area() PRODUCT_RETURN; + virtual void mangle_unused_area_complete() PRODUCT_RETURN; + virtual void check_mangled_unused_area(HeapWord* limit) PRODUCT_RETURN; + virtual void check_mangled_unused_area_complete() PRODUCT_RETURN; + virtual void set_top_for_allocations(HeapWord* v) PRODUCT_RETURN; + + // Used to save the space's current top for later use during mangling. + virtual void set_top_for_allocations() PRODUCT_RETURN; + virtual void ensure_parsability() { } - void mangle_region(MemRegion mr) { - debug_only(Copy::fill_to_words(mr.start(), mr.word_size(), badHeapWord)); - } + virtual void mangle_region(MemRegion mr) PRODUCT_RETURN; // Boolean querries. bool is_empty() const { return used_in_words() == 0; } diff --git a/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.cpp b/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.cpp new file mode 100644 index 00000000000..2d9fc59f675 --- /dev/null +++ b/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.cpp @@ -0,0 +1,140 @@ +/* + * Copyright 2002-2005 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + */ + +# include "incls/_precompiled.incl" +# include "incls/_spaceDecorator.cpp.incl" + +// Catch-all file for utility classes + +#ifndef PRODUCT + +// Returns true is the location q matches the mangling +// pattern. +bool SpaceMangler::is_mangled(HeapWord* q) { + // This test loses precision but is good enough + return badHeapWord == (max_juint & (uintptr_t) q->value()); +} + + +void SpaceMangler::set_top_for_allocations(HeapWord* v) { + if (v < end()) { + assert(is_mangled(v), "The high water mark is not mangled"); + } + _top_for_allocations = v; +} + +// Mangle only the unused space that has not previously +// been mangled and that has not been allocated since being +// mangled. +void SpaceMangler::mangle_unused_area() { + assert(ZapUnusedHeapArea, "Mangling should not be in use"); + // Mangle between top and the high water mark. Safeguard + // against the space changing since top_for_allocations was + // set. + HeapWord* mangled_end = MIN2(top_for_allocations(), end()); + if (top() < mangled_end) { + MemRegion mangle_mr(top(), mangled_end); + SpaceMangler::mangle_region(mangle_mr); + // Light weight check of mangling. + check_mangled_unused_area(end()); + } + // Complete check of unused area which is functional when + // DEBUG_MANGLING is defined. + check_mangled_unused_area_complete(); +} + +// A complete mangle is expected in the +// exceptional case where top_for_allocations is not +// properly tracking the high water mark for mangling. +// This can be the case when to-space is being used for +// scratch space during a mark-sweep-compact. See +// contribute_scratch() and PSMarkSweep::allocate_stacks(). +void SpaceMangler::mangle_unused_area_complete() { + assert(ZapUnusedHeapArea, "Mangling should not be in use"); + MemRegion mangle_mr(top(), end()); + SpaceMangler::mangle_region(mangle_mr); +} + +// Simply mangle the MemRegion mr. +void SpaceMangler::mangle_region(MemRegion mr) { + assert(ZapUnusedHeapArea, "Mangling should not be in use"); +#ifdef ASSERT + if(TraceZapUnusedHeapArea) { + gclog_or_tty->print("Mangling [0x%x to 0x%x)", mr.start(), mr.end()); + } + Copy::fill_to_words(mr.start(), mr.word_size(), badHeapWord); + if(TraceZapUnusedHeapArea) { + gclog_or_tty->print_cr(" done"); + } +#endif +} + +// Check that top, top_for_allocations and the last +// word of the space are mangled. In a tight memory +// situation even this light weight mangling could +// cause paging by touching the end of the space. +void SpaceMangler::check_mangled_unused_area(HeapWord* limit) { + if (CheckZapUnusedHeapArea) { + // This method can be called while the spaces are + // being reshaped so skip the test if the end of the + // space is beyond the specified limit; + if (end() > limit) return; + + assert(top() == end() || + (is_mangled(top())), "Top not mangled"); + assert((top_for_allocations() < top()) || + (top_for_allocations() >= end()) || + (is_mangled(top_for_allocations())), + "Older unused not mangled"); + assert(top() == end() || + (is_mangled(end() - 1)), "End not properly mangled"); + // Only does checking when DEBUG_MANGLING is defined. + check_mangled_unused_area_complete(); + } +} + +#undef DEBUG_MANGLING +// This should only be used while debugging the mangling +// because of the high cost of checking the completeness. +void SpaceMangler::check_mangled_unused_area_complete() { + if (CheckZapUnusedHeapArea) { + assert(ZapUnusedHeapArea, "Not mangling unused area"); +#ifdef DEBUG_MANGLING + HeapWord* q = top(); + HeapWord* limit = end(); + + bool passed = true; + while (q < limit) { + if (!is_mangled(q)) { + passed = false; + break; + } + q++; + } + assert(passed, "Mangling is not complete"); +#endif + } +} +#undef DEBUG_MANGLING +#endif // not PRODUCT diff --git a/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.hpp b/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.hpp new file mode 100644 index 00000000000..7298c47a91b --- /dev/null +++ b/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.hpp @@ -0,0 +1,141 @@ +/* + * Copyright 2002-2005 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + */ + +class SpaceDecorator: public AllStatic { + public: + // Initialization flags. + static const bool Clear = true; + static const bool DontClear = false; + static const bool Mangle = true; + static const bool DontMangle = false; +}; + +// Functionality for use with class Space and class MutableSpace. +// The approach taken with the mangling is to mangle all +// the space initially and then to mangle areas that have +// been allocated since the last collection. Mangling is +// done in the context of a generation and in the context +// of a space. +// The space in a generation is mangled when it is first +// initialized and when the generation grows. The spaces +// are not necessarily up-to-date when this mangling occurs +// and the method mangle_region() is used. +// After allocations have been done in a space, the space generally +// need to be remangled. Remangling is only done on the +// recently allocated regions in the space. Typically, that is +// the region between the new top and the top just before a +// garbage collection. +// An exception to the usual mangling in a space is done when the +// space is used for an extraordinary purpose. Specifically, when +// to-space is used as scratch space for a mark-sweep-compact +// collection. +// Spaces are mangled after a collection. If the generation +// grows after a collection, the added space is mangled as part of +// the growth of the generation. No additional mangling is needed when the +// spaces are resized after an expansion. +// The class SpaceMangler keeps a pointer to the top of the allocated +// area and provides the methods for doing the piece meal mangling. +// Methods for doing sparces and full checking of the mangling are +// included. The full checking is done if DEBUG_MANGLING is defined. +// GenSpaceMangler is used with the GenCollectedHeap collectors and +// MutableSpaceMangler is used with the ParallelScavengeHeap collectors. +// These subclasses abstract the differences in the types of spaces used +// by each heap. + +class SpaceMangler: public CHeapObj { + friend class VMStructs; + + // High water mark for allocations. Typically, the space above + // this point have been mangle previously and don't need to be + // touched again. Space belows this point has been allocated + // and remangling is needed between the current top and this + // high water mark. + HeapWord* _top_for_allocations; + HeapWord* top_for_allocations() { return _top_for_allocations; } + + public: + + // Setting _top_for_allocations to NULL at initialization + // makes it always below top so that mangling done as part + // of the initialize() call of a space does nothing (as it + // should since the mangling is done as part of the constructor + // for the space. + SpaceMangler() : _top_for_allocations(NULL) {} + + // Methods for top and end that delegate to the specific + // space type. + virtual HeapWord* top() const = 0; + virtual HeapWord* end() const = 0; + + // Return true if q matches the mangled pattern. + static bool is_mangled(HeapWord* q) PRODUCT_RETURN0; + + // Used to save the an address in a space for later use during mangling. + void set_top_for_allocations(HeapWord* v); + + // Overwrites the unused portion of this space. + // Mangle only the region not previously mangled [top, top_previously_mangled) + void mangle_unused_area(); + // Mangle all the unused region [top, end) + void mangle_unused_area_complete(); + // Do some sparse checking on the area that should have been mangled. + void check_mangled_unused_area(HeapWord* limit) PRODUCT_RETURN; + // Do a complete check of the area that should be mangled. + void check_mangled_unused_area_complete() PRODUCT_RETURN; + + // Mangle the MemRegion. This is a non-space specific mangler. It + // is used during the initial mangling of a space before the space + // is fully constructed. Also is used when a generation is expanded + // and possibly before the spaces have been reshaped to to the new + // size of the generation. + static void mangle_region(MemRegion mr); +}; + +class ContiguousSpace; + +// For use with GenCollectedHeap's +class GenSpaceMangler: public SpaceMangler { + ContiguousSpace* _sp; + + ContiguousSpace* sp() { return _sp; } + + HeapWord* top() const { return _sp->top(); } + HeapWord* end() const { return _sp->end(); } + + public: + GenSpaceMangler(ContiguousSpace* sp) : SpaceMangler(), _sp(sp) {} +}; + +// For use with ParallelScavengeHeap's. +class MutableSpaceMangler: public SpaceMangler { + MutableSpace* _sp; + + MutableSpace* sp() { return _sp; } + + HeapWord* top() const { return _sp->top(); } + HeapWord* end() const { return _sp->end(); } + + public: + MutableSpaceMangler(MutableSpace* sp) : SpaceMangler(), _sp(sp) {} +}; diff --git a/hotspot/src/share/vm/includeDB_core b/hotspot/src/share/vm/includeDB_core index 2af8fd826f1..8fade1d4d27 100644 --- a/hotspot/src/share/vm/includeDB_core +++ b/hotspot/src/share/vm/includeDB_core @@ -1405,6 +1405,7 @@ defNewGeneration.cpp java.hpp defNewGeneration.cpp oop.inline.hpp defNewGeneration.cpp referencePolicy.hpp defNewGeneration.cpp space.inline.hpp +defNewGeneration.cpp spaceDecorator.hpp defNewGeneration.cpp thread_.inline.hpp defNewGeneration.hpp ageTable.hpp @@ -1789,6 +1790,7 @@ generation.cpp generation.inline.hpp generation.cpp java.hpp generation.cpp oop.hpp generation.cpp oop.inline.hpp +generation.cpp spaceDecorator.hpp generation.cpp space.inline.hpp generation.hpp allocation.hpp @@ -3722,6 +3724,7 @@ space.cpp oop.inline2.hpp space.cpp safepoint.hpp space.cpp space.hpp space.cpp space.inline.hpp +space.cpp spaceDecorator.hpp space.cpp systemDictionary.hpp space.cpp universe.inline.hpp space.cpp vmSymbols.hpp @@ -3744,6 +3747,13 @@ space.inline.hpp safepoint.hpp space.inline.hpp space.hpp space.inline.hpp universe.hpp +spaceDecorator.hpp globalDefinitions.hpp +spaceDecorator.hpp mutableSpace.hpp +spaceDecorator.hpp space.hpp + +spaceDecorator.cpp copy.hpp +spaceDecorator.cpp spaceDecorator.hpp + specialized_oop_closures.cpp ostream.hpp specialized_oop_closures.cpp specialized_oop_closures.hpp diff --git a/hotspot/src/share/vm/includeDB_features b/hotspot/src/share/vm/includeDB_features index eec1c35259e..88f4c293643 100644 --- a/hotspot/src/share/vm/includeDB_features +++ b/hotspot/src/share/vm/includeDB_features @@ -51,6 +51,7 @@ dump.cpp oop.hpp dump.cpp oopFactory.hpp dump.cpp resourceArea.hpp dump.cpp signature.hpp +dump.cpp spaceDecorator.hpp dump.cpp symbolTable.hpp dump.cpp systemDictionary.hpp dump.cpp vmThread.hpp diff --git a/hotspot/src/share/vm/memory/defNewGeneration.cpp b/hotspot/src/share/vm/memory/defNewGeneration.cpp index d13c9e9adff..23449688dd7 100644 --- a/hotspot/src/share/vm/memory/defNewGeneration.cpp +++ b/hotspot/src/share/vm/memory/defNewGeneration.cpp @@ -172,15 +172,25 @@ DefNewGeneration::DefNewGeneration(ReservedSpace rs, _to_counters = new CSpaceCounters("s1", 2, _max_survivor_size, _to_space, _gen_counters); - compute_space_boundaries(0); + compute_space_boundaries(0, SpaceDecorator::Clear, SpaceDecorator::Mangle); update_counters(); _next_gen = NULL; _tenuring_threshold = MaxTenuringThreshold; _pretenure_size_threshold_words = PretenureSizeThreshold >> LogHeapWordSize; } -void DefNewGeneration::compute_space_boundaries(uintx minimum_eden_size) { - uintx alignment = GenCollectedHeap::heap()->collector_policy()->min_alignment(); +void DefNewGeneration::compute_space_boundaries(uintx minimum_eden_size, + bool clear_space, + bool mangle_space) { + uintx alignment = + GenCollectedHeap::heap()->collector_policy()->min_alignment(); + + // If the spaces are being cleared (only done at heap initialization + // currently), the survivor spaces need not be empty. + // Otherwise, no care is taken for used areas in the survivor spaces + // so check. + assert(clear_space || (to()->is_empty() && from()->is_empty()), + "Initialization of the survivor spaces assumes these are empty"); // Compute sizes uintx size = _virtual_space.committed_size(); @@ -214,16 +224,41 @@ void DefNewGeneration::compute_space_boundaries(uintx minimum_eden_size) { MemRegion fromMR((HeapWord*)from_start, (HeapWord*)to_start); MemRegion toMR ((HeapWord*)to_start, (HeapWord*)to_end); - eden()->initialize(edenMR, (minimum_eden_size == 0)); - // If minumum_eden_size != 0, we will not have cleared any + // A minimum eden size implies that there is a part of eden that + // is being used and that affects the initialization of any + // newly formed eden. + bool live_in_eden = minimum_eden_size > 0; + + // If not clearing the spaces, do some checking to verify that + // the space are already mangled. + if (!clear_space) { + // Must check mangling before the spaces are reshaped. Otherwise, + // the bottom or end of one space may have moved into another + // a failure of the check may not correctly indicate which space + // is not properly mangled. + if (ZapUnusedHeapArea) { + HeapWord* limit = (HeapWord*) _virtual_space.high(); + eden()->check_mangled_unused_area(limit); + from()->check_mangled_unused_area(limit); + to()->check_mangled_unused_area(limit); + } + } + + // Reset the spaces for their new regions. + eden()->initialize(edenMR, + clear_space && !live_in_eden, + SpaceDecorator::Mangle); + // If clear_space and live_in_eden, we will not have cleared any // portion of eden above its top. This can cause newly // expanded space not to be mangled if using ZapUnusedHeapArea. // We explicitly do such mangling here. - if (ZapUnusedHeapArea && (minimum_eden_size != 0)) { + if (ZapUnusedHeapArea && clear_space && live_in_eden && mangle_space) { eden()->mangle_unused_area(); } - from()->initialize(fromMR, true); - to()->initialize(toMR , true); + from()->initialize(fromMR, clear_space, mangle_space); + to()->initialize(toMR, clear_space, mangle_space); + + // Set next compaction spaces. eden()->set_next_compaction_space(from()); // The to-space is normally empty before a compaction so need // not be considered. The exception is during promotion @@ -250,7 +285,16 @@ void DefNewGeneration::swap_spaces() { bool DefNewGeneration::expand(size_t bytes) { MutexLocker x(ExpandHeap_lock); + HeapWord* prev_high = (HeapWord*) _virtual_space.high(); bool success = _virtual_space.expand_by(bytes); + if (success && ZapUnusedHeapArea) { + // Mangle newly committed space immediately because it + // can be done here more simply that after the new + // spaces have been computed. + HeapWord* new_high = (HeapWord*) _virtual_space.high(); + MemRegion mangle_region(prev_high, new_high); + SpaceMangler::mangle_region(mangle_region); + } // Do not attempt an expand-to-the reserve size. The // request should properly observe the maximum size of @@ -262,7 +306,8 @@ bool DefNewGeneration::expand(size_t bytes) { // value. if (GC_locker::is_active()) { if (PrintGC && Verbose) { - gclog_or_tty->print_cr("Garbage collection disabled, expanded heap instead"); + gclog_or_tty->print_cr("Garbage collection disabled, " + "expanded heap instead"); } } @@ -326,16 +371,24 @@ void DefNewGeneration::compute_new_size() { changed = true; } if (changed) { - compute_space_boundaries(eden()->used()); - MemRegion cmr((HeapWord*)_virtual_space.low(), (HeapWord*)_virtual_space.high()); + // The spaces have already been mangled at this point but + // may not have been cleared (set top = bottom) and should be. + // Mangling was done when the heap was being expanded. + compute_space_boundaries(eden()->used(), + SpaceDecorator::Clear, + SpaceDecorator::DontMangle); + MemRegion cmr((HeapWord*)_virtual_space.low(), + (HeapWord*)_virtual_space.high()); Universe::heap()->barrier_set()->resize_covered_region(cmr); if (Verbose && PrintGC) { size_t new_size_after = _virtual_space.committed_size(); size_t eden_size_after = eden()->capacity(); size_t survivor_size_after = from()->capacity(); - gclog_or_tty->print("New generation size " SIZE_FORMAT "K->" SIZE_FORMAT "K [eden=" + gclog_or_tty->print("New generation size " SIZE_FORMAT "K->" + SIZE_FORMAT "K [eden=" SIZE_FORMAT "K,survivor=" SIZE_FORMAT "K]", - new_size_before/K, new_size_after/K, eden_size_after/K, survivor_size_after/K); + new_size_before/K, new_size_after/K, + eden_size_after/K, survivor_size_after/K); if (WizardMode) { gclog_or_tty->print("[allowed " SIZE_FORMAT "K extra for %d threads]", thread_increase_size/K, threads_count); @@ -480,7 +533,7 @@ void DefNewGeneration::collect(bool full, ScanWeakRefClosure scan_weak_ref(this); age_table()->clear(); - to()->clear(); + to()->clear(SpaceDecorator::Mangle); gch->rem_set()->prepare_for_younger_refs_iterate(false); @@ -525,8 +578,18 @@ void DefNewGeneration::collect(bool full, soft_ref_policy, &is_alive, &keep_alive, &evacuate_followers, NULL); if (!promotion_failed()) { // Swap the survivor spaces. - eden()->clear(); - from()->clear(); + eden()->clear(SpaceDecorator::Mangle); + from()->clear(SpaceDecorator::Mangle); + if (ZapUnusedHeapArea) { + // This is now done here because of the piece-meal mangling which + // can check for valid mangling at intermediate points in the + // collection(s). When a minor collection fails to collect + // sufficient space resizing of the young generation can occur + // an redistribute the spaces in the young generation. Mangle + // here so that unzapped regions don't get distributed to + // other spaces. + to()->mangle_unused_area(); + } swap_spaces(); assert(to()->is_empty(), "to space should be empty now"); @@ -753,6 +816,15 @@ void DefNewGeneration::contribute_scratch(ScratchBlock*& list, Generation* reque } } +void DefNewGeneration::reset_scratch() { + // If contributing scratch in to_space, mangle all of + // to_space if ZapUnusedHeapArea. This is needed because + // top is not maintained while using to-space as scratch. + if (ZapUnusedHeapArea) { + to()->mangle_unused_area_complete(); + } +} + bool DefNewGeneration::collection_attempt_is_safe() { if (!to()->is_empty()) { return false; @@ -806,11 +878,25 @@ void DefNewGeneration::gc_epilogue(bool full) { } } + if (ZapUnusedHeapArea) { + eden()->check_mangled_unused_area_complete(); + from()->check_mangled_unused_area_complete(); + to()->check_mangled_unused_area_complete(); + } + // update the generation and space performance counters update_counters(); gch->collector_policy()->counters()->update_counters(); } +void DefNewGeneration::record_spaces_top() { + assert(ZapUnusedHeapArea, "Not mangling unused space"); + eden()->set_top_for_allocations(); + to()->set_top_for_allocations(); + from()->set_top_for_allocations(); +} + + void DefNewGeneration::update_counters() { if (UsePerfData) { _eden_counters->update_all(); diff --git a/hotspot/src/share/vm/memory/defNewGeneration.hpp b/hotspot/src/share/vm/memory/defNewGeneration.hpp index 893afc055c7..9d0cd68364a 100644 --- a/hotspot/src/share/vm/memory/defNewGeneration.hpp +++ b/hotspot/src/share/vm/memory/defNewGeneration.hpp @@ -279,6 +279,9 @@ protected: virtual void gc_prologue(bool full); virtual void gc_epilogue(bool full); + // Save the tops for eden, from, and to + virtual void record_spaces_top(); + // Doesn't require additional work during GC prologue and epilogue virtual bool performs_in_place_marking() const { return false; } @@ -299,9 +302,12 @@ protected: // For non-youngest collection, the DefNewGeneration can contribute // "to-space". - void contribute_scratch(ScratchBlock*& list, Generation* requestor, + virtual void contribute_scratch(ScratchBlock*& list, Generation* requestor, size_t max_alloc_words); + // Reset for contribution of "to-space". + virtual void reset_scratch(); + // GC support virtual void compute_new_size(); virtual void collect(bool full, @@ -331,7 +337,12 @@ protected: void verify(bool allow_dirty); protected: - void compute_space_boundaries(uintx minimum_eden_size); + // If clear_space is true, clear the survivor spaces. Eden is + // cleared if the minimum size of eden is 0. If mangle_space + // is true, also mangle the space in debug mode. + void compute_space_boundaries(uintx minimum_eden_size, + bool clear_space, + bool mangle_space); // Scavenge support void swap_spaces(); }; diff --git a/hotspot/src/share/vm/memory/dump.cpp b/hotspot/src/share/vm/memory/dump.cpp index 9499336282b..c5b938ea73f 100644 --- a/hotspot/src/share/vm/memory/dump.cpp +++ b/hotspot/src/share/vm/memory/dump.cpp @@ -645,7 +645,7 @@ public: class ClearSpaceClosure : public SpaceClosure { public: void do_space(Space* s) { - s->clear(); + s->clear(SpaceDecorator::Mangle); } }; diff --git a/hotspot/src/share/vm/memory/genCollectedHeap.cpp b/hotspot/src/share/vm/memory/genCollectedHeap.cpp index dc3ba9b3cf3..efb3a95596f 100644 --- a/hotspot/src/share/vm/memory/genCollectedHeap.cpp +++ b/hotspot/src/share/vm/memory/genCollectedHeap.cpp @@ -465,6 +465,11 @@ void GenCollectedHeap::do_collection(bool full, _gens[i]->stat_record()->invocations++; _gens[i]->stat_record()->accumulated_time.start(); + // Must be done anew before each collection because + // a previous collection will do mangling and will + // change top of some spaces. + record_gen_tops_before_GC(); + if (PrintGC && Verbose) { gclog_or_tty->print("level=%d invoke=%d size=" SIZE_FORMAT, i, @@ -1058,6 +1063,12 @@ ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor, return res; } +void GenCollectedHeap::release_scratch() { + for (int i = 0; i < _n_gens; i++) { + _gens[i]->reset_scratch(); + } +} + size_t GenCollectedHeap::large_typearray_limit() { return gen_policy()->large_typearray_limit(); } @@ -1285,6 +1296,24 @@ void GenCollectedHeap::gc_epilogue(bool full) { always_do_update_barrier = UseConcMarkSweepGC; }; +#ifndef PRODUCT +class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure { + private: + public: + void do_generation(Generation* gen) { + gen->record_spaces_top(); + } +}; + +void GenCollectedHeap::record_gen_tops_before_GC() { + if (ZapUnusedHeapArea) { + GenGCSaveTopsBeforeGCClosure blk; + generation_iterate(&blk, false); // not old-to-young. + perm_gen()->record_spaces_top(); + } +} +#endif // not PRODUCT + class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure { public: void do_generation(Generation* gen) { diff --git a/hotspot/src/share/vm/memory/genCollectedHeap.hpp b/hotspot/src/share/vm/memory/genCollectedHeap.hpp index 54dce33bb80..1872c01ae6d 100644 --- a/hotspot/src/share/vm/memory/genCollectedHeap.hpp +++ b/hotspot/src/share/vm/memory/genCollectedHeap.hpp @@ -259,6 +259,9 @@ public: // be provided are returned as a list of ScratchBlocks, sorted by // decreasing size. ScratchBlock* gather_scratch(Generation* requestor, size_t max_alloc_words); + // Allow each generation to reset any scratch space that it has + // contributed as it needs. + void release_scratch(); size_t large_typearray_limit(); @@ -482,6 +485,9 @@ private: bool should_do_concurrent_full_gc(GCCause::Cause cause); void collect_mostly_concurrent(GCCause::Cause cause); + // Save the tops of the spaces in all generations + void record_gen_tops_before_GC() PRODUCT_RETURN; + protected: virtual void gc_prologue(bool full); virtual void gc_epilogue(bool full); diff --git a/hotspot/src/share/vm/memory/genMarkSweep.cpp b/hotspot/src/share/vm/memory/genMarkSweep.cpp index e98f6793001..318a3525cb7 100644 --- a/hotspot/src/share/vm/memory/genMarkSweep.cpp +++ b/hotspot/src/share/vm/memory/genMarkSweep.cpp @@ -190,6 +190,10 @@ void GenMarkSweep::allocate_stacks() { void GenMarkSweep::deallocate_stacks() { + + GenCollectedHeap* gch = GenCollectedHeap::heap(); + gch->release_scratch(); + if (_preserved_oop_stack) { delete _preserved_mark_stack; _preserved_mark_stack = NULL; diff --git a/hotspot/src/share/vm/memory/generation.cpp b/hotspot/src/share/vm/memory/generation.cpp index 5ed3ec09b7b..efefddf96d4 100644 --- a/hotspot/src/share/vm/memory/generation.cpp +++ b/hotspot/src/share/vm/memory/generation.cpp @@ -32,6 +32,12 @@ Generation::Generation(ReservedSpace rs, size_t initial_size, int level) : vm_exit_during_initialization("Could not reserve enough space for " "object heap"); } + // Mangle all of the the initial generation. + if (ZapUnusedHeapArea) { + MemRegion mangle_region((HeapWord*)_virtual_space.low(), + (HeapWord*)_virtual_space.high()); + SpaceMangler::mangle_region(mangle_region); + } _reserved = MemRegion((HeapWord*)_virtual_space.low_boundary(), (HeapWord*)_virtual_space.high_boundary()); } @@ -505,8 +511,11 @@ bool OneContigSpaceCardGeneration::grow_by(size_t bytes) { _bts->resize(new_word_size); // Fix for bug #4668531 - MemRegion mangle_region(_the_space->end(), (HeapWord*)_virtual_space.high()); - _the_space->mangle_region(mangle_region); + if (ZapUnusedHeapArea) { + MemRegion mangle_region(_the_space->end(), + (HeapWord*)_virtual_space.high()); + SpaceMangler::mangle_region(mangle_region); + } // Expand space -- also expands space's BOT // (which uses (part of) shared array above) @@ -622,6 +631,14 @@ void OneContigSpaceCardGeneration::gc_epilogue(bool full) { // update the generation and space performance counters update_counters(); + if (ZapUnusedHeapArea) { + the_space()->check_mangled_unused_area_complete(); + } +} + +void OneContigSpaceCardGeneration::record_spaces_top() { + assert(ZapUnusedHeapArea, "Not mangling unused space"); + the_space()->set_top_for_allocations(); } void OneContigSpaceCardGeneration::verify(bool allow_dirty) { diff --git a/hotspot/src/share/vm/memory/generation.hpp b/hotspot/src/share/vm/memory/generation.hpp index 2e146d53844..d87ebc3e529 100644 --- a/hotspot/src/share/vm/memory/generation.hpp +++ b/hotspot/src/share/vm/memory/generation.hpp @@ -376,6 +376,9 @@ class Generation: public CHeapObj { // The default is to do nothing. virtual void gc_epilogue(bool full) {}; + // Save the high water marks for the used space in a generation. + virtual void record_spaces_top() {}; + // Some generations may need to be "fixed-up" after some allocation // activity to make them parsable again. The default is to do nothing. virtual void ensure_parsability() {}; @@ -476,6 +479,10 @@ class Generation: public CHeapObj { virtual void contribute_scratch(ScratchBlock*& list, Generation* requestor, size_t max_alloc_words) {} + // Give each generation an opportunity to do clean up for any + // contributed scratch. + virtual void reset_scratch() {}; + // When an older generation has been collected, and perhaps resized, // this method will be invoked on all younger generations (from older to // younger), allowing them to resize themselves as appropriate. @@ -699,6 +706,8 @@ class OneContigSpaceCardGeneration: public CardGeneration { virtual void gc_epilogue(bool full); + virtual void record_spaces_top(); + virtual void verify(bool allow_dirty); virtual void print_on(outputStream* st) const; }; diff --git a/hotspot/src/share/vm/memory/space.cpp b/hotspot/src/share/vm/memory/space.cpp index 50dfd1df8d6..b3dab36a045 100644 --- a/hotspot/src/share/vm/memory/space.cpp +++ b/hotspot/src/share/vm/memory/space.cpp @@ -232,30 +232,44 @@ ContiguousSpace::new_dcto_cl(OopClosure* cl, return new ContiguousSpaceDCTOC(this, cl, precision, boundary); } -void Space::initialize(MemRegion mr, bool clear_space) { +void Space::initialize(MemRegion mr, + bool clear_space, + bool mangle_space) { HeapWord* bottom = mr.start(); HeapWord* end = mr.end(); assert(Universe::on_page_boundary(bottom) && Universe::on_page_boundary(end), "invalid space boundaries"); set_bottom(bottom); set_end(end); - if (clear_space) clear(); + if (clear_space) clear(mangle_space); } -void Space::clear() { - if (ZapUnusedHeapArea) mangle_unused_area(); +void Space::clear(bool mangle_space) { + if (ZapUnusedHeapArea && mangle_space) { + mangle_unused_area(); + } } -void ContiguousSpace::initialize(MemRegion mr, bool clear_space) +ContiguousSpace::ContiguousSpace(): CompactibleSpace(), _top(NULL) { + _mangler = new GenSpaceMangler(this); +} + +ContiguousSpace::~ContiguousSpace() { + delete _mangler; +} + +void ContiguousSpace::initialize(MemRegion mr, + bool clear_space, + bool mangle_space) { - CompactibleSpace::initialize(mr, clear_space); + CompactibleSpace::initialize(mr, clear_space, mangle_space); _concurrent_iteration_safe_limit = top(); } -void ContiguousSpace::clear() { +void ContiguousSpace::clear(bool mangle_space) { set_top(bottom()); set_saved_mark(); - Space::clear(); + Space::clear(mangle_space); } bool Space::is_in(const void* p) const { @@ -271,8 +285,8 @@ bool ContiguousSpace::is_free_block(const HeapWord* p) const { return p >= _top; } -void OffsetTableContigSpace::clear() { - ContiguousSpace::clear(); +void OffsetTableContigSpace::clear(bool mangle_space) { + ContiguousSpace::clear(mangle_space); _offsets.initialize_threshold(); } @@ -288,17 +302,46 @@ void OffsetTableContigSpace::set_end(HeapWord* new_end) { Space::set_end(new_end); } +#ifndef PRODUCT + +void ContiguousSpace::set_top_for_allocations(HeapWord* v) { + mangler()->set_top_for_allocations(v); +} +void ContiguousSpace::set_top_for_allocations() { + mangler()->set_top_for_allocations(top()); +} +void ContiguousSpace::check_mangled_unused_area(HeapWord* limit) { + mangler()->check_mangled_unused_area(limit); +} + +void ContiguousSpace::check_mangled_unused_area_complete() { + mangler()->check_mangled_unused_area_complete(); +} + +// Mangled only the unused space that has not previously +// been mangled and that has not been allocated since being +// mangled. void ContiguousSpace::mangle_unused_area() { - // to-space is used for storing marks during mark-sweep - mangle_region(MemRegion(top(), end())); + mangler()->mangle_unused_area(); +} +void ContiguousSpace::mangle_unused_area_complete() { + mangler()->mangle_unused_area_complete(); } - void ContiguousSpace::mangle_region(MemRegion mr) { - debug_only(Copy::fill_to_words(mr.start(), mr.word_size(), badHeapWord)); + // Although this method uses SpaceMangler::mangle_region() which + // is not specific to a space, the when the ContiguousSpace version + // is called, it is always with regard to a space and this + // bounds checking is appropriate. + MemRegion space_mr(bottom(), end()); + assert(space_mr.contains(mr), "Mangling outside space"); + SpaceMangler::mangle_region(mr); } +#endif // NOT_PRODUCT -void CompactibleSpace::initialize(MemRegion mr, bool clear_space) { - Space::initialize(mr, clear_space); +void CompactibleSpace::initialize(MemRegion mr, + bool clear_space, + bool mangle_space) { + Space::initialize(mr, clear_space, mangle_space); _compaction_top = bottom(); _next_compaction_space = NULL; } @@ -820,8 +863,8 @@ void ContiguousSpace::allocate_temporary_filler(int factor) { } } -void EdenSpace::clear() { - ContiguousSpace::clear(); +void EdenSpace::clear(bool mangle_space) { + ContiguousSpace::clear(mangle_space); set_soft_end(end()); } @@ -878,7 +921,7 @@ OffsetTableContigSpace::OffsetTableContigSpace(BlockOffsetSharedArray* sharedOff _par_alloc_lock(Mutex::leaf, "OffsetTableContigSpace par alloc lock", true) { _offsets.set_contig_space(this); - initialize(mr, true); + initialize(mr, SpaceDecorator::Clear, SpaceDecorator::Mangle); } diff --git a/hotspot/src/share/vm/memory/space.hpp b/hotspot/src/share/vm/memory/space.hpp index 37f726e5b3f..1cecd3a06ab 100644 --- a/hotspot/src/share/vm/memory/space.hpp +++ b/hotspot/src/share/vm/memory/space.hpp @@ -131,15 +131,17 @@ class Space: public CHeapObj { return MemRegion(bottom(), saved_mark_word()); } - // Initialization - virtual void initialize(MemRegion mr, bool clear_space); - virtual void clear(); + // Initialization. These may be run to reset an existing + // Space. + virtual void initialize(MemRegion mr, bool clear_space, bool mangle_space); + virtual void clear(bool mangle_space); // For detecting GC bugs. Should only be called at GC boundaries, since // some unused space may be used as scratch space during GC's. // Default implementation does nothing. We also call this when expanding // a space to satisfy an allocation request. See bug #4668531 virtual void mangle_unused_area() {} + virtual void mangle_unused_area_complete() {} virtual void mangle_region(MemRegion mr) {} // Testers @@ -354,7 +356,7 @@ private: CompactibleSpace* _next_compaction_space; public: - virtual void initialize(MemRegion mr, bool clear_space); + virtual void initialize(MemRegion mr, bool clear_space, bool mangle_space); // Used temporarily during a compaction phase to hold the value // top should have when compaction is complete. @@ -724,12 +726,14 @@ protected: /* continuously, but those that weren't need to have their thresholds */ \ /* re-initialized. Also mangles unused area for debugging. */ \ if (is_empty()) { \ - clear(); \ + clear(SpaceDecorator::Mangle); \ } else { \ if (ZapUnusedHeapArea) mangle_unused_area(); \ } \ } +class GenSpaceMangler; + // A space in which the free area is contiguous. It therefore supports // faster allocation, and compaction. class ContiguousSpace: public CompactibleSpace { @@ -738,13 +742,21 @@ class ContiguousSpace: public CompactibleSpace { protected: HeapWord* _top; HeapWord* _concurrent_iteration_safe_limit; + // A helper for mangling the unused area of the space in debug builds. + GenSpaceMangler* _mangler; + + GenSpaceMangler* mangler() { return _mangler; } // Allocation helpers (return NULL if full). inline HeapWord* allocate_impl(size_t word_size, HeapWord* end_value); inline HeapWord* par_allocate_impl(size_t word_size, HeapWord* end_value); public: - virtual void initialize(MemRegion mr, bool clear_space); + + ContiguousSpace(); + ~ContiguousSpace(); + + virtual void initialize(MemRegion mr, bool clear_space, bool mangle_space); // Accessors HeapWord* top() const { return _top; } @@ -753,15 +765,34 @@ class ContiguousSpace: public CompactibleSpace { void set_saved_mark() { _saved_mark_word = top(); } void reset_saved_mark() { _saved_mark_word = bottom(); } - virtual void clear(); + virtual void clear(bool mangle_space); WaterMark bottom_mark() { return WaterMark(this, bottom()); } WaterMark top_mark() { return WaterMark(this, top()); } WaterMark saved_mark() { return WaterMark(this, saved_mark_word()); } bool saved_mark_at_top() const { return saved_mark_word() == top(); } - void mangle_unused_area(); - void mangle_region(MemRegion mr); + // In debug mode mangle (write it with a particular bit + // pattern) the unused part of a space. + + // Used to save the an address in a space for later use during mangling. + void set_top_for_allocations(HeapWord* v) PRODUCT_RETURN; + // Used to save the space's current top for later use during mangling. + void set_top_for_allocations() PRODUCT_RETURN; + + // Mangle regions in the space from the current top up to the + // previously mangled part of the space. + void mangle_unused_area() PRODUCT_RETURN; + // Mangle [top, end) + void mangle_unused_area_complete() PRODUCT_RETURN; + // Mangle the given MemRegion. + void mangle_region(MemRegion mr) PRODUCT_RETURN; + + // Do some sparse checking on the area that should have been mangled. + void check_mangled_unused_area(HeapWord* limit) PRODUCT_RETURN; + // Check the complete area that should have been mangled. + // This code may be NULL depending on the macro DEBUG_MANGLING. + void check_mangled_unused_area_complete() PRODUCT_RETURN; // Size computations: sizes in bytes. size_t capacity() const { return byte_size(bottom(), end()); } @@ -956,7 +987,7 @@ class EdenSpace : public ContiguousSpace { void set_soft_end(HeapWord* value) { _soft_end = value; } // Override. - void clear(); + void clear(bool mangle_space); // Set both the 'hard' and 'soft' limits (_end and _soft_end). void set_end(HeapWord* value) { @@ -1000,7 +1031,7 @@ class OffsetTableContigSpace: public ContiguousSpace { void set_bottom(HeapWord* value); void set_end(HeapWord* value); - void clear(); + void clear(bool mangle_space); inline HeapWord* block_start(const void* p) const; diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index f54347f0251..fd490c9c033 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -589,9 +589,15 @@ class CommandLineFlags { develop(bool, ZapJNIHandleArea, trueInDebug, \ "Zap freed JNI handle space with 0xFEFEFEFE") \ \ - develop(bool, ZapUnusedHeapArea, false, \ + develop(bool, ZapUnusedHeapArea, trueInDebug, \ "Zap unused heap space with 0xBAADBABE") \ \ + develop(bool, TraceZapUnusedHeapArea, false, \ + "Trace zapping of unused heap space") \ + \ + develop(bool, CheckZapUnusedHeapArea, false, \ + "Check zapping of unused heap space") \ + \ develop(bool, PrintVMMessages, true, \ "Print vm messages on console") \ \ diff --git a/hotspot/src/share/vm/utilities/globalDefinitions.hpp b/hotspot/src/share/vm/utilities/globalDefinitions.hpp index c46312f49d7..120ef1f43ec 100644 --- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp +++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp @@ -97,8 +97,12 @@ const int SerializePageShiftCount = 3; // object size. class HeapWord { friend class VMStructs; -private: + private: char* i; +#ifdef ASSERT + public: + char* value() { return i; } +#endif }; // HeapWordSize must be 2^LogHeapWordSize. From 398aa66a77bc8086ba00eb1a36295aca912cf39c Mon Sep 17 00:00:00 2001 From: John Coomes Date: Fri, 11 Jul 2008 16:11:34 -0700 Subject: [PATCH 031/325] 6718283: existing uses of *_FORMAT_W() were broken by 6521491 Reviewed-by: ysr, pbk --- .../parallelScavenge/psParallelCompact.cpp | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp index 2b25332ab96..7a41736fb63 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp @@ -200,8 +200,8 @@ void PSParallelCompact::print_chunk_ranges() for (unsigned int id = 0; id < last_space_id; ++id) { const MutableSpace* space = _space_info[id].space(); tty->print_cr("%u %s " - SIZE_FORMAT_W("10") " " SIZE_FORMAT_W("10") " " - SIZE_FORMAT_W("10") " " SIZE_FORMAT_W("10") " ", + SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " " + SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " ", id, space_names[id], summary_data().addr_to_chunk_idx(space->bottom()), summary_data().addr_to_chunk_idx(space->top()), @@ -213,8 +213,8 @@ void PSParallelCompact::print_chunk_ranges() void print_generic_summary_chunk(size_t i, const ParallelCompactData::ChunkData* c) { -#define CHUNK_IDX_FORMAT SIZE_FORMAT_W("7") -#define CHUNK_DATA_FORMAT SIZE_FORMAT_W("5") +#define CHUNK_IDX_FORMAT SIZE_FORMAT_W(7) +#define CHUNK_DATA_FORMAT SIZE_FORMAT_W(5) ParallelCompactData& sd = PSParallelCompact::summary_data(); size_t dci = c->destination() ? sd.addr_to_chunk_idx(c->destination()) : 0; @@ -269,9 +269,9 @@ print_initial_summary_chunk(size_t i, const ParallelCompactData::ChunkData* c, bool newline = true) { - tty->print(SIZE_FORMAT_W("5") " " PTR_FORMAT " " - SIZE_FORMAT_W("5") " " SIZE_FORMAT_W("5") " " - SIZE_FORMAT_W("5") " " SIZE_FORMAT_W("5") " %d", + tty->print(SIZE_FORMAT_W(5) " " PTR_FORMAT " " + SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " + SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d", i, c->destination(), c->partial_obj_size(), c->live_obj_size(), c->data_size(), c->source_chunk(), c->destination_count()); @@ -326,7 +326,7 @@ print_initial_summary_data(ParallelCompactData& summary_data, } print_initial_summary_chunk(i, c, false); - tty->print_cr(" %12.10f " SIZE_FORMAT_W("10") " " SIZE_FORMAT_W("10"), + tty->print_cr(" %12.10f " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10), reclaimed_ratio, dead_to_right, live_to_right); live_to_right -= c->data_size(); @@ -338,8 +338,8 @@ print_initial_summary_data(ParallelCompactData& summary_data, print_initial_summary_chunk(i, summary_data.chunk(i)); } - tty->print_cr("max: " SIZE_FORMAT_W("4") " d2r=" SIZE_FORMAT_W("10") " " - "l2r=" SIZE_FORMAT_W("10") " max_ratio=%14.12f", + tty->print_cr("max: " SIZE_FORMAT_W(4) " d2r=" SIZE_FORMAT_W(10) " " + "l2r=" SIZE_FORMAT_W(10) " max_ratio=%14.12f", max_reclaimed_ratio_chunk, max_dead_to_right, max_live_to_right, max_reclaimed_ratio); } @@ -1121,8 +1121,8 @@ PSParallelCompact::compute_dense_prefix_via_density(const SpaceId id, HeapWord* chunk_destination = cp->destination(); const size_t cur_deadwood = pointer_delta(dense_prefix, chunk_destination); if (TraceParallelOldGCDensePrefix && Verbose) { - tty->print_cr("c#=" SIZE_FORMAT_W("04") " dst=" PTR_FORMAT " " - "dp=" SIZE_FORMAT_W("08") " " "cdw=" SIZE_FORMAT_W("08"), + tty->print_cr("c#=" SIZE_FORMAT_W(4) " dst=" PTR_FORMAT " " + "dp=" SIZE_FORMAT_W(8) " " "cdw=" SIZE_FORMAT_W(8), sd.chunk(cp), chunk_destination, dense_prefix, cur_deadwood); } @@ -1147,7 +1147,7 @@ PSParallelCompact::compute_dense_prefix_via_density(const SpaceId id, return dense_prefix; } if (TraceParallelOldGCDensePrefix && Verbose) { - tty->print_cr("backing up from c=" SIZE_FORMAT_W("4") " d2r=%10.8f " + tty->print_cr("backing up from c=" SIZE_FORMAT_W(4) " d2r=%10.8f " "pc_d2r=%10.8f", sd.chunk(cp), density_to_right, prev_chunk_density_to_right); } @@ -1184,7 +1184,7 @@ void PSParallelCompact::print_dense_prefix_stats(const char* const algorithm, const size_t live_to_right = new_top - cp->destination(); const size_t dead_to_right = space->top() - addr - live_to_right; - tty->print_cr("%s=" PTR_FORMAT " dpc=" SIZE_FORMAT_W("05") " " + tty->print_cr("%s=" PTR_FORMAT " dpc=" SIZE_FORMAT_W(5) " " "spl=" SIZE_FORMAT " " "d2l=" SIZE_FORMAT " d2l%%=%6.4f " "d2r=" SIZE_FORMAT " l2r=" SIZE_FORMAT @@ -2513,7 +2513,7 @@ void PSParallelCompact::enqueue_chunk_draining_tasks(GCTaskQueue* q, if (TraceParallelOldGCCompactionPhase && Verbose) { const size_t count_mod_8 = fillable_chunks & 7; if (count_mod_8 == 0) gclog_or_tty->print("fillable: "); - gclog_or_tty->print(" " SIZE_FORMAT_W("7"), cur); + gclog_or_tty->print(" " SIZE_FORMAT_W(7), cur); if (count_mod_8 == 7) gclog_or_tty->cr(); } From 038a30dde34c5e17ed802ff43397099e6d3a4b77 Mon Sep 17 00:00:00 2001 From: John Coomes Date: Fri, 11 Jul 2008 16:11:43 -0700 Subject: [PATCH 032/325] 6483129: par compact assertion failure (new_top > bottom) Avoid computing the dense prefix if a space is empty Reviewed-by: pbk, tonyp --- .../parallelScavenge/psParallelCompact.cpp | 53 ++++++++++--------- 1 file changed, 29 insertions(+), 24 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp index 7a41736fb63..27b4ea90f56 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp @@ -1524,48 +1524,53 @@ void PSParallelCompact::summarize_space(SpaceId id, bool maximum_compaction) { assert(id < last_space_id, "id out of range"); + assert(_space_info[id].dense_prefix() == _space_info[id].space()->bottom(), + "should have been set in summarize_spaces_quick()"); const MutableSpace* space = _space_info[id].space(); - HeapWord** new_top_addr = _space_info[id].new_top_addr(); - - HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction); - _space_info[id].set_dense_prefix(dense_prefix_end); + if (_space_info[id].new_top() != space->bottom()) { + HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction); + _space_info[id].set_dense_prefix(dense_prefix_end); #ifndef PRODUCT - if (TraceParallelOldGCDensePrefix) { - print_dense_prefix_stats("ratio", id, maximum_compaction, dense_prefix_end); - HeapWord* addr = compute_dense_prefix_via_density(id, maximum_compaction); - print_dense_prefix_stats("density", id, maximum_compaction, addr); - } + if (TraceParallelOldGCDensePrefix) { + print_dense_prefix_stats("ratio", id, maximum_compaction, + dense_prefix_end); + HeapWord* addr = compute_dense_prefix_via_density(id, maximum_compaction); + print_dense_prefix_stats("density", id, maximum_compaction, addr); + } #endif // #ifndef PRODUCT - // If dead space crosses the dense prefix boundary, it is (at least partially) - // filled with a dummy object, marked live and added to the summary data. - // This simplifies the copy/update phase and must be done before the final - // locations of objects are determined, to prevent leaving a fragment of dead - // space that is too small to fill with an object. - if (!maximum_compaction && dense_prefix_end != space->bottom()) { - fill_dense_prefix_end(id); - } + // If dead space crosses the dense prefix boundary, it is (at least + // partially) filled with a dummy object, marked live and added to the + // summary data. This simplifies the copy/update phase and must be done + // before the final locations of objects are determined, to prevent leaving + // a fragment of dead space that is too small to fill with an object. + if (!maximum_compaction && dense_prefix_end != space->bottom()) { + fill_dense_prefix_end(id); + } - // Compute the destination of each Chunk, and thus each object. - _summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end); - _summary_data.summarize(dense_prefix_end, space->end(), - dense_prefix_end, space->top(), - new_top_addr); + // Compute the destination of each Chunk, and thus each object. + _summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end); + _summary_data.summarize(dense_prefix_end, space->end(), + dense_prefix_end, space->top(), + _space_info[id].new_top_addr()); + } if (TraceParallelOldGCSummaryPhase) { const size_t chunk_size = ParallelCompactData::ChunkSize; + HeapWord* const dense_prefix_end = _space_info[id].dense_prefix(); const size_t dp_chunk = _summary_data.addr_to_chunk_idx(dense_prefix_end); const size_t dp_words = pointer_delta(dense_prefix_end, space->bottom()); - const HeapWord* nt_aligned_up = _summary_data.chunk_align_up(*new_top_addr); + HeapWord* const new_top = _space_info[id].new_top(); + const HeapWord* nt_aligned_up = _summary_data.chunk_align_up(new_top); const size_t cr_words = pointer_delta(nt_aligned_up, dense_prefix_end); tty->print_cr("id=%d cap=" SIZE_FORMAT " dp=" PTR_FORMAT " " "dp_chunk=" SIZE_FORMAT " " "dp_count=" SIZE_FORMAT " " "cr_count=" SIZE_FORMAT " " "nt=" PTR_FORMAT, id, space->capacity_in_words(), dense_prefix_end, dp_chunk, dp_words / chunk_size, - cr_words / chunk_size, *new_top_addr); + cr_words / chunk_size, new_top); } } From 26625ab7f58d0741a1a3536746a819fd4da7c7b5 Mon Sep 17 00:00:00 2001 From: John Coomes Date: Fri, 11 Jul 2008 16:11:50 -0700 Subject: [PATCH 033/325] 6724367: par compact could clear less young gen summary data Reviewed-by: jmasa, apetrusenko --- .../parallelScavenge/psParallelCompact.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp index 27b4ea90f56..0b0d981fdc4 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp @@ -1639,7 +1639,7 @@ void PSParallelCompact::summary_phase(ParCompactionManager* cm, const size_t live = pointer_delta(_space_info[id].new_top(), space->bottom()); const size_t available = pointer_delta(target_space_end, *new_top_addr); - if (live <= available) { + if (live > 0 && live <= available) { // All the live data will fit. if (TraceParallelOldGCSummaryPhase) { tty->print_cr("summarizing %d into old_space @ " PTR_FORMAT, @@ -1649,16 +1649,18 @@ void PSParallelCompact::summary_phase(ParCompactionManager* cm, space->bottom(), space->top(), new_top_addr); - // Reset the new_top value for the space. - _space_info[id].set_new_top(space->bottom()); - // Clear the source_chunk field for each chunk in the space. + HeapWord* const new_top = _space_info[id].new_top(); + HeapWord* const clear_end = _summary_data.chunk_align_up(new_top); ChunkData* beg_chunk = _summary_data.addr_to_chunk_ptr(space->bottom()); - ChunkData* end_chunk = _summary_data.addr_to_chunk_ptr(space->top() - 1); - while (beg_chunk <= end_chunk) { + ChunkData* end_chunk = _summary_data.addr_to_chunk_ptr(clear_end); + while (beg_chunk < end_chunk) { beg_chunk->set_source_chunk(0); ++beg_chunk; } + + // Reset the new_top value for the space. + _space_info[id].set_new_top(space->bottom()); } } From cc0b15ccd8a80631794d153bc3c8eb187f0eee0a Mon Sep 17 00:00:00 2001 From: Michael McMahon Date: Mon, 14 Jul 2008 11:39:42 +0100 Subject: [PATCH 034/325] 6536211: flaw in ServerImpl Removed doPrivileged block Reviewed-by: jccollet --- jdk/src/share/classes/sun/net/httpserver/ServerImpl.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java b/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java index 104bdb0180b..c041e0bc065 100644 --- a/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java +++ b/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java @@ -120,14 +120,8 @@ class ServerImpl implements TimeSource { if (executor == null) { executor = new DefaultExecutor(); } + Thread t = new Thread (dispatcher); started = true; - final Dispatcher d = dispatcher; - Thread t = AccessController.doPrivileged(new PrivilegedAction() { - public Thread run() { - Thread t = new Thread (d); - return t; - } - }); t.start(); } From e9e432633bdaa3b094c84f1d85ed476d5cc0eab2 Mon Sep 17 00:00:00 2001 From: Igor Veresov Date: Mon, 14 Jul 2008 04:12:47 -0700 Subject: [PATCH 035/325] 6720130: NUMA allocator: The linux version should search for libnuma.so.1 Search for libnuma.so.1 on Linux and liblgrp.so.1 on Solaris. Reviewed-by: jmasa --- hotspot/src/os/linux/vm/os_linux.cpp | 2 +- hotspot/src/os/solaris/vm/os_solaris.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp index 73bcd1d0733..831cffcb81b 100644 --- a/hotspot/src/os/linux/vm/os_linux.cpp +++ b/hotspot/src/os/linux/vm/os_linux.cpp @@ -2278,7 +2278,7 @@ void os::Linux::libnuma_init() { dlsym(RTLD_DEFAULT, "sched_getcpu"))); if (sched_getcpu() != -1) { // Does it work? - void *handle = dlopen("libnuma.so", RTLD_LAZY); + void *handle = dlopen("libnuma.so.1", RTLD_LAZY); if (handle != NULL) { set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t, dlsym(handle, "numa_node_to_cpus"))); diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp index ce6765e8d50..99005264c7b 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.cpp +++ b/hotspot/src/os/solaris/vm/os_solaris.cpp @@ -4570,7 +4570,7 @@ void os::Solaris::synchronization_init() { } void os::Solaris::liblgrp_init() { - void *handle = dlopen("liblgrp.so", RTLD_LAZY); + void *handle = dlopen("liblgrp.so.1", RTLD_LAZY); if (handle != NULL) { os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home"))); os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init"))); From a8fc1db8c1e873443bdc011e0803f45c265528ff Mon Sep 17 00:00:00 2001 From: Chuck Rasbold Date: Wed, 16 Jul 2008 10:08:57 -0700 Subject: [PATCH 036/325] 6707044: uncommon_trap of ifnull bytecode leaves garbage on expression stack Remove call to repush_if_args() Reviewed-by: kvn, jrose --- hotspot/src/share/vm/opto/parse2.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/opto/parse2.cpp b/hotspot/src/share/vm/opto/parse2.cpp index b3e0a9aff10..e244d6a098e 100644 --- a/hotspot/src/share/vm/opto/parse2.cpp +++ b/hotspot/src/share/vm/opto/parse2.cpp @@ -875,6 +875,8 @@ bool Parse::seems_never_taken(float prob) { return prob < PROB_MIN; } +//-------------------------------repush_if_args-------------------------------- +// Push arguments of an "if" bytecode back onto the stack by adjusting _sp. inline void Parse::repush_if_args() { #ifndef PRODUCT if (PrintOpto && WizardMode) { @@ -906,7 +908,6 @@ void Parse::do_ifnull(BoolTest::mask btest) { if (PrintOpto && Verbose) tty->print_cr("Never-taken backedge stops compilation at bci %d",bci()); #endif - repush_if_args(); // to gather stats on loop // We need to mark this branch as taken so that if we recompile we will // see that it is possible. In the tiered system the interpreter doesn't // do profiling and by the time we get to the lower tier from the interpreter From fae39068e8e2e14e65ac5f4e906e60efc90ba241 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 16 Jul 2008 16:04:39 -0700 Subject: [PATCH 037/325] 6723160: Nightly failure: Error: meet not symmetric Add missing _instance_id settings and other EA fixes. Reviewed-by: rasbold --- hotspot/src/share/vm/adlc/formssel.cpp | 2 + hotspot/src/share/vm/opto/callnode.cpp | 58 ++------------- hotspot/src/share/vm/opto/cfgnode.cpp | 6 +- hotspot/src/share/vm/opto/compile.cpp | 44 ++++++++--- hotspot/src/share/vm/opto/escape.cpp | 23 ++++-- hotspot/src/share/vm/opto/macro.cpp | 77 +++++++++++-------- hotspot/src/share/vm/opto/macro.hpp | 2 +- hotspot/src/share/vm/opto/memnode.cpp | 4 +- hotspot/src/share/vm/opto/node.hpp | 4 + hotspot/src/share/vm/opto/type.cpp | 35 +++------ hotspot/test/compiler/6724218/Test.java | 98 +++++++++++++++++++++++++ 11 files changed, 224 insertions(+), 129 deletions(-) create mode 100644 hotspot/test/compiler/6724218/Test.java diff --git a/hotspot/src/share/vm/adlc/formssel.cpp b/hotspot/src/share/vm/adlc/formssel.cpp index 47fe6ae04eb..b45de088afb 100644 --- a/hotspot/src/share/vm/adlc/formssel.cpp +++ b/hotspot/src/share/vm/adlc/formssel.cpp @@ -3825,6 +3825,8 @@ int MatchRule::is_expensive() const { strcmp(opType,"ConvL2D")==0 || strcmp(opType,"ConvL2F")==0 || strcmp(opType,"ConvL2I")==0 || + strcmp(opType,"DecodeN")==0 || + strcmp(opType,"EncodeP")==0 || strcmp(opType,"RoundDouble")==0 || strcmp(opType,"RoundFloat")==0 || strcmp(opType,"ReverseBytesI")==0 || diff --git a/hotspot/src/share/vm/opto/callnode.cpp b/hotspot/src/share/vm/opto/callnode.cpp index 84015b5335c..389db14fed5 100644 --- a/hotspot/src/share/vm/opto/callnode.cpp +++ b/hotspot/src/share/vm/opto/callnode.cpp @@ -631,61 +631,13 @@ uint CallNode::match_edge(uint idx) const { bool CallNode::may_modify(const TypePtr *addr_t, PhaseTransform *phase) { const TypeOopPtr *adrInst_t = addr_t->isa_oopptr(); - // if not an InstPtr or not an instance type, assume the worst - if (adrInst_t == NULL || !adrInst_t->is_known_instance_field()) { + // If not an OopPtr or not an instance type, assume the worst. + // Note: currently this method is called only for instance types. + if (adrInst_t == NULL || !adrInst_t->is_known_instance()) { return true; } - Compile *C = phase->C; - int offset = adrInst_t->offset(); - assert(adrInst_t->klass_is_exact() && offset >= 0, "should be valid offset"); - ciKlass* adr_k = adrInst_t->klass(); - assert(adr_k->is_loaded() && - adr_k->is_java_klass() && - !adr_k->is_interface(), - "only non-abstract classes are expected"); - - int base_idx = C->get_alias_index(adrInst_t); - int size = BytesPerLong; // If we don't know the size, assume largest. - if (adrInst_t->isa_instptr()) { - ciField* field = C->alias_type(base_idx)->field(); - if (field != NULL) { - size = field->size_in_bytes(); - } - } else { - assert(adrInst_t->isa_aryptr(), "only arrays are expected"); - size = type2aelembytes(adr_k->as_array_klass()->element_type()->basic_type()); - } - - ciMethod * meth = is_CallStaticJava() ? as_CallStaticJava()->method() : NULL; - BCEscapeAnalyzer *bcea = (meth != NULL) ? meth->get_bcea() : NULL; - - const TypeTuple * d = tf()->domain(); - for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { - const Type* t = d->field_at(i); - Node *arg = in(i); - const Type *at = phase->type(arg); - if (at == TypePtr::NULL_PTR || at == Type::TOP) - continue; // null can't affect anything - - const TypeOopPtr *at_ptr = at->isa_oopptr(); - if (!arg->is_top() && (t->isa_oopptr() != NULL || - t->isa_ptr() && at_ptr != NULL)) { - assert(at_ptr != NULL, "expecting an OopPtr"); - ciKlass* at_k = at_ptr->klass(); - if ((adrInst_t->base() == at_ptr->base()) && - at_k->is_loaded() && - at_k->is_java_klass()) { - // If we have found an argument matching addr_t, check if the field - // at the specified offset is modified. - if ((at_k->is_interface() || adr_k == at_k || - adr_k->is_subclass_of(at_k) && !at_ptr->klass_is_exact()) && - (bcea == NULL || - bcea->is_arg_modified(i - TypeFunc::Parms, offset, size))) { - return true; - } - } - } - } + // The instance_id is set only for scalar-replaceable allocations which + // are not passed as arguments according to Escape Analysis. return false; } diff --git a/hotspot/src/share/vm/opto/cfgnode.cpp b/hotspot/src/share/vm/opto/cfgnode.cpp index 6087c17e0dd..0e7b2845dbc 100644 --- a/hotspot/src/share/vm/opto/cfgnode.cpp +++ b/hotspot/src/share/vm/opto/cfgnode.cpp @@ -713,7 +713,9 @@ PhiNode* PhiNode::split_out_instance(const TypePtr* at, PhaseIterGVN *igvn) cons assert(type() == Type::MEMORY && (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM || t->isa_oopptr() && !t->is_oopptr()->is_known_instance() && - t->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop), + t->is_oopptr()->cast_to_exactness(true) + ->is_oopptr()->cast_to_ptr_type(t_oop->ptr()) + ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop), "bottom or raw memory required"); // Check if an appropriate node already exists. @@ -1089,6 +1091,8 @@ Node* PhiNode::unique_input(PhaseTransform* phase) { if (rc == NULL || phase->type(rc) == Type::TOP) continue; // ignore unreachable control path Node* n = in(i); + if (n == NULL) + continue; Node* un = n->uncast(); if (un == NULL || un == this || phase->type(un) == Type::TOP) { continue; // ignore if top, or in(i) and "this" are in a data cycle diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp index 117fa54ff1b..c57a460d45d 100644 --- a/hotspot/src/share/vm/opto/compile.cpp +++ b/hotspot/src/share/vm/opto/compile.cpp @@ -999,9 +999,14 @@ const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { int offset = tj->offset(); TypePtr::PTR ptr = tj->ptr(); + // Known instance (scalarizable allocation) alias only with itself. + bool is_known_inst = tj->isa_oopptr() != NULL && + tj->is_oopptr()->is_known_instance(); + // Process weird unsafe references. if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) { assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops"); + assert(!is_known_inst, "scalarizable allocation should not have unsafe references"); tj = TypeOopPtr::BOTTOM; ptr = tj->ptr(); offset = tj->offset(); @@ -1009,14 +1014,20 @@ const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { // Array pointers need some flattening const TypeAryPtr *ta = tj->isa_aryptr(); - if( ta && _AliasLevel >= 2 ) { + if( ta && is_known_inst ) { + if ( offset != Type::OffsetBot && + offset > arrayOopDesc::length_offset_in_bytes() ) { + offset = Type::OffsetBot; // Flatten constant access into array body only + tj = ta = TypeAryPtr::make(ptr, ta->ary(), ta->klass(), true, offset, ta->instance_id()); + } + } else if( ta && _AliasLevel >= 2 ) { // For arrays indexed by constant indices, we flatten the alias // space to include all of the array body. Only the header, klass // and array length can be accessed un-aliased. if( offset != Type::OffsetBot ) { if( ta->const_oop() ) { // methodDataOop or methodOop offset = Type::OffsetBot; // Flatten constant access into array body - tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,Type::OffsetBot, ta->instance_id()); + tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,offset); } else if( offset == arrayOopDesc::length_offset_in_bytes() ) { // range is OK as-is. tj = ta = TypeAryPtr::RANGE; @@ -1030,29 +1041,29 @@ const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { ptr = TypePtr::BotPTR; } else { // Random constant offset into array body offset = Type::OffsetBot; // Flatten constant access into array body - tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,Type::OffsetBot, ta->instance_id()); + tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,offset); } } // Arrays of fixed size alias with arrays of unknown size. if (ta->size() != TypeInt::POS) { const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS); - tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset, ta->instance_id()); + tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset); } // Arrays of known objects become arrays of unknown objects. if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) { const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size()); - tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset, ta->instance_id()); + tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset); } if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) { const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size()); - tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset, ta->instance_id()); + tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset); } // Arrays of bytes and of booleans both use 'bastore' and 'baload' so // cannot be distinguished by bytecode alone. if (ta->elem() == TypeInt::BOOL) { const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size()); ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE); - tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset, ta->instance_id()); + tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset); } // During the 2nd round of IterGVN, NotNull castings are removed. // Make sure the Bottom and NotNull variants alias the same. @@ -1072,21 +1083,24 @@ const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { if( ptr == TypePtr::Constant ) { // No constant oop pointers (such as Strings); they alias with // unknown strings. + assert(!is_known_inst, "not scalarizable allocation"); tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset); - } else if( to->is_known_instance_field() ) { + } else if( is_known_inst ) { tj = to; // Keep NotNull and klass_is_exact for instance type } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) { // During the 2nd round of IterGVN, NotNull castings are removed. // Make sure the Bottom and NotNull variants alias the same. // Also, make sure exact and non-exact variants alias the same. - tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset, to->instance_id()); + tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset); } // Canonicalize the holder of this field ciInstanceKlass *k = to->klass()->as_instance_klass(); if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) { // First handle header references such as a LoadKlassNode, even if the // object's klass is unloaded at compile time (4965979). - tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset, to->instance_id()); + if (!is_known_inst) { // Do it only for non-instance types + tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset); + } } else if (offset < 0 || offset >= k->size_helper() * wordSize) { to = NULL; tj = TypeOopPtr::BOTTOM; @@ -1094,7 +1108,11 @@ const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const { } else { ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset); if (!k->equals(canonical_holder) || tj->offset() != offset) { - tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset, to->instance_id()); + if( is_known_inst ) { + tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id()); + } else { + tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset); + } } } } @@ -1280,7 +1298,9 @@ Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_cr assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr"); if (flat->isa_oopptr() && !flat->isa_klassptr()) { const TypeOopPtr* foop = flat->is_oopptr(); - const TypePtr* xoop = foop->cast_to_exactness(!foop->klass_is_exact())->is_ptr(); + // Scalarizable allocations have exact klass always. + bool exact = !foop->klass_is_exact() || foop->is_known_instance(); + const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr(); assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type"); } assert(flat == flatten_alias_type(flat), "exact bit doesn't matter"); diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index 795741284b0..8a779f59431 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -717,12 +717,17 @@ Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArra } } } - if (is_instance && result->is_Phi()) { + if (result->is_Phi()) { PhiNode *mphi = result->as_Phi(); assert(mphi->bottom_type() == Type::MEMORY, "memory phi required"); const TypePtr *t = mphi->adr_type(); if (C->get_alias_index(t) != alias_idx) { + // Create a new Phi with the specified alias index type. result = split_memory_phi(mphi, alias_idx, orig_phis, phase); + } else if (!is_instance) { + // Push all non-instance Phis on the orig_phis worklist to update inputs + // during Phase 4 if needed. + orig_phis.append_if_missing(mphi); } } // the result is either MemNode, PhiNode, InitializeNode. @@ -859,10 +864,14 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) !n->is_CheckCastPP()) // not unique CheckCastPP. continue; // The inline code for Object.clone() casts the allocation result to - // java.lang.Object and then to the the actual type of the allocated + // java.lang.Object and then to the actual type of the allocated // object. Detect this case and use the second cast. + // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when + // the allocation result is cast to java.lang.Object and then + // to the actual Array type. if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL - && igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT) { + && (alloc->is_AllocateArray() || + igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT)) { Node *cast2 = NULL; for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { Node *use = n->fast_out(i); @@ -878,7 +887,7 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) } } set_escape_state(n->_idx, es); - // in order for an object to be stackallocatable, it must be: + // in order for an object to be scalar-replaceable, it must be: // - a direct allocation (not a call returning an object) // - non-escaping // - eligible to be a unique type @@ -888,7 +897,7 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) const TypeOopPtr *t = igvn->type(n)->isa_oopptr(); if (t == NULL) continue; // not a TypeInstPtr - tinst = t->cast_to_instance_id(ni); + tinst = t->cast_to_exactness(true)->is_oopptr()->cast_to_instance_id(ni); igvn->hash_delete(n); igvn->set_type(n, tinst); n->raise_bottom_type(tinst); @@ -1204,8 +1213,8 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) // to recursively process Phi's encounted on the input memory // chains as is done in split_memory_phi() since they will // also be processed here. - while (orig_phis.length() != 0) { - PhiNode *phi = orig_phis.pop(); + for (int j = 0; j < orig_phis.length(); j++) { + PhiNode *phi = orig_phis.at(j); int alias_idx = _compile->get_alias_index(phi->adr_type()); igvn->hash_delete(phi); for (uint i = 1; i < phi->req(); i++) { diff --git a/hotspot/src/share/vm/opto/macro.cpp b/hotspot/src/share/vm/opto/macro.cpp index cd38a4be324..3e036249edd 100644 --- a/hotspot/src/share/vm/opto/macro.cpp +++ b/hotspot/src/share/vm/opto/macro.cpp @@ -231,8 +231,7 @@ static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_me } else { return mem; } - if (mem == orig_mem) - return mem; + assert(mem != orig_mem, "dead memory loop"); } } @@ -241,21 +240,44 @@ static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_me // on the input paths. // Note: this function is recursive, its depth is limied by the "level" argument // Returns the computed Phi, or NULL if it cannot compute it. -Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, Node *alloc, int level) { - - if (level <= 0) { - return NULL; - } +Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, Node *alloc, Node_Stack *value_phis, int level) { + assert(mem->is_Phi(), "sanity"); int alias_idx = C->get_alias_index(adr_t); int offset = adr_t->offset(); int instance_id = adr_t->instance_id(); + // Check if an appropriate value phi already exists. + Node* region = mem->in(0); + for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) { + Node* phi = region->fast_out(k); + if (phi->is_Phi() && phi != mem && + phi->as_Phi()->is_same_inst_field(phi_type, instance_id, alias_idx, offset)) { + return phi; + } + } + // Check if an appropriate new value phi already exists. + Node* new_phi = NULL; + uint size = value_phis->size(); + for (uint i=0; i < size; i++) { + if ( mem->_idx == value_phis->index_at(i) ) { + return value_phis->node_at(i); + } + } + + if (level <= 0) { + return NULL; + } Node *start_mem = C->start()->proj_out(TypeFunc::Memory); Node *alloc_mem = alloc->in(TypeFunc::Memory); uint length = mem->req(); GrowableArray values(length, length, NULL); + // create a new Phi for the value + PhiNode *phi = new (C, length) PhiNode(mem->in(0), phi_type, NULL, instance_id, alias_idx, offset); + transform_later(phi); + value_phis->push(phi, mem->_idx); + for (uint j = 1; j < length; j++) { Node *in = mem->in(j); if (in == NULL || in->is_top()) { @@ -280,33 +302,17 @@ Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type * } else if(val->is_Proj() && val->in(0) == alloc) { values.at_put(j, _igvn.zerocon(ft)); } else if (val->is_Phi()) { - // Check if an appropriate node already exists. - Node* region = val->in(0); - Node* old_phi = NULL; - for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) { - Node* phi = region->fast_out(k); - if (phi->is_Phi() && phi != val && - phi->as_Phi()->is_same_inst_field(phi_type, instance_id, alias_idx, offset)) { - old_phi = phi; - break; - } - } - if (old_phi == NULL) { - val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, level-1); - if (val == NULL) { - return NULL; - } - values.at_put(j, val); - } else { - values.at_put(j, old_phi); + val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1); + if (val == NULL) { + return NULL; } + values.at_put(j, val); } else { return NULL; // unknown node on this path } } } - // create a new Phi for the value - PhiNode *phi = new (C, length) PhiNode(mem->in(0), phi_type, NULL, instance_id, alias_idx, offset); + // Set Phi's inputs for (uint j = 1; j < length; j++) { if (values.at(j) == mem) { phi->init_req(j, phi); @@ -314,7 +320,6 @@ Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type * phi->init_req(j, values.at(j)); } } - transform_later(phi); return phi; } @@ -329,7 +334,8 @@ Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, BasicType ft, const Type Node *start_mem = C->start()->proj_out(TypeFunc::Memory); Node *alloc_ctrl = alloc->in(TypeFunc::Control); Node *alloc_mem = alloc->in(TypeFunc::Memory); - VectorSet visited(Thread::current()->resource_area()); + Arena *a = Thread::current()->resource_area(); + VectorSet visited(a); bool done = sfpt_mem == alloc_mem; @@ -389,9 +395,18 @@ Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, BasicType ft, const Type return mem->in(MemNode::ValueIn); } else if (mem->is_Phi()) { // attempt to produce a Phi reflecting the values on the input paths of the Phi - Node * phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, 8); + Node_Stack value_phis(a, 8); + Node * phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, 8); if (phi != NULL) { return phi; + } else { + // Kill all new Phis + while(value_phis.is_nonempty()) { + Node* n = value_phis.node(); + _igvn.hash_delete(n); + _igvn.subsume_node(n, C->top()); + value_phis.pop(); + } } } } diff --git a/hotspot/src/share/vm/opto/macro.hpp b/hotspot/src/share/vm/opto/macro.hpp index 0f784aafc02..89ed2bd2f47 100644 --- a/hotspot/src/share/vm/opto/macro.hpp +++ b/hotspot/src/share/vm/opto/macro.hpp @@ -79,7 +79,7 @@ private: const TypeFunc* slow_call_type, address slow_call_address); Node *value_from_mem(Node *mem, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, Node *alloc); - Node *value_from_mem_phi(Node *mem, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, Node *alloc, int level); + Node *value_from_mem_phi(Node *mem, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, Node *alloc, Node_Stack *value_phis, int level); bool eliminate_allocate_node(AllocateNode *alloc); bool can_eliminate_allocation(AllocateNode *alloc, GrowableArray & safepoints); diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp index 5015d99c483..8388753e937 100644 --- a/hotspot/src/share/vm/opto/memnode.cpp +++ b/hotspot/src/share/vm/opto/memnode.cpp @@ -135,7 +135,9 @@ Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, PhaseGV const TypePtr *t = mphi->adr_type(); if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM || t->isa_oopptr() && !t->is_oopptr()->is_known_instance() && - t->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) { + t->is_oopptr()->cast_to_exactness(true) + ->is_oopptr()->cast_to_ptr_type(t_oop->ptr()) + ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()) == t_oop) { // clone the Phi with our address type result = mphi->split_out_instance(t_adr, igvn); } else { diff --git a/hotspot/src/share/vm/opto/node.hpp b/hotspot/src/share/vm/opto/node.hpp index 7f78b426b1c..e027265bf67 100644 --- a/hotspot/src/share/vm/opto/node.hpp +++ b/hotspot/src/share/vm/opto/node.hpp @@ -1399,6 +1399,10 @@ public: uint index() const { return _inode_top->indx; } + uint index_at(uint i) const { + assert(_inodes + i <= _inode_top, "in range"); + return _inodes[i].indx; + } void set_node(Node *n) { _inode_top->node = n; } diff --git a/hotspot/src/share/vm/opto/type.cpp b/hotspot/src/share/vm/opto/type.cpp index bb6c959388f..3a77c9da4f0 100644 --- a/hotspot/src/share/vm/opto/type.cpp +++ b/hotspot/src/share/vm/opto/type.cpp @@ -2218,7 +2218,7 @@ const Type *TypeOopPtr::cast_to_ptr_type(PTR ptr) const { return make(ptr, _offset); } -//-----------------------------cast_to_instance------------------------------- +//-----------------------------cast_to_instance_id---------------------------- const TypeOopPtr *TypeOopPtr::cast_to_instance_id(int instance_id) const { // There are no instances of a general oop. // Return self unchanged. @@ -2610,8 +2610,7 @@ const TypeInstPtr *TypeInstPtr::make(PTR ptr, // Ptr is never Null assert( ptr != Null, "NULL pointers are not typed" ); - if ( instance_id > 0 ) - xk = true; // instances are always exactly typed + assert(instance_id <= 0 || xk || !UseExactTypes, "instances are always exactly typed"); if (!UseExactTypes) xk = false; if (ptr == Constant) { // Note: This case includes meta-object constants, such as methods. @@ -2650,16 +2649,10 @@ const Type *TypeInstPtr::cast_to_exactness(bool klass_is_exact) const { return make(ptr(), klass(), klass_is_exact, const_oop(), _offset, _instance_id); } -//-----------------------------cast_to_instance------------------------------- +//-----------------------------cast_to_instance_id---------------------------- const TypeOopPtr *TypeInstPtr::cast_to_instance_id(int instance_id) const { if( instance_id == _instance_id ) return this; - bool exact = _klass_is_exact; - PTR ptr_t = _ptr; - if ( instance_id > 0 ) { // instances are always exactly typed - if (UseExactTypes) exact = true; - ptr_t = NotNull; - } - return make(ptr_t, klass(), exact, const_oop(), _offset, instance_id); + return make(_ptr, klass(), _klass_is_exact, const_oop(), _offset, instance_id); } //------------------------------xmeet_unloaded--------------------------------- @@ -2899,6 +2892,7 @@ const Type *TypeInstPtr::xmeet( const Type *t ) const { xk = above_centerline(ptr) ? tinst_xk : false; // Watch out for Constant vs. AnyNull interface. if (ptr == Constant) ptr = NotNull; // forget it was a constant + instance_id = InstanceBot; } ciObject* o = NULL; // the Constant value, if any if (ptr == Constant) { @@ -2989,6 +2983,7 @@ const Type *TypeInstPtr::xmeet( const Type *t ) const { // class hierarchy - which means we have to fall to at least NotNull. if( ptr == TopPTR || ptr == AnyNull || ptr == Constant ) ptr = NotNull; + instance_id = InstanceBot; // Now we find the LCA of Java classes ciKlass* k = this_klass->least_common_ancestor(tinst_klass); @@ -3101,8 +3096,7 @@ const TypeAryPtr *TypeAryPtr::make( PTR ptr, const TypeAry *ary, ciKlass* k, boo assert(!(k == NULL && ary->_elem->isa_int()), "integral arrays must be pre-equipped with a class"); if (!xk) xk = ary->ary_must_be_exact(); - if ( instance_id > 0 ) - xk = true; // instances are always exactly typed + assert(instance_id <= 0 || xk || !UseExactTypes, "instances are always exactly typed"); if (!UseExactTypes) xk = (ptr == Constant); return (TypeAryPtr*)(new TypeAryPtr(ptr, NULL, ary, k, xk, offset, instance_id))->hashcons(); } @@ -3113,8 +3107,7 @@ const TypeAryPtr *TypeAryPtr::make( PTR ptr, ciObject* o, const TypeAry *ary, ci "integral arrays must be pre-equipped with a class"); assert( (ptr==Constant && o) || (ptr!=Constant && !o), "" ); if (!xk) xk = (o != NULL) || ary->ary_must_be_exact(); - if ( instance_id > 0 ) - xk = true; // instances are always exactly typed + assert(instance_id <= 0 || xk || !UseExactTypes, "instances are always exactly typed"); if (!UseExactTypes) xk = (ptr == Constant); return (TypeAryPtr*)(new TypeAryPtr(ptr, o, ary, k, xk, offset, instance_id))->hashcons(); } @@ -3134,16 +3127,10 @@ const Type *TypeAryPtr::cast_to_exactness(bool klass_is_exact) const { return make(ptr(), const_oop(), _ary, klass(), klass_is_exact, _offset, _instance_id); } -//-----------------------------cast_to_instance------------------------------- +//-----------------------------cast_to_instance_id---------------------------- const TypeOopPtr *TypeAryPtr::cast_to_instance_id(int instance_id) const { if( instance_id == _instance_id ) return this; - bool exact = _klass_is_exact; - PTR ptr_t = _ptr; - if ( instance_id > 0 ) { // instances are always exactly typed - if (UseExactTypes) exact = true; - ptr_t = NotNull; - } - return make(ptr_t, const_oop(), _ary, klass(), exact, _offset, instance_id); + return make(_ptr, const_oop(), _ary, klass(), _klass_is_exact, _offset, instance_id); } //-----------------------------narrow_size_type------------------------------- @@ -3300,6 +3287,7 @@ const Type *TypeAryPtr::xmeet( const Type *t ) const { } else { // Something like byte[int+] meets char[int+]. // This must fall to bottom, not (int[-128..65535])[int+]. + instance_id = InstanceBot; tary = TypeAry::make(Type::BOTTOM, tary->_size); } } @@ -3316,6 +3304,7 @@ const Type *TypeAryPtr::xmeet( const Type *t ) const { if( tap->const_oop() != NULL && !o->equals(tap->const_oop()) ) { ptr = NotNull; o = NULL; + instance_id = InstanceBot; } } else if( above_centerline(_ptr) ) { o = tap->const_oop(); diff --git a/hotspot/test/compiler/6724218/Test.java b/hotspot/test/compiler/6724218/Test.java new file mode 100644 index 00000000000..c2835168567 --- /dev/null +++ b/hotspot/test/compiler/6724218/Test.java @@ -0,0 +1,98 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6724218 + * @summary Fix raise_LCA_above_marks() early termination + * @run main/othervm -Xbatch -XX:CompileCommand=exclude,Test.update Test + */ + +public class Test { + Test next = null; + Object value = null; + + static boolean _closed = false; + static int size = 0; + static Test list = null; + static int cache_size = 0; + static Test cache = null; + + Object get(int i) { + Test t = list; + list = t.next; + size -= 1; + Object o = t.value; + if (i > 0) { + t.next = cache; + t.value = null; + cache = t; + cache_size = +1; + } + return o; + } + + void update() { + // Exclude compilation of this one. + if (size == 0) { + Test t; + if (cache_size > 0) { + t = cache; + cache = t.next; + cache_size = -1; + } else { + t = new Test(); + } + t.value = new Object(); + t.next = list; + list = t; + size += 1; + } + } + + synchronized Object test(int i) { + while (true) { + if (_closed) { + return null; + } else if (size > 0) { + return get(i); + } + update(); + } + } + + public static void main(String argv[]) throws Exception { + Test t = new Test(); + int lim = 500000; + Object o; + for (int j = 0; j < lim; j++) { + o = t.test(j&1); + if (o == null) { + throw new Exception("*** Failed on iteration " + j); + } + if ((j&1) == 0) { + t.update(); + } + } + } +} From 1193f0f9dbe9e365e86f1865d828a86bccbc39ce Mon Sep 17 00:00:00 2001 From: Igor Veresov Date: Thu, 17 Jul 2008 10:26:33 -0700 Subject: [PATCH 038/325] 6723228: NUMA allocator: assert(lgrp_id != -1, "No lgrp_id set") 6723229: NUMA allocator: assert(lgrp_num > 0, "There should be at least one locality group") The fix takes care of the assertion triggered during TLAB resizing after reconfiguration. Also it now handles a defect in the topology graph, in which a single leaf node doesn't have memory. Reviewed-by: jmasa --- hotspot/src/os/solaris/vm/os_solaris.cpp | 6 ++++ .../vm/gc_implementation/shared/gcUtil.hpp | 12 +++++++ .../shared/mutableNUMASpace.cpp | 32 +++++++++++++++++-- .../shared/mutableNUMASpace.hpp | 1 + 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp index 99005264c7b..6a8d173691d 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.cpp +++ b/hotspot/src/os/solaris/vm/os_solaris.cpp @@ -2658,6 +2658,12 @@ size_t os::numa_get_leaf_groups(int *ids, size_t size) { top += r; cur++; } + if (bottom == 0) { + // Handle a situation, when the OS reports no memory available. + // Assume UMA architecture. + ids[0] = 0; + return 1; + } return bottom; } diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcUtil.hpp b/hotspot/src/share/vm/gc_implementation/shared/gcUtil.hpp index 83fdf871de7..a6596e7e99f 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/gcUtil.hpp +++ b/hotspot/src/share/vm/gc_implementation/shared/gcUtil.hpp @@ -58,6 +58,12 @@ class AdaptiveWeightedAverage : public CHeapObj { _average(0.0), _sample_count(0), _weight(weight), _last_sample(0.0) { } + void clear() { + _average = 0; + _sample_count = 0; + _last_sample = 0; + } + // Accessors float average() const { return _average; } unsigned weight() const { return _weight; } @@ -115,6 +121,12 @@ class AdaptivePaddedAverage : public AdaptiveWeightedAverage { float deviation() const { return _deviation; } unsigned padding() const { return _padding; } + void clear() { + AdaptiveWeightedAverage::clear(); + _padded_avg = 0; + _deviation = 0; + } + // Override void sample(float new_sample); }; diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp index 20ca6d3e31f..50cfe16c887 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp +++ b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp @@ -141,7 +141,20 @@ size_t MutableNUMASpace::free_in_words() const { size_t MutableNUMASpace::tlab_capacity(Thread *thr) const { guarantee(thr != NULL, "No thread"); int lgrp_id = thr->lgrp_id(); - assert(lgrp_id != -1, "No lgrp_id set"); + if (lgrp_id == -1) { + // This case can occur after the topology of the system has + // changed. Thread can change their location, the new home + // group will be determined during the first allocation + // attempt. For now we can safely assume that all spaces + // have equal size because the whole space will be reinitialized. + if (lgrp_spaces()->length() > 0) { + return capacity_in_bytes() / lgrp_spaces()->length(); + } else { + assert(false, "There should be at least one locality group"); + return 0; + } + } + // That's the normal case, where we know the locality group of the thread. int i = lgrp_spaces()->find(&lgrp_id, LGRPSpace::equals); if (i == -1) { return 0; @@ -150,9 +163,17 @@ size_t MutableNUMASpace::tlab_capacity(Thread *thr) const { } size_t MutableNUMASpace::unsafe_max_tlab_alloc(Thread *thr) const { + // Please see the comments for tlab_capacity(). guarantee(thr != NULL, "No thread"); int lgrp_id = thr->lgrp_id(); - assert(lgrp_id != -1, "No lgrp_id set"); + if (lgrp_id == -1) { + if (lgrp_spaces()->length() > 0) { + return free_in_bytes() / lgrp_spaces()->length(); + } else { + assert(false, "There should be at least one locality group"); + return 0; + } + } int i = lgrp_spaces()->find(&lgrp_id, LGRPSpace::equals); if (i == -1) { return 0; @@ -250,10 +271,15 @@ void MutableNUMASpace::free_region(MemRegion mr) { void MutableNUMASpace::update() { if (update_layout(false)) { // If the topology has changed, make all chunks zero-sized. + // And clear the alloc-rate statistics. + // In future we may want to handle this more gracefully in order + // to avoid the reallocation of the pages as much as possible. for (int i = 0; i < lgrp_spaces()->length(); i++) { - MutableSpace *s = lgrp_spaces()->at(i)->space(); + LGRPSpace *ls = lgrp_spaces()->at(i); + MutableSpace *s = ls->space(); s->set_end(s->bottom()); s->set_top(s->bottom()); + ls->clear_alloc_rate(); } // A NUMA space is never mangled initialize(region(), diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp index 54a01299beb..61ee6d2bcc1 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp +++ b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp @@ -112,6 +112,7 @@ class MutableNUMASpace : public MutableSpace { int lgrp_id() const { return _lgrp_id; } MutableSpace* space() const { return _space; } AdaptiveWeightedAverage* alloc_rate() const { return _alloc_rate; } + void clear_alloc_rate() { _alloc_rate->clear(); } SpaceStats* space_stats() { return &_space_stats; } void clear_space_stats() { _space_stats = SpaceStats(); } From e91ae90285a36fff3584aaf5b2017f8b762de829 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Fri, 18 Jul 2008 18:26:22 +0400 Subject: [PATCH 039/325] 6552812: Add HSL tab to JColorChooser Reviewed-by: peterz, avu --- .../plaf/basic/resources/basic.properties | 33 +- .../plaf/basic/resources/basic_de.properties | 33 +- .../plaf/basic/resources/basic_es.properties | 33 +- .../plaf/basic/resources/basic_fr.properties | 33 +- .../plaf/basic/resources/basic_it.properties | 33 +- .../plaf/basic/resources/basic_ja.properties | 33 +- .../plaf/basic/resources/basic_ko.properties | 33 +- .../plaf/basic/resources/basic_sv.properties | 33 +- .../basic/resources/basic_zh_CN.properties | 33 +- .../basic/resources/basic_zh_TW.properties | 33 +- .../ColorChooserComponentFactory.java | 19 +- .../swing/colorchooser/ColorChooserPanel.java | 182 ++++ .../javax/swing/colorchooser/ColorModel.java | 102 +++ .../swing/colorchooser/ColorModelCMYK.java | 94 ++ .../swing/colorchooser/ColorModelHSL.java | 188 ++++ .../swing/colorchooser/ColorModelHSV.java | 138 +++ .../javax/swing/colorchooser/ColorPanel.java | 210 +++++ .../colorchooser/DefaultHSBChooserPanel.java | 801 ------------------ .../colorchooser/DefaultRGBChooserPanel.java | 294 ------- .../swing/colorchooser/DiagramComponent.java | 160 ++++ .../swing/colorchooser/SlidingSpinner.java | 118 +++ .../swing/colorchooser/SyntheticImage.java | 166 ---- .../swing/colorchooser/ValueFormatter.java | 151 ++++ .../swing/plaf/basic/BasicColorChooserUI.java | 6 +- .../swing/JColorChooser/Test6524757.java | 166 ++-- .../swing/JColorChooser/Test6559154.java | 75 ++ 26 files changed, 1726 insertions(+), 1474 deletions(-) create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java delete mode 100644 jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java delete mode 100644 jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java delete mode 100644 jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java create mode 100644 jdk/src/share/classes/javax/swing/colorchooser/ValueFormatter.java create mode 100644 jdk/test/javax/swing/JColorChooser/Test6559154.java diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties index 6087def3607..4dac249bfa0 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=Sample Text Sample Text ColorChooser.swatchesNameText=Swatches ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Recent: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Red ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=Green ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=Blue ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties index 93660548035..b3455977738 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=90 ColorChooser.sampleText=Beispieltext Beispieltext ColorChooser.swatchesNameText=Muster ColorChooser.swatchesMnemonic=77 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Aktuell: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rot ColorChooser.rgbRedMnemonic=82 ColorChooser.rgbGreenText=Gr\u00fcn ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=Blau ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties index b553b26f065..75877dd6560 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=Texto de ejemplo Texto de ejemplo ColorChooser.swatchesNameText=Muestras ColorChooser.swatchesMnemonic=77 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Reciente: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=V -ColorChooser.hsbBlueText=A +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rojo ColorChooser.rgbRedMnemonic=74 ColorChooser.rgbGreenText=Verde ColorChooser.rgbGreenMnemonic=86 ColorChooser.rgbBlueText=Azul ColorChooser.rgbBlueMnemonic=76 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties index b18de0274a8..333a1a82fa1 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=Echantillon de texte Echantillon de texte ColorChooser.swatchesNameText=Echantillons ColorChooser.swatchesMnemonic=69 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Dernier : -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=V -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RVB ColorChooser.rgbMnemonic=86 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rouge ColorChooser.rgbRedMnemonic=71 ColorChooser.rgbGreenText=Vert ColorChooser.rgbGreenMnemonic=84 ColorChooser.rgbBlueText=Bleu ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties index 1c9f3790e6f..7bc69dbcf5e 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=Testo di prova Testo di prova ColorChooser.swatchesNameText=Colori campione ColorChooser.swatchesMnemonic=67 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Recenti: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rosso ColorChooser.rgbRedMnemonic=79 ColorChooser.rgbGreenText=Verde ColorChooser.rgbGreenMnemonic=69 ColorChooser.rgbBlueText=Blu ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties index 1b5a131cabd..5603e9aa1bc 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=\u30b5\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8 \u30b5\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8 ColorChooser.swatchesNameText=\u30b5\u30f3\u30d7\u30eb(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=5 ColorChooser.swatchesRecentText=\u6700\u65b0: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u8d64(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7dd1(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u9752(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties index 9b873a43a61..f3866d01f31 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=\uc0d8\ud50c \ud14d\uc2a4\ud2b8 \uc0d8\ud50c \ud14d\uc2a4\ud2b8 ColorChooser.swatchesNameText=\uacac\ubcf8(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=3 ColorChooser.swatchesRecentText=\ucd5c\uadfc \ubaa9\ub85d: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\ube68\uac04\uc0c9(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\ub179\uc0c9(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\ud30c\ub780\uc0c9(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties index 2b8561b812e..17ef3b2be26 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=84 ColorChooser.sampleText=Exempeltext Exempeltext ColorChooser.swatchesNameText=Prov ColorChooser.swatchesMnemonic=80 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Tidigare: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=R\u00f6d ColorChooser.rgbRedMnemonic=82 ColorChooser.rgbGreenText=Gr\u00f6n ColorChooser.rgbGreenMnemonic=71 ColorChooser.rgbBlueText=Bl\u00e5 ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties index 7ef35330d86..b030c20a944 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=\u6837\u54c1\u6587\u672c \u6837\u54c1\u6587\u672c ColorChooser.swatchesNameText=\u6837\u54c1(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=3 ColorChooser.swatchesRecentText=\u6700\u8fd1: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u7ea2 ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7eff ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u84dd ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties index dba0d76de28..47f99f0dcc9 100644 --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties @@ -101,30 +101,41 @@ ColorChooser.resetMnemonic=82 ColorChooser.sampleText=\u7bc4\u4f8b\u6587\u5b57 \u7bc4\u4f8b\u6587\u5b57 ColorChooser.swatchesNameText=\u8abf\u8272\u677f(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=4 ColorChooser.swatchesRecentText=\u6700\u65b0\u9078\u64c7: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u7d05\u8272(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7da0\u8272(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u85cd\u8272(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java index b36c6524d8a..0ee01e6cb5a 100644 --- a/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,7 @@ package javax.swing.colorchooser; -import javax.swing.*; - - +import javax.swing.JComponent; /** * A class designed to produce preconfigured "accessory" objects to @@ -49,16 +47,17 @@ public class ColorChooserComponentFactory { private ColorChooserComponentFactory() { } // can't instantiate - public static AbstractColorChooserPanel[] getDefaultChooserPanels() { - AbstractColorChooserPanel[] choosers = { new DefaultSwatchChooserPanel(), - new DefaultHSBChooserPanel(), - new DefaultRGBChooserPanel() }; - return choosers; + return new AbstractColorChooserPanel[] { + new DefaultSwatchChooserPanel(), + new ColorChooserPanel(new ColorModelHSV()), + new ColorChooserPanel(new ColorModelHSL()), + new ColorChooserPanel(new ColorModel()), + new ColorChooserPanel(new ColorModelCMYK()), + }; } public static JComponent getPreviewPanel() { return new DefaultPreviewPanel(); } - } diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java new file mode 100644 index 00000000000..46b5351c695 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java @@ -0,0 +1,182 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Color; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import javax.swing.Icon; +import javax.swing.JComponent; +import javax.swing.JFormattedTextField; +import javax.swing.JLabel; +import javax.swing.SwingConstants; + +final class ColorChooserPanel extends AbstractColorChooserPanel implements PropertyChangeListener { + + private static final int MASK = 0xFF000000; + private final ColorModel model; + private final ColorPanel panel; + private final DiagramComponent slider; + private final DiagramComponent diagram; + private final JFormattedTextField text; + private final JLabel label; + + ColorChooserPanel(ColorModel model) { + this.model = model; + this.panel = new ColorPanel(this.model); + this.slider = new DiagramComponent(this.panel, false); + this.diagram = new DiagramComponent(this.panel, true); + this.text = new JFormattedTextField(); + this.label = new JLabel(null, null, SwingConstants.RIGHT); + ValueFormatter.init(6, true, this.text); + } + + @Override + public void updateChooser() { + Color color = getColorFromModel(); + this.panel.setColor(color); + this.text.setValue(Integer.valueOf(color.getRGB())); + this.slider.repaint(); + this.diagram.repaint(); + } + + @Override + protected void buildChooser() { + if (0 == getComponentCount()) { + setLayout(new GridBagLayout()); + + GridBagConstraints gbc = new GridBagConstraints(); + + gbc.gridx = 3; + gbc.gridwidth = 2; + gbc.weighty = 1.0; + gbc.anchor = GridBagConstraints.NORTH; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.insets.top = 10; + gbc.insets.right = 10; + add(this.panel, gbc); + + gbc.gridwidth = 1; + gbc.weightx = 1.0; + gbc.weighty = 0.0; + gbc.anchor = GridBagConstraints.CENTER; + gbc.insets.right = 5; + gbc.insets.bottom = 10; + add(this.label, gbc); + + gbc.gridx = 4; + gbc.weightx = 0.0; + gbc.insets.right = 10; + add(this.text, gbc); + + gbc.gridx = 2; + gbc.gridheight = 2; + gbc.anchor = GridBagConstraints.NORTH; + gbc.ipadx = this.text.getPreferredSize().height; + gbc.ipady = getPreferredSize().height; + add(this.slider, gbc); + + gbc.gridx = 1; + gbc.insets.left = 10; + gbc.ipadx = gbc.ipady; + add(this.diagram, gbc); + + this.label.setLabelFor(this.text); + this.text.addPropertyChangeListener("value", this); // NON-NLS: the property name + this.slider.setBorder(this.text.getBorder()); + this.diagram.setBorder(this.text.getBorder()); + + setInheritsPopupMenu(this, true); // CR:4966112 + } + String label = this.model.getText(this, "HexCode"); // NON-NLS: suffix + boolean visible = label != null; + this.text.setVisible(visible); + this.label.setVisible(visible); + if (visible) { + this.label.setText(label); + int mnemonic = this.model.getInteger(this, "HexCodeMnemonic"); // NON-NLS: suffix + if (mnemonic > 0) { + this.label.setDisplayedMnemonic(mnemonic); + mnemonic = this.model.getInteger(this, "HexCodeMnemonicIndex"); // NON-NLS: suffix + if (mnemonic >= 0) { + this.label.setDisplayedMnemonicIndex(mnemonic); + } + } + } + this.panel.buildPanel(); + } + + @Override + public String getDisplayName() { + return this.model.getText(this, "Name"); // NON-NLS: suffix + } + + @Override + public int getMnemonic() { + return this.model.getInteger(this, "Mnemonic"); // NON-NLS: suffix + } + + @Override + public int getDisplayedMnemonicIndex() { + return this.model.getInteger(this, "DisplayedMnemonicIndex"); // NON-NLS: suffix + } + + @Override + public Icon getSmallDisplayIcon() { + return null; + } + + @Override + public Icon getLargeDisplayIcon() { + return null; + } + + public void propertyChange(PropertyChangeEvent event) { + Object object = event.getNewValue(); + if (object instanceof Integer) { + int value = MASK & getColorFromModel().getRGB() | (Integer) object; + getColorSelectionModel().setSelectedColor(new Color(value, true)); + } + this.text.selectAll(); + } + + /** + * Allows to show context popup for all components recursively. + * + * @param component the root component of the tree + * @param value whether or not the popup menu is inherited + */ + private static void setInheritsPopupMenu(JComponent component, boolean value) { + component.setInheritsPopupMenu(value); + for (Object object : component.getComponents()) { + if (object instanceof JComponent) { + setInheritsPopupMenu((JComponent) object, value); + } + } + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java new file mode 100644 index 00000000000..955ed162663 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java @@ -0,0 +1,102 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Component; +import javax.swing.UIManager; + +class ColorModel { + + private final String prefix; + private final String[] labels; + + ColorModel(String name, String... labels) { + this.prefix = "ColorChooser." + name; // NON-NLS: default prefix + this.labels = labels; + } + + ColorModel() { + this("rgb", "Red", "Green", "Blue", "Alpha"); // NON-NLS: components + } + + void setColor(int color, float[] model) { + model[0] = normalize(color >> 16); + model[1] = normalize(color >> 8); + model[2] = normalize(color); + model[3] = normalize(color >> 24); + } + + int getColor(float[] model) { + return to8bit(model[2]) | (to8bit(model[1]) << 8) | (to8bit(model[0]) << 16) | (to8bit(model[3]) << 24); + } + + int getCount() { + return this.labels.length; + } + + int getMinimum(int index) { + return 0; + } + + int getMaximum(int index) { + return 255; + } + + float getDefault(int index) { + return 0.0f; + } + + final String getLabel(Component component, int index) { + return getText(component, this.labels[index]); + } + + private static float normalize(int value) { + return (float) (value & 0xFF) / 255.0f; + } + + private static int to8bit(float value) { + return (int) (255.0f * value); + } + + final String getText(Component component, String suffix) { + return UIManager.getString(this.prefix + suffix + "Text", component.getLocale()); // NON-NLS: default postfix + } + + final int getInteger(Component component, String suffix) { + Object value = UIManager.get(this.prefix + suffix, component.getLocale()); + if (value instanceof Integer) { + return (Integer) value; + } + if (value instanceof String) { + try { + return Integer.parseInt((String) value); + } + catch (NumberFormatException exception) { + } + } + return -1; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java new file mode 100644 index 00000000000..77a7ca55594 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java @@ -0,0 +1,94 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +final class ColorModelCMYK extends ColorModel { + + ColorModelCMYK() { + super("cmyk", "Cyan", "Magenta", "Yellow", "Black", "Alpha"); // NON-NLS: components + } + + @Override + void setColor(int color, float[] space) { + super.setColor(color, space); + space[4] = space[3]; + RGBtoCMYK(space, space); + } + + @Override + int getColor(float[] space) { + CMYKtoRGB(space, space); + space[3] = space[4]; + return super.getColor(space); + } + + /** + * Converts CMYK components of a color to a set of RGB components. + * + * @param cmyk a float array with length equal to + * the number of CMYK components + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @return a float array that contains RGB components + */ + private static float[] CMYKtoRGB(float[] cmyk, float[] rgb) { + if (rgb == null) { + rgb = new float[3]; + } + rgb[0] = 1.0f + cmyk[0] * cmyk[3] - cmyk[3] - cmyk[0]; + rgb[1] = 1.0f + cmyk[1] * cmyk[3] - cmyk[3] - cmyk[1]; + rgb[2] = 1.0f + cmyk[2] * cmyk[3] - cmyk[3] - cmyk[2]; + return rgb; + } + + /** + * Converts RGB components of a color to a set of CMYK components. + * + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @param cmyk a float array with length equal to + * the number of CMYK components + * @return a float array that contains CMYK components + */ + private static float[] RGBtoCMYK(float[] rgb, float[] cmyk) { + if (cmyk == null) { + cmyk = new float[4]; + } + float max = ColorModelHSL.max(rgb[0], rgb[1], rgb[2]); + if (max > 0.0f) { + cmyk[0] = 1.0f - rgb[0] / max; + cmyk[1] = 1.0f - rgb[1] / max; + cmyk[2] = 1.0f - rgb[2] / max; + } + else { + cmyk[0] = 0.0f; + cmyk[1] = 0.0f; + cmyk[2] = 0.0f; + } + cmyk[3] = 1.0f - max; + return cmyk; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java new file mode 100644 index 00000000000..85b0c8e5da4 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java @@ -0,0 +1,188 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +final class ColorModelHSL extends ColorModel { + + ColorModelHSL() { + super("hsl", "Hue", "Saturation", "Lightness", "Transparency"); // NON-NLS: components + } + + @Override + void setColor(int color, float[] space) { + super.setColor(color, space); + RGBtoHSL(space, space); + space[3] = 1.0f - space[3]; + } + + @Override + int getColor(float[] space) { + space[3] = 1.0f - space[3]; + HSLtoRGB(space, space); + return super.getColor(space); + } + + @Override + int getMaximum(int index) { + return (index == 0) ? 360 : 100; + } + + @Override + float getDefault(int index) { + return (index == 0) ? -1.0f : (index == 2) ? 0.5f : 1.0f; + } + + /** + * Converts HSL components of a color to a set of RGB components. + * + * @param hsl a float array with length equal to + * the number of HSL components + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @return a float array that contains RGB components + */ + private static float[] HSLtoRGB(float[] hsl, float[] rgb) { + if (rgb == null) { + rgb = new float[3]; + } + float hue = hsl[0]; + float saturation = hsl[1]; + float lightness = hsl[2]; + + if (saturation > 0.0f) { + hue = (hue < 1.0f) ? hue * 6.0f : 0.0f; + float q = lightness + saturation * ((lightness > 0.5f) ? 1.0f - lightness : lightness); + float p = 2.0f * lightness - q; + rgb[0]= normalize(q, p, (hue < 4.0f) ? (hue + 2.0f) : (hue - 4.0f)); + rgb[1]= normalize(q, p, hue); + rgb[2]= normalize(q, p, (hue < 2.0f) ? (hue + 4.0f) : (hue - 2.0f)); + } + else { + rgb[0] = lightness; + rgb[1] = lightness; + rgb[2] = lightness; + } + return rgb; + } + + /** + * Converts RGB components of a color to a set of HSL components. + * + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @param hsl a float array with length equal to + * the number of HSL components + * @return a float array that contains HSL components + */ + private static float[] RGBtoHSL(float[] rgb, float[] hsl) { + if (hsl == null) { + hsl = new float[3]; + } + float max = max(rgb[0], rgb[1], rgb[2]); + float min = min(rgb[0], rgb[1], rgb[2]); + + float summa = max + min; + float saturation = max - min; + if (saturation > 0.0f) { + saturation /= (summa > 1.0f) + ? 2.0f - summa + : summa; + } + hsl[0] = getHue(rgb[0], rgb[1], rgb[2], max, min); + hsl[1] = saturation; + hsl[2] = summa / 2.0f; + return hsl; + } + + /** + * Returns the smaller of three color components. + * + * @param red the red component of the color + * @param green the green component of the color + * @param blue the blue component of the color + * @return the smaller of {@code red}, {@code green} and {@code blue} + */ + static float min(float red, float green, float blue) { + float min = (red < green) ? red : green; + return (min < blue) ? min : blue; + } + + /** + * Returns the larger of three color components. + * + * @param red the red component of the color + * @param green the green component of the color + * @param blue the blue component of the color + * @return the larger of {@code red}, {@code green} and {@code blue} + */ + static float max(float red, float green, float blue) { + float max = (red > green) ? red : green; + return (max > blue) ? max : blue; + } + + /** + * Calculates the hue component for HSL and HSV color spaces. + * + * @param red the red component of the color + * @param green the green component of the color + * @param blue the blue component of the color + * @param max the larger of {@code red}, {@code green} and {@code blue} + * @param min the smaller of {@code red}, {@code green} and {@code blue} + * @return the hue component + */ + static float getHue(float red, float green, float blue, float max, float min) { + float hue = max - min; + if (hue > 0.0f) { + if (max == red) { + hue = (green - blue) / hue; + if (hue < 0.0f) { + hue += 6.0f; + } + } + else if (max == green) { + hue = 2.0f + (blue - red) / hue; + } + else /*max == blue*/ { + hue = 4.0f + (red - green) / hue; + } + hue /= 6.0f; + } + return hue; + } + + private static float normalize(float q, float p, float color) { + if (color < 1.0f) { + return p + (q - p) * color; + } + if (color < 3.0f) { + return q; + } + if (color < 4.0f) { + return p + (q - p) * (4.0f - color); + } + return p; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java new file mode 100644 index 00000000000..e33eef77dfe --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java @@ -0,0 +1,138 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +final class ColorModelHSV extends ColorModel { + + ColorModelHSV() { + super("hsv", "Hue", "Saturation", "Value", "Transparency"); // NON-NLS: components + } + + @Override + void setColor(int color, float[] space) { + super.setColor(color, space); + RGBtoHSV(space, space); + space[3] = 1.0f - space[3]; + } + + @Override + int getColor(float[] space) { + space[3] = 1.0f - space[3]; + HSVtoRGB(space, space); + return super.getColor(space); + } + + @Override + int getMaximum(int index) { + return (index == 0) ? 360 : 100; + } + + @Override + float getDefault(int index) { + return (index == 0) ? -1.0f : 1.0f; + } + + /** + * Converts HSV components of a color to a set of RGB components. + * + * @param hsv a float array with length equal to + * the number of HSV components + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @return a float array that contains RGB components + */ + private static float[] HSVtoRGB(float[] hsv, float[] rgb) { + if (rgb == null) { + rgb = new float[3]; + } + float hue = hsv[0]; + float saturation = hsv[1]; + float value = hsv[2]; + + rgb[0] = value; + rgb[1] = value; + rgb[2] = value; + + if (saturation > 0.0f) { + hue = (hue < 1.0f) ? hue * 6.0f : 0.0f; + int integer = (int) hue; + float f = hue - (float) integer; + switch (integer) { + case 0: + rgb[1] *= 1.0f - saturation * (1.0f - f); + rgb[2] *= 1.0f - saturation; + break; + case 1: + rgb[0] *= 1.0f - saturation * f; + rgb[2] *= 1.0f - saturation; + break; + case 2: + rgb[0] *= 1.0f - saturation; + rgb[2] *= 1.0f - saturation * (1.0f - f); + break; + case 3: + rgb[0] *= 1.0f - saturation; + rgb[1] *= 1.0f - saturation * f; + break; + case 4: + rgb[0] *= 1.0f - saturation * (1.0f - f); + rgb[1] *= 1.0f - saturation; + break; + case 5: + rgb[1] *= 1.0f - saturation; + rgb[2] *= 1.0f - saturation * f; + break; + } + } + return rgb; + } + + /** + * Converts RGB components of a color to a set of HSV components. + * + * @param rgb a float array with length of at least 3 + * that contains RGB components of a color + * @param hsv a float array with length equal to + * the number of HSV components + * @return a float array that contains HSV components + */ + private static float[] RGBtoHSV(float[] rgb, float[] hsv) { + if (hsv == null) { + hsv = new float[3]; + } + float max = ColorModelHSL.max(rgb[0], rgb[1], rgb[2]); + float min = ColorModelHSL.min(rgb[0], rgb[1], rgb[2]); + + float saturation = max - min; + if (saturation > 0.0f) { + saturation /= max; + } + hsv[0] = ColorModelHSL.getHue(rgb[0], rgb[1], rgb[2], max, min); + hsv[1] = saturation; + hsv[2] = max; + return hsv; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java new file mode 100644 index 00000000000..6e9329dbefb --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java @@ -0,0 +1,210 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Color; +import java.awt.ContainerOrderFocusTraversalPolicy; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.ButtonGroup; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.border.EmptyBorder; + +final class ColorPanel extends JPanel implements ActionListener { + + private final SlidingSpinner[] spinners = new SlidingSpinner[5]; + private final float[] values = new float[this.spinners.length]; + + private final ColorModel model; + private Color color; + private int x = 1; + private int y = 2; + private int z; + + ColorPanel(ColorModel model) { + super(new GridBagLayout()); + + GridBagConstraints gbc = new GridBagConstraints(); + gbc.fill = GridBagConstraints.HORIZONTAL; + + gbc.gridx = 1; + ButtonGroup group = new ButtonGroup(); + EmptyBorder border = null; + for (int i = 0; i < this.spinners.length; i++) { + if (i < 3) { + JRadioButton button = new JRadioButton(); + if (i == 0) { + Insets insets = button.getInsets(); + insets.left = button.getPreferredSize().width; + border = new EmptyBorder(insets); + button.setSelected(true); + gbc.insets.top = 5; + } + add(button, gbc); + group.add(button); + button.setActionCommand(Integer.toString(i)); + button.addActionListener(this); + this.spinners[i] = new SlidingSpinner(this, button); + } + else { + JLabel label = new JLabel(); + add(label, gbc); + label.setBorder(border); + label.setFocusable(false); + this.spinners[i] = new SlidingSpinner(this, label); + } + } + gbc.gridx = 2; + gbc.weightx = 1.0; + gbc.insets.top = 0; + gbc.insets.left = 5; + for (SlidingSpinner spinner : this.spinners) { + add(spinner.getSlider(), gbc); + gbc.insets.top = 5; + } + gbc.gridx = 3; + gbc.weightx = 0.0; + gbc.insets.top = 0; + for (SlidingSpinner spinner : this.spinners) { + add(spinner.getSpinner(), gbc); + gbc.insets.top = 5; + } + setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy()); + setFocusTraversalPolicyProvider(true); + setFocusable(false); + + this.model = model; + } + + public void actionPerformed(ActionEvent event) { + try { + this.z = Integer.parseInt(event.getActionCommand()); + this.y = (this.z != 2) ? 2 : 1; + this.x = (this.z != 0) ? 0 : 1; + getParent().repaint(); + } + catch (NumberFormatException exception) { + } + } + + void buildPanel() { + int count = this.model.getCount(); + this.spinners[4].setVisible(count > 4); + for (int i = 0; i < count; i++) { + Object object = this.spinners[i].getLabel(); + if (object instanceof JRadioButton) { + JRadioButton button = (JRadioButton) object; + button.setText(this.model.getLabel(this, i)); + } + else if (object instanceof JLabel) { + JLabel label = (JLabel) object; + label.setText(this.model.getLabel(this, i)); + } + this.spinners[i].setRange(this.model.getMinimum(i), this.model.getMaximum(i)); + this.spinners[i].setValue(this.values[i]); + } + } + + void colorChanged() { + this.color = new Color(getColor(0), true); + Object parent = getParent(); + if (parent instanceof ColorChooserPanel) { + ColorChooserPanel chooser = (ColorChooserPanel) parent; + chooser.getColorSelectionModel().setSelectedColor(this.color); + chooser.repaint(); + } + } + + float getValueX() { + return this.spinners[this.x].getValue(); + } + + float getValueY() { + return 1.0f - this.spinners[this.y].getValue(); + } + + float getValueZ() { + return 1.0f - this.spinners[this.z].getValue(); + } + + void setValue(float z) { + this.spinners[this.z].setValue(1.0f - z); + colorChanged(); + } + + void setValue(float x, float y) { + this.spinners[this.x].setValue(x); + this.spinners[this.y].setValue(1.0f - y); + colorChanged(); + } + + int getColor(float z) { + setDefaultValue(this.x); + setDefaultValue(this.y); + this.values[this.z] = 1.0f - z; + return getColor(3); + } + + int getColor(float x, float y) { + this.values[this.x] = x; + this.values[this.y] = 1.0f - y; + setValue(this.z); + return getColor(3); + } + + void setColor(Color color) { + if (!color.equals(this.color)) { + this.color = color; + this.model.setColor(color.getRGB(), this.values); + for (int i = 0; i < this.model.getCount(); i++) { + this.spinners[i].setValue(this.values[i]); + } + } + } + + private int getColor(int index) { + while (index < this.model.getCount()) { + setValue(index++); + } + return this.model.getColor(this.values); + } + + private void setValue(int index) { + this.values[index] = this.spinners[index].getValue(); + } + + private void setDefaultValue(int index) { + float value = this.model.getDefault(index); + this.values[index] = (value < 0.0f) + ? this.spinners[index].getValue() + : value; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java deleted file mode 100644 index 89759e247a4..00000000000 --- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java +++ /dev/null @@ -1,801 +0,0 @@ -/* - * Copyright 1998-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.colorchooser; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import javax.swing.event.*; -import javax.swing.border.*; -import java.awt.image.*; -import java.util.Locale; - -/** - * Implements the default HSB Color chooser - * - * @author Tom Santos - * @author Steve Wilson - * @author Mark Davidson - * @author Shannon Hickey - */ -class DefaultHSBChooserPanel extends AbstractColorChooserPanel implements ChangeListener, HierarchyListener { - - private transient HSBImage palette; - private transient HSBImage sliderPalette; - - private transient Image paletteImage; - private transient Image sliderPaletteImage; - - private JSlider slider; - private JSpinner hField; - private JSpinner sField; - private JSpinner bField; - - private JTextField redField; - private JTextField greenField; - private JTextField blueField; - - private boolean isAdjusting = false; // Flag which indicates that values are set internally - private Point paletteSelection = new Point(); - private JLabel paletteLabel; - private JLabel sliderPaletteLabel; - - private JRadioButton hRadio; - private JRadioButton sRadio; - private JRadioButton bRadio; - - private static final int PALETTE_DIMENSION = 200; - private static final int MAX_HUE_VALUE = 359; - private static final int MAX_SATURATION_VALUE = 100; - private static final int MAX_BRIGHTNESS_VALUE = 100; - - private int currentMode = HUE_MODE; - - private static final int HUE_MODE = 0; - private static final int SATURATION_MODE = 1; - private static final int BRIGHTNESS_MODE = 2; - - public DefaultHSBChooserPanel() { - } - - private void addPaletteListeners() { - paletteLabel.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent e ) { - float[] hsb = new float[3]; - palette.getHSBForLocation( e.getX(), e.getY(), hsb ); - updateHSB( hsb[0], hsb[1], hsb[2] ); - } - }); - - paletteLabel.addMouseMotionListener(new MouseMotionAdapter() { - public void mouseDragged( MouseEvent e ){ - int labelWidth = paletteLabel.getWidth(); - - int labelHeight = paletteLabel.getHeight(); - int x = e.getX(); - int y = e.getY(); - - if ( x >= labelWidth ) { - x = labelWidth - 1; - } - - if ( y >= labelHeight ) { - y = labelHeight - 1; - } - - if ( x < 0 ) { - x = 0; - } - - if ( y < 0 ) { - y = 0; - } - - float[] hsb = new float[3]; - palette.getHSBForLocation( x, y, hsb ); - updateHSB( hsb[0], hsb[1], hsb[2] ); - } - }); - } - - private void updatePalette( float h, float s, float b ) { - int x = 0; - int y = 0; - - switch ( currentMode ) { - case HUE_MODE: - if ( h != palette.getHue() ) { - palette.setHue( h ); - palette.nextFrame(); - } - x = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION); - y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION); - break; - case SATURATION_MODE: - if ( s != palette.getSaturation() ) { - palette.setSaturation( s ); - palette.nextFrame(); - } - x = (int)(h * PALETTE_DIMENSION); - y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION); - break; - case BRIGHTNESS_MODE: - if ( b != palette.getBrightness() ) { - palette.setBrightness( b ); - palette.nextFrame(); - } - x = (int)(h * PALETTE_DIMENSION); - y = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION); - break; - } - - paletteSelection.setLocation( x, y ); - paletteLabel.repaint(); - } - - private void updateSlider( float h, float s, float b ) { - // Update the slider palette if necessary. - // When the slider is the hue slider or the hue hasn't changed, - // the hue of the palette will not need to be updated. - if (currentMode != HUE_MODE && h != sliderPalette.getHue() ) { - sliderPalette.setHue( h ); - sliderPalette.nextFrame(); - } - - float value = 0f; - - switch ( currentMode ) { - case HUE_MODE: - value = h; - break; - case SATURATION_MODE: - value = s; - break; - case BRIGHTNESS_MODE: - value = b; - break; - } - - slider.setValue( Math.round(value * (slider.getMaximum())) ); - } - - private void updateHSBTextFields( float hue, float saturation, float brightness ) { - int h = Math.round(hue * 359); - int s = Math.round(saturation * 100); - int b = Math.round(brightness * 100); - - if (((Integer)hField.getValue()).intValue() != h) { - hField.setValue(new Integer(h)); - } - if (((Integer)sField.getValue()).intValue() != s) { - sField.setValue(new Integer(s)); - } - if (((Integer)bField.getValue()).intValue() != b) { - bField.setValue(new Integer(b)); - } - } - - /** - * Updates the values of the RGB fields to reflect the new color change - */ - private void updateRGBTextFields( Color color ) { - redField.setText(String.valueOf(color.getRed())); - greenField.setText(String.valueOf(color.getGreen())); - blueField.setText(String.valueOf(color.getBlue())); - } - - /** - * Main internal method of updating the ui controls and the color model. - */ - private void updateHSB( float h, float s, float b ) { - if ( !isAdjusting ) { - isAdjusting = true; - - updatePalette( h, s, b ); - updateSlider( h, s, b ); - updateHSBTextFields( h, s, b ); - - Color color = Color.getHSBColor(h, s, b); - updateRGBTextFields( color ); - - getColorSelectionModel().setSelectedColor( color ); - - isAdjusting = false; - } - } - - /** - * Invoked automatically when the model's state changes. - * It is also called by installChooserPanel to allow - * you to set up the initial state of your chooser. - * Override this method to update your ChooserPanel. - */ - public void updateChooser() { - if ( !isAdjusting ) { - float[] hsb = getHSBColorFromModel(); - updateHSB( hsb[0], hsb[1], hsb[2] ); - } - } - - public void installChooserPanel(JColorChooser enclosingChooser) { - super.installChooserPanel(enclosingChooser); - setInheritsPopupMenu(true); - addHierarchyListener(this); - } - - /** - * Invoked when the panel is removed from the chooser. - */ - public void uninstallChooserPanel(JColorChooser enclosingChooser) { - super.uninstallChooserPanel(enclosingChooser); - cleanupPalettesIfNecessary(); - removeAll(); - removeHierarchyListener(this); - } - - /** - * Returns an float array containing the HSB values of the selected color from - * the ColorSelectionModel - */ - private float[] getHSBColorFromModel() { - Color color = getColorFromModel(); - float[] hsb = new float[3]; - Color.RGBtoHSB( color.getRed(), color.getGreen(), color.getBlue(), hsb ); - - return hsb; - } - - /** - * Builds a new chooser panel. - */ - protected void buildChooser() { - setLayout(new BorderLayout()); - JComponent spp = buildSliderPalettePanel(); - spp.setInheritsPopupMenu(true); - add(spp, BorderLayout.BEFORE_LINE_BEGINS); - - JPanel controlHolder = new JPanel(new SmartGridLayout(1,3)); - JComponent hsbControls = buildHSBControls(); - hsbControls.setInheritsPopupMenu(true); - controlHolder.add(hsbControls); - - controlHolder.add(new JLabel(" ")); // spacer - - JComponent rgbControls = buildRGBControls(); - rgbControls.setInheritsPopupMenu(true); - controlHolder.add(rgbControls); - controlHolder.setInheritsPopupMenu(true); - - controlHolder.setBorder(new EmptyBorder( 10, 5, 10, 5)); - add( controlHolder, BorderLayout.CENTER); - } - - /** - * Creates the panel with the uneditable RGB field - */ - private JComponent buildRGBControls() { - JPanel panel = new JPanel(new SmartGridLayout(2,3)); - panel.setInheritsPopupMenu(true); - - Color color = getColorFromModel(); - redField = new JTextField( String.valueOf(color.getRed()), 3 ); - redField.setEditable(false); - redField.setHorizontalAlignment( JTextField.RIGHT ); - redField.setInheritsPopupMenu(true); - - greenField = new JTextField(String.valueOf(color.getGreen()), 3 ); - greenField.setEditable(false); - greenField.setHorizontalAlignment( JTextField.RIGHT ); - greenField.setInheritsPopupMenu(true); - - blueField = new JTextField( String.valueOf(color.getBlue()), 3 ); - blueField.setEditable(false); - blueField.setHorizontalAlignment( JTextField.RIGHT ); - blueField.setInheritsPopupMenu(true); - - Locale locale = getLocale(); - String redString = UIManager.getString("ColorChooser.hsbRedText", locale); - String greenString = UIManager.getString("ColorChooser.hsbGreenText", locale); - String blueString = UIManager.getString("ColorChooser.hsbBlueText", locale); - - panel.add( new JLabel(redString) ); - panel.add( redField ); - panel.add( new JLabel(greenString) ); - panel.add( greenField ); - panel.add( new JLabel(blueString) ); - panel.add( blueField ); - - return panel; - } - - /** - * Creates the panel with the editable HSB fields and the radio buttons. - */ - private JComponent buildHSBControls() { - - Locale locale = getLocale(); - String hueString = UIManager.getString("ColorChooser.hsbHueText", locale); - String saturationString = UIManager.getString("ColorChooser.hsbSaturationText", locale); - String brightnessString = UIManager.getString("ColorChooser.hsbBrightnessText", locale); - - RadioButtonHandler handler = new RadioButtonHandler(); - - hRadio = new JRadioButton(hueString); - hRadio.addActionListener(handler); - hRadio.setSelected(true); - hRadio.setInheritsPopupMenu(true); - - sRadio = new JRadioButton(saturationString); - sRadio.addActionListener(handler); - sRadio.setInheritsPopupMenu(true); - - bRadio = new JRadioButton(brightnessString); - bRadio.addActionListener(handler); - bRadio.setInheritsPopupMenu(true); - - ButtonGroup group = new ButtonGroup(); - group.add(hRadio); - group.add(sRadio); - group.add(bRadio); - - float[] hsb = getHSBColorFromModel(); - - hField = new JSpinner(new SpinnerNumberModel((int)(hsb[0] * 359), 0, 359, 1)); - sField = new JSpinner(new SpinnerNumberModel((int)(hsb[1] * 100), 0, 100, 1)); - bField = new JSpinner(new SpinnerNumberModel((int)(hsb[2] * 100), 0, 100, 1)); - - hField.addChangeListener(this); - sField.addChangeListener(this); - bField.addChangeListener(this); - - hField.setInheritsPopupMenu(true); - sField.setInheritsPopupMenu(true); - bField.setInheritsPopupMenu(true); - - JPanel panel = new JPanel( new SmartGridLayout(2, 3) ); - - panel.add(hRadio); - panel.add(hField); - panel.add(sRadio); - panel.add(sField); - panel.add(bRadio); - panel.add(bField); - panel.setInheritsPopupMenu(true); - - return panel; - } - - /** - * Handler for the radio button classes. - */ - private class RadioButtonHandler implements ActionListener { - public void actionPerformed(ActionEvent evt) { - Object obj = evt.getSource(); - - if (obj instanceof JRadioButton) { - JRadioButton button = (JRadioButton)obj; - if (button == hRadio) { - setMode(HUE_MODE); - } else if (button == sRadio) { - setMode(SATURATION_MODE); - } else if (button == bRadio) { - setMode(BRIGHTNESS_MODE); - } - } - } - } - - private void setMode(int mode) { - if (currentMode == mode) { - return; - } - - isAdjusting = true; // Ensure no events propagate from changing slider value. - currentMode = mode; - - float[] hsb = getHSBColorFromModel(); - - switch (currentMode) { - case HUE_MODE: - slider.setInverted(true); - slider.setMaximum(MAX_HUE_VALUE); - palette.setValues(HSBImage.HSQUARE, hsb[0], 1.0f, 1.0f); - sliderPalette.setValues(HSBImage.HSLIDER, 0f, 1.0f, 1.0f); - break; - case SATURATION_MODE: - slider.setInverted(false); - slider.setMaximum(MAX_SATURATION_VALUE); - palette.setValues(HSBImage.SSQUARE, hsb[0], hsb[1], 1.0f); - sliderPalette.setValues(HSBImage.SSLIDER, hsb[0], 1.0f, 1.0f); - break; - case BRIGHTNESS_MODE: - slider.setInverted(false); - slider.setMaximum(MAX_BRIGHTNESS_VALUE); - palette.setValues(HSBImage.BSQUARE, hsb[0], 1.0f, hsb[2]); - sliderPalette.setValues(HSBImage.BSLIDER, hsb[0], 1.0f, 1.0f); - break; - } - - isAdjusting = false; - - palette.nextFrame(); - sliderPalette.nextFrame(); - - updateChooser(); - } - - protected JComponent buildSliderPalettePanel() { - - // This slider has to have a minimum of 0. A lot of math in this file is simplified due to this. - slider = new JSlider(JSlider.VERTICAL, 0, MAX_HUE_VALUE, 0); - slider.setInverted(true); - slider.setPaintTrack(false); - slider.setPreferredSize(new Dimension(slider.getPreferredSize().width, PALETTE_DIMENSION + 15)); - slider.addChangeListener(this); - slider.setInheritsPopupMenu(true); - // We're not painting ticks, but need to ask UI classes to - // paint arrow shape anyway, if possible. - slider.putClientProperty("Slider.paintThumbArrowShape", Boolean.TRUE); - paletteLabel = createPaletteLabel(); - addPaletteListeners(); - sliderPaletteLabel = new JLabel(); - - JPanel panel = new JPanel(); - panel.add( paletteLabel ); - panel.add( slider ); - panel.add( sliderPaletteLabel ); - - initializePalettesIfNecessary(); - - return panel; - } - - private void initializePalettesIfNecessary() { - if (palette != null) { - return; - } - - float[] hsb = getHSBColorFromModel(); - - switch(currentMode){ - case HUE_MODE: - palette = new HSBImage(HSBImage.HSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, hsb[0], 1.0f, 1.0f); - sliderPalette = new HSBImage(HSBImage.HSLIDER, 16, PALETTE_DIMENSION, 0f, 1.0f, 1.0f); - break; - case SATURATION_MODE: - palette = new HSBImage(HSBImage.SSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, hsb[1], 1.0f); - sliderPalette = new HSBImage(HSBImage.SSLIDER, 16, PALETTE_DIMENSION, 1.0f, 0f, 1.0f); - break; - case BRIGHTNESS_MODE: - palette = new HSBImage(HSBImage.BSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, 1.0f, hsb[2]); - sliderPalette = new HSBImage(HSBImage.BSLIDER, 16, PALETTE_DIMENSION, 1.0f, 1.0f, 0f); - break; - } - paletteImage = Toolkit.getDefaultToolkit().createImage(palette); - sliderPaletteImage = Toolkit.getDefaultToolkit().createImage(sliderPalette); - - paletteLabel.setIcon(new ImageIcon(paletteImage)); - sliderPaletteLabel.setIcon(new ImageIcon(sliderPaletteImage)); - } - - private void cleanupPalettesIfNecessary() { - if (palette == null) { - return; - } - - palette.aborted = true; - sliderPalette.aborted = true; - - palette.nextFrame(); - sliderPalette.nextFrame(); - - palette = null; - sliderPalette = null; - - paletteImage = null; - sliderPaletteImage = null; - - paletteLabel.setIcon(null); - sliderPaletteLabel.setIcon(null); - } - - protected JLabel createPaletteLabel() { - return new JLabel() { - protected void paintComponent( Graphics g ) { - super.paintComponent( g ); - g.setColor( Color.white ); - g.drawOval( paletteSelection.x - 4, paletteSelection.y - 4, 8, 8 ); - } - }; - } - - public String getDisplayName() { - return UIManager.getString("ColorChooser.hsbNameText", getLocale()); - } - - /** - * Provides a hint to the look and feel as to the - * KeyEvent.VK constant that can be used as a mnemonic to - * access the panel. A return value <= 0 indicates there is no mnemonic. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. - *

- * This implementation looks up the value from the default - * ColorChooser.hsbMnemonic, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbMnemonic");. - * - * @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no - * mnemonic - * @see #getDisplayedMnemonicIndex - * @since 1.4 - */ - public int getMnemonic() { - return getInt("ColorChooser.hsbMnemonic", -1); - } - - /** - * Provides a hint to the look and feel as to the index of the character in - * getDisplayName that should be visually identified as the - * mnemonic. The look and feel should only use this if - * getMnemonic returns a value > 0. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. For example, - * a look and feel may wish to render each - * AbstractColorChooserPanel in a JTabbedPane, - * and further use this return value to underline a character in - * the getDisplayName. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbDisplayedMnemonicIndex, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.hsbDisplayedMnemonicIndex");. - * - * @return Character index to render mnemonic for; -1 to provide no - * visual identifier for this panel. - * @see #getMnemonic - * @since 1.4 - */ - public int getDisplayedMnemonicIndex() { - return getInt("ColorChooser.hsbDisplayedMnemonicIndex", -1); - } - - public Icon getSmallDisplayIcon() { - return null; - } - - public Icon getLargeDisplayIcon() { - return null; - } - - /** - * Class for the slider and palette images. - */ - class HSBImage extends SyntheticImage { - protected float h = .0f; - protected float s = .0f; - protected float b = .0f; - protected float[] hsb = new float[3]; - - protected boolean isDirty = true; - protected int cachedY; - protected int cachedColor; - protected int type; - - private static final int HSQUARE = 0; - private static final int SSQUARE = 1; - private static final int BSQUARE = 2; - private static final int HSLIDER = 3; - private static final int SSLIDER = 4; - private static final int BSLIDER = 5; - - protected HSBImage(int type, int width, int height, float h, float s, float b) { - super(width, height); - setValues(type, h, s, b); - } - - public void setValues(int type, float h, float s, float b) { - this.type = type; - cachedY = -1; - cachedColor = 0; - setHue( h ); - setSaturation( s ); - setBrightness( b ); - } - - public final void setHue( float hue ) { - h = hue; - } - - public final void setSaturation( float saturation ) { - s = saturation; - } - - public final void setBrightness( float brightness ) { - b = brightness; - } - - public final float getHue() { - return h; - } - - public final float getSaturation() { - return s; - } - - public final float getBrightness() { - return b; - } - - protected boolean isStatic() { - return false; - } - - public synchronized void nextFrame() { - isDirty = true; - notifyAll(); - } - - public synchronized void addConsumer(ImageConsumer ic) { - isDirty = true; - super.addConsumer(ic); - } - - private int getRGBForLocation( int x, int y ) { - if (type >= HSLIDER && y == cachedY) { - return cachedColor; - } - - getHSBForLocation( x, y, hsb ); - cachedY = y; - cachedColor = Color.HSBtoRGB( hsb[0], hsb[1], hsb[2] ); - - return cachedColor; - } - - public void getHSBForLocation( int x, int y, float[] hsbArray ) { - switch (type) { - case HSQUARE: { - float saturationStep = ((float)x) / width; - float brightnessStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s - saturationStep; - hsbArray[2] = b - brightnessStep; - break; - } - case SSQUARE: { - float brightnessStep = ((float)y) / height; - float step = 1.0f / ((float)width); - hsbArray[0] = x * step; - hsbArray[1] = s; - hsbArray[2] = 1.0f - brightnessStep; - break; - } - case BSQUARE: { - float saturationStep = ((float)y) / height; - float step = 1.0f / ((float)width); - hsbArray[0] = x * step; - hsbArray[1] = 1.0f - saturationStep; - hsbArray[2] = b; - break; - } - case HSLIDER: { - float step = 1.0f / ((float)height); - hsbArray[0] = y * step; - hsbArray[1] = s; - hsbArray[2] = b; - break; - } - case SSLIDER: { - float saturationStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s - saturationStep; - hsbArray[2] = b; - break; - } - case BSLIDER: { - float brightnessStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s; - hsbArray[2] = b - brightnessStep; - break; - } - } - } - - /** - * Overriden method from SyntheticImage - */ - protected void computeRow( int y, int[] row ) { - if ( y == 0 ) { - synchronized ( this ) { - try { - while ( !isDirty ) { - wait(); - } - } catch (InterruptedException ie) { - } - isDirty = false; - } - } - - if (aborted) { - return; - } - - for ( int i = 0; i < row.length; ++i ) { - row[i] = getRGBForLocation( i, y ); - } - } - } - - public void stateChanged(ChangeEvent e) { - if (e.getSource() == slider) { - boolean modelIsAdjusting = slider.getModel().getValueIsAdjusting(); - - if (!modelIsAdjusting && !isAdjusting) { - int sliderValue = slider.getValue(); - int sliderRange = slider.getMaximum(); - float value = (float)sliderValue / (float)sliderRange; - - float[] hsb = getHSBColorFromModel(); - - switch ( currentMode ){ - case HUE_MODE: - updateHSB(value, hsb[1], hsb[2]); - break; - case SATURATION_MODE: - updateHSB(hsb[0], value, hsb[2]); - break; - case BRIGHTNESS_MODE: - updateHSB(hsb[0], hsb[1], value); - break; - } - } - } else if (e.getSource() instanceof JSpinner) { - float hue = ((Integer)hField.getValue()).floatValue() / 359f; - float saturation = ((Integer)sField.getValue()).floatValue() / 100f; - float brightness = ((Integer)bField.getValue()).floatValue() / 100f; - - updateHSB(hue, saturation, brightness); - } - } - - public void hierarchyChanged(HierarchyEvent he) { - if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) { - if (isDisplayable()) { - initializePalettesIfNecessary(); - } else { - cleanupPalettesIfNecessary(); - } - } - } - -} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java deleted file mode 100644 index 28850dffaac..00000000000 --- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright 1998-2004 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.colorchooser; - -import javax.swing.*; -import javax.swing.event.*; -import java.awt.*; -import java.util.Locale; - -/** - * The standard RGB chooser. - *

- * Warning: - * Serialized objects of this class will not be compatible with - * future Swing releases. The current serialization support is - * appropriate for short term storage or RMI between applications running - * the same version of Swing. As of 1.4, support for long term storage - * of all JavaBeansTM - * has been added to the java.beans package. - * Please see {@link java.beans.XMLEncoder}. - * - * @author Steve Wilson - * @author Mark Davidson - * @see JColorChooser - * @see AbstractColorChooserPanel - */ -class DefaultRGBChooserPanel extends AbstractColorChooserPanel implements ChangeListener { - - protected JSlider redSlider; - protected JSlider greenSlider; - protected JSlider blueSlider; - protected JSpinner redField; - protected JSpinner blueField; - protected JSpinner greenField; - - private final int minValue = 0; - private final int maxValue = 255; - - private boolean isAdjusting = false; // indicates the fields are being set internally - - public DefaultRGBChooserPanel() { - super(); - setInheritsPopupMenu(true); - } - - /** - * Sets the values of the controls to reflect the color - */ - private void setColor( Color newColor ) { - int red = newColor.getRed(); - int blue = newColor.getBlue(); - int green = newColor.getGreen(); - - if (redSlider.getValue() != red) { - redSlider.setValue(red); - } - if (greenSlider.getValue() != green) { - greenSlider.setValue(green); - } - if (blueSlider.getValue() != blue) { - blueSlider.setValue(blue); - } - - if (((Integer)redField.getValue()).intValue() != red) - redField.setValue(new Integer(red)); - if (((Integer)greenField.getValue()).intValue() != green) - greenField.setValue(new Integer(green)); - if (((Integer)blueField.getValue()).intValue() != blue ) - blueField.setValue(new Integer(blue)); - } - - public String getDisplayName() { - return UIManager.getString("ColorChooser.rgbNameText", getLocale()); - } - - /** - * Provides a hint to the look and feel as to the - * KeyEvent.VK constant that can be used as a mnemonic to - * access the panel. A return value <= 0 indicates there is no mnemonic. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbMnemonic, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbMnemonic");. - * - * @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no - * mnemonic - * @see #getDisplayedMnemonicIndex - * @since 1.4 - */ - public int getMnemonic() { - return getInt("ColorChooser.rgbMnemonic", -1); - } - - /** - * Provides a hint to the look and feel as to the index of the character in - * getDisplayName that should be visually identified as the - * mnemonic. The look and feel should only use this if - * getMnemonic returns a value > 0. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. For example, - * a look and feel may wish to render each - * AbstractColorChooserPanel in a JTabbedPane, - * and further use this return value to underline a character in - * the getDisplayName. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbDisplayedMnemonicIndex, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbDisplayedMnemonicIndex");. - * - * @return Character index to render mnemonic for; -1 to provide no - * visual identifier for this panel. - * @see #getMnemonic - * @since 1.4 - */ - public int getDisplayedMnemonicIndex() { - return getInt("ColorChooser.rgbDisplayedMnemonicIndex", -1); - } - - public Icon getSmallDisplayIcon() { - return null; - } - - public Icon getLargeDisplayIcon() { - return null; - } - - /** - * The background color, foreground color, and font are already set to the - * defaults from the defaults table before this method is called. - */ - public void installChooserPanel(JColorChooser enclosingChooser) { - super.installChooserPanel(enclosingChooser); - } - - protected void buildChooser() { - - Locale locale = getLocale(); - String redString = UIManager.getString("ColorChooser.rgbRedText", locale); - String greenString = UIManager.getString("ColorChooser.rgbGreenText", locale); - String blueString = UIManager.getString("ColorChooser.rgbBlueText", locale); - - setLayout( new BorderLayout() ); - Color color = getColorFromModel(); - - - JPanel enclosure = new JPanel(); - enclosure.setLayout( new SmartGridLayout( 3, 3 ) ); - enclosure.setInheritsPopupMenu(true); - - // The panel that holds the sliders - - add( enclosure, BorderLayout.CENTER ); - // sliderPanel.setBorder(new LineBorder(Color.black)); - - // The row for the red value - JLabel l = new JLabel(redString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbRedMnemonic", -1)); - enclosure.add(l); - redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getRed()); - redSlider.setMajorTickSpacing( 85 ); - redSlider.setMinorTickSpacing( 17 ); - redSlider.setPaintTicks( true ); - redSlider.setPaintLabels( true ); - redSlider.setInheritsPopupMenu(true); - enclosure.add( redSlider ); - redField = new JSpinner( - new SpinnerNumberModel(color.getRed(), minValue, maxValue, 1)); - l.setLabelFor(redSlider); - redField.setInheritsPopupMenu(true); - JPanel redFieldHolder = new JPanel(new CenterLayout()); - redFieldHolder.setInheritsPopupMenu(true); - redField.addChangeListener(this); - redFieldHolder.add(redField); - enclosure.add(redFieldHolder); - - - // The row for the green value - l = new JLabel(greenString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbGreenMnemonic", -1)); - enclosure.add(l); - greenSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getGreen()); - greenSlider.setMajorTickSpacing( 85 ); - greenSlider.setMinorTickSpacing( 17 ); - greenSlider.setPaintTicks( true ); - greenSlider.setPaintLabels( true ); - greenSlider.setInheritsPopupMenu(true); - enclosure.add(greenSlider); - greenField = new JSpinner( - new SpinnerNumberModel(color.getGreen(), minValue, maxValue, 1)); - l.setLabelFor(greenSlider); - greenField.setInheritsPopupMenu(true); - JPanel greenFieldHolder = new JPanel(new CenterLayout()); - greenFieldHolder.add(greenField); - greenFieldHolder.setInheritsPopupMenu(true); - greenField.addChangeListener(this); - enclosure.add(greenFieldHolder); - - // The slider for the blue value - l = new JLabel(blueString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbBlueMnemonic", -1)); - enclosure.add(l); - blueSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getBlue()); - blueSlider.setMajorTickSpacing( 85 ); - blueSlider.setMinorTickSpacing( 17 ); - blueSlider.setPaintTicks( true ); - blueSlider.setPaintLabels( true ); - blueSlider.setInheritsPopupMenu(true); - enclosure.add(blueSlider); - blueField = new JSpinner( - new SpinnerNumberModel(color.getBlue(), minValue, maxValue, 1)); - l.setLabelFor(blueSlider); - blueField.setInheritsPopupMenu(true); - JPanel blueFieldHolder = new JPanel(new CenterLayout()); - blueFieldHolder.add(blueField); - blueField.addChangeListener(this); - blueFieldHolder.setInheritsPopupMenu(true); - enclosure.add(blueFieldHolder); - - redSlider.addChangeListener( this ); - greenSlider.addChangeListener( this ); - blueSlider.addChangeListener( this ); - - redSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - greenSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - blueSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - } - - public void uninstallChooserPanel(JColorChooser enclosingChooser) { - super.uninstallChooserPanel(enclosingChooser); - removeAll(); - } - - public void updateChooser() { - if (!isAdjusting) { - isAdjusting = true; - - setColor(getColorFromModel()); - - isAdjusting = false; - } - } - - public void stateChanged( ChangeEvent e ) { - if ( e.getSource() instanceof JSlider && !isAdjusting) { - - int red = redSlider.getValue(); - int green = greenSlider.getValue(); - int blue = blueSlider.getValue() ; - Color color = new Color (red, green, blue); - - getColorSelectionModel().setSelectedColor(color); - } else if (e.getSource() instanceof JSpinner && !isAdjusting) { - - int red = ((Integer)redField.getValue()).intValue(); - int green = ((Integer)greenField.getValue()).intValue(); - int blue = ((Integer)blueField.getValue()).intValue(); - Color color = new Color (red, green, blue); - - getColorSelectionModel().setSelectedColor(color); - } - } - -} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java b/jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java new file mode 100644 index 00000000000..04905589e99 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java @@ -0,0 +1,160 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.image.BufferedImage; +import javax.swing.JComponent; + +final class DiagramComponent extends JComponent implements MouseListener, MouseMotionListener { + + private final ColorPanel panel; + private final boolean diagram; + + private final Insets insets = new Insets(0, 0, 0, 0); + + private int width; + private int height; + + private int[] array; + private BufferedImage image; + + DiagramComponent(ColorPanel panel, boolean diagram) { + this.panel = panel; + this.diagram = diagram; + addMouseListener(this); + addMouseMotionListener(this); + } + + @Override + protected void paintComponent(Graphics g) { + getInsets(this.insets); + this.width = getWidth() - this.insets.left - this.insets.right; + this.height = getHeight() - this.insets.top - this.insets.bottom; + + boolean update = (this.image == null) + || (this.width != this.image.getWidth()) + || (this.height != this.image.getHeight()); + if (update) { + int size = this.width * this.height; + if ((this.array == null) || (this.array.length < size)) { + this.array = new int[size]; + } + this.image = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB); + } + { + float dx = 1.0f / (float) (this.width - 1); + float dy = 1.0f / (float) (this.height - 1); + + int offset = 0; + float y = 0.0f; + for (int h = 0; h < this.height; h++, y += dy) { + if (this.diagram) { + float x = 0.0f; + for (int w = 0; w < this.width; w++, x += dx, offset++) { + this.array[offset] = this.panel.getColor(x, y); + } + } + else { + int color = this.panel.getColor(y); + for (int w = 0; w < this.width; w++, offset++) { + this.array[offset] = color; + } + } + } + } + this.image.setRGB(0, 0, this.width, this.height, this.array, 0, this.width); + g.drawImage(this.image, this.insets.left, this.insets.top, this.width, this.height, this); + if (isEnabled()) { + this.width--; + this.height--; + g.setXORMode(Color.WHITE); + g.setColor(Color.BLACK); + if (this.diagram) { + int x = getValue(this.panel.getValueX(), this.insets.left, this.width); + int y = getValue(this.panel.getValueY(), this.insets.top, this.height); + g.drawLine(x - 8, y, x + 8, y); + g.drawLine(x, y - 8, x, y + 8); + } + else { + int z = getValue(this.panel.getValueZ(), this.insets.top, this.height); + g.drawLine(this.insets.left, z, this.insets.left + this.width, z); + } + g.setPaintMode(); + } + } + + public void mousePressed(MouseEvent event) { + mouseDragged(event); + } + + public void mouseReleased(MouseEvent event) { + } + + public void mouseClicked(MouseEvent event) { + } + + public void mouseEntered(MouseEvent event) { + } + + public void mouseExited(MouseEvent event) { + } + + public void mouseMoved(MouseEvent event) { + } + + public void mouseDragged(MouseEvent event) { + if (isEnabled()) { + float y = getValue(event.getY(), this.insets.top, this.height); + if (this.diagram) { + float x = getValue(event.getX(), this.insets.left, this.width); + this.panel.setValue(x, y); + } + else { + this.panel.setValue(y); + } + } + } + + private static int getValue(float value, int min, int max) { + return min + (int) (value * (float) (max)); + } + + private static float getValue(int value, int min, int max) { + if (min < value) { + value -= min; + return (value < max) + ? (float) value / (float) max + : 1.0f; + } + return 0.0f; + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java b/jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java new file mode 100644 index 00000000000..99e9bf29858 --- /dev/null +++ b/jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java @@ -0,0 +1,118 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import javax.swing.JComponent; +import javax.swing.JSlider; +import javax.swing.JSpinner; +import javax.swing.JSpinner.DefaultEditor; +import javax.swing.SpinnerNumberModel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +final class SlidingSpinner implements ChangeListener { + + private final ColorPanel panel; + private final JComponent label; + private final SpinnerNumberModel model = new SpinnerNumberModel(); + private final JSlider slider = new JSlider(); + private final JSpinner spinner = new JSpinner(this.model); + private float value; + private boolean internal; + + SlidingSpinner(ColorPanel panel, JComponent label) { + this.panel = panel; + this.label = label; + this.slider.addChangeListener(this); + this.spinner.addChangeListener(this); + DefaultEditor editor = (DefaultEditor) this.spinner.getEditor(); + ValueFormatter.init(3, false, editor.getTextField()); + editor.setFocusable(false); + this.spinner.setFocusable(false); + } + + JComponent getLabel() { + return this.label; + } + + JSlider getSlider() { + return this.slider; + } + + JSpinner getSpinner() { + return this.spinner; + } + + float getValue() { + return this.value; + } + + void setValue(float value) { + int min = this.slider.getMinimum(); + int max = this.slider.getMaximum(); + this.internal = true; + this.slider.setValue(min + (int) (value * (float) (max - min))); + this.spinner.setValue(Integer.valueOf(this.slider.getValue())); + this.internal = false; + this.value = value; + } + + void setRange(int min, int max) { + this.internal = true; + this.slider.setMinimum(min); + this.slider.setMaximum(max); + this.model.setMinimum(Integer.valueOf(min)); + this.model.setMaximum(Integer.valueOf(max)); + this.internal = false; + } + + void setVisible(boolean visible) { + this.label.setVisible(visible); + this.slider.setVisible(visible); + this.spinner.setVisible(visible); + } + + public void stateChanged(ChangeEvent event) { + if (!this.internal) { + if (this.spinner == event.getSource()) { + Object value = this.spinner.getValue(); + if (value instanceof Integer) { + this.internal = true; + this.slider.setValue((Integer) value); + this.internal = false; + } + } + int value = this.slider.getValue(); + this.internal = true; + this.spinner.setValue(Integer.valueOf(value)); + this.internal = false; + int min = this.slider.getMinimum(); + int max = this.slider.getMaximum(); + this.value = (float) (value - min) / (float) (max - min); + this.panel.colorChanged(); + } + } +} diff --git a/jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java b/jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java deleted file mode 100644 index cec69e9c39d..00000000000 --- a/jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved. - * 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 - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * 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. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.colorchooser; - -import java.awt.*; -import java.awt.image.*; - -/** A helper class to make computing synthetic images a little easier. - * All you need to do is define a subclass that overrides computeRow - * to compute a row of the image. It is passed the y coordinate of the - * row and an array into which to put the pixels in - * - * standard ARGB format. - *

Normal usage looks something like this: - *

 Image i = createImage(new SyntheticImage(200, 100) {
- *       protected void computeRow(int y, int[] row) {
- *         for(int i = width; --i>=0; ) {
- *             int grey = i*255/(width-1);
- *             row[i] = (255<<24)|(grey<<16)|(grey<<8)|grey;
- *         }
- *       }
- *   }
- *  
This creates a image 200 pixels wide and 100 pixels high - * that is a horizontal grey ramp, going from black on the left to - * white on the right. - *

- * If the image is to be a movie, override isStatic to return false, - * y cycling back to 0 is computeRow's signal that the next - * frame has started. It is acceptable (expected?) for computeRow(0,r) - * to pause until the appropriate time to start the next frame. - * - * @author James Gosling - */ -abstract class SyntheticImage implements ImageProducer { - private SyntheticImageGenerator root; - protected int width=10, height=100; - static final ColorModel cm = ColorModel.getRGBdefault(); - public static final int pixMask = 0xFF; - private Thread runner; - protected SyntheticImage() { } - protected SyntheticImage(int w, int h) { width = w; height = h; } - protected void computeRow(int y, int[] row) { - int p = 255-255*y/(height-1); - p = (pixMask<<24)|(p<<16)|(p<<8)|p; - for (int i = row.length; --i>=0; ) row[i] = p; - } - public synchronized void addConsumer(ImageConsumer ic){ - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.ic == ic) return; - root = new SyntheticImageGenerator(ic, root, this); - } - public synchronized boolean isConsumer(ImageConsumer ic){ - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.ic == ic) return true; - return false; - } - public synchronized void removeConsumer(ImageConsumer ic) { - SyntheticImageGenerator prev = null; - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) { - if (ics.ic == ic) { - ics.useful = false; - if (prev!=null) prev.next = ics.next; - else root = ics.next; - return; - } - prev = ics; - } - } - public synchronized void startProduction(ImageConsumer ic) { - addConsumer(ic); - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.useful && !ics.isAlive()) - ics.start(); - } - protected boolean isStatic() { return true; } - public void nextFrame(int param) {}//Override if !isStatic - public void requestTopDownLeftRightResend(ImageConsumer ic){} - - protected volatile boolean aborted = false; -} - -class SyntheticImageGenerator extends Thread { - ImageConsumer ic; - boolean useful; - SyntheticImageGenerator next; - SyntheticImage parent; - SyntheticImageGenerator(ImageConsumer ic, SyntheticImageGenerator next, - SyntheticImage parent) { - super("SyntheticImageGenerator"); - this.ic = ic; - this.next = next; - this.parent = parent; - useful = true; - setDaemon(true); - } - public void run() { - ImageConsumer ic = this.ic; - int w = parent.width; - int h = parent.height; - int hints = ic.SINGLEPASS|ic.COMPLETESCANLINES|ic.TOPDOWNLEFTRIGHT; - if (parent.isStatic()) - hints |= ic.SINGLEFRAME; - ic.setHints(hints); - ic.setDimensions(w, h); - ic.setProperties(null); - ic.setColorModel(parent.cm); - - if (useful) { - int[] row=new int[w]; - doPrivileged( new Runnable() { - public void run() { - Thread.currentThread().setPriority(Thread.MIN_PRIORITY); - } - }); - - do { - for (int y = 0; y>= 4; + } + return new String(array).toUpperCase(ENGLISH); + } + throw new ParseException("illegal object", 0); + } + + @Override + protected DocumentFilter getDocumentFilter() { + return this.filter; + } + + public void focusGained(FocusEvent event) { + Object source = event.getSource(); + if (source instanceof JFormattedTextField) { + this.text = (JFormattedTextField) source; + SwingUtilities.invokeLater(this); + } + } + + public void focusLost(FocusEvent event) { + } + + public void run() { + if (this.text != null) { + this.text.selectAll(); + } + } + + private boolean isValid(int length) { + return (0 <= length) && (length <= this.length); + } + + private boolean isValid(String text) { + int length = text.length(); + for (int i = 0; i < length; i++) { + char ch = text.charAt(i); + if (Character.digit(ch, this.radix) < 0) { + return false; + } + } + return true; + } +} diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java index fd63e7fcbb6..09f9372b9c3 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java @@ -299,8 +299,10 @@ public class BasicColorChooserUI extends ColorChooserUI tabbedPane.addTab(name, centerWrapper); if (mnemonic > 0) { tabbedPane.setMnemonicAt(i, mnemonic); - tabbedPane.setDisplayedMnemonicIndexAt( - i, newPanels[i].getDisplayedMnemonicIndex()); + int index = newPanels[i].getDisplayedMnemonicIndex(); + if (index >= 0) { + tabbedPane.setDisplayedMnemonicIndexAt(i, index); + } } } } diff --git a/jdk/test/javax/swing/JColorChooser/Test6524757.java b/jdk/test/javax/swing/JColorChooser/Test6524757.java index 0389efc70ad..dc7fa06ce59 100644 --- a/jdk/test/javax/swing/JColorChooser/Test6524757.java +++ b/jdk/test/javax/swing/JColorChooser/Test6524757.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,14 +34,13 @@ import java.awt.Dimension; import java.util.ArrayList; import java.util.List; import java.util.Locale; -import javax.swing.JButton; +import javax.swing.AbstractButton; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; -import javax.swing.JRadioButton; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.colorchooser.AbstractColorChooserPanel; @@ -59,31 +58,41 @@ public class Test6524757 { "ColorChooser.swatchesNameText", // NON-NLS: string key from DefaultSwatchChooserPanel "ColorChooser.swatchesMnemonic", // NON-NLS: string key from DefaultSwatchChooserPanel:int - "ColorChooser.swatchesDisplayedMnemonicIndex", // NON-NLS: int key from DefaultSwatchChooserPanel "ColorChooser.swatchesSwatchSize", // NON-NLS: dimension key from DefaultSwatchChooserPanel "ColorChooser.swatchesRecentText", // NON-NLS: string key from DefaultSwatchChooserPanel "ColorChooser.swatchesRecentSwatchSize", // NON-NLS: dimension key from DefaultSwatchChooserPanel //NotAvail: "ColorChooser.swatchesDefaultRecentColor", // NON-NLS: color key from DefaultSwatchChooserPanel - "ColorChooser.hsbNameText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbMnemonic", // NON-NLS: int key from DefaultHSBChooserPanel - "ColorChooser.hsbDisplayedMnemonicIndex", // NON-NLS: int key from DefaultHSBChooserPanel - "ColorChooser.hsbHueText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbSaturationText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbBrightnessText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbRedText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbGreenText", // NON-NLS: string key from DefaultHSBChooserPanel - "ColorChooser.hsbBlueText", // NON-NLS: string key from DefaultHSBChooserPanel + "ColorChooser.hsvNameText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hsvMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + "ColorChooser.hsvHueText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hsvSaturationText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hsvValueText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hsvTransparencyText", // NON-NLS: string key from HSV ColorChooserPanel - "ColorChooser.rgbNameText", // NON-NLS: string key from DefaultRGBChooserPanel - "ColorChooser.rgbMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel - "ColorChooser.rgbDisplayedMnemonicIndex", // NON-NLS: int key from DefaultRGBChooserPanel - "ColorChooser.rgbRedText", // NON-NLS: string key from DefaultRGBChooserPanel - "ColorChooser.rgbGreenText", // NON-NLS: string key from DefaultRGBChooserPanel - "ColorChooser.rgbBlueText", // NON-NLS: string key from DefaultRGBChooserPanel - "ColorChooser.rgbRedMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel - "ColorChooser.rgbGreenMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel - "ColorChooser.rgbBlueMnemonic", // NON-NLS: int key from DefaultRGBChooserPanel + "ColorChooser.hslNameText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hslMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + "ColorChooser.hslHueText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hslSaturationText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hslLightnessText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.hslTransparencyText", // NON-NLS: string key from HSV ColorChooserPanel + + "ColorChooser.rgbNameText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + "ColorChooser.rgbRedText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbGreenText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbBlueText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbAlphaText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbHexCodeText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.rgbHexCodeMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + + "ColorChooser.cmykNameText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykMnemonic", // NON-NLS: int key from HSV ColorChooserPanel + "ColorChooser.cmykCyanText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykMagentaText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykYellowText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykBlackText", // NON-NLS: string key from HSV ColorChooserPanel + "ColorChooser.cmykAlphaText", // NON-NLS: string key from HSV ColorChooserPanel }; private static final Object[] KOREAN = convert(Locale.KOREAN, KEYS); private static final Object[] FRENCH = convert(Locale.FRENCH, KEYS); @@ -91,19 +100,15 @@ public class Test6524757 { public static void main(String[] args) { // it affects Swing because it is not initialized Locale.setDefault(Locale.KOREAN); - Object[] korean = create(); + validate(KOREAN, create()); // it does not affect Swing because it is initialized Locale.setDefault(Locale.CANADA); - Object[] canada = create(); + validate(KOREAN, create()); // it definitely should affect Swing JComponent.setDefaultLocale(Locale.FRENCH); - Object[] french = create(); - - validate(KOREAN, korean); - validate(KOREAN, canada); - validate(FRENCH, french); + validate(FRENCH, create()); } private static void validate(Object[] expected, Object[] actual) { @@ -153,10 +158,47 @@ public class Test6524757 { // process all values List list = new ArrayList(KEYS.length); - addMain(list, dialog); - addSwatch(list, chooser); - addHSB(list, chooser); - addRGB(list, chooser); + + Component component = getC(getC(dialog.getLayeredPane(), 0), 1); + AbstractButton ok = (AbstractButton) getC(component, 0); + AbstractButton cancel = (AbstractButton) getC(component, 1); + AbstractButton reset = (AbstractButton) getC(component, 2); + list.add(ok.getText()); + list.add(cancel.getText()); + list.add(reset.getText()); + list.add(Integer.valueOf(reset.getMnemonic())); + + for (int i = 0; i < 5; i++) { + AbstractColorChooserPanel panel = (AbstractColorChooserPanel) getC(getC(getC(chooser, 0), i), 0); + list.add(panel.getDisplayName()); + list.add(Integer.valueOf(panel.getMnemonic())); + if (i == 0) { + JLabel label = (JLabel) getC(getC(panel, 0), 1); + JPanel upper = (JPanel) getC(getC(getC(panel, 0), 0), 0); + JPanel lower = (JPanel) getC(getC(getC(panel, 0), 2), 0); + addSize(list, upper, 1, 1, 31, 9); + list.add(label.getText()); + addSize(list, lower, 1, 1, 5, 7); + } + else { + Component container = getC(panel, 0); + for (int j = 0; j < 3; j++) { + AbstractButton button = (AbstractButton) getC(container, j); + list.add(button.getText()); + } + JLabel label = (JLabel) getC(container, 3); + list.add(label.getText()); + if (i == 4) { + label = (JLabel) getC(container, 4); + list.add(label.getText()); + } + if (i == 3) { + label = (JLabel) getC(panel, 1); + list.add(label.getText()); + list.add(Integer.valueOf(label.getDisplayedMnemonic())); + } + } + } // close dialog dialog.setVisible(false); @@ -169,56 +211,6 @@ public class Test6524757 { return list.toArray(); } - private static void addMain(List list, JDialog dialog) { - Component component = getC(getC(dialog.getLayeredPane(), 0), 1); - JButton ok = (JButton) getC(component, 0); - JButton cancel = (JButton) getC(component, 1); - JButton reset = (JButton) getC(component, 2); - list.add(ok.getText()); - list.add(cancel.getText()); - list.add(reset.getText()); - list.add(Integer.valueOf(reset.getMnemonic())); - } - - private static void addSwatch(List list, JColorChooser chooser) { - Component component = addPanel(list, chooser, 0); - JLabel label = (JLabel) getC(getC(component, 0), 1); - JPanel upper = (JPanel) getC(getC(getC(component, 0), 0), 0); - JPanel lower = (JPanel) getC(getC(getC(component, 0), 2), 0); - addSize(list, upper, 1, 1, 31, 9); - list.add(label.getText()); - addSize(list, lower, 1, 1, 5, 7); - } - - private static void addHSB(List list, JColorChooser chooser) { - Component component = addPanel(list, chooser, 1); - JRadioButton h = (JRadioButton) getC(getC(getC(component, 1), 0), 0); - JRadioButton s = (JRadioButton) getC(getC(getC(component, 1), 0), 2); - JRadioButton b = (JRadioButton) getC(getC(getC(component, 1), 0), 4); - list.add(h.getText()); - list.add(s.getText()); - list.add(b.getText()); - JLabel red = (JLabel) getC(getC(getC(component, 1), 2), 0); - JLabel green = (JLabel) getC(getC(getC(component, 1), 2), 2); - JLabel blue = (JLabel) getC(getC(getC(component, 1), 2), 4); - list.add(red.getText()); - list.add(green.getText()); - list.add(blue.getText()); - } - - private static void addRGB(List list, JColorChooser chooser) { - Component component = addPanel(list, chooser, 2); - JLabel red = (JLabel) getC(getC(component, 0), 0); - JLabel green = (JLabel) getC(getC(component, 0), 3); - JLabel blue = (JLabel) getC(getC(component, 0), 6); - list.add(red.getText()); - list.add(green.getText()); - list.add(blue.getText()); - list.add(Integer.valueOf(red.getDisplayedMnemonic())); - list.add(Integer.valueOf(green.getDisplayedMnemonic())); - list.add(Integer.valueOf(blue.getDisplayedMnemonic())); - } - private static void addSize(List list, Component component, int x, int y, int w, int h) { Dimension size = component.getPreferredSize(); int width = (size.width + 1) / w - x; @@ -226,14 +218,6 @@ public class Test6524757 { list.add(new Dimension(width, height)); } - private static Component addPanel(List list, JColorChooser chooser, int index) { - AbstractColorChooserPanel panel = (AbstractColorChooserPanel) getC(getC(getC(chooser, 0), index), 0); - list.add(panel.getDisplayName()); - list.add(Integer.valueOf(panel.getMnemonic())); - list.add(Integer.valueOf(panel.getDisplayedMnemonicIndex())); - return panel; - } - private static Component getC(Component component, int index) { Container container = (Container) component; return container.getComponent(index); diff --git a/jdk/test/javax/swing/JColorChooser/Test6559154.java b/jdk/test/javax/swing/JColorChooser/Test6559154.java new file mode 100644 index 00000000000..e84d90539d4 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test6559154.java @@ -0,0 +1,75 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6559154 + * @summary Tests EDT hanging + * @author Sergey Malenkov + */ + +import java.awt.Component; +import java.awt.Container; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.SwingUtilities; +import javax.swing.Timer; + +public class Test6559154 implements ActionListener, Runnable { + + private JDialog dialog; + + public void actionPerformed(ActionEvent event) { + if (this.dialog != null) { + this.dialog.dispose(); + } + } + + public void run() { + Timer timer = new Timer(1000, this); + timer.setRepeats(false); + timer.start(); + + JColorChooser chooser = new JColorChooser(); + setEnabledRecursive(chooser, false); + + this.dialog = new JDialog(); + this.dialog.add(chooser); + this.dialog.setVisible(true); + } + + private static void setEnabledRecursive(Container container, boolean enabled) { + for (Component component : container.getComponents()) { + component.setEnabled(enabled); + if (component instanceof Container) { + setEnabledRecursive((Container) component, enabled); + } + } + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Test6559154()); + } +} From 22e8b43f705fdb4847f9e9421f96d676826db666 Mon Sep 17 00:00:00 2001 From: Chris Hegarty Date: Sat, 19 Jul 2008 10:27:34 +0100 Subject: [PATCH 040/325] 6726164: jdk\src\windows\native\java\net\NetworkInterface.h(172) : error C2365: 'IpPrefixOriginOther' : redef Change the NetworkInterface header that allows it to compile on the current compiler/SDK version as well as the SDK bundled with Visual Studio 2008. Reviewed-by: ohair, alanb --- jdk/src/windows/native/java/net/NetworkInterface.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/jdk/src/windows/native/java/net/NetworkInterface.h b/jdk/src/windows/native/java/net/NetworkInterface.h index 74c9c13c25c..c75892c5303 100644 --- a/jdk/src/windows/native/java/net/NetworkInterface.h +++ b/jdk/src/windows/native/java/net/NetworkInterface.h @@ -26,6 +26,7 @@ #ifndef NETWORK_INTERFACE_H #define NETWORK_INTERFACE_H +#include #include "net_util.h" /* @@ -86,6 +87,12 @@ extern jfieldID ni_ibaddressID; /* InterfaceAddress.address */ extern jfieldID ni_ibbroadcastID; /* InterfaceAddress.broadcast */ extern jfieldID ni_ibmaskID; /* InterfaceAddress.maskLength */ +/* We have included iphlpapi.h which includes iptypes.h which has the definition + * for MAX_ADAPTER_DESCRIPTION_LENGTH (along with the other definitions in this + * ifndef block). Therefore if MAX_ADAPTER_DESCRIPTION_LENGTH is defined we can + * be sure that the other definitions are also defined */ +#ifndef MAX_ADAPTER_DESCRIPTION_LENGTH + /* * Following includes come from iptypes.h */ @@ -372,6 +379,7 @@ typedef struct { UINT EnableProxy; UINT EnableDns; } FIXED_INFO, *PFIXED_INFO; +#endif /*!MAX_ADAPTER_DESCRIPTION_LENGTH*/ #ifndef IP_INTERFACE_NAME_INFO_DEFINED #define IP_INTERFACE_NAME_INFO_DEFINED From 7f530b42c8dc1ad26f21e4b1a7cff18fd8f21158 Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Mon, 21 Jul 2008 10:21:42 -0400 Subject: [PATCH 041/325] 6668281: NullPointerException in DefaultTableCellHeaderRenderer.getColumnSortOrder() Reviewed-by: alexp --- .../com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java index e2217e0f35a..0f2b39d8937 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java @@ -124,7 +124,7 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI { setIcon(null); sortIcon = null; SortOrder sortOrder = - getColumnSortOrder(header.getTable(), column); + getColumnSortOrder(table, column); if (sortOrder != null) { switch (sortOrder) { case ASCENDING: From a44852b8fe9e4cfe0ce204d61870c382998e18d8 Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Mon, 21 Jul 2008 19:58:43 +0400 Subject: [PATCH 042/325] 6607130: REGRESSION: JComboBox cell editor isn't hidden if the same value is selected with keyboard JComboBox cell editor now hides if the same value is selected with keyboard Reviewed-by: peterz, alexp --- .../swing/plaf/basic/BasicComboBoxUI.java | 12 +- .../swing/JComboBox/6607130/bug6607130.java | 149 ++++++++++++++++++ 2 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 jdk/test/javax/swing/JComboBox/6607130/bug6607130.java diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java index f073eeda816..c49387fd91f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java @@ -1509,15 +1509,21 @@ public class BasicComboBoxUI extends ComboBoxUI { || ui.isTableCellEditor) { Object listItem = ui.popup.getList().getSelectedValue(); if (listItem != null) { - comboBox.getModel().setSelectedItem(listItem); - // Ensure that JComboBox.actionPerformed() - // doesn't set editor value as selected item + // Use the selected value from popup + // to set the selected item in combo box, + // but ensure before that JComboBox.actionPerformed() + // won't use editor's value to set the selected item comboBox.getEditor().setItem(listItem); + comboBox.setSelectedItem(listItem); } } comboBox.setPopupVisible(false); } else { + // Hide combo box if it is a table cell editor + if (ui.isTableCellEditor && !comboBox.isEditable()) { + comboBox.setSelectedItem(comboBox.getSelectedItem()); + } // Call the default button binding. // This is a pretty messy way of passing an event through // to the root pane. diff --git a/jdk/test/javax/swing/JComboBox/6607130/bug6607130.java b/jdk/test/javax/swing/JComboBox/6607130/bug6607130.java new file mode 100644 index 00000000000..5d465c9d79d --- /dev/null +++ b/jdk/test/javax/swing/JComboBox/6607130/bug6607130.java @@ -0,0 +1,149 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6607130 + * @summary Checks that JComboBox cell editor is hidden if the same + * item is selected with keyboard. + * Also checks that JComboBox cell editor is hidden if F2 and then + * ENTER were pressed. + * @author Mikhail Lapshin + */ + +import sun.awt.SunToolkit; + +import javax.swing.*; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.KeyEvent; + +public class bug6607130 { + private JFrame frame; + private JComboBox cb; + private Robot robot; + + public static void main(String[] args) throws Exception { + final bug6607130 test = new bug6607130(); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + test.setupUI(); + } + }); + test.test(); + } finally { + if (test.frame != null) { + test.frame.dispose(); + } + } + } + + public bug6607130() throws AWTException { + robot = new Robot(); + } + + private void setupUI() { + frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + DefaultTableModel model = new DefaultTableModel(1, 1); + JTable table = new JTable(model); + + cb = new JComboBox(new String[]{"one", "two", "three"}); + table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(cb)); + frame.add(table); + + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private void test() throws Exception { + realSync(); + test1(); + realSync(); + checkResult("First test"); + test2(); + realSync(); + checkResult("Second test"); + } + + private void test1() throws Exception { + // Select 'one' + hitKey(KeyEvent.VK_TAB); + realSync(); + hitKey(KeyEvent.VK_F2); + realSync(); + hitKey(KeyEvent.VK_DOWN); + realSync(); + hitKey(KeyEvent.VK_DOWN); + realSync(); + hitKey(KeyEvent.VK_ENTER); + realSync(); + + // Select 'one' again + hitKey(KeyEvent.VK_F2); + realSync(); + hitKey(KeyEvent.VK_DOWN); + realSync(); + hitKey(KeyEvent.VK_ENTER); + realSync(); + } + + private void test2() throws Exception { + // Press F2 and then press ENTER + // Editor should be shown and then closed + hitKey(KeyEvent.VK_F2); + realSync(); + hitKey(KeyEvent.VK_ENTER); + realSync(); + } + + private void checkResult(String testName) { + if (!cb.isShowing()) { + System.out.println(testName + " passed"); + } else { + System.out.println(testName + " failed"); + throw new RuntimeException("JComboBox is showing " + + "after item selection."); + } + } + + private static void realSync() { + ((SunToolkit) (Toolkit.getDefaultToolkit())).realSync(); + } + + public void hitKey(int keycode) { + robot.keyPress(keycode); + robot.keyRelease(keycode); + delay(); + } + + private void delay() { + try { + Thread.sleep(1000); + } catch(InterruptedException ie) { + ie.printStackTrace(); + } + } +} From fcbf2d124562828671e68f0d2275334bda16d2a7 Mon Sep 17 00:00:00 2001 From: Chuck Rasbold Date: Mon, 21 Jul 2008 13:37:05 -0700 Subject: [PATCH 043/325] 6726504: handle do_ifxxx calls in parser more uniformly Make do_ifnull() handling similar to do_if() Reviewed-by: jrose, kvn --- hotspot/src/share/vm/opto/parse.hpp | 2 +- hotspot/src/share/vm/opto/parse2.cpp | 36 +++++++++++----------------- 2 files changed, 15 insertions(+), 23 deletions(-) diff --git a/hotspot/src/share/vm/opto/parse.hpp b/hotspot/src/share/vm/opto/parse.hpp index 10b3fe2ca14..bf344cb6f5f 100644 --- a/hotspot/src/share/vm/opto/parse.hpp +++ b/hotspot/src/share/vm/opto/parse.hpp @@ -479,7 +479,7 @@ class Parse : public GraphKit { float branch_prediction(float &cnt, BoolTest::mask btest, int target_bci); bool seems_never_taken(float prob); - void do_ifnull(BoolTest::mask btest); + void do_ifnull(BoolTest::mask btest, Node* c); void do_if(BoolTest::mask btest, Node* c); void repush_if_args(); void adjust_map_after_if(BoolTest::mask btest, Node* c, float prob, diff --git a/hotspot/src/share/vm/opto/parse2.cpp b/hotspot/src/share/vm/opto/parse2.cpp index e244d6a098e..a71c7726a2b 100644 --- a/hotspot/src/share/vm/opto/parse2.cpp +++ b/hotspot/src/share/vm/opto/parse2.cpp @@ -894,7 +894,7 @@ inline void Parse::repush_if_args() { } //----------------------------------do_ifnull---------------------------------- -void Parse::do_ifnull(BoolTest::mask btest) { +void Parse::do_ifnull(BoolTest::mask btest, Node *c) { int target_bci = iter().get_dest(); Block* branch_block = successor_for_bci(target_bci); @@ -906,8 +906,9 @@ void Parse::do_ifnull(BoolTest::mask btest) { // (An earlier version of do_ifnull omitted this trap for OSR methods.) #ifndef PRODUCT if (PrintOpto && Verbose) - tty->print_cr("Never-taken backedge stops compilation at bci %d",bci()); + tty->print_cr("Never-taken edge stops compilation at bci %d",bci()); #endif + repush_if_args(); // to gather stats on loop // We need to mark this branch as taken so that if we recompile we will // see that it is possible. In the tiered system the interpreter doesn't // do profiling and by the time we get to the lower tier from the interpreter @@ -928,14 +929,6 @@ void Parse::do_ifnull(BoolTest::mask btest) { maybe_add_safepoint(target_bci); explicit_null_checks_inserted++; - Node* a = null(); - Node* b = pop(); - Node* c = _gvn.transform( new (C, 3) CmpPNode(b, a) ); - - // Make a cast-away-nullness that is control dependent on the test - const Type *t = _gvn.type(b); - const Type *t_not_null = t->join(TypePtr::NOTNULL); - Node *cast = new (C, 2) CastPPNode(b,t_not_null); // Generate real control flow Node *tst = _gvn.transform( new (C, 2) BoolNode( c, btest ) ); @@ -997,7 +990,7 @@ void Parse::do_if(BoolTest::mask btest, Node* c) { if (prob == PROB_UNKNOWN) { #ifndef PRODUCT if (PrintOpto && Verbose) - tty->print_cr("Never-taken backedge stops compilation at bci %d",bci()); + tty->print_cr("Never-taken edge stops compilation at bci %d",bci()); #endif repush_if_args(); // to gather stats on loop // We need to mark this branch as taken so that if we recompile we will @@ -1016,6 +1009,9 @@ void Parse::do_if(BoolTest::mask btest, Node* c) { return; } + // If this is a backwards branch in the bytecodes, add Safepoint + maybe_add_safepoint(target_bci); + // Sanity check the probability value assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser"); @@ -2101,18 +2097,18 @@ void Parse::do_one_bytecode() { break; } - case Bytecodes::_ifnull: - do_ifnull(BoolTest::eq); - break; - case Bytecodes::_ifnonnull: - do_ifnull(BoolTest::ne); + case Bytecodes::_ifnull: btest = BoolTest::eq; goto handle_if_null; + case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null; + handle_if_null: + a = null(); + b = pop(); + c = _gvn.transform( new (C, 3) CmpPNode(b, a) ); + do_ifnull(btest, c); break; case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp; case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp; handle_if_acmp: - // If this is a backwards branch in the bytecodes, add Safepoint - maybe_add_safepoint(iter().get_dest()); a = pop(); b = pop(); c = _gvn.transform( new (C, 3) CmpPNode(b, a) ); @@ -2126,8 +2122,6 @@ void Parse::do_one_bytecode() { case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx; case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx; handle_ifxx: - // If this is a backwards branch in the bytecodes, add Safepoint - maybe_add_safepoint(iter().get_dest()); a = _gvn.intcon(0); b = pop(); c = _gvn.transform( new (C, 3) CmpINode(b, a) ); @@ -2141,8 +2135,6 @@ void Parse::do_one_bytecode() { case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp; case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp; handle_if_icmp: - // If this is a backwards branch in the bytecodes, add Safepoint - maybe_add_safepoint(iter().get_dest()); a = pop(); b = pop(); c = _gvn.transform( new (C, 3) CmpINode( b, a ) ); From 7f639280120729851184b2933d91e9ec6715f97e Mon Sep 17 00:00:00 2001 From: Michael McMahon Date: Wed, 23 Jul 2008 12:05:19 +0100 Subject: [PATCH 044/325] 6728076: Test case for 6536211 is failing on all platforms Exception needed to be caught and logged Reviewed-by: chegar --- jdk/src/share/classes/sun/net/httpserver/ServerImpl.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java b/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java index c041e0bc065..a9658d4b351 100644 --- a/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java +++ b/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java @@ -349,10 +349,8 @@ class ServerImpl implements TimeSource { } } } - } catch (CancelledKeyException e) { + } catch (Exception e) { logger.log (Level.FINER, "Dispatcher (3)", e); - } catch (IOException e) { - logger.log (Level.FINER, "Dispatcher (4)", e); } } } @@ -364,10 +362,10 @@ class ServerImpl implements TimeSource { Exchange t = new Exchange (chan, protocol, conn); executor.execute (t); } catch (HttpError e1) { - logger.log (Level.FINER, "Dispatcher (5)", e1); + logger.log (Level.FINER, "Dispatcher (4)", e1); conn.close(); } catch (IOException e) { - logger.log (Level.FINER, "Dispatcher (6)", e); + logger.log (Level.FINER, "Dispatcher (5)", e); conn.close(); } } From f3eff961d36d7e4c1e00e1b5b1bcf97ceb6c01c4 Mon Sep 17 00:00:00 2001 From: Jonathan Gibbons Date: Wed, 23 Jul 2008 19:55:30 -0700 Subject: [PATCH 045/325] 6726015: JavaCompiler: replace desugarLater by compileStates Reviewed-by: mcimadamore --- .../sun/tools/javac/main/JavaCompiler.java | 96 ++++++++++--------- langtools/test/tools/javac/6199662/Tree.java | 2 +- 2 files changed, 51 insertions(+), 47 deletions(-) diff --git a/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java b/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java index 402c2998275..1ab7c1096e0 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java +++ b/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java @@ -63,6 +63,7 @@ import static com.sun.tools.javac.util.ListBuffer.lb; // TEMP, until we have a more efficient way to save doc comment info import com.sun.tools.javac.parser.DocCommentScanner; +import java.util.HashMap; import java.util.Queue; import javax.lang.model.SourceVersion; @@ -444,7 +445,25 @@ public class JavaCompiler implements ClassReader.SourceCompleter { */ public Todo todo; - private Set> deferredSugar = new HashSet>(); + protected enum CompileState { + TODO(0), + ATTR(1), + FLOW(2); + CompileState(int value) { + this.value = value; + } + boolean isDone(CompileState other) { + return value >= other.value; + } + private int value; + }; + protected class CompileStates extends HashMap,CompileState> { + boolean isDone(Env env, CompileState cs) { + CompileState ecs = get(env); + return ecs != null && ecs.isDone(cs); + } + } + private CompileStates compileStates = new CompileStates(); /** The set of currently compiled inputfiles, needed to ensure * we don't accidentally overwrite an input file when -s is set. @@ -1039,6 +1058,9 @@ public class JavaCompiler implements ClassReader.SourceCompleter { * @returns the attributed parse tree */ public Env attribute(Env env) { + if (compileStates.isDone(env, CompileState.ATTR)) + return env; + if (verboseCompilePolicy) log.printLines(log.noticeWriter, "[attribute " + env.enclClass.sym + "]"); if (verbose) @@ -1055,6 +1077,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter { env.toplevel.sourcefile); try { attr.attribClass(env.tree.pos(), env.enclClass.sym); + compileStates.put(env, CompileState.ATTR); } finally { log.useSource(prev); @@ -1094,7 +1117,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter { if (errorCount() > 0) return; - if (relax || deferredSugar.contains(env)) { + if (relax || compileStates.isDone(env, CompileState.FLOW)) { results.append(env); return; } @@ -1109,6 +1132,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter { make.at(Position.FIRSTPOS); TreeMaker localMake = make.forToplevel(env.toplevel); flow.analyzeTree(env.tree, localMake); + compileStates.put(env, CompileState.FLOW); if (errorCount() > 0) return; @@ -1146,7 +1170,7 @@ public class JavaCompiler implements ClassReader.SourceCompleter { * the current implicitSourcePolicy is taken into account. * The preparation stops as soon as an error is found. */ - protected void desugar(Env env, Queue, JCClassDecl>> results) { + protected void desugar(final Env env, Queue, JCClassDecl>> results) { if (errorCount() > 0) return; @@ -1155,13 +1179,30 @@ public class JavaCompiler implements ClassReader.SourceCompleter { return; } - if (desugarLater(env)) { - if (verboseCompilePolicy) - log.printLines(log.noticeWriter, "[defer " + env.enclClass.sym + "]"); - todo.append(env); - return; + /** + * As erasure (TransTypes) destroys information needed in flow analysis, + * including information in supertypes, we need to ensure that supertypes + * are processed through attribute and flow before subtypes are translated. + */ + class ScanNested extends TreeScanner { + Set> dependencies = new HashSet>(); + public void visitClassDef(JCClassDecl node) { + Type st = types.supertype(node.sym.type); + if (st.tag == TypeTags.CLASS) { + ClassSymbol c = st.tsym.outermostClass(); + Env stEnv = enter.getEnv(c); + if (stEnv != null && env != stEnv) + dependencies.add(stEnv); + } + super.visitClassDef(node); + } + } + ScanNested scanner = new ScanNested(); + scanner.scan(env.tree); + for (Env dep: scanner.dependencies) { + if (!compileStates.isDone(dep, CompileState.FLOW)) + flow(attribute(dep)); } - deferredSugar.remove(env); if (verboseCompilePolicy) log.printLines(log.noticeWriter, "[desugar " + env.enclClass.sym + "]"); @@ -1234,43 +1275,6 @@ public class JavaCompiler implements ClassReader.SourceCompleter { } - /** - * Determine if a class needs to be desugared later. As erasure - * (TransTypes) destroys information needed in flow analysis, we - * need to ensure that supertypes are translated before derived - * types are translated. - */ - public boolean desugarLater(final Env env) { - if (compilePolicy == CompilePolicy.BY_FILE) - return false; - if (!devVerbose && deferredSugar.contains(env)) - // guarantee that compiler terminates - return false; - class ScanNested extends TreeScanner { - Set externalSupers = new HashSet(); - public void visitClassDef(JCClassDecl node) { - Type st = types.supertype(node.sym.type); - if (st.tag == TypeTags.CLASS) { - ClassSymbol c = st.tsym.outermostClass(); - Env stEnv = enter.getEnv(c); - if (stEnv != null && env != stEnv) - externalSupers.add(st.tsym); - } - super.visitClassDef(node); - } - } - ScanNested scanner = new ScanNested(); - scanner.scan(env.tree); - if (scanner.externalSupers.isEmpty()) - return false; - if (!deferredSugar.add(env) && devVerbose) { - throw new AssertionError(env.enclClass.sym + " was deferred, " + - "second time has these external super types " + - scanner.externalSupers); - } - return true; - } - /** Generates the source or class file for a list of classes. * The decision to generate a source file or a class file is * based upon the compiler's options. diff --git a/langtools/test/tools/javac/6199662/Tree.java b/langtools/test/tools/javac/6199662/Tree.java index add54d1013e..70346183770 100644 --- a/langtools/test/tools/javac/6199662/Tree.java +++ b/langtools/test/tools/javac/6199662/Tree.java @@ -23,7 +23,7 @@ /* * @test - * @bug 6199662 6325201 + * @bug 6199662 6325201 6726015 * @summary javac: compilation success depends on compilation order * * @compile Tree.java TreeScanner.java TreeInfo.java From fec04e0a18d65269afafe0785688c0c82d3bbf47 Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Thu, 24 Jul 2008 10:35:38 +0100 Subject: [PATCH 046/325] 6651719: Compiler crashes possibly during forward reference of TypeParameter Compiler should apply capture conversion when checking for bound conformance Reviewed-by: jjg --- .../com/sun/tools/javac/comp/Check.java | 34 +++++++++++++------ .../generics/wildcards/6651719/T6651719a.java | 33 ++++++++++++++++++ .../wildcards/6651719/T6651719b.java} | 25 +++++--------- 3 files changed, 65 insertions(+), 27 deletions(-) create mode 100644 langtools/test/tools/javac/generics/wildcards/6651719/T6651719a.java rename langtools/test/tools/javac/{capture/Capture4.java => generics/wildcards/6651719/T6651719b.java} (72%) diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java index 59b909c7b96..efdb075d121 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java @@ -422,9 +422,7 @@ public class Check { * @param bs The bound. */ private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) { - if (a.isUnbound()) { - return; - } else if (a.tag != WILDCARD) { + if (!(a instanceof CapturedType)) { a = types.upperBound(a); for (List l = types.getBounds(bs); l.nonEmpty(); l = l.tail) { if (!types.isSubtype(a, l.head)) { @@ -432,11 +430,24 @@ public class Check { return; } } - } else if (a.isExtendsBound()) { - if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings)) - log.error(pos, "not.within.bounds", a); - } else if (a.isSuperBound()) { - if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound())) + } + else { + CapturedType ct = (CapturedType)a; + boolean ok = false; + switch (ct.wildcard.kind) { + case EXTENDS: + ok = types.isCastable(bs.getUpperBound(), + types.upperBound(a), + Warner.noWarnings); + break; + case SUPER: + ok = !types.notSoftSubtype(types.lowerBound(a), + bs.getUpperBound()); + break; + case UNBOUND: + ok = true; + } + if (!ok) log.error(pos, "not.within.bounds", a); } } @@ -776,7 +787,7 @@ public class Check { public void visitTypeApply(JCTypeApply tree) { if (tree.type.tag == CLASS) { List formals = tree.type.tsym.type.getTypeArguments(); - List actuals = tree.type.getTypeArguments(); + List actuals = types.capture(tree.type).getTypeArguments(); List args = tree.arguments; List forms = formals; ListBuffer tvars_buf = new ListBuffer(); @@ -792,7 +803,7 @@ public class Check { // bounds substed with actuals. tvars_buf.append(types.substBound(((TypeVar)forms.head), formals, - Type.removeBounds(actuals))); + actuals)); args = args.tail; forms = forms.tail; @@ -811,10 +822,11 @@ public class Check { tvars = tvars_buf.toList(); while (args.nonEmpty() && tvars.nonEmpty()) { checkExtends(args.head.pos(), - args.head.type, + actuals.head, tvars.head); args = args.tail; tvars = tvars.tail; + actuals = actuals.tail; } // Check that this type is either fully parameterized, or diff --git a/langtools/test/tools/javac/generics/wildcards/6651719/T6651719a.java b/langtools/test/tools/javac/generics/wildcards/6651719/T6651719a.java new file mode 100644 index 00000000000..28bdcf4257b --- /dev/null +++ b/langtools/test/tools/javac/generics/wildcards/6651719/T6651719a.java @@ -0,0 +1,33 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6651719 + * @summary Compiler crashes possibly during forward reference of TypeParameter + * @compile T6651719a.java + */ + +public class T6651719a { + T6651719a, ? extends T6651719a> crash = null; +} diff --git a/langtools/test/tools/javac/capture/Capture4.java b/langtools/test/tools/javac/generics/wildcards/6651719/T6651719b.java similarity index 72% rename from langtools/test/tools/javac/capture/Capture4.java rename to langtools/test/tools/javac/generics/wildcards/6651719/T6651719b.java index 2f82f41cf70..f14e4799638 100644 --- a/langtools/test/tools/javac/capture/Capture4.java +++ b/langtools/test/tools/javac/generics/wildcards/6651719/T6651719b.java @@ -1,5 +1,5 @@ /* - * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,22 +23,15 @@ /* * @test - * @bug 4916650 - * @summary wildcards versus recursive F-bounds - * @author gafter - * - * @compile -source 1.5 Capture4.java + * @bug 6651719 + * @summary Compiler crashes possibly during forward reference of TypeParameter + * @compile T6651719b.java */ +import java.util.*; -package capture4; - -class WildcardFBoundCheck { - interface I4 {} - - static class C4, Y extends I4> {} - - WildcardFBoundCheck() - { - C4,?> x2; // <> +public class T6651719b { + void m(T t, List> list) {} + void test(List> list) { + m("", list); } } From 9879011723a68c11a4cc9d96f613148ba26af31a Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Thu, 24 Jul 2008 11:12:41 +0100 Subject: [PATCH 047/325] 6594284: NPE thrown when calling a method on an intersection type Javac should report an error when the capture of an actual type parameter does not exist Reviewed-by: jjg --- .../com/sun/tools/javac/code/Type.java | 9 ++++ .../com/sun/tools/javac/code/Types.java | 2 +- .../com/sun/tools/javac/comp/Check.java | 48 +++++++++++-------- .../test/tools/javac/capture/T6594284.java | 43 +++++++++++++++++ 4 files changed, 81 insertions(+), 21 deletions(-) create mode 100644 langtools/test/tools/javac/capture/T6594284.java diff --git a/langtools/src/share/classes/com/sun/tools/javac/code/Type.java b/langtools/src/share/classes/com/sun/tools/javac/code/Type.java index b3115da9b2f..4c8e78cc294 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/code/Type.java +++ b/langtools/src/share/classes/com/sun/tools/javac/code/Type.java @@ -979,6 +979,10 @@ public class Type implements PrimitiveType { return TypeKind.TYPEVAR; } + public boolean isCaptured() { + return false; + } + public R accept(TypeVisitor v, P p) { return v.visitTypeVariable(this, p); } @@ -1014,6 +1018,11 @@ public class Type implements PrimitiveType { return lower; } + @Override + public boolean isCaptured() { + return true; + } + @Override public String toString() { return "capture#" diff --git a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java index cc86c636f29..36a605d5eb1 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java +++ b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java @@ -835,7 +835,7 @@ public class Types { }; public boolean isCaptureOf(Type s, WildcardType t) { - if (s.tag != TYPEVAR || !(s instanceof CapturedType)) + if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured()) return false; return isSameWildcard(t, ((CapturedType)s).wildcard); } diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java index efdb075d121..44fbc6ba9ea 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java @@ -422,7 +422,34 @@ public class Check { * @param bs The bound. */ private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) { - if (!(a instanceof CapturedType)) { + if (a.tag == TYPEVAR && ((TypeVar)a).isCaptured()) { + CapturedType ct = (CapturedType)a; + boolean ok; + if (ct.bound.isErroneous()) {//capture doesn't exist + ok = false; + } + else { + switch (ct.wildcard.kind) { + case EXTENDS: + ok = types.isCastable(bs.getUpperBound(), + types.upperBound(a), + Warner.noWarnings); + break; + case SUPER: + ok = !types.notSoftSubtype(types.lowerBound(a), + bs.getUpperBound()); + break; + case UNBOUND: + ok = true; + break; + default: + throw new AssertionError("Invalid bound kind"); + } + } + if (!ok) + log.error(pos, "not.within.bounds", a); + } + else { a = types.upperBound(a); for (List l = types.getBounds(bs); l.nonEmpty(); l = l.tail) { if (!types.isSubtype(a, l.head)) { @@ -431,25 +458,6 @@ public class Check { } } } - else { - CapturedType ct = (CapturedType)a; - boolean ok = false; - switch (ct.wildcard.kind) { - case EXTENDS: - ok = types.isCastable(bs.getUpperBound(), - types.upperBound(a), - Warner.noWarnings); - break; - case SUPER: - ok = !types.notSoftSubtype(types.lowerBound(a), - bs.getUpperBound()); - break; - case UNBOUND: - ok = true; - } - if (!ok) - log.error(pos, "not.within.bounds", a); - } } /** Check that type is different from 'void'. diff --git a/langtools/test/tools/javac/capture/T6594284.java b/langtools/test/tools/javac/capture/T6594284.java new file mode 100644 index 00000000000..71112f7044d --- /dev/null +++ b/langtools/test/tools/javac/capture/T6594284.java @@ -0,0 +1,43 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6594284 + * @summary NPE thrown when calling a method on an intersection type + * @author Maurizio Cimadamore + * + * @compile/fail T6594284.java + */ + +public class T6594284 { + class A{ public void a(){}} + class B extends A{ public void b(){}} + interface I{ void i();} + interface I1 { void i1(); } + class E extends B implements I{ public void i(){};} + + class C{ + C arg; + } +} From c3732ffc5d459769b969da2ae7c5b90d36d3d523 Mon Sep 17 00:00:00 2001 From: Mikhail Lapshin Date: Thu, 24 Jul 2008 14:34:02 +0400 Subject: [PATCH 048/325] 6725409: Unable to localize JInternalFrame system menu during run-time Use of the static final constants replaced by direct calls of UIManager.getString(). Reviewed-by: alexp --- .../basic/BasicInternalFrameTitlePane.java | 19 +- .../JInternalFrame/6725409/bug6725409.java | 162 ++++++++++++++++++ 2 files changed, 175 insertions(+), 6 deletions(-) create mode 100644 jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java index 344a4b2b512..d8f25731266 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java @@ -86,6 +86,7 @@ public class BasicInternalFrameTitlePane extends JComponent protected Action moveAction; protected Action sizeAction; + // These constants are not used in JDK code protected static final String CLOSE_CMD = UIManager.getString("InternalFrameTitlePane.closeButtonText"); protected static final String ICONIFY_CMD = @@ -600,7 +601,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class CloseAction extends AbstractAction { public CloseAction() { - super(CLOSE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.closeButtonText")); } public void actionPerformed(ActionEvent e) { @@ -616,7 +618,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class MaximizeAction extends AbstractAction { public MaximizeAction() { - super(MAXIMIZE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.maximizeButtonText")); } public void actionPerformed(ActionEvent evt) { @@ -644,7 +647,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class IconifyAction extends AbstractAction { public IconifyAction() { - super(ICONIFY_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.minimizeButtonText")); } public void actionPerformed(ActionEvent e) { @@ -664,7 +668,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class RestoreAction extends AbstractAction { public RestoreAction() { - super(RESTORE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.restoreButtonText")); } public void actionPerformed(ActionEvent evt) { @@ -690,7 +695,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class MoveAction extends AbstractAction { public MoveAction() { - super(MOVE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.moveButtonText")); } public void actionPerformed(ActionEvent e) { @@ -723,7 +729,8 @@ public class BasicInternalFrameTitlePane extends JComponent */ public class SizeAction extends AbstractAction { public SizeAction() { - super(SIZE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.sizeButtonText")); } public void actionPerformed(ActionEvent e) { diff --git a/jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java b/jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java new file mode 100644 index 00000000000..b118fed88be --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/6725409/bug6725409.java @@ -0,0 +1,162 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6725409 + * @summary Checks that JInternalFrame's system menu + * can be localized during run-time + * @author Mikhail Lapshin + */ + +import javax.swing.*; +import java.awt.*; + +public class bug6725409 { + private JFrame frame; + private JInternalFrame iFrame; + private TestTitlePane testTitlePane; + private boolean passed; + + public static void main(String[] args) throws Exception { + try { + UIManager.setLookAndFeel( + new com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel()); + } catch(UnsupportedLookAndFeelException e) { + System.out.println("The test is for Windows LaF only"); + System.exit(0); + } + + final bug6725409 bug6725409 = new bug6725409(); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + bug6725409.setupUIStep1(); + } + }); + realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + bug6725409.setupUIStep2(); + } + }); + realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + bug6725409.test(); + } + }); + realSync(); + bug6725409.checkResult(); + } finally { + if (bug6725409.frame != null) { + bug6725409.frame.dispose(); + } + } + } + + private void setupUIStep1() { + frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JDesktopPane desktop = new JDesktopPane(); + iFrame = new JInternalFrame("Internal Frame", true, true, true, true); + iFrame.setSize(200, 100); + desktop.add(iFrame); + frame.add(desktop); + iFrame.setVisible(true); + + frame.setSize(500, 300); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private void setupUIStep2() { + UIManager.put("InternalFrameTitlePane.restoreButtonText", + "CUSTOM.restoreButtonText"); + UIManager.put("InternalFrameTitlePane.moveButtonText", + "CUSTOM.moveButtonText"); + UIManager.put("InternalFrameTitlePane.sizeButtonText", + "CUSTOM.sizeButtonText"); + UIManager.put("InternalFrameTitlePane.minimizeButtonText", + "CUSTOM.minimizeButtonText"); + UIManager.put("InternalFrameTitlePane.maximizeButtonText", + "CUSTOM.maximizeButtonText"); + UIManager.put("InternalFrameTitlePane.closeButtonText", + "CUSTOM.closeButtonText"); + SwingUtilities.updateComponentTreeUI(frame); + } + + // The test depends on the order of the menu items in + // WindowsInternalFrameTitlePane.systemPopupMenu + private void test() { + testTitlePane = new TestTitlePane(iFrame); + passed = true; + checkMenuItemText(0, "CUSTOM.restoreButtonText"); + checkMenuItemText(1, "CUSTOM.moveButtonText"); + checkMenuItemText(2, "CUSTOM.sizeButtonText"); + checkMenuItemText(3, "CUSTOM.minimizeButtonText"); + checkMenuItemText(4, "CUSTOM.maximizeButtonText"); + // Skip separator + checkMenuItemText(6, "CUSTOM.closeButtonText"); + } + + private void checkMenuItemText(int index, String text) { + JMenuItem menuItem = (JMenuItem) + testTitlePane.getSystemPopupMenu().getComponent(index); + if (!text.equals(menuItem.getText())) { + passed = false; + } + } + + private void checkResult() { + if (passed) { + System.out.println("Test passed"); + } else { + throw new RuntimeException("Unable to localize " + + "JInternalFrame's system menu during run-time"); + } + } + + private static void realSync() { + ((sun.awt.SunToolkit) (Toolkit.getDefaultToolkit())).realSync(); + } + + // Extend WindowsInternalFrameTitlePane to get access to systemPopupMenu + private class TestTitlePane extends + com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane { + private JPopupMenu systemPopupMenu; + + public TestTitlePane(JInternalFrame f) { + super(f); + } + + public JPopupMenu getSystemPopupMenu() { + return systemPopupMenu; + } + + protected void addSystemMenuItems(JPopupMenu menu) { + super.addSystemMenuItems(menu); + systemPopupMenu = menu; + } + } +} From 02a6cd79141120a36b79ee2e64c72b11f8269ab8 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 24 Jul 2008 14:51:13 +0400 Subject: [PATCH 049/325] 4778988: CompoundBorder.isBorderOpaque() has incorrect documentation Reviewed-by: peterz, rupashka --- .../share/classes/javax/swing/border/CompoundBorder.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/border/CompoundBorder.java b/jdk/src/share/classes/javax/swing/border/CompoundBorder.java index f736cf90278..46ac44e50c0 100644 --- a/jdk/src/share/classes/javax/swing/border/CompoundBorder.java +++ b/jdk/src/share/classes/javax/swing/border/CompoundBorder.java @@ -79,10 +79,13 @@ public class CompoundBorder extends AbstractBorder { } /** - * Returns whether or not this compound border is opaque. - * Returns true if both the inside and outside borders are - * non-null and opaque; returns false otherwise. + * Returns whether or not the compound border is opaque. + * + * @return {@code true} if the inside and outside borders + * are each either {@code null} or opaque; + * or {@code false} otherwise */ + @Override public boolean isBorderOpaque() { return (outsideBorder == null || outsideBorder.isBorderOpaque()) && (insideBorder == null || insideBorder.isBorderOpaque()); From 2fa9f3bee9fde9e920fe1bc114a5a83ac3c3d91a Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Thu, 24 Jul 2008 12:40:30 +0100 Subject: [PATCH 050/325] 6728728: (se) WindowsSelectorImpl.c doesn't compile with Visual Studio 2008 Reviewed-by: tbell, chegar --- .../native/sun/nio/ch/WindowsSelectorImpl.c | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/jdk/src/windows/native/sun/nio/ch/WindowsSelectorImpl.c b/jdk/src/windows/native/sun/nio/ch/WindowsSelectorImpl.c index 4927d68c2ec..cb424adebc4 100644 --- a/jdk/src/windows/native/sun/nio/ch/WindowsSelectorImpl.c +++ b/jdk/src/windows/native/sun/nio/ch/WindowsSelectorImpl.c @@ -37,6 +37,7 @@ #include "jni.h" #include "jni_util.h" #include "sun_nio_ch_WindowsSelectorImpl.h" +#include "sun_nio_ch_PollArrayWrapper.h" #include "winsock2.h" @@ -45,10 +46,6 @@ typedef struct { jshort events; } pollfd; -static int POLLIN = 1; -static int POLLCONN = 2; -static int POLLOUT = 4; - #define WAKEUP_SOCKET_BUF_SIZE 16 @@ -82,11 +79,13 @@ Java_sun_nio_ch_WindowsSelectorImpl_00024SubSelector_poll0(JNIEnv *env, jobject /* Set FD_SET structures required for select */ for (i = 0; i < numfds; i++) { - if (fds[i].events & POLLIN) { + if (fds[i].events & sun_nio_ch_PollArrayWrapper_POLLIN) { readfds.fd_array[read_count] = fds[i].fd; read_count++; } - if (fds[i].events & (POLLOUT | POLLCONN)) { + if (fds[i].events & (sun_nio_ch_PollArrayWrapper_POLLOUT | + sun_nio_ch_PollArrayWrapper_POLLCONN)) + { writefds.fd_array[write_count] = fds[i].fd; write_count++; } @@ -111,11 +110,13 @@ Java_sun_nio_ch_WindowsSelectorImpl_00024SubSelector_poll0(JNIEnv *env, jobject /* prepare select structures for the i-th socket */ errreadfds.fd_count = 0; errwritefds.fd_count = 0; - if (fds[i].events & POLLIN) { + if (fds[i].events & sun_nio_ch_PollArrayWrapper_POLLIN) { errreadfds.fd_array[0] = fds[i].fd; errreadfds.fd_count = 1; } - if (fds[i].events & (POLLOUT | POLLCONN)) { + if (fds[i].events & (sun_nio_ch_PollArrayWrapper_POLLOUT | + sun_nio_ch_PollArrayWrapper_POLLCONN)) + { errwritefds.fd_array[0] = fds[i].fd; errwritefds.fd_count = 1; } @@ -187,7 +188,8 @@ Java_sun_nio_ch_WindowsSelectorImpl_setWakeupSocket0(JNIEnv *env, jclass this, jint scoutFd) { /* Write one byte into the pipe */ - send(scoutFd, (char*)&POLLIN, 1, 0); + const char byte = 1; + send(scoutFd, &byte, 1, 0); } JNIEXPORT void JNICALL From 949d3854a5b8695f9a46aa3528c0ed323c6fec7a Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Thu, 24 Jul 2008 12:46:41 +0100 Subject: [PATCH 051/325] 6726309: Compiler warnings in nio code Reviewed-by: sherman, iris --- .../java/nio/channels/spi/AbstractSelector.java | 2 +- .../java/nio/charset/Charset-X-Coder.java | 8 ++++---- .../share/classes/java/nio/charset/Charset.java | 10 +++++----- .../classes/java/nio/charset/CoderResult.java | 12 ++++++------ .../share/classes/sun/nio/ch/SelectorImpl.java | 16 ++++++++-------- jdk/src/share/classes/sun/nio/ch/Util.java | 8 ++++++-- jdk/src/share/native/java/nio/Bits.c | 12 ++++++------ .../classes/sun/nio/ch/DevPollSelectorImpl.java | 11 +++++------ .../classes/sun/nio/ch/EPollSelectorImpl.java | 11 +++++------ .../solaris/native/java/nio/MappedByteBuffer.c | 6 +++++- .../native/sun/nio/ch/DatagramChannelImpl.c | 2 +- .../solaris/native/sun/nio/ch/InheritedChannel.c | 3 ++- jdk/src/solaris/native/sun/nio/ch/Net.c | 4 ++-- .../native/sun/nio/ch/ServerSocketChannelImpl.c | 5 +++-- .../native/sun/nio/ch/SocketChannelImpl.c | 2 +- jdk/src/windows/classes/sun/nio/ch/PipeImpl.java | 4 ++-- .../classes/sun/nio/ch/WindowsSelectorImpl.java | 3 ++- 17 files changed, 64 insertions(+), 55 deletions(-) diff --git a/jdk/src/share/classes/java/nio/channels/spi/AbstractSelector.java b/jdk/src/share/classes/java/nio/channels/spi/AbstractSelector.java index 2e2b910bbb3..019dd6ef49d 100644 --- a/jdk/src/share/classes/java/nio/channels/spi/AbstractSelector.java +++ b/jdk/src/share/classes/java/nio/channels/spi/AbstractSelector.java @@ -82,7 +82,7 @@ public abstract class AbstractSelector this.provider = provider; } - private final Set cancelledKeys = new HashSet(); + private final Set cancelledKeys = new HashSet(); void cancel(SelectionKey k) { // package-private synchronized (cancelledKeys) { diff --git a/jdk/src/share/classes/java/nio/charset/Charset-X-Coder.java b/jdk/src/share/classes/java/nio/charset/Charset-X-Coder.java index 4b7c83f8084..1593be1da3d 100644 --- a/jdk/src/share/classes/java/nio/charset/Charset-X-Coder.java +++ b/jdk/src/share/classes/java/nio/charset/Charset-X-Coder.java @@ -303,7 +303,7 @@ public abstract class Charset$Coder$ { #if[encoder] - private WeakReference cachedDecoder = null; + private WeakReference cachedDecoder = null; /** * Tells whether or not the given byte array is a legal replacement value @@ -322,13 +322,13 @@ public abstract class Charset$Coder$ { * is a legal replacement value for this encoder */ public boolean isLegalReplacement(byte[] repl) { - WeakReference wr = cachedDecoder; + WeakReference wr = cachedDecoder; CharsetDecoder dec = null; - if ((wr == null) || ((dec = (CharsetDecoder)wr.get()) == null)) { + if ((wr == null) || ((dec = wr.get()) == null)) { dec = charset().newDecoder(); dec.onMalformedInput(CodingErrorAction.REPORT); dec.onUnmappableCharacter(CodingErrorAction.REPORT); - cachedDecoder = new WeakReference(dec); + cachedDecoder = new WeakReference(dec); } else { dec.reset(); } diff --git a/jdk/src/share/classes/java/nio/charset/Charset.java b/jdk/src/share/classes/java/nio/charset/Charset.java index 98f504dc5d3..4908c77d1db 100644 --- a/jdk/src/share/classes/java/nio/charset/Charset.java +++ b/jdk/src/share/classes/java/nio/charset/Charset.java @@ -379,7 +379,7 @@ public abstract class Charset } // Thread-local gate to prevent recursive provider lookups - private static ThreadLocal gate = new ThreadLocal(); + private static ThreadLocal gate = new ThreadLocal(); private static Charset lookupViaProviders(final String charsetName) { @@ -539,9 +539,9 @@ public abstract class Charset // Fold charsets from the given iterator into the given map, ignoring // charsets whose names already have entries in the map. // - private static void put(Iterator i, Map m) { + private static void put(Iterator i, Map m) { while (i.hasNext()) { - Charset cs = (Charset)i.next(); + Charset cs = i.next(); if (!m.containsKey(cs.name())) m.put(cs.name(), cs); } @@ -623,7 +623,7 @@ public abstract class Charset private final String name; // tickles a bug in oldjavac private final String[] aliases; // tickles a bug in oldjavac - private Set aliasSet = null; + private Set aliasSet = null; /** * Initializes a new charset with the given canonical name and alias @@ -665,7 +665,7 @@ public abstract class Charset if (aliasSet != null) return aliasSet; int n = aliases.length; - HashSet hs = new HashSet(n); + HashSet hs = new HashSet(n); for (int i = 0; i < n; i++) hs.add(aliases[i]); aliasSet = Collections.unmodifiableSet(hs); diff --git a/jdk/src/share/classes/java/nio/charset/CoderResult.java b/jdk/src/share/classes/java/nio/charset/CoderResult.java index 954d6a9c249..8f3c0befacc 100644 --- a/jdk/src/share/classes/java/nio/charset/CoderResult.java +++ b/jdk/src/share/classes/java/nio/charset/CoderResult.java @@ -194,7 +194,7 @@ public class CoderResult { private static abstract class Cache { - private Map cache = null; + private Map> cache = null; protected abstract CoderResult create(int len); @@ -202,16 +202,16 @@ public class CoderResult { if (len <= 0) throw new IllegalArgumentException("Non-positive length"); Integer k = new Integer(len); - WeakReference w; + WeakReference w; CoderResult e = null; if (cache == null) { - cache = new HashMap(); - } else if ((w = (WeakReference)cache.get(k)) != null) { - e = (CoderResult)w.get(); + cache = new HashMap>(); + } else if ((w = cache.get(k)) != null) { + e = w.get(); } if (e == null) { e = create(len); - cache.put(k, new WeakReference(e)); + cache.put(k, new WeakReference(e)); } return e; } diff --git a/jdk/src/share/classes/sun/nio/ch/SelectorImpl.java b/jdk/src/share/classes/sun/nio/ch/SelectorImpl.java index f092db00d79..ce6e39b08e9 100644 --- a/jdk/src/share/classes/sun/nio/ch/SelectorImpl.java +++ b/jdk/src/share/classes/sun/nio/ch/SelectorImpl.java @@ -42,19 +42,19 @@ abstract class SelectorImpl { // The set of keys with data ready for an operation - protected Set selectedKeys; + protected Set selectedKeys; // The set of keys registered with this Selector - protected HashSet keys; + protected HashSet keys; // Public views of the key sets - private Set publicKeys; // Immutable - private Set publicSelectedKeys; // Removal allowed, but not addition + private Set publicKeys; // Immutable + private Set publicSelectedKeys; // Removal allowed, but not addition protected SelectorImpl(SelectorProvider sp) { super(sp); - keys = new HashSet(); - selectedKeys = new HashSet(); + keys = new HashSet(); + selectedKeys = new HashSet(); if (Util.atBugLevel("1.4")) { publicKeys = keys; publicSelectedKeys = selectedKeys; @@ -64,13 +64,13 @@ abstract class SelectorImpl } } - public Set keys() { + public Set keys() { if (!isOpen() && !Util.atBugLevel("1.4")) throw new ClosedSelectorException(); return publicKeys; } - public Set selectedKeys() { + public Set selectedKeys() { if (!isOpen() && !Util.atBugLevel("1.4")) throw new ClosedSelectorException(); return publicSelectedKeys; diff --git a/jdk/src/share/classes/sun/nio/ch/Util.java b/jdk/src/share/classes/sun/nio/ch/Util.java index 7aedce2a294..534548ff778 100644 --- a/jdk/src/share/classes/sun/nio/ch/Util.java +++ b/jdk/src/share/classes/sun/nio/ch/Util.java @@ -51,9 +51,13 @@ class Util { // Per-thread soft cache of the last temporary direct buffer private static ThreadLocal>[] bufferPool; + @SuppressWarnings("unchecked") + static ThreadLocal>[] createThreadLocalBufferPool() { + return new ThreadLocal[TEMP_BUF_POOL_SIZE]; + } + static { - bufferPool = (ThreadLocal>[]) - new ThreadLocal[TEMP_BUF_POOL_SIZE]; + bufferPool = createThreadLocalBufferPool(); for (int i=0; i>(); } diff --git a/jdk/src/share/native/java/nio/Bits.c b/jdk/src/share/native/java/nio/Bits.c index ce9fe637770..0227d6de86b 100644 --- a/jdk/src/share/native/java/nio/Bits.c +++ b/jdk/src/share/native/java/nio/Bits.c @@ -116,7 +116,7 @@ Java_java_nio_Bits_copyFromShortArray(JNIEnv *env, jobject this, jobject src, jshort *srcShort, *dstShort, *endShort; jshort tmpShort; - dstShort = (jshort *)dstAddr; + dstShort = (jshort *)jlong_to_ptr(dstAddr); while (length > 0) { /* do not change this if-else statement, see WARNING above */ @@ -151,7 +151,7 @@ Java_java_nio_Bits_copyToShortArray(JNIEnv *env, jobject this, jlong srcAddr, jshort *srcShort, *dstShort, *endShort; jshort tmpShort; - srcShort = (jshort *)srcAddr; + srcShort = (jshort *)jlong_to_ptr(srcAddr); while (length > 0) { /* do not change this if-else statement, see WARNING above */ @@ -186,7 +186,7 @@ Java_java_nio_Bits_copyFromIntArray(JNIEnv *env, jobject this, jobject src, jint *srcInt, *dstInt, *endInt; jint tmpInt; - dstInt = (jint *)dstAddr; + dstInt = (jint *)jlong_to_ptr(dstAddr); while (length > 0) { /* do not change this code, see WARNING above */ @@ -221,7 +221,7 @@ Java_java_nio_Bits_copyToIntArray(JNIEnv *env, jobject this, jlong srcAddr, jint *srcInt, *dstInt, *endInt; jint tmpInt; - srcInt = (jint *)srcAddr; + srcInt = (jint *)jlong_to_ptr(srcAddr); while (length > 0) { /* do not change this code, see WARNING above */ @@ -256,7 +256,7 @@ Java_java_nio_Bits_copyFromLongArray(JNIEnv *env, jobject this, jobject src, jlong *srcLong, *dstLong, *endLong; jlong tmpLong; - dstLong = (jlong *)dstAddr; + dstLong = (jlong *)jlong_to_ptr(dstAddr); while (length > 0) { /* do not change this code, see WARNING above */ @@ -291,7 +291,7 @@ Java_java_nio_Bits_copyToLongArray(JNIEnv *env, jobject this, jlong srcAddr, jlong *srcLong, *dstLong, *endLong; jlong tmpLong; - srcLong = (jlong *)srcAddr; + srcLong = (jlong *)jlong_to_ptr(srcAddr); while (length > 0) { /* do not change this code, see WARNING above */ diff --git a/jdk/src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java b/jdk/src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java index c9704334bc1..7261443a6cb 100644 --- a/jdk/src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java +++ b/jdk/src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java @@ -50,7 +50,7 @@ class DevPollSelectorImpl private int totalChannels; // Maps from file descriptors to keys - private HashMap fdToKey; + private Map fdToKey; // True if this Selector has been closed private boolean closed = false; @@ -71,7 +71,7 @@ class DevPollSelectorImpl fd1 = fdes[1]; pollWrapper = new DevPollArrayWrapper(); pollWrapper.initInterrupt(fd0, fd1); - fdToKey = new HashMap(); + fdToKey = new HashMap(); totalChannels = 1; } @@ -110,8 +110,7 @@ class DevPollSelectorImpl int numKeysUpdated = 0; for (int i=0; i= 0); int fd = ski.channel.getFDVal(); - fdToKey.remove(new Integer(fd)); + fdToKey.remove(Integer.valueOf(fd)); pollWrapper.release(fd); totalChannels--; ski.setIndex(-1); diff --git a/jdk/src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java b/jdk/src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java index 47911b4736d..341fd4704b3 100644 --- a/jdk/src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java +++ b/jdk/src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java @@ -48,7 +48,7 @@ class EPollSelectorImpl EPollArrayWrapper pollWrapper; // Maps from file descriptors to keys - private HashMap fdToKey; + private Map fdToKey; // True if this Selector has been closed private boolean closed = false; @@ -69,7 +69,7 @@ class EPollSelectorImpl fd1 = fdes[1]; pollWrapper = new EPollArrayWrapper(); pollWrapper.initInterrupt(fd0, fd1); - fdToKey = new HashMap(); + fdToKey = new HashMap(); } protected int doSelect(long timeout) @@ -107,8 +107,7 @@ class EPollSelectorImpl int numKeysUpdated = 0; for (int i=0; i= 0); int fd = ski.channel.getFDVal(); - fdToKey.remove(new Integer(fd)); + fdToKey.remove(Integer.valueOf(fd)); pollWrapper.release(fd); ski.setIndex(-1); keys.remove(ski); diff --git a/jdk/src/solaris/native/java/nio/MappedByteBuffer.c b/jdk/src/solaris/native/java/nio/MappedByteBuffer.c index 70c2d07fb0f..70d5c3e658e 100644 --- a/jdk/src/solaris/native/java/nio/MappedByteBuffer.c +++ b/jdk/src/solaris/native/java/nio/MappedByteBuffer.c @@ -43,7 +43,11 @@ Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, int result = 0; int i = 0; void *a = (void *) jlong_to_ptr(address); - char * vec = (char *)malloc(numPages * sizeof(char)); +#ifdef __linux__ + unsigned char *vec = (unsigned char *)malloc(numPages * sizeof(char)); +#else + char *vec = (char *)malloc(numPages * sizeof(char)); +#endif if (vec == NULL) { JNU_ThrowOutOfMemoryError(env, NULL); diff --git a/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c b/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c index 2bf8b83ce88..b1f9f680b18 100644 --- a/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c +++ b/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c @@ -123,7 +123,7 @@ Java_sun_nio_ch_DatagramChannelImpl_receive0(JNIEnv *env, jobject this, jint fd = fdval(env, fdo); void *buf = (void *)jlong_to_ptr(address); SOCKADDR sa; - int sa_len = SOCKADDR_LEN; + socklen_t sa_len = SOCKADDR_LEN; jboolean retry = JNI_FALSE; jint n = 0; jobject senderAddr; diff --git a/jdk/src/solaris/native/sun/nio/ch/InheritedChannel.c b/jdk/src/solaris/native/sun/nio/ch/InheritedChannel.c index dbd329d785c..c6ba463a5a0 100644 --- a/jdk/src/solaris/native/sun/nio/ch/InheritedChannel.c +++ b/jdk/src/solaris/native/sun/nio/ch/InheritedChannel.c @@ -88,7 +88,8 @@ Java_sun_nio_ch_InheritedChannel_peerPort0(JNIEnv *env, jclass cla, jint fd) JNIEXPORT jint JNICALL Java_sun_nio_ch_InheritedChannel_soType0(JNIEnv *env, jclass cla, jint fd) { - int sotype, arglen=sizeof(sotype); + int sotype; + socklen_t arglen=sizeof(sotype); if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen) == 0) { if (sotype == SOCK_STREAM) return sun_nio_ch_InheritedChannel_SOCK_STREAM; diff --git a/jdk/src/solaris/native/sun/nio/ch/Net.c b/jdk/src/solaris/native/sun/nio/ch/Net.c index ae2ef65cb89..9eb31c8926e 100644 --- a/jdk/src/solaris/native/sun/nio/ch/Net.c +++ b/jdk/src/solaris/native/sun/nio/ch/Net.c @@ -138,7 +138,7 @@ JNIEXPORT jint JNICALL Java_sun_nio_ch_Net_localPort(JNIEnv *env, jclass clazz, jobject fdo) { SOCKADDR sa; - int sa_len = SOCKADDR_LEN; + socklen_t sa_len = SOCKADDR_LEN; if (getsockname(fdval(env, fdo), (struct sockaddr *)&sa, &sa_len) < 0) { handleSocketError(env, errno); return -1; @@ -150,7 +150,7 @@ JNIEXPORT jobject JNICALL Java_sun_nio_ch_Net_localInetAddress(JNIEnv *env, jclass clazz, jobject fdo) { SOCKADDR sa; - int sa_len = SOCKADDR_LEN; + socklen_t sa_len = SOCKADDR_LEN; int port; if (getsockname(fdval(env, fdo), (struct sockaddr *)&sa, &sa_len) < 0) { handleSocketError(env, errno); diff --git a/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c b/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c index fff46c4a95d..da92ed73d95 100644 --- a/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c +++ b/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c @@ -81,12 +81,12 @@ Java_sun_nio_ch_ServerSocketChannelImpl_accept0(JNIEnv *env, jobject this, jint ssfd = (*env)->GetIntField(env, ssfdo, fd_fdID); jint newfd; struct sockaddr *sa; - int sa_len; + int alloc_len; jobject remote_ia = 0; jobject isa; jint remote_port; - NET_AllocSockaddr(&sa, &sa_len); + NET_AllocSockaddr(&sa, &alloc_len); /* * accept connection but ignore ECONNABORTED indicating that @@ -94,6 +94,7 @@ Java_sun_nio_ch_ServerSocketChannelImpl_accept0(JNIEnv *env, jobject this, * accept() was called. */ for (;;) { + socklen_t sa_len = alloc_len; newfd = accept(ssfd, sa, &sa_len); if (newfd >= 0) { break; diff --git a/jdk/src/solaris/native/sun/nio/ch/SocketChannelImpl.c b/jdk/src/solaris/native/sun/nio/ch/SocketChannelImpl.c index 94a6d9dfe26..94c8467cf21 100644 --- a/jdk/src/solaris/native/sun/nio/ch/SocketChannelImpl.c +++ b/jdk/src/solaris/native/sun/nio/ch/SocketChannelImpl.c @@ -55,7 +55,7 @@ Java_sun_nio_ch_SocketChannelImpl_checkConnect(JNIEnv *env, jobject this, jboolean ready) { int error = 0; - int n = sizeof(int); + socklen_t n = sizeof(int); jint fd = fdval(env, fdo); int result = 0; struct pollfd poller; diff --git a/jdk/src/windows/classes/sun/nio/ch/PipeImpl.java b/jdk/src/windows/classes/sun/nio/ch/PipeImpl.java index 03165d68196..f021265f491 100644 --- a/jdk/src/windows/classes/sun/nio/ch/PipeImpl.java +++ b/jdk/src/windows/classes/sun/nio/ch/PipeImpl.java @@ -67,7 +67,7 @@ class PipeImpl } private class Initializer - implements PrivilegedExceptionAction + implements PrivilegedExceptionAction { private final SelectorProvider sp; @@ -76,7 +76,7 @@ class PipeImpl this.sp = sp; } - public Object run() throws IOException { + public Void run() throws IOException { ServerSocketChannel ssc = null; SocketChannel sc1 = null; SocketChannel sc2 = null; diff --git a/jdk/src/windows/classes/sun/nio/ch/WindowsSelectorImpl.java b/jdk/src/windows/classes/sun/nio/ch/WindowsSelectorImpl.java index 211b66364f3..0617c0f7ddc 100644 --- a/jdk/src/windows/classes/sun/nio/ch/WindowsSelectorImpl.java +++ b/jdk/src/windows/classes/sun/nio/ch/WindowsSelectorImpl.java @@ -72,7 +72,7 @@ final class WindowsSelectorImpl extends SelectorImpl { private int threadsCount = 0; // A list of helper threads for select. - private final List threads = new ArrayList(); + private final List threads = new ArrayList(); //Pipe used as a wakeup object. private final Pipe wakeupPipe; @@ -82,6 +82,7 @@ final class WindowsSelectorImpl extends SelectorImpl { // Maps file descriptors to their indices in pollArray private final static class FdMap extends HashMap { + static final long serialVersionUID = 0L; private MapEntry get(int desc) { return get(new Integer(desc)); } From 8ad3454b18021915cf22eacd3a87ede111620cb6 Mon Sep 17 00:00:00 2001 From: Florian Brunner Date: Thu, 24 Jul 2008 16:43:36 +0400 Subject: [PATCH 052/325] 6722802: Code improvement and warnings removing from the javax.swing.text package Removed unnecessary castings and other warnings Reviewed-by: peterz --- .../javax/swing/text/AbstractDocument.java | 29 +++-- .../javax/swing/text/AsyncBoxView.java | 12 +-- .../javax/swing/text/ComponentView.java | 5 +- .../javax/swing/text/DefaultCaret.java | 5 +- .../javax/swing/text/DefaultFormatter.java | 4 +- .../javax/swing/text/DefaultHighlighter.java | 20 ++-- .../swing/text/DefaultStyledDocument.java | 97 ++++++++--------- .../javax/swing/text/ElementIterator.java | 20 ++-- .../classes/javax/swing/text/FlowView.java | 6 +- .../classes/javax/swing/text/GapContent.java | 14 +-- .../swing/text/InternationalFormatter.java | 9 +- .../javax/swing/text/JTextComponent.java | 73 ++++++------- .../classes/javax/swing/text/LayoutQueue.java | 6 +- .../javax/swing/text/MaskFormatter.java | 6 +- .../javax/swing/text/NumberFormatter.java | 18 +--- .../javax/swing/text/PlainDocument.java | 4 +- .../javax/swing/text/SegmentCache.java | 6 +- .../javax/swing/text/SimpleAttributeSet.java | 6 +- .../javax/swing/text/StringContent.java | 10 +- .../javax/swing/text/StyleContext.java | 38 +++---- .../classes/javax/swing/text/TableView.java | 11 +- .../classes/javax/swing/text/TextAction.java | 8 +- .../javax/swing/text/TextLayoutStrategy.java | 12 +-- .../classes/javax/swing/text/ZoneView.java | 10 +- .../javax/swing/text/html/AccessibleHTML.java | 42 ++++---- .../classes/javax/swing/text/html/CSS.java | 71 ++++++------ .../classes/javax/swing/text/html/HTML.java | 18 ++-- .../javax/swing/text/html/HTMLDocument.java | 69 ++++++------ .../javax/swing/text/html/HTMLEditorKit.java | 25 +++-- .../javax/swing/text/html/HTMLWriter.java | 33 +++--- .../classes/javax/swing/text/html/Map.java | 18 ++-- .../swing/text/html/MinimalHTMLWriter.java | 8 +- .../swing/text/html/OptionListModel.java | 9 +- .../javax/swing/text/html/StyleSheet.java | 102 +++++++++--------- .../javax/swing/text/html/TableView.java | 10 +- .../swing/text/html/parser/AttributeList.java | 2 +- .../javax/swing/text/html/parser/DTD.java | 28 +++-- .../javax/swing/text/html/parser/Element.java | 4 +- .../javax/swing/text/html/parser/Entity.java | 4 +- .../javax/swing/text/html/parser/Parser.java | 14 ++- .../swing/text/html/parser/TagStack.java | 16 --- .../swing/text/rtf/MockAttributeSet.java | 2 +- .../javax/swing/text/rtf/RTFAttributes.java | 13 ++- .../javax/swing/text/rtf/RTFGenerator.java | 42 ++++---- .../javax/swing/text/rtf/RTFParser.java | 2 +- .../javax/swing/text/rtf/RTFReader.java | 102 +++++++++--------- 46 files changed, 499 insertions(+), 564 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java index 406350a9b10..a5cbdc2396c 100644 --- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java +++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java @@ -123,15 +123,15 @@ public abstract class AbstractDocument implements Document, Serializable { if (defaultI18NProperty == null) { // determine default setting for i18n support - Object o = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + String o = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public String run() { return System.getProperty(I18NProperty); } } ); if (o != null) { - defaultI18NProperty = Boolean.valueOf((String)o); + defaultI18NProperty = Boolean.valueOf(o); } else { defaultI18NProperty = Boolean.FALSE; } @@ -163,7 +163,7 @@ public abstract class AbstractDocument implements Document, Serializable { */ public Dictionary getDocumentProperties() { if (documentProperties == null) { - documentProperties = new Hashtable(2); + documentProperties = new Hashtable(2); } return documentProperties; } @@ -467,8 +467,7 @@ public abstract class AbstractDocument implements Document, Serializable { * @since 1.4 */ public DocumentListener[] getDocumentListeners() { - return (DocumentListener[])listenerList.getListeners( - DocumentListener.class); + return listenerList.getListeners(DocumentListener.class); } /** @@ -508,8 +507,7 @@ public abstract class AbstractDocument implements Document, Serializable { * @since 1.4 */ public UndoableEditListener[] getUndoableEditListeners() { - return (UndoableEditListener[])listenerList.getListeners( - UndoableEditListener.class); + return listenerList.getListeners(UndoableEditListener.class); } /** @@ -610,7 +608,7 @@ public abstract class AbstractDocument implements Document, Serializable { DefaultDocumentEvent chng = new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE); - boolean isComposedTextElement = false; + boolean isComposedTextElement; // Check whether the position of interest is the composed text isComposedTextElement = Utilities.isComposedTextElement(this, offs); @@ -1051,7 +1049,7 @@ public abstract class AbstractDocument implements Document, Serializable { byte levels[] = calculateBidiLevels( firstPStart, lastPEnd ); - Vector newElements = new Vector(); + Vector newElements = new Vector(); // Calculate the first span of characters in the affected range with // the same bidi level. If this level is the same as the level of the @@ -1831,7 +1829,6 @@ public abstract class AbstractDocument implements Document, Serializable { } out.println("["+contentStr+"]"); } catch (BadLocationException e) { - ; } } else { @@ -2460,7 +2457,7 @@ public abstract class AbstractDocument implements Document, Serializable { if(nchildren == 0) return null; - Vector tempVector = new Vector(nchildren); + Vector tempVector = new Vector(nchildren); for(int counter = 0; counter < nchildren; counter++) tempVector.addElement(children[counter]); @@ -2749,7 +2746,7 @@ public abstract class AbstractDocument implements Document, Serializable { // if the number of changes gets too great, start using // a hashtable for to locate the change for a given element. if ((changeLookup == null) && (edits.size() > 10)) { - changeLookup = new Hashtable(); + changeLookup = new Hashtable(); int n = edits.size(); for (int i = 0; i < n; i++) { Object o = edits.elementAt(i); @@ -2918,7 +2915,7 @@ public abstract class AbstractDocument implements Document, Serializable { */ public DocumentEvent.ElementChange getChange(Element elem) { if (changeLookup != null) { - return (DocumentEvent.ElementChange) changeLookup.get(elem); + return changeLookup.get(elem); } int n = edits.size(); for (int i = 0; i < n; i++) { @@ -2937,7 +2934,7 @@ public abstract class AbstractDocument implements Document, Serializable { private int offset; private int length; - private Hashtable changeLookup; + private Hashtable changeLookup; private DocumentEvent.EventType type; } diff --git a/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java b/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java index 54a0e973553..ae11bde8122 100644 --- a/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java +++ b/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java @@ -25,6 +25,7 @@ package javax.swing.text; import java.util.*; +import java.util.List; import java.awt.*; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; @@ -58,7 +59,7 @@ public class AsyncBoxView extends View { */ public AsyncBoxView(Element elem, int axis) { super(elem); - stats = new ArrayList(); + stats = new ArrayList(); this.axis = axis; locator = new ChildLocator(); flushTask = new FlushTask(); @@ -197,7 +198,7 @@ public class AsyncBoxView extends View { protected ChildState getChildState(int index) { synchronized(stats) { if ((index >= 0) && (index < stats.size())) { - return (ChildState) stats.get(index); + return stats.get(index); } return null; } @@ -357,7 +358,7 @@ public class AsyncBoxView extends View { synchronized(stats) { // remove the replaced state records for (int i = 0; i < length; i++) { - ChildState cs = (ChildState)stats.remove(offset); + ChildState cs = stats.remove(offset); float csSpan = cs.getMajorSpan(); cs.getChildView().setParent(null); @@ -863,7 +864,7 @@ public class AsyncBoxView extends View { /** * The children and their layout statistics. */ - java.util.List stats; + List stats; /** * Current span along the major axis. This @@ -1110,7 +1111,7 @@ public class AsyncBoxView extends View { */ int updateChildOffsets(float targetOffset) { int n = getViewCount(); - int targetIndex = n - 1;; + int targetIndex = n - 1; int pos = lastValidOffset.getChildView().getStartOffset(); int startIndex = getViewIndex(pos, Position.Bias.Forward); float start = lastValidOffset.getMajorOffset(); @@ -1394,7 +1395,6 @@ public class AsyncBoxView extends View { private float min; private float pref; private float max; - private float align; private boolean minorValid; // major axis diff --git a/jdk/src/share/classes/javax/swing/text/ComponentView.java b/jdk/src/share/classes/javax/swing/text/ComponentView.java index 62e4bd02acb..085d999675d 100644 --- a/jdk/src/share/classes/javax/swing/text/ComponentView.java +++ b/jdk/src/share/classes/javax/swing/text/ComponentView.java @@ -27,6 +27,7 @@ package javax.swing.text; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; +import java.util.Set; import javax.swing.SwingUtilities; import javax.swing.event.*; @@ -434,7 +435,7 @@ public class ComponentView extends View { /** * Shows or hides this component depending on the value of parameter * b. - * @param b If true, shows this component; + * @param b If true, shows this component; * otherwise, hides this component. * @see #isVisible * @since JDK1.1 @@ -480,7 +481,7 @@ public class ComponentView extends View { return yalign; } - public java.util.Set getFocusTraversalKeys(int id) { + public Set getFocusTraversalKeys(int id) { return KeyboardFocusManager.getCurrentKeyboardFocusManager(). getDefaultFocusTraversalKeys(id); } diff --git a/jdk/src/share/classes/javax/swing/text/DefaultCaret.java b/jdk/src/share/classes/javax/swing/text/DefaultCaret.java index 22ec280ba09..e0e15681188 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultCaret.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultCaret.java @@ -774,8 +774,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } /** @@ -1330,7 +1329,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou if (this.dot != this.mark && component != null) { Clipboard clip = getSystemSelection(); if (clip != null) { - String selectedText = null; + String selectedText; if (component instanceof JPasswordField && component.getClientProperty("JPasswordField.cutCopyAllowed") != Boolean.TRUE) { diff --git a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java index 79419047273..51dab601ca1 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java @@ -68,7 +68,7 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter private boolean commitOnEdit; /** Class used to create new instances. */ - private Class valueClass; + private Class valueClass; /** NavigationFilter that forwards calls back to DefaultFormatter. */ private NavigationFilter navigationFilter; @@ -231,7 +231,7 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter * @return Object representation of text */ public Object stringToValue(String string) throws ParseException { - Class vc = getValueClass(); + Class vc = getValueClass(); JFormattedTextField ftf = getFormattedTextField(); if (vc == null && ftf != null) { diff --git a/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java b/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java index 9e3202130d3..028b24c0ea6 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java @@ -56,7 +56,7 @@ public class DefaultHighlighter extends LayeredHighlighter { // PENDING(prinz) - should cull ranges not visible int len = highlights.size(); for (int i = 0; i < len; i++) { - HighlightInfo info = (HighlightInfo) highlights.elementAt(i); + HighlightInfo info = highlights.elementAt(i); if (!(info instanceof LayeredHighlightInfo)) { // Avoid allocing unless we need it. Rectangle a = component.getBounds(); @@ -66,7 +66,7 @@ public class DefaultHighlighter extends LayeredHighlighter { a.width -= insets.left + insets.right; a.height -= insets.top + insets.bottom; for (; i < len; i++) { - info = (HighlightInfo)highlights.elementAt(i); + info = highlights.elementAt(i); if (!(info instanceof LayeredHighlightInfo)) { Highlighter.HighlightPainter p = info.getPainter(); p.paint(g, info.getStartOffset(), info.getEndOffset(), @@ -159,7 +159,7 @@ public class DefaultHighlighter extends LayeredHighlighter { int p0 = -1; int p1 = -1; for (int i = 0; i < len; i++) { - HighlightInfo hi = (HighlightInfo)highlights.elementAt(i); + HighlightInfo hi = highlights.elementAt(i); if (hi instanceof LayeredHighlightInfo) { LayeredHighlightInfo info = (LayeredHighlightInfo)hi; minX = Math.min(minX, info.x); @@ -195,7 +195,7 @@ public class DefaultHighlighter extends LayeredHighlighter { int p0 = Integer.MAX_VALUE; int p1 = 0; for (int i = 0; i < len; i++) { - HighlightInfo info = (HighlightInfo) highlights.elementAt(i); + HighlightInfo info = highlights.elementAt(i); p0 = Math.min(p0, info.p0.getOffset()); p1 = Math.max(p1, info.p1.getOffset()); } @@ -282,7 +282,7 @@ public class DefaultHighlighter extends LayeredHighlighter { Shape viewBounds, JTextComponent editor, View view) { for (int counter = highlights.size() - 1; counter >= 0; counter--) { - Object tag = highlights.elementAt(counter); + HighlightInfo tag = highlights.elementAt(counter); if (tag instanceof LayeredHighlightInfo) { LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag; int start = lhi.getStartOffset(); @@ -333,7 +333,7 @@ public class DefaultHighlighter extends LayeredHighlighter { private final static Highlighter.Highlight[] noHighlights = new Highlighter.Highlight[0]; - private Vector highlights = new Vector(); // Vector + private Vector highlights = new Vector(); private JTextComponent component; private boolean drawsLayeredHighlights; private SafeDamager safeDamager = new SafeDamager(); @@ -573,8 +573,8 @@ public class DefaultHighlighter extends LayeredHighlighter { * call. */ class SafeDamager implements Runnable { - private Vector p0 = new Vector(10); - private Vector p1 = new Vector(10); + private Vector p0 = new Vector(10); + private Vector p1 = new Vector(10); private Document lastDoc = null; /** @@ -589,8 +589,8 @@ public class DefaultHighlighter extends LayeredHighlighter { int len = p0.size(); for (int i = 0; i < len; i++){ mapper.damageRange(component, - ((Position)p0.get(i)).getOffset(), - ((Position)p1.get(i)).getOffset()); + p0.get(i).getOffset(), + p1.get(i).getOffset()); } } } diff --git a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java index 4939a7615c3..d3ba5d98df8 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java @@ -84,7 +84,7 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc */ public DefaultStyledDocument(Content c, StyleContext styles) { super(c, styles); - listeningStyles = new Vector(); + listeningStyles = new Vector is received. */ - private java.util.List _stateInfos; + private List _stateInfos; /** * Current style. @@ -151,7 +152,7 @@ class SynthParser extends HandlerBase { /** * Bindings for the current InputMap */ - private java.util.List _inputMapBindings; + private List _inputMapBindings; /** * ID for the input map. This is cached as @@ -177,30 +178,30 @@ class SynthParser extends HandlerBase { /** * List of ColorTypes. This is populated in startColorType. */ - private java.util.List _colorTypes; + private List _colorTypes; /** * defaultsPropertys are placed here. */ - private Map _defaultsMap; + private Map _defaultsMap; /** * List of SynthStyle.Painters that will be applied to the current style. */ - private java.util.List _stylePainters; + private List _stylePainters; /** * List of SynthStyle.Painters that will be applied to the current state. */ - private java.util.List _statePainters; + private List _statePainters; SynthParser() { _mapping = new HashMap(); - _stateInfos = new ArrayList(); - _colorTypes = new ArrayList(); - _inputMapBindings = new ArrayList(); - _stylePainters = new ArrayList(); - _statePainters = new ArrayList(); + _stateInfos = new ArrayList(); + _colorTypes = new ArrayList(); + _inputMapBindings = new ArrayList(); + _stylePainters = new ArrayList(); + _statePainters = new ArrayList(); } /** @@ -219,7 +220,7 @@ class SynthParser extends HandlerBase { public void parse(InputStream inputStream, DefaultSynthStyleFactory factory, URL urlResourceBase, Class classResourceBase, - Map defaultsMap) + Map defaultsMap) throws ParseException, IllegalArgumentException { if (inputStream == null || factory == null || (urlResourceBase == null && classResourceBase == null)) { @@ -333,7 +334,7 @@ class SynthParser extends HandlerBase { * type type, this will throw an exception. */ private Object lookup(String key, Class type) throws SAXException { - Object value = null; + Object value; if (_handler != null) { if ((value = _handler.lookup(key)) != null) { return checkCast(value, type); @@ -423,15 +424,12 @@ class SynthParser extends HandlerBase { private void endStyle() throws SAXException { int size = _stylePainters.size(); if (size > 0) { - _style.setPainters((ParsedSynthStyle.PainterInfo[]) - _stylePainters.toArray(new ParsedSynthStyle. - PainterInfo[size])); + _style.setPainters(_stylePainters.toArray(new ParsedSynthStyle.PainterInfo[size])); _stylePainters.clear(); } size = _stateInfos.size(); if (size > 0) { - _style.setStateInfo((ParsedSynthStyle.StateInfo[])_stateInfos. - toArray(new ParsedSynthStyle.StateInfo[size])); + _style.setStateInfo(_stateInfos.toArray(new ParsedSynthStyle.StateInfo[size])); _stateInfos.clear(); } _style = null; @@ -501,9 +499,7 @@ class SynthParser extends HandlerBase { private void endState() throws SAXException { int size = _statePainters.size(); if (size > 0) { - _stateInfo.setPainters((ParsedSynthStyle.PainterInfo[]) - _statePainters.toArray(new ParsedSynthStyle. - PainterInfo[size])); + _stateInfo.setPainters(_statePainters.toArray(new ParsedSynthStyle.PainterInfo[size])); _statePainters.clear(); } _stateInfo = null; @@ -684,8 +680,7 @@ class SynthParser extends HandlerBase { int max = 0; for (int counter = _colorTypes.size() - 1; counter >= 0; counter--) { - max = Math.max(max, ((ColorType)_colorTypes.get(counter)). - getID()); + max = Math.max(max, _colorTypes.get(counter).getID()); } if (colors == null || colors.length <= max) { Color[] newColors = new Color[max + 1]; @@ -696,7 +691,7 @@ class SynthParser extends HandlerBase { } for (int counter = _colorTypes.size() - 1; counter >= 0; counter--) { - colors[((ColorType)_colorTypes.get(counter)).getID()] = color; + colors[_colorTypes.get(counter).getID()] = color; } _stateInfo.setColors(colors); } @@ -705,7 +700,7 @@ class SynthParser extends HandlerBase { private void startProperty(AttributeList attributes, Object property) throws SAXException { Object value = null; - Object key = null; + String key = null; // Type of the value: 0=idref, 1=boolean, 2=dimension, 3=insets, // 4=integer,5=string int iType = 0; @@ -1027,7 +1022,7 @@ class SynthParser extends HandlerBase { } } - private void addPainterOrMerge(java.util.List painters, String method, + private void addPainterOrMerge(List painters, String method, SynthPainter painter, int direction) { ParsedSynthStyle.PainterInfo painterInfo; painterInfo = new ParsedSynthStyle.PainterInfo(method, diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java index ddbc7ae7e69..21466d96093 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java @@ -48,13 +48,13 @@ class SynthSplitPaneUI extends BasicSplitPaneUI implements * Keys to use for forward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusForwardTraversalKeys; + private static Set managingFocusForwardTraversalKeys; /** * Keys to use for backward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusBackwardTraversalKeys; + private static Set managingFocusBackwardTraversalKeys; /** * Style for the JSplitPane. @@ -96,7 +96,7 @@ class SynthSplitPaneUI extends BasicSplitPaneUI implements // focus forward traversal key if (managingFocusForwardTraversalKeys==null) { - managingFocusForwardTraversalKeys = new HashSet(); + managingFocusForwardTraversalKeys = new HashSet(); managingFocusForwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); } @@ -104,7 +104,7 @@ class SynthSplitPaneUI extends BasicSplitPaneUI implements managingFocusForwardTraversalKeys); // focus backward traversal key if (managingFocusBackwardTraversalKeys==null) { - managingFocusBackwardTraversalKeys = new HashSet(); + managingFocusBackwardTraversalKeys = new HashSet(); managingFocusBackwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java index c9475f91b54..ab9e42b41e5 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java @@ -53,7 +53,7 @@ public abstract class SynthStyle { /** * Contains the default values for certain properties. */ - private static Map DEFAULT_VALUES; + private static Map DEFAULT_VALUES; /** * Shared SynthGraphics. @@ -715,7 +715,7 @@ public abstract class SynthStyle { private static Object getDefaultValue(Object key) { synchronized(SynthStyle.class) { if (DEFAULT_VALUES == null) { - DEFAULT_VALUES = new HashMap(); + DEFAULT_VALUES = new HashMap(); populateDefaultValues(); } Object value = DEFAULT_VALUES.get(key); diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java index f52d3a68b0d..d07c4d5ad88 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java @@ -66,7 +66,7 @@ class SynthTextAreaUI extends BasicTextAreaUI implements SynthUI { protected void installDefaults() { // Installs the text cursor on the component super.installDefaults(); - updateStyle((JTextComponent)getComponent()); + updateStyle(getComponent()); } protected void uninstallDefaults() { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java index 5b7cbd0a5f5..28bbdf843c4 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java @@ -232,7 +232,7 @@ class SynthTextFieldUI protected void installDefaults() { // Installs the text cursor on the component super.installDefaults(); - updateStyle((JTextComponent)getComponent()); + updateStyle(getComponent()); getComponent().addFocusListener(this); } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java index 1e12a820ece..464b947b071 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java @@ -390,7 +390,7 @@ class SynthTreeUI extends BasicTreeUI implements PropertyChangeListener, } private Rectangle getDropLineRect(JTree.DropLocation loc) { - Rectangle rect = null; + Rectangle rect; TreePath path = loc.getPath(); int index = loc.getChildIndex(); boolean ltr = tree.getComponentOrientation().isLeftToRight(); @@ -523,7 +523,7 @@ class SynthTreeUI extends BasicTreeUI implements PropertyChangeListener, // Don't paint the renderer if editing this row. boolean selected = tree.isRowSelected(row); - JTree.DropLocation dropLocation = (JTree.DropLocation)tree.getDropLocation(); + JTree.DropLocation dropLocation = tree.getDropLocation(); boolean isDrop = dropLocation != null && dropLocation.getChildIndex() == -1 && path == dropLocation.getPath(); diff --git a/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java b/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java index de209df68eb..f66692e5778 100644 --- a/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java +++ b/jdk/src/share/classes/sun/swing/plaf/synth/DefaultSynthStyle.java @@ -44,7 +44,7 @@ import javax.swing.plaf.*; * @author Scott Violet */ public class DefaultSynthStyle extends SynthStyle implements Cloneable { - private static final Object PENDING = new String("Pending"); + private static final String PENDING = "Pending"; /** * Should the component be opaque? @@ -690,8 +690,8 @@ public class DefaultSynthStyle extends SynthStyle implements Cloneable { StateInfo[] states = getStateInfo(); if (states != null) { buf.append("states["); - for (int i = 0; i < states.length; i++) { - buf.append(states[i].toString()).append(','); + for (StateInfo state : states) { + buf.append(state.toString()).append(','); } buf.append(']').append(','); } @@ -888,7 +888,7 @@ public class DefaultSynthStyle extends SynthStyle implements Cloneable { * Returns the number of states that are similar between the * ComponentState this StateInfo represents and val. */ - private final int getMatchCount(int val) { + private int getMatchCount(int val) { // This comes from BigInteger.bitCnt val &= state; val -= (0xaaaaaaaa & val) >>> 1; diff --git a/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java b/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java index abd99439ed0..2721764d1d7 100644 --- a/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java +++ b/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java @@ -735,7 +735,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { * Data model for a type-face selection combo-box. */ protected class DirectoryComboBoxModel extends AbstractListModel implements ComboBoxModel { - Vector directories = new Vector(); + Vector directories = new Vector(); int[] depths = null; File selectedDirectory = null; JFileChooser chooser = getFileChooser(); @@ -778,7 +778,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { // Get the canonical (full) path. This has the side // benefit of removing extraneous chars from the path, // for example /foo/bar/ becomes /foo/bar - File canonical = null; + File canonical; try { canonical = directory.getCanonicalFile(); } catch (IOException e) { @@ -791,7 +791,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { File sf = useShellFolder ? ShellFolder.getShellFolder(canonical) : canonical; File f = sf; - Vector path = new Vector(10); + Vector path = new Vector(10); do { path.addElement(f); } while ((f = f.getParentFile()) != null); @@ -799,7 +799,7 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { int pathCount = path.size(); // Insert chain at appropriate place in vector for (int i = 0; i < pathCount; i++) { - f = (File)path.get(i); + f = path.get(i); if (directories.contains(f)) { int topIndex = directories.indexOf(f); for (int j = i-1; j >= 0; j--) { @@ -818,12 +818,12 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { private void calculateDepths() { depths = new int[directories.size()]; for (int i = 0; i < depths.length; i++) { - File dir = (File)directories.get(i); + File dir = directories.get(i); File parent = dir.getParentFile(); depths[i] = 0; if (parent != null) { for (int j = i-1; j >= 0; j--) { - if (parent.equals((File)directories.get(j))) { + if (parent.equals(directories.get(j))) { depths[i] = depths[j] + 1; break; } @@ -940,8 +940,8 @@ public class SynthFileChooserUIImpl extends SynthFileChooserUI { FileFilter currentFilter = getFileChooser().getFileFilter(); boolean found = false; if(currentFilter != null) { - for(int i=0; i < filters.length; i++) { - if(filters[i] == currentFilter) { + for (FileFilter filter : filters) { + if (filter == currentFilter) { found = true; } } From f7be937495c26e171cca46739ba26ac275468eb6 Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Fri, 25 Jul 2008 11:32:12 -0400 Subject: [PATCH 062/325] 6608456: need API to define RepaintManager per components hierarchy Reviewed-by: alexp --- jdk/make/javax/swing/Makefile | 2 +- .../com/sun/java/swing/SwingUtilities3.java | 91 ++++++++++ .../classes/javax/swing/RepaintManager.java | 51 ++++++ .../RepaintManager/6608456/bug6608456.java | 162 ++++++++++++++++++ 4 files changed, 305 insertions(+), 1 deletion(-) create mode 100644 jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java create mode 100644 jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java diff --git a/jdk/make/javax/swing/Makefile b/jdk/make/javax/swing/Makefile index c2056a45ce2..e112e609cd9 100644 --- a/jdk/make/javax/swing/Makefile +++ b/jdk/make/javax/swing/Makefile @@ -33,7 +33,7 @@ include $(BUILDDIR)/common/Defs.gmk # Files # include FILES.gmk -AUTO_FILES_JAVA_DIRS = javax/swing sun/swing +AUTO_FILES_JAVA_DIRS = javax/swing sun/swing com/sun/java/swing AUTO_JAVA_PRUNE = plaf SUBDIRS = html32dtd plaf diff --git a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java new file mode 100644 index 00000000000..2ace1e4ce77 --- /dev/null +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -0,0 +1,91 @@ +/* + * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package com.sun.java.swing; + +import sun.awt.AppContext; +import java.awt.Component; +import javax.swing.JComponent; +import javax.swing.RepaintManager; + +/** + * A collection of utility methods for Swing. + *

+ * WARNING: While this class is public, it should not be treated as + * public API and its API may change in incompatable ways between dot dot + * releases and even patch releases. You should not rely on this class even + * existing. + * + * This is a second part of sun.swing.SwingUtilities2. It is required + * to provide services for JavaFX applets. + * + */ +public class SwingUtilities3 { + /** + * The {@code clientProperty} key for delegate {@code RepaintManager} + */ + private static final Object DELEGATE_REPAINT_MANAGER_KEY = + new StringBuilder("DelegateRepaintManagerKey"); + + /** + * Registers delegate RepaintManager for {@code JComponent}. + */ + public static void setDelegateRepaintManager(JComponent component, + RepaintManager repaintManager) { + /* setting up flag in AppContext to speed up lookups in case + * there are no delegate RepaintManagers used. + */ + AppContext.getAppContext().put(DELEGATE_REPAINT_MANAGER_KEY, + Boolean.TRUE); + + component.putClientProperty(DELEGATE_REPAINT_MANAGER_KEY, + repaintManager); + } + + /** + * Returns delegate {@code RepaintManager} for {@code component} hierarchy. + */ + public static RepaintManager getDelegateRepaintManager(Component + component) { + RepaintManager delegate = null; + if (Boolean.TRUE == AppContext.getAppContext().get( + DELEGATE_REPAINT_MANAGER_KEY)) { + while (delegate == null && component != null) { + while (component != null + && ! (component instanceof JComponent)) { + component = component.getParent(); + } + if (component != null) { + delegate = (RepaintManager) + ((JComponent) component) + .getClientProperty(DELEGATE_REPAINT_MANAGER_KEY); + component = component.getParent(); + } + + } + } + return delegate; + } +} diff --git a/jdk/src/share/classes/javax/swing/RepaintManager.java b/jdk/src/share/classes/javax/swing/RepaintManager.java index 91034dbf8f2..81c81602255 100644 --- a/jdk/src/share/classes/javax/swing/RepaintManager.java +++ b/jdk/src/share/classes/javax/swing/RepaintManager.java @@ -40,6 +40,8 @@ import sun.awt.SunToolkit; import sun.java2d.SunGraphicsEnvironment; import sun.security.action.GetPropertyAction; +import com.sun.java.swing.SwingUtilities3; + /** * This class manages repaint requests, allowing the number @@ -303,6 +305,11 @@ public class RepaintManager */ public synchronized void addInvalidComponent(JComponent invalidComponent) { + RepaintManager delegate = getDelegate(invalidComponent); + if (delegate != null) { + delegate.addInvalidComponent(invalidComponent); + return; + } Component validateRoot = null; /* Find the first JComponent ancestor of this component whose @@ -373,6 +380,11 @@ public class RepaintManager * @see #addInvalidComponent */ public synchronized void removeInvalidComponent(JComponent component) { + RepaintManager delegate = getDelegate(component); + if (delegate != null) { + delegate.removeInvalidComponent(component); + return; + } if(invalidComponents != null) { int index = invalidComponents.indexOf(component); if(index != -1) { @@ -464,6 +476,11 @@ public class RepaintManager */ public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { + RepaintManager delegate = getDelegate(c); + if (delegate != null) { + delegate.addDirtyRegion(c, x, y, w, h); + return; + } addDirtyRegion0(c, x, y, w, h); } @@ -588,6 +605,10 @@ public class RepaintManager * dirty. */ public Rectangle getDirtyRegion(JComponent aComponent) { + RepaintManager delegate = getDelegate(aComponent); + if (delegate != null) { + return delegate.getDirtyRegion(aComponent); + } Rectangle r = null; synchronized(this) { r = (Rectangle)dirtyComponents.get(aComponent); @@ -603,6 +624,11 @@ public class RepaintManager * completely painted during the next paintDirtyRegions() call. */ public void markCompletelyDirty(JComponent aComponent) { + RepaintManager delegate = getDelegate(aComponent); + if (delegate != null) { + delegate.markCompletelyDirty(aComponent); + return; + } addDirtyRegion(aComponent,0,0,Integer.MAX_VALUE,Integer.MAX_VALUE); } @@ -611,6 +637,11 @@ public class RepaintManager * get painted during the next paintDirtyRegions() call. */ public void markCompletelyClean(JComponent aComponent) { + RepaintManager delegate = getDelegate(aComponent); + if (delegate != null) { + delegate.markCompletelyClean(aComponent); + return; + } synchronized(this) { dirtyComponents.remove(aComponent); } @@ -623,6 +654,10 @@ public class RepaintManager * if it return true. */ public boolean isCompletelyDirty(JComponent aComponent) { + RepaintManager delegate = getDelegate(aComponent); + if (delegate != null) { + return delegate.isCompletelyDirty(aComponent); + } Rectangle r; r = getDirtyRegion(aComponent); @@ -900,6 +935,10 @@ public class RepaintManager * repaint manager. */ public Image getOffscreenBuffer(Component c,int proposedWidth,int proposedHeight) { + RepaintManager delegate = getDelegate(c); + if (delegate != null) { + return delegate.getOffscreenBuffer(c, proposedWidth, proposedHeight); + } return _getOffscreenBuffer(c, proposedWidth, proposedHeight); } @@ -917,6 +956,11 @@ public class RepaintManager */ public Image getVolatileOffscreenBuffer(Component c, int proposedWidth,int proposedHeight) { + RepaintManager delegate = getDelegate(c); + if (delegate != null) { + return delegate.getVolatileOffscreenBuffer(c, proposedWidth, + proposedHeight); + } GraphicsConfiguration config = c.getGraphicsConfiguration(); if (config == null) { config = GraphicsEnvironment.getLocalGraphicsEnvironment(). @@ -1550,4 +1594,11 @@ public class RepaintManager prePaintDirtyRegions(); } } + private RepaintManager getDelegate(Component c) { + RepaintManager delegate = SwingUtilities3.getDelegateRepaintManager(c); + if (this == delegate) { + delegate = null; + } + return delegate; + } } diff --git a/jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java b/jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java new file mode 100644 index 00000000000..1d8a14fcaa2 --- /dev/null +++ b/jdk/test/javax/swing/RepaintManager/6608456/bug6608456.java @@ -0,0 +1,162 @@ +/* + * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * + * @bug 6608456 + * @author Igor Kushnirskiy + * @summary tests if delegate RepaintManager gets invoked. + */ + +import java.awt.*; +import java.lang.reflect.Method; +import java.util.concurrent.Callable; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; + +import javax.swing.JComponent; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.RepaintManager; +import javax.swing.SwingUtilities; + + + +public class bug6608456 { + private static final TestFuture testFuture = new TestFuture(); + public static void main(String[] args) throws Exception { + final JComponent component = invokeAndWait( + new Callable() { + public JComponent call() throws Exception { + RepaintManager.setCurrentManager(new TestRepaintManager()); + JFrame frame = new JFrame("test"); + frame.setLayout(new FlowLayout()); + JButton button = new JButton("default"); + + frame.add(button); + button = new JButton("delegate"); + if ( ! registerDelegate( + button, new TestRepaintManager())) { + return null; + } + frame.add(button); + frame.pack(); + frame.setVisible(true); + return button; + } + }); + if (component == null) { + throw new RuntimeException("failed. can not register delegate"); + } + blockTillDisplayed(component); + // trigger repaint for delegate RepaintManager + invokeAndWait( + new Callable() { + public Void call() { + component.repaint(); + return null; + } + }); + try { + if (testFuture.get(10, TimeUnit.SECONDS)) { + // passed + } + } catch (Exception e) { + throw new RuntimeException("failed", e); + } finally { + JFrame frame = (JFrame) SwingUtilities + .getAncestorOfClass(JFrame.class, component); + if (frame != null) { + frame.dispose(); + } + } + } + static class TestRepaintManager extends RepaintManager { + @Override + public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { + if (RepaintManager.currentManager(c) == this) { + testFuture.defaultCalled(); + } else { + testFuture.delegateCalled(); + } + super.addDirtyRegion(c, x, y, w, h); + } + } + static class TestFuture extends FutureTask { + private volatile boolean defaultCalled = false; + private volatile boolean delegateCalled = false; + public TestFuture() { + super(new Callable() { + public Boolean call() { + return null; + } + }); + } + public void defaultCalled() { + defaultCalled = true; + updateState(); + } + public void delegateCalled() { + delegateCalled = true; + updateState(); + } + private void updateState() { + if (defaultCalled && delegateCalled) { + set(Boolean.TRUE); + } + } + } + + private static boolean registerDelegate(JComponent c, + RepaintManager repaintManager) { + boolean rv = false; + try { + Class clazz = Class.forName("com.sun.java.swing.SwingUtilities3"); + Method method = clazz.getMethod("setDelegateRepaintManager", + JComponent.class, RepaintManager.class); + method.invoke(clazz, c, repaintManager); + rv = true; + } catch (Exception ignore) { + } + return rv; + } + static T invokeAndWait(Callable callable) throws Exception { + FutureTask future = new FutureTask(callable); + SwingUtilities.invokeLater(future); + return future.get(); + } + + public static void blockTillDisplayed(Component comp) { + Point p = null; + while (p == null) { + try { + p = comp.getLocationOnScreen(); + } catch (IllegalStateException e) { + try { + Thread.sleep(100); + } catch (InterruptedException ie) { + } + } + } + } +} From 97c80b8c8476d3499583fdeb1d2dd69fc1d15f81 Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Fri, 25 Jul 2008 09:07:29 -0700 Subject: [PATCH 063/325] 6717457: Internal Error (src/share/vm/code/relocInfo.hpp:1089) Reviewed-by: kvn --- hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp | 6 +++--- hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp | 10 +++++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp index 9d17fce5ff3..058c230282f 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp @@ -779,9 +779,9 @@ class StubGenerator: public StubCodeGenerator { __ shrl(end, CardTableModRefBS::card_shift); __ subl(end, start); // end --> count __ BIND(L_loop); - ExternalAddress base((address)ct->byte_map_base); - Address index(start, count, Address::times_1, 0); - __ movbyte(ArrayAddress(base, index), 0); + intptr_t disp = (intptr_t) ct->byte_map_base; + Address cardtable(start, count, Address::times_1, disp); + __ movb(cardtable, 0); __ decrement(count); __ jcc(Assembler::greaterEqual, L_loop); } diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp index 68188361b50..c3b61d5bf76 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp @@ -1222,8 +1222,16 @@ class StubGenerator: public StubCodeGenerator { __ shrq(end, CardTableModRefBS::card_shift); __ subq(end, start); // number of bytes to copy + intptr_t disp = (intptr_t) ct->byte_map_base; + if (__ is_simm32(disp)) { + Address cardtable(noreg, noreg, Address::no_scale, disp); + __ lea(scratch, cardtable); + } else { + ExternalAddress cardtable((address)disp); + __ lea(scratch, cardtable); + } + const Register count = end; // 'end' register contains bytes count now - __ lea(scratch, ExternalAddress((address)ct->byte_map_base)); __ addq(start, scratch); __ BIND(L_loop); __ movb(Address(start, count, Address::times_1), 0); From 873a9176c75501f08faca765df10ef6b4f8879a5 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Fri, 25 Jul 2008 21:00:05 +0400 Subject: [PATCH 064/325] 6630275: The spec on VetoableChangeSupport.fireVetoableChange should be updated Reviewed-by: peterz, rupashka --- .../java/beans/PropertyChangeSupport.java | 195 ++++++++-------- .../java/beans/VetoableChangeSupport.java | 215 ++++++++++-------- .../VetoableChangeSupport/Test6630275.java | 81 +++++++ 3 files changed, 293 insertions(+), 198 deletions(-) create mode 100644 jdk/test/java/beans/VetoableChangeSupport/Test6630275.java diff --git a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java index 2d4ed88fdb3..2a3f79ff3f2 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -208,91 +208,91 @@ public class PropertyChangeSupport implements Serializable { } /** - * Report a bound property update to any registered listeners. - * No event is fired if old and new are equal and non-null. - * + * Reports a bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal and non-null. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes {@code - * PropertyChangeEvent} value. + * {@link #firePropertyChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - Object oldValue, Object newValue) { - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + firePropertyChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue)); } - firePropertyChange(new PropertyChangeEvent(source, propertyName, - oldValue, newValue)); } /** - * Report an int bound property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports an integer bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes Object values. + * {@link #firePropertyChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - int oldValue, int newValue) { - if (oldValue == newValue) { - return; + public void firePropertyChange(String propertyName, int oldValue, int newValue) { + if (oldValue != newValue) { + firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** - * Report a boolean bound property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports a boolean bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes Object values. + * {@link #firePropertyChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - boolean oldValue, boolean newValue) { - if (oldValue == newValue) { - return; + public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { + if (oldValue != newValue) { + firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** - * Fire an existing PropertyChangeEvent to any registered listeners. - * No event is fired if the given event's old and new values are - * equal and non-null. - * @param evt The PropertyChangeEvent object. + * Fires a property change event to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if the given event's old and new values are equal and non-null. + * + * @param event the {@code PropertyChangeEvent} to be fired */ - public void firePropertyChange(PropertyChangeEvent evt) { - Object oldValue = evt.getOldValue(); - Object newValue = evt.getNewValue(); - String propertyName = evt.getPropertyName(); - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; - } - PropertyChangeListener[] common = this.map.get(null); - PropertyChangeListener[] named = (propertyName != null) - ? this.map.get(propertyName) - : null; + public void firePropertyChange(PropertyChangeEvent event) { + Object oldValue = event.getOldValue(); + Object newValue = event.getNewValue(); + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + String name = event.getPropertyName(); - fire(common, evt); - fire(named, evt); + PropertyChangeListener[] common = this.map.get(null); + PropertyChangeListener[] named = (name != null) + ? this.map.get(name) + : null; + + fire(common, event); + fire(named, event); + } } - private void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) { + private static void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) { if (listeners != null) { for (PropertyChangeListener listener : listeners) { listener.propertyChange(event); @@ -301,78 +301,69 @@ public class PropertyChangeSupport implements Serializable { } /** - * Report a bound indexed property update to any registered - * listeners. + * Reports a bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new values are equal - * and non-null. - * + * No event is fired if old and new values are equal and non-null. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes {@code PropertyChangeEvent} value. + * {@link #firePropertyChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - Object oldValue, Object newValue) { - firePropertyChange(new IndexedPropertyChangeEvent - (source, propertyName, oldValue, newValue, index)); + public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + firePropertyChange(new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index)); + } } /** - * Report an int bound indexed property update to any registered - * listeners. + * Reports an integer bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

* No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireIndexedPropertyChange method which takes Object values. + * {@link #fireIndexedPropertyChange(String, int, Object, Object)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - int oldValue, int newValue) { - if (oldValue == newValue) { - return; + public void fireIndexedPropertyChange(String propertyName, int index, int oldValue, int newValue) { + if (oldValue != newValue) { + fireIndexedPropertyChange(propertyName, index, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - fireIndexedPropertyChange(propertyName, index, - Integer.valueOf(oldValue), - Integer.valueOf(newValue)); } /** - * Report a boolean bound indexed property update to any - * registered listeners. + * Reports a boolean bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

* No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireIndexedPropertyChange method which takes Object values. + * {@link #fireIndexedPropertyChange(String, int, Object, Object)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - boolean oldValue, boolean newValue) { - if (oldValue == newValue) { - return; + public void fireIndexedPropertyChange(String propertyName, int index, boolean oldValue, boolean newValue) { + if (oldValue != newValue) { + fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), - Boolean.valueOf(newValue)); } /** diff --git a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java index 7d1418e17d2..f6707b49f7f 100644 --- a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java +++ b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -208,126 +208,149 @@ public class VetoableChangeSupport implements Serializable { } /** - * Report a vetoable property update to any registered listeners. If - * anyone vetos the change, then fire a new event reverting everyone to - * the old value and then rethrow the PropertyVetoException. + * Reports a constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new are equal and non-null. - * - * @param propertyName The programmatic name of the property - * that is about to change.. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. - * @exception PropertyVetoException if the recipient wishes the property - * change to be rolled back. - */ - public void fireVetoableChange(String propertyName, - Object oldValue, Object newValue) - throws PropertyVetoException { - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; - } - PropertyChangeEvent evt = new PropertyChangeEvent(source, propertyName, - oldValue, newValue); - fireVetoableChange(evt); - } - - /** - * Report a int vetoable property update to any registered listeners. - * No event is fired if old and new are equal. + * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal and non-null. *

* This is merely a convenience wrapper around the more general - * fireVetoableChange method that takes Object values. + * {@link #fireVetoableChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property - * that is about to change. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(String propertyName, - int oldValue, int newValue) - throws PropertyVetoException { - if (oldValue == newValue) { - return; + public void fireVetoableChange(String propertyName, Object oldValue, Object newValue) + throws PropertyVetoException { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + fireVetoableChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue)); } - fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** - * Report a boolean vetoable property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports an integer constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireVetoableChange method that takes Object values. + * {@link #fireVetoableChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that is about to change. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(String propertyName, - boolean oldValue, boolean newValue) - throws PropertyVetoException { - if (oldValue == newValue) { - return; + public void fireVetoableChange(String propertyName, int oldValue, int newValue) + throws PropertyVetoException { + if (oldValue != newValue) { + fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** - * Fire a vetoable property update to any registered listeners. If - * anyone vetos the change, then fire a new event reverting everyone to - * the old value and then rethrow the PropertyVetoException. + * Reports a boolean constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new are equal and non-null. + * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal. + *

+ * This is merely a convenience wrapper around the more general + * {@link #fireVetoableChange(String, Object, Object)} method. * - * @param evt The PropertyChangeEvent to be fired. - * @exception PropertyVetoException if the recipient wishes the property - * change to be rolled back. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(PropertyChangeEvent evt) - throws PropertyVetoException { - - Object oldValue = evt.getOldValue(); - Object newValue = evt.getNewValue(); - String propertyName = evt.getPropertyName(); - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; + public void fireVetoableChange(String propertyName, boolean oldValue, boolean newValue) + throws PropertyVetoException { + if (oldValue != newValue) { + fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - VetoableChangeListener[] common = this.map.get(null); - VetoableChangeListener[] named = (propertyName != null) - ? this.map.get(propertyName) - : null; - fire(common, evt); - fire(named, evt); } - private void fire(VetoableChangeListener[] listeners, PropertyChangeEvent event) throws PropertyVetoException { - if (listeners != null) { - VetoableChangeListener current = null; - try { - for (VetoableChangeListener listener : listeners) { - current = listener; - listener.vetoableChange(event); - } - } catch (PropertyVetoException veto) { - // Create an event to revert everyone to the old value. - event = new PropertyChangeEvent( this.source, - event.getPropertyName(), - event.getNewValue(), - event.getOldValue() ); - for (VetoableChangeListener listener : listeners) { - if (current == listener) { - break; - } - try { - listener.vetoableChange(event); - } catch (PropertyVetoException ex) { - // We just ignore exceptions that occur during reversions. + /** + * Fires a property change event to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if the given event's old and new values are equal and non-null. + * + * @param event the {@code PropertyChangeEvent} to be fired + * @throws PropertyVetoException if one of listeners vetoes the property update + */ + public void fireVetoableChange(PropertyChangeEvent event) + throws PropertyVetoException { + Object oldValue = event.getOldValue(); + Object newValue = event.getNewValue(); + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + String name = event.getPropertyName(); + + VetoableChangeListener[] common = this.map.get(null); + VetoableChangeListener[] named = (name != null) + ? this.map.get(name) + : null; + + VetoableChangeListener[] listeners; + if (common == null) { + listeners = named; + } + else if (named == null) { + listeners = common; + } + else { + listeners = new VetoableChangeListener[common.length + named.length]; + System.arraycopy(common, 0, listeners, 0, common.length); + System.arraycopy(named, 0, listeners, common.length, named.length); + } + if (listeners != null) { + int current = 0; + try { + while (current < listeners.length) { + listeners[current].vetoableChange(event); + current++; } } - // And now rethrow the PropertyVetoException. - throw veto; + catch (PropertyVetoException veto) { + event = new PropertyChangeEvent(this.source, name, newValue, oldValue); + for (int i = 0; i < current; i++) { + try { + listeners[i].vetoableChange(event); + } + catch (PropertyVetoException exception) { + // ignore exceptions that occur during rolling back + } + } + throw veto; // rethrow the veto exception + } } } } diff --git a/jdk/test/java/beans/VetoableChangeSupport/Test6630275.java b/jdk/test/java/beans/VetoableChangeSupport/Test6630275.java new file mode 100644 index 00000000000..ce68720d809 --- /dev/null +++ b/jdk/test/java/beans/VetoableChangeSupport/Test6630275.java @@ -0,0 +1,81 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6630275 + * @summary Tests VetoableChangeSupport specification + * @author Sergey Malenkov + */ + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyVetoException; +import java.beans.VetoableChangeListener; +import java.beans.VetoableChangeSupport; + +public class Test6630275 { + private static final String PROPERTY = "property"; // NON-NLS: predefined property name + + public static void main(String[] args) { + CheckListener first = new CheckListener(false); + CheckListener second = new CheckListener(true); + CheckListener third = new CheckListener(false); + + VetoableChangeSupport vcs = new VetoableChangeSupport(Test6630275.class); + vcs.addVetoableChangeListener(first); + vcs.addVetoableChangeListener(PROPERTY, first); + vcs.addVetoableChangeListener(PROPERTY, second); + vcs.addVetoableChangeListener(PROPERTY, third); + try { + vcs.fireVetoableChange(PROPERTY, true, false); + } catch (PropertyVetoException exception) { + first.validate(); + second.validate(); + third.validate(); + return; // expected exception + } + throw new Error("exception should be thrown"); + } + + private static class CheckListener implements VetoableChangeListener { + private final boolean veto; + private boolean odd; // even/odd check for notification + + private CheckListener(boolean veto) { + this.veto = veto; + } + + private void validate() { + if (this.veto != this.odd) + throw new Error(this.odd + ? "undo event expected" + : "unexpected undo event"); + } + + public void vetoableChange(PropertyChangeEvent event) throws PropertyVetoException { + this.odd = !this.odd; + if (this.veto) + throw new PropertyVetoException("disable all changes", event); + } + } +} From b4ae1216b3d0441294a6485c7f36f8df48340b50 Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Fri, 25 Jul 2008 14:13:59 -0400 Subject: [PATCH 065/325] 6638195: need API for EventQueueDelegate Reviewed-by: bchristi --- .../com/sun/java/swing/SwingUtilities3.java | 83 +++++++++++ .../classes/java/awt/EventDispatchThread.java | 20 ++- .../classes/sun/awt/EventQueueDelegate.java | 71 +++++++++ .../awt/EventQueue/6638195/bug6638195.java | 138 ++++++++++++++++++ 4 files changed, 309 insertions(+), 3 deletions(-) create mode 100644 jdk/src/share/classes/sun/awt/EventQueueDelegate.java create mode 100644 jdk/test/java/awt/EventQueue/6638195/bug6638195.java diff --git a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java index 2ace1e4ce77..9268d7370a3 100644 --- a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -25,7 +25,12 @@ package com.sun.java.swing; +import sun.awt.EventQueueDelegate; import sun.awt.AppContext; +import java.util.Map; +import java.util.concurrent.Callable; +import java.awt.AWTEvent; +import java.awt.EventQueue; import java.awt.Component; import javax.swing.JComponent; import javax.swing.RepaintManager; @@ -88,4 +93,82 @@ public class SwingUtilities3 { } return delegate; } + + /* + * We use maps to avoid reflection. Hopefully it should perform better + * this way. + */ + public static void setEventQueueDelegate( + Map> map) { + EventQueueDelegate.setDelegate(new EventQueueDelegateFromMap(map)); + } + + private static class EventQueueDelegateFromMap + implements EventQueueDelegate.Delegate { + private final AWTEvent[] afterDispatchEventArgument; + private final Object[] afterDispatchHandleArgument; + private final Callable afterDispatchCallable; + + private final AWTEvent[] beforeDispatchEventArgument; + private final Callable beforeDispatchCallable; + + private final EventQueue[] getNextEventEventQueueArgument; + private final Callable getNextEventCallable; + + @SuppressWarnings("unchecked") + public EventQueueDelegateFromMap(Map> objectMap) { + Map methodMap = objectMap.get("afterDispatch"); + afterDispatchEventArgument = (AWTEvent[]) methodMap.get("event"); + afterDispatchHandleArgument = (Object[]) methodMap.get("handle"); + afterDispatchCallable = (Callable) methodMap.get("method"); + + methodMap = objectMap.get("beforeDispatch"); + beforeDispatchEventArgument = (AWTEvent[]) methodMap.get("event"); + beforeDispatchCallable = (Callable) methodMap.get("method"); + + methodMap = objectMap.get("getNextEvent"); + getNextEventEventQueueArgument = + (EventQueue[]) methodMap.get("eventQueue"); + getNextEventCallable = (Callable) methodMap.get("method"); + } + + @Override + public void afterDispatch(AWTEvent event, Object handle) { + afterDispatchEventArgument[0] = event; + afterDispatchHandleArgument[0] = handle; + try { + afterDispatchCallable.call(); + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + } + } + + @Override + public Object beforeDispatch(AWTEvent event) { + beforeDispatchEventArgument[0] = event; + try { + return beforeDispatchCallable.call(); + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + } + return null; + } + + @Override + public AWTEvent getNextEvent(EventQueue eventQueue) { + getNextEventEventQueueArgument[0] = eventQueue; + try { + return getNextEventCallable.call(); + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + } + return null; + } + } } diff --git a/jdk/src/share/classes/java/awt/EventDispatchThread.java b/jdk/src/share/classes/java/awt/EventDispatchThread.java index f49bacb670a..23d08a0d418 100644 --- a/jdk/src/share/classes/java/awt/EventDispatchThread.java +++ b/jdk/src/share/classes/java/awt/EventDispatchThread.java @@ -39,6 +39,7 @@ import java.util.Vector; import java.util.logging.*; import sun.awt.dnd.SunDragSourceContextPeer; +import sun.awt.EventQueueDelegate; /** * EventDispatchThread is a package-private AWT class which takes @@ -243,10 +244,16 @@ class EventDispatchThread extends Thread { try { AWTEvent event; boolean eventOK; + EventQueueDelegate.Delegate delegate = + EventQueueDelegate.getDelegate(); do { - event = (id == ANY_EVENT) - ? theQueue.getNextEvent() - : theQueue.getNextEvent(id); + if (delegate != null && id == ANY_EVENT) { + event = delegate.getNextEvent(theQueue); + } else { + event = (id == ANY_EVENT) + ? theQueue.getNextEvent() + : theQueue.getNextEvent(id); + } eventOK = true; synchronized (eventFilters) { @@ -272,7 +279,14 @@ class EventDispatchThread extends Thread { eventLog.log(Level.FINEST, "Dispatching: " + event); } + Object handle = null; + if (delegate != null) { + handle = delegate.beforeDispatch(event); + } theQueue.dispatchEvent(event); + if (delegate != null) { + delegate.afterDispatch(event, handle); + } return true; } catch (ThreadDeath death) { diff --git a/jdk/src/share/classes/sun/awt/EventQueueDelegate.java b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java new file mode 100644 index 00000000000..8f8a6f3fe0b --- /dev/null +++ b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java @@ -0,0 +1,71 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.awt; + +import java.awt.AWTEvent; +import java.awt.EventQueue; + + +public class EventQueueDelegate { + private static final Object EVENT_QUEUE_DELEGATE_KEY = + new StringBuilder("EventQueueDelegate.Delegate"); + + public static void setDelegate(Delegate delegate) { + AppContext.getAppContext().put(EVENT_QUEUE_DELEGATE_KEY, delegate); + } + public static Delegate getDelegate() { + return + (Delegate) AppContext.getAppContext().get(EVENT_QUEUE_DELEGATE_KEY); + } + public interface Delegate { + /** + * This method allows for changing {@code EventQueue} events order. + * + * @param eventQueue current {@code EventQueue} + * @return next {@code event} for the {@code EventDispatchThread} + */ + + public AWTEvent getNextEvent(EventQueue eventQueue) throws InterruptedException; + + /** + * Notifies delegate before EventQueue.dispatch method. + * + * Note: this method may mutate the event + * + * @param event to be dispatched by {@code dispatch} method + * @return handle to be passed to {@code afterDispatch} method + */ + public Object beforeDispatch(AWTEvent event); + + /** + * Notifies delegate after EventQueue.dispatch method. + * + * @param event {@code event} dispatched by the {@code dispatch} method + * @param handle object which came from {@code beforeDispatch} method + */ + public void afterDispatch(AWTEvent event, Object handle); + } +} diff --git a/jdk/test/java/awt/EventQueue/6638195/bug6638195.java b/jdk/test/java/awt/EventQueue/6638195/bug6638195.java new file mode 100644 index 00000000000..b1109967071 --- /dev/null +++ b/jdk/test/java/awt/EventQueue/6638195/bug6638195.java @@ -0,0 +1,138 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * + * @bug 6638195 + * @author Igor Kushnirskiy + * @summary tests if EventQueueDelegate.Delegate is invoked. + */ + +import sun.awt.EventQueueDelegate; +import com.sun.java.swing.SwingUtilities3; + +import java.util.*; +import java.util.concurrent.*; +import java.awt.*; + +public class bug6638195 { + public static void main(String[] args) throws Exception { + MyEventQueueDelegate delegate = new MyEventQueueDelegate(); + EventQueueDelegate.setDelegate(delegate); + runTest(delegate); + + delegate = new MyEventQueueDelegate(); + SwingUtilities3.setEventQueueDelegate(getObjectMap(delegate)); + runTest(delegate); + } + + private static void runTest(MyEventQueueDelegate delegate) throws Exception { + EventQueue.invokeLater( + new Runnable() { + public void run() { + } + }); + final CountDownLatch latch = new CountDownLatch(1); + EventQueue.invokeLater( + new Runnable() { + public void run() { + latch.countDown(); + } + }); + latch.await(); + if (! delegate.allInvoked()) { + throw new RuntimeException("failed"); + } + } + + static Map> getObjectMap( + final EventQueueDelegate.Delegate delegate) { + Map> objectMap = + new HashMap>(); + Map methodMap; + + final AWTEvent[] afterDispatchEventArgument = new AWTEvent[1]; + final Object[] afterDispatchHandleArgument = new Object[1]; + Callable afterDispatchCallable = + new Callable() { + public Void call() { + delegate.afterDispatch(afterDispatchEventArgument[0], + afterDispatchHandleArgument[0]); + return null; + } + }; + methodMap = new HashMap(); + methodMap.put("event", afterDispatchEventArgument); + methodMap.put("handle", afterDispatchHandleArgument); + methodMap.put("method", afterDispatchCallable); + objectMap.put("afterDispatch", methodMap); + + final AWTEvent[] beforeDispatchEventArgument = new AWTEvent[1]; + Callable beforeDispatchCallable = + new Callable() { + public Object call() { + return delegate.beforeDispatch( + beforeDispatchEventArgument[0]); + } + }; + methodMap = new HashMap(); + methodMap.put("event", beforeDispatchEventArgument); + methodMap.put("method", beforeDispatchCallable); + objectMap.put("beforeDispatch", methodMap); + + final EventQueue[] getNextEventEventQueueArgument = new EventQueue[1]; + Callable getNextEventCallable = + new Callable() { + public AWTEvent call() throws Exception { + return delegate.getNextEvent( + getNextEventEventQueueArgument[0]); + } + }; + methodMap = new HashMap(); + methodMap.put("eventQueue", getNextEventEventQueueArgument); + methodMap.put("method", getNextEventCallable); + objectMap.put("getNextEvent", methodMap); + + return objectMap; + } + static class MyEventQueueDelegate implements EventQueueDelegate.Delegate { + private volatile boolean getNextEventInvoked = false; + private volatile boolean beforeDispatchInvoked = false; + private volatile boolean afterDispatchInvoked = false; + public AWTEvent getNextEvent(EventQueue eventQueue) + throws InterruptedException { + getNextEventInvoked = true; + return eventQueue.getNextEvent(); + } + public Object beforeDispatch(AWTEvent event) { + beforeDispatchInvoked = true; + return null; + } + public void afterDispatch(AWTEvent event, Object handle) { + afterDispatchInvoked = true; + } + private boolean allInvoked() { + return getNextEventInvoked && beforeDispatchInvoked && afterDispatchInvoked; + } + } +} From 1dce4ceddd3c2e0a986e7e5fcdc46790ef8043fa Mon Sep 17 00:00:00 2001 From: Igor Kushnirskiy Date: Fri, 25 Jul 2008 14:26:27 -0400 Subject: [PATCH 066/325] 6699328: NullPointerException in EventQueue.dispatchEvent when applet is closed, only reprise/scenario applet Reviewed-by: bchristi --- .../com/sun/java/swing/SwingUtilities3.java | 32 +++++++++++-------- .../classes/sun/awt/EventQueueDelegate.java | 4 +-- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java index 9268d7370a3..28d9e8af6ec 100644 --- a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -133,42 +133,46 @@ public class SwingUtilities3 { } @Override - public void afterDispatch(AWTEvent event, Object handle) { + public void afterDispatch(AWTEvent event, Object handle) throws InterruptedException { afterDispatchEventArgument[0] = event; afterDispatchHandleArgument[0] = handle; try { afterDispatchCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } + throw new RuntimeException(e); } } @Override - public Object beforeDispatch(AWTEvent event) { + public Object beforeDispatch(AWTEvent event) throws InterruptedException { beforeDispatchEventArgument[0] = event; try { return beforeDispatchCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } + throw new RuntimeException(e); } - return null; } @Override - public AWTEvent getNextEvent(EventQueue eventQueue) { + public AWTEvent getNextEvent(EventQueue eventQueue) throws InterruptedException { getNextEventEventQueueArgument[0] = eventQueue; try { return getNextEventCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } + throw new RuntimeException(e); } - return null; } } } diff --git a/jdk/src/share/classes/sun/awt/EventQueueDelegate.java b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java index 8f8a6f3fe0b..c9d0a90d2af 100644 --- a/jdk/src/share/classes/sun/awt/EventQueueDelegate.java +++ b/jdk/src/share/classes/sun/awt/EventQueueDelegate.java @@ -58,7 +58,7 @@ public class EventQueueDelegate { * @param event to be dispatched by {@code dispatch} method * @return handle to be passed to {@code afterDispatch} method */ - public Object beforeDispatch(AWTEvent event); + public Object beforeDispatch(AWTEvent event) throws InterruptedException; /** * Notifies delegate after EventQueue.dispatch method. @@ -66,6 +66,6 @@ public class EventQueueDelegate { * @param event {@code event} dispatched by the {@code dispatch} method * @param handle object which came from {@code beforeDispatch} method */ - public void afterDispatch(AWTEvent event, Object handle); + public void afterDispatch(AWTEvent event, Object handle) throws InterruptedException; } } From 7b4a7f7bdc40568b99edf9ea7341d8e29d8a9d87 Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Fri, 25 Jul 2008 11:32:56 -0700 Subject: [PATCH 067/325] 6712835: Server compiler fails with assertion (loop_count < K,"infinite loop in PhaseIterGVN::transform") Reviewed-by: kvn --- hotspot/src/share/vm/ci/ciMethodBlocks.cpp | 2 +- .../src/share/vm/opto/idealGraphPrinter.cpp | 2 + hotspot/src/share/vm/opto/ifnode.cpp | 6 + .../test/compiler/6712835/Test6712835.java | 1578 +++++++++++++++++ 4 files changed, 1587 insertions(+), 1 deletion(-) create mode 100644 hotspot/test/compiler/6712835/Test6712835.java diff --git a/hotspot/src/share/vm/ci/ciMethodBlocks.cpp b/hotspot/src/share/vm/ci/ciMethodBlocks.cpp index 9bfba219b88..2810523f4fc 100644 --- a/hotspot/src/share/vm/ci/ciMethodBlocks.cpp +++ b/hotspot/src/share/vm/ci/ciMethodBlocks.cpp @@ -351,7 +351,7 @@ void ciBlock::set_exception_range(int start_bci, int limit_bci) { } #ifndef PRODUCT -static char *flagnames[] = { +static const char *flagnames[] = { "Processed", "Handler", "MayThrow", diff --git a/hotspot/src/share/vm/opto/idealGraphPrinter.cpp b/hotspot/src/share/vm/opto/idealGraphPrinter.cpp index 114a7ea17c7..de961127e68 100644 --- a/hotspot/src/share/vm/opto/idealGraphPrinter.cpp +++ b/hotspot/src/share/vm/opto/idealGraphPrinter.cpp @@ -473,10 +473,12 @@ void IdealGraphPrinter::visit_node(Node *n, void *param) { print_prop("is_dontcare", "false"); } +#ifdef ASSERT Node* old = C->matcher()->find_old_node(node); if (old != NULL) { print_prop("old_node_idx", old->_idx); } +#endif } if (node->is_Proj()) { diff --git a/hotspot/src/share/vm/opto/ifnode.cpp b/hotspot/src/share/vm/opto/ifnode.cpp index 073d4202f68..c6a76a853e1 100644 --- a/hotspot/src/share/vm/opto/ifnode.cpp +++ b/hotspot/src/share/vm/opto/ifnode.cpp @@ -725,6 +725,11 @@ static Node *remove_useless_bool(IfNode *iff, PhaseGVN *phase) { int true_path = phi->is_diamond_phi(); if( true_path == 0 ) return NULL; + // Make sure that iff and the control of the phi are different. This + // should really only happen for dead control flow since it requires + // an illegal cycle. + if (phi->in(0)->in(1)->in(0) == iff) return NULL; + // phi->region->if_proj->ifnode->bool->cmp BoolNode *bol2 = phi->in(0)->in(1)->in(0)->in(1)->as_Bool(); @@ -751,6 +756,7 @@ static Node *remove_useless_bool(IfNode *iff, PhaseGVN *phase) { } Node* new_bol = (flip ? phase->transform( bol2->negate(phase) ) : bol2); + assert(new_bol != iff->in(1), "must make progress"); iff->set_req(1, new_bol); // Intervening diamond probably goes dead phase->C->set_major_progress(); diff --git a/hotspot/test/compiler/6712835/Test6712835.java b/hotspot/test/compiler/6712835/Test6712835.java new file mode 100644 index 00000000000..2f1dbda198c --- /dev/null +++ b/hotspot/test/compiler/6712835/Test6712835.java @@ -0,0 +1,1578 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * @test + * @bug 6712835 + * @summary Server compiler fails with assertion (loop_count < K,"infinite loop in PhaseIterGVN::transform") + * @run main/othervm -Xcomp Test6712835 + */ + +/* Complexity upper bound: 349851 ops */ + +abstract class Tester_Class_0 { + boolean var_1 = true; + static double var_2; + float var_3 = 1.8301116E38F; + final String var_4 = "wck"; + final static short var_5 = 25624; + + + public Tester_Class_0() + { + var_2 = (byte)1.7374809293839066E308; + { + double var_18 = false ? 8027040614338917376L * var_3 + - (var_2 = var_5) : (var_3 += (char)4.491494085158084E307); + var_3 *= ~ ((byte)702579792) / 6600332715431236608L; + long var_19 = 0L; + var_18 -= 1759091496; + do + { + final long var_20 = (new long[(byte)(var_3 += + +1.6695243696502334E308)][(byte)((byte)1110410742 | ~var_19)])[var_1 & var_1 ? (byte)1047514041090199552L : (byte)var_5][(byte)(var_1 ? 123309551 : - ((byte)5932930312361050112L))]; + var_19++; + final short var_21 = var_5; + } while (var_19 < 1 && var_1 ^ var_3 == + ((byte)var_5)); + { + int var_22; + } + { + var_4.endsWith("o"); + } + int var_23 = 0; + var_1 &= (var_1 = true); + for (byte var_24 = 26; (var_1 = !var_1) && var_23 < 1; var_18 += var_1 ^ (var_1 |= false) ^ true ? var_24 : (byte)1504077779675035648L) + { + var_18 *= var_23; + var_23++; + float var_25; + (((new Tester_Class_0[var_24][var_24][var_24])[var_24])[var_24 >>= var_19][var_24 &= 6702582681202665472L]).var_3 *= var_5; + } + var_1 = (var_3 -= var_5) > (byte)func_2(1317089759, var_5, (byte)var_19) % (false & true ? 475183200 : 8947159119888251904L); + var_18 /= ~var_19 ^ ((byte)(var_18 %= (int)var_5) >= 6773554922270913536L ? (byte)var_5 : (byte)'u'); + var_3 = ~ ((byte)var_19); + } + double var_26 = 0; + var_1 &= (var_1 |= ! (var_1 |= true)); + while (var_26 < 1) + { + var_2 = 'e'; + var_26++; + var_1 ^= !true | 'j' * ((var_2 = 93384362) + var_5) <= var_5; + var_2 = true ? 2056852215 : var_5; + } + switch ((new char[(byte)var_3])[(byte)(short)var_4.charAt(438929928)] / (new byte[(byte)1779353916050551808L][(byte)+ ~8903539475459755008L])[(byte)836413337621087232L][(byte)784406244]) + { + case 101: + var_3 -= var_5; + break; + + case 'L': + + case 20: + final int var_27 = 2146473580; + break; + + case 18: + + default: + "mwh".substring((byte)(float)'A' % var_5, ']' | var_5 ^ ~ ((byte)'E')); + break; + + case 'H': + + } + var_3 = var_5; + long var_28; + var_28 = (var_1 = 'u' != (var_3 = var_1 ? 1384770002488557568L : ~ ~6691557565676772352L)) ? - ((byte)938410603) : var_5; + ((new Tester_Class_0[(byte)var_26])[(byte)'w']).var_3 = (byte)(short)'I'; + var_2 = (var_1 ^= "sfltwylm".startsWith("ytmeds")) ? 1837260339 * 434565574 : (new double[(byte)var_26])[(byte)var_3]; + } + + + + public boolean equals(Object obj) + { + var_2 = 785819716 / 'i'; + switch ((! (var_1 ^= var_1) ^ (! ((false | (var_1 |= var_1)) ^ !false) ? false : (var_1 |= !false)) ? var_1 : ! !var_1 ^ var_1) ? 1426689390 : var_5 * var_5) + { + case '`': + + case 89: + + case 13: + char var_9 = 'W'; + break; + + case 31: + + case 15: + + case 'm': + var_1 &= var_1; + break; + + case 'Z': + + case 34: + String[] var_10 = (new String[(byte)5534253842608756736L][(byte)'M'])[(byte)8717534666212195328L]; + break; + + case 124: + + } + var_3 += var_5; + var_1 |= (var_1 |= (var_1 = (var_1 |= var_5 >= (var_2 = (byte)var_3)))); + var_1 ^= (var_1 = var_4.endsWith(new String())); + var_2 = (var_3 %= 664966429); + { + var_4.lastIndexOf((int)('i' * (! !true & (true & !var_1) ? (byte)2.2562587635371023E307 : (byte)(var_3 %= var_3)) / var_3), 'P' % (false ? (byte)'N' : (byte)943393108)); + } + var_3 /= false | ! !var_1 ? (char)1.3721055E38F : '\\'; + if (var_1) + { + var_4.compareTo("uaqmqwg"); + } + else + { + var_1 ^= var_1 & (var_1 &= (var_1 ^= (var_1 ^= var_1))); + } + var_3 *= (new int[(byte)1980200282][(byte)'i'])[(byte)(var_2 = (byte)'O')][false ? (byte)2.4739911E38F : (byte)- ((byte)1.6045903096088714E308)]; + var_1 = var_5 != (byte)var_5 & (1.5002759009669559E308 < (byte)5110733568033040384L ^ (var_1 ? (var_1 ^= true) : var_1)); + long var_11; + return (var_2 = (byte)'B') < 550125954; + } + + + public static char func_0(final int arg_0, long[] arg_1, final boolean arg_2) + { + var_2 = (short)(false ? (byte)1.2577737E38F : (byte)'t'); + "xdf".codePointBefore((!arg_2 ? (byte)1426638765 : (byte)541094055) * ((byte)var_5 / var_5)); + ((new Tester_Class_0[(byte)(short)(var_2 = 'A')])[(byte)arg_0]).var_3 = 7823141134226481152L; + ((new Tester_Class_0[(byte)- ~1368497135389664256L])[!false || true ? (byte)2.5393905E38F : (byte)2.4415902E38F]).var_3 -= (int)(false ? (byte)var_5 : (byte)"musnlk".charAt(785792957)); + ((new Tester_Class_0[(byte)357672172])[(byte)7.709380171237795E307]).var_3 = arg_0; + ((new Tester_Class_0[(byte)var_5])[(byte)('Z' / + + -2.6037312E38F)]).var_3 %= arg_2 ? + - - + - + +4.6761156E37F : (byte)- (var_2 = - - ~3113191255384341504L); + (("exseqpham" + "uigdxg").equalsIgnoreCase("oeutvibnv") ? "l" : "qra").replace(false ^ true ? 't' : "jwpf".charAt(+ ((byte)arg_0)), 6.624090730243228E307 > 2.7771497E38F ? 't' : "tcfesyg".charAt(arg_0)); + ((new Tester_Class_0[(byte)arg_0][(byte)6943189372481268736L])[(byte)2.6713643513095145E307][(byte)var_5]).var_1 &= !"ipgqq".endsWith("aecnyvpmf"); + ((new Tester_Class_0[(byte)(+ +2158971337956592640L ^ var_5)])[false ? (byte)8594725249859841024L : (byte)var_5]).var_3 = (byte)"jd".charAt((byte)1.6298661301128909E307 << (byte)'B'); + var_2 = (float)1014982842 * (byte)var_5 * ((new Tester_Class_0[(byte)2.7842814E38F])[(byte)"n".charAt('e' ^ (byte)arg_0)]).var_3; + if (false) + { + ((new Tester_Class_0[(byte)8.702990410251979E307][(byte)8.865924E37F])[(byte)var_5][(byte)+ ((long)var_5)]).var_1 ^= arg_2; + } + else + { + ((new Tester_Class_0[(byte)('I' | var_5)])[(byte)('L' + (+ - - (var_2 = 'N') + 1.324025E38F))]).var_3 = var_5 % '[' + (byte)var_5; + } + ((new Tester_Class_0[(byte)7.41761E37F][(byte)(var_2 = var_5)])[(byte)var_5][(byte)'o']).var_1 &= false; + ((new Tester_Class_0[(byte)+ ((byte)7.9065203E37F)])[(byte)var_5]).var_1 ^= 630582880 > - (var_2 = var_5); + return 'K'; + } + + protected float func_1(int arg_0, final Object arg_1, Object arg_2) + { + var_1 ^= (var_1 ^= true) & !var_1; + { + var_3 -= var_3; + var_2 = var_1 && (var_1 &= ! !true) | + ~3353396000385141760L < 7949306917320622080L ? (byte)306954754 : (byte)var_5; + final long var_12 = 1048994076885686272L; + } + short var_13 = 8706; + byte var_14 = (new byte[(byte)6.697464316212731E307])[(byte)var_4.indexOf("clbr", (byte)var_5 + 'F')]; + ((new Tester_Class_0[var_14][var_14 &= 'b'])[var_14][var_14]).var_1 |= var_14 >= var_3; + (((new String[var_14][var_14])[var_14])[var_14]).codePointAt(585064460); + var_14 -= 2121015302; + var_2 = 1.241922E38F; + { + (((new Tester_Class_0[var_14][var_14 ^= 'y'])[var_14])[var_14 |= var_14]).var_3 *= 5756647686007829504L; + } + { + var_13--; + } + double var_15; + var_1 = (var_1 = true) ? false : true; + arg_0--; + return var_3; + } + + public final static short func_2(int arg_0, final short arg_1, byte arg_2) + { + arg_0 %= (((new Tester_Class_0[arg_2][arg_2])[arg_2++][--arg_2]).var_1 |= true) ? 'e' : var_5 >>> arg_2; + float var_16 = ((false ? ~3951083684045828096L >>> - -3880809660598466560L : arg_0) ^ arg_1) - 1.1257035E37F; + var_2 = var_5 + 3.3679594E38F; + arg_2 += true & (((new Tester_Class_0[arg_2])[arg_2 *= 4301185995603340288L]).var_1 = arg_1 != arg_1) ? (var_2 = arg_0) : 988311987505040384L + ']' >>> --arg_2; + arg_2 = arg_2; + var_16 /= (arg_2 += (arg_0 += (var_16 %= arg_2)) + (var_16 -= arg_2)); + var_16 += 7416220016668043264L; + ((new Tester_Class_0[arg_2])[arg_2]).var_1 &= false; + ((new Tester_Class_0[--arg_2])[--arg_2]).var_1 = true | (true & true ? true : false); + arg_2 -= (var_2 = 7997355759027275776L); + ((new Tester_Class_0[arg_2])[arg_2 %= 8660960251961819136L]).var_3 *= 4180634858198604800L; + arg_0 /= -1.3063173E38F; + var_2 = arg_2; + var_2 = (6266377813429248L ^ 'j') / (!false & (1.1423139843154216E308 >= (var_2 = arg_2) || (((new Tester_Class_0[arg_2])[arg_2]).var_1 ^= true)) ? (short)('e' * arg_0) : var_5); + --arg_0; + var_2 = (+ - ~8598445599816821760L << arg_1) % 1890075208 & (!true & !true ^ false & false ? 'w' : 'm') % (5614521287604667392L / arg_2) & ~193105176465084416L; + arg_2 &= (arg_2 |= arg_0) ^ ((((new Tester_Class_0[arg_2][arg_2])[arg_2])[arg_2]).var_1 ? arg_2 : (new long[arg_2])[arg_2]); + ((new Tester_Class_0[arg_2 &= 'V'][arg_2])[arg_2 /= 5486057194586717184L][arg_2 %= var_16]).var_1 |= (new boolean[((new Tester_Class_0[arg_2])[arg_2]).var_1 ? arg_2 : arg_2])[arg_2]; + return ((((new Tester_Class_0[arg_2][arg_2][arg_2])[--arg_2])[arg_2 |= arg_2][arg_2 %= 6782653882738869248L]).var_1 ? false : !true | "hopq".equalsIgnoreCase("wvm") | "qmhtjvm".endsWith("gewqas")) && ! !false & false ? arg_1 : arg_1; + } + + protected final static char func_3(byte arg_0, final int arg_1, final short arg_2, long[] arg_3) + { + ((new Tester_Class_0[arg_0 ^= 1902924521091955712L])[arg_0]).var_1 &= ((((new Tester_Class_0[arg_0][arg_0])[--arg_0])[arg_0 *= - -1.0959788E38F]).var_1 = false); + { + var_2 = (new float[arg_0][(byte)1082004329])[arg_0][arg_0 <<= 'T']; + } + ((new Tester_Class_0[arg_0 >>= arg_1][arg_0])[arg_0][arg_0]).var_1 |= ((new Tester_Class_0[arg_0])[--arg_0]).var_4.startsWith(((new Tester_Class_0[arg_0])[arg_0]).var_4); + ((new Tester_Class_0[(byte)var_5])[arg_0]).var_4.substring(273513722, 'f' * 'n').substring((new short[arg_0][arg_0])[arg_0][arg_0] % 'C' >> (arg_3[arg_0] - 's') % ("".charAt(arg_1) & var_5)); + var_2 = 'Q' + (char)arg_0; + { + ((new Tester_Class_0[++arg_0])[arg_0]).var_1 ^= !true || !true ? !false ^ false : ! (1.7030813E38F != ~arg_0); + } + { + "jbdu".indexOf(((new Tester_Class_0[arg_0 *= 2628674024589069312L])[arg_0 -= arg_1]).var_4, "gqglwwbab".charAt(~arg_0) >>> 'M'); + } + { + --arg_0; + } + ((new Tester_Class_0[arg_0])[arg_0]).var_1 = 'n' == ('t' | (+9156142987836739584L | 's')) - 2915339344736463872L; + int var_17; + var_17 = 'k'; + var_17 = (((new Tester_Class_0[arg_0])[arg_0]).var_1 &= false) ? (short)'q' : arg_2; + return '`'; + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_0.var_5 = "; result += Test6712835.Printer.print(var_5); + result += "\n"; + result += "Tester_Class_0.var_4 = "; result += Test6712835.Printer.print(var_4); + result += "\n"; + result += "Tester_Class_0.var_1 = "; result += Test6712835.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_0.var_2 = "; result += Test6712835.Printer.print(var_2); + result += "\n"; + result += "Tester_Class_0.var_3 = "; result += Test6712835.Printer.print(var_3); + result += ""; + result += "\n]"; + return result; + } +} + + +final class Tester_Class_1 extends Tester_Class_0 { + final boolean var_29 = false; + static short var_30; + Tester_Class_0 var_31; + + + public Tester_Class_1() + { + new String(); + byte var_43 = (var_1 ? var_29 : var_1) ? (byte)(~ ~ ~6520122970162626560L | ~6642750731731981312L) : (byte)(var_30 = var_5); + { + var_2 = Tester_Class_0.var_5; + } + ((Tester_Class_0)(new Object[var_43])[var_43]).var_1 = var_29; + var_43 += 512311665; + } + + + + + final int func_0() + { + Tester_Class_0.var_2 = var_29 ? (var_29 ? (byte)'D' : (byte)Tester_Class_0.var_5) : (!var_1 ^ var_1 | (var_1 ^= var_1) ? (byte)'J' : (byte)51510881); + new String(); + new String(); + new String(); + return 1731501229; + } + + private final static void func_1(final String arg_0, final Object arg_1) + { + long var_32 = ((new Tester_Class_1[(byte)37719380])['I' == Tester_Class_0.var_5 + Tester_Class_0.var_5 ? (byte)(var_30 = (byte)1.3043569561522328E308) : (byte)1.1111420042091164E308]).var_1 ? ~2569063513521638400L - Tester_Class_0.var_5 ^ 'm' : 660383226; + ((Tester_Class_0)arg_1).var_3 += (char)8417109805993570304L; + var_30 = var_5; + var_2 = (new byte[(byte)2102078692])[(byte)7.942050823719592E307]; + if (((new Tester_Class_1[(byte)224717297])[(byte)2889830453578512384L]).var_1) + { + Tester_Class_0.var_2 = (new byte[(byte)'C'])[(byte)Tester_Class_0.var_5]; + } + else + { + var_32 <<= 'u'; + } + Tester_Class_0.var_2 = Tester_Class_0.var_5; + final Object var_33 = arg_1; + final byte var_34 = 40; + ++var_32; + (((new Tester_Class_1[var_34][var_34])[var_34][var_34]).var_31 = ((new Tester_Class_0[var_34][var_34])[var_34])[var_34]).var_1 ^= (((new Tester_Class_1[var_34][var_34])[var_34][var_34]).var_31 = (Tester_Class_0)var_33).var_1; + ((new Tester_Class_1[var_34])[var_34]).var_31 = (((new Tester_Class_1[var_34])[((new Tester_Class_1[var_34][var_34])[var_34][var_34]).var_1 ? var_34 : var_34]).var_31 = (((new Tester_Class_1[(byte)2.4941036E38F])[var_34]).var_31 = (Tester_Class_0)arg_1)); + } + + public static int[][] func_2(long arg_0, final float arg_1, short arg_2, final double arg_3) + { + long var_35; + { + arg_0++; + var_2 = true ? (byte)9.691601510156328E307 : (byte)"a".charAt(~ ((byte)arg_1)); + if (((new Tester_Class_1[(byte)'\\'][(byte)arg_2])[(byte)arg_2][(byte)arg_0]).var_29) + { + arg_2++; + } + else + { + Tester_Class_0.var_2 = arg_2; + var_30 = arg_2; + Tester_Class_0.var_2 = arg_0; + } + arg_2 /= 157487965; + arg_2 -= func_2(~ ((byte)arg_0), (short)arg_3, (byte)+2.2503214E38F); + } + arg_0--; + double var_36; + arg_0 <<= (arg_0 >>= (arg_0 = 'O')); + { + arg_0++; + --arg_0; + } + --arg_2; + ++arg_2; + "gbcrkn".length(); + var_30 = (short)7.14672E37F; + { + arg_0 %= (arg_0 >>= (arg_2 *= (byte)1.5835087622116814E308)) % arg_3; + var_36 = 'n'; + int[][] var_37 = new int[(byte)(double)arg_0][(byte)(arg_2 >>= 'o')]; + if ((byte)1390907656194158592L <= arg_2) + { + "uuoeps".indexOf("", 899321600); + } + else + { + var_36 = - ~ -arg_0; + } + short var_38 = var_5; + var_36 = ~arg_0 + (6482428938632186880L + 6995927649252739072L); + } + if (((new Tester_Class_1[(byte)arg_1][(byte)arg_2])[(new byte[(byte)arg_0])[(byte)var_5]][(byte)'s']).var_1 = false) + { + ++arg_0; + } + else + { + ((new Tester_Class_1[(byte)2.7176027E38F])[(byte)((arg_2 -= 2.595396436487417E307) % 'p')]).var_1 ^= ((new Tester_Class_1[(byte)4.393706E36F])[false ? (byte)4826960994531808256L : (byte)arg_0]).var_29; + } + int var_39 = 0; + arg_2 <<= 'Y'; + while (var_39 < 1 && false) + { + arg_0++; + var_39++; + Object var_40; + ((Tester_Class_0)(var_40 = new long[(byte)3.285531E38F])).var_3 += var_39; + } + Object var_41; + "w".substring(1359453539); + return new int[(byte)((arg_2 /= 4.143015135482291E307) - 3.2659622E38F)][(byte)++arg_2]; + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_1.var_5 = "; result += Test6712835.Printer.print(var_5); + result += "\n"; + result += "Tester_Class_1.var_30 = "; result += Test6712835.Printer.print(var_30); + result += "\n"; + result += "Tester_Class_1.var_4 = "; result += Test6712835.Printer.print(var_4); + result += "\n"; + result += "Tester_Class_1.var_1 = "; result += Test6712835.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_1.var_29 = "; result += Test6712835.Printer.print(var_29); + result += "\n"; + result += "Tester_Class_1.var_2 = "; result += Test6712835.Printer.print(var_2); + result += "\n"; + result += "Tester_Class_1.var_3 = "; result += Test6712835.Printer.print(var_3); + result += "\n"; + result += "Tester_Class_1.var_31 = "; result += Test6712835.Printer.print(var_31); + result += ""; + result += "\n]"; + return result; + } +} + + +final class Tester_Class_2 extends Tester_Class_0 { + static float var_44 = 2.7867988E38F; + static byte var_45; + static long var_46 = 4319798868443575296L; + + + public Tester_Class_2() + { + Tester_Class_1.var_30 = (byte)3.1718026E38F; + var_45 = (new byte[(byte)'o'])[var_45 = (byte)Tester_Class_0.var_5]; + Tester_Class_1.var_30 = (Tester_Class_1.var_30 = Tester_Class_0.var_5); + if (true) + { + ++var_46; + boolean var_51 = false ? (var_1 &= !var_1) : true; + --var_46; + if (false) + { + var_3 *= 6.882788442363403E307; + } + else + { + Tester_Class_0.var_2 = '`'; + } + final float var_52 = (var_1 ^= var_1 || (var_1 &= false)) | (var_51 |= (var_51 &= false)) ? (byte)4.751813848964725E307 : (var_3 *= var_5); + (false ? var_4 : var_4).startsWith("j" + var_4); + var_46++; + var_3 %= Tester_Class_1.var_5; + } + else + { + Tester_Class_1.var_30 = (var_45 = (var_45 = (var_45 = (byte)Tester_Class_1.var_5))); + Tester_Class_1.var_2 = (var_3 -= ~ ((byte)var_46) - 2018787280); + Tester_Class_1.var_30 = (Tester_Class_1.var_30 = (Tester_Class_1.var_30 = (Tester_Class_1.var_30 = var_5))); + } + char var_53; + ++var_46; + short var_54 = 138; + ++var_46; + var_2 = 1435782089; + Tester_Class_0.var_2 = var_46; + } + + + + + protected final boolean func_0(final boolean arg_0, final boolean arg_1) + { + var_2 = 2.6153986361247174E307; + var_45 = (var_45 = (var_45 = (var_45 = (var_45 = (byte)(var_44 += var_46))))); + var_46++; + long var_47 = 0L; + var_3 -= + ((byte)(~var_46 * ~var_46 ^ var_46 % 1910419567)); + do + { + ++var_46; + var_47++; + char var_48 = 'b'; + } while (var_47 < 2); + new Tester_Class_1().var_31 = ((new Tester_Class_1[var_45 = (byte)3.0853839E38F])[(new byte[var_45 = (byte)1.4974966426791287E308])[var_45 = (byte)Tester_Class_0.var_5]]).var_1 ? new Tester_Class_1() : new Tester_Class_1(); + var_45 = (var_45 = (byte)var_44); + double var_49 = 0; + var_45 = (byte)(Tester_Class_1.var_30 = Tester_Class_0.var_5); + while (((false ^ (var_1 &= var_1) | (var_1 |= arg_0) ? new Tester_Class_1() : new Tester_Class_1()).var_29 ? var_1 : false && (var_1 ^= arg_0)) && (var_49 < 3 && (true ? new Tester_Class_1() : new Tester_Class_1()).var_1)) + { + var_45 = (var_45 = (var_45 = (var_45 = (var_45 = (byte)1.933612E38F)))); + var_49++; + var_45 = (var_45 = (var_45 = (var_45 = (byte)685709636))); + long var_50; + } + var_45 = (var_45 = (var_45 = (byte)var_5)); + var_46--; + return true; + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_2.var_46 = "; result += Test6712835.Printer.print(var_46); + result += "\n"; + result += "Tester_Class_2.var_2 = "; result += Test6712835.Printer.print(var_2); + result += "\n"; + result += "Tester_Class_2.var_3 = "; result += Test6712835.Printer.print(var_3); + result += "\n"; + result += "Tester_Class_2.var_44 = "; result += Test6712835.Printer.print(var_44); + result += "\n"; + result += "Tester_Class_2.var_5 = "; result += Test6712835.Printer.print(var_5); + result += "\n"; + result += "Tester_Class_2.var_45 = "; result += Test6712835.Printer.print(var_45); + result += "\n"; + result += "Tester_Class_2.var_4 = "; result += Test6712835.Printer.print(var_4); + result += "\n"; + result += "Tester_Class_2.var_1 = "; result += Test6712835.Printer.print(var_1); + result += ""; + result += "\n]"; + return result; + } +} + + +class Tester_Class_3 extends Tester_Class_0 { + static boolean var_55 = true; + short var_56; + char var_57 = (char)723612093; + final static byte var_58 = 118; + static float var_59 = true ? -2818156175448416256L : - - (Tester_Class_2.var_44 += var_58); + static Tester_Class_1 var_60; + byte var_61 = 112; + Tester_Class_2[] var_62; + static short var_63 = 19813; + static double var_64 = (var_55 = true) ? (Tester_Class_1.var_2 = 'M') : Tester_Class_2.var_46; + + + public Tester_Class_3() + { + var_56 = var_58; + Tester_Class_1 var_65 = var_60 = (var_60 = (var_60 = (new Tester_Class_1[var_61 |= '\\'])[(var_1 = true) || var_55 ? var_58 : var_61])); + var_64 /= 1253632965 * '`'; + Tester_Class_2.var_46 >>>= var_58; + (((var_61 = var_58) * (var_55 ? 1641980027 : var_63) >= 1490788063 ? var_65 : var_65).var_29 ? var_65 : var_65).var_31 = (new Tester_Class_2[var_58])[var_58]; + ++var_63; + new String(); + var_64 += var_55 ? (var_61 >>>= 'Q') : (var_63 <<= var_57); + ((new Tester_Class_2().var_3 >= Tester_Class_2.var_46 ? !var_55 : var_4.startsWith(var_4, 586086925)) ? "gjsdhuop" : "juqrt").substring(("pm" + ((new Tester_Class_2[var_61][var_58])[var_58][var_58]).var_4).codePointBefore((~var_61 << 3032688286897486848L) - Tester_Class_1.var_5), (var_61 += 4.0796373033184064E306) >> (Tester_Class_2.var_46 >>> var_58)); + var_63 -= (var_63 ^= var_57); + var_64 = var_5 - (Tester_Class_2.var_46 *= var_57); + Tester_Class_2.var_46 &= 7544159045139005440L; + var_55 |= false; + Tester_Class_2.var_46 = var_61; + } + + + + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_3.var_57 = "; result += Test6712835.Printer.print(var_57); + result += "\n"; + result += "Tester_Class_3.var_62 = "; result += Test6712835.Printer.print(var_62); + result += "\n"; + result += "Tester_Class_3.var_2 = "; result += Test6712835.Printer.print(var_2); + result += "\n"; + result += "Tester_Class_3.var_64 = "; result += Test6712835.Printer.print(var_64); + result += "\n"; + result += "Tester_Class_3.var_3 = "; result += Test6712835.Printer.print(var_3); + result += "\n"; + result += "Tester_Class_3.var_59 = "; result += Test6712835.Printer.print(var_59); + result += "\n"; + result += "Tester_Class_3.var_5 = "; result += Test6712835.Printer.print(var_5); + result += "\n"; + result += "Tester_Class_3.var_56 = "; result += Test6712835.Printer.print(var_56); + result += "\n"; + result += "Tester_Class_3.var_63 = "; result += Test6712835.Printer.print(var_63); + result += "\n"; + result += "Tester_Class_3.var_58 = "; result += Test6712835.Printer.print(var_58); + result += "\n"; + result += "Tester_Class_3.var_61 = "; result += Test6712835.Printer.print(var_61); + result += "\n"; + result += "Tester_Class_3.var_4 = "; result += Test6712835.Printer.print(var_4); + result += "\n"; + result += "Tester_Class_3.var_1 = "; result += Test6712835.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_3.var_55 = "; result += Test6712835.Printer.print(var_55); + result += "\n"; + result += "Tester_Class_3.var_60 = "; result += Test6712835.Printer.print(var_60); + result += ""; + result += "\n]"; + return result; + } +} + + +final class Tester_Class_4 { + static long var_66; + final long var_67 = 7113579489152300032L * 985636454; + int[] var_68; + Tester_Class_3 var_69; + final long var_70 = Tester_Class_2.var_46 <<= Tester_Class_1.var_5; + byte var_71 = Tester_Class_3.var_58; + + + public Tester_Class_4() + { + Tester_Class_2.var_46++; + (var_69 = new Tester_Class_3()).var_61 += (!true | (Tester_Class_3.var_55 ^= Tester_Class_3.var_55) ? new Tester_Class_3() : new Tester_Class_3()).var_61; + final String[][] var_79 = new String[var_71 >>= (Tester_Class_3.var_63 ^= 'm')][((Tester_Class_3)(new Tester_Class_1().var_31 = new Tester_Class_2())).var_61 >>= (var_71 >>>= (Tester_Class_2.var_46 += 465205188010511360L))]; + ++(var_69 = (var_69 = (var_69 = (Tester_Class_3)(new Object[Tester_Class_3.var_58][var_71])[Tester_Class_3.var_58][var_71]))).var_61; + (((new Tester_Class_2[var_71][Tester_Class_3.var_58])[Tester_Class_2.var_45 = var_71])[var_71]).var_3 += (Tester_Class_2.var_46 <<= (Tester_Class_2.var_46 /= 9.03047405760868E307) >> (new Tester_Class_2().var_1 ? 2099696051 : Tester_Class_3.var_63)); + Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = new Tester_Class_1()))); + char var_80; + Tester_Class_3.var_64 += 355712574; + ++Tester_Class_2.var_46; + } + + + + + private final static Tester_Class_1 func_0(boolean arg_0, double arg_1) + { + Tester_Class_3.var_60 = (Tester_Class_3.var_60 = new Tester_Class_1()); + byte var_72 = (byte)Tester_Class_2.var_46; + Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = new Tester_Class_1())))); + float var_73 = 0F; + "flfix".offsetByCodePoints((Tester_Class_3.var_63 ^= 3286104714651747328L) + ((Tester_Class_3)(new Tester_Class_0[var_72])[var_72]).var_61, Tester_Class_0.var_5 + Tester_Class_3.var_58); + while (var_73 < 2 && (false ? (Tester_Class_3.var_60 = new Tester_Class_1()) : (Tester_Class_1)(new Tester_Class_0[var_72])[var_72]).var_29) + { + ((Tester_Class_3)(Tester_Class_0)(new Object[var_72])[Tester_Class_3.var_58]).var_61 >>= ((new Tester_Class_4[var_72])[var_72]).var_67; + var_73++; + new String("blod"); + --var_72; + } + ((new Tester_Class_4[Tester_Class_3.var_58][var_72])[new Tester_Class_3().var_61][Tester_Class_3.var_58]).var_69 = new Tester_Class_3(); + float var_74 = (! ("dkcx".lastIndexOf(Tester_Class_1.var_5 >> - (var_72 >>>= 1433506903139345408L)) == Tester_Class_2.var_46) ? 'O' : 'e' - new Tester_Class_2().var_3) * ~ (var_72 ^= var_72); + Tester_Class_3.var_60 = !true ? new Tester_Class_1() : (new Tester_Class_1[Tester_Class_3.var_58])[var_72]; + ((arg_0 &= Tester_Class_3.var_55 | (Tester_Class_3.var_60 = new Tester_Class_1()).var_29) ? (Tester_Class_3.var_60 = (Tester_Class_1)(new Tester_Class_1().var_31 = new Tester_Class_2())) : (Tester_Class_3.var_60 = (new Tester_Class_1[var_72])[Tester_Class_3.var_58])).var_31 = (new Tester_Class_3[var_72 |= 546982927])[Tester_Class_3.var_58]; + long var_75 = 0L; + final double var_76 = +arg_1; + while (var_75 < 1) + { + short var_77; + var_75++; + new Tester_Class_3().var_57 = (false & true ? new Tester_Class_3() : new Tester_Class_3()).var_57; + (Tester_Class_3.var_60 = (new Tester_Class_1[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_31 = (new Tester_Class_2[Tester_Class_3.var_58][var_72])[var_72][var_72]; + } + Tester_Class_3.var_64 *= (arg_0 ? (Tester_Class_3.var_55 ^= (arg_0 ^= arg_0)) & ! (Tester_Class_3.var_55 = arg_0) : arg_0) ^ new Tester_Class_1().var_29 ? ++((new Tester_Class_3[var_72][var_72])[(new byte[Tester_Class_3.var_58])[Tester_Class_3.var_58]][(((new Tester_Class_4[var_72][Tester_Class_3.var_58])[Tester_Class_3.var_58][Tester_Class_3.var_58]).var_69 = (new Tester_Class_3[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_61]).var_57 : 'C'; + long var_78; + var_74 %= (Tester_Class_3.var_55 |= (arg_0 = (arg_0 ^= (arg_0 &= !arg_0)))) ? new Tester_Class_3().var_61 : (Tester_Class_3.var_63 ^= var_72); + arg_1 /= (Tester_Class_2.var_46 &= 'W'); + --(((new Tester_Class_4[var_72])[var_72]).var_69 = (((new Tester_Class_4[var_72])[var_72]).var_69 = new Tester_Class_3())).var_61; + return (new Tester_Class_1[var_72][Tester_Class_3.var_58])[var_72][new Tester_Class_3().var_61]; + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_4.var_68 = "; result += Test6712835.Printer.print(var_68); + result += "\n"; + result += "Tester_Class_4.var_66 = "; result += Test6712835.Printer.print(var_66); + result += "\n"; + result += "Tester_Class_4.var_67 = "; result += Test6712835.Printer.print(var_67); + result += "\n"; + result += "Tester_Class_4.var_70 = "; result += Test6712835.Printer.print(var_70); + result += "\n"; + result += "Tester_Class_4.var_71 = "; result += Test6712835.Printer.print(var_71); + result += "\n"; + result += "Tester_Class_4.var_69 = "; result += Test6712835.Printer.print(var_69); + result += ""; + result += "\n]"; + return result; + } +} + + +final class Tester_Class_5 extends Tester_Class_0 { + static boolean var_81; + final int var_82 = 174395841; + int var_83; + byte var_84; + boolean var_85 = Tester_Class_3.var_55; + static boolean var_86 = Tester_Class_3.var_55; + + + public Tester_Class_5() + { + { + short var_87 = (new short[Tester_Class_3.var_58][var_84 = Tester_Class_3.var_58])[(((new Tester_Class_4[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_69 = (Tester_Class_3)(Tester_Class_0)(new Object[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_61][Tester_Class_3.var_58]; + Tester_Class_4 var_88 = var_85 ^ (var_81 = false) ? (new Tester_Class_4[Tester_Class_3.var_58])[Tester_Class_3.var_58] : (new Tester_Class_4[Tester_Class_3.var_58])[Tester_Class_3.var_58]; + { + ++var_87; + } + short var_89; + (var_88.var_69 = (new Tester_Class_3[var_88.var_71][var_88.var_71])[var_88.var_71][var_88.var_71]).var_61 += (((Tester_Class_2)(new Tester_Class_1().var_31 = new Tester_Class_2())).var_3 = Tester_Class_3.var_58); + var_88 = var_88; + } + { + ++Tester_Class_2.var_46; + --Tester_Class_2.var_46; + } + { + Tester_Class_2.var_46++; + Tester_Class_3.var_64 /= Tester_Class_3.var_59; + ((Tester_Class_4)(new Object[Tester_Class_2.var_45 = Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_71 %= (var_3 /= 3637233239489444864L); + ++Tester_Class_2.var_46; + } + new Tester_Class_3().var_57++; + var_85 &= (Tester_Class_3.var_55 |= false); + Tester_Class_3.var_60 = new Tester_Class_1(); + Tester_Class_2.var_46++; + ((Tester_Class_3)(true ? (new Tester_Class_2[Tester_Class_3.var_58])[Tester_Class_3.var_58] : (new Tester_Class_0[Tester_Class_3.var_58])[Tester_Class_2.var_45 = Tester_Class_3.var_58])).var_57 *= ((new Tester_Class_3[Tester_Class_3.var_58])[(byte)'`']).var_57; + var_3 += (int)Tester_Class_3.var_59 ^ (Tester_Class_2.var_46 -= Tester_Class_2.var_46) % ~((new Tester_Class_4[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_71; + ++Tester_Class_2.var_46; + --Tester_Class_2.var_46; + var_83 = Tester_Class_3.var_58; + } + + + + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_5.var_82 = "; result += Test6712835.Printer.print(var_82); + result += "\n"; + result += "Tester_Class_5.var_83 = "; result += Test6712835.Printer.print(var_83); + result += "\n"; + result += "Tester_Class_5.var_2 = "; result += Test6712835.Printer.print(var_2); + result += "\n"; + result += "Tester_Class_5.var_3 = "; result += Test6712835.Printer.print(var_3); + result += "\n"; + result += "Tester_Class_5.var_5 = "; result += Test6712835.Printer.print(var_5); + result += "\n"; + result += "Tester_Class_5.var_84 = "; result += Test6712835.Printer.print(var_84); + result += "\n"; + result += "Tester_Class_5.var_4 = "; result += Test6712835.Printer.print(var_4); + result += "\n"; + result += "Tester_Class_5.var_1 = "; result += Test6712835.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_5.var_81 = "; result += Test6712835.Printer.print(var_81); + result += "\n"; + result += "Tester_Class_5.var_85 = "; result += Test6712835.Printer.print(var_85); + result += "\n"; + result += "Tester_Class_5.var_86 = "; result += Test6712835.Printer.print(var_86); + result += ""; + result += "\n]"; + return result; + } +} + + +class Tester_Class_6 extends Tester_Class_0 { + long var_90 = 8467263472031702016L; + final static int var_91 = 1648594448 * ']'; + char var_92 = 'x'; + short var_93 = Tester_Class_3.var_63; + Tester_Class_4 var_94; + String[] var_95; + static short var_96 = Tester_Class_3.var_63 -= 83376045 << 40225606; + final static double var_97 = 5.387227213380301E307; + final static short var_98 = Tester_Class_3.var_63 &= var_91; + byte var_99 = 44; + + + public Tester_Class_6() + { + (Tester_Class_3.var_60 = (Tester_Class_1)(new Object[Tester_Class_3.var_58][var_99])[Tester_Class_3.var_58][var_99]).var_31 = true | true ? (Tester_Class_5)(new Object[var_99])[Tester_Class_3.var_58] : (Tester_Class_5)(new Object[Tester_Class_3.var_58])[var_99]; + var_92 &= 'p'; + Tester_Class_5.var_81 = (((new Tester_Class_1[var_99][Tester_Class_3.var_58])[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_29; + { + { + ++Tester_Class_2.var_46; + Tester_Class_3.var_2 = var_98; + var_93 -= var_96; + } + Tester_Class_2.var_46--; + { + (var_5 == (((Tester_Class_3)(new Tester_Class_0[var_99])[Tester_Class_3.var_58]).var_61 /= var_5) ? "fsajxeuao".replace('s', 'K') : var_4).substring('e' >>> var_5).toLowerCase(); + } + var_93 %= ((new Tester_Class_6[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_90; + var_93 /= var_93; + if (Tester_Class_5.var_86) + { + (var_94 = (new Tester_Class_4[var_99])[var_99]).var_69 = (new Tester_Class_3[var_99])[var_99 %= -var_90]; + } + else + { + --var_96; + } + var_93 *= 'O'; + final long var_103 = 7573900518735055872L; + --Tester_Class_3.var_63; + } + Tester_Class_3.var_64 /= var_93; + if (true) + { + --Tester_Class_2.var_46; + Tester_Class_5 var_104; + final double var_105 = Tester_Class_3.var_64 += Tester_Class_5.var_86 & (new Tester_Class_2().var_1 & ((Tester_Class_3.var_55 = (var_1 ^= Tester_Class_5.var_86) & false) & (Tester_Class_5.var_81 = Tester_Class_5.var_86))) ? (byte)'g' : var_99; + Tester_Class_3.var_64 *= var_99; + } + else + { + char var_106 = var_92 -= Tester_Class_3.var_58; + } + double[] var_107 = ((new double[Tester_Class_3.var_58][var_99][var_99])[var_99])[false ? Tester_Class_3.var_58 : Tester_Class_3.var_58]; + var_99 <<= (Tester_Class_3.var_63 >>= Tester_Class_3.var_58); + ++var_99; + } + + + + + final static byte func_0(final byte arg_0, final char arg_1, final Tester_Class_5[] arg_2) + { + ((Tester_Class_4)(new Object[Tester_Class_3.var_58][Tester_Class_3.var_58])[Tester_Class_3.var_58][arg_0]).var_69 = (Tester_Class_3)(new Tester_Class_0[Tester_Class_3.var_58])[Tester_Class_2.var_45 = Tester_Class_3.var_58]; + long var_100 = 0L; + Tester_Class_3.var_64 /= (Tester_Class_5.var_86 = true) || 'o' > (Tester_Class_3.var_63 -= (float)arg_0) ? var_98 : 1.7875238E38F; + do + { + Tester_Class_3.var_64 %= var_5; + var_100++; + Tester_Class_3.var_64 += var_96 + 'r'; + } while (true && (var_100 < 1 && (new Tester_Class_1().var_29 ? new Tester_Class_1() : (new Tester_Class_1[arg_0][Tester_Class_3.var_58])[arg_0][Tester_Class_3.var_58]).var_29)); + (Tester_Class_3.var_55 ^ (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = new Tester_Class_1()))).var_29 ? new Tester_Class_3() : new Tester_Class_3()).var_57 = ((((new Tester_Class_6[Tester_Class_3.var_58][Tester_Class_3.var_58])[Tester_Class_3.var_58][Tester_Class_3.var_58]).var_94 = (((new Tester_Class_6[Tester_Class_3.var_58][Tester_Class_3.var_58])[Tester_Class_3.var_58][arg_0]).var_94 = (new Tester_Class_4[Tester_Class_3.var_58][arg_0])[Tester_Class_3.var_58][Tester_Class_3.var_58])).var_69 = new Tester_Class_3()).var_57; + final double var_101 = 1.6798216578519203E308; + Tester_Class_3.var_60 = (Tester_Class_3.var_60 = false ? new Tester_Class_1() : (Tester_Class_3.var_60 = new Tester_Class_1())); + Tester_Class_2 var_102 = new Tester_Class_2(); + return Tester_Class_3.var_58; + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_6.var_92 = "; result += Test6712835.Printer.print(var_92); + result += "\n"; + result += "Tester_Class_6.var_91 = "; result += Test6712835.Printer.print(var_91); + result += "\n"; + result += "Tester_Class_6.var_95 = "; result += Test6712835.Printer.print(var_95); + result += "\n"; + result += "Tester_Class_6.var_90 = "; result += Test6712835.Printer.print(var_90); + result += "\n"; + result += "Tester_Class_6.var_2 = "; result += Test6712835.Printer.print(var_2); + result += "\n"; + result += "Tester_Class_6.var_97 = "; result += Test6712835.Printer.print(var_97); + result += "\n"; + result += "Tester_Class_6.var_3 = "; result += Test6712835.Printer.print(var_3); + result += "\n"; + result += "Tester_Class_6.var_5 = "; result += Test6712835.Printer.print(var_5); + result += "\n"; + result += "Tester_Class_6.var_93 = "; result += Test6712835.Printer.print(var_93); + result += "\n"; + result += "Tester_Class_6.var_96 = "; result += Test6712835.Printer.print(var_96); + result += "\n"; + result += "Tester_Class_6.var_98 = "; result += Test6712835.Printer.print(var_98); + result += "\n"; + result += "Tester_Class_6.var_99 = "; result += Test6712835.Printer.print(var_99); + result += "\n"; + result += "Tester_Class_6.var_4 = "; result += Test6712835.Printer.print(var_4); + result += "\n"; + result += "Tester_Class_6.var_1 = "; result += Test6712835.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_6.var_94 = "; result += Test6712835.Printer.print(var_94); + result += ""; + result += "\n]"; + return result; + } +} + + +abstract class Tester_Class_7 { + final static char var_108 = '_'; + static Tester_Class_3 var_109; + final short var_110 = 4360; + short var_111; + Object var_112; + Tester_Class_4 var_113; + static Tester_Class_5 var_114; + final short var_115 = Tester_Class_6.var_96; + final static float var_116 = Tester_Class_3.var_59; + + + public Tester_Class_7() + { + --Tester_Class_2.var_46; + --Tester_Class_6.var_96; + var_113 = (new Tester_Class_4[new Tester_Class_6().var_99])[Tester_Class_3.var_58]; + --Tester_Class_2.var_46; + Tester_Class_6.var_96--; + Tester_Class_3.var_63 -= 'i'; + if (!Tester_Class_5.var_86) + { + Tester_Class_3.var_64 %= var_116; + if ((Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)(Tester_Class_0)(var_112 = "yosyghjm"))).var_29) + { + Tester_Class_2.var_46++; + } + else + { + (var_114 = (var_114 = (Tester_Class_5)(Tester_Class_0)(var_112 = "bxt"))).var_83 = (Tester_Class_2.var_45 = (Tester_Class_2.var_45 = Tester_Class_3.var_58)); + } + var_114 = (var_114 = (var_114 = (var_114 = (var_114 = (var_114 = (Tester_Class_5)(var_112 = "blrobgg")))))); + var_113 = (((Tester_Class_6)(var_112 = "popebwfp")).var_94 = (new Tester_Class_4[Tester_Class_3.var_58])[Tester_Class_3.var_58]); + } + else + { + Tester_Class_3.var_60 = new Tester_Class_1(); + } + final Tester_Class_6 var_122 = new Tester_Class_6(); + var_122.var_92 &= (var_122.var_92 |= var_108); + ((new Tester_Class_5[var_122.var_99])[((new Tester_Class_3[Tester_Class_3.var_58])[var_122.var_99--]).var_61]).var_83 = 1708230145; + } + + + + public boolean equals(Object obj) + { + (((Tester_Class_5.var_81 = (Tester_Class_5.var_81 = false)) ? (Tester_Class_3.var_55 &= false) : !Tester_Class_3.var_55 & ((Tester_Class_1)obj).var_29) ? (new Tester_Class_2[Tester_Class_3.var_58])[Tester_Class_3.var_58] : (Tester_Class_2)obj).equals((Tester_Class_5.var_86 |= Tester_Class_3.var_55) | (Tester_Class_3.var_55 = Tester_Class_3.var_55) ? obj : (Tester_Class_6)(Tester_Class_0)obj); + Tester_Class_3.var_64 *= 2.8258473339654136E307; + { + final int var_118 = 1248523063; + short var_119 = 30906; + Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)obj); + ((Tester_Class_6)(((Tester_Class_1)obj).var_31 = ((var_113 = (Tester_Class_4)obj).var_69 = (Tester_Class_3)obj))).var_94 = (var_113 = (Tester_Class_4)(var_112 = (Tester_Class_1)obj)); + } + final Tester_Class_1 var_120 = false ^ (((Tester_Class_1)obj).var_1 = !true) ^ (((Tester_Class_6)(Tester_Class_0)obj).var_92 *= (((Tester_Class_3)obj).var_57 |= (Tester_Class_2.var_46 >>= 6986775136305733632L))) < (byte)Tester_Class_6.var_97 ? (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)obj)) : (true ? (Tester_Class_1)obj : (Tester_Class_1)obj); + (var_114 = (var_114 = (Tester_Class_5)obj)).var_83 = (((new Tester_Class_6[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_92 &= ((Tester_Class_4)obj).var_70 << (Tester_Class_2.var_45 = Tester_Class_3.var_58)); + var_114 = (Tester_Class_5)obj; + obj = ((Tester_Class_3.var_60 = var_120).var_29 ? false : false) ? (new Tester_Class_6[Tester_Class_3.var_58])[Tester_Class_3.var_58] : obj; + (var_120.var_29 ? (Tester_Class_6)(obj = (Tester_Class_3.var_60 = var_120)) : (new Tester_Class_6[Tester_Class_3.var_58])[((Tester_Class_3)obj).var_61 ^= Tester_Class_6.var_91]).var_90 ^= 2127530040436251648L; + Object var_121; + return (new boolean[Tester_Class_3.var_58])[((var_113 = (Tester_Class_4)obj).var_69 = (var_109 = (new Tester_Class_3[Tester_Class_3.var_58][Tester_Class_3.var_58])[Tester_Class_3.var_58][Tester_Class_3.var_58])).var_61]; + } + + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_7.var_108 = "; result += Test6712835.Printer.print(var_108); + result += "\n"; + result += "Tester_Class_7.var_116 = "; result += Test6712835.Printer.print(var_116); + result += "\n"; + result += "Tester_Class_7.var_110 = "; result += Test6712835.Printer.print(var_110); + result += "\n"; + result += "Tester_Class_7.var_111 = "; result += Test6712835.Printer.print(var_111); + result += "\n"; + result += "Tester_Class_7.var_115 = "; result += Test6712835.Printer.print(var_115); + result += "\n"; + result += "Tester_Class_7.var_114 = "; result += Test6712835.Printer.print(var_114); + result += "\n"; + result += "Tester_Class_7.var_113 = "; result += Test6712835.Printer.print(var_113); + result += "\n"; + result += "Tester_Class_7.var_109 = "; result += Test6712835.Printer.print(var_109); + result += "\n"; + result += "Tester_Class_7.var_112 = "; result += Test6712835.Printer.print(var_112); + result += ""; + result += "\n]"; + return result; + } +} + + +class Tester_Class_8 extends Tester_Class_7 { + static char var_123; + Tester_Class_4 var_124; + static short var_125; + + + public Tester_Class_8() + { + { + Tester_Class_3.var_64 -= (Tester_Class_2.var_46 *= Tester_Class_3.var_64); + { + Tester_Class_2.var_46--; + } + ++Tester_Class_3.var_63; + Tester_Class_5.var_86 |= true; + Tester_Class_6.var_96--; + } + "w".indexOf(312689020); + if (false) + { + (Tester_Class_7.var_114 = (new Tester_Class_5[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_83 = 'I'; + } + else + { + --Tester_Class_6.var_96; + } + switch (Tester_Class_5.var_86 ? Tester_Class_3.var_58 : Tester_Class_3.var_58) + { + case 95: + + case 35: + + } + Tester_Class_6.var_96--; + Tester_Class_3.var_64 *= 4.516167673347119E307; + --Tester_Class_3.var_63; + { + int var_126; + } + Tester_Class_3.var_60 = new Tester_Class_1(); + Tester_Class_2.var_46++; + ((new Tester_Class_6[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_99 &= Tester_Class_6.var_91; + ((new Tester_Class_1[((new Tester_Class_4[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_71])[((Tester_Class_3)(var_112 = "fsmtm")).var_61]).var_31 = (Tester_Class_2)(new Tester_Class_0[Tester_Class_3.var_58])[Tester_Class_3.var_58]; + } + + + + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_8.var_108 = "; result += Test6712835.Printer.print(var_108); + result += "\n"; + result += "Tester_Class_8.var_123 = "; result += Test6712835.Printer.print(var_123); + result += "\n"; + result += "Tester_Class_8.var_116 = "; result += Test6712835.Printer.print(var_116); + result += "\n"; + result += "Tester_Class_8.var_110 = "; result += Test6712835.Printer.print(var_110); + result += "\n"; + result += "Tester_Class_8.var_111 = "; result += Test6712835.Printer.print(var_111); + result += "\n"; + result += "Tester_Class_8.var_115 = "; result += Test6712835.Printer.print(var_115); + result += "\n"; + result += "Tester_Class_8.var_125 = "; result += Test6712835.Printer.print(var_125); + result += "\n"; + result += "Tester_Class_8.var_114 = "; result += Test6712835.Printer.print(var_114); + result += "\n"; + result += "Tester_Class_8.var_113 = "; result += Test6712835.Printer.print(var_113); + result += "\n"; + result += "Tester_Class_8.var_124 = "; result += Test6712835.Printer.print(var_124); + result += "\n"; + result += "Tester_Class_8.var_109 = "; result += Test6712835.Printer.print(var_109); + result += "\n"; + result += "Tester_Class_8.var_112 = "; result += Test6712835.Printer.print(var_112); + result += ""; + result += "\n]"; + return result; + } +} + + +final class Tester_Class_9 { + final static String var_127 = "pxk"; + Tester_Class_2 var_128; + final static char var_129 = '\\'; + static float var_130; + static boolean var_131; + final static float var_132 = Tester_Class_3.var_59; + static Tester_Class_0 var_133; + boolean[] var_134; + + + public Tester_Class_9() + { + Tester_Class_2.var_44 -= Tester_Class_3.var_58; + Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (new Tester_Class_1[Tester_Class_3.var_58][Tester_Class_3.var_58])[Tester_Class_3.var_58][Tester_Class_3.var_58])); + { + Tester_Class_8 var_136; + } + ++Tester_Class_2.var_46; + Tester_Class_6.var_96--; + var_128 = (var_128 = (var_128 = (Tester_Class_2)(var_133 = (new Tester_Class_1[Tester_Class_3.var_58])[Tester_Class_3.var_58]))); + ++Tester_Class_6.var_96; + ++Tester_Class_2.var_46; + Tester_Class_4 var_137; + var_128 = (var_128 = (new Tester_Class_2[Tester_Class_3.var_58])[Tester_Class_3.var_58]); + (Tester_Class_8.var_114 = (Tester_Class_8.var_114 = (new Tester_Class_5[Tester_Class_3.var_58])[Tester_Class_3.var_58])).var_83 = (((new Tester_Class_4[Tester_Class_3.var_58][Tester_Class_3.var_58])[Tester_Class_3.var_58][Tester_Class_3.var_58]).var_69 = (new Tester_Class_3[Tester_Class_3.var_58][Tester_Class_3.var_58])[Tester_Class_3.var_58][Tester_Class_3.var_58]).var_57++; + Tester_Class_2.var_46++; + } + + + + + protected static short func_1() + { + { + Tester_Class_3.var_63--; + } + Tester_Class_3.var_64 *= Tester_Class_2.var_46; + short var_135; + Tester_Class_3.var_64 -= Tester_Class_6.var_96; + return new Tester_Class_6().var_93; + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_9.var_129 = "; result += Test6712835.Printer.print(var_129); + result += "\n"; + result += "Tester_Class_9.var_134 = "; result += Test6712835.Printer.print(var_134); + result += "\n"; + result += "Tester_Class_9.var_130 = "; result += Test6712835.Printer.print(var_130); + result += "\n"; + result += "Tester_Class_9.var_132 = "; result += Test6712835.Printer.print(var_132); + result += "\n"; + result += "Tester_Class_9.var_131 = "; result += Test6712835.Printer.print(var_131); + result += "\n"; + result += "Tester_Class_9.var_127 = "; result += Test6712835.Printer.print(var_127); + result += "\n"; + result += "Tester_Class_9.var_128 = "; result += Test6712835.Printer.print(var_128); + result += "\n"; + result += "Tester_Class_9.var_133 = "; result += Test6712835.Printer.print(var_133); + result += ""; + result += "\n]"; + return result; + } +} + + +final class Tester_Class_10 extends Tester_Class_0 { + final static byte var_138 = 78; + Object var_139; + final static boolean var_140 = true; + float var_141 = 1.2816267E38F; + Tester_Class_8 var_142; + static Tester_Class_3 var_143; + short var_144 = var_1 ? (Tester_Class_6.var_96 &= 8024552544994698240L) : Tester_Class_0.var_5; + final boolean var_145 = var_140; + long var_146; + float[] var_147; + + + public Tester_Class_10() + { + "xuc".codePointCount(new Tester_Class_6().var_99 / ((new Tester_Class_9().var_128 = new Tester_Class_2()).var_1 ? var_138 : (int)(Tester_Class_3.var_64 += Tester_Class_3.var_64)), 882345740); + Tester_Class_3.var_64 /= Tester_Class_9.var_132; + Tester_Class_9.var_127.indexOf((Tester_Class_7.var_114 = (Tester_Class_8.var_114 = (Tester_Class_5)(var_139 = "mcyagebtv"))).var_83 = var_145 ? (Tester_Class_2.var_45 = Tester_Class_3.var_58) : Tester_Class_6.var_96); + --Tester_Class_2.var_46; + final float var_148 = 3.0263434E38F; + ((Tester_Class_7.var_114 = (Tester_Class_5)(Tester_Class_9.var_133 = new Tester_Class_1())).var_85 & ((Tester_Class_1)(var_139 = new Tester_Class_6())).var_1 ? "gmxwrgik" : Tester_Class_9.var_127).compareTo(var_4); + --Tester_Class_2.var_46; + new Tester_Class_6(); + ++Tester_Class_2.var_46; + Tester_Class_3.var_60 = Tester_Class_5.var_86 ? new Tester_Class_1() : new Tester_Class_1(); + { + --Tester_Class_6.var_96; + ((Tester_Class_7)(var_139 = new Tester_Class_1().var_4)).var_112 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)(var_139 = "gugsy"))); + } + Tester_Class_9.var_133 = (Tester_Class_3.var_60 = new Tester_Class_1()); + if (var_140 & !var_140) + { + Tester_Class_6.var_96++; + } + else + { + Tester_Class_2.var_46++; + } + { + ++new Tester_Class_6().var_92; + } + Tester_Class_7.var_109 = (((new Tester_Class_4[Tester_Class_3.var_58])[Tester_Class_3.var_58]).var_69 = (var_143 = new Tester_Class_3())); + Tester_Class_3.var_63--; + } + + + + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_10.var_147 = "; result += Test6712835.Printer.print(var_147); + result += "\n"; + result += "Tester_Class_10.var_146 = "; result += Test6712835.Printer.print(var_146); + result += "\n"; + result += "Tester_Class_10.var_3 = "; result += Test6712835.Printer.print(var_3); + result += "\n"; + result += "Tester_Class_10.var_141 = "; result += Test6712835.Printer.print(var_141); + result += "\n"; + result += "Tester_Class_10.var_5 = "; result += Test6712835.Printer.print(var_5); + result += "\n"; + result += "Tester_Class_10.var_144 = "; result += Test6712835.Printer.print(var_144); + result += "\n"; + result += "Tester_Class_10.var_138 = "; result += Test6712835.Printer.print(var_138); + result += "\n"; + result += "Tester_Class_10.var_1 = "; result += Test6712835.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_10.var_140 = "; result += Test6712835.Printer.print(var_140); + result += "\n"; + result += "Tester_Class_10.var_145 = "; result += Test6712835.Printer.print(var_145); + result += "\n"; + result += "Tester_Class_10.var_139 = "; result += Test6712835.Printer.print(var_139); + result += "\n"; + result += "Tester_Class_10.var_142 = "; result += Test6712835.Printer.print(var_142); + result += "\n"; + result += "Tester_Class_10.var_2 = "; result += Test6712835.Printer.print(var_2); + result += "\n"; + result += "Tester_Class_10.var_4 = "; result += Test6712835.Printer.print(var_4); + result += "\n"; + result += "Tester_Class_10.var_143 = "; result += Test6712835.Printer.print(var_143); + result += ""; + result += "\n]"; + return result; + } +} + + +interface Tester_Interface_11 { + public Tester_Class_4 func_0(final int arg_0, final byte arg_1); + public Tester_Class_2 func_1(Tester_Class_5 arg_0, final Tester_Class_0 arg_1, final int arg_2); +} + +public class Test6712835 { + final boolean var_149 = false; + Tester_Class_8 var_150; + final long var_151 = 8058077687473630208L; + + + protected final Tester_Class_1 func_0(final Object arg_0, Tester_Class_3 arg_1, final Tester_Class_4 arg_2, int arg_3) + { + Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)arg_0)); + --Tester_Class_3.var_63; + (var_150 = (((new Tester_Class_10[arg_2.var_71])[(((Tester_Class_6)arg_0).var_94 = arg_2).var_71 &= Tester_Class_3.var_63 << ~arg_2.var_71]).var_142 = (var_150 = (((Tester_Class_10)arg_0).var_142 = (Tester_Class_8)arg_0)))).var_113 = arg_2; + Tester_Class_7.var_114 = (Tester_Class_7.var_114 = false ? (Tester_Class_5)arg_0 : (Tester_Class_5)arg_0); + ((((arg_1 = arg_1).var_1 |= "lgcrda".equalsIgnoreCase("ontlkst")) ? (Tester_Class_1)arg_0 : (Tester_Class_3.var_60 = (Tester_Class_1)arg_0)).var_29 ? (arg_1 = (Tester_Class_3)(((Tester_Class_7)arg_0).var_112 = (Tester_Class_9)arg_0)) : arg_1).var_57 >>>= ']'; + Tester_Class_8.var_114 = (Tester_Class_5)arg_0; + ((Tester_Class_3.var_55 &= (arg_1.var_1 = true)) ? (Tester_Class_6)(new Tester_Class_0[Tester_Class_3.var_58][Tester_Class_10.var_138])[Tester_Class_10.var_138][Tester_Class_10.var_138] : (Tester_Class_6)arg_0).var_94 = arg_2; + { + Tester_Class_3.var_55 &= ((Tester_Class_3.var_60 = new Tester_Class_1()).var_1 &= false); + Tester_Class_2.var_44 -= (arg_3 |= + ~6610561718704644096L); + ((Tester_Class_8)arg_0).var_113 = ((((Tester_Class_10)(Tester_Class_0)arg_0).var_142 = (var_150 = (Tester_Class_8)arg_0)).var_124 = arg_2); + (! (false | Tester_Class_5.var_86) ? (Tester_Class_10)arg_0 : (new Tester_Class_10[arg_1.var_61][arg_1.var_61])[Tester_Class_10.var_138][Tester_Class_10.var_138]).var_139 = ((Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)arg_0)).var_31 = (((Tester_Class_9)arg_0).var_128 = (((Tester_Class_9)arg_0).var_128 = (Tester_Class_2)arg_0))); + } + final Tester_Interface_11 var_152 = !((Tester_Class_1)arg_0).var_29 ^ Tester_Class_5.var_86 ? (new Tester_Interface_11[arg_2.var_71][arg_1.var_61])[arg_1.var_61][arg_1.var_61] : (new Tester_Interface_11[arg_2.var_71][arg_2.var_71])[Tester_Class_10.var_138][Tester_Class_3.var_58]; + Tester_Class_3.var_64 /= (arg_3 >>= ++((Tester_Class_6)(Tester_Class_0)arg_0).var_92) * Tester_Class_9.var_132; + Tester_Class_0 var_153 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)arg_0))))).var_31 = (((new Tester_Class_9[arg_1.var_61])[arg_1.var_61 *= 634692606]).var_128 = !false ? (Tester_Class_2)arg_0 : (Tester_Class_2)arg_0); + (Tester_Class_10.var_140 ? (Tester_Class_7)arg_0 : (var_150 = (Tester_Class_8)(Tester_Class_7)arg_0)).var_112 = Tester_Class_3.var_64 != ((((Tester_Class_10)(var_153 = (Tester_Class_8.var_114 = (Tester_Class_5)arg_0))).var_1 |= arg_1.var_1) ? (Tester_Class_6)var_153 : (Tester_Class_6)var_153).var_99-- ? (Tester_Class_7)((var_150 = (Tester_Class_8)arg_0).var_112 = (Tester_Class_10)var_153) : (Tester_Class_7)arg_0; + (((new Tester_Class_7[Tester_Class_10.var_138][arg_2.var_71])[Tester_Class_3.var_58])[arg_2.var_71]).var_112 = arg_0; + if (!false) + { + arg_3 <<= (Tester_Class_2.var_46 /= - ((byte)((Tester_Class_10)arg_0).var_144)) - ((Tester_Class_6)arg_0).var_99; + } + else + { + ((Tester_Class_7)(((Tester_Class_8)arg_0).var_112 = var_153)).var_113 = arg_2; + ((Tester_Class_9)arg_0).var_128 = (((Tester_Class_9)(((Tester_Class_7)arg_0).var_112 = (Tester_Class_7)arg_0)).var_128 = (((Tester_Class_9)arg_0).var_128 = (Tester_Class_2)arg_0)); + } + (((Tester_Class_10)arg_0).var_142 = (Tester_Class_8)arg_0).var_124 = (((Tester_Class_6)var_153).var_94 = arg_2); + final char var_154 = arg_1.var_57 %= ((Tester_Class_6)var_153).var_93--; + (true ? arg_1 : (arg_1 = arg_1)).equals(arg_0); + (Tester_Class_10.var_140 ? (new Tester_Class_6[Tester_Class_10.var_138])[arg_2.var_71] : (new Tester_Class_6[(Tester_Class_10.var_143 = arg_1).var_61])[arg_1.var_61]).var_94 = ((((new Tester_Class_7[arg_2.var_71][arg_1.var_61][Tester_Class_10.var_138])[Tester_Class_10.var_138])[arg_2.var_71 = arg_2.var_71][Tester_Class_10.var_138]).var_113 = (((Tester_Class_7)arg_0).var_113 = arg_2)); + Tester_Class_3.var_60 = ((Tester_Class_10)(((Tester_Class_7)arg_0).var_112 = (Tester_Class_7)(((Tester_Class_10)var_153).var_139 = new Tester_Class_6[Tester_Class_10.var_138][Tester_Class_10.var_138]))).var_1 ? (Tester_Class_3.var_60 = (Tester_Class_1)var_153) : (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)(Tester_Class_9.var_133 = (Tester_Class_10)arg_0))); + ((Tester_Class_7)(((Tester_Class_10)arg_0).var_139 = new Tester_Class_10[Tester_Class_3.var_58][--arg_2.var_71])).var_112 = new byte[(((Tester_Class_8)(Tester_Class_7)((var_150 = (var_150 = (Tester_Class_8)arg_0)).var_112 = arg_2)).var_113 = (((Tester_Class_7)arg_0).var_113 = arg_2)).var_71]; + Tester_Class_8 var_155; + (Tester_Class_3.var_55 & arg_2.equals(arg_0) ? (Tester_Class_10)var_153 : (Tester_Class_10)var_153).var_3 %= Tester_Class_6.var_91; + return ((Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)var_153)))).var_29 ? ! !true : Tester_Class_10.var_140 | Tester_Class_3.var_55) || Tester_Class_3.var_55 ? (Tester_Class_3.var_60 = (Tester_Class_1)(((Tester_Class_10)var_153).var_139 = (Tester_Class_6)var_153)) : new Tester_Class_1(); + } + + protected Tester_Class_5 func_1(Tester_Class_0 arg_0, final float arg_1) + { + (!Tester_Class_10.var_140 ? (Tester_Class_6)arg_0 : (Tester_Class_6)arg_0).var_90 /= ((Tester_Class_8.var_109 = (new boolean[Tester_Class_10.var_138][Tester_Class_3.var_58])[((Tester_Class_6)arg_0).var_99][Tester_Class_10.var_138] ? (Tester_Class_3)((Tester_Class_3.var_60 = (Tester_Class_1)arg_0).var_31 = (Tester_Class_6)arg_0) : (Tester_Class_3)arg_0).var_61 *= Tester_Class_3.var_58); + { + "".toLowerCase(); + } + ((Tester_Class_10)arg_0).var_139 = new Tester_Class_8(); + arg_0 = (new Tester_Class_6[((Tester_Class_6)arg_0).var_99])[Tester_Class_3.var_58]; + if (((Tester_Class_10)(arg_0 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)arg_0)))).var_145) + { + Tester_Class_3.var_63++; + } + else + { + ++Tester_Class_2.var_46; + } + (((Tester_Class_3.var_55 ^= Tester_Class_3.var_55 ^ true) ? (Tester_Class_10)arg_0 : (Tester_Class_10)arg_0).var_145 || true ? (Tester_Class_6)arg_0 : (Tester_Class_6)(((Tester_Class_7)(((Tester_Class_10)arg_0).var_139 = (Tester_Class_10)arg_0)).var_112 = "jlixai")).var_99--; + Tester_Class_5.var_81 = Tester_Class_3.var_55 && ! (arg_0.var_1 = arg_0.var_1); + { + ((new Tester_Class_6[Tester_Class_3.var_58])[(true ? (Tester_Class_6)(Tester_Class_9.var_133 = (Tester_Class_10)arg_0) : (Tester_Class_6)(((Tester_Class_1)arg_0).var_31 = (Tester_Class_10)arg_0)).var_99]).var_90 *= (Tester_Class_3.var_64 %= Tester_Class_3.var_63); + } + ++Tester_Class_2.var_46; + Tester_Class_0 var_156; + Tester_Class_2.var_46++; + Tester_Class_8.var_114 = (Tester_Class_7.var_114 = (Tester_Class_8.var_114 = (Tester_Class_5)arg_0)); + Tester_Class_6.func_2((Tester_Class_7.var_114 = (Tester_Class_7.var_114 = (Tester_Class_7.var_114 = (Tester_Class_5)arg_0))).var_83 = (byte)(((Tester_Class_10)arg_0).var_142 = (new Tester_Class_8[Tester_Class_3.var_58][Tester_Class_3.var_58])[Tester_Class_3.var_58][Tester_Class_10.var_138]).var_110, Tester_Class_6.var_96, (new byte[Tester_Class_3.var_58])[Tester_Class_10.var_138]); + Tester_Class_7.var_114 = (new Tester_Class_5[Tester_Class_10.var_138])[((Tester_Class_3)arg_0).var_61]; + boolean var_157 = Tester_Class_10.var_140; + (Tester_Class_3.var_60 = (Tester_Class_1)arg_0).var_1 ^= Tester_Class_10.var_140; + return Tester_Class_8.var_114 = (Tester_Class_7.var_114 = (Tester_Class_8.var_114 = (Tester_Class_5)arg_0)); + } + + final static int func_2(Tester_Class_6 arg_0) + { + new Tester_Class_9(); + { + ++Tester_Class_3.var_63; + } + new Tester_Class_3().var_57--; + Tester_Class_1 var_158; + String var_159; + --Tester_Class_6.var_96; + { + new String(); + } + var_159 = (var_159 = arg_0.var_4); + { + --Tester_Class_2.var_46; + } + final double var_160 = (Tester_Class_7.var_114 = (Tester_Class_8.var_114 = (Tester_Class_8.var_114 = (Tester_Class_5)(new Tester_Class_0[arg_0.var_99][arg_0.var_99])[Tester_Class_3.var_58][Tester_Class_3.var_58]))).var_1 ? Tester_Class_9.var_132 : Tester_Class_6.var_97; + Tester_Class_8 var_161; + char var_162 = 'O'; + Tester_Class_2.var_46++; + Tester_Class_6.var_96++; + { + new String(); + } + ++Tester_Class_6.var_96; + var_162 >>= ((new Tester_Class_4[arg_0.var_99])[arg_0.var_99++]).var_70 >> Tester_Class_6.var_91; + (Tester_Class_7.var_114 = (Tester_Class_7.var_114 = (new Tester_Class_5[Tester_Class_3.var_58])[++arg_0.var_99])).var_83 = (arg_0.var_93 <<= Tester_Class_7.var_108); + --Tester_Class_6.var_96; + { + new Tester_Class_9().var_128 = new Tester_Class_2(); + } + arg_0 = arg_0; + { + Tester_Class_9 var_163; + } + ((Tester_Class_5)(Tester_Class_9.var_133 = arg_0)).var_83 = (arg_0.var_99 >>= Tester_Class_5.var_5); + arg_0.var_99 = Tester_Class_10.var_138; + Tester_Class_3.var_60 = (var_158 = (Tester_Class_3.var_60 = (Tester_Class_1)(Tester_Class_9.var_133 = arg_0))); + return Tester_Class_6.var_91; + } + + protected final Tester_Class_9 func_3() + { + Tester_Class_2.var_44 = 3210658399310388224L; + ++Tester_Class_6.var_96; + short var_164 = 15978; + var_164++; + Tester_Class_5.var_81 = true; + return Tester_Class_3.var_55 ? new Tester_Class_9() : new Tester_Class_9(); + } + + final static Tester_Class_10 func_4(Tester_Class_3 arg_0, String arg_1, final byte[] arg_2, final Object arg_3) + { + Tester_Class_1 var_165; + Tester_Class_3.var_63 += new Tester_Class_6().var_92 >= 3821095133162842112L ? (arg_0.var_61 |= Tester_Class_6.var_91) : Tester_Class_10.var_138; + return false ? ((var_165 = (Tester_Class_1)arg_3).var_29 ? (Tester_Class_10)arg_3 : (Tester_Class_10)arg_3) : (Tester_Class_10)(Tester_Class_0)arg_3; + } + + private static Object func_7(final short arg_0, String arg_1, final Tester_Class_3 arg_2) + { + Tester_Class_3.var_60 = (new Tester_Class_1[arg_2.var_61])[Tester_Class_10.var_138]; + return ((new Tester_Class_7[arg_2.var_61 |= Tester_Class_3.var_63])[arg_2.var_61 *= Tester_Class_6.var_98]).var_112 = new Tester_Class_8(); + } + + public static String execute() + { + try { + Test6712835 t = new Test6712835(); + try { t.test(); } + catch(Throwable e) { } + try { return t.toString(); } + catch (Throwable e) { return "Error during result conversion to String"; } + } catch (Throwable e) { return "Error during test execution"; } + } + + public static void main(String[] args) + { + try { + Test6712835 t = new Test6712835(); + try { t.test(); } + catch(Throwable e) { } + try { System.out.println(t); } + catch(Throwable e) { } + } catch (Throwable e) { } + } + + private void test() + { + Tester_Class_3.var_60 = true ? (Tester_Class_3.var_60 = new Tester_Class_1()) : new Tester_Class_1(); + double var_170 = 0; + Tester_Class_9.var_133 = (new Tester_Class_4().var_69 = new Tester_Class_3()); + new Tester_Class_6(); + String var_171; + new Tester_Class_9(); + do + { + new String(); + var_170++; + Tester_Class_3.var_64 = 1.0240330514364089E307; + new String(); + var_171 = (var_171 = Tester_Class_9.var_127); + Tester_Class_3.var_63--; + } while (var_170 < 525); + ((new Tester_Class_10[Tester_Class_10.var_138])[Tester_Class_2.var_45 = Tester_Class_3.var_58]).var_142 = (Tester_Class_8)(Tester_Class_7)(new Tester_Class_10().var_139 = new Tester_Class_2()); + long var_172 = 0L; + Tester_Class_3.var_64 /= (((new Tester_Class_6[Tester_Class_3.var_58])[Tester_Class_10.var_138]).var_99 ^= ((new Tester_Class_6[Tester_Class_3.var_58])[Tester_Class_10.var_138]).var_90) > 9.462466046830147E307 ? new Tester_Class_6().var_99 : Tester_Class_3.var_58; + short var_173; + (true ? new Tester_Class_2() : (func_3().var_128 = new Tester_Class_2())).var_3 *= (var_150 = new Tester_Class_8()).var_115; + (Tester_Class_3.var_60 = new Tester_Class_1()).var_31 = (((new Tester_Class_9[Tester_Class_3.var_58])[Tester_Class_10.var_138]).var_128 = (func_3().var_128 = (func_3().var_128 = (new Tester_Class_9().var_128 = new Tester_Class_2())))); + for (((new Tester_Class_10[new Tester_Class_6().var_99])[new Tester_Class_6().var_99++]).var_142 = (new Tester_Class_8[Tester_Class_10.var_138])[Tester_Class_3.var_58]; var_172 < 203 && (Tester_Class_3.var_55 &= (new boolean[Tester_Class_2.var_45 = Tester_Class_3.var_58])[Tester_Class_10.var_138]); Tester_Class_9.var_133 = (Tester_Class_7.var_114 = (new Tester_Class_5[Tester_Class_2.var_45 = Tester_Class_10.var_138][Tester_Class_10.var_138])[Tester_Class_3.var_58][Tester_Class_2.var_45 = Tester_Class_3.var_58])) + { + var_171 = Tester_Class_9.var_127; + var_172++; + Tester_Class_3.var_63++; + Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_1)(new Object[Tester_Class_3.var_58][Tester_Class_10.var_138])[Tester_Class_3.var_58][Tester_Class_3.var_58]))); + ++Tester_Class_2.var_46; + Tester_Class_2.var_46--; + Tester_Class_3.var_64 -= Tester_Class_3.var_58; + } + (Tester_Class_3.var_60 = new Tester_Class_1()).var_31 = ((new Tester_Class_8().var_124 = new Tester_Class_4()).var_69 = new Tester_Class_3()); + int var_174 = 0; + ((new Tester_Class_6[Tester_Class_10.var_138][Tester_Class_10.var_138])[Tester_Class_2.var_45 = Tester_Class_10.var_138][Tester_Class_2.var_45 = Tester_Class_3.var_58]).var_92 = 'Z'; + while ((Tester_Class_9.var_131 = Tester_Class_3.var_55) && (var_174 < 24 && !true)) + { + new Tester_Class_10(); + var_174++; + Tester_Class_3.var_64 %= (((new Tester_Class_6[Tester_Class_3.var_58])[Tester_Class_2.var_45 = Tester_Class_3.var_58]).var_93 ^= (byte)Tester_Class_3.var_59); + ((Tester_Class_10)(Tester_Class_9.var_133 = (new Tester_Class_5[((Tester_Class_6)(new Tester_Class_0[Tester_Class_10.var_138])[(byte)(Tester_Class_2.var_46 >>>= Tester_Class_7.var_108)]).var_99])[Tester_Class_10.var_138])).var_139 = (new Tester_Class_10[new Tester_Class_6().var_99][new Tester_Class_4().var_71])[new Tester_Class_4().var_71]; + } + int var_175 = 0; + (Tester_Class_10.var_140 ? (Tester_Class_2)(Tester_Class_9.var_133 = (Tester_Class_7.var_114 = (new Tester_Class_5[Tester_Class_10.var_138])[Tester_Class_10.var_138])) : new Tester_Class_2()).var_1 &= Tester_Class_3.var_55; + do + { + Tester_Class_10.var_143 = new Tester_Class_3(); + var_175++; + ++Tester_Class_2.var_46; + } while ((false ? true : var_149) | !Tester_Class_10.var_140 && var_175 < 97); + Tester_Class_9.var_131 = true; + (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = (Tester_Class_3.var_60 = new Tester_Class_1())))).var_1 &= (((new Tester_Class_10().var_1 = !true) ? new Tester_Class_10() : new Tester_Class_10()).var_145 ? new Tester_Class_3() : new Tester_Class_3()).var_1; + (true ? func_3() : func_3()).var_128 = ((((Tester_Class_5.var_86 = (Tester_Class_3.var_55 &= !var_149)) ? new Tester_Class_10() : new Tester_Class_10()).var_145 ? new Tester_Class_9() : func_3()).var_128 = var_149 ? new Tester_Class_2() : new Tester_Class_2()); + Tester_Class_3.var_59 -= (Tester_Class_5.var_81 = new Tester_Class_1().var_29) ^ !true ? 7920143378515332096L : new Tester_Class_6().var_92; + ((Tester_Class_3.var_60 = new Tester_Class_1()).var_1 ? (new Tester_Class_5[Tester_Class_10.var_138][Tester_Class_3.var_58])[Tester_Class_3.var_58][Tester_Class_3.var_58] : (Tester_Class_8.var_114 = new Tester_Class_5())).var_83 = Tester_Class_10.var_140 ? (Tester_Class_3.var_63 -= 2.0167496E38F) : ++Tester_Class_3.var_63; + double var_176 = 9.327780852480363E307; + } + public String toString() + { + String result = "[\n"; + result += "Test6712835.var_151 = "; result += Printer.print(var_151); + result += "\n"; + result += "Test6712835.var_149 = "; result += Printer.print(var_149); + result += "\n"; + result += "Test6712835.var_150 = "; result += Printer.print(var_150); + result += ""; + result += "\n]"; + return result; + } + static class Printer + { + public static String print(boolean arg) { return String.valueOf(arg); } + public static String print(byte arg) { return String.valueOf(arg); } + public static String print(short arg) { return String.valueOf(arg); } + public static String print(char arg) { return String.valueOf((int)arg); } + public static String print(int arg) { return String.valueOf(arg); } + public static String print(long arg) { return String.valueOf(arg); } + public static String print(float arg) { return String.valueOf(arg); } + public static String print(double arg) { return String.valueOf(arg); } + + + public static String print(Object arg) + { + return print_r(new java.util.Stack(), arg); + } + + private static String print_r(java.util.Stack visitedObjects, Object arg) + { + String result = ""; + if (arg == null) + result += "null"; + else + if (arg.getClass().isArray()) + { + for (int i = 0; i < visitedObjects.size(); i++) + if (visitedObjects.elementAt(i) == arg) return ""; + + visitedObjects.push(arg); + + final String delimiter = ", "; + result += "["; + + if (arg instanceof Object[]) + { + Object[] array = (Object[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print_r(visitedObjects, array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof boolean[]) + { + boolean[] array = (boolean[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof byte[]) + { + byte[] array = (byte[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof short[]) + { + short[] array = (short[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof char[]) + { + char[] array = (char[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof int[]) + { + int[] array = (int[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof long[]) + { + long[] array = (long[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof float[]) + { + float[] array = (float[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof double[]) + { + double[] array = (double[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + + result += "]"; + visitedObjects.pop(); + + } else + { + result += arg.toString(); + } + + return result; + } + } +} From 20de63f383e1417b4e39b9b5197db870a8c56df8 Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Fri, 25 Jul 2008 15:54:23 -0700 Subject: [PATCH 068/325] 6700047: C2 failed in idom_no_update Partial peeling shouldn't place clones into loop Reviewed-by: kvn --- hotspot/src/share/vm/opto/loopopts.cpp | 17 +++--- .../test/compiler/6700047/Test6700047.java | 60 +++++++++++++++++++ 2 files changed, 69 insertions(+), 8 deletions(-) create mode 100644 hotspot/test/compiler/6700047/Test6700047.java diff --git a/hotspot/src/share/vm/opto/loopopts.cpp b/hotspot/src/share/vm/opto/loopopts.cpp index f7fa3f21b2c..4353219f41c 100644 --- a/hotspot/src/share/vm/opto/loopopts.cpp +++ b/hotspot/src/share/vm/opto/loopopts.cpp @@ -1891,18 +1891,19 @@ void PhaseIdealLoop::clone_for_use_outside_loop( IdealLoopTree *loop, Node* n, N _igvn.hash_delete(use); use->set_req(j, n_clone); _igvn._worklist.push(use); + Node* use_c; if (!use->is_Phi()) { - Node* use_c = has_ctrl(use) ? get_ctrl(use) : use->in(0); - set_ctrl(n_clone, use_c); - assert(!loop->is_member(get_loop(use_c)), "should be outside loop"); - get_loop(use_c)->_body.push(n_clone); + use_c = has_ctrl(use) ? get_ctrl(use) : use->in(0); } else { // Use in a phi is considered a use in the associated predecessor block - Node *prevbb = use->in(0)->in(j); - set_ctrl(n_clone, prevbb); - assert(!loop->is_member(get_loop(prevbb)), "should be outside loop"); - get_loop(prevbb)->_body.push(n_clone); + use_c = use->in(0)->in(j); } + if (use_c->is_CountedLoop()) { + use_c = use_c->in(LoopNode::EntryControl); + } + set_ctrl(n_clone, use_c); + assert(!loop->is_member(get_loop(use_c)), "should be outside loop"); + get_loop(use_c)->_body.push(n_clone); _igvn.register_new_node_with_optimizer(n_clone); #if !defined(PRODUCT) if (TracePartialPeeling) { diff --git a/hotspot/test/compiler/6700047/Test6700047.java b/hotspot/test/compiler/6700047/Test6700047.java new file mode 100644 index 00000000000..55921d59465 --- /dev/null +++ b/hotspot/test/compiler/6700047/Test6700047.java @@ -0,0 +1,60 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * @test + * @bug 6700047 + * @summary C2 failed in idom_no_update + * @run main Test6700047 + */ + +public class Test6700047 { + public static void main(String[] args) { + for (int i = 0; i < 100000; i++) { + intToLeftPaddedAsciiBytes(); + } + } + + public static int intToLeftPaddedAsciiBytes() { + int offset = 40; + int q; + int r; + int i = 100; + int result = 1; + while (offset > 0) { + q = (i * 52429); + r = i; + offset--; + i = q; + if (i == 0) { + break; + } + } + if (offset > 0) { + for(int j = 0; j < offset; j++) { + result++; + } + } + return result; + } +} From 2d1fcda0d7fc039b1d2be6fd72fab6acb01c9804 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 25 Jul 2008 16:03:40 -0700 Subject: [PATCH 069/325] 6729552: jvm98 crashes with SS12 built jdk on Solaris X64 fastdebug version SS12 C++ tripped over new templates usage in instanceKlass.cpp. Reviewed-by: never --- hotspot/make/solaris/makefiles/fastdebug.make | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hotspot/make/solaris/makefiles/fastdebug.make b/hotspot/make/solaris/makefiles/fastdebug.make index 62eaeb8f968..3ac2ae212b1 100644 --- a/hotspot/make/solaris/makefiles/fastdebug.make +++ b/hotspot/make/solaris/makefiles/fastdebug.make @@ -38,6 +38,8 @@ OPT_CFLAGS/SLOWER = -xO2 # Problem with SS12 compiler, dtrace doesn't like the .o files (bug 6693876) ifeq ($(COMPILER_REV), 5.9) + # To avoid jvm98 crash + OPT_CFLAGS/instanceKlass.o = $(OPT_CFLAGS/SLOWER) # Not clear this workaround could be skipped in some cases. OPT_CFLAGS/vmGCOperations.o = $(OPT_CFLAGS/SLOWER) OPT_CFLAGS/java.o = $(OPT_CFLAGS/SLOWER) From 6a3f9fd998530b899a225a57564aa486f6f014b1 Mon Sep 17 00:00:00 2001 From: Xueming Shen Date: Sat, 26 Jul 2008 20:42:35 -0700 Subject: [PATCH 070/325] 6681798: (build) CharsetEncoder.java fails to compile in openjdk6 on ubutu 8.04 Replace awk-sed based spp.sh with a java regex based pre-processor Reviewed-by: alanb --- jdk/make/java/nio/Makefile | 6 +- jdk/make/java/nio/genCoder.sh | 6 +- jdk/make/java/nio/spp.sh | 165 ----------------- jdk/make/tools/Makefile | 1 + jdk/make/tools/spp/Makefile | 45 +++++ jdk/make/tools/src/build/tools/spp/Spp.java | 189 ++++++++++++++++++++ 6 files changed, 241 insertions(+), 171 deletions(-) delete mode 100644 jdk/make/java/nio/spp.sh create mode 100644 jdk/make/tools/spp/Makefile create mode 100644 jdk/make/tools/src/build/tools/spp/Spp.java diff --git a/jdk/make/java/nio/Makefile b/jdk/make/java/nio/Makefile index 9d083dab535..49446c69488 100644 --- a/jdk/make/java/nio/Makefile +++ b/jdk/make/java/nio/Makefile @@ -166,8 +166,8 @@ include $(BUILDDIR)/common/Library.gmk # Generate source files # -SPP = spp.sh -SPP_CMD = $(SH) $(SPP) +SPP_JARFILE = $(BUILDTOOLJARDIR)/spp.jar +SPP_CMD = $(BOOT_JAVA_CMD) -jar $(SPP_JARFILE) FILES_genout = $(FILES_gen:%.java=$(GENSRCDIR)/%.java) @@ -183,7 +183,7 @@ CS_GEN=$(NIO_GEN)/charset SCH_GEN=$(SNIO_GEN)/ch SCS_GEN=$(SNIO_GEN)/cs -sources: $(SPP) $(FILES_genout) +sources: $(SPP_JARFILE) $(FILES_genout) # # Generated buffer classes diff --git a/jdk/make/java/nio/genCoder.sh b/jdk/make/java/nio/genCoder.sh index def83d94dfd..769b98cd523 100644 --- a/jdk/make/java/nio/genCoder.sh +++ b/jdk/make/java/nio/genCoder.sh @@ -53,8 +53,8 @@ if [ x$what = xdecoder ]; then -Dcoding='decoding' \ -DOtherCoder='Encoder' \ -DreplTypeName='string' \ - -DdefaultRepl='"\\\\uFFFD"' \ - -DdefaultReplName='"\\\\uFFFD"<\/tt>' \ + -DdefaultRepl='"\\uFFFD"' \ + -DdefaultReplName='"\\uFFFD"<\/tt>' \ -DreplType='String' \ -DreplFQType='java.lang.String' \ -DreplLength='length()' \ @@ -84,7 +84,7 @@ elif [ x$what = xencoder ]; then -DOtherCoder='Decoder' \ -DreplTypeName='byte array' \ -DdefaultRepl='new byte[] { (byte)'"'"\\?"'"' }' \ - -DdefaultReplName='{<\/tt>\\\ (byte)'"'"\\?"'"'<\/tt>\\\ }<\/tt>' \ + -DdefaultReplName='{<\/tt>\ (byte)'"'"\\?"'"'<\/tt>\ }<\/tt>' \ -DreplType='byte[]' \ -DreplFQType='byte[]' \ -DreplLength='length' \ diff --git a/jdk/make/java/nio/spp.sh b/jdk/make/java/nio/spp.sh deleted file mode 100644 index 036ca228882..00000000000 --- a/jdk/make/java/nio/spp.sh +++ /dev/null @@ -1,165 +0,0 @@ -#! /bin/sh - -# -# Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved. -# 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 -# published by the Free Software Foundation. Sun designates this -# particular file as subject to the "Classpath" exception as provided -# by Sun in the LICENSE file that accompanied this code. -# -# 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. -# -# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, -# CA 95054 USA or visit www.sun.com if you need additional information or -# have any questions. -# - -# SPP: A simple/sed-based/stream preprocessor -# Mark Reinhold / mr@sun.com -# -# Usage: spp [-be] [-Kkey] -Dvar=value ... out -# -# Source-file constructs -# -# Meaningful only at beginning of line, works with any number of keys: -# -# #if[key] Includes text between #if/#end if -Kkey specified, -# #else[key] otherwise changes text to blank lines; key test -# #end[key] may be negated by prefixing !, e.g., #if[!key] -# -# #begin If -be is specified then lines up to and including -# #end #begin, and from #end to EOF, are deleted -# -# #warn Changed into warning that file is generated -# -# // ## Changed into blank line -# -# Meaningful anywhere in line, works only for first two keys: -# -# {#if[key]?yes} Expands to yes if -Kkey specified -# {#if[key]?yes:no} Expands to yes if -Kkey, otherwise no -# {#if[!key]?yes} Expands to yes if -Kother -# {#if[!key]?yes:no} Expands to yes if -Kother, otherwise no -# $var$ Expands to value if -Dvar=value given -# -# yes, no must not contain whitespace -# -# If the environment variable SED is defined, uses that instead of sed -# If the environment variable NAWK is defined, uses that instead of awk -# - -SED=${SED:-sed} -NAWK=${NAWK:-awk} - -# Map a string of the form -Dvar=value into an appropriate sed command -# -subst() { - # The first two lines are to avoid the direct use of echo, - # which does not treat backslashes consistently across platforms - echo '' \ - | $SED -e "s.*$*" \ - | $SED -e 's-D\([a-zA-Z_][-a-zA-Z_]*\)=\(.*\)'"s\\\\\$\\1\\\\\$\2gg" \ - -e 's-D\([a-zA-Z_][-a-zA-Z_]*\)'"s\\\\\$\\1\\\\\$1gg" \ - -e 's/ //g' -} - -es= -be= -keys= -key1=_1_ -key2=_2_ -while [ $# -gt 0 ]; do - case "$1" in - -be) - be='-e 1,/^#begin$/d -e /^#end$/,$d' - ;; - -D*) - es="$es -e `subst $1`" - ;; - -K*) - nk=`echo $1 | $SED -e 's/-K//'` - if [ "x$keys" = x ]; then keys="$nk"; else keys="$keys $nk"; fi - if [ "x$key1" = x_1_ ]; then key1="$nk"; - elif [ "x$key2" = x_2_ ]; then key2="$nk"; fi - ;; - *) - echo "Usage: $0 [-be] [-Kkey] -Dvar=value ... out" - exit 1 - ;; - esac - shift -done - -text='[-a-zA-Z0-9&;,.<>/#() ]' - -$SED $es \ - -e 's// /g' \ - -e "s@^#warn .*@// -- This file was mechanically generated: Do not edit! -- //@" \ - -e 's-// ##.*$--' $be \ - -e "s/{#if\[$key1\]?\($text*\):\($text*\)}/\1/g" \ - -e "s/{#if\[!$key1\]?\($text*\):\($text*\)}/\2/g" \ - -e "s/{#if\[$key1\]?\($text*\)}/\1/g" \ - -e "s/{#if\[!$key1\]?\($text*\)}//g" \ - -e "s/{#if\[$key2\]?\($text*\):\($text*\)}/\1/g" \ - -e "s/{#if\[!$key2\]?\($text*\):\($text*\)}/\2/g" \ - -e "s/{#if\[$key2\]?\($text*\)}/\1/g" \ - -e "s/{#if\[!$key2\]?\($text*\)}//g" \ - -e "s/{#if\[[a-z]*\]?\($text*\):\($text*\)}/\2/g" \ - -e "s/{#if\[![a-z]*\]?\($text*\):\($text*\)}/\1/g" \ - -e "s/{#if\[[a-z]*\]?\($text*\)}//g" \ - -e "s/{#if\[![a-z]*\]?\($text*\)}/\1/g" \ -| $NAWK \ - 'function key(s) { - i = match(s, "[a-zA-Z][a-zA-Z]*\\]"); - if (i > 0) return substr(s, i, RLENGTH - 1); - return "XYZZY"; } - function neg(s) { return match(s, "!") > 0; } - BEGIN { - KEYS = "'"$keys"'" - n = split(KEYS, ks, " *"); - for (i = 1; i <= n; i++) keys[ks[i]] = 1; - top = 1; copy[top] = 1 } - /^#if\[!?[a-zA-Z][a-zA-Z]*\]/ \ - { k = key($0); - n = neg($0); - stack[++top] = k; - if ((k in keys) == !n) { - copy[top] = copy[top - 1]; - } else { - copy[top] = 0; - } - print ""; next } - /^#else\[!?[a-zA-Z][a-zA-Z]*\]/ \ - { k = key($0); - if (stack[top] == k) { - copy[top] = copy[top - 1] && !copy[top]; - } else { - printf "%d: Mismatched #else key\n", NR | "cat 1>&2"; - exit 11 - } - print ""; next } - /^#end\[!?[a-zA-Z][a-zA-Z]*\]/ \ - { k = key($0); - if (stack[top] == k) { - top--; - } else { - printf "%d: Mismatched #end key\n", NR | "cat 1>&2" - exit 11 - } - print ""; next } - /^#/ { - printf "%d: Malformed #directive\n", NR | "cat 1>&2" - exit 11 - } - { if (copy[top]) print; else print "" }' diff --git a/jdk/make/tools/Makefile b/jdk/make/tools/Makefile index 1b3c4063c8c..68dfe8ef333 100644 --- a/jdk/make/tools/Makefile +++ b/jdk/make/tools/Makefile @@ -51,6 +51,7 @@ SUBDIRS = \ jdwpgen \ makeclasslist \ strip_properties \ + spp \ CharsetMapping all build clean clobber:: diff --git a/jdk/make/tools/spp/Makefile b/jdk/make/tools/spp/Makefile new file mode 100644 index 00000000000..5f720120b0d --- /dev/null +++ b/jdk/make/tools/spp/Makefile @@ -0,0 +1,45 @@ +# +# Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. +# 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 +# published by the Free Software Foundation. Sun designates this +# particular file as subject to the "Classpath" exception as provided +# by Sun in the LICENSE file that accompanied this code. +# +# 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. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + +# +# Makefile for build spp tool +# + +BUILDDIR = ../.. +PACKAGE = build.tools.spp +PRODUCT = tools +PROGRAM = spp +include $(BUILDDIR)/common/Defs.gmk + + +BUILDTOOL_SOURCE_ROOT = $(BUILDDIR)/tools/src +BUILDTOOL_MAIN = $(PKGDIR)/Spp.java + +# +# Build tool jar rules. +# +include $(BUILDDIR)/common/BuildToolJar.gmk + + diff --git a/jdk/make/tools/src/build/tools/spp/Spp.java b/jdk/make/tools/src/build/tools/spp/Spp.java new file mode 100644 index 00000000000..8a220f59234 --- /dev/null +++ b/jdk/make/tools/src/build/tools/spp/Spp.java @@ -0,0 +1,189 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package build.tools.spp; + +import java.util.*; +import java.util.regex.*; + +/* + * Spp: A simple regex-based stream preprocessor based on Mark Reinhold's + * sed-based spp.sh + * + * Usage: java build.tools.spp.Spp [-be] [-Kkey] -Dvar=value ... out + * + * Source-file constructs + * + * Meaningful only at beginning of line, works with any number of keys: + * + * #if[key] Includes text between #if/#end if -Kkey specified, + * #else[key] otherwise changes text to blank lines; key test + * #end[key] may be negated by prefixing !, e.g., #if[!key] + * + * #begin If -be is specified then lines up to and including + * #end #begin, and from #end to EOF, are deleted + * + * #warn Changed into warning that file is generated + * + * // ## Changed into blank line + * + * Meaningful anywhere in line + * + * {#if[key]?yes} Expands to yes if -Kkey specified + * {#if[key]?yes:no} Expands to yes if -Kkey, otherwise no + * {#if[!key]?yes} Expands to yes if -Kother + * {#if[!key]?yes:no} Expands to yes if -Kother, otherwise no + * $var$ Expands to value if -Dvar=value given + * + * yes, no must not contain whitespace + * + * @author Xueming Shen + */ + +public class Spp { + public static void main(String args[]) throws Exception { + Map vars = new HashMap(); + Set keys = new HashSet(); + boolean be = false; + + for (String arg:args) { + if (arg.startsWith("-D")) { + int i = arg.indexOf('='); + vars.put(arg.substring(2, i),arg.substring(i+1)); + } else if (arg.startsWith("-K")) { + keys.add(arg.substring(2)); + } else if ("-be".equals(arg)) { + be = true; + } else { + System.err.println("Usage: java build.tools.spp.Spp [-be] [-Kkey] -Dvar=value ... out"); + System.exit(-1); + } + } + + StringBuffer out = new StringBuffer(); + new Spp().spp(new Scanner(System.in), + out, "", + keys, vars, be, + false); + System.out.print(out.toString()); + } + + static final String LNSEP = System.getProperty("line.separator"); + static final String KEY = "([a-zA-Z0-9]+)"; + static final String VAR = "([a-zA-Z0-9_\\-]+)"; + static final String TEXT = "([a-zA-Z0-9&;,.<>/#() \\$]+)"; // $ -- hack embedded $var$ + + static final int GN_NOT = 1; + static final int GN_KEY = 2; + static final int GN_YES = 3; + static final int GN_NO = 5; + static final int GN_VAR = 6; + + Matcher ifkey = Pattern.compile("^#if\\[(!)?" + KEY + "\\]").matcher(""); + Matcher elsekey = Pattern.compile("^#else\\[(!)?" + KEY + "\\]").matcher(""); + Matcher endkey = Pattern.compile("^#end\\[(!)?" + KEY + "\\]").matcher(""); + Matcher vardef = Pattern.compile("\\{#if\\[(!)?" + KEY + "\\]\\?" + TEXT + "(:"+ TEXT + ")?\\}|\\$" + VAR + "\\$").matcher(""); + Matcher vardef2 = Pattern.compile("\\$" + VAR + "\\$").matcher(""); + + void append(StringBuffer buf, String ln, + Set keys, Map vars) { + vardef.reset(ln); + while (vardef.find()) { + String repl = ""; + if (vardef.group(GN_VAR) != null) + repl = vars.get(vardef.group(GN_VAR)); + else { + boolean test = keys.contains(vardef.group(GN_KEY)); + if (vardef.group(GN_NOT) != null) + test = !test; + repl = test?vardef.group(GN_YES):vardef.group(GN_NO); + if (repl == null) + repl = ""; + else { // embedded $var$ + while (vardef2.reset(repl).find()) { + repl = vardef2.replaceFirst(vars.get(vardef2.group(1))); + } + } + } + vardef.appendReplacement(buf, repl); + } + vardef.appendTail(buf); + } + + // return true if #end[key], #end or EOF reached + boolean spp(Scanner in, StringBuffer buf, String key, + Set keys, Map vars, + boolean be, boolean skip) { + while (in.hasNextLine()) { + String ln = in.nextLine(); + if (be) { + if (ln.startsWith("#begin")) { + buf.setLength(0); //clean up to this line + continue; + } + if (ln.equals("#end")) { + while (in.hasNextLine()) + in.nextLine(); + return true; //discard the rest to EOF + } + } + if (ifkey.reset(ln).find()) { + String k = ifkey.group(GN_KEY); + boolean test = keys.contains(k); + if (ifkey.group(GN_NOT) != null) + test = !test; + buf.append(LNSEP); + if (!spp(in, buf, k, keys, vars, be, skip || !test)) { + spp(in, buf, k, keys, vars, be, skip || test); + } + continue; + } + if (elsekey.reset(ln).find()) { + if (!key.equals(elsekey.group(GN_KEY))) { + throw new Error("Mis-matched #if-else-end at line <" + ln + ">"); + } + buf.append(LNSEP); + return false; + } + if (endkey.reset(ln).find()) { + if (!key.equals(endkey.group(GN_KEY))) { + throw new Error("Mis-matched #if-else-end at line <" + ln + ">"); + } + buf.append(LNSEP); + return true; + } + if (ln.startsWith("#warn")) { + ln = "// -- This file was mechanically generated: Do not edit! -- //"; + } else if (ln.trim().startsWith("// ##")) { + ln = ""; + } + if (!skip) { + append(buf, ln, keys, vars); + } + buf.append(LNSEP); + } + return true; + } +} From 4d46dbd62c9064102ddb1d7bcc72f22c84ab1507 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Sun, 27 Jul 2008 19:16:15 +0800 Subject: [PATCH 071/325] 6709758: keytool default cert fingerprint algorithm should be SHA1, not MD5 Reviewed-by: mullan, xuelei --- jdk/src/share/classes/sun/security/tools/KeyTool.java | 8 ++++---- jdk/src/share/classes/sun/security/util/Resources.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/jdk/src/share/classes/sun/security/tools/KeyTool.java b/jdk/src/share/classes/sun/security/tools/KeyTool.java index 68fb2fa953e..220dbd033b1 100644 --- a/jdk/src/share/classes/sun/security/tools/KeyTool.java +++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java @@ -1454,8 +1454,8 @@ public final class KeyTool { } else { // Print the digest of the user cert only out.println - (rb.getString("Certificate fingerprint (MD5): ") + - getCertFingerPrint("MD5", chain[0])); + (rb.getString("Certificate fingerprint (SHA1): ") + + getCertFingerPrint("SHA1", chain[0])); } } } else if (keyStore.entryInstanceOf(alias, @@ -1472,8 +1472,8 @@ public final class KeyTool { out.println(cert.toString()); } else { out.println(rb.getString("trustedCertEntry,")); - out.println(rb.getString("Certificate fingerprint (MD5): ") - + getCertFingerPrint("MD5", cert)); + out.println(rb.getString("Certificate fingerprint (SHA1): ") + + getCertFingerPrint("SHA1", cert)); } } else { out.println(rb.getString("Unknown Entry Type")); diff --git a/jdk/src/share/classes/sun/security/util/Resources.java b/jdk/src/share/classes/sun/security/util/Resources.java index 0f5982183ad..e89d6cdfc99 100644 --- a/jdk/src/share/classes/sun/security/util/Resources.java +++ b/jdk/src/share/classes/sun/security/util/Resources.java @@ -171,7 +171,7 @@ public class Resources extends java.util.ListResourceBundle { {"Entry type: ", "Entry type: {0}"}, {"Certificate chain length: ", "Certificate chain length: "}, {"Certificate[(i + 1)]:", "Certificate[{0,number,integer}]:"}, - {"Certificate fingerprint (MD5): ", "Certificate fingerprint (MD5): "}, + {"Certificate fingerprint (SHA1): ", "Certificate fingerprint (SHA1): "}, {"Entry type: trustedCertEntry\n", "Entry type: trustedCertEntry\n"}, {"trustedCertEntry,", "trustedCertEntry,"}, {"Keystore type: ", "Keystore type: "}, From c936a75ed04433b52cb87c9bd4b5c8958d2b0d3c Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Mon, 28 Jul 2008 10:22:10 +0100 Subject: [PATCH 072/325] 6720185: DiagnosticFormatter refactoring Brand new hierarchy of diagnostic formatters for achieving better reusability Reviewed-by: jjg --- .../tools/javac/api/DiagnosticFormatter.java | 117 ++++++++ .../util/AbstractDiagnosticFormatter.java | 169 +++++++++++ .../javac/util/BasicDiagnosticFormatter.java | 190 +++++++++++++ .../tools/javac/util/DiagnosticFormatter.java | 267 ------------------ .../sun/tools/javac/util/JCDiagnostic.java | 58 +--- .../classes/com/sun/tools/javac/util/Log.java | 18 +- .../javac/util/RawDiagnosticFormatter.java | 107 +++++++ 7 files changed, 606 insertions(+), 320 deletions(-) create mode 100644 langtools/src/share/classes/com/sun/tools/javac/api/DiagnosticFormatter.java create mode 100644 langtools/src/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java create mode 100644 langtools/src/share/classes/com/sun/tools/javac/util/BasicDiagnosticFormatter.java delete mode 100644 langtools/src/share/classes/com/sun/tools/javac/util/DiagnosticFormatter.java create mode 100644 langtools/src/share/classes/com/sun/tools/javac/util/RawDiagnosticFormatter.java diff --git a/langtools/src/share/classes/com/sun/tools/javac/api/DiagnosticFormatter.java b/langtools/src/share/classes/com/sun/tools/javac/api/DiagnosticFormatter.java new file mode 100644 index 00000000000..03bc2fe9468 --- /dev/null +++ b/langtools/src/share/classes/com/sun/tools/javac/api/DiagnosticFormatter.java @@ -0,0 +1,117 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.tools.javac.api; + +import java.util.Locale; +import javax.tools.Diagnostic; + +/** + * Provides simple functionalities for javac diagnostic formatting + * @param type of diagnostic handled by this formatter + */ +public interface DiagnosticFormatter> { + + /** + * Whether the source code output for this diagnostic is to be displayed + * + * @param diag diagnostic to be formatted + * @return true if the source line this diagnostic refers to is to be displayed + */ + boolean displaySource(D diag); + + /** + * Format the contents of a diagnostics + * + * @param diag the diagnostic to be formatted + * @param l locale object to be used for i18n + * @return a string representing the diagnostic + */ + public String format(D diag, Locale l); + + /** + * Controls the way in which a diagnostic message is displayed. + * + * @param diag diagnostic to be formatted + * @param l locale object to be used for i18n + * @return string representation of the diagnostic message + */ + public String formatMessage(D diag,Locale l); + + /** + * Controls the way in which a diagnostic kind is displayed. + * + * @param diag diagnostic to be formatted + * @param l locale object to be used for i18n + * @return string representation of the diagnostic prefix + */ + public String formatKind(D diag, Locale l); + + /** + * Controls the way in which a diagnostic source is displayed. + * + * @param diag diagnostic to be formatted + * @param l locale object to be used for i18n + * @return string representation of the diagnostic source + */ + public String formatSource(D diag, Locale l); + + /** + * Controls the way in which a diagnostic position is displayed. + * + * @param diag diagnostic to be formatted + * @param pk enum constant representing the position kind + * @param l locale object to be used for i18n + * @return string representation of the diagnostic position + */ + public String formatPosition(D diag, PositionKind pk, Locale l); + //where + /** + * This enum defines a set of constants for all the kinds of position + * that a diagnostic can be asked for. All positions are intended to be + * relative to a given diagnostic source. + */ + public enum PositionKind { + /** + * Start position + */ + START, + /** + * End position + */ + END, + /** + * Line number + */ + LINE, + /** + * Column number + */ + COLUMN, + /** + * Offset position + */ + OFFSET + } +} diff --git a/langtools/src/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java b/langtools/src/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java new file mode 100644 index 00000000000..54844470bcf --- /dev/null +++ b/langtools/src/share/classes/com/sun/tools/javac/util/AbstractDiagnosticFormatter.java @@ -0,0 +1,169 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * 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 + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * 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. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.tools.javac.util; + +import java.util.Collection; +import java.util.Locale; +import javax.tools.JavaFileObject; + +import com.sun.tools.javac.api.DiagnosticFormatter; +import com.sun.tools.javac.api.Formattable; +import com.sun.tools.javac.api.DiagnosticFormatter.PositionKind; +import com.sun.tools.javac.file.JavacFileManager; + +/** + * This abstract class provides a basic implementation of the functionalities that should be provided + * by any formatter used by javac. Among the main features provided by AbstractDiagnosticFormatter are: + * + *