]> 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 61fe21ba389fe9bbaaf4a0c2014e74369c2354d4..0089dc3a415129ccefbcf79b52e6fe0700f16f72 100644 (file)
@@ -1,5 +1,5 @@
 /* NeXT/Open/GNUstep / MacOSX communication module.
-   Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008
+   Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009
      Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
@@ -25,12 +25,16 @@ MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
 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 <math.h>
 #include <sys/types.h>
 #include <time.h>
+#include <signal.h>
 #include <unistd.h>
 
-#include "config.h"
 #include "lisp.h"
 #include "blockinput.h"
 #include "sysselect.h"
@@ -66,19 +70,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)
-
 /* 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... */
@@ -119,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. */
@@ -145,11 +145,13 @@ Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
 
 
-EmacsPrefsController *prefsController;
+/* 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. */
 
-/* Defaults managed through the OpenStep defaults system.  These pertain to
-   the NS interface specifically.  Although a customization group could be
-   created, it's more natural to manage them via defaults. */
+/* 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. */
@@ -167,18 +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 the rate at which to blink the cursor.
-   YES indicates 0.5, NO indicates no blinking. */
-Lisp_Object ns_cursor_blink_rate;
-
-/* Used for liason with core emacs cursor-blink-mode. */
-Lisp_Object ns_cursor_blink_mode;
-
-/* 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,9 +182,10 @@ 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. */
+Lisp_Object ns_confirm_quit;
 
 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
 
@@ -215,6 +206,7 @@ static int ns_window_num =0;
 static NSRect uRect;
 static BOOL gsaved = NO;
 BOOL ns_in_resize = NO;
+static BOOL ns_fake_keydown = NO;
 int ns_tmp_flags; /* FIXME */
 struct nsfont_info *ns_tmp_font; /* FIXME */
 /*static int debug_lock = 0; */
@@ -234,13 +226,11 @@ static BOOL send_appdefined = YES;
 static NSEvent *last_appdefined_event = 0;
 static NSTimer *timed_entry = 0;
 static NSTimer *fd_entry = nil;
-static NSTimer *cursor_blink_entry = nil;
 static NSTimer *scroll_repeat_entry = nil;
 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;
@@ -267,14 +257,18 @@ static BOOL inNsSelect = 0;
 #define EV_UDMODIFIERS(e)                                      \
     ((([e type] == NSLeftMouseDown) ? down_modifier : 0)       \
      | (([e type] == NSRightMouseDown) ? down_modifier : 0)    \
+     | (([e type] == NSOtherMouseDown) ? down_modifier : 0)    \
      | (([e type] == NSLeftMouseDragged) ? down_modifier : 0)  \
      | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
+     | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
      | (([e type] == NSLeftMouseUp)   ? up_modifier   : 0)     \
-     | (([e type] == NSRightMouseUp)   ? up_modifier   : 0))
+     | (([e type] == NSRightMouseUp)   ? up_modifier   : 0)    \
+     | (([e type] == NSOtherMouseUp)   ? up_modifier   : 0))
 
 #define EV_BUTTON(e)                                                         \
     ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 :    \
-      (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : 1)
+      (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
+     [e buttonNumber] - 1)
 
 /* Convert the time field to a timestamp in milliseconds. */
 #ifdef NS_IMPL_GNUSTEP
@@ -288,8 +282,7 @@ static BOOL inNsSelect = 0;
    methods.  Maybe it should even be a function.  */
 #define EV_TRAILER(e)                                         \
   {                                                           \
-  XSETFRAME (emacs_event->frame_or_window, [NSApp isActive] ? \
-             emacsframe : SELECTED_FRAME ());                 \
+  XSETFRAME (emacs_event->frame_or_window, emacsframe);       \
   if (e) emacs_event->timestamp = EV_TIMESTAMP (e);           \
   n_emacs_events_pending++;                                   \
   kbd_buffer_store_event_hold (emacs_event, q_event_ptr);     \
@@ -297,9 +290,12 @@ static BOOL inNsSelect = 0;
   ns_send_appdefined (-1);                                    \
   }
 
+void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
+
 /* TODO: get rid of need for these forward declarations */
-static void ns_condemn_scroll_bars (struct frame *f),
-            ns_judge_scroll_bars (struct frame *f);
+static void ns_condemn_scroll_bars (struct frame *f);
+static void ns_judge_scroll_bars (struct frame *f);
+void x_set_frame_alpha (struct frame *f);
 
 /* unused variables needed for compatibility reasons */
 int x_use_underline_position_properties, x_underline_at_descent_line;
@@ -418,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. */
     }
 }
 
@@ -549,12 +547,11 @@ static void
 ns_update_begin (struct frame *f)
 /* --------------------------------------------------------------------------
    Prepare for a grouped sequence of drawing calls
-   23: external (RIF) call; now split w/ and called before update_window_begin
+   external (RIF) call; whole frame, called before update_window_begin
    -------------------------------------------------------------------------- */
 {
   NSView *view = FRAME_NS_VIEW (f);
   NSTRACE (ns_update_begin);
-/*fprintf (stderr, "\\%p\n", f); */
 
   ns_updating_frame = f;
   [view lockFocus];
@@ -569,7 +566,7 @@ static void
 ns_update_window_begin (struct window *w)
 /* --------------------------------------------------------------------------
    Prepare for a grouped sequence of drawing calls
-   23: external (RIF) call; now split with and called after update_begin
+   external (RIF) call; for one window, called after update_begin
    -------------------------------------------------------------------------- */
 {
   struct frame *f = XFRAME (WINDOW_FRAME (w));
@@ -603,7 +600,7 @@ ns_update_window_end (struct window *w, int cursor_on_p,
                       int mouse_face_overwritten_p)
 /* --------------------------------------------------------------------------
    Finished a grouped sequence of drawing calls
-   23: external (RIF) call; now split with and called before update_window_end
+   external (RIF) call; for one window called before update_end
    -------------------------------------------------------------------------- */
 {
   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
@@ -642,7 +639,7 @@ static void
 ns_update_end (struct frame *f)
 /* --------------------------------------------------------------------------
    Finished a grouped sequence of drawing calls
-   23: external (RIF) call; now split with and called after update_window_end
+   external (RIF) call; for whole frame, called after update_window_end
    -------------------------------------------------------------------------- */
 {
   NSView *view = FRAME_NS_VIEW (f);
@@ -671,7 +668,7 @@ ns_update_end (struct frame *f)
 static void
 ns_flush (struct frame *f)
 /* --------------------------------------------------------------------------
-   23: external (RIF) call
+   external (RIF) call
    NS impl is no-op since currently we flush in ns_update_end and elsewhere
    -------------------------------------------------------------------------- */
 {
@@ -690,7 +687,7 @@ ns_focus (struct frame *f, NSRect *r, int n)
      the entire window.
    -------------------------------------------------------------------------- */
 {
-  NSTRACE (ns_focus);
+//  NSTRACE (ns_focus);
 #ifdef NS_IMPL_GNUSTEP
   NSRect u;
     if (n == 2)
@@ -744,7 +741,7 @@ ns_focus (struct frame *f, NSRect *r, int n)
     }
 #endif
 
-  /*23: clipping */
+  /* clipping */
   if (r)
     {
       [[NSGraphicsContext currentContext] saveGraphicsState];
@@ -763,7 +760,7 @@ ns_unfocus (struct frame *f)
      Internal: Remove focus on given frame
    -------------------------------------------------------------------------- */
 {
-  NSTRACE (ns_unfocus);
+//  NSTRACE (ns_unfocus);
 
   if (gsaved)
     {
@@ -787,7 +784,7 @@ ns_unfocus (struct frame *f)
 static void
 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
 /* --------------------------------------------------------------------------
-     23: Internal (but parallels other terms): Focus drawing on given row
+     Internal (but parallels other terms): Focus drawing on given row
    -------------------------------------------------------------------------- */
 {
   struct frame *f = XFRAME (WINDOW_FRAME (w));
@@ -846,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);
@@ -902,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;
 }
 
@@ -964,17 +963,16 @@ ns_frame_rehighlight (struct frame *frame)
   if (dpyinfo->x_highlight_frame &&
          dpyinfo->x_highlight_frame != old_highlight)
     {
-      /* as of 20080602 the lower and raise are superfluous */
       if (old_highlight)
-        {
-          /*ns_lower_frame (old_highlight); */
+       {
           x_update_cursor (old_highlight, 1);
-        }
+         x_set_frame_alpha (old_highlight);
+       }
       if (dpyinfo->x_highlight_frame)
-        {
-          /*ns_raise_frame (dpyinfo->x_highlight_frame); */
+       {
           x_update_cursor (dpyinfo->x_highlight_frame, 1);
-        }
+          x_set_frame_alpha (dpyinfo->x_highlight_frame);
+       }
     }
 }
 
@@ -990,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);
+    }
 }
 
 
@@ -1004,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;
 }
 
 
@@ -1154,22 +1157,22 @@ 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;
 
@@ -1234,12 +1237,14 @@ x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
 }
 
 
+
 /* ==========================================================================
 
     Color management
 
    ========================================================================== */
 
+
 NSColor *
 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
 {
@@ -1293,7 +1298,6 @@ ns_index_color (NSColor *color, struct frame *f)
                                    color_table->size * sizeof (NSColor *));
         }
       idx = color_table->avail++;
