2 * Cocoa's event loop must be in main thread.
4 * Unless otherwise stated, all coordinate systems
5 * are bottom-left-based.
8 #define Cursor OSXCursor
12 #import <Cocoa/Cocoa.h>
20 #include "cocoa-thread.h"
25 #include "cocoa-screen.h"
26 #include "osx-keycodes.h"
29 #include "glendapng.h"
31 // Use non-deprecated names.
32 #define NSKeyDown NSEventTypeKeyDown
33 #define NSShiftKeyMask NSEventModifierFlagShift
34 #define NSAlternateKeyMask NSEventModifierFlagOption
35 #define NSCommandKeyMask NSEventModifierFlagCommand
36 #define NSResizableWindowMask NSWindowStyleMaskResizable
37 #define NSLeftMouseDown NSEventTypeLeftMouseDown
38 #define NSLeftMouseUp NSEventTypeLeftMouseUp
39 #define NSRightMouseDown NSEventTypeRightMouseDown
40 #define NSRightMouseUp NSEventTypeRightMouseUp
41 #define NSOtherMouseDown NSEventTypeOtherMouseDown
42 #define NSOtherMouseUp NSEventTypeOtherMouseUp
43 #define NSScrollWheel NSEventTypeScrollWheel
44 #define NSMouseMoved NSEventTypeMouseMoved
45 #define NSLeftMouseDragged NSEventTypeLeftMouseDragged
46 #define NSRightMouseDragged NSEventTypeRightMouseDragged
47 #define NSOtherMouseDragged NSEventTypeOtherMouseDragged
48 #define NSCompositeCopy NSCompositingOperationCopy
49 #define NSCompositeSourceIn NSCompositingOperationSourceIn
50 #define NSFlagsChanged NSEventTypeFlagsChanged
51 #define NSTitledWindowMask NSWindowStyleMaskTitled
52 #define NSClosableWindowMask NSWindowStyleMaskClosable
53 #define NSMiniaturizableWindowMask NSWindowStyleMaskMiniaturizable
54 #define NSBorderlessWindowMask NSWindowStyleMaskBorderless
58 #define LOG if(0)NSLog
59 #define panic sysfatal
62 int useliveresizing = 0;
63 int useoldfullscreen = 0;
66 static void setprocname(const char*);
69 * By default, devdraw uses retina displays.
70 * Set devdrawretina=0 in the environment to override.
72 int devdrawretina = 1;
77 fprint(2, "usage: devdraw (don't run directly)\n");
78 threadexitsall("usage");
81 @interface appdelegate : NSObject<NSApplicationDelegate,NSWindowDelegate> @end
83 NSObject<NSApplicationDelegate,NSWindowDelegate> *myApp;
86 threadmain(int argc, char **argv)
91 * Move the protocol off stdin/stdout so that
92 * any inadvertent prints don't screw things up.
98 open("/dev/null", OREAD);
99 open("/dev/null", OWRITE);
102 case 'D': /* for good ps -a listings */
105 useoldfullscreen = 1;
119 if (envvar = getenv("devdrawretina"))
120 devdrawretina = atoi(envvar) > 0;
122 if(OSX_VERSION < 100700)
123 [NSAutoreleasePool new];
125 [NSApplication sharedApplication];
126 [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
127 myApp = [appdelegate new];
128 [NSApp setDelegate:myApp];
132 #define WIN win.ofs[win.isofs]
136 NSWindow *ofs[2]; /* ofs[1] for old fullscreen; ofs[0] else */
140 NSBitmapImageRep *img;
144 CGFloat topointscale;
145 CGFloat topixelscale;
158 static void hidebars(int);
159 static void flushimg(NSRect);
160 static void autoflushwin(int);
161 static void flushwin(void);
162 static void followzoombutton(NSRect);
163 static void getmousepos(void);
164 static void makeicon(void);
165 static void makemenu(void);
166 static void makewin(char*);
167 static void sendmouse(void);
168 static void kicklabel0(char*);
169 static void setcursor0(Cursor*);
170 static void togglefs(void);
171 static void acceptresizing(int);
173 static NSCursor* makecursor(Cursor*);
175 static NSSize winsizepixels();
176 static NSSize winsizepoints();
177 static NSRect scalerect(NSRect, CGFloat);
178 static NSPoint scalepoint(NSPoint, CGFloat);
179 static NSRect dilate(NSRect);
181 @implementation appdelegate
182 - (void)applicationDidFinishLaunching:(id)arg
184 in.bigarrow = makecursor(&bigarrow);
188 detachDrawingThread:@selector(callservep9p:)
189 toTarget:[self class] withObject:nil];
192 - (void)windowDidBecomeKey:(id)arg
197 - (void)windowDidResize:(id)arg
202 - (void)windowWillStartLiveResize:(id)arg
204 if(useliveresizing == 0)
205 [win.content setHidden:YES];
207 - (void)windowDidEndLiveResize:(id)arg
209 if(useliveresizing == 0)
210 [win.content setHidden:NO];
212 - (void)windowDidChangeScreen:(id)arg
214 if(win.isnfs || win.isofs)
216 [win.ofs[1] setFrame:[[WIN screen] frame] display:YES];
218 - (BOOL)windowShouldZoom:(id)arg toFrame:(NSRect)r
223 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(id)arg
227 - (void)applicationDidBecomeActive:(id)arg{ in.willactivate = 0;}
228 - (void)windowWillEnterFullScreen:(id)arg{ acceptresizing(1);}
229 - (void)windowDidEnterFullScreen:(id)arg{ win.isnfs = 1; hidebars(1);}
230 - (void)windowWillExitFullScreen:(id)arg{ win.isnfs = 0; hidebars(0);}
231 - (void)windowDidExitFullScreen:(id)arg
235 b = [WIN standardWindowButton:NSWindowMiniaturizeButton];
237 if([b isEnabled] == 0){
242 - (void)windowWillClose:(id)arg
244 autoflushwin(0); /* can crash otherwise */
247 + (void)callservep9p:(id)arg
250 [NSApp terminate:self];
252 - (void)plumbmanual:(id)arg
256 execl("plumb", "plumb", "devdraw(1)", nil);
258 + (void)callflushwin:(id)arg{ flushwin();}
259 - (void)calltogglefs:(id)arg{ togglefs();}
261 + (void)callflushimg:(NSValue*)v{ flushimg([v rectValue]);}
262 + (void)callmakewin:(NSValue*)v{ makewin([v pointerValue]);}
263 + (void)callsetcursor0:(NSValue*)v{ setcursor0([v pointerValue]);}
264 + (void)callkicklabel0:(NSValue*)v{ kicklabel0([v pointerValue]);}
267 static Memimage* initimg(void);
270 attachscreen(char *label, char *winsize)
272 static int first = 1;
277 panic("attachscreen called twice");
280 label = "gnot a label";
281 if(strcmp(label, "page") == 0)
285 * Create window in main thread, else no cursor
286 * change while resizing.
289 performSelectorOnMainThread:@selector(callmakewin:)
290 withObject:[NSValue valueWithPointer:winsize]
298 @interface appwin : NSWindow @end
299 @interface contentview : NSView @end
301 @implementation appwin
302 - (NSTimeInterval)animationResizeTime:(NSRect)r
306 - (BOOL)canBecomeKeyWindow
308 return YES; /* else no keyboard for old fullscreen */
310 - (void)makeKeyAndOrderFront:(id)arg
312 LOG(@"makeKeyAndOrderFront");
315 [win.content setHidden:NO];
316 [super makeKeyAndOrderFront:arg];
318 - (void)miniaturize:(id)arg
320 [super miniaturize:arg];
323 [win.content setHidden:YES];
326 - (void)deminiaturize:(id)arg
329 [win.content setHidden:NO];
330 [super deminiaturize:arg];
333 - (NSDragOperation)draggingEntered:(id)arg
338 op = [arg draggingSourceOperationMask];
339 b = [arg draggingPasteboard];
341 if([[b types] containsObject:NSFilenamesPboardType])
342 if(op&NSDragOperationLink)
343 return NSDragOperationLink;
345 return NSDragOperationNone;
348 - (BOOL)performDragOperation:(id)arg
354 b = [arg draggingPasteboard];
355 if(![[b types] containsObject:NSFilenamesPboardType])
358 files = [b propertyListForType:NSFilenamesPboardType];
362 execl("macedit", "macedit", [[files objectAtIndex:i] UTF8String], nil);
370 min(double a, double b)
377 Winstyle = NSTitledWindowMask
378 | NSClosableWindowMask
379 | NSMiniaturizableWindowMask
380 | NSResizableWindowMask
391 sr = [[NSScreen mainScreen] frame];
392 r = [[NSScreen mainScreen] visibleFrame];
395 if(parsewinsize(s, &wr, &set) < 0)
398 wr = Rect(0, 0, sr.size.width*2/3, sr.size.height*2/3);
402 r.origin.x = wr.min.x;
403 r.origin.y = sr.size.height-wr.max.y; /* winsize is top-left-based */
404 r.size.width = min(Dx(wr), r.size.width);
405 r.size.height = min(Dy(wr), r.size.height);
406 r = [NSWindow contentRectForFrameRect:r
410 initWithContentRect:r
412 backing:NSBackingStoreBuffered defer:NO];
413 [w setTitle:@"devdraw"];
417 #if OSX_VERSION >= 100700
418 [w setCollectionBehavior:
419 NSWindowCollectionBehaviorFullScreenPrimary];
421 [w setContentMinSize:NSMakeSize(128,128)];
423 [w registerForDraggedTypes:[NSArray arrayWithObjects:
424 NSFilenamesPboardType, nil]];
427 win.ofs[1] = [[appwin alloc]
428 initWithContentRect:sr
429 styleMask:NSBorderlessWindowMask
430 backing:NSBackingStoreBuffered defer:YES];
432 [win.ofs[i] setAcceptsMouseMovedEvents:YES];
433 [win.ofs[i] setDelegate:myApp];
434 [win.ofs[i] setDisplaysWhenScreenProfileChanges:NO];
437 win.content = [contentview new];
438 [WIN setContentView:win.content];
450 size = winsizepixels();
451 LOG(@"initimg %.0f %.0f", size.width, size.height);
453 r = Rect(0, 0, size.width, size.height);
454 i = allocmemimage(r, XBGR32);
456 panic("allocmemimage: %r");
458 panic("i->data == nil");
460 win.img = [[NSBitmapImageRep alloc]
461 initWithBitmapDataPlanes:&i->data->bdata
468 colorSpaceName:NSDeviceRGBColorSpace
469 bytesPerRow:bytesperline(r, 32)
471 ptsize = winsizepoints();
472 [win.img setSize: ptsize];
473 win.topixelscale = size.width / ptsize.width;
474 win.topointscale = 1.0f / win.topixelscale;
476 // NOTE: This is not really the display DPI.
477 // On retina, topixelscale is 2; otherwise it is 1.
478 // This formula gives us 220 for retina, 110 otherwise.
479 // That's not quite right but it's close to correct.
480 // http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density#Apple
481 displaydpi = win.topixelscale * 110;
490 _drawreplacescreenimage(initimg());
506 limit = [NSDate dateWithTimeIntervalSinceNow:msec/1000.0];
508 [[NSRunLoop currentRunLoop]
509 runMode:@"waiting image"
512 }while(win.needimg && [(NSDate*)[NSDate date] compare:limit]<0);
514 win.deferflush = win.needimg;
516 LOG(@"waitimg %s (%d loop)", win.needimg?"defer":"ok", n);
520 _flushmemscreen(Rectangle r)
525 LOG(@"_flushmemscreen");
529 return; /* to skip useless white init rect */
532 [WIN performSelectorOnMainThread:
533 @selector(makeKeyAndOrderFront:)
538 if([win.content canDraw] == 0)
541 rect = NSMakeRect(r.min.x, r.min.y, Dx(r), Dy(r));
543 performSelectorOnMainThread:@selector(callflushimg:)
544 withObject:[NSValue valueWithRect:rect]
546 modes:[NSArray arrayWithObjects:
547 NSRunLoopCommonModes,
548 @"waiting image", nil]];
551 static void drawimg(NSRect, uint);
552 static void drawresizehandle(void);
558 Cornersize = 3*Pixel,
559 Handlesize = 3*Barsize + 1*Pixel,
563 * |rect| is in pixel coordinates.
566 flushimg(NSRect rect)
570 if([win.content lockFocusIfCanDraw] == 0)
574 if(!NSEqualSizes(scalerect(rect, win.topointscale).size, [win.img size])){
575 LOG(@"flushimg reject %.0f %.0f",
576 rect.size.width, rect.size.height);
577 [win.content unlockFocus];
584 LOG(@"flushimg ok %.0f %.0f", rect.size.width, rect.size.height);
587 * Unless we are inside "drawRect", we have to round
588 * the corners ourselves, if this is the custom.
589 * "NSCompositeSourceIn" can do that, but we don't
590 * apply it to the whole rectangle, because this
591 * slows down trackpad scrolling considerably in
594 r = [win.content bounds];
595 rect = dilate(scalerect(rect, win.topointscale));
596 r.size.height -= Cornersize;
597 dr = NSIntersectionRect(r, rect);
598 LOG(@"r %.0f %.0f %.0f %.0f", r.origin.x, r.origin.y, rect.size.width, rect.size.height);
599 LOG(@"rect in points %f %f %.0f %.0f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
600 LOG(@"dr in points %f %f %.0f %.0f", dr.origin.x, dr.origin.y, dr.size.width, dr.size.height);
601 drawimg(dr, NSCompositeCopy);
603 r.origin.y = r.size.height;
604 r.size = NSMakeSize(Cornersize, Cornersize);
605 dr = NSIntersectionRect(r, rect);
606 drawimg(dr, NSCompositeSourceIn);
608 r.origin.x = [win.img size].width - Cornersize;
609 dr = NSIntersectionRect(r, rect);
610 drawimg(dr, NSCompositeSourceIn);
612 r.size.width = r.origin.x - Cornersize;
613 r.origin.x -= r.size.width;
614 dr = NSIntersectionRect(r, rect);
615 drawimg(dr, NSCompositeCopy);
617 if(OSX_VERSION<100700 && win.isofs==0){
618 r.origin.x = [win.img size].width - Handlesize;
619 r.origin.y = [win.img size].height - Handlesize;
620 r.size = NSMakeSize(Handlesize, Handlesize);
621 if(NSIntersectsRect(r, rect))
624 [win.content unlockFocus];
628 autoflushwin(int set)
636 * We need "NSRunLoopCommonModes", otherwise the
637 * timer will not fire during live resizing.
640 timerWithTimeInterval:0.033
641 target:[appdelegate class]
642 selector:@selector(callflushwin:) userInfo:nil
644 [[NSRunLoop currentRunLoop] addTimer:t
645 forMode:NSRunLoopCommonModes];
656 if(win.deferflush && win.needimg==0){
663 * |dr| is sized in points. What if I make it pixels?
666 drawimg(NSRect dr, uint op)
672 if(NSIsEmptyRect(dr))
675 sr = [win.content convertRect:dr fromView:nil];
676 LOG(@"before dr: %f %f %f %f\n", dr.origin.x, dr.origin.y, dr.size.width, dr.size.height);
677 LOG(@"before sr: %f %f %f %f\n", sr.origin.x, sr.origin.y, sr.size.width, sr.size.height);
679 dr = scalerect(dr, win.topixelscale);
680 sr = scalerect(sr, win.topixelscale);
682 LOG(@"dr: %f %f %f %f\n", dr.origin.x, dr.origin.y, dr.size.width, dr.size.height);
683 LOG(@"sr: %f %f %f %f\n", sr.origin.x, sr.origin.y, sr.size.width, sr.size.height);
684 if(OSX_VERSION >= 100800){
685 i = CGImageCreateWithImageInRect([win.img CGImage], NSRectToCGRect(dr));
686 c = [[WIN graphicsContext] graphicsPort];
688 CGContextSaveGState(c);
689 if(op == NSCompositeSourceIn)
690 CGContextSetBlendMode(c, kCGBlendModeSourceIn);
691 LOG(@"wim.img size %f %f\n", [win.img size].width, [win.img size].height);
692 CGContextTranslateCTM(c, 0, [win.img size].height);
693 CGContextScaleCTM(c, win.topointscale, -win.topointscale);
694 CGContextDrawImage(c, NSRectToCGRect(sr), i);
695 CGContextRestoreGState(c);
699 [win.img drawInRect:dr fromRect:sr
700 operation:op fraction:1
701 respectFlipped:YES hints:nil];
707 drawresizehandle(void)
709 NSColor *color[Barsize];
714 c = Pt([win.img size].width, [win.img size].height);
716 [[WIN graphicsContext] setShouldAntialias:NO];
718 color[0] = [NSColor clearColor];
719 color[1] = [NSColor darkGrayColor];
720 color[2] = [NSColor lightGrayColor];
721 color[3] = [NSColor whiteColor];
723 for(i=1; i+Barsize <= Handlesize; )
724 for(j=0; j<Barsize; j++){
725 [color[j] setStroke];
727 a = NSMakePoint(c.x-i, c.y-1);
728 b = NSMakePoint(c.x-2, c.y+1-i);
729 [NSBezierPath strokeLineFromPoint:a toPoint:b];
733 static void getgesture(NSEvent*);
734 static void getkeyboard(NSEvent*);
735 static void getmouse(NSEvent*);
736 static void gettouch(NSEvent*, int);
737 static void updatecursor(void);
739 @implementation contentview
741 * "drawRect" is called each time Cocoa needs an
742 * image, and each time we call "display". It is
743 * preceded by background painting, and followed by
746 - (void)drawRect:(NSRect)r
748 static int first = 1;
750 LOG(@"drawrect %.0f %.0f %.0f %.0f",
751 r.origin.x, r.origin.y, r.size.width, r.size.height);
758 if([WIN inLiveResize])
765 return YES; /* to make the content's origin top left */
767 - (BOOL)acceptsFirstResponder
769 return YES; /* else no keyboard */
771 - (id)initWithFrame:(NSRect)r
773 [super initWithFrame:r];
774 [self setAcceptsTouchEvents:YES];
775 [self setHidden:YES]; /* to avoid early "drawRect" call */
778 - (void)setHidden:(BOOL)set
781 [WIN makeFirstResponder:self]; /* for keyboard focus */
782 [super setHidden:set];
784 - (void)cursorUpdate:(NSEvent*)e{ updatecursor();}
786 - (void)mouseMoved:(NSEvent*)e{ getmouse(e);}
787 - (void)mouseDown:(NSEvent*)e{ getmouse(e);}
788 - (void)mouseDragged:(NSEvent*)e{ getmouse(e);}
789 - (void)mouseUp:(NSEvent*)e{ getmouse(e);}
790 - (void)otherMouseDown:(NSEvent*)e{ getmouse(e);}
791 - (void)otherMouseDragged:(NSEvent*)e{ getmouse(e);}
792 - (void)otherMouseUp:(NSEvent*)e{ getmouse(e);}
793 - (void)rightMouseDown:(NSEvent*)e{ getmouse(e);}
794 - (void)rightMouseDragged:(NSEvent*)e{ getmouse(e);}
795 - (void)rightMouseUp:(NSEvent*)e{ getmouse(e);}
796 - (void)scrollWheel:(NSEvent*)e{ getmouse(e);}
798 - (void)keyDown:(NSEvent*)e{ getkeyboard(e);}
799 - (void)flagsChanged:(NSEvent*)e{ getkeyboard(e);}
801 - (void)magnifyWithEvent:(NSEvent*)e{ getgesture(e);}
803 - (void)touchesBeganWithEvent:(NSEvent*)e
805 gettouch(e, NSTouchPhaseBegan);
807 - (void)touchesMovedWithEvent:(NSEvent*)e
809 gettouch(e, NSTouchPhaseMoved);
811 - (void)touchesEndedWithEvent:(NSEvent*)e
813 gettouch(e, NSTouchPhaseEnded);
815 - (void)touchesCancelledWithEvent:(NSEvent*)e
817 gettouch(e, NSTouchPhaseCancelled);
821 static int keycvt[] =
823 [QZ_IBOOK_ENTER]= '\n',
826 [QZ_BACKSPACE]= '\b',
850 [QZ_PAGEDOWN]= Kpgdown,
855 [QZ_KP_MULTIPLY]= '*',
871 @interface apptext : NSTextView @end
873 @implementation apptext
874 - (void)doCommandBySelector:(SEL)s{} /* Esc key beeps otherwise */
875 - (void)insertText:(id)arg{} /* to avoid a latency after some time */
879 interpretdeadkey(NSEvent *e)
885 [t interpretKeyEvents:[NSArray arrayWithObject:e]];
889 getkeyboard(NSEvent *e)
897 m = [e modifierFlags];
902 c = [s UTF8String][0];
906 if(m & NSCommandKeyMask){
907 if((m & NSShiftKeyMask) && 'a' <= c && c <= 'z')
915 if(code<nelem(keycvt) && keycvt[code])
922 keystroke([s characterAtIndex:0]);
926 if(in.mbuttons || in.kbuttons){
928 if(m & NSAlternateKeyMask)
930 if(m & NSCommandKeyMask)
934 if(m&NSAlternateKeyMask && (omod&NSAlternateKeyMask)==0)
939 panic("getkey: unexpected event type");
945 * Devdraw does not use NSTrackingArea, that often
946 * forgets to update the cursor on entering and on
947 * leaving the area, and that sometimes stops sending
948 * us MouseMove events, at least on OS X Lion.
954 int isdown, isinside;
956 isinside = NSPointInRect(in.mpos, [win.content bounds]);
957 isdown = (in.mbuttons || in.kbuttons);
959 if(win.cursor && (isinside || isdown))
961 else if(isinside && usebigarrow)
964 c = [NSCursor arrowCursor];
968 * Without this trick, we can come back from the dock
969 * with a resize cursor.
971 if(OSX_VERSION >= 100700)
976 acceptresizing(int set)
980 old = [WIN styleMask];
982 if((old | NSResizableWindowMask) != Winstyle)
983 return; /* when entering new fullscreen */
988 style = Winstyle & ~NSResizableWindowMask;
991 [WIN setStyleMask:style];
999 p = [WIN mouseLocationOutsideOfEventStream];
1000 q = [win.content convertPoint:p fromView:nil];
1002 /* q is in point coordinates. in.mpos is in pixels. */
1003 q = scalepoint(q, win.topixelscale);
1005 in.mpos.x = round(q.x);
1006 in.mpos.y = round(q.y);
1010 if(win.isnfs || win.isofs)
1012 else if(OSX_VERSION>=100700 && [WIN inLiveResize]==0){
1013 if(p.x<12 && p.y<12 && p.x>2 && p.y>2)
1021 getmouse(NSEvent *e)
1026 if([WIN isKeyWindow] == 0)
1032 case NSLeftMouseDown:
1034 case NSOtherMouseDown:
1035 case NSOtherMouseUp:
1036 case NSRightMouseDown:
1037 case NSRightMouseUp:
1038 b = [NSEvent pressedMouseButtons];
1039 b = b&~6 | (b&4)>>1 | (b&2)<<1;
1043 m = [e modifierFlags];
1044 if(m & NSAlternateKeyMask){
1048 if(m & NSCommandKeyMask)
1055 #if OSX_VERSION >= 100700
1056 d = [e scrollingDeltaY];
1068 case NSLeftMouseDragged:
1069 case NSRightMouseDragged:
1070 case NSOtherMouseDragged:
1074 panic("getmouse: unexpected event type");
1079 #define Minpinch 0.02
1082 getgesture(NSEvent *e)
1085 case NSEventTypeMagnify:
1086 if(fabs([e magnification]) > Minpinch)
1092 static void sendclick(int);
1097 return nsec()/1000000;
1101 gettouch(NSEvent *e, int type)
1104 static uint taptime;
1109 case NSTouchPhaseBegan:
1110 p = NSTouchPhaseTouching;
1111 set = [e touchesMatchingPhase:p inView:nil];
1120 case NSTouchPhaseMoved:
1124 case NSTouchPhaseEnded:
1125 p = NSTouchPhaseTouching;
1126 set = [e touchesMatchingPhase:p inView:nil];
1128 if(tapping && msec()-taptime<400)
1134 case NSTouchPhaseCancelled:
1138 panic("gettouch: unexpected event type");
1157 size = winsizepixels();
1158 mouserect = Rect(0, 0, size.width, size.height);
1160 b = in.kbuttons | in.mbuttons | in.mscroll;
1161 mousetrack(in.mpos.x, in.mpos.y, b, msec());
1174 if([NSApp isActive]==0 && in.willactivate==0)
1177 if([WIN inLiveResize])
1180 in.mpos = scalepoint(NSMakePoint(p.x, p.y), win.topointscale); // race condition
1182 q = [win.content convertPoint:in.mpos toView:nil];
1183 q = [WIN convertRectToScreen:NSMakeRect(q.x, q.y, 0, 0)].origin;
1185 r = [[[NSScreen screens] objectAtIndex:0] frame];
1186 q.y = r.size.height - q.y; /* Quartz is top-left-based here */
1188 CGWarpMouseCursorPosition(NSPointToCGPoint(q));
1189 CGAssociateMouseAndMouseCursorPosition(true);
1196 followzoombutton(NSRect r)
1203 wr.origin.y += wr.size.height;
1204 r.origin.y += r.size.height;
1209 pt = scalepoint(pt, win.topointscale);
1210 pt.x = (r.origin.x - wr.origin.x) + pt.x;
1211 pt.y = -(r.origin.y - wr.origin.y) + pt.y;
1212 pt = scalepoint(pt, win.topixelscale);
1225 #if OSX_VERSION >= 100700
1229 s0 = [[NSScreen screens] objectAtIndex:0];
1231 if((s==s0 && useoldfullscreen==0) || win.isnfs) {
1232 [WIN toggleFullScreen:nil];
1236 [win.content retain];
1238 [WIN setContentView:nil];
1240 win.isofs = ! win.isofs;
1241 hidebars(win.isofs);
1244 * If we move the window from one space to another,
1245 * ofs[0] and ofs[1] can be on different spaces.
1246 * This "setCollectionBehavior" trick moves the
1247 * window to the active space.
1249 opt = [WIN collectionBehavior];
1250 tmp = opt | NSWindowCollectionBehaviorCanJoinAllSpaces;
1251 [WIN setContentView:win.content];
1252 [WIN setCollectionBehavior:tmp];
1253 [WIN makeKeyAndOrderFront:nil];
1254 [WIN setCollectionBehavior:opt];
1255 [win.content release];
1260 Autohiddenbars = NSApplicationPresentationAutoHideDock
1261 | NSApplicationPresentationAutoHideMenuBar,
1263 Hiddenbars = NSApplicationPresentationHideDock
1264 | NSApplicationPresentationHideMenuBar,
1274 s0 = [[NSScreen screens] objectAtIndex:0];
1275 old = [NSApp presentationOptions];
1277 #if OSX_VERSION >= 100700
1278 /* This bit can get lost, resulting in dreadful bugs. */
1280 old |= NSApplicationPresentationFullScreen;
1284 opt = (old & ~Autohiddenbars) | Hiddenbars;
1286 opt = old & ~(Autohiddenbars | Hiddenbars);
1289 [NSApp setPresentationOptions:opt];
1299 i0 = [m addItemWithTitle:@"app" action:NULL keyEquivalent:@""];
1300 i1 = [m addItemWithTitle:@"help" action:NULL keyEquivalent:@""];
1301 [NSApp setMainMenu:m];
1304 m = [[NSMenu alloc] initWithTitle:@"app"];
1305 [m addItemWithTitle:@"Full Screen"
1306 action:@selector(calltogglefs:)
1307 keyEquivalent:@"f"];
1308 [m addItemWithTitle:@"Hide"
1309 action:@selector(hide:)
1310 keyEquivalent:@"h"];
1311 [m addItemWithTitle:@"Quit"
1312 action:@selector(terminate:)
1313 keyEquivalent:@"q"];
1317 m = [[NSMenu alloc] initWithTitle:@"help"];
1318 [m addItemWithTitle:@"Plumb devdraw(1)"
1319 action:@selector(plumbmanual:)
1325 // FIXME: Introduce a high-resolution Glenda image.
1333 initWithBytes:glenda_png
1334 length:(sizeof glenda_png)];
1336 i = [[NSImage alloc] initWithData:d];
1337 [NSApp setApplicationIconImage:i];
1338 [[NSApp dockTile] display];
1351 pb = [NSPasteboard generalPasteboard];
1354 s = [pb stringForType:NSPasteboardTypeString];
1358 return strdup((char*)[s UTF8String]);
1370 if(strlen(s) >= SnarfSize)
1373 t = [NSArray arrayWithObject:NSPasteboardTypeString];
1374 pb = [NSPasteboard generalPasteboard];
1375 str = [[NSString alloc] initWithUTF8String:s];
1378 [pb declareTypes:t owner:nil];
1379 [pb setString:str forType:NSPasteboardTypeString];
1386 kicklabel(char *label)
1392 performSelectorOnMainThread:@selector(callkicklabel0:)
1393 withObject:[NSValue valueWithPointer:label]
1398 kicklabel0(char *label) {
1401 s = [[NSString alloc] initWithUTF8String:label];
1402 [win.ofs[0] setTitle:s];
1403 [win.ofs[1] setTitle:s];
1404 [[NSApp dockTile] setBadgeLabel:s];
1409 setcursor(Cursor *c)
1412 * No cursor change unless in main thread.
1415 performSelectorOnMainThread:@selector(callsetcursor0:)
1416 withObject:[NSValue valueWithPointer:c]
1421 setcursor0(Cursor *c)
1428 win.cursor = makecursor(c);
1439 * Cursors will be scaled on retina display.
1442 makecursor(Cursor *c)
1444 NSBitmapImageRep *r;
1451 r = [[NSBitmapImageRep alloc]
1452 initWithBitmapDataPlanes:nil
1459 colorSpaceName:NSDeviceWhiteColorSpace
1463 [r getBitmapDataPlanes:plane];
1465 for(b=0; b<2*16; b++){
1466 plane[0][b] = ~c->set[b];
1467 plane[1][b] = c->clr[b];
1469 p = NSMakePoint(-c->offset.x, -c->offset.y);
1471 [i addRepresentation:r];
1474 d = [[NSCursor alloc] initWithImage:i hotSpot:p];
1482 [WIN performSelectorOnMainThread:
1483 @selector(makeKeyAndOrderFront:)
1487 in.willactivate = 1;
1488 [NSApp activateIgnoringOtherApps:YES];
1494 return [win.content bounds].size;
1500 #if OSX_VERSION >= 100700
1501 if (OSX_VERSION >= 100700 && devdrawretina)
1502 return [win.content convertSizeToBacking: winsizepoints()];
1505 return winsizepoints();
1509 scalerect(NSRect r, CGFloat scale)
1511 r.origin.x *= scale;
1512 r.origin.y *= scale;
1513 r.size.width *= scale;
1514 r.size.height *= scale;
1519 * Expands rectangle |r|'s bounds to more inclusive integer bounds to
1520 * eliminate 1 pixel gaps.
1525 if(win.topixelscale > 1.0f){
1526 r.origin.x = floorf(r.origin.x);
1527 r.origin.y = floorf(r.origin.y);
1528 r.size.width = ceilf(r.size.width + 0.5);
1529 r.size.height = ceilf(r.size.height + 0.5);
1535 scalepoint(NSPoint pt, CGFloat scale)
1543 setprocname(const char *s)
1545 CFStringRef process_name;
1547 process_name = CFStringCreateWithBytes(nil, (uchar*)s, strlen(s), kCFStringEncodingUTF8, false);
1549 // Adapted from Chrome's mac_util.mm.
1550 // http://src.chromium.org/viewvc/chrome/trunk/src/base/mac/mac_util.mm
1552 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
1554 // Redistribution and use in source and binary forms, with or without
1555 // modification, are permitted provided that the following conditions are
1558 // * Redistributions of source code must retain the above copyright
1559 // notice, this list of conditions and the following disclaimer.
1560 // * Redistributions in binary form must reproduce the above
1561 // copyright notice, this list of conditions and the following disclaimer
1562 // in the documentation and/or other materials provided with the
1564 // * Neither the name of Google Inc. nor the names of its
1565 // contributors may be used to endorse or promote products derived from
1566 // this software without specific prior written permission.
1568 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1569 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1570 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1571 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1572 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1573 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1574 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1575 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1576 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1577 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1578 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1579 // Warning: here be dragons! This is SPI reverse-engineered from WebKit's
1580 // plugin host, and could break at any time (although realistically it's only
1581 // likely to break in a new major release).
1582 // When 10.7 is available, check that this still works, and update this
1583 // comment for 10.8.
1585 // Private CFType used in these LaunchServices calls.
1586 typedef CFTypeRef PrivateLSASN;
1587 typedef PrivateLSASN (*LSGetCurrentApplicationASNType)();
1588 typedef OSStatus (*LSSetApplicationInformationItemType)(int, PrivateLSASN,
1593 static LSGetCurrentApplicationASNType ls_get_current_application_asn_func =
1595 static LSSetApplicationInformationItemType
1596 ls_set_application_information_item_func = NULL;
1597 static CFStringRef ls_display_name_key = NULL;
1599 static bool did_symbol_lookup = false;
1600 if (!did_symbol_lookup) {
1601 did_symbol_lookup = true;
1602 CFBundleRef launch_services_bundle =
1603 CFBundleGetBundleWithIdentifier(CFSTR("com.apple.LaunchServices"));
1604 if (!launch_services_bundle) {
1605 fprint(2, "Failed to look up LaunchServices bundle\n");
1609 ls_get_current_application_asn_func =
1610 (LSGetCurrentApplicationASNType)(
1611 CFBundleGetFunctionPointerForName(
1612 launch_services_bundle, CFSTR("_LSGetCurrentApplicationASN")));
1613 if (!ls_get_current_application_asn_func)
1614 fprint(2, "Could not find _LSGetCurrentApplicationASN\n");
1616 ls_set_application_information_item_func =
1617 (LSSetApplicationInformationItemType)(
1618 CFBundleGetFunctionPointerForName(
1619 launch_services_bundle,
1620 CFSTR("_LSSetApplicationInformationItem")));
1621 if (!ls_set_application_information_item_func)
1622 fprint(2, "Could not find _LSSetApplicationInformationItem\n");
1624 CFStringRef* key_pointer = (CFStringRef*)(
1625 CFBundleGetDataPointerForName(launch_services_bundle,
1626 CFSTR("_kLSDisplayNameKey")));
1627 ls_display_name_key = key_pointer ? *key_pointer : NULL;
1628 if (!ls_display_name_key)
1629 fprint(2, "Could not find _kLSDisplayNameKey\n");
1631 // Internally, this call relies on the Mach ports that are started up by the
1632 // Carbon Process Manager. In debug builds this usually happens due to how
1633 // the logging layers are started up; but in release, it isn't started in as
1634 // much of a defined order. So if the symbols had to be loaded, go ahead
1635 // and force a call to make sure the manager has been initialized and hence
1636 // the ports are opened.
1637 ProcessSerialNumber psn;
1638 GetCurrentProcess(&psn);
1640 if (!ls_get_current_application_asn_func ||
1641 !ls_set_application_information_item_func ||
1642 !ls_display_name_key) {
1646 PrivateLSASN asn = ls_get_current_application_asn_func();
1647 // Constant used by WebKit; what exactly it means is unknown.
1648 const int magic_session_constant = -2;
1650 ls_set_application_information_item_func(magic_session_constant, asn,
1651 ls_display_name_key,
1653 NULL /* optional out param */);
1655 fprint(2, "Call to set process name failed\n");