1 /*
   2  * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.lwawt.macosx;
  27 
  28 import java.awt.im.spi.*;
  29 import java.util.*;
  30 import java.awt.*;
  31 import java.awt.peer.*;
  32 import java.awt.event.*;
  33 import java.awt.im.*;
  34 import java.awt.font.*;
  35 import java.lang.Character.Subset;
  36 import java.lang.reflect.InvocationTargetException;
  37 import java.text.AttributedCharacterIterator.Attribute;
  38 import java.text.*;
  39 import javax.swing.text.JTextComponent;
  40 
  41 import sun.awt.im.InputMethodAdapter;
  42 import sun.lwawt.*;
  43 
  44 public class CInputMethod extends InputMethodAdapter {
  45     private InputMethodContext fIMContext;
  46     private Component fAwtFocussedComponent;
  47     private LWComponentPeer<?, ?> fAwtFocussedComponentPeer;
  48     private boolean isActive;
  49 
  50     private static Map<TextAttribute, Integer>[] sHighlightStyles;
  51 
  52     // Intitalize highlight mapping table and its mapper.
  53     static {
  54         @SuppressWarnings({"rawtypes", "unchecked"})
  55         Map<TextAttribute, Integer> styles[] = new Map[4];
  56         HashMap<TextAttribute, Integer> map;
  57 
  58         // UNSELECTED_RAW_TEXT_HIGHLIGHT
  59         map = new HashMap<TextAttribute, Integer>(1);
  60         map.put(TextAttribute.INPUT_METHOD_UNDERLINE,
  61                 TextAttribute.UNDERLINE_LOW_GRAY);
  62         styles[0] = Collections.unmodifiableMap(map);
  63 
  64         // SELECTED_RAW_TEXT_HIGHLIGHT
  65         map = new HashMap<TextAttribute, Integer>(1);
  66         map.put(TextAttribute.INPUT_METHOD_UNDERLINE,
  67                 TextAttribute.UNDERLINE_LOW_GRAY);
  68         styles[1] = Collections.unmodifiableMap(map);
  69 
  70         // UNSELECTED_CONVERTED_TEXT_HIGHLIGHT
  71         map = new HashMap<TextAttribute, Integer>(1);
  72         map.put(TextAttribute.INPUT_METHOD_UNDERLINE,
  73                 TextAttribute.UNDERLINE_LOW_ONE_PIXEL);
  74         styles[2] = Collections.unmodifiableMap(map);
  75 
  76         // SELECTED_CONVERTED_TEXT_HIGHLIGHT
  77         map = new HashMap<TextAttribute, Integer>(1);
  78         map.put(TextAttribute.INPUT_METHOD_UNDERLINE,
  79                 TextAttribute.UNDERLINE_LOW_TWO_PIXEL);
  80         styles[3] = Collections.unmodifiableMap(map);
  81 
  82         sHighlightStyles = styles;
  83 
  84         nativeInit();
  85 
  86     }
  87 
  88     public CInputMethod() {
  89     }
  90 
  91 
  92     /**
  93         * Sets the input method context, which is used to dispatch input method
  94      * events to the client component and to request information from
  95      * the client component.
  96      * <p>
  97      * This method is called once immediately after instantiating this input
  98      * method.
  99      *
 100      * @param context the input method context for this input method
 101      * @exception NullPointerException if <code>context</code> is null
 102      */
 103     public void setInputMethodContext(InputMethodContext context) {
 104         fIMContext = context;
 105     }
 106 
 107     /**
 108         * Attempts to set the input locale. If the input method supports the
 109      * desired locale, it changes its behavior to support input for the locale
 110      * and returns true.
 111      * Otherwise, it returns false and does not change its behavior.
 112      * <p>
 113      * This method is called
 114      * <ul>
 115      * <li>by {@link java.awt.im.InputContext#selectInputMethod InputContext.selectInputMethod},
 116      * <li>when switching to this input method through the user interface if the user
 117      *     specified a locale or if the previously selected input method's
 118      *     {@link java.awt.im.spi.InputMethod#getLocale getLocale} method
 119      *     returns a non-null value.
 120      * </ul>
 121      *
 122      * @param lang locale to input
 123      * @return whether the specified locale is supported
 124      * @exception NullPointerException if <code>locale</code> is null
 125      */
 126     public boolean setLocale(Locale lang) {
 127         return setLocale(lang, false);
 128     }
 129 
 130     private boolean setLocale(Locale lang, boolean onActivate) {
 131         Object[] available = CInputMethodDescriptor.getAvailableLocalesInternal();
 132         for (int i = 0; i < available.length; i++) {
 133             Locale locale = (Locale)available[i];
 134             if (lang.equals(locale) ||
 135                 // special compatibility rule for Japanese and Korean
 136                 locale.equals(Locale.JAPAN) && lang.equals(Locale.JAPANESE) ||
 137                 locale.equals(Locale.KOREA) && lang.equals(Locale.KOREAN)) {
 138                 if (isActive) {
 139                     setNativeLocale(locale.toString(), onActivate);
 140                 }
 141                 return true;
 142             }
 143         }
 144         return false;
 145     }
 146 
 147     /**
 148         * Returns the current input locale. Might return null in exceptional cases.
 149      * <p>
 150      * This method is called
 151      * <ul>
 152      * <li>by {@link java.awt.im.InputContext#getLocale InputContext.getLocale} and
 153      * <li>when switching from this input method to a different one through the
 154      *     user interface.
 155      * </ul>
 156      *
 157      * @return the current input locale, or null
 158      */
 159     public Locale getLocale() {
 160         // On Mac OS X we'll ask the currently active input method what its locale is.
 161         Locale returnValue = getNativeLocale();
 162         if (returnValue == null) {
 163             returnValue = Locale.getDefault();
 164         }
 165 
 166         return returnValue;
 167     }
 168 
 169     /**
 170         * Sets the subsets of the Unicode character set that this input method
 171      * is allowed to input. Null may be passed in to indicate that all
 172      * characters are allowed.
 173      * <p>
 174      * This method is called
 175      * <ul>
 176      * <li>immediately after instantiating this input method,
 177      * <li>when switching to this input method from a different one, and
 178      * <li>by {@link java.awt.im.InputContext#setCharacterSubsets InputContext.setCharacterSubsets}.
 179      * </ul>
 180      *
 181      * @param subsets the subsets of the Unicode character set from which
 182      * characters may be input
 183      */
 184     public void setCharacterSubsets(Subset[] subsets) {
 185         // -- SAK: Does mac OS X support this?
 186     }
 187 
 188     /**
 189         * Composition cannot be set on Mac OS X -- the input method remembers this
 190      */
 191     public void setCompositionEnabled(boolean enable) {
 192         throw new UnsupportedOperationException("Can't adjust composition mode on Mac OS X.");
 193     }
 194 
 195     public boolean isCompositionEnabled() {
 196         throw new UnsupportedOperationException("Can't adjust composition mode on Mac OS X.");
 197     }
 198 
 199     /**
 200      * Dispatches the event to the input method. If input method support is
 201      * enabled for the focussed component, incoming events of certain types
 202      * are dispatched to the current input method for this component before
 203      * they are dispatched to the component's methods or event listeners.
 204      * The input method decides whether it needs to handle the event. If it
 205      * does, it also calls the event's <code>consume</code> method; this
 206      * causes the event to not get dispatched to the component's event
 207      * processing methods or event listeners.
 208      * <p>
 209      * Events are dispatched if they are instances of InputEvent or its
 210      * subclasses.
 211      * This includes instances of the AWT classes KeyEvent and MouseEvent.
 212      * <p>
 213      * This method is called by {@link java.awt.im.InputContext#dispatchEvent InputContext.dispatchEvent}.
 214      *
 215      * @param event the event being dispatched to the input method
 216      * @exception NullPointerException if <code>event</code> is null
 217      */
 218     public void dispatchEvent(final AWTEvent event) {
 219         // No-op for Mac OS X.
 220     }
 221 
 222 
 223     /**
 224      * Activate and deactivate are no-ops on Mac OS X.
 225      * A non-US keyboard layout is an 'input method' in that it generates events the same way as
 226      * a CJK input method. A component that doesn't want input method events still wants the dead-key
 227      * events.
 228      *
 229      *
 230      */
 231     public void activate() {
 232         isActive = true;
 233     }
 234 
 235     public void deactivate(boolean isTemporary) {
 236         isActive = false;
 237     }
 238 
 239     /**
 240      * Closes or hides all windows opened by this input method instance or
 241      * its class.  Deactivate hides windows for us on Mac OS X.
 242      */
 243     public void hideWindows() {
 244     }
 245 
 246     long getNativeViewPtr(LWComponentPeer<?, ?> peer) {
 247         if (peer.getPlatformWindow() instanceof CPlatformWindow) {
 248             CPlatformWindow platformWindow = (CPlatformWindow) peer.getPlatformWindow();
 249             CPlatformView platformView = platformWindow.getContentView();
 250             return platformView.getAWTView();
 251         } else {
 252             return 0;
 253         }
 254     }
 255 
 256     /**
 257         * Notifies the input method that a client component has been
 258      * removed from its containment hierarchy, or that input method
 259      * support has been disabled for the component.
 260      */
 261     public void removeNotify() {
 262         if (fAwtFocussedComponentPeer != null) {
 263             nativeEndComposition(getNativeViewPtr(fAwtFocussedComponentPeer));
 264         }
 265 
 266         fAwtFocussedComponentPeer = null;
 267     }
 268 
 269     /**
 270      * Informs the input method adapter about the component that has the AWT
 271      * focus if it's using the input context owning this adapter instance.
 272      * We also take the opportunity to tell the native side that we are the input method
 273      * to talk to when responding to key events.
 274      */
 275     protected void setAWTFocussedComponent(Component component) {
 276         LWComponentPeer<?, ?> peer = null;
 277         long modelPtr = 0;
 278         CInputMethod imInstance = this;
 279 
 280         // component will be null when we are told there's no focused component.
 281         // When that happens we need to notify the native architecture to stop generating IMEs
 282         if (component == null) {
 283             peer = fAwtFocussedComponentPeer;
 284             imInstance = null;
 285         } else {
 286             peer = getNearestNativePeer(component);
 287 
 288             // If we have a passive client, don't pass input method events to it.
 289             if (component.getInputMethodRequests() == null) {
 290                 imInstance = null;
 291             }
 292         }
 293 
 294         if (peer != null) {
 295             modelPtr = getNativeViewPtr(peer);
 296 
 297             // modelPtr refers to the ControlModel that either got or lost focus.
 298             nativeNotifyPeer(modelPtr, imInstance);
 299         }
 300 
 301         // Track the focused component and its nearest peer.
 302         fAwtFocussedComponent = component;
 303         fAwtFocussedComponentPeer = getNearestNativePeer(component);
 304     }
 305 
 306     /**
 307         * @see java.awt.Toolkit#mapInputMethodHighlight
 308      */
 309     public static Map<TextAttribute, ?> mapInputMethodHighlight(InputMethodHighlight highlight) {
 310         int index;
 311         int state = highlight.getState();
 312         if (state == InputMethodHighlight.RAW_TEXT) {
 313             index = 0;
 314         } else if (state == InputMethodHighlight.CONVERTED_TEXT) {
 315             index = 2;
 316         } else {
 317             return null;
 318         }
 319         if (highlight.isSelected()) {
 320             index += 1;
 321         }
 322         return sHighlightStyles[index];
 323     }
 324 
 325     /**
 326         * Ends any input composition that may currently be going on in this
 327      * context. Depending on the platform and possibly user preferences,
 328      * this may commit or delete uncommitted text. Any changes to the text
 329      * are communicated to the active component using an input method event.
 330      *
 331      * <p>
 332      * A text editing component may call this in a variety of situations,
 333      * for example, when the user moves the insertion point within the text
 334      * (but outside the composed text), or when the component's text is
 335      * saved to a file or copied to the clipboard.
 336      * <p>
 337      * This method is called
 338      * <ul>
 339      * <li>by {@link java.awt.im.InputContext#endComposition InputContext.endComposition},
 340      * <li>by {@link java.awt.im.InputContext#dispatchEvent InputContext.dispatchEvent}
 341      *     when switching to a different client component
 342      * <li>when switching from this input method to a different one using the
 343      *     user interface or
 344      *     {@link java.awt.im.InputContext#selectInputMethod InputContext.selectInputMethod}.
 345      * </ul>
 346      */
 347     public void endComposition() {
 348         if (fAwtFocussedComponentPeer != null)
 349             nativeEndComposition(getNativeViewPtr(fAwtFocussedComponentPeer));
 350     }
 351 
 352     /**
 353         * Disposes of the input method and releases the resources used by it.
 354      * In particular, the input method should dispose windows and close files that are no
 355      * longer needed.
 356      * <p>
 357      * This method is called by {@link java.awt.im.InputContext#dispose InputContext.dispose}.
 358      * <p>
 359      * The method is only called when the input method is inactive.
 360      * No method of this interface is called on this instance after dispose.
 361      */
 362     public void dispose() {
 363         fIMContext = null;
 364         fAwtFocussedComponent = null;
 365         fAwtFocussedComponentPeer = null;
 366     }
 367 
 368     /**
 369         * Returns a control object from this input method, or null. A
 370      * control object provides methods that control the behavior of the
 371      * input method or obtain information from the input method. The type
 372      * of the object is an input method specific class. Clients have to
 373      * compare the result against known input method control object
 374      * classes and cast to the appropriate class to invoke the methods
 375      * provided.
 376      * <p>
 377      * This method is called by
 378      * {@link java.awt.im.InputContext#getInputMethodControlObject InputContext.getInputMethodControlObject}.
 379      *
 380      * @return a control object from this input method, or null
 381      */
 382     public Object getControlObject() {
 383         return null;
 384     }
 385 
 386     // java.awt.Toolkit#getNativeContainer() is not available
 387     //    from this package
 388     @SuppressWarnings("deprecation")
 389     private LWComponentPeer<?, ?> getNearestNativePeer(Component comp) {
 390         if (comp==null)
 391             return null;
 392 
 393         ComponentPeer peer = comp.getPeer();
 394         if (peer==null)
 395             return null;
 396 
 397         while (peer instanceof java.awt.peer.LightweightPeer) {
 398             comp = comp.getParent();
 399             if (comp==null)
 400                 return null;
 401             peer = comp.getPeer();
 402             if (peer==null)
 403                 return null;
 404         }
 405 
 406         if (peer instanceof LWComponentPeer)
 407             return (LWComponentPeer)peer;
 408 
 409         return null;
 410     }
 411 
 412     // =========================== NSTextInput callbacks ===========================
 413     // The 'marked text' that we get from Cocoa.  We need to track this separately, since
 414     // Java doesn't let us ask the IM context for it.
 415     private AttributedString fCurrentText = null;
 416     private String fCurrentTextAsString = null;
 417     private int fCurrentTextLength = 0;
 418 
 419     /**
 420      * Tell the component to commit all of the characters in the string to the current
 421      * text view. This effectively wipes out any text in progress.
 422      */
 423     synchronized private void insertText(String aString, int replaceStart, int replaceLength) {
 424         AttributedString attribString = new AttributedString(aString);
 425 
 426         // Set locale information on the new string.
 427         attribString.addAttribute(Attribute.LANGUAGE, getLocale(), 0, aString.length());
 428 
 429         TextHitInfo theCaret = TextHitInfo.afterOffset(aString.length() - 1);
 430         InputMethodEvent event = new InputMethodEvent(fAwtFocussedComponent,
 431                                                       InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
 432                                                       attribString.getIterator(),
 433                                                       aString.length(),
 434                                                       theCaret,
 435                                                       theCaret,
 436                                                       replaceStart, replaceStart + replaceLength);
 437         LWCToolkit.postEvent(LWCToolkit.targetToAppContext(fAwtFocussedComponent), event);
 438         fCurrentText = null;
 439         fCurrentTextAsString = null;
 440         fCurrentTextLength = 0;
 441     }
 442 
 443     private void startIMUpdate (String rawText) {
 444         fCurrentTextAsString = new String(rawText);
 445         fCurrentText = new AttributedString(fCurrentTextAsString);
 446         fCurrentTextLength = rawText.length();
 447     }
 448 
 449     static private final int kCaretPosition = 0;
 450     static private final int kRawText = 1;
 451     static private final int kSelectedRawText = 2;
 452     static private final int kConvertedText = 3;
 453     static private final int kSelectedConvertedText = 4;
 454 
 455     /**
 456      * Convert Cocoa text highlight attributes into Java input method highlighting.
 457      */
 458     private void addAttribute (boolean isThickUnderline, boolean isGray, int start, int length) {
 459         int begin = start;
 460         int end = start + length;
 461         int markupType = kRawText;
 462 
 463         if (isThickUnderline && isGray) {
 464             markupType = kRawText;
 465         } else if (!isThickUnderline && isGray) {
 466             markupType = kRawText;
 467         } else if (isThickUnderline && !isGray) {
 468             markupType = kSelectedConvertedText;
 469         } else if (!isThickUnderline && !isGray) {
 470             markupType = kConvertedText;
 471         }
 472 
 473         InputMethodHighlight theHighlight;
 474 
 475         switch (markupType) {
 476             case kSelectedRawText:
 477                 theHighlight = InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT;
 478                 break;
 479             case kConvertedText:
 480                 theHighlight = InputMethodHighlight.UNSELECTED_CONVERTED_TEXT_HIGHLIGHT;
 481                 break;
 482             case kSelectedConvertedText:
 483                 theHighlight = InputMethodHighlight.SELECTED_CONVERTED_TEXT_HIGHLIGHT;
 484                 break;
 485             case kRawText:
 486             default:
 487                 theHighlight = InputMethodHighlight.UNSELECTED_RAW_TEXT_HIGHLIGHT;
 488                 break;
 489         }
 490 
 491         fCurrentText.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT, theHighlight, begin, end);
 492     }
 493 
 494     private void selectNextGlyph() {
 495         if (fIMContext == null || !(fAwtFocussedComponent instanceof JTextComponent)) return;
 496         try {
 497             LWCToolkit.invokeLater(new Runnable() {
 498                 public void run() {
 499                     final int offset = fIMContext.getInsertPositionOffset();
 500                     if (offset < 0) return;
 501                     ((JTextComponent) fAwtFocussedComponent).select(offset, offset + 1);
 502                     return;
 503                 }
 504             }, fAwtFocussedComponent);
 505         } catch (Exception e) {
 506             e.printStackTrace();
 507         }
 508     }
 509 
 510     private void dispatchText(int selectStart, int selectLength, int replaceStart, int replaceEnd, boolean pressAndHold) {
 511         // Nothing to do if we have no text.
 512         if (fCurrentText == null)
 513             return;
 514 
 515         TextHitInfo theCaret = (selectLength == 0 ? TextHitInfo.beforeOffset(selectStart) : null);
 516         TextHitInfo visiblePosition = TextHitInfo.beforeOffset(0);
 517 
 518         InputMethodEvent event = new InputMethodEvent(fAwtFocussedComponent,
 519                                                       InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
 520                                                       fCurrentText.getIterator(),
 521                                                       0,
 522                                                       theCaret,
 523                                                       visiblePosition,
 524                                                       replaceStart, replaceStart + replaceEnd);
 525         LWCToolkit.postEvent(LWCToolkit.targetToAppContext(fAwtFocussedComponent), event);
 526 
 527         if (pressAndHold) selectNextGlyph();
 528     }
 529 
 530     /**
 531      * Frequent callbacks from NSTextInput.  I think we're supposed to commit it here?
 532      */
 533     synchronized private void unmarkText() {
 534         if (fCurrentText == null)
 535             return;
 536 
 537         TextHitInfo theCaret = TextHitInfo.afterOffset(fCurrentTextLength);
 538         TextHitInfo visiblePosition = theCaret;
 539         InputMethodEvent event = new InputMethodEvent(fAwtFocussedComponent,
 540                                                       InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
 541                                                       fCurrentText.getIterator(),
 542                                                       fCurrentTextLength,
 543                                                       theCaret,
 544                                                       visiblePosition);
 545         LWCToolkit.postEvent(LWCToolkit.targetToAppContext(fAwtFocussedComponent), event);
 546         fCurrentText = null;
 547         fCurrentTextAsString = null;
 548         fCurrentTextLength = 0;
 549     }
 550 
 551     synchronized private boolean hasMarkedText() {
 552         return fCurrentText != null;
 553     }
 554 
 555     /**
 556         * Cocoa assumes the marked text and committed text is all stored in the same storage, but
 557      * Java does not.  So, we have to see where the request is and based on that return the right
 558      * substring.
 559      */
 560     synchronized private String attributedSubstringFromRange(final int locationIn, final int lengthIn) {
 561         final String[] retString = new String[1];
 562 
 563         try {
 564             LWCToolkit.invokeAndWait(new Runnable() {
 565                 public void run() { synchronized(retString) {
 566                     int location = locationIn;
 567                     int length = lengthIn;
 568 
 569                     if ((location + length) > (fIMContext.getCommittedTextLength() + fCurrentTextLength)) {
 570                         length = fIMContext.getCommittedTextLength() - location;
 571                     }
 572 
 573                     AttributedCharacterIterator theIterator = null;
 574 
 575                     if (fCurrentText == null) {
 576                         theIterator = fIMContext.getCommittedText(location, location + length, null);
 577                     } else {
 578                         int insertSpot = fIMContext.getInsertPositionOffset();
 579 
 580                         if (location < insertSpot) {
 581                             theIterator = fIMContext.getCommittedText(location, location + length, null);
 582                         } else if (location >= insertSpot && location < insertSpot + fCurrentTextLength) {
 583                             theIterator = fCurrentText.getIterator(null, location - insertSpot, location - insertSpot +length);
 584                         } else  {
 585                             theIterator = fIMContext.getCommittedText(location - fCurrentTextLength, location - fCurrentTextLength + length, null);
 586                         }
 587                     }
 588 
 589                     // Get the characters from the iterator
 590                     char selectedText[] = new char[theIterator.getEndIndex() - theIterator.getBeginIndex()];
 591                     char current = theIterator.first();
 592                     int index = 0;
 593                     while (current != CharacterIterator.DONE) {
 594                         selectedText[index++] = current;
 595                         current = theIterator.next();
 596                     }
 597 
 598                     retString[0] = new String(selectedText);
 599                 }}
 600             }, fAwtFocussedComponent);
 601         } catch (InvocationTargetException ite) { ite.printStackTrace(); }
 602 
 603         synchronized(retString) { return retString[0]; }
 604     }
 605 
 606     /**
 607      * Cocoa wants the range of characters that are currently selected.  We have to synthesize this
 608      * by getting the insert location and the length of the selected text. NB:  This does NOT allow
 609      * for the fact that the insert point in Swing can come AFTER the selected text, making this
 610      * potentially incorrect.
 611      */
 612     synchronized private int[] selectedRange() {
 613         final int[] returnValue = new int[2];
 614 
 615         try {
 616             LWCToolkit.invokeAndWait(new Runnable() {
 617                 public void run() { synchronized(returnValue) {
 618                     AttributedCharacterIterator theIterator = fIMContext.getSelectedText(null);
 619                     if (theIterator == null) {
 620                         returnValue[0] = fIMContext.getInsertPositionOffset();
 621                         returnValue[1] = 0;
 622                         return;
 623                     }
 624 
 625                     int startLocation;
 626 
 627                     if (fAwtFocussedComponent instanceof JTextComponent) {
 628                         JTextComponent theComponent = (JTextComponent)fAwtFocussedComponent;
 629                         startLocation = theComponent.getSelectionStart();
 630                     } else if (fAwtFocussedComponent instanceof TextComponent) {
 631                         TextComponent theComponent = (TextComponent)fAwtFocussedComponent;
 632                         startLocation = theComponent.getSelectionStart();
 633                     } else {
 634                         // If we don't have a Swing or AWT component, we have to guess whether the selection is before or after the input spot.
 635                         startLocation = fIMContext.getInsertPositionOffset() - (theIterator.getEndIndex() - theIterator.getBeginIndex());
 636 
 637                         // If the calculated spot is negative the insert spot must be at the beginning of
 638                         // the selection.
 639                         if (startLocation <  0) {
 640                             startLocation = fIMContext.getInsertPositionOffset() + (theIterator.getEndIndex() - theIterator.getBeginIndex());
 641                         }
 642                     }
 643 
 644                     returnValue[0] = startLocation;
 645                     returnValue[1] = theIterator.getEndIndex() - theIterator.getBeginIndex();
 646 
 647                 }}
 648             }, fAwtFocussedComponent);
 649         } catch (InvocationTargetException ite) { ite.printStackTrace(); }
 650 
 651         synchronized(returnValue) { return returnValue; }
 652     }
 653 
 654     /**
 655      * Cocoa wants the range of characters that are currently marked.  Since Java doesn't store committed and
 656      * text in progress (composed text) together, we have to synthesize it.  We know where the text will be
 657      * inserted, so we can return that position, and the length of the text in progress.  If there is no marked text
 658      * return null.
 659      */
 660     synchronized private int[] markedRange() {
 661         if (fCurrentText == null)
 662             return null;
 663 
 664         final int[] returnValue = new int[2];
 665 
 666         try {
 667             LWCToolkit.invokeAndWait(new Runnable() {
 668                 public void run() { synchronized(returnValue) {
 669                     // The insert position is always after the composed text, so the range start is the
 670                     // insert spot less the length of the composed text.
 671                     returnValue[0] = fIMContext.getInsertPositionOffset();
 672                 }}
 673             }, fAwtFocussedComponent);
 674         } catch (InvocationTargetException ite) { ite.printStackTrace(); }
 675 
 676         returnValue[1] = fCurrentTextLength;
 677         synchronized(returnValue) { return returnValue; }
 678     }
 679 
 680     /**
 681      * Cocoa wants a rectangle that describes where a particular range is on screen, but only cares about the
 682      * location of that rectangle.  We are given the index of the character for which we want the location on
 683      * screen, which will be a character in the in-progress text.  By subtracting the current insert position,
 684      * which is always in front of the in-progress text, we get the offset into the composed text, and we get
 685      * that location from the input method context.
 686      */
 687     synchronized private int[] firstRectForCharacterRange(final int absoluteTextOffset) {
 688         final int[] rect = new int[4];
 689 
 690         try {
 691             LWCToolkit.invokeAndWait(new Runnable() {
 692                 public void run() { synchronized(rect) {
 693                     int insertOffset = fIMContext.getInsertPositionOffset();
 694                     int composedTextOffset = absoluteTextOffset - insertOffset;
 695                     if (composedTextOffset < 0) composedTextOffset = 0;
 696                     Rectangle r = fIMContext.getTextLocation(TextHitInfo.beforeOffset(composedTextOffset));
 697                     rect[0] = r.x;
 698                     rect[1] = r.y;
 699                     rect[2] = r.width;
 700                     rect[3] = r.height;
 701 
 702                     // This next if-block is a hack to work around a bug in JTextComponent. getTextLocation ignores
 703                     // the TextHitInfo passed to it and always returns the location of the insertion point, which is
 704                     // at the start of the composed text.  We'll do some calculation so the candidate window for Kotoeri
 705                     // follows the requested offset into the composed text.
 706                     if (composedTextOffset > 0 && (fAwtFocussedComponent instanceof JTextComponent)) {
 707                         Rectangle r2 = fIMContext.getTextLocation(TextHitInfo.beforeOffset(0));
 708 
 709                         if (r.equals(r2)) {
 710                             // FIXME: (SAK) If the candidate text wraps over two lines, this calculation pushes the candidate
 711                             // window off the right edge of the component.
 712                             String inProgressSubstring = fCurrentTextAsString.substring(0, composedTextOffset);
 713                             Graphics g = fAwtFocussedComponent.getGraphics();
 714                             int xOffset = g.getFontMetrics().stringWidth(inProgressSubstring);
 715                             rect[0] += xOffset;
 716                             g.dispose();
 717                         }
 718                     }
 719                 }}
 720             }, fAwtFocussedComponent);
 721         } catch (InvocationTargetException ite) { ite.printStackTrace(); }
 722 
 723         synchronized(rect) { return rect; }
 724     }
 725 
 726     /* This method returns the index for the character that is nearest to the point described by screenX and screenY.
 727      * The coordinates are in Java screen coordinates.  If no character in the composed text was hit, we return -1, indicating
 728      * not found.
 729      */
 730     synchronized private int characterIndexForPoint(final int screenX, final int screenY) {
 731         final TextHitInfo[] offsetInfo = new TextHitInfo[1];
 732         final int[] insertPositionOffset = new int[1];
 733 
 734         try {
 735             LWCToolkit.invokeAndWait(new Runnable() {
 736                 public void run() { synchronized(offsetInfo) {
 737                     offsetInfo[0] = fIMContext.getLocationOffset(screenX, screenY);
 738                     insertPositionOffset[0] = fIMContext.getInsertPositionOffset();
 739                 }}
 740             }, fAwtFocussedComponent);
 741         } catch (InvocationTargetException ite) { ite.printStackTrace(); }
 742 
 743         // This bit of gymnastics ensures that the returned location is within the composed text.
 744         // If it falls outside that region, the input method will commit the text, which is inconsistent with native
 745         // Cocoa apps (see TextEdit, for example.)  Clicking to the left of or above the selected text moves the
 746         // cursor to the start of the composed text, and to the right or below moves it to one character before the end.
 747         if (offsetInfo[0] == null) {
 748             return insertPositionOffset[0];
 749         }
 750 
 751         int returnValue = offsetInfo[0].getCharIndex() + insertPositionOffset[0];
 752 
 753         if (offsetInfo[0].getCharIndex() == fCurrentTextLength)
 754             returnValue --;
 755 
 756         return returnValue;
 757     }
 758 
 759     // On Mac OS X we effectively disabled the input method when focus was lost, so
 760     // this call can be ignored.
 761     public void disableInputMethod()
 762     {
 763         // Deliberately ignored. See setAWTFocussedComponent above.
 764     }
 765 
 766     public String getNativeInputMethodInfo()
 767     {
 768         return nativeGetCurrentInputMethodInfo();
 769     }
 770 
 771 
 772     // =========================== Native methods ===========================
 773     // Note that if nativePeer isn't something that normally accepts keystrokes (i.e., a CPanel)
 774     // these calls will be ignored.
 775     private native void nativeNotifyPeer(long nativePeer, CInputMethod imInstance);
 776     private native void nativeEndComposition(long nativePeer);
 777     private native void nativeHandleEvent(LWComponentPeer<?, ?> peer, AWTEvent event);
 778 
 779     // Returns the locale of the active input method.
 780     static native Locale getNativeLocale();
 781 
 782     // Switches to the input method with language indicated in localeName
 783     static native boolean setNativeLocale(String localeName, boolean onActivate);
 784 
 785     // Returns information about the currently selected input method.
 786     static native String nativeGetCurrentInputMethodInfo();
 787 
 788     // Initialize toolbox routines
 789     static native void nativeInit();
 790 }