-      index = [NSNumber numberWithUnsignedInt: idx];
     }
 
   color_table->colors[idx] = color;
@@ -1306,10 +1310,26 @@ ns_index_color (NSColor *color, struct frame *f)
 void
 ns_free_indexed_color (unsigned long idx, struct frame *f)
 {
-  struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
+  struct ns_color_table *color_table;
   NSColor *color;
-  if (!idx)
+  NSNumber *index;
+
+  if (!f)
+    return;
+
+  color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
+
+  if (idx <= 0 || idx >= color_table->size) {
+    message1("ns_free_indexed_color: Color index out of range.\n");
+    return;
+  }
+
+  index = [NSNumber numberWithUnsignedInt: idx];
+  if ([color_table->empty_indices containsObject: index]) {
+    message1("ns_free_indexed_color: attempt to free already freed color.\n");
     return;
+  }
+
   color = color_table->colors[idx];
   [color release];
   color_table->colors[idx] = nil;
@@ -1358,9 +1378,9 @@ ns_get_color (const char *name, NSColor **col)
       return 0;
     }
 
-  /* 23: 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. */
+  /*  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;
@@ -1402,13 +1422,22 @@ ns_get_color (const char *name, NSColor **col)
   /* Direct colors (hex values) */
   if (hex)
     {
-      unsigned int color = 0;
+      unsigned long long color = 0;
       if (sscanf (hex, "%x", &color))
         {
-          float f1 = ((color >> 24) & 0xff) / 255.0;
-          float f2 = ((color >> 16) & 0xff) / 255.0;
-          float f3 = ((color >>  8) & 0xff) / 255.0;
-          float f4 = ((color      ) & 0xff) / 255.0;
+          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)
             {
@@ -1458,17 +1487,13 @@ ns_get_color (const char *name, NSColor **col)
     NSEnumerator *lenum, *cenum;
     NSString *name;
     NSColorList *clist;
+
 #ifdef NS_IMPL_GNUSTEP
     /* XXX: who is wrong, the requestor or the implementation? */
     if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
         == NSOrderedSame)
       nsname = @"highlightColor";
 #endif
-    if ([nsname compare: @"dark blue" options: NSCaseInsensitiveSearch]
-        == NSOrderedSame
-      || [nsname compare: @"darkblue" options: NSCaseInsensitiveSearch]
-        == NSOrderedSame)
-      nsname = @"navy blue";
 
     lenum = [[NSColorList availableColorLists] objectEnumerator];
     while ( (clist = [lenum nextObject]) && new == nil)
@@ -1563,11 +1588,33 @@ 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.
+   -------------------------------------------------------------------------- */
+{
+  float 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)
 /* --------------------------------------------------------------------------
-   23:   Return 1 if named color found, and set color_def rgb accordingly.
+         Return 1 if named color found, and set color_def rgb accordingly.
          If makeIndex and alloc are nonzero put the color in the color_table,
          and set color_def pixel to the resulting index.
          If makeIndex is zero, set color_def pixel to ARGB.
@@ -1575,7 +1622,6 @@ ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
    -------------------------------------------------------------------------- */
 {
   NSColor *temp;
-  float r, g, b, a;
   int notFound = ns_get_color (name, &temp);
 
   NSTRACE (ns_defined_color);
@@ -1586,15 +1632,7 @@ ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
   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 * 256;
-  color_def->green = g * 256;
-  color_def->blue  = b * 256;
-
-  if (!makeIndex)
-    color_def->pixel
-      = ARGB_TO_ULONG((int)(a*256),
-                     color_def->red, color_def->green, color_def->blue);
+  ns_query_color (temp, color_def, !makeIndex);
 
   return 1;
 }
@@ -1620,6 +1658,39 @@ ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
 }
 
 
+void
+x_set_frame_alpha (struct frame *f)
+/* --------------------------------------------------------------------------
+     change the entire-frame transparency
+   -------------------------------------------------------------------------- */
+{
+  struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
+  EmacsView *view = FRAME_NS_VIEW (f);
+  double alpha = 1.0;
+  double alpha_min = 1.0;
+
+  if (dpyinfo->x_highlight_frame == f)
+    alpha = f->alpha[0];
+  else
+    alpha = f->alpha[1];
+
+  if (FLOATP (Vframe_alpha_lower_limit))
+    alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
+  else if (INTEGERP (Vframe_alpha_lower_limit))
+    alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
+
+  if (alpha < 0.0)
+    return;
+  else if (1.0 < alpha)
+    alpha = 1.0;
+  else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
+    alpha = alpha_min;
+
+#ifdef NS_IMPL_COCOA
+  [[view window] setAlphaValue: alpha];
+#endif
+}
+
 
 /* ==========================================================================
 
@@ -1676,10 +1747,10 @@ note_mouse_movement (struct frame *frame, float x, float y)
      known as last_mouse_glyph.
      ------------------------------------------------------------------------ */
 {
-  NSTRACE (note_mouse_movement);
+//  NSTRACE (note_mouse_movement);
 
   XSETFRAME (last_mouse_motion_frame, frame);
-  
+
   /* Note, this doesn't get called for enter/leave, since we don't have a
      position.  Those are taken care of in the corresponding NSView methods. */
 
@@ -1689,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;
     }
 
