Replace bcopy, bzero, bcmp by memcpy, memmove, memset, memcmp
[bpt/emacs.git] / src / nsterm.m
index 2f8eccb..62f1c0b 100644 (file)
@@ -1,5 +1,5 @@
 /* NeXT/Open/GNUstep / MacOSX communication module.
-   Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009
+   Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009, 2010
      Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
@@ -27,12 +27,14 @@ GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
 
 /* This should be the first include, as it may set up #defines affecting
    interpretation of even the system includes. */
-#include "config.h"
+#include <config.h>
 
 #include <math.h>
 #include <sys/types.h>
 #include <time.h>
+#include <signal.h>
 #include <unistd.h>
+#include <setjmp.h>
 
 #include "lisp.h"
 #include "blockinput.h"
@@ -69,20 +71,6 @@ int term_trace_num = 0;
 
    ========================================================================== */
 
-/* Special keycodes that we pass down the event chain */
-#define KEY_NS_POWER_OFF               ((1<<28)|(0<<16)|1)
-#define KEY_NS_OPEN_FILE               ((1<<28)|(0<<16)|2)
-#define KEY_NS_OPEN_TEMP_FILE          ((1<<28)|(0<<16)|3)
-#define KEY_NS_DRAG_FILE               ((1<<28)|(0<<16)|4)
-#define KEY_NS_DRAG_COLOR              ((1<<28)|(0<<16)|5)
-#define KEY_NS_DRAG_TEXT               ((1<<28)|(0<<16)|6)
-#define KEY_NS_CHANGE_FONT             ((1<<28)|(0<<16)|7)
-#define KEY_NS_OPEN_FILE_LINE          ((1<<28)|(0<<16)|8)
-#define KEY_NS_INSERT_WORKING_TEXT     ((1<<28)|(0<<16)|9)
-#define KEY_NS_DELETE_WORKING_TEXT     ((1<<28)|(0<<16)|10)
-#define KEY_NS_SPI_SERVICE_CALL        ((1<<28)|(0<<16)|11)
-#define KEY_NS_NEW_FRAME               ((1<<28)|(0<<16)|12)
-
 /* Convert a symbol indexed with an NSxxx value to a value as defined
    in keyboard.c (lispy_function_key). I hope this is a correct way
    of doing things... */
@@ -123,6 +111,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. */
@@ -144,25 +141,9 @@ Lisp_Object ns_input_color, ns_input_text, ns_working_text;
 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
 Lisp_Object Vx_toolkit_scroll_bars;
 static Lisp_Object Qmodifier_value;
-/* TODO: unsure why these defined in term files, anyway we need in keymap.c */
-Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
+Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
 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
-   options. */
-
-/* Set in emacs.c. */
-char ns_no_defaults;
-
 /* Specifies which emacs modifier should be generated when NS receives
    the Alternate modifer.  May be Qnone or any of the modifier lisp symbols. */
 Lisp_Object ns_alternate_modifier;
@@ -179,11 +160,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;
 
@@ -192,16 +168,14 @@ Lisp_Object ns_antialias_text;
    no way to control this behavior. */
 float ns_antialias_threshold;
 
-/* Controls use of an undocumented CG function to do Quickdraw-style font
-   smoothing (less heavy) instead of regular Quartz smoothing. */
-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. */
+Lisp_Object ns_confirm_quit;
 
 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
+NSString *ns_app_name = @"Emacs";  /* default changed later */
 
 /* Display variables */
 struct ns_display_info *x_display_list; /* Chain of existing displays */
@@ -225,16 +199,6 @@ int ns_tmp_flags; /* FIXME */
 struct nsfont_info *ns_tmp_font; /* FIXME */
 /*static int debug_lock = 0; */
 
-#ifdef NS_IMPL_COCOA
-/* This undocumented Quartz function controls how fonts are anti-aliased.
-   (Found from code in Mac wxWindows impl, discovered by running `nm' on
-   the "QD" framework.)
-   Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
-   4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
-extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
-#endif
-
-
 /* event loop */
 static BOOL send_appdefined = YES;
 static NSEvent *last_appdefined_event = 0;
@@ -245,7 +209,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;
@@ -286,12 +249,7 @@ static BOOL inNsSelect = 0;
      [e buttonNumber] - 1)
 
 /* Convert the time field to a timestamp in milliseconds. */
-#ifdef NS_IMPL_GNUSTEP
-/* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
-#define EV_TIMESTAMP(e) ([e timestamp])
-#else
 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
-#endif /* not gnustep */
 
 /* This is a piece of code which is common to all the event handling
    methods.  Maybe it should even be a function.  */
@@ -386,7 +344,7 @@ ns_init_paths ()
         }
       if ([resourcePaths length] > 0)
         setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
-/*NSLog (@"loadPath: '%s'\n", resourcePaths); */
+/*NSLog (@"loadPath: '%@'\n", resourcePaths); */
     }
 
   if (!getenv ("EMACSPATH"))
@@ -429,7 +387,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. */
     }
 }
 
@@ -856,11 +816,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);
@@ -887,6 +845,7 @@ ns_reset_terminal_modes (struct terminal *terminal)
   NSTRACE (ns_reset_terminal_modes);
 }
 
+
 static void
 ns_set_terminal_modes (struct terminal *terminal)
 /*  Externally called as hook */
@@ -912,7 +871,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;
 }
 
@@ -999,7 +962,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);
+    }
 }
 
 
@@ -1013,6 +979,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;
 }
 
 
@@ -1108,6 +1076,7 @@ x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
   if (xoff < 100)
     f->left_pos = 100;  /* don't overlap menu */
 #endif
+
   if (view != nil && (screen = [[view window] screen]))
     [[view window] setFrameTopLeftPoint:
         NSMakePoint (SCREENMAXBOUND (f->left_pos),
@@ -1164,27 +1133,20 @@ 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]])
+    /* 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 */
+    FRAME_TOOLBAR_HEIGHT (f) =
+      NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
         - FRAME_NS_TITLEBAR_HEIGHT (f);
