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 <JavaNativeFoundation/JavaNativeFoundation.h>
  27 
  28 #import "CMenuItem.h"
  29 #import "CMenu.h"
  30 #import "AWTEvent.h"
  31 #import "ThreadUtilities.h"
  32 
  33 #import "java_awt_Event.h"
  34 #import "java_awt_event_KeyEvent.h"
  35 #import "sun_lwawt_macosx_CMenuItem.h"
  36 
  37 #define NOT_A_CHECKBOXMENU -2
  38 
  39 
  40 @implementation CMenuItem
  41 
  42 - (id) initWithPeer:(jobject)peer asSeparator: (NSNumber *) asSeparator{
  43 AWT_ASSERT_APPKIT_THREAD;
  44     self = [super initWithPeer:peer];
  45     if (self) {
  46         if ([asSeparator boolValue]) {
  47             fMenuItem = (NSMenuItem*)[NSMenuItem separatorItem];
  48             [fMenuItem retain];
  49         } else {
  50             fMenuItem = [[NSMenuItem alloc] init];
  51             [fMenuItem setAction:@selector(handleAction:)];
  52             [fMenuItem setTarget:self];
  53         }
  54         fIsCheckbox = NO;
  55         fIsEnabled = YES;
  56     }
  57     return self;
  58 }
  59 
  60 // This is because NSApplication doesn't check the target's window when sending
  61 // actions; they only check the target itself.  We always return YES,
  62 // since we shouldn't even be installed unless our window is active.
  63 - (BOOL) worksWhenModal {
  64     return YES;
  65 }
  66 
  67 // Events
  68 - (void)handleAction:(NSMenuItem *)sender {
  69 AWT_ASSERT_APPKIT_THREAD;
  70     JNIEnv *env = [ThreadUtilities getJNIEnv];
  71 JNF_COCOA_ENTER(env);
  72 
  73     // If we are called as a result of user pressing a shorcut, do nothing,
  74     // because AWTView has already sent corresponding key event to the Java 
  75     // layer from performKeyEquivalent
  76     NSEvent *currEvent = [[NSApplication sharedApplication] currentEvent];
  77     if ([currEvent type] == NSKeyDown) {
  78         NSString *menuKey = [sender keyEquivalent];
  79         NSString *eventKey = [currEvent charactersIgnoringModifiers];
  80         if ([menuKey isEqualToString:eventKey]) {
  81             return;
  82         }
  83     }
  84 
  85     if (fIsCheckbox) {
  86         static JNF_CLASS_CACHE(jc_CCheckboxMenuItem, "sun/lwawt/macosx/CCheckboxMenuItem");
  87         static JNF_MEMBER_CACHE(jm_ckHandleAction, jc_CCheckboxMenuItem, "handleAction", "(Z)V");
  88 
  89         // Send the opposite of what's currently checked -- the action
  90         // indicates what state we're going to.
  91         NSInteger state = [sender state];
  92         jboolean newState = (state == NSOnState ? JNI_FALSE : JNI_TRUE);
  93         JNFCallVoidMethod(env, fPeer, jm_ckHandleAction, newState);
  94     } else {
  95         static JNF_CLASS_CACHE(jc_CMenuItem, "sun/lwawt/macosx/CMenuItem");
  96         static JNF_MEMBER_CACHE(jm_handleAction, jc_CMenuItem, "handleAction", "(JI)V"); // AWT_THREADING Safe (event)
  97 
  98         NSUInteger modifiers = [currEvent modifierFlags];
  99         jint javaModifiers = NsKeyModifiersToJavaModifiers(modifiers, NO);
 100 
 101         JNFCallVoidMethod(env, fPeer, jm_handleAction, UTC(currEvent), javaModifiers); // AWT_THREADING Safe (event)
 102     }
 103 JNF_COCOA_EXIT(env);
 104 }
 105 
 106 - (void) setJavaLabel:(NSString *)theLabel shortcut:(NSString *)theKeyEquivalent modifierMask:(jint)modifiers {
 107 
 108     NSUInteger modifierMask = 0;
 109 
 110     if (![theKeyEquivalent isEqualToString:@""]) {
 111         // Force the key equivalent to lower case if not using the shift key.
 112         // Otherwise AppKit will draw a Shift glyph in the menu.
 113         if ((modifiers & java_awt_event_KeyEvent_SHIFT_MASK) == 0) {
 114             theKeyEquivalent = [theKeyEquivalent lowercaseString];
 115         }
 116 
 117         // Hack for the question mark -- SHIFT and / means use the question mark.
 118         if ((modifiers & java_awt_event_KeyEvent_SHIFT_MASK) != 0 &&
 119             [theKeyEquivalent isEqualToString:@"/"])
 120         {
 121             theKeyEquivalent = @"?";
 122             modifiers &= ~java_awt_event_KeyEvent_SHIFT_MASK;
 123         }
 124 
 125         modifierMask = JavaModifiersToNsKeyModifiers(modifiers, NO);
 126     }
 127 
 128     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 129         [fMenuItem setKeyEquivalent:theKeyEquivalent];
 130         [fMenuItem setKeyEquivalentModifierMask:modifierMask];
 131         [fMenuItem setTitle:theLabel];
 132     }];
 133 }
 134 
 135 - (void) setJavaImage:(NSImage *)theImage {
 136 
 137     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 138         [fMenuItem setImage:theImage];
 139     }];
 140 }
 141 
 142 - (void) setJavaToolTipText:(NSString *)theText {
 143 
 144     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 145         [fMenuItem setToolTip:theText];
 146     }];
 147 }
 148 
 149 
 150 - (void)setJavaEnabled:(BOOL) enabled {
 151 
 152     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 153         @synchronized(self) {
 154             fIsEnabled = enabled;
 155 
 156             // Warning:  This won't work if the parent menu is disabled.
 157             // See [CMenu syncFromJava]. We still need to call it here so
 158             // the NSMenuItem itself gets properly updated.
 159             [fMenuItem setEnabled:fIsEnabled];
 160         }
 161     }];
 162 }
 163 
 164 - (BOOL)isEnabled {
 165 
 166     BOOL enabled = NO;
 167     @synchronized(self) {
 168         enabled = fIsEnabled;
 169     }
 170     return enabled;
 171 }
 172 
 173 
 174 - (void)setJavaState:(BOOL)newState {
 175 
 176     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 177         [fMenuItem setState:(newState ? NSOnState : NSOffState)];
 178     }];
 179 }
 180 
 181 - (void)cleanup {
 182     [fMenuItem setAction:NULL];
 183     [fMenuItem setTarget:nil];
 184 }
 185 
 186 - (void)dealloc {
 187     [fMenuItem release];
 188     fMenuItem = nil;
 189 
 190     [super dealloc];
 191 }
 192 
 193 - (void)addNSMenuItemToMenu:(NSMenu *)inMenu {
 194     [inMenu addItem:fMenuItem];
 195 }
 196 
 197 - (NSMenuItem *)menuItem {
 198     return [[fMenuItem retain] autorelease];
 199 }
 200 
 201 - (void)setIsCheckbox {
 202     fIsCheckbox = YES;
 203 }
 204 
 205 - (void) _createMenuItem_OnAppKitThread: (NSMutableArray *)argValue {
 206     jobject cPeerObjGlobal = (jobject)[[argValue objectAtIndex: 0] pointerValue];
 207     NSNumber * asSeparator = (NSNumber *)[argValue objectAtIndex: 1];
 208     CMenuItem *aCMenuItem = [self initWithPeer: cPeerObjGlobal asSeparator: asSeparator];
 209     [argValue removeAllObjects];
 210     [argValue addObject: aCMenuItem];
 211 }
 212 
 213 - (NSString *)description {
 214     return [NSString stringWithFormat:@"CMenuItem[ %@ ]", fMenuItem];
 215 }
 216 
 217 @end
 218 
 219 /** Convert a Java keycode for SetMenuItemCmd */
 220 static unichar AWTKeyToMacShortcut(jint awtKey, BOOL doShift) {
 221     unichar macKey = 0;
 222 
 223     if ((awtKey >= java_awt_event_KeyEvent_VK_0 && awtKey <= java_awt_event_KeyEvent_VK_9) ||
 224         (awtKey >= java_awt_event_KeyEvent_VK_A && awtKey <= java_awt_event_KeyEvent_VK_Z))
 225     {
 226         // These ranges are the same in ASCII
 227         macKey = awtKey;
 228     } else if (awtKey >= java_awt_event_KeyEvent_VK_F1 && awtKey <= java_awt_event_KeyEvent_VK_F12) {
 229         // Support for F1 - F12 has been around since Java 1.0 and fall into a lower range.
 230         macKey = awtKey - java_awt_event_KeyEvent_VK_F1 + NSF1FunctionKey;
 231     } else if (awtKey >= java_awt_event_KeyEvent_VK_F13 && awtKey <= java_awt_event_KeyEvent_VK_F24) {
 232         // Support for F13-F24 came in Java 1.2 and are at a different range.
 233         macKey = awtKey - java_awt_event_KeyEvent_VK_F13 + NSF13FunctionKey;
 234     } else {
 235         // Special characters
 236         switch (awtKey) {
 237         case java_awt_event_KeyEvent_VK_BACK_QUOTE      : macKey = '`'; break;
 238         case java_awt_event_KeyEvent_VK_QUOTE           : macKey = '\''; break;
 239 
 240         case java_awt_event_KeyEvent_VK_ESCAPE          : macKey = 0x1B; break;
 241 //        case java_awt_event_KeyEvent_VK_SPACE           : macKey = kMenuSpaceGlyph; break;
 242         case java_awt_event_KeyEvent_VK_PAGE_UP         : macKey = NSPageUpFunctionKey; break;
 243         case java_awt_event_KeyEvent_VK_PAGE_DOWN       : macKey = NSPageDownFunctionKey; break;
 244         case java_awt_event_KeyEvent_VK_END             : macKey = NSEndFunctionKey; break;
 245         case java_awt_event_KeyEvent_VK_HOME            : macKey = NSHomeFunctionKey; break;
 246 
 247         case java_awt_event_KeyEvent_VK_LEFT            : macKey = NSLeftArrowFunctionKey; break;
 248         case java_awt_event_KeyEvent_VK_UP              : macKey = NSUpArrowFunctionKey; break;
 249         case java_awt_event_KeyEvent_VK_RIGHT           : macKey = NSRightArrowFunctionKey; break;
 250         case java_awt_event_KeyEvent_VK_DOWN            : macKey = NSDownArrowFunctionKey; break;
 251 
 252         case java_awt_event_KeyEvent_VK_COMMA           : macKey = ','; break;
 253 
 254         // Mac OS doesn't distinguish between the two '-' keys...
 255         case java_awt_event_KeyEvent_VK_MINUS           :
 256         case java_awt_event_KeyEvent_VK_SUBTRACT        : macKey = '-'; break;
 257 
 258         // or the two '.' keys...
 259         case java_awt_event_KeyEvent_VK_DECIMAL         :
 260         case java_awt_event_KeyEvent_VK_PERIOD          : macKey = '.'; break;
 261 
 262         // or the two '/' keys.
 263         case java_awt_event_KeyEvent_VK_DIVIDE          :
 264         case java_awt_event_KeyEvent_VK_SLASH           : macKey = '/'; break;
 265 
 266         case java_awt_event_KeyEvent_VK_SEMICOLON       : macKey = ';'; break;
 267         case java_awt_event_KeyEvent_VK_EQUALS          : macKey = '='; break;
 268 
 269         case java_awt_event_KeyEvent_VK_OPEN_BRACKET    : macKey = '['; break;
 270         case java_awt_event_KeyEvent_VK_BACK_SLASH      : macKey = '\\'; break;
 271         case java_awt_event_KeyEvent_VK_CLOSE_BRACKET   : macKey = ']'; break;
 272 
 273         case java_awt_event_KeyEvent_VK_MULTIPLY        : macKey = '*'; break;
 274         case java_awt_event_KeyEvent_VK_ADD             : macKey = '+'; break;
 275 
 276         case java_awt_event_KeyEvent_VK_HELP            : macKey = NSHelpFunctionKey; break;
 277         case java_awt_event_KeyEvent_VK_TAB             : macKey = NSTabCharacter; break;
 278         case java_awt_event_KeyEvent_VK_ENTER           : macKey = NSCarriageReturnCharacter; break;
 279         case java_awt_event_KeyEvent_VK_BACK_SPACE      : macKey = NSBackspaceCharacter; break;
 280         case java_awt_event_KeyEvent_VK_DELETE          : macKey = NSDeleteCharacter; break;
 281         case java_awt_event_KeyEvent_VK_CLEAR           : macKey = NSClearDisplayFunctionKey; break;
 282         case java_awt_event_KeyEvent_VK_AMPERSAND       : macKey = '&'; break;
 283         case java_awt_event_KeyEvent_VK_ASTERISK        : macKey = '*'; break;
 284         case java_awt_event_KeyEvent_VK_QUOTEDBL        : macKey = '\"'; break;
 285         case java_awt_event_KeyEvent_VK_LESS            : macKey = '<'; break;
 286         case java_awt_event_KeyEvent_VK_GREATER         : macKey = '>'; break;
 287         case java_awt_event_KeyEvent_VK_BRACELEFT       : macKey = '{'; break;
 288         case java_awt_event_KeyEvent_VK_BRACERIGHT      : macKey = '}'; break;
 289         case java_awt_event_KeyEvent_VK_AT              : macKey = '@'; break;
 290         case java_awt_event_KeyEvent_VK_COLON           : macKey = ':'; break;
 291         case java_awt_event_KeyEvent_VK_CIRCUMFLEX      : macKey = '^'; break;
 292         case java_awt_event_KeyEvent_VK_DOLLAR          : macKey = '$'; break;
 293         case java_awt_event_KeyEvent_VK_EXCLAMATION_MARK : macKey = '!'; break;
 294         case java_awt_event_KeyEvent_VK_LEFT_PARENTHESIS : macKey = '('; break;
 295         case java_awt_event_KeyEvent_VK_NUMBER_SIGN     : macKey = '#'; break;
 296         case java_awt_event_KeyEvent_VK_PLUS            : macKey = '+'; break;
 297         case java_awt_event_KeyEvent_VK_RIGHT_PARENTHESIS: macKey = ')'; break;
 298         case java_awt_event_KeyEvent_VK_UNDERSCORE      : macKey = '_'; break;
 299         }
 300     }
 301     return macKey;
 302 }
 303 
 304 /*
 305  * Class:     sun_lwawt_macosx_CMenuItem
 306  * Method:    nativeSetLabel
 307  * Signature: (JLjava/lang/String;CII)V
 308  */
 309 JNIEXPORT void JNICALL
 310 Java_sun_lwawt_macosx_CMenuItem_nativeSetLabel
 311 (JNIEnv *env, jobject peer,
 312      jlong menuItemObj, jstring label,
 313      jchar shortcutKey, jint shortcutKeyCode, jint mods)
 314 {
 315 JNF_COCOA_ENTER(env);
 316     NSString *theLabel = JNFJavaToNSString(env, label);
 317     NSString *theKeyEquivalent = nil;
 318     unichar macKey = shortcutKey;
 319 
 320     if (macKey == 0) {
 321         macKey = AWTKeyToMacShortcut(shortcutKeyCode, (mods & java_awt_event_KeyEvent_SHIFT_MASK) != 0);
 322     }
 323 
 324     if (macKey != 0) {
 325         unichar equivalent[1] = {macKey};
 326         theKeyEquivalent = [NSString stringWithCharacters:equivalent length:1];
 327     } else {
 328         theKeyEquivalent = @"";
 329     }
 330 
 331     [((CMenuItem *)jlong_to_ptr(menuItemObj)) setJavaLabel:theLabel shortcut:theKeyEquivalent modifierMask:mods];
 332 JNF_COCOA_EXIT(env);
 333 }
 334 
 335 /*
 336  * Class:     sun_lwawt_macosx_CMenuItem
 337  * Method:    nativeSetTooltip
 338  * Signature: (JLjava/lang/String;)V
 339  */
 340 JNIEXPORT void JNICALL
 341 Java_sun_lwawt_macosx_CMenuItem_nativeSetTooltip
 342 (JNIEnv *env, jobject peer, jlong menuItemObj, jstring tooltip)
 343 {
 344 JNF_COCOA_ENTER(env);
 345     NSString *theTooltip = JNFJavaToNSString(env, tooltip);
 346     [((CMenuItem *)jlong_to_ptr(menuItemObj)) setJavaToolTipText:theTooltip];
 347 JNF_COCOA_EXIT(env);
 348 }
 349 
 350 /*
 351  * Class:     sun_lwawt_macosx_CMenuItem
 352  * Method:    nativeSetImage
 353  * Signature: (JJ)V
 354  */
 355 JNIEXPORT void JNICALL
 356 Java_sun_lwawt_macosx_CMenuItem_nativeSetImage
 357 (JNIEnv *env, jobject peer, jlong menuItemObj, jlong image)
 358 {
 359 JNF_COCOA_ENTER(env);
 360     [((CMenuItem *)jlong_to_ptr(menuItemObj)) setJavaImage:(NSImage*)jlong_to_ptr(image)];
 361 JNF_COCOA_EXIT(env);
 362 }
 363 
 364 /*
 365  * Class:     sun_lwawt_macosx_CMenuItem
 366  * Method:    nativeCreate
 367  * Signature: (JZ)J
 368  */
 369 JNIEXPORT jlong JNICALL
 370 Java_sun_lwawt_macosx_CMenuItem_nativeCreate
 371     (JNIEnv *env, jobject peer, jlong parentCMenuObj, jboolean isSeparator)
 372 {
 373 
 374     CMenuItem *aCMenuItem = nil;
 375     CMenu *parentCMenu = (CMenu *)jlong_to_ptr(parentCMenuObj);
 376 JNF_COCOA_ENTER(env);
 377 
 378     jobject cPeerObjGlobal = (*env)->NewGlobalRef(env, peer);
 379 
 380     NSMutableArray *args = nil;
 381 
 382     // Create a new item....
 383     if (isSeparator == JNI_TRUE) {
 384         args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:YES],  nil];
 385     } else {
 386         args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:NO],  nil];
 387     }
 388 
 389     [ThreadUtilities performOnMainThread:@selector(_createMenuItem_OnAppKitThread:) onObject:[CMenuItem alloc] withObject:args waitUntilDone:YES awtMode:YES];
 390 
 391     aCMenuItem = (CMenuItem *)[args objectAtIndex: 0];
 392 
 393     if (aCMenuItem == nil) {
 394         return 0L;
 395     }
 396 
 397     // and add it to the parent item.
 398     [parentCMenu addJavaMenuItem: aCMenuItem];
 399 
 400     // setLabel will be called after creation completes.
 401 
 402     if (aCMenuItem) {
 403         CFRetain(aCMenuItem); // GC
 404         [aCMenuItem release];
 405     }
 406 
 407 JNF_COCOA_EXIT(env);
 408     return ptr_to_jlong(aCMenuItem);
 409 }
 410 
 411 /*
 412  * Class:     sun_lwawt_macosx_CMenuItem
 413  * Method:    nativeSetEnabled
 414  * Signature: (JZ)V
 415  */
 416 JNIEXPORT void JNICALL
 417 Java_sun_lwawt_macosx_CMenuItem_nativeSetEnabled
 418 (JNIEnv *env, jobject peer, jlong menuItemObj, jboolean enable)
 419 {
 420 JNF_COCOA_ENTER(env);
 421     CMenuItem *item = (CMenuItem *)jlong_to_ptr(menuItemObj);
 422     [item setJavaEnabled: (enable == JNI_TRUE)];
 423 JNF_COCOA_EXIT(env);
 424 }
 425 
 426 /*
 427  * Class:     sun_lwawt_macosx_CCheckboxMenuItem
 428  * Method:    nativeSetState
 429  * Signature: (IZ)V
 430  */
 431 JNIEXPORT void JNICALL
 432 Java_sun_lwawt_macosx_CCheckboxMenuItem_nativeSetState
 433 (JNIEnv *env, jobject peer, jlong menuItemObj, jboolean state)
 434 {
 435 JNF_COCOA_ENTER(env);
 436     CMenuItem *item = (CMenuItem *)jlong_to_ptr(menuItemObj);
 437     [item setJavaState: (state == JNI_TRUE)];
 438 JNF_COCOA_EXIT(env);
 439 }
 440 
 441 /*
 442  * Class:     sun_lwawt_macosx_CCheckboxMenuItem
 443  * Method:    nativeSetState
 444  * Signature: (IZ)V
 445  */
 446 JNIEXPORT void JNICALL
 447 Java_sun_lwawt_macosx_CCheckboxMenuItem_nativeSetIsCheckbox
 448 (JNIEnv *env, jobject peer, jlong menuItemObj)
 449 {
 450 JNF_COCOA_ENTER(env);
 451     CMenuItem *item = (CMenuItem *)jlong_to_ptr(menuItemObj);
 452     [item setIsCheckbox];
 453 JNF_COCOA_EXIT(env);
 454 }