@@ -1793,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;
         }
     }
@@ -1929,7 +2004,7 @@ ns_clear_frame (struct frame *f)
 void
 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
 /* --------------------------------------------------------------------------
-   23: External (RIF):  Clear section of frame
+    External (RIF):  Clear section of frame
    -------------------------------------------------------------------------- */
 {
   NSRect r = NSMakeRect (x, y, width, height);
@@ -1939,6 +2014,8 @@ ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
   if (!view || !face)
     return;
 
+  NSTRACE (ns_clear_frame_area);
+
   r = NSIntersectionRect (r, [view frame]);
   ns_focus (f, &r, 1);
   [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
@@ -1980,7 +2057,7 @@ ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
 static void
 ns_scroll_run (struct window *w, struct run *run)
 /* --------------------------------------------------------------------------
-   23: External (RIF):  Insert or delete n lines at line vpos
+    External (RIF):  Insert or delete n lines at line vpos
    -------------------------------------------------------------------------- */
 {
   struct frame *f = XFRAME (w->frame);
@@ -2043,7 +2120,7 @@ ns_scroll_run (struct window *w, struct run *run)
 static void
 ns_after_update_window_line (struct glyph_row *desired_row)
 /* --------------------------------------------------------------------------
-   23: External (RIF): preparatory to fringe update after text was updated
+    External (RIF): preparatory to fringe update after text was updated
    -------------------------------------------------------------------------- */
 {
   struct window *w = updated_window;
@@ -2098,7 +2175,7 @@ ns_shift_glyphs_for_insert (struct frame *f,
                            int x, int y, int width, int height,
                            int shift_by)
 /* --------------------------------------------------------------------------
-   23: External (RIF): copy an area horizontally, don't worry about clearing src
+    External (RIF): copy an area horizontally, don't worry about clearing src
    -------------------------------------------------------------------------- */
 {
   NSRect srcRect = NSMakeRect (x, y, width, height);
@@ -2124,7 +2201,7 @@ ns_shift_glyphs_for_insert (struct frame *f,
 static inline void
 ns_compute_glyph_string_overhangs (struct glyph_string *s)
 /* --------------------------------------------------------------------------
-   23:  External (RIF); compute left/right overhang of whole string and set in s
+     External (RIF); compute left/right overhang of whole string and set in s
    -------------------------------------------------------------------------- */
 {
   struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
@@ -2165,7 +2242,7 @@ static void
 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
                       struct draw_fringe_bitmap_params *p)
 /* --------------------------------------------------------------------------
-   23: External (RIF); fringe-related
+    External (RIF); fringe-related
    -------------------------------------------------------------------------- */
 {
   struct frame *f = XFRAME (WINDOW_FRAME (w));
@@ -2273,6 +2350,10 @@ ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
                        int on_p, int active_p)
 /* --------------------------------------------------------------------------
      External call (RIF): draw cursor
+     (modeled after x_draw_window_cursor
+     FIXME: cursor_width is effectively bogus -- it sometimes gets set
+     in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
+     DON'T USE IT (no other terms do)
    -------------------------------------------------------------------------- */
 {
   NSRect r, s;
@@ -2280,15 +2361,15 @@ ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
   struct frame *f = WINDOW_XFRAME (w);
   struct glyph *phys_cursor_glyph;
   int overspill;
-  unsigned char drawGlyph = 0, cursorType, oldCursorType;
 
   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);
 
   if (!on_p)
-      return;
+       return;
 
   w->phys_cursor_type = cursor_type;
-  w->phys_cursor_on_p = 1;
+  w->phys_cursor_on_p = on_p;
 
   if (cursor_type == NO_CURSOR)
     {
@@ -2321,75 +2402,55 @@ ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
   if (overspill > 0)
     r.size.width -= overspill;
 
-  /* TODO: 23: use emacs stored f->cursor_type instead of ns-specific */
-  oldCursorType = FRAME_CURSOR (f);
-  cursorType = FRAME_CURSOR (f) = FRAME_NEW_CURSOR (f);
-  f->output_data.ns->current_cursor_color
-    = f->output_data.ns->desired_cursor_color;
-
   /* TODO: only needed in rare cases with last-resort font in HELLO..
      should we do this more efficiently? */
-  ns_clip_to_row (w, glyph_row, -1, NO);
-/*  ns_focus (f, &r, 1); */
-
-  if (FRAME_LAST_INACTIVE (f))
-    {
-      /* previously hollow box; clear entire area */
-      [FRAME_BACKGROUND_COLOR (f) set];
-      NSRectFill (r);
-      drawGlyph = 1;
-      FRAME_LAST_INACTIVE (f) = NO;
-    }
-
-  /* prepare to draw */
-  if (cursorType == no_highlight || cursor_type == NO_CURSOR)
-    {
-      /* clearing for blink: erase the cursor itself */
-      [FRAME_BACKGROUND_COLOR (f) set];
-      cursorType = oldCursorType; /* just clear what we had before */
-    }
-  else
-      [FRAME_CURSOR_COLOR (f) set];
+  ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
+  [FRAME_CURSOR_COLOR (f) set];
 
-  if (!active_p)
-    {
-      /* inactive window: ignore what we just set and use a hollow box */
-      cursorType = hollow_box;
-      [FRAME_CURSOR_COLOR (f) set];
-    }
+#ifdef NS_IMPL_COCOA
+  /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
+           atomic.  Cleaner ways of doing this should be investigated.
+           One way would be to set a global variable DRAWING_CURSOR
+          when making the call to draw_phys..(), don't focus in that
+          case, then move the ns_unfocus() here after that call. */
+  NSDisableScreenUpdates ();
+#endif
 
-  switch (cursorType)
+  switch (cursor_type)
     {
-    case no_highlight:
+    case NO_CURSOR:
       break;
-    case filled_box:
+    case FILLED_BOX_CURSOR:
       NSRectFill (r);
-      drawGlyph = 1;
       break;
-    case hollow_box:
+    case HOLLOW_BOX_CURSOR:
       NSRectFill (r);
       [FRAME_BACKGROUND_COLOR (f) set];
       NSRectFill (NSInsetRect (r, 1, 1));
       [FRAME_CURSOR_COLOR (f) set];
-      drawGlyph = 1;
       break;
-    case underscore:
+    case HBAR_CURSOR:
       s = r;
       s.origin.y += lrint (0.75 * s.size.height);
       s.size.height = lrint (s.size.height * 0.25);
       NSRectFill (s);
       break;
-    case bar:
+    case BAR_CURSOR:
       s = r;
-      s.size.width = 1;
+      s.size.width = min (cursor_width, 2); //FIXME(see above)
       NSRectFill (s);
       break;
     }
   ns_unfocus (f);
 
-  /* if needed, draw the character under the cursor */
-  if (drawGlyph)
+  /* draw the character under the cursor */
+  if (cursor_type != NO_CURSOR)
     draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
+
+#ifdef NS_IMPL_COCOA
+  NSEnableScreenUpdates ();
+#endif
+
 }
 
 
@@ -2401,14 +2462,16 @@ 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);
 
   face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
   if (face)
       [ns_lookup_indexed_color(face->foreground, f) set];
 
   ns_focus (f, &r, 1);
-  NSDrawGroove (r, r);
+  NSRectFill(r);
   ns_unfocus (f);
 }
 
@@ -2452,11 +2515,11 @@ hide_hourglass ()
 
 
 static inline NSRect
+ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
 /* --------------------------------------------------------------------------
     Under NS we draw internal borders inside fringes, and want full-width
     rendering to go all the way to edge.  This function makes that correction.
    -------------------------------------------------------------------------- */
-ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
 {
   if (r.origin.y <= fibw+1)
     {
@@ -2752,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);
 
@@ -2771,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)
@@ -2830,10 +2903,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;
     }
 }
 
@@ -2851,13 +2992,29 @@ ns_draw_glyph_string (struct glyph_string *s)
 
   NSTRACE (ns_draw_glyph_string);
 
-  if (s->next && s->right_overhang && !s->for_overlaps && s->hl != DRAW_CURSOR)
+  if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
     {
-      xassert (s->next->img == NULL);
-      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);
+      int width;
+      struct glyph_string *next;
+
+      for (width = 0, next = s->next;
+          next && width < s->right_overhang;
+          width += next->width, next = next->next)
+       if (next->first_glyph->type != IMAGE_GLYPH)
+          {
+            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;
+          }
     }
 
   if (!s->for_overlaps && s->face->box != FACE_NO_BOX
@@ -2883,48 +3040,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:
@@ -2932,9 +3048,10 @@ ns_draw_glyph_string (struct glyph_string *s)
       n = ns_get_glyph_string_clip_rect (s, r);
       ns_focus (s->f, r, n);
 
-      if (s->for_overlaps || s->gidx > 0)
+      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);
 
@@ -2967,6 +3084,7 @@ ns_draw_glyph_string (struct glyph_string *s)
       ns_unfocus (s->f);
     }
 