-#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); */
-#endif
   else
-    FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
+    FRAME_TOOLBAR_HEIGHT (f) = 0;
 
   wr.size.width = pixelwidth + f->border_width;
   wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f) 
-                  + FRAME_NS_TOOLBAR_HEIGHT (f);
+                  + FRAME_TOOLBAR_HEIGHT (f);
 
   /* constrain to screen if we can */
   if (screen)
@@ -1255,6 +1217,8 @@ NSColor *
 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
 {
   struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
+  if (idx < 1 || idx >= color_table->avail)
+    return nil;
   return color_table->colors[idx];
 }
 
@@ -1272,6 +1236,7 @@ ns_index_color (NSColor *color, struct frame *f)
       color_table->avail = 1; /* skip idx=0 as marker */
       color_table->colors
        = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
+      color_table->colors[0] = nil;
       color_table->empty_indices = [[NSMutableSet alloc] init];
     }
 
@@ -1348,18 +1313,15 @@ static int
 ns_get_color (const char *name, NSColor **col)
 /* --------------------------------------------------------------------------
      Parse a color name
-/* --------------------------------------------------------------------------
-/* On *Step, we recognize several color formats, in addition to a catalog
-   of colors found in the file Emacs.clr. Color formats include:
-   - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
-   - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
-   - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
-     value;
-   - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
-{
-  NSColor * new = nil;
-  const char *hex = NULL;
-  enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
+   -------------------------------------------------------------------------- */
+/* On *Step, we attempt to mimic the X11 platform here, down to installing an
+   X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
+   See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
+{
+  NSColor *new = nil;
+  static char hex[20];
+  int scaling;
+  float r = -1.0, g, b;
   NSString *nsname = [NSString stringWithUTF8String: name];
 
 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
@@ -1371,123 +1333,54 @@ ns_get_color (const char *name, NSColor **col)
       name = [ns_selection_color UTF8String];
     }
 
-  if (name[0] == '0' || name[0] == '1' || name[0] == '.')
+  /* First, check for some sort of numeric specification. */
+  hex[0] = '\0';
+
+  if (name[0] == '0' || name[0] == '1' || name[0] == '.')  /* RGB decimal */
     {
-      /* RGB decimal */
       NSScanner *scanner = [NSScanner scannerWithString: nsname];
-      float r, g, b;
       [scanner scanFloat: &r];
       [scanner scanFloat: &g];
       [scanner scanFloat: &b];
-      *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
-      UNBLOCK_INPUT;
-      return 0;
-    }
-
-  /*  FIXME: emacs seems to downcase everything before passing it here,
-        which we can work around, except for GRAY, since gray##, where ## is
-        decimal between 0 and 99, is also an X11 colorname. */
-  if (name[0] == '#')             /* X11 format */
-    {
-      hex = name + 1;
-      color_space = rgb;
-    }
-  else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
-    {
-      hex = name + 3;
-      color_space = rgb;
-    }
-  else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
-    {
-      hex = name + 4;
-      color_space = argb;
-    }
-  else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) || 
-           !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
-    {
-      hex = name + 3;
-      color_space = hsv;
-    }
-  else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
-           !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
-    {
-      hex = name + 4;
-      color_space = ahsv;
     }
-  else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
+  else if (!strncmp(name, "rgb:", 4))  /* A newer X11 format -- rgb:r/g/b */
     {
-      hex = name + 4;
-      color_space = cmyk;
+      strncpy (hex, name + 4, 19);
+      hex[19] = '\0';
+      scaling = (strlen(hex) - 2) / 3;
     }
-  else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
+  else if (name[0] == '#')        /* An old X11 format; convert to newer */
     {
-      hex = name + 4;
-      color_space = gray;
+      int len = (strlen(name) - 1);
+      int start = (len % 3 == 0) ? 1 : len / 4 + 1;
+      int i;
+      scaling = strlen(name+start) / 3;
+      for (i=0; i<3; i++) {
+        strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
+        hex[(i+1) * (scaling + 1) - 1] = '/';
+      }
+      hex[3 * (scaling + 1) - 1] = '\0';
     }
 
-  /* Direct colors (hex values) */
-  if (hex)
+  if (hex[0])
     {
-      unsigned long long color = 0;
-      if (sscanf (hex, "%x", &color))
+      int rr, gg, bb;
+      float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
+      if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
         {
-          float f1, f2, f3, f4;
-          /* Assume it's either 1 byte or 2 per channel... */
-          if (strlen(hex) > 8) {
-            f1 = ((color >> 48) & 0xffff) / 65535.0;
-            f2 = ((color >> 32) & 0xffff) / 65535.0;
-            f3 = ((color >> 16) & 0xffff) / 65535.0;
-            f4 = ((color      ) & 0xffff) / 65535.0;
-          } else {
-            f1 = ((color >> 24) & 0xff) / 255.0;
-            f2 = ((color >> 16) & 0xff) / 255.0;
-            f3 = ((color >>  8) & 0xff) / 255.0;
-            f4 = ((color      ) & 0xff) / 255.0;
-          }
-
-          switch (color_space)
-            {
-            case rgb:
-              *col = [NSColor colorWithCalibratedRed: f2
-                                               green: f3
-                                                blue: f4
-                                               alpha: 1.0];
-              break;
-            case argb:
-              *col = [NSColor colorWithCalibratedRed: f2
-                                               green: f3
-                                                blue: f4
-                                               alpha: f1];
-              break;
-            case hsv:
-              *col = [NSColor colorWithCalibratedHue: f2
-                                          saturation: f3
-                                          brightness: f4
-                                               alpha: 1.0];
-              break;
-            case ahsv:
-              *col = [NSColor colorWithCalibratedHue: f2
-                                          saturation: f3
-                                          brightness: f4
-                                               alpha: f1];
-              break;
-            case gray:
-              *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
-              break;
-            case cmyk:
-              *col = [NSColor colorWithDeviceCyan: f1
-                                          magenta: f2
-                                           yellow: f3
-                                            black: f4
-                                            alpha: 1.0];
-              break;
-            }
-          *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
-          UNBLOCK_INPUT;
-          return 0;
+          r = rr / fscale;
+          g = gg / fscale;
+          b = bb / fscale;
         }
     }
 
