1 /*
   2  * Copyright (c) 2011, 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 
  35 
  36 static BOOL sUsingDefaultNIB = YES;
  37 static NSString *SHARED_FRAMEWORK_BUNDLE = @"/System/Library/Frameworks/JavaVM.framework";
  38 static id <NSApplicationDelegate> applicationDelegate = nil;
  39 static QueuingApplicationDelegate * qad = nil;
  40 
  41 // Flag used to indicate to the Plugin2 event synthesis code to do a postEvent instead of sendEvent
  42 BOOL postEventDuringEventSynthesis = NO;
  43 
  44 @implementation NSApplicationAWT
  45 
  46 - (id) init
  47 {
  48     // Headless: NO
  49     // Embedded: NO
  50     // Multiple Calls: NO
  51     //  Caller: +[NSApplication sharedApplication]
  52 
  53 AWT_ASSERT_APPKIT_THREAD;
  54     fApplicationName = nil;
  55     fUseDefaultIcon = NO;
  56 
  57     // NSApplication will call _RegisterApplication with the application's bundle, but there may not be one.
  58     // So, we need to call it ourselves to ensure the app is set up properly.
  59     [self registerWithProcessManager];
  60 
  61     return [super init];
  62 }
  63 
  64 - (void)dealloc
  65 {
  66     [fApplicationName release];
  67     fApplicationName = nil;
  68 
  69     [super dealloc];
  70 }
  71 //- (void)finalize { [super finalize]; }
  72 
  73 - (void)finishLaunching
  74 {
  75 AWT_ASSERT_APPKIT_THREAD;
  76 
  77     JNIEnv *env = [ThreadUtilities getJNIEnv];
  78 
  79     // Get default nib file location
  80     // NOTE: This should learn about the current java.version. Probably best thru
  81     //  the Makefile system's -DFRAMEWORK_VERSION define. Need to be able to pass this
  82     //  thru to PB from the Makefile system and for local builds.
  83     NSString *defaultNibFile = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.nib" withEnv:env];
  84     if (!defaultNibFile) {
  85         NSBundle *javaBundle = [NSBundle bundleWithPath:SHARED_FRAMEWORK_BUNDLE];
  86         defaultNibFile = [javaBundle pathForResource:@"DefaultApp" ofType:@"nib"];
  87     } else {
  88         sUsingDefaultNIB = NO;
  89     }
  90 
  91     [NSBundle loadNibFile:defaultNibFile externalNameTable: [NSDictionary dictionaryWithObject:self forKey:@"NSOwner"] withZone:nil];
  92 
  93     // Set user defaults to not try to parse application arguments.
  94     NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
  95     NSDictionary * noOpenDict = [NSDictionary dictionaryWithObject:@"NO" forKey:@"NSTreatUnknownArgumentsAsOpen"];
  96     [defs registerDefaults:noOpenDict];
  97 
  98     // Fix up the dock icon now that we are registered with CAS and the Dock.
  99     [self setDockIconWithEnv:env];
 100 
 101     // If we are using our nib (the default application NIB) we need to put the app name into
 102     // the application menu, which has placeholders for the name.
 103     if (sUsingDefaultNIB) {
 104         NSUInteger i, itemCount;
 105         NSMenu *theMainMenu = [NSApp mainMenu];
 106 
 107         // First submenu off the main menu is the application menu.
 108         NSMenuItem *appMenuItem = [theMainMenu itemAtIndex:0];
 109         NSMenu *appMenu = [appMenuItem submenu];
 110         itemCount = [appMenu numberOfItems];
 111 
 112         for (i = 0; i < itemCount; i++) {
 113             NSMenuItem *anItem = [appMenu itemAtIndex:i];
 114             NSString *oldTitle = [anItem title];
 115             [anItem setTitle:[NSString stringWithFormat:oldTitle, fApplicationName]];
 116         }
 117     }
 118 
 119     if (applicationDelegate) {
 120         [self setDelegate:applicationDelegate];
 121     } else {
 122         qad = [QueuingApplicationDelegate sharedDelegate];
 123         [self setDelegate:qad];
 124     }
 125 
 126     [super finishLaunching];
 127 
 128     // inform any interested parties that the AWT has arrived and is pumping
 129     [[NSNotificationCenter defaultCenter] postNotificationName:JNFRunLoopDidStartNotification object:self];
 130 }
 131 
 132 - (void) registerWithProcessManager
 133 {
 134     // Headless: NO
 135     // Embedded: NO
 136     // Multiple Calls: NO
 137     //  Caller: -[NSApplicationAWT init]
 138 
 139 AWT_ASSERT_APPKIT_THREAD;
 140     JNIEnv *env = [ThreadUtilities getJNIEnv];
 141 
 142     char envVar[80];
 143 
 144     // The following environment variable is set from the -Xdock:name param. It should be UTF8.
 145     snprintf(envVar, sizeof(envVar), "APP_NAME_%d", getpid());
 146     char *appName = getenv(envVar);
 147     if (appName != NULL) {
 148         fApplicationName = [NSString stringWithUTF8String:appName];
 149         unsetenv(envVar);
 150 
 151         // If this environment variable was set we were launched from the command line, so we
 152         // should use a generic app icon if one wasn't set.
 153         fUseDefaultIcon = YES;
 154     }
 155 
 156     // If it wasn't specified as an argument, see if it was specified as a system property.
 157     if (fApplicationName == nil) {
 158         fApplicationName = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.name" withEnv:env];
 159     }
 160 
 161     // If we STILL don't have it, the app name is retrieved from an environment variable (set in java.c) It should be UTF8.
 162     if (fApplicationName == nil) {
 163         char mainClassEnvVar[80];
 164         snprintf(mainClassEnvVar, sizeof(mainClassEnvVar), "JAVA_MAIN_CLASS_%d", getpid());
 165         char *mainClass = getenv(mainClassEnvVar);
 166         if (mainClass != NULL) {
 167             fApplicationName = [NSString stringWithUTF8String:mainClass];
 168             unsetenv(mainClassEnvVar);
 169 
 170             NSRange lastPeriod = [fApplicationName rangeOfString:@"." options:NSBackwardsSearch];
 171             if (lastPeriod.location != NSNotFound) {
 172                 fApplicationName = [fApplicationName substringFromIndex:lastPeriod.location + 1];
 173             }
 174             // If this environment variable was set we were launched from the command line, so we
 175             // should use a generic app icon if one wasn't set.
 176             fUseDefaultIcon = YES;
 177         }
 178     }
 179 
 180     // The dock name is nil for double-clickable Java apps (bundled and Web Start apps)
 181     // When that happens get the display name, and if that's not available fall back to
 182     // CFBundleName.
 183     NSBundle *mainBundle = [NSBundle mainBundle];
 184     if (fApplicationName == nil) {
 185         fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
 186 
 187         if (fApplicationName == nil) {
 188             fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
 189 
 190             if (fApplicationName == nil) {
 191                 fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey: (NSString *)kCFBundleExecutableKey];
 192 
 193                 if (fApplicationName == nil) {
 194                     // Name of last resort is the last part of the applicatoin name without the .app (consistent with CopyProcessName)
 195                     fApplicationName = [[mainBundle bundlePath] lastPathComponent];
 196 
 197                     if ([fApplicationName hasSuffix:@".app"]) {
 198                         fApplicationName = [fApplicationName stringByDeletingPathExtension];
 199                     }
 200                 }
 201             }
 202         }
 203     }
 204 
 205     // We're all done trying to determine the app name.  Hold on to it.
 206     [fApplicationName retain];
 207 
 208     NSDictionary *registrationOptions = [NSMutableDictionary dictionaryWithObject:fApplicationName forKey:@"JRSAppNameKey"];
 209 
 210     NSString *launcherType = [PropertiesUtilities javaSystemPropertyForKey:@"sun.java.launcher" withEnv:env];
 211     if ([@"SUN_STANDARD" isEqualToString:launcherType]) {
 212         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsCommandLineKey"];
 213     }
 214 
 215     NSString *uiElementProp = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.UIElement" withEnv:env];
 216     if ([@"true" isCaseInsensitiveLike:uiElementProp]) {
 217         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsUIElementKey"];
 218     }
 219 
 220     NSString *backgroundOnlyProp = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.BackgroundOnly" withEnv:env];
 221     if ([@"true" isCaseInsensitiveLike:backgroundOnlyProp]) {
 222         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsBackgroundOnlyKey"];
 223     }
 224 
 225     // TODO replace with direct call
 226     // [JRSAppKitAWT registerAWTAppWithOptions:registrationOptions];
 227     // and remove below transform/activate/run hack
 228 
 229     id jrsAppKitAWTClass = objc_getClass("JRSAppKitAWT");
 230     SEL registerSel = @selector(registerAWTAppWithOptions:);
 231     if ([jrsAppKitAWTClass respondsToSelector:registerSel]) {
 232         [jrsAppKitAWTClass performSelector:registerSel withObject:registrationOptions];
 233         return;
 234     }
 235 
 236 // HACK BEGIN
 237     // The following is necessary to make the java process behave like a
 238     // proper foreground application...
 239     [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^(){
 240         ProcessSerialNumber psn;
 241         GetCurrentProcess(&psn);
 242         TransformProcessType(&psn, kProcessTransformToForegroundApplication);
 243 
 244         [NSApp activateIgnoringOtherApps:YES];
 245         [NSApp run];
 246     }];
 247 // HACK END
 248 }
 249 
 250 - (void) setDockIconWithEnv:(JNIEnv *)env {
 251     NSString *theIconPath = nil;
 252 
 253     // The following environment variable is set in java.c. It is probably UTF8.
 254     char envVar[80];
 255     snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid());
 256     char *appIcon = getenv(envVar);
 257     if (appIcon != NULL) {
 258         theIconPath = [NSString stringWithUTF8String:appIcon];
 259         unsetenv(envVar);
 260     }
 261 
 262     if (theIconPath == nil) {
 263         theIconPath = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.icon" withEnv:env];
 264     }
 265 
 266     // If the icon file wasn't specified as an argument and we need to get an icon
 267     // we'll use the generic java app icon.
 268     NSString *defaultIconPath = [NSString stringWithFormat:@"%@%@", SHARED_FRAMEWORK_BUNDLE, @"/Resources/GenericApp.icns"];
 269     if (fUseDefaultIcon && (theIconPath == nil)) {
 270         theIconPath = defaultIconPath;
 271     }
 272 
 273     // Set up the dock icon if we have an icon name.
 274     if (theIconPath != nil) {
 275         NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile:theIconPath];
 276 
 277         // If we failed for some reason fall back to the default icon.
 278         if (iconImage == nil) {
 279             iconImage = [[NSImage alloc] initWithContentsOfFile:defaultIconPath];
 280         }
 281 
 282         [NSApp setApplicationIconImage:iconImage];
 283         [iconImage release];
 284     }
 285 }
 286 
 287 + (void) runAWTLoopWithApp:(NSApplication*)app {
 288     NSAutoreleasePool *pool = [NSAutoreleasePool new];
 289 
 290     // Make sure that when we run in AWTRunLoopMode we don't exit randomly
 291     [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:[JNFRunLoop javaRunLoopMode]];
 292 
 293     do {
 294         @try {
 295             [app run];
 296         } @catch (NSException* e) {
 297             NSLog(@"Apple AWT Startup Exception: %@", [e description]);
 298             NSLog(@"Apple AWT Restarting Native Event Thread");
 299 
 300             [app stop:app];
 301         }
 302     } while (YES);
 303 
 304     [pool drain];
 305 }
 306 
 307 - (BOOL)usingDefaultNib {
 308     return sUsingDefaultNIB;
 309 }
 310 
 311 - (void)orderFrontStandardAboutPanelWithOptions:(NSDictionary *)optionsDictionary {
 312     if (!optionsDictionary) {
 313         optionsDictionary = [NSMutableDictionary dictionaryWithCapacity:2];
 314         [optionsDictionary setValue:[[[[[NSApp mainMenu] itemAtIndex:0] submenu] itemAtIndex:0] title] forKey:@"ApplicationName"];
 315         if (![NSImage imageNamed:@"NSApplicationIcon"]) {
 316             [optionsDictionary setValue:[NSApp applicationIconImage] forKey:@"ApplicationIcon"];
 317         }
 318     }
 319 
 320     [super orderFrontStandardAboutPanelWithOptions:optionsDictionary];
 321 }
 322 
 323 #define DRAGMASK (NSMouseMovedMask | NSLeftMouseDraggedMask | NSRightMouseDownMask | NSRightMouseDraggedMask | NSLeftMouseUpMask | NSRightMouseUpMask | NSFlagsChangedMask | NSKeyDownMask)
 324 
 325 - (NSEvent *)nextEventMatchingMask:(NSUInteger)mask untilDate:(NSDate *)expiration inMode:(NSString *)mode dequeue:(BOOL)deqFlag {
 326     if (mask == DRAGMASK && [((NSString *)kCFRunLoopDefaultMode) isEqual:mode]) {
 327         postEventDuringEventSynthesis = YES;
 328     }
 329 
 330     NSEvent *event = [super nextEventMatchingMask:mask untilDate:expiration inMode:mode dequeue: deqFlag];
 331     postEventDuringEventSynthesis = NO;
 332 
 333     return event;
 334 }
 335 
 336 @end
 337 
 338 
 339 void OSXAPP_SetApplicationDelegate(id <NSApplicationDelegate> delegate)
 340 {
 341 AWT_ASSERT_APPKIT_THREAD;
 342     applicationDelegate = delegate;
 343 
 344     if (NSApp != nil) {
 345         [NSApp setDelegate: applicationDelegate];
 346 
 347         if (applicationDelegate && qad) {
 348             [qad processQueuedEventsWithTargetDelegate: applicationDelegate];
 349             qad = nil;
 350         }
 351     }
 352 }
 353