+  s->num_clips = 0;
 }
 
 
@@ -3037,28 +3155,29 @@ ns_read_socket (struct terminal *terminal, int expected,
 /* --------------------------------------------------------------------------
      External (hook): Post an event to ourself and keep reading events until
      we read it back again.  In effect process all events which were waiting.
-   23: Now we have to manage the event buffer ourselves.
+     From 21+ we have to manage the event buffer ourselves.
    -------------------------------------------------------------------------- */
 {
   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;
@@ -3072,7 +3191,7 @@ ns_read_socket (struct terminal *terminal, int expected,
 
   /* If have pending open-file requests, attend to the next one of those. */
   if (ns_pending_files && [ns_pending_files count] != 0
-      && [NSApp openFile: [ns_pending_files objectAtIndex: 0]])
+      && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
     {
       [ns_pending_files removeObjectAtIndex: 0];
     }
@@ -3091,15 +3210,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))  // (!inNsSelect || !expected)
         {
           /* Post an application defined event on the event queue.  When this is
              received the [NXApp run] will return, thus having processed all
@@ -3113,11 +3232,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;
 }
 
@@ -3134,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);
@@ -3176,39 +3292,14 @@ ns_select (int nfds, fd_set *readfds, fd_set *writefds,
                                               repeats: YES]
                retain];
 
-  if (!NILP (ns_cursor_blink_mode) && !cursor_blink_entry)
-    {
-      if (!NUMBERP (ns_cursor_blink_rate))
-        ns_cursor_blink_rate = make_float (0.5);
-      cursor_blink_entry = [[NSTimer
-        scheduledTimerWithTimeInterval: XFLOATINT (ns_cursor_blink_rate)
-                                target: NSApp
-                              selector: @selector (cursor_blink_handler:)
-                              userInfo: 0
-                               repeats: YES]
-                             retain];
-    }
-  else if (NILP (ns_cursor_blink_mode) && cursor_blink_entry)
-    {
-      if (NUMBERP (ns_cursor_blink_rate))
-          ns_cursor_blink_rate = Qnil;
-      struct ns_display_info *dpyinfo = x_display_list; /* HACK */
-      [cursor_blink_entry invalidate];
-      [cursor_blink_entry release];
-      cursor_blink_entry = 0;
-      if (dpyinfo->x_highlight_frame)
-        {
-          Lisp_Object tem
-           = get_frame_param (dpyinfo->x_highlight_frame, Qcursor_type);
-          dpyinfo->x_highlight_frame->output_data.ns->desired_cursor
-           = ns_lisp_to_cursor_type (tem);
-        }
-    }
-
   /* 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;
 
@@ -3417,17 +3508,10 @@ ns_judge_scroll_bars (struct frame *f)
 }
 
 
-
-/* ==========================================================================
-
-    Miscellaneous, mainly stubbed-out functions added in 23
-
-   ========================================================================== */
-
-
 void
 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
 {
+  /* XXX irrelevant under NS */
 }
 
 
@@ -3438,6 +3522,23 @@ x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
 
    ========================================================================== */
 
+int
+x_display_pixel_height (dpyinfo)
+     struct ns_display_info *dpyinfo;
+{
+  NSScreen *screen = [NSScreen mainScreen];
+  return [screen frame].size.height;
+}
+
+int
+x_display_pixel_width (dpyinfo)
+     struct ns_display_info *dpyinfo;
+{
+  NSScreen *screen = [NSScreen mainScreen];
+  return [screen frame].size.width;
+}
+
+
 static Lisp_Object ns_string_to_lispmod (const char *s)
 /* --------------------------------------------------------------------------
      Convert modifier name to lisp symbol
@@ -3490,13 +3591,10 @@ ns_set_default_prefs ()
   ns_command_modifier = Qsuper;
   ns_control_modifier = Qcontrol;
   ns_function_modifier = Qnone;
-  ns_cursor_blink_rate = Qnil;
-  ns_cursor_blink_mode = Qnil;
-  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;
 }
 
 
@@ -3539,8 +3637,6 @@ ns_initialize_display_info (struct ns_display_info *dpyinfo)
     NSScreen *screen = [NSScreen mainScreen];
     NSWindowDepth depth = [screen depth];
 
-    dpyinfo->width = [screen frame].size.width;
-    dpyinfo->height = [screen frame].size.height;
     dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
     dpyinfo->resy = 72.27;
     dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
@@ -3573,8 +3669,7 @@ ns_initialize_display_info (struct ns_display_info *dpyinfo)
 }
 
 
-/* 23: Needed as new part of display engine; this and next define public
-      functions in this file (well, many of them, anyway). */
+/* This and next define (many of the) public functions in this file. */
 /* x_... are generic versions in xdisp.c that we, and other terms, get away
          with using despite presence in the "system dependent" redisplay
          interface.  In addition, many of the ns_ methods have code that is
@@ -3583,28 +3678,28 @@ extern frame_parm_handler ns_frame_parm_handlers[];
 static struct redisplay_interface ns_redisplay_interface =
 {
   ns_frame_parm_handlers,
-  x_produce_glyphs, /*generic OK */
-  x_write_glyphs, /*generic OK */
-  x_insert_glyphs, /*generic OK */
-  x_clear_end_of_line, /*generic OK */
-  ns_scroll_run, /*23 */
-  ns_after_update_window_line, /*23: added */
-  ns_update_window_begin, /*23: split from update_begin */
-  ns_update_window_end, /*23: split from update_end */
-  x_cursor_to, /*generic OK */
+  x_produce_glyphs,
+  x_write_glyphs,
+  x_insert_glyphs,
+  x_clear_end_of_line,
+  ns_scroll_run,
+  ns_after_update_window_line,
+  ns_update_window_begin,
+  ns_update_window_end,
+  x_cursor_to,
   ns_flush,
   0, /* flush_display_optional */
-  x_clear_window_mouse_face, /*generic OK */
-  x_get_glyph_overhangs, /*23: generic OK */
-  x_fix_overlapping_area, /*generic OK */
-  ns_draw_fringe_bitmap, /*23 */
+  x_clear_window_mouse_face,
+  x_get_glyph_overhangs,
+  x_fix_overlapping_area,
+  ns_draw_fringe_bitmap,
   0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
   0, /* destroy_fringe_bitmap */
-  ns_compute_glyph_string_overhangs, /*23 */
-  ns_draw_glyph_string, /*23: interface to nsfont.m */
-  ns_define_frame_cursor, /*23 */
-  ns_clear_frame_area, /*23 */
-  ns_draw_window_cursor, /*23: revamped ns_dumpcursor */
+  ns_compute_glyph_string_overhangs,
+  ns_draw_glyph_string, /* interface to nsfont.m */
+  ns_define_frame_cursor,
+  ns_clear_frame_area,
+  ns_draw_window_cursor,
   ns_draw_vertical_window_border,
   ns_shift_glyphs_for_insert
 };
