]> code.delx.au - gnu-emacs/blobdiff - src/nsterm.m
nsterm.m (ns_draw_window_cursor): Respect cursor_type for nonactive windows. (ns_ini...
[gnu-emacs] / src / nsterm.m
index b9902fbe774dce0d8a36ef290efc5d615590f7a4..0089dc3a415129ccefbcf79b52e6fe0700f16f72 100644 (file)
@@ -32,6 +32,7 @@ GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
 #include <math.h>
 #include <sys/types.h>
 #include <time.h>
+#include <signal.h>
 #include <unistd.h>
 
 #include "lisp.h"
@@ -109,6 +110,15 @@ static unsigned convert_ns_to_X_keysym[] =
   NSF13FunctionKey,             0xCA,
   NSF14FunctionKey,             0xCB,
   NSF15FunctionKey,             0xCC,
+  NSF16FunctionKey,             0xCD,
+  NSF17FunctionKey,             0xCE,
+  NSF18FunctionKey,             0xCF,
+  NSF19FunctionKey,             0xD0,
+  NSF20FunctionKey,             0xD1,
+  NSF21FunctionKey,             0xD2,
+  NSF22FunctionKey,             0xD3,
+  NSF23FunctionKey,             0xD4,
+  NSF24FunctionKey,             0xD5,
 
   NSBackspaceCharacter,         0x08,  /* 8: Not on some KBs. */
   NSDeleteCharacter,            0xFF,  /* 127: Big 'delete' key upper right. */
@@ -135,15 +145,9 @@ Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
 
 
-EmacsPrefsController *prefsController;
-
-/* Preferences equivalent to those set by X resources under X are managed
-   through the OpenStep defaults system.  These pertain to behavior of the
-   graphical interface components.  The one difference from X is that the
-   values below are SET when the user chooses save-options. This makes
-   things easier for users, but sometimes violates expectations when some
-   user-set options appear when running under -q/Q.  Therefore we depart
-   from X behavior and refuse to read defaults when started under these
+/* Some preferences equivalent to those set by X resources under X are
+   managed through the OpenStep defaults system. We depart from X
+   behavior and refuse to read defaults when started under these
    options. */
 
 /* Set in emacs.c. */
@@ -165,11 +169,6 @@ Lisp_Object ns_control_modifier;
    the Function modifer (laptops).  May be any of the modifier lisp symbols. */
 Lisp_Object ns_function_modifier;
 
-/* A floating point value specifying vertical stretch (positive) or shrink
-  (negative) of text line spacing.  Zero means default spacing.
-  YES indicates 0.5, NO indicates 0.0. */
-Lisp_Object ns_expand_space;
-
 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
 Lisp_Object ns_antialias_text;
 
@@ -183,7 +182,6 @@ float ns_antialias_threshold;
 Lisp_Object ns_use_qd_smoothing;
 
 /* Used to pick up AppleHighlightColor on OS X */
-Lisp_Object ns_use_system_highlight_color;
 NSString *ns_selection_color;
 
 /* Confirm on exit. */
@@ -233,7 +231,6 @@ static fd_set select_readfds, t_readfds;
 static struct timeval select_timeout;
 static int select_nfds;
 static NSAutoreleasePool *outerpool;
-static BOOL ns_shutdown_properly = NO;
 static struct input_event *emacs_event = NULL;
 static struct input_event *q_event_ptr = NULL;
 static int n_emacs_events_pending = 0;
@@ -417,7 +414,9 @@ ns_init_paths ()
       resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
       if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
         if (isDir)
-          setenv ("INFOPATH", [resourcePath UTF8String], 1);
+          setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
+                                             UTF8String], 1);
+      /* Note, extra colon needed to cause merge w/later user additions. */
     }
 }
 
@@ -844,11 +843,9 @@ ns_ring_bell ()
           r.origin.y += (r.size.height - dim.y) / 2;
           r.size.width = dim.x;
           r.size.height = dim.y;
-          /* XXX: cacheImageInRect under GNUstep does not account for
-             offset in x_set_window_size, so overestimate (4 fine on Cocoa) */
-          surr = NSInsetRect (r, -10, -10);
+          surr = NSInsetRect (r, -2, -2);
           ns_focus (frame, &surr, 1);
-          [[view window] cacheImageInRect: surr];
+          [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
           [ns_lookup_indexed_color (NS_FACE_FOREGROUND
                                       (FRAME_DEFAULT_FACE (frame)), frame) set];
           NSRectFill (r);
@@ -900,7 +897,11 @@ ns_raise_frame (struct frame *f)
   NSView *view = FRAME_NS_VIEW (f);
   check_ns ();
   BLOCK_INPUT;
-  [[view window] makeKeyAndOrderFront: NSApp];
+  FRAME_SAMPLE_VISIBILITY (f);
+  if (FRAME_VISIBLE_P (f))
+    {
+      [[view window] makeKeyAndOrderFront: NSApp];
+    }
   UNBLOCK_INPUT;
 }
 
