1 /*
   2  * Copyright (c) 2011, 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 #import "CGLGraphicsConfig.h"
  27 
  28 #import <JavaNativeFoundation/JavaNativeFoundation.h>
  29 #import <JavaRuntimeSupport/JavaRuntimeSupport.h>
  30 
  31 #import "ThreadUtilities.h"
  32 #import "AWTView.h"
  33 #import "AWTEvent.h"
  34 #import "AWTWindow.h"
  35 #import "LWCToolkit.h"
  36 #import "JavaComponentAccessibility.h"
  37 #import "JavaTextAccessibility.h"
  38 #import "GeomUtilities.h"
  39 #import "OSVersion.h"
  40 #import "CGLLayer.h"
  41 
  42 @interface AWTView()
  43 @property (retain) CDropTarget *_dropTarget;
  44 @property (retain) CDragSource *_dragSource;
  45 @end
  46 
  47 // Uncomment this line to see fprintfs of each InputMethod API being called on this View
  48 //#define IM_DEBUG TRUE
  49 //#define EXTRA_DEBUG
  50 
  51 static BOOL shouldUsePressAndHold() {
  52     static int shouldUsePressAndHold = -1;
  53     if (shouldUsePressAndHold != -1) return shouldUsePressAndHold;
  54     shouldUsePressAndHold = !isSnowLeopardOrLower();
  55     return shouldUsePressAndHold;
  56 }
  57 
  58 @implementation AWTView
  59 
  60 @synthesize _dropTarget;
  61 @synthesize _dragSource;
  62 @synthesize cglLayer;
  63 @synthesize mouseIsOver;
  64 
  65 // Note: Must be called on main (AppKit) thread only
  66 - (id) initWithRect: (NSRect) rect
  67        platformView: (jobject) cPlatformView
  68        windowLayer: (CALayer*) windowLayer
  69 {
  70 AWT_ASSERT_APPKIT_THREAD;
  71     // Initialize ourselves
  72     self = [super initWithFrame: rect];
  73     if (self == nil) return self;
  74 
  75     m_cPlatformView = cPlatformView;
  76     fInputMethodLOCKABLE = NULL;
  77     fKeyEventsNeeded = NO;
  78     fProcessingKeystroke = NO;
  79 
  80     fEnablePressAndHold = shouldUsePressAndHold();
  81     fInPressAndHold = NO;
  82     fPAHNeedsToSelect = NO;
  83 
  84     mouseIsOver = NO;
  85 
  86     if (windowLayer != nil) {
  87         self.cglLayer = windowLayer;
  88         [self setWantsLayer: YES];
  89         [self.layer addSublayer: (CALayer *)cglLayer];
  90         [self setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize];
  91         [self setLayerContentsPlacement: NSViewLayerContentsPlacementTopLeft];
  92         [self setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable];
  93 
  94 #ifdef REMOTELAYER
  95         CGLLayer *parentLayer = (CGLLayer*)self.cglLayer;
  96         parentLayer.parentLayer = NULL;
  97         parentLayer.remoteLayer = NULL;
  98         if (JRSRemotePort != 0 && remoteSocketFD > 0) {
  99             CGLLayer *remoteLayer = [[CGLLayer alloc] initWithJavaLayer: parentLayer.javaLayer];
 100             remoteLayer.target = GL_TEXTURE_2D;
 101             NSLog(@"Creating Parent=%p, Remote=%p", parentLayer, remoteLayer);
 102             parentLayer.remoteLayer = remoteLayer;
 103             remoteLayer.parentLayer = parentLayer;
 104             remoteLayer.remoteLayer = NULL;
 105             remoteLayer.jrsRemoteLayer = [remoteLayer createRemoteLayerBoundTo:JRSRemotePort];
 106             CFRetain(remoteLayer);  // REMIND
 107             remoteLayer.frame = CGRectMake(0, 0, 720, 500); // REMIND
 108             CFRetain(remoteLayer.jrsRemoteLayer); // REMIND
 109             int layerID = [remoteLayer.jrsRemoteLayer layerID];
 110             NSLog(@"layer id to send = %d", layerID);
 111             sendLayerID(layerID);
 112         }
 113 #endif /* REMOTELAYER */
 114     }
 115 
 116     return self;
 117 }
 118 
 119 - (void) dealloc {
 120 AWT_ASSERT_APPKIT_THREAD;
 121 
 122     self.cglLayer = nil;
 123 
 124     JNIEnv *env = [ThreadUtilities getJNIEnv];
 125     (*env)->DeleteGlobalRef(env, m_cPlatformView);
 126     m_cPlatformView = NULL;
 127 
 128     if (fInputMethodLOCKABLE != NULL)
 129     {
 130         JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 131 
 132         JNFDeleteGlobalRef(env, fInputMethodLOCKABLE);
 133         fInputMethodLOCKABLE = NULL;
 134     }
 135 
 136 
 137     [super dealloc];
 138 }
 139 
 140 - (void) viewDidMoveToWindow {
 141 AWT_ASSERT_APPKIT_THREAD;
 142 
 143     [AWTToolkit eventCountPlusPlus];
 144 
 145     [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^() {
 146         [[self window] makeFirstResponder: self];
 147     }];
 148     if ([self window] != NULL) {
 149         [self resetTrackingRect];
 150     }
 151 }
 152 
 153 - (BOOL) acceptsFirstMouse: (NSEvent *)event {
 154     return YES;
 155 }
 156 
 157 - (BOOL) acceptsFirstResponder {
 158     return YES;
 159 }
 160 
 161 - (BOOL) becomeFirstResponder {
 162     return YES;
 163 }
 164 
 165 - (BOOL) preservesContentDuringLiveResize {
 166     return YES;
 167 }
 168 
 169 /*
 170  * Automatically triggered functions.
 171  */
 172 
 173 /*
 174  * MouseEvents support
 175  */
 176 
 177 - (void) mouseDown: (NSEvent *)event {
 178     NSInputManager *inputManager = [NSInputManager currentInputManager];
 179     if ([inputManager wantsToHandleMouseEvents]) {
 180 #if IM_DEBUG
 181         NSLog(@"-> IM wants to handle event");
 182 #endif
 183         if (![inputManager handleMouseEvent:event]) {
 184             [self deliverJavaMouseEvent: event];
 185         } else {
 186 #if IM_DEBUG
 187             NSLog(@"-> Event was handled.");
 188 #endif
 189         }
 190     } else {
 191 #if IM_DEBUG
 192         NSLog(@"-> IM does not want to handle event");
 193 #endif
 194         [self deliverJavaMouseEvent: event];
 195     }
 196 }
 197 
 198 - (void) mouseUp: (NSEvent *)event {
 199     [self deliverJavaMouseEvent: event];
 200 }
 201 
 202 - (void) rightMouseDown: (NSEvent *)event {
 203     [self deliverJavaMouseEvent: event];
 204 }
 205 
 206 - (void) rightMouseUp: (NSEvent *)event {
 207     [self deliverJavaMouseEvent: event];
 208 }
 209 
 210 - (void) otherMouseDown: (NSEvent *)event {
 211     [self deliverJavaMouseEvent: event];
 212 }
 213 
 214 - (void) otherMouseUp: (NSEvent *)event {
 215     [self deliverJavaMouseEvent: event];
 216 }
 217 
 218 - (void) mouseMoved: (NSEvent *)event {
 219     // TODO: better way to redirect move events to the "under" view
 220 
 221     NSPoint eventLocation = [event locationInWindow];
 222     NSPoint localPoint = [self convertPoint: eventLocation fromView: nil];
 223 
 224     if  ([self mouse: localPoint inRect: [self bounds]]) {
 225         [self deliverJavaMouseEvent: event];
 226     } else {
 227         [[self nextResponder] mouseDown:event];
 228     }
 229 }
 230 
 231 - (void) mouseDragged: (NSEvent *)event {
 232     [self deliverJavaMouseEvent: event];
 233 }
 234 
 235 - (void) rightMouseDragged: (NSEvent *)event {
 236     [self deliverJavaMouseEvent: event];
 237 }
 238 
 239 - (void) otherMouseDragged: (NSEvent *)event {
 240     [self deliverJavaMouseEvent: event];
 241 }
 242 
 243 - (void) mouseEntered: (NSEvent *)event {
 244     [[self window] setAcceptsMouseMovedEvents:YES];
 245     //[[self window] makeFirstResponder:self];
 246     [self deliverJavaMouseEvent: event];
 247 }
 248 
 249 - (void) mouseExited: (NSEvent *)event {
 250     [[self window] setAcceptsMouseMovedEvents:NO];
 251     [self deliverJavaMouseEvent: event];
 252     //Restore the cursor back.
 253     //[CCursorManager _setCursor: [NSCursor arrowCursor]];
 254 }
 255 
 256 - (void) scrollWheel: (NSEvent*) event {
 257     [self deliverJavaMouseEvent: event];
 258 }
 259 
 260 /*
 261  * KeyEvents support
 262  */
 263 
 264 - (void) keyDown: (NSEvent *)event {
 265 
 266     fProcessingKeystroke = YES;
 267     fKeyEventsNeeded = YES;
 268 
 269     // Allow TSM to look at the event and potentially send back NSTextInputClient messages.
 270     [self interpretKeyEvents:[NSArray arrayWithObject:event]];
 271 
 272     if (fEnablePressAndHold && [event willBeHandledByComplexInputMethod]) {
 273         fProcessingKeystroke = NO;
 274         if (!fInPressAndHold) {
 275             fInPressAndHold = YES;
 276             fPAHNeedsToSelect = YES;
 277         }
 278         return;
 279     }
 280 
 281     NSString *eventCharacters = [event characters];
 282     BOOL isDeadKey = (eventCharacters != nil && [eventCharacters length] == 0);
 283 
 284     if ((![self hasMarkedText] && fKeyEventsNeeded) || isDeadKey) {
 285         [self deliverJavaKeyEventHelper: event];
 286     }
 287 
 288     fProcessingKeystroke = NO;
 289 }
 290 
 291 - (void) keyUp: (NSEvent *)event {
 292     [self deliverJavaKeyEventHelper: event];
 293 }
 294 
 295 - (void) flagsChanged: (NSEvent *)event {
 296     [self deliverJavaKeyEventHelper: event];
 297 }
 298 
 299 - (BOOL) performKeyEquivalent: (NSEvent *) event {
 300     [self deliverJavaKeyEventHelper: event];
 301     return NO;
 302 }
 303 
 304 /**
 305  * Utility methods and accessors
 306  */
 307 
 308 -(void) deliverJavaMouseEvent: (NSEvent *) event {
 309     BOOL isEnabled = YES;
 310     NSWindow* window = [self window];
 311     if ([window isKindOfClass: [AWTWindow_Panel class]] || [window isKindOfClass: [AWTWindow_Normal class]]) {
 312         isEnabled = [(AWTWindow*)[window delegate] isEnabled];
 313     }
 314 
 315     if (!isEnabled) {
 316         return;
 317     }
 318 
 319     NSEventType type = [event type];
 320 
 321     // check synthesized mouse entered/exited events
 322     if ((type == NSMouseEntered && mouseIsOver) || (type == NSMouseExited && !mouseIsOver)) {
 323         return;
 324     }else if ((type == NSMouseEntered && !mouseIsOver) || (type == NSMouseExited && mouseIsOver)) {
 325         mouseIsOver = !mouseIsOver;
 326     }
 327 
 328 
 329     [AWTToolkit eventCountPlusPlus];
 330 
 331     JNIEnv *env = [ThreadUtilities getJNIEnv];
 332 
 333     NSPoint eventLocation = [event locationInWindow];
 334     NSPoint localPoint = [self convertPoint: eventLocation fromView: nil];
 335     NSPoint absP = [NSEvent mouseLocation];
 336 
 337     // Convert global numbers between Cocoa's coordinate system and Java.
 338     // TODO: need consitent way for doing that both with global as well as with local coordinates.
 339     // The reason to do it here is one more native method for getting screen dimension otherwise.
 340 
 341     NSRect screenRect = [[NSScreen mainScreen] frame];
 342     absP.y = screenRect.size.height - absP.y;
 343     jint clickCount;
 344 
 345     if (type == NSMouseEntered ||
 346         type == NSMouseExited ||
 347         type == NSScrollWheel ||
 348         type == NSMouseMoved) {
 349         clickCount = 0;
 350     } else {
 351         clickCount = [event clickCount];
 352     }
 353 
 354     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/event/NSEvent");
 355     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDD)V");
 356     jobject jEvent = JNFNewObject(env, jctor_NSEvent,
 357                                   [event type],
 358                                   [event modifierFlags],
 359                                   clickCount,
 360                                   [event buttonNumber],
 361                                   (jint)localPoint.x, (jint)localPoint.y,
 362                                   (jint)absP.x, (jint)absP.y,
 363                                   [event deltaY],
 364                                   [event deltaX]);
 365     if (jEvent == nil) {
 366         // Unable to create event by some reason.
 367         return;
 368     }
 369 
 370     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
 371     static JNF_MEMBER_CACHE(jm_deliverMouseEvent, jc_PlatformView, "deliverMouseEvent", "(Lsun/lwawt/macosx/event/NSEvent;)V");
 372     JNFCallVoidMethod(env, m_cPlatformView, jm_deliverMouseEvent, jEvent);
 373 }
 374 
 375 
 376 - (void) clearTrackingRect {
 377     if (rolloverTrackingRectTag > 0) {
 378         [self removeTrackingRect:rolloverTrackingRectTag];
 379         rolloverTrackingRectTag = 0;
 380     }
 381 }
 382 
 383 - (void) resetTrackingRect {
 384     [self clearTrackingRect];
 385     rolloverTrackingRectTag = [self addTrackingRect:[self visibleRect]
 386                                               owner:self
 387                                            userData:NULL
 388                                        assumeInside:NO];
 389 }
 390 
 391 - (void)updateTrackingAreas {
 392     [super updateTrackingAreas];
 393     [self resetTrackingRect];
 394 }
 395 
 396 - (void) resetCursorRects {
 397     [super resetCursorRects];
 398     [self resetTrackingRect];
 399 }
 400 
 401 -(void) deliverJavaKeyEventHelper: (NSEvent *) event {
 402     static NSEvent* sLastKeyEvent = nil;
 403     if (event == sLastKeyEvent) {
 404         // The event is repeatedly delivered by keyDown: after performKeyEquivalent:
 405         return;
 406     }
 407     [sLastKeyEvent release];
 408     sLastKeyEvent = [event retain];
 409 
 410     [AWTToolkit eventCountPlusPlus];
 411     JNIEnv *env = [ThreadUtilities getJNIEnv];
 412 
 413     jstring characters = NULL;
 414     if ([event type] != NSFlagsChanged) {
 415         characters = JNFNSToJavaString(env, [event characters]);
 416     }
 417 
 418     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/event/NSEvent");
 419     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;)V");
 420     jobject jevent = JNFNewObject(env, jctor_NSEvent,
 421                                   [event type],
 422                                   [event modifierFlags],
 423                                   [event keyCode],
 424                                   characters);
 425 
 426     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
 427     static JNF_MEMBER_CACHE(jm_deliverKeyEvent, jc_PlatformView,
 428                             "deliverKeyEvent", "(Lsun/lwawt/macosx/event/NSEvent;)V");
 429     JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jevent);
 430 
 431     if (characters != NULL) {
 432         (*env)->DeleteLocalRef(env, characters);
 433     }
 434 }
 435 
 436 - (void) drawRect:(NSRect)dirtyRect {
 437 AWT_ASSERT_APPKIT_THREAD;
 438 
 439     [super drawRect:dirtyRect];
 440     JNIEnv *env = [ThreadUtilities getJNIEnv];
 441     if (env != NULL) {
 442 /*
 443         if ([self inLiveResize]) {
 444         NSRect rs[4];
 445         NSInteger count;
 446         [self getRectsExposedDuringLiveResize:rs count:&count];
 447         for (int i = 0; i < count; i++) {
 448             JNU_CallMethodByName(env, NULL, [m_awtWindow cPlatformView],
 449                  "deliverWindowDidExposeEvent", "(FFFF)V",
 450                  (jfloat)rs[i].origin.x, (jfloat)rs[i].origin.y,
 451                  (jfloat)rs[i].size.width, (jfloat)rs[i].size.height);
 452         if ((*env)->ExceptionOccurred(env)) {
 453             (*env)->ExceptionDescribe(env);
 454             (*env)->ExceptionClear(env);
 455         }
 456         }
 457         } else {
 458 */
 459         static JNF_CLASS_CACHE(jc_CPlatformView, "sun/lwawt/macosx/CPlatformView");
 460         static JNF_MEMBER_CACHE(jm_deliverWindowDidExposeEvent, jc_CPlatformView, "deliverWindowDidExposeEvent", "()V");
 461         JNFCallVoidMethod(env, m_cPlatformView, jm_deliverWindowDidExposeEvent);
 462 /*
 463         }
 464 */
 465     }
 466 }
 467 
 468 // NSAccessibility support
 469 - (jobject)awtComponent:(JNIEnv*)env
 470 {
 471     static JNF_CLASS_CACHE(jc_CPlatformView, "sun/lwawt/macosx/CPlatformView");
 472     static JNF_MEMBER_CACHE(jf_Peer, jc_CPlatformView, "peer", "Lsun/lwawt/LWWindowPeer;");
 473     if ((env == NULL) || (m_cPlatformView == NULL)) {
 474         NSLog(@"Apple AWT : Error AWTView:awtComponent given bad parameters.");
 475         if (env != NULL)
 476         {
 477             JNFDumpJavaStack(env);
 478         }
 479         return NULL;
 480     }
 481     jobject peer = JNFGetObjectField(env, m_cPlatformView, jf_Peer);
 482     static JNF_CLASS_CACHE(jc_LWWindowPeer, "sun/lwawt/LWWindowPeer");
 483     static JNF_MEMBER_CACHE(jf_Target, jc_LWWindowPeer, "target", "Ljava/awt/Component;");
 484     if (peer == NULL) {
 485         NSLog(@"Apple AWT : Error AWTView:awtComponent got null peer from CPlatformView");
 486         JNFDumpJavaStack(env);
 487         return NULL;
 488     }
 489     return JNFGetObjectField(env, peer, jf_Target);
 490 }
 491 
 492 - (id)getAxData:(JNIEnv*)env
 493 {
 494     return [[[JavaComponentAccessibility alloc] initWithParent:self withEnv:env withAccessible:[self awtComponent:env] withIndex:-1 withView:self withJavaRole:nil] autorelease];
 495 }
 496 
 497 - (NSArray *)accessibilityAttributeNames
 498 {
 499     return [[super accessibilityAttributeNames] arrayByAddingObject:NSAccessibilityChildrenAttribute];
 500 }
 501 
 502 // NSAccessibility messages
 503 // attribute methods
 504 - (id)accessibilityAttributeValue:(NSString *)attribute
 505 {
 506     AWT_ASSERT_APPKIT_THREAD;
 507 
 508     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute])
 509     {
 510         JNIEnv *env = [ThreadUtilities getJNIEnv];
 511 
 512         (*env)->PushLocalFrame(env, 4);
 513 
 514         id result = NSAccessibilityUnignoredChildrenForOnlyChild([self getAxData:env]);
 515 
 516         (*env)->PopLocalFrame(env, NULL);
 517 
 518         return result;
 519     }
 520     else
 521     {
 522         return [super accessibilityAttributeValue:attribute];
 523     }
 524 }
 525 - (BOOL)accessibilityIsIgnored
 526 {
 527     return YES;
 528 }
 529 
 530 - (id)accessibilityHitTest:(NSPoint)point
 531 {
 532     AWT_ASSERT_APPKIT_THREAD;
 533     JNIEnv *env = [ThreadUtilities getJNIEnv];
 534 
 535     (*env)->PushLocalFrame(env, 4);
 536 
 537     id result = [[self getAxData:env] accessibilityHitTest:point withEnv:env];
 538 
 539     (*env)->PopLocalFrame(env, NULL);
 540 
 541     return result;
 542 }
 543 
 544 - (id)accessibilityFocusedUIElement
 545 {
 546     AWT_ASSERT_APPKIT_THREAD;
 547 
 548     JNIEnv *env = [ThreadUtilities getJNIEnv];
 549 
 550     (*env)->PushLocalFrame(env, 4);
 551 
 552     id result = [[self getAxData:env] accessibilityFocusedUIElement];
 553 
 554     (*env)->PopLocalFrame(env, NULL);
 555 
 556     return result;
 557 }
 558 
 559 // --- Services menu support for lightweights ---
 560 
 561 // finds the focused accessable element, and if it's a text element, obtains the text from it
 562 - (NSString *)accessibleSelectedText
 563 {
 564     id focused = [self accessibilityFocusedUIElement];
 565     if (![focused isKindOfClass:[JavaTextAccessibility class]]) return nil;
 566     return [(JavaTextAccessibility *)focused accessibilitySelectedTextAttribute];
 567 }
 568 
 569 // same as above, but converts to RTFD
 570 - (NSData *)accessibleSelectedTextAsRTFD
 571 {
 572     NSString *selectedText = [self accessibleSelectedText];
 573     NSAttributedString *styledText = [[NSAttributedString alloc] initWithString:selectedText];
 574     NSData *rtfdData = [styledText RTFDFromRange:NSMakeRange(0, [styledText length]) documentAttributes:nil];
 575     [styledText release];
 576     return rtfdData;
 577 }
 578 
 579 // finds the focused accessable element, and if it's a text element, sets the text in it
 580 - (BOOL)replaceAccessibleTextSelection:(NSString *)text
 581 {
 582     id focused = [self accessibilityFocusedUIElement];
 583     if (![focused isKindOfClass:[JavaTextAccessibility class]]) return NO;
 584     [(JavaTextAccessibility *)focused accessibilitySetSelectedTextAttribute:text];
 585     return YES;
 586 }
 587 
 588 // called for each service in the Services menu - only handle text for now
 589 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
 590 {
 591     if ([[self window] firstResponder] != self) return nil; // let AWT components handle themselves
 592 
 593     if ([sendType isEqual:NSStringPboardType] || [returnType isEqual:NSStringPboardType]) {
 594         NSString *selectedText = [self accessibleSelectedText];
 595         if (selectedText) return self;
 596     }
 597 
 598     return nil;
 599 }
 600 
 601 // fetch text from Java and hand off to the service
 602 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types
 603 {
 604     if ([types containsObject:NSStringPboardType])
 605     {
 606         [pboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
 607         return [pboard setString:[self accessibleSelectedText] forType:NSStringPboardType];
 608     }
 609 
 610     if ([types containsObject:NSRTFDPboardType])
 611     {
 612         [pboard declareTypes:[NSArray arrayWithObject:NSRTFDPboardType] owner:nil];
 613         return [pboard setData:[self accessibleSelectedTextAsRTFD] forType:NSRTFDPboardType];
 614     }
 615 
 616     return NO;
 617 }
 618 
 619 // write text back to Java from the service
 620 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
 621 {
 622     if ([[pboard types] containsObject:NSStringPboardType])
 623     {
 624         NSString *text = [pboard stringForType:NSStringPboardType];
 625         return [self replaceAccessibleTextSelection:text];
 626     }
 627 
 628     if ([[pboard types] containsObject:NSRTFDPboardType])
 629     {
 630         NSData *rtfdData = [pboard dataForType:NSRTFDPboardType];
 631         NSAttributedString *styledText = [[NSAttributedString alloc] initWithRTFD:rtfdData documentAttributes:nil];
 632         NSString *text = [styledText string];
 633         [styledText release];
 634 
 635         return [self replaceAccessibleTextSelection:text];
 636     }
 637 
 638     return NO;
 639 }
 640 
 641 
 642 -(void) setDragSource:(CDragSource *)source {
 643     self._dragSource = source;
 644 }
 645 
 646 
 647 - (void) setDropTarget:(CDropTarget *)target {
 648     self._dropTarget = target;
 649     [ThreadUtilities performOnMainThread:@selector(controlModelControlValid) onObject:self._dropTarget withObject:nil waitUntilDone:YES awtMode:YES];
 650 }
 651 
 652 /********************************  BEGIN NSDraggingSource Interface  ********************************/
 653 
 654 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)flag
 655 {
 656     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 657     CDragSource *dragSource = self._dragSource;
 658     NSDragOperation dragOp = NSDragOperationNone;
 659 
 660     if (dragSource != nil)
 661         dragOp = [dragSource draggingSourceOperationMaskForLocal:flag];
 662     else if ([super respondsToSelector:@selector(draggingSourceOperationMaskForLocal:)])
 663         dragOp = [super draggingSourceOperationMaskForLocal:flag];
 664 
 665     return dragOp;
 666 }
 667 
 668 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
 669 {
 670     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 671     CDragSource *dragSource = self._dragSource;
 672     NSArray* array = nil;
 673 
 674     if (dragSource != nil)
 675         array = [dragSource namesOfPromisedFilesDroppedAtDestination:dropDestination];
 676     else if ([super respondsToSelector:@selector(namesOfPromisedFilesDroppedAtDestination:)])
 677         array = [super namesOfPromisedFilesDroppedAtDestination:dropDestination];
 678 
 679     return array;
 680 }
 681 
 682 - (void)draggedImage:(NSImage *)image beganAt:(NSPoint)screenPoint
 683 {
 684     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 685     CDragSource *dragSource = self._dragSource;
 686 
 687     if (dragSource != nil)
 688         [dragSource draggedImage:image beganAt:screenPoint];
 689     else if ([super respondsToSelector:@selector(draggedImage::)])
 690         [super draggedImage:image beganAt:screenPoint];
 691 }
 692 
 693 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)screenPoint operation:(NSDragOperation)operation
 694 {
 695     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 696     CDragSource *dragSource = self._dragSource;
 697 
 698     if (dragSource != nil)
 699         [dragSource draggedImage:image endedAt:screenPoint operation:operation];
 700     else if ([super respondsToSelector:@selector(draggedImage:::)])
 701         [super draggedImage:image endedAt:screenPoint operation:operation];
 702 }
 703 
 704 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenPoint
 705 {
 706     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 707     CDragSource *dragSource = self._dragSource;
 708 
 709     if (dragSource != nil)
 710         [dragSource draggedImage:image movedTo:screenPoint];
 711     else if ([super respondsToSelector:@selector(draggedImage::)])
 712         [super draggedImage:image movedTo:screenPoint];
 713 }
 714 
 715 - (BOOL)ignoreModifierKeysWhileDragging
 716 {
 717     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 718     CDragSource *dragSource = self._dragSource;
 719     BOOL result = FALSE;
 720 
 721     if (dragSource != nil)
 722         result = [dragSource ignoreModifierKeysWhileDragging];
 723     else if ([super respondsToSelector:@selector(ignoreModifierKeysWhileDragging)])
 724         result = [super ignoreModifierKeysWhileDragging];
 725 
 726     return result;
 727 }
 728 
 729 /********************************  END NSDraggingSource Interface  ********************************/
 730 
 731 /********************************  BEGIN NSDraggingDestination Interface  ********************************/
 732 
 733 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
 734 {
 735     // If draggingDestination is nil route the message to the superclass:
 736     CDropTarget *dropTarget = self._dropTarget;
 737     NSDragOperation dragOp = NSDragOperationNone;
 738 
 739     if (dropTarget != nil)
 740         dragOp = [dropTarget draggingEntered:sender];
 741     else if ([super respondsToSelector:@selector(draggingEntered:)])
 742         dragOp = [super draggingEntered:sender];
 743 
 744     return dragOp;
 745 }
 746 
 747 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
 748 {
 749     // If draggingDestination is nil route the message to the superclass:
 750     CDropTarget *dropTarget = self._dropTarget;
 751     NSDragOperation dragOp = NSDragOperationNone;
 752 
 753     if (dropTarget != nil)
 754         dragOp = [dropTarget draggingUpdated:sender];
 755     else if ([super respondsToSelector:@selector(draggingUpdated:)])
 756         dragOp = [super draggingUpdated:sender];
 757 
 758     return dragOp;
 759 }
 760 
 761 - (void)draggingExited:(id <NSDraggingInfo>)sender
 762 {
 763     // If draggingDestination is nil route the message to the superclass:
 764     CDropTarget *dropTarget = self._dropTarget;
 765 
 766     if (dropTarget != nil)
 767         [dropTarget draggingExited:sender];
 768     else if ([super respondsToSelector:@selector(draggingExited:)])
 769         [super draggingExited:sender];
 770 }
 771 
 772 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
 773 {
 774     // If draggingDestination is nil route the message to the superclass:
 775     CDropTarget *dropTarget = self._dropTarget;
 776     BOOL result = FALSE;
 777 
 778     if (dropTarget != nil)
 779         result = [dropTarget prepareForDragOperation:sender];
 780     else if ([super respondsToSelector:@selector(prepareForDragOperation:)])
 781         result = [super prepareForDragOperation:sender];
 782 
 783     return result;
 784 }
 785 
 786 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
 787 {
 788     // If draggingDestination is nil route the message to the superclass:
 789     CDropTarget *dropTarget = self._dropTarget;
 790     BOOL result = FALSE;
 791 
 792     if (dropTarget != nil)
 793         result = [dropTarget performDragOperation:sender];
 794     else if ([super respondsToSelector:@selector(performDragOperation:)])
 795         result = [super performDragOperation:sender];
 796 
 797     return result;
 798 }
 799 
 800 - (void)concludeDragOperation:(id <NSDraggingInfo>)sender
 801 {
 802     // If draggingDestination is nil route the message to the superclass:
 803     CDropTarget *dropTarget = self._dropTarget;
 804 
 805     if (dropTarget != nil)
 806         [dropTarget concludeDragOperation:sender];
 807     else if ([super respondsToSelector:@selector(concludeDragOperation:)])
 808         [super concludeDragOperation:sender];
 809 }
 810 
 811 - (void)draggingEnded:(id <NSDraggingInfo>)sender
 812 {
 813     // If draggingDestination is nil route the message to the superclass:
 814     CDropTarget *dropTarget = self._dropTarget;
 815 
 816     if (dropTarget != nil)
 817         [dropTarget draggingEnded:sender];
 818     else if ([super respondsToSelector:@selector(draggingEnded:)])
 819         [super draggingEnded:sender];
 820 }
 821 
 822 /********************************  END NSDraggingDestination Interface  ********************************/
 823 
 824 /********************************  BEGIN NSTextInputClient Protocol  ********************************/
 825 
 826 
 827 JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod");
 828 
 829 - (void) insertText:(id)aString replacementRange:(NSRange)replacementRange
 830 {
 831 #ifdef IM_DEBUG
 832     fprintf(stderr, "AWTView InputMethod Selector Called : [insertText]: %s\n", [aString UTF8String]);
 833 #endif // IM_DEBUG
 834 
 835     if (fInputMethodLOCKABLE == NULL) {
 836         return;
 837     }
 838 
 839     // Insert happens at the end of PAH
 840     fInPressAndHold = NO;
 841 
 842     // insertText gets called when the user commits text generated from an input method.  It also gets
 843     // called during ordinary input as well.  We only need to send an input method event when we have marked
 844     // text, or 'text in progress'.  We also need to send the event if we get an insert text out of the blue!
 845     // (i.e., when the user uses the Character palette or Inkwell), or when the string to insert is a complex
 846     // Unicode value.
 847     NSUInteger utf8Length = [aString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
 848 
 849     if ([self hasMarkedText] || !fProcessingKeystroke || (utf8Length > 1)) {
 850         JNIEnv *env = [ThreadUtilities getJNIEnv];
 851 
 852         static JNF_MEMBER_CACHE(jm_selectPreviousGlyph, jc_CInputMethod, "selectPreviousGlyph", "()V");
 853         // We need to select the previous glyph so that it is overwritten.
 854         if (fPAHNeedsToSelect) {
 855             JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_selectPreviousGlyph);
 856             fPAHNeedsToSelect = NO;
 857         }
 858 
 859         static JNF_MEMBER_CACHE(jm_insertText, jc_CInputMethod, "insertText", "(Ljava/lang/String;)V");
 860         jstring insertedText =  JNFNSToJavaString(env, aString);
 861         JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_insertText, insertedText); // AWT_THREADING Safe (AWTRunLoopMode)
 862         (*env)->DeleteLocalRef(env, insertedText);
 863 
 864         // The input method event will create psuedo-key events for each character in the committed string.
 865         // We also don't want to send the character that triggered the insertText, usually a return. [3337563]
 866         fKeyEventsNeeded = NO;
 867     }
 868 
 869     fPAHNeedsToSelect = NO;
 870 
 871 }
 872 
 873 - (void) doCommandBySelector:(SEL)aSelector
 874 {
 875 #ifdef IM_DEBUG
 876     fprintf(stderr, "AWTView InputMethod Selector Called : [doCommandBySelector]\n");
 877     NSLog(@"%@", NSStringFromSelector(aSelector));
 878 #endif // IM_DEBUG
 879     if (@selector(insertNewline:) == aSelector || @selector(insertTab:) == aSelector || @selector(deleteBackward:) == aSelector)
 880     {
 881         fKeyEventsNeeded = YES;
 882     }
 883 }
 884 
 885 // setMarkedText: cannot take a nil first argument. aString can be NSString or NSAttributedString
 886 - (void) setMarkedText:(id)aString selectedRange:(NSRange)selectionRange replacementRange:(NSRange)replacementRange
 887 {
 888     if (!fInputMethodLOCKABLE)
 889         return;
 890 
 891     BOOL isAttributedString = [aString isKindOfClass:[NSAttributedString class]];
 892     NSAttributedString *attrString = (isAttributedString ? (NSAttributedString *)aString : nil);
 893     NSString *incomingString = (isAttributedString ? [aString string] : aString);
 894 #ifdef IM_DEBUG
 895     fprintf(stderr, "AWTView InputMethod Selector Called : [setMarkedText] \"%s\", loc=%lu, length=%lu\n", [incomingString UTF8String], (unsigned long)selectionRange.location, (unsigned long)selectionRange.length);
 896 #endif // IM_DEBUG
 897     static JNF_MEMBER_CACHE(jm_startIMUpdate, jc_CInputMethod, "startIMUpdate", "(Ljava/lang/String;)V");
 898     static JNF_MEMBER_CACHE(jm_addAttribute, jc_CInputMethod, "addAttribute", "(ZZII)V");
 899     static JNF_MEMBER_CACHE(jm_dispatchText, jc_CInputMethod, "dispatchText", "(IIZ)V");
 900     JNIEnv *env = [ThreadUtilities getJNIEnv];
 901 
 902     // NSInputContext already did the analysis of the TSM event and created attributes indicating
 903     // the underlining and color that should be done to the string.  We need to look at the underline
 904     // style and color to determine what kind of Java hilighting needs to be done.
 905     jstring inProcessText = JNFNSToJavaString(env, incomingString);
 906     JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_startIMUpdate, inProcessText); // AWT_THREADING Safe (AWTRunLoopMode)
 907     (*env)->DeleteLocalRef(env, inProcessText);
 908 
 909     if (isAttributedString) {
 910         NSUInteger length;
 911         NSRange effectiveRange;
 912         NSDictionary *attributes;
 913         length = [attrString length];
 914         effectiveRange = NSMakeRange(0, 0);
 915         while (NSMaxRange(effectiveRange) < length) {
 916             attributes = [attrString attributesAtIndex:NSMaxRange(effectiveRange)
 917                                         effectiveRange:&effectiveRange];
 918             if (attributes) {
 919                 BOOL isThickUnderline, isGray;
 920                 NSNumber *underlineSizeObj =
 921                 (NSNumber *)[attributes objectForKey:NSUnderlineStyleAttributeName];
 922                 NSInteger underlineSize = [underlineSizeObj integerValue];
 923                 isThickUnderline = (underlineSize > 1);
 924 
 925                 NSColor *underlineColorObj =
 926                 (NSColor *)[attributes objectForKey:NSUnderlineColorAttributeName];
 927                 isGray = !([underlineColorObj isEqual:[NSColor blackColor]]);
 928 
 929                 JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_addAttribute, isThickUnderline, isGray, effectiveRange.location, effectiveRange.length); // AWT_THREADING Safe (AWTRunLoopMode)
 930             }
 931         }
 932     }
 933 
 934     static JNF_MEMBER_CACHE(jm_selectPreviousGlyph, jc_CInputMethod, "selectPreviousGlyph", "()V");
 935     // We need to select the previous glyph so that it is overwritten.
 936     if (fPAHNeedsToSelect) {
 937         JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_selectPreviousGlyph);
 938         fPAHNeedsToSelect = NO;
 939     }
 940 
 941     JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_dispatchText, selectionRange.location, selectionRange.length, JNI_FALSE); // AWT_THREADING Safe (AWTRunLoopMode)
 942 
 943     // If the marked text is being cleared (zero-length string) don't handle the key event.
 944     if ([incomingString length] == 0) {
 945         fKeyEventsNeeded = NO;
 946     }
 947 }
 948 
 949 - (void) unmarkText
 950 {
 951 #ifdef IM_DEBUG
 952     fprintf(stderr, "AWTView InputMethod Selector Called : [unmarkText]\n");
 953 #endif // IM_DEBUG
 954 
 955     if (!fInputMethodLOCKABLE) {
 956         return;
 957     }
 958 
 959     // unmarkText cancels any input in progress and commits it to the text field.
 960     static JNF_MEMBER_CACHE(jm_unmarkText, jc_CInputMethod, "unmarkText", "()V");
 961     JNIEnv *env = [ThreadUtilities getJNIEnv];
 962     JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_unmarkText); // AWT_THREADING Safe (AWTRunLoopMode)
 963 
 964 }
 965 
 966 - (BOOL) hasMarkedText
 967 {
 968 #ifdef IM_DEBUG
 969     fprintf(stderr, "AWTView InputMethod Selector Called : [hasMarkedText]\n");
 970 #endif // IM_DEBUG
 971 
 972     if (!fInputMethodLOCKABLE) {
 973         return NO;
 974     }
 975 
 976     static JNF_MEMBER_CACHE(jf_fCurrentText, jc_CInputMethod, "fCurrentText", "Ljava/text/AttributedString;");
 977     static JNF_MEMBER_CACHE(jf_fCurrentTextLength, jc_CInputMethod, "fCurrentTextLength", "I");
 978     JNIEnv *env = [ThreadUtilities getJNIEnv];
 979     jobject currentText = JNFGetObjectField(env, fInputMethodLOCKABLE, jf_fCurrentText);
 980 
 981     jint currentTextLength = JNFGetIntField(env, fInputMethodLOCKABLE, jf_fCurrentTextLength);
 982 
 983     BOOL hasMarkedText = (currentText != NULL && currentTextLength > 0);
 984 
 985     if (currentText != NULL) {
 986         (*env)->DeleteLocalRef(env, currentText);
 987     }
 988 
 989     return hasMarkedText;
 990 }
 991 
 992 - (NSInteger) conversationIdentifier
 993 {
 994 #ifdef IM_DEBUG
 995     fprintf(stderr, "AWTView InputMethod Selector Called : [conversationIdentifier]\n");
 996 #endif // IM_DEBUG
 997 
 998     return (NSInteger) self;
 999 }