@@ -3624,7 +3719,7 @@ ns_delete_terminal (struct terminal *terminal)
   struct ns_display_info *dpyinfo = terminal->display_info.ns;
   int i;
 
-  /* Protect against recursive calls.  Fdelete_frame in
+  /* Protect against recursive calls.  delete_frame in
      delete_terminal calls us back when it deletes our last frame.  */
   if (!terminal->name)
     return;
@@ -3656,21 +3751,21 @@ ns_create_terminal (struct ns_display_info *dpyinfo)
   terminal->rif = &ns_redisplay_interface;
 
   terminal->clear_frame_hook = ns_clear_frame;
-  terminal->ins_del_lines_hook = 0; /* 23: vestigial? */
-  terminal->delete_glyphs_hook = 0; /* 23: vestigial? */
+  terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
+  terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
   terminal->ring_bell_hook = ns_ring_bell;
   terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
   terminal->set_terminal_modes_hook = ns_set_terminal_modes;
   terminal->update_begin_hook = ns_update_begin;
   terminal->update_end_hook = ns_update_end;
-  terminal->set_terminal_window_hook = NULL; /* 23: vestigial? */
+  terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
   terminal->read_socket_hook = ns_read_socket;
   terminal->frame_up_to_date_hook = ns_frame_up_to_date;
   terminal->mouse_position_hook = ns_mouse_position;
   terminal->frame_rehighlight_hook = ns_frame_rehighlight;
   terminal->frame_raise_lower_hook = ns_frame_raise_lower;
 
-  terminal->fullscreen_hook = 0; /*XTfullscreen_hook;//23.50 */
+  terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
 
   terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
   terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
@@ -3690,25 +3785,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;
@@ -3723,7 +3805,8 @@ ns_term_init (Lisp_Object display_name)
 
   if (!ns_initialized)
     {
-      ns_initialize ();
+      baud_rate = 38400;
+      Fset_input_interrupt_mode (Qnil);
       ns_initialized = 1;
     }
 
@@ -3768,9 +3851,6 @@ ns_term_init (Lisp_Object display_name)
   /* Put it on ns_display_name_list */
   ns_display_name_list = Fcons (Fcons (display_name, Qnil),
                                 ns_display_name_list);
-/*      ns_display_name_list = Fcons (Fcons (display_name,
-                                           Fcons (Qnil, dpyinfo->xrdb)),
-                                    ns_display_name_list); */
   dpyinfo->name_list_element = XCAR (ns_display_name_list);
 
   /* Set the name of the terminal. */
@@ -3782,48 +3862,22 @@ ns_term_init (Lisp_Object display_name)
 
   /* Read various user defaults. */
   ns_set_default_prefs ();
-  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 ("CursorBlinkRate", &ns_cursor_blink_rate,
-             make_float (0.5), Qnil, YES, NO);
-  if (NUMBERP (ns_cursor_blink_rate))
-    ns_cursor_blink_mode = Qt;
-  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;
-  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;
+  if (!ns_no_defaults)
+    {
+      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);
     }
-  else
-    ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
 
+  ns_selection_color = [[NSUserDefaults standardUserDefaults]
+                        stringForKey: @"AppleHighlightColor"];
+  if (ns_selection_color == nil)
+    ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
+  
   {
     NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
 
@@ -3884,6 +3938,7 @@ ns_term_init (Lisp_Object display_name)
     appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
     [appMenu setAutoenablesItems: NO];
     mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
+    dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
 
     [appMenu insertItemWithTitle: @"About Emacs"
                           action: @selector (orderFrontStandardAboutPanel:)
@@ -3922,6 +3977,10 @@ ns_term_init (Lisp_Object display_name)
                            keyEquivalent: @""
                                  atIndex: 0];
     [mainMenu setSubmenu: appMenu forItem: item];
+    [dockMenu insertItemWithTitle: @"New Frame"
+                          action: @selector (newFrame:)
+                   keyEquivalent: @""
+                         atIndex: 0];
 
     [NSApp setMainMenu: mainMenu];
     [NSApp setAppleMenu: appMenu];
@@ -3945,8 +4004,14 @@ ns_term_shutdown (int sig)
   if (STRINGP (Vauto_save_list_file_name))
     unlink (SDATA (Vauto_save_list_file_name));
 
-  ns_shutdown_properly = YES;
-  [NSApp terminate: NSApp];
+  if (sig == 0 || sig == SIGTERM)
+    {
+      [NSApp terminate: NSApp];
+    }
+  else // force a stack trace to happen
+    {
+      abort();
+    }
 }
 
 
@@ -3970,13 +4035,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)
     {
@@ -4014,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];
@@ -4024,9 +4101,29 @@ 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);
+}
+
+
+- (void)newFrame: (id)sender
+{
+  struct frame *emacsframe = SELECTED_FRAME ();
+  NSEvent *theEvent = [NSApp currentEvent];
+
+  if (!emacs_event)
+    return;
+  emacs_event->kind = NS_NONKEY_EVENT;
+  emacs_event->code = KEY_NS_NEW_FRAME;
+  emacs_event->modifiers = 0;
+  EV_TRAILER (theEvent);
 }
 
 
@@ -4039,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 */
@@ -4065,39 +4162,59 @@ ns_term_shutdown (int sig)
   [NSApp setServicesProvider: NSApp];
   ns_send_appdefined (-2);
 }
 
-- (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;
+
+/* 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
+{
+  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([[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)
+        return NSTerminateNow;
+    else if (ret == NSAlertAlternateReturn)
+        return NSTerminateCancel;
+    return NSTerminateNow;  /* just in case */
 }
 
 
@@ -4133,20 +4250,34 @@ fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
   while ((file = [files nextObject]) != nil)
     [ns_pending_files addObject: file];
 
-#ifdef NS_IMPL_GNUSTEP
-  [self replyToOpenOrPrint: 0];
-#else
+/* TODO: when GNUstep implements this (and we require that version of
+         GNUstep), remove. */
+#ifndef NS_IMPL_GNUSTEP
   [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
-#endif /* NS_IMPL_GNUSTEP */
+#endif /* !NS_IMPL_GNUSTEP */
 
 }
 
