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