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