+
+/* Handle dock menu requests.  */
+- (NSMenu *)applicationDockMenu: (NSApplication *) sender
+{
+  return dockMenu;
+}
+
+
 /* TODO: these may help w/IO switching btwn terminal and NSApp */
+- (void)applicationWillBecomeActive: (NSNotification *)notification
+{
+  //ns_app_active=YES;
+}
 - (void)applicationDidBecomeActive: (NSNotification *)notification
 {
+  //ns_app_active=YES;
 }
 - (void)applicationDidResignActive: (NSNotification *)notification
 {
+  //ns_app_active=NO;
   ns_send_appdefined (-1);
 }
 
@@ -4170,31 +4301,6 @@ fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
 
 extern void update_window_cursor (struct window *w, int on);
 
-- (void)cursor_blink_handler: (NSTimer *)cursorEntry
-/* --------------------------------------------------------------------------
-     Flash the cursor
-   -------------------------------------------------------------------------- */
-{
-  struct ns_display_info *dpyinfo = x_display_list; /*HACK, but OK for now */
-  struct frame *f = dpyinfo->x_highlight_frame;
-  NSTRACE (cursor_blink_handler);
-
-  if (!f)
-    return;
-  if (f->output_data.ns->current_cursor == no_highlight)
-    {
-      Lisp_Object tem = get_frame_param (f, Qcursor_type);
-      f->output_data.ns->desired_cursor = ns_lisp_to_cursor_type (tem);
-    }
-  else
-    {
-      f->output_data.ns->desired_cursor = no_highlight;
-    }
-  update_window_cursor (XWINDOW (FRAME_SELECTED_WINDOW (f)), 1);
-  /*x_update_cursor (f, 1); */
-}
-
-
 - (void)fd_handler: (NSTimer *) fdEntry
 /* --------------------------------------------------------------------------
      Check data waiting on file descriptors and terminate if so
@@ -4246,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]);
@@ -4300,7 +4406,9 @@ extern void update_window_cursor (struct window *w, int on);
   if (newFont = [sender convertFont:
                            ((struct nsfont_info *)face->font)->nsfont])
     {
-      emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
+      SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
+
+      emacs_event->kind = NS_NONKEY_EVENT;
       emacs_event->modifiers = 0;
       emacs_event->code = KEY_NS_CHANGE_FONT;
 
@@ -4334,6 +4442,7 @@ extern void update_window_cursor (struct window *w, int on);
 }
 
 
+
 /*****************************************************************************/
 /* Keyboard handling. */
 #define NS_KEYLOG 0
@@ -4350,23 +4459,24 @@ extern void update_window_cursor (struct window *w, int on);
   NSTRACE (keyDown);
 
   /* Rhapsody and OS X give up and down events for the arrow keys */
-  if ([theEvent type] != NSKeyDown)
+  if (ns_fake_keydown == YES)
+    ns_fake_keydown = NO;
+  else if ([theEvent type] != NSKeyDown)
     return;
 
   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;
    }
 
@@ -4445,14 +4555,17 @@ extern void update_window_cursor (struct window *w, int on);
         }
 
       if (flags & NSControlKeyMask)
-          emacs_event->modifiers |= parse_solitary_modifier (ns_control_modifier);
+          emacs_event->modifiers |=
+            parse_solitary_modifier (ns_control_modifier);
 
       if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
-          emacs_event->modifiers |= parse_solitary_modifier (ns_function_modifier);
+          emacs_event->modifiers |=
+            parse_solitary_modifier (ns_function_modifier);
 
       if (flags & NSAlternateKeyMask) /* default = meta */
         {
-          if (EQ (ns_alternate_modifier, Qnone) && !fnKeysym)
+          if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
+              && !fnKeysym)
             {   /* accept pre-interp alt comb */
               if ([[theEvent characters] length] > 0)
                 code = [[theEvent characters] characterAtIndex: 0];
@@ -4461,10 +4574,13 @@ extern void update_window_cursor (struct window *w, int on);
                 emacs_event->modifiers = 0;
             }
           else
-              emacs_event->modifiers |= parse_solitary_modifier (ns_alternate_modifier);
+              emacs_event->modifiers |=
+                parse_solitary_modifier (ns_alternate_modifier);
         }
 