+  if (r >= 0.0)
+    {
+      *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
+      UNBLOCK_INPUT;
+      return 0;
+    }
+
   /* Otherwise, color is expected to be from a list */
   {
     NSEnumerator *lenum, *cenum;
@@ -1514,10 +1407,8 @@ ns_get_color (const char *name, NSColor **col)
       }
   }
 
-  if ( new )
+  if (new)
     *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
-/*     else
-       NSLog (@"Failed to find color '%@'", nsname); */
   UNBLOCK_INPUT;
   return new ? 0 : 1;
 }
@@ -1559,7 +1450,7 @@ ns_color_to_lisp (NSColor *col)
      Convert a color to a lisp string with the RGB equivalent
    -------------------------------------------------------------------------- */
 {
-  float red, green, blue, alpha, gray;
+  CGFloat red, green, blue, alpha, gray;
   char buf[1024];
   const char *str;
   NSTRACE (ns_color_to_lisp);
@@ -1579,14 +1470,13 @@ ns_color_to_lisp (NSColor *col)
     {
       [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
             getWhite: &gray alpha: &alpha];
-      snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
-               lrint (gray * 0xff), lrint (alpha * 0xff));
+      snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
+               lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
       UNBLOCK_INPUT;
       return build_string (buf);
     }
 
-  snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
-            lrint (alpha*0xff),
+  snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
             lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
 
   UNBLOCK_INPUT;
@@ -1594,6 +1484,28 @@ ns_color_to_lisp (NSColor *col)
 }
 
 
+void
+ns_query_color(void *col, XColor *color_def, int setPixel)
+/* --------------------------------------------------------------------------
+         Get ARGB values out of NSColor col and put them into color_def.
+         If setPixel, set the pixel to a concatenated version.
+         and set color_def pixel to the resulting index.
+   -------------------------------------------------------------------------- */
+{
+  CGFloat r, g, b, a;
+
+  [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
+  color_def->red   = r * 65535;
+  color_def->green = g * 65535;
+  color_def->blue  = b * 65535;
+
+  if (setPixel == YES)
+    color_def->pixel
+      = ARGB_TO_ULONG((int)(a*255),
+                     (int)(r*255), (int)(g*255), (int)(b*255));
+}
+
+
 int
 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
                   char makeIndex)
@@ -1605,28 +1517,19 @@ ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
          Return 0 if not found
    -------------------------------------------------------------------------- */
 {
-  NSColor *temp;
-  float r, g, b, a;
-  int notFound = ns_get_color (name, &temp);
-
+  NSColor *col;
   NSTRACE (ns_defined_color);
 
-  if (notFound)
-    return 0;
-
+  BLOCK_INPUT;
+  if (ns_get_color (name, &col) != 0) /* Color not found  */
+    {
+      UNBLOCK_INPUT;
+      return 0;
+    }
   if (makeIndex && alloc)
-      color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
-
-  [temp getRed: &r green: &g blue: &b alpha: &a];
-  color_def->red   = r * 65535;
-  color_def->green = g * 65535;
-  color_def->blue  = b * 65535;
-
-  if (!makeIndex)
-    color_def->pixel
-      = ARGB_TO_ULONG((int)(a*255),
-                     (int)(r*255), (int)(g*255), (int)(b*255));
-
+    color_def->pixel = ns_index_color (col, f);
+  ns_query_color (col, color_def, !makeIndex);
+  UNBLOCK_INPUT;
   return 1;
 }
 
@@ -1753,9 +1656,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;
     }
 
@@ -1857,11 +1762,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;
         }
     }
@@ -2256,11 +2163,11 @@ ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
     {
       EmacsImage **newBimgs
        = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
-      bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
+      memset (newBimgs, 0, max_used_fringe_bitmap * sizeof (EmacsImage *));
 
       if (nBimgs)
         {
-          bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
+          memcpy (newBimgs, bimgs, nBimgs * sizeof (EmacsImage *));
           xfree (bimgs);
         }
 
@@ -2349,7 +2256,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);
@@ -2405,8 +2312,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;
@@ -2422,7 +2328,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;
@@ -2435,7 +2340,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
@@ -2453,7 +2358,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);
 
@@ -2462,7 +2367,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);
 }
 
@@ -2709,9 +2614,9 @@ ns_dumpglyphs_box_or_relief (struct glyph_string *s)
     r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
                         FRAME_PIXEL_WIDTH (s->f));
 
