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