-/*fprintf (stderr,"code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",code,fnKeysym,flags,emacs_event->modifiers); */
+  if (NS_KEYLOG)
+    fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
+             code, fnKeysym, flags, emacs_event->modifiers);
 
       /* if it was a function key or had modifiers, pass it directly to emacs */
       if (fnKeysym || (emacs_event->modifiers
@@ -4494,7 +4610,7 @@ extern void update_window_cursor (struct window *w, int on);
   firstTime = NO;
 
   if (NS_KEYLOG && !processingCompose)
-    fprintf (stderr, "Begin compose sequence.\n");
+    fprintf (stderr, "keyDown: Begin compose sequence.\n");
 
   processingCompose = YES;
   [nsEvArray addObject: theEvent];
@@ -4503,17 +4619,40 @@ extern void update_window_cursor (struct window *w, int on);
 }
 
 
+#ifdef NS_IMPL_COCOA
+/* 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
+   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 (NS_KEYLOG)
+        fprintf (stderr, "keyUp: passed test");
+      ns_fake_keydown = YES;
+      [self keyDown: theEvent];
+    }
+}
+#endif
+
+
 /* <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;
   int len = [(NSString *)aString length];
   int i;
 
-if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
+  if (NS_KEYLOG)
+    NSLog (@"insertText '%@'\tlen = %d", aString, len);
   processingCompose = NO;
 
   if (!emacs_event)
@@ -4560,20 +4699,9 @@ if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
   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);
 }
 
 
@@ -4583,7 +4711,7 @@ if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
   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;
@@ -4591,18 +4719,10 @@ if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
   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
@@ -4610,28 +4730,34 @@ if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
   return workingText != nil;
 }
 
+
 - (NSRange)markedRange
 {
   NSRange rng = workingText != nil
     ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
-if (NS_KEYLOG) NSLog (@"markedRange request");
+  if (NS_KEYLOG)
+    NSLog (@"markedRange request");
   return rng;
 }
 
+
 - (void)unmarkText
 {
-if (NS_KEYLOG) NSLog (@"unmark (accept) text");
+  if (NS_KEYLOG)
+    NSLog (@"unmark (accept) text");
   [self deleteWorkingText];
   processingCompose = NO;
 }
 
+
 /* used to position char selection windows, etc. */
 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
 {
   NSRect rect;
   NSPoint pt;
   struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
-if (NS_KEYLOG) NSLog (@"firstRectForCharRange request");
+  if (NS_KEYLOG)
+    NSLog (@"firstRectForCharRange request");
 
   rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
   rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
@@ -4645,24 +4771,17 @@ if (NS_KEYLOG) NSLog (@"firstRectForCharRange request");
   return rect;
 }
 
-#ifdef NS_IMPL_GNUSTEP
-- (long)conversationIdentifier
-{
-  return (long)self;
-}
-#else
+
 - (NSInteger)conversationIdentifier
 {
   return (NSInteger)self;
 }
-#endif
 
-/* TODO: below here not yet implemented correctly, but may not be needed */
 
 - (void)doCommandBySelector: (SEL)aSelector
 {
-  if (NS_KEYLOG) NSLog (@"Do command by selector: %@",
-                       NSStringFromSelector (aSelector));
+  if (NS_KEYLOG)
+    NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
 
   if (aSelector == @selector (deleteBackward:))
     {
@@ -4686,13 +4805,15 @@ if (NS_KEYLOG) NSLog (@"firstRectForCharRange request");
 
 - (NSRange)selectedRange
 {
-if (NS_KEYLOG) NSLog (@"selectedRange request");
+  if (NS_KEYLOG)
+    NSLog (@"selectedRange request");
   return NSMakeRange (NSNotFound, 0);
 }
 
 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
 {
-if (NS_KEYLOG) NSLog (@"characterIndexForPoint request");
+  if (NS_KEYLOG)
+    NSLog (@"characterIndexForPoint request");
   return 0;
 }
 
@@ -4700,7 +4821,8 @@ if (NS_KEYLOG) NSLog (@"characterIndexForPoint request");
 {
   static NSAttributedString *str = nil;
   if (str == nil) str = [NSAttributedString new];
-if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
+  if (NS_KEYLOG)
+    NSLog (@"attributedSubstringFromRange request");
   return str;
 }
 
@@ -4750,16 +4872,23 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 }
 
 
-- (void)mouseUp: (NSEvent *)theEvent
+- (void)rightMouseDown: (NSEvent *)theEvent
 {
-  NSTRACE (mouseUp);
+  NSTRACE (rightMouseDown);
   [self mouseDown: theEvent];
 }
 
 
-- (void)rightMouseDown: (NSEvent *)theEvent
+- (void)otherMouseDown: (NSEvent *)theEvent
 {
-  NSTRACE (rightMouseDown);
+  NSTRACE (otherMouseDown);
+  [self mouseDown: theEvent];
+}
+
+
+- (void)mouseUp: (NSEvent *)theEvent
+{
+  NSTRACE (mouseUp);
   [self mouseDown: theEvent];
 }
 
@@ -4771,6 +4900,13 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 }
 
 
+- (void)otherMouseUp: (NSEvent *)theEvent
+{
+  NSTRACE (otherMouseUp);
+  [self mouseDown: theEvent];
+}
+
+
 - (void) scrollWheel: (NSEvent *)theEvent
 {
   NSTRACE (scrollWheel);
@@ -4784,7 +4920,7 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
   Lisp_Object frame;
 
-  NSTRACE (mouseMoved);
+//  NSTRACE (mouseMoved);
 
   last_mouse_movement_time = EV_TIMESTAMP (e);
   last_mouse_motion_position
@@ -4839,14 +4975,19 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 }
 
 
+- (void)otherMouseDragged: (NSEvent *)e
+{
+  NSTRACE (otherMouseDragged);
+  [self mouseMoved: e];
+}
+
+
 - (BOOL)windowShouldClose: (id)sender
 {
   NSEvent *e =[[self window] currentEvent];
 
   NSTRACE (windowShouldClose);
   windowClosing = YES;
-  if (ns_window_num <= 1)
-    return NO;
   if (!emacs_event)
     return NO;
   emacs_event->kind = DELETE_WINDOW_EVENT;
@@ -4949,17 +5090,22 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
     }
 #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);
-  [NSApp stopModal];
 }
 
 
 - (void)windowDidBecomeKey: (NSNotification *)notification
+/* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
 {
-  int val = ns_lisp_to_cursor_type (get_frame_param (emacsframe, Qcursor_type));
   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
   struct frame *old_focus = dpyinfo->x_focus_frame;
 
@@ -4967,13 +5113,6 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 
   if (emacsframe != old_focus)
     dpyinfo->x_focus_frame = emacsframe;
-  /*/last_mouse_frame = emacsframe;? */
-
-  if (val >= 0)
-    {
-      FRAME_NEW_CURSOR (emacsframe) = val;
-/*    x_update_cursor (emacsframe, 1); // will happen in ns_frame_rehighlight */
-    }
 
   ns_frame_rehighlight (emacsframe);
 
@@ -4986,26 +5125,22 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 
 
 - (void)windowDidResignKey: (NSNotification *)notification
+/* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
 {
   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
   NSTRACE (windowDidResignKey);
 
-  if (!windowClosing && [[self window] isVisible] == YES)
-    {
-      FRAME_NEW_CURSOR (emacsframe) = hollow_box;
-      x_update_cursor (emacsframe, 1);
-      FRAME_LAST_INACTIVE (emacsframe) = YES;
-    }
-
-  if (dpyinfo->x_highlight_frame == emacsframe)
-    dpyinfo->x_highlight_frame = 0;
   if (dpyinfo->x_focus_frame == emacsframe)
     dpyinfo->x_focus_frame = 0;
 
-  if (dpyinfo->mouse_face_mouse_frame == emacsframe)
+  ns_frame_rehighlight (emacsframe);
+
+  /* FIXME: for some reason needed on second and subsequent clicks away
+            from sole-frame Emacs to get hollow box to show */
+  if (!windowClosing && [[self window] isVisible] == YES)
     {
-      clear_mouse_face (dpyinfo);
-      dpyinfo->mouse_face_mouse_frame = 0;
+      x_update_cursor (emacsframe, 1);
+      x_set_frame_alpha (emacsframe);
     }
 
   if (emacs_event)
@@ -5158,14 +5293,33 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 /* 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
@@ -5173,8 +5327,8 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
   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)
@@ -5205,6 +5359,7 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
     return;
 
   emacsframe->async_iconified = 1;
+  emacsframe->async_visible = 0;
 
   if (emacs_event)
     {
@@ -5278,7 +5433,7 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
     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);
@@ -5295,11 +5450,13 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 
 - 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;
 }
 
 
@@ -5310,18 +5467,20 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 
   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;
+  */
 }
 
 
@@ -5375,7 +5534,7 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
       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);
@@ -5396,7 +5555,7 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
         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);
@@ -5413,7 +5572,7 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
       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);
@@ -5425,7 +5584,7 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
   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);
@@ -5445,7 +5604,7 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
       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);
