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