Simplify by avoiding confusing use of strncpy etc.
[bpt/emacs.git] / src / nsmenu.m
index e8d4a25..2cd626e 100644 (file)
@@ -1,5 +1,5 @@
 /* NeXT/Open/GNUstep and MacOSX Cocoa menu and toolbar module.
-   Copyright (C) 2007-2011 Free Software Foundation, Inc.
+   Copyright (C) 2007-2012 Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
 
@@ -28,6 +28,7 @@ Carbon version by Yamamoto Mitsuharu. */
 
 #include "lisp.h"
 #include "window.h"
+#include "character.h"
 #include "buffer.h"
 #include "keymap.h"
 #include "coding.h"
@@ -74,6 +75,10 @@ EmacsMenu *mainMenu, *svcsMenu, *dockMenu;
 static int popup_activated_flag;
 static NSModalSession popupSession;
 
+/* Nonzero means we are tracking and updating menus.  */
+static int trackingMenu;
+
+
 /* NOTE: toolbar implementation is at end,
   following complete menu implementation. */
 
@@ -182,11 +187,10 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
       int *submenu_top_level_items, *submenu_n_panes;
       struct buffer *prev = current_buffer;
       Lisp_Object buffer;
-      int specpdl_count = SPECPDL_INDEX ();
+      ptrdiff_t specpdl_count = SPECPDL_INDEX ();
       int previous_menu_items_used = f->menu_bar_items_used;
       Lisp_Object *previous_items
-       = (Lisp_Object *) alloca (previous_menu_items_used
-                                 * sizeof (Lisp_Object));
+       = alloca (previous_menu_items_used * sizeof *previous_items);
 
       /* lisp preliminaries */
       buffer = XWINDOW (FRAME_SELECTED_WINDOW (f))->buffer;
@@ -218,7 +222,7 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
 
       /* Save the frame's previous menu bar contents data */
       if (previous_menu_items_used)
