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