@@ -987,7 +988,10 @@ x_make_frame_visible (struct frame *f)
      called this (frame.c:Fraise_frame ()) also called raise_lower;
      if this ends up the case again, comment this out again. */
   if (!FRAME_VISIBLE_P (f))
-    ns_raise_frame (f);
+    {
+      f->async_visible = 1;
+      ns_raise_frame (f);
+    }
 }
 
 
@@ -1001,6 +1005,8 @@ x_make_frame_invisible (struct frame *f)
   NSTRACE (x_make_frame_invisible);
   check_ns ();
   [[view window] orderOut: NSApp];
+  f->async_visible = 0;
+  f->async_iconified = 0;
 }
 
 
@@ -1152,21 +1158,21 @@ x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
   pixelwidth =  FRAME_TEXT_COLS_TO_PIXEL_WIDTH   (f, cols);
   pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
 
-  /* If we have a change in toolbar display, calculate height */
+  /* If we have a toolbar, take its height into account. */
   if (tb)
-    /* XXX: GNUstep has not yet implemented the first method below, added
-           in Panther, however the second is incorrect under Cocoa. */
-#ifdef NS_IMPL_GNUSTEP
-    FRAME_NS_TOOLBAR_HEIGHT (f)
-      = NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
-                           styleMask: [window styleMask]])
-        - FRAME_NS_TITLEBAR_HEIGHT (f);
+    FRAME_NS_TOOLBAR_HEIGHT (f) =
+      /* XXX: GNUstep has not yet implemented the first method below, added
+        in Panther, however the second is incorrect under Cocoa. */
+#ifdef NS_IMPL_COCOA
+      NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
+      /* NOTE: previously this would generate wrong result if toolbar not
+               yet displayed and fixing toolbar_height=32 helped, but
+               now (200903) seems no longer needed */
 #else
-    FRAME_NS_TOOLBAR_HEIGHT (f) = 32;
-      /* actually get wrong result here if toolbar not yet displayed
-         NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
-         - FRAME_NS_TITLEBAR_HEIGHT (f); */
+      NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
+                                       styleMask: [window styleMask]])
 #endif
+            - FRAME_NS_TITLEBAR_HEIGHT (f);
   else
     FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
 
@@ -1754,9 +1760,11 @@ note_mouse_movement (struct frame *frame, float x, float y)
       y < last_mouse_glyph.origin.y ||
       y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
     {
+      ns_update_begin(frame);
       frame->mouse_moved = 1;
       note_mouse_highlight (frame, x, y);
       remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
+      ns_update_end(frame);
       return 1;
     }
 
@@ -1858,11 +1866,13 @@ ns_frame_up_to_date (struct frame *f)
       /*&& dpyinfo->mouse_face_mouse_frame*/)
         {
           BLOCK_INPUT;
+         ns_update_begin(f);
           if (dpyinfo->mouse_face_mouse_frame)
             note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
                                   dpyinfo->mouse_face_mouse_x,
                                   dpyinfo->mouse_face_mouse_y);
           dpyinfo->mouse_face_deferred_gc = 0;
+         ns_update_end(f);
           UNBLOCK_INPUT;
         }
     }
@@ -2350,7 +2360,7 @@ ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
   int fx, fy, h;
   struct frame *f = WINDOW_XFRAME (w);
   struct glyph *phys_cursor_glyph;
-  int overspill, cursorToDraw;
+  int overspill;
 
   NSTRACE (dumpcursor);
 //fprintf(stderr, "drawcursor (%d,%d) activep = %d\tonp = %d\tc_type = %d\twidth = %d\n",x,y, active_p,on_p,cursor_type,cursor_width);
@@ -2406,8 +2416,7 @@ ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
   NSDisableScreenUpdates ();
 #endif
 