-  if (s->face->box == FACE_SIMPLE_BOX)
+  /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
+  if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
     {
-      xassert (s->face->box_color != nil);
       ns_draw_box (r, abs (thickness),
                    ns_lookup_indexed_color (face->box_color, s->f),
                   left_p, right_p);
@@ -2806,6 +2711,7 @@ ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
   int th;
   char raised_p;
   NSRect br;
+  struct face *face;
 
   NSTRACE (ns_dumpglyphs_image);
 
@@ -2825,8 +2731,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)
@@ -2884,10 +2799,78 @@ ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
       r.size.width = s->slice.width + 2*th-1;
       r.size.height = s->slice.height + 2*th-1;
       ns_draw_relief (r, th, raised_p,
-                     s->slice.y == 0,
-                     s->slice.y + s->slice.height == s->img->height,
-                     s->slice.x == 0,
-                     s->slice.x + s->slice.width == s->img->width, s);
+                      s->slice.y == 0,
+                      s->slice.y + s->slice.height == s->img->height,
+                      s->slice.x == 0,
+                      s->slice.x + s->slice.width == s->img->width, s);
+    }
+}
+
+
+static void
+ns_dumpglyphs_stretch (struct glyph_string *s)
+{
+  NSRect r[2];
+  int n, i;
+  struct face *face;
+
+  if (!s->background_filled_p)
+    {
+      n = ns_get_glyph_string_clip_rect (s, r);
+      *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
+
+      for (i=0; i<n; i++)
+        {
+          if (!s->row->full_width_p)
+            {
+              /* truncate to avoid overwriting fringe and/or scrollbar */
+              int overrun = max (0, (s->x + s->background_width)
+                                  - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
+                                    - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
+              r[i].size.width -= overrun;
+
+              /* XXX: Try to work between problem where a stretch glyph on
+                 a partially-visible bottom row will clear part of the
+                 modeline, and another where list-buffers headers and similar
+                 rows erroneously have visible_height set to 0.  Not sure
+                 where this is coming from as other terms seem not to show. */
+              r[i].size.height = min (s->height, s->row->visible_height);
+            }
+
+          /* expand full-width rows over internal borders */
+          else
+            {
+              r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
+                                      FRAME_PIXEL_WIDTH (s->f));
+            }
+
+          /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
+             overwriting cursor (usually when cursor on a tab) */
+          if (s->hl == DRAW_CURSOR)
+            {
+              r[i].origin.x += s->width;
+              r[i].size.width -= s->width;
+            }
+        }
+
+      ns_focus (s->f, r, n);
+
+      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);
+      s->background_filled_p = 1;
     }
 }
 
@@ -2915,10 +2898,17 @@ ns_draw_glyph_string (struct glyph_string *s)
           width += next->width, next = next->next)
        if (next->first_glyph->type != IMAGE_GLYPH)
           {
-            n = ns_get_glyph_string_clip_rect (s->next, r);
-            ns_focus (s->f, r, n);
-            ns_maybe_dumpglyphs_background (s->next, 1);
-            ns_unfocus (s->f);
+            if (next->first_glyph->type != STRETCH_GLYPH)
+              {
+                n = ns_get_glyph_string_clip_rect (s->next, r);
+                ns_focus (s->f, r, n);
+                ns_maybe_dumpglyphs_background (s->next, 1);
+                ns_unfocus (s->f);
+              }
+            else
+              {
+                ns_dumpglyphs_stretch (s->next);
+              }
             next->num_clips = 0;
           }
     }
@@ -2946,48 +2936,7 @@ ns_draw_glyph_string (struct glyph_string *s)
       break;
 
     case STRETCH_GLYPH:
-      if (!s->background_filled_p)
-        {
-          *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
-
-          if (!s->row->full_width_p)
-            {
-              /* truncate to avoid overwriting fringe and/or scrollbar */
-              int overrun = max (0, (s->x + s->background_width)
-                                 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
-                                    - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
-              r[0].size.width -= overrun;
-
-              /* XXX: Try to work between problem where a stretch glyph on
-                  a partially-visible bottom row will clear part of the
-                  modeline, and another where list-buffers headers and similar
-                  rows erroneously have visible_height set to 0.  Not sure
-                  where this is coming from as other terms seem not to show. */
-              r[0].size.height = min (s->height, s->row->visible_height);
-            }
-
-          /* expand full-width rows over internal borders */
-          else
-            {
-              r[0] = ns_fix_rect_ibw (r[0], FRAME_INTERNAL_BORDER_WIDTH (s->f),
-                                     FRAME_PIXEL_WIDTH (s->f));
-            }
-
-          /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
-             overwriting cursor (usually when cursor on a tab) */
-          if (s->hl == DRAW_CURSOR)
-            {
-              r[0].origin.x += s->width;
-              r[0].size.width -= s->width;
-            }
-
-          ns_focus (s->f, r, 1);
-          [ns_lookup_indexed_color (NS_FACE_BACKGROUND
-               (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
-          NSRectFill (r[0]);
-          ns_unfocus (s->f);
-          s->background_filled_p = 1;
-        }
+      ns_dumpglyphs_stretch (s);
       break;
 
     case CHAR_GLYPH:
@@ -2998,7 +2947,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);
 
@@ -3107,23 +3056,24 @@ 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)
     {
       interrupt_input_pending = 1;
+#ifdef SYNC_INPUT
+      pending_signals = 1;
+#endif
       return -1;
     }
 
   interrupt_input_pending = 0;
-  BLOCK_INPUT;
-
-#ifdef COCOA_EXPERIMENTAL_CTRL_G
-  /* causes Feval to abort; unclear on why this isn't in calling code */
-  ++handling_signal;
+#ifdef SYNC_INPUT
+  pending_signals = pending_atimers;
 #endif
 
+  BLOCK_INPUT;
   n_emacs_events_pending = 0;
   EVENT_INIT (ev);
   emacs_event = &ev;
@@ -3156,15 +3106,15 @@ ns_read_socket (struct terminal *terminal, int expected,
          to ourself, otherwise [NXApp run] will never exit.  */
       send_appdefined = YES;
 
-      /* TODO: from termhooks.h: */
-      /* XXX Please note that a non-zero value of EXPECTED only means that
-     there is available input on at least one of the currently opened
-     terminal devices -- but not necessarily on this device.
-     Therefore, in most cases EXPECTED should be simply ignored. */
-      /* However, if in ns_select, this is called from gobble_input, which
-         appears to set it correctly for our purposes, and always assuming
-         !expected causes 100% CPU usage. */
-      if (!inNsSelect || !expected)
+      /* If called via ns_select, this is called once with expected=1,
+         because we expect either the timeout or file descriptor activity.
+         In this case the first event through will either be real input or
+         one of these.  read_avail_input() then calls once more with expected=0
+         and in that case we need to return quickly if there is nothing.
+         If we're being called outside of that, it's also OK to return quickly
+         after one iteration through the event loop, since other terms do
+         this and emacs expects it. */
+      if (!(inNsSelect && expected))
         {
           /* Post an application defined event on the event queue.  When this is
              received the [NXApp run] will return, thus having processed all
@@ -3178,11 +3128,8 @@ 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;
 }
 
@@ -3199,7 +3146,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);
@@ -3242,9 +3189,13 @@ ns_select (int nfds, fd_set *readfds, fd_set *writefds,
                retain];
 
   /* Let Application dispatch events until it receives an event of the type
-       NX_APPDEFINED, which should only be sent by timeout_handler.  */
+     NX_APPDEFINED, which should only be sent by timeout_handler.
+     We tell read_avail_input() that input is "expected" because we do expect
+     either the timeout or fd handler to fire, and if they don't, the original
+     call from process.c that got us here expects us to wait until some input
+     comes. */
   inNsSelect = 1;
-  gobble_input (timeout ? 1 : 0);
+  gobble_input (1);
   ev = last_appdefined_event;
   inNsSelect = 0;
 
@@ -3526,24 +3477,6 @@ static Lisp_Object ns_mod_to_lisp (int m)
 }
 
 
-static void
-ns_set_default_prefs ()
-/* --------------------------------------------------------------------------
-      Initialize preference variables to defaults
-   -------------------------------------------------------------------------- */
-{
-  ns_alternate_modifier = Qmeta;
-  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;
-}
-
-
 static void
 ns_default (const char *parameter, Lisp_Object *result,
            Lisp_Object yesval, Lisp_Object noval,
@@ -3731,25 +3664,12 @@ ns_create_terminal (struct ns_display_info *dpyinfo)
 }
 
 
-void
-ns_initialize ()
-/* --------------------------------------------------------------------------
-   Mainly vestigial under NS now that ns_create_terminal () does most things.
-   -------------------------------------------------------------------------- */
-{
-  baud_rate = 38400;
-  Fset_input_interrupt_mode (Qt);
-}
-
-
 struct ns_display_info *
 ns_term_init (Lisp_Object display_name)
 /* --------------------------------------------------------------------------
      Start the Application and get things rolling.
    -------------------------------------------------------------------------- */
 {
-  extern Lisp_Object Fset_input_mode (Lisp_Object, Lisp_Object,
-                                     Lisp_Object, Lisp_Object);
   struct terminal *terminal;
   struct ns_display_info *dpyinfo;
   static int ns_initialized = 0;
@@ -3764,7 +3684,8 @@ ns_term_init (Lisp_Object display_name)
 
   if (!ns_initialized)
     {
-      ns_initialize ();
+      baud_rate = 38400;
+      Fset_input_interrupt_mode (Qnil);
       ns_initialized = 1;
     }
 
@@ -3786,7 +3707,7 @@ ns_term_init (Lisp_Object display_name)
                                              name: nil object: nil]; */
 
   dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
-  bzero (dpyinfo, sizeof (struct ns_display_info));
+  memset (dpyinfo, 0, sizeof (struct ns_display_info));
 
   ns_initialize_display_info (dpyinfo);
   terminal = ns_create_terminal (dpyinfo);
@@ -3818,50 +3739,22 @@ ns_term_init (Lisp_Object display_name)
 
   UNBLOCK_INPUT; 
 
-  /* Read various user defaults. */
-  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);
+  if (!inhibit_x_resources)
+    {
       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);
     }
 
-  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"];
 
@@ -3911,6 +3804,8 @@ ns_term_init (Lisp_Object display_name)
 
   delete_keyboard_wait_descriptor (0);
 
+  ns_app_name = [[NSProcessInfo processInfo] processName];
+
 /* Set up OS X app menu */
 #ifdef NS_IMPL_COCOA
   {
@@ -3939,7 +3834,6 @@ ns_term_init (Lisp_Object display_name)
                           keyEquivalent: @""
                                 atIndex: 4];
     [appMenu setSubmenu: svcsMenu forItem: item];
-/*    [svcsMenu setSupercell: item]; */
     [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
     [appMenu insertItemWithTitle: @"Hide Emacs"
                           action: @selector (hide:)
@@ -3956,7 +3850,7 @@ ns_term_init (Lisp_Object display_name)
                    keyEquivalent: @"q"
                          atIndex: 9];
 
-    item = [mainMenu insertItemWithTitle: @"Emacs"
+    item = [mainMenu insertItemWithTitle: ns_app_name                       
                                   action: @selector (menuDown:)
                            keyEquivalent: @""
                                  atIndex: 0];
@@ -3990,7 +3884,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
@@ -4020,13 +3913,14 @@ 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];
   NSWindow *window = [theEvent window];
 /*  NSTRACE (sendEvent); */
-/*fprintf (stderr, "received event of type %d\n", [theEvent type]); */
+/*fprintf (stderr, "received event of type %d\t%d\n", type);*/
 
   if (type == NSCursorUpdate && window == nil)
     {
@@ -4064,8 +3958,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];
@@ -4074,9 +3979,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);
 }
 
 
@@ -4087,7 +3998,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);
@@ -4103,7 +4014,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 */
@@ -4131,37 +4042,57 @@ ns_term_shutdown (int sig)
 }
 
 
