blob: 5fd52d68c91b05bb6ea6f5d346877bcdfca95e38 [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;
1669- (BOOL)handleKeyDown:(NSEvent *)theEvent;
1670- (void)keyDown:(NSEvent *)theEvent;
1671- (void)keyUp:(NSEvent *)theEvent;
1672- (void)flagsChanged:(NSEvent *)theEvent;
1673- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender;
1674- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender;
1675- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
1676- (void)draggingExited:(id < NSDraggingInfo >)sender;
1677- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal;
1678@end
1679
1680@implementation FLView
1681- (id)init
1682{
1683 self = [super init];
1684 if (self) {
1685 next_compose_length = -1;
1686 in_key_event = false;
1687 }
1688 return self;
1689}
1690- (void)drawRect:(NSRect)rect
1691{
1692 fl_lock_function();
1693 FLWindow *cw = (FLWindow*)[self window];
1694 Fl_Window *w = [cw getFl_Window];
1695 handleUpdateEvent(w);
1696 fl_unlock_function();
1697}
1698
1699- (BOOL)acceptsFirstResponder
1700{
1701 return YES;
1702}
1703- (BOOL)performKeyEquivalent:(NSEvent*)theEvent
1704{
1705 //NSLog(@"performKeyEquivalent:");
1706 return [self handleKeyDown:theEvent];
1707}
1708- (BOOL)acceptsFirstMouse:(NSEvent*)theEvent
1709{
1710 Fl_Window *w = [(FLWindow*)[theEvent window] getFl_Window];
1711 Fl_Window *first = Fl::first_window();
1712 return (first == w || !first->modal());
1713}
DRC685f17e2011-07-28 09:23:00 +00001714- (void)resetCursorRects {
1715 Fl_Window *w = [(FLWindow*)[self window] getFl_Window];
1716 Fl_X *i = Fl_X::i(w);
1717 // We have to have at least one cursor rect for invalidateCursorRectsForView
1718 // to work, hence the "else" clause.
1719 if (i->cursor)
1720 [self addCursorRect:[self visibleRect] cursor:(NSCursor*)i->cursor];
1721 else
1722 [self addCursorRect:[self visibleRect] cursor:[NSCursor arrowCursor]];
1723}
DRC2ff39b82011-07-28 08:38:59 +00001724- (void)mouseUp:(NSEvent *)theEvent {
1725 cocoaMouseHandler(theEvent);
1726}
1727- (void)rightMouseUp:(NSEvent *)theEvent {
1728 cocoaMouseHandler(theEvent);
1729}
1730- (void)otherMouseUp:(NSEvent *)theEvent {
1731 cocoaMouseHandler(theEvent);
1732}
1733- (void)mouseDown:(NSEvent *)theEvent {
1734 cocoaMouseHandler(theEvent);
1735}
1736- (void)rightMouseDown:(NSEvent *)theEvent {
1737 cocoaMouseHandler(theEvent);
1738}
1739- (void)otherMouseDown:(NSEvent *)theEvent {
1740 cocoaMouseHandler(theEvent);
1741}
1742- (void)mouseMoved:(NSEvent *)theEvent {
1743 cocoaMouseHandler(theEvent);
1744}
1745- (void)mouseDragged:(NSEvent *)theEvent {
1746 cocoaMouseHandler(theEvent);
1747}
1748- (void)rightMouseDragged:(NSEvent *)theEvent {
1749 cocoaMouseHandler(theEvent);
1750}
1751- (void)otherMouseDragged:(NSEvent *)theEvent {
1752 cocoaMouseHandler(theEvent);
1753}
1754- (void)scrollWheel:(NSEvent *)theEvent {
1755 cocoaMouseWheelHandler(theEvent);
1756}
1757- (BOOL)handleKeyDown:(NSEvent *)theEvent {
1758 //NSLog(@"handleKeyDown");
1759 fl_lock_function();
1760
1761 Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
1762 Fl::first_window(window);
1763
1764 next_compose_length = -1;
1765 // First let's process the raw key press
1766 cocoaKeyboardHandler(theEvent);
1767
1768 int no_text_key = false;
1769 static const int notext[] = { // keys that don't emit text
1770 FL_BackSpace, FL_Print, FL_Scroll_Lock, FL_Pause,
1771 FL_Insert, FL_Home, FL_Page_Up, FL_Delete, FL_End, FL_Page_Down,
1772 FL_Left, FL_Up, FL_Right, FL_Down,
1773 FL_Menu, FL_Num_Lock, FL_Help
1774 };
1775 static const int count = sizeof(notext)/sizeof(int);
1776 if (Fl::e_keysym > FL_F && Fl::e_keysym <= FL_F_Last) no_text_key = true;
1777 else for (int i=0; i < count; i++) {
1778 if (notext[i] == Fl::e_keysym) {
1779 no_text_key = true;
1780 break;
1781 }
1782 }
DRC685f17e2011-07-28 09:23:00 +00001783 // Don't send cmd-<key> to interpretKeyEvents because it beeps.
DRC2ff39b82011-07-28 08:38:59 +00001784 if (!no_text_key && !(Fl::e_state & FL_META) ) {
DRC685f17e2011-07-28 09:23:00 +00001785 // The simple keyboard model will ignore insertText, so we need to grab
1786 // the symbol directly from the event. Note that we still use setMarkedText.
1787 if (use_simple_keyboard)
1788 [FLView prepareEtext:[theEvent charactersIgnoringModifiers]];
1789
DRC2ff39b82011-07-28 08:38:59 +00001790 // Then we can let the OS have a stab at it and see if it thinks it
1791 // should result in some text
1792 NSText *edit = [[theEvent window] fieldEditor:YES forObject:nil];
1793 in_key_event = true;
1794 [edit interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
1795 in_key_event = false;
1796 }
1797 //NSLog(@"to text=%@ l=%d", [NSString stringWithUTF8String:Fl::e_text], Fl::e_length);
1798 int handled = Fl::handle(FL_KEYDOWN, window);
1799 // We have to update this after Fl::handle as it says what to do on the
1800 // _next_ input
1801 if (next_compose_length != -1)
1802 Fl::compose_state = next_compose_length;
1803
1804 fl_unlock_function();
1805 return (handled ? YES : NO);
1806}
1807- (void)keyDown:(NSEvent *)theEvent {
1808 //NSLog(@"keyDown: ");
1809 [self handleKeyDown:theEvent];
1810}
1811- (void)keyUp:(NSEvent *)theEvent {
1812 //NSLog(@"keyUp: ");
1813 fl_lock_function();
1814 Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
1815 Fl::first_window(window);
1816 cocoaKeyboardHandler(theEvent);
1817 NSString *s = [theEvent characters];
1818 if ([s length] >= 1) [FLView prepareEtext:[s substringToIndex:1]];
1819 Fl::handle(FL_KEYUP,window);
1820 fl_unlock_function();
1821}
1822- (void)flagsChanged:(NSEvent *)theEvent {
1823 //NSLog(@"flagsChanged: ");
1824 fl_lock_function();
1825 static UInt32 prevMods = 0;
1826 NSUInteger mods = [theEvent modifierFlags];
1827 Fl_Window *window = (Fl_Window*)[(FLWindow*)[theEvent window] getFl_Window];
1828 UInt32 tMods = prevMods ^ mods;
1829 int sendEvent = 0;
1830 if ( tMods )
1831 {
1832 unsigned short keycode = [theEvent keyCode];
1833 Fl::e_keysym = Fl::e_original_keysym = macKeyLookUp[keycode & 0x7f];
1834 if ( Fl::e_keysym )
1835 sendEvent = ( prevMods<mods ) ? FL_KEYBOARD : FL_KEYUP;
1836 Fl::e_length = 0;
1837 Fl::e_text = (char*)"";
1838 prevMods = mods;
1839 }
1840 mods_to_e_state( mods );
1841 while (window->parent()) window = window->window();
1842 if (sendEvent) Fl::handle(sendEvent,window);
1843 fl_unlock_function();
1844}
1845- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender
1846{
1847 fl_lock_function();
1848 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
1849 update_e_xy_and_e_xy_root([self window]);
1850 fl_dnd_target_window = target;
1851 int ret = Fl::handle( FL_DND_ENTER, target );
1852 breakMacEventLoop();
1853 fl_unlock_function();
1854 return ret ? NSDragOperationCopy : NSDragOperationNone;
1855}
1856- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender
1857{
1858 fl_lock_function();
1859 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
1860 update_e_xy_and_e_xy_root([self window]);
1861 fl_dnd_target_window = target;
1862 int ret = Fl::handle( FL_DND_DRAG, target );
1863 breakMacEventLoop();
1864 fl_unlock_function();
1865 return ret ? NSDragOperationCopy : NSDragOperationNone;
1866}
1867- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1868{
1869 static char *DragData = NULL;
1870 fl_lock_function();
1871 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
1872 if ( !Fl::handle( FL_DND_RELEASE, target ) ) {
1873 breakMacEventLoop();
1874 fl_unlock_function();
1875 return NO;
1876 }
1877 NSPasteboard *pboard;
1878 // NSDragOperation sourceDragMask;
1879 // sourceDragMask = [sender draggingSourceOperationMask];
1880 pboard = [sender draggingPasteboard];
1881 update_e_xy_and_e_xy_root([self window]);
1882 if (DragData) { free(DragData); DragData = NULL; }
1883 if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
1884 CFArrayRef files = (CFArrayRef)[pboard propertyListForType:NSFilenamesPboardType];
1885 CFStringRef all = CFStringCreateByCombiningStrings(NULL, files, CFSTR("\n"));
1886 int l = CFStringGetMaximumSizeForEncoding(CFStringGetLength(all), kCFStringEncodingUTF8);
1887 DragData = (char *)malloc(l + 1);
1888 CFStringGetCString(all, DragData, l + 1, kCFStringEncodingUTF8);
1889 CFRelease(all);
1890 }
1891 else if ( [[pboard types] containsObject:NSStringPboardType] ) {
1892 NSData *data = [pboard dataForType:NSStringPboardType];
1893 DragData = (char *)malloc([data length] + 1);
1894 [data getBytes:DragData];
1895 DragData[[data length]] = 0;
1896 convert_crlf(DragData, strlen(DragData));
1897 }
1898 else {
1899 breakMacEventLoop();
1900 fl_unlock_function();
1901 return NO;
1902 }
1903 Fl::e_text = DragData;
1904 Fl::e_length = strlen(DragData);
1905 int old_event = Fl::e_number;
1906 Fl::belowmouse()->handle(Fl::e_number = FL_PASTE);
1907 Fl::e_number = old_event;
1908 if (DragData) { free(DragData); DragData = NULL; }
1909 Fl::e_text = NULL;
1910 Fl::e_length = 0;
1911 fl_dnd_target_window = NULL;
1912 breakMacEventLoop();
1913 fl_unlock_function();
1914 return YES;
1915}
1916- (void)draggingExited:(id < NSDraggingInfo >)sender
1917{
1918 fl_lock_function();
1919 if ( fl_dnd_target_window ) {
1920 Fl::handle( FL_DND_LEAVE, fl_dnd_target_window );
1921 fl_dnd_target_window = 0;
1922 }
1923 fl_unlock_function();
1924}
1925- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
1926{
1927 return NSDragOperationGeneric;
1928}
1929
1930+ (void)prepareEtext:(NSString*)aString {
1931 // fills Fl::e_text with UTF-8 encoded aString using an adequate memory allocation
1932 static char *received_utf8 = NULL;
1933 static int lreceived = 0;
1934 char *p = (char*)[aString UTF8String];
1935 int l = strlen(p);
1936 if (l > 0) {
1937 if (lreceived == 0) {
1938 received_utf8 = (char*)malloc(l + 1);
1939 lreceived = l;
1940 }
1941 else if (l > lreceived) {
1942 received_utf8 = (char*)realloc(received_utf8, l + 1);
1943 lreceived = l;
1944 }
1945 strcpy(received_utf8, p);
1946 Fl::e_text = received_utf8;
1947 }
1948 Fl::e_length = l;
1949}
1950
1951// These functions implement text input.
1952// Only two-stroke character composition works at this point.
1953// Needs much elaboration to fully support CJK text input,
1954// but this is the way to go.
1955- (void)doCommandBySelector:(SEL)aSelector {
1956}
1957
1958- (void)insertText:(id)aString {
1959 NSString *received;
1960 if ([aString isKindOfClass:[NSAttributedString class]]) {
1961 received = [(NSAttributedString*)aString string];
1962 } else {
1963 received = (NSString*)aString;
1964 }
1965 //NSLog(@"insertText: received=%@",received);
1966
1967 if (!in_key_event) fl_lock_function();
DRC685f17e2011-07-28 09:23:00 +00001968
1969 // Simple keyboard widgets do not want these side channel inputs.
1970 if (use_simple_keyboard)
1971 goto end;
1972
DRC2ff39b82011-07-28 08:38:59 +00001973 [FLView prepareEtext:received];
DRC685f17e2011-07-28 09:23:00 +00001974
DRC2ff39b82011-07-28 08:38:59 +00001975 // We can get called outside of key events (e.g. from the character
DRC685f17e2011-07-28 09:23:00 +00001976 // palette). We need to fake our own key event at that point.
DRC2ff39b82011-07-28 08:38:59 +00001977 if (!in_key_event) {
1978 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
DRC685f17e2011-07-28 09:23:00 +00001979 Fl::e_keysym = Fl::e_original_keysym = 0;
1980 Fl::handle(FL_KEYDOWN, target);
DRC2ff39b82011-07-28 08:38:59 +00001981 // for some reason, the window does not redraw until the next mouse move or button push
1982 // sending a 'redraw()' or 'awake()' does not solve the issue!
1983 Fl::flush();
1984 }
DRC685f17e2011-07-28 09:23:00 +00001985
1986end:
DRC2ff39b82011-07-28 08:38:59 +00001987 if (!in_key_event) fl_unlock_function();
1988}
1989
1990- (void)setMarkedText:(id)aString selectedRange:(NSRange)newSelection {
DRC685f17e2011-07-28 09:23:00 +00001991 NSString *received, *current, *aggregate;
DRC2ff39b82011-07-28 08:38:59 +00001992 if (newSelection.location == 0) {
1993 [self unmarkText];
1994 return;
1995 }
1996 if ([aString isKindOfClass:[NSAttributedString class]]) {
1997 received = [(NSAttributedString*)aString string];
1998 } else {
1999 received = (NSString*)aString;
2000 }
2001 //NSLog(@"setMarkedText: %@ %d %d",received,newSelection.location,newSelection.length);
DRC685f17e2011-07-28 09:23:00 +00002002
2003 fl_lock_function();
2004
2005 // Simple keyboard widgets generally do not want these side channel
2006 // inputs, but we have no other way of getting dead keys so we make
2007 // an exception in that case.
2008 if (use_simple_keyboard) {
2009 if (in_key_event && (Fl::e_length == 0)) {
2010 [FLView prepareEtext:received];
2011
2012 Fl::e_text = (char*)cocoaDead2FLTK(Fl::e_text);
2013 Fl::e_length = strlen(Fl::e_text);
2014 }
2015 goto end;
2016 }
2017
DRC2ff39b82011-07-28 08:38:59 +00002018 // This code creates the OS X behaviour of seeing dead keys as things
2019 // are being composed.
DRC685f17e2011-07-28 09:23:00 +00002020 //
2021 // Note: The concatenation thing is because of how OS X deals with
2022 // invalid sequences. At that point it will spit out one call
2023 // to insertText with the now aborted sequence, and one new
2024 // call to setMarkedText with the new sequence. Since we want
2025 // both to be visible, we need to concatenate.
DRC2ff39b82011-07-28 08:38:59 +00002026 next_compose_length = newSelection.location;
DRC685f17e2011-07-28 09:23:00 +00002027 current = [NSString stringWithUTF8String:Fl::e_text];
2028 aggregate = [current stringByAppendingString:received];
2029
2030 [FLView prepareEtext:aggregate];
2031 //NSLog(@"Fl::e_text=%@ Fl::e_length=%d next_compose_length=%d", aggregate, Fl::e_length, next_compose_length);
2032
2033 // We can get called outside of key events (e.g. from the character
2034 // palette). We need to fake our own key event at that point.
2035 if (!in_key_event) {
2036 Fl_Window *target = [(FLWindow*)[self window] getFl_Window];
2037 Fl::e_keysym = Fl::e_original_keysym = 0;
2038 Fl::handle(FL_KEYDOWN, target);
2039 }
2040
2041end:
2042 fl_unlock_function();
DRC2ff39b82011-07-28 08:38:59 +00002043}
2044
2045- (void)unmarkText {
2046 fl_lock_function();
2047 Fl::compose_state = 0;
2048 fl_unlock_function();
2049 //NSLog(@"unmarkText");
2050}
2051
2052- (NSRange)selectedRange {
2053 return NSMakeRange(NSNotFound, 0);
2054}
2055
2056- (NSRange)markedRange {
2057 //NSLog(@"markedRange ?");
2058 return NSMakeRange(NSNotFound, Fl::compose_state);
2059}
2060
2061- (BOOL)hasMarkedText {
2062 //NSLog(@"hasMarkedText %s", Fl::compose_state > 0?"YES":"NO");
2063 return (Fl::compose_state > 0);
2064}
2065
2066- (NSAttributedString *)attributedSubstringFromRange:(NSRange)aRange {
2067 //NSLog(@"attributedSubstringFromRange: %d %d",aRange.location,aRange.length);
2068 return nil;
2069}
2070
2071- (NSArray *)validAttributesForMarkedText {
2072 return nil;
2073}
2074
2075- (NSRect)firstRectForCharacterRange:(NSRange)aRange {
2076 NSRect glyphRect;
2077 fl_lock_function();
2078 Fl_Widget *focus = Fl::focus();
2079 Fl_Window *wfocus = focus->window();
2080 while (wfocus->window()) wfocus = wfocus->window();
2081 glyphRect.size.width = 0;
2082
2083 if (dynamic_cast<Fl_Text_Display*>(focus) != NULL) {
2084 int x, y;
2085 Fl_Text_Display *current = (Fl_Text_Display*)focus;
2086 current->position_to_xy( current->insert_position(), &x, &y );
2087 glyphRect.origin.x = (CGFloat)x;
2088 glyphRect.origin.y = (CGFloat)y + current->textsize();
2089 glyphRect.size.height = current->textsize();
2090 } else {
2091 glyphRect.origin.x = focus->x();
2092 glyphRect.origin.y = focus->y() + focus->h();
2093 glyphRect.size.height = 12;
2094 }
2095 // Convert the rect to screen coordinates
2096 glyphRect.origin.y = wfocus->h() - glyphRect.origin.y;
2097 glyphRect.origin = [[self window] convertBaseToScreen:glyphRect.origin];
2098 fl_unlock_function();
2099 return glyphRect;
2100}
2101
2102- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
2103 return 0;
2104}
2105
2106- (NSInteger)conversationIdentifier {
2107 return (NSInteger)self;
2108}
2109
2110@end
2111
DRC685f17e2011-07-28 09:23:00 +00002112void fullscreen_x(Fl_Window *w) {
2113 w->_set_fullscreen();
2114 /* On OS X < 10.6, it is necessary to recreate the window. This is done
2115 with hide+show. */
2116 w->hide();
2117 w->show();
2118 Fl::handle(FL_FULLSCREEN, w);
2119}
2120
2121void fullscreen_off_x(Fl_Window *w, int X, int Y, int W, int H) {
2122 w->_clear_fullscreen();
2123 w->hide();
2124 w->resize(X, Y, W, H);
2125 w->show();
2126 Fl::handle(FL_FULLSCREEN, w);
2127}
DRC2ff39b82011-07-28 08:38:59 +00002128
2129/*
2130 * go ahead, create that (sub)window
2131 */
2132void Fl_X::make(Fl_Window* w)
2133{
2134 static int xyPos = 100;
2135 if ( w->parent() ) { // create a subwindow
2136 Fl_Group::current(0);
2137 // our subwindow needs this structure to know about its clipping.
2138 Fl_X* x = new Fl_X;
2139 x->subwindow = true;
2140 x->other_xid = 0;
2141 x->region = 0;
2142 x->subRegion = 0;
DRC685f17e2011-07-28 09:23:00 +00002143 x->cursor = NULL;
DRC2ff39b82011-07-28 08:38:59 +00002144 x->gc = 0; // stay 0 for Quickdraw; fill with CGContext for Quartz
2145 Fl_Window *win = w->window();
2146 Fl_X *xo = Fl_X::i(win);
2147 if (xo) {
2148 x->xidNext = xo->xidChildren;
2149 x->xidChildren = 0L;
2150 xo->xidChildren = x;
2151 x->xid = win->i->xid;
2152 x->w = w; w->i = x;
2153 x->wait_for_expose = 0;
2154 {
2155 Fl_X *z = xo->next; // we don't want a subwindow in Fl_X::first
2156 xo->next = x;
2157 x->next = z;
2158 }
2159 int old_event = Fl::e_number;
2160 w->handle(Fl::e_number = FL_SHOW);
2161 Fl::e_number = old_event;
2162 w->redraw(); // force draw to happen
2163 }
2164 if (w->as_gl_window()) { // if creating a sub-GL-window
2165 while (win->window()) win = win->window();
2166 [(FLWindow*)Fl_X::i(win)->xid setContainsGLsubwindow:YES];
2167 }
2168 fl_show_iconic = 0;
2169 }
2170 else { // create a desktop window
2171 Fl_Group::current(0);
2172 fl_open_display();
2173 NSInteger winlevel = NSNormalWindowLevel;
2174 NSUInteger winstyle;
2175 if (w->border()) winstyle = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask;
2176 else winstyle = NSBorderlessWindowMask;
2177 int xp = w->x();
2178 int yp = w->y();
2179 int wp = w->w();
2180 int hp = w->h();
2181 if (w->size_range_set) {
2182 if ( w->minh != w->maxh || w->minw != w->maxw) {
2183 winstyle |= NSResizableWindowMask;
2184 }
2185 } else {
2186 if (w->resizable()) {
2187 Fl_Widget *o = w->resizable();
2188 int minw = o->w(); if (minw > 100) minw = 100;
2189 int minh = o->h(); if (minh > 100) minh = 100;
2190 w->size_range(w->w() - o->w() + minw, w->h() - o->h() + minh, 0, 0);
2191 winstyle |= NSResizableWindowMask;
2192 } else {
2193 w->size_range(w->w(), w->h(), w->w(), w->h());
2194 }
2195 }
2196 int xwm = xp, ywm = yp, bt, bx, by;
2197
2198 if (!fake_X_wm(w, xwm, ywm, bt, bx, by)) {
2199 // menu windows and tooltips
2200 if (w->modal()||w->tooltip_window()) {
2201 winstyle = NSBorderlessWindowMask;
2202 winlevel = NSModalPanelWindowLevel;
2203 } else {
2204 winstyle = NSBorderlessWindowMask;
2205 }
2206 } else if (w->modal()) {
2207 winstyle &= ~NSMiniaturizableWindowMask;
2208 // winstyle &= ~(NSResizableWindowMask | NSMiniaturizableWindowMask);
2209 winlevel = NSModalPanelWindowLevel;
2210 }
2211 else if (w->non_modal()) {
2212 winlevel = NSFloatingWindowLevel;
2213 }
2214
2215 if (by+bt) {
2216 wp += 2*bx;
2217 hp += 2*by+bt;
2218 }
2219 if (!(w->flags() & Fl_Window::FORCE_POSITION)) {
2220 // use the Carbon functions below for default window positioning
2221 w->x(xyPos+Fl::x());
2222 w->y(xyPos+Fl::y());
2223 xyPos += 25;
2224 if (xyPos>200) xyPos = 100;
2225 } else {
2226 if (!Fl::grab()) {
2227 xp = xwm; yp = ywm;
2228 w->x(xp);w->y(yp);
2229 }
2230 xp -= bx;
2231 yp -= by+bt;
2232 }
2233
2234 if (w->non_modal() && Fl_X::first /*&& !fl_disable_transient_for*/) {
2235 // find some other window to be "transient for":
2236 Fl_Window* w = Fl_X::first->w;
2237 while (w->parent()) w = w->window(); // todo: this code does not make any sense! (w!=w??)
2238 }
2239
2240 Fl_X* x = new Fl_X;
2241 x->subwindow = false;
2242 x->other_xid = 0; // room for doublebuffering image map. On OS X this is only used by overlay windows
2243 x->region = 0;
2244 x->subRegion = 0;
DRC685f17e2011-07-28 09:23:00 +00002245 x->cursor = NULL;
DRC2ff39b82011-07-28 08:38:59 +00002246 x->xidChildren = 0;
2247 x->xidNext = 0;
2248 x->gc = 0;
2249
2250 NSRect srect = [[NSScreen mainScreen] frame];
DRC685f17e2011-07-28 09:23:00 +00002251 if (w->flags() & Fl_Widget::FULLSCREEN) {
2252 int sx, sy, sw, sh;
2253 Fl::screen_xywh(sx, sy, sw, sh, w->x(), w->y(), w->w(), w->h());
2254 w->resize(sx, sy, sw, sh);
2255 winstyle = NSBorderlessWindowMask;
2256 winlevel = NSStatusWindowLevel;
2257 }
DRC2ff39b82011-07-28 08:38:59 +00002258 NSRect crect;
2259 crect.origin.x = w->x();
2260 crect.origin.y = srect.size.height - (w->y() + w->h());
2261 crect.size.width=w->w();
2262 crect.size.height=w->h();
2263 FLWindow *cw = [[FLWindow alloc] initWithFl_W:w
2264 contentRect:crect
2265 styleMask:winstyle];
2266 [cw setHasShadow:YES];
2267 [cw setAcceptsMouseMovedEvents:YES];
2268 x->xid = cw;
2269 FLView *myview = [[FLView alloc] init];
2270 [cw setContentView:myview];
2271 [cw setLevel:winlevel];
2272
2273 q_set_window_title(cw, w->label(), w->iconlabel());
2274 if (!(w->flags() & Fl_Window::FORCE_POSITION)) {
2275 if (w->modal()) {
2276 [cw center];
2277 } else if (w->non_modal()) {
2278 [cw center];
2279 } else {
2280 static NSPoint delta = NSZeroPoint;
2281 delta = [cw cascadeTopLeftFromPoint:delta];
2282 }
2283 }
2284 if(w->menu_window()) { // make menu windows slightly transparent
2285 [cw setAlphaValue:0.97];
2286 }
2287 x->w = w; w->i = x;
2288 x->wait_for_expose = 1;
2289 x->next = Fl_X::first;
2290 Fl_X::first = x;
2291 // Install DnD handlers
2292 [myview registerForDraggedTypes:[NSArray arrayWithObjects:
2293 NSStringPboardType, NSFilenamesPboardType, nil]];
2294 if ( ! Fl_X::first->next ) {
2295 // if this is the first window, we need to bring the application to the front
2296 ProcessSerialNumber psn = { 0, kCurrentProcess };
2297 SetFrontProcess( &psn );
2298 }
2299
2300 if (w->size_range_set) w->size_range_();
2301
2302 if ( w->border() || (!w->modal() && !w->tooltip_window()) ) {
2303 Fl_Tooltip::enter(0);
2304 }
2305 w->set_visible();
2306 if ( w->border() || (!w->modal() && !w->tooltip_window()) ) Fl::handle(FL_FOCUS, w);
2307 Fl::first_window(w);
2308 [cw setDelegate:mydelegate];
2309 if (fl_show_iconic) {
2310 fl_show_iconic = 0;
2311 [cw miniaturize:nil];
2312 } else {
2313 [cw makeKeyAndOrderFront:nil];
2314 }
2315
2316 crect = [[cw contentView] frame];
2317 w->w(int(crect.size.width));
2318 w->h(int(crect.size.height));
2319 crect = [cw frame];
2320 w->x(int(crect.origin.x));
2321 srect = [[cw screen] frame];
2322 w->y(int(srect.size.height - (crect.origin.y + w->h())));
2323
2324 int old_event = Fl::e_number;
2325 w->handle(Fl::e_number = FL_SHOW);
2326 Fl::e_number = old_event;
2327
2328 if (w->modal()) { Fl::modal_ = w; fl_fix_focus(); }
2329 }
2330}
2331
2332
2333/*
2334 * Tell the OS what window sizes we want to allow
2335 */
2336void Fl_Window::size_range_() {
2337 int bx, by, bt;
2338 get_window_frame_sizes(bx, by, bt);
2339 size_range_set = 1;
2340 NSSize minSize = { minw, minh + bt };
2341 NSSize maxSize = { maxw?maxw:32000, maxh?maxh + bt:32000 };
2342 if (i && i->xid) {
2343 [(NSWindow*)i->xid setMinSize:minSize];
2344 [(NSWindow*)i->xid setMaxSize:maxSize];
2345 }
2346}
2347
2348
2349/*
2350 * returns pointer to the filename, or null if name ends with ':'
2351 */
2352const char *fl_filename_name( const char *name )
2353{
2354 const char *p, *q;
2355 if (!name) return (0);
2356 for ( p = q = name ; *p ; ) {
2357 if ( ( p[0] == ':' ) && ( p[1] == ':' ) ) {
2358 q = p+2;
2359 p++;
2360 }
2361 else if (p[0] == '/') {
2362 q = p + 1;
2363 }
2364 p++;
2365 }
2366 return q;
2367}
2368
2369
2370/*
2371 * set the window title bar name
2372 */
2373void Fl_Window::label(const char *name, const char *mininame) {
2374 Fl_Widget::label(name);
2375 iconlabel_ = mininame;
2376 if (shown() || i) {
2377 NSWindow* nsw = (NSWindow*)i->xid;
2378 q_set_window_title(nsw, name, mininame);
2379 }
2380}
2381
2382
2383/*
2384 * make a window visible
2385 */
2386void Fl_Window::show() {
2387 image(Fl::scheme_bg_);
2388 if (Fl::scheme_bg_) {
2389 labeltype(FL_NORMAL_LABEL);
2390 align(FL_ALIGN_CENTER | FL_ALIGN_INSIDE | FL_ALIGN_CLIP);
2391 } else {
2392 labeltype(FL_NO_LABEL);
2393 }
2394 Fl_Tooltip::exit(this);
2395 if (!shown() || !i) {
2396 Fl_X::make(this);
2397 } else {
2398 if ( !parent() ) {
2399 if ([(NSWindow*)i->xid isMiniaturized]) {
2400 i->w->redraw();
2401 [(NSWindow*)i->xid deminiaturize:nil];
2402 }
2403 if (!fl_capture) {
2404 [(NSWindow*)i->xid makeKeyAndOrderFront:nil];
2405 }
2406 }
2407 }
2408}
2409
2410
2411/*
2412 * resize a window
2413 */
2414void Fl_Window::resize(int X,int Y,int W,int H) {
2415 if (W<=0) W = 1; // OS X does not like zero width windows
2416 if (H<=0) H = 1;
2417 int is_a_resize = (W != w() || H != h());
2418 // printf("Fl_Window::resize(X=%d, Y=%d, W=%d, H=%d), is_a_resize=%d, resize_from_system=%p, this=%p\n",
2419 // X, Y, W, H, is_a_resize, resize_from_system, this);
2420 if (X != x() || Y != y()) set_flag(FORCE_POSITION);
2421 else if (!is_a_resize) return;
2422 if ( (resize_from_system!=this) && (!parent()) && shown()) {
2423 if (is_a_resize) {
2424 if (resizable()) {
2425 if (W<minw) minw = W; // user request for resize takes priority
2426 if (maxw && W>maxw) maxw = W; // over a previously set size_range
2427 if (H<minh) minh = H;
2428 if (maxh && H>maxh) maxh = H;
2429 size_range(minw, minh, maxw, maxh);
2430 } else {
2431 size_range(W, H, W, H);
2432 }
2433 int bx, by, bt;
2434 if ( ! this->border() ) bt = 0;
2435 else get_window_frame_sizes(bx, by, bt);
2436 NSRect dim;
2437 dim.origin.x = X;
2438 dim.origin.y = [[(NSWindow*)i->xid screen] frame].size.height - (Y + H);
2439 dim.size.width = W;
2440 dim.size.height = H + bt;
2441 [(NSWindow*)i->xid setFrame:dim display:YES];
2442 } else {
2443 NSPoint pt;
2444 pt.x = X;
2445 pt.y = [[(NSWindow*)i->xid screen] frame].size.height - (Y + h());
2446 [(NSWindow*)i->xid setFrameOrigin:pt];
2447 }
2448 }
2449 resize_from_system = 0;
2450 if (is_a_resize) {
2451 Fl_Group::resize(X,Y,W,H);
2452 if (shown()) {
2453 redraw();
2454 }
2455 } else {
2456 x(X); y(Y);
2457 }
2458}
2459
2460
2461/*
2462 * make all drawing go into this window (called by subclass flush() impl.)
2463 */
2464void Fl_Window::make_current()
2465{
2466 Fl_X::q_release_context();
2467 fl_window = i->xid;
2468 current_ = this;
2469
2470 int xp = 0, yp = 0;
2471 Fl_Window *win = this;
2472 while ( win ) {
2473 if ( !win->window() )
2474 break;
2475 xp += win->x();
2476 yp += win->y();
2477 win = (Fl_Window*)win->window();
2478 }
2479
2480 NSView *current_focus = [NSView focusView];
2481 // sometimes current_focus is set to a non-FLTK view: don't touch that
2482 if ( [current_focus isKindOfClass:[FLView class]] ) [current_focus unlockFocus];
2483 [[(NSWindow*)i->xid contentView] lockFocus];
2484 i->gc = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
2485 fl_gc = i->gc;
2486 Fl_Region fl_window_region = XRectangleRegion(0,0,w(),h());
2487 if ( ! this->window() ) {
2488 for ( Fl_X *cx = i->xidChildren; cx; cx = cx->xidNext ) { // clip-out all sub-windows
2489 Fl_Window *cw = cx->w;
2490 Fl_Region from = fl_window_region;
2491 fl_window_region = MacRegionMinusRect(from, cw->x(), cw->y(), cw->w(), cw->h() );
2492 XDestroyRegion(from);
2493 }
2494 }
2495
2496 // antialiasing must be deactivated because it applies to rectangles too
2497 // and escapes even clipping!!!
2498 // it gets activated when needed (e.g., draw text)
2499 CGContextSetShouldAntialias(fl_gc, false);
2500 CGFloat hgt = [[(NSWindow*)fl_window contentView] frame].size.height;
2501 CGContextTranslateCTM(fl_gc, 0.5, hgt-0.5f);
2502 CGContextScaleCTM(fl_gc, 1.0f, -1.0f); // now 0,0 is top-left point of the window
2503 win = this;
2504 while(win && win->window()) { // translate to subwindow origin if this is a subwindow context
2505 CGContextTranslateCTM(fl_gc, win->x(), win->y());
2506 win = win->window();
2507 }
2508 //apply window's clip
2509 CGContextClipToRects(fl_gc, fl_window_region->rects, fl_window_region->count );
2510 XDestroyRegion(fl_window_region);
2511// this is the context with origin at top left of (sub)window clipped out of its subwindows if any
2512 CGContextSaveGState(fl_gc);
2513#if defined(FLTK_USE_CAIRO)
2514 if (Fl::cairo_autolink_context()) Fl::cairo_make_current(this); // capture gc changes automatically to update the cairo context adequately
2515#endif
2516 fl_clip_region( 0 );
2517
2518#if defined(FLTK_USE_CAIRO)
2519 // update the cairo_t context
2520 if (Fl::cairo_autolink_context()) Fl::cairo_make_current(this);
2521#endif
2522}
2523
2524// helper function to manage the current CGContext fl_gc
2525extern void fl_quartz_restore_line_style_();
2526
2527// FLTK has only one global graphics state. This function copies the FLTK state into the
2528// current Quartz context
2529void Fl_X::q_fill_context() {
2530 if (!fl_gc) return;
2531 if ( ! fl_window) { // a bitmap context
2532 size_t hgt = CGBitmapContextGetHeight(fl_gc);
2533 CGContextTranslateCTM(fl_gc, 0.5, hgt-0.5f);
2534 CGContextScaleCTM(fl_gc, 1.0f, -1.0f); // now 0,0 is top-left point of the context
2535 }
2536 fl_color(fl_graphics_driver->color());
2537 fl_quartz_restore_line_style_();
2538}
2539
2540// The only way to reset clipping to its original state is to pop the current graphics
2541// state and restore the global state.
2542void Fl_X::q_clear_clipping() {
2543 if (!fl_gc) return;
2544 CGContextRestoreGState(fl_gc);
2545 CGContextSaveGState(fl_gc);
2546}
2547
2548// Give the Quartz context back to the system
2549void Fl_X::q_release_context(Fl_X *x) {
2550 if (x && x->gc!=fl_gc) return;
2551 if (!fl_gc) return;
2552 CGContextRestoreGState(fl_gc); // matches the CGContextSaveGState of make_current
2553 fl_gc = 0;
2554#if defined(FLTK_USE_CAIRO)
2555 if (Fl::cairo_autolink_context()) Fl::cairo_make_current((Fl_Window*) 0); // capture gc changes automatically to update the cairo context adequately
2556#endif
2557}
2558
2559void Fl_X::q_begin_image(CGRect &rect, int cx, int cy, int w, int h) {
2560 CGContextSaveGState(fl_gc);
2561 CGRect r2 = rect;
2562 r2.origin.x -= 0.5f;
2563 r2.origin.y -= 0.5f;
2564 CGContextClipToRect(fl_gc, r2);
2565 // move graphics context to origin of vertically reversed image
2566 CGContextTranslateCTM(fl_gc, rect.origin.x - cx - 0.5, rect.origin.y - cy + h - 0.5);
2567 CGContextScaleCTM(fl_gc, 1, -1);
2568 rect.origin.x = rect.origin.y = 0;
2569 rect.size.width = w;
2570 rect.size.height = h;
2571}
2572
2573void Fl_X::q_end_image() {
2574 CGContextRestoreGState(fl_gc);
2575}
2576
2577
2578////////////////////////////////////////////////////////////////
2579// Copy & Paste fltk implementation.
2580////////////////////////////////////////////////////////////////
2581
2582static void convert_crlf(char * s, size_t len)
2583{
2584 // turn all \r characters into \n:
2585 for (size_t x = 0; x < len; x++) if (s[x] == '\r') s[x] = '\n';
2586}
2587
2588// fltk 1.3 clipboard support constant definitions:
2589const CFStringRef flavorNames[] = {
2590 CFSTR("public.utf16-plain-text"),
2591 CFSTR("public.utf8-plain-text"),
2592 CFSTR("com.apple.traditional-mac-plain-text") };
2593const CFStringEncoding encodings[] = {
2594 kCFStringEncodingUnicode,
2595 kCFStringEncodingUTF8,
2596 kCFStringEncodingMacRoman};
2597const size_t handledFlavorsCount = sizeof(encodings)/sizeof(CFStringEncoding);
2598
2599// clipboard variables definitions :
2600char *fl_selection_buffer[2];
2601int fl_selection_length[2];
2602static int fl_selection_buffer_length[2];
2603
2604static PasteboardRef myPasteboard = 0;
2605static void allocatePasteboard() {
2606 if (!myPasteboard)
2607 PasteboardCreate(kPasteboardClipboard, &myPasteboard);
2608}
2609
2610
2611/*
2612 * create a selection
2613 * owner: widget that created the selection
2614 * stuff: pointer to selected data
2615 * size of selected data
2616 */
2617void Fl::copy(const char *stuff, int len, int clipboard) {
2618 if (!stuff || len<0) return;
2619 if (len+1 > fl_selection_buffer_length[clipboard]) {
2620 delete[] fl_selection_buffer[clipboard];
2621 fl_selection_buffer[clipboard] = new char[len+100];
2622 fl_selection_buffer_length[clipboard] = len+100;
2623 }
2624 memcpy(fl_selection_buffer[clipboard], stuff, len);
2625 fl_selection_buffer[clipboard][len] = 0; // needed for direct paste
2626 fl_selection_length[clipboard] = len;
2627 if (clipboard) {
2628 allocatePasteboard();
2629 OSStatus err = PasteboardClear(myPasteboard);
2630 if (err!=noErr) return; // clear did not work, maybe not owner of clipboard.
2631 PasteboardSynchronize(myPasteboard);
2632 CFDataRef text = CFDataCreate(kCFAllocatorDefault, (UInt8*)fl_selection_buffer[1], len);
2633 if (text==NULL) return; // there was a pb creating the object, abort.
2634 err=PasteboardPutItemFlavor(myPasteboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), text, 0);
2635 CFRelease(text);
2636 }
2637}
2638
2639// Call this when a "paste" operation happens:
2640void Fl::paste(Fl_Widget &receiver, int clipboard) {
2641 if (clipboard) {
2642 // see if we own the selection, if not go get it:
2643 fl_selection_length[1] = 0;
2644 OSStatus err = noErr;
2645 Boolean found = false;
2646 CFDataRef flavorData = NULL;
2647 CFStringEncoding encoding = 0;
2648
2649 allocatePasteboard();
2650 PasteboardSynchronize(myPasteboard);
2651 ItemCount nFlavor = 0, i, j;
2652 err = PasteboardGetItemCount(myPasteboard, &nFlavor);
2653 if (err==noErr) {
2654 for (i=1; i<=nFlavor; i++) {
2655 PasteboardItemID itemID = 0;
2656 CFArrayRef flavorTypeArray = NULL;
2657 found = false;
2658 err = PasteboardGetItemIdentifier(myPasteboard, i, &itemID);
2659 if (err!=noErr) continue;
2660 err = PasteboardCopyItemFlavors(myPasteboard, itemID, &flavorTypeArray);
2661 if (err!=noErr) {
2662 if (flavorTypeArray) {CFRelease(flavorTypeArray); flavorTypeArray = NULL;}
2663 continue;
2664 }
2665 CFIndex flavorCount = CFArrayGetCount(flavorTypeArray);
2666 for (j = 0; j < handledFlavorsCount; j++) {
2667 for (CFIndex flavorIndex=0; flavorIndex<flavorCount; flavorIndex++) {
2668 CFStringRef flavorType = (CFStringRef)CFArrayGetValueAtIndex(flavorTypeArray, flavorIndex);
2669 if (UTTypeConformsTo(flavorType, flavorNames[j])) {
2670 err = PasteboardCopyItemFlavorData( myPasteboard, itemID, flavorNames[j], &flavorData );
2671 if (err != noErr) continue;
2672 encoding = encodings[j];
2673 found = true;
2674 break;
2675 }
2676 }
2677 if (found) break;
2678 }
2679 if (flavorTypeArray) {CFRelease(flavorTypeArray); flavorTypeArray = NULL;}
2680 if (found) break;
2681 }
2682 if (found) {
2683 CFIndex len = CFDataGetLength(flavorData);
2684 CFStringRef mycfs = CFStringCreateWithBytes(NULL, CFDataGetBytePtr(flavorData), len, encoding, false);
2685 CFRelease(flavorData);
2686 len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(mycfs), kCFStringEncodingUTF8) + 1;
2687 if ( len >= fl_selection_buffer_length[1] ) {
2688 fl_selection_buffer_length[1] = len;
2689 delete[] fl_selection_buffer[1];
2690 fl_selection_buffer[1] = new char[len];
2691 }
2692 CFStringGetCString(mycfs, fl_selection_buffer[1], len, kCFStringEncodingUTF8);
2693 CFRelease(mycfs);
2694 len = strlen(fl_selection_buffer[1]);
2695 fl_selection_length[1] = len;
2696 convert_crlf(fl_selection_buffer[1],len); // turn all \r characters into \n:
2697 }
2698 }
2699 }
2700 Fl::e_text = fl_selection_buffer[clipboard];
2701 Fl::e_length = fl_selection_length[clipboard];
2702 if (!Fl::e_text) Fl::e_text = (char *)"";
2703 receiver.handle(FL_PASTE);
2704}
2705
DRC685f17e2011-07-28 09:23:00 +00002706extern void fl_trigger_clipboard_notify(int source);
2707
2708void fl_clipboard_notify_change() {
2709 // No need to do anything here...
2710}
2711
2712static void clipboard_check(void)
2713{
2714 PasteboardSyncFlags flags;
2715
2716 allocatePasteboard();
2717 flags = PasteboardSynchronize(myPasteboard);
2718
2719 if (!(flags & kPasteboardModified))
2720 return;
2721 if (flags & kPasteboardClientIsOwner)
2722 return;
2723
2724 fl_trigger_clipboard_notify(1);
2725}
2726
DRC2ff39b82011-07-28 08:38:59 +00002727void Fl::add_timeout(double time, Fl_Timeout_Handler cb, void* data)
2728{
2729 // check, if this timer slot exists already
2730 for (int i = 0; i < mac_timer_used; ++i) {
2731 MacTimeout& t = mac_timers[i];
2732 // if so, simply change the fire interval
2733 if (t.callback == cb && t.data == data) {
2734 CFRunLoopTimerSetNextFireDate(t.timer, CFAbsoluteTimeGetCurrent() + time );
2735 t.pending = 1;
2736 return;
2737 }
2738 }
2739 // no existing timer to use. Create a new one:
2740 int timer_id = -1;
2741 // find an empty slot in the timer array
2742 for (int i = 0; i < mac_timer_used; ++i) {
2743 if ( !mac_timers[i].timer ) {
2744 timer_id = i;
2745 break;
2746 }
2747 }
2748 // if there was no empty slot, append a new timer
2749 if (timer_id == -1) {
2750 // make space if needed
2751 if (mac_timer_used == mac_timer_alloc) {
2752 realloc_timers();
2753 }
2754 timer_id = mac_timer_used++;
2755 }
2756 // now install a brand new timer
2757 MacTimeout& t = mac_timers[timer_id];
2758 CFRunLoopTimerContext context = {0, data, NULL,NULL,NULL};
2759 CFRunLoopTimerRef timerRef = CFRunLoopTimerCreate(kCFAllocatorDefault,
2760 CFAbsoluteTimeGetCurrent() + time,
2761 1E30,
2762 0,
2763 0,
2764 do_timer,
2765 &context
2766 );
2767 if (timerRef) {
2768 CFRunLoopAddTimer(CFRunLoopGetCurrent(),
2769 timerRef,
2770 kCFRunLoopDefaultMode);
2771 t.callback = cb;
2772 t.data = data;
2773 t.timer = timerRef;
2774 t.pending = 1;
2775 }
2776}
2777
2778void Fl::repeat_timeout(double time, Fl_Timeout_Handler cb, void* data)
2779{
2780 // currently, repeat_timeout does not subtract the trigger time of the previous timer event as it should.
2781 add_timeout(time, cb, data);
2782}
2783
2784int Fl::has_timeout(Fl_Timeout_Handler cb, void* data)
2785{
2786 for (int i = 0; i < mac_timer_used; ++i) {
2787 MacTimeout& t = mac_timers[i];
2788 if (t.callback == cb && t.data == data && t.pending) {
2789 return 1;
2790 }
2791 }
2792 return 0;
2793}
2794
2795void Fl::remove_timeout(Fl_Timeout_Handler cb, void* data)
2796{
2797 for (int i = 0; i < mac_timer_used; ++i) {
2798 MacTimeout& t = mac_timers[i];
2799 if (t.callback == cb && ( t.data == data || data == NULL)) {
2800 delete_timer(t);
2801 }
2802 }
2803}
2804
2805int Fl_X::unlink(Fl_X *start) {
2806 if (start) {
2807 Fl_X *pc = start;
2808 while (pc) {
2809 if (pc->xidNext == this) {
2810 pc->xidNext = xidNext;
2811 return 1;
2812 }
2813 if (pc->xidChildren) {
2814 if (pc->xidChildren == this) {
2815 pc->xidChildren = xidNext;
2816 return 1;
2817 }
2818 if (unlink(pc->xidChildren))
2819 return 1;
2820 }
2821 pc = pc->xidNext;
2822 }
2823 } else {
2824 for ( Fl_X *pc = Fl_X::first; pc; pc = pc->next ) {
2825 if (unlink(pc))
2826 return 1;
2827 }
2828 }
2829 return 0;
2830}
2831
2832void Fl_X::relink(Fl_Window *w, Fl_Window *wp) {
2833 Fl_X *x = Fl_X::i(w);
2834 Fl_X *p = Fl_X::i(wp);
2835 if (!x || !p) return;
2836 // first, check if 'x' is already registered as a child of 'p'
2837 for (Fl_X *i = p->xidChildren; i; i=i->xidNext) {
2838 if (i == x) return;
2839 }
2840 // now add 'x' as the first child of 'p'
2841 x->xidNext = p->xidChildren;
2842 p->xidChildren = x;
2843}
2844
2845void Fl_X::destroy() {
2846 // subwindows share their xid with their parent window, so should not close it
2847 if (!subwindow && w && !w->parent() && xid) {
2848 [[(NSWindow *)xid contentView] release];
2849 [(NSWindow *)xid close];
2850 }
DRC685f17e2011-07-28 09:23:00 +00002851 if (cursor) {
2852 [(NSCursor*)cursor release];
2853 cursor = NULL;
2854 }
DRC2ff39b82011-07-28 08:38:59 +00002855}
2856
2857void Fl_X::map() {
2858 if (w && xid) {
2859 [(NSWindow *)xid orderFront:nil];
2860 }
2861 //+ link to window list
2862 if (w && w->parent()) {
2863 Fl_X::relink(w, w->window() );
2864 w->redraw();
2865 }
2866}
2867
2868void Fl_X::unmap() {
2869 if (w && !w->parent() && xid) {
2870 [(NSWindow *)xid orderOut:nil];
2871 }
2872 if (w && Fl_X::i(w))
2873 Fl_X::i(w)->unlink();
2874}
2875
2876
2877// removes x,y,w,h rectangle from region r and returns result as a new Fl_Region
2878static Fl_Region MacRegionMinusRect(Fl_Region r, int x,int y,int w,int h)
2879{
2880 Fl_Region outr = (Fl_Region)malloc(sizeof(*outr));
2881 outr->rects = (CGRect*)malloc(4 * r->count * sizeof(CGRect));
2882 outr->count = 0;
2883 CGRect rect = fl_cgrectmake_cocoa(x, y, w, h);
2884 for( int i = 0; i < r->count; i++) {
2885 CGRect A = r->rects[i];
2886 CGRect test = CGRectIntersection(A, rect);
2887 if (CGRectIsEmpty(test)) {
2888 outr->rects[(outr->count)++] = A;
2889 }
2890 else {
2891 const CGFloat verylarge = 100000.;
2892 CGRect side = CGRectMake(0,0,rect.origin.x,verylarge);// W side
2893 test = CGRectIntersection(A, side);
2894 if ( ! CGRectIsEmpty(test)) {
2895 outr->rects[(outr->count)++] = test;
2896 }
2897 side = CGRectMake(0,rect.origin.y + rect.size.height,verylarge,verylarge);// N side
2898 test = CGRectIntersection(A, side);
2899 if ( ! CGRectIsEmpty(test)) {
2900 outr->rects[(outr->count)++] = test;
2901 }
2902 side = CGRectMake(rect.origin.x + rect.size.width, 0, verylarge, verylarge);// E side
2903 test = CGRectIntersection(A, side);
2904 if ( ! CGRectIsEmpty(test)) {
2905 outr->rects[(outr->count)++] = test;
2906 }
2907 side = CGRectMake(0, 0, verylarge, rect.origin.y);// S side
2908 test = CGRectIntersection(A, side);
2909 if ( ! CGRectIsEmpty(test)) {
2910 outr->rects[(outr->count)++] = test;
2911 }
2912 }
2913 }
2914 if (outr->count == 0) {
2915 free(outr->rects);
2916 free(outr);
2917 outr = XRectangleRegion(0,0,0,0);
2918 }
2919 else outr->rects = (CGRect*)realloc(outr->rects, outr->count * sizeof(CGRect));
2920 return outr;
2921}
2922
2923// intersects current and x,y,w,h rectangle and returns result as a new Fl_Region
2924Fl_Region Fl_X::intersect_region_and_rect(Fl_Region current, int x,int y,int w, int h)
2925{
2926 if (current == NULL) return XRectangleRegion(x,y,w,h);
2927 CGRect r = fl_cgrectmake_cocoa(x, y, w, h);
2928 Fl_Region outr = (Fl_Region)malloc(sizeof(*outr));
2929 outr->count = current->count;
2930 outr->rects =(CGRect*)malloc(outr->count * sizeof(CGRect));
2931 int j = 0;
2932 for(int i = 0; i < current->count; i++) {
2933 CGRect test = CGRectIntersection(current->rects[i], r);
2934 if (!CGRectIsEmpty(test)) outr->rects[j++] = test;
2935 }
2936 if (j) {
2937 outr->count = j;
2938 outr->rects = (CGRect*)realloc(outr->rects, outr->count * sizeof(CGRect));
2939 }
2940 else {
2941 XDestroyRegion(outr);
2942 outr = XRectangleRegion(0,0,0,0);
2943 }
2944 return outr;
2945}
2946
2947void Fl_X::collapse() {
2948 [(NSWindow *)xid miniaturize:nil];
2949}
2950
2951static NSImage *CGBitmapContextToNSImage(CGContextRef c)
2952// the returned NSImage is autoreleased
2953{
2954 unsigned char *pdata = (unsigned char *)CGBitmapContextGetData(c);
2955 NSBitmapImageRep *imagerep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&pdata
2956 pixelsWide:CGBitmapContextGetWidth(c)
2957 pixelsHigh:CGBitmapContextGetHeight(c)
2958 bitsPerSample:8
2959 samplesPerPixel:4
2960 hasAlpha:YES
2961 isPlanar:NO
2962 colorSpaceName:NSDeviceRGBColorSpace
2963 bytesPerRow:CGBitmapContextGetBytesPerRow(c)
2964 bitsPerPixel:CGBitmapContextGetBitsPerPixel(c)];
2965 NSImage* image = [[NSImage alloc] initWithData: [imagerep TIFFRepresentation]];
2966 [imagerep release];
2967 return [image autorelease];
2968}
2969
DRC685f17e2011-07-28 09:23:00 +00002970int Fl_X::set_cursor(Fl_Cursor c)
DRC2ff39b82011-07-28 08:38:59 +00002971{
DRC685f17e2011-07-28 09:23:00 +00002972 if (cursor) {
2973 [(NSCursor*)cursor release];
2974 cursor = NULL;
DRC2ff39b82011-07-28 08:38:59 +00002975 }
DRC685f17e2011-07-28 09:23:00 +00002976
2977 switch (c) {
2978 case FL_CURSOR_ARROW: cursor = [NSCursor arrowCursor]; break;
2979 case FL_CURSOR_CROSS: cursor = [NSCursor crosshairCursor]; break;
2980 case FL_CURSOR_INSERT: cursor = [NSCursor IBeamCursor]; break;
2981 case FL_CURSOR_HAND: cursor = [NSCursor pointingHandCursor]; break;
2982 case FL_CURSOR_MOVE: cursor = [NSCursor openHandCursor]; break;
2983 case FL_CURSOR_NS: cursor = [NSCursor resizeUpDownCursor]; break;
2984 case FL_CURSOR_WE: cursor = [NSCursor resizeLeftRightCursor]; break;
2985 case FL_CURSOR_N: cursor = [NSCursor resizeUpCursor]; break;
2986 case FL_CURSOR_E: cursor = [NSCursor resizeRightCursor]; break;
2987 case FL_CURSOR_W: cursor = [NSCursor resizeLeftCursor]; break;
2988 case FL_CURSOR_S: cursor = [NSCursor resizeDownCursor]; break;
2989 default:
2990 return 0;
2991 }
2992
2993 [(NSCursor*)cursor retain];
2994
2995 [(NSWindow*)xid invalidateCursorRectsForView:[(NSWindow*)xid contentView]];
2996
2997 return 1;
DRC2ff39b82011-07-28 08:38:59 +00002998}
2999
DRC685f17e2011-07-28 09:23:00 +00003000int Fl_X::set_cursor(const Fl_RGB_Image *image, int hotx, int hoty) {
3001 if (cursor) {
3002 [(NSCursor*)cursor release];
3003 cursor = NULL;
DRC2ff39b82011-07-28 08:38:59 +00003004 }
DRC685f17e2011-07-28 09:23:00 +00003005
3006 if ((hotx < 0) || (hotx >= image->w()))
3007 return 0;
3008 if ((hoty < 0) || (hoty >= image->h()))
3009 return 0;
3010
3011 // OS X >= 10.6 can create a NSImage from a CGImage, but we need to
3012 // support older versions, hence this pesky handling.
3013
3014 NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
3015 initWithBitmapDataPlanes:NULL
3016 pixelsWide:image->w()
3017 pixelsHigh:image->h()
3018 bitsPerSample:8
3019 samplesPerPixel:image->d()
3020 hasAlpha:!(image->d() & 1)
3021 isPlanar:NO
3022 colorSpaceName:(image->d()<=2) ? NSDeviceWhiteColorSpace : NSDeviceRGBColorSpace
3023 bytesPerRow:(image->w() * image->d())
3024 bitsPerPixel:(image->d()*8)];
3025
3026 // Alpha needs to be premultiplied for this format
3027
3028 const uchar *i = (const uchar*)*image->data();
3029 unsigned char *o = [bitmap bitmapData];
3030 for (int y = 0;y < image->h();y++) {
3031 if (image->d() & 1) {
3032 for (int x = 0;x < image->w();x++) {
3033 unsigned int alpha;
3034 if (image->d() == 4) {
3035 alpha = i[3];
3036 *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
3037 *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
3038 }
3039
3040 alpha = i[1];
3041 *o++ = (unsigned char)((unsigned int)*i++ * alpha / 255);
3042 *o++ = alpha;
3043 i++;
3044 }
3045 } else {
3046 // No alpha, so we can just copy everything directly.
3047 int len = image->w() * image->d();
3048 memcpy(o, i, len);
3049 o += len;
3050 i += len;
3051 }
3052 i += image->ld();
3053 }
3054
3055 NSImage *nsimage = [[NSImage alloc]
3056 initWithSize:NSMakeSize(image->w(), image->h())];
3057
3058 [nsimage addRepresentation:bitmap];
3059
3060 cursor = [[NSCursor alloc]
3061 initWithImage:nsimage
3062 hotSpot:NSMakePoint(hotx, hoty)];
3063
3064 [(NSWindow*)xid invalidateCursorRectsForView:[(NSWindow*)xid contentView]];
3065
3066 [bitmap release];
3067 [nsimage release];
3068
3069 return 1;
DRC2ff39b82011-07-28 08:38:59 +00003070}
3071
3072@interface FLaboutItemTarget : NSObject
3073{
3074}
3075- (void)showPanel;
3076- (void)printPanel;
3077@end
3078@implementation FLaboutItemTarget
3079- (void)showPanel
3080{
3081 NSDictionary *options;
3082 options = [NSDictionary dictionaryWithObjectsAndKeys:
3083 [NSString stringWithFormat:@" GUI with FLTK %d.%d", FL_MAJOR_VERSION,
3084 FL_MINOR_VERSION ], @"Copyright",
3085 nil];
3086 [NSApp orderFrontStandardAboutPanelWithOptions:options];
3087 }
3088//#include <FL/Fl_PostScript.H>
3089- (void)printPanel
3090{
3091 Fl_Printer printer;
3092 //Fl_PostScript_File_Device printer;
3093 int w, h, ww, wh;
3094 Fl_Window *win = Fl::first_window();
3095 if(!win) return;
3096 if( printer.start_job(1) ) return;
3097 if( printer.start_page() ) return;
3098 // scale the printer device so that the window fits on the page
3099 float scale = 1;
3100 printer.printable_rect(&w, &h);
3101 ww = win->decorated_w();
3102 wh = win->decorated_h();
3103 if (ww>w || wh>h) {
3104 scale = (float)w/win->w();
3105 if ((float)h/wh < scale) scale = (float)h/wh;
3106 printer.scale(scale);
3107 }
3108//#define ROTATE 1
3109#ifdef ROTATE
3110 printer.scale(scale * 0.8, scale * 0.8);
3111 printer.printable_rect(&w, &h);
3112 printer.origin(w/2, h/2 );
3113 printer.rotate(20.);
3114 printer.print_widget( win, - win->w()/2, - win->h()/2 );
3115#else
3116 printer.print_window(win);
3117#endif
3118 printer.end_page();
3119 printer.end_job();
3120}
3121@end
3122
3123static void createAppleMenu(void)
3124{
3125 static BOOL donethat = NO;
3126 if (donethat) return;
3127 donethat = YES;
3128 NSMenu *mainmenu, *services, *appleMenu;
3129 NSMenuItem *menuItem;
3130 NSString *title;
3131
3132 NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
3133 if (nsappname == nil)
3134 nsappname = [[NSProcessInfo processInfo] processName];
3135 appleMenu = [[NSMenu alloc] initWithTitle:@""];
3136 /* Add menu items */
3137 title = [[NSString stringWithUTF8String:Fl_Mac_App_Menu::about] stringByAppendingString:nsappname];
3138 menuItem = [appleMenu addItemWithTitle:title action:@selector(showPanel) keyEquivalent:@""];
3139 FLaboutItemTarget *about = [[FLaboutItemTarget alloc] init];
3140 [menuItem setTarget:about];
3141 [appleMenu addItem:[NSMenuItem separatorItem]];
3142 // Print front window
3143 if (strlen(Fl_Mac_App_Menu::print) > 0) {
3144 menuItem = [appleMenu
3145 addItemWithTitle:[NSString stringWithUTF8String:Fl_Mac_App_Menu::print]
3146 action:@selector(printPanel)
3147 keyEquivalent:@""];
3148 [menuItem setTarget:about];
3149 [appleMenu setAutoenablesItems:NO];
3150 [menuItem setEnabled:YES];
3151 [appleMenu addItem:[NSMenuItem separatorItem]];
3152 }
3153 // Services Menu
3154 services = [[NSMenu alloc] init];
3155 menuItem = [appleMenu
3156 addItemWithTitle:[NSString stringWithUTF8String:Fl_Mac_App_Menu::services]
3157 action:nil
3158 keyEquivalent:@""];
3159 [appleMenu setSubmenu:services forItem:menuItem];
3160 [appleMenu addItem:[NSMenuItem separatorItem]];
3161 // Hide AppName
3162 title = [[NSString stringWithUTF8String:Fl_Mac_App_Menu::hide] stringByAppendingString:nsappname];
3163 [appleMenu addItemWithTitle:title
3164 action:@selector(hide:)
3165 keyEquivalent:@"h"];
3166 // Hide Others
3167 menuItem = [appleMenu
3168 addItemWithTitle:[NSString stringWithUTF8String:Fl_Mac_App_Menu::hide_others]
3169 action:@selector(hideOtherApplications:)
3170 keyEquivalent:@"h"];
3171 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
3172 // Show All
3173 [appleMenu addItemWithTitle:[NSString stringWithUTF8String:Fl_Mac_App_Menu::show]
3174 action:@selector(unhideAllApplications:) keyEquivalent:@""];
3175 [appleMenu addItem:[NSMenuItem separatorItem]];
3176 // Quit AppName
3177 title = [[NSString stringWithUTF8String:Fl_Mac_App_Menu::quit]
3178 stringByAppendingString:nsappname];
3179 [appleMenu addItemWithTitle:title
3180 action:@selector(terminate:)
3181 keyEquivalent:@"q"];
3182 /* Put menu into the menubar */
3183 menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
3184 [menuItem setSubmenu:appleMenu];
3185 mainmenu = [[NSMenu alloc] initWithTitle:@""];
3186 [mainmenu addItem:menuItem];
3187 if (fl_mac_os_version < 100600) {
3188 // [NSApp setAppleMenu:appleMenu];
3189 // to avoid compiler warning raised by use of undocumented setAppleMenu :
3190 [NSApp performSelector:@selector(setAppleMenu:) withObject:appleMenu];
3191 }
3192 [NSApp setServicesMenu:services];
3193 [NSApp setMainMenu:mainmenu];
3194 [services release];
3195 [mainmenu release];
3196 [appleMenu release];
3197 [menuItem release];
3198}
3199
3200@interface FLMenuItem : NSMenuItem {
3201}
3202- (void) doCallback:(id)unused;
3203- (void) directCallback:(id)unused;
3204@end
3205@implementation FLMenuItem
3206- (void) doCallback:(id)unused
3207{
3208 int flRank = [self tag];
3209 const Fl_Menu_Item *items = fl_sys_menu_bar->Fl_Menu_::menu();
3210 const Fl_Menu_Item *item = items + flRank;
3211 if (item) {
3212 fl_sys_menu_bar->picked(item);
3213 if ( item->flags & FL_MENU_TOGGLE ) { // update the menu toggle symbol
3214 [self setState:(item->value() ? NSOnState : NSOffState)];
3215 }
3216 else if ( item->flags & FL_MENU_RADIO ) { // update the menu radio symbols
3217 int from = flRank;
3218 while( from > 0 && items[from - 1].label() && (items[from - 1].flags & FL_MENU_RADIO) &&
3219 !(items[from - 1].flags & FL_MENU_DIVIDER) ) {
3220 from--;
3221 }
3222 int to = flRank;
3223 while( !(items[to].flags & FL_MENU_DIVIDER) && items[to + 1].label() &&
3224 (items[to + 1].flags & FL_MENU_RADIO) ) {
3225 to++;
3226 }
3227 NSMenu *nsmenu = [self menu];
3228 int nsrank = (int)[nsmenu indexOfItem:self];
3229 for(int i = from - flRank + nsrank ; i <= to - flRank + nsrank; i++) {
3230 NSMenuItem *nsitem = [nsmenu itemAtIndex:i];
3231 if (nsitem != self) [nsitem setState:NSOffState];
3232 else [nsitem setState:(item->value() ? NSOnState : NSOffState) ];
3233 }
3234 }
3235 }
3236}
3237- (void) directCallback:(id)unused
3238{
3239 Fl_Menu_Item *item = (Fl_Menu_Item *)[(NSData*)[self representedObject] bytes];
3240 if ( item && item->callback() ) item->do_callback(NULL);
3241}
3242@end
3243
3244void fl_mac_set_about( Fl_Callback *cb, void *user_data, int shortcut)
3245{
3246 fl_open_display();
3247 Fl_Menu_Item aboutItem;
3248 memset(&aboutItem, 0, sizeof(Fl_Menu_Item));
3249 aboutItem.callback(cb);
3250 aboutItem.user_data(user_data);
3251 aboutItem.shortcut(shortcut);
3252 NSMenu *appleMenu = [[[NSApp mainMenu] itemAtIndex:0] submenu];
3253 CFStringRef cfname = CFStringCreateCopy(NULL, (CFStringRef)[[appleMenu itemAtIndex:0] title]);
3254 [appleMenu removeItemAtIndex:0];
3255 FLMenuItem *item = [[[FLMenuItem alloc] initWithTitle:(NSString*)cfname
3256 action:@selector(directCallback:)
3257 keyEquivalent:@""] autorelease];
3258 if (aboutItem.shortcut()) {
3259 Fl_Sys_Menu_Bar::doMenuOrItemOperation(Fl_Sys_Menu_Bar::setKeyEquivalent, item, aboutItem.shortcut() & 0xff);
3260 Fl_Sys_Menu_Bar::doMenuOrItemOperation(Fl_Sys_Menu_Bar::setKeyEquivalentModifierMask, item, aboutItem.shortcut() );
3261 }
3262 NSData *pointer = [NSData dataWithBytes:&aboutItem length:sizeof(Fl_Menu_Item)];
3263 [item setRepresentedObject:pointer];
3264 [appleMenu insertItem:item atIndex:0];
3265 CFRelease(cfname);
3266 [item setTarget:item];
3267}
3268
3269static char *remove_ampersand(const char *s)
3270{
3271 char *ret = strdup(s);
3272 const char *p = s;
3273 char *q = ret;
3274 while(*p != 0) {
3275 if (p[0]=='&') {
3276 if (p[1]=='&') {
3277 *q++ = '&'; p+=2;
3278 } else {
3279 p++;
3280 }
3281 } else {
3282 *q++ = *p++;
3283 }
3284 }
3285 *q = 0;
3286 return ret;
3287}
3288
3289void *Fl_Sys_Menu_Bar::doMenuOrItemOperation(Fl_Sys_Menu_Bar::menuOrItemOperation operation, ...)
3290/* these operations apply to menus, submenus, or menu items
3291 */
3292{
3293 NSAutoreleasePool *localPool;
3294 localPool = [[NSAutoreleasePool alloc] init];
3295 NSMenu *menu;
3296 NSMenuItem *item;
3297 int value;
3298 void *pter;
3299 void *retval = NULL;
3300 va_list ap;
3301 va_start(ap, operation);
3302
3303 if (operation == Fl_Sys_Menu_Bar::itemAtIndex) { // arguments: NSMenu*, int. Returns the item
3304 menu = va_arg(ap, NSMenu*);
3305 value = va_arg(ap, int);
3306 retval = (void *)[menu itemAtIndex:value];
3307 }
3308 else if (operation == Fl_Sys_Menu_Bar::setKeyEquivalent) { // arguments: NSMenuItem*, int
3309 item = va_arg(ap, NSMenuItem*);
3310 value = va_arg(ap, int);
3311 char key = value;
3312 NSString *equiv = [[NSString alloc] initWithBytes:&key length:1 encoding:NSASCIIStringEncoding];
3313 [item setKeyEquivalent:equiv];
3314 [equiv release];
3315 }
3316 else if (operation == Fl_Sys_Menu_Bar::setKeyEquivalentModifierMask) { // arguments: NSMenuItem*, int
3317 item = va_arg(ap, NSMenuItem*);
3318 value = va_arg(ap, int);
3319 NSUInteger macMod = 0;
3320 if ( value & FL_META ) macMod = NSCommandKeyMask;
3321 if ( value & FL_SHIFT || isupper(value) ) macMod |= NSShiftKeyMask;
3322 if ( value & FL_ALT ) macMod |= NSAlternateKeyMask;
3323 if ( value & FL_CTRL ) macMod |= NSControlKeyMask;
3324 [item setKeyEquivalentModifierMask:macMod];
3325 }
3326 else if (operation == Fl_Sys_Menu_Bar::setState) { // arguments: NSMenuItem*, int
3327 item = va_arg(ap, NSMenuItem*);
3328 value = va_arg(ap, int);
3329 [item setState:(value ? NSOnState : NSOffState)];
3330 }
3331 else if (operation == Fl_Sys_Menu_Bar::initWithTitle) { // arguments: const char*title. Returns the newly created menu
3332 // creates a new (sub)menu
3333 char *ts = remove_ampersand(va_arg(ap, char *));
3334 CFStringRef title = CFStringCreateWithCString(NULL, ts, kCFStringEncodingUTF8);
3335 free(ts);
3336 NSMenu *menu = [[NSMenu alloc] initWithTitle:(NSString*)title];
3337 CFRelease(title);
3338 [menu setAutoenablesItems:NO];
3339 retval = (void *)menu;
3340 }
3341 else if (operation == Fl_Sys_Menu_Bar::numberOfItems) { // arguments: NSMenu *menu, int *pcount
3342 // upon return, *pcount is set to menu's item count
3343 menu = va_arg(ap, NSMenu*);
3344 pter = va_arg(ap, void *);
3345 *(int*)pter = [menu numberOfItems];
3346 }
3347 else if (operation == Fl_Sys_Menu_Bar::setSubmenu) { // arguments: NSMenuItem *item, NSMenu *menu
3348 // sets 'menu' as submenu attached to 'item'
3349 item = va_arg(ap, NSMenuItem*);
3350 menu = va_arg(ap, NSMenu*);
3351 [item setSubmenu:menu];
3352 [menu release];
3353 }
3354 else if (operation == Fl_Sys_Menu_Bar::setEnabled) { // arguments: NSMenuItem*, int
3355 item = va_arg(ap, NSMenuItem*);
3356 value = va_arg(ap, int);
3357 [item setEnabled:(value ? YES : NO)];
3358 }
3359 else if (operation == Fl_Sys_Menu_Bar::addSeparatorItem) { // arguments: NSMenu*
3360 menu = va_arg(ap, NSMenu*);
3361 [menu addItem:[NSMenuItem separatorItem]];
3362 }
3363 else if (operation == Fl_Sys_Menu_Bar::setTitle) { // arguments: NSMenuItem*, const char *
3364 item = va_arg(ap, NSMenuItem*);
3365 char *ts = remove_ampersand(va_arg(ap, char *));
3366 CFStringRef title = CFStringCreateWithCString(NULL, ts, kCFStringEncodingUTF8);
3367 free(ts);
3368 [item setTitle:(NSString*)title];
3369 CFRelease(title);
3370 }
3371 else if (operation == Fl_Sys_Menu_Bar::removeItem) { // arguments: NSMenu*, int
3372 menu = va_arg(ap, NSMenu*);
3373 value = va_arg(ap, int);
3374 [menu removeItem:[menu itemAtIndex:value]];
3375 }
3376 else if (operation == Fl_Sys_Menu_Bar::addNewItem) { // arguments: NSMenu *menu, int flrank, int *prank
3377 // creates a new menu item at the end of 'menu'
3378 // attaches the item of rank flrank (counted in Fl_Menu_) of fl_sys_menu_bar to it
3379 // upon return, puts the rank (counted in NSMenu) of the new item in *prank unless prank is NULL
3380 menu = va_arg(ap, NSMenu*);
3381 int flRank = va_arg(ap, int);
3382 char *name = remove_ampersand( (fl_sys_menu_bar->Fl_Menu_::menu() + flRank)->label());
3383 int *prank = va_arg(ap, int*);
3384 CFStringRef cfname = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);
3385 free(name);
3386 FLMenuItem *item = [[FLMenuItem alloc] initWithTitle:(NSString*)cfname
3387 action:@selector(doCallback:)
3388 keyEquivalent:@""];
3389 [item setTag:flRank];
3390 [menu addItem:item];
3391 CFRelease(cfname);
3392 [item setTarget:item];
3393 if (prank != NULL) *prank = [menu indexOfItem:item];
3394 [item release];
3395 }
3396 else if (operation == Fl_Sys_Menu_Bar::renameItem) { // arguments: int rank, const char *newname
3397 // renames the system menu item numbered rank in fl_sys_menu_bar->menu()
3398 int rank = va_arg(ap, int);
3399 char *newname = remove_ampersand( va_arg(ap, const char *) );
3400 int countmenus = [[NSApp mainMenu] numberOfItems];
3401 bool found = NO;
3402 NSMenuItem *macitem = 0;
3403 for(int i = 1; (!found) && i < countmenus; i++) {
3404 NSMenuItem *item = [[NSApp mainMenu] itemAtIndex:i];
3405 NSMenu *submenu = [item submenu];
3406 if (submenu == nil) continue;
3407 int countitems = [submenu numberOfItems];
3408 for(int j = 0; j < countitems; j++) {
3409 macitem = [submenu itemAtIndex:j];
3410 if ([macitem tag] == rank) { found = YES; break; }
3411 }
3412 }
3413 if (found) {
3414 [macitem setTitle:[[[NSString alloc] initWithUTF8String:newname] autorelease]];
3415 }
3416 free(newname);
3417 }
3418 va_end(ap);
3419 [localPool release];
3420 return retval;
3421}
3422
3423void Fl_X::set_key_window()
3424{
3425 [(NSWindow*)xid makeKeyWindow];
3426}
3427
3428static NSImage *imageFromText(const char *text, int *pwidth, int *pheight)
3429{
3430 const char *p, *q;
3431 int width = 0, height, w2, ltext = strlen(text);
3432 fl_font(FL_HELVETICA, 10);
3433 p = text;
3434 int nl = 0;
3435 while((q=strchr(p, '\n')) != NULL) {
3436 nl++;
3437 w2 = int(fl_width(p, q - p));
3438 if (w2 > width) width = w2;
3439 p = q + 1;
3440 }
3441 if (text[ ltext - 1] != '\n') {
3442 nl++;
3443 w2 = int(fl_width(p));
3444 if (w2 > width) width = w2;
3445 }
3446 height = nl * fl_height() + 3;
3447 width += 6;
3448 Fl_Offscreen off = fl_create_offscreen_with_alpha(width, height);
3449 fl_begin_offscreen(off);
3450 CGContextSetRGBFillColor( (CGContextRef)off, 0,0,0,0);
3451 fl_rectf(0,0,width,height);
3452 fl_color(FL_BLACK);
3453 p = text;
3454 int y = fl_height();
3455 while(TRUE) {
3456 q = strchr(p, '\n');
3457 if (q) {
3458 fl_draw(p, q - p, 3, y);
3459 } else {
3460 fl_draw(p, 3, y);
3461 break;
3462 }
3463 y += fl_height();
3464 p = q + 1;
3465 }
3466 fl_end_offscreen();
3467 NSImage* image = CGBitmapContextToNSImage( (CGContextRef)off );
3468 fl_delete_offscreen( off );
3469 *pwidth = width;
3470 *pheight = height;
3471 return image;
3472}
3473
3474static NSImage *defaultDragImage(int *pwidth, int *pheight)
3475{
3476 const int width = 16, height = 16;
3477 Fl_Offscreen off = fl_create_offscreen_with_alpha(width, height);
3478 fl_begin_offscreen(off);
3479 CGContextSetRGBFillColor( (CGContextRef)off, 0,0,0,0);
3480 fl_rectf(0,0,width,height);
3481 CGContextSetRGBStrokeColor( (CGContextRef)off, 0,0,0,0.6);
3482 fl_rect(0,0,width,height);
3483 fl_rect(2,2,width-4,height-4);
3484 fl_end_offscreen();
3485 NSImage* image = CGBitmapContextToNSImage( (CGContextRef)off );
3486 fl_delete_offscreen( off );
3487 *pwidth = width;
3488 *pheight = height;
3489 return image;
3490}
3491
3492int Fl::dnd(void)
3493{
3494 CFDataRef text = CFDataCreate(kCFAllocatorDefault, (UInt8*)fl_selection_buffer[0], fl_selection_length[0]);
3495 if (text==NULL) return false;
3496 NSAutoreleasePool *localPool;
3497 localPool = [[NSAutoreleasePool alloc] init];
3498 NSPasteboard *mypasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
3499 [mypasteboard declareTypes:[NSArray arrayWithObjects:@"public.utf8-plain-text", nil] owner:nil];
3500 [mypasteboard setData:(NSData*)text forType:@"public.utf8-plain-text"];
3501 CFRelease(text);
3502 Fl_Widget *w = Fl::pushed();
3503 Fl_Window *win = w->window();
3504 if (win == NULL) {
3505 win = (Fl_Window*)w;
3506 } else {
3507 while(win->window()) win = win->window();
3508 }
3509 NSView *myview = [(NSWindow*)Fl_X::i(win)->xid contentView];
3510 NSEvent *theEvent = [NSApp currentEvent];
3511
3512 int width, height;
3513 NSImage *image;
3514 if ( dynamic_cast<Fl_Input_*>(w) != NULL || dynamic_cast<Fl_Text_Display*>(w) != NULL) {
3515 fl_selection_buffer[0][ fl_selection_length[0] ] = 0;
3516 image = imageFromText(fl_selection_buffer[0], &width, &height);
3517 } else {
3518 image = defaultDragImage(&width, &height);
3519 }
3520
3521 static NSSize offset={0,0};
3522 NSPoint pt = [theEvent locationInWindow];
3523 pt.x -= width/2;
3524 pt.y -= height/2;
3525 [myview dragImage:image at:pt offset:offset
3526 event:theEvent pasteboard:mypasteboard
3527 source:myview slideBack:YES];
3528 if ( w ) {
3529 int old_event = Fl::e_number;
3530 w->handle(Fl::e_number = FL_RELEASE);
3531 Fl::e_number = old_event;
3532 Fl::pushed( 0 );
3533 }
3534 [localPool release];
3535 return true;
3536}
3537
3538unsigned char *Fl_X::bitmap_from_window_rect(Fl_Window *win, int x, int y, int w, int h, int *bytesPerPixel)
3539// delete the returned pointer after use
3540{
3541 while(win->window()) {
3542 x += win->x();
3543 y += win->y();
3544 win = win->window();
3545 }
3546 CGFloat epsilon = 0;
3547 if (fl_mac_os_version >= 100600) epsilon = 0.001;
3548 // The epsilon offset is absolutely necessary under 10.6. Without it, the top pixel row and
3549 // left pixel column are not read, and bitmap is read shifted by one pixel in both directions.
3550 // Under 10.5, we want no offset.
3551 NSRect rect = NSMakeRect(x - epsilon, y - epsilon, w, h);
3552 NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:rect];
3553 *bytesPerPixel = [bitmap bitsPerPixel]/8;
3554 int bpp = (int)[bitmap bytesPerPlane];
3555 int bpr = (int)[bitmap bytesPerRow];
3556 int hh = bpp/bpr; // sometimes hh = h-1 for unclear reason
3557 int ww = bpr/(*bytesPerPixel); // sometimes ww = w-1
3558 unsigned char *data = new unsigned char[w * h * *bytesPerPixel];
3559 if (w == ww) {
3560 memcpy(data, [bitmap bitmapData], w * hh * *bytesPerPixel);
3561 } else {
3562 unsigned char *p = [bitmap bitmapData];
3563 unsigned char *q = data;
3564 for(int i = 0;i < hh; i++) {
3565 memcpy(q, p, *bytesPerPixel * ww);
3566 p += bpr;
3567 q += w * *bytesPerPixel;
3568 }
3569 }
3570 [bitmap release];
3571 return data;
3572}
3573
3574static void imgProviderReleaseData (void *info, const void *data, size_t size)
3575{
3576 delete[] (unsigned char *)data;
3577}
3578
3579CGImageRef Fl_X::CGImage_from_window_rect(Fl_Window *win, int x, int y, int w, int h)
3580// CFRelease the returned CGImageRef after use
3581{
3582 int bpp;
3583 unsigned char *bitmap = bitmap_from_window_rect(win, x, y, w, h, &bpp);
3584 CGImageRef img;
3585 CGColorSpaceRef lut = CGColorSpaceCreateDeviceRGB();
3586 CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmap, w*h*bpp, imgProviderReleaseData);
3587 img = CGImageCreate(w, h, 8, 8*bpp, w*bpp, lut,
3588 bpp == 3 ? kCGImageAlphaNone : kCGImageAlphaLast,
3589 provider, NULL, false, kCGRenderingIntentDefault);
3590 CGColorSpaceRelease(lut);
3591 CGDataProviderRelease(provider);
3592 return img;
3593}
3594
3595WindowRef Fl_X::window_ref()
3596{
3597 return (WindowRef)[(FLWindow*)xid windowRef];
3598}
3599
3600// so a CGRect matches exactly what is denoted x,y,w,h for clipping purposes
3601CGRect fl_cgrectmake_cocoa(int x, int y, int w, int h) {
3602 if (Fl_Surface_Device::surface()->class_name() == Fl_Printer::class_id) return CGRectMake(x-0.5, y-0.5, w, h);
3603 return CGRectMake(x, y, w > 0 ? w - 0.9 : 0, h > 0 ? h - 0.9 : 0);
3604}
3605
3606Window fl_xid(const Fl_Window* w)
3607{
3608 Fl_X *temp = Fl_X::i(w);
3609 return temp ? temp->xid : 0;
3610}
3611
3612int Fl_Window::decorated_w()
3613{
3614 if (!shown() || parent() || !border() || !visible()) return w();
3615 int bx, by, bt;
3616 get_window_frame_sizes(bx, by, bt);
3617 return w() + 2 * bx;
3618}
3619
3620int Fl_Window::decorated_h()
3621{
3622 if (!shown() || parent() || !border() || !visible()) return h();
3623 int bx, by, bt;
3624 get_window_frame_sizes(bx, by, bt);
3625 return h() + bt + by;
3626}
3627
3628void Fl_Paged_Device::print_window(Fl_Window *win, int x_offset, int y_offset)
3629{
3630 if (!win->shown() || win->parent() || !win->border() || !win->visible()) {
3631 this->print_widget(win, x_offset, y_offset);
3632 return;
3633 }
3634 int bx, by, bt;
3635 get_window_frame_sizes(bx, by, bt);
3636 Fl_Display_Device::display_device()->set_current(); // send win to front and make it current
3637 win->show();
3638 fl_gc = NULL;
3639 Fl::check();
3640 win->make_current();
3641 // capture the window title bar from screen
3642 CGImageRef img = Fl_X::CGImage_from_window_rect(win, 0, -bt, win->w(), bt);
3643 this->set_current(); // back to the Fl_Paged_Device
3644 CGRect rect = { { 0, 0 }, { win->w(), bt } }; // print the title bar
3645 Fl_X::q_begin_image(rect, 0, 0, win->w(), bt);
3646 CGContextDrawImage(fl_gc, rect, img);
3647 Fl_X::q_end_image();
3648 CGImageRelease(img);
3649 this->print_widget(win, x_offset, y_offset + bt); // print the window inner part
3650}
3651
3652#include <dlfcn.h>
3653
3654/* Returns the address of a Carbon function after dynamically loading the Carbon library if needed.
3655 Supports old Mac OS X versions that may use a couple of Carbon calls:
3656 GetKeys used by OS X 10.3 or before (in Fl::get_key())
3657 PMSessionPageSetupDialog and PMSessionPrintDialog used by 10.4 or before (in Fl_Printer::start_job())
3658 GetWindowPort used by 10.4 or before (in Fl_Gl_Choice.cxx)
3659 */
3660void *Fl_X::get_carbon_function(const char *function_name) {
3661 static void *carbon = NULL;
3662 void *f = NULL;
3663 if (!carbon) {
3664 carbon = dlopen("/System/Library/Frameworks/Carbon.framework/Carbon", RTLD_LAZY);
3665 }
3666 if (carbon) {
3667 f = dlsym(carbon, function_name);
3668 }
3669 return f;
3670}
3671
3672#endif // __APPLE__
3673
3674//
3675// End of "$Id: Fl_cocoa.mm 8807 2011-06-16 12:35:32Z manolo $".
3676//