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