Index: src/fl_font_mac.cxx
===================================================================
--- src/fl_font_mac.cxx	(revision 6985)
+++ src/fl_font_mac.cxx	(working copy)
@@ -34,6 +34,9 @@
 #define check_default_font() {if (!fl_fontsize) fl_font(0, 12);}
 
 static const CGAffineTransform font_mx = { 1, 0, 0, -1, 0, 0 };
+#if defined(__APPLE_COCOA__)
+static SInt32 MACsystemVersion = 0;
+#endif
 
 Fl_Font_Descriptor::Fl_Font_Descriptor(const char* name, Fl_Fontsize Size) {
   next = 0;
@@ -47,7 +50,9 @@
   size = Size;
   minsize = maxsize = Size;
 #if defined(__APPLE_COCOA__) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-if(CTFontCreateWithName != NULL) {
+  if(MACsystemVersion == 0) Gestalt(gestaltSystemVersion, &MACsystemVersion);
+
+if(MACsystemVersion >= 0x1050) {//unfortunately, CTFontCreateWithName != NULL on 10.4 also!
   CFStringRef str = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);
   fontref = CTFontCreateWithName(str, size, NULL);
   CGGlyph glyph[2];
@@ -58,11 +63,11 @@
   CTFontGetAdvancesForGlyphs(fontref, kCTFontHorizontalOrientation, glyph, advances, 2);
   w = advances[0].width;
   if( abs(advances[0].width - advances[1].width) < 1E-2 ) {//this is a fixed-width font
-	//slightly rescale fixed-width fonts so the character width has an integral value
-	CFRelease(fontref);
-	CGFloat fsize = size / ( w/floor(w + 0.5) );
-	fontref = CTFontCreateWithName(str, fsize, NULL);
-	w = CTFontGetAdvancesForGlyphs(fontref, kCTFontHorizontalOrientation, glyph, NULL, 1);
+    //slightly rescale fixed-width fonts so the character width has an integral value
+    CFRelease(fontref);
+    CGFloat fsize = size / ( w/floor(w + 0.5) );
+    fontref = CTFontCreateWithName(str, fsize, NULL);
+    w = CTFontGetAdvancesForGlyphs(fontref, kCTFontHorizontalOrientation, glyph, NULL, 1);
   }
   CFRelease(str);
   ascent = (short)(CTFontGetAscent(fontref) + 0.5);
@@ -165,7 +170,7 @@
   */
   if (this == fl_fontsize) fl_fontsize = 0;
 #if defined(__APPLE_COCOA__) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-  if(CTFontCreateWithName != NULL)  CFRelease(fontref);
+  if(MACsystemVersion >= 0x1050)  CFRelease(fontref);
 #else
 	/*  ATSUDisposeTextLayout(layout);
   ATSUDisposeStyle(style); */
@@ -272,7 +277,7 @@
       return 8*n; // user must select a font first!
   }
 #if defined(__APPLE_COCOA__) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-if(CTFontCreateWithName != NULL) {
+if(MACsystemVersion >= 0x1050) {
   CTFontRef fontref = fl_fontsize->fontref;
   CFStringRef str = CFStringCreateWithBytes(NULL, (const UInt8*)txt, n * sizeof(UniChar), kCFStringEncodingUTF16, false);
   CFAttributedStringRef astr = CFAttributedStringCreate(NULL, str, NULL);
@@ -340,7 +345,7 @@
       return;
   }
 #if defined(__APPLE_COCOA__) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-if(CTFontCreateWithName != NULL) {