+/* Termination sequences:
+    C-x C-c:
+    Cmd-Q:
+    MenuBar | File | Exit:
+    Select Quit from App menubar:
+        -terminate
+       KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
+       ns_term_shutdown()
+
+    Select Quit from Dock menu:
+    Logout attempt:
+        -appShouldTerminate
+          Cancel -> Nothing else
+          Accept ->
+         
+         -terminate
+         KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
+         ns_term_shutdown()
+
+*/
+
 - (void) terminate: (id)sender
 {
-  BLOCK_INPUT;
-  if (ns_shutdown_properly)
-    [super terminate: sender];
-  else
-    {
-/*    Fkill_emacs (Qnil); */
-      ns_shutdown_properly = YES;
-      Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
-    }
-  UNBLOCK_INPUT;
+  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);
 }
 
 
 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
 {
-  if (ns_shutdown_properly)
+  int ret;
+
+  if (NILP (ns_confirm_quit)) //   || ns_shutdown_properly  --> TO DO
     return NSTerminateNow;
 
-  Lisp_Object contents = list3 (build_string ("Exit requested.  Would you like to Save Buffers and Exit, or Cancel the request?"),
-      Fcons (build_string ("Cancel"), Qnil),
-      Fcons (build_string ("Save and Exit"), Qt));
-  Lisp_Object res = ns_popup_dialog (Qt, contents, Qnil);
-fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
-  if (EQ (res, Qt))
-    {
-      Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
-      return NSTerminateNow;
-    }
-  return NSTerminateCancel;
+    ret = NSRunAlertPanel(ns_app_name,
+                          [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)
+        return NSTerminateNow;
+    else if (ret == NSAlertAlternateReturn)
+        return NSTerminateCancel;
+    return NSTerminateNow;  /* just in case */
 }
 
 
@@ -4197,11 +4128,7 @@ fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
   while ((file = [files nextObject]) != nil)
     [ns_pending_files addObject: file];
 
-/* TODO: when GNUstep implements this (and we require that version of
-         GNUstep), remove. */
-#ifndef NS_IMPL_GNUSTEP
   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
-#endif /* !NS_IMPL_GNUSTEP */
 
 }
 
@@ -4246,8 +4173,6 @@ fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
   ns_send_appdefined (-2);
 }
 
-extern void update_window_cursor (struct window *w, int on);
-
 - (void)fd_handler: (NSTimer *) fdEntry
 /* --------------------------------------------------------------------------
      Check data waiting on file descriptors and terminate if so
@@ -4299,7 +4224,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]);
@@ -4355,7 +4280,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;
 
@@ -4414,17 +4339,18 @@ 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]]
+     /* we must avoid an infinite loop here. */
+     && (EmacsView *)[[theEvent window] delegate] != self)
    {
-     /* 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;
    }
 
@@ -4571,12 +4497,14 @@ extern void update_window_cursor (struct window *w, int on);
 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
    decided not to send key-down for.
    See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
+   This only applies on Tiger and earlier.
    If it matches one of these, send it on to keyDown. */
 -(void)keyUp: (NSEvent *)theEvent
 {
   int flags = [theEvent modifierFlags];
   int code = [theEvent keyCode];
-  if (code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
+  if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
+      code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
     {
       if (NS_KEYLOG)
         fprintf (stderr, "keyUp: passed test");
@@ -4590,7 +4518,9 @@ extern void update_window_cursor (struct window *w, int on);
 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
 
 
-/* <NSTextInput>: called through when done composing */
+/* <NSTextInput>: called when done composing;
+   NOTE: also called when we delete over working text, followed immed.
+         by doCommandBySelector: deleteBackward: */
 - (void)insertText: (id)aString
 {
   int code;
@@ -4645,20 +4575,9 @@ extern void update_window_cursor (struct window *w, int on);
   workingText = [str copy];
   ns_working_text = build_string ([workingText UTF8String]);
 
-  /* if in "echo area", not true minibuffer, can't show chars in interactive
-     mode, so call using eval; otherwise we send a key event, which was the
-     original way this was done */
-  if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
-    {
-      Feval (Fcons (intern ("ns-echo-working-text"), Qnil));
-      ns_send_appdefined (-1);
-    }
-  else
-    {
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
-      emacs_event->code = KEY_NS_INSERT_WORKING_TEXT;
-      EV_TRAILER ((id)nil);
-    }
+  emacs_event->kind = NS_TEXT_EVENT;
+  emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
+  EV_TRAILER ((id)nil);
 }
 
 
@@ -4668,7 +4587,7 @@ extern void update_window_cursor (struct window *w, int on);
   if (workingText == nil)
     return;
   if (NS_KEYLOG)
-    fprintf (stderr, "deleteWorkingText len =%d\n", [workingText length]);
+    NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
   [workingText release];
   workingText = nil;
   processingCompose = NO;
@@ -4676,18 +4595,10 @@ extern void update_window_cursor (struct window *w, int on);
   if (!emacs_event)
     return;
 
-  if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
-    {
-      Feval (Fcons (intern ("ns-unecho-working-text"), Qnil));
-      ns_send_appdefined (-1);
-    }
-  else
-    {
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
-      emacs_event->code = KEY_NS_DELETE_WORKING_TEXT;
-      EV_TRAILER ((id)nil);
-    }
- }
+  emacs_event->kind = NS_TEXT_EVENT;
+  emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
+  EV_TRAILER ((id)nil);
+}
 
 
 - (BOOL)hasMarkedText
@@ -4695,6 +4606,7 @@ extern void update_window_cursor (struct window *w, int on);
   return workingText != nil;
 }
 
+
 - (NSRange)markedRange
 {
   NSRange rng = workingText != nil
@@ -4704,6 +4616,7 @@ extern void update_window_cursor (struct window *w, int on);
   return rng;
 }
 
+
 - (void)unmarkText
 {
   if (NS_KEYLOG)
@@ -4712,6 +4625,7 @@ extern void update_window_cursor (struct window *w, int on);
   processingCompose = NO;
 }
 
+
 /* used to position char selection windows, etc. */
 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
 {
@@ -4733,12 +4647,12 @@ extern void update_window_cursor (struct window *w, int on);
   return rect;
 }
 
-- (NSInteger)conversationIdentifier
+
+- (long)conversationIdentifier
 {
-  return (NSInteger)self;
+  return (long)self;
 }
 
-/* TODO: below here not yet implemented correctly, but may not be needed */
 
 - (void)doCommandBySelector: (SEL)aSelector
 {
@@ -4772,7 +4686,7 @@ extern void update_window_cursor (struct window *w, int on);
   return NSMakeRange (NSNotFound, 0);
 }
 
-- (unsigned int)characterIndexForPoint: (NSPoint)thePoint
+- (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
 {
   if (NS_KEYLOG)
     NSLog (@"characterIndexForPoint request");
@@ -4980,16 +4894,16 @@ extern void update_window_cursor (struct window *w, int on);
   rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
 #ifdef NS_IMPL_GNUSTEP
       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
-        - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
+        - FRAME_TOOLBAR_HEIGHT (emacsframe));
 #else
       - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
-        - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
+        - FRAME_TOOLBAR_HEIGHT (emacsframe));
 #endif
   if (rows < MINHEIGHT)
     rows = MINHEIGHT;
   frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
                        + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
-                       + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
+                       + FRAME_TOOLBAR_HEIGHT (emacsframe);
 #ifdef NS_IMPL_COCOA
   {
     /* this sets window title to have size in it; the wm does this under GS */
@@ -5052,17 +4966,15 @@ extern void update_window_cursor (struct window *w, int on);
     }
 #endif /* NS_IMPL_COCOA */
 
+  /* Avoid loop under GNUstep due to call at beginning of this function.
+     (x_set_window_size causes a resize which causes
+     a "windowDidResize" which calls x_set_window_size).  */
+#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
 }
 
 