@@ -5477,6 +5636,28 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 }
 
 
+/* 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
@@ -5959,219 +6140,10 @@ if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
 
 
 
-/* ==========================================================================
-
-    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];
-}
-
-
-- (void) setPanelFromValues
-{
-  int cursorType
-    = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
-  prevExpandSpace = XFLOATINT (ns_expand_space);
-  prevBlinkRate = NILP (ns_cursor_blink_rate)
-    ? 0 : XFLOATINT (ns_cursor_blink_rate);
-
-#ifdef NS_IMPL_COCOA
-  prevUseHighlightColor = ns_use_system_highlight_color;
-#endif
-
-  [expandSpaceSlider setFloatValue: prevExpandSpace];
-  [cursorBlinkSlider setFloatValue: prevBlinkRate];
-  [cursorTypeMatrix selectCellWithTag: (cursorType == filled_box ? 1 :
-                                        (cursorType == bar ? 2 :
-                                         (cursorType == underscore ? 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
-}
-
-
-- (void) setValuesFromPanel
-{
-  int cursorTag = [[cursorTypeMatrix selectedCell] tag];
-  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 blinkRate = [cursorBlinkSlider floatValue];
-  float expandSpace = [expandSpaceSlider floatValue];
-  Lisp_Object old_cursor_blink_mode;
-
-  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;
-    }
-  if (blinkRate != prevBlinkRate)
-    {
-      old_cursor_blink_mode = ns_cursor_blink_mode;
-      if (blinkRate == 0.0)
-        {
-          ns_cursor_blink_rate = Qnil;
-          ns_cursor_blink_mode = Qnil;
-        }
-      else
-        {
-          ns_cursor_blink_rate = make_float (blinkRate);
-          ns_cursor_blink_mode = Qt;
-        }
-      if (!EQ (ns_cursor_blink_mode, old_cursor_blink_mode))
-          Feval (Fcons (intern ("blink-cursor-mode"), Qnil));
-
-      if (blinkRate != 0.0 && prevBlinkRate != 0.0)
-        {  /* if changed rates, remove blink handler so change picked up */
-          struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
-          [cursor_blink_entry invalidate];
-          [cursor_blink_entry release];
-          cursor_blink_entry = 0;
-          if (dpyinfo->x_highlight_frame)
-            {
-              Lisp_Object tem
-               = get_frame_param (dpyinfo->x_highlight_frame, Qcursor_type);
-              dpyinfo->x_highlight_frame->output_data.ns->desired_cursor
-               = ns_lisp_to_cursor_type (tem);
-            }
-        }
-      prevBlinkRate = blinkRate;
-    }
-  FRAME_NEW_CURSOR (frame)
-    = (cursorTag == 1 ? filled_box
-       : cursorTag == 2 ? bar
-       : cursorTag == 3 ? underscore : hollow_box);
-  store_frame_param (frame, Qcursor_type,
-                    ns_cursor_type_to_lisp (FRAME_NEW_CURSOR (frame)));
-  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
-{
-  ns_set_default_prefs ();
-  [self setPanelFromValues];
-}
-
-
-- (IBAction)runHelp: (id)sender
-{
-  Feval (Fcons (intern ("info"),
-              Fcons (build_string ("(ns-emacs)Preferences Panel"), Qnil)));
-  SET_FRAME_GARBAGED (frame);
-  ns_send_appdefined (-1);
-}
-
-
-- (IBAction)setColors: (id)sender
-{
-  Lisp_Object lispFrame;
-  XSETFRAME (lispFrame, frame);
-  Fns_popup_color_panel (lispFrame);
-}
-
-
-- (IBAction)setDefaultFont: (id)sender
-{
-  Lisp_Object lispFrame;
-  XSETFRAME (lispFrame, frame);
-  Fns_popup_font_panel (lispFrame);
-}
-
-@end  /* EmacsPrefsController */
-
-
-
 
 /* ==========================================================================
 
    Font-related functions; these used to be in nsfaces.m
-   The XLFD functions (115 lines) are an abomination that should be removed.
 
    ========================================================================== */
 
@@ -6221,76 +6193,8 @@ x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
 
 
 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
-
-static const char *
-ns_font_to_xlfd (NSFont *nsfont)
-/* --------------------------------------------------------------------------
-    Convert an NS font name to an X font name (XLFD).
-    The string returned is temporarily allocated.
-   -------------------------------------------------------------------------- */
-{
-  NSFontManager *mgr = [NSFontManager sharedFontManager];
-  NSString *sname = [nsfont /*familyName*/fontName];
-  char *famName = (char *)[sname UTF8String];
-  char *weightStr = [mgr fontNamed: sname hasTraits: NSBoldFontMask] ?
-      "bold" : "medium";
-  char *slantStr = [mgr fontNamed: sname hasTraits: NSItalicFontMask] ?
-      "i" : "r";
-  int size = [nsfont pointSize];
-  int aWidth = lrint (10.0 * [nsfont widthOfString: @"a"]);
-  const char *xlfd;
-  int i, len;
-
-  /* change '-' to '$' to avoid messing w/XLFD separator */
-  for (len = strlen (famName), i =0; i<len; i++)
-    if (famName[i] == '-')
-      {
-        famName[i] = '\0';
-        break;
-      }
-
-  xlfd = [[NSString stringWithFormat:
-                       @"-apple-%s-%s-%s-normal--%d-%d-75-75-m-%d-iso10646-1",
-                       famName, weightStr, slantStr, size, 10*size, aWidth]
-                  UTF8String];
-/*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
-  return xlfd;
-}
-
-static const char *
-ns_fontname_to_xlfd (const char *name)
-/* --------------------------------------------------------------------------
-    Convert an NS font name to an X font name (XLFD).
-    Sizes are set to 0.
-    The string returned is temporarily allocated.
-   -------------------------------------------------------------------------- */
-{
-  char famName[180];
-  char *weightStr = strcasestr (name, "bold") ? "bold" : "medium";
-  char *slantStr = strcasestr (name, "italic") || strcasestr (name, "oblique")
-    || strcasestr (name, "synthital") ? "i" : "r";
-  int i, len;
-  const char *xlfd;
-
-  /* change '-' to '$' to avoid messing w/XLFD separator, and ' ' to '_' */
-  bzero (famName, 180);
-  bcopy (name, famName, max (strlen (name), 179));
-  for (len =strlen (famName), i =0; i<len; i++)
-    {
-      if (famName[i] == '-')
-        famName[i] = '$';
-      else if (famName[i] == ' ')
-        famName[i] = '_';
-    }
-
-  xlfd = [[NSString stringWithFormat:
-                           @"-apple-%s-%s-%s-normal--0-0-75-75-m-0-iso10646-1",
-                           famName, weightStr, slantStr]
-                  UTF8String];
-/*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
-  return xlfd;
-}
-
+/* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
+         in 1.43. */
 
 const char *
 ns_xlfd_to_fontname (const char *xlfd)
@@ -6303,7 +6207,7 @@ ns_xlfd_to_fontname (const char *xlfd)
   char *name = xmalloc (180);
   int i, len;
   const char *ret;
-  
+
   if (!strncmp (xlfd, "--", 2))
     sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
   else
@@ -6398,28 +6302,14 @@ 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-cursor-blink-rate", &ns_cursor_blink_rate,
-               "Rate at which the Emacs cursor blinks (in seconds).\n\
-Set to nil to disable blinking.");
-
-  DEFVAR_LISP ("ns-cursor-blink-mode", &ns_cursor_blink_mode,
-               "Internal variable -- use M-x blink-cursor-mode or preferences\n\
-panel to control this setting.");
-
-  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.");
 
   staticpro (&ns_display_name_list);
   ns_display_name_list = Qnil;
@@ -6427,7 +6317,7 @@ or shrunk (negative).  Zero (the default) means standard line height.\n\
   staticpro (&last_mouse_motion_frame);
   last_mouse_motion_frame = Qnil;
 
-  /*23: now apparently we need to tell emacs what modifiers there are.. */
+  /* 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));
@@ -6473,13 +6363,6 @@ baseline level.  The default value is nil.  */);
 
   /* Tell emacs about this window system. */
   Fprovide (intern ("ns"), Qnil);
-  /* TODO: try to move this back into lisp,  ns-win.el loaded too late
-           right now */
-  {
-    Lisp_Object args[3] = { intern ("ns-version-string"), build_string ("9.0"),
-                    build_string ("NS Window system port version number.") };
-    Fdefconst (Flist (3, args));
-  }
 }