1000 
1001 /* Returns attributed string at the range.  This allows input mangers to
1002  query any range in backing-store (Andy's request)
1003  */
1004 - (NSAttributedString *) attributedSubstringForProposedRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1005 {
1006 #ifdef IM_DEBUG
1007     fprintf(stderr, "AWTView InputMethod Selector Called : [attributedSubstringFromRange] location=%lu, length=%lu\n", (unsigned long)theRange.location, (unsigned long)theRange.length);
1008 #endif // IM_DEBUG
1009 
1010     static JNF_MEMBER_CACHE(jm_substringFromRange, jc_CInputMethod, "attributedSubstringFromRange", "(II)Ljava/lang/String;");
1011     JNIEnv *env = [ThreadUtilities getJNIEnv];
1012     jobject theString = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_substringFromRange, theRange.location, theRange.length); // AWT_THREADING Safe (AWTRunLoopMode)
1013 
1014     id result = [[[NSAttributedString alloc] initWithString:JNFJavaToNSString(env, theString)] autorelease];
1015 #ifdef IM_DEBUG
1016     NSLog(@"attributedSubstringFromRange returning \"%@\"", result);
1017 #endif // IM_DEBUG
1018 
1019     (*env)->DeleteLocalRef(env, theString);
1020     return result;
1021 }
1022 
1023 /* This method returns the range for marked region.  If hasMarkedText == false,
1024  it'll return NSNotFound location & 0 length range.
1025  */
1026 - (NSRange) markedRange
1027 {
1028 
1029 #ifdef IM_DEBUG
1030     fprintf(stderr, "AWTView InputMethod Selector Called : [markedRange]\n");
1031 #endif // IM_DEBUG
1032 
1033     if (!fInputMethodLOCKABLE) {
1034         return NSMakeRange(NSNotFound, 0);
1035     }
1036 
1037     static JNF_MEMBER_CACHE(jm_markedRange, jc_CInputMethod, "markedRange", "()[I");
1038     JNIEnv *env = [ThreadUtilities getJNIEnv];
1039     jarray array;
1040     jboolean isCopy;
1041     jint *_array;
1042     NSRange range;
1043 
1044     array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_markedRange); // AWT_THREADING Safe (AWTRunLoopMode)
1045 
1046     if (array) {
1047         _array = (*env)->GetIntArrayElements(env, array, &isCopy);
1048         range = NSMakeRange(_array[0], _array[1]);
1049 
1050 #ifdef IM_DEBUG
1051         fprintf(stderr, "markedRange returning (%lu, %lu)\n", (unsigned long)range.location, (unsigned long)range.length);
1052 #endif // IM_DEBUG
1053         (*env)->ReleaseIntArrayElements(env, array, _array, 0);
1054         (*env)->DeleteLocalRef(env, array);
1055     } else {
1056         range = NSMakeRange(NSNotFound, 0);
1057     }
1058 
1059     return range;
1060 }
1061 
1062 /* This method returns the range for selected region.  Just like markedRange method,
1063  its location field contains char index from the text beginning.
1064  */
1065 - (NSRange) selectedRange
1066 {
1067     if (!fInputMethodLOCKABLE) {
1068         return NSMakeRange(NSNotFound, 0);
1069     }
1070 
1071     static JNF_MEMBER_CACHE(jm_selectedRange, jc_CInputMethod, "selectedRange", "()[I");
1072     JNIEnv *env = [ThreadUtilities getJNIEnv];
1073     jarray array;
1074     jboolean isCopy;
1075     jint *_array;
1076     NSRange range;
1077 
1078 #ifdef IM_DEBUG
1079     fprintf(stderr, "AWTView InputMethod Selector Called : [selectedRange]\n");
1080 #endif // IM_DEBUG
1081 
1082     array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_selectedRange); // AWT_THREADING Safe (AWTRunLoopMode)
1083     if (array) {
1084         _array = (*env)->GetIntArrayElements(env, array, &isCopy);
1085         range = NSMakeRange(_array[0], _array[1]);
1086         (*env)->ReleaseIntArrayElements(env, array, _array, 0);
1087         (*env)->DeleteLocalRef(env, array);
1088     } else {
1089         range = NSMakeRange(NSNotFound, 0);
1090     }
1091 
1092     return range;
1093 
1094 }
1095 
1096 /* This method returns the first frame of rects for theRange in screen coordindate system.
1097  */
1098 - (NSRect) firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1099 {
1100     if (!fInputMethodLOCKABLE) {
1101         return NSMakeRect(0, 0, 0, 0);
1102     }
1103 
1104     static JNF_MEMBER_CACHE(jm_firstRectForCharacterRange, jc_CInputMethod,
1105                             "firstRectForCharacterRange", "(I)[I");
1106     JNIEnv *env = [ThreadUtilities getJNIEnv];
1107     jarray array;
1108     jboolean isCopy;
1109     jint *_array;
1110     NSRect rect;
1111 
1112 #ifdef IM_DEBUG
1113     fprintf(stderr, "AWTView InputMethod Selector Called : [firstRectForCharacterRange:] location=%lu, length=%lu\n", (unsigned long)theRange.location, (unsigned long)theRange.length);
1114 #endif // IM_DEBUG
1115 
1116     array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_firstRectForCharacterRange, theRange.location); // AWT_THREADING Safe (AWTRunLoopMode)
1117 
1118     _array = (*env)->GetIntArrayElements(env, array, &isCopy);
1119     rect = ConvertNSScreenRect(env, NSMakeRect(_array[0], _array[1], _array[2], _array[3]));
1120     (*env)->ReleaseIntArrayElements(env, array, _array, 0);
1121     (*env)->DeleteLocalRef(env, array);
1122 
1123 #ifdef IM_DEBUG
1124     fprintf(stderr, "firstRectForCharacterRange returning x=%f, y=%f, width=%f, height=%f\n", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
1125 #endif // IM_DEBUG
1126     return rect;
1127 }
1128 
1129 /* This method returns the index for character that is nearest to thePoint.  thPoint is in
1130  screen coordinate system.
1131  */
1132 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1133 {
1134     if (!fInputMethodLOCKABLE) {
1135         return NSNotFound;
1136     }
1137 
1138     static JNF_MEMBER_CACHE(jm_characterIndexForPoint, jc_CInputMethod,
1139                             "characterIndexForPoint", "(II)I");
1140     JNIEnv *env = [ThreadUtilities getJNIEnv];
1141 
1142     NSPoint flippedLocation = ConvertNSScreenPoint(env, thePoint);
1143 
1144 #ifdef IM_DEBUG
1145     fprintf(stderr, "AWTView InputMethod Selector Called : [characterIndexForPoint:(NSPoint)thePoint] x=%f, y=%f\n", flippedLocation.x, flippedLocation.y);
1146 #endif // IM_DEBUG
1147 
1148     jint index = JNFCallIntMethod(env, fInputMethodLOCKABLE, jm_characterIndexForPoint, (jint)flippedLocation.x, (jint)flippedLocation.y); // AWT_THREADING Safe (AWTRunLoopMode)
1149 
1150 #ifdef IM_DEBUG
1151     fprintf(stderr, "characterIndexForPoint returning %ld\n", index);
1152 #endif // IM_DEBUG
1153 
1154     if (index == -1) {
1155         return NSNotFound;
1156     } else {
1157         return (NSUInteger)index;
1158     }
1159 }
1160 
1161 - (NSArray*) validAttributesForMarkedText
1162 {
1163 #ifdef IM_DEBUG
1164     fprintf(stderr, "AWTView InputMethod Selector Called : [validAttributesForMarkedText]\n");
1165 #endif // IM_DEBUG
1166 
1167     return [NSArray array];
1168 }
1169 
1170 - (void)setInputMethod:(jobject)inputMethod
1171 {
1172 #ifdef IM_DEBUG
1173     fprintf(stderr, "AWTView InputMethod Selector Called : [setInputMethod]\n");
1174 #endif // IM_DEBUG
1175 
1176     JNIEnv *env = [ThreadUtilities getJNIEnv];
1177 
1178     // Get rid of the old one
1179     if (fInputMethodLOCKABLE) {
1180         JNFDeleteGlobalRef(env, fInputMethodLOCKABLE);
1181     }
1182 
1183     // Save a global ref to the new input method.
1184     if (inputMethod != NULL)
1185         fInputMethodLOCKABLE = JNFNewGlobalRef(env, inputMethod);
1186     else
1187         fInputMethodLOCKABLE = NULL;
1188 }
1189 
1190 - (void)abandonInput
1191 {
1192 #ifdef IM_DEBUG
1193     fprintf(stderr, "AWTView InputMethod Selector Called : [abandonInput]\n");
1194 #endif // IM_DEBUG
1195 
1196     [ThreadUtilities performOnMainThread:@selector(markedTextAbandoned:) onObject:[NSInputManager currentInputManager] withObject:self waitUntilDone:YES awtMode:YES];
1197     [self unmarkText];
1198 }
1199 
1200 /********************************   END NSTextInputClient Protocol   ********************************/
1201 
1202 
1203 
1204 
1205 @end // AWTView
1206 
1207 /*
1208  * Class:     sun_lwawt_macosx_CPlatformView
1209  * Method:    nativeCreateView
1210  * Signature: (IIII)J
1211  */
1212 JNIEXPORT jlong JNICALL
1213 Java_sun_lwawt_macosx_CPlatformView_nativeCreateView
1214 (JNIEnv *env, jobject obj, jint originX, jint originY, jint width, jint height, jlong windowLayerPtr)
1215 {
1216     __block AWTView *newView = nil;
1217 
1218 JNF_COCOA_ENTER(env);
1219 AWT_ASSERT_NOT_APPKIT_THREAD;
1220 
1221     NSRect rect = NSMakeRect(originX, originY, width, height);
1222     jobject cPlatformView = (*env)->NewGlobalRef(env, obj);
1223 
1224     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
1225         AWT_ASSERT_APPKIT_THREAD;
1226 
1227         CALayer *windowLayer = jlong_to_ptr(windowLayerPtr);
1228         AWTView *view = [[AWTView alloc] initWithRect:rect
1229                                          platformView:cPlatformView
1230                                          windowLayer:windowLayer];
1231         CFRetain(view);
1232         [view release]; // GC
1233 
1234         newView = view;
1235     }];
1236 
1237 JNF_COCOA_EXIT(env);
1238 
1239     return ptr_to_jlong(newView);
1240 }