+if(MACsystemVersion >= 0x1050) {
   CTFontRef fontref = fl_fontsize->fontref;
   CFStringRef str16 = CFStringCreateWithBytes(NULL, (const UInt8*)txt, n *sizeof(UniChar), kCFStringEncodingUTF16, false);
   CFAttributedStringRef astr = CFAttributedStringCreate(NULL, str16, NULL);
@@ -408,32 +413,20 @@
 
 
 #if defined(__APPLE_COCOA__)
-static unsigned fl_cmap[256] = {
-#include "fl_cmap.h" // this is a file produced by "cmap.cxx":
-};
-CGColorRef flcolortocgcolor(Fl_Color i)
+static CGColorRef flcolortocgcolor(Fl_Color i)
 {
-  int index;
   uchar r, g, b;
-  if (i & 0xFFFFFF00) {
-    // translate rgb colors into color index
-    r = i>>24;
-    g = i>>16;
-    b = i>> 8;
-  } else {
-    // translate index into rgb:
-    index = i;
-    unsigned c = fl_cmap[i];
-    r = c>>24;
-    g = c>>16;
-    b = c>> 8;
-  }
+  Fl::get_color(i, r, g, b);
   CGFloat components[4] = {r/255.0f, g/255.0f, b/255.0f, 1.};
-#if defined(__APPLE_COCOA__) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
-  return CGColorCreate(CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), components);
+  static CGColorSpaceRef cspace = NULL;
+  if(cspace == NULL) {
+#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
+    cspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
 #else
-  return CGColorCreate(CGColorSpaceCreateWithName(kCGColorSpaceUserRGB), components);
+    cspace = CGColorSpaceCreateWithName(kCGColorSpaceUserRGB);
 #endif
+    }
+  return CGColorCreate(cspace, components);
 }
 #endif
 
@@ -444,7 +437,7 @@
   // convert to UTF-16 first
   UniChar *uniStr = mac_Utf8_to_Utf16(str, n, &n);
 #if defined(__APPLE_COCOA__) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-  if(CTFontCreateWithName != NULL) {
+  if(MACsystemVersion >= 0x1050) {
     CFStringRef keys[2];
     CFTypeRef values[2];  
     CFStringRef str16 = CFStringCreateWithBytes(NULL, (const UInt8*)uniStr, n * sizeof(UniChar), kCFStringEncodingUTF16, false);
Index: src/fl_set_fonts_mac.cxx
===================================================================
--- src/fl_set_fonts_mac.cxx	(revision 6991)
+++ src/fl_set_fonts_mac.cxx	(working copy)
@@ -61,10 +61,14 @@
 Fl_Font Fl::set_fonts(const char* xstarname) {
 #pragma unused ( xstarname )
 #if defined(__APPLE_COCOA__) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-if(CTFontCreateWithFontDescriptor != NULL) {
+static SInt32 MACsystemVersion = 0;
+if(MACsystemVersion == 0) Gestalt(gestaltSystemVersion, &MACsystemVersion);
+if(MACsystemVersion >= 0x1050) {
+//if(CTFontCreateWithFontDescriptor != NULL) {// CTFontCreateWithFontDescriptor != NULL on 10.4 also!
   int value[1] = {1};
-  CFDictionaryRef dict = CFDictionaryCreate(NULL, (const void **)kCTFontCollectionRemoveDuplicatesOption, 
-											(const void **)&value, 1, NULL, NULL);
+  CFDictionaryRef dict = CFDictionaryCreate(NULL, 
+					    (const void **)kCTFontCollectionRemoveDuplicatesOption, 
+					    (const void **)&value, 1, NULL, NULL);
   CTFontCollectionRef fcref = CTFontCollectionCreateFromAvailableFonts(dict);
   CFRelease(dict);
   CFArrayRef arrayref = CTFontCollectionCreateMatchingFontDescriptors(fcref);
Index: src/fl_draw_pixmap.cxx
===================================================================
--- src/fl_draw_pixmap.cxx	(revision 6985)
+++ src/fl_draw_pixmap.cxx	(working copy)
@@ -336,7 +336,7 @@
       }
     } else {
       for (int X = 0; X < d.w; X++) {
-        U32* colors = d.byte1[*p++];
+        U32* colors = (U32*)d.byte1[*p++];
         *q++ = colors[*p++];
       }
     }
Index: src/fl_rect.cxx
===================================================================
--- src/fl_rect.cxx	(revision 6985)
+++ src/fl_rect.cxx	(working copy)
@@ -684,10 +684,10 @@
     r = CreateRectRgn(0,0,0,0);
 #elif defined(__APPLE_QUARTZ__)
 #ifdef __APPLE_COCOA__
-		r = NULL;
+    r = XRectangleRegion(0,0,0,0);
 #else
-		r = NewRgn();
-		SetEmptyRgn(r);
+    r = NewRgn();
+    SetEmptyRgn(r);
 #endif
 #else
 # error unsupported platform
@@ -747,12 +747,12 @@
 #elif defined(__APPLE_QUARTZ__)
   if (!r) return 1;
 #ifdef __APPLE_COCOA__
-	CGRect arg = CGRectMake(x,y,w - 1,h - 1);
-	for(int i = 0; i < r->count; i++) {
-		CGRect test = CGRectIntersection(r->rects[i], arg);
-		if( ! CGRectIsEmpty(test)) return 1;
-	}
-	return 0;
+  CGRect arg = CGRectMake(x, y, w - 0.9, h - 0.9);
+  for(int i = 0; i < r->count; i++) {
+    CGRect test = CGRectIntersection(r->rects[i], arg);
+    if( ! CGRectIsEmpty(test)) return 1;
+  }
+  return 0;
 #else
   Rect rect;
   rect.left = x; rect.top = y; rect.right = x+w; rect.bottom = y+h;
@@ -825,7 +825,7 @@
   return ret;
 #elif defined(__APPLE_QUARTZ__)
 #ifdef __APPLE_COCOA__
-	CGRect arg = CGRectMake(x,y,w - 1,h - 1);
+	CGRect arg = CGRectMake(x, y, w - 0.9, h - 0.9);
 	CGRect u = CGRectMake(0,0,0,0);
 	CGRect test;
 	for(int i = 0; i < r->count; i++) {
@@ -837,8 +837,8 @@
 		}
 	X = u.origin.x;
 	Y = u.origin.y;
-	W = u.size.width;
-	H = u.size.height;
+	W = u.size.width + 1;
+	H = u.size.height + 1;
 	if(CGRectIsEmpty(u)) W = H = 0;
 	return ! CGRectEqualToRect(arg, u);
 #else
Index: src/gl_draw.cxx
===================================================================
--- src/gl_draw.cxx	(revision 6985)
+++ src/gl_draw.cxx	(working copy)
@@ -110,7 +110,7 @@
     wglUseFontBitmaps(fl_gc, base, count, fl_fontsize->listbase+base);
     SelectObject(fl_gc, oldFid);
 # elif defined(__APPLE_QUARTZ__)
-#if ! __LP64__
+#if ! defined(__APPLE_COCOA__)
 //AGL is not supported for use in 64-bit applications:
 //http://developer.apple.com/mac/library/documentation/Carbon/Conceptual/Carbon64BitGuide/OtherAPIChanges/OtherAPIChanges.html
     short font, face, size;
@@ -132,7 +132,7 @@
 
   }
   gl_fontsize = fl_fontsize;
