1 /*
   2  * Copyright (c) 2011, 2020, 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 "NSApplicationAWT.h"
  27 
  28 #import <objc/runtime.h>
  29 #import <JavaRuntimeSupport/JavaRuntimeSupport.h>
  30 
  31 #import "PropertiesUtilities.h"
  32 #import "ThreadUtilities.h"
  33 #import "QueuingApplicationDelegate.h"
  34 #import "AWTIconData.h"
  35 
  36 /*
  37  * Declare library specific JNI_Onload entry if static build
  38  */
  39 DEF_STATIC_JNI_OnLoad
  40 
  41 static BOOL sUsingDefaultNIB = YES;
  42 static NSString *SHARED_FRAMEWORK_BUNDLE = @"/System/Library/Frameworks/JavaVM.framework";
  43 static id <NSApplicationDelegate> applicationDelegate = nil;
  44 static QueuingApplicationDelegate * qad = nil;
  45 
  46 // Flag used to indicate to the Plugin2 event synthesis code to do a postEvent instead of sendEvent
  47 BOOL postEventDuringEventSynthesis = NO;
  48 
  49 /**
  50  * Subtypes of NSApplicationDefined, which are used for custom events.
  51  */
  52 enum {
  53     ExecuteBlockEvent = 777, NativeSyncQueueEvent
  54 };
  55 
  56 @implementation NSApplicationAWT
  57 
  58 - (id) init
  59 {
  60     // Headless: NO
  61     // Embedded: NO
  62     // Multiple Calls: NO
  63     //  Caller: +[NSApplication sharedApplication]
  64 
  65 AWT_ASSERT_APPKIT_THREAD;
  66     fApplicationName = nil;
  67     dummyEventTimestamp = 0.0;
  68     seenDummyEventLock = nil;
  69 
  70 
  71     // NSApplication will call _RegisterApplication with the application's bundle, but there may not be one.
  72     // So, we need to call it ourselves to ensure the app is set up properly.
  73     [self registerWithProcessManager];
  74 
  75     return [super init];
  76 }
  77 
  78 - (void)dealloc
  79 {
  80     [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil];
  81 
  82     [fApplicationName release];
  83     fApplicationName = nil;
  84 
  85     [super dealloc];
  86 }
  87 
  88 - (void)finishLaunching
  89 {
  90 AWT_ASSERT_APPKIT_THREAD;
  91 
  92     JNIEnv *env = [ThreadUtilities getJNIEnv];
  93 
  94     SEL appearanceSel = @selector(setAppearance:); // macOS 10.14+
  95     if ([self respondsToSelector:appearanceSel]) {
  96         NSString *appearanceProp = [PropertiesUtilities
  97                 javaSystemPropertyForKey:@"apple.awt.application.appearance"
  98                                  withEnv:env];
  99         if (![@"system" isEqual:appearanceProp]) {
 100             // by default use light mode, because dark mode is not supported yet
 101             NSAppearance *appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
 102             if (appearanceProp != nil) {
 103                 NSAppearance *requested = [NSAppearance appearanceNamed:appearanceProp];
 104                 if (requested != nil) {
 105                     appearance = requested;
 106                 }
 107             }
 108             // [self setAppearance:appearance];
 109             [self performSelector:appearanceSel withObject:appearance];
 110         }
 111     }
 112 
 113     // Get default nib file location
 114     // NOTE: This should learn about the current java.version. Probably best thru
 115     //  the Makefile system's -DFRAMEWORK_VERSION define. Need to be able to pass this
 116     //  thru to PB from the Makefile system and for local builds.
 117     NSString *defaultNibFile = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.nib" withEnv:env];
 118     if (!defaultNibFile) {
 119         NSBundle *javaBundle = [NSBundle bundleWithPath:SHARED_FRAMEWORK_BUNDLE];
 120         defaultNibFile = [javaBundle pathForResource:@"DefaultApp" ofType:@"nib"];
 121     } else {
 122         sUsingDefaultNIB = NO;
 123     }
 124 
 125     [NSBundle loadNibFile:defaultNibFile externalNameTable: [NSDictionary dictionaryWithObject:self forKey:@"NSOwner"] withZone:nil];
 126 
 127     // Set user defaults to not try to parse application arguments.
 128     NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
 129     NSDictionary * noOpenDict = [NSDictionary dictionaryWithObject:@"NO" forKey:@"NSTreatUnknownArgumentsAsOpen"];
 130     [defs registerDefaults:noOpenDict];
 131 
 132     // Fix up the dock icon now that we are registered with CAS and the Dock.
 133     [self setDockIconWithEnv:env];
 134 
 135     // If we are using our nib (the default application NIB) we need to put the app name into
 136     // the application menu, which has placeholders for the name.
 137     if (sUsingDefaultNIB) {
 138         NSUInteger i, itemCount;
 139         NSMenu *theMainMenu = [NSApp mainMenu];
 140 
 141         // First submenu off the main menu is the application menu.
 142         NSMenuItem *appMenuItem = [theMainMenu itemAtIndex:0];
 143         NSMenu *appMenu = [appMenuItem submenu];
 144         itemCount = [appMenu numberOfItems];
 145 
 146         for (i = 0; i < itemCount; i++) {
 147             NSMenuItem *anItem = [appMenu itemAtIndex:i];
 148             NSString *oldTitle = [anItem title];
 149             [anItem setTitle:[NSString stringWithFormat:oldTitle, fApplicationName]];
 150         }
 151     }
 152 
 153     if (applicationDelegate) {
 154         [self setDelegate:applicationDelegate];
 155     } else {
 156         qad = [QueuingApplicationDelegate sharedDelegate];
 157         [self setDelegate:qad];
 158     }
 159 
 160     [super finishLaunching];
 161 
 162     [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
 163 
 164     // inform any interested parties that the AWT has arrived and is pumping
 165     [[NSNotificationCenter defaultCenter] postNotificationName:JNFRunLoopDidStartNotification object:self];
 166 }
 167 
 168 - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
 169      shouldPresentNotification:(NSUserNotification *)notification
 170 {
 171     return YES; // We always show notifications to the user
 172 }
 173 
 174 - (void) registerWithProcessManager
 175 {
 176     // Headless: NO
 177     // Embedded: NO
 178     // Multiple Calls: NO
 179     //  Caller: -[NSApplicationAWT init]
 180 
 181 AWT_ASSERT_APPKIT_THREAD;
 182     JNIEnv *env = [ThreadUtilities getJNIEnv];
 183 
 184     char envVar[80];
 185 
 186     // The following environment variable is set from the -Xdock:name param. It should be UTF8.
 187     snprintf(envVar, sizeof(envVar), "APP_NAME_%d", getpid());
 188     char *appName = getenv(envVar);
 189     if (appName != NULL) {
 190         fApplicationName = [NSString stringWithUTF8String:appName];
 191         unsetenv(envVar);
 192     }
 193 
 194     // If it wasn't specified as an argument, see if it was specified as a system property.
 195     if (fApplicationName == nil) {
 196         fApplicationName = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.name" withEnv:env];
 197     }
 198 
 199     // If we STILL don't have it, the app name is retrieved from an environment variable (set in java.c) It should be UTF8.
 200     if (fApplicationName == nil) {
 201         char mainClassEnvVar[80];
 202         snprintf(mainClassEnvVar, sizeof(mainClassEnvVar), "JAVA_MAIN_CLASS_%d", getpid());
 203         char *mainClass = getenv(mainClassEnvVar);
 204         if (mainClass != NULL) {
 205             fApplicationName = [NSString stringWithUTF8String:mainClass];
 206             unsetenv(mainClassEnvVar);
 207 
 208             NSRange lastPeriod = [fApplicationName rangeOfString:@"." options:NSBackwardsSearch];
 209             if (lastPeriod.location != NSNotFound) {
 210                 fApplicationName = [fApplicationName substringFromIndex:lastPeriod.location + 1];
 211             }
 212         }
 213     }
 214 
 215     // The dock name is nil for double-clickable Java apps (bundled and Web Start apps)
 216     // When that happens get the display name, and if that's not available fall back to
 217     // CFBundleName.
 218     NSBundle *mainBundle = [NSBundle mainBundle];
 219     if (fApplicationName == nil) {
 220         fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
 221 
 222         if (fApplicationName == nil) {
 223             fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
 224 
 225             if (fApplicationName == nil) {
 226                 fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey: (NSString *)kCFBundleExecutableKey];
 227 
 228                 if (fApplicationName == nil) {
 229                     // Name of last resort is the last part of the applicatoin name without the .app (consistent with CopyProcessName)
 230                     fApplicationName = [[mainBundle bundlePath] lastPathComponent];
 231 
 232                     if ([fApplicationName hasSuffix:@".app"]) {
 233                         fApplicationName = [fApplicationName stringByDeletingPathExtension];
 234                     }
 235                 }
 236             }
 237         }
 238     }
 239 
 240     // We're all done trying to determine the app name.  Hold on to it.
 241     [fApplicationName retain];
 242 
 243     NSDictionary *registrationOptions = [NSMutableDictionary dictionaryWithObject:fApplicationName forKey:@"JRSAppNameKey"];
 244 
 245     NSString *launcherType = [PropertiesUtilities javaSystemPropertyForKey:@"sun.java.launcher" withEnv:env];
 246     if ([@"SUN_STANDARD" isEqualToString:launcherType]) {
 247         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsCommandLineKey"];
 248     }
 249 
 250     NSString *uiElementProp = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.UIElement" withEnv:env];
 251     if ([@"true" isCaseInsensitiveLike:uiElementProp]) {
 252         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsUIElementKey"];
 253     }
 254 
 255     NSString *backgroundOnlyProp = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.BackgroundOnly" withEnv:env];
 256     if ([@"true" isCaseInsensitiveLike:backgroundOnlyProp]) {
 257         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsBackgroundOnlyKey"];
 258     }
 259 
 260     // TODO replace with direct call
 261     // [JRSAppKitAWT registerAWTAppWithOptions:registrationOptions];
 262     // and remove below transform/activate/run hack
 263 
 264     id jrsAppKitAWTClass = objc_getClass("JRSAppKitAWT");
 265     SEL registerSel = @selector(registerAWTAppWithOptions:);
 266     if ([jrsAppKitAWTClass respondsToSelector:registerSel]) {
 267         [jrsAppKitAWTClass performSelector:registerSel withObject:registrationOptions];
 268         return;
 269     }
 270 
 271 // HACK BEGIN
 272     // The following is necessary to make the java process behave like a
 273     // proper foreground application...
 274     [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^(){
 275         ProcessSerialNumber psn;
 276         GetCurrentProcess(&psn);
 277         TransformProcessType(&psn, kProcessTransformToForegroundApplication);
 278 
 279         [NSApp activateIgnoringOtherApps:YES];
 280         [NSApp run];
 281     }];
 282 // HACK END
 283 }
 284 
 285 - (void) setDockIconWithEnv:(JNIEnv *)env {
 286     NSString *theIconPath = nil;
 287 
 288     // The following environment variable is set in java.c. It is probably UTF8.
 289     char envVar[80];
 290     snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid());
 291     char *appIcon = getenv(envVar);
 292     if (appIcon != NULL) {
 293         theIconPath = [NSString stringWithUTF8String:appIcon];
 294         unsetenv(envVar);
 295     }
 296 
 297     if (theIconPath == nil) {
 298         theIconPath = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.icon" withEnv:env];
 299     }
 300 
 301     // Use the path specified to get the icon image
 302     NSImage* iconImage = nil;
 303     if (theIconPath != nil) {
 304         iconImage = [[NSImage alloc] initWithContentsOfFile:theIconPath];
 305     }
 306 
 307     // If no icon file was specified or we failed to get the icon image
 308     // and there is no bundle's icon, then use the default icon
 309     if (iconImage == nil) {
 310         NSString* bundleIcon = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIconFile"];
 311         if (bundleIcon == nil) {
 312             NSData* iconData;
 313             iconData = [[NSData alloc] initWithBytesNoCopy: sAWTIconData length: sizeof(sAWTIconData) freeWhenDone: NO];
 314             iconImage = [[NSImage alloc] initWithData: iconData];
 315             [iconData release];
 316         }
 317     }
 318 
 319     // Set up the dock icon if we have an icon image.
 320     if (iconImage != nil) {
 321         [NSApp setApplicationIconImage:iconImage];
 322         [iconImage release];
 323     }
 324 }
 325 
 326 + (void) runAWTLoopWithApp:(NSApplication*)app {
 327     NSAutoreleasePool *pool = [NSAutoreleasePool new];
 328 
 329     // Make sure that when we run in AWTRunLoopMode we don't exit randomly
 330     [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:[JNFRunLoop javaRunLoopMode]];
 331 
 332     do {
 333         @try {
 334             [app run];
 335         } @catch (NSException* e) {
 336             NSLog(@"Apple AWT Startup Exception: %@", [e description]);
 337             NSLog(@"Apple AWT Startup Exception callstack: %@", [e callStackSymbols]);
 338             NSLog(@"Apple AWT Restarting Native Event Thread");
 339 
 340             [app stop:app];
 341         }
 342     } while (YES);
 343 
 344     [pool drain];
 345 }
 346 
 347 - (BOOL)usingDefaultNib {
 348     return sUsingDefaultNIB;
 349 }
 350 
 351 - (void)orderFrontStandardAboutPanelWithOptions:(NSDictionary *)optionsDictionary {
 352     if (!optionsDictionary) {
 353         optionsDictionary = [NSMutableDictionary dictionaryWithCapacity:2];
 354         [optionsDictionary setValue:[[[[[NSApp mainMenu] itemAtIndex:0] submenu] itemAtIndex:0] title] forKey:@"ApplicationName"];
 355         if (![NSImage imageNamed:@"NSApplicationIcon"]) {
 356             [optionsDictionary setValue:[NSApp applicationIconImage] forKey:@"ApplicationIcon"];
 357         }
 358     }
 359 
 360     [super orderFrontStandardAboutPanelWithOptions:optionsDictionary];
 361 }
 362 
 363 #define DRAGMASK (NSMouseMovedMask | NSLeftMouseDraggedMask | NSRightMouseDownMask | NSRightMouseDraggedMask | NSLeftMouseUpMask | NSRightMouseUpMask | NSFlagsChangedMask | NSKeyDownMask)
 364 
 365 #if defined(MAC_OS_X_VERSION_10_12) && __LP64__
 366    // 10.12 changed `mask` to NSEventMask (unsigned long long) for x86_64 builds.
 367 - (NSEvent *)nextEventMatchingMask:(NSEventMask)mask
 368 #else
 369 - (NSEvent *)nextEventMatchingMask:(NSUInteger)mask
 370 #endif
 371 untilDate:(NSDate *)expiration inMode:(NSString *)mode dequeue:(BOOL)deqFlag {
 372     if (mask == DRAGMASK && [((NSString *)kCFRunLoopDefaultMode) isEqual:mode]) {
 373         postEventDuringEventSynthesis = YES;
 374     }
 375 
 376     NSEvent *event = [super nextEventMatchingMask:mask untilDate:expiration inMode:mode dequeue: deqFlag];
 377     postEventDuringEventSynthesis = NO;
 378 
 379     return event;
 380 }
 381 
 382 // NSTimeInterval has microseconds precision
 383 #define TS_EQUAL(ts1, ts2) (fabs((ts1) - (ts2)) < 1e-6)
 384 
 385 - (void)sendEvent:(NSEvent *)event
 386 {
 387     if ([event type] == NSApplicationDefined
 388             && TS_EQUAL([event timestamp], dummyEventTimestamp)
 389             && (short)[event subtype] == NativeSyncQueueEvent
 390             && [event data1] == NativeSyncQueueEvent
 391             && [event data2] == NativeSyncQueueEvent) {
 392         [seenDummyEventLock lockWhenCondition:NO];
 393         [seenDummyEventLock unlockWithCondition:YES];
 394     } else if ([event type] == NSApplicationDefined
 395                && (short)[event subtype] == ExecuteBlockEvent
 396                && [event data1] != 0 && [event data2] == ExecuteBlockEvent) {
 397         void (^block)() = (void (^)()) [event data1];
 398         block();
 399         [block release];
 400     } else if ([event type] == NSKeyUp && ([event modifierFlags] & NSCommandKeyMask)) {
 401         // Cocoa won't send us key up event when releasing a key while Cmd is down,
 402         // so we have to do it ourselves.
 403         [[self keyWindow] sendEvent:event];
 404     } else {
 405         [super sendEvent:event];
 406     }
 407 }
 408 
 409 /*
 410  * Posts the block to the AppKit event queue which will be executed
 411  * on the main AppKit loop.
 412  * While running nested loops this event will be ignored.
 413  */
 414 - (void)postRunnableEvent:(void (^)())block
 415 {
 416     void (^copy)() = [block copy];
 417     NSInteger encode = (NSInteger) copy;
 418     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 419     NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined
 420                                         location: NSMakePoint(0,0)
 421                                    modifierFlags: 0
 422                                        timestamp: 0
 423                                     windowNumber: 0
 424                                          context: nil
 425                                          subtype: ExecuteBlockEvent
 426                                            data1: encode
 427                                            data2: ExecuteBlockEvent];
 428 
 429     [NSApp postEvent: event atStart: NO];
 430     [pool drain];
 431 }
 432 
 433 - (void)postDummyEvent:(bool)useCocoa {
 434     seenDummyEventLock = [[NSConditionLock alloc] initWithCondition:NO];
 435     dummyEventTimestamp = [NSProcessInfo processInfo].systemUptime;
 436 
 437     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 438     NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined
 439                                         location: NSMakePoint(0,0)
 440                                    modifierFlags: 0
 441                                        timestamp: dummyEventTimestamp
 442                                     windowNumber: 0
 443                                          context: nil
 444                                          subtype: NativeSyncQueueEvent
 445                                            data1: NativeSyncQueueEvent
 446                                            data2: NativeSyncQueueEvent];
 447     if (useCocoa) {
 448         [NSApp postEvent:event atStart:NO];
 449     } else {
 450         ProcessSerialNumber psn;
 451         GetCurrentProcess(&psn);
 452         CGEventPostToPSN(&psn, [event CGEvent]);
 453     }
 454     [pool drain];
 455 }
 456 
 457 - (void)waitForDummyEvent:(double)timeout {
 458     bool unlock = true;
 459     if (timeout >= 0) {
 460         double sec = timeout / 1000;
 461         unlock = [seenDummyEventLock lockWhenCondition:YES
 462                                beforeDate:[NSDate dateWithTimeIntervalSinceNow:sec]];
 463     } else {
 464         [seenDummyEventLock lockWhenCondition:YES];
 465     }
 466     if (unlock) {
 467         [seenDummyEventLock unlock];
 468     }
 469     [seenDummyEventLock release];
 470 
 471     seenDummyEventLock = nil;
 472 }
 473 
 474 @end
 475 
 476 
 477 void OSXAPP_SetApplicationDelegate(id <NSApplicationDelegate> newdelegate)
 478 {
 479 AWT_ASSERT_APPKIT_THREAD;
 480     applicationDelegate = newdelegate;
 481 
 482     if (NSApp != nil) {
 483         [NSApp setDelegate: applicationDelegate];
 484 
 485         if (applicationDelegate && qad) {
 486             [qad processQueuedEventsWithTargetDelegate: applicationDelegate];
 487             qad = nil;
 488         }
 489     }
 490 }