fix for python called operators getting/setting the operator last used state, also...
[blender.git] / source / blender / windowmanager / intern / wm_event_system.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/windowmanager/intern/wm_event_system.c
28  *  \ingroup wm
29  */
30
31
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include "DNA_listBase.h"
36 #include "DNA_screen_types.h"
37 #include "DNA_scene_types.h"
38 #include "DNA_windowmanager_types.h"
39 #include "DNA_userdef_types.h"
40
41 #include "MEM_guardedalloc.h"
42
43 #include "GHOST_C-api.h"
44
45 #include "BLI_blenlib.h"
46 #include "BLI_utildefines.h"
47 #include "BLI_math.h"
48
49 #include "BKE_blender.h"
50 #include "BKE_context.h"
51 #include "BKE_idprop.h"
52 #include "BKE_global.h"
53 #include "BKE_main.h"
54 #include "BKE_report.h"
55 #include "BKE_scene.h"
56 #include "BKE_screen.h"
57
58 #include "BKE_sound.h"
59
60 #include "ED_fileselect.h"
61 #include "ED_info.h"
62 #include "ED_render.h"
63 #include "ED_screen.h"
64 #include "ED_view3d.h"
65 #include "ED_util.h"
66
67 #include "RNA_access.h"
68
69 #include "UI_interface.h"
70
71 #include "PIL_time.h"
72
73 #include "WM_api.h"
74 #include "WM_types.h"
75 #include "wm.h"
76 #include "wm_window.h"
77 #include "wm_event_system.h"
78 #include "wm_event_types.h"
79 #include "wm_draw.h"
80
81 #ifndef NDEBUG
82 #  include "RNA_enum_types.h"
83 #endif
84
85 static int wm_operator_call_internal(bContext *C, wmOperatorType *ot, PointerRNA *properties, ReportList *reports,
86                                      short context, short poll_only);
87
88 /* ************ event management ************** */
89
90 void wm_event_add(wmWindow *win, wmEvent *event_to_add)
91 {
92         wmEvent *event= MEM_callocN(sizeof(wmEvent), "wmEvent");
93         
94         *event= *event_to_add;
95         BLI_addtail(&win->queue, event);
96 }
97
98 void wm_event_free(wmEvent *event)
99 {
100         if(event->customdata) {
101                 if(event->customdatafree) {
102                         /* note: pointer to listbase struct elsewhere */
103                         if(event->custom==EVT_DATA_LISTBASE)
104                                 BLI_freelistN(event->customdata);
105                         else
106                                 MEM_freeN(event->customdata);
107                 }
108         }
109         MEM_freeN(event);
110 }
111
112 void wm_event_free_all(wmWindow *win)
113 {
114         wmEvent *event;
115         
116         while((event= win->queue.first)) {
117                 BLI_remlink(&win->queue, event);
118                 wm_event_free(event);
119         }
120 }
121
122 /* ********************* notifiers, listeners *************** */
123
124 static int wm_test_duplicate_notifier(wmWindowManager *wm, unsigned int type, void *reference)
125 {
126         wmNotifier *note;
127
128         for(note=wm->queue.first; note; note=note->next)
129                 if((note->category|note->data|note->subtype|note->action) == type && note->reference == reference)
130                         return 1;
131         
132         return 0;
133 }
134
135 /* XXX: in future, which notifiers to send to other windows? */
136 void WM_event_add_notifier(const bContext *C, unsigned int type, void *reference)
137 {
138         wmNotifier *note= MEM_callocN(sizeof(wmNotifier), "notifier");
139         
140         note->wm= CTX_wm_manager(C);
141         BLI_addtail(&note->wm->queue, note);
142         
143         note->window= CTX_wm_window(C);
144         
145         if(CTX_wm_region(C))
146                 note->swinid= CTX_wm_region(C)->swinid;
147         
148         note->category= type & NOTE_CATEGORY;
149         note->data= type & NOTE_DATA;
150         note->subtype= type & NOTE_SUBTYPE;
151         note->action= type & NOTE_ACTION;
152         
153         note->reference= reference;
154 }
155
156 void WM_main_add_notifier(unsigned int type, void *reference)
157 {
158         Main *bmain= G.main;
159         wmWindowManager *wm= bmain->wm.first;
160
161         if(wm && !wm_test_duplicate_notifier(wm, type, reference)) {
162                 wmNotifier *note= MEM_callocN(sizeof(wmNotifier), "notifier");
163                 
164                 note->wm= wm;
165                 BLI_addtail(&note->wm->queue, note);
166                 
167                 note->category= type & NOTE_CATEGORY;
168                 note->data= type & NOTE_DATA;
169                 note->subtype= type & NOTE_SUBTYPE;
170                 note->action= type & NOTE_ACTION;
171                 
172                 note->reference= reference;
173         }
174 }
175
176 static wmNotifier *wm_notifier_next(wmWindowManager *wm)
177 {
178         wmNotifier *note= wm->queue.first;
179         
180         if(note) BLI_remlink(&wm->queue, note);
181         return note;
182 }
183
184 /* called in mainloop */
185 void wm_event_do_notifiers(bContext *C)
186 {
187         wmWindowManager *wm= CTX_wm_manager(C);
188         wmNotifier *note, *next;
189         wmWindow *win;
190         uint64_t win_combine_v3d_datamask= 0;
191         
192         if(wm==NULL)
193                 return;
194         
195         /* cache & catch WM level notifiers, such as frame change, scene/screen set */
196         for(win= wm->windows.first; win; win= win->next) {
197                 int do_anim= 0;
198                 
199                 CTX_wm_window_set(C, win);
200                 
201                 for(note= wm->queue.first; note; note= next) {
202                         next= note->next;
203
204                         if(note->category==NC_WM) {
205                                 if( ELEM(note->data, ND_FILEREAD, ND_FILESAVE)) {
206                                         wm->file_saved= 1;
207                                         wm_window_title(wm, win);
208                                 }
209                                 else if(note->data==ND_DATACHANGED)
210                                         wm_window_title(wm, win);
211                         }
212                         if(note->window==win) {
213                                 if(note->category==NC_SCREEN) {
214                                         if(note->data==ND_SCREENBROWSE) {
215                                                 ED_screen_set(C, note->reference);      // XXX hrms, think this over!
216                                                 if(G.f & G_DEBUG)
217                                                         printf("screen set %p\n", note->reference);
218                                         }
219                                         else if(note->data==ND_SCREENDELETE) {
220                                                 ED_screen_delete(C, note->reference);   // XXX hrms, think this over!
221                                                 if(G.f & G_DEBUG)
222                                                         printf("screen delete %p\n", note->reference);
223                                         }
224                                 }
225                         }
226
227                         if (note->window == win ||
228                                 (note->window == NULL && (note->reference == NULL || note->reference == CTX_data_scene(C))))
229                         {
230                                 if(note->category==NC_SCENE) {
231                                         if(note->data==ND_FRAME)
232                                                 do_anim= 1;
233                                 }
234                         }
235                         if(ELEM5(note->category, NC_SCENE, NC_OBJECT, NC_GEOM, NC_SCENE, NC_WM)) {
236                                 ED_info_stats_clear(CTX_data_scene(C));
237                                 WM_event_add_notifier(C, NC_SPACE|ND_SPACE_INFO, NULL);
238                         }
239                 }
240                 if(do_anim) {
241
242                         /* XXX, quick frame changes can cause a crash if framechange and rendering
243                          * collide (happens on slow scenes), scene_update_for_newframe can be called
244                          * twice which can depgraph update the same object at once */
245                         if(!G.rendering) {
246
247                                 /* depsgraph gets called, might send more notifiers */
248                                 ED_update_for_newframe(CTX_data_main(C), win->screen->scene, win->screen, 1);
249                         }
250                 }
251         }
252         
253         /* the notifiers are sent without context, to keep it clean */
254         while( (note=wm_notifier_next(wm)) ) {
255                 for(win= wm->windows.first; win; win= win->next) {
256                         
257                         /* filter out notifiers */
258                         if(note->category==NC_SCREEN && note->reference && note->reference!=win->screen);
259                         else if(note->category==NC_SCENE && note->reference && note->reference!=win->screen->scene);
260                         else {
261                                 ScrArea *sa;
262                                 ARegion *ar;
263
264                                 /* XXX context in notifiers? */
265                                 CTX_wm_window_set(C, win);
266
267                                 /* printf("notifier win %d screen %s cat %x\n", win->winid, win->screen->id.name+2, note->category); */
268                                 ED_screen_do_listen(C, note);
269
270                                 for(ar=win->screen->regionbase.first; ar; ar= ar->next) {
271                                         ED_region_do_listen(ar, note);
272                                 }
273                                 
274                                 for(sa= win->screen->areabase.first; sa; sa= sa->next) {
275                                         ED_area_do_listen(sa, note);
276                                         for(ar=sa->regionbase.first; ar; ar= ar->next) {
277                                                 ED_region_do_listen(ar, note);
278                                         }
279                                 }
280                         }
281                 }
282                 
283                 MEM_freeN(note);
284         }
285         
286         /* combine datamasks so 1 win doesn't disable UV's in another [#26448] */
287         for(win= wm->windows.first; win; win= win->next) {
288                 win_combine_v3d_datamask |= ED_view3d_screen_datamask(win->screen);
289         }
290
291         /* cached: editor refresh callbacks now, they get context */
292         for(win= wm->windows.first; win; win= win->next) {
293                 ScrArea *sa;
294                 
295                 CTX_wm_window_set(C, win);
296                 for(sa= win->screen->areabase.first; sa; sa= sa->next) {
297                         if(sa->do_refresh) {
298                                 CTX_wm_area_set(C, sa);
299                                 ED_area_do_refresh(C, sa);
300                         }
301                 }
302                 
303                 /* XXX make lock in future, or separated derivedmesh users in scene */
304                 if(!G.rendering) {
305                         /* depsgraph & animation: update tagged datablocks */
306                         Main *bmain = CTX_data_main(C);
307
308                         /* copied to set's in scene_update_tagged_recursive() */
309                         win->screen->scene->customdata_mask= win_combine_v3d_datamask;
310
311                         /* XXX, hack so operators can enforce datamasks [#26482], gl render */
312                         win->screen->scene->customdata_mask |= win->screen->scene->customdata_mask_modal;
313
314                         scene_update_tagged(bmain, win->screen->scene);
315                 }
316         }
317
318         CTX_wm_window_set(C, NULL);
319 }
320
321 static int wm_event_always_pass(wmEvent *event)
322 {
323         /* some events we always pass on, to ensure proper communication */
324         return ISTIMER(event->type) || (event->type == WINDEACTIVATE);
325 }
326
327 /* ********************* ui handler ******************* */
328
329 static int wm_handler_ui_call(bContext *C, wmEventHandler *handler, wmEvent *event, int always_pass)
330 {
331         ScrArea *area= CTX_wm_area(C);
332         ARegion *region= CTX_wm_region(C);
333         ARegion *menu= CTX_wm_menu(C);
334         static int do_wheel_ui= 1;
335         int is_wheel= ELEM(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE);
336         int retval;
337         
338         /* UI is quite aggressive with swallowing events, like scrollwheel */
339         /* I realize this is not extremely nice code... when UI gets keymaps it can be maybe smarter */
340         if(do_wheel_ui==0) {
341                 if(is_wheel)
342                         return WM_HANDLER_CONTINUE;
343                 else if(wm_event_always_pass(event)==0)
344                         do_wheel_ui= 1;
345         }
346         
347         /* we set context to where ui handler came from */
348         if(handler->ui_area) CTX_wm_area_set(C, handler->ui_area);
349         if(handler->ui_region) CTX_wm_region_set(C, handler->ui_region);
350         if(handler->ui_menu) CTX_wm_menu_set(C, handler->ui_menu);
351
352         retval= handler->ui_handle(C, event, handler->ui_userdata);
353
354         /* putting back screen context */
355         if((retval != WM_UI_HANDLER_BREAK) || always_pass) {
356                 CTX_wm_area_set(C, area);
357                 CTX_wm_region_set(C, region);
358                 CTX_wm_menu_set(C, menu);
359         }
360         else {
361                 /* this special cases is for areas and regions that get removed */
362                 CTX_wm_area_set(C, NULL);
363                 CTX_wm_region_set(C, NULL);
364                 CTX_wm_menu_set(C, NULL);
365         }
366         
367         if(retval == WM_UI_HANDLER_BREAK)
368                 return WM_HANDLER_BREAK;
369         
370         /* event not handled in UI, if wheel then we temporarily disable it */
371         if(is_wheel)
372                 do_wheel_ui= 0;
373         
374         return WM_HANDLER_CONTINUE;
375 }
376
377 static void wm_handler_ui_cancel(bContext *C)
378 {
379         wmWindow *win= CTX_wm_window(C);
380         ARegion *ar= CTX_wm_region(C);
381         wmEventHandler *handler, *nexthandler;
382
383         if(!ar)
384                 return;
385
386         for(handler= ar->handlers.first; handler; handler= nexthandler) {
387                 nexthandler= handler->next;
388
389                 if(handler->ui_handle) {
390                         wmEvent event= *(win->eventstate);
391                         event.type= EVT_BUT_CANCEL;
392                         handler->ui_handle(C, &event, handler->ui_userdata);
393                 }
394         }
395 }
396
397 /* ********************* operators ******************* */
398
399 int WM_operator_poll(bContext *C, wmOperatorType *ot)
400 {
401         wmOperatorTypeMacro *otmacro;
402         
403         for(otmacro= ot->macro.first; otmacro; otmacro= otmacro->next) {
404                 wmOperatorType *ot_macro= WM_operatortype_find(otmacro->idname, 0);
405                 
406                 if(0==WM_operator_poll(C, ot_macro))
407                         return 0;
408         }
409         
410         /* python needs operator type, so we added exception for it */
411         if(ot->pyop_poll)
412                 return ot->pyop_poll(C, ot);
413         else if(ot->poll)
414                 return ot->poll(C);
415
416         return 1;
417 }
418
419 /* sets up the new context and calls 'wm_operator_invoke()' with poll_only */
420 int WM_operator_poll_context(bContext *C, wmOperatorType *ot, int context)
421 {
422         return wm_operator_call_internal(C, ot, NULL, NULL, context, TRUE);
423 }
424
425 static void wm_operator_print(bContext *C, wmOperator *op)
426 {
427         /* context is needed for enum function */
428         char *buf = WM_operator_pystring(C, op->type, op->ptr, 1);
429         printf("%s\n", buf);
430         MEM_freeN(buf);
431 }
432
433 /* for debugging only, getting inspecting events manually is tedious */
434 #ifndef NDEBUG
435
436 void WM_event_print(wmEvent *event)
437 {
438         if(event) {
439                 const char *unknown= "UNKNOWN";
440                 const char *type_id= unknown;
441                 const char *val_id= unknown;
442
443                 RNA_enum_identifier(event_type_items, event->type, &type_id);
444                 RNA_enum_identifier(event_value_items, event->val, &val_id);
445
446                 printf("wmEvent - type:%d/%s, val:%d/%s, "
447                        "shift:%d, ctrl:%d, alt:%d, oskey:%d, keymodifier:%d, "
448                        "mouse:(%d,%d), ascii:'%c', utf8:'%.*s', "
449                        "keymap_idname:%s, pointer:%p\n",
450                        event->type, type_id, event->val, val_id,
451                        event->shift, event->ctrl, event->alt, event->oskey, event->keymodifier,
452                        event->x, event->y, event->ascii,
453                        BLI_str_utf8_size(event->utf8_buf), event->utf8_buf,
454                        event->keymap_idname, (void *)event);
455         }
456         else {
457                 printf("wmEvent - NULL\n");
458         }
459 }
460
461 #endif /* NDEBUG */
462
463 /* (caller_owns_reports == TRUE) when called from python */
464 static void wm_operator_reports(bContext *C, wmOperator *op, int retval, int caller_owns_reports)
465 {
466         if (caller_owns_reports == FALSE) { /* popup */
467                 if(op->reports->list.first) {
468                         /* FIXME, temp setting window, see other call to uiPupMenuReports for why */
469                         wmWindow *win_prev= CTX_wm_window(C);
470                         ScrArea *area_prev= CTX_wm_area(C);
471                         ARegion *ar_prev= CTX_wm_region(C);
472
473                         if(win_prev==NULL)
474                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
475
476                         uiPupMenuReports(C, op->reports);
477
478                         CTX_wm_window_set(C, win_prev);
479                         CTX_wm_area_set(C, area_prev);
480                         CTX_wm_region_set(C, ar_prev);
481                 }
482         }
483         
484         if(retval & OPERATOR_FINISHED) {
485                 if(G.f & G_DEBUG) {
486                         /* todo - this print may double up, might want to check more flags then the FINISHED */
487                         wm_operator_print(C, op);
488                 }
489
490                 if (caller_owns_reports == FALSE) {
491                         BKE_reports_print(op->reports, RPT_DEBUG); /* print out reports to console. */
492                 }
493
494                 if (op->type->flag & OPTYPE_REGISTER) {
495                         if(G.background == 0) { /* ends up printing these in the terminal, gets annoying */
496                                 /* Report the python string representation of the operator */
497                                 char *buf = WM_operator_pystring(C, op->type, op->ptr, 1);
498                                 BKE_report(CTX_wm_reports(C), RPT_OPERATOR, buf);
499                                 MEM_freeN(buf);
500                         }
501                 }
502         }
503
504         /* if the caller owns them, handle this */
505         if (op->reports->list.first && (op->reports->flag & RPT_OP_HOLD) == 0) {
506
507                 wmWindowManager *wm = CTX_wm_manager(C);
508                 ReportList *wm_reports= CTX_wm_reports(C);
509                 ReportTimerInfo *rti;
510
511                 /* add reports to the global list, otherwise they are not seen */
512                 BLI_movelisttolist(&wm_reports->list, &op->reports->list);
513                 
514                 /* After adding reports to the global list, reset the report timer. */
515                 WM_event_remove_timer(wm, NULL, wm_reports->reporttimer);
516                 
517                 /* Records time since last report was added */
518                 wm_reports->reporttimer= WM_event_add_timer(wm, CTX_wm_window(C), TIMERREPORT, 0.05);
519                 
520                 rti = MEM_callocN(sizeof(ReportTimerInfo), "ReportTimerInfo");
521                 wm_reports->reporttimer->customdata = rti;
522         }
523 }
524
525 /* this function is mainly to check that the rules for freeing
526  * an operator are kept in sync.
527  */
528 static int wm_operator_register_check(wmWindowManager *wm, wmOperatorType *ot)
529 {
530         return wm && (wm->op_undo_depth == 0) && (ot->flag & OPTYPE_REGISTER);
531 }
532
533 static void wm_operator_finished(bContext *C, wmOperator *op, int repeat)
534 {
535         wmWindowManager *wm= CTX_wm_manager(C);
536
537         op->customdata= NULL;
538
539         /* we don't want to do undo pushes for operators that are being
540          * called from operators that already do an undo push. usually
541          * this will happen for python operators that call C operators */
542         if(wm->op_undo_depth == 0)
543                 if(op->type->flag & OPTYPE_UNDO)
544                         ED_undo_push_op(C, op);
545         
546         if(repeat==0) {
547                 if(G.f & G_DEBUG) {
548                         char *buf = WM_operator_pystring(C, op->type, op->ptr, 1);
549                         BKE_report(CTX_wm_reports(C), RPT_OPERATOR, buf);
550                         MEM_freeN(buf);
551                 }
552
553                 if(wm_operator_register_check(wm, op->type))
554                         wm_operator_register(C, op);
555                 else
556                         WM_operator_free(op);
557         }
558 }
559
560 /* if repeat is true, it doesn't register again, nor does it free */
561 static int wm_operator_exec(bContext *C, wmOperator *op, int repeat)
562 {
563         wmWindowManager *wm= CTX_wm_manager(C);
564         int retval= OPERATOR_CANCELLED;
565         
566         CTX_wm_operator_poll_msg_set(C, NULL);
567         
568         if(op==NULL || op->type==NULL)
569                 return retval;
570         
571         if(0==WM_operator_poll(C, op->type))
572                 return retval;
573         
574         if(op->type->exec) {
575                 if(op->type->flag & OPTYPE_UNDO)
576                         wm->op_undo_depth++;
577
578                 retval= op->type->exec(C, op);
579                 OPERATOR_RETVAL_CHECK(retval);
580
581                 if(op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
582                         wm->op_undo_depth--;
583         }
584         
585         if (retval & (OPERATOR_FINISHED|OPERATOR_CANCELLED) && repeat == 0)
586                 wm_operator_reports(C, op, retval, FALSE);
587         
588         if(retval & OPERATOR_FINISHED) {
589                 if (repeat) {
590                         if (wm->op_undo_depth == 0) { /* not called by py script */
591                                 WM_operator_last_properties_store(op);
592                         }
593                 }
594                 wm_operator_finished(C, op, repeat);
595         }
596         else if(repeat==0) {
597                 WM_operator_free(op);
598         }
599         
600         return retval | OPERATOR_HANDLED;
601         
602 }
603
604 /* simply calls exec with basic checks */
605 static int wm_operator_exec_notest(bContext *C, wmOperator *op)
606 {
607         int retval= OPERATOR_CANCELLED;
608
609         if(op==NULL || op->type==NULL || op->type->exec==NULL)
610                 return retval;
611
612         retval= op->type->exec(C, op);
613         OPERATOR_RETVAL_CHECK(retval);
614
615         return retval;
616 }
617
618 /* for running operators with frozen context (modal handlers, menus)
619  *
620  * warning: do not use this within an operator to call its self! [#29537] */
621 int WM_operator_call(bContext *C, wmOperator *op)
622 {
623         return wm_operator_exec(C, op, 0);
624 }
625
626 /* this is intended to be used when an invoke operator wants to call exec on its self
627  * and is basically like running op->type->exec() directly, no poll checks no freeing,
628  * since we assume whoever called invokle will take care of that */
629 int WM_operator_call_notest(bContext *C, wmOperator *op)
630 {
631         return wm_operator_exec_notest(C, op);
632 }
633
634 /* do this operator again, put here so it can share above code */
635 int WM_operator_repeat(bContext *C, wmOperator *op)
636 {
637         return wm_operator_exec(C, op, 1);
638 }
639 /* TRUE if WM_operator_repeat can run
640  * simple check for now but may become more involved.
641  * To be sure the operator can run call WM_operator_poll(C, op->type) also, since this call
642  * checks if WM_operator_repeat() can run at all, not that it WILL run at any time. */
643 int WM_operator_repeat_check(const bContext *UNUSED(C), wmOperator *op)
644 {
645         return op->type->exec != NULL;
646 }
647
648 static wmOperator *wm_operator_create(wmWindowManager *wm, wmOperatorType *ot, PointerRNA *properties, ReportList *reports)
649 {
650         /* XXX operatortype names are static still. for debug */
651         wmOperator *op= MEM_callocN(sizeof(wmOperator), ot->idname);
652         
653         /* XXX adding new operator could be function, only happens here now */
654         op->type= ot;
655         BLI_strncpy(op->idname, ot->idname, OP_MAX_TYPENAME);
656         
657         /* initialize properties, either copy or create */
658         op->ptr= MEM_callocN(sizeof(PointerRNA), "wmOperatorPtrRNA");
659         if(properties && properties->data) {
660                 op->properties= IDP_CopyProperty(properties->data);
661         }
662         else {
663                 IDPropertyTemplate val = {0};
664                 op->properties= IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
665         }
666         RNA_pointer_create(&wm->id, ot->srna, op->properties, op->ptr);
667
668         /* initialize error reports */
669         if (reports) {
670                 op->reports= reports; /* must be initialized already */
671         }
672         else {
673                 op->reports= MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
674                 BKE_reports_init(op->reports, RPT_STORE|RPT_FREE);
675         }
676         
677         /* recursive filling of operator macro list */
678         if(ot->macro.first) {
679                 static wmOperator *motherop= NULL;
680                 wmOperatorTypeMacro *otmacro;
681                 int root = 0;
682                 
683                 /* ensure all ops are in execution order in 1 list */
684                 if(motherop==NULL) {
685                         motherop = op;
686                         root = 1;
687                 }
688
689                 
690                 /* if properties exist, it will contain everything needed */
691                 if (properties) {
692                         otmacro= ot->macro.first;
693
694                         RNA_STRUCT_BEGIN(properties, prop) {
695
696                                 if (otmacro == NULL)
697                                         break;
698
699                                 /* skip invalid properties */
700                                 if (strcmp(RNA_property_identifier(prop), otmacro->idname) == 0) {
701                                         wmOperatorType *otm= WM_operatortype_find(otmacro->idname, 0);
702                                         PointerRNA someptr = RNA_property_pointer_get(properties, prop);
703                                         wmOperator *opm= wm_operator_create(wm, otm, &someptr, NULL);
704
705                                         IDP_ReplaceGroupInGroup(opm->properties, otmacro->properties);
706
707                                         BLI_addtail(&motherop->macro, opm);
708                                         opm->opm= motherop; /* pointer to mom, for modal() */
709
710                                         otmacro= otmacro->next;
711                                 }
712                         }
713                         RNA_STRUCT_END;
714                 } else {
715                         for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) {
716                                 wmOperatorType *otm= WM_operatortype_find(otmacro->idname, 0);
717                                 wmOperator *opm= wm_operator_create(wm, otm, otmacro->ptr, NULL);
718
719                                 BLI_addtail(&motherop->macro, opm);
720                                 opm->opm= motherop; /* pointer to mom, for modal() */
721                         }
722                 }
723                 
724                 if (root)
725                         motherop= NULL;
726         }
727         
728         WM_operator_properties_sanitize(op->ptr, 0);
729
730         return op;
731 }
732
733 static void wm_region_mouse_co(bContext *C, wmEvent *event)
734 {
735         ARegion *ar= CTX_wm_region(C);
736         if(ar) {
737                 /* compatibility convention */
738                 event->mval[0]= event->x - ar->winrct.xmin;
739                 event->mval[1]= event->y - ar->winrct.ymin;
740         }
741         else {
742                 /* these values are invalid (avoid odd behavior by relying on old mval values) */
743                 event->mval[0]= -1;
744                 event->mval[1]= -1;
745         }
746 }
747
748 int WM_operator_last_properties_init(wmOperator *op)
749 {
750         int change= FALSE;
751
752         if (op->type->last_properties) {
753                 PropertyRNA *iterprop;
754
755                 if (G.f & G_DEBUG) printf("%s: loading previous properties for '%s'\n", __func__, op->type->idname);
756
757                 iterprop = RNA_struct_iterator_property(op->type->srna);
758
759                 RNA_PROP_BEGIN(op->ptr, itemptr, iterprop) {
760                         PropertyRNA *prop= itemptr.data;
761                         if((RNA_property_flag(prop) & PROP_SKIP_SAVE) == 0) {
762                                 if (!RNA_property_is_set(op->ptr, prop)) { /* don't override a setting already set */
763                                         const char *identifier= RNA_property_identifier(prop);
764                                         IDProperty *idp_src= IDP_GetPropertyFromGroup(op->type->last_properties, identifier);
765                                         if(idp_src) {
766                                                 IDProperty *idp_dst = IDP_CopyProperty(idp_src);
767
768                                                 /* note - in the future this may need to be done recursively,
769                                                  * but for now RNA doesn't access nested operators */
770                                                 idp_dst->flag |= IDP_FLAG_GHOST;
771
772                                                 IDP_ReplaceInGroup(op->properties, idp_dst);
773                                                 change= TRUE;
774                                         }
775                                 }
776                         }
777                 }
778                 RNA_PROP_END;
779         }
780
781         return change;
782 }
783
784 int WM_operator_last_properties_store(wmOperator *op)
785 {
786         if (op->type->last_properties) {
787                 IDP_FreeProperty(op->type->last_properties);
788                 MEM_freeN(op->type->last_properties);
789                 op->type->last_properties = NULL;
790         }
791
792         if (op->properties) {
793                 if (G.f & G_DEBUG) printf("%s: storing properties for '%s'\n", __func__, op->type->idname);
794                 op->type->last_properties = IDP_CopyProperty(op->properties);
795                 return TRUE;
796         }
797         else {
798                 return FALSE;
799         }
800 }
801
802 static int wm_operator_invoke(bContext *C, wmOperatorType *ot, wmEvent *event, PointerRNA *properties, ReportList *reports, short poll_only)
803 {
804         wmWindowManager *wm= CTX_wm_manager(C);
805         int retval= OPERATOR_PASS_THROUGH;
806
807         /* this is done because complicated setup is done to call this function that is better not duplicated */
808         if(poll_only)
809                 return WM_operator_poll(C, ot);
810
811         if(WM_operator_poll(C, ot)) {
812                 wmOperator *op= wm_operator_create(wm, ot, properties, reports); /* if reports==NULL, theyll be initialized */
813                 const short is_nested_call = (wm->op_undo_depth != 0);
814                 
815                 /* initialize setting from previous run */
816                 if(!is_nested_call) { /* not called by py script */
817                         WM_operator_last_properties_init(op);
818                 }
819
820                 if((G.f & G_DEBUG) && event && event->type!=MOUSEMOVE)
821                         printf("handle evt %d win %d op %s\n", event?event->type:0, CTX_wm_screen(C)->subwinactive, ot->idname); 
822                 
823                 if(op->type->invoke && event) {
824                         wm_region_mouse_co(C, event);
825
826                         if(op->type->flag & OPTYPE_UNDO)
827                                 wm->op_undo_depth++;
828
829                         retval= op->type->invoke(C, op, event);
830                         OPERATOR_RETVAL_CHECK(retval);
831
832                         if(op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
833                                 wm->op_undo_depth--;
834                 }
835                 else if(op->type->exec) {
836                         if(op->type->flag & OPTYPE_UNDO)
837                                 wm->op_undo_depth++;
838
839                         retval= op->type->exec(C, op);
840                         OPERATOR_RETVAL_CHECK(retval);
841
842                         if(op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
843                                 wm->op_undo_depth--;
844                 }
845                 else {
846                         /* debug, important to leave a while, should never happen */
847                         printf("invalid operator call '%s'\n", ot->idname);
848                 }
849                 
850                 /* Note, if the report is given as an argument then assume the caller will deal with displaying them
851                  * currently python only uses this */
852                 if (!(retval & OPERATOR_HANDLED) && (retval & (OPERATOR_FINISHED|OPERATOR_CANCELLED))) {
853                         /* only show the report if the report list was not given in the function */
854                         wm_operator_reports(C, op, retval, (reports != NULL));
855                 }
856
857                 if(retval & OPERATOR_HANDLED)
858                         ; /* do nothing, wm_operator_exec() has been called somewhere */
859                 else if(retval & OPERATOR_FINISHED) {
860                         if (!is_nested_call) { /* not called by py script */
861                                 WM_operator_last_properties_store(op);
862                         }
863                         wm_operator_finished(C, op, 0);
864                 }
865                 else if(retval & OPERATOR_RUNNING_MODAL) {
866                         /* grab cursor during blocking modal ops (X11)
867                          * Also check for macro
868                          */
869                         if(ot->flag & OPTYPE_BLOCKING || (op->opm && op->opm->type->flag & OPTYPE_BLOCKING)) {
870                                 int bounds[4] = {-1,-1,-1,-1};
871                                 int wrap;
872
873                                 if (op->opm) {
874                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
875                                                ((op->opm->flag & OP_GRAB_POINTER) || (op->opm->type->flag & OPTYPE_GRAB_POINTER));
876                                 }
877                                 else {
878                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
879                                                ((op->flag & OP_GRAB_POINTER) || (ot->flag & OPTYPE_GRAB_POINTER));
880                                 }
881
882                                 /* exception, cont. grab in header is annoying */
883                                 if(wrap) {
884                                         ARegion *ar= CTX_wm_region(C);
885                                         if(ar && ar->regiontype == RGN_TYPE_HEADER) {
886                                                 wrap= FALSE;
887                                         }
888                                 }
889
890                                 if(wrap) {
891                                         rcti *winrect= NULL;
892                                         ARegion *ar= CTX_wm_region(C);
893                                         ScrArea *sa= CTX_wm_area(C);
894
895                                         if (ar && ar->regiontype == RGN_TYPE_WINDOW && event &&
896                                             BLI_in_rcti(&ar->winrct, event->x, event->y))
897                                         {
898                                                 winrect= &ar->winrct;
899                                         }
900                                         else if(sa) {
901                                                 winrect= &sa->totrct;
902                                         }
903
904                                         if(winrect) {
905                                                 bounds[0]= winrect->xmin;
906                                                 bounds[1]= winrect->ymax;
907                                                 bounds[2]= winrect->xmax;
908                                                 bounds[3]= winrect->ymin;
909                                         }
910                                 }
911
912                                 WM_cursor_grab(CTX_wm_window(C), wrap, FALSE, bounds);
913                         }
914
915                         /* cancel UI handlers, typically tooltips that can hang around
916                          * while dragging the view or worse, that stay there permanently
917                          * after the modal operator has swallowed all events and passed
918                          * none to the UI handler */
919                         wm_handler_ui_cancel(C);
920                 }
921                 else
922                         WM_operator_free(op);
923         }
924
925         return retval;
926 }
927
928 /* WM_operator_name_call is the main accessor function
929  * this is for python to access since its done the operator lookup
930  * 
931  * invokes operator in context */
932 static int wm_operator_call_internal(bContext *C, wmOperatorType *ot, PointerRNA *properties, ReportList *reports,
933                                      short context, short poll_only)
934 {
935         wmWindow *window= CTX_wm_window(C);
936         wmEvent *event;
937         
938         int retval;
939
940         CTX_wm_operator_poll_msg_set(C, NULL);
941
942         /* dummie test */
943         if(ot && C) {
944                 switch(context) {
945                         case WM_OP_INVOKE_DEFAULT:
946                         case WM_OP_INVOKE_REGION_WIN:
947                         case WM_OP_INVOKE_AREA:
948                         case WM_OP_INVOKE_SCREEN:
949                                 /* window is needed for invoke, cancel operator */
950                                 if (window == NULL)
951                                         return 0;
952                                 else
953                                         event= window->eventstate;
954                                 break;
955                         default:
956                                 event = NULL;
957                 }
958
959                 switch(context) {
960                         
961                         case WM_OP_EXEC_REGION_WIN:
962                         case WM_OP_INVOKE_REGION_WIN: 
963                         case WM_OP_EXEC_REGION_CHANNELS:
964                         case WM_OP_INVOKE_REGION_CHANNELS:
965                         case WM_OP_EXEC_REGION_PREVIEW:
966                         case WM_OP_INVOKE_REGION_PREVIEW:
967                         {
968                                 /* forces operator to go to the region window/channels/preview, for header menus
969                                  * but we stay in the same region if we are already in one 
970                                  */
971                                 ARegion *ar= CTX_wm_region(C);
972                                 ScrArea *area= CTX_wm_area(C);
973                                 int type = RGN_TYPE_WINDOW;
974                                 
975                                 switch (context) {
976                                         case WM_OP_EXEC_REGION_CHANNELS:
977                                         case WM_OP_INVOKE_REGION_CHANNELS:
978                                                 type = RGN_TYPE_CHANNELS;
979                                                 break;
980                                         
981                                         case WM_OP_EXEC_REGION_PREVIEW:
982                                         case WM_OP_INVOKE_REGION_PREVIEW:
983                                                 type = RGN_TYPE_PREVIEW;
984                                                 break;
985                                         
986                                         case WM_OP_EXEC_REGION_WIN:
987                                         case WM_OP_INVOKE_REGION_WIN: 
988                                         default:
989                                                 type = RGN_TYPE_WINDOW;
990                                                 break;
991                                 }
992                                 
993                                 if(!(ar && ar->regiontype == type) && area) {
994                                         ARegion *ar1= BKE_area_find_region_type(area, type);
995                                         if(ar1)
996                                                 CTX_wm_region_set(C, ar1);
997                                 }
998                                 
999                                 retval= wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1000                                 
1001                                 /* set region back */
1002                                 CTX_wm_region_set(C, ar);
1003                                 
1004                                 return retval;
1005                         }
1006                         case WM_OP_EXEC_AREA:
1007                         case WM_OP_INVOKE_AREA:
1008                         {
1009                                         /* remove region from context */
1010                                 ARegion *ar= CTX_wm_region(C);
1011
1012                                 CTX_wm_region_set(C, NULL);
1013                                 retval= wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1014                                 CTX_wm_region_set(C, ar);
1015
1016                                 return retval;
1017                         }
1018                         case WM_OP_EXEC_SCREEN:
1019                         case WM_OP_INVOKE_SCREEN:
1020                         {
1021                                 /* remove region + area from context */
1022                                 ARegion *ar= CTX_wm_region(C);
1023                                 ScrArea *area= CTX_wm_area(C);
1024
1025                                 CTX_wm_region_set(C, NULL);
1026                                 CTX_wm_area_set(C, NULL);
1027                                 retval= wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1028                                 CTX_wm_area_set(C, area);
1029                                 CTX_wm_region_set(C, ar);
1030
1031                                 return retval;
1032                         }
1033                         case WM_OP_EXEC_DEFAULT:
1034                         case WM_OP_INVOKE_DEFAULT:
1035                                 return wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1036                 }
1037         }
1038         
1039         return 0;
1040 }
1041
1042
1043 /* invokes operator in context */
1044 int WM_operator_name_call(bContext *C, const char *opstring, int context, PointerRNA *properties)
1045 {
1046         wmOperatorType *ot= WM_operatortype_find(opstring, 0);
1047         if(ot)
1048                 return wm_operator_call_internal(C, ot, properties, NULL, context, FALSE);
1049
1050         return 0;
1051 }
1052
1053 /* Similar to WM_operator_name_call called with WM_OP_EXEC_DEFAULT context.
1054  * - wmOperatorType is used instead of operator name since python already has the operator type
1055  * - poll() must be called by python before this runs.
1056  * - reports can be passed to this function (so python can report them as exceptions)
1057  */
1058 int WM_operator_call_py(bContext *C, wmOperatorType *ot, int context, PointerRNA *properties, ReportList *reports)
1059 {
1060         int retval= OPERATOR_CANCELLED;
1061
1062 #if 0
1063         wmOperator *op;
1064         op= wm_operator_create(wm, ot, properties, reports);
1065
1066         if (op->type->exec) {
1067                 if(op->type->flag & OPTYPE_UNDO)
1068                         wm->op_undo_depth++;
1069
1070                 retval= op->type->exec(C, op);
1071                 OPERATOR_RETVAL_CHECK(retval);
1072
1073                 if(op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1074                         wm->op_undo_depth--;
1075         }
1076         else
1077                 printf("error \"%s\" operator has no exec function, python cannot call it\n", op->type->name);
1078 #endif
1079
1080         /* not especially nice using undo depth here, its used so py never
1081          * triggers undo or stores operators last used state.
1082          *
1083          * we could have some more obvious way of doing this like passing a flag.
1084          */
1085         wmWindowManager *wm = CTX_wm_manager(C);
1086         if (wm) wm->op_undo_depth++;
1087
1088         retval = wm_operator_call_internal(C, ot, properties, reports, context, FALSE);
1089         
1090         if (wm == CTX_wm_manager(C)) wm->op_undo_depth--;
1091
1092         /* keep the reports around if needed later */
1093         if (    (retval & OPERATOR_RUNNING_MODAL) ||
1094                         ((retval & OPERATOR_FINISHED) && wm_operator_register_check(CTX_wm_manager(C), ot))
1095         ) {
1096                 reports->flag |= RPT_FREE; /* let blender manage freeing */
1097         }
1098         
1099         return retval;
1100 }
1101
1102
1103 /* ********************* handlers *************** */
1104
1105 /* future extra customadata free? */
1106 void wm_event_free_handler(wmEventHandler *handler)
1107 {
1108         MEM_freeN(handler);
1109 }
1110
1111 /* only set context when area/region is part of screen */
1112 static void wm_handler_op_context(bContext *C, wmEventHandler *handler)
1113 {
1114         bScreen *screen= CTX_wm_screen(C);
1115         
1116         if(screen && handler->op) {
1117                 if(handler->op_area==NULL)
1118                         CTX_wm_area_set(C, NULL);
1119                 else {
1120                         ScrArea *sa;
1121                         
1122                         for(sa= screen->areabase.first; sa; sa= sa->next)
1123                                 if(sa==handler->op_area)
1124                                         break;
1125                         if(sa==NULL) {
1126                                 /* when changing screen layouts with running modal handlers (like render display), this
1127                                  * is not an error to print */
1128                                 if(handler->op==NULL)
1129                                         printf("internal error: handler (%s) has invalid area\n", handler->op->type->idname);
1130                         }
1131                         else {
1132                                 ARegion *ar;
1133                                 CTX_wm_area_set(C, sa);
1134                                 for(ar= sa->regionbase.first; ar; ar= ar->next)
1135                                         if(ar==handler->op_region)
1136                                                 break;
1137                                 /* XXX no warning print here, after full-area and back regions are remade */
1138                                 if(ar)
1139                                         CTX_wm_region_set(C, ar);
1140                         }
1141                 }
1142         }
1143 }
1144
1145 /* called on exit or remove area, only here call cancel callback */
1146 void WM_event_remove_handlers(bContext *C, ListBase *handlers)
1147 {
1148         wmEventHandler *handler;
1149         wmWindowManager *wm= CTX_wm_manager(C);
1150         
1151         /* C is zero on freeing database, modal handlers then already were freed */
1152         while((handler=handlers->first)) {
1153                 BLI_remlink(handlers, handler);
1154                 
1155                 if(handler->op) {
1156                         if(handler->op->type->cancel) {
1157                                 ScrArea *area= CTX_wm_area(C);
1158                                 ARegion *region= CTX_wm_region(C);
1159                                 
1160                                 wm_handler_op_context(C, handler);
1161
1162                                 if(handler->op->type->flag & OPTYPE_UNDO)
1163                                         wm->op_undo_depth++;
1164
1165                                 handler->op->type->cancel(C, handler->op);
1166
1167                                 if(handler->op->type->flag & OPTYPE_UNDO)
1168                                         wm->op_undo_depth--;
1169
1170                                 CTX_wm_area_set(C, area);
1171                                 CTX_wm_region_set(C, region);
1172                         }
1173
1174                         WM_cursor_ungrab(CTX_wm_window(C));
1175                         WM_operator_free(handler->op);
1176                 }
1177                 else if(handler->ui_remove) {
1178                         ScrArea *area= CTX_wm_area(C);
1179                         ARegion *region= CTX_wm_region(C);
1180                         ARegion *menu= CTX_wm_menu(C);
1181                         
1182                         if(handler->ui_area) CTX_wm_area_set(C, handler->ui_area);
1183                         if(handler->ui_region) CTX_wm_region_set(C, handler->ui_region);
1184                         if(handler->ui_menu) CTX_wm_menu_set(C, handler->ui_menu);
1185
1186                         handler->ui_remove(C, handler->ui_userdata);
1187
1188                         CTX_wm_area_set(C, area);
1189                         CTX_wm_region_set(C, region);
1190                         CTX_wm_menu_set(C, menu);
1191                 }
1192
1193                 wm_event_free_handler(handler);
1194         }
1195 }
1196
1197 /* do userdef mappings */
1198 int WM_userdef_event_map(int kmitype)
1199 {
1200         switch(kmitype) {
1201                 case SELECTMOUSE:
1202                         if(U.flag & USER_LMOUSESELECT)
1203                                 return LEFTMOUSE;
1204                         else
1205                                 return RIGHTMOUSE;
1206                         
1207                 case ACTIONMOUSE:
1208                         if(U.flag & USER_LMOUSESELECT)
1209                                 return RIGHTMOUSE;
1210                         else
1211                                 return LEFTMOUSE;
1212                         
1213                 case WHEELOUTMOUSE:
1214                         if(U.uiflag & USER_WHEELZOOMDIR)
1215                                 return WHEELUPMOUSE;
1216                         else
1217                                 return WHEELDOWNMOUSE;
1218                         
1219                 case WHEELINMOUSE:
1220                         if(U.uiflag & USER_WHEELZOOMDIR)
1221                                 return WHEELDOWNMOUSE;
1222                         else
1223                                 return WHEELUPMOUSE;
1224                         
1225                 case EVT_TWEAK_A:
1226                         if(U.flag & USER_LMOUSESELECT)
1227                                 return EVT_TWEAK_R;
1228                         else
1229                                 return EVT_TWEAK_L;
1230                         
1231                 case EVT_TWEAK_S:
1232                         if(U.flag & USER_LMOUSESELECT)
1233                                 return EVT_TWEAK_L;
1234                         else
1235                                 return EVT_TWEAK_R;
1236         }
1237         
1238         return kmitype;
1239 }
1240
1241 static void wm_eventemulation(wmEvent *event)
1242 {
1243         static int mmb_emulated = 0; /* this should be in a data structure somwhere */
1244         
1245         /* middlemouse emulation */
1246         if(U.flag & USER_TWOBUTTONMOUSE) {
1247                 if(event->type == LEFTMOUSE && (event->alt || mmb_emulated == KM_PRESS)) {
1248                         event->type = MIDDLEMOUSE;
1249                         event->alt = 0;
1250                         mmb_emulated = event->val;
1251                 }
1252         }
1253
1254 #ifdef __APPLE__
1255         /* rightmouse emulation */
1256         if(U.flag & USER_TWOBUTTONMOUSE) {
1257                 if(event->type == LEFTMOUSE && (event->oskey || mmb_emulated == KM_PRESS)) {
1258                         event->type = RIGHTMOUSE;
1259                         event->oskey = 0;
1260                         mmb_emulated = event->val;
1261                 }
1262         }
1263 #endif
1264
1265         /* numpad emulation */
1266         if(U.flag & USER_NONUMPAD) {
1267                 switch(event->type) {
1268                         case ZEROKEY: event->type = PAD0; break;
1269                         case ONEKEY: event->type = PAD1; break;
1270                         case TWOKEY: event->type = PAD2; break;
1271                         case THREEKEY: event->type = PAD3; break;
1272                         case FOURKEY: event->type = PAD4; break;
1273                         case FIVEKEY: event->type = PAD5; break;
1274                         case SIXKEY: event->type = PAD6; break;
1275                         case SEVENKEY: event->type = PAD7; break;
1276                         case EIGHTKEY: event->type = PAD8; break;
1277                         case NINEKEY: event->type = PAD9; break;
1278                         case MINUSKEY: event->type = PADMINUS; break;
1279                         case EQUALKEY: event->type = PADPLUSKEY; break;
1280                         case BACKSLASHKEY: event->type = PADSLASHKEY; break;
1281                 }
1282         }
1283 }
1284
1285 static int wm_eventmatch(wmEvent *winevent, wmKeyMapItem *kmi)
1286 {
1287         int kmitype= WM_userdef_event_map(kmi->type);
1288
1289         if(kmi->flag & KMI_INACTIVE) return 0;
1290
1291         /* the matching rules */
1292         if(kmitype==KM_TEXTINPUT)
1293                 if(ISTEXTINPUT(winevent->type) && (winevent->ascii || winevent->utf8_buf[0])) return 1;
1294         if(kmitype!=KM_ANY)
1295                 if(winevent->type!=kmitype) return 0;
1296         
1297         if(kmi->val!=KM_ANY)
1298                 if(winevent->val!=kmi->val) return 0;
1299         
1300         /* modifiers also check bits, so it allows modifier order */
1301         if(kmi->shift!=KM_ANY)
1302                 if(winevent->shift != kmi->shift && !(winevent->shift & kmi->shift)) return 0;
1303         if(kmi->ctrl!=KM_ANY)
1304                 if(winevent->ctrl != kmi->ctrl && !(winevent->ctrl & kmi->ctrl)) return 0;
1305         if(kmi->alt!=KM_ANY)
1306                 if(winevent->alt != kmi->alt && !(winevent->alt & kmi->alt)) return 0;
1307         if(kmi->oskey!=KM_ANY)
1308                 if(winevent->oskey != kmi->oskey && !(winevent->oskey & kmi->oskey)) return 0;
1309         
1310         if(kmi->keymodifier)
1311                 if(winevent->keymodifier!=kmi->keymodifier) return 0;
1312                 
1313         /* key modifiers always check when event has it */
1314         /* otherwise regular keypresses with keymodifier still work */
1315         if(winevent->keymodifier)
1316                 if(ISTEXTINPUT(winevent->type)) 
1317                         if(winevent->keymodifier!=kmi->keymodifier) return 0;
1318         
1319         return 1;
1320 }
1321
1322
1323 /* operator exists */
1324 static void wm_event_modalkeymap(const bContext *C, wmOperator *op, wmEvent *event)
1325 {
1326         /* support for modal keymap in macros */
1327         if (op->opm)
1328                 op = op->opm;
1329
1330         if(op->type->modalkeymap) {
1331                 wmKeyMap *keymap= WM_keymap_active(CTX_wm_manager(C), op->type->modalkeymap);
1332                 wmKeyMapItem *kmi;
1333
1334                 for(kmi= keymap->items.first; kmi; kmi= kmi->next) {
1335                         if(wm_eventmatch(event, kmi)) {
1336                                         
1337                                 event->type= EVT_MODAL_MAP;
1338                                 event->val= kmi->propvalue;
1339                         }
1340                 }
1341         }
1342 }
1343
1344 /* Warning: this function removes a modal handler, when finished */
1345 static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHandler *handler,
1346                                     wmEvent *event, PointerRNA *properties)
1347 {
1348         int retval= OPERATOR_PASS_THROUGH;
1349         
1350         /* derived, modal or blocking operator */
1351         if(handler->op) {
1352                 wmOperator *op= handler->op;
1353                 wmOperatorType *ot= op->type;
1354
1355                 if(ot->modal) {
1356                         /* we set context to where modal handler came from */
1357                         wmWindowManager *wm= CTX_wm_manager(C);
1358                         ScrArea *area= CTX_wm_area(C);
1359                         ARegion *region= CTX_wm_region(C);
1360                         
1361                         wm_handler_op_context(C, handler);
1362                         wm_region_mouse_co(C, event);
1363                         wm_event_modalkeymap(C, op, event);
1364                         
1365                         if(ot->flag & OPTYPE_UNDO)
1366                                 wm->op_undo_depth++;
1367
1368                         retval= ot->modal(C, op, event);
1369                         OPERATOR_RETVAL_CHECK(retval);
1370
1371                         /* when this is _not_ the case the modal modifier may have loaded
1372                          * a new blend file (demo mode does this), so we have to assume
1373                          * the event, operator etc have all been freed. - campbell */
1374                         if(CTX_wm_manager(C) == wm) {
1375
1376                                 if(ot->flag & OPTYPE_UNDO)
1377                                         wm->op_undo_depth--;
1378
1379                                 /* putting back screen context, reval can pass trough after modal failures! */
1380                                 if((retval & OPERATOR_PASS_THROUGH) || wm_event_always_pass(event)) {
1381                                         CTX_wm_area_set(C, area);
1382                                         CTX_wm_region_set(C, region);
1383                                 }
1384                                 else {
1385                                         /* this special cases is for areas and regions that get removed */
1386                                         CTX_wm_area_set(C, NULL);
1387                                         CTX_wm_region_set(C, NULL);
1388                                 }
1389
1390                                 if(retval & (OPERATOR_CANCELLED|OPERATOR_FINISHED))
1391                                         wm_operator_reports(C, op, retval, FALSE);
1392
1393                                 if(retval & OPERATOR_FINISHED) {
1394                                         wm_operator_finished(C, op, 0);
1395                                         handler->op= NULL;
1396                                 }
1397                                 else if(retval & (OPERATOR_CANCELLED|OPERATOR_FINISHED)) {
1398                                         WM_operator_free(op);
1399                                         handler->op= NULL;
1400                                 }
1401
1402                                 /* remove modal handler, operator itself should have been canceled and freed */
1403                                 if(retval & (OPERATOR_CANCELLED|OPERATOR_FINISHED)) {
1404                                         WM_cursor_ungrab(CTX_wm_window(C));
1405
1406                                         BLI_remlink(handlers, handler);
1407                                         wm_event_free_handler(handler);
1408
1409                                         /* prevent silly errors from operator users */
1410                                         //retval &= ~OPERATOR_PASS_THROUGH;
1411                                 }
1412                         }
1413                         
1414                 }
1415                 else
1416                         printf("wm_handler_operator_call error\n");
1417         }
1418         else {
1419                 wmOperatorType *ot= WM_operatortype_find(event->keymap_idname, 0);
1420
1421                 if(ot)
1422                         retval= wm_operator_invoke(C, ot, event, properties, NULL, FALSE);
1423         }
1424         /* Finished and pass through flag as handled */
1425
1426         /* Finished and pass through flag as handled */
1427         if(retval == (OPERATOR_FINISHED|OPERATOR_PASS_THROUGH))
1428                 return WM_HANDLER_HANDLED;
1429
1430         /* Modal unhandled, break */
1431         if(retval == (OPERATOR_PASS_THROUGH|OPERATOR_RUNNING_MODAL))
1432                 return (WM_HANDLER_BREAK|WM_HANDLER_MODAL);
1433
1434         if(retval & OPERATOR_PASS_THROUGH)
1435                 return WM_HANDLER_CONTINUE;
1436
1437         return WM_HANDLER_BREAK;
1438 }
1439
1440 /* fileselect handlers are only in the window queue, so it's save to switch screens or area types */
1441 static int wm_handler_fileselect_call(bContext *C, ListBase *handlers, wmEventHandler *handler, wmEvent *event)
1442 {
1443         wmWindowManager *wm= CTX_wm_manager(C);
1444         SpaceFile *sfile;
1445         int action= WM_HANDLER_CONTINUE;
1446         
1447         if(event->type != EVT_FILESELECT)
1448                 return action;
1449         if(handler->op != (wmOperator *)event->customdata)
1450                 return action;
1451         
1452         switch(event->val) {
1453                 case EVT_FILESELECT_OPEN: 
1454                 case EVT_FILESELECT_FULL_OPEN: 
1455                         {       
1456                                 ScrArea *sa;
1457                                 
1458                                 /* sa can be null when window A is active, but mouse is over window B */
1459                                 /* in this case, open file select in original window A */
1460                                 if (handler->op_area == NULL) {
1461                                         bScreen *screen = CTX_wm_screen(C);
1462                                         sa = (ScrArea *)screen->areabase.first;
1463                                 }
1464                                 else {
1465                                         sa = handler->op_area;
1466                                 }
1467                                         
1468                                 if(event->val==EVT_FILESELECT_OPEN) {
1469                                         ED_area_newspace(C, sa, SPACE_FILE); /* 'sa' is modified in-place */
1470                                 }
1471                                 else {
1472                                         sa= ED_screen_full_newspace(C, sa, SPACE_FILE); /* sets context */
1473                                 }
1474
1475                                 /* note, getting the 'sa' back from the context causes a nasty bug where the newly created
1476                                  * 'sa' != CTX_wm_area(C). removed the line below and set 'sa' in the 'if' above */
1477                                 /* sa = CTX_wm_area(C); */
1478
1479                                 /* settings for filebrowser, sfile is not operator owner but sends events */
1480                                 sfile= (SpaceFile*)sa->spacedata.first;
1481                                 sfile->op= handler->op;
1482
1483                                 ED_fileselect_set_params(sfile);
1484                                 
1485                                 action= WM_HANDLER_BREAK;
1486                         }
1487                         break;
1488                         
1489                 case EVT_FILESELECT_EXEC:
1490                 case EVT_FILESELECT_CANCEL:
1491                 case EVT_FILESELECT_EXTERNAL_CANCEL:
1492                         {
1493                                 /* XXX validate area and region? */
1494                                 bScreen *screen= CTX_wm_screen(C);
1495
1496                                 /* remlink now, for load file case before removing*/
1497                                 BLI_remlink(handlers, handler);
1498                                 
1499                                 if(event->val!=EVT_FILESELECT_EXTERNAL_CANCEL) {
1500                                         if(screen != handler->filescreen) {
1501                                                 ED_screen_full_prevspace(C, CTX_wm_area(C));
1502                                         }
1503                                         else {
1504                                                 ED_area_prevspace(C, CTX_wm_area(C));
1505                                         }
1506                                 }
1507                                 
1508                                 wm_handler_op_context(C, handler);
1509
1510                                 /* needed for uiPupMenuReports */
1511
1512                                 if(event->val==EVT_FILESELECT_EXEC) {
1513 #if 0                           // use REDALERT now
1514
1515                                         /* a bit weak, might become arg for WM_event_fileselect? */
1516                                         /* XXX also extension code in image-save doesnt work for this yet */
1517                                         if (RNA_struct_find_property(handler->op->ptr, "check_existing") && 
1518                                                         RNA_boolean_get(handler->op->ptr, "check_existing")) {
1519                                                 char *path= RNA_string_get_alloc(handler->op->ptr, "filepath", NULL, 0);
1520                                                 /* this gives ownership to pupmenu */
1521                                                 uiPupMenuSaveOver(C, handler->op, (path)? path: "");
1522                                                 if(path)
1523                                                         MEM_freeN(path);
1524                                         }
1525                                         else
1526 #endif
1527                                         {
1528                                                 int retval;
1529                                                 
1530                                                 if(handler->op->type->flag & OPTYPE_UNDO)
1531                                                         wm->op_undo_depth++;
1532
1533                                                 retval= handler->op->type->exec(C, handler->op);
1534
1535                                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1536                                                 if(handler->op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1537                                                         wm->op_undo_depth--;
1538                                                 
1539                                                 if (retval & OPERATOR_FINISHED)
1540                                                         if(G.f & G_DEBUG)
1541                                                                 wm_operator_print(C, handler->op);
1542                                                 
1543                                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1544                                                 if(CTX_wm_manager(C) == wm && wm->op_undo_depth == 0)
1545                                                         if(handler->op->type->flag & OPTYPE_UNDO)
1546                                                                 ED_undo_push_op(C, handler->op);
1547
1548                                                 if(handler->op->reports->list.first) {
1549
1550                                                         /* FIXME, temp setting window, this is really bad!
1551                                                          * only have because lib linking errors need to be seen by users :(
1552                                                          * it can be removed without breaking anything but then no linking errors - campbell */
1553                                                         wmWindow *win_prev= CTX_wm_window(C);
1554                                                         ScrArea *area_prev= CTX_wm_area(C);
1555                                                         ARegion *ar_prev= CTX_wm_region(C);
1556
1557                                                         if(win_prev==NULL)
1558                                                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
1559
1560                                                         handler->op->reports->printlevel = RPT_WARNING;
1561                                                         uiPupMenuReports(C, handler->op->reports);
1562
1563                                                         /* XXX - copied from 'wm_operator_finished()' */
1564                                                         /* add reports to the global list, otherwise they are not seen */
1565                                                         BLI_movelisttolist(&CTX_wm_reports(C)->list, &handler->op->reports->list);
1566
1567                                                         CTX_wm_window_set(C, win_prev);
1568                                                         CTX_wm_area_set(C, area_prev);
1569                                                         CTX_wm_region_set(C, ar_prev);
1570                                                 }
1571
1572                                                 if (retval & OPERATOR_FINISHED) {
1573                                                         WM_operator_last_properties_store(handler->op);
1574                                                 }
1575
1576                                                 WM_operator_free(handler->op);
1577                                         }
1578                                 }
1579                                 else {
1580                                         if(handler->op->type->cancel) {
1581                                                 if(handler->op->type->flag & OPTYPE_UNDO)
1582                                                         wm->op_undo_depth++;
1583
1584                                                 handler->op->type->cancel(C, handler->op);
1585
1586                                                 if(handler->op->type->flag & OPTYPE_UNDO)
1587                                                         wm->op_undo_depth--;
1588                                         }
1589
1590                                         WM_operator_free(handler->op);
1591                                 }
1592
1593                                 CTX_wm_area_set(C, NULL);
1594                                 
1595                                 wm_event_free_handler(handler);
1596                                 
1597                                 action= WM_HANDLER_BREAK;
1598                         }
1599                         break;
1600         }
1601         
1602         return action;
1603 }
1604
1605 static int handler_boundbox_test(wmEventHandler *handler, wmEvent *event)
1606 {
1607         if(handler->bbwin) {
1608                 if(handler->bblocal) {
1609                         rcti rect= *handler->bblocal;
1610                         BLI_translate_rcti(&rect, handler->bbwin->xmin, handler->bbwin->ymin);
1611
1612                         if(BLI_in_rcti(&rect, event->x, event->y))
1613                                 return 1;
1614                         else if(event->type==MOUSEMOVE && BLI_in_rcti(&rect, event->prevx, event->prevy))
1615                                 return 1;
1616                         else
1617                                 return 0;
1618                 }
1619                 else {
1620                         if(BLI_in_rcti(handler->bbwin, event->x, event->y))
1621                                 return 1;
1622                         else if(event->type==MOUSEMOVE && BLI_in_rcti(handler->bbwin, event->prevx, event->prevy))
1623                                 return 1;
1624                         else
1625                                 return 0;
1626                 }
1627         }
1628         return 1;
1629 }
1630
1631 static int wm_action_not_handled(int action)
1632 {
1633         return action == WM_HANDLER_CONTINUE || action == (WM_HANDLER_BREAK|WM_HANDLER_MODAL);
1634 }
1635
1636 static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
1637 {
1638         wmWindowManager *wm= CTX_wm_manager(C);
1639         wmEventHandler *handler, *nexthandler;
1640         int action= WM_HANDLER_CONTINUE;
1641         int always_pass;
1642
1643         if(handlers==NULL) return action;
1644
1645         /* modal handlers can get removed in this loop, we keep the loop this way */
1646         for(handler= handlers->first; handler; handler= nexthandler) {
1647                 
1648                 nexthandler= handler->next;
1649                 
1650                 /* during this loop, ui handlers for nested menus can tag multiple handlers free */
1651                 if(handler->flag & WM_HANDLER_DO_FREE);
1652                         /* optional boundbox */
1653                 else if(handler_boundbox_test(handler, event)) {
1654                         /* in advance to avoid access to freed event on window close */
1655                         always_pass= wm_event_always_pass(event);
1656                 
1657                         /* modal+blocking handler */
1658                         if(handler->flag & WM_HANDLER_BLOCKING)
1659                                 action |= WM_HANDLER_BREAK;
1660
1661                         if(handler->keymap) {
1662                                 wmKeyMap *keymap= WM_keymap_active(wm, handler->keymap);
1663                                 wmKeyMapItem *kmi;
1664                                 
1665                                 if(!keymap->poll || keymap->poll(C)) {
1666                                         for(kmi= keymap->items.first; kmi; kmi= kmi->next) {
1667                                                 if(wm_eventmatch(event, kmi)) {
1668
1669                                                         /* weak, but allows interactive callback to not use rawkey */
1670                                                         event->keymap_idname = kmi->idname;
1671
1672                                                         action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
1673                                                         if(action & WM_HANDLER_BREAK)  /* not always_pass here, it denotes removed handler */
1674                                                                 break;
1675                                                 }
1676                                         }
1677                                 }
1678                         }
1679                         else if(handler->ui_handle) {
1680                                 action |= wm_handler_ui_call(C, handler, event, always_pass);
1681                         }
1682                         else if(handler->type==WM_HANDLER_FILESELECT) {
1683                                 /* screen context changes here */
1684                                 action |= wm_handler_fileselect_call(C, handlers, handler, event);
1685                         }
1686                         else if(handler->dropboxes) {
1687                                 if(event->type==EVT_DROP) {
1688                                         wmDropBox *drop= handler->dropboxes->first;
1689                                         for(; drop; drop= drop->next) {
1690                                                 /* other drop custom types allowed */
1691                                                 if(event->custom==EVT_DATA_LISTBASE) {
1692                                                         ListBase *lb= (ListBase *)event->customdata;
1693                                                         wmDrag *drag;
1694                                                         
1695                                                         for(drag= lb->first; drag; drag= drag->next) {
1696                                                                 if(drop->poll(C, drag, event)) {
1697                                                                         
1698                                                                         drop->copy(drag, drop);
1699                                                                         
1700                                                                         /* free the drags before calling operator */
1701                                                                         BLI_freelistN(event->customdata);
1702                                                                         event->customdata= NULL;
1703                                                                         event->custom= 0;
1704                                                                         
1705                                                                         WM_operator_name_call(C, drop->ot->idname, drop->opcontext, drop->ptr);
1706                                                                         action |= WM_HANDLER_BREAK;
1707                                                                         
1708                                                                         /* XXX fileread case */
1709                                                                         if(CTX_wm_window(C)==NULL)
1710                                                                                 return action;
1711                                                                         
1712                                                                         /* escape from drag loop, got freed */
1713                                                                         break;
1714                                                                 }
1715                                                         }
1716                                                 }
1717                                         }
1718                                 }
1719                         }
1720                         else {
1721                                 /* modal, swallows all */
1722                                 action |= wm_handler_operator_call(C, handlers, handler, event, NULL);
1723                         }
1724
1725                         if(action & WM_HANDLER_BREAK) {
1726                                 if(always_pass)
1727                                         action &= ~WM_HANDLER_BREAK;
1728                                 else
1729                                         break;
1730                         }
1731                 }
1732                 
1733                 /* XXX fileread case, if the wm is freed then the handler's
1734                  * will have been too so the code below need not run. */
1735                 if(CTX_wm_window(C)==NULL) {
1736                         return action;
1737                 }
1738
1739                 /* XXX code this for all modal ops, and ensure free only happens here */
1740                 
1741                 /* modal ui handler can be tagged to be freed */ 
1742                 if(BLI_findindex(handlers, handler) != -1) { /* could be freed already by regular modal ops */
1743                         if(handler->flag & WM_HANDLER_DO_FREE) {
1744                                 BLI_remlink(handlers, handler);
1745                                 wm_event_free_handler(handler);
1746                         }
1747                 }
1748         }
1749
1750         /* test for CLICK event */
1751         if (wm_action_not_handled(action) && event->val == KM_RELEASE) {
1752                 wmWindow *win = CTX_wm_window(C);
1753
1754                 if (win && win->eventstate->prevtype == event->type && win->eventstate->prevval == KM_PRESS) {
1755                         /* test for double click first,
1756                          * note1: this can be problematic because single click operators can get the
1757                          *   double click event but then with old mouse coords which is highly confusing,
1758                          *   so check for mouse moves too.
1759                          * note2: the first click event will be handled but still used to create a
1760                          *   double click event if clicking again quickly.
1761                          *   If no double click events are found it will fallback to a single click.
1762                          *   So a double click event can result in 2 successive single click calls
1763                          *   if its not handled by the keymap - campbell */
1764                         if (    (ABS(event->x - win->eventstate->prevclickx)) <= 2 &&
1765                                         (ABS(event->y - win->eventstate->prevclicky)) <= 2 &&
1766                                         ((PIL_check_seconds_timer() - win->eventstate->prevclicktime) * 1000 < U.dbl_click_time)
1767                         ) {
1768                                 event->val = KM_DBL_CLICK;
1769                                 /* removed this because in cases where we're this is used as a single click
1770                                  * event, this will give old coords,
1771                                  * since the distance is checked above, using new coords should be ok. */
1772                                 //   event->x = win->eventstate->prevclickx;
1773                                 //   event->y = win->eventstate->prevclicky;
1774                                 action |= wm_handlers_do(C, event, handlers);
1775                         }
1776
1777                         if (wm_action_not_handled(action)) {
1778                                 event->val = KM_CLICK;
1779                                 action |= wm_handlers_do(C, event, handlers);
1780                         }
1781
1782
1783                         /* revert value if not handled */
1784                         if (wm_action_not_handled(action)) {
1785                                 event->val = KM_RELEASE;
1786                         }
1787                 }
1788         }
1789         
1790         if(action == (WM_HANDLER_BREAK|WM_HANDLER_MODAL))
1791                 wm_cursor_arrow_move(CTX_wm_window(C), event);
1792
1793         return action;
1794 }
1795
1796 static int wm_event_inside_i(wmEvent *event, rcti *rect)
1797 {
1798         if(wm_event_always_pass(event))
1799                 return 1;
1800         if(BLI_in_rcti(rect, event->x, event->y))
1801                 return 1;
1802         if(event->type==MOUSEMOVE) {
1803                 if( BLI_in_rcti(rect, event->prevx, event->prevy)) {
1804                         return 1;
1805                 }
1806                 return 0;
1807         }
1808         return 0;
1809 }
1810
1811 static ScrArea *area_event_inside(bContext *C, int x, int y)
1812 {
1813         bScreen *screen= CTX_wm_screen(C);
1814         ScrArea *sa;
1815         
1816         if(screen)
1817                 for(sa= screen->areabase.first; sa; sa= sa->next)
1818                         if(BLI_in_rcti(&sa->totrct, x, y))
1819                                 return sa;
1820         return NULL;
1821 }
1822
1823 static ARegion *region_event_inside(bContext *C, int x, int y)
1824 {
1825         bScreen *screen= CTX_wm_screen(C);
1826         ScrArea *area= CTX_wm_area(C);
1827         ARegion *ar;
1828         
1829         if(screen && area)
1830                 for(ar= area->regionbase.first; ar; ar= ar->next)
1831                         if(BLI_in_rcti(&ar->winrct, x, y))
1832                                 return ar;
1833         return NULL;
1834 }
1835
1836 static void wm_paintcursor_tag(bContext *C, wmPaintCursor *pc, ARegion *ar)
1837 {
1838         if(ar) {
1839                 for(; pc; pc= pc->next) {
1840                         if(pc->poll == NULL || pc->poll(C)) {
1841                                 wmWindow *win= CTX_wm_window(C);
1842                                 win->screen->do_draw_paintcursor= 1;
1843                                 wm_tag_redraw_overlay(win, ar);
1844                         }
1845                 }
1846         }
1847 }
1848
1849 /* called on mousemove, check updates for paintcursors */
1850 /* context was set on active area and region */
1851 static void wm_paintcursor_test(bContext *C, wmEvent *event)
1852 {
1853         wmWindowManager *wm= CTX_wm_manager(C);
1854         
1855         if(wm->paintcursors.first) {
1856                 ARegion *ar= CTX_wm_region(C);
1857                 
1858                 if(ar)
1859                         wm_paintcursor_tag(C, wm->paintcursors.first, ar);
1860                 
1861                 /* if previous position was not in current region, we have to set a temp new context */
1862                 if(ar==NULL || !BLI_in_rcti(&ar->winrct, event->prevx, event->prevy)) {
1863                         ScrArea *sa= CTX_wm_area(C);
1864                         
1865                         CTX_wm_area_set(C, area_event_inside(C, event->prevx, event->prevy));
1866                         CTX_wm_region_set(C, region_event_inside(C, event->prevx, event->prevy));
1867
1868                         wm_paintcursor_tag(C, wm->paintcursors.first, CTX_wm_region(C));
1869                         
1870                         CTX_wm_area_set(C, sa);
1871                         CTX_wm_region_set(C, ar);
1872                 }
1873         }
1874 }
1875
1876 static void wm_event_drag_test(wmWindowManager *wm, wmWindow *win, wmEvent *event)
1877 {
1878         if(wm->drags.first==NULL) return;
1879         
1880         if(event->type==MOUSEMOVE)
1881                 win->screen->do_draw_drag= 1;
1882         else if(event->type==ESCKEY) {
1883                 BLI_freelistN(&wm->drags);
1884                 win->screen->do_draw_drag= 1;
1885         }
1886         else if(event->type==LEFTMOUSE && event->val==KM_RELEASE) {
1887                 event->type= EVT_DROP;
1888                 
1889                 /* create customdata, first free existing */
1890                 if(event->customdata) {
1891                         if(event->customdatafree)
1892                                 MEM_freeN(event->customdata);
1893                 }
1894                 
1895                 event->custom= EVT_DATA_LISTBASE;
1896                 event->customdata= &wm->drags;
1897                 event->customdatafree= 1;
1898                 
1899                 /* clear drop icon */
1900                 win->screen->do_draw_drag= 1;
1901                 
1902                 /* restore cursor (disabled, see wm_dragdrop.c) */
1903                 // WM_cursor_restore(win);
1904         }
1905         
1906         /* overlap fails otherwise */
1907         if(win->screen->do_draw_drag)
1908                 if(win->drawmethod == USER_DRAW_OVERLAP)
1909                         win->screen->do_draw= 1;
1910         
1911 }
1912
1913 /* called in main loop */
1914 /* goes over entire hierarchy:  events -> window -> screen -> area -> region */
1915 void wm_event_do_handlers(bContext *C)
1916 {
1917         wmWindowManager *wm= CTX_wm_manager(C);
1918         wmWindow *win;
1919
1920         /* update key configuration before handling events */
1921         WM_keyconfig_update(wm);
1922
1923         for(win= wm->windows.first; win; win= win->next) {
1924                 wmEvent *event;
1925                 
1926                 if( win->screen==NULL )
1927                         wm_event_free_all(win);
1928                 else {
1929                         Scene* scene = win->screen->scene;
1930                         
1931                         if(scene) {
1932                                 int playing = sound_scene_playing(win->screen->scene);
1933                                 
1934                                 if(playing != -1) {
1935                                         CTX_wm_window_set(C, win);
1936                                         CTX_wm_screen_set(C, win->screen);
1937                                         CTX_data_scene_set(C, scene);
1938                                         
1939                                         if(((playing == 1) && (!win->screen->animtimer)) || ((playing == 0) && (win->screen->animtimer))){
1940                                                 ED_screen_animation_play(C, -1, 1);
1941                                         }
1942                                         
1943                                         if(playing == 0) {
1944                                                 float time = sound_sync_scene(scene);
1945                                                 if(finite(time)) {
1946                                                         int ncfra = sound_sync_scene(scene) * (float)FPS + 0.5f;
1947                                                         if(ncfra != scene->r.cfra)      {
1948                                                                 scene->r.cfra = ncfra;
1949                                                                 ED_update_for_newframe(CTX_data_main(C), scene, win->screen, 1);
1950                                                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
1951                                                         }
1952                                                 }
1953                                         }
1954                                         
1955                                         CTX_data_scene_set(C, NULL);
1956                                         CTX_wm_screen_set(C, NULL);
1957                                         CTX_wm_window_set(C, NULL);
1958                                 }
1959                         }
1960                 }
1961                 
1962                 while( (event= win->queue.first) ) {
1963                         int action = WM_HANDLER_CONTINUE;
1964
1965                         if((G.f & G_DEBUG) && event && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE))
1966                                 printf("pass on evt %d val %d\n", event->type, event->val); 
1967                         
1968                         wm_eventemulation(event);
1969
1970                         CTX_wm_window_set(C, win);
1971                         
1972                         /* we let modal handlers get active area/region, also wm_paintcursor_test needs it */
1973                         CTX_wm_area_set(C, area_event_inside(C, event->x, event->y));
1974                         CTX_wm_region_set(C, region_event_inside(C, event->x, event->y));
1975                         
1976                         /* MVC demands to not draw in event handlers... but we need to leave it for ogl selecting etc */
1977                         wm_window_make_drawable(C, win);
1978                         
1979                         wm_region_mouse_co(C, event);
1980
1981                         /* first we do priority handlers, modal + some limited keymaps */
1982                         action |= wm_handlers_do(C, event, &win->modalhandlers);
1983                         
1984                         /* fileread case */
1985                         if(CTX_wm_window(C)==NULL)
1986                                 return;
1987                         
1988                         /* check dragging, creates new event or frees, adds draw tag */
1989                         wm_event_drag_test(wm, win, event);
1990                         
1991                         /* builtin tweak, if action is break it removes tweak */
1992                         wm_tweakevent_test(C, event, action);
1993
1994                         if((action & WM_HANDLER_BREAK) == 0) {
1995                                 ScrArea *sa;
1996                                 ARegion *ar;
1997                                 int doit= 0;
1998         
1999                                 /* Note: setting subwin active should be done here, after modal handlers have been done */
2000                                 if(event->type==MOUSEMOVE) {
2001                                         /* state variables in screen, cursors. Also used in wm_draw.c, fails for modal handlers though */
2002                                         ED_screen_set_subwinactive(C, event);   
2003                                         /* for regions having custom cursors */
2004                                         wm_paintcursor_test(C, event);
2005                                 }
2006                                 else if (event->type==NDOF_MOTION) {
2007                                         win->addmousemove = TRUE;
2008                                 }
2009
2010                                 for(sa= win->screen->areabase.first; sa; sa= sa->next) {
2011                                         if(wm_event_inside_i(event, &sa->totrct)) {
2012                                                 CTX_wm_area_set(C, sa);
2013
2014                                                 if((action & WM_HANDLER_BREAK) == 0) {
2015                                                         for(ar=sa->regionbase.first; ar; ar= ar->next) {
2016                                                                 if(wm_event_inside_i(event, &ar->winrct)) {
2017                                                                         CTX_wm_region_set(C, ar);
2018                                                                         
2019                                                                         /* call even on non mouse events, since the */
2020                                                                         wm_region_mouse_co(C, event);
2021
2022                                                                         /* does polls for drop regions and checks uibuts */
2023                                                                         /* need to be here to make sure region context is true */
2024                                                                         if(ELEM(event->type, MOUSEMOVE, EVT_DROP)) {
2025                                                                                 wm_drags_check_ops(C, event);
2026                                                                         }
2027                                                                         
2028                                                                         action |= wm_handlers_do(C, event, &ar->handlers);
2029
2030                                                                         /* fileread case (python), [#29489] */
2031                                                                         if(CTX_wm_window(C)==NULL)
2032                                                                                 return;
2033
2034                                                                         doit |= (BLI_in_rcti(&ar->winrct, event->x, event->y));
2035                                                                         
2036                                                                         if(action & WM_HANDLER_BREAK)
2037                                                                                 break;
2038                                                                 }
2039                                                         }
2040                                                 }
2041
2042                                                 CTX_wm_region_set(C, NULL);
2043
2044                                                 if((action & WM_HANDLER_BREAK) == 0) {
2045                                                         wm_region_mouse_co(C, event); /* only invalidates event->mval in this case */
2046                                                         action |= wm_handlers_do(C, event, &sa->handlers);
2047                                                 }
2048                                                 CTX_wm_area_set(C, NULL);
2049
2050                                                 /* NOTE: do not escape on WM_HANDLER_BREAK, mousemove needs handled for previous area */
2051                                         }
2052                                 }
2053                                 
2054                                 if((action & WM_HANDLER_BREAK) == 0) {
2055                                         /* also some non-modal handlers need active area/region */
2056                                         CTX_wm_area_set(C, area_event_inside(C, event->x, event->y));
2057                                         CTX_wm_region_set(C, region_event_inside(C, event->x, event->y));
2058
2059                                         wm_region_mouse_co(C, event);
2060
2061                                         action |= wm_handlers_do(C, event, &win->handlers);
2062
2063                                         /* fileread case */
2064                                         if(CTX_wm_window(C)==NULL)
2065                                                 return;
2066                                 }
2067
2068                                 /* XXX hrmf, this gives reliable previous mouse coord for area change, feels bad? 
2069                                  * doing it on ghost queue gives errors when mousemoves go over area borders */
2070                                 if(doit && win->screen && win->screen->subwinactive != win->screen->mainwin) {
2071                                         win->eventstate->prevx= event->x;
2072                                         win->eventstate->prevy= event->y;
2073                                         //printf("win->eventstate->prev = %d %d\n", event->x, event->y);
2074                                 }
2075                                 else {
2076                                         //printf("not setting prev to %d %d\n", event->x, event->y);
2077                                 }
2078                         }
2079                         
2080                         /* store last event for this window */
2081                         /* mousemove and timer events don't overwrite last type */
2082                         if (!ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) && !ISTIMER(event->type)) {
2083                                 if (wm_action_not_handled(action)) {
2084                                         if (win->eventstate->prevtype == event->type) {
2085                                                 /* set click time on first click (press -> release) */
2086                                                 if (win->eventstate->prevval == KM_PRESS && event->val == KM_RELEASE) {
2087                                                         win->eventstate->prevclicktime = PIL_check_seconds_timer();
2088                                                         win->eventstate->prevclickx = event->x;
2089                                                         win->eventstate->prevclicky = event->y;
2090                                                 }
2091                                         } else {
2092                                                 /* reset click time if event type not the same */
2093                                                 win->eventstate->prevclicktime = 0;
2094                                         }
2095
2096                                         win->eventstate->prevval = event->val;
2097                                         win->eventstate->prevtype = event->type;
2098                                 } else if (event->val == KM_CLICK) { /* keep click for double click later */
2099                                         win->eventstate->prevtype = event->type;
2100                                         win->eventstate->prevval = event->val;
2101                                         win->eventstate->prevclicktime = PIL_check_seconds_timer();
2102                                         win->eventstate->prevclickx = event->x;
2103                                         win->eventstate->prevclicky = event->y;
2104                                 } else { /* reset if not */
2105                                         win->eventstate->prevtype = -1;
2106                                         win->eventstate->prevval = 0;
2107                                         win->eventstate->prevclicktime = 0;
2108                                 }
2109                         }
2110
2111                         /* unlink and free here, blender-quit then frees all */
2112                         BLI_remlink(&win->queue, event);
2113                         wm_event_free(event);
2114                         
2115                 }
2116                 
2117                 /* only add mousemove when queue was read entirely */
2118                 if(win->addmousemove && win->eventstate) {
2119                         wmEvent tevent= *(win->eventstate);
2120                         //printf("adding MOUSEMOVE %d %d\n", tevent.x, tevent.y);
2121                         tevent.type= MOUSEMOVE;
2122                         tevent.prevx= tevent.x;
2123                         tevent.prevy= tevent.y;
2124                         wm_event_add(win, &tevent);
2125                         win->addmousemove= 0;
2126                 }
2127                 
2128                 CTX_wm_window_set(C, NULL);
2129         }
2130
2131         /* update key configuration after handling events */
2132         WM_keyconfig_update(wm);
2133 }
2134
2135 /* ********** filesector handling ************ */
2136
2137 void WM_event_fileselect_event(bContext *C, void *ophandle, int eventval)
2138 {
2139         /* add to all windows! */
2140         wmWindow *win;
2141         
2142         for(win= CTX_wm_manager(C)->windows.first; win; win= win->next) {
2143                 wmEvent event= *win->eventstate;
2144                 
2145                 event.type= EVT_FILESELECT;
2146                 event.val= eventval;
2147                 event.customdata= ophandle;             // only as void pointer type check
2148
2149                 wm_event_add(win, &event);
2150         }
2151 }
2152
2153 /* operator is supposed to have a filled "path" property */
2154 /* optional property: filetype (XXX enum?) */
2155
2156 /* Idea is to keep a handler alive on window queue, owning the operator.
2157  * The filewindow can send event to make it execute, thus ensuring
2158  * executing happens outside of lower level queues, with UI refreshed.
2159  * Should also allow multiwin solutions */
2160
2161 void WM_event_add_fileselect(bContext *C, wmOperator *op)
2162 {
2163         wmEventHandler *handler, *handlernext;
2164         wmWindow *win= CTX_wm_window(C);
2165         int full= 1;    // XXX preset?
2166
2167         /* only allow 1 file selector open per window */
2168         for(handler= win->modalhandlers.first; handler; handler=handlernext) {
2169                 handlernext= handler->next;
2170                 
2171                 if(handler->type == WM_HANDLER_FILESELECT) {
2172                         if(handler->op)
2173                                 WM_operator_free(handler->op);
2174                         BLI_remlink(&win->modalhandlers, handler);
2175                         wm_event_free_handler(handler);
2176                 }
2177         }
2178         
2179         handler = MEM_callocN(sizeof(wmEventHandler), "fileselect handler");
2180         
2181         handler->type= WM_HANDLER_FILESELECT;
2182         handler->op= op;
2183         handler->op_area= CTX_wm_area(C);
2184         handler->op_region= CTX_wm_region(C);
2185         handler->filescreen= CTX_wm_screen(C);
2186         
2187         BLI_addhead(&win->modalhandlers, handler);
2188         
2189         /* check props once before invoking if check is available
2190          * ensures initial properties are valid */
2191         if(op->type->check) {
2192                 op->type->check(C, op); /* ignore return value */
2193         }
2194
2195         WM_event_fileselect_event(C, op, full?EVT_FILESELECT_FULL_OPEN:EVT_FILESELECT_OPEN);
2196 }
2197
2198 #if 0
2199 /* lets not expose struct outside wm? */
2200 static void WM_event_set_handler_flag(wmEventHandler *handler, int flag)
2201 {
2202         handler->flag= flag;
2203 }
2204 #endif
2205
2206 wmEventHandler *WM_event_add_modal_handler(bContext *C, wmOperator *op)
2207 {
2208         wmEventHandler *handler= MEM_callocN(sizeof(wmEventHandler), "event modal handler");
2209         wmWindow *win= CTX_wm_window(C);
2210         
2211         /* operator was part of macro */
2212         if(op->opm) {
2213                 /* give the mother macro to the handler */
2214                 handler->op= op->opm;
2215                 /* mother macro opm becomes the macro element */
2216                 handler->op->opm= op;
2217         }
2218         else
2219                 handler->op= op;
2220         
2221         handler->op_area= CTX_wm_area(C);               /* means frozen screen context for modal handlers! */
2222         handler->op_region= CTX_wm_region(C);
2223         
2224         BLI_addhead(&win->modalhandlers, handler);
2225
2226         return handler;
2227 }
2228
2229 wmEventHandler *WM_event_add_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2230 {
2231         wmEventHandler *handler;
2232
2233         if(!keymap) {
2234                 printf("WM_event_add_keymap_handler called with NULL keymap\n");
2235                 return NULL;
2236         }
2237
2238         /* only allow same keymap once */
2239         for(handler= handlers->first; handler; handler= handler->next)
2240                 if(handler->keymap==keymap)
2241                         return handler;
2242         
2243         handler= MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2244         BLI_addtail(handlers, handler);
2245         handler->keymap= keymap;
2246
2247         return handler;
2248 }
2249
2250 /* priorities not implemented yet, for time being just insert in begin of list */
2251 wmEventHandler *WM_event_add_keymap_handler_priority(ListBase *handlers, wmKeyMap *keymap, int UNUSED(priority))
2252 {
2253         wmEventHandler *handler;
2254         
2255         WM_event_remove_keymap_handler(handlers, keymap);
2256         
2257         handler= MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2258         BLI_addhead(handlers, handler);
2259         handler->keymap= keymap;
2260         
2261         return handler;
2262 }
2263
2264 wmEventHandler *WM_event_add_keymap_handler_bb(ListBase *handlers, wmKeyMap *keymap, rcti *bblocal, rcti *bbwin)
2265 {
2266         wmEventHandler *handler= WM_event_add_keymap_handler(handlers, keymap);
2267         
2268         if(handler) {
2269                 handler->bblocal= bblocal;
2270                 handler->bbwin= bbwin;
2271         }
2272         return handler;
2273 }
2274
2275 void WM_event_remove_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2276 {
2277         wmEventHandler *handler;
2278         
2279         for(handler= handlers->first; handler; handler= handler->next) {
2280                 if(handler->keymap==keymap) {
2281                         BLI_remlink(handlers, handler);
2282                         wm_event_free_handler(handler);
2283                         break;
2284                 }
2285         }
2286 }
2287
2288 wmEventHandler *WM_event_add_ui_handler(const bContext *C, ListBase *handlers,
2289                                         wmUIHandlerFunc func, wmUIHandlerRemoveFunc remove, void *userdata)
2290 {
2291         wmEventHandler *handler= MEM_callocN(sizeof(wmEventHandler), "event ui handler");
2292         handler->ui_handle= func;
2293         handler->ui_remove= remove;
2294         handler->ui_userdata= userdata;
2295         handler->ui_area= (C)? CTX_wm_area(C): NULL;
2296         handler->ui_region= (C)? CTX_wm_region(C): NULL;
2297         handler->ui_menu= (C)? CTX_wm_menu(C): NULL;
2298         
2299         BLI_addhead(handlers, handler);
2300         
2301         return handler;
2302 }
2303
2304 /* set "postpone" for win->modalhandlers, this is in a running for() loop in wm_handlers_do() */
2305 void WM_event_remove_ui_handler(ListBase *handlers,
2306                                 wmUIHandlerFunc func, wmUIHandlerRemoveFunc remove, void *userdata, int postpone)
2307 {
2308         wmEventHandler *handler;
2309         
2310         for(handler= handlers->first; handler; handler= handler->next) {
2311                 if(handler->ui_handle == func && handler->ui_remove == remove && handler->ui_userdata == userdata) {
2312                         /* handlers will be freed in wm_handlers_do() */
2313                         if(postpone) {
2314                                 handler->flag |= WM_HANDLER_DO_FREE;
2315                         }
2316                         else {
2317                                 BLI_remlink(handlers, handler);
2318                                 wm_event_free_handler(handler);
2319                         }
2320                         break;
2321                 }
2322         }
2323 }
2324
2325 wmEventHandler *WM_event_add_dropbox_handler(ListBase *handlers, ListBase *dropboxes)
2326 {
2327         wmEventHandler *handler;
2328
2329         /* only allow same dropbox once */
2330         for(handler= handlers->first; handler; handler= handler->next)
2331                 if(handler->dropboxes==dropboxes)
2332                         return handler;
2333         
2334         handler= MEM_callocN(sizeof(wmEventHandler), "dropbox handler");
2335         
2336         /* dropbox stored static, no free or copy */
2337         handler->dropboxes= dropboxes;
2338         BLI_addhead(handlers, handler);
2339         
2340         return handler;
2341 }
2342
2343 /* XXX solution works, still better check the real cause (ton) */
2344 void WM_event_remove_area_handler(ListBase *handlers, void *area)
2345 {
2346         wmEventHandler *handler, *nexthandler;
2347
2348         for(handler = handlers->first; handler; handler= nexthandler) {
2349                 nexthandler = handler->next;
2350                 if (handler->type != WM_HANDLER_FILESELECT) {
2351                         if (handler->ui_area == area) {
2352                                 BLI_remlink(handlers, handler);
2353                                 wm_event_free_handler(handler);
2354                         }
2355                 }
2356         }
2357 }
2358
2359 #if 0
2360 static void WM_event_remove_handler(ListBase *handlers, wmEventHandler *handler)
2361 {
2362         BLI_remlink(handlers, handler);
2363         wm_event_free_handler(handler);
2364 }
2365 #endif
2366
2367 void WM_event_add_mousemove(bContext *C)
2368 {
2369         wmWindow *window= CTX_wm_window(C);
2370         
2371         window->addmousemove= 1;
2372 }
2373
2374 /* for modal callbacks, check configuration for how to interpret exit with tweaks  */
2375 int WM_modal_tweak_exit(wmEvent *evt, int tweak_event)
2376 {
2377         /* if the release-confirm userpref setting is enabled, 
2378          * tweak events can be canceled when mouse is released
2379          */
2380         if (U.flag & USER_RELEASECONFIRM) {
2381                 /* option on, so can exit with km-release */
2382                 if (evt->val == KM_RELEASE) {
2383                         switch (tweak_event) {
2384                                 case EVT_TWEAK_L:
2385                                 case EVT_TWEAK_M:
2386                                 case EVT_TWEAK_R:
2387                                         return 1;
2388                         }
2389                 }
2390                 else {
2391                         /* if the initial event wasn't a tweak event then
2392                          * ignore USER_RELEASECONFIRM setting: see [#26756] */
2393                         if(ELEM3(tweak_event, EVT_TWEAK_L, EVT_TWEAK_M, EVT_TWEAK_R) == 0) {
2394                                 return 1;
2395                         }
2396                 }
2397         }
2398         else {
2399                 /* this is fine as long as not doing km-release, otherwise
2400                  * some items (i.e. markers) being tweaked may end up getting
2401                  * dropped all over
2402                  */
2403                 if (evt->val != KM_RELEASE)
2404                         return 1;
2405         }
2406         
2407         return 0;
2408 }
2409
2410 /* ********************* ghost stuff *************** */
2411
2412 static int convert_key(GHOST_TKey key) 
2413 {
2414         if (key>=GHOST_kKeyA && key<=GHOST_kKeyZ) {
2415                 return (AKEY + ((int) key - GHOST_kKeyA));
2416         } else if (key>=GHOST_kKey0 && key<=GHOST_kKey9) {
2417                 return (ZEROKEY + ((int) key - GHOST_kKey0));
2418         } else if (key>=GHOST_kKeyNumpad0 && key<=GHOST_kKeyNumpad9) {
2419                 return (PAD0 + ((int) key - GHOST_kKeyNumpad0));
2420         } else if (key>=GHOST_kKeyF1 && key<=GHOST_kKeyF19) {
2421                 return (F1KEY + ((int) key - GHOST_kKeyF1));
2422         } else {
2423                 switch (key) {
2424                         case GHOST_kKeyBackSpace:               return BACKSPACEKEY;
2425                         case GHOST_kKeyTab:                             return TABKEY;
2426                         case GHOST_kKeyLinefeed:                return LINEFEEDKEY;
2427                         case GHOST_kKeyClear:                   return 0;
2428                         case GHOST_kKeyEnter:                   return RETKEY;
2429                                 
2430                         case GHOST_kKeyEsc:                             return ESCKEY;
2431                         case GHOST_kKeySpace:                   return SPACEKEY;
2432                         case GHOST_kKeyQuote:                   return QUOTEKEY;
2433                         case GHOST_kKeyComma:                   return COMMAKEY;
2434                         case GHOST_kKeyMinus:                   return MINUSKEY;
2435                         case GHOST_kKeyPeriod:                  return PERIODKEY;
2436                         case GHOST_kKeySlash:                   return SLASHKEY;
2437                                 
2438                         case GHOST_kKeySemicolon:               return SEMICOLONKEY;
2439                         case GHOST_kKeyEqual:                   return EQUALKEY;
2440                                 
2441                         case GHOST_kKeyLeftBracket:             return LEFTBRACKETKEY;
2442                         case GHOST_kKeyRightBracket:    return RIGHTBRACKETKEY;
2443                         case GHOST_kKeyBackslash:               return BACKSLASHKEY;
2444                         case GHOST_kKeyAccentGrave:             return ACCENTGRAVEKEY;
2445                                 
2446                         case GHOST_kKeyLeftShift:               return LEFTSHIFTKEY;
2447                         case GHOST_kKeyRightShift:              return RIGHTSHIFTKEY;
2448                         case GHOST_kKeyLeftControl:             return LEFTCTRLKEY;
2449                         case GHOST_kKeyRightControl:    return RIGHTCTRLKEY;
2450                         case GHOST_kKeyOS:                              return OSKEY;
2451                         case GHOST_kKeyLeftAlt:                 return LEFTALTKEY;
2452                         case GHOST_kKeyRightAlt:                return RIGHTALTKEY;
2453                                 
2454                         case GHOST_kKeyCapsLock:                return CAPSLOCKKEY;
2455                         case GHOST_kKeyNumLock:                 return 0;
2456                         case GHOST_kKeyScrollLock:              return 0;
2457                                 
2458                         case GHOST_kKeyLeftArrow:               return LEFTARROWKEY;
2459                         case GHOST_kKeyRightArrow:              return RIGHTARROWKEY;
2460                         case GHOST_kKeyUpArrow:                 return UPARROWKEY;
2461                         case GHOST_kKeyDownArrow:               return DOWNARROWKEY;
2462                                 
2463                         case GHOST_kKeyPrintScreen:             return 0;
2464                         case GHOST_kKeyPause:                   return PAUSEKEY;
2465                                 
2466                         case GHOST_kKeyInsert:                  return INSERTKEY;
2467                         case GHOST_kKeyDelete:                  return DELKEY;
2468                         case GHOST_kKeyHome:                    return HOMEKEY;
2469                         case GHOST_kKeyEnd:                             return ENDKEY;
2470                         case GHOST_kKeyUpPage:                  return PAGEUPKEY;
2471                         case GHOST_kKeyDownPage:                return PAGEDOWNKEY;
2472                                 
2473                         case GHOST_kKeyNumpadPeriod:    return PADPERIOD;
2474                         case GHOST_kKeyNumpadEnter:             return PADENTER;
2475                         case GHOST_kKeyNumpadPlus:              return PADPLUSKEY;
2476                         case GHOST_kKeyNumpadMinus:             return PADMINUS;
2477                         case GHOST_kKeyNumpadAsterisk:  return PADASTERKEY;
2478                         case GHOST_kKeyNumpadSlash:             return PADSLASHKEY;
2479                                 
2480                         case GHOST_kKeyGrLess:              return GRLESSKEY; 
2481                         
2482                         case GHOST_kKeyMediaPlay:               return MEDIAPLAY;
2483                         case GHOST_kKeyMediaStop:               return MEDIASTOP;
2484                         case GHOST_kKeyMediaFirst:              return MEDIAFIRST;
2485                         case GHOST_kKeyMediaLast:               return MEDIALAST;
2486                         
2487                         default:
2488                                 return UNKNOWNKEY;      /* GHOST_kKeyUnknown */
2489                 }
2490         }
2491 }
2492
2493 /* adds customdata to event */
2494 static void update_tablet_data(wmWindow *win, wmEvent *event)
2495 {
2496         const GHOST_TabletData *td= GHOST_GetTabletData(win->ghostwin);
2497         
2498         /* if there's tablet data from an active tablet device then add it */
2499         if ((td != NULL) && td->Active != GHOST_kTabletModeNone) {
2500                 struct wmTabletData *wmtab= MEM_mallocN(sizeof(wmTabletData), "customdata tablet");
2501                 
2502                 wmtab->Active = (int)td->Active;
2503                 wmtab->Pressure = td->Pressure;
2504                 wmtab->Xtilt = td->Xtilt;
2505                 wmtab->Ytilt = td->Ytilt;
2506                 
2507                 event->custom= EVT_DATA_TABLET;
2508                 event->customdata= wmtab;
2509                 event->customdatafree= 1;
2510         } 
2511 }
2512
2513 /* adds customdata to event */
2514 static void attach_ndof_data(wmEvent* event, const GHOST_TEventNDOFMotionData* ghost)
2515 {
2516         wmNDOFMotionData* data = MEM_mallocN(sizeof(wmNDOFMotionData), "customdata NDOF");
2517
2518         const float s = U.ndof_sensitivity;
2519
2520         data->tx = s * ghost->tx;
2521
2522         data->rx = s * ghost->rx;
2523         data->ry = s * ghost->ry;
2524         data->rz = s * ghost->rz;
2525
2526         if (U.ndof_flag & NDOF_ZOOM_UPDOWN) {
2527                 /* rotate so Y is where Z was */
2528                 data->ty = s * ghost->tz;
2529                 data->tz = s * ghost->ty;
2530                 /* maintain handed-ness? or just do what feels right? */
2531
2532                 /* should this affect rotation also?
2533                  * initial guess is 'yes', but get user feedback immediately!
2534                  */
2535 #if 0
2536                 /* after turning this on, my guess becomes 'no' */
2537                 data->ry = s * ghost->rz;
2538                 data->rz = s * ghost->ry;
2539 #endif
2540                 }
2541         else {
2542                 data->ty = s * ghost->ty;
2543                 data->tz = s * ghost->tz;
2544                 }
2545
2546         data->dt = ghost->dt;
2547
2548         data->progress = (wmProgress) ghost->progress;
2549
2550         event->custom = EVT_DATA_NDOF_MOTION;
2551         event->customdata = data;
2552         event->customdatafree = 1;
2553 }
2554
2555 /* imperfect but probably usable... draw/enable drags to other windows */
2556 static wmWindow *wm_event_cursor_other_windows(wmWindowManager *wm, wmWindow *win, wmEvent *evt)
2557 {
2558         int mx= evt->x, my= evt->y;
2559         
2560         if(wm->windows.first== wm->windows.last)
2561                 return NULL;
2562         
2563         /* top window bar... */
2564         if(mx<0 || my<0 || mx>win->sizex || my>win->sizey+30) { 
2565                 wmWindow *owin;
2566                 wmEventHandler *handler;
2567                 
2568                 /* let's skip windows having modal handlers now */
2569                 /* potential XXX ugly... I wouldn't have added a modalhandlers list (introduced in rev 23331, ton) */
2570                 for(handler= win->modalhandlers.first; handler; handler= handler->next)
2571                         if(handler->ui_handle || handler->op)
2572                                 return NULL;
2573                 
2574                 /* to desktop space */
2575                 mx += (int)win->posx;
2576                 my += (int)win->posy;
2577                 
2578                 /* check other windows to see if it has mouse inside */
2579                 for(owin= wm->windows.first; owin; owin= owin->next) {
2580                         
2581                         if(owin!=win) {
2582                                 if(mx-owin->posx >= 0 && my-owin->posy >= 0 &&
2583                                    mx-owin->posx <= owin->sizex && my-owin->posy <= owin->sizey) {
2584                                         evt->x= mx - (int)owin->posx;
2585                                         evt->y= my - (int)owin->posy;
2586                                         
2587                                         return owin;
2588                                 }
2589                         }
2590                 }
2591         }
2592         return NULL;
2593 }
2594
2595 /* windows store own event queues, no bContext here */
2596 /* time is in 1000s of seconds, from ghost */
2597 void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int UNUSED(time), void *customdata)
2598 {
2599         wmWindow *owin;
2600         wmEvent event, *evt= win->eventstate;
2601
2602         /* initialize and copy state (only mouse x y and modifiers) */
2603         event= *evt;
2604         
2605         switch (type) {
2606                 /* mouse move */
2607                 case GHOST_kEventCursorMove: {
2608                         if(win->active) {
2609                                 GHOST_TEventCursorData *cd= customdata;
2610                                 wmEvent *lastevent= win->queue.last;
2611                                 int cx, cy;
2612                                 
2613                                 GHOST_ScreenToClient(win->ghostwin, cd->x, cd->y, &cx, &cy);
2614                                 evt->x= cx;
2615                                 evt->y= (win->sizey-1) - cy;
2616                                 
2617                                 event.x= evt->x;
2618                                 event.y= evt->y;
2619
2620                                 event.type= MOUSEMOVE;
2621
2622                                 /* some painting operators want accurate mouse events, they can
2623                                  * handle in between mouse move moves, others can happily ignore
2624                                  * them for better performance */
2625                                 if(lastevent && lastevent->type == MOUSEMOVE)
2626                                         lastevent->type = INBETWEEN_MOUSEMOVE;
2627
2628                                 update_tablet_data(win, &event);
2629                                 wm_event_add(win, &event);
2630
2631                                 //printf("sending MOUSEMOVE %d %d\n", event.x, event.y);
2632                                 
2633                                 /* also add to other window if event is there, this makes overdraws disappear nicely */
2634                                 /* it remaps mousecoord to other window in event */
2635                                 owin= wm_event_cursor_other_windows(wm, win, &event);
2636                                 if(owin) {
2637                                         wmEvent oevent= *(owin->eventstate);
2638                                         
2639                                         oevent.x=owin->eventstate->x= event.x;
2640                                         oevent.y=owin->eventstate->y= event.y;
2641                                         oevent.type= MOUSEMOVE;
2642                                         
2643                                         update_tablet_data(owin, &oevent);
2644                                         wm_event_add(owin, &oevent);
2645                                 }
2646                                 
2647                         }
2648                         break;
2649                 }
2650                 case GHOST_kEventTrackpad: {
2651                         GHOST_TEventTrackpadData * pd = customdata;
2652                         switch (pd->subtype) {
2653                                 case GHOST_kTrackpadEventMagnify:
2654                                         event.type = MOUSEZOOM;
2655                                         break;
2656                                 case GHOST_kTrackpadEventRotate:
2657                                         event.type = MOUSEROTATE;
2658                                         break;
2659                                 case GHOST_kTrackpadEventScroll:
2660                                 default:
2661                                         event.type= MOUSEPAN;
2662                                         break;
2663                         }
2664
2665                         {
2666                                 int cx, cy;
2667                                 GHOST_ScreenToClient(win->ghostwin, pd->x, pd->y, &cx, &cy);
2668                                 event.x= evt->x= cx;
2669                                 event.y= evt->y= (win->sizey-1) - cy;
2670                         }
2671
2672                         // Use prevx/prevy so we can calculate the delta later
2673                         event.prevx= event.x - pd->deltaX;
2674                         event.prevy= event.y - (-pd->deltaY);
2675                         
2676                         update_tablet_data(win, &event);
2677                         wm_event_add(win, &event);
2678                         break;
2679                 }
2680                 /* mouse button */
2681                 case GHOST_kEventButtonDown:
2682                 case GHOST_kEventButtonUp: {
2683                         GHOST_TEventButtonData *bd= customdata;
2684
2685                         /* Note!, this starts as 0/1 but later is converted to KM_PRESS/KM_RELEASE by tweak */
2686                         event.val= (type==GHOST_kEventButtonDown) ? KM_PRESS:KM_RELEASE;
2687                         
2688                         if (bd->button == GHOST_kButtonMaskLeft)
2689                                 event.type= LEFTMOUSE;
2690                         else if (bd->button == GHOST_kButtonMaskRight)
2691                                 event.type= RIGHTMOUSE;
2692                         else if (bd->button == GHOST_kButtonMaskButton4)
2693                                 event.type= BUTTON4MOUSE;
2694                         else if (bd->button == GHOST_kButtonMaskButton5)
2695                                 event.type= BUTTON5MOUSE;
2696                         else
2697                                 event.type= MIDDLEMOUSE;
2698                         
2699                         if(win->active==0) {
2700                                 int cx, cy;
2701                                 
2702                                 /* entering window, update mouse pos. (ghost sends win-activate *after* the mouseclick in window!) */
2703                                 wm_get_cursor_position(win, &cx, &cy);
2704
2705                                 event.x= evt->x= cx;
2706                                 event.y= evt->y= cy;
2707                         }
2708                         
2709                         /* add to other window if event is there (not to both!) */
2710                         owin= wm_event_cursor_other_windows(wm, win, &event);
2711                         if(owin) {
2712                                 wmEvent oevent= *(owin->eventstate);
2713                                 
2714                                 oevent.x= event.x;
2715                                 oevent.y= event.y;
2716                                 oevent.type= event.type;
2717                                 oevent.val= event.val;
2718                                 
2719                                 update_tablet_data(owin, &oevent);
2720                                 wm_event_add(owin, &oevent);
2721                         }
2722                         else {
2723                                 update_tablet_data(win, &event);
2724                                 wm_event_add(win, &event);
2725                         }
2726                         
2727                         break;
2728                 }
2729                 /* keyboard */
2730                 case GHOST_kEventKeyDown:
2731                 case GHOST_kEventKeyUp: {
2732                         GHOST_TEventKeyData *kd= customdata;
2733                         event.type= convert_key(kd->key);
2734                         event.ascii= kd->ascii;
2735                         memcpy(event.utf8_buf, kd->utf8_buf,sizeof(event.utf8_buf));/* might be not null terminated*/
2736                         event.val= (type==GHOST_kEventKeyDown)?KM_PRESS:KM_RELEASE;
2737                         
2738                         /* exclude arrow keys, esc, etc from text input */
2739                         if(type==GHOST_kEventKeyUp) {
2740                                 event.ascii= '\0';
2741
2742                                 /* ghost should do this already for key up */
2743                                 if (event.utf8_buf[0]) {
2744                                         printf("%s: ghost on your platform is misbehaving, utf8 events on key up!\n", __func__);
2745                                 }
2746                                 event.utf8_buf[0]= '\0';
2747                         }
2748                         else {
2749                                 if (event.ascii<32 && event.ascii > 0)
2750                                         event.ascii= '\0';
2751                                 if (event.utf8_buf[0]<32 && event.utf8_buf[0] > 0)
2752                                         event.utf8_buf[0]= '\0';
2753                         }
2754
2755                         if (event.utf8_buf[0]) {
2756                                 if (BLI_str_utf8_size(event.utf8_buf) == -1) {
2757                                         printf("%s: ghost detected an invalid unicode character '%d'!\n",
2758                                                __func__, (int)(unsigned char)event.utf8_buf[0]);
2759                                         event.utf8_buf[0]= '\0';
2760                                 }
2761                         }
2762
2763     &