-#if !( defined(__APPLE__) &&  __LP64__ )
+#if !( defined(__APPLE__) &&  defined(__APPLE_COCOA__) )
   glListBase(fl_fontsize->listbase);
 #endif
 }
@@ -210,14 +210,14 @@
   Draws an array of n characters of the string in the current font
   at the current position.
   */
-#if defined(__APPLE__) && __LP64__
+#if defined(__APPLE__) && defined(__APPLE_COCOA__)
 static void gl_draw_cocoa(const char* str, int n);
 #endif
 
 void gl_draw(const char* str, int n) {
 #ifdef __APPLE__
   
-#if __LP64__
+#if defined(__APPLE_COCOA__)
   gl_draw_cocoa(str, n);
 #else
 // Should be converting the text here, as for other platforms???
@@ -367,7 +367,7 @@
   glDrawPixels(w,h,d<4?GL_RGB:GL_RGBA,GL_UNSIGNED_BYTE,(const ulong*)b);
 }
 
-#if defined(__APPLE__) && defined(__APPLE_COCOA__) && __LP64__
+#if defined(__APPLE__) && defined(__APPLE_COCOA__)
 
 #include <FL/glu.h>
 
Index: src/Fl_cocoa.mm
===================================================================
--- src/Fl_cocoa.mm	(revision 7011)
+++ src/Fl_cocoa.mm	(working copy)
@@ -122,7 +122,6 @@
 // forward declarations of variables in this file
 static int got_events = 0;
 static Fl_Window* resize_from_system;
-static NSView *viewWithLockedFocus = nil;
 static SInt32 MACsystemVersion;
 
 #if CONSOLIDATE_MOTION
@@ -198,9 +197,9 @@
 
 
 /*
- * convert the current mouse chord into the FLTK keysym
+ * convert the current key chord into the FLTK keysym
  */