-       memcpy (previous_items, XVECTOR (f->menu_bar_vector)->contents,
+       memcpy (previous_items, &AREF (f->menu_bar_vector, 0),
                previous_menu_items_used * sizeof (Lisp_Object));
 
       /* parse stage 1: extract from lisp */
@@ -226,19 +230,19 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
 
       menu_items = f->menu_bar_vector;
       menu_items_allocated = VECTORP (menu_items) ? ASIZE (menu_items) : 0;
-      submenu_start = (int *) alloca (XVECTOR (items)->size * sizeof (int *));
-      submenu_end = (int *) alloca (XVECTOR (items)->size * sizeof (int *));
-      submenu_n_panes = (int *) alloca (XVECTOR (items)->size * sizeof (int));
-      submenu_top_level_items
-       = (int *) alloca (XVECTOR (items)->size * sizeof (int *));
+      submenu_start = alloca (ASIZE (items) * sizeof *submenu_start);
+      submenu_end = alloca (ASIZE (items) * sizeof *submenu_end);
+      submenu_n_panes = alloca (ASIZE (items) * sizeof *submenu_n_panes);
+      submenu_top_level_items = alloca (ASIZE (items)
+                                       * sizeof *submenu_top_level_items);
       init_menu_items ();
-      for (i = 0; i < XVECTOR (items)->size; i += 4)
+      for (i = 0; i < ASIZE (items); i += 4)
        {
          Lisp_Object key, string, maps;
 
-         key = XVECTOR (items)->contents[i];
-         string = XVECTOR (items)->contents[i + 1];
-         maps = XVECTOR (items)->contents[i + 2];
+         key = AREF (items, i);
+         string = AREF (items, i + 1);
+         maps = AREF (items, i + 2);
          if (NILP (string))
            break;
 
@@ -311,11 +315,11 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
             /* FIXME: this ALWAYS fails on Buffers menu items.. something
                  about their strings causes them to change every time, so we
                  double-check failures */
-            if (!EQ (previous_items[i], XVECTOR (menu_items)->contents[i]))
+            if (!EQ (previous_items[i], AREF (menu_items, i)))
               if (!(STRINGP (previous_items[i])
-                    && STRINGP (XVECTOR (menu_items)->contents[i])
+                    && STRINGP (AREF (menu_items, i))
                     && !strcmp (SDATA (previous_items[i]),
-                               SDATA (XVECTOR (menu_items)->contents[i]))))
+                               SDATA (AREF (menu_items, i)))))
                   break;
           if (i == previous_menu_items_used)
             {
@@ -346,10 +350,10 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
       /* Parse stage 2a: now GC cannot happen during the lifetime of the
          widget_value, so it's safe to store data from a Lisp_String */
       wv = first_wv->contents;
-      for (i = 0; i < XVECTOR (items)->size; i += 4)
+      for (i = 0; i < ASIZE (items); i += 4)
        {
          Lisp_Object string;
-         string = XVECTOR (items)->contents[i + 1];
+         string = AREF (items, i + 1);
          if (NILP (string))
            break;
 /*           if (submenu && strcmp (submenuTitle, SDATA (string)))
@@ -400,6 +404,7 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
       items = FRAME_MENU_BAR_ITEMS (f);
       if (NILP (items))
         {
+          free_menubar_widget_value_tree (first_wv);
           [pool release];
           UNBLOCK_INPUT;
           return;
@@ -407,7 +412,7 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
 
 
       /* check if no change.. this mechanism is a bit rough, but ready */
-      n = XVECTOR (items)->size / 4;
+      n = ASIZE (items) / 4;
       if (f == last_f && n_previous_strings == n)
         {
           for (i = 0; i<n; i++)
@@ -421,12 +426,14 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
                   break;
               else
                 continue;
-              if (strncmp (previous_strings[i], SDATA (string), 10))
+              if (memcmp (previous_strings[i], SDATA (string),
+                         min (10, SBYTES (string) + 1)))
                 break;
             }
 
           if (i == n)
             {
+              free_menubar_widget_value_tree (first_wv);
               [pool release];
               UNBLOCK_INPUT;
               return;
@@ -434,14 +441,15 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
         }
 
       [menu clear];
-      for (i = 0; i < XVECTOR (items)->size; i += 4)
+      for (i = 0; i < ASIZE (items); i += 4)
        {
-         string = XVECTOR (items)->contents[i + 1];
+         string = AREF (items, i + 1);
          if (NILP (string))
            break;
 
           if (n < 100)
-            strncpy (previous_strings[i/4], SDATA (string), 10);
+           memcpy (previous_strings[i/4], min (10, SBYTES (string) + 1),
+                   SDATA (string));
 
          wv = xmalloc_widget_value ();
          wv->name = SSDATA (string);
@@ -449,7 +457,7 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
          wv->enabled = 1;
          wv->button_type = BUTTON_TYPE_NONE;
          wv->help = Qnil;
-         wv->call_data = (void *) (EMACS_INT) (-1);
+         wv->call_data = (void *) (intptr_t) (-1);
 
 #ifdef NS_IMPL_COCOA
           /* we'll update the real copy under app menu when time comes */
@@ -457,7 +465,6 @@ ns_update_menubar (struct frame *f, int deep_p, EmacsMenu *submenu)
             {
               /* but we need to make sure it will update on demand */
               [svcsMenu setFrame: f];
-              [svcsMenu setDelegate: svcsMenu];
             }
           else
 #endif
@@ -544,21 +551,44 @@ set_frame_menubar (struct frame *f, int first_time, int deep_p)
   frame = f;
 }
 
+#ifdef NS_IMPL_COCOA
+#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
+extern NSString *NSMenuDidBeginTrackingNotification;
+#endif
+#endif
+
+#ifdef NS_IMPL_COCOA
+-(void)trackingNotification:(NSNotification *)notification
+{
+  /* Update menu in menuNeedsUpdate only while tracking menus.  */
+  trackingMenu = ([notification name] == NSMenuDidBeginTrackingNotification
+                  ? 1 : 0);
+}
+#endif
 
 /* delegate method called when a submenu is being opened: run a 'deep' call
    to set_frame_menubar */
 - (void)menuNeedsUpdate: (NSMenu *)menu
 {
-  NSEvent *event;
   if (!FRAME_LIVE_P (frame))
     return;
-  event = [[FRAME_NS_VIEW (frame) window] currentEvent];
-  /* HACK: Cocoa/Carbon will request update on every keystroke
+
+  /* Cocoa/Carbon will request update on every keystroke
      via IsMenuKeyEvent -> CheckMenusForKeyEvent.  These are not needed
      since key equivalents are handled through emacs.
-     On Leopard, even keystroke events generate SystemDefined events, but
-     their subtype is 8. */
-  if ([event type] != NSSystemDefined || [event subtype] == 8
+     On Leopard, even keystroke events generate SystemDefined event.
+     Third-party applications that enhance mouse / trackpad
+     interaction, or also VNC/Remote Desktop will send events
+     of type AppDefined rather than SysDefined.
+     Menus will fail to show up if they haven't been initialized.
+     AppDefined events may lack timing data.
+
+     Thus, we rely on the didBeginTrackingNotification notification
+     as above to indicate the need for updates.
+     From 10.6 on, we could also use -[NSMenu propertiesToUpdate]: In the
+     key press case, NSMenuPropertyItemImage (e.g.) won't be set.
+  */
+  if (trackingMenu == 0
       /* Also, don't try this if from an event picked up asynchronously,
          as lots of lisp evaluation happens in ns_update_menubar. */
       || handling_signal != 0)
@@ -591,7 +621,7 @@ set_frame_menubar (struct frame *f, int first_time, int deep_p)
 
   if (!key || !strlen (key))
     return @"";
-  
+
   while (*tpos == ' ' || *tpos == '(')
     tpos++;
   if ((*tpos == 's') && (*(tpos+1) == '-'))
@@ -652,7 +682,7 @@ set_frame_menubar (struct frame *f, int first_time, int deep_p)
 -(void)clear
 {
   int n;
-  
+
   for (n = [self numberOfItems]-1; n >= 0; n--)
     {
       NSMenuItem *item = [self itemAtIndex: n];
@@ -696,9 +726,11 @@ set_frame_menubar (struct frame *f, int first_time, int deep_p)
   if ([[self window] isVisible])
     [self sizeToFit];
 #else
+#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_2
   if ([self supermenu] == nil)
     [self sizeToFit];
 #endif
+#endif
 }
 
 
@@ -762,7 +794,7 @@ ns_menu_show (FRAME_PTR f, int x, int y, int for_click, int keymaps,
   EmacsMenu *pmenu;
   NSPoint p;
   Lisp_Object window, tem, keymap;
-  int specpdl_count = SPECPDL_INDEX ();
+  ptrdiff_t specpdl_count = SPECPDL_INDEX ();
   widget_value *wv, *first_wv = 0;
 
   p.x = x; p.y = y;
@@ -783,9 +815,9 @@ ns_menu_show (FRAME_PTR f, int x, int y, int for_click, int keymaps,
   {
   widget_value *save_wv = 0, *prev_wv = 0;
   widget_value **submenu_stack
-    = (widget_value **) alloca (menu_items_used * sizeof (widget_value *));
+    = alloca (menu_items_used * sizeof *submenu_stack);
 /*   Lisp_Object *subprefix_stack
-       = (Lisp_Object *) alloca (menu_items_used * sizeof (Lisp_Object)); */
+       = alloca (menu_items_used * sizeof *subprefix_stack); */
   int submenu_depth = 0;
   int first_pane = 1;
   int i;
@@ -794,7 +826,7 @@ ns_menu_show (FRAME_PTR f, int x, int y, int for_click, int keymaps,
   i = 0;
   while (i < menu_items_used)
     {
-      if (EQ (XVECTOR (menu_items)->contents[i], Qnil))
+      if (EQ (AREF (menu_items, i), Qnil))
        {
          submenu_stack[submenu_depth++] = save_wv;
          save_wv = prev_wv;
@@ -802,21 +834,21 @@ ns_menu_show (FRAME_PTR f, int x, int y, int for_click, int keymaps,
          first_pane = 1;
          i++;
        }
-      else if (EQ (XVECTOR (menu_items)->contents[i], Qlambda))
+      else if (EQ (AREF (menu_items, i), Qlambda))
        {
          prev_wv = save_wv;
          save_wv = submenu_stack[--submenu_depth];
          first_pane = 0;
          i++;
        }
-      else if (EQ (XVECTOR (menu_items)->contents[i], Qt)
+      else if (EQ (AREF (menu_items, i), Qt)
               && submenu_depth != 0)
        i += MENU_ITEMS_PANE_LENGTH;
       /* Ignore a nil in the item list.
         It's meaningful only for dialog boxes.  */
-      else if (EQ (XVECTOR (menu_items)->contents[i], Qquote))
+      else if (EQ (AREF (menu_items, i), Qquote))
        i += 1;
-      else if (EQ (XVECTOR (menu_items)->contents[i], Qt))
+      else if (EQ (AREF (menu_items, i), Qt))
        {
          /* Create a new pane.  */
          Lisp_Object pane_name, prefix;
@@ -906,7 +938,7 @@ ns_menu_show (FRAME_PTR f, int x, int y, int for_click, int keymaps,
             make the call_data null so that it won't display a box
             when the mouse is on it.  */
          wv->call_data
-             = !NILP (def) ? (void *) &XVECTOR (menu_items)->contents[i] : 0;
+             = !NILP (def) ? (void *) &AREF (menu_items, i) : 0;
          wv->enabled = !NILP (enable);
 
          if (NILP (type))
@@ -1013,7 +1045,7 @@ update_frame_tool_bar (FRAME_PTR f)
       BOOL enabled_p = !NILP (TOOLPROP (TOOL_BAR_ITEM_ENABLED_P));
       BOOL selected_p = !NILP (TOOLPROP (TOOL_BAR_ITEM_SELECTED_P));
       int idx;
-      int img_id;
+      ptrdiff_t img_id;
       struct image *img;
       Lisp_Object image;
       Lisp_Object helpObj;
@@ -1026,7 +1058,7 @@ update_frame_tool_bar (FRAME_PTR f)
        {
           /* NS toolbar auto-computes disabled and selected images */
           idx = TOOL_BAR_IMAGE_ENABLED_SELECTED;
-         xassert (ASIZE (image) >= idx);
+         eassert (ASIZE (image) >= idx);
          image = AREF (image, idx);
        }
       else
@@ -1227,8 +1259,8 @@ update_frame_tool_bar (FRAME_PTR f)
 
   [textField setEditable: NO];
   [textField setSelectable: NO];
-  [textField setBordered: YES];
-  [textField setBezeled: YES];
+  [textField setBordered: NO];
+  [textField setBezeled: NO];
   [textField setDrawsBackground: YES];
 
   win = [[NSWindow alloc]
@@ -1236,6 +1268,7 @@ update_frame_tool_bar (FRAME_PTR f)
                       styleMask: 0
                         backing: NSBackingStoreBuffered
                           defer: YES];
+  [win setHasShadow: YES];
   [win setReleasedWhenClosed: NO];
   [win setDelegate: self];
   [[win contentView] addSubview: textField];
@@ -1256,17 +1289,15 @@ update_frame_tool_bar (FRAME_PTR f)
 - (void) setText: (char *)text
 {
   NSString *str = [NSString stringWithUTF8String: text];
-  NSRect r = [textField frame];
-  NSSize textSize = [str sizeWithAttributes: 
-     [NSDictionary dictionaryWithObject: [[textField font] screenFont]
-                                forKey: NSFontAttributeName]];
-  NSSize padSize = [[[textField font] screenFont] 
-                    boundingRectForFont].size;
-  r.size.width = textSize.width + padSize.width/2;
-  r.size.height = textSize.height + padSize.height/2;
-  [textField setFrame: r];
+  NSRect r  = [textField frame];
+  NSSize tooltipDims;
+
   [textField setStringValue: str];
+  tooltipDims = [[textField cell] cellSize];
+
+  r.size.width = tooltipDims.width;
+  r.size.height = tooltipDims.height;
+  [textField setFrame: r];
 }
 
 - (void) showAtX: (int)x Y: (int)y for: (int)seconds
@@ -1339,13 +1370,13 @@ Lisp_Object
 ns_popup_dialog (Lisp_Object position, Lisp_Object contents, Lisp_Object header)
 {
   id dialog;
-  Lisp_Object window, tem;
+  Lisp_Object window, tem, title;
   struct frame *f;
   NSPoint p;
   BOOL isQ;
 
   NSTRACE (x-popup-dialog);
-  
+
   check_ns ();
 
   isQ = NILP (header);
@@ -1388,11 +1419,19 @@ ns_popup_dialog (Lisp_Object position, Lisp_Object contents, Lisp_Object header)
   p.x = (int)f->left_pos + ((int)FRAME_COLUMN_WIDTH (f) * f->text_cols)/2;
   p.y = (int)f->top_pos + (FRAME_LINE_HEIGHT (f) * f->text_lines)/2;
 
+  title = Fcar (contents);
+  CHECK_STRING (title);
+
+  if (NILP (Fcar (Fcdr (contents))))
+    /* No buttons specified, add an "Ok" button so users can pop down
+       the dialog.  */
+    contents = Fcons (title, Fcons (Fcons (build_string ("Ok"), Qt), Qnil));
+
   BLOCK_INPUT;
   dialog = [[EmacsDialogPanel alloc] initFromContents: contents
                                            isQuestion: isQ];
   {
-    int specpdl_count = SPECPDL_INDEX ();
+    ptrdiff_t specpdl_count = SPECPDL_INDEX ();
     record_unwind_protect (pop_down_menu, make_save_value (dialog, 0));
     popup_activated_flag = 1;
     tem = [dialog runDialogAt: p];
@@ -1507,10 +1546,10 @@ ns_popup_dialog (Lisp_Object position, Lisp_Object contents, Lisp_Object header)
   [cell setCellAttribute: NSCellIsInsetButton to: 8];
   [cell setBezelStyle: NSRoundedBezelStyle];
 
-  matrix = [[NSMatrix alloc] initWithFrame: contentRect 
-                                      mode: NSHighlightModeMatrix 
-                                 prototype: cell 
-                              numberOfRows: 0 
+  matrix = [[NSMatrix alloc] initWithFrame: contentRect
+                                      mode: NSHighlightModeMatrix
+                                 prototype: cell
+                              numberOfRows: 0
                            numberOfColumns: 1];
   [[self contentView] addSubview: matrix];
   [matrix release];
@@ -1561,7 +1600,7 @@ void process_dialog (id window, Lisp_Object list)
 - addButton: (char *)str value: (Lisp_Object)val row: (int)row
 {
   id cell;
-       
+
   if (row >= rows)
     {
       [matrix addRow];
@@ -1582,7 +1621,7 @@ void process_dialog (id window, Lisp_Object list)
 - addString: (char *)str row: (int)row
 {
   id cell;
-       
+
   if (row >= rows)
     {
       [matrix addRow];
@@ -1611,7 +1650,7 @@ void process_dialog (id window, Lisp_Object list)
   EMACS_INT seltag;
 
   sellist = [sender selectedCells];
-  if ([sellist count]<1) 
+  if ([sellist count]<1)
     return self;
 
   seltag = [[sellist objectAtIndex: 0] tag];
@@ -1705,7 +1744,6 @@ void process_dialog (id window, Lisp_Object list)
 - (Lisp_Object)runDialogAt: (NSPoint)p
 {
   NSInteger ret;
-  extern EMACS_TIME timer_check (int do_it_now); /* TODO: add to a header */
 
   /* initiate a session that will be ended by pop_down_menu */
   popupSession = [NSApp beginModalSessionForWindow: self];
@@ -1715,7 +1753,7 @@ void process_dialog (id window, Lisp_Object list)
     {
       /* Run this for timers.el, indep of atimers; might not return.
          TODO: use return value to avoid calling every iteration. */
-      timer_check (1);
+      timer_check ();
       [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.1]];
     }
 
@@ -1788,6 +1826,11 @@ DEFUN ("menu-or-popup-active-p", Fmenu_or_popup_active_p, Smenu_or_popup_active_
 void
 syms_of_nsmenu (void)
 {
+#ifndef NS_IMPL_COCOA
+  /* Don't know how to keep track of this in Next/Open/Gnustep.  Always
+     update menus there.  */
+  trackingMenu = 1;
+#endif
   defsubr (&Sx_popup_dialog);
   defsubr (&Sns_reset_menu);
   defsubr (&Smenu_or_popup_active_p);
@@ -1795,4 +1838,3 @@ syms_of_nsmenu (void)
   Qdebug_on_next_call = intern_c_string ("debug-on-next-call");
   staticpro (&Qdebug_on_next_call);
 }
-