Path: blob/master/src/java.desktop/unix/classes/sun/awt/X11/XChoicePeer.java
41159 views
/*1* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.awt.X11;2627import java.awt.Color;28import java.awt.Insets;29import java.awt.Point;30import java.awt.FontMetrics;31import java.awt.Dimension;32import java.awt.Rectangle;33import java.awt.Choice;34import java.awt.Toolkit;35import java.awt.Graphics;36import java.awt.Component;37import java.awt.AWTEvent;38import java.awt.Insets;39import java.awt.Font;4041import java.awt.peer.ChoicePeer;4243import java.awt.event.FocusEvent;44import java.awt.event.InvocationEvent;45import java.awt.event.MouseEvent;46import java.awt.event.MouseWheelEvent;47import java.awt.event.KeyEvent;48import java.awt.event.ItemEvent;4950import sun.util.logging.PlatformLogger;5152// FIXME: tab traversal should be disabled when mouse is captured (4816336)5354// FIXME: key and mouse events should not be delivered to listeners when the Choice is unfurled. Must override handleNativeKey/MouseEvent (4816336)5556// FIXME: test programmatic add/remove/clear/etc5758// FIXME: account for unfurling at the edge of the screen59// Note: can't set x,y on layout(), 'cause moving the top-level to the60// edge of the screen won't call layout(). Just do it on paint, I guess6162// TODO: make painting more efficient (i.e. when down arrow is pressed, only two items should need to be repainted.6364public final class XChoicePeer extends XComponentPeer implements ChoicePeer, ToplevelStateListener {65private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.X11.XChoicePeer");6667private static final int MAX_UNFURLED_ITEMS = 10; // Maximum number of68// items to be displayed69// at a time in an70// unfurled Choice71// Description of these constants in ListHelper72public static final int TEXT_SPACE = 1;73public static final int BORDER_WIDTH = 1;74public static final int ITEM_MARGIN = 1;75public static final int SCROLLBAR_WIDTH = 15;767778// SHARE THESE!79private static final Insets focusInsets = new Insets(0,0,0,0);808182static final int WIDGET_OFFSET = 18;8384// Stolen from Tiny85static final int TEXT_XPAD = 8;86static final int TEXT_YPAD = 6;8788// FIXME: Motif uses a different focus color for the item within89// the unfurled Choice list and for when the Choice itself is focused and90// popped up.91static final Color focusColor = Color.black;9293// TODO: there is a time value that the mouse is held down. If short94// enough, the Choice stays popped down. If long enough, Choice95// is furled when the mouse is released9697private boolean unfurled = false; // Choice list is popped down9899private boolean dragging = false; // Mouse was pressed and is being100// dragged over the (unfurled)101// Choice102103private boolean mouseInSB = false; // Mouse is interacting with the104// scrollbar105106private boolean firstPress = false; // mouse was pressed on107// furled Choice so we108// not need to furl the109// Choice when MOUSE_RELEASED occurred110111// 6425067. Mouse was pressed on furled choice and dropdown list appeared over Choice itself112// and then there were no mouse movements until MOUSE_RELEASE.113// This scenario leads to ItemStateChanged as the choice logic uses114// MouseReleased event to send ItemStateChanged. To prevent it we should115// use a combination of firstPress and wasDragged variables.116// The only difference in dragging and wasDragged is: last one will not117// set to false on mouse ungrab. It become false after MouseRelased() finishes.118private boolean wasDragged = false;119private ListHelper helper;120private UnfurledChoice unfurledChoice;121122// TODO: Choice remembers where it was scrolled to when unfurled - it's not123// always to the currently selected item.124125// Indicates whether or not to paint selected item in the choice.126// Default is to paint127private boolean drawSelectedItem = true;128129// If set, indicates components under which choice popup should be showed.130// The choice's popup width and location should be adjust to appear131// under both choice and alignUnder component.132private Component alignUnder;133134// If cursor is outside of an unfurled Choice when the mouse is135// released, Choice item should NOT be updated. Remember the proper index.136private int dragStartIdx = -1;137138// Holds the listener (XFileDialogPeer) which the processing events from the choice139// See 6240074 for more information140private XChoicePeerListener choiceListener;141142XChoicePeer(Choice target) {143super(target);144}145146void preInit(XCreateWindowParams params) {147super.preInit(params);148Choice target = (Choice)this.target;149int numItems = target.getItemCount();150unfurledChoice = new UnfurledChoice(target);151getToplevelXWindow().addToplevelStateListener(this);152helper = new ListHelper(unfurledChoice,153getGUIcolors(),154numItems,155false,156true,157false,158target.getFont(),159MAX_UNFURLED_ITEMS,160TEXT_SPACE,161ITEM_MARGIN,162BORDER_WIDTH,163SCROLLBAR_WIDTH);164}165166void postInit(XCreateWindowParams params) {167super.postInit(params);168Choice target = (Choice)this.target;169int numItems = target.getItemCount();170171// Add all items172for (int i = 0; i < numItems; i++) {173helper.add(target.getItem(i));174}175if (!helper.isEmpty()) {176helper.select(target.getSelectedIndex());177helper.setFocusedIndex(target.getSelectedIndex());178}179helper.updateColors(getGUIcolors());180updateMotifColors(getPeerBackground());181}182183public boolean isFocusable() { return true; }184185// 6399679. check if super.setBounds() actually changes the size of the186// component and then compare current Choice size with a new one. If187// they differs then hide dropdown menu188public void setBounds(int x, int y, int width, int height, int op) {189int oldX = this.x;190int oldY = this.y;191int oldWidth = this.width;192int oldHeight = this.height;193super.setBounds(x, y, width, height, op);194if (unfurled && (oldX != this.x || oldY != this.y || oldWidth != this.width || oldHeight != this.height) ) {195hidePopdownMenu();196}197}198199public void focusGained(FocusEvent e) {200// TODO: only need to paint the focus bit201super.focusGained(e);202repaint();203}204205/*206* Fix for 6246503 : Disabling a choice after selection locks keyboard, mouse and makes the system unusable, Xtoolkit207* if setEnabled(false) invoked we should close opened choice in208* order to prevent keyboard/mouse lock.209*/210public void setEnabled(boolean value) {211super.setEnabled(value);212helper.updateColors(getGUIcolors());213if (!value && unfurled){214hidePopdownMenu();215}216}217218public void focusLost(FocusEvent e) {219// TODO: only need to paint the focus bit?220super.focusLost(e);221repaint();222}223224void ungrabInputImpl() {225if (unfurled) {226unfurled = false;227dragging = false;228mouseInSB = false;229unfurledChoice.setVisible(false);230}231232super.ungrabInputImpl();233}234235void handleJavaKeyEvent(KeyEvent e) {236if (e.getID() == KeyEvent.KEY_PRESSED) {237keyPressed(e);238}239}240241public void keyPressed(KeyEvent e) {242switch(e.getKeyCode()) {243// UP & DOWN are same if furled or unfurled244case KeyEvent.VK_DOWN:245case KeyEvent.VK_KP_DOWN: {246if (helper.getItemCount() > 1) {247helper.down();248int newIdx = helper.getSelectedIndex();249250if (((Choice)target).getSelectedIndex() != newIdx) {251((Choice)target).select(newIdx);252postEvent(new ItemEvent((Choice)target,253ItemEvent.ITEM_STATE_CHANGED,254((Choice)target).getItem(newIdx),255ItemEvent.SELECTED));256repaint();257}258}259break;260}261case KeyEvent.VK_UP:262case KeyEvent.VK_KP_UP: {263if (helper.getItemCount() > 1) {264helper.up();265int newIdx = helper.getSelectedIndex();266267if (((Choice)target).getSelectedIndex() != newIdx) {268((Choice)target).select(newIdx);269postEvent(new ItemEvent((Choice)target,270ItemEvent.ITEM_STATE_CHANGED,271((Choice)target).getItem(newIdx),272ItemEvent.SELECTED));273repaint();274}275}276break;277}278case KeyEvent.VK_PAGE_DOWN:279if (unfurled && !dragging) {280int oldIdx = helper.getSelectedIndex();281helper.pageDown();282int newIdx = helper.getSelectedIndex();283if (oldIdx != newIdx) {284((Choice)target).select(newIdx);285postEvent(new ItemEvent((Choice)target,286ItemEvent.ITEM_STATE_CHANGED,287((Choice)target).getItem(newIdx),288ItemEvent.SELECTED));289repaint();290}291}292break;293case KeyEvent.VK_PAGE_UP:294if (unfurled && !dragging) {295int oldIdx = helper.getSelectedIndex();296helper.pageUp();297int newIdx = helper.getSelectedIndex();298if (oldIdx != newIdx) {299((Choice)target).select(newIdx);300postEvent(new ItemEvent((Choice)target,301ItemEvent.ITEM_STATE_CHANGED,302((Choice)target).getItem(newIdx),303ItemEvent.SELECTED));304repaint();305}306}307break;308case KeyEvent.VK_ESCAPE:309case KeyEvent.VK_ENTER:310if (unfurled) {311if (dragging){312if (e.getKeyCode() == KeyEvent.VK_ESCAPE){313//This also happens on314// - MouseButton2,3, etc. press315// - ENTER press316helper.select(dragStartIdx);317} else { //KeyEvent.VK_ENTER:318int newIdx = helper.getSelectedIndex();319if (newIdx != (((Choice)target).getSelectedIndex())) {320((Choice)target).select(newIdx);321postEvent(new ItemEvent((Choice)target,322ItemEvent.ITEM_STATE_CHANGED,323((Choice)target).getItem(newIdx),324ItemEvent.SELECTED));325}326}327}328hidePopdownMenu();329dragging = false;330wasDragged = false;331mouseInSB = false;332333// See 6240074 for more information334if (choiceListener != null){335choiceListener.unfurledChoiceClosing();336}337}338break;339default:340if (unfurled) {341Toolkit.getDefaultToolkit().beep();342}343break;344}345}346347public boolean handlesWheelScrolling() { return true; }348349void handleJavaMouseWheelEvent(MouseWheelEvent e) {350if (unfurled && helper.isVSBVisible()) {351if (ListHelper.doWheelScroll(helper.getVSB(), null, e)) {352repaint();353}354}355}356357void handleJavaMouseEvent(MouseEvent e) {358super.handleJavaMouseEvent(e);359int i = e.getID();360switch (i) {361case MouseEvent.MOUSE_PRESSED:362mousePressed(e);363break;364case MouseEvent.MOUSE_RELEASED:365mouseReleased(e);366break;367case MouseEvent.MOUSE_DRAGGED:368mouseDragged(e);369break;370}371}372373public void mousePressed(MouseEvent e) {374/*375* fix for 5003166: a Choice on XAWT shouldn't react to any376* mouse button presses except left. This involves presses on377* Choice but not on opened part of choice.378*/379if (e.getButton() == MouseEvent.BUTTON1){380dragStartIdx = helper.getSelectedIndex();381if (unfurled) {382//fix 6259328: PIT: Choice scrolls when dragging the parent frame while drop-down is active, XToolkit383if (! (isMouseEventInChoice(e) ||384unfurledChoice.isMouseEventInside(e)))385{386hidePopdownMenu();387}388// Press on unfurled Choice. Highlight the item under the cursor,389// but don't send item event or set the text on the button yet390unfurledChoice.trackMouse(e);391}392else {393// Choice is up - unfurl it394grabInput();395unfurledChoice.toFront();396firstPress = true;397wasDragged = false;398unfurled = true;399}400}401}402403/*404* helper method for mouseReleased routine405*/406void hidePopdownMenu(){407ungrabInput();408unfurledChoice.setVisible(false);409unfurled = false;410}411412public void mouseReleased(MouseEvent e) {413if (unfurled) {414if (mouseInSB) {415unfurledChoice.trackMouse(e);416}417else {418// We pressed and dragged onto the Choice, or, this is the419// second release after clicking to make the Choice "stick"420// unfurled.421// This release should ungrab/furl, and set the new item if422// release was over the unfurled Choice.423424// Fix for 6239944 : Choice shouldn't close its425// pop-down menu if user presses Mouse on Choice's Scrollbar426// some additional cases like releasing mouse outside427// of Choice are considered too428boolean isMouseEventInside = unfurledChoice.isMouseEventInside( e );429boolean isMouseInListArea = unfurledChoice.isMouseInListArea( e );430431// Fixed 6318746: REG: File Selection is failing432// We shouldn't restore the selected item433// if the mouse was dragged outside the drop-down choice area434if (!helper.isEmpty() && !isMouseInListArea && dragging) {435// Set the selected item back how it was.436((Choice)target).select(dragStartIdx);437}438439// Choice must be closed if user releases mouse on440// pop-down menu on the second click441if ( !firstPress && isMouseInListArea) {442hidePopdownMenu();443}444// Choice must be closed if user releases mouse445// outside of Choice's pop-down menu on the second click446if ( !firstPress && !isMouseEventInside) {447hidePopdownMenu();448}449//if user drags Mouse on pop-down menu, Scrollbar or450// outside the Choice451if ( firstPress && dragging) {452hidePopdownMenu();453}454/* this could happen when user has opened a Choice and455* released mouse button. Then he drags mouse on the456* Scrollbar and releases mouse again.457*/458if ( !firstPress && !isMouseInListArea &&459isMouseEventInside && dragging)460{461hidePopdownMenu();462}463464if (!helper.isEmpty()) {465// Only update the Choice if the mouse button is released466// over the list of items.467if (unfurledChoice.isMouseInListArea(e)) {468int newIdx = helper.getSelectedIndex();469if (newIdx >= 0) {470int currentItem = ((Choice)target).getSelectedIndex();471// Update the selected item in the target now that472// the mouse selection is complete.473if (newIdx != dragStartIdx) {474((Choice)target).select(newIdx);475// NOTE: We get a repaint when Choice.select()476// calls our peer.select().477}478if (wasDragged && e.getButton() != MouseEvent.BUTTON1){479((Choice)target).select(dragStartIdx);480}481482/*fix for 6239941 : Choice triggers ItemEvent when selecting an item with right mouse button, Xtoolkit483* We should generate ItemEvent if only484* LeftMouseButton used */485if (e.getButton() == MouseEvent.BUTTON1 &&486(!firstPress || wasDragged ) &&487(newIdx != currentItem))488{489((Choice)target).select(newIdx);490postEvent(new ItemEvent((Choice)target,491ItemEvent.ITEM_STATE_CHANGED,492((Choice)target).getItem(newIdx),493ItemEvent.SELECTED));494}495496// see 6240074 for more information497if (choiceListener != null) {498choiceListener.unfurledChoiceClosing();499}500}501}502}503// See 6243382 for more information504unfurledChoice.trackMouse(e);505}506}507508dragging = false;509wasDragged = false;510firstPress = false;511dragStartIdx = -1;512}513@SuppressWarnings("deprecation")514public void mouseDragged(MouseEvent e) {515/*516* fix for 5003166. On Motif user are unable to drag517* mouse inside opened Choice if he drags the mouse with518* different from LEFT mouse button ( e.g. RIGHT or MIDDLE).519* This fix make impossible to drag mouse inside opened choice520* with other mouse buttons rather then LEFT one.521*/522if ( e.getModifiers() == MouseEvent.BUTTON1_MASK ){523dragging = true;524wasDragged = true;525unfurledChoice.trackMouse(e);526}527}528529// Stolen from TinyChoicePeer530@SuppressWarnings("deprecation")531public Dimension getMinimumSize() {532// TODO: move this impl into ListHelper?533FontMetrics fm = getFontMetrics(target.getFont());534Choice c = (Choice)target;535int w = 0;536for (int i = c.countItems() ; i-- > 0 ;) {537w = Math.max(fm.stringWidth(c.getItem(i)), w);538}539return new Dimension(w + TEXT_XPAD + WIDGET_OFFSET,540fm.getMaxAscent() + fm.getMaxDescent() + TEXT_YPAD);541}542543/*544* Layout the...545*/546public void layout() {547/*548Dimension size = target.getSize();549Font f = target.getFont();550FontMetrics fm = target.getFontMetrics(f);551String text = ((Choice)target).getLabel();552553textRect.height = fm.getHeight();554555checkBoxSize = getChoiceSize(fm);556557// Note - Motif appears to use an left inset that is slightly558// scaled to the checkbox/font size.559cbX = borderInsets.left + checkBoxInsetFromText;560cbY = size.height / 2 - checkBoxSize / 2;561int minTextX = borderInsets.left + 2 * checkBoxInsetFromText + checkBoxSize;562// FIXME: will need to account for alignment?563// FIXME: call layout() on alignment changes564//textRect.width = fm.stringWidth(text);565textRect.width = fm.stringWidth(text == null ? "" : text);566textRect.x = Math.max(minTextX, size.width / 2 - textRect.width / 2);567textRect.y = size.height / 2 - textRect.height / 2 + borderInsets.top;568569focusRect.x = focusInsets.left;570focusRect.y = focusInsets.top;571focusRect.width = size.width-(focusInsets.left+focusInsets.right)-1;572focusRect.height = size.height-(focusInsets.top+focusInsets.bottom)-1;573574myCheckMark = AffineTransform.getScaleInstance((double)target.getFont().getSize() / MASTER_SIZE, (double)target.getFont().getSize() / MASTER_SIZE).createTransformedShape(MASTER_CHECKMARK);575*/576577}578579/**580* Paint the choice581*/582@Override583void paintPeer(final Graphics g) {584flush();585Dimension size = getPeerSize();586// TODO: when mouse is down over button, widget should be drawn depressed587g.setColor(getPeerBackground());588g.fillRect(0, 0, width, height);589590drawMotif3DRect(g, 1, 1, width-2, height-2, false);591drawMotif3DRect(g, width - WIDGET_OFFSET, (height / 2) - 3, 12, 6, false);592593if (!helper.isEmpty() && helper.getSelectedIndex() != -1) {594g.setFont(getPeerFont());595FontMetrics fm = g.getFontMetrics();596String lbl = helper.getItem(helper.getSelectedIndex());597if (lbl != null && drawSelectedItem) {598g.setClip(1, 1, width - WIDGET_OFFSET - 2, height);599if (isEnabled()) {600g.setColor(getPeerForeground());601g.drawString(lbl, 5, (height + fm.getMaxAscent()-fm.getMaxDescent())/2);602}603else {604g.setColor(getPeerBackground().brighter());605g.drawString(lbl, 5, (height + fm.getMaxAscent()-fm.getMaxDescent())/2);606g.setColor(getPeerBackground().darker());607g.drawString(lbl, 4, ((height + fm.getMaxAscent()-fm.getMaxDescent())/2)-1);608}609g.setClip(0, 0, width, height);610}611}612if (hasFocus()) {613paintFocus(g,focusInsets.left,focusInsets.top,size.width-(focusInsets.left+focusInsets.right)-1,size.height-(focusInsets.top+focusInsets.bottom)-1);614}615if (unfurled) {616unfurledChoice.repaint();617}618flush();619}620621protected void paintFocus(Graphics g,622int x, int y, int w, int h) {623g.setColor(focusColor);624g.drawRect(x,y,w,h);625}626627628629/*630* ChoicePeer methods stolen from TinyChoicePeer631*/632633public void select(int index) {634helper.select(index);635helper.setFocusedIndex(index);636repaint();637}638639public void add(String item, int index) {640helper.add(item, index);641repaint();642}643644public void remove(int index) {645boolean selected = (index == helper.getSelectedIndex());646boolean visibled = (index >= helper.firstDisplayedIndex() && index <= helper.lastDisplayedIndex());647helper.remove(index);648if (selected) {649if (helper.isEmpty()) {650helper.select(-1);651}652else {653helper.select(0);654}655}656/*657* Fix for 6248016658* After removing the item of the choice we need to reshape unfurled choice659* in order to keep actual bounds of the choice660*/661662/*663* condition added only for performance664*/665if (!unfurled) {666// Fix 6292186: PIT: Choice is not refreshed properly when the last item gets removed, XToolkit667// We should take into account that there is no 'select' invoking (hence 'repaint')668// if the choice is empty (see Choice.java method removeNoInvalidate())669// The condition isn't 'visibled' since it would be cause of the twice repainting670if (helper.isEmpty()) {671repaint();672}673return;674}675676/*677* condition added only for performance678* the count of the visible items changed679*/680if (visibled){681Rectangle r = unfurledChoice.placeOnScreen();682unfurledChoice.reshape(r.x, r.y, r.width, r.height);683return;684}685686/*687* condition added only for performance688* the structure of visible items changed689* if removable item is non visible and non selected then there is no repaint690*/691if (visibled || selected){692repaint();693}694}695696public void removeAll() {697helper.removeAll();698helper.select(-1);699/*700* Fix for 6248016701* After removing the item of the choice we need to reshape unfurled choice702* in order to keep actual bounds of the choice703*/704Rectangle r = unfurledChoice.placeOnScreen();705unfurledChoice.reshape(r.x, r.y, r.width, r.height);706repaint();707}708709public void setFont(Font font) {710super.setFont(font);711helper.setFont(this.font);712}713714public void setForeground(Color c) {715super.setForeground(c);716helper.updateColors(getGUIcolors());717}718719public void setBackground(Color c) {720super.setBackground(c);721unfurledChoice.setBackground(c);722helper.updateColors(getGUIcolors());723updateMotifColors(c);724}725726public void setDrawSelectedItem(boolean value) {727drawSelectedItem = value;728}729730public void setAlignUnder(Component comp) {731alignUnder = comp;732}733734// see 6240074 for more information735public void addXChoicePeerListener(XChoicePeerListener l){736choiceListener = l;737}738739// see 6240074 for more information740public void removeXChoicePeerListener(){741choiceListener = null;742}743744public boolean isUnfurled(){745return unfurled;746}747748/* fix for 6261352. We should detect if current parent Window (containing a Choice) become iconified and hide pop-down menu with grab release.749* In this case we should hide pop-down menu.750*/751//calls from XWindowPeer. Could accept X-styled state events752public void stateChangedICCCM(int oldState, int newState) {753if (unfurled && oldState != newState){754hidePopdownMenu();755}756}757758//calls from XFramePeer. Could accept Frame's states.759public void stateChangedJava(int oldState, int newState) {760if (unfurled && oldState != newState){761hidePopdownMenu();762}763}764765@Override766protected void initGraphicsConfiguration() {767super.initGraphicsConfiguration();768// The popup have the same graphic config, so update it at the same time769if (unfurledChoice != null) {770unfurledChoice.initGraphicsConfiguration();771unfurledChoice.doValidateSurface();772}773}774775/**************************************************************************/776/* Common functionality between List & Choice777/**************************************************************************/778779/**780* Inner class for the unfurled Choice list781* Much, much more docs782*/783final class UnfurledChoice extends XWindow /*implements XScrollbarClient*/ {784785// First try - use Choice as the target786787public UnfurledChoice(Component target) {788super(target);789}790791// Override so we can do our own create()792public void preInit(XCreateWindowParams params) {793// A parent of this window is the target, at this point: wrong.794// Remove parent window; in the following preInit() call we'll calculate as a default795// a correct root window which is the proper parent for override redirect.796params.delete(PARENT_WINDOW);797super.preInit(params);798// Reset bounds(we'll set them later), set overrideRedirect799params.remove(BOUNDS);800params.add(OVERRIDE_REDIRECT, Boolean.TRUE);801}802803// Generally, bounds should be:804// x = target.x805// y = target.y + target.height806// w = Max(target.width, getLongestItemWidth) + possible vertScrollbar807// h = Min(MAX_UNFURLED_ITEMS, target.getItemCount()) * itemHeight808Rectangle placeOnScreen() {809int numItemsDisplayed;810// Motif paints an empty Choice the same size as a single item811if (helper.isEmpty()) {812numItemsDisplayed = 1;813}814else {815int numItems = helper.getItemCount();816numItemsDisplayed = Math.min(MAX_UNFURLED_ITEMS, numItems);817}818Point global = XChoicePeer.this.toGlobal(0,0);819Rectangle screenBounds = graphicsConfig.getBounds();820821if (alignUnder != null) {822Rectangle choiceRec = XChoicePeer.this.getBounds();823choiceRec.setLocation(0, 0);824choiceRec = XChoicePeer.this.toGlobal(choiceRec);825Rectangle alignUnderRec = new Rectangle(alignUnder.getLocationOnScreen(), alignUnder.getSize()); // TODO: Security?826Rectangle result = choiceRec.union(alignUnderRec);827// we've got the left and width, calculate top and height828width = result.width;829x = result.x;830y = result.y + result.height;831height = 2*BORDER_WIDTH +832numItemsDisplayed*(helper.getItemHeight()+2*ITEM_MARGIN);833} else {834x = global.x;835y = global.y + XChoicePeer.this.height;836width = Math.max(XChoicePeer.this.width,837helper.getMaxItemWidth() + 2 * (BORDER_WIDTH + ITEM_MARGIN + TEXT_SPACE) + (helper.isVSBVisible() ? SCROLLBAR_WIDTH : 0));838height = 2*BORDER_WIDTH +839numItemsDisplayed*(helper.getItemHeight()+2*ITEM_MARGIN);840}841// Don't run off the edge of the screenBounds842if (x < screenBounds.x) {843x = screenBounds.x;844}845else if (x + width > screenBounds.x + screenBounds.width) {846x = screenBounds.x + screenBounds.width - width;847}848849if (y + height > screenBounds.y + screenBounds.height) {850y = global.y - height;851}852if (y < screenBounds.y) {853y = screenBounds.y;854}855return new Rectangle(x, y, width, height);856}857858public void toFront() {859// see 6240074 for more information860if (choiceListener != null)861choiceListener.unfurledChoiceOpening(helper);862863Rectangle r = placeOnScreen();864reshape(r.x, r.y, r.width, r.height);865super.toFront();866setVisible(true);867}868869/*870* Track a MouseEvent (either a drag or a press) and paint a new871* selected item, if necessary.872*/873// FIXME: first unfurl after move is not at edge of the screen onto second monitor doesn't874// track mouse correctly. Problem is w/ UnfurledChoice coords875public void trackMouse(MouseEvent e) {876// Event coords are relative to the button, so translate a bit877Point local = toLocalCoords(e);878879// If x,y is over unfurled Choice,880// highlight item under cursor881882switch (e.getID()) {883case MouseEvent.MOUSE_PRESSED:884// FIXME: If the Choice is unfurled and the mouse is pressed885// outside of the Choice, the mouse should ungrab on the886// the press, not the release887if (helper.isInVertSB(getBounds(), local.x, local.y)) {888mouseInSB = true;889helper.handleVSBEvent(e, getBounds(), local.x, local.y);890}891else {892trackSelection(local.x, local.y);893}894break;895case MouseEvent.MOUSE_RELEASED:896if (mouseInSB) {897mouseInSB = false;898helper.handleVSBEvent(e, getBounds(), local.x, local.y);899}else{900// See 6243382 for more information901helper.trackMouseReleasedScroll();902}903/*904else {905trackSelection(local.x, local.y);906}907*/908break;909case MouseEvent.MOUSE_DRAGGED:910if (mouseInSB) {911helper.handleVSBEvent(e, getBounds(), local.x, local.y);912}913else {914// See 6243382 for more information915helper.trackMouseDraggedScroll(local.x, local.y, width, height);916trackSelection(local.x, local.y);917}918break;919}920}921922private void trackSelection(int transX, int transY) {923if (!helper.isEmpty()) {924if (transX > 0 && transX < width &&925transY > 0 && transY < height) {926int newIdx = helper.y2index(transY);927if (log.isLoggable(PlatformLogger.Level.FINE)) {928log.fine("transX=" + transX + ", transY=" + transY929+ ",width=" + width + ", height=" + height930+ ", newIdx=" + newIdx + " on " + target);931}932if ((newIdx >=0) && (newIdx < helper.getItemCount())933&& (newIdx != helper.getSelectedIndex()))934{935helper.select(newIdx);936unfurledChoice.repaint();937}938}939}940// FIXME: If dragged off top or bottom, scroll if there's a vsb941// (ICK - we'll need a timer or our own event or something)942}943944/*945* fillRect with current Background color on the whole dropdown list.946*/947public void paintBackground() {948final Graphics g = getGraphics();949if (g != null) {950try {951g.setColor(getPeerBackground());952g.fillRect(0, 0, width, height);953} finally {954g.dispose();955}956}957}958/*959* 6405689. In some cases we should erase background to eliminate painting960* artefacts.961*/962@Override963public void repaint() {964if (!isVisible()) {965return;966}967if (helper.checkVsbVisibilityChangedAndReset()){968paintBackground();969}970super.repaint();971}972@Override973public void paintPeer(Graphics g) {974//System.out.println("UC.paint()");975Choice choice = (Choice)target;976Color[] colors = XChoicePeer.this.getGUIcolors();977draw3DRect(g, getSystemColors(), 0, 0, width - 1, height - 1, true);978draw3DRect(g, getSystemColors(), 1, 1, width - 3, height - 3, true);979980helper.paintAllItems(g,981colors,982getBounds());983}984985public void setVisible(boolean vis) {986xSetVisible(vis);987988if (!vis && alignUnder != null) {989alignUnder.requestFocusInWindow();990}991}992993/**994* Return a MouseEvent's Point in coordinates relative to the995* UnfurledChoice.996*/997private Point toLocalCoords(MouseEvent e) {998// Event coords are relative to the button, so translate a bit999Point global = e.getLocationOnScreen();10001001global.x -= x;1002global.y -= y;1003return global;1004}10051006/* Returns true if the MouseEvent coords (which are based on the Choice)1007* are inside of the UnfurledChoice.1008*/1009private boolean isMouseEventInside(MouseEvent e) {1010Point local = toLocalCoords(e);1011if (local.x > 0 && local.x < width &&1012local.y > 0 && local.y < height) {1013return true;1014}1015return false;1016}10171018/**1019* Tests if the mouse cursor is in the Unfurled Choice, yet not1020* in the vertical scrollbar1021*/1022private boolean isMouseInListArea(MouseEvent e) {1023if (isMouseEventInside(e)) {1024Point local = toLocalCoords(e);1025Rectangle bounds = getBounds();1026if (!helper.isInVertSB(bounds, local.x, local.y)) {1027return true;1028}1029}1030return false;1031}10321033/*1034* Overridden from XWindow() because we don't want to send1035* ComponentEvents1036*/1037public void handleConfigureNotifyEvent(XEvent xev) {}1038public void handleMapNotifyEvent(XEvent xev) {}1039public void handleUnmapNotifyEvent(XEvent xev) {}1040} //UnfurledChoice10411042public void dispose() {1043if (unfurledChoice != null) {1044unfurledChoice.destroy();1045}1046super.dispose();1047}10481049/*1050* fix for 6239938 : Choice drop-down does not disappear when it loses1051* focus, on XToolkit1052* We are able to handle all _Key_ events received by Choice when1053* it is in opened state without sending it to EventQueue.1054* If Choice is in closed state we should behave like before: send1055* all events to EventQueue.1056* To be compatible with Motif we should handle all KeyEvents in1057* Choice if it is opened. KeyEvents should be sent into Java if Choice is not opened.1058*/1059boolean prePostEvent(final AWTEvent e) {1060if (unfurled){1061// fix for 6253211: PIT: MouseWheel events not triggered for Choice drop down in XAWT1062if (e instanceof MouseWheelEvent){1063return super.prePostEvent(e);1064}1065//fix 6252982: PIT: Keyboard FocusTraversal not working when choice's drop-down is visible, on XToolkit1066if (e instanceof KeyEvent){1067// notify XWindow that this event had been already handled and no need to post it again1068InvocationEvent ev = new InvocationEvent(target, new Runnable() {1069public void run() {1070if(target.isFocusable() &&1071getParentTopLevel().isFocusableWindow() )1072{1073handleJavaKeyEvent((KeyEvent)e);1074}1075}1076});1077postEvent(ev);10781079return true;1080} else {1081if (e instanceof MouseEvent){1082// Fix for 6240046 : REG:Choice's Drop-down does not disappear when clicking somewhere, after popup menu is disposed1083// if user presses Right Mouse Button on opened (unfurled)1084// Choice then we mustn't open a popup menu. We could filter1085// Mouse Events and handle them in XChoicePeer if Choice1086// currently in opened state.1087MouseEvent me = (MouseEvent)e;1088int eventId = e.getID();1089// fix 6251983: PIT: MouseDragged events not triggered1090// fix 6251988: PIT: Choice consumes MouseReleased, MouseClicked events when clicking it with left button,1091if ((unfurledChoice.isMouseEventInside(me) ||1092(!firstPress && eventId == MouseEvent.MOUSE_DRAGGED)))1093{1094return handleMouseEventByChoice(me);1095}1096// MouseMoved events should be fired in Choice's comp if it's not opened1097// Shouldn't generate Moved Events. CR : 62519951098if (eventId == MouseEvent.MOUSE_MOVED){1099return handleMouseEventByChoice(me);1100}1101//fix for 6272965: PIT: Choice triggers MousePressed when pressing mouse outside comp while drop-down is active, XTkt1102if ( !firstPress && !( isMouseEventInChoice(me) ||1103unfurledChoice.isMouseEventInside(me)) &&1104( eventId == MouseEvent.MOUSE_PRESSED ||1105eventId == MouseEvent.MOUSE_RELEASED ||1106eventId == MouseEvent.MOUSE_CLICKED )1107)1108{1109return handleMouseEventByChoice(me);1110}1111}1112}//else KeyEvent1113}//if unfurled1114return super.prePostEvent(e);1115}11161117//convenient method1118//do not generate this kind of Events1119public boolean handleMouseEventByChoice(final MouseEvent me){1120InvocationEvent ev = new InvocationEvent(target, new Runnable() {1121public void run() {1122handleJavaMouseEvent(me);1123}1124});1125postEvent(ev);11261127return true;1128}11291130/* Returns true if the MouseEvent coords1131* are inside of the Choice itself (it doesnt's depends on1132* if this choice opened or not).1133*/1134private boolean isMouseEventInChoice(MouseEvent e) {1135int x = e.getX();1136int y = e.getY();1137Rectangle choiceRect = getBounds();11381139if (x < 0 || x > choiceRect.width ||1140y < 0 || y > choiceRect.height)1141{1142return false;1143}1144return true;1145}1146}114711481149