-/*
+
  static void mods_to_e_keysym( NSUInteger mods )
  {
  if ( mods & NSCommandKeyMask ) Fl::e_keysym = FL_Meta_L;
@@ -212,7 +211,7 @@
  else Fl::e_keysym = 0;
  //printf( "to sym 0x%08x (%04x)\n", Fl::e_keysym, mods );
  }
- */
+
 // these pointers are set by the Fl::lock() function:
 static void nothing() {}
 void (*fl_lock_function)() = nothing;
@@ -774,7 +773,19 @@
   NSUInteger mods = [theEvent modifierFlags];  
   int sendEvent = 0;
   
-  switch ( [theEvent type] ) {
+  NSEventType etype = [theEvent type];
+  if (etype == NSLeftMouseDown || etype == NSRightMouseDown || etype == NSOtherMouseDown) {
+    if (btn == 1) Fl::e_state |= FL_BUTTON1;
+    else if (btn == 3) Fl::e_state |= FL_BUTTON2;
+    else if (btn == 2) Fl::e_state |= FL_BUTTON3;
+  }
+  else if (etype == NSLeftMouseUp || etype == NSRightMouseUp || etype == NSOtherMouseUp) {
+    if (btn == 1) Fl::e_state &= ~FL_BUTTON1;
+    else if (btn == 3) Fl::e_state &= ~FL_BUTTON2;
+    else if (btn == 2) Fl::e_state &= ~FL_BUTTON3;
+    }
+    
+  switch ( etype ) {
     case NSLeftMouseDown:
     case NSRightMouseDown:
     case NSOtherMouseDown:
@@ -782,9 +793,6 @@
       sendEvent = FL_PUSH;
       Fl::e_is_click = 1; 
       px = (int)pos.x; py = (int)pos.y;
-      if (btn == 1) Fl::e_state |= FL_BUTTON1;
-      else if (btn == 3) Fl::e_state |= FL_BUTTON2;
-      else if (btn == 2) Fl::e_state |= FL_BUTTON3;
       if (clickCount>1) 
         Fl::e_clicks++;
       else
@@ -793,7 +801,6 @@
     case NSLeftMouseUp:
     case NSRightMouseUp:
     case NSOtherMouseUp:
-      Fl::e_state &=  0xff0000;
       if (suppressed) {
         suppressed = 0;
         break;
@@ -1533,13 +1540,7 @@
 void Fl_X::flush()
 {
   w->flush();
-  if (fl_gc) {
-    CGContextFlush(fl_gc);
-    if (viewWithLockedFocus) {
-      [viewWithLockedFocus unlockFocus];
-      viewWithLockedFocus = nil;
-    }
-  }
+  if (fl_gc) CGContextFlush(fl_gc);
 }
 
 /*
@@ -1717,6 +1718,7 @@
 - (void)scrollWheel:(NSEvent *)theEvent;
 - (void)keyDown:(NSEvent *)theEvent;
 - (void)keyUp:(NSEvent *)theEvent;
+- (void)flagsChanged:(NSEvent *)theEvent;
 - (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender;
 - (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender;
 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
@@ -1780,6 +1782,27 @@
 - (void)keyUp:(NSEvent *)theEvent {
   cocoaKeyboardHandler(theEvent);
 }
+- (void)flagsChanged:(NSEvent *)theEvent {
+  fl_lock_function();
+  static UInt32 prevMods = mods_to_e_state( GetCurrentKeyModifiers() );
+  NSUInteger mods = [theEvent modifierFlags];
+  Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
+  UInt32 tMods = prevMods ^ mods;
+  int sendEvent = 0;
+  if ( tMods )
+  {
+    mods_to_e_keysym( tMods );
+    if ( Fl::e_keysym ) 
+      sendEvent = ( prevMods<mods ) ? FL_KEYBOARD : FL_KEYUP;
+    Fl::e_length = 0;
+    Fl::e_text = "";
+    prevMods = mods;
+  }
+  mods_to_e_state( mods );
+  while (window->parent()) window = window->window();
+  if (sendEvent) Fl::handle(sendEvent,window);
+  fl_unlock_function();
+}
 - (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender
 {
   Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
@@ -2222,8 +2245,8 @@
     win = (Fl_Window*)win->window();
   }
   
-  viewWithLockedFocus = [(NSWindow*)i->xid contentView];
-  [viewWithLockedFocus lockFocusIfCanDraw];// important
+  [[NSView focusView] unlockFocus];
+  [[(NSWindow*)i->xid contentView]  lockFocus];
   i->gc = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
   fl_gc = i->gc;
   if ( fl_window_region ) XDestroyRegion(fl_window_region);
@@ -2604,7 +2627,7 @@
   Fl_Region outr = (Fl_Region)malloc(sizeof(*outr));
   outr->rects = (CGRect*)malloc(4 * r->count * sizeof(CGRect));
   outr->count = 0;
-  CGRect rect = CGRectMake(x,y,w - 1,h - 1);
+  CGRect rect = CGRectMake(x,y,w - 0.9,h - 0.9);
   for( int i = 0; i < r->count; i++) {
     CGRect A = r->rects[i];
     CGRect test = CGRectIntersection(A, rect);
@@ -2649,7 +2672,7 @@
  */
 {
   if (current == NULL) return XRectangleRegion(x,y,w,h);
-  CGRect r = CGRectMake(x, y, w - 1, h - 1);
+  CGRect r = CGRectMake(x, y, w - 0.9, h - 0.9);
   Fl_Region outr = (Fl_Region)malloc(sizeof(*outr));
   outr->count = current->count;
   outr->rects =(CGRect*)malloc(outr->count * sizeof(CGRect));
@@ -3213,8 +3236,6 @@
     y += win->y();
     win = win->window();
   }
-  NSView *myview = [(NSWindow*)Fl_X::i(win)->xid contentView];
-  [myview lockFocus];
   CGFloat epsilon = 0;
   if (MACsystemVersion >= 0x1060) epsilon = 0.001;
   // The epsilon offset is absolutely necessary under 10.6. Without it, the top pixel row and
@@ -3222,10 +3243,23 @@
   // Under 10.5, we want no offset.
   NSRect rect = NSMakeRect(x - epsilon, y - epsilon, w, h);
   NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:rect];
-  [myview unlockFocus];
   *bytesPerPixel = [bitmap bitsPerPixel]/8;
+  int bpp = (int)[bitmap bytesPerPlane];
+  int bpr = (int)[bitmap bytesPerRow];
+  int hh = bpp/bpr; // sometimes hh = h-1 for unclear reason
+  int ww = bpr/(*bytesPerPixel); // sometimes ww = w-1
   unsigned char *data = new unsigned char[w * h *  *bytesPerPixel];
-  memcpy(data, [bitmap bitmapData], w * h *  *bytesPerPixel);
+  if (w == ww) {
+    memcpy(data, [bitmap bitmapData], w * hh *  *bytesPerPixel);
+  } else {
+    unsigned char *p = [bitmap bitmapData];
+    unsigned char *q = data;
+    for(int i = 0;i < hh; i++) {
+      memcpy(q, p, *bytesPerPixel * ww);
+      p += bpr;
+      q += w * *bytesPerPixel;
+      }
+  }
   [bitmap release];
   return data;
 }
Index: src/Fl.cxx
===================================================================
--- src/Fl.cxx	(revision 6985)
+++ src/Fl.cxx	(working copy)
@@ -1474,7 +1474,7 @@
       XDestroyRegion(R);
 #elif defined(__APPLE_QUARTZ__)
 #ifdef __APPLE_COCOA__
-	  CGRect arg = CGRectMake(X,Y,W - 1,H - 1);
+	  CGRect arg = CGRectMake(X, Y, W - 0.9, H - 0.9);
 	  int j;//don't add a rectangle totally inside the Fl_Region
 	  for(j = 0; j < i->region->count; j++) {
 		if(CGRectContainsRect(i->region->rects[j], arg)) break;
Index: FL/mac.H
===================================================================
--- FL/mac.H	(revision 7008)
+++ FL/mac.H	(working copy)
@@ -83,7 +83,7 @@
   Fl_Region R = (Fl_Region)malloc(sizeof(*R));
   R->count = 1;
   R->rects = (CGRect *)malloc(sizeof(CGRect));
-  *(R->rects) = CGRectMake(x, y, w - 1, h - 1);
+  *(R->rects) = CGRectMake(x, y, w > 0 ? w - 0.9 : 0, h > 0 ? h - 0.9 : 0);
   return R;
 }
 inline void XDestroyRegion(Fl_Region r) {

