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 | NSTrackingCursorUpdate |
 379                    NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
 380                    NSTrackingEnabledDuringMouseDrag);
 381 
 382     rolloverTrackingArea = [[NSTrackingArea alloc] initWithRect:[self visibleRect]
 383                                                         options: options
 384                                                           owner:self
 385                                                        userInfo:nil
 386                             ];
 387     [self addTrackingArea:rolloverTrackingArea];
 388 }
 389 
 390 - (void)updateTrackingAreas {
 391     [super updateTrackingAreas];
 392     [self resetTrackingArea];
 393 }
 394 
 395 - (void) resetCursorRects {
 396     [super resetCursorRects];
 397     [self resetTrackingArea];
 398 }
 399 
 400 -(void) deliverJavaKeyEventHelper: (NSEvent *) event {
 401     static NSEvent* sLastKeyEvent = nil;
 402     if (event == sLastKeyEvent) {
 403         // The event is repeatedly delivered by keyDown: after performKeyEquivalent:
 404         return;
 405     }
 406     [sLastKeyEvent release];
 407     sLastKeyEvent = [event retain];
 408         
 409     [AWTToolkit eventCountPlusPlus];
 410     JNIEnv *env = [ThreadUtilities getJNIEnv];
 411 
 412     jstring characters = NULL;
 413     if ([event type] != NSFlagsChanged) {
 414         characters = JNFNSToJavaString(env, [event characters]);
 415     }
 416 
 417     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/event/NSEvent");
 418     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;)V");
 419     jobject jevent = JNFNewObject(env, jctor_NSEvent,
 420                                   [event type],
 421                                   [event modifierFlags],
 422                                   [event keyCode],
 423                                   characters);
 424 
 425     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
 426     static JNF_MEMBER_CACHE(jm_deliverKeyEvent, jc_PlatformView,
 427                             "deliverKeyEvent", "(Lsun/lwawt/macosx/event/NSEvent;)V");
 428     JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jevent);
 429 
 430     if (characters != NULL) {
 431         (*env)->DeleteLocalRef(env, characters);
 432     }
 433 }
 434 
 435 - (void) drawRect:(NSRect)dirtyRect {
 436 AWT_ASSERT_APPKIT_THREAD;
 437 
 438     [super drawRect:dirtyRect];
 439     JNIEnv *env = [ThreadUtilities getJNIEnv];
 440     if (env != NULL) {
 441 /*
 442         if ([self inLiveResize]) {
 443         NSRect rs[4];
 444         NSInteger count;
 445         [self getRectsExposedDuringLiveResize:rs count:&count];
 446         for (int i = 0; i < count; i++) {
 447             JNU_CallMethodByName(env, NULL, [m_awtWindow cPlatformView],
 448                  "deliverWindowDidExposeEvent", "(FFFF)V",
 449                  (jfloat)rs[i].origin.x, (jfloat)rs[i].origin.y,
 450                  (jfloat)rs[i].size.width, (jfloat)rs[i].size.height);
 451         if ((*env)->ExceptionOccurred(env)) {
 452             (*env)->ExceptionDescribe(env);
 453             (*env)->ExceptionClear(env);
 454         }
 455         }
 456         } else {
 457 */
 458         static JNF_CLASS_CACHE(jc_CPlatformView, "sun/lwawt/macosx/CPlatformView");
 459         static JNF_MEMBER_CACHE(jm_deliverWindowDidExposeEvent, jc_CPlatformView, "deliverWindowDidExposeEvent", "()V");
 460         JNFCallVoidMethod(env, m_cPlatformView, jm_deliverWindowDidExposeEvent);
 461 /*
 462         }
 463 */
 464     }
 465 }
 466 
 467 // NSAccessibility support
 468 - (jobject)awtComponent:(JNIEnv*)env
 469 {
 470     static JNF_CLASS_CACHE(jc_CPlatformView, "sun/lwawt/macosx/CPlatformView");
 471     static JNF_MEMBER_CACHE(jf_Peer, jc_CPlatformView, "peer", "Lsun/lwawt/LWWindowPeer;");
 472     if ((env == NULL) || (m_cPlatformView == NULL)) {
 473         NSLog(@"Apple AWT : Error AWTView:awtComponent given bad parameters.");
 474         if (env != NULL)
 475         {
 476             JNFDumpJavaStack(env);
 477         }
 478         return NULL;
 479     }
 480     jobject peer = JNFGetObjectField(env, m_cPlatformView, jf_Peer);
 481     static JNF_CLASS_CACHE(jc_LWWindowPeer, "sun/lwawt/LWWindowPeer");
 482     static JNF_MEMBER_CACHE(jf_Target, jc_LWWindowPeer, "target", "Ljava/awt/Component;");
 483     if (peer == NULL) {
 484         NSLog(@"Apple AWT : Error AWTView:awtComponent got null peer from CPlatformView");
 485         JNFDumpJavaStack(env);
 486         return NULL;
 487     }
 488     return JNFGetObjectField(env, peer, jf_Target);
 489 }
 490 
 491 - (id)getAxData:(JNIEnv*)env
 492 {
 493     return [[[JavaComponentAccessibility alloc] initWithParent:self withEnv:env withAccessible:[self awtComponent:env] withIndex:-1 withView:self withJavaRole:nil] autorelease];
 494 }
 495 
 496 - (NSArray *)accessibilityAttributeNames
 497 {
 498     return [[super accessibilityAttributeNames] arrayByAddingObject:NSAccessibilityChildrenAttribute];
 499 }
 500 
 501 // NSAccessibility messages
 502 // attribute methods
 503 - (id)accessibilityAttributeValue:(NSString *)attribute
 504 {
 505     AWT_ASSERT_APPKIT_THREAD;
 506 
 507     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute])
 508     {
 509         JNIEnv *env = [ThreadUtilities getJNIEnv];
 510 
 511         (*env)->PushLocalFrame(env, 4);
 512 
 513         id result = NSAccessibilityUnignoredChildrenForOnlyChild([self getAxData:env]);
 514 
 515         (*env)->PopLocalFrame(env, NULL);
 516 
 517         return result;
 518     }
 519     else
 520     {
 521         return [super accessibilityAttributeValue:attribute];
 522     }
 523 }
 524 - (BOOL)accessibilityIsIgnored
 525 {
 526     return YES;
 527 }
 528 
 529 - (id)accessibilityHitTest:(NSPoint)point
 530 {
 531     AWT_ASSERT_APPKIT_THREAD;
 532     JNIEnv *env = [ThreadUtilities getJNIEnv];
 533 
 534     (*env)->PushLocalFrame(env, 4);
 535 
 536     id result = [[self getAxData:env] accessibilityHitTest:point withEnv:env];
 537 
 538     (*env)->PopLocalFrame(env, NULL);
 539 
 540     return result;
 541 }
 542 
 543 - (id)accessibilityFocusedUIElement
 544 {
 545     AWT_ASSERT_APPKIT_THREAD;
 546 
 547     JNIEnv *env = [ThreadUtilities getJNIEnv];
 548 
 549     (*env)->PushLocalFrame(env, 4);
 550 
 551     id result = [[self getAxData:env] accessibilityFocusedUIElement];
 552 
 553     (*env)->PopLocalFrame(env, NULL);
 554 
 555     return result;
 556 }
 557 
 558 // --- Services menu support for lightweights ---
 559 
 560 // finds the focused accessable element, and if it's a text element, obtains the text from it
 561 - (NSString *)accessibleSelectedText
 562 {
 563     id focused = [self accessibilityFocusedUIElement];
 564     if (![focused isKindOfClass:[JavaTextAccessibility class]]) return nil;
 565     return [(JavaTextAccessibility *)focused accessibilitySelectedTextAttribute];
 566 }
 567 
 568 // same as above, but converts to RTFD
 569 - (NSData *)accessibleSelectedTextAsRTFD
 570 {
 571     NSString *selectedText = [self accessibleSelectedText];
 572     NSAttributedString *styledText = [[NSAttributedString alloc] initWithString:selectedText];
 573     NSData *rtfdData = [styledText RTFDFromRange:NSMakeRange(0, [styledText length]) documentAttributes:nil];
 574     [styledText release];
 575     return rtfdData;
 576 }
 577 
 578 // finds the focused accessable element, and if it's a text element, sets the text in it
 579 - (BOOL)replaceAccessibleTextSelection:(NSString *)text
 580 {
 581     id focused = [self accessibilityFocusedUIElement];
 582     if (![focused isKindOfClass:[JavaTextAccessibility class]]) return NO;
 583     [(JavaTextAccessibility *)focused accessibilitySetSelectedTextAttribute:text];
 584     return YES;
 585 }
 586 
 587 // called for each service in the Services menu - only handle text for now
 588 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
 589 {
 590     if ([[self window] firstResponder] != self) return nil; // let AWT components handle themselves
 591 
 592     if ([sendType isEqual:NSStringPboardType] || [returnType isEqual:NSStringPboardType]) {
 593         NSString *selectedText = [self accessibleSelectedText];
 594         if (selectedText) return self;
 595     }
 596 
 597     return nil;
 598 }
 599 
 600 // fetch text from Java and hand off to the service
 601 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types
 602 {
 603     if ([types containsObject:NSStringPboardType])
 604     {
 605         [pboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
 606         return [pboard setString:[self accessibleSelectedText] forType:NSStringPboardType];
 607     }
 608 
 609     if ([types containsObject:NSRTFDPboardType])
 610     {
 611         [pboard declareTypes:[NSArray arrayWithObject:NSRTFDPboardType] owner:nil];
 612         return [pboard setData:[self accessibleSelectedTextAsRTFD] forType:NSRTFDPboardType];
 613     }
 614 
 615     return NO;
 616 }
 617 
 618 // write text back to Java from the service
 619 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
 620 {
 621     if ([[pboard types] containsObject:NSStringPboardType])
 622     {
 623         NSString *text = [pboard stringForType:NSStringPboardType];
 624         return [self replaceAccessibleTextSelection:text];
 625     }
 626 
 627     if ([[pboard types] containsObject:NSRTFDPboardType])
 628     {
 629         NSData *rtfdData = [pboard dataForType:NSRTFDPboardType];
 630         NSAttributedString *styledText = [[NSAttributedString alloc] initWithRTFD:rtfdData documentAttributes:nil];
 631         NSString *text = [styledText string];
 632         [styledText release];
 633 
 634         return [self replaceAccessibleTextSelection:text];
 635     }
 636 
 637     return NO;
 638 }
 639 
 640 
 641 -(void) setDragSource:(CDragSource *)source {
 642     self._dragSource = source;
 643 }
 644 
 645 
 646 - (void) setDropTarget:(CDropTarget *)target {
 647     self._dropTarget = target;
 648     [ThreadUtilities performOnMainThread:@selector(controlModelControlValid) onObject:self._dropTarget withObject:nil waitUntilDone:YES awtMode:YES];
 649 }
 650 
 651 /********************************  BEGIN NSDraggingSource Interface  ********************************/
 652 
 653 - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)flag
 654 {
 655     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 656     CDragSource *dragSource = self._dragSource;
 657     NSDragOperation dragOp = NSDragOperationNone;
 658 
 659     if (dragSource != nil)
 660         dragOp = [dragSource draggingSourceOperationMaskForLocal:flag];
 661     else if ([super respondsToSelector:@selector(draggingSourceOperationMaskForLocal:)])
 662         dragOp = [super draggingSourceOperationMaskForLocal:flag];
 663 
 664     return dragOp;
 665 }
 666 
 667 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
 668 {
 669     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 670     CDragSource *dragSource = self._dragSource;
 671     NSArray* array = nil;
 672 
 673     if (dragSource != nil)
 674         array = [dragSource namesOfPromisedFilesDroppedAtDestination:dropDestination];
 675     else if ([super respondsToSelector:@selector(namesOfPromisedFilesDroppedAtDestination:)])
 676         array = [super namesOfPromisedFilesDroppedAtDestination:dropDestination];
 677 
 678     return array;
 679 }
 680 
 681 - (void)draggedImage:(NSImage *)image beganAt:(NSPoint)screenPoint
 682 {
 683     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 684     CDragSource *dragSource = self._dragSource;
 685 
 686     if (dragSource != nil)
 687         [dragSource draggedImage:image beganAt:screenPoint];
 688     else if ([super respondsToSelector:@selector(draggedImage::)])
 689         [super draggedImage:image beganAt:screenPoint];
 690 }
 691 
 692 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)screenPoint operation:(NSDragOperation)operation
 693 {
 694     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 695     CDragSource *dragSource = self._dragSource;
 696 
 697     if (dragSource != nil)
 698         [dragSource draggedImage:image endedAt:screenPoint operation:operation];
 699     else if ([super respondsToSelector:@selector(draggedImage:::)])
 700         [super draggedImage:image endedAt:screenPoint operation:operation];
 701 }
 702 
 703 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenPoint
 704 {
 705     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 706     CDragSource *dragSource = self._dragSource;
 707 
 708     if (dragSource != nil)
 709         [dragSource draggedImage:image movedTo:screenPoint];
 710     else if ([super respondsToSelector:@selector(draggedImage::)])
 711         [super draggedImage:image movedTo:screenPoint];
 712 }
 713 
 714 - (BOOL)ignoreModifierKeysWhileDragging
 715 {
 716     // If draggingSource is nil route the message to the superclass (if responding to the selector):
 717     CDragSource *dragSource = self._dragSource;
 718     BOOL result = FALSE;
 719 
 720     if (dragSource != nil)
 721         result = [dragSource ignoreModifierKeysWhileDragging];
 722     else if ([super respondsToSelector:@selector(ignoreModifierKeysWhileDragging)])
 723         result = [super ignoreModifierKeysWhileDragging];
 724 
 725     return result;
 726 }
 727 
 728 /********************************  END NSDraggingSource Interface  ********************************/
 729 
 730 /********************************  BEGIN NSDraggingDestination Interface  ********************************/
 731 
 732 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
 733 {
 734     // If draggingDestination is nil route the message to the superclass:
 735     CDropTarget *dropTarget = self._dropTarget;
 736     NSDragOperation dragOp = NSDragOperationNone;
 737 
 738     if (dropTarget != nil)
 739         dragOp = [dropTarget draggingEntered:sender];
 740     else if ([super respondsToSelector:@selector(draggingEntered:)])
 741         dragOp = [super draggingEntered:sender];
 742 
 743     return dragOp;
 744 }
 745 
 746 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
 747 {
 748     // If draggingDestination is nil route the message to the superclass:
 749     CDropTarget *dropTarget = self._dropTarget;
 750     NSDragOperation dragOp = NSDragOperationNone;
 751 
 752     if (dropTarget != nil)
 753         dragOp = [dropTarget draggingUpdated:sender];
 754     else if ([super respondsToSelector:@selector(draggingUpdated:)])
 755         dragOp = [super draggingUpdated:sender];
 756 
 757     return dragOp;
 758 }
 759 
 760 - (void)draggingExited:(id <NSDraggingInfo>)sender
 761 {
 762     // If draggingDestination is nil route the message to the superclass:
 763     CDropTarget *dropTarget = self._dropTarget;
 764 
 765     if (dropTarget != nil)
 766         [dropTarget draggingExited:sender];
 767     else if ([super respondsToSelector:@selector(draggingExited:)])
 768         [super draggingExited:sender];
 769 }
 770 
 771 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
 772 {
 773     // If draggingDestination is nil route the message to the superclass:
 774     CDropTarget *dropTarget = self._dropTarget;
 775     BOOL result = FALSE;
 776 
 777     if (dropTarget != nil)
 778         result = [dropTarget prepareForDragOperation:sender];
 779     else if ([super respondsToSelector:@selector(prepareForDragOperation:)])
 780         result = [super prepareForDragOperation:sender];
 781 
 782     return result;
 783 }
 784 
 785 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
 786 {
 787     // If draggingDestination is nil route the message to the superclass:
 788     CDropTarget *dropTarget = self._dropTarget;
 789     BOOL result = FALSE;
 790 
 791     if (dropTarget != nil)
 792         result = [dropTarget performDragOperation:sender];
 793     else if ([super respondsToSelector:@selector(performDragOperation:)])
 794         result = [super performDragOperation:sender];
 795 
 796     return result;
 797 }
 798 
 799 - (void)concludeDragOperation:(id <NSDraggingInfo>)sender
 800 {
 801     // If draggingDestination is nil route the message to the superclass:
 802     CDropTarget *dropTarget = self._dropTarget;
 803 
 804     if (dropTarget != nil)
 805         [dropTarget concludeDragOperation:sender];
 806     else if ([super respondsToSelector:@selector(concludeDragOperation:)])
 807         [super concludeDragOperation:sender];
 808 }
 809 
 810 - (void)draggingEnded:(id <NSDraggingInfo>)sender
 811 {
 812     // If draggingDestination is nil route the message to the superclass:
 813     CDropTarget *dropTarget = self._dropTarget;
 814 
 815     if (dropTarget != nil)
 816         [dropTarget draggingEnded:sender];
 817     else if ([super respondsToSelector:@selector(draggingEnded:)])
 818         [super draggingEnded:sender];
 819 }
 820 
 821 /********************************  END NSDraggingDestination Interface  ********************************/
 822 
 823 /********************************  BEGIN NSTextInputClient Protocol  ********************************/
 824 
 825 
 826 JNF_CLASS_CACHE(jc_CInputMethod, "sun/lwawt/macosx/CInputMethod");
 827 
 828 - (void) insertText:(id)aString replacementRange:(NSRange)replacementRange
 829 {
 830 #ifdef IM_DEBUG
 831     fprintf(stderr, "AWTView InputMethod Selector Called : [insertText]: %s\n", [aString UTF8String]);
 832 #endif // IM_DEBUG
 833 
 834     if (fInputMethodLOCKABLE == NULL) {
 835         return;
 836     }
 837 
 838     // Insert happens at the end of PAH
 839     fInPressAndHold = NO;
 840 
 841     // insertText gets called when the user commits text generated from an input method.  It also gets
 842     // called during ordinary input as well.  We only need to send an input method event when we have marked
 843     // text, or 'text in progress'.  We also need to send the event if we get an insert text out of the blue!
 844     // (i.e., when the user uses the Character palette or Inkwell), or when the string to insert is a complex
 845     // Unicode value.
 846     NSUInteger utf8Length = [aString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
 847 
 848     if ([self hasMarkedText] || !fProcessingKeystroke || (utf8Length > 1)) {
 849         JNIEnv *env = [ThreadUtilities getJNIEnv];
 850 
 851         static JNF_MEMBER_CACHE(jm_selectPreviousGlyph, jc_CInputMethod, "selectPreviousGlyph", "()V");
 852         // We need to select the previous glyph so that it is overwritten.
 853         if (fPAHNeedsToSelect) {
 854             JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_selectPreviousGlyph);
 855             fPAHNeedsToSelect = NO;
 856         }
 857 
 858         static JNF_MEMBER_CACHE(jm_insertText, jc_CInputMethod, "insertText", "(Ljava/lang/String;)V");
 859         jstring insertedText =  JNFNSToJavaString(env, aString);
 860         JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_insertText, insertedText); // AWT_THREADING Safe (AWTRunLoopMode)
 861         (*env)->DeleteLocalRef(env, insertedText);
 862 
 863         // The input method event will create psuedo-key events for each character in the committed string.
 864         // We also don't want to send the character that triggered the insertText, usually a return. [3337563]
 865         fKeyEventsNeeded = NO;
 866     }
 867 
 868     fPAHNeedsToSelect = NO;
 869 
 870 }
 871 
 872 - (void) doCommandBySelector:(SEL)aSelector
 873 {
 874 #ifdef IM_DEBUG
 875     fprintf(stderr, "AWTView InputMethod Selector Called : [doCommandBySelector]\n");
 876     NSLog(@"%@", NSStringFromSelector(aSelector));
 877 #endif // IM_DEBUG
 878     if (@selector(insertNewline:) == aSelector || @selector(insertTab:) == aSelector || @selector(deleteBackward:) == aSelector)
 879     {
 880         fKeyEventsNeeded = YES;
 881     }
 882 }
 883 
 884 // setMarkedText: cannot take a nil first argument. aString can be NSString or NSAttributedString
 885 - (void) setMarkedText:(id)aString selectedRange:(NSRange)selectionRange replacementRange:(NSRange)replacementRange
 886 {
 887     if (!fInputMethodLOCKABLE)
 888         return;
 889 
 890     BOOL isAttributedString = [aString isKindOfClass:[NSAttributedString class]];
 891     NSAttributedString *attrString = (isAttributedString ? (NSAttributedString *)aString : nil);
 892     NSString *incomingString = (isAttributedString ? [aString string] : aString);
 893 #ifdef IM_DEBUG
 894     fprintf(stderr, "AWTView InputMethod Selector Called : [setMarkedText] \"%s\", loc=%lu, length=%lu\n", [incomingString UTF8String], (unsigned long)selectionRange.location, (unsigned long)selectionRange.length);
 895 #endif // IM_DEBUG
 896     static JNF_MEMBER_CACHE(jm_startIMUpdate, jc_CInputMethod, "startIMUpdate", "(Ljava/lang/String;)V");
 897     static JNF_MEMBER_CACHE(jm_addAttribute, jc_CInputMethod, "addAttribute", "(ZZII)V");
 898     static JNF_MEMBER_CACHE(jm_dispatchText, jc_CInputMethod, "dispatchText", "(IIZ)V");
 899     JNIEnv *env = [ThreadUtilities getJNIEnv];
 900 
 901     // NSInputContext already did the analysis of the TSM event and created attributes indicating
 902     // the underlining and color that should be done to the string.  We need to look at the underline
 903     // style and color to determine what kind of Java hilighting needs to be done.
 904     jstring inProcessText = JNFNSToJavaString(env, incomingString);
 905     JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_startIMUpdate, inProcessText); // AWT_THREADING Safe (AWTRunLoopMode)
 906     (*env)->DeleteLocalRef(env, inProcessText);
 907 
 908     if (isAttributedString) {
 909         NSUInteger length;
 910         NSRange effectiveRange;
 911         NSDictionary *attributes;
 912         length = [attrString length];
 913         effectiveRange = NSMakeRange(0, 0);
 914         while (NSMaxRange(effectiveRange) < length) {
 915             attributes = [attrString attributesAtIndex:NSMaxRange(effectiveRange)
 916                                         effectiveRange:&effectiveRange];
 917             if (attributes) {
 918                 BOOL isThickUnderline, isGray;
 919                 NSNumber *underlineSizeObj =
 920                 (NSNumber *)[attributes objectForKey:NSUnderlineStyleAttributeName];
 921                 NSInteger underlineSize = [underlineSizeObj integerValue];
 922                 isThickUnderline = (underlineSize > 1);
 923 
 924                 NSColor *underlineColorObj =
 925                 (NSColor *)[attributes objectForKey:NSUnderlineColorAttributeName];
 926                 isGray = !([underlineColorObj isEqual:[NSColor blackColor]]);
 927 
 928                 JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_addAttribute, isThickUnderline, isGray, effectiveRange.location, effectiveRange.length); // AWT_THREADING Safe (AWTRunLoopMode)
 929             }
 930         }
 931     }
 932 
 933     static JNF_MEMBER_CACHE(jm_selectPreviousGlyph, jc_CInputMethod, "selectPreviousGlyph", "()V");
 934     // We need to select the previous glyph so that it is overwritten.
 935     if (fPAHNeedsToSelect) {
 936         JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_selectPreviousGlyph);
 937         fPAHNeedsToSelect = NO;
 938     }
 939 
 940     JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_dispatchText, selectionRange.location, selectionRange.length, JNI_FALSE); // AWT_THREADING Safe (AWTRunLoopMode)
 941 
 942     // If the marked text is being cleared (zero-length string) don't handle the key event.
 943     if ([incomingString length] == 0) {
 944         fKeyEventsNeeded = NO;
 945     }
 946 }
 947 
 948 - (void) unmarkText
 949 {
 950 #ifdef IM_DEBUG
 951     fprintf(stderr, "AWTView InputMethod Selector Called : [unmarkText]\n");
 952 #endif // IM_DEBUG
 953 
 954     if (!fInputMethodLOCKABLE) {
 955         return;
 956     }
 957 
 958     // unmarkText cancels any input in progress and commits it to the text field.
 959     static JNF_MEMBER_CACHE(jm_unmarkText, jc_CInputMethod, "unmarkText", "()V");
 960     JNIEnv *env = [ThreadUtilities getJNIEnv];
 961     JNFCallVoidMethod(env, fInputMethodLOCKABLE, jm_unmarkText); // AWT_THREADING Safe (AWTRunLoopMode)
 962 
 963 }
 964 
 965 - (BOOL) hasMarkedText
 966 {
 967 #ifdef IM_DEBUG
 968     fprintf(stderr, "AWTView InputMethod Selector Called : [hasMarkedText]\n");
 969 #endif // IM_DEBUG
 970 
 971     if (!fInputMethodLOCKABLE) {
 972         return NO;
 973     }
 974 
 975     static JNF_MEMBER_CACHE(jf_fCurrentText, jc_CInputMethod, "fCurrentText", "Ljava/text/AttributedString;");
 976     static JNF_MEMBER_CACHE(jf_fCurrentTextLength, jc_CInputMethod, "fCurrentTextLength", "I");
 977     JNIEnv *env = [ThreadUtilities getJNIEnv];
 978     jobject currentText = JNFGetObjectField(env, fInputMethodLOCKABLE, jf_fCurrentText);
 979 
 980     jint currentTextLength = JNFGetIntField(env, fInputMethodLOCKABLE, jf_fCurrentTextLength);
 981 
 982     BOOL hasMarkedText = (currentText != NULL && currentTextLength > 0);
 983 
 984     if (currentText != NULL) {
 985         (*env)->DeleteLocalRef(env, currentText);
 986     }
 987 
 988     return hasMarkedText;
 989 }
 990 
 991 - (NSInteger) conversationIdentifier
 992 {
 993 #ifdef IM_DEBUG
 994     fprintf(stderr, "AWTView InputMethod Selector Called : [conversationIdentifier]\n");
 995 #endif // IM_DEBUG
 996 
 997     return (NSInteger) self;
 998 }
 999 