@@ -5155,6 +5067,7 @@ extern void update_window_cursor (struct window *w, int on);
   r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
                  FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
   [self initWithFrame: r];
+  [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
 
   FRAME_NS_VIEW (f) = self;
   emacsframe = f;
@@ -5201,7 +5114,7 @@ extern void update_window_cursor (struct window *w, int on);
   [toggleButton setTarget: self];
   [toggleButton setAction: @selector (toggleToolbar: )];
 #endif
-  FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
+  FRAME_TOOLBAR_HEIGHT (f) = 0;
 
   tem = f->icon_name;
   if (!NILP (tem))
@@ -5238,7 +5151,6 @@ extern void update_window_cursor (struct window *w, int on);
   NSWindow *win = [self window];
   NSRect r = [win frame];
   NSScreen *screen = [win screen];
-  NSRect sr = [screen frame];
 
   NSTRACE (windowDidMove);
 
@@ -5246,24 +5158,57 @@ extern void update_window_cursor (struct window *w, int on);
     return;
   if (screen != nil)
     {
-      emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
-      emacsframe->top_pos = sr.size.height -
-        (r.origin.y + r.size.height); /* + sr.origin.y; */
+      emacsframe->left_pos = r.origin.x;
+      emacsframe->top_pos =
+        [screen frame].size.height - (r.origin.y + r.size.height);
     }
 }
 
-#ifdef NS_IMPL_COCOA
-/* if we don't do this manually, the window will resize but not move */
+
+/* Called AFTER method below, but before our windowWillResize call there leads
+   to windowDidResize -> x_set_window_size.  Update emacs' notion of frame
+   location so set_window_size moves the frame. */
 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
 {
-  [[self window] setFrame: newFrame display: NO];
+  NSTRACE (windowShouldZoom);
+  emacsframe->left_pos = (int)newFrame.origin.x;
+  emacsframe->top_pos = [[sender screen] frame].size.height
+                            - (newFrame.origin.y+newFrame.size.height);
   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];
+  static NSRect ns_userRect = { 0, 0, 0, 0 };
+
+  NSTRACE (windowWillUseStandardFrame);
+
+  if (abs (defaultFrame.size.height - result.size.height)
+      > FRAME_LINE_HEIGHT (emacsframe))
+    {
+      /* first click */
+      ns_userRect = result;
+      result.size.height = defaultFrame.size.height;
+      result.origin.y = defaultFrame.origin.y;
+    }
+  else
+    {
+      if (abs (defaultFrame.size.width - result.size.width)
+          > FRAME_COLUMN_WIDTH (emacsframe))
+        result = defaultFrame;  /* second click */
+      else
+        result = ns_userRect.size.height ? ns_userRect : result;  /* restore */
+    }
+
+  [self windowWillResize: sender toSize: result.size];
+  return result;
+}
 
 
 - (void)windowDidDeminiaturize: sender
@@ -5271,8 +5216,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)
@@ -5303,6 +5248,7 @@ extern void update_window_cursor (struct window *w, int on);
     return;
 
   emacsframe->async_iconified = 1;
+  emacsframe->async_visible = 0;
 
   if (emacs_event)
     {
@@ -5376,7 +5322,7 @@ extern void update_window_cursor (struct window *w, int on);
     return self;
 
   /* send first event (for some reason two needed) */
-  theEvent =[[self window] currentEvent];
+  theEvent = [[self window] currentEvent];
   emacs_event->kind = TOOL_BAR_EVENT;
   XSETFRAME (emacs_event->arg, emacsframe);
   EV_TRAILER (theEvent);
@@ -5393,11 +5339,13 @@ extern void update_window_cursor (struct window *w, int on);
 
 - toggleToolbar: (id)sender
 {
-  Lisp_Object lispFrame;
-  XSETFRAME (lispFrame, emacsframe);
-  Feval (Fcons (intern ("ns-toggle-toolbar"), Fcons (lispFrame, Qnil)));
-  SET_FRAME_GARBAGED (emacsframe);
-  ns_send_appdefined (-1);
+  if (!emacs_event)
+    return self;
+
+  emacs_event->kind = NS_NONKEY_EVENT;
+  emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
+  EV_TRAILER ((id)nil);
+  return self;
 }
 
 
@@ -5408,25 +5356,27 @@ 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;
+  */
 }
 
 
 /* NSDraggingDestination protocol methods.  Actually this is not really a
    protocol, but a category of Object.  O well...  */
 
