blob: 19a58acfb59bc3a037efa605477ad6377c1022ee [file] [log] [blame]
DRC2ff39b82011-07-28 08:38:59 +00001//
2// "$Id: Fl_cocoa.mm 8807 2011-06-16 12:35:32Z manolo $"
3//
4// MacOS-Cocoa specific code for the Fast Light Tool Kit (FLTK).
5//
6// Copyright 1998-2011 by Bill Spitzak and others.
7//
8// This library is free software; you can redistribute it and/or
9// modify it under the terms of the GNU Library General Public
10// License as published by the Free Software Foundation; either
11// version 2 of the License, or (at your option) any later version.
12//
13// This library is distributed in the hope that it will be useful,
14// but WITHOUT ANY WARRANTY; without even the implied warranty of
15// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16// Library General Public License for more details.
17//
18// You should have received a copy of the GNU Library General Public
19// License along with this library; if not, write to the Free Software
20// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21// USA.
22//
23// Please report all bugs and problems on the following page:
24//
25// http://www.fltk.org/str.php
26//
27
28//// From the inner edge of a MetroWerks CodeWarrior CD:
29// (without permission)
30//
31// "Three Compiles for 68Ks under the sky,
32// Seven Compiles for PPCs in their fragments of code,
33// Nine Compiles for Mortal Carbon doomed to die,
34// One Compile for Mach-O Cocoa on its Mach-O throne,
35// in the Land of MacOS X where the Drop-Shadows lie.
36//
37// One Compile to link them all, One Compile to merge them,
38// One Compile to copy them all and in the bundle bind them,
39// in the Land of MacOS X where the Drop-Shadows lie."
40
41#ifdef __APPLE__
42
43#define CONSOLIDATE_MOTION 0
44extern "C" {
45#include <pthread.h>
46}
47
48
49#include <FL/Fl.H>
50#include <FL/x.H>
51#include <FL/Fl_Window.H>
52#include <FL/Fl_Tooltip.H>
53#include <FL/Fl_Sys_Menu_Bar.H>
54#include <FL/Fl_Printer.H>
55#include <FL/Fl_Input_.H>
56#include <FL/Fl_Text_Display.H>
57#include <stdio.h>
58#include <stdlib.h>
59#include "flstring.h"
60#include <unistd.h>
61#include <stdarg.h>
62
63#import <Cocoa/Cocoa.h>
DRC685f17e2011-07-28 09:23:00 +000064#import <Carbon/Carbon.h>
DRC2ff39b82011-07-28 08:38:59 +000065
66#ifndef NSINTEGER_DEFINED // appears with 10.5 in NSObjCRuntime.h
67#if defined(__LP64__) && __LP64__
68typedef long NSInteger;
69typedef unsigned long NSUInteger;
70#else
71typedef long NSInteger;
72typedef unsigned int NSUInteger;
73#endif
74#endif
75
76
77// #define DEBUG_SELECT // UNCOMMENT FOR SELECT()/THREAD DEBUGGING
78#ifdef DEBUG_SELECT
79#include <stdio.h> // testing
80#define DEBUGMSG(msg) if ( msg ) fprintf(stderr, msg);
81#define DEBUGPERRORMSG(msg) if ( msg ) perror(msg)
82#define DEBUGTEXT(txt) txt
83#else
84#define DEBUGMSG(msg)
85#define DEBUGPERRORMSG(msg)
86#define DEBUGTEXT(txt) NULL
87#endif /*DEBUG_SELECT*/
88
89// external functions
90extern void fl_fix_focus();
91extern Fl_Offscreen fl_create_offscreen_with_alpha(int w, int h);
92
93// forward definition of functions in this file
94// converting cr lf converter function
95static void convert_crlf(char * string, size_t len);
96static void createAppleMenu(void);
97static Fl_Region MacRegionMinusRect(Fl_Region r, int x,int y,int w,int h);
98static void cocoaMouseHandler(NSEvent *theEvent);
99
100static Fl_Quartz_Graphics_Driver fl_quartz_driver;
101static Fl_Display_Device fl_quartz_display(&fl_quartz_driver);
102FL_EXPORT Fl_Graphics_Driver *fl_graphics_driver = (Fl_Graphics_Driver*)&fl_quartz_driver; // the current target device of graphics operations
103Fl_Surface_Device* Fl_Surface_Device::_surface = (Fl_Surface_Device*)&fl_quartz_display; // the current target surface of graphics operations
104Fl_Display_Device *Fl_Display_Device::_display = &fl_quartz_display; // the platform display
105
106// public variables
107int fl_screen;
108CGContextRef fl_gc = 0;
109void *fl_system_menu; // this is really a NSMenu*
110Fl_Sys_Menu_Bar *fl_sys_menu_bar = 0;
DRC2ff39b82011-07-28 08:38:59 +0000111void *fl_capture = 0; // (NSWindow*) we need this to compensate for a missing(?) mouse capture
112bool fl_show_iconic; // true if called from iconize() - shows the next created window in collapsed state
113//int fl_disable_transient_for; // secret method of removing TRANSIENT_FOR
114Window fl_window;
115Fl_Window *Fl_Window::current_;
116int fl_mac_os_version = 0; // the version number of the running Mac OS X (e.g., 100604 for 10.6.4)
117
118// forward declarations of variables in this file
119static int got_events = 0;
120static Fl_Window* resize_from_system;
121
122#if CONSOLIDATE_MOTION
123static Fl_Window* send_motion;
124extern Fl_Window* fl_xmousewin;
125#endif
126
DRC685f17e2011-07-28 09:23:00 +0000127bool use_simple_keyboard = false;
128
DRC2ff39b82011-07-28 08:38:59 +0000129enum { FLTKTimerEvent = 1, FLTKDataReadyEvent };
130
131
132/* fltk-utf8 placekeepers */
133void fl_reset_spot()
134{
135}
136
137void fl_set_spot(int font, int size, int X, int Y, int W, int H, Fl_Window *win)
138{
139}
140
141void fl_set_status(int x, int y, int w, int h)
142{
143}
144
DRC685f17e2011-07-28 09:23:00 +0000145// Undocumented voodoo. Taken from Mozilla.
146#define ENABLE_ROMAN_KYBDS_ONLY -23
147
148void fl_update_focus(void)
149{
150 Fl_Widget *focus;
151
152 focus = Fl::grab();
153 if (!focus)
154 focus = Fl::focus();
155 if (!focus)
156 return;
157
158 if (focus->simple_keyboard())
159 use_simple_keyboard = true;
160 else
161 use_simple_keyboard = false;
162
163 // Force a "Roman" or "ASCII" keyboard, which both the Mozilla and
164 // Safari people seem to think implies turning off advanced IME stuff
165 // (see nsTSMManager::SyncKeyScript in Mozilla and enableSecureTextInput
166 // in Safari/Webcore). Should be good enough for us then...
167#if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
168 CFArrayRef inputSources = TISCreateASCIICapableInputSourceList();
169 TSMSetDocumentProperty(TSMGetActiveDocument(),
170 kTSMDocumentEnabledInputSourcesPropertyTag,
171 sizeof(CFArrayRef), &inputSources);
172 CFRelease(inputSources);
173#else
174 KeyScript(use_simple_keyboard ? ENABLE_ROMAN_KYBDS_ONLY : smKeyEnableKybds);
175#endif
176}
177
DRC2ff39b82011-07-28 08:38:59 +0000178/*
179 * Mac keyboard lookup table
180 * See also the inverse converter vktab in Fl_get_key_mac.cxx
181 */
182static unsigned short macKeyLookUp[128] =
183{
184 'a', 's', 'd', 'f', 'h', 'g', 'z', 'x',
185 'c', 'v', '^', 'b', 'q', 'w', 'e', 'r',
186
187 'y', 't', '1', '2', '3', '4', '6', '5',
188 '=', '9', '7', '-', '8', '0', ']', 'o',
189
190 'u', '[', 'i', 'p', FL_Enter, 'l', 'j', '\'',
191 'k', ';', '\\', ',', '/', 'n', 'm', '.',
192
193 FL_Tab, ' ', '`', FL_BackSpace,
194 FL_KP_Enter, FL_Escape, FL_Meta_R, FL_Meta_L,
195 FL_Shift_L, FL_Caps_Lock, FL_Alt_L, FL_Control_L,
196 FL_Shift_R, FL_Alt_R, FL_Control_R, 0/*FL_F*/,
197
198 0, FL_KP+'.', FL_Right, FL_KP+'*', 0, FL_KP+'+', FL_Left, FL_Num_Lock,
199 FL_Down, 0, 0, FL_KP+'/', FL_KP_Enter, FL_Up, FL_KP+'-', 0,
200
201 0, FL_KP+'=', FL_KP+'0', FL_KP+'1', FL_KP+'2', FL_KP+'3', FL_KP+'4', FL_KP+'5',
202 FL_KP+'6', FL_KP+'7', 0, FL_KP+'8', FL_KP+'9', 0, 0, 0,
203
204 FL_F+5, FL_F+6, FL_F+7, FL_F+3, FL_F+8, FL_F+9, 0, FL_F+11,
205 0, FL_F+13, FL_F+16, FL_F+14, 0, FL_F+10, FL_Menu, FL_F+12,
206
207 0, FL_F+15, FL_Help, FL_Home, FL_Page_Up, FL_Delete, FL_F+4, FL_End,
208 FL_F+2, FL_Page_Down, FL_F+1, FL_Left, FL_Right, FL_Down, FL_Up, 0/*FL_Power*/,
209};
210
211/*
212 * convert the current mouse chord into the FLTK modifier state
213 */
214static unsigned int mods_to_e_state( NSUInteger mods )
215{
216 long state = 0;
217 if ( mods & NSCommandKeyMask ) state |= FL_META;
218 if ( mods & NSAlternateKeyMask ) state |= FL_ALT;
219 if ( mods & NSControlKeyMask ) state |= FL_CTRL;
220 if ( mods & NSShiftKeyMask ) state |= FL_SHIFT;
221 if ( mods & NSAlphaShiftKeyMask ) state |= FL_CAPS_LOCK;
222 unsigned int ret = ( Fl::e_state & 0xff000000 ) | state;
223 Fl::e_state = ret;
224 //printf( "State 0x%08x (%04x)\n", Fl::e_state, mods );
225 return ret;
226}
227
228// these pointers are set by the Fl::lock() function:
229static void nothing() {}
230void (*fl_lock_function)() = nothing;
231void (*fl_unlock_function)() = nothing;
232
233//
234// Select interface -- how it's implemented:
235// When the user app configures one or more file descriptors to monitor
236// with Fl::add_fd(), we start a separate thread to select() the data,
237// sending a custom OSX 'FLTK data ready event' to the parent thread's
238// RunApplicationLoop(), so that it triggers the data ready callbacks
239// in the parent thread. -erco 04/04/04
240//
241#define POLLIN 1
242#define POLLOUT 4
243#define POLLERR 8
244
245// Class to handle select() 'data ready'
246class DataReady
247{
248 struct FD
249 {
250 int fd;
251 short events;
252 void (*cb)(int, void*);
253 void* arg;
254 };
255 int nfds, fd_array_size;
256 FD *fds;
257 pthread_t tid; // select()'s thread id
258
259 // Data that needs to be locked (all start with '_')
260 pthread_mutex_t _datalock; // data lock
261 fd_set _fdsets[3]; // r/w/x sets user wants to monitor
262 int _maxfd; // max fd count to monitor
263 int _cancelpipe[2]; // pipe used to help cancel thread
264
265public:
266 DataReady()
267 {
268 nfds = 0;
269 fd_array_size = 0;
270 fds = 0;
271 tid = 0;
272
273 pthread_mutex_init(&_datalock, NULL);
274 FD_ZERO(&_fdsets[0]); FD_ZERO(&_fdsets[1]); FD_ZERO(&_fdsets[2]);
275 _cancelpipe[0] = _cancelpipe[1] = 0;
276 _maxfd = -1;
277 }
278
279 ~DataReady()
280 {
281 CancelThread(DEBUGTEXT("DESTRUCTOR\n"));
282 if (fds) { free(fds); fds = 0; }
283 nfds = 0;
284 }
285
286 // Locks
287 // The convention for locks: volatile vars start with '_',
288 // and must be locked before use. Locked code is prefixed
289 // with /*LOCK*/ to make painfully obvious esp. in debuggers. -erco
290 //
291 void DataLock() { pthread_mutex_lock(&_datalock); }
292 void DataUnlock() { pthread_mutex_unlock(&_datalock); }
293
294 // Accessors
295 int IsThreadRunning() { return(tid ? 1 : 0); }
296 int GetNfds() { return(nfds); }
297 int GetCancelPipe(int ix) { return(_cancelpipe[ix]); }
298 fd_set GetFdset(int ix) { return(_fdsets[ix]); }
299
300 // Methods
301 void AddFD(int n, int events, void (*cb)(int, void*), void *v);
302 void RemoveFD(int n, int events);
303 int CheckData(fd_set& r, fd_set& w, fd_set& x);
304 void HandleData(fd_set& r, fd_set& w, fd_set& x);
305 static void* DataReadyThread(void *self);
306 void StartThread(void);
307 void CancelThread(const char *reason);
308};
309
310static DataReady dataready;
311
312void DataReady::AddFD(int n, int events, void (*cb)(int, void*), void *v)
313{
314 RemoveFD(n, events);
315 int i = nfds++;
316 if (i >= fd_array_size)
317 {
318 fl_open_display(); // necessary for NSApp to be defined and the event loop to work
319 FD *temp;
320 fd_array_size = 2*fd_array_size+1;
321 if (!fds) { temp = (FD*)malloc(fd_array_size*sizeof(FD)); }
322 else { temp = (FD*)realloc(fds, fd_array_size*sizeof(FD)); }
323 if (!temp) return;
324 fds = temp;
325 }
326 fds[i].cb = cb;
327 fds[i].arg = v;
328 fds[i].fd = n;
329 fds[i].events = events;
330 DataLock();
331 /*LOCK*/ if (events & POLLIN) FD_SET(n, &_fdsets[0]);
332 /*LOCK*/ if (events & POLLOUT) FD_SET(n, &_fdsets[1]);
333 /*LOCK*/ if (events & POLLERR) FD_SET(n, &_fdsets[2]);
334 /*LOCK*/ if (n > _maxfd) _maxfd = n;
335 DataUnlock();
336}
337
338// Remove an FD from the array
339void DataReady::RemoveFD(int n, int events)
340{
341 int i,j;
342 _maxfd = -1; // recalculate maxfd on the fly
343 for (i=j=0; i<nfds; i++) {
344 if (fds[i].fd == n) {
345 int e = fds[i].events & ~events;
346 if (!e) continue; // if no events left, delete this fd
347 fds[i].events = e;
348 }
349 if (fds[i].fd > _maxfd) _maxfd = fds[i].fd;
350 // move it down in the array if necessary:
351 if (j<i) {
352 fds[j] = fds[i];
353 }
354 j++;
355 }
356 nfds = j;
357 DataLock();
358 /*LOCK*/ if (events & POLLIN) FD_CLR(n, &_fdsets[0]);
359 /*LOCK*/ if (events & POLLOUT) FD_CLR(n, &_fdsets[1]);
360 /*LOCK*/ if (events & POLLERR) FD_CLR(n, &_fdsets[2]);
361 DataUnlock();
362}
363
364// CHECK IF USER DATA READY, RETURNS r/w/x INDICATING WHICH IF ANY
365int DataReady::CheckData(fd_set& r, fd_set& w, fd_set& x)
366{
367 int ret;
368 DataLock();
369 /*LOCK*/ timeval t = { 0, 1 }; // quick check
370 /*LOCK*/ r = _fdsets[0], w = _fdsets[1], x = _fdsets[2];
371 /*LOCK*/ ret = ::select(_maxfd+1, &r, &w, &x, &t);
372 DataUnlock();
373 if ( ret == -1 ) {
374 DEBUGPERRORMSG("CheckData(): select()");
375 }
376 return(ret);
377}
378
379// HANDLE DATA READY CALLBACKS
380void DataReady::HandleData(fd_set& r, fd_set& w, fd_set& x)
381{
382 for (int i=0; i<nfds; i++) {
383 int f = fds[i].fd;
384 short revents = 0;
385 if (FD_ISSET(f, &r)) revents |= POLLIN;
386 if (FD_ISSET(f, &w)) revents |= POLLOUT;
387 if (FD_ISSET(f, &x)) revents |= POLLERR;
388 if (fds[i].events & revents) {
389 DEBUGMSG("DOING CALLBACK: ");
390 fds[i].cb(f, fds[i].arg);
391 DEBUGMSG("DONE\n");
392 }
393 }
394}
395
396// DATA READY THREAD
397// This thread watches for changes in user's file descriptors.
398// Sends a 'data ready event' to the main thread if any change.
399//
400void* DataReady::DataReadyThread(void *o)
401{
402 DataReady *self = (DataReady*)o;
403 NSAutoreleasePool *localPool;
404 localPool = [[NSAutoreleasePool alloc] init];
405 while ( 1 ) { // loop until thread cancel or error
406 // Thread safe local copies of data before each select()
407 self->DataLock();
408 /*LOCK*/ int maxfd = self->_maxfd;
409 /*LOCK*/ fd_set r = self->GetFdset(0);
410 /*LOCK*/ fd_set w = self->GetFdset(1);
411 /*LOCK*/ fd_set x = self->GetFdset(2);
412 /*LOCK*/ int cancelpipe = self->GetCancelPipe(0);
413 /*LOCK*/ if ( cancelpipe > maxfd ) maxfd = cancelpipe;
414 /*LOCK*/ FD_SET(cancelpipe, &r); // add cancelpipe to fd's to watch
415 /*LOCK*/ FD_SET(cancelpipe, &x);
416 self->DataUnlock();
417 // timeval t = { 1000, 0 }; // 1000 seconds;
418 timeval t = { 2, 0 }; // HACK: 2 secs prevents 'hanging' problem
419 int ret = ::select(maxfd+1, &r, &w, &x, &t);
420 pthread_testcancel(); // OSX 10.0.4 and older: needed for parent to cancel
421 switch ( ret ) {
422 case 0: // NO DATA
423 continue;
424 case -1: // ERROR
425 {
426 DEBUGPERRORMSG("CHILD THREAD: select() failed");
427 return(NULL); // error? exit thread
428 }
429 default: // DATA READY
430 {
431 if (FD_ISSET(cancelpipe, &r) || FD_ISSET(cancelpipe, &x)) // cancel?
432 { return(NULL); } // just exit
433 DEBUGMSG("CHILD THREAD: DATA IS READY\n");
434 NSPoint pt={0,0};
435 NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:pt
436 modifierFlags:0
437 timestamp:0
438 windowNumber:0 context:NULL
439 subtype:FLTKDataReadyEvent data1:0 data2:0];
440 [NSApp postEvent:event atStart:NO];
441 return(NULL); // done with thread
442 }
443 }
444 }
445}
446
447// START 'DATA READY' THREAD RUNNING, CREATE INTER-THREAD PIPE
448void DataReady::StartThread(void)
449{
450 CancelThread(DEBUGTEXT("STARTING NEW THREAD\n"));
451 DataLock();
452 /*LOCK*/ pipe(_cancelpipe); // pipe for sending cancel msg to thread
453 DataUnlock();
454 DEBUGMSG("*** START THREAD\n");
455 pthread_create(&tid, NULL, DataReadyThread, (void*)this);
456}
457
458// CANCEL 'DATA READY' THREAD, CLOSE PIPE
459void DataReady::CancelThread(const char *reason)
460{
461 if ( tid ) {
462 DEBUGMSG("*** CANCEL THREAD: ");
463 DEBUGMSG(reason);
464 if ( pthread_cancel(tid) == 0 ) { // cancel first
465 DataLock();
466 /*LOCK*/ write(_cancelpipe[1], "x", 1); // wake thread from select
467 DataUnlock();
468 pthread_join(tid, NULL); // wait for thread to finish
469 }
470 tid = 0;
471 DEBUGMSG("(JOINED) OK\n");
472 }
473 // Close pipe if open
474 DataLock();
475 /*LOCK*/ if ( _cancelpipe[0] ) { close(_cancelpipe[0]); _cancelpipe[0] = 0; }
476 /*LOCK*/ if ( _cancelpipe[1] ) { close(_cancelpipe[1]); _cancelpipe[1] = 0; }
477 DataUnlock();
478}
479
480void Fl::add_fd( int n, int events, void (*cb)(int, void*), void *v )
481{
482 dataready.AddFD(n, events, cb, v);
483}
484
485void Fl::add_fd(int fd, void (*cb)(int, void*), void* v)
486{
487 dataready.AddFD(fd, POLLIN, cb, v);
488}
489
490void Fl::remove_fd(int n, int events)
491{
492 dataready.RemoveFD(n, events);
493}
494
495void Fl::remove_fd(int n)
496{
497 dataready.RemoveFD(n, -1);
498}
499
500/*
501 * Check if there is actually a message pending!
502 */
503int fl_ready()
504{
505 NSEvent *retval = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow:0]
506 inMode:NSDefaultRunLoopMode dequeue:NO];
507 return retval != nil;
508}
509
510
511static void processFLTKEvent(void) {
512 fl_lock_function();
513 dataready.CancelThread(DEBUGTEXT("DATA READY EVENT\n"));
514
515 // CHILD THREAD TELLS US DATA READY
516 // Check to see what's ready, and invoke user's cb's
517 //
518 fd_set r,w,x;
519 switch(dataready.CheckData(r,w,x)) {
520 case 0: // NO DATA
521 break;
522 case -1: // ERROR
523 break;
524 default: // DATA READY
525 dataready.HandleData(r,w,x);
526 break;
527 }
528 fl_unlock_function();
529 return;
530}
531
532
533/*
534 * break the current event loop
535 */
536static void breakMacEventLoop()
537{
538 fl_lock_function();
539
540 NSPoint pt={0,0};
541 NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:pt
542 modifierFlags:0
543 timestamp:0
544 windowNumber:0 context:NULL
545 subtype:FLTKTimerEvent data1:0 data2:0];
546 [NSApp postEvent:event atStart:NO];
547 fl_unlock_function();
548}
549
550//
551// MacOS X timers
552//
553
554struct MacTimeout {
555 Fl_Timeout_Handler callback;
556 void* data;
557 CFRunLoopTimerRef timer;
558 char pending;
559};
560static MacTimeout* mac_timers;
561static int mac_timer_alloc;
562static int mac_timer_used;
563
564static void realloc_timers()
565{
566 if (mac_timer_alloc == 0) {
567 mac_timer_alloc = 8;
568 fl_open_display(); // needed because the timer creates an event
569 }
570 mac_timer_alloc *= 2;
571 MacTimeout* new_timers = new MacTimeout[mac_timer_alloc];
572 memset(new_timers, 0, sizeof(MacTimeout)*mac_timer_alloc);
573 memcpy(new_timers, mac_timers, sizeof(MacTimeout) * mac_timer_used);
574 MacTimeout* delete_me = mac_timers;
575 mac_timers = new_timers;
576 delete [] delete_me;
577}
578
579static void delete_timer(MacTimeout& t)
580{
581 if (t.timer) {
582 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(),
583 t.timer,
584 kCFRunLoopDefaultMode);
585 CFRelease(t.timer);
586 memset(&t, 0, sizeof(MacTimeout));
587 }
588}
589
590static void do_timer(CFRunLoopTimerRef timer, void* data)
591{
592 for (int i = 0; i < mac_timer_used; ++i) {
593 MacTimeout& t = mac_timers[i];
594 if (t.timer == timer && t.data == data) {
595 t.pending = 0;
596 (*t.callback)(data);
597 if (t.pending==0)
598 delete_timer(t);
599 break;
600 }
601 }
602 breakMacEventLoop();
603}
604
605@interface FLWindow : NSWindow {
606 Fl_Window *w;
607 BOOL containsGLsubwindow;
608}
609- (FLWindow*)initWithFl_W:(Fl_Window *)flw
610 contentRect:(NSRect)rect
611 styleMask:(NSUInteger)windowStyle;
612- (Fl_Window *)getFl_Window;
613- (BOOL)windowShouldClose:(FLWindow *)w;
614- (BOOL)containsGLsubwindow;
615- (void)setContainsGLsubwindow:(BOOL)contains;
616@end
617
618@implementation FLWindow
619- (FLWindow*)initWithFl_W:(Fl_Window *)flw
620 contentRect:(NSRect)rect
621 styleMask:(NSUInteger)windowStyle
622{
623 self = [super initWithContentRect:rect styleMask:windowStyle backing:NSBackingStoreBuffered defer:NO];
624 if (self) {
625 w = flw;
626 containsGLsubwindow = NO;
627 }
628 return self;
629}
630- (Fl_Window *)getFl_Window;
631{
632 return w;
633}
634- (BOOL)windowShouldClose:(FLWindow *)fl
635{
636 fl_lock_function();
637 Fl::handle( FL_CLOSE, [fl getFl_Window] ); // this might or might not close the window
638 if (!Fl_X::first) return YES;
639 Fl_Window *l = Fl::first_window();
640 while( l != NULL && l != [fl getFl_Window]) l = Fl::next_window(l);
641 fl_unlock_function();
642 return (l == NULL ? YES : NO);
643}
644- (BOOL)containsGLsubwindow
645{
646 return containsGLsubwindow;
647}
648- (void)setContainsGLsubwindow:(BOOL)contains
649{
650 containsGLsubwindow = contains;
651}
DRC685f17e2011-07-28 09:23:00 +0000652- (BOOL)canBecomeKeyWindow
653{
654 return YES;
655}
DRC2ff39b82011-07-28 08:38:59 +0000656@end
657
658@interface FLApplication : NSObject
659{
660}
661+ (void)sendEvent:(NSEvent *)theEvent;
662@end
663
664/*
665 * This function is the central event handler.
666 * It reads events from the event queue using the given maximum time
667 * Funny enough, it returns the same time that it got as the argument.
668 */
669static double do_queued_events( double time = 0.0 )
670{
671 got_events = 0;
672
673 // Check for re-entrant condition
674 if ( dataready.IsThreadRunning() ) {
675 dataready.CancelThread(DEBUGTEXT("AVOID REENTRY\n"));
676 }
677
678 // Start thread to watch for data ready
679 if ( dataready.GetNfds() ) {
680 dataready.StartThread();
681 }
682
683 fl_unlock_function();
684 NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask
685 untilDate:[NSDate dateWithTimeIntervalSinceNow:time]
686 inMode:NSDefaultRunLoopMode dequeue:YES];
687 if (event != nil) {
688 got_events = 1;
689 [FLApplication sendEvent:event]; // will then call [NSApplication sendevent:]
690 }
691 fl_lock_function();
692
693#if CONSOLIDATE_MOTION
694 if (send_motion && send_motion == fl_xmousewin) {
695 send_motion = 0;
696 Fl::handle(FL_MOVE, fl_xmousewin);
697 }
698#endif
699
700 return time;
701}
702
703/*
704 * This public function handles all events. It wait a maximum of
705 * 'time' seconds for an event. This version returns 1 if events
706 * other than the timeout timer were processed.
707 *
708 * \todo there is no socket handling in this code whatsoever
709 */
710int fl_wait( double time )
711{
712 do_queued_events( time );
713 return (got_events);
714}
715
716double fl_mac_flush_and_wait(double time_to_wait, char in_idle) {
717 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
718 Fl::flush();
719 if (Fl::idle && !in_idle) // 'idle' may have been set within flush()
720 time_to_wait = 0.0;
721 double retval = fl_wait(time_to_wait);
722 [pool release];
723 return retval;
724}
725
726// updates Fl::e_x, Fl::e_y, Fl::e_x_root, and Fl::e_y_root
727static void update_e_xy_and_e_xy_root(NSWindow *nsw)
728{
729 NSPoint pt;
730 pt = [nsw mouseLocationOutsideOfEventStream];
731 Fl::e_x = int(pt.x);
732 Fl::e_y = int([[nsw contentView] frame].size.height - pt.y);
733 pt = [NSEvent mouseLocation];
734 Fl::e_x_root = int(pt.x);
735 Fl::e_y_root = int([[nsw screen] frame].size.height - pt.y);
736}
737
738/*
739 * Cocoa Mousewheel handler
740 */
741static void cocoaMouseWheelHandler(NSEvent *theEvent)
742{
743 // Handle the new "MightyMouse" mouse wheel events. Please, someone explain
744 // to me why Apple changed the API on this even though the current API
745 // supports two wheels just fine. Matthias,
746 fl_lock_function();
747
748 Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
749 if ( !window->shown() ) {
750 fl_unlock_function();
751 return;
752 }
753 Fl::first_window(window);
754
755 // Under OSX, single mousewheel increments are 0.1,
756 // so make sure they show up as at least 1..
757 //
758 float dx = [theEvent deltaX]; if ( fabs(dx) < 1.0 ) dx = (dx > 0) ? 1.0 : -1.0;
759 float dy = [theEvent deltaY]; if ( fabs(dy) < 1.0 ) dy = (dy > 0) ? 1.0 : -1.0;
760 if ([theEvent deltaX] != 0) {
761 Fl::e_dx = (int)-dx;
762 Fl::e_dy = 0;
763 if ( Fl::e_dx) Fl::handle( FL_MOUSEWHEEL, window );
764 } else if ([theEvent deltaY] != 0) {
765 Fl::e_dx = 0;
766 Fl::e_dy = (int)-dy;
767 if ( Fl::e_dy) Fl::handle( FL_MOUSEWHEEL, window );
768 } else {
769 fl_unlock_function();
770 return;
771 }
772
773 fl_unlock_function();
774
775 // return noErr;
776}
777
778/*
779 * Cocoa Mouse Button Handler
780 */
781static void cocoaMouseHandler(NSEvent *theEvent)
782{
783 static int keysym[] = { 0, FL_Button+1, FL_Button+3, FL_Button+2 };
784 static int px, py;
785 static char suppressed = 0;
786
787 fl_lock_function();
788
789 Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
790 if ( !window->shown() ) {
791 fl_unlock_function();
792 return;
793 }
794 Fl_Window *first = Fl::first_window();
795 if (first != window && !(first->modal() || first->non_modal())) Fl::first_window(window);
796 NSPoint pos = [theEvent locationInWindow];
797 pos.y = window->h() - pos.y;
798 NSInteger btn = [theEvent buttonNumber] + 1;
799 NSUInteger mods = [theEvent modifierFlags];
800 int sendEvent = 0;
801
802 NSEventType etype = [theEvent type];
803 if (etype == NSLeftMouseDown || etype == NSRightMouseDown || etype == NSOtherMouseDown) {
804 if (btn == 1) Fl::e_state |= FL_BUTTON1;
805 else if (btn == 3) Fl::e_state |= FL_BUTTON2;
806 else if (btn == 2) Fl::e_state |= FL_BUTTON3;
807 }
808 else if (etype == NSLeftMouseUp || etype == NSRightMouseUp || etype == NSOtherMouseUp) {
809 if (btn == 1) Fl::e_state &= ~FL_BUTTON1;
810 else if (btn == 3) Fl::e_state &= ~FL_BUTTON2;
811 else if (btn == 2) Fl::e_state &= ~FL_BUTTON3;
812 }
813
814 switch ( etype ) {
815 case NSLeftMouseDown:
816 case NSRightMouseDown:
817 case NSOtherMouseDown:
818 suppressed = 0;
819 sendEvent = FL_PUSH;
820 Fl::e_is_click = 1;
821 px = (int)pos.x; py = (int)pos.y;
822 if ([theEvent clickCount] > 1)
823 Fl::e_clicks++;
824 else
825 Fl::e_clicks = 0;
826 // fall through
827 case NSLeftMouseUp:
828 case NSRightMouseUp:
829 case NSOtherMouseUp:
830 if (suppressed) {
831 suppressed = 0;
832 break;
833 }
834 if ( !window ) break;
835 if ( !sendEvent ) {
836 sendEvent = FL_RELEASE;
837 }
838 Fl::e_keysym = keysym[ btn ];
839 // fall through
840 case NSMouseMoved:
841 suppressed = 0;
842 if ( !sendEvent ) {
843 sendEvent = FL_MOVE;
844 }
845 // fall through
846 case NSLeftMouseDragged:
847 case NSRightMouseDragged:
848 case NSOtherMouseDragged: {
849 if (suppressed) break;
850 if ( !sendEvent ) {
851 sendEvent = FL_MOVE; // Fl::handle will convert into FL_DRAG
852 if (fabs(pos.x-px)>5 || fabs(pos.y-py)>5)
853 Fl::e_is_click = 0;
854 }
855 mods_to_e_state( mods );
856 update_e_xy_and_e_xy_root([theEvent window]);
857 Fl::handle( sendEvent, window );
858 }
859 break;
860 default:
861 break;
862 }
863
864 fl_unlock_function();
865
866 return;
867}
868
869@interface FLTextView : NSTextView
870// this subclass is needed under OS X <= 10.5 but not under >= 10.6 where the base class is enough
871{
872}
873@end
874@implementation FLTextView
875- (void)insertText:(id)aString
876{
877 [[[NSApp keyWindow] contentView] insertText:aString];
878}
879- (void)doCommandBySelector:(SEL)aSelector
880{
881 [[[NSApp keyWindow] contentView] doCommandBySelector:aSelector];
882}
883@end
884
DRC685f17e2011-07-28 09:23:00 +0000885static const char* cocoaDead2FLTK(const char *in)
886{
887 if (strcmp(in, "\140") == 0) // GRAVE ACCENT
888 return "\314\200"; // COMBINING GRAVE ACCENT
889 if (strcmp(in, "\302\264") == 0) // ACUTE ACCENT
890 return "\314\201"; // COMBINING ACUTE ACCENT
891 if (strcmp(in, "\136") == 0) // CIRCUMFLEX ACCENT
892 return "\314\202"; // COMBINING CIRCUMFLEX ACCENT
893 if (strcmp(in, "\176") == 0) // TILDE
894 return "\314\203"; // COMBINING TILDE
895 if (strcmp(in, "\302\250") == 0) // DIAERESIS
896 return "\314\210"; // COMBINING DIAERESIS
897 // FIXME: OS X dead key behaviour isn't documented and I don't have
898 // any more keyboards to test with...
899
900 // hope that OS X gave us something proper to begin with
901 return in;
902}
903
DRC2ff39b82011-07-28 08:38:59 +0000904/*
905Handle cocoa keyboard events
906Events during a character composition sequence:
907 - keydown with deadkey -> [[theEvent characters] length] is 0
908 - keyup -> [theEvent characters] contains the deadkey
909 - keydown with next key -> [theEvent characters] contains the composed character
910 - keyup -> [theEvent characters] contains the standard character
911 */
912static void cocoaKeyboardHandler(NSEvent *theEvent)
913{
914 NSUInteger mods;
915
916 // get the modifiers
917 mods = [theEvent modifierFlags];
918 // get the key code
919 UInt32 keyCode = 0, maskedKeyCode = 0;
920 unsigned short sym = 0;
921 keyCode = [theEvent keyCode];
922 NSString *s = [theEvent characters];
923 if ( (mods & NSShiftKeyMask) && (mods & NSCommandKeyMask) ) {
924 s = [s uppercaseString]; // US keyboards return lowercase letter in s if cmd-shift-key is hit
925 }
926 // extended keyboards can also send sequences on key-up to generate Kanji etc. codes.
927 // Some observed prefixes are 0x81 to 0x83, followed by an 8 bit keycode.
928 // In this mode, there seem to be no key-down codes
929 // printf("%08x %08x %08x\n", keyCode, mods, key);
930 maskedKeyCode = keyCode & 0x7f;
931
932 if ([theEvent type] == NSKeyUp) {
933 Fl::e_state &= 0xbfffffff; // clear the deadkey flag
934 }
935
936 mods_to_e_state( mods ); // process modifier keys
937 sym = macKeyLookUp[maskedKeyCode];
938 if (sym < 0xff00) { // a "simple" key
939 // find the result of this key without modifier
940 NSString *sim = [theEvent charactersIgnoringModifiers];
941 UniChar one;
942 CFStringGetCharacters((CFStringRef)sim, CFRangeMake(0, 1), &one);
943 // charactersIgnoringModifiers doesn't ignore shift, remove it when it's on
944 if(one >= 'A' && one <= 'Z') one += 32;
945 if (one > 0 && one <= 0x7f && (sym<'0' || sym>'9') ) sym = one;
946 }
947 Fl::e_keysym = Fl::e_original_keysym = sym;
948
949 //NSLog(@"cocoaKeyboardHandler: keycode=%08x keysym=%08x mods=%08x symbol=%@ (%@)",
950 // keyCode, sym, mods, [theEvent characters], [theEvent charactersIgnoringModifiers]);
951
952 // If there is text associated with this key, it will be filled in later.
953 Fl::e_length = 0;
954 Fl::e_text = (char*)"";
955}
956
957
958/*
959 * Open callback function to call...
960 */
961
962static void (*open_cb)(const char *) = 0;
963
964
965/*
966 * Install an open documents event handler...
967 */
968@interface FLAppleEventHandler : NSObject
969{
970}
971- (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent: (NSAppleEventDescriptor *)replyEvent;
972@end
973@implementation FLAppleEventHandler
974- (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent: (NSAppleEventDescriptor *)replyEvent
975{
976 NSAppleEventDescriptor *single = [event descriptorAtIndex:1];
977 const AEDesc *document = [single aeDesc];
978 long i, n;
979 FSRef fileRef;
980 AEKeyword keyWd;
981 DescType typeCd;
982 Size actSz;
983 char filename[1024];
984 // Lock access to FLTK in this thread...
985 fl_lock_function();
986
987 // Open the documents via the callback...
988 if (AECountItems(document, &n) == noErr) {
989 for (i = 1; i <= n; i ++) {
990 AEGetNthPtr(document, i, typeFSRef, &keyWd, &typeCd,
991 (Ptr)&fileRef, sizeof(fileRef),
992 (actSz = sizeof(fileRef), &actSz));
993 FSRefMakePath( &fileRef, (UInt8*)filename, sizeof(filename) );
994
995 (*open_cb)(filename);
996 }
997 }
998 // Unlock access to FLTK for all threads...
999 fl_unlock_function();
1000}
1001@end
1002
1003void fl_open_callback(void (*cb)(const char *)) {
1004 static NSAppleEventManager *aeventmgr = nil;
1005 static FLAppleEventHandler *handler;
1006 fl_open_display();
1007 if (!aeventmgr) {
1008 aeventmgr = [NSAppleEventManager sharedAppleEventManager];
1009 handler = [[FLAppleEventHandler alloc] init];
1010 }
1011
1012 open_cb = cb;
1013 if (cb) {
1014 [aeventmgr setEventHandler:handler andSelector: @selector(handleAppleEvent:withReplyEvent:)
1015 forEventClass:kCoreEventClass andEventID:kAEOpenDocuments];
1016 } else {
1017 [aeventmgr removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEOpenDocuments];
1018 }
1019}
1020
1021
1022/*
1023 * initialize the Mac toolboxes, dock status, and set the default menubar
1024 */
1025
1026extern "C" {
1027 extern OSErr CPSEnableForegroundOperation(ProcessSerialNumber *psn, UInt32 _arg2,
1028 UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
1029}
1030
1031
1032@interface FLDelegate : NSObject
1033#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1034<NSWindowDelegate, NSApplicationDelegate>
1035#endif
1036{
1037}
1038- (void)windowDidMove:(NSNotification *)notif;
1039- (void)windowDidResize:(NSNotification *)notif;
1040- (void)windowDidResignKey:(NSNotification *)notif;
1041- (void)windowDidBecomeKey:(NSNotification *)notif;
1042- (void)windowDidBecomeMain:(NSNotification *)notif;
1043- (void)windowDidDeminiaturize:(NSNotification *)notif;
1044- (void)windowDidMiniaturize:(NSNotification *)notif;
1045- (void)windowWillClose:(NSNotification *)notif;
1046- (void)anywindowwillclosenotif:(NSNotification *)notif;
1047- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender;
1048- (void)applicationDidBecomeActive:(NSNotification *)notify;
1049- (void)applicationWillResignActive:(NSNotification *)notify;
1050- (void)applicationWillHide:(NSNotification *)notify;
1051- (void)applicationWillUnhide:(NSNotification *)notify;
1052- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client;
1053@end
1054@implementation FLDelegate
1055- (void)windowDidMove:(NSNotification *)notif
1056{
1057 fl_lock_function();
1058 FLWindow *nsw = (FLWindow*)[notif object];
1059 Fl_Window *window = [nsw getFl_Window];
1060 NSPoint pt, pt2;
1061 pt.x = 0;
1062 pt.y = [[nsw contentView] frame].size.height;
1063 pt2 = [nsw convertBaseToScreen:pt];
1064 update_e_xy_and_e_xy_root(nsw);
1065 window->position((int)pt2.x, (int)([[nsw screen] frame].size.height - pt2.y));
1066 if ([nsw containsGLsubwindow] ) {
1067 [nsw display];// redraw window after moving if it contains OpenGL subwindows
1068 }
1069 fl_unlock_function();
1070}
1071- (void)windowDidResize:(NSNotification *)notif
1072{
1073 fl_lock_function();
1074 FLWindow *nsw = (FLWindow*)[notif object];
1075 Fl_Window *window = [nsw getFl_Window];
1076 NSRect r = [[nsw contentView] frame];
1077 NSPoint pt, pt2;
1078 pt.x = 0;
1079 pt.y = [[nsw contentView] frame].size.height;
1080 pt2 = [nsw convertBaseToScreen:pt];
1081 resize_from_system = window;
1082 update_e_xy_and_e_xy_root(nsw);
1083 window->resize((int)pt2.x,
1084 (int)([[nsw screen] frame].size.height - pt2.y),
1085 (int)r.size.width,
1086 (int)r.size.height);
1087 fl_unlock_function();
1088}
1089- (void)windowDidResignKey:(NSNotification *)notif
1090{
1091 fl_lock_function();
1092 FLWindow *nsw = (FLWindow*)[notif object];
1093 Fl_Window *window = [nsw getFl_Window];
DRC685f17e2011-07-28 09:23:00 +00001094 /* Fullscreen windows obscure all other windows so we need to return
1095 to a "normal" level when the user switches to another window */
1096 if (window->fullscreen_active())
1097 [nsw setLevel:NSNormalWindowLevel];
DRC2ff39b82011-07-28 08:38:59 +00001098 Fl::handle( FL_UNFOCUS, window);
1099 fl_unlock_function();
1100}
1101- (void)windowDidBecomeKey:(NSNotification *)notif
1102{
1103 fl_lock_function();
1104 FLWindow *nsw = (FLWindow*)[notif object];
1105 Fl_Window *w = [nsw getFl_Window];
DRC685f17e2011-07-28 09:23:00 +00001106 /* Restore previous fullscreen level */
1107 if (w->fullscreen_active())
1108 [nsw setLevel:NSStatusWindowLevel];
DRC2ff39b82011-07-28 08:38:59 +00001109 if ( w->border() || (!w->modal() && !w->tooltip_window()) ) Fl::handle( FL_FOCUS, w);
1110 fl_unlock_function();
1111}
1112- (void)windowDidBecomeMain:(NSNotification *)notif
1113{
1114 fl_lock_function();
1115 FLWindow *nsw = (FLWindow*)[notif object];
1116 Fl_Window *window = [nsw getFl_Window];
1117 Fl::first_window(window);
1118 update_e_xy_and_e_xy_root(nsw);
1119 fl_unlock_function();
1120}
1121- (void)windowDidDeminiaturize:(NSNotification *)notif
1122{
1123 fl_lock_function();
1124 FLWindow *nsw = (FLWindow*)[notif object];
1125 Fl_Window *window = [nsw getFl_Window];
1126 Fl::handle(FL_SHOW, window);
1127 update_e_xy_and_e_xy_root(nsw);
1128 fl_unlock_function();
1129}
1130- (void)windowDidMiniaturize:(NSNotification *)notif
1131{
1132 fl_lock_function();
1133 FLWindow *nsw = (FLWindow*)[notif object];
1134 Fl_Window *window = [nsw getFl_Window];
1135 Fl::handle(FL_HIDE, window);
1136 fl_unlock_function();
1137}
1138- (void)windowWillClose:(NSNotification *)notif
1139{
1140 fl_lock_function();
1141 Fl_Window *w = Fl::first_window();
1142 if (w) {
1143 NSWindow *cw = (NSWindow*)Fl_X::i(w)->xid;
1144 if ( ![cw isMiniaturized] && ([cw styleMask] & NSTitledWindowMask) ) {
1145 if (![cw isKeyWindow]) { // always make Fl::first_window() the key widow
1146 [cw makeKeyAndOrderFront:nil];
1147 }
1148 if (![cw isMainWindow]) { // always make Fl::first_window() the main widow
1149 [cw makeMainWindow];
1150 }
1151 }
1152 }
1153 fl_unlock_function();
1154}
1155- (void)anywindowwillclosenotif:(NSNotification *)notif
1156{
1157 // necessary so that after closing a non-FLTK window (e.g., Fl_Native_File_Chooser)
1158 // the front window turns key again
1159 NSWindow *closing = (NSWindow*)[notif object];
1160 if ([closing isMemberOfClass:[FLWindow class]]) return;
1161 NSWindow *nsk = [NSApp keyWindow];
1162 NSWindow *nsm = [NSApp mainWindow];
1163 if ([nsm isMemberOfClass:[FLWindow class]] && nsk == nil) {
1164 [nsm makeKeyAndOrderFront:nil];
1165 }
1166}
1167- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender
1168{
1169 fl_lock_function();
1170 NSApplicationTerminateReply reply = NSTerminateNow;
1171 while ( Fl_X::first ) {
1172 Fl_X *x = Fl_X::first;
1173 Fl::handle( FL_CLOSE, x->w );
1174 if ( Fl_X::first == x ) {
1175 reply = NSTerminateCancel; // FLTK has not closed all windows, so we return to the main program now
1176 break;
1177 }
1178 }
1179 fl_unlock_function();
1180 return reply;
1181}
1182/**
1183 * Cocoa organizes the Z depth of windows on a global priority. FLTK however
1184 * expects the window manager to organize Z level by application. The trickery
1185 * below will change Z order during activation and deactivation.
1186 */
1187- (void)applicationDidBecomeActive:(NSNotification *)notify
1188{
1189 fl_lock_function();
1190 Fl_X *x;
1191 FLWindow *top = 0, *topModal = 0, *topNonModal = 0;
1192 for (x = Fl_X::first;x;x = x->next) {
1193 FLWindow *cw = (FLWindow*)x->xid;
1194 Fl_Window *win = x->w;
1195 if (win && cw) {
1196 if (win->modal()) {
1197 [cw setLevel:NSModalPanelWindowLevel];
1198 if (topModal)
1199 [cw orderWindow:NSWindowBelow relativeTo:[topModal windowNumber]];
1200 else
1201 topModal = cw;
1202 } else if (win->non_modal()) {
1203 [cw setLevel:NSFloatingWindowLevel];
1204 if (topNonModal)
1205 [cw orderWindow:NSWindowBelow relativeTo:[topNonModal windowNumber]];
1206 else
1207 topNonModal = cw;
1208 } else {
1209 if (top)
1210 ;
1211 else
1212 top = cw;
1213 }
1214 }
1215 }
1216 fl_unlock_function();
1217}
1218- (void)applicationWillResignActive:(NSNotification *)notify
1219{
1220 fl_lock_function();
1221 Fl_X *x;
1222 FLWindow *top = 0;
1223 // sort in all regular windows
1224 for (x = Fl_X::first;x;x = x->next) {
1225 FLWindow *cw = (FLWindow*)x->xid;
1226 Fl_Window *win = x->w;
1227 if (win && cw) {
1228 if (win->modal()) {
1229 } else if (win->non_modal()) {
1230 } else {
1231 if (!top) top = cw;
1232 }
1233 }
1234 }
1235 // now sort in all modals
1236 for (x = Fl_X::first;x;x = x->next) {
1237 FLWindow *cw = (FLWindow*)x->xid;
1238 Fl_Window *win = x->w;
1239 if (win && cw) {
1240 if (win->modal()) {
1241 [cw setLevel:NSNormalWindowLevel];
1242 if (top) [cw orderWindow:NSWindowAbove relativeTo:[top windowNumber]];
1243 }
1244 }
1245 }
1246 // finally all non-modals
1247 for (x = Fl_X::first;x;x = x->next) {
1248 FLWindow *cw = (FLWindow*)x->xid;
1249 Fl_Window *win = x->w;
1250 if (win && cw) {
1251 if (win->non_modal()) {
1252 [cw setLevel:NSNormalWindowLevel];
1253 if (top) [cw orderWindow:NSWindowAbove relativeTo:[top windowNumber]];
1254 }
1255 }
1256 }
1257 fl_unlock_function();
1258}
1259- (void)applicationWillHide:(NSNotification *)notify
1260{
1261 fl_lock_function();
1262 Fl_X *x;
1263 for (x = Fl_X::first;x;x = x->next) {
1264 Fl_Window *window = x->w;
1265 if ( !window->parent() ) Fl::handle( FL_HIDE, window);
1266 }
1267 fl_unlock_function();
1268}
1269- (void)applicationWillUnhide:(NSNotification *)notify
1270{
1271 fl_lock_function();
1272 Fl_X *x;
1273 for (x = Fl_X::first;x;x = x->next) {
1274 Fl_Window *w = x->w;
1275 if ( !w->parent() ) {
1276 if ( w->border() || (!w->modal() && !w->tooltip_window()) ) Fl::handle( FL_FOCUS, w);
1277 Fl::handle( FL_SHOW, w);
1278 }
1279 }
1280 fl_unlock_function();
1281}
1282- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client
1283{
1284 if (fl_mac_os_version < 100600) {
1285 static FLTextView *view = nil;
1286 if (!view) {
1287 NSRect rect={{0,0},{20,20}};
1288 view = [[FLTextView alloc] initWithFrame:rect];
1289 }
1290 return view;
1291 }
1292 return nil;
1293}
1294@end
1295
DRC685f17e2011-07-28 09:23:00 +00001296static void clipboard_check(void);
1297
DRC2ff39b82011-07-28 08:38:59 +00001298@implementation FLApplication
1299+ (void)sendEvent:(NSEvent *)theEvent
1300{
DRC685f17e2011-07-28 09:23:00 +00001301 // update clipboard status
1302 clipboard_check();
DRC2ff39b82011-07-28 08:38:59 +00001303 NSEventType type = [theEvent type];
1304 if (type == NSLeftMouseDown) {
1305 fl_lock_function();
1306 Fl_Window *grab = Fl::grab();
1307 if (grab) {
1308 FLWindow *win = (FLWindow *)[theEvent window];
1309 if ( [win isKindOfClass:[FLWindow class]] && grab != [win getFl_Window]) {
1310 // a click event out of a menu window, so we should close this menu
1311 // done here to catch also clicks on window title bar/resize box
1312 cocoaMouseHandler(theEvent);
1313 }
1314 }
1315 fl_unlock_function();
1316 } else if (type == NSApplicationDefined) {
1317 if ([theEvent subtype] == FLTKDataReadyEvent) {
1318 processFLTKEvent();
1319 }
1320 return;
1321 } else if (type == NSKeyUp) {
1322 // The default sendEvent turns key downs into performKeyEquivalent when
1323 // modifiers are down, but swallows the key up if the modifiers include
1324 // command. This one makes all modifiers consistent by always sending key ups.
1325 // FLView treats performKeyEquivalent to keyDown, but performKeyEquivalent is
1326 // still needed for the system menu.
1327 [[NSApp keyWindow] sendEvent:theEvent];
1328 return;
1329 }
1330 [NSApp sendEvent:theEvent];
1331}
1332@end
1333
1334static FLDelegate *mydelegate;
1335
1336void fl_open_display() {
1337 static char beenHereDoneThat = 0;
1338 if ( !beenHereDoneThat ) {
1339 beenHereDoneThat = 1;
1340
1341 BOOL need_new_nsapp = (NSApp == nil);
1342 if (need_new_nsapp) [NSApplication sharedApplication];
1343 NSAutoreleasePool *localPool;
1344 localPool = [[NSAutoreleasePool alloc] init]; // never released
1345 mydelegate = [[FLDelegate alloc] init];
1346 [NSApp setDelegate:mydelegate];
1347 if (need_new_nsapp) [NSApp finishLaunching];
1348
1349 // empty the event queue but keep system events for drag&drop of files at launch
1350 NSEvent *ign_event;
1351 do ign_event = [NSApp nextEventMatchingMask:(NSAnyEventMask & ~NSSystemDefinedMask)
1352 untilDate:[NSDate dateWithTimeIntervalSinceNow:0]
1353 inMode:NSDefaultRunLoopMode
1354 dequeue:YES];
1355 while (ign_event);
1356
DRC2ff39b82011-07-28 08:38:59 +00001357 // bring the application into foreground without a 'CARB' resource
1358 Boolean same_psn;
1359 ProcessSerialNumber cur_psn, front_psn;
1360 if ( !GetCurrentProcess( &cur_psn ) && !GetFrontProcess( &front_psn ) &&
1361 !SameProcess( &front_psn, &cur_psn, &same_psn ) && !same_psn ) {
1362 // only transform the application type for unbundled apps
1363 CFBundleRef bundle = CFBundleGetMainBundle();
1364 if ( bundle ) {
1365 FSRef execFs;
1366 CFURLRef execUrl = CFBundleCopyExecutableURL( bundle );
1367 CFURLGetFSRef( execUrl, &execFs );
1368
1369 FSRef bundleFs;
1370 GetProcessBundleLocation( &cur_psn, &bundleFs );
1371
1372 if ( !FSCompareFSRefs( &execFs, &bundleFs ) )
1373 bundle = NULL;
1374
1375 CFRelease(execUrl);
1376 }
1377
1378 if ( !bundle )
1379 {
1380 // Earlier versions of this code tried to use weak linking, however it
1381 // appears that this does not work on 10.2. Since 10.3 and higher provide
1382 // both TransformProcessType and CPSEnableForegroundOperation, the following
1383 // conditional code compiled on 10.2 will still work on newer releases...
1384 OSErr err;
1385#if __LP64__
1386 err = TransformProcessType(&cur_psn, kProcessTransformToForegroundApplication);
1387#else
1388
1389#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_2
1390 if (TransformProcessType != NULL) {
1391 err = TransformProcessType(&cur_psn, kProcessTransformToForegroundApplication);
1392 } else
1393#endif // MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_2
1394 err = CPSEnableForegroundOperation(&cur_psn, 0x03, 0x3C, 0x2C, 0x1103);
1395#endif // __LP64__
1396 if (err == noErr) {
1397 SetFrontProcess( &cur_psn );
1398 }
1399 }
1400 }
1401 if (![NSApp servicesMenu]) createAppleMenu();
1402 fl_system_menu = [NSApp mainMenu];
1403
1404 [[NSNotificationCenter defaultCenter] addObserver:mydelegate
1405 selector:@selector(anywindowwillclosenotif:)
1406 name:NSWindowWillCloseNotification
1407 object:nil];
1408 }
1409}
1410
1411
1412/*
1413 * get rid of allocated resources
1414 */
1415void fl_close_display() {
1416}
1417
1418
1419// Gets the border sizes and the titlebar size
1420static void get_window_frame_sizes(int &bx, int &by, int &bt) {
1421 static bool first = true;
1422 static int top, left, bottom;
1423 if (first) {
1424 first = false;
1425 if (NSApp == nil) fl_open_display();
1426 NSRect inside = { {20,20}, {100,100} };
1427 NSRect outside = [NSWindow frameRectForContentRect:inside styleMask:NSTitledWindowMask];
1428 left = int(outside.origin.x - inside.origin.x);
1429 bottom = int(outside.origin.y - inside.origin.y);
1430 top = int(outside.size.height - inside.size.height) - bottom;
1431 }
1432 bx = left;
1433 by = bottom;
1434 bt = top;
1435}
1436
1437/*
1438 * smallest x ccordinate in screen space
1439 */
1440int Fl::x() {
1441 return int([[NSScreen mainScreen] visibleFrame].origin.x);
1442}
1443
1444
1445/*
1446 * smallest y coordinate in screen space
1447 */
1448int Fl::y() {
1449 NSRect all = [[NSScreen mainScreen] frame];
1450 NSRect visible = [[NSScreen mainScreen] visibleFrame];
1451 return int(all.size.height - (visible.origin.y + visible.size.height));
1452}
1453
1454
1455/*
1456 * screen width
1457 */
1458int Fl::w() {
1459 return int([[NSScreen mainScreen] visibleFrame].size.width);
1460}
1461
1462
1463/*
1464 * screen height
1465 */
1466int Fl::h() {
1467 return int([[NSScreen mainScreen] visibleFrame].size.height);
1468}
1469
1470
1471/*
1472 * get the current mouse pointer world coordinates
1473 */
1474void Fl::get_mouse(int &x, int &y)
1475{
1476 fl_open_display();
1477 NSPoint pt = [NSEvent mouseLocation];
1478 x = int(pt.x);
1479 y = int([[NSScreen mainScreen] frame].size.height - pt.y);
1480}
1481
1482
1483/*
1484 * Initialize the given port for redraw and call the window's flush() to actually draw the content
1485 */
1486void Fl_X::flush()
1487{
1488 w->flush();
1489 if (fl_gc) CGContextFlush(fl_gc);
1490}
1491
1492/*
1493 * Gets called when a window is created, resized, or deminiaturized
1494 */
1495static void handleUpdateEvent( Fl_Window *window )
1496{
1497 if ( !window ) return;
1498 Fl_X *i = Fl_X::i( window );
1499 i->wait_for_expose = 0;
1500
1501 if ( i->region ) {
1502 XDestroyRegion(i->region);
1503 i->region = 0;
1504 }
1505
1506 for ( Fl_X *cx = i->xidChildren; cx; cx = cx->xidNext ) {
1507 if ( cx->region ) {
1508 XDestroyRegion(cx->region);
1509 cx->region = 0;
1510 }
1511 cx->w->clear_damage(FL_DAMAGE_ALL);
1512 cx->flush();
1513 cx->w->clear_damage();
1514 }
1515 window->clear_damage(FL_DAMAGE_ALL);
1516 i->flush();
1517 window->clear_damage();
1518}
1519
1520
1521int Fl_X::fake_X_wm(const Fl_Window* w,int &X,int &Y, int &bt,int &bx, int &by) {
1522 int W, H, xoff, yoff, dx, dy;
1523 int ret = bx = by = bt = 0;
1524 if (w->border() && !w->parent()) {
1525 if (w->maxw != w->minw || w->maxh != w->minh) {
1526 ret = 2;
1527 } else {
1528 ret = 1;
1529 }
1530 get_window_frame_sizes(bx, by, bt);
1531 }
1532 // The coordinates of the whole window, including non-client area
1533 xoff = bx;
1534 yoff = by + bt;
1535 dx = 2*bx;
1536 dy = 2*by + bt;
1537 X = w->x()-xoff;
1538 Y = w->y()-yoff;
1539 W = w->w()+dx;
1540 H = w->h()+dy;
1541
1542 // Proceed to positioning the window fully inside the screen, if possible
1543
1544 // let's get a little elaborate here. Mac OS X puts a lot of stuff on the desk
1545 // that we want to avoid when positioning our window, namely the Dock and the
1546 // top menu bar (and even more stuff in 10.4 Tiger). So we will go through the
1547 // list of all available screens and find the one that this window is most
1548 // likely to go to, and then reposition it to fit withing the 'good' area.
1549 // Rect r;
1550 // find the screen, that the center of this window will fall into
1551 int R = X+W, B = Y+H; // right and bottom
1552 int cx = (X+R)/2, cy = (Y+B)/2; // center of window;
1553 NSScreen *gd = NULL;
1554 NSArray *a = [NSScreen screens]; int count = (int)[a count]; NSRect r; int i;
1555 for( i = 0; i < count; i++) {
1556 r = [[a objectAtIndex:i] frame];
1557 cy = int(r.size.height - cy);
1558 if ( cx >= r.origin.x && cx <= r.origin.x + r.size.width
1559 && cy >= r.origin.y && cy <= r.origin.y + r.size.height)
1560 break;
1561 }
1562 if (i < count) gd = [a objectAtIndex:i];
1563
1564 // if the center doesn't fall on a screen, try the top left
1565 if (!gd) {
1566 for( i = 0; i < count; i++) {
1567 r = [[a objectAtIndex:i] frame];
1568 if ( X >= r.origin.x && X <= r.origin.x + r.size.width
1569 && r.size.height - Y >= r.origin.y && r.size.height - Y <= r.origin.y + r.size.height)
1570 break;
1571 }
1572 if (i < count) gd = [a objectAtIndex:i];
1573 }
1574 // if that doesn't fall on a screen, try the top right
1575 if (!gd) {
1576 for( i = 0; i < count; i++) {
1577 r = [[a objectAtIndex:i] frame];
1578 if ( R >= r.origin.x && R <= r.origin.x + r.size.width
1579 && r.size.height - Y >= r.origin.y && r.size.height - Y <= r.origin.y + r.size.height)
1580 break;
1581 }
1582 if (i < count) gd = [a objectAtIndex:i];
1583 }
1584 // if that doesn't fall on a screen, try the bottom left
1585 if (!gd) {
1586 for( i = 0; i < count; i++) {
1587 r = [[a objectAtIndex:i] frame];
1588 if ( X >= r.origin.x && X <= r.origin.x + r.size.width
1589 && Y-H >= r.origin.y && Y-H <= r.origin.y + r.size.height)
1590 break;
1591 }
1592 if (i < count) gd = [a objectAtIndex:i];
1593 }
1594 // last resort, try the bottom right
1595 if (!gd) {
1596 for( i = 0; i < count; i++) {
1597 r = [[a objectAtIndex:i] frame];
1598 if ( R >= r.origin.x && R <= r.origin.x + r.size.width
1599 && Y-H >= r.origin.y && Y-H <= r.origin.y + r.size.height)
1600 break;
1601 }
1602 if (i < count) gd = [a objectAtIndex:i];
1603 }
1604 // if we still have not found a screen, we will use the main
1605 // screen, the one that has the application menu bar.
1606 if (!gd) gd = [a objectAtIndex:0];
1607 if (gd) {
1608 r = [gd visibleFrame];
1609 int sh = int([gd frame].size.height);
1610 if ( R > r.origin.x + r.size.width ) X -= int(R - (r.origin.x + r.size.width));
1611 if ( B > sh - r.origin.y ) Y -= int(B - (sh - r.origin.y));
1612 if ( X < r.origin.x ) X = int(r.origin.x);
1613 if ( Y < sh - (r.origin.y + r.size.height) ) Y = int(sh - (r.origin.y + r.size.height));
1614 }
1615
1616 // Return the client area's top left corner in (X,Y)
1617 X+=xoff;
1618 Y+=yoff;
1619
1620 return ret;
1621}
1622
1623
1624Fl_Window *fl_dnd_target_window = 0;
1625
1626static void q_set_window_title(NSWindow *nsw, const char * name, const char *mininame) {
1627 CFStringRef title = CFStringCreateWithCString(NULL, (name ? name : ""), kCFStringEncodingUTF8);
1628 if(!title) { // fallback when name contains malformed UTF-8
1629 int l = strlen(name);
1630 unsigned short* utf16 = new unsigned short[l + 1];
1631 l = fl_utf8toUtf16(name, l, utf16, l + 1);
1632 title = CFStringCreateWithCharacters(NULL, utf16, l);
1633 delete[] utf16;
1634 }
1635 [nsw setTitle:(NSString*)title];
1636 CFRelease(title);
1637 if (mininame && strlen(mininame)) {
1638 CFStringRef minititle = CFStringCreateWithCString(NULL, mininame, kCFStringEncodingUTF8);
1639 if (minititle) {
1640 [nsw setMiniwindowTitle:(NSString*)minititle];
1641 CFRelease(minititle);
1642 }
1643 }
1644}
1645
1646
1647@interface FLView : NSView <NSTextInput> {
1648 int next_compose_length;
1649 bool in_key_event;
1650}
1651+ (void)prepareEtext:(NSString*)aString;
1652- (id)init;
1653- (void)drawRect:(NSRect)rect;
1654- (BOOL)acceptsFirstResponder;
1655- (BOOL)acceptsFirstMouse:(NSEvent*)theEvent;
DRC685f17e2011-07-28 09:23:00 +00001656- (void)resetCursorRects;
DRC2ff39b82011-07-28 08:38:59 +00001657- (BOOL)performKeyEquivalent:(NSEvent*)theEvent;
1658- (void)mouseUp:(NSEvent *)theEvent;
1659- (void)rightMouseUp:(NSEvent *)theEvent;
1660- (void)otherMouseUp:(NSEvent *)theEvent;
1661- (void)mouseDown:(NSEvent *)theEvent;
1662- (void)rightMouseDown:(NSEvent *)theEvent;
1663- (void)otherMouseDown:(NSEvent *)theEvent;
1664- (void)mouseMoved:(NSEvent *)theEvent;
1665- (void)mouseDragged:(NSEvent *)theEvent;
1666- (void)rightMouseDragged:(NSEvent *)theEvent;
1667- (void)otherMouseDragged:(NSEvent *)theEvent;
1668- (void)scrollWheel:(NSEvent *)theEvent;
Henrik Andersson485f4192011-09-16 11:51:32 +00001669+ (NSString *)keyTranslate:(UInt16)keyCode withModifierFlags:(UInt32)modifierFlags;
DRC2ff39b82011-07-28 08:38:59 +00001670- (BOOL)handleKeyDown:(NSEvent *)theEvent;
1671- (void)keyDown:(NSEvent *)theEvent;
1672- (void)keyUp:(NSEvent *)theEvent;
1673- (void)flagsChanged:(NSEvent *)theEvent;
1674- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender;
1675- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender;
1676- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
1677- (void)draggingExited:(id < NSDraggingInfo >)sender;
1678- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal;
1679@end
1680
1681@implementation FLView
1682- (id)init
1683{
1684 self = [super init];
1685 if (self) {
1686 next_compose_length = -1;
1687 in_key_event = false;
1688 }
1689 return self;
1690}
1691- (void)drawRect:(NSRect)rect
1692{
1693 fl_lock_function();
1694 FLWindow *cw = (FLWindow*)[self window];
1695 Fl_Window *w = [cw getFl_Window];
1696 handleUpdateEvent(w);
1697 fl_unlock_function();
1698}
1699
1700- (BOOL)acceptsFirstResponder
1701{
1702 return YES;
1703}
1704- (BOOL)performKeyEquivalent:(NSEvent*)theEvent
1705{
1706 //NSLog(@"performKeyEquivalent:");
1707 return [self handleKeyDown:theEvent];
1708}
1709- (BOOL)acceptsFirstMouse:(NSEvent*)theEvent
1710{
1711 Fl_Window *w = [(FLWindow*)[theEvent window] getFl_Window];
1712 Fl_Window *first = Fl::first_window();
1713 return (first == w || !first->modal());
1714}
DRC685f17e2011-07-28 09:23:00 +00001715- (void)resetCursorRects {
1716 Fl_Window *w = [(FLWindow*)[self window] getFl_Window];
1717 Fl_X *i = Fl_X::i(w);
1718 // We have to have at least one cursor rect for invalidateCursorRectsForView
1719 // to work, hence the "else" clause.
1720 if (i->cursor)
1721 [self addCursorRect:[self visibleRect] cursor:(NSCursor*)i->cursor];
1722 else
1723 [self addCursorRect:[self visibleRect] cursor:[NSCursor arrowCursor]];
1724}
DRC2ff39b82011-07-28 08:38:59 +00001725- (void)mouseUp:(NSEvent *)theEvent {
1726 cocoaMouseHandler(theEvent);
1727}
1728- (void)rightMouseUp:(NSEvent *)theEvent {
1729 cocoaMouseHandler(theEvent);
1730}
1731- (void)otherMouseUp:(NSEvent *)theEvent {
1732 cocoaMouseHandler(theEvent);
1733}
1734- (void)mouseDown:(NSEvent *)theEvent {
1735 cocoaMouseHandler(theEvent);
1736}
1737- (void)rightMouseDown:(NSEvent *)theEvent {
1738 cocoaMouseHandler(theEvent);
1739}
1740- (void)otherMouseDown:(NSEvent *)theEvent {
1741 cocoaMouseHandler(theEvent);
1742}
1743- (void)mouseMoved:(NSEvent *)theEvent {
1744 cocoaMouseHandler(theEvent);
1745}
1746- (void)mouseDragged:(NSEvent *)theEvent {
1747 cocoaMouseHandler(theEvent);
1748}
1749- (void)rightMouseDragged:(NSEvent *)theEvent {
1750 cocoaMouseHandler(theEvent);
1751}
1752- (void)otherMouseDragged:(NSEvent *)theEvent {
1753 cocoaMouseHandler(theEvent);
1754}
1755- (void)scrollWheel:(NSEvent *)theEvent {
1756 cocoaMouseWheelHandler(theEvent);
1757}
Henrik Andersson485f4192011-09-16 11:51:32 +00001758+ (NSString *)keyTranslate:(UInt16)keyCode withModifierFlags:(UInt32)modifierFlags {
1759 const UCKeyboardLayout *layout;
1760 OSStatus err;
1761
1762 layout = NULL;
1763
1764#if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
1765 TISInputSourceRef keyboard;
1766 CFDataRef uchr;
1767
1768 keyboard = TISCopyCurrentKeyboardInputSource();
1769 uchr = (CFDataRef)TISGetInputSourceProperty(keyboard,
1770 kTISPropertyUnicodeKeyLayoutData);
1771 if (uchr == NULL)
1772 return nil;
1773
1774 layout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
1775#else
1776 KeyboardLayoutRef old_layout;
1777 int kind;
1778
1779 err = KLGetCurrentKeyboardLayout(&old_layout);
1780 if (err != noErr)
1781 return nil;
1782
1783 err = KLGetKeyboardLayoutProperty(old_layout, kKLKind,
1784 (const void**)&kind);
1785 if (err != noErr)
1786 return nil;
1787
1788 // Old, crufty layout format?
1789 if (kind == kKLKCHRKind) {
1790 void *kchr_layout;
1791
1792 UInt32 chars, state;
1793 char buf[3];
1794
1795 unichar result[16];
1796 ByteCount in_len, out_len;
1797
1798 err = KLGetKeyboardLayoutProperty(old_layout, kKLKCHRData,
1799 (const void**)&kchr_layout);
1800 if (err != noErr)
1801 return nil;
1802
1803 state = 0;
1804
1805 keyCode &= 0x7f;
1806 modifierFlags &= 0xff00;
1807
1808 chars = KeyTranslate(kchr_layout, keyCode | modifierFlags, &state);
1809
1810 buf[0] = (chars >> 16) & 0xff;
1811 buf[1] = chars & 0xff;
1812 buf[2] = '\0';
1813
1814 if (buf[0] == '\0') {
1815 buf[0] = buf[1];
1816 buf[1] = '\0';
1817 }
1818
1819 // The data is now in some layout specific encoding. Need to convert
1820 // this to unicode.
1821
1822 ScriptCode script;
1823 TextEncoding encoding;
1824 TECObjectRef converter;
1825
1826 script = (ScriptCode)GetScriptManagerVariable(smKeyScript);
1827
1828 err = UpgradeScriptInfoToTextEncoding(script, kTextLanguageDontCare,
1829 kTextRegionDontCare, NULL,
1830 &encoding);
1831 if (err != noErr)
1832 return nil;
1833
1834 err = TECCreateConverter(&converter, encoding, kTextEncodingUnicodeV4_0);
1835 if (err != noErr)
1836 return nil;
1837
1838 in_len = strlen(buf);
1839 out_len = sizeof(result);
1840
1841 err = TECConvertText(converter, (ConstTextPtr)buf, in_len, &in_len,
1842 (TextPtr)result, out_len, &out_len);
1843
1844 TECDisposeConverter(converter);
1845
1846 if (err != noErr)
1847 return nil;
1848
1849 return [NSString stringWithCharacters:result
1850 length:(out_len / sizeof(unichar))];
1851 }
1852
1853 if ((kind != kKLKCHRuchrKind) && (kind != kKLuchrKind))
1854 return nil;
1855
1856 err = KLGetKeyboardLayoutProperty(old_layout, kKLuchrData,
1857 (const void**)&layout);
1858 if (err != noErr)
1859 return nil;
1860#endif
1861
1862 if (layout == NULL)
1863 return nil;
1864
1865 UInt32 dead_state;
1866 UniCharCount max_len, actual_len;
1867 UniChar string[255];
1868
1869 dead_state = 0;
1870 max_len = sizeof(string)/sizeof(*string);
1871
1872 modifierFlags = (modifierFlags >> 8) & 0xff;
1873
1874 err = UCKeyTranslate(layout, keyCode, kUCKeyActionDown, modifierFlags,
1875 LMGetKbdType(), 0, &dead_state, max_len, &actual_len,
1876 string);
1877 if (err != noErr)
1878 return nil;
1879
1880 return [NSString stringWithCharacters:string length:actual_len];
1881}
DRC2ff39b82011-07-28 08:38:59 +00001882- (BOOL)handleKeyDown:(NSEvent *)theEvent {
1883 //NSLog(@"handleKeyDown");
1884 fl_lock_function();
1885
1886 Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
1887 Fl::first_window(window);
1888
1889 next_compose_length = -1;
1890 // First let's process the raw key press
1891 cocoaKeyboardHandler(theEvent);
1892
1893 int no_text_key = false;
1894 static const int notext[] = { // keys that don't emit text
1895 FL_BackSpace, FL_Print, FL_Scroll_Lock, FL_Pause,
1896 FL_Insert, FL_Home, FL_Page_Up, FL_Delete, FL_End, FL_Page_Down,
1897 FL_Left, FL_Up, FL_Right, FL_Down,
1898 FL_Menu, FL_Num_Lock, FL_Help
1899 };
1900 static const int count = sizeof(notext)/sizeof(int);
1901 if (Fl::e_keysym > FL_F && Fl::e_keysym <= FL_F_Last) no_text_key = true;
1902 else for (int i=0; i < count; i++) {
1903 if (notext[i] == Fl::e_keysym) {
1904 no_text_key = true;
1905 break;
1906 }
1907 }
Henrik Andersson485f4192011-09-16 11:51:32 +00001908 if (!no_text_key) {
DRC685f17e2011-07-28 09:23:00 +00001909 // The simple keyboard model will ignore insertText, so we need to grab
1910 // the symbol directly from the event. Note that we still use setMarkedText.
Henrik Andersson485f4192011-09-16 11:51:32 +00001911 if (use_simple_keyboard) {
1912 NSString *simple_chars;
1913 UInt32 modifiers;
1914
1915 // We want a "normal" symbol out of the event, which basically means
1916 // we only respect the shift and alt/altgr modifiers. Cocoa can help
1917 // us if we only wanted shift, but as we also want alt/altgr, we'll
1918 // have to do some lookup ourselves. This matches our behaviour on
1919 // other platforms.
1920
1921 modifiers = 0;
1922 if ([theEvent modifierFlags] & NSAlphaShiftKeyMask)
1923 modifiers |= alphaLock;
1924 if ([theEvent modifierFlags] & NSShiftKeyMask)
1925 modifiers |= shiftKey;
1926 if ([theEvent modifierFlags] & NSAlternateKeyMask)
1927 modifiers |= optionKey;
1928
1929 simple_chars = [FLView keyTranslate:[theEvent keyCode]
1930 withModifierFlags:modifiers];
1931 if (simple_chars == nil) {
1932 // Something went wrong. Fall back to what Cocoa gave us...
1933 simple_chars = [theEvent charactersIgnoringModifiers];
1934 }
1935
1936 [FLView prepareEtext:simple_chars];
1937 }
DRC685f17e2011-07-28 09:23:00 +00001938
DRC2ff39b82011-07-28 08:38:59 +00001939 // Then we can let the OS have a stab at it and see if it thinks it
1940 // should result in some text
Henrik Andersson485f4192011-09-16 11:51:32 +00001941
1942 // Don't send cmd-<key> to interpretKeyEvents because it beeps.
1943 if (!(Fl::e_state & FL_META)) {
1944 NSText *edit = [[theEvent window] fieldEditor:YES forObject:nil];
1945 in_key_event = true;
1946 [edit interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
1947 in_key_event = false;
1948 }
DRC2ff39b82011-07-28 08:38:59 +00001949 }
1950 //NSLog(@"to text=%@ l=%d", [NSString stringWithUTF8String:Fl::e_text], Fl::e_length);
1951 int handled = Fl::handle(FL_KEYDOWN, window);
1952 // We have to update this after Fl::handle as it says what to do on the
1953 // _next_ input
1954 if (next_compose_length != -1)
1955 Fl::compose_state = next_compose_length;
1956
1957 fl_unlock_function();
1958 return (handled ? YES : NO);
1959}
1960- (void)keyDown:(NSEvent *)theEvent {
1961 //NSLog(@"keyDown: ");
1962 [self handleKeyDown:theEvent];
1963}
1964- (void)keyUp:(NSEvent *)theEvent {
1965 //NSLog(@"keyUp: ");
1966 fl_lock_function();
1967 Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
1968 Fl::first_window(window);
1969 cocoaKeyboardHandler(theEvent);
1970 NSString *s = [theEvent characters];
1971 if ([s length] >= 1) [FLView prepareEtext:[s substringToIndex:1]];
1972 Fl::handle(FL_KEYUP,window);
1973 fl_unlock_function();
1974}
1975- (void)flagsChanged:(NSEvent *)theEvent {
1976 //NSLog(@"flagsChanged: ");
1977 fl_lock_function();
1978 static UInt32 prevMods = 0;
1979 NSUInteger mods = [theEvent modifierFlags];
1980 Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
1981 UInt32 tMods = prevMods ^ mods;
1982 int sendEvent = 0;
1983 if ( tMods )
1984 {
1985 unsigned short keycode = [theEvent keyCode];
1986 Fl::e_keysym = Fl::e_original_keysym = macKeyLookUp[keycode & 0x7f];
1987 if ( Fl::e_keysym )
1988 sendEvent = ( prevMods<mods ) ? FL_KEYBOARD : FL_KEYUP;
1989 Fl::e_length = 0;
1990 Fl::e_text = (char*)"";
1991 prevMods = mods;
1992 }
1993 mods_to_e_state( mods );
1994 while (window->parent()) window = window->window();
1995 if (sendEvent) Fl::handle(sendEvent,window);
1996 fl_unlock_function();
1997}
1998- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender
1999{
2000 fl_lock_function();
2001 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
2002 update_e_xy_and_e_xy_root([self window]);
2003 fl_dnd_target_window = target;
2004 int ret = Fl::handle( FL_DND_ENTER, target );
2005 breakMacEventLoop();
2006 fl_unlock_function();
2007 return ret ? NSDragOperationCopy : NSDragOperationNone;
2008}
2009- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender
2010{
2011 fl_lock_function();
2012 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
2013 update_e_xy_and_e_xy_root([self window]);
2014 fl_dnd_target_window = target;
2015 int ret = Fl::handle( FL_DND_DRAG, target );
2016 breakMacEventLoop();
2017 fl_unlock_function();
2018 return ret ? NSDragOperationCopy : NSDragOperationNone;
2019}
2020- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
2021{
2022 static char *DragData = NULL;
2023 fl_lock_function();
2024 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
2025 if ( !Fl::handle( FL_DND_RELEASE, target ) ) {
2026 breakMacEventLoop();
2027 fl_unlock_function();
2028 return NO;
2029 }
2030 NSPasteboard *pboard;
2031 // NSDragOperation sourceDragMask;
2032 // sourceDragMask = [sender draggingSourceOperationMask];
2033 pboard = [sender draggingPasteboard];
2034 update_e_xy_and_e_xy_root([self window]);
2035 if (DragData) { free(DragData); DragData = NULL; }
2036 if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
2037 CFArrayRef files = (CFArrayRef)[pboard propertyListForType:NSFilenamesPboardType];
2038 CFStringRef all = CFStringCreateByCombiningStrings(NULL, files, CFSTR("\n"));
2039 int l = CFStringGetMaximumSizeForEncoding(CFStringGetLength(all), kCFStringEncodingUTF8);
2040 DragData = (char *)malloc(l + 1);
2041 CFStringGetCString(all, DragData, l + 1, kCFStringEncodingUTF8);
2042 CFRelease(all);
2043 }
2044 else if ( [[pboard types] containsObject:NSStringPboardType] ) {
2045 NSData *data = [pboard dataForType:NSStringPboardType];
2046 DragData = (char *)malloc([data length] + 1);
2047 [data getBytes:DragData];
2048 DragData[[data length]] = 0;
2049 convert_crlf(DragData, strlen(DragData));
2050 }
2051 else {
2052 breakMacEventLoop();
2053 fl_unlock_function();
2054 return NO;
2055 }
2056 Fl::e_text = DragData;
2057 Fl::e_length = strlen(DragData);
2058 int old_event = Fl::e_number;
2059 Fl::belowmouse()->handle(Fl::e_number = FL_PASTE);
2060 Fl::e_number = old_event;
2061 if (DragData) { free(DragData); DragData = NULL; }
2062 Fl::e_text = NULL;
2063 Fl::e_length = 0;
2064 fl_dnd_target_window = NULL;
2065 breakMacEventLoop();
2066 fl_unlock_function();
2067 return YES;
2068}
2069- (void)draggingExited:(id < NSDraggingInfo >)sender
2070{
2071 fl_lock_function();
2072 if ( fl_dnd_target_window ) {
2073 Fl::handle( FL_DND_LEAVE, fl_dnd_target_window );
2074 fl_dnd_target_window = 0;
2075 }
2076 fl_unlock_function();
2077}
2078- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
2079{
2080 return NSDragOperationGeneric;
2081}
2082
2083+ (void)prepareEtext:(NSString*)aString {
2084 // fills Fl::e_text with UTF-8 encoded aString using an adequate memory allocation
2085 static char *received_utf8 = NULL;
2086 static int lreceived = 0;
2087 char *p = (char*)[aString UTF8String];
2088 int l = strlen(p);
2089 if (l > 0) {
2090 if (lreceived == 0) {
2091 received_utf8 = (char*)malloc(l + 1);
2092 lreceived = l;
2093 }
2094 else if (l > lreceived) {
2095 received_utf8 = (char*)realloc(received_utf8, l + 1);
2096 lreceived = l;
2097 }
2098 strcpy(received_utf8, p);
2099 Fl::e_text = received_utf8;
2100 }
2101 Fl::e_length = l;
2102}
2103
2104// These functions implement text input.
2105// Only two-stroke character composition works at this point.
2106// Needs much elaboration to fully support CJK text input,
2107// but this is the way to go.
2108- (void)doCommandBySelector:(SEL)aSelector {
2109}
2110
2111- (void)insertText:(id)aString {
2112 NSString *received;
2113 if ([aString isKindOfClass:[NSAttributedString class]]) {
2114 received = [(NSAttributedString*)aString string];
2115 } else {
2116 received = (NSString*)aString;
2117 }
2118 //NSLog(@"insertText: received=%@",received);
2119
2120 if (!in_key_event) fl_lock_function();
DRC685f17e2011-07-28 09:23:00 +00002121
2122 // Simple keyboard widgets do not want these side channel inputs.
2123 if (use_simple_keyboard)
2124 goto end;
2125
DRC2ff39b82011-07-28 08:38:59 +00002126 [FLView prepareEtext:received];
DRC685f17e2011-07-28 09:23:00 +00002127
DRC2ff39b82011-07-28 08:38:59 +00002128 // We can get called outside of key events (e.g. from the character
DRC685f17e2011-07-28 09:23:00 +00002129 // palette). We need to fake our own key event at that point.
DRC2ff39b82011-07-28 08:38:59 +00002130 if (!in_key_event) {
2131 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
DRC685f17e2011-07-28 09:23:00 +00002132 Fl::e_keysym = Fl::e_original_keysym = 0;
2133 Fl::handle(FL_KEYDOWN, target);
DRC2ff39b82011-07-28 08:38:59 +00002134 // for some reason, the window does not redraw until the next mouse move or button push
2135 // sending a 'redraw()' or 'awake()' does not solve the issue!
2136 Fl::flush();
2137 }
DRC685f17e2011-07-28 09:23:00 +00002138
2139end:
DRC2ff39b82011-07-28 08:38:59 +00002140 if (!in_key_event) fl_unlock_function();
2141}
2142
2143- (void)setMarkedText:(id)aString selectedRange:(NSRange)newSelection {
DRC685f17e2011-07-28 09:23:00 +00002144 NSString *received, *current, *aggregate;
DRC2ff39b82011-07-28 08:38:59 +00002145 if (newSelection.location == 0) {
2146 [self unmarkText];
2147 return;
2148 }
2149 if ([aString isKindOfClass:[NSAttributedString class]]) {
2150 received = [(NSAttributedString*)aString string];
2151 } else {
2152 received = (NSString*)aString;
2153 }
2154 //NSLog(@"setMarkedText: %@ %d %d",received,newSelection.location,newSelection.length);
DRC685f17e2011-07-28 09:23:00 +00002155
2156 fl_lock_function();
2157
2158 // Simple keyboard widgets generally do not want these side channel
2159 // inputs, but we have no other way of getting dead keys so we make
2160 // an exception in that case.
2161 if (use_simple_keyboard) {
2162 if (in_key_event && (Fl::e_length == 0)) {
2163 [FLView prepareEtext:received];
2164
2165 Fl::e_text = (char*)cocoaDead2FLTK(Fl::e_text);
2166 Fl::e_length = strlen(Fl::e_text);
2167 }
2168 goto end;
2169 }
2170
DRC2ff39b82011-07-28 08:38:59 +00002171 // This code creates the OS X behaviour of seeing dead keys as things
2172 // are being composed.
DRC685f17e2011-07-28 09:23:00 +00002173 //
2174 // Note: The concatenation thing is because of how OS X deals with
2175 // invalid sequences. At that point it will spit out one call
2176 // to insertText with the now aborted sequence, and one new
2177 // call to setMarkedText with the new sequence. Since we want
2178 // both to be visible, we need to concatenate.
DRC2ff39b82011-07-28 08:38:59 +00002179 next_compose_length = newSelection.location;
DRC685f17e2011-07-28 09:23:00 +00002180 current = [NSString stringWithUTF8String:Fl::e_text];
2181 aggregate = [current stringByAppendingString:received];
2182
2183 [FLView prepareEtext:aggregate];
2184 //NSLog(@"Fl::e_text=%@ Fl::e_length=%d next_compose_length=%d", aggregate, Fl::e_length, next_compose_length);
2185
2186 // We can get called outside of key events (e.g. from the character
2187 // palette). We need to fake our own key event at that point.
2188 if (!in_key_event) {
2189 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
2190 Fl::e_keysym = Fl::e_original_keysym = 0;
2191 Fl::handle(FL_KEYDOWN, target);
2192 }
2193
2194end:
2195 fl_unlock_function();
DRC2ff39b82011-07-28 08:38:59 +00002196}
2197
2198- (void)unmarkText {
2199 fl_lock_function();
2200 Fl::compose_state = 0;
2201 fl_unlock_function();
2202 //NSLog(@"unmarkText");
2203}
2204
2205- (NSRange)selectedRange {
2206 return NSMakeRange(NSNotFound, 0);
2207}
2208
2209- (NSRange)markedRange {
2210 //NSLog(@"markedRange ?");
2211 return NSMakeRange(NSNotFound, Fl::compose_state);
2212}
2213
2214- (BOOL)hasMarkedText {
2215 //NSLog(@"hasMarkedText %s", Fl::compose_state > 0?"YES":"NO");
2216 return (Fl::compose_state > 0);
2217}
2218
2219- (NSAttributedString *)attributedSubstringFromRange:(NSRange)aRange {
2220 //NSLog(@"attributedSubstringFromRange: %d %d",aRange.location,aRange.length);
2221 return nil;
2222}
2223
2224- (NSArray *)validAttributesForMarkedText {
2225 return nil;
2226}
2227
2228- (NSRect)firstRectForCharacterRange:(NSRange)aRange {
2229 NSRect glyphRect;
2230 fl_lock_function();
2231 Fl_Widget *focus = Fl::focus();
2232 Fl_Window *wfocus = focus->window();
2233 while (wfocus->window()) wfocus = wfocus->window();
2234 glyphRect.size.width = 0;
2235
2236 if (dynamic_cast<Fl_Text_Display*>(focus) != NULL) {
2237 int x, y;
2238 Fl_Text_Display *current = (Fl_Text_Display*)focus;
2239 current->position_to_xy( current->insert_position(), &x, &y );
2240 glyphRect.origin.x = (CGFloat)x;
2241 glyphRect.origin.y = (CGFloat)y + current->textsize();
2242 glyphRect.size.height = current->textsize();
2243 } else {
2244 glyphRect.origin.x = focus->x();
2245 glyphRect.origin.y = focus->y() + focus->h();
2246 glyphRect.size.height = 12;
2247 }
2248 // Convert the rect to screen coordinates
2249 glyphRect.origin.y = wfocus->h() - glyphRect.origin.y;
2250 glyphRect.origin = [[self window] convertBaseToScreen:glyphRect.origin];
2251 fl_unlock_function();
2252 return glyphRect;
2253}
2254
2255- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
2256 return 0;
2257}
2258
2259- (NSInteger)conversationIdentifier {
2260 return (NSInteger)self;
2261}
2262
2263@end
2264
DRC685f17e2011-07-28 09:23:00 +00002265void fullscreen_x(Fl_Window *w) {
2266 w->_set_fullscreen();
2267 /* On OS X < 10.6, it is necessary to recreate the window. This is done
2268 with hide+show. */
2269 w->hide();
2270 w->show();
2271 Fl::handle(FL_FULLSCREEN, w);
2272}
2273
2274void fullscreen_off_x(Fl_Window *w, int X, int Y, int W, int H) {
2275 w->_clear_fullscreen();
2276 w->hide();
2277 w->resize(X, Y, W, H);
2278 w->show();
2279 Fl::handle(FL_FULLSCREEN, w);
2280}
DRC2ff39b82011-07-28 08:38:59 +00002281
2282/*
2283 * go ahead, create that (sub)window
2284 */
2285void Fl_X::make(Fl_Window* w)
2286{
2287 static int xyPos = 100;
2288 if ( w->parent() ) { // create a subwindow
2289 Fl_Group::current(0);
2290 // our subwindow needs this structure to know about its clipping.
2291 Fl_X* x = new Fl_X;
2292 x->subwindow = true;
2293 x->other_xid = 0;
2294 x->region = 0;
2295 x->subRegion = 0;
DRC685f17e2011-07-28 09:23:00 +00002296 x->cursor = NULL;
DRC2ff39b82011-07-28 08:38:59 +00002297 x->gc = 0; // stay 0 for Quickdraw; fill with CGContext for Quartz
2298 Fl_Window *win = w->window();
2299 Fl_X *xo = Fl_X::i(win);
2300 if (xo) {
2301 x->xidNext = xo->xidChildren;
2302 x->xidChildren = 0L;
2303 xo->xidChildren = x;
2304 x->xid = win->i->xid;
2305 x->w = w; w->i = x;
2306 x->wait_for_expose = 0;
2307 {
2308 Fl_X *z = xo->next; // we don't want a subwindow in Fl_X::first
2309 xo->next = x;
2310 x->next = z;
2311 }
2312 int old_event = Fl::e_number;
2313 w->handle(Fl::e_number = FL_SHOW);
2314 Fl::e_number = old_event;
2315 w->redraw(); // force draw to happen
2316 }
2317 if (w->as_gl_window()) { // if creating a sub-GL-window
2318 while (win->window()) win = win->window();
2319 [(FLWindow*)Fl_X::i(win)->xid setContainsGLsubwindow:YES];
2320 }
2321 fl_show_iconic = 0;
2322 }
2323 else { // create a desktop window
2324 Fl_Group::current(0);
2325 fl_open_display();
2326 NSInteger winlevel = NSNormalWindowLevel;
2327 NSUInteger winstyle;
2328 if (w->border()) winstyle = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask;
2329 else winstyle = NSBorderlessWindowMask;
2330 int xp = w->x();
2331 int yp = w->y();
2332 int wp = w->w();
2333 int hp = w->h();
2334 if (w->size_range_set) {
2335 if ( w->minh != w->maxh || w->minw != w->maxw) {
2336 winstyle |= NSResizableWindowMask;
2337 }
2338 } else {
2339 if (w->resizable()) {
2340 Fl_Widget *o = w->resizable();
2341 int minw = o->w(); if (minw > 100) minw = 100;
2342 int minh = o->h(); if (minh > 100) minh = 100;
2343 w->size_range(w->w() - o->w() + minw, w->h() - o->h() + minh, 0, 0);
2344 winstyle |= NSResizableWindowMask;
2345 } else {
2346 w->size_range(w->w(), w->h(), w->w(), w->h());
2347 }
2348 }
2349 int xwm = xp, ywm = yp, bt, bx, by;
2350
2351 if (!fake_X_wm(w, xwm, ywm, bt, bx, by)) {
2352 // menu windows and tooltips
2353 if (w->modal()||w->tooltip_window()) {
2354 winstyle = NSBorderlessWindowMask;
2355 winlevel = NSModalPanelWindowLevel;
2356 } else {
2357 winstyle = NSBorderlessWindowMask;
2358 }
2359 } else if (w->modal()) {
2360 winstyle &= ~NSMiniaturizableWindowMask;
2361 // winstyle &= ~(NSResizableWindowMask | NSMiniaturizableWindowMask);
2362 winlevel = NSModalPanelWindowLevel;
2363 }
2364 else if (w->non_modal()) {
2365 winlevel = NSFloatingWindowLevel;
2366 }
2367
2368 if (by+bt) {
2369 wp += 2*bx;
2370 hp += 2*by+bt;
2371 }
2372 if (!(w->flags() & Fl_Window::FORCE_POSITION)) {
2373 // use the Carbon functions below for default window positioning
2374 w->x(xyPos+Fl::x());
2375 w->y(xyPos+Fl::y());
2376 xyPos += 25;
2377 if (xyPos>200) xyPos = 100;
2378 } else {
2379 if (!Fl::grab()) {
2380 xp = xwm; yp = ywm;
2381 w->x(xp);w->y(yp);
2382 }
2383 xp -= bx;
2384 yp -= by+bt;
2385 }
2386
2387 if (w->non_modal() && Fl_X::first /*&& !fl_disable_transient_for*/) {
2388 // find some other window to be "transient for":
2389 Fl_Window* w = Fl_X::first->w;
2390 while (w->parent()) w = w->window(); // todo: this code does not make any sense! (w!=w??)
2391 }
2392
2393 Fl_X* x = new Fl_X;
2394 x->subwindow = false;
2395 x->other_xid = 0; // room for doublebuffering image map. On OS X this is only used by overlay windows
2396 x->region = 0;
2397 x->subRegion = 0;
DRC685f17e2011-07-28 09:23:00 +00002398 x->cursor = NULL;
DRC2ff39b82011-07-28 08:38:59 +00002399 x->xidChildren = 0;
2400 x->xidNext = 0;
2401 x->gc = 0;
2402
2403 NSRect srect = [[NSScreen mainScreen] frame];
DRC685f17e2011-07-28 09:23:00 +00002404 if (w->flags() & Fl_Widget::FULLSCREEN) {
2405 int sx, sy, sw, sh;
2406 Fl::screen_xywh(sx, sy, sw, sh, w->x(), w->y(), w->w(), w->h());
2407 w->resize(sx, sy, sw, sh);
2408 winstyle = NSBorderlessWindowMask;
2409 winlevel = NSStatusWindowLevel;
2410 }
DRC2ff39b82011-07-28 08:38:59 +00002411 NSRect crect;
2412 crect.origin.x = w->x();
2413 crect.origin.y = srect.size.height - (w->y() + w->h());
2414 crect.size.width=w->w();
2415 crect.size.height=w->h();
2416 FLWindow *cw = [[FLWindow alloc] initWithFl_W:w
2417 contentRect:crect
2418 styleMask:winstyle];
2419 [cw setHasShadow:YES];
2420 [cw setAcceptsMouseMovedEvents:YES];
2421 x->xid = cw;
2422 FLView *myview = [[FLView alloc] init];
2423 [cw setContentView:myview];
2424 [cw setLevel:winlevel];
2425
2426 q_set_window_title(cw, w->label(), w->iconlabel());
2427 if (!(w->flags() & Fl_Window::FORCE_POSITION)) {
2428 if (w->modal()) {
2429 [cw center];
2430 } else if (w->non_modal()) {
2431 [cw center];
2432 } else {
2433 static NSPoint delta = NSZeroPoint;
2434 delta = [cw cascadeTopLeftFromPoint:delta];
2435 }
2436 }
2437 if(w->menu_window()) { // make menu windows slightly transparent
2438 [cw setAlphaValue:0.97];
2439 }
2440 x->w = w; w->i = x;
2441 x->wait_for_expose = 1;
2442 x->next = Fl_X::first;
2443 Fl_X::first = x;
2444 // Install DnD handlers
2445 [myview registerForDraggedTypes:[NSArray arrayWithObjects:
2446 NSStringPboardType, NSFilenamesPboardType, nil]];
2447 if ( ! Fl_X::first->next ) {
2448 // if this is the first window, we need to bring the application to the front
2449 ProcessSerialNumber psn = { 0, kCurrentProcess };
2450 SetFrontProcess( &psn );
2451 }
2452
2453 if (w->size_range_set) w->size_range_();
2454
2455 if ( w->border() || (!w->modal() && !w->tooltip_window()) ) {
2456 Fl_Tooltip::enter(0);
2457 }
2458 w->set_visible();
2459 if ( w->border() || (!w->modal() && !w->tooltip_window()) ) Fl::handle(FL_FOCUS, w);
2460 Fl::first_window(w);
2461 [cw setDelegate:mydelegate];
2462 if (fl_show_iconic) {
2463 fl_show_iconic = 0;
2464 [cw miniaturize:nil];
2465 } else {
2466 [cw makeKeyAndOrderFront:nil];
2467 }
2468
2469 crect = [[cw contentView] frame];
2470 w->w(int(crect.size.width));
2471 w->h(int(crect.size.height));
2472 crect = [cw frame];
2473 w->x(int(crect.origin.x));
2474 srect = [[cw screen] frame];
2475 w->y(int(srect.size.height - (crect.origin.y + w->h())));
2476
2477 int old_event = Fl::e_number;
2478 w->handle(Fl::e_number = FL_SHOW);
2479 Fl::e_number = old_event;
2480
2481 if (w->modal()) { Fl::modal_ = w; fl_fix_focus(); }
2482 }
2483}
2484
2485
2486/*
2487 * Tell the OS what window sizes we want to allow
2488 */
2489void Fl_Window::size_range_() {
2490 int bx, by, bt;
2491 get_window_frame_sizes(bx, by, bt);
2492 size_range_set = 1;
2493 NSSize minSize = { minw, minh + bt };
2494 NSSize maxSize = { maxw?maxw:32000, maxh?maxh + bt:32000 };
2495 if (i && i->xid) {
2496 [(NSWindow*)i->xid setMinSize:minSize];
2497 [(NSWindow*)i->xid setMaxSize:maxSize];
2498 }
2499}
2500
2501
2502/*
2503 * returns pointer to the filename, or null if name ends with ':'
2504 */
2505const char *fl_filename_name( const char *name )
2506{
2507 const char *p, *q;
2508 if (!name) return (0);
2509 for ( p = q = name ; *p ; ) {
2510 if ( ( p[0] == ':' ) && ( p[1] == ':' ) ) {
2511 q = p+2;
2512 p++;
2513 }
2514 else if (p[0] == '/') {
2515 q = p + 1;
2516 }
2517 p++;
2518 }
2519 return q;
2520}
2521
2522
2523/*
2524 * set the window title bar name
2525 */
2526void Fl_Window::label(const char *name, const char *mininame) {
2527 Fl_Widget::label(name);
2528 iconlabel_ = mininame;
2529 if (shown() || i) {
2530 NSWindow* nsw = (NSWindow*)i->xid;
2531 q_set_window_title(nsw, name, mininame);
2532 }
2533}
2534
2535
2536/*
2537 * make a window visible
2538 */
2539void Fl_Window::show() {
2540 image(Fl::scheme_bg_);
2541 if (Fl::scheme_bg_) {
2542 labeltype(FL_NORMAL_LABEL);
2543 align(FL_ALIGN_CENTER | FL_ALIGN_INSIDE | FL_ALIGN_CLIP);
2544 } else {
2545 labeltype(FL_NO_LABEL);
2546 }
2547 Fl_Tooltip::exit(this);
2548 if (!shown() || !i) {
2549 Fl_X::make(this);
2550 } else {
2551 if ( !parent() ) {
2552 if ([(NSWindow*)i->xid isMiniaturized]) {
2553 i->w->redraw();
2554 [(NSWindow*)i->xid deminiaturize:nil];
2555 }
2556 if (!fl_capture) {
2557 [(NSWindow*)i->xid makeKeyAndOrderFront:nil];
2558 }
2559 }
2560 }
2561}
2562
2563
2564/*
2565 * resize a window
2566 */
2567void Fl_Window::resize(int X,int Y,int W,int H) {
2568 if (W<=0) W = 1; // OS X does not like zero width windows
2569 if (H<=0) H = 1;
2570 int is_a_resize = (W != w() || H != h());
2571 // printf("Fl_Window::resize(X=%d, Y=%d, W=%d, H=%d), is_a_resize=%d, resize_from_system=%p, this=%p\n",
2572 // X, Y, W, H, is_a_resize, resize_from_system, this);
2573 if (X != x() || Y != y()) set_flag(FORCE_POSITION);
2574 else if (!is_a_resize) return;
2575 if ( (resize_from_system!=this) && (!parent()) && shown()) {
2576 if (is_a_resize) {
2577 if (resizable()) {
2578 if (W<minw) minw = W; // user request for resize takes priority
2579 if (maxw && W>maxw) maxw = W; // over a previously set size_range
2580 if (H<minh) minh = H;
2581 if (maxh && H>maxh) maxh = H;
2582 size_range(minw, minh, maxw, maxh);
2583 } else {
2584 size_range(W, H, W, H);
2585 }
2586 int bx, by, bt;
2587 if ( ! this->border() ) bt = 0;
2588 else get_window_frame_sizes(bx, by, bt);
2589 NSRect dim;
2590 dim.origin.x = X;
2591 dim.origin.y = [[(NSWindow*)i->xid screen] frame].size.height - (Y + H);
2592 dim.size.width = W;
2593 dim.size.height = H + bt;
2594 [(NSWindow*)i->xid setFrame:dim display:YES];
2595 } else {
2596 NSPoint pt;
2597 pt.x = X;
2598 pt.y = [[(NSWindow*)i->xid screen] frame].size.height - (Y + h());
2599 [(NSWindow*)i->xid setFrameOrigin:pt];
2600 }
Pierre Ossmandd321ad2011-11-21 14:04:29 +00002601 // setFrame and setFrameOrigin are only requests to the system to
2602 // do a resize or move. We will get callbacks later if the system allowed
2603 // this, and possibly with adjusted values. We avoid processing until
2604 // that happens (which usually happens directly as setFrame[Origin] is
2605 // called).
2606 return;
DRC2ff39b82011-07-28 08:38:59 +00002607 }
2608 resize_from_system = 0;
2609 if (is_a_resize) {
2610 Fl_Group::resize(X,Y,W,H);
2611 if (shown()) {
2612 redraw();
2613 }
2614 } else {
2615 x(X); y(Y);
2616 }
2617}
2618
2619
2620/*
2621 * make all drawing go into this window (called by subclass flush() impl.)
2622 */
2623void Fl_Window::make_current()
2624{
2625 Fl_X::q_release_context();
2626 fl_window = i->xid;
2627 current_ = this;
2628
2629 int xp = 0, yp = 0;
2630 Fl_Window *win = this;
2631 while ( win ) {
2632 if ( !win->window() )
2633 break;
2634 xp += win->x();
2635 yp += win->y();
2636 win = (Fl_Window*)win->window();
2637 }
2638
2639 NSView *current_focus = [NSView focusView];
2640 // sometimes current_focus is set to a non-FLTK view: don't touch that
2641 if ( [current_focus isKindOfClass:[FLView class]] ) [current_focus unlockFocus];
2642 [[(NSWindow*)i->xid contentView] lockFocus];
2643 i->gc = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
2644 fl_gc = i->gc;
2645 Fl_Region fl_window_region = XRectangleRegion(0,0,w(),h());
2646 if ( ! this->window() ) {
2647 for ( Fl_X *cx = i->xidChildren; cx; cx = cx->xidNext ) { // clip-out all sub-windows
2648 Fl_Window *cw = cx->w;
2649 Fl_Region from = fl_window_region;
2650 fl_window_region = MacRegionMinusRect(from, cw->x(), cw->y(), cw->w(), cw->h() );
2651 XDestroyRegion(from);
2652 }
2653 }
2654
2655 // antialiasing must be deactivated because it applies to rectangles too
2656 // and escapes even clipping!!!
2657 // it gets activated when needed (e.g., draw text)
2658 CGContextSetShouldAntialias(fl_gc, false);
2659 CGFloat hgt = [[(NSWindow*)fl_window contentView] frame].size.height;
2660 CGContextTranslateCTM(fl_gc, 0.5, hgt-0.5f);
2661 CGContextScaleCTM(fl_gc, 1.0f, -1.0f); // now 0,0 is top-left point of the window
2662 win = this;
2663 while(win && win->window()) { // translate to subwindow origin if this is a subwindow context
2664 CGContextTranslateCTM(fl_gc, win->x(), win->y());
2665 win = win->window();
2666 }
2667 //apply window's clip
2668 CGContextClipToRects(fl_gc, fl_window_region->rects, fl_window_region->count );
2669 XDestroyRegion(fl_window_region);
2670// this is the context with origin at top left of (sub)window clipped out of its subwindows if any
2671 CGContextSaveGState(fl_gc);
2672#if defined(FLTK_USE_CAIRO)
2673 if (Fl::cairo_autolink_context()) Fl::cairo_make_current(this); // capture gc changes automatically to update the cairo context adequately
2674#endif
2675 fl_clip_region( 0 );
2676
2677#if defined(FLTK_USE_CAIRO)
2678 // update the cairo_t context
2679 if (Fl::cairo_autolink_context()) Fl::cairo_make_current(this);
2680#endif
2681}
2682
2683// helper function to manage the current CGContext fl_gc
2684extern void fl_quartz_restore_line_style_();
2685
2686// FLTK has only one global graphics state. This function copies the FLTK state into the
2687// current Quartz context
2688void Fl_X::q_fill_context() {
2689 if (!fl_gc) return;
2690 if ( ! fl_window) { // a bitmap context
2691 size_t hgt = CGBitmapContextGetHeight(fl_gc);
2692 CGContextTranslateCTM(fl_gc, 0.5, hgt-0.5f);
2693 CGContextScaleCTM(fl_gc, 1.0f, -1.0f); // now 0,0 is top-left point of the context
2694 }
2695 fl_color(fl_graphics_driver->color());
2696 fl_quartz_restore_line_style_();
2697}
2698
2699// The only way to reset clipping to its original state is to pop the current graphics
2700// state and restore the global state.
2701void Fl_X::q_clear_clipping() {
2702 if (!fl_gc) return;
2703 CGContextRestoreGState(fl_gc);
2704 CGContextSaveGState(fl_gc);
2705}
2706
2707// Give the Quartz context back to the system
2708void Fl_X::q_release_context(Fl_X *x) {
2709 if (x && x->gc!=fl_gc) return;
2710 if (!fl_gc) return;
2711 CGContextRestoreGState(fl_gc); // matches the CGContextSaveGState of make_current
2712 fl_gc = 0;
2713#if defined(FLTK_USE_CAIRO)
2714 if (Fl::cairo_autolink_context()) Fl::cairo_make_current((Fl_Window*) 0); // capture gc changes automatically to update the cairo context adequately
2715#endif
2716}
2717
2718void Fl_X::q_begin_image(CGRect &rect, int cx, int cy, int w, int h) {
2719 CGContextSaveGState(fl_gc);
2720 CGRect r2 = rect;
2721 r2.origin.x -= 0.5f;
2722 r2.origin.y -= 0.5f;
2723 CGContextClipToRect(fl_gc, r2);
2724 // move graphics context to origin of vertically reversed image
2725 CGContextTranslateCTM(fl_gc, rect.origin.x - cx - 0.5, rect.origin.y - cy + h - 0.5);
2726 CGContextScaleCTM(fl_gc, 1, -1);
2727 rect.origin.x = rect.origin.y = 0;
2728 rect.size.width = w;
2729 rect.size.height = h;
2730}
2731
2732void Fl_X::q_end_image() {
2733 CGContextRestoreGState(fl_gc);
2734}
2735
2736
2737////////////////////////////////////////////////////////////////
2738// Copy & Paste fltk implementation.
2739////////////////////////////////////////////////////////////////
2740
2741static void convert_crlf(char * s, size_t len)
2742{
2743 // turn all \r characters into \n:
2744 for (size_t x = 0; x < len; x++) if (s[x] == '\r') s[x] = '\n';
2745}
2746
2747// fltk 1.3 clipboard support constant definitions:
2748const CFStringRef flavorNames[] = {
2749 CFSTR("public.utf16-plain-text"),
2750 CFSTR("public.utf8-plain-text"),
2751 CFSTR("com.apple.traditional-mac-plain-text") };
2752const CFStringEncoding encodings[] = {
2753 kCFStringEncodingUnicode,
2754 kCFStringEncodingUTF8,
2755 kCFStringEncodingMacRoman};
2756const size_t handledFlavorsCount = sizeof(encodings)/sizeof(CFStringEncoding);
2757
2758// clipboard variables definitions :
2759char *fl_selection_buffer[2];
2760int fl_selection_length[2];
2761static int fl_selection_buffer_length[2];
2762
2763static PasteboardRef myPasteboard = 0;
2764static void allocatePasteboard() {
2765 if (!myPasteboard)
2766 PasteboardCreate(kPasteboardClipboard, &myPasteboard);
2767}
2768
2769
2770/*
2771 * create a selection
2772 * owner: widget that created the selection
2773 * stuff: pointer to selected data
2774 * size of selected data
2775 */
2776void Fl::copy(const char *stuff, int len, int clipboard) {
2777 if (!stuff || len<0) return;
2778 if (len+1 > fl_selection_buffer_length[clipboard]) {
2779 delete[] fl_selection_buffer[clipboard];
2780 fl_selection_buffer[clipboard] = new char[len+100];
2781 fl_selection_buffer_length[clipboard] = len+100;
2782 }
2783 memcpy(fl_selection_buffer[clipboard], stuff, len);
2784 fl_selection_buffer[clipboard][len] = 0; // needed for direct paste
2785 fl_selection_length[clipboard] = len;
2786 if (clipboard) {
2787 allocatePasteboard();
2788 OSStatus err = PasteboardClear(myPasteboard);
2789 if (err!=noErr) return; // clear did not work, maybe not owner of clipboard.
2790 PasteboardSynchronize(myPasteboard);
2791 CFDataRef text = CFDataCreate(kCFAllocatorDefault, (UInt8*)fl_selection_buffer[1], len);
2792 if (text==NULL) return; // there was a pb creating the object, abort.
2793 err=PasteboardPutItemFlavor(myPasteboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), text, 0);
2794 CFRelease(text);
2795 }
2796}
2797
2798// Call this when a "paste" operation happens:
2799void Fl::paste(Fl_Widget &receiver, int clipboard) {
2800 if (clipboard) {
2801 // see if we own the selection, if not go get it:
2802 fl_selection_length[1] = 0;
2803 OSStatus err = noErr;
2804 Boolean found = false;
2805 CFDataRef flavorData = NULL;
2806 CFStringEncoding encoding = 0;
2807
2808 allocatePasteboard();
2809 PasteboardSynchronize(myPasteboard);
2810 ItemCount nFlavor = 0, i, j;
2811 err = PasteboardGetItemCount(myPasteboard, &nFlavor);
2812 if (err==noErr) {
2813 for (i=1; i<=nFlavor; i++) {
2814 PasteboardItemID itemID = 0;
2815 CFArrayRef flavorTypeArray = NULL;
2816 found = false;
2817 err = PasteboardGetItemIdentifier(myPasteboard, i, &itemID);
2818 if (err!=noErr) continue;
2819 err = PasteboardCopyItemFlavors(myPasteboard, itemID, &flavorTypeArray);
2820 if (err!=noErr) {
2821 if (flavorTypeArray) {CFRelease(flavorTypeArray); flavorTypeArray = NULL;}
2822 continue;
2823 }
2824 CFIndex flavorCount = CFArrayGetCount(flavorTypeArray);
2825 for (j = 0; j < handledFlavorsCount; j++) {
2826 for (CFIndex flavorIndex=0; flavorIndex<flavorCount; flavorIndex++) {
2827 CFStringRef flavorType = (CFStringRef)CFArrayGetValueAtIndex(flavorTypeArray, flavorIndex);
2828 if (UTTypeConformsTo(flavorType, flavorNames[j])) {
2829 err = PasteboardCopyItemFlavorData( myPasteboard, itemID, flavorNames[j], &flavorData );
2830 if (err != noErr) continue;
2831 encoding = encodings[j];
2832 found = true;
2833 break;
2834 }
2835 }
2836 if (found) break;
2837 }
2838 if (flavorTypeArray) {CFRelease(flavorTypeArray); flavorTypeArray = NULL;}
2839 if (found) break;
2840 }
2841 if (found) {
2842 CFIndex len = CFDataGetLength(flavorData);
2843 CFStringRef mycfs = CFStringCreateWithBytes(NULL, CFDataGetBytePtr(flavorData), len, encoding, false);
2844 CFRelease(flavorData);
2845 len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(mycfs), kCFStringEncodingUTF8) + 1;
2846 if ( len >= fl_selection_buffer_length[1] ) {
2847 fl_selection_buffer_length[1] = len;
2848 delete[] fl_selection_buffer[1];
2849 fl_selection_buffer[1] = new char[len];
2850 }
2851 CFStringGetCString(mycfs, fl_selection_buffer[1], len, kCFStringEncodingUTF8);
2852 CFRelease(mycfs);
2853 len = strlen(fl_selection_buffer[1]);
2854 fl_selection_length[1] = len;
2855 convert_crlf(fl_selection_buffer[1],len); // turn all \r characters into \n:
2856 }
2857 }
2858 }
2859 Fl::e_text = fl_selection_buffer[clipboard];
2860 Fl::e_length = fl_selection_length[clipboard];
2861 if (!Fl::e_text) Fl::e_text = (char *)"";
2862 receiver.handle(FL_PASTE);
2863}
2864
DRC685f17e2011-07-28 09:23:00 +00002865extern void fl_trigger_clipboard_notify(int source);
2866
2867void fl_clipboard_notify_change() {
2868 // No need to do anything here...
2869}
2870
2871static void clipboard_check(void)
2872{
2873 PasteboardSyncFlags flags;
2874
2875 allocatePasteboard();
2876 flags = PasteboardSynchronize(myPasteboard);
2877
2878 if (!(flags & kPasteboardModified))
2879 return;
2880 if (flags & kPasteboardClientIsOwner)
2881 return;
2882
2883 fl_trigger_clipboard_notify(1);
2884}
2885
DRC2ff39b82011-07-28 08:38:59 +00002886void Fl::add_timeout(double time, Fl_Timeout_Handler cb, void* data)
2887{
2888 // check, if this timer slot exists already
2889 for (int i = 0; i < mac_timer_used; ++i) {
2890 MacTimeout& t = mac_timers[i];
2891 // if so, simply change the fire interval
2892 if (t.callback == cb && t.data == data) {
2893 CFRunLoopTimerSetNextFireDate(t.timer, CFAbsoluteTimeGetCurrent() + time );
2894 t.pending = 1;
2895 return;
2896 }
2897 }
2898 // no existing timer to use. Create a new one:
2899 int timer_id = -1;
2900 // find an empty slot in the timer array
2901 for (int i = 0; i < mac_timer_used; ++i) {
2902 if ( !mac_timers[i].timer ) {
2903 timer_id = i;
2904 break;
2905 }
2906 }
2907 // if there was no empty slot, append a new timer
2908 if (timer_id == -1) {
2909 // make space if needed
2910 if (mac_timer_used == mac_timer_alloc) {
2911 realloc_timers();
2912 }
2913 timer_id = mac_timer_used++;
2914 }
2915 // now install a brand new timer
2916 MacTimeout& t = mac_timers[timer_id];
2917 CFRunLoopTimerContext context = {0, data, NULL,NULL,NULL};
2918 CFRunLoopTimerRef timerRef = CFRunLoopTimerCreate(kCFAllocatorDefault,
2919 CFAbsoluteTimeGetCurrent() + time,
2920 1E30,
2921 0,
2922 0,
2923 do_timer,
2924 &context
2925 );
2926 if (timerRef) {
2927 CFRunLoopAddTimer(CFRunLoopGetCurrent(),
2928 timerRef,
2929 kCFRunLoopDefaultMode);
2930 t.callback = cb;
2931 t.data = data;
2932 t.timer = timerRef;
2933 t.pending = 1;
2934 }
2935}
2936
2937void Fl::repeat_timeout(double time, Fl_Timeout_Handler cb, void* data)
2938{
2939 // currently, repeat_timeout does not subtract the trigger time of the previous timer event as it should.
2940 add_timeout(time, cb, data);
2941}
2942
2943int Fl::has_timeout(Fl_Timeout_Handler cb, void* data)
2944{
2945 for (int i = 0; i < mac_timer_used; ++i) {
2946 MacTimeout& t = mac_timers[i];
2947 if (t.callback == cb && t.data == data && t.pending) {
2948 return 1;
2949 }
2950 }
2951 return 0;
2952}
2953
2954void Fl::remove_timeout(Fl_Timeout_Handler cb, void* data)
2955{
2956 for (int i = 0; i < mac_timer_used; ++i) {
2957 MacTimeout& t = mac_timers[i];
2958 if (t.callback == cb && ( t.data == data || data == NULL)) {
2959 delete_timer(t);
2960 }
2961 }
2962}
2963
2964int Fl_X::unlink(Fl_X *start) {
2965 if (start) {
2966 Fl_X *pc = start;
2967 while (pc) {
2968 if (pc->xidNext == this) {
2969 pc->xidNext = xidNext;
2970 return 1;
2971 }
2972 if (pc->xidChildren) {
2973 if (pc->xidChildren == this) {
2974 pc->xidChildren = xidNext;
2975 return 1;
2976 }
2977 if (unlink(pc->xidChildren))
2978 return 1;
2979 }
2980 pc = pc->xidNext;
2981 }
2982 } else {
2983 for ( Fl_X *pc = Fl_X::first; pc; pc = pc->next ) {
2984 if (unlink(pc))
2985 return 1;
2986 }
2987 }
2988 return 0;
2989}
2990
2991void Fl_X::relink(Fl_Window *w, Fl_Window *wp) {
2992 Fl_X *x = Fl_X::i(w);
2993 Fl_X *p = Fl_X::i(wp);
2994 if (!x || !p) return;
2995 // first, check if 'x' is already registered as a child of 'p'
2996 for (Fl_X *i = p->xidChildren; i; i=i->xidNext) {
2997 if (i == x) return;
2998 }
2999 // now add 'x' as the first child of 'p'
3000 x->xidNext = p->xidChildren;
3001 p->xidChildren = x;
3002}
3003
3004void Fl_X::destroy() {
3005 // subwindows share their xid with their parent window, so should not close it
3006 if (!subwindow && w && !w->parent() && xid) {
3007 [[(NSWindow *)xid contentView] release];
3008 [(NSWindow *)xid close];
3009 }
DRC685f17e2011-07-28 09:23:00 +00003010 if (cursor) {
3011 [(NSCursor*)cursor release];
3012 cursor = NULL;
3013 }
DRC2ff39b82011-07-28 08:38:59 +00003014}
3015
3016void Fl_X::map() {
3017 if (w && xid) {
3018 [(NSWindow *)xid orderFront:nil];
3019 }
3020 //+ link to window list
3021 if (w && w->parent()) {
3022 Fl_X::relink(w, w->window() );
3023 w->redraw();
3024 }
3025}
3026
3027void Fl_X::unmap() {
3028 if (w && !w->parent() && xid) {
3029 [(NSWindow *)xid orderOut:nil];
3030 }
3031 if (w && Fl_X::i(w))
3032 Fl_X::i(w)->unlink();
3033}
3034
3035
3036// removes x,y,w,h rectangle from region r and returns result as a new Fl_Region
3037static Fl_Region MacRegionMinusRect(Fl_Region r, int x,int y,int w,int h)
3038{
3039 Fl_Region outr = (Fl_Region)malloc(sizeof(*outr));
3040 outr->rects = (CGRect*)malloc(4 * r->count * sizeof(CGRect));
3041 outr->count = 0;
3042 CGRect rect = fl_cgrectmake_cocoa(x, y, w, h);
3043 for( int i = 0; i < r->count; i++) {
3044 CGRect A = r->rects[i];
3045 CGRect test = CGRectIntersection(A, rect);
3046 if (CGRectIsEmpty(test)) {
3047 outr->rects[(outr->count)++] = A;
3048 }
3049 else {
3050 const CGFloat verylarge = 100000.;
3051 CGRect side = CGRectMake(0,0,rect.origin.x,verylarge);// W side
3052 test = CGRectIntersection(A, side);
3053 if ( ! CGRectIsEmpty(test)) {
3054 outr->rects[(outr->count)++] = test;
3055 }
3056 side = CGRectMake(0,rect.origin.y + rect.size.height,verylarge,verylarge);// N side
3057 test = CGRectIntersection(A, side);
3058 if ( ! CGRectIsEmpty(test)) {
3059 outr->rects[(outr->count)++] = test;
3060 }
3061 side = CGRectMake(rect.origin.x + rect.size.width, 0, verylarge, verylarge);// E side
3062 test = CGRectIntersection(A, side);
3063 if ( ! CGRectIsEmpty(test)) {
3064 outr->rects[(outr->count)++] = test;
3065 }
3066 side = CGRectMake(0, 0, verylarge, rect.origin.y);// S side
3067 test = CGRectIntersection(A, side);
3068 if ( ! CGRectIsEmpty(test)) {
3069 outr->rects[(outr->count)++] = test;
3070 }
3071 }
3072 }
3073 if (outr->count == 0) {
3074 free(outr->rects);
3075 free(outr);
3076 outr = XRectangleRegion(0,0,0,0);
3077 }
3078 else outr->rects = (CGRect*)realloc(outr->rects, outr->count * sizeof(CGRect));
3079 return outr;
3080}
3081
3082// intersects current and x,y,w,h rectangle and returns result as a new Fl_Region
3083Fl_Region Fl_X::intersect_region_and_rect(Fl_Region current, int x,int y,int w, int h)
3084{
3085 if (current == NULL) return XRectangleRegion(x,y,w,h);
3086 CGRect r = fl_cgrectmake_cocoa(x, y, w, h);
3087 Fl_Region outr = (Fl_Region)malloc(sizeof(*outr));
3088 outr->count = current->count;
3089 outr->rects =(CGRect*)malloc(outr->count * sizeof(CGRect));
3090 int j = 0;
3091 for(int i = 0; i < current->count; i++) {
3092 CGRect test = CGRectIntersection(current->rects[i], r);
3093 if (!CGRectIsEmpty(test)) outr->rects[j++] = test;
3094 }
3095 if (j) {
3096 outr->count = j;
3097 outr->rects = (CGRect*)realloc(outr->rects, outr->count * sizeof(CGRect));
3098 }
3099 else {
3100 XDestroyRegion(outr);
3101 outr = XRectangleRegion(0,0,0,0);
3102 }
3103 return outr;
3104}
3105
3106void Fl_X::collapse() {
3107 [(NSWindow *)xid miniaturize:nil];
3108}
3109
3110static NSImage *CGBitmapContextToNSImage(CGContextRef c)
3111// the returned NSImage is autoreleased
3112{
3113 unsigned char *pdata = (unsigned char *)CGBitmapContextGetData(c);
3114 NSBitmapImageRep *imagerep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&pdata
3115 pixelsWide:CGBitmapContextGetWidth(c)
3116 pixelsHigh:CGBitmapContextGetHeight(c)
3117 bitsPerSample:8
3118 samplesPerPixel:4
3119 hasAlpha:YES
3120 isPlanar:NO
3121 colorSpaceName:NSDeviceRGBColorSpace
3122 bytesPerRow:CGBitmapContextGetBytesPerRow(c)
3123 bitsPerPixel:CGBitmapContextGetBitsPerPixel(c)];
3124 NSImage* image = [[NSImage alloc] initWithData: [imagerep TIFFRepresentation]];
3125 [imagerep release];
3126 return [image autorelease];
3127}
3128
DRC685f17e2011-07-28 09:23:00 +00003129int Fl_X::set_cursor(Fl_Cursor c)
DRC2ff39b82011-07-28 08:38:59 +00003130{
DRC685f17e2011-07-28 09:23:00 +00003131 if (cursor) {
3132 [(NSCursor*)cursor release];
3133 cursor = NULL;
DRC2ff39b82011-07-28 08:38:59 +00003134 }
DRC685f17e2011-07-28 09:23:00 +00003135
3136 switch (c) {
3137 case FL_CURSOR_ARROW: cursor = [NSCursor arrowCursor]; break;
3138 case FL_CURSOR_CROSS: cursor = [NSCursor crosshairCursor]; break;
3139 case FL_CURSOR_INSERT: cursor = [NSCursor IBeamCursor]; break;
3140 case FL_CURSOR_HAND: cursor = [NSCursor pointingHandCursor]; break;
3141 case FL_CURSOR_MOVE: cursor = [NSCursor openHandCursor]; break;
3142 case FL_CURSOR_NS: cursor = [NSCursor resizeUpDownCursor]; break;
3143 case FL_CURSOR_WE: cursor = [NSCursor resizeLeftRightCursor]; break;
3144 case FL_CURSOR_N: cursor = [NSCursor resizeUpCursor]; break;
3145 case FL_CURSOR_E: cursor = [NSCursor resizeRightCursor]; break;
3146 case FL_CURSOR_W: cursor = [NSCursor resizeLeftCursor]; break;
3147 case FL_CURSOR_S: cursor = [NSCursor resizeDownCursor]; break;
3148 default:
3149 return 0;
3150 }
3151
3152 [(NSCursor*)cursor retain];
3153
3154 [(NSWindow*)xid invalidateCursorRectsForView:[(NSWindow*)xid contentView]];
3155
3156 return 1;
DRC2ff39b82011-07-28 08:38:59 +00003157}
3158
DRC685f17e2011-07-28 09:23:00 +00003159int Fl_X::set_cursor(const Fl_RGB_Image *image, int hotx, int hoty) {
3160 if (cursor) {
3161 [(NSCursor*)cursor release];
3162 cursor = NULL;
DRC2ff39b82011-07-28 08:38:59 +00003163 }
DRC685f17e2011-07-28 09:23:00 +00003164
3165 if ((hotx < 0) || (hotx >= image->w()))
3166 return 0;
3167 if ((hoty < 0) || (hoty >= image->h()))
3168 return 0;
3169
3170 // OS X >= 10.6 can create a NSImage from a CGImage, but we need to
3171 // support older versions, hence this pesky handling.
3172
3173 NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
3174 initWithBitmapDataPlanes:NULL
3175 pixelsWide:image->w()
3176 pixelsHigh:image->h()
3177 bitsPerSample:8
3178 samplesPerPixel:image->d()
3179 hasAlpha:!(image->d() & 1)
3180 isPlanar:NO
3181 colorSpaceName:(image->d()<=2) ? NSDeviceWhiteColorSpace : NSDeviceRGBColorSpace
3182 bytesPerRow:(image->w() * image->d())
3183 bitsPerPixel:(image->d()*8)];
3184
3185 // Alpha needs to be premultiplied for this format
3186
3187 const uchar *i = (const uchar*)*image->data();
3188 unsigned char *o = [bitmap bitmapData];
3189 for (int y = 0;y < image->h();y++) {
3190 if (image->d() & 1) {
3191 for (int x = 0;x < image->w();x++) {
3192 unsigned int alpha;
3193 if (image->d() == 4) {
3194 alpha = i[3];
3195 *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
3196 *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
3197 }
3198
3199 alpha = i[1];
3200 *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
3201 *o++ = alpha;
3202 i++;
3203 }
3204 } else {
3205 // No alpha, so we can just copy everything directly.
3206 int len = image->w() * image->d();
3207 memcpy(o, i, len);
3208 o += len;
3209 i += len;
3210 }
3211 i += image->ld();
3212 }
3213
3214 NSImage *nsimage = [[NSImage alloc]
3215 initWithSize:NSMakeSize(image->w(), image->h())];
3216
3217 [nsimage addRepresentation:bitmap];
3218
3219 cursor = [[NSCursor alloc]
3220 initWithImage:nsimage
3221 hotSpot:NSMakePoint(hotx, hoty)];
3222
3223 [(NSWindow*)xid invalidateCursorRectsForView:[(NSWindow*)xid contentView]];
3224
3225 [bitmap release];
3226 [nsimage release];
3227
3228 return 1;
DRC2ff39b82011-07-28 08:38:59 +00003229}
3230
3231@interface FLaboutItemTarget : NSObject
3232{
3233}
3234- (void)showPanel;
3235- (void)printPanel;
3236@end
3237@implementation FLaboutItemTarget
3238- (void)showPanel
3239{
Henrik Andersson485f4192011-09-16 11:51:32 +00003240 if ((Fl_Mac_App_Menu::copyright == NULL) ||
3241 (strlen(Fl_Mac_App_Menu::copyright) > 0)) {
3242 NSString *copyright;
3243
3244 if (Fl_Mac_App_Menu::copyright == NULL)
3245 copyright = [NSString stringWithFormat:@" GUI with FLTK %d.%d",
3246 FL_MAJOR_VERSION, FL_MINOR_VERSION ];
3247 else
3248 copyright = [NSString stringWithUTF8String:Fl_Mac_App_Menu::copyright];
3249
3250 NSDictionary *options;
3251 options = [NSDictionary dictionaryWithObjectsAndKeys:
3252 copyright, @"Copyright",
3253 nil];
3254
3255 [NSApp orderFrontStandardAboutPanelWithOptions:options];
3256 } else {
3257 [NSApp orderFrontStandardAboutPanelWithOptions:nil];
3258 }
DRC2ff39b82011-07-28 08:38:59 +00003259 }
3260//#include <FL/Fl_PostScript.H>
3261- (void)printPanel
3262{
3263 Fl_Printer printer;
3264 //Fl_PostScript_File_Device printer;
3265 int w, h, ww, wh;
3266 Fl_Window *win = Fl::first_window();
3267 if(!win) return;
3268 if( printer.start_job(1) ) return;
3269 if( printer.start_page() ) return;
3270 // scale the printer device so that the window fits on the page
3271 float scale = 1;
3272 printer.printable_rect(&w, &h);
3273 ww = win->decorated_w();
3274 wh = win->decorated_h();
3275 if (ww>w || wh>h) {
3276 scale = (float)w/win->w();
3277 if ((float)h/wh < scale) scale = (float)h/wh;
3278 printer.scale(scale);
3279 }
3280//#define ROTATE 1
3281#ifdef ROTATE
3282 printer.scale(scale * 0.8, scale * 0.8);
3283 printer.printable_rect(&w, &h);
3284 printer.origin(w/2, h/2 );
3285 printer.rotate(20.);
3286 printer.print_widget( win, - win->w()/2, - win->h()/2 );
3287#else
3288 printer.print_window(win);
3289#endif
3290 printer.end_page();
3291 printer.end_job();
3292}
3293@end
3294
3295static void createAppleMenu(void)
3296{
3297 static BOOL donethat = NO;
3298 if (donethat) return;
3299 donethat = YES;
3300 NSMenu *mainmenu, *services, *appleMenu;
3301 NSMenuItem *menuItem;
3302 NSString *title;
3303
3304 NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
3305 if (nsappname == nil)
3306 nsappname = [[NSProcessInfo processInfo] processName];
3307 appleMenu = [[NSMenu alloc] initWithTitle:@""];
3308 /* Add menu items */
3309 title = [[NSString stringWithUTF8String:Fl_Mac_App_Menu::about] stringByAppendingString:nsappname];
3310 menuItem = [appleMenu addItemWithTitle:title action:@selector(showPanel) keyEquivalent:@""];
3311 FLaboutItemTarget *about = [[FLaboutItemTarget alloc] init];
3312 [menuItem setTarget:about];
3313 [appleMenu addItem:[NSMenuItem separatorItem]];
3314 // Print front window
3315 if (strlen(Fl_Mac_App_Menu::print) > 0) {
3316 menuItem = [appleMenu
3317 addItemWithTitle:[NSString stringWithUTF8String:Fl_Mac_App_Menu::print]
3318 action:@selector(printPanel)
3319 keyEquivalent:@""];
3320 [menuItem setTarget:about];
3321 [appleMenu setAutoenablesItems:NO];
3322 [menuItem setEnabled:YES];
3323 [appleMenu addItem:[NSMenuItem separatorItem]];
3324 }
3325 // Services Menu
3326 services = [[NSMenu alloc] init];
3327 menuItem = [appleMenu
3328 addItemWithTitle:[NSString stringWithUTF8String:Fl_Mac_App_Menu::services]
3329 action:nil
3330 keyEquivalent:@""];
3331 [appleMenu setSubmenu:services forItem:menuItem];
3332 [appleMenu addItem:[NSMenuItem separatorItem]];
3333 // Hide AppName
3334 title = [[NSString stringWithUTF8String:Fl_Mac_App_Menu::hide] stringByAppendingString:nsappname];
3335 [appleMenu addItemWithTitle:title
3336 action:@selector(hide:)
3337 keyEquivalent:@"h"];
3338 // Hide Others
3339 menuItem = [appleMenu
3340 addItemWithTitle:[NSString stringWithUTF8String:Fl_Mac_App_Menu::hide_others]
3341 action:@selector(hideOtherApplications:)
3342 keyEquivalent:@"h"];
3343 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
3344 // Show All
3345 [appleMenu addItemWithTitle:[NSString stringWithUTF8String:Fl_Mac_App_Menu::show]
3346 action:@selector(unhideAllApplications:) keyEquivalent:@""];
3347 [appleMenu addItem:[NSMenuItem separatorItem]];
3348 // Quit AppName
3349 title = [[NSString stringWithUTF8String:Fl_Mac_App_Menu::quit]
3350 stringByAppendingString:nsappname];
3351 [appleMenu addItemWithTitle:title
3352 action:@selector(terminate:)
3353 keyEquivalent:@"q"];
3354 /* Put menu into the menubar */
3355 menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
3356 [menuItem setSubmenu:appleMenu];
3357 mainmenu = [[NSMenu alloc] initWithTitle:@""];
3358 [mainmenu addItem:menuItem];
3359 if (fl_mac_os_version < 100600) {
3360 // [NSApp setAppleMenu:appleMenu];
3361 // to avoid compiler warning raised by use of undocumented setAppleMenu :
3362 [NSApp performSelector:@selector(setAppleMenu:) withObject:appleMenu];
3363 }
3364 [NSApp setServicesMenu:services];
3365 [NSApp setMainMenu:mainmenu];
3366 [services release];
3367 [mainmenu release];
3368 [appleMenu release];
3369 [menuItem release];
3370}
3371
3372@interface FLMenuItem : NSMenuItem {
3373}
3374- (void) doCallback:(id)unused;
3375- (void) directCallback:(id)unused;
3376@end
3377@implementation FLMenuItem
3378- (void) doCallback:(id)unused
3379{
3380 int flRank = [self tag];
3381 const Fl_Menu_Item *items = fl_sys_menu_bar->Fl_Menu_::menu();
3382 const Fl_Menu_Item *item = items + flRank;
3383 if (item) {
3384 fl_sys_menu_bar->picked(item);
3385 if ( item->flags & FL_MENU_TOGGLE ) { // update the menu toggle symbol
3386 [self setState:(item->value() ? NSOnState : NSOffState)];
3387 }
3388 else if ( item->flags & FL_MENU_RADIO ) { // update the menu radio symbols
3389 int from = flRank;
3390 while( from > 0 && items[from - 1].label() && (items[from - 1].flags & FL_MENU_RADIO) &&
3391 !(items[from - 1].flags & FL_MENU_DIVIDER) ) {
3392 from--;
3393 }
3394 int to = flRank;
3395 while( !(items[to].flags & FL_MENU_DIVIDER) && items[to + 1].label() &&
3396 (items[to + 1].flags & FL_MENU_RADIO) ) {
3397 to++;
3398 }
3399 NSMenu *nsmenu = [self menu];
3400 int nsrank = (int)[nsmenu indexOfItem:self];
3401 for(int i = from - flRank + nsrank ; i <= to - flRank + nsrank; i++) {
3402 NSMenuItem *nsitem = [nsmenu itemAtIndex:i];
3403 if (nsitem != self) [nsitem setState:NSOffState];
3404 else [nsitem setState:(item->value() ? NSOnState : NSOffState) ];
3405 }
3406 }
3407 }
3408}
3409- (void) directCallback:(id)unused
3410{
3411 Fl_Menu_Item *item = (Fl_Menu_Item *)[(NSData*)[self representedObject] bytes];
3412 if ( item && item->callback() ) item->do_callback(NULL);
3413}
3414@end
3415
3416void fl_mac_set_about( Fl_Callback *cb, void *user_data, int shortcut)
3417{
3418 fl_open_display();
3419 Fl_Menu_Item aboutItem;
3420 memset(&aboutItem, 0, sizeof(Fl_Menu_Item));
3421 aboutItem.callback(cb);
3422 aboutItem.user_data(user_data);
3423 aboutItem.shortcut(shortcut);
3424 NSMenu *appleMenu = [[[NSApp mainMenu] itemAtIndex:0] submenu];
3425 CFStringRef cfname = CFStringCreateCopy(NULL, (CFStringRef)[[appleMenu itemAtIndex:0] title]);
3426 [appleMenu removeItemAtIndex:0];
3427 FLMenuItem *item = [[[FLMenuItem alloc] initWithTitle:(NSString*)cfname
3428 action:@selector(directCallback:)
3429 keyEquivalent:@""] autorelease];
3430 if (aboutItem.shortcut()) {
3431 Fl_Sys_Menu_Bar::doMenuOrItemOperation(Fl_Sys_Menu_Bar::setKeyEquivalent, item, aboutItem.shortcut() & 0xff);
3432 Fl_Sys_Menu_Bar::doMenuOrItemOperation(Fl_Sys_Menu_Bar::setKeyEquivalentModifierMask, item, aboutItem.shortcut() );
3433 }
3434 NSData *pointer = [NSData dataWithBytes:&aboutItem length:sizeof(Fl_Menu_Item)];
3435 [item setRepresentedObject:pointer];
3436 [appleMenu insertItem:item atIndex:0];
3437 CFRelease(cfname);
3438 [item setTarget:item];
3439}
3440
3441static char *remove_ampersand(const char *s)
3442{
3443 char *ret = strdup(s);
3444 const char *p = s;
3445 char *q = ret;
3446 while(*p != 0) {
3447 if (p[0]=='&') {
3448 if (p[1]=='&') {
3449 *q++ = '&'; p+=2;
3450 } else {
3451 p++;
3452 }
3453 } else {
3454 *q++ = *p++;
3455 }
3456 }
3457 *q = 0;
3458 return ret;
3459}
3460
3461void *Fl_Sys_Menu_Bar::doMenuOrItemOperation(Fl_Sys_Menu_Bar::menuOrItemOperation operation, ...)
3462/* these operations apply to menus, submenus, or menu items
3463 */
3464{
3465 NSAutoreleasePool *localPool;
3466 localPool = [[NSAutoreleasePool alloc] init];
3467 NSMenu *menu;
3468 NSMenuItem *item;
3469 int value;
3470 void *pter;
3471 void *retval = NULL;
3472 va_list ap;
3473 va_start(ap, operation);
3474
3475 if (operation == Fl_Sys_Menu_Bar::itemAtIndex) { // arguments: NSMenu*, int. Returns the item
3476 menu = va_arg(ap, NSMenu*);
3477 value = va_arg(ap, int);
3478 retval = (void *)[menu itemAtIndex:value];
3479 }
3480 else if (operation == Fl_Sys_Menu_Bar::setKeyEquivalent) { // arguments: NSMenuItem*, int
3481 item = va_arg(ap, NSMenuItem*);
3482 value = va_arg(ap, int);
3483 char key = value;
3484 NSString *equiv = [[NSString alloc] initWithBytes:&key length:1 encoding:NSASCIIStringEncoding];
3485 [item setKeyEquivalent:equiv];
3486 [equiv release];
3487 }
3488 else if (operation == Fl_Sys_Menu_Bar::setKeyEquivalentModifierMask) { // arguments: NSMenuItem*, int
3489 item = va_arg(ap, NSMenuItem*);
3490 value = va_arg(ap, int);
3491 NSUInteger macMod = 0;
3492 if ( value & FL_META ) macMod = NSCommandKeyMask;
3493 if ( value & FL_SHIFT || isupper(value) ) macMod |= NSShiftKeyMask;
3494 if ( value & FL_ALT ) macMod |= NSAlternateKeyMask;
3495 if ( value & FL_CTRL ) macMod |= NSControlKeyMask;
3496 [item setKeyEquivalentModifierMask:macMod];
3497 }
3498 else if (operation == Fl_Sys_Menu_Bar::setState) { // arguments: NSMenuItem*, int
3499 item = va_arg(ap, NSMenuItem*);
3500 value = va_arg(ap, int);
3501 [item setState:(value ? NSOnState : NSOffState)];
3502 }
3503 else if (operation == Fl_Sys_Menu_Bar::initWithTitle) { // arguments: const char*title. Returns the newly created menu
3504 // creates a new (sub)menu
3505 char *ts = remove_ampersand(va_arg(ap, char *));
3506 CFStringRef title = CFStringCreateWithCString(NULL, ts, kCFStringEncodingUTF8);
3507 free(ts);
3508 NSMenu *menu = [[NSMenu alloc] initWithTitle:(NSString*)title];
3509 CFRelease(title);
3510 [menu setAutoenablesItems:NO];
3511 retval = (void *)menu;
3512 }
3513 else if (operation == Fl_Sys_Menu_Bar::numberOfItems) { // arguments: NSMenu *menu, int *pcount
3514 // upon return, *pcount is set to menu's item count
3515 menu = va_arg(ap, NSMenu*);
3516 pter = va_arg(ap, void *);
3517 *(int*)pter = [menu numberOfItems];
3518 }
3519 else if (operation == Fl_Sys_Menu_Bar::setSubmenu) { // arguments: NSMenuItem *item, NSMenu *menu
3520 // sets 'menu' as submenu attached to 'item'
3521 item = va_arg(ap, NSMenuItem*);
3522 menu = va_arg(ap, NSMenu*);
3523 [item setSubmenu:menu];
3524 [menu release];
3525 }
3526 else if (operation == Fl_Sys_Menu_Bar::setEnabled) { // arguments: NSMenuItem*, int
3527 item = va_arg(ap, NSMenuItem*);
3528 value = va_arg(ap, int);
3529 [item setEnabled:(value ? YES : NO)];
3530 }
3531 else if (operation == Fl_Sys_Menu_Bar::addSeparatorItem) { // arguments: NSMenu*
3532 menu = va_arg(ap, NSMenu*);
3533 [menu addItem:[NSMenuItem separatorItem]];
3534 }
3535 else if (operation == Fl_Sys_Menu_Bar::setTitle) { // arguments: NSMenuItem*, const char *
3536 item = va_arg(ap, NSMenuItem*);
3537 char *ts = remove_ampersand(va_arg(ap, char *));
3538 CFStringRef title = CFStringCreateWithCString(NULL, ts, kCFStringEncodingUTF8);
3539 free(ts);
3540 [item setTitle:(NSString*)title];
3541 CFRelease(title);
3542 }
3543 else if (operation == Fl_Sys_Menu_Bar::removeItem) { // arguments: NSMenu*, int
3544 menu = va_arg(ap, NSMenu*);
3545 value = va_arg(ap, int);
3546 [menu removeItem:[menu itemAtIndex:value]];
3547 }
3548 else if (operation == Fl_Sys_Menu_Bar::addNewItem) { // arguments: NSMenu *menu, int flrank, int *prank
3549 // creates a new menu item at the end of 'menu'
3550 // attaches the item of rank flrank (counted in Fl_Menu_) of fl_sys_menu_bar to it
3551 // upon return, puts the rank (counted in NSMenu) of the new item in *prank unless prank is NULL
3552 menu = va_arg(ap, NSMenu*);
3553 int flRank = va_arg(ap, int);
3554 char *name = remove_ampersand( (fl_sys_menu_bar->Fl_Menu_::menu() + flRank)->label());
3555 int *prank = va_arg(ap, int*);
3556 CFStringRef cfname = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);
3557 free(name);
3558 FLMenuItem *item = [[FLMenuItem alloc] initWithTitle:(NSString*)cfname
3559 action:@selector(doCallback:)
3560 keyEquivalent:@""];
3561 [item setTag:flRank];
3562 [menu addItem:item];
3563 CFRelease(cfname);
3564 [item setTarget:item];
3565 if (prank != NULL) *prank = [menu indexOfItem:item];
3566 [item release];
3567 }
3568 else if (operation == Fl_Sys_Menu_Bar::renameItem) { // arguments: int rank, const char *newname
3569 // renames the system menu item numbered rank in fl_sys_menu_bar->menu()
3570 int rank = va_arg(ap, int);
3571 char *newname = remove_ampersand( va_arg(ap, const char *) );
3572 int countmenus = [[NSApp mainMenu] numberOfItems];
3573 bool found = NO;
3574 NSMenuItem *macitem = 0;
3575 for(int i = 1; (!found) && i < countmenus; i++) {
3576 NSMenuItem *item = [[NSApp mainMenu] itemAtIndex:i];
3577 NSMenu *submenu = [item submenu];
3578 if (submenu == nil) continue;
3579 int countitems = [submenu numberOfItems];
3580 for(int j = 0; j < countitems; j++) {
3581 macitem = [submenu itemAtIndex:j];
3582 if ([macitem tag] == rank) { found = YES; break; }
3583 }
3584 }
3585 if (found) {
3586 [macitem setTitle:[[[NSString alloc] initWithUTF8String:newname] autorelease]];
3587 }
3588 free(newname);
3589 }
3590 va_end(ap);
3591 [localPool release];
3592 return retval;
3593}
3594
3595void Fl_X::set_key_window()
3596{
3597 [(NSWindow*)xid makeKeyWindow];
3598}
3599
3600static NSImage *imageFromText(const char *text, int *pwidth, int *pheight)
3601{
3602 const char *p, *q;
3603 int width = 0, height, w2, ltext = strlen(text);
3604 fl_font(FL_HELVETICA, 10);
3605 p = text;
3606 int nl = 0;
3607 while((q=strchr(p, '\n')) != NULL) {
3608 nl++;
3609 w2 = int(fl_width(p, q - p));
3610 if (w2 > width) width = w2;
3611 p = q + 1;
3612 }
3613 if (text[ ltext - 1] != '\n') {
3614 nl++;
3615 w2 = int(fl_width(p));
3616 if (w2 > width) width = w2;
3617 }
3618 height = nl * fl_height() + 3;
3619 width += 6;
3620 Fl_Offscreen off = fl_create_offscreen_with_alpha(width, height);
3621 fl_begin_offscreen(off);
3622 CGContextSetRGBFillColor( (CGContextRef)off, 0,0,0,0);
3623 fl_rectf(0,0,width,height);
3624 fl_color(FL_BLACK);
3625 p = text;
3626 int y = fl_height();
3627 while(TRUE) {
3628 q = strchr(p, '\n');
3629 if (q) {
3630 fl_draw(p, q - p, 3, y);
3631 } else {
3632 fl_draw(p, 3, y);
3633 break;
3634 }
3635 y += fl_height();
3636 p = q + 1;
3637 }
3638 fl_end_offscreen();
3639 NSImage* image = CGBitmapContextToNSImage( (CGContextRef)off );
3640 fl_delete_offscreen( off );
3641 *pwidth = width;
3642 *pheight = height;
3643 return image;
3644}
3645
3646static NSImage *defaultDragImage(int *pwidth, int *pheight)
3647{
3648 const int width = 16, height = 16;
3649 Fl_Offscreen off = fl_create_offscreen_with_alpha(width, height);
3650 fl_begin_offscreen(off);
3651 CGContextSetRGBFillColor( (CGContextRef)off, 0,0,0,0);
3652 fl_rectf(0,0,width,height);
3653 CGContextSetRGBStrokeColor( (CGContextRef)off, 0,0,0,0.6);
3654 fl_rect(0,0,width,height);
3655 fl_rect(2,2,width-4,height-4);
3656 fl_end_offscreen();
3657 NSImage* image = CGBitmapContextToNSImage( (CGContextRef)off );
3658 fl_delete_offscreen( off );
3659 *pwidth = width;
3660 *pheight = height;
3661 return image;
3662}
3663
3664int Fl::dnd(void)
3665{
3666 CFDataRef text = CFDataCreate(kCFAllocatorDefault, (UInt8*)fl_selection_buffer[0], fl_selection_length[0]);
3667 if (text==NULL) return false;
3668 NSAutoreleasePool *localPool;
3669 localPool = [[NSAutoreleasePool alloc] init];
3670 NSPasteboard *mypasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
3671 [mypasteboard declareTypes:[NSArray arrayWithObjects:@"public.utf8-plain-text", nil] owner:nil];
3672 [mypasteboard setData:(NSData*)text forType:@"public.utf8-plain-text"];
3673 CFRelease(text);
3674 Fl_Widget *w = Fl::pushed();
3675 Fl_Window *win = w->window();
3676 if (win == NULL) {
3677 win = (Fl_Window*)w;
3678 } else {
3679 while(win->window()) win = win->window();
3680 }
3681 NSView *myview = [(NSWindow*)Fl_X::i(win)->xid contentView];
3682 NSEvent *theEvent = [NSApp currentEvent];
3683
3684 int width, height;
3685 NSImage *image;
3686 if ( dynamic_cast<Fl_Input_*>(w) != NULL || dynamic_cast<Fl_Text_Display*>(w) != NULL) {
3687 fl_selection_buffer[0][ fl_selection_length[0] ] = 0;
3688 image = imageFromText(fl_selection_buffer[0], &width, &height);
3689 } else {
3690 image = defaultDragImage(&width, &height);
3691 }
3692
3693 static NSSize offset={0,0};
3694 NSPoint pt = [theEvent locationInWindow];
3695 pt.x -= width/2;
3696 pt.y -= height/2;
3697 [myview dragImage:image at:pt offset:offset
3698 event:theEvent pasteboard:mypasteboard
3699 source:myview slideBack:YES];
3700 if ( w ) {
3701 int old_event = Fl::e_number;
3702 w->handle(Fl::e_number = FL_RELEASE);
3703 Fl::e_number = old_event;
3704 Fl::pushed( 0 );
3705 }
3706 [localPool release];
3707 return true;
3708}
3709
3710unsigned char *Fl_X::bitmap_from_window_rect(Fl_Window *win, int x, int y, int w, int h, int *bytesPerPixel)
3711// delete the returned pointer after use
3712{
3713 while(win->window()) {
3714 x += win->x();
3715 y += win->y();
3716 win = win->window();
3717 }
3718 CGFloat epsilon = 0;
3719 if (fl_mac_os_version >= 100600) epsilon = 0.001;
3720 // The epsilon offset is absolutely necessary under 10.6. Without it, the top pixel row and
3721 // left pixel column are not read, and bitmap is read shifted by one pixel in both directions.
3722 // Under 10.5, we want no offset.
3723 NSRect rect = NSMakeRect(x - epsilon, y - epsilon, w, h);
3724 NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:rect];
3725 *bytesPerPixel = [bitmap bitsPerPixel]/8;
3726 int bpp = (int)[bitmap bytesPerPlane];
3727 int bpr = (int)[bitmap bytesPerRow];
3728 int hh = bpp/bpr; // sometimes hh = h-1 for unclear reason
3729 int ww = bpr/(*bytesPerPixel); // sometimes ww = w-1
3730 unsigned char *data = new unsigned char[w * h * *bytesPerPixel];
3731 if (w == ww) {
3732 memcpy(data, [bitmap bitmapData], w * hh * *bytesPerPixel);
3733 } else {
3734 unsigned char *p = [bitmap bitmapData];
3735 unsigned char *q = data;
3736 for(int i = 0;i < hh; i++) {
3737 memcpy(q, p, *bytesPerPixel * ww);
3738 p += bpr;
3739 q += w * *bytesPerPixel;
3740 }
3741 }
3742 [bitmap release];
3743 return data;
3744}
3745
3746static void imgProviderReleaseData (void *info, const void *data, size_t size)
3747{
3748 delete[] (unsigned char *)data;
3749}
3750
3751CGImageRef Fl_X::CGImage_from_window_rect(Fl_Window *win, int x, int y, int w, int h)
3752// CFRelease the returned CGImageRef after use
3753{
3754 int bpp;
3755 unsigned char *bitmap = bitmap_from_window_rect(win, x, y, w, h, &bpp);
3756 CGImageRef img;
3757 CGColorSpaceRef lut = CGColorSpaceCreateDeviceRGB();
3758 CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmap, w*h*bpp, imgProviderReleaseData);
3759 img = CGImageCreate(w, h, 8, 8*bpp, w*bpp, lut,
3760 bpp == 3 ? kCGImageAlphaNone : kCGImageAlphaLast,
3761 provider, NULL, false, kCGRenderingIntentDefault);
3762 CGColorSpaceRelease(lut);
3763 CGDataProviderRelease(provider);
3764 return img;
3765}
3766
3767WindowRef Fl_X::window_ref()
3768{
3769 return (WindowRef)[(FLWindow*)xid windowRef];
3770}
3771
3772// so a CGRect matches exactly what is denoted x,y,w,h for clipping purposes
3773CGRect fl_cgrectmake_cocoa(int x, int y, int w, int h) {
3774 if (Fl_Surface_Device::surface()->class_name() == Fl_Printer::class_id) return CGRectMake(x-0.5, y-0.5, w, h);
3775 return CGRectMake(x, y, w > 0 ? w - 0.9 : 0, h > 0 ? h - 0.9 : 0);
3776}
3777
3778Window fl_xid(const Fl_Window* w)
3779{
3780 Fl_X *temp = Fl_X::i(w);
3781 return temp ? temp->xid : 0;
3782}
3783
3784int Fl_Window::decorated_w()
3785{
3786 if (!shown() || parent() || !border() || !visible()) return w();
3787 int bx, by, bt;
3788 get_window_frame_sizes(bx, by, bt);
3789 return w() + 2 * bx;
3790}
3791
3792int Fl_Window::decorated_h()
3793{
3794 if (!shown() || parent() || !border() || !visible()) return h();
3795 int bx, by, bt;
3796 get_window_frame_sizes(bx, by, bt);
3797 return h() + bt + by;
3798}
3799
3800void Fl_Paged_Device::print_window(Fl_Window *win, int x_offset, int y_offset)
3801{
3802 if (!win->shown() || win->parent() || !win->border() || !win->visible()) {
3803 this->print_widget(win, x_offset, y_offset);
3804 return;
3805 }
3806 int bx, by, bt;
3807 get_window_frame_sizes(bx, by, bt);
3808 Fl_Display_Device::display_device()->set_current(); // send win to front and make it current
3809 win->show();
3810 fl_gc = NULL;
3811 Fl::check();
3812 win->make_current();
3813 // capture the window title bar from screen
3814 CGImageRef img = Fl_X::CGImage_from_window_rect(win, 0, -bt, win->w(), bt);
3815 this->set_current(); // back to the Fl_Paged_Device
3816 CGRect rect = { { 0, 0 }, { win->w(), bt } }; // print the title bar
3817 Fl_X::q_begin_image(rect, 0, 0, win->w(), bt);
3818 CGContextDrawImage(fl_gc, rect, img);
3819 Fl_X::q_end_image();
3820 CGImageRelease(img);
3821 this->print_widget(win, x_offset, y_offset + bt); // print the window inner part
3822}
3823
3824#include <dlfcn.h>
3825
3826/* Returns the address of a Carbon function after dynamically loading the Carbon library if needed.
3827 Supports old Mac OS X versions that may use a couple of Carbon calls:
3828 GetKeys used by OS X 10.3 or before (in Fl::get_key())
3829 PMSessionPageSetupDialog and PMSessionPrintDialog used by 10.4 or before (in Fl_Printer::start_job())
3830 GetWindowPort used by 10.4 or before (in Fl_Gl_Choice.cxx)
3831 */
3832void *Fl_X::get_carbon_function(const char *function_name) {
3833 static void *carbon = NULL;
3834 void *f = NULL;
3835 if (!carbon) {
3836 carbon = dlopen("/System/Library/Frameworks/Carbon.framework/Carbon", RTLD_LAZY);
3837 }
3838 if (carbon) {
3839 f = dlsym(carbon, function_name);
3840 }
3841 return f;
3842}
3843
3844#endif // __APPLE__
3845
3846//
3847// End of "$Id: Fl_cocoa.mm 8807 2011-06-16 12:35:32Z manolo $".
3848//