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 <dlfcn.h>
  27 #import <pthread.h>
  28 #import <objc/runtime.h>
  29 #import <Cocoa/Cocoa.h>
  30 #import <Security/AuthSession.h>
  31 #import <JavaNativeFoundation/JavaNativeFoundation.h>
  32 #import <JavaRuntimeSupport/JavaRuntimeSupport.h>
  33 
  34 #include "jni_util.h"
  35 #import "CMenuBar.h"
  36 #import "InitIDs.h"
  37 #import "LWCToolkit.h"
  38 #import "ThreadUtilities.h"
  39 #import "AWT_debug.h"
  40 #import "CSystemColors.h"
  41 #import  "NSApplicationAWT.h"
  42 #import "PropertiesUtilities.h"
  43 #import "ApplicationDelegate.h"
  44 
  45 #import "sun_lwawt_macosx_LWCToolkit.h"
  46 
  47 #import "sizecalc.h"
  48 
  49 int gNumberOfButtons;
  50 jint* gButtonDownMasks;
  51 
  52 // Indicates that the app has been started with -XstartOnFirstThread
  53 // (directly or via WebStart settings), and AWT should not run its
  54 // own event loop in this mode. Even if a loop isn't running yet,
  55 // we expect an embedder (e.g. SWT) to start it some time later.
  56 static BOOL forceEmbeddedMode = NO;
  57 
  58 // This is the data necessary to have JNI_OnLoad wait for AppKit to start.
  59 static BOOL sAppKitStarted = NO;
  60 static pthread_mutex_t sAppKitStarted_mutex = PTHREAD_MUTEX_INITIALIZER;
  61 static pthread_cond_t sAppKitStarted_cv = PTHREAD_COND_INITIALIZER;
  62 
  63 @implementation AWTToolkit
  64 
  65 static long eventCount;
  66 
  67 + (long) getEventCount{
  68     return eventCount;
  69 }
  70 
  71 + (void) eventCountPlusPlus{    
  72     eventCount++;
  73 }
  74 
  75 @end
  76 
  77 
  78 @interface AWTRunLoopObject : NSObject {
  79     BOOL _shouldEndRunLoop;
  80 }
  81 @end
  82 
  83 @implementation AWTRunLoopObject
  84 
  85 - (id) init {
  86     self = [super init];
  87     if (self != nil) {
  88         _shouldEndRunLoop = NO;
  89     }
  90     return self;
  91 }
  92 
  93 - (BOOL) shouldEndRunLoop {
  94     return _shouldEndRunLoop;
  95 }
  96 
  97 - (void) endRunLoop {
  98     _shouldEndRunLoop = YES;
  99 }
 100 
 101 @end
 102 
 103 @interface JavaRunnable : NSObject { }
 104 @property jobject runnable;
 105 - (id)initWithRunnable:(jobject)gRunnable;
 106 - (void)perform;
 107 @end
 108 
 109 @implementation JavaRunnable
 110 @synthesize runnable = _runnable;
 111 
 112 - (id)initWithRunnable:(jobject)gRunnable {
 113     if (self = [super init]) {
 114         self.runnable = gRunnable;
 115     }
 116     return self;
 117 }
 118 
 119 - (void)dealloc {
 120     JNIEnv *env = [ThreadUtilities getJNIEnv];
 121     if (self.runnable) {
 122         (*env)->DeleteGlobalRef(env, self.runnable);
 123     }
 124     [super dealloc];
 125 }
 126 
 127 - (void)perform {
 128     JNIEnv* env = [ThreadUtilities getJNIEnv];
 129     static JNF_CLASS_CACHE(sjc_Runnable, "java/lang/Runnable");
 130     static JNF_MEMBER_CACHE(jm_Runnable_run, sjc_Runnable, "run", "()V");
 131     JNFCallVoidMethod(env, self.runnable, jm_Runnable_run);
 132     [self release];
 133 }
 134 @end
 135 
 136 void setBusy(BOOL busy) {
 137     AWT_ASSERT_APPKIT_THREAD;
 138 
 139     JNIEnv *env = [ThreadUtilities getJNIEnv];
 140     static JNF_CLASS_CACHE(jc_AWTAutoShutdown, "sun/awt/AWTAutoShutdown");
 141 
 142     if (busy) {
 143         static JNF_STATIC_MEMBER_CACHE(jm_notifyBusyMethod, jc_AWTAutoShutdown, "notifyToolkitThreadBusy", "()V");
 144         JNFCallStaticVoidMethod(env, jm_notifyBusyMethod);
 145     } else {
 146         static JNF_STATIC_MEMBER_CACHE(jm_notifyFreeMethod, jc_AWTAutoShutdown, "notifyToolkitThreadFree", "()V");
 147         JNFCallStaticVoidMethod(env, jm_notifyFreeMethod);
 148     }
 149 }
 150 
 151 static void setUpAWTAppKit(BOOL installObservers)
 152 {
 153     if (installObservers) {
 154         AWT_STARTUP_LOG(@"Setting up busy observers");
 155 
 156         // Add CFRunLoopObservers to call into AWT so that AWT knows that the
 157         //  AWT thread (which is the AppKit main thread) is alive. This way AWT
 158         //  will not automatically shutdown.
 159         CFRunLoopObserverRef busyObserver = CFRunLoopObserverCreateWithHandler(
 160                                                NULL,                        // CFAllocator
 161                                                kCFRunLoopAfterWaiting,      // CFOptionFlags
 162                                                true,                        // repeats
 163                                                NSIntegerMax,                // order
 164                                                ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
 165                                                    setBusy(YES);
 166                                                });
 167         
 168         CFRunLoopObserverRef notBusyObserver = CFRunLoopObserverCreateWithHandler(
 169                                                 NULL,                        // CFAllocator
 170                                                 kCFRunLoopBeforeWaiting,     // CFOptionFlags
 171                                                 true,                        // repeats
 172                                                 NSIntegerMin,                // order
 173                                                 ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
 174                                                     setBusy(NO);
 175                                                 });
 176         
 177         CFRunLoopRef runLoop = [[NSRunLoop currentRunLoop] getCFRunLoop];
 178         CFRunLoopAddObserver(runLoop, busyObserver, kCFRunLoopDefaultMode);
 179         CFRunLoopAddObserver(runLoop, notBusyObserver, kCFRunLoopDefaultMode);
 180         
 181         CFRelease(busyObserver);
 182         CFRelease(notBusyObserver);
 183         
 184         setBusy(YES);
 185     }
 186 
 187     JNIEnv* env = [ThreadUtilities getJNIEnv];
 188     static JNF_CLASS_CACHE(jc_LWCToolkit, "sun/lwawt/macosx/LWCToolkit");
 189     static JNF_STATIC_MEMBER_CACHE(jsm_installToolkitThreadInJava, jc_LWCToolkit, "installToolkitThreadInJava", "()V");
 190     JNFCallStaticVoidMethod(env, jsm_installToolkitThreadInJava);
 191 }
 192 
 193 BOOL isSWTInWebStart(JNIEnv* env) {
 194     NSString *swtWebStart = [PropertiesUtilities javaSystemPropertyForKey:@"com.apple.javaws.usingSWT" withEnv:env];
 195     return [@"true" isCaseInsensitiveLike:swtWebStart];
 196 }
 197 
 198 static void AWT_NSUncaughtExceptionHandler(NSException *exception) {
 199     NSLog(@"Apple AWT Internal Exception: %@", [exception description]);
 200 }
 201 
 202 @interface AWTStarter : NSObject
 203 + (void)start:(BOOL)headless;
 204 + (void)starter:(BOOL)onMainThread headless:(BOOL)headless;
 205 + (void)appKitIsRunning:(id)arg;
 206 @end
 207 
 208 @implementation AWTStarter
 209 
 210 + (BOOL) isConnectedToWindowServer {
 211     SecuritySessionId session_id;
 212     SessionAttributeBits session_info;
 213     OSStatus status = SessionGetInfo(callerSecuritySession, &session_id, &session_info);
 214     if (status != noErr) return NO;
 215     if (!(session_info & sessionHasGraphicAccess)) return NO;
 216     return YES;
 217 }
 218 
 219 + (BOOL) markAppAsDaemon {
 220     id jrsAppKitAWTClass = objc_getClass("JRSAppKitAWT");
 221     SEL markAppSel = @selector(markAppIsDaemon);
 222     if (![jrsAppKitAWTClass respondsToSelector:markAppSel]) return NO;
 223     return [jrsAppKitAWTClass performSelector:markAppSel] ? YES : NO;
 224 }
 225 
 226 + (void)appKitIsRunning:(id)arg {
 227     AWT_ASSERT_APPKIT_THREAD;
 228     AWT_STARTUP_LOG(@"About to message AppKit started");
 229 
 230     // Signal that AppKit has started (or is already running).
 231     pthread_mutex_lock(&sAppKitStarted_mutex);
 232     sAppKitStarted = YES;
 233     pthread_cond_signal(&sAppKitStarted_cv);
 234     pthread_mutex_unlock(&sAppKitStarted_mutex);
 235 
 236     AWT_STARTUP_LOG(@"Finished messaging AppKit started");
 237 }
 238 
 239 + (void)start:(BOOL)headless
 240 {
 241     // onMainThread is NOT the same at SWT mode!
 242     // If the JVM was started on the first thread for SWT, but the SWT loads the AWT on a secondary thread,
 243     // onMainThread here will be false but SWT mode will be true.  If we are currently on the main thread, we don't
 244     // need to throw AWT startup over to another thread.
 245     BOOL onMainThread = [NSThread isMainThread];
 246 
 247     NSString* msg = [NSString stringWithFormat:@"+[AWTStarter start headless:%d] { onMainThread:%d }", headless, onMainThread];
 248     AWT_STARTUP_LOG(msg);
 249 
 250     if (!headless)
 251     {
 252         // Listen for the NSApp to start. This indicates that JNI_OnLoad can proceed.
 253         //  It must wait because there is a chance that another java thread will grab
 254         //  the AppKit lock before the +[NSApplication sharedApplication] returns.
 255         //  See <rdar://problem/3492666> for an example.
 256         [[NSNotificationCenter defaultCenter] addObserver:[AWTStarter class]
 257                                                  selector:@selector(appKitIsRunning:)
 258                                                      name:NSApplicationDidFinishLaunchingNotification
 259                                                    object:nil];
 260 
 261         AWT_STARTUP_LOG(@"+[AWTStarter start:::]: registered NSApplicationDidFinishLaunchingNotification");
 262     }
 263 
 264     [ThreadUtilities performOnMainThreadWaiting:NO block:^() {
 265         [AWTStarter starter:onMainThread headless:headless];
 266     }];
 267 
 268 
 269     if (!headless && !onMainThread) {
 270 
 271         AWT_STARTUP_LOG(@"about to wait on AppKit startup mutex");
 272 
 273         // Wait here for AppKit to have started (or for AWT to have been loaded into
 274         //  an already running NSApplication).
 275         pthread_mutex_lock(&sAppKitStarted_mutex);
 276         while (sAppKitStarted == NO) {
 277             pthread_cond_wait(&sAppKitStarted_cv, &sAppKitStarted_mutex);
 278         }
 279         pthread_mutex_unlock(&sAppKitStarted_mutex);
 280 
 281         // AWT gets here AFTER +[AWTStarter appKitIsRunning:] is called.
 282         AWT_STARTUP_LOG(@"got out of the AppKit startup mutex");
 283     }
 284 
 285     if (!headless) {
 286         // Don't set the delegate until the NSApplication has been created and
 287         // its finishLaunching has initialized it.
 288         //  ApplicationDelegate is the support code for com.apple.eawt.
 289         [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 290             id<NSApplicationDelegate> delegate = [ApplicationDelegate sharedDelegate];
 291             if (delegate != nil) {
 292                 OSXAPP_SetApplicationDelegate(delegate);
 293             }
 294         }];
 295     }
 296 }
 297 
 298 + (void)starter:(BOOL)wasOnMainThread headless:(BOOL)headless {
 299     NSAutoreleasePool *pool = [NSAutoreleasePool new];
 300     // Add the exception handler of last resort
 301     NSSetUncaughtExceptionHandler(AWT_NSUncaughtExceptionHandler);
 302 
 303     // Headless mode trumps either ordinary AWT or SWT-in-AWT mode.  Declare us a daemon and return.
 304     if (headless) {
 305         // Note that we don't install run loop observers in headless mode
 306         // because we don't need them (see 7174704)
 307         if (!forceEmbeddedMode) {
 308             setUpAWTAppKit(false);
 309         }
 310         [AWTStarter markAppAsDaemon];
 311         return;
 312     }
 313 
 314     if (forceEmbeddedMode) {
 315         AWT_STARTUP_LOG(@"in SWT or SWT/WebStart mode");
 316 
 317         // Init a default NSApplication instance instead of the NSApplicationAWT.
 318         // Note that [NSApp isRunning] will return YES after that, though
 319         // this behavior isn't specified anywhere. We rely on that.
 320         NSApplicationLoad();
 321     }
 322 
 323     // This will create a NSApplicationAWT for standalone AWT programs, unless there is
 324     //  already a NSApplication instance. If there is already a NSApplication instance,
 325     //  and -[NSApplication isRunning] returns YES, AWT is embedded inside another
 326     //  AppKit Application.
 327     NSApplication *app = [NSApplicationAWT sharedApplication];
 328     BOOL isEmbedded = ![NSApp isKindOfClass:[NSApplicationAWT class]];
 329     [ThreadUtilities setAWTEmbedded:isEmbedded];
 330 
 331     if (!isEmbedded) {
 332         // Install run loop observers and set the AppKit Java thread name
 333         setUpAWTAppKit(true);
 334     }
 335 
 336     // AWT gets to this point BEFORE NSApplicationDidFinishLaunchingNotification is sent.
 337     if (![app isRunning]) {
 338         AWT_STARTUP_LOG(@"+[AWTStarter startAWT]: ![app isRunning]");
 339         // This is where the AWT AppKit thread parks itself to process events.
 340         [NSApplicationAWT runAWTLoopWithApp: app];
 341     } else {
 342         // We're either embedded, or showing a splash screen
 343         if (isEmbedded) {
 344             AWT_STARTUP_LOG(@"running embedded");
 345             
 346             // We don't track if the runloop is busy, so set it free to let AWT finish when it needs
 347             setBusy(NO);
 348         } else {
 349             AWT_STARTUP_LOG(@"running after showing a splash screen");
 350         }
 351         
 352         // Signal so that JNI_OnLoad can proceed.
 353         if (!wasOnMainThread) [AWTStarter appKitIsRunning:nil];
 354         
 355         // Proceed to exit this call as there is no reason to run the NSApplication event loop.
 356     }
 357     
 358     [pool drain];
 359 }
 360 
 361 @end
 362 
 363 /*
 364  * Class:     sun_lwawt_macosx_LWCToolkit
 365  * Method:    nativeSyncQueue
 366  * Signature: (J)Z
 367  */
 368 JNIEXPORT jboolean JNICALL Java_sun_lwawt_macosx_LWCToolkit_nativeSyncQueue
 369 (JNIEnv *env, jobject self, jlong timeout)
 370 {
 371     int currentEventNum = [AWTToolkit getEventCount];
 372 
 373     NSApplication* sharedApp = [NSApplication sharedApplication];
 374     if ([sharedApp isKindOfClass:[NSApplicationAWT class]]) {
 375         NSApplicationAWT* theApp = (NSApplicationAWT*)sharedApp;
 376         [theApp postDummyEvent];
 377         [theApp waitForDummyEvent];
 378     } else {
 379         // could happen if we are embedded inside SWT application,
 380         // in this case just spin a single empty block through 
 381         // the event loop to give it a chance to process pending events
 382         [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){}];
 383     }
 384     
 385     if (([AWTToolkit getEventCount] - currentEventNum) != 0) {
 386         return JNI_TRUE;
 387     }
 388         
 389     return JNI_FALSE;
 390 }
 391 
 392 /*
 393  * Class:     sun_lwawt_macosx_LWCToolkit
 394  * Method:    flushNativeSelectors
 395  * Signature: ()J
 396  */
 397 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_flushNativeSelectors
 398 (JNIEnv *env, jclass clz)
 399 {
 400 JNF_COCOA_ENTER(env);
 401         [ThreadUtilities performOnMainThreadWaiting:YES block:^(){}];
 402 JNF_COCOA_EXIT(env);
 403 }
 404 
 405 /*
 406  * Class:     sun_lwawt_macosx_LWCToolkit
 407  * Method:    beep
 408  * Signature: ()V
 409  */
 410 JNIEXPORT void JNICALL
 411 Java_sun_lwawt_macosx_LWCToolkit_beep
 412 (JNIEnv *env, jobject self)
 413 {
 414     NSBeep(); // produces both sound and visual flash, if configured in System Preferences
 415 }
 416 














































 417 static UInt32 RGB(NSColor *c) {
 418     c = [c colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
 419     if (c == nil)
 420     {
 421         return -1; // opaque white
 422     }
 423 
 424     CGFloat r, g, b, a;
 425     [c getRed:&r green:&g blue:&b alpha:&a];
 426 
 427     UInt32 ir = (UInt32) (r*255+0.5),
 428     ig = (UInt32) (g*255+0.5),
 429     ib = (UInt32) (b*255+0.5),
 430     ia = (UInt32) (a*255+0.5);
 431 
 432     //    NSLog(@"%@ %d, %d, %d", c, ir, ig, ib);
 433 
 434     return ((ia & 0xFF) << 24) | ((ir & 0xFF) << 16) | ((ig & 0xFF) << 8) | ((ib & 0xFF) << 0);
 435 }
 436 
 437 BOOL doLoadNativeColors(JNIEnv *env, jintArray jColors, BOOL useAppleColors) {
 438     jint len = (*env)->GetArrayLength(env, jColors);
 439 
 440     UInt32 colorsArray[len];
 441     UInt32 *colors = colorsArray;
 442 
 443     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 444         NSUInteger i;
 445         for (i = 0; i < len; i++) {
 446             colors[i] = RGB([CSystemColors getColor:i useAppleColor:useAppleColors]);
 447         }
 448     }];
 449 
 450     jint *_colors = (*env)->GetPrimitiveArrayCritical(env, jColors, 0);
 451     if (_colors == NULL) {
 452         return NO;
 453     }
 454     memcpy(_colors, colors, len * sizeof(UInt32));
 455     (*env)->ReleasePrimitiveArrayCritical(env, jColors, _colors, 0);
 456     return YES;
 457 }
 458 
 459 /**
 460  * Class:     sun_lwawt_macosx_LWCToolkit
 461  * Method:    loadNativeColors
 462  * Signature: ([I[I)V
 463  */
 464 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_loadNativeColors
 465 (JNIEnv *env, jobject peer, jintArray jSystemColors, jintArray jAppleColors)
 466 {
 467 JNF_COCOA_ENTER(env);
 468     if (doLoadNativeColors(env, jSystemColors, NO)) {
 469         doLoadNativeColors(env, jAppleColors, YES);
 470     }
 471 JNF_COCOA_EXIT(env);
 472 }
 473 
 474 /*
 475  * Class:     sun_lwawt_macosx_LWCToolkit
 476  * Method:    createAWTRunLoopMediator
 477  * Signature: ()J
 478  */
 479 JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_LWCToolkit_createAWTRunLoopMediator
 480 (JNIEnv *env, jclass clz)
 481 {
 482 AWT_ASSERT_APPKIT_THREAD;
 483 
 484     jlong result;
 485 
 486 JNF_COCOA_ENTER(env);
 487     // We double retain because this object is owned by both main thread and "other" thread
 488     // We release in both doAWTRunLoop and stopAWTRunLoop
 489     result = ptr_to_jlong([[[AWTRunLoopObject alloc] init] retain]);
 490 JNF_COCOA_EXIT(env);
 491 
 492     return result;
 493 }
 494 
 495 /*
 496  * Class:     sun_lwawt_macosx_LWCToolkit
 497  * Method:    doAWTRunLoopImpl
 498  * Signature: (JZZ)V
 499  */
 500 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_doAWTRunLoopImpl
 501 (JNIEnv *env, jclass clz, jlong mediator, jboolean processEvents, jboolean inAWT)
 502 {
 503 AWT_ASSERT_APPKIT_THREAD;
 504 JNF_COCOA_ENTER(env);
 505 
 506     AWTRunLoopObject* mediatorObject = (AWTRunLoopObject*)jlong_to_ptr(mediator);
 507 
 508     if (mediatorObject == nil) return;
 509 
 510     // Don't use acceptInputForMode because that doesn't setup autorelease pools properly
 511     BOOL isRunning = true;
 512     while (![mediatorObject shouldEndRunLoop] && isRunning) {
 513         isRunning = [[NSRunLoop currentRunLoop] runMode:(inAWT ? [JNFRunLoop javaRunLoopMode] : NSDefaultRunLoopMode)
 514                                              beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.010]];
 515         if (processEvents) {
 516             //We do not spin a runloop here as date is nil, so does not matter which mode to use
 517             NSEvent *event;
 518             if ((event = [NSApp nextEventMatchingMask:NSAnyEventMask
 519                                            untilDate:nil
 520                                               inMode:NSDefaultRunLoopMode
 521                                              dequeue:YES]) != nil) {
 522                 [NSApp sendEvent:event];
 523             }
 524 
 525         }
 526     }
 527     [mediatorObject release];
 528 JNF_COCOA_EXIT(env);
 529 }
 530 
 531 /*
 532  * Class:     sun_lwawt_macosx_LWCToolkit
 533  * Method:    stopAWTRunLoop
 534  * Signature: (J)V
 535  */
 536 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_stopAWTRunLoop
 537 (JNIEnv *env, jclass clz, jlong mediator)
 538 {
 539 JNF_COCOA_ENTER(env);
 540 
 541     AWTRunLoopObject* mediatorObject = (AWTRunLoopObject*)jlong_to_ptr(mediator);
 542 
 543     [ThreadUtilities performOnMainThread:@selector(endRunLoop) on:mediatorObject withObject:nil waitUntilDone:NO];
 544 
 545     [mediatorObject release];
 546 
 547 JNF_COCOA_EXIT(env);
 548 }
 549 
 550 /*
 551  * Class:     sun_lwawt_macosx_LWCToolkit
 552  * Method:    performOnMainThreadAfterDelay
 553  * Signature: (Ljava/lang/Runnable;J)V
 554  */
 555 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_performOnMainThreadAfterDelay
 556 (JNIEnv *env, jclass clz, jobject runnable, jlong delay)
 557 {
 558 JNF_COCOA_ENTER(env);
 559     jobject gRunnable = (*env)->NewGlobalRef(env, runnable);
 560     CHECK_NULL(gRunnable);
 561     [ThreadUtilities performOnMainThreadWaiting:NO block:^() {
 562         JavaRunnable* performer = [[JavaRunnable alloc] initWithRunnable:gRunnable];
 563         [performer performSelector:@selector(perform) withObject:nil afterDelay:(delay/1000.0)];
 564     }];
 565 JNF_COCOA_EXIT(env);
 566 }
 567 
 568 
 569 /*
 570  * Class:     sun_lwawt_macosx_LWCToolkit
 571  * Method:    isCapsLockOn
 572  * Signature: ()Z
 573  */
 574 JNIEXPORT jboolean JNICALL Java_sun_lwawt_macosx_LWCToolkit_isCapsLockOn
 575 (JNIEnv *env, jobject self)
 576 {
 577     __block jboolean isOn = JNI_FALSE;
 578     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
 579         NSUInteger modifiers = [NSEvent modifierFlags];
 580         isOn = (modifiers & NSAlphaShiftKeyMask) != 0;
 581     }];
 582 
 583     return isOn;
 584 }
 585 
 586 /*
 587  * Class:     sun_lwawt_macosx_LWCToolkit
 588  * Method:    isApplicationActive
 589  * Signature: ()Z
 590  */
 591 JNIEXPORT jboolean JNICALL Java_sun_lwawt_macosx_LWCToolkit_isApplicationActive
 592 (JNIEnv *env, jclass clazz)
 593 {
 594     __block jboolean active = JNI_FALSE;
 595 
 596 JNF_COCOA_ENTER(env);
 597 
 598     [ThreadUtilities performOnMainThreadWaiting:YES block:^() {
 599         active = (jboolean)[NSRunningApplication currentApplication].active;
 600     }];
 601 
 602 JNF_COCOA_EXIT(env);
 603 
 604     return active;
 605 }
 606 
 607 
 608 /*
 609  * Class:     sun_awt_SunToolkit
 610  * Method:    closeSplashScreen
 611  * Signature: ()V
 612  */
 613 JNIEXPORT void JNICALL
 614 Java_sun_awt_SunToolkit_closeSplashScreen(JNIEnv *env, jclass cls)
 615 {
 616     void *hSplashLib = dlopen(0, RTLD_LAZY);
 617     if (!hSplashLib) return;
 618 
 619     void (*splashClose)() = dlsym(hSplashLib, "SplashClose");
 620     if (splashClose) {
 621         splashClose();
 622     }
 623     dlclose(hSplashLib);
 624 }
 625 
 626 
 627 // TODO: definitely doesn't belong here (copied from fontpath.c in the
 628 // solaris tree)...
 629 
 630 JNIEXPORT jstring JNICALL
 631 Java_sun_font_FontManager_getFontPath
 632 (JNIEnv *env, jclass obj, jboolean noType1)
 633 {
 634     return JNFNSToJavaString(env, @"/Library/Fonts");
 635 }
 636 
 637 // This isn't yet used on unix, the implementation is added since shared
 638 // code calls this method in preparation for future use.
 639 JNIEXPORT void JNICALL
 640 Java_sun_font_FontManager_populateFontFileNameMap
 641 (JNIEnv *env, jclass obj, jobject fontToFileMap, jobject fontToFamilyMap, jobject familyToFontListMap, jobject locale)
 642 {
 643 
 644 }
 645 
 646 /*
 647  * Class:     sun_lwawt_macosx_LWCToolkit
 648  * Method:    initIDs
 649  * Signature: ()V
 650  */
 651 JNIEXPORT void JNICALL
 652 Java_sun_lwawt_macosx_LWCToolkit_initIDs
 653 (JNIEnv *env, jclass klass) {
 654 
 655     JNF_COCOA_ENTER(env)
 656 
 657     gNumberOfButtons = sun_lwawt_macosx_LWCToolkit_BUTTONS;
 658 
 659     jclass inputEventClazz = (*env)->FindClass(env, "java/awt/event/InputEvent");
 660     CHECK_NULL(inputEventClazz);
 661     jmethodID getButtonDownMasksID = (*env)->GetStaticMethodID(env, inputEventClazz, "getButtonDownMasks", "()[I");
 662     CHECK_NULL(getButtonDownMasksID);
 663     jintArray obj = (jintArray)(*env)->CallStaticObjectMethod(env, inputEventClazz, getButtonDownMasksID);
 664     jint * tmp = (*env)->GetIntArrayElements(env, obj, JNI_FALSE);
 665     CHECK_NULL(tmp);
 666 
 667     gButtonDownMasks = (jint*)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(jint), gNumberOfButtons);
 668     if (gButtonDownMasks == NULL) {
 669         gNumberOfButtons = 0;
 670         (*env)->ReleaseIntArrayElements(env, obj, tmp, JNI_ABORT);
 671         JNU_ThrowOutOfMemoryError(env, NULL);
 672         return;
 673     }
 674 
 675     int i;
 676     for (i = 0; i < gNumberOfButtons; i++) {
 677         gButtonDownMasks[i] = tmp[i];
 678     }
 679 
 680     (*env)->ReleaseIntArrayElements(env, obj, tmp, 0);
 681     (*env)->DeleteLocalRef(env, obj);
 682 
 683     JNF_COCOA_EXIT(env)
 684 }
 685 
 686 /*
 687  * Class:     sun_lwawt_macosx_LWCToolkit
 688  * Method:    initAppkit
 689  * Signature: (Ljava/lang/ThreadGroup;)V
 690  */
 691 JNIEXPORT void JNICALL
 692 Java_sun_lwawt_macosx_LWCToolkit_initAppkit
 693 (JNIEnv *env, jclass klass, jobject appkitThreadGroup, jboolean headless) {
 694     JNF_COCOA_ENTER(env)
 695 
 696     [ThreadUtilities setAppkitThreadGroup:(*env)->NewGlobalRef(env, appkitThreadGroup)];
 697 
 698     // Launcher sets this env variable if -XstartOnFirstThread is specified
 699     char envVar[80];
 700     snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid());
 701     if (getenv(envVar) != NULL) {
 702         forceEmbeddedMode = YES;
 703         unsetenv(envVar);
 704     }
 705 
 706     if (isSWTInWebStart(env)) {
 707         forceEmbeddedMode = YES;
 708     }
 709 
 710     [AWTStarter start:headless ? YES : NO];
 711 
 712     JNF_COCOA_EXIT(env)
 713 }
 714 
 715 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
 716     OSXAPP_SetJavaVM(vm);
 717 
 718     // We need to let Foundation know that this is a multithreaded application, if it isn't already.
 719     if (![NSThread isMultiThreaded]) {
 720         [NSThread detachNewThreadSelector:nil toTarget:nil withObject:nil];
 721     }
 722 
 723     return JNI_VERSION_1_4;
 724 }
 725 
--- EOF ---