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 #import "AWTIconData.h"
  35 
  36 
  37 static BOOL sUsingDefaultNIB = YES;
  38 static NSString *SHARED_FRAMEWORK_BUNDLE = @"/System/Library/Frameworks/JavaVM.framework";
  39 static id <NSApplicationDelegate> applicationDelegate = nil;
  40 static QueuingApplicationDelegate * qad = nil;
  41 
  42 // Flag used to indicate to the Plugin2 event synthesis code to do a postEvent instead of sendEvent
  43 BOOL postEventDuringEventSynthesis = NO;
  44 
  45 @implementation NSApplicationAWT
  46 
  47 - (id) init
  48 {
  49     // Headless: NO
  50     // Embedded: NO
  51     // Multiple Calls: NO
  52     //  Caller: +[NSApplication sharedApplication]
  53 
  54 AWT_ASSERT_APPKIT_THREAD;
  55     fApplicationName = nil;
  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 
 152     // If it wasn't specified as an argument, see if it was specified as a system property.
 153     if (fApplicationName == nil) {
 154         fApplicationName = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.name" withEnv:env];
 155     }
 156 
 157     // If we STILL don't have it, the app name is retrieved from an environment variable (set in java.c) It should be UTF8.
 158     if (fApplicationName == nil) {
 159         char mainClassEnvVar[80];
 160         snprintf(mainClassEnvVar, sizeof(mainClassEnvVar), "JAVA_MAIN_CLASS_%d", getpid());
 161         char *mainClass = getenv(mainClassEnvVar);
 162         if (mainClass != NULL) {
 163             fApplicationName = [NSString stringWithUTF8String:mainClass];
 164             unsetenv(mainClassEnvVar);
 165 
 166             NSRange lastPeriod = [fApplicationName rangeOfString:@"." options:NSBackwardsSearch];
 167             if (lastPeriod.location != NSNotFound) {
 168                 fApplicationName = [fApplicationName substringFromIndex:lastPeriod.location + 1];
 169             }
 170         }
 171     }
 172 
 173     // The dock name is nil for double-clickable Java apps (bundled and Web Start apps)
 174     // When that happens get the display name, and if that's not available fall back to
 175     // CFBundleName.
 176     NSBundle *mainBundle = [NSBundle mainBundle];
 177     if (fApplicationName == nil) {
 178         fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
 179 
 180         if (fApplicationName == nil) {
 181             fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
 182 
 183             if (fApplicationName == nil) {
 184                 fApplicationName = (NSString *)[mainBundle objectForInfoDictionaryKey: (NSString *)kCFBundleExecutableKey];
 185 
 186                 if (fApplicationName == nil) {
 187                     // Name of last resort is the last part of the applicatoin name without the .app (consistent with CopyProcessName)
 188                     fApplicationName = [[mainBundle bundlePath] lastPathComponent];
 189 
 190                     if ([fApplicationName hasSuffix:@".app"]) {
 191                         fApplicationName = [fApplicationName stringByDeletingPathExtension];
 192                     }
 193                 }
 194             }
 195         }
 196     }
 197 
 198     // We're all done trying to determine the app name.  Hold on to it.
 199     [fApplicationName retain];
 200 
 201     NSDictionary *registrationOptions = [NSMutableDictionary dictionaryWithObject:fApplicationName forKey:@"JRSAppNameKey"];
 202 
 203     NSString *launcherType = [PropertiesUtilities javaSystemPropertyForKey:@"sun.java.launcher" withEnv:env];
 204     if ([@"SUN_STANDARD" isEqualToString:launcherType]) {
 205         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsCommandLineKey"];
 206     }
 207 
 208     NSString *uiElementProp = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.UIElement" withEnv:env];
 209     if ([@"true" isCaseInsensitiveLike:uiElementProp]) {
 210         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsUIElementKey"];
 211     }
 212 
 213     NSString *backgroundOnlyProp = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.BackgroundOnly" withEnv:env];
 214     if ([@"true" isCaseInsensitiveLike:backgroundOnlyProp]) {
 215         [registrationOptions setValue:[NSNumber numberWithBool:YES] forKey:@"JRSAppIsBackgroundOnlyKey"];
 216     }
 217 
 218     // TODO replace with direct call
 219     // [JRSAppKitAWT registerAWTAppWithOptions:registrationOptions];
 220     // and remove below transform/activate/run hack
 221 
 222     id jrsAppKitAWTClass = objc_getClass("JRSAppKitAWT");
 223     SEL registerSel = @selector(registerAWTAppWithOptions:);
 224     if ([jrsAppKitAWTClass respondsToSelector:registerSel]) {
 225         [jrsAppKitAWTClass performSelector:registerSel withObject:registrationOptions];
 226         return;
 227     }
 228 
 229 // HACK BEGIN
 230     // The following is necessary to make the java process behave like a
 231     // proper foreground application...
 232     [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^(){
 233         ProcessSerialNumber psn;
 234         GetCurrentProcess(&psn);
 235         TransformProcessType(&psn, kProcessTransformToForegroundApplication);
 236 
 237         [NSApp activateIgnoringOtherApps:YES];
 238         [NSApp run];
 239     }];
 240 // HACK END
 241 }
 242 
 243 - (void) setDockIconWithEnv:(JNIEnv *)env {
 244     NSString *theIconPath = nil;
 245 
 246     // The following environment variable is set in java.c. It is probably UTF8.
 247     char envVar[80];
 248     snprintf(envVar, sizeof(envVar), "APP_ICON_%d", getpid());
 249     char *appIcon = getenv(envVar);
 250     if (appIcon != NULL) {
 251         theIconPath = [NSString stringWithUTF8String:appIcon];
 252         unsetenv(envVar);
 253     }
 254 
 255     if (theIconPath == nil) {
 256         theIconPath = [PropertiesUtilities javaSystemPropertyForKey:@"apple.awt.application.icon" withEnv:env];
 257     }
 258 
 259     // Use the path specified to get the icon image
 260     NSImage* iconImage = nil;
 261     if (theIconPath != nil) {
 262         iconImage = [[NSImage alloc] initWithContentsOfFile:theIconPath];
 263     } 
 264 
 265     // If no icon file was specified or we failed to get the icon image
 266     // and we need to get an icon, then use the default icon
 267     if (iconImage == nil) {
 268         NSString* bundleIcon = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIconFile"];
 269         if (bundleIcon == nil) {
 270             NSData* iconData;
 271             iconData = [[NSData alloc] initWithBytesNoCopy: sAWTIconData length: sizeof(sAWTIconData) freeWhenDone: NO];
 272             iconImage = [[NSImage alloc] initWithData: iconData];
 273             [iconData release];
 274         }
 275     }
 276 
 277     // Set up the dock icon if we have an icon image.
 278     if (iconImage != nil) {
 279         [NSApp setApplicationIconImage:iconImage];
 280         [iconImage release];
 281     }
 282 }
 283 
 284 + (void) runAWTLoopWithApp:(NSApplication*)app {
 285     NSAutoreleasePool *pool = [NSAutoreleasePool new];
 286 
 287     // Make sure that when we run in AWTRunLoopMode we don't exit randomly
 288     [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:[JNFRunLoop javaRunLoopMode]];
 289 
 290     do {
 291         @try {
 292             [app run];
 293         } @catch (NSException* e) {
 294             NSLog(@"Apple AWT Startup Exception: %@", [e description]);
 295             NSLog(@"Apple AWT Restarting Native Event Thread");
 296 
 297             [app stop:app];
 298         }
 299     } while (YES);
 300 
 301     [pool drain];
 302 }
 303 
 304 - (BOOL)usingDefaultNib {
 305     return sUsingDefaultNIB;
 306 }
 307 
 308 - (void)orderFrontStandardAboutPanelWithOptions:(NSDictionary *)optionsDictionary {
 309     if (!optionsDictionary) {
 310         optionsDictionary = [NSMutableDictionary dictionaryWithCapacity:2];
 311         [optionsDictionary setValue:[[[[[NSApp mainMenu] itemAtIndex:0] submenu] itemAtIndex:0] title] forKey:@"ApplicationName"];
 312         if (![NSImage imageNamed:@"NSApplicationIcon"]) {
 313             [optionsDictionary setValue:[NSApp applicationIconImage] forKey:@"ApplicationIcon"];
 314         }
 315     }
 316 
 317     [super orderFrontStandardAboutPanelWithOptions:optionsDictionary];
 318 }
 319 
 320 #define DRAGMASK (NSMouseMovedMask | NSLeftMouseDraggedMask | NSRightMouseDownMask | NSRightMouseDraggedMask | NSLeftMouseUpMask | NSRightMouseUpMask | NSFlagsChangedMask | NSKeyDownMask)
 321 
 322 - (NSEvent *)nextEventMatchingMask:(NSUInteger)mask untilDate:(NSDate *)expiration inMode:(NSString *)mode dequeue:(BOOL)deqFlag {
 323     if (mask == DRAGMASK && [((NSString *)kCFRunLoopDefaultMode) isEqual:mode]) {
 324         postEventDuringEventSynthesis = YES;
 325     }
 326 
 327     NSEvent *event = [super nextEventMatchingMask:mask untilDate:expiration inMode:mode dequeue: deqFlag];
 328     postEventDuringEventSynthesis = NO;
 329 
 330     return event;
 331 }
 332 
 333 @end
 334 
 335 
 336 void OSXAPP_SetApplicationDelegate(id <NSApplicationDelegate> delegate)
 337 {
 338 AWT_ASSERT_APPKIT_THREAD;
 339     applicationDelegate = delegate;
 340 
 341     if (NSApp != nil) {
 342         [NSApp setDelegate: applicationDelegate];
 343 
 344         if (applicationDelegate && qad) {
 345             [qad processQueuedEventsWithTargetDelegate: applicationDelegate];
 346             qad = nil;
 347         }
 348     }
 349 }
 350