1000 /* Returns attributed string at the range.  This allows input mangers to
1001  query any range in backing-store (Andy's request)
1002  */
1003 - (NSAttributedString *) attributedSubstringForProposedRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1004 {
1005 #ifdef IM_DEBUG
1006     fprintf(stderr, "AWTView InputMethod Selector Called : [attributedSubstringFromRange] location=%lu, length=%lu\n", (unsigned long)theRange.location, (unsigned long)theRange.length);
1007 #endif // IM_DEBUG
1008 
1009     static JNF_MEMBER_CACHE(jm_substringFromRange, jc_CInputMethod, "attributedSubstringFromRange", "(II)Ljava/lang/String;");
1010     JNIEnv *env = [ThreadUtilities getJNIEnv];
1011     jobject theString = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_substringFromRange, theRange.location, theRange.length); // AWT_THREADING Safe (AWTRunLoopMode)
1012 
1013     id result = [[[NSAttributedString alloc] initWithString:JNFJavaToNSString(env, theString)] autorelease];
1014 #ifdef IM_DEBUG
1015     NSLog(@"attributedSubstringFromRange returning \"%@\"", result);
1016 #endif // IM_DEBUG
1017 
1018     (*env)->DeleteLocalRef(env, theString);
1019     return result;
1020 }
1021 
1022 /* This method returns the range for marked region.  If hasMarkedText == false,
1023  it'll return NSNotFound location & 0 length range.
1024  */
1025 - (NSRange) markedRange
1026 {
1027 
1028 #ifdef IM_DEBUG
1029     fprintf(stderr, "AWTView InputMethod Selector Called : [markedRange]\n");
1030 #endif // IM_DEBUG
1031 
1032     if (!fInputMethodLOCKABLE) {
1033         return NSMakeRange(NSNotFound, 0);
1034     }
1035 
1036     static JNF_MEMBER_CACHE(jm_markedRange, jc_CInputMethod, "markedRange", "()[I");
1037     JNIEnv *env = [ThreadUtilities getJNIEnv];
1038     jarray array;
1039     jboolean isCopy;
1040     jint *_array;
1041     NSRange range;
1042 
1043     array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_markedRange); // AWT_THREADING Safe (AWTRunLoopMode)
1044 
1045     if (array) {
1046         _array = (*env)->GetIntArrayElements(env, array, &isCopy);
1047         range = NSMakeRange(_array[0], _array[1]);
1048 
1049 #ifdef IM_DEBUG
1050         fprintf(stderr, "markedRange returning (%lu, %lu)\n", (unsigned long)range.location, (unsigned long)range.length);
1051 #endif // IM_DEBUG
1052         (*env)->ReleaseIntArrayElements(env, array, _array, 0);
1053         (*env)->DeleteLocalRef(env, array);
1054     } else {
1055         range = NSMakeRange(NSNotFound, 0);
1056     }
1057 
1058     return range;
1059 }
1060 
1061 /* This method returns the range for selected region.  Just like markedRange method,
1062  its location field contains char index from the text beginning.
1063  */
1064 - (NSRange) selectedRange
1065 {
1066     if (!fInputMethodLOCKABLE) {
1067         return NSMakeRange(NSNotFound, 0);
1068     }
1069 
1070     static JNF_MEMBER_CACHE(jm_selectedRange, jc_CInputMethod, "selectedRange", "()[I");
1071     JNIEnv *env = [ThreadUtilities getJNIEnv];
1072     jarray array;
1073     jboolean isCopy;
1074     jint *_array;
1075     NSRange range;
1076 
1077 #ifdef IM_DEBUG
1078     fprintf(stderr, "AWTView InputMethod Selector Called : [selectedRange]\n");
1079 #endif // IM_DEBUG
1080 
1081     array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_selectedRange); // AWT_THREADING Safe (AWTRunLoopMode)
1082     if (array) {
1083         _array = (*env)->GetIntArrayElements(env, array, &isCopy);
1084         range = NSMakeRange(_array[0], _array[1]);
1085         (*env)->ReleaseIntArrayElements(env, array, _array, 0);
1086         (*env)->DeleteLocalRef(env, array);
1087     } else {
1088         range = NSMakeRange(NSNotFound, 0);
1089     }
1090 
1091     return range;
1092 
1093 }
1094 
1095 /* This method returns the first frame of rects for theRange in screen coordindate system.
1096  */
1097 - (NSRect) firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1098 {
1099     if (!fInputMethodLOCKABLE) {
1100         return NSMakeRect(0, 0, 0, 0);
1101     }
1102 
1103     static JNF_MEMBER_CACHE(jm_firstRectForCharacterRange, jc_CInputMethod,
1104                             "firstRectForCharacterRange", "(I)[I");
1105     JNIEnv *env = [ThreadUtilities getJNIEnv];
1106     jarray array;
1107     jboolean isCopy;
1108     jint *_array;
1109     NSRect rect;
1110 
1111 #ifdef IM_DEBUG
1112     fprintf(stderr, "AWTView InputMethod Selector Called : [firstRectForCharacterRange:] location=%lu, length=%lu\n", (unsigned long)theRange.location, (unsigned long)theRange.length);
1113 #endif // IM_DEBUG
1114 
1115     array = JNFCallObjectMethod(env, fInputMethodLOCKABLE, jm_firstRectForCharacterRange, theRange.location); // AWT_THREADING Safe (AWTRunLoopMode)
1116 
1117     _array = (*env)->GetIntArrayElements(env, array, &isCopy);
1118     rect = ConvertNSScreenRect(env, NSMakeRect(_array[0], _array[1], _array[2], _array[3]));
1119     (*env)->ReleaseIntArrayElements(env, array, _array, 0);
1120     (*env)->DeleteLocalRef(env, array);
1121 
1122 #ifdef IM_DEBUG
1123     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);
1124 #endif // IM_DEBUG
1125     return rect;
1126 }
1127 
1128 /* This method returns the index for character that is nearest to thePoint.  thPoint is in
1129  screen coordinate system.
1130  */
1131 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1132 {
1133     if (!fInputMethodLOCKABLE) {
1134         return NSNotFound;
1135     }
1136 
1137     static JNF_MEMBER_CACHE(jm_characterIndexForPoint, jc_CInputMethod,
1138                             "characterIndexForPoint", "(II)I");
1139     JNIEnv *env = [ThreadUtilities getJNIEnv];
1140 
1141     NSPoint flippedLocation = ConvertNSScreenPoint(env, thePoint);
1142 
1143 #ifdef IM_DEBUG
1144     fprintf(stderr, "AWTView InputMethod Selector Called : [characterIndexForPoint:(NSPoint)thePoint] x=%f, y=%f\n", flippedLocation.x, flippedLocation.y);
1145 #endif // IM_DEBUG
1146 
1147     jint index = JNFCallIntMethod(env, fInputMethodLOCKABLE, jm_characterIndexForPoint, (jint)flippedLocation.x, (jint)flippedLocation.y); // AWT_THREADING Safe (AWTRunLoopMode)
1148 
1149 #ifdef IM_DEBUG
1150     fprintf(stderr, "characterIndexForPoint returning %ld\n", index);
1151 #endif // IM_DEBUG
1152 
1153     if (index == -1) {
1154         return NSNotFound;
1155     } else {
1156         return (NSUInteger)index;
1157     }
1158 }
1159 
1160 - (NSArray*) validAttributesForMarkedText
1161 {
1162 #ifdef IM_DEBUG
1163     fprintf(stderr, "AWTView InputMethod Selector Called : [validAttributesForMarkedText]\n");
1164 #endif // IM_DEBUG
1165 
1166     return [NSArray array];
1167 }
1168 
1169 - (void)setInputMethod:(jobject)inputMethod
1170 {
1171 #ifdef IM_DEBUG
1172     fprintf(stderr, "AWTView InputMethod Selector Called : [setInputMethod]\n");
1173 #endif // IM_DEBUG
1174 
1175     JNIEnv *env = [ThreadUtilities getJNIEnv];
1176 
1177     // Get rid of the old one
1178     if (fInputMethodLOCKABLE) {
1179         JNFDeleteGlobalRef(env, fInputMethodLOCKABLE);
1180     }
1181 
1182     // Save a global ref to the new input method.
1183     if (inputMethod != NULL)
1184         fInputMethodLOCKABLE = JNFNewGlobalRef(env, inputMethod);
1185     else
1186         fInputMethodLOCKABLE = NULL;
1187 }
1188 
1189 - (void)abandonInput
1190 {
1191 #ifdef IM_DEBUG
1192     fprintf(stderr, "AWTView InputMethod Selector Called : [abandonInput]\n");
1193 #endif // IM_DEBUG
1194 
1195     [ThreadUtilities performOnMainThread:@selector(markedTextAbandoned:) onObject:[NSInputManager currentInputManager] withObject:self waitUntilDone:YES awtMode:YES];
1196     [self unmarkText];
1197 }
1198 
1199 /********************************   END NSTextInputClient Protocol   ********************************/
1200 
1201 
1202 
1203 
1204 @end // AWTView
1205 
1206 /*
1207  * Class:     sun_lwawt_macosx_CPlatformView
1208  * Method:    nativeCreateView
1209  * Signature: (IIII)J
1210  */
1211 JNIEXPORT jlong JNICALL
1212 Java_sun_lwawt_macosx_CPlatformView_nativeCreateView
1213 (JNIEnv *env, jobject obj, jint originX, jint originY, jint width, jint height, jlong windowLayerPtr)
1214 {
1215     __block AWTView *newView = nil;
1216 
1217 JNF_COCOA_ENTER(env);
1218 AWT_ASSERT_NOT_APPKIT_THREAD;
1219 
1220     NSRect rect = NSMakeRect(originX, originY, width, height);
1221     jobject cPlatformView = (*env)->NewGlobalRef(env, obj);
1222 
1223     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
1224         AWT_ASSERT_APPKIT_THREAD;
1225 
1226         CALayer *windowLayer = jlong_to_ptr(windowLayerPtr);
1227         AWTView *view = [[AWTView alloc] initWithRect:rect
1228                                          platformView:cPlatformView
1229                                          windowLayer:windowLayer];
1230         CFRetain(view);
1231         [view release]; // GC
1232 
1233         newView = view;
1234     }];
1235 
1236 JNF_COCOA_EXIT(env);
1237 
1238     return ptr_to_jlong(newView);
1239 }