-  cursorToDraw = active_p ? cursor_type : HOLLOW_BOX_CURSOR;
-  switch (cursorToDraw)
+  switch (cursor_type)
     {
     case NO_CURSOR:
       break;
@@ -2423,7 +2432,6 @@ ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
     case HBAR_CURSOR:
       s = r;
       s.origin.y += lrint (0.75 * s.size.height);
-      s.size.width = min (FRAME_COLUMN_WIDTH (f), s.size.width);
       s.size.height = lrint (s.size.height * 0.25);
       NSRectFill (s);
       break;
@@ -2436,7 +2444,7 @@ ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
   ns_unfocus (f);
 
   /* draw the character under the cursor */
-  if (cursorToDraw != NO_CURSOR)
+  if (cursor_type != NO_CURSOR)
     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
 
 #ifdef NS_IMPL_COCOA
@@ -2454,7 +2462,7 @@ ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
 {
   struct frame *f = XFRAME (WINDOW_FRAME (w));
   struct face *face;
-  NSRect r = NSMakeRect (x, y0, 2, y1-y0);
+  NSRect r = NSMakeRect (x, y0, 1, y1-y0);
 
   NSTRACE (ns_draw_vertical_window_border);
 
@@ -2463,7 +2471,7 @@ ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
       [ns_lookup_indexed_color(face->foreground, f) set];
 
   ns_focus (f, &r, 1);
-  NSDrawGroove (r, r);
+  NSRectFill(r);
   ns_unfocus (f);
 }
 
@@ -2807,6 +2815,7 @@ ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
   int th;
   char raised_p;
   NSRect br;
+  struct face *face;
 
   NSTRACE (ns_dumpglyphs_image);
 
@@ -2826,8 +2835,17 @@ ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
   /* Draw BG: if we need larger area than image itself cleared, do that,
      otherwise, since we composite the image under NS (instead of mucking
      with its background color), we must clear just the image area. */
-  [ns_lookup_indexed_color (NS_FACE_BACKGROUND
-            (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
+  if (s->hl == DRAW_MOUSE_FACE)
+    {
+      face = FACE_FROM_ID
+       (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
+      if (!face)
+       face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
+    }
+  else
+    face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
+
+  [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
 
   if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
       || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
@@ -2898,6 +2916,7 @@ ns_dumpglyphs_stretch (struct glyph_string *s)
 {
   NSRect r[2];
   int n, i;
+  struct face *face;
 
   if (!s->background_filled_p)
     {
@@ -2939,8 +2958,19 @@ ns_dumpglyphs_stretch (struct glyph_string *s)
         }
 
       ns_focus (s->f, r, n);
-      [ns_lookup_indexed_color (NS_FACE_BACKGROUND
-           (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
+
+      if (s->hl == DRAW_MOUSE_FACE)
+       {
+         face = FACE_FROM_ID
+           (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
+         if (!face)
+           face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
+       }
+      else
+       face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
+
+      [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
+
       NSRectFill (r[0]);
       NSRectFill (r[1]);
       ns_unfocus (s->f);
@@ -3021,7 +3051,7 @@ ns_draw_glyph_string (struct glyph_string *s)
       if (s->for_overlaps || (s->cmp_from > 0
                              && ! s->first_glyph->u.cmp.automatic))
         s->background_filled_p = 1;
-      else      /* 1 */
+      else
         ns_maybe_dumpglyphs_background
           (s, s->first_glyph->type == COMPOSITE_GLYPH);
 
@@ -3130,9 +3160,8 @@ ns_read_socket (struct terminal *terminal, int expected,
 {
   struct input_event ev;
   int nevents;
-  static NSDate *lastCheck = nil;
 
-/*  NSTRACE (ns_read_socket); */
+/* NSTRACE (ns_read_socket); */
 
   if (interrupt_input_blocked)
     {
@@ -3147,15 +3176,8 @@ ns_read_socket (struct terminal *terminal, int expected,
 #ifdef SYNC_INPUT
   pending_signals = pending_atimers;
 #endif
-  BLOCK_INPUT;
-
-#ifdef COCOA_EXPERIMENTAL_CTRL_G
-  /* causes Feval to abort; should probably set this in calling code when
-     it IS actually called from signal handler (which is only the case
-     under NS if SYNC_INPUT is off) */
-  ++handling_signal;
-#endif
 
+  BLOCK_INPUT;
   n_emacs_events_pending = 0;
   EVENT_INIT (ev);
   emacs_event = &ev;
@@ -3210,10 +3232,6 @@ ns_read_socket (struct terminal *terminal, int expected,
   nevents = n_emacs_events_pending;
   n_emacs_events_pending = 0;
   emacs_event = q_event_ptr = NULL;
-
-#ifdef COCOA_EXPERIMENTAL_CTRL_G
-  --handling_signal;
-#endif
   UNBLOCK_INPUT;
 
   return nevents;
@@ -3232,7 +3250,7 @@ ns_select (int nfds, fd_set *readfds, fd_set *writefds,
   NSEvent *ev;
 /*  NSTRACE (ns_select); */
 
-  if (NSApp == nil /* || ([NSApp isActive] == NO &&
+  if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
                       [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
  inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
     return select (nfds, readfds, writefds, exceptfds, timeout);
@@ -3573,11 +3591,9 @@ ns_set_default_prefs ()
   ns_command_modifier = Qsuper;
   ns_control_modifier = Qcontrol;
   ns_function_modifier = Qnone;
-  ns_expand_space = make_float (0.0);
   ns_antialias_text = Qt;
   ns_antialias_threshold = 10.0; /* not exposed to lisp side */
   ns_use_qd_smoothing = Qnil;
-  ns_use_system_highlight_color = Qt;
   ns_confirm_quit = Qnil;
 }
 
@@ -3848,48 +3864,20 @@ ns_term_init (Lisp_Object display_name)
   ns_set_default_prefs ();
   if (!ns_no_defaults)
     {
-      ns_default ("AlternateModifier", &ns_alternate_modifier,
-                 Qnil, Qnil, NO, YES);
-      if (NILP (ns_alternate_modifier))
-        ns_alternate_modifier = Qmeta;
-      ns_default ("CommandModifier", &ns_command_modifier,
-                 Qnil, Qnil, NO, YES);
-      if (NILP (ns_command_modifier))
-        ns_command_modifier = Qsuper;
-      ns_default ("ControlModifier", &ns_control_modifier,
-                 Qnil, Qnil, NO, YES);
-      if (NILP (ns_control_modifier))
-        ns_control_modifier = Qcontrol;
-      ns_default ("FunctionModifier", &ns_function_modifier,
-                 Qnil, Qnil, NO, YES);
-      if (NILP (ns_function_modifier))
-        ns_function_modifier = Qnone;
-      ns_default ("ExpandSpace", &ns_expand_space,
-                 make_float (0.5), make_float (0.0), YES, NO);
       ns_default ("GSFontAntiAlias", &ns_antialias_text,
                  Qt, Qnil, NO, NO);
       tmp = Qnil;
+      /* this is a standard variable */
       ns_default ("AppleAntiAliasingThreshold", &tmp,
                  make_float (10.0), make_float (6.0), YES, NO);
       ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
-      ns_default ("UseQuickdrawSmoothing", &ns_use_qd_smoothing,
-                 Qt, Qnil, NO, NO);
-      ns_default ("UseSystemHighlightColor", &ns_use_system_highlight_color,
-                 Qt, Qnil, NO, NO);
-      ns_default ("ConfirmQuit", &ns_confirm_quit,
-                 Qt, Qnil, NO, NO);
     }
 
-  if (EQ (ns_use_system_highlight_color, Qt))
-    {
-      ns_selection_color = [[NSUserDefaults standardUserDefaults]
-                               stringForKey: @"AppleHighlightColor"];
-      if (ns_selection_color == nil)
-        ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
-    }
-  else
+  ns_selection_color = [[NSUserDefaults standardUserDefaults]
+                        stringForKey: @"AppleHighlightColor"];
+  if (ns_selection_color == nil)
     ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
-
+  
   {
     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
 
@@ -4018,7 +4006,6 @@ ns_term_shutdown (int sig)
 
   if (sig == 0 || sig == SIGTERM)
     {
-      ns_shutdown_properly = YES;
       [NSApp terminate: NSApp];
     }
   else // force a stack trace to happen
@@ -4048,7 +4035,8 @@ ns_term_shutdown (int sig)
 
 - (void)sendEvent: (NSEvent *)theEvent
 /* --------------------------------------------------------------------------
-     Events posted by ns_send_appdefined interrupt the run loop here
+     Called when NSApp is running for each event received.  Used to stop
+     the loop when we choose, since there's no way to just run one iteration.
    -------------------------------------------------------------------------- */
 {
   int type = [theEvent type];
@@ -4092,8 +4080,19 @@ ns_term_shutdown (int sig)
 
   if (type == NSApplicationDefined)
     {
-      last_appdefined_event = theEvent;
-      [self stop: self];
+      /* Events posted by ns_send_appdefined interrupt the run loop here.
+         But, if a modal window is up, an appdefined can still come through,
+         (e.g., from a makeKeyWindow event) but stopping self also stops the
+         modal loop. Just defer it until later. */
+      if ([NSApp modalWindow] == nil)
+        {
+          last_appdefined_event = theEvent;
+          [self stop: self];
+        }
+      else
+        {
+          send_appdefined = YES;
+        }
     }
 
   [super sendEvent: theEvent];
@@ -4102,9 +4101,15 @@ ns_term_shutdown (int sig)
 
 - (void)showPreferencesWindow: (id)sender
 {
-  if (prefsController == nil)
-    prefsController = [[EmacsPrefsController alloc] init];
-  [prefsController showForFrame: SELECTED_FRAME ()];
+  struct frame *emacsframe = SELECTED_FRAME ();
+  NSEvent *theEvent = [NSApp currentEvent];
+
+  if (!emacs_event)
+    return;
+  emacs_event->kind = NS_NONKEY_EVENT;
+  emacs_event->code = KEY_NS_SHOW_PREFS;
+  emacs_event->modifiers = 0;
+  EV_TRAILER (theEvent);
 }
 
 
@@ -4115,7 +4120,7 @@ ns_term_shutdown (int sig)
 
   if (!emacs_event)
     return;
-  emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+  emacs_event->kind = NS_NONKEY_EVENT;
   emacs_event->code = KEY_NS_NEW_FRAME;
   emacs_event->modifiers = 0;
   EV_TRAILER (theEvent);
@@ -4131,7 +4136,7 @@ ns_term_shutdown (int sig)
   if (!emacs_event)
     return NO;
 
-  emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+  emacs_event->kind = NS_NONKEY_EVENT;
   emacs_event->code = KEY_NS_OPEN_FILE_LINE;
   ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
   ns_input_line = Qnil; /* can be start or cons start,end */
@@ -4159,47 +4164,38 @@ ns_term_shutdown (int sig)
 }
 
 
-/* Termination sequences (ns_shutdown_properly):
+/* Termination sequences:
     C-x C-c:
     Cmd-Q:
     MenuBar | File | Exit:
-        ns_term_shutdown: 0
-        received -terminate: 1
-        received -appShouldTerminate: 1
-
     Select Quit from App menubar:
-        received -terminate: 0
-        ns_term_shutdown: 0
-        received -terminate: 1
-        received -appShouldTerminate: 1
+        -terminate
+       KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
+       ns_term_shutdown()
 
     Select Quit from Dock menu:
     Logout attempt:
-        received -appShouldTerminate: 0
+        -appShouldTerminate
           Cancel -> Nothing else
           Accept ->
-            received -terminate: 0
-            ns_term_shutdown: 0
-            received -terminate: 1
-            received -appShouldTerminate: 1
+         
+         -terminate
+         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
+         ns_term_shutdown()
+
 */
 
 - (void) terminate: (id)sender
 {
-  if (ns_shutdown_properly)
-    [super terminate: sender];
-  else
-    {
-      struct frame *emacsframe = SELECTED_FRAME ();
-
-      if (!emacs_event)
-        return;
-
-      ns_shutdown_properly = YES;
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
-      emacs_event->code = KEY_NS_POWER_OFF;
-      EV_TRAILER ((id)nil);
-    }
+  struct frame *emacsframe = SELECTED_FRAME ();
+  
+  if (!emacs_event)
+    return;
+  
+  emacs_event->kind = NS_NONKEY_EVENT;
+  emacs_event->code = KEY_NS_POWER_OFF;
+  emacs_event->arg = Qt; /* mark as non-key event */
+  EV_TRAILER ((id)nil);
 }
 
 
@@ -4207,31 +4203,18 @@ ns_term_shutdown (int sig)
 {
   int ret;
 
-  if (ns_shutdown_properly || NILP (ns_confirm_quit))
+  if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
     return NSTerminateNow;
 
-  /* XXX: This while() loop is needed because if the user switches to another
-          application while the panel is up, it is taken down w/a return value
-          of -1000, and the event queue gets messed up.  In this case resend
-          the appdefined and put up the window again. */
-  while (1) {
     ret = NSRunAlertPanel([[NSProcessInfo processInfo] processName],
                           [NSString stringWithUTF8String:"Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"],
                           @"Save Buffers and Exit", @"Cancel", nil);
 
     if (ret == NSAlertDefaultReturn)
-      {
-        send_appdefined = YES;
-        ns_send_appdefined(-1);
         return NSTerminateNow;
-      }
     else if (ret == NSAlertAlternateReturn)
-      {
-        send_appdefined = YES;
-        ns_send_appdefined(-1);
         return NSTerminateCancel;
-      }
-  }
+    return NSTerminateNow;  /* just in case */
 }
 
 
@@ -4369,7 +4352,7 @@ extern void update_window_cursor (struct window *w, int on);
   if (!emacs_event)
     return NO;
 
-  emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+  emacs_event->kind = NS_NONKEY_EVENT;
   emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
   ns_input_spi_name = build_string ([name UTF8String]);
   ns_input_spi_arg = build_string ([arg UTF8String]);
@@ -4425,7 +4408,7 @@ extern void update_window_cursor (struct window *w, int on);
     {
       SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
 
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+      emacs_event->kind = NS_NONKEY_EVENT;
       emacs_event->modifiers = 0;
       emacs_event->code = KEY_NS_CHANGE_FONT;
 
@@ -4484,17 +4467,16 @@ extern void update_window_cursor (struct window *w, int on);
   if (!emacs_event)
     return;
 
- if (![[self window] isKeyWindow])
+ if (![[self window] isKeyWindow]
+     && [[theEvent window] isKindOfClass: [EmacsWindow class]])
    {
-     /* XXX: Using NO_SOCK_SIGIO like Carbon causes a condition in which,
-         when Emacs display updates a different frame from the current one,
-         and temporarily selects it, then processes some interrupt-driven
-         input (dispnew.c:3878), OS will send the event to the correct NSWindow,
-         but for some reason that window has its first responder set to the
-         NSView most recently updated (I guess), which is not the correct one.
-         UPDATE: After multi-TTY merge this happens even w/o NO_SOCK_SIGIO */
-     if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
-         [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
+     /* XXX: There is an occasional condition in which, when Emacs display
+         updates a different frame from the current one, and temporarily
+         selects it, then processes some interrupt-driven input
+         (dispnew.c:3878), OS will send the event to the correct NSWindow, but
+         for some reason that window has its first responder set to the NSView
+         most recently updated (I guess), which is not the correct one. */
+     [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
      return;
    }
 
@@ -5108,17 +5090,16 @@ extern void update_window_cursor (struct window *w, int on);
     }
 #endif /* NS_IMPL_COCOA */
 
+  // Calling x_set_window_size tends to get us into inf-loops
+  // (x_set_window_size causes a resize which causes
+  // a "windowDidResize" which calls x_set_window_size).
+  // At least with GNUStep, don't know about MacOSX.  --Stef
+#ifndef NS_IMPL_GNUSTEP
   if (cols > 0 && rows > 0)
-    x_set_window_size (emacsframe, 0, cols, rows);
+     x_set_window_size (emacsframe, 0, cols, rows);
+#endif
 
   ns_send_appdefined (-1);
-
-  /* The following line causes a crash on GNUstep.  Adrian Robert
-     says he doesn't remember why he added this line, but removing it
-     doesn't seem to cause problems on OSX, either.  */
-#if 0
-  [NSApp stopModal];
-#endif
 }
 
 
@@ -5312,14 +5293,33 @@ extern void update_window_cursor (struct window *w, int on);
 /* if we don't do this manually, the window will resize but not move */
 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
 {
+  NSTRACE (windowShouldZoom);
   [[self window] setFrame: newFrame display: NO];
   return YES;
 }
 #endif
 
-/* Implement this to control size of frame on zoom.
+
+/* Override to do something slightly nonstandard, but nice.  First click on
+   zoom button will zoom vertically.  Second will zoom completely.  Third
+   returns to original. */
 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
-                        defaultFrame:(NSRect)defaultFrame; */
+                        defaultFrame:(NSRect)defaultFrame
+{
+  NSRect result = [sender frame];
+  NSTRACE (windowWillUseStandardFrame);
+
+  if (result.size.height == defaultFrame.size.height) {
+    result = defaultFrame;
+  } else {
+    result.size.height = defaultFrame.size.height;
+    result.origin.y = defaultFrame.origin.y;
+  }
+
+  /* A windowWillResize does not get generated at least on Tiger. */
+  [self windowWillResize: sender toSize: result.size];
+  return result;
+}
 
 
 - (void)windowDidDeminiaturize: sender
@@ -5327,8 +5327,8 @@ extern void update_window_cursor (struct window *w, int on);
   NSTRACE (windowDidDeminiaturize);
   if (!emacsframe->output_data.ns)
     return;
-  emacsframe->async_visible   = 1;
   emacsframe->async_iconified = 0;
+  emacsframe->async_visible   = 1;
   windows_or_buffers_changed++;
 
   if (emacs_event)
@@ -5359,6 +5359,7 @@ extern void update_window_cursor (struct window *w, int on);
     return;
 
   emacsframe->async_iconified = 1;
+  emacsframe->async_visible = 0;
 
   if (emacs_event)
     {
@@ -5452,7 +5453,7 @@ extern void update_window_cursor (struct window *w, int on);
   if (!emacs_event)
     return self;
 
-  emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+  emacs_event->kind = NS_NONKEY_EVENT;
   emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
   EV_TRAILER ((id)nil);
   return self;
@@ -5466,18 +5467,20 @@ extern void update_window_cursor (struct window *w, int on);
 
   NSTRACE (drawRect);
 
-  if (!emacsframe || !emacsframe->output_data.ns)
+  if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
     return;
 
-  if (!ns_in_resize)
-    ns_clear_frame_area (emacsframe, x, y, width, height);
+  ns_clear_frame_area (emacsframe, x, y, width, height);
   expose_frame (emacsframe, x, y, width, height);
 
-  emacsframe->async_visible = 1;
-  emacsframe->async_iconified = 0;
+  /*
+    drawRect: may be called (at least in OS X 10.5) for invisible
+    views as well for some reason.  Thus, do not infer visibility 
+    here.
 
-/*    SET_FRAME_GARBAGED (emacsframe);
-      ns_send_appdefined (-1); */
+    emacsframe->async_visible = 1;
+    emacsframe->async_iconified = 0;
+  */
 }
 
 
@@ -5531,7 +5534,7 @@ extern void update_window_cursor (struct window *w, int on);
       fenum = [files objectEnumerator];
       while ( (file = [fenum nextObject]) )
         {
-          emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+          emacs_event->kind = NS_NONKEY_EVENT;
           emacs_event->code = KEY_NS_DRAG_FILE;
           XSETINT (emacs_event->x, x);
           XSETINT (emacs_event->y, y);
@@ -5552,7 +5555,7 @@ extern void update_window_cursor (struct window *w, int on);
         return NO;
 
       file = [fileURL path];
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+      emacs_event->kind = NS_NONKEY_EVENT;
       emacs_event->code = KEY_NS_DRAG_FILE;
       XSETINT (emacs_event->x, x);
       XSETINT (emacs_event->y, y);
@@ -5569,7 +5572,7 @@ extern void update_window_cursor (struct window *w, int on);
       if (! (data = [pb stringForType: type]))
         return NO;
 
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+      emacs_event->kind = NS_NONKEY_EVENT;
       emacs_event->code = KEY_NS_DRAG_TEXT;
       XSETINT (emacs_event->x, x);
       XSETINT (emacs_event->y, y);
@@ -5581,7 +5584,7 @@ extern void update_window_cursor (struct window *w, int on);
   else if ([type isEqualToString: NSColorPboardType])
     {
       NSColor *c = [NSColor colorFromPasteboard: pb];
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+      emacs_event->kind = NS_NONKEY_EVENT;
       emacs_event->code = KEY_NS_DRAG_COLOR;
       XSETINT (emacs_event->x, x);
       XSETINT (emacs_event->y, y);
@@ -5601,7 +5604,7 @@ extern void update_window_cursor (struct window *w, int on);
       if (font == nil)
         return NO;
 
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+      emacs_event->kind = NS_NONKEY_EVENT;
       emacs_event->code = KEY_NS_CHANGE_FONT;
       XSETINT (emacs_event->x, x);
       XSETINT (emacs_event->y, y);
@@ -5637,8 +5640,7 @@ extern void update_window_cursor (struct window *w, int on);
    supposedly called when a services menu item is chosen from this app.
    But this should not happen because we override the services menu with our
    own entries which call ns-perform-service.
-   Nonetheless, it appeared to happen here (under strange circumstances):
-   http://emacsbugs.donarmstrong.com/cgi-bin/bugreport.cgi?bug=1435 
+   Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
    So let's at least stub them out until further investigation can be done. */
 
 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
@@ -6138,203 +6140,6 @@ extern void update_window_cursor (struct window *w, int on);
 
 
 
-/* ==========================================================================
-
-    EmacsPrefsController implementation
-
-   ========================================================================== */
-
-
-@implementation EmacsPrefsController
-
-/* in Tiger+, can just do [popup selectItemWithTag: tag]; */
-static void selectItemWithTag (NSPopUpButton *popup, int tag)
-{
-  NSEnumerator *items = [[popup itemArray] objectEnumerator];
-  NSMenuItem *item;
-  while (item = [items nextObject])
-    {
-      if ([item tag] == tag)
-        {
-          [popup selectItem: item];
-          return;
-        }
-    }
-}
-
-- init
-{
-  [NSBundle loadNibNamed: @"preferences" owner: self];
-  return self;
-}
-
-
-- (void) showForFrame: (struct frame *)f
-{
-  frame = f;
-  [self setPanelFromValues];
-  [prefsWindow makeKeyAndOrderFront: self];
-  [prefsWindow display];
-}
-
-
-/* If you change this, change setPanelFromDefaultValues too. */
-- (void) setPanelFromValues
-{
-  int cursorType
-    = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
-  prevExpandSpace = XFLOATINT (ns_expand_space);
-
-#ifdef NS_IMPL_COCOA
-  prevUseHighlightColor = ns_use_system_highlight_color;
-#endif
-
-  [expandSpaceSlider setFloatValue: prevExpandSpace];
-  [cursorTypeMatrix selectCellWithTag: (cursorType == FILLED_BOX_CURSOR ? 1 :
-                                        (cursorType == BAR_CURSOR ? 2 :
-                                         (cursorType == HBAR_CURSOR ? 3 : 4)))];
-  selectItemWithTag (alternateModMenu,
-                    parse_solitary_modifier (ns_alternate_modifier));
-  selectItemWithTag (commandModMenu,
-                    parse_solitary_modifier (ns_command_modifier));
-#ifdef NS_IMPL_COCOA
-  selectItemWithTag (controlModMenu,
-                    parse_solitary_modifier (ns_control_modifier));
-  selectItemWithTag (functionModMenu,
-                    parse_solitary_modifier (ns_function_modifier));
-  [smoothFontsCheck setState: (NILP (ns_antialias_text) ? NO : YES)];
-  [useQuickdrawCheck setState: (NILP (ns_use_qd_smoothing) ? NO : YES)];
-  [useSysHiliteCheck setState: (NILP (prevUseHighlightColor) ? NO : YES)];
-  [confirmQuitCheck setState: (NILP (ns_confirm_quit) ? NO : YES)];
-#endif
-}
-
-
-/* This and ns_set_default_prefs should be changed together. */
-- (void) setPanelFromDefaultValues
-{
-  [expandSpaceSlider setFloatValue: 0.0];
-  [cursorTypeMatrix selectCellWithTag: 1]; /* filled box */
-  selectItemWithTag (alternateModMenu, meta_modifier);
-  selectItemWithTag (commandModMenu, super_modifier);
-#ifdef NS_IMPL_COCOA
-  selectItemWithTag (controlModMenu, ctrl_modifier);
-  selectItemWithTag (functionModMenu, 0); /* none */
-  [smoothFontsCheck setState: YES];
-  [useQuickdrawCheck setState: NO];
-  [useSysHiliteCheck setState: YES];
-#endif
-}
-
-
-- (void) setValuesFromPanel
-{
-  int altTag = [[alternateModMenu selectedItem] tag];
-  int cmdTag = [[commandModMenu selectedItem] tag];
-#ifdef NS_IMPL_COCOA
-  int ctrlTag = [[controlModMenu selectedItem] tag];
-  int fnTag = [[functionModMenu selectedItem] tag];
-#endif
-  float expandSpace = [expandSpaceSlider floatValue];
-  int cursorTag = [[cursorTypeMatrix selectedCell] tag];
-  Lisp_Object cursor_type = ns_cursor_type_to_lisp
-       ( cursorTag == 1 ? FILLED_BOX_CURSOR
-       : cursorTag == 2 ? BAR_CURSOR
-       : cursorTag == 3 ? HBAR_CURSOR : HOLLOW_BOX_CURSOR);
-
-  if (expandSpace != prevExpandSpace)
-    {
-      ns_expand_space = make_float (expandSpace);
-      /* TODO: more needed: store needed metrics in nsfont_info, update
-         frame default font max_bounds and fontp, recompute faces */
-/*         FRAME_LINE_HEIGHT (frame) *= (expandSpace / prevExpandSpace);
-           x_set_window_size (frame, 0, frame->text_cols, frame->text_lines); */
-      prevExpandSpace = expandSpace;
-    }
-
-  store_frame_param (frame, Qcursor_type, cursor_type);
-  x_set_cursor_type (frame, cursor_type, Qnil);  /* FIXME: do only if changed */
-
-  ns_alternate_modifier = ns_mod_to_lisp (altTag);
-  ns_command_modifier = ns_mod_to_lisp (cmdTag);
-#ifdef NS_IMPL_COCOA
-  ns_control_modifier = ns_mod_to_lisp (ctrlTag);
-  ns_function_modifier = ns_mod_to_lisp (fnTag);
-  ns_antialias_text = [smoothFontsCheck state] ? Qt : Qnil;
-  ns_use_qd_smoothing = [useQuickdrawCheck state] ? Qt : Qnil;
-  ns_use_system_highlight_color = [useSysHiliteCheck state] ? Qt : Qnil;
-  ns_confirm_quit = [confirmQuitCheck state] ? Qt : Qnil;
-  if (! EQ (ns_use_system_highlight_color, prevUseHighlightColor))
-    {
-      prevUseHighlightColor = ns_use_system_highlight_color;
-      if (EQ (ns_use_system_highlight_color, Qt))
-        {
-          ns_selection_color = [[NSUserDefaults standardUserDefaults]
-                                 stringForKey: @"AppleHighlightColor"];
-          if (ns_selection_color == nil)
-            ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
-        }
-      else
-        ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
-    }
-#endif /* NS_IMPL_COCOA */
-  Fcall_interactively (intern ("ns-save-preferences"), Qnil, Qnil);
-}
-
-
-/* buttons */
-- (IBAction)cancel: (id)sender
-{
-  [prefsWindow close];
-}
-
-
-- (IBAction)ok: (id)sender
-{
-  [self setValuesFromPanel];
-  [prefsWindow close];
-}
-
-
-- (IBAction)resetToDefaults: (id)sender
-{
-  [self setPanelFromDefaultValues];
-}
-
-
-- (IBAction)runHelp: (id)sender
-{
-  struct frame *emacsframe = frame;
-  if (!emacs_event)
-    return;
-  ns_raise_frame(frame);
-  emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
-  emacs_event->code = KEY_NS_INFO_PREFS;
-  EV_TRAILER ((id)nil);
-}
-
-
-- (IBAction)setColors: (id)sender
-{
-  Lisp_Object lispFrame;
-  XSETFRAME (lispFrame, frame);
-  ns_raise_frame(frame);
-  Fns_popup_color_panel (lispFrame);
-}
-
-
-- (IBAction)setDefaultFont: (id)sender
-{
-  Lisp_Object lispFrame;
-  XSETFRAME (lispFrame, frame);
-  ns_raise_frame(frame);
-  Fns_popup_font_panel (lispFrame);
-}
-
-@end  /* EmacsPrefsController */
-
-
-
 
 /* ==========================================================================
 
@@ -6497,21 +6302,12 @@ Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
 Set to none means that the function key is not interpreted by Emacs at all,\n\
 allowing it to be used at a lower level for accented character entry.");
 
-  DEFVAR_LISP ("ns-expand-space", &ns_expand_space,
-               "Amount by which spacing between lines is expanded (positive)\n\
-or shrunk (negative).  Zero (the default) means standard line height.\n\
-(This variable should only be read, never set.)");
-
   DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
                "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
 
   DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
                "Whether to render text using QuickDraw (less heavy) antialiasing. Only has an effect on OS X Panther and above.  Default is nil (use Quartz smoothing).");
 
-  DEFVAR_LISP ("ns-use-system-highlight-color",
-               &ns_use_system_highlight_color,
-               "Whether to use the system default (on OS X only) for the highlight color.  Nil means to use standard emacs (prior to version 21) 'grey'.");
-
   DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
                "Whether to confirm application quit using dialog.");