--(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
+-(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
 {
   NSTRACE (draggingEntered);
   return NSDragOperationGeneric;
@@ -5473,7 +5423,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);
@@ -5494,7 +5444,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);
@@ -5511,7 +5461,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);
@@ -5523,7 +5473,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);
@@ -5543,7 +5493,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);
@@ -5575,6 +5525,28 @@ extern void update_window_cursor (struct window *w, int on);
 }
 
 
+/* The next two methods are part of NSServicesRequests informal protocol,
+   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 (under strange circumstances): bug#1435.
+   So let's at least stub them out until further investigation can be done. */
+
+- (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
+{
+  /* we could call ns_string_from_pasteboard(pboard) here but then it should
+     be written into the buffer in place of the existing selection..
+     ordinary service calls go through functions defined in ns-win.el */
+  return NO;
+}
+
+- (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
+{
+  /* supposed to write for as many of types as we are able */
+  return NO;
+}
+
+
 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
    (gives a miniaturized version of the window); currently we use the latter for
    frames whose active buffer doesn't correspond to any file
@@ -5689,7 +5661,7 @@ extern void update_window_cursor (struct window *w, int on);
 #define SCROLL_BAR_FIRST_DELAY 0.5
 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
 
-+ (float) scrollerWidth
++ (CGFloat) scrollerWidth
 {
   /* TODO: if we want to allow variable widths, this is the place to do it,
            however neither GNUstep nor Cocoa support it very well */
@@ -5707,8 +5679,13 @@ extern void update_window_cursor (struct window *w, int on);
   [self setEnabled: YES];
 
   /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
-     locked against the right, top and bottom edges. */
+     locked against the top and bottom edges, and right edge on OS X, where
+     scrollers are on right. */
+#ifdef NS_IMPL_GNUSTEP
+  [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
+#else
   [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
+#endif
 
   win = nwin;
   condemned = NO;
@@ -5829,9 +5806,6 @@ extern void update_window_cursor (struct window *w, int on);
       por = (float)portion/whole;
       [self setFloatValue: pos knobProportion: por];
     }
-#ifdef NS_IMPL_GNUSTEP
-  [self display];
-#endif
   return self;
 }
 
@@ -5932,7 +5906,8 @@ extern void update_window_cursor (struct window *w, int on);
     case NSScrollerKnobSlot:  /* GNUstep-only */
       last_hit_part = scroll_bar_move_ratio; break;
     default:  /* NSScrollerNoPart? */
-      fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
+      fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
+               (long) part);
       return;
     }
 
@@ -5942,7 +5917,7 @@ extern void update_window_cursor (struct window *w, int on);
 
       /* set a timer to repeat, as we can't let superclass do this modally */
       scroll_repeat_entry
-       = [[NSTimer scheduledTimerWithTimeInterval: 0.5
+       = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
                                             target: self
                                           selector: @selector (repeatScroll:)
                                           userInfo: 0
@@ -6057,199 +6032,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)];
-#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;
-  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
-{
-  Feval (Fcons (intern ("info"),
-                Fcons (build_string ("(emacs)Mac / GNUstep Customization"),
-                       Qnil)));
-  SET_FRAME_GARBAGED (frame);
-  ns_send_appdefined (-1);
-}
-
-
-- (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 */
-
-
-
 
 /* ==========================================================================
 
@@ -6356,6 +6138,23 @@ void
 syms_of_nsterm ()
 {
   NSTRACE (syms_of_nsterm);
+
+  ns_antialias_threshold = 10.0;
+
+  /* from 23+ we need to tell emacs what modifiers there are.. */
+  DEFSYM (Qmodifier_value, "modifier-value");
+  DEFSYM (Qalt, "alt");
+  DEFSYM (Qhyper, "hyper");
+  DEFSYM (Qmeta, "meta");
+  DEFSYM (Qsuper, "super");
+  DEFSYM (Qcontrol, "control");
+  DEFSYM (Qnone, "none");
+  Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
+  Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
+  Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
+  Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
+  Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
+
   DEFVAR_LISP ("ns-input-file", &ns_input_file,
               "The file specified in the last NS event.");
   ns_input_file =Qnil;
@@ -6397,35 +6196,32 @@ syms_of_nsterm ()
 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
 Set to none means that the alternate / option key is not interpreted by Emacs\n\
 at all, allowing it to be used at a lower level for accented character entry.");
+  ns_alternate_modifier = Qmeta;
 
   DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
                "This variable describes the behavior of the command key.\n\
 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
+  ns_command_modifier = Qsuper;
 
   DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
                "This variable describes the behavior of the control key.\n\
 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
+  ns_control_modifier = Qcontrol;
 
   DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
                "This variable describes the behavior of the function key (on laptops).\n\
 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.)");
+  ns_function_modifier = Qnone;
 
   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.");
+  ns_antialias_text = Qt;
 
-  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.");
+  ns_confirm_quit = Qnil;
 
   staticpro (&ns_display_name_list);
   ns_display_name_list = Qnil;
@@ -6433,19 +6229,6 @@ or shrunk (negative).  Zero (the default) means standard line height.\n\
   staticpro (&last_mouse_motion_frame);
   last_mouse_motion_frame = Qnil;
 
-  /* from 23+ we need to tell emacs what modifiers there are.. */
-  Qmodifier_value = intern ("modifier-value");
-  Qalt = intern ("alt");
-  Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
-  Qhyper = intern ("hyper");
-  Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
-  Qmeta = intern ("meta");
-  Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
-  Qsuper = intern ("super");
-  Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
-  Qcontrol = intern ("control");
-  Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
-
   /* TODO: move to common code */
   DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
               doc: /* If not nil, Emacs uses toolkit scroll bars.  */);