1c446346dc14f752771be33c67780665902894fe
[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                 iterprop= RNA_struct_iterator_property(op->type->srna);
755
756                 RNA_PROP_BEGIN(op->ptr, itemptr, iterprop) {
757                         PropertyRNA *prop= itemptr.data;
758                         if((RNA_property_flag(prop) & PROP_SKIP_SAVE) == 0) {
759                                 if (!RNA_property_is_set(op->ptr, prop)) { /* don't override a setting already set */
760                                         const char *identifier= RNA_property_identifier(prop);
761                                         IDProperty *idp_src= IDP_GetPropertyFromGroup(op->type->last_properties, identifier);
762                                         if(idp_src) {
763                                                 IDProperty *idp_dst = IDP_CopyProperty(idp_src);
764
765                                                 /* note - in the future this may need to be done recursively,
766                                                  * but for now RNA doesn't access nested operators */
767                                                 idp_dst->flag |= IDP_FLAG_GHOST;
768
769                                                 IDP_ReplaceInGroup(op->properties, idp_dst);
770                                                 change= TRUE;
771                                         }
772                                 }
773                         }
774                 }
775                 RNA_PROP_END;
776         }
777
778         return change;
779 }
780
781 int WM_operator_last_properties_store(wmOperator *op)
782 {
783         if (op->type->last_properties) {
784                 IDP_FreeProperty(op->type->last_properties);
785                 MEM_freeN(op->type->last_properties);
786                 op->type->last_properties = NULL;
787         }
788
789         if (op->properties) {
790                 op->type->last_properties = IDP_CopyProperty(op->properties);
791                 return TRUE;
792         }
793         else {
794                 return FALSE;
795         }
796 }
797
798 static int wm_operator_invoke(bContext *C, wmOperatorType *ot, wmEvent *event, PointerRNA *properties, ReportList *reports, short poll_only)
799 {
800         wmWindowManager *wm= CTX_wm_manager(C);
801         int retval= OPERATOR_PASS_THROUGH;
802
803         /* this is done because complicated setup is done to call this function that is better not duplicated */
804         if(poll_only)
805                 return WM_operator_poll(C, ot);
806
807         if(WM_operator_poll(C, ot)) {
808                 wmOperator *op= wm_operator_create(wm, ot, properties, reports); /* if reports==NULL, theyll be initialized */
809                 const short is_nested_call = (wm->op_undo_depth != 0);
810                 
811                 /* initialize setting from previous run */
812                 if(!is_nested_call) { /* not called by py script */
813                         WM_operator_last_properties_init(op);
814                 }
815
816                 if((G.f & G_DEBUG) && event && event->type!=MOUSEMOVE)
817                         printf("handle evt %d win %d op %s\n", event?event->type:0, CTX_wm_screen(C)->subwinactive, ot->idname); 
818                 
819                 if(op->type->invoke && event) {
820                         wm_region_mouse_co(C, event);
821
822                         if(op->type->flag & OPTYPE_UNDO)
823                                 wm->op_undo_depth++;
824
825                         retval= op->type->invoke(C, op, event);
826                         OPERATOR_RETVAL_CHECK(retval);
827
828                         if(op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
829                                 wm->op_undo_depth--;
830                 }
831                 else if(op->type->exec) {
832                         if(op->type->flag & OPTYPE_UNDO)
833                                 wm->op_undo_depth++;
834
835                         retval= op->type->exec(C, op);
836                         OPERATOR_RETVAL_CHECK(retval);
837
838                         if(op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
839                                 wm->op_undo_depth--;
840                 }
841                 else {
842                         /* debug, important to leave a while, should never happen */
843                         printf("invalid operator call '%s'\n", ot->idname);
844                 }
845                 
846                 /* Note, if the report is given as an argument then assume the caller will deal with displaying them
847                  * currently python only uses this */
848                 if (!(retval & OPERATOR_HANDLED) && (retval & (OPERATOR_FINISHED|OPERATOR_CANCELLED))) {
849                         /* only show the report if the report list was not given in the function */
850                         wm_operator_reports(C, op, retval, (reports != NULL));
851                 }
852
853                 if(retval & OPERATOR_HANDLED)
854                         ; /* do nothing, wm_operator_exec() has been called somewhere */
855                 else if(retval & OPERATOR_FINISHED) {
856                         if (!is_nested_call) { /* not called by py script */
857                                 WM_operator_last_properties_store(op);
858                         }
859                         wm_operator_finished(C, op, 0);
860                 }
861                 else if(retval & OPERATOR_RUNNING_MODAL) {
862                         /* grab cursor during blocking modal ops (X11)
863                          * Also check for macro
864                          */
865                         if(ot->flag & OPTYPE_BLOCKING || (op->opm && op->opm->type->flag & OPTYPE_BLOCKING)) {
866                                 int bounds[4] = {-1,-1,-1,-1};
867                                 int wrap;
868
869                                 if (op->opm) {
870                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
871                                                ((op->opm->flag & OP_GRAB_POINTER) || (op->opm->type->flag & OPTYPE_GRAB_POINTER));
872                                 }
873                                 else {
874                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
875                                                ((op->flag & OP_GRAB_POINTER) || (ot->flag & OPTYPE_GRAB_POINTER));
876                                 }
877
878                                 /* exception, cont. grab in header is annoying */
879                                 if(wrap) {
880                                         ARegion *ar= CTX_wm_region(C);
881                                         if(ar && ar->regiontype == RGN_TYPE_HEADER) {
882                                                 wrap= FALSE;
883                                         }
884                                 }
885
886                                 if(wrap) {
887                                         rcti *winrect= NULL;
888                                         ARegion *ar= CTX_wm_region(C);
889                                         ScrArea *sa= CTX_wm_area(C);
890
891                                         if (ar && ar->regiontype == RGN_TYPE_WINDOW && event &&
892                                             BLI_in_rcti(&ar->winrct, event->x, event->y))
893                                         {
894                                                 winrect= &ar->winrct;
895                                         }
896                                         else if(sa) {
897                                                 winrect= &sa->totrct;
898                                         }
899
900                                         if(winrect) {
901                                                 bounds[0]= winrect->xmin;
902                                                 bounds[1]= winrect->ymax;
903                                                 bounds[2]= winrect->xmax;
904                                                 bounds[3]= winrect->ymin;
905                                         }
906                                 }
907
908                                 WM_cursor_grab(CTX_wm_window(C), wrap, FALSE, bounds);
909                         }
910
911                         /* cancel UI handlers, typically tooltips that can hang around
912                          * while dragging the view or worse, that stay there permanently
913                          * after the modal operator has swallowed all events and passed
914                          * none to the UI handler */
915                         wm_handler_ui_cancel(C);
916                 }
917                 else
918                         WM_operator_free(op);
919         }
920
921         return retval;
922 }
923
924 /* WM_operator_name_call is the main accessor function
925  * this is for python to access since its done the operator lookup
926  * 
927  * invokes operator in context */
928 static int wm_operator_call_internal(bContext *C, wmOperatorType *ot, PointerRNA *properties, ReportList *reports,
929                                      short context, short poll_only)
930 {
931         wmWindow *window= CTX_wm_window(C);
932         wmEvent *event;
933         
934         int retval;
935
936         CTX_wm_operator_poll_msg_set(C, NULL);
937
938         /* dummie test */
939         if(ot && C) {
940                 switch(context) {
941                         case WM_OP_INVOKE_DEFAULT:
942                         case WM_OP_INVOKE_REGION_WIN:
943                         case WM_OP_INVOKE_AREA:
944                         case WM_OP_INVOKE_SCREEN:
945                                 /* window is needed for invoke, cancel operator */
946                                 if (window == NULL)
947                                         return 0;
948                                 else
949                                         event= window->eventstate;
950                                 break;
951                         default:
952                                 event = NULL;
953                 }
954
955                 switch(context) {
956                         
957                         case WM_OP_EXEC_REGION_WIN:
958                         case WM_OP_INVOKE_REGION_WIN: 
959                         case WM_OP_EXEC_REGION_CHANNELS:
960                         case WM_OP_INVOKE_REGION_CHANNELS:
961                         case WM_OP_EXEC_REGION_PREVIEW:
962                         case WM_OP_INVOKE_REGION_PREVIEW:
963                         {
964                                 /* forces operator to go to the region window/channels/preview, for header menus
965                                  * but we stay in the same region if we are already in one 
966                                  */
967                                 ARegion *ar= CTX_wm_region(C);
968                                 ScrArea *area= CTX_wm_area(C);
969                                 int type = RGN_TYPE_WINDOW;
970                                 
971                                 switch (context) {
972                                         case WM_OP_EXEC_REGION_CHANNELS:
973                                         case WM_OP_INVOKE_REGION_CHANNELS:
974                                                 type = RGN_TYPE_CHANNELS;
975                                                 break;
976                                         
977                                         case WM_OP_EXEC_REGION_PREVIEW:
978                                         case WM_OP_INVOKE_REGION_PREVIEW:
979                                                 type = RGN_TYPE_PREVIEW;
980                                                 break;
981                                         
982                                         case WM_OP_EXEC_REGION_WIN:
983                                         case WM_OP_INVOKE_REGION_WIN: 
984                                         default:
985                                                 type = RGN_TYPE_WINDOW;
986                                                 break;
987                                 }
988                                 
989                                 if(!(ar && ar->regiontype == type) && area) {
990                                         ARegion *ar1= BKE_area_find_region_type(area, type);
991                                         if(ar1)
992                                                 CTX_wm_region_set(C, ar1);
993                                 }
994                                 
995                                 retval= wm_operator_invoke(C, ot, event, properties, reports, poll_only);
996                                 
997                                 /* set region back */
998                                 CTX_wm_region_set(C, ar);
999                                 
1000                                 return retval;
1001                         }
1002                         case WM_OP_EXEC_AREA:
1003                         case WM_OP_INVOKE_AREA:
1004                         {
1005                                         /* remove region from context */
1006                                 ARegion *ar= CTX_wm_region(C);
1007
1008                                 CTX_wm_region_set(C, NULL);
1009                                 retval= wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1010                                 CTX_wm_region_set(C, ar);
1011
1012                                 return retval;
1013                         }
1014                         case WM_OP_EXEC_SCREEN:
1015                         case WM_OP_INVOKE_SCREEN:
1016                         {
1017                                 /* remove region + area from context */
1018                                 ARegion *ar= CTX_wm_region(C);
1019                                 ScrArea *area= CTX_wm_area(C);
1020
1021                                 CTX_wm_region_set(C, NULL);
1022                                 CTX_wm_area_set(C, NULL);
1023                                 retval= wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1024                                 CTX_wm_area_set(C, area);
1025                                 CTX_wm_region_set(C, ar);
1026
1027                                 return retval;
1028                         }
1029                         case WM_OP_EXEC_DEFAULT:
1030                         case WM_OP_INVOKE_DEFAULT:
1031                                 return wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1032                 }
1033         }
1034         
1035         return 0;
1036 }
1037
1038
1039 /* invokes operator in context */
1040 int WM_operator_name_call(bContext *C, const char *opstring, int context, PointerRNA *properties)
1041 {
1042         wmOperatorType *ot= WM_operatortype_find(opstring, 0);
1043         if(ot)
1044                 return wm_operator_call_internal(C, ot, properties, NULL, context, FALSE);
1045
1046         return 0;
1047 }
1048
1049 /* Similar to WM_operator_name_call called with WM_OP_EXEC_DEFAULT context.
1050  * - wmOperatorType is used instead of operator name since python already has the operator type
1051  * - poll() must be called by python before this runs.
1052  * - reports can be passed to this function (so python can report them as exceptions)
1053  */
1054 int WM_operator_call_py(bContext *C, wmOperatorType *ot, int context, PointerRNA *properties, ReportList *reports)
1055 {
1056         int retval= OPERATOR_CANCELLED;
1057
1058 #if 0
1059         wmOperator *op;
1060         op= wm_operator_create(wm, ot, properties, reports);
1061
1062         if (op->type->exec) {
1063                 if(op->type->flag & OPTYPE_UNDO)
1064                         wm->op_undo_depth++;
1065
1066                 retval= op->type->exec(C, op);
1067                 OPERATOR_RETVAL_CHECK(retval);
1068
1069                 if(op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1070                         wm->op_undo_depth--;
1071         }
1072         else
1073                 printf("error \"%s\" operator has no exec function, python cannot call it\n", op->type->name);
1074 #endif
1075
1076         retval= wm_operator_call_internal(C, ot, properties, reports, context, FALSE);
1077         
1078         /* keep the reports around if needed later */
1079         if (    (retval & OPERATOR_RUNNING_MODAL) ||
1080                         ((retval & OPERATOR_FINISHED) && wm_operator_register_check(CTX_wm_manager(C), ot))
1081         ) {
1082                 reports->flag |= RPT_FREE; /* let blender manage freeing */
1083         }
1084         
1085         return retval;
1086 }
1087
1088
1089 /* ********************* handlers *************** */
1090
1091 /* future extra customadata free? */
1092 void wm_event_free_handler(wmEventHandler *handler)
1093 {
1094         MEM_freeN(handler);
1095 }
1096
1097 /* only set context when area/region is part of screen */
1098 static void wm_handler_op_context(bContext *C, wmEventHandler *handler)
1099 {
1100         bScreen *screen= CTX_wm_screen(C);
1101         
1102         if(screen && handler->op) {
1103                 if(handler->op_area==NULL)
1104                         CTX_wm_area_set(C, NULL);
1105                 else {
1106                         ScrArea *sa;
1107                         
1108                         for(sa= screen->areabase.first; sa; sa= sa->next)
1109                                 if(sa==handler->op_area)
1110                                         break;
1111                         if(sa==NULL) {
1112                                 /* when changing screen layouts with running modal handlers (like render display), this
1113                                  * is not an error to print */
1114                                 if(handler->op==NULL)
1115                                         printf("internal error: handler (%s) has invalid area\n", handler->op->type->idname);
1116                         }
1117                         else {
1118                                 ARegion *ar;
1119                                 CTX_wm_area_set(C, sa);
1120                                 for(ar= sa->regionbase.first; ar; ar= ar->next)
1121                                         if(ar==handler->op_region)
1122                                                 break;
1123                                 /* XXX no warning print here, after full-area and back regions are remade */
1124                                 if(ar)
1125                                         CTX_wm_region_set(C, ar);
1126                         }
1127                 }
1128         }
1129 }
1130
1131 /* called on exit or remove area, only here call cancel callback */
1132 void WM_event_remove_handlers(bContext *C, ListBase *handlers)
1133 {
1134         wmEventHandler *handler;
1135         wmWindowManager *wm= CTX_wm_manager(C);
1136         
1137         /* C is zero on freeing database, modal handlers then already were freed */
1138         while((handler=handlers->first)) {
1139                 BLI_remlink(handlers, handler);
1140                 
1141                 if(handler->op) {
1142                         if(handler->op->type->cancel) {
1143                                 ScrArea *area= CTX_wm_area(C);
1144                                 ARegion *region= CTX_wm_region(C);
1145                                 
1146                                 wm_handler_op_context(C, handler);
1147
1148                                 if(handler->op->type->flag & OPTYPE_UNDO)
1149                                         wm->op_undo_depth++;
1150
1151                                 handler->op->type->cancel(C, handler->op);
1152
1153                                 if(handler->op->type->flag & OPTYPE_UNDO)
1154                                         wm->op_undo_depth--;
1155
1156                                 CTX_wm_area_set(C, area);
1157                                 CTX_wm_region_set(C, region);
1158                         }
1159
1160                         WM_cursor_ungrab(CTX_wm_window(C));
1161                         WM_operator_free(handler->op);
1162                 }
1163                 else if(handler->ui_remove) {
1164                         ScrArea *area= CTX_wm_area(C);
1165                         ARegion *region= CTX_wm_region(C);
1166                         ARegion *menu= CTX_wm_menu(C);
1167                         
1168                         if(handler->ui_area) CTX_wm_area_set(C, handler->ui_area);
1169                         if(handler->ui_region) CTX_wm_region_set(C, handler->ui_region);
1170                         if(handler->ui_menu) CTX_wm_menu_set(C, handler->ui_menu);
1171
1172                         handler->ui_remove(C, handler->ui_userdata);
1173
1174                         CTX_wm_area_set(C, area);
1175                         CTX_wm_region_set(C, region);
1176                         CTX_wm_menu_set(C, menu);
1177                 }
1178
1179                 wm_event_free_handler(handler);
1180         }
1181 }
1182
1183 /* do userdef mappings */
1184 int WM_userdef_event_map(int kmitype)
1185 {
1186         switch(kmitype) {
1187                 case SELECTMOUSE:
1188                         if(U.flag & USER_LMOUSESELECT)
1189                                 return LEFTMOUSE;
1190                         else
1191                                 return RIGHTMOUSE;
1192                         
1193                 case ACTIONMOUSE:
1194                         if(U.flag & USER_LMOUSESELECT)
1195                                 return RIGHTMOUSE;
1196                         else
1197                                 return LEFTMOUSE;
1198                         
1199                 case WHEELOUTMOUSE:
1200                         if(U.uiflag & USER_WHEELZOOMDIR)
1201                                 return WHEELUPMOUSE;
1202                         else
1203                                 return WHEELDOWNMOUSE;
1204                         
1205                 case WHEELINMOUSE:
1206                         if(U.uiflag & USER_WHEELZOOMDIR)
1207                                 return WHEELDOWNMOUSE;
1208                         else
1209                                 return WHEELUPMOUSE;
1210                         
1211                 case EVT_TWEAK_A:
1212                         if(U.flag & USER_LMOUSESELECT)
1213                                 return EVT_TWEAK_R;
1214                         else
1215                                 return EVT_TWEAK_L;
1216                         
1217                 case EVT_TWEAK_S:
1218                         if(U.flag & USER_LMOUSESELECT)
1219                                 return EVT_TWEAK_L;
1220                         else
1221                                 return EVT_TWEAK_R;
1222         }
1223         
1224         return kmitype;
1225 }
1226
1227 static void wm_eventemulation(wmEvent *event)
1228 {
1229         static int mmb_emulated = 0; /* this should be in a data structure somwhere */
1230         
1231         /* middlemouse emulation */
1232         if(U.flag & USER_TWOBUTTONMOUSE) {
1233                 if(event->type == LEFTMOUSE && (event->alt || mmb_emulated == KM_PRESS)) {
1234                         event->type = MIDDLEMOUSE;
1235                         event->alt = 0;
1236                         mmb_emulated = event->val;
1237                 }
1238         }
1239
1240 #ifdef __APPLE__
1241         /* rightmouse emulation */
1242         if(U.flag & USER_TWOBUTTONMOUSE) {
1243                 if(event->type == LEFTMOUSE && (event->oskey || mmb_emulated == KM_PRESS)) {
1244                         event->type = RIGHTMOUSE;
1245                         event->oskey = 0;
1246                         mmb_emulated = event->val;
1247                 }
1248         }
1249 #endif
1250
1251         /* numpad emulation */
1252         if(U.flag & USER_NONUMPAD) {
1253                 switch(event->type) {
1254                         case ZEROKEY: event->type = PAD0; break;
1255                         case ONEKEY: event->type = PAD1; break;
1256                         case TWOKEY: event->type = PAD2; break;
1257                         case THREEKEY: event->type = PAD3; break;
1258                         case FOURKEY: event->type = PAD4; break;
1259                         case FIVEKEY: event->type = PAD5; break;
1260                         case SIXKEY: event->type = PAD6; break;
1261                         case SEVENKEY: event->type = PAD7; break;
1262                         case EIGHTKEY: event->type = PAD8; break;
1263                         case NINEKEY: event->type = PAD9; break;
1264                         case MINUSKEY: event->type = PADMINUS; break;
1265                         case EQUALKEY: event->type = PADPLUSKEY; break;
1266                         case BACKSLASHKEY: event->type = PADSLASHKEY; break;
1267                 }
1268         }
1269 }
1270
1271 static int wm_eventmatch(wmEvent *winevent, wmKeyMapItem *kmi)
1272 {
1273         int kmitype= WM_userdef_event_map(kmi->type);
1274
1275         if(kmi->flag & KMI_INACTIVE) return 0;
1276
1277         /* the matching rules */
1278         if(kmitype==KM_TEXTINPUT)
1279                 if(ISTEXTINPUT(winevent->type) && (winevent->ascii || winevent->utf8_buf[0])) return 1;
1280         if(kmitype!=KM_ANY)
1281                 if(winevent->type!=kmitype) return 0;
1282         
1283         if(kmi->val!=KM_ANY)
1284                 if(winevent->val!=kmi->val) return 0;
1285         
1286         /* modifiers also check bits, so it allows modifier order */
1287         if(kmi->shift!=KM_ANY)
1288                 if(winevent->shift != kmi->shift && !(winevent->shift & kmi->shift)) return 0;
1289         if(kmi->ctrl!=KM_ANY)
1290                 if(winevent->ctrl != kmi->ctrl && !(winevent->ctrl & kmi->ctrl)) return 0;
1291         if(kmi->alt!=KM_ANY)
1292                 if(winevent->alt != kmi->alt && !(winevent->alt & kmi->alt)) return 0;
1293         if(kmi->oskey!=KM_ANY)
1294                 if(winevent->oskey != kmi->oskey && !(winevent->oskey & kmi->oskey)) return 0;
1295         
1296         if(kmi->keymodifier)
1297                 if(winevent->keymodifier!=kmi->keymodifier) return 0;
1298                 
1299         /* key modifiers always check when event has it */
1300         /* otherwise regular keypresses with keymodifier still work */
1301         if(winevent->keymodifier)
1302                 if(ISTEXTINPUT(winevent->type)) 
1303                         if(winevent->keymodifier!=kmi->keymodifier) return 0;
1304         
1305         return 1;
1306 }
1307
1308
1309 /* operator exists */
1310 static void wm_event_modalkeymap(const bContext *C, wmOperator *op, wmEvent *event)
1311 {
1312         /* support for modal keymap in macros */
1313         if (op->opm)
1314                 op = op->opm;
1315
1316         if(op->type->modalkeymap) {
1317                 wmKeyMap *keymap= WM_keymap_active(CTX_wm_manager(C), op->type->modalkeymap);
1318                 wmKeyMapItem *kmi;
1319
1320                 for(kmi= keymap->items.first; kmi; kmi= kmi->next) {
1321                         if(wm_eventmatch(event, kmi)) {
1322                                         
1323                                 event->type= EVT_MODAL_MAP;
1324                                 event->val= kmi->propvalue;
1325                         }
1326                 }
1327         }
1328 }
1329
1330 /* Warning: this function removes a modal handler, when finished */
1331 static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHandler *handler,
1332                                     wmEvent *event, PointerRNA *properties)
1333 {
1334         int retval= OPERATOR_PASS_THROUGH;
1335         
1336         /* derived, modal or blocking operator */
1337         if(handler->op) {
1338                 wmOperator *op= handler->op;
1339                 wmOperatorType *ot= op->type;
1340
1341                 if(ot->modal) {
1342                         /* we set context to where modal handler came from */
1343                         wmWindowManager *wm= CTX_wm_manager(C);
1344                         ScrArea *area= CTX_wm_area(C);
1345                         ARegion *region= CTX_wm_region(C);
1346                         
1347                         wm_handler_op_context(C, handler);
1348                         wm_region_mouse_co(C, event);
1349                         wm_event_modalkeymap(C, op, event);
1350                         
1351                         if(ot->flag & OPTYPE_UNDO)
1352                                 wm->op_undo_depth++;
1353
1354                         retval= ot->modal(C, op, event);
1355                         OPERATOR_RETVAL_CHECK(retval);
1356
1357                         /* when this is _not_ the case the modal modifier may have loaded
1358                          * a new blend file (demo mode does this), so we have to assume
1359                          * the event, operator etc have all been freed. - campbell */
1360                         if(CTX_wm_manager(C) == wm) {
1361
1362                                 if(ot->flag & OPTYPE_UNDO)
1363                                         wm->op_undo_depth--;
1364
1365                                 /* putting back screen context, reval can pass trough after modal failures! */
1366                                 if((retval & OPERATOR_PASS_THROUGH) || wm_event_always_pass(event)) {
1367                                         CTX_wm_area_set(C, area);
1368                                         CTX_wm_region_set(C, region);
1369                                 }
1370                                 else {
1371                                         /* this special cases is for areas and regions that get removed */
1372                                         CTX_wm_area_set(C, NULL);
1373                                         CTX_wm_region_set(C, NULL);
1374                                 }
1375
1376                                 if(retval & (OPERATOR_CANCELLED|OPERATOR_FINISHED))
1377                                         wm_operator_reports(C, op, retval, FALSE);
1378
1379                                 if(retval & OPERATOR_FINISHED) {
1380                                         wm_operator_finished(C, op, 0);
1381                                         handler->op= NULL;
1382                                 }
1383                                 else if(retval & (OPERATOR_CANCELLED|OPERATOR_FINISHED)) {
1384                                         WM_operator_free(op);
1385                                         handler->op= NULL;
1386                                 }
1387
1388                                 /* remove modal handler, operator itself should have been canceled and freed */
1389                                 if(retval & (OPERATOR_CANCELLED|OPERATOR_FINISHED)) {
1390                                         WM_cursor_ungrab(CTX_wm_window(C));
1391
1392                                         BLI_remlink(handlers, handler);
1393                                         wm_event_free_handler(handler);
1394
1395                                         /* prevent silly errors from operator users */
1396                                         //retval &= ~OPERATOR_PASS_THROUGH;
1397                                 }
1398                         }
1399                         
1400                 }
1401                 else
1402                         printf("wm_handler_operator_call error\n");
1403         }
1404         else {
1405                 wmOperatorType *ot= WM_operatortype_find(event->keymap_idname, 0);
1406
1407                 if(ot)
1408                         retval= wm_operator_invoke(C, ot, event, properties, NULL, FALSE);
1409         }
1410         /* Finished and pass through flag as handled */
1411
1412         /* Finished and pass through flag as handled */
1413         if(retval == (OPERATOR_FINISHED|OPERATOR_PASS_THROUGH))
1414                 return WM_HANDLER_HANDLED;
1415
1416         /* Modal unhandled, break */
1417         if(retval == (OPERATOR_PASS_THROUGH|OPERATOR_RUNNING_MODAL))
1418                 return (WM_HANDLER_BREAK|WM_HANDLER_MODAL);
1419
1420         if(retval & OPERATOR_PASS_THROUGH)
1421                 return WM_HANDLER_CONTINUE;
1422
1423         return WM_HANDLER_BREAK;
1424 }
1425
1426 /* fileselect handlers are only in the window queue, so it's save to switch screens or area types */
1427 static int wm_handler_fileselect_call(bContext *C, ListBase *handlers, wmEventHandler *handler, wmEvent *event)
1428 {
1429         wmWindowManager *wm= CTX_wm_manager(C);
1430         SpaceFile *sfile;
1431         int action= WM_HANDLER_CONTINUE;
1432         
1433         if(event->type != EVT_FILESELECT)
1434                 return action;
1435         if(handler->op != (wmOperator *)event->customdata)
1436                 return action;
1437         
1438         switch(event->val) {
1439                 case EVT_FILESELECT_OPEN: 
1440                 case EVT_FILESELECT_FULL_OPEN: 
1441                         {       
1442                                 ScrArea *sa;
1443                                 
1444                                 /* sa can be null when window A is active, but mouse is over window B */
1445                                 /* in this case, open file select in original window A */
1446                                 if (handler->op_area == NULL) {
1447                                         bScreen *screen = CTX_wm_screen(C);
1448                                         sa = (ScrArea *)screen->areabase.first;
1449                                 }
1450                                 else {
1451                                         sa = handler->op_area;
1452                                 }
1453                                         
1454                                 if(event->val==EVT_FILESELECT_OPEN) {
1455                                         ED_area_newspace(C, sa, SPACE_FILE); /* 'sa' is modified in-place */
1456                                 }
1457                                 else {
1458                                         sa= ED_screen_full_newspace(C, sa, SPACE_FILE); /* sets context */
1459                                 }
1460
1461                                 /* note, getting the 'sa' back from the context causes a nasty bug where the newly created
1462                                  * 'sa' != CTX_wm_area(C). removed the line below and set 'sa' in the 'if' above */
1463                                 /* sa = CTX_wm_area(C); */
1464
1465                                 /* settings for filebrowser, sfile is not operator owner but sends events */
1466                                 sfile= (SpaceFile*)sa->spacedata.first;
1467                                 sfile->op= handler->op;
1468
1469                                 ED_fileselect_set_params(sfile);
1470                                 
1471                                 action= WM_HANDLER_BREAK;
1472                         }
1473                         break;
1474                         
1475                 case EVT_FILESELECT_EXEC:
1476                 case EVT_FILESELECT_CANCEL:
1477                 case EVT_FILESELECT_EXTERNAL_CANCEL:
1478                         {
1479                                 /* XXX validate area and region? */
1480                                 bScreen *screen= CTX_wm_screen(C);
1481
1482                                 /* remlink now, for load file case before removing*/
1483                                 BLI_remlink(handlers, handler);
1484                                 
1485                                 if(event->val!=EVT_FILESELECT_EXTERNAL_CANCEL) {
1486                                         if(screen != handler->filescreen) {
1487                                                 ED_screen_full_prevspace(C, CTX_wm_area(C));
1488                                         }
1489                                         else {
1490                                                 ED_area_prevspace(C, CTX_wm_area(C));
1491                                         }
1492                                 }
1493                                 
1494                                 wm_handler_op_context(C, handler);
1495
1496                                 /* needed for uiPupMenuReports */
1497
1498                                 if(event->val==EVT_FILESELECT_EXEC) {
1499 #if 0                           // use REDALERT now
1500
1501                                         /* a bit weak, might become arg for WM_event_fileselect? */
1502                                         /* XXX also extension code in image-save doesnt work for this yet */
1503                                         if (RNA_struct_find_property(handler->op->ptr, "check_existing") && 
1504                                                         RNA_boolean_get(handler->op->ptr, "check_existing")) {
1505                                                 char *path= RNA_string_get_alloc(handler->op->ptr, "filepath", NULL, 0);
1506                                                 /* this gives ownership to pupmenu */
1507                                                 uiPupMenuSaveOver(C, handler->op, (path)? path: "");
1508                                                 if(path)
1509                                                         MEM_freeN(path);
1510                                         }
1511                                         else
1512 #endif
1513                                         {
1514                                                 int retval;
1515                                                 
1516                                                 if(handler->op->type->flag & OPTYPE_UNDO)
1517                                                         wm->op_undo_depth++;
1518
1519                                                 retval= handler->op->type->exec(C, handler->op);
1520
1521                                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1522                                                 if(handler->op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1523                                                         wm->op_undo_depth--;
1524                                                 
1525                                                 if (retval & OPERATOR_FINISHED)
1526                                                         if(G.f & G_DEBUG)
1527                                                                 wm_operator_print(C, handler->op);
1528                                                 
1529                                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1530                                                 if(CTX_wm_manager(C) == wm && wm->op_undo_depth == 0)
1531                                                         if(handler->op->type->flag & OPTYPE_UNDO)
1532                                                                 ED_undo_push_op(C, handler->op);
1533
1534                                                 if(handler->op->reports->list.first) {
1535
1536                                                         /* FIXME, temp setting window, this is really bad!
1537                                                          * only have because lib linking errors need to be seen by users :(
1538                                                          * it can be removed without breaking anything but then no linking errors - campbell */
1539                                                         wmWindow *win_prev= CTX_wm_window(C);
1540                                                         ScrArea *area_prev= CTX_wm_area(C);
1541                                                         ARegion *ar_prev= CTX_wm_region(C);
1542
1543                                                         if(win_prev==NULL)
1544                                                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
1545
1546                                                         handler->op->reports->printlevel = RPT_WARNING;
1547                                                         uiPupMenuReports(C, handler->op->reports);
1548
1549                                                         /* XXX - copied from 'wm_operator_finished()' */
1550                                                         /* add reports to the global list, otherwise they are not seen */
1551                                                         BLI_movelisttolist(&CTX_wm_reports(C)->list, &handler->op->reports->list);
1552
1553                                                         CTX_wm_window_set(C, win_prev);
1554                                                         CTX_wm_area_set(C, area_prev);
1555                                                         CTX_wm_region_set(C, ar_prev);
1556                                                 }
1557
1558                                                 if (retval & OPERATOR_FINISHED) {
1559                                                         WM_operator_last_properties_store(handler->op);
1560                                                 }
1561
1562                                                 WM_operator_free(handler->op);
1563                                         }
1564                                 }
1565                                 else {
1566                                         if(handler->op->type->cancel) {
1567                                                 if(handler->op->type->flag & OPTYPE_UNDO)
1568                                                         wm->op_undo_depth++;
1569
1570                                                 handler->op->type->cancel(C, handler->op);
1571
1572                                                 if(handler->op->type->flag & OPTYPE_UNDO)
1573                                                         wm->op_undo_depth--;
1574                                         }
1575
1576                                         WM_operator_free(handler->op);
1577                                 }
1578
1579                                 CTX_wm_area_set(C, NULL);
1580                                 
1581                                 wm_event_free_handler(handler);
1582                                 
1583                                 action= WM_HANDLER_BREAK;
1584                         }
1585                         break;
1586         }
1587         
1588         return action;
1589 }
1590
1591 static int handler_boundbox_test(wmEventHandler *handler, wmEvent *event)
1592 {
1593         if(handler->bbwin) {
1594                 if(handler->bblocal) {
1595                         rcti rect= *handler->bblocal;
1596                         BLI_translate_rcti(&rect, handler->bbwin->xmin, handler->bbwin->ymin);
1597
1598                         if(BLI_in_rcti(&rect, event->x, event->y))
1599                                 return 1;
1600                         else if(event->type==MOUSEMOVE && BLI_in_rcti(&rect, event->prevx, event->prevy))
1601                                 return 1;
1602                         else
1603                                 return 0;
1604                 }
1605                 else {
1606                         if(BLI_in_rcti(handler->bbwin, event->x, event->y))
1607                                 return 1;
1608                         else if(event->type==MOUSEMOVE && BLI_in_rcti(handler->bbwin, event->prevx, event->prevy))
1609                                 return 1;
1610                         else
1611                                 return 0;
1612                 }
1613         }
1614         return 1;
1615 }
1616
1617 static int wm_action_not_handled(int action)
1618 {
1619         return action == WM_HANDLER_CONTINUE || action == (WM_HANDLER_BREAK|WM_HANDLER_MODAL);
1620 }
1621
1622 static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
1623 {
1624         wmWindowManager *wm= CTX_wm_manager(C);
1625         wmEventHandler *handler, *nexthandler;
1626         int action= WM_HANDLER_CONTINUE;
1627         int always_pass;
1628
1629         if(handlers==NULL) return action;
1630
1631         /* modal handlers can get removed in this loop, we keep the loop this way */
1632         for(handler= handlers->first; handler; handler= nexthandler) {
1633                 
1634                 nexthandler= handler->next;
1635                 
1636                 /* during this loop, ui handlers for nested menus can tag multiple handlers free */
1637                 if(handler->flag & WM_HANDLER_DO_FREE);
1638                         /* optional boundbox */
1639                 else if(handler_boundbox_test(handler, event)) {
1640                         /* in advance to avoid access to freed event on window close */
1641                         always_pass= wm_event_always_pass(event);
1642                 
1643                         /* modal+blocking handler */
1644                         if(handler->flag & WM_HANDLER_BLOCKING)
1645                                 action |= WM_HANDLER_BREAK;
1646
1647                         if(handler->keymap) {
1648                                 wmKeyMap *keymap= WM_keymap_active(wm, handler->keymap);
1649                                 wmKeyMapItem *kmi;
1650                                 
1651                                 if(!keymap->poll || keymap->poll(C)) {
1652                                         for(kmi= keymap->items.first; kmi; kmi= kmi->next) {
1653                                                 if(wm_eventmatch(event, kmi)) {
1654
1655                                                         /* weak, but allows interactive callback to not use rawkey */
1656                                                         event->keymap_idname = kmi->idname;
1657
1658                                                         action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
1659                                                         if(action & WM_HANDLER_BREAK)  /* not always_pass here, it denotes removed handler */
1660                                                                 break;
1661                                                 }
1662                                         }
1663                                 }
1664                         }
1665                         else if(handler->ui_handle) {
1666                                 action |= wm_handler_ui_call(C, handler, event, always_pass);
1667                         }
1668                         else if(handler->type==WM_HANDLER_FILESELECT) {
1669                                 /* screen context changes here */
1670                                 action |= wm_handler_fileselect_call(C, handlers, handler, event);
1671                         }
1672                         else if(handler->dropboxes) {
1673                                 if(event->type==EVT_DROP) {
1674                                         wmDropBox *drop= handler->dropboxes->first;
1675                                         for(; drop; drop= drop->next) {
1676                                                 /* other drop custom types allowed */
1677                                                 if(event->custom==EVT_DATA_LISTBASE) {
1678                                                         ListBase *lb= (ListBase *)event->customdata;
1679                                                         wmDrag *drag;
1680                                                         
1681                                                         for(drag= lb->first; drag; drag= drag->next) {
1682                                                                 if(drop->poll(C, drag, event)) {
1683                                                                         
1684                                                                         drop->copy(drag, drop);
1685                                                                         
1686                                                                         /* free the drags before calling operator */
1687                                                                         BLI_freelistN(event->customdata);
1688                                                                         event->customdata= NULL;
1689                                                                         event->custom= 0;
1690                                                                         
1691                                                                         WM_operator_name_call(C, drop->ot->idname, drop->opcontext, drop->ptr);
1692                                                                         action |= WM_HANDLER_BREAK;
1693                                                                         
1694                                                                         /* XXX fileread case */
1695                                                                         if(CTX_wm_window(C)==NULL)
1696                                                                                 return action;
1697                                                                         
1698                                                                         /* escape from drag loop, got freed */
1699                                                                         break;
1700                                                                 }
1701                                                         }
1702                                                 }
1703                                         }
1704                                 }
1705                         }
1706                         else {
1707                                 /* modal, swallows all */
1708                                 action |= wm_handler_operator_call(C, handlers, handler, event, NULL);
1709                         }
1710
1711                         if(action & WM_HANDLER_BREAK) {
1712                                 if(always_pass)
1713                                         action &= ~WM_HANDLER_BREAK;
1714                                 else
1715                                         break;
1716                         }
1717                 }
1718                 
1719                 /* XXX fileread case, if the wm is freed then the handler's
1720                  * will have been too so the code below need not run. */
1721                 if(CTX_wm_window(C)==NULL) {
1722                         return action;
1723                 }
1724
1725                 /* XXX code this for all modal ops, and ensure free only happens here */
1726                 
1727                 /* modal ui handler can be tagged to be freed */ 
1728                 if(BLI_findindex(handlers, handler) != -1) { /* could be freed already by regular modal ops */
1729                         if(handler->flag & WM_HANDLER_DO_FREE) {
1730                                 BLI_remlink(handlers, handler);
1731                                 wm_event_free_handler(handler);
1732                         }
1733                 }
1734         }
1735
1736         /* test for CLICK event */
1737         if (wm_action_not_handled(action) && event->val == KM_RELEASE) {
1738                 wmWindow *win = CTX_wm_window(C);
1739
1740                 if (win && win->eventstate->prevtype == event->type && win->eventstate->prevval == KM_PRESS) {
1741                         /* test for double click first,
1742                          * note1: this can be problematic because single click operators can get the
1743                          *   double click event but then with old mouse coords which is highly confusing,
1744                          *   so check for mouse moves too.
1745                          * note2: the first click event will be handled but still used to create a
1746                          *   double click event if clicking again quickly.
1747                          *   If no double click events are found it will fallback to a single click.
1748                          *   So a double click event can result in 2 successive single click calls
1749                          *   if its not handled by the keymap - campbell */
1750                         if (    (ABS(event->x - win->eventstate->prevclickx)) <= 2 &&
1751                                         (ABS(event->y - win->eventstate->prevclicky)) <= 2 &&
1752                                         ((PIL_check_seconds_timer() - win->eventstate->prevclicktime) * 1000 < U.dbl_click_time)
1753                         ) {
1754                                 event->val = KM_DBL_CLICK;
1755                                 /* removed this because in cases where we're this is used as a single click
1756                                  * event, this will give old coords,
1757                                  * since the distance is checked above, using new coords should be ok. */
1758                                 //   event->x = win->eventstate->prevclickx;
1759                                 //   event->y = win->eventstate->prevclicky;
1760                                 action |= wm_handlers_do(C, event, handlers);
1761                         }
1762
1763                         if (wm_action_not_handled(action)) {
1764                                 event->val = KM_CLICK;
1765                                 action |= wm_handlers_do(C, event, handlers);
1766                         }
1767
1768
1769                         /* revert value if not handled */
1770                         if (wm_action_not_handled(action)) {
1771                                 event->val = KM_RELEASE;
1772                         }
1773                 }
1774         }
1775         
1776         if(action == (WM_HANDLER_BREAK|WM_HANDLER_MODAL))
1777                 wm_cursor_arrow_move(CTX_wm_window(C), event);
1778
1779         return action;
1780 }
1781
1782 static int wm_event_inside_i(wmEvent *event, rcti *rect)
1783 {
1784         if(wm_event_always_pass(event))
1785                 return 1;
1786         if(BLI_in_rcti(rect, event->x, event->y))
1787                 return 1;
1788         if(event->type==MOUSEMOVE) {
1789                 if( BLI_in_rcti(rect, event->prevx, event->prevy)) {
1790                         return 1;
1791                 }
1792                 return 0;
1793         }
1794         return 0;
1795 }
1796
1797 static ScrArea *area_event_inside(bContext *C, int x, int y)
1798 {
1799         bScreen *screen= CTX_wm_screen(C);
1800         ScrArea *sa;
1801         
1802         if(screen)
1803                 for(sa= screen->areabase.first; sa; sa= sa->next)
1804                         if(BLI_in_rcti(&sa->totrct, x, y))
1805                                 return sa;
1806         return NULL;
1807 }
1808
1809 static ARegion *region_event_inside(bContext *C, int x, int y)
1810 {
1811         bScreen *screen= CTX_wm_screen(C);
1812         ScrArea *area= CTX_wm_area(C);
1813         ARegion *ar;
1814         
1815         if(screen && area)
1816                 for(ar= area->regionbase.first; ar; ar= ar->next)
1817                         if(BLI_in_rcti(&ar->winrct, x, y))
1818                                 return ar;
1819         return NULL;
1820 }
1821
1822 static void wm_paintcursor_tag(bContext *C, wmPaintCursor *pc, ARegion *ar)
1823 {
1824         if(ar) {
1825                 for(; pc; pc= pc->next) {
1826                         if(pc->poll == NULL || pc->poll(C)) {
1827                                 wmWindow *win= CTX_wm_window(C);
1828                                 win->screen->do_draw_paintcursor= 1;
1829                                 wm_tag_redraw_overlay(win, ar);
1830                         }
1831                 }
1832         }
1833 }
1834
1835 /* called on mousemove, check updates for paintcursors */
1836 /* context was set on active area and region */
1837 static void wm_paintcursor_test(bContext *C, wmEvent *event)
1838 {
1839         wmWindowManager *wm= CTX_wm_manager(C);
1840         
1841         if(wm->paintcursors.first) {
1842                 ARegion *ar= CTX_wm_region(C);
1843                 
1844                 if(ar)
1845                         wm_paintcursor_tag(C, wm->paintcursors.first, ar);
1846                 
1847                 /* if previous position was not in current region, we have to set a temp new context */
1848                 if(ar==NULL || !BLI_in_rcti(&ar->winrct, event->prevx, event->prevy)) {
1849                         ScrArea *sa= CTX_wm_area(C);
1850                         
1851                         CTX_wm_area_set(C, area_event_inside(C, event->prevx, event->prevy));
1852                         CTX_wm_region_set(C, region_event_inside(C, event->prevx, event->prevy));
1853
1854                         wm_paintcursor_tag(C, wm->paintcursors.first, CTX_wm_region(C));
1855                         
1856                         CTX_wm_area_set(C, sa);
1857                         CTX_wm_region_set(C, ar);
1858                 }
1859         }
1860 }
1861
1862 static void wm_event_drag_test(wmWindowManager *wm, wmWindow *win, wmEvent *event)
1863 {
1864         if(wm->drags.first==NULL) return;
1865         
1866         if(event->type==MOUSEMOVE)
1867                 win->screen->do_draw_drag= 1;
1868         else if(event->type==ESCKEY) {
1869                 BLI_freelistN(&wm->drags);
1870                 win->screen->do_draw_drag= 1;
1871         }
1872         else if(event->type==LEFTMOUSE && event->val==KM_RELEASE) {
1873                 event->type= EVT_DROP;
1874                 
1875                 /* create customdata, first free existing */
1876                 if(event->customdata) {
1877                         if(event->customdatafree)
1878                                 MEM_freeN(event->customdata);
1879                 }
1880                 
1881                 event->custom= EVT_DATA_LISTBASE;
1882                 event->customdata= &wm->drags;
1883                 event->customdatafree= 1;
1884                 
1885                 /* clear drop icon */
1886                 win->screen->do_draw_drag= 1;
1887                 
1888                 /* restore cursor (disabled, see wm_dragdrop.c) */
1889                 // WM_cursor_restore(win);
1890         }
1891         
1892         /* overlap fails otherwise */
1893         if(win->screen->do_draw_drag)
1894                 if(win->drawmethod == USER_DRAW_OVERLAP)
1895                         win->screen->do_draw= 1;
1896         
1897 }
1898
1899 /* called in main loop */
1900 /* goes over entire hierarchy:  events -> window -> screen -> area -> region */
1901 void wm_event_do_handlers(bContext *C)
1902 {
1903         wmWindowManager *wm= CTX_wm_manager(C);
1904         wmWindow *win;
1905
1906         /* update key configuration before handling events */
1907         WM_keyconfig_update(wm);
1908
1909         for(win= wm->windows.first; win; win= win->next) {
1910                 wmEvent *event;
1911                 
1912                 if( win->screen==NULL )
1913                         wm_event_free_all(win);
1914                 else {
1915                         Scene* scene = win->screen->scene;
1916                         
1917                         if(scene) {
1918                                 int playing = sound_scene_playing(win->screen->scene);
1919                                 
1920                                 if(playing != -1) {
1921                                         CTX_wm_window_set(C, win);
1922                                         CTX_wm_screen_set(C, win->screen);
1923                                         CTX_data_scene_set(C, scene);
1924                                         
1925                                         if(((playing == 1) && (!win->screen->animtimer)) || ((playing == 0) && (win->screen->animtimer))){
1926                                                 ED_screen_animation_play(C, -1, 1);
1927                                         }
1928                                         
1929                                         if(playing == 0) {
1930                                                 float time = sound_sync_scene(scene);
1931                                                 if(finite(time)) {
1932                                                         int ncfra = sound_sync_scene(scene) * (float)FPS + 0.5f;
1933                                                         if(ncfra != scene->r.cfra)      {
1934                                                                 scene->r.cfra = ncfra;
1935                                                                 ED_update_for_newframe(CTX_data_main(C), scene, win->screen, 1);
1936                                                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
1937                                                         }
1938                                                 }
1939                                         }
1940                                         
1941                                         CTX_data_scene_set(C, NULL);
1942                                         CTX_wm_screen_set(C, NULL);
1943                                         CTX_wm_window_set(C, NULL);
1944                                 }
1945                         }
1946                 }
1947                 
1948                 while( (event= win->queue.first) ) {
1949                         int action = WM_HANDLER_CONTINUE;
1950
1951                         if((G.f & G_DEBUG) && event && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE))
1952                                 printf("pass on evt %d val %d\n", event->type, event->val); 
1953                         
1954                         wm_eventemulation(event);
1955
1956                         CTX_wm_window_set(C, win);
1957                         
1958                         /* we let modal handlers get active area/region, also wm_paintcursor_test needs it */
1959                         CTX_wm_area_set(C, area_event_inside(C, event->x, event->y));
1960                         CTX_wm_region_set(C, region_event_inside(C, event->x, event->y));
1961                         
1962                         /* MVC demands to not draw in event handlers... but we need to leave it for ogl selecting etc */
1963                         wm_window_make_drawable(C, win);
1964                         
1965                         wm_region_mouse_co(C, event);
1966
1967                         /* first we do priority handlers, modal + some limited keymaps */
1968                         action |= wm_handlers_do(C, event, &win->modalhandlers);
1969                         
1970                         /* fileread case */
1971                         if(CTX_wm_window(C)==NULL)
1972                                 return;
1973                         
1974                         /* check dragging, creates new event or frees, adds draw tag */
1975                         wm_event_drag_test(wm, win, event);
1976                         
1977                         /* builtin tweak, if action is break it removes tweak */
1978                         wm_tweakevent_test(C, event, action);
1979
1980                         if((action & WM_HANDLER_BREAK) == 0) {
1981                                 ScrArea *sa;
1982                                 ARegion *ar;
1983                                 int doit= 0;
1984         
1985                                 /* Note: setting subwin active should be done here, after modal handlers have been done */
1986                                 if(event->type==MOUSEMOVE) {
1987                                         /* state variables in screen, cursors. Also used in wm_draw.c, fails for modal handlers though */
1988                                         ED_screen_set_subwinactive(C, event);   
1989                                         /* for regions having custom cursors */
1990                                         wm_paintcursor_test(C, event);
1991                                 }
1992                                 else if (event->type==NDOF_MOTION) {
1993                                         win->addmousemove = TRUE;
1994                                 }
1995
1996                                 for(sa= win->screen->areabase.first; sa; sa= sa->next) {
1997                                         if(wm_event_inside_i(event, &sa->totrct)) {
1998                                                 CTX_wm_area_set(C, sa);
1999
2000                                                 if((action & WM_HANDLER_BREAK) == 0) {
2001                                                         for(ar=sa->regionbase.first; ar; ar= ar->next) {
2002                                                                 if(wm_event_inside_i(event, &ar->winrct)) {
2003                                                                         CTX_wm_region_set(C, ar);
2004                                                                         
2005                                                                         /* call even on non mouse events, since the */
2006                                                                         wm_region_mouse_co(C, event);
2007
2008                                                                         /* does polls for drop regions and checks uibuts */
2009                                                                         /* need to be here to make sure region context is true */
2010                                                                         if(ELEM(event->type, MOUSEMOVE, EVT_DROP)) {
2011                                                                                 wm_drags_check_ops(C, event);
2012                                                                         }
2013                                                                         
2014                                                                         action |= wm_handlers_do(C, event, &ar->handlers);
2015
2016                                                                         /* fileread case (python), [#29489] */
2017                                                                         if(CTX_wm_window(C)==NULL)
2018                                                                                 return;
2019
2020                                                                         doit |= (BLI_in_rcti(&ar->winrct, event->x, event->y));
2021                                                                         
2022                                                                         if(action & WM_HANDLER_BREAK)
2023                                                                                 break;
2024                                                                 }
2025                                                         }
2026                                                 }
2027
2028                                                 CTX_wm_region_set(C, NULL);
2029
2030                                                 if((action & WM_HANDLER_BREAK) == 0) {
2031                                                         wm_region_mouse_co(C, event); /* only invalidates event->mval in this case */
2032                                                         action |= wm_handlers_do(C, event, &sa->handlers);
2033                                                 }
2034                                                 CTX_wm_area_set(C, NULL);
2035
2036                                                 /* NOTE: do not escape on WM_HANDLER_BREAK, mousemove needs handled for previous area */
2037                                         }
2038                                 }
2039                                 
2040                                 if((action & WM_HANDLER_BREAK) == 0) {
2041                                         /* also some non-modal handlers need active area/region */
2042                                         CTX_wm_area_set(C, area_event_inside(C, event->x, event->y));
2043                                         CTX_wm_region_set(C, region_event_inside(C, event->x, event->y));
2044
2045                                         wm_region_mouse_co(C, event);
2046
2047                                         action |= wm_handlers_do(C, event, &win->handlers);
2048
2049                                         /* fileread case */
2050                                         if(CTX_wm_window(C)==NULL)
2051                                                 return;
2052                                 }
2053
2054                                 /* XXX hrmf, this gives reliable previous mouse coord for area change, feels bad? 
2055                                  * doing it on ghost queue gives errors when mousemoves go over area borders */
2056                                 if(doit && win->screen && win->screen->subwinactive != win->screen->mainwin) {
2057                                         win->eventstate->prevx= event->x;
2058                                         win->eventstate->prevy= event->y;
2059                                         //printf("win->eventstate->prev = %d %d\n", event->x, event->y);
2060                                 }
2061                                 else {
2062                                         //printf("not setting prev to %d %d\n", event->x, event->y);
2063                                 }
2064                         }
2065                         
2066                         /* store last event for this window */
2067                         /* mousemove and timer events don't overwrite last type */
2068                         if (!ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) && !ISTIMER(event->type)) {
2069                                 if (wm_action_not_handled(action)) {
2070                                         if (win->eventstate->prevtype == event->type) {
2071                                                 /* set click time on first click (press -> release) */
2072                                                 if (win->eventstate->prevval == KM_PRESS && event->val == KM_RELEASE) {
2073                                                         win->eventstate->prevclicktime = PIL_check_seconds_timer();
2074                                                         win->eventstate->prevclickx = event->x;
2075                                                         win->eventstate->prevclicky = event->y;
2076                                                 }
2077                                         } else {
2078                                                 /* reset click time if event type not the same */
2079                                                 win->eventstate->prevclicktime = 0;
2080                                         }
2081
2082                                         win->eventstate->prevval = event->val;
2083                                         win->eventstate->prevtype = event->type;
2084                                 } else if (event->val == KM_CLICK) { /* keep click for double click later */
2085                                         win->eventstate->prevtype = event->type;
2086                                         win->eventstate->prevval = event->val;
2087                                         win->eventstate->prevclicktime = PIL_check_seconds_timer();
2088                                         win->eventstate->prevclickx = event->x;
2089                                         win->eventstate->prevclicky = event->y;
2090                                 } else { /* reset if not */
2091                                         win->eventstate->prevtype = -1;
2092                                         win->eventstate->prevval = 0;
2093                                         win->eventstate->prevclicktime = 0;
2094                                 }
2095                         }
2096
2097                         /* unlink and free here, blender-quit then frees all */
2098                         BLI_remlink(&win->queue, event);
2099                         wm_event_free(event);
2100                         
2101                 }
2102                 
2103                 /* only add mousemove when queue was read entirely */
2104                 if(win->addmousemove && win->eventstate) {
2105                         wmEvent tevent= *(win->eventstate);
2106                         //printf("adding MOUSEMOVE %d %d\n", tevent.x, tevent.y);
2107                         tevent.type= MOUSEMOVE;
2108                         tevent.prevx= tevent.x;
2109                         tevent.prevy= tevent.y;
2110                         wm_event_add(win, &tevent);
2111                         win->addmousemove= 0;
2112                 }
2113                 
2114                 CTX_wm_window_set(C, NULL);
2115         }
2116
2117         /* update key configuration after handling events */
2118         WM_keyconfig_update(wm);
2119 }
2120
2121 /* ********** filesector handling ************ */
2122
2123 void WM_event_fileselect_event(bContext *C, void *ophandle, int eventval)
2124 {
2125         /* add to all windows! */
2126         wmWindow *win;
2127         
2128         for(win= CTX_wm_manager(C)->windows.first; win; win= win->next) {
2129                 wmEvent event= *win->eventstate;
2130                 
2131                 event.type= EVT_FILESELECT;
2132                 event.val= eventval;
2133                 event.customdata= ophandle;             // only as void pointer type check
2134
2135                 wm_event_add(win, &event);
2136         }
2137 }
2138
2139 /* operator is supposed to have a filled "path" property */
2140 /* optional property: filetype (XXX enum?) */
2141
2142 /* Idea is to keep a handler alive on window queue, owning the operator.
2143  * The filewindow can send event to make it execute, thus ensuring
2144  * executing happens outside of lower level queues, with UI refreshed.
2145  * Should also allow multiwin solutions */
2146
2147 void WM_event_add_fileselect(bContext *C, wmOperator *op)
2148 {
2149         wmEventHandler *handler, *handlernext;
2150         wmWindow *win= CTX_wm_window(C);
2151         int full= 1;    // XXX preset?
2152
2153         /* only allow 1 file selector open per window */
2154         for(handler= win->modalhandlers.first; handler; handler=handlernext) {
2155                 handlernext= handler->next;
2156                 
2157                 if(handler->type == WM_HANDLER_FILESELECT) {
2158                         if(handler->op)
2159                                 WM_operator_free(handler->op);
2160                         BLI_remlink(&win->modalhandlers, handler);
2161                         wm_event_free_handler(handler);
2162                 }
2163         }
2164         
2165         handler = MEM_callocN(sizeof(wmEventHandler), "fileselect handler");
2166         
2167         handler->type= WM_HANDLER_FILESELECT;
2168         handler->op= op;
2169         handler->op_area= CTX_wm_area(C);
2170         handler->op_region= CTX_wm_region(C);
2171         handler->filescreen= CTX_wm_screen(C);
2172         
2173         BLI_addhead(&win->modalhandlers, handler);
2174         
2175         /* check props once before invoking if check is available
2176          * ensures initial properties are valid */
2177         if(op->type->check) {
2178                 op->type->check(C, op); /* ignore return value */
2179         }
2180
2181         WM_event_fileselect_event(C, op, full?EVT_FILESELECT_FULL_OPEN:EVT_FILESELECT_OPEN);
2182 }
2183
2184 #if 0
2185 /* lets not expose struct outside wm? */
2186 static void WM_event_set_handler_flag(wmEventHandler *handler, int flag)
2187 {
2188         handler->flag= flag;
2189 }
2190 #endif
2191
2192 wmEventHandler *WM_event_add_modal_handler(bContext *C, wmOperator *op)
2193 {
2194         wmEventHandler *handler= MEM_callocN(sizeof(wmEventHandler), "event modal handler");
2195         wmWindow *win= CTX_wm_window(C);
2196         
2197         /* operator was part of macro */
2198         if(op->opm) {
2199                 /* give the mother macro to the handler */
2200                 handler->op= op->opm;
2201                 /* mother macro opm becomes the macro element */
2202                 handler->op->opm= op;
2203         }
2204         else
2205                 handler->op= op;
2206         
2207         handler->op_area= CTX_wm_area(C);               /* means frozen screen context for modal handlers! */
2208         handler->op_region= CTX_wm_region(C);
2209         
2210         BLI_addhead(&win->modalhandlers, handler);
2211
2212         return handler;
2213 }
2214
2215 wmEventHandler *WM_event_add_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2216 {
2217         wmEventHandler *handler;
2218
2219         if(!keymap) {
2220                 printf("WM_event_add_keymap_handler called with NULL keymap\n");
2221                 return NULL;
2222         }
2223
2224         /* only allow same keymap once */
2225         for(handler= handlers->first; handler; handler= handler->next)
2226                 if(handler->keymap==keymap)
2227                         return handler;
2228         
2229         handler= MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2230         BLI_addtail(handlers, handler);
2231         handler->keymap= keymap;
2232
2233         return handler;
2234 }
2235
2236 /* priorities not implemented yet, for time being just insert in begin of list */
2237 wmEventHandler *WM_event_add_keymap_handler_priority(ListBase *handlers, wmKeyMap *keymap, int UNUSED(priority))
2238 {
2239         wmEventHandler *handler;
2240         
2241         WM_event_remove_keymap_handler(handlers, keymap);
2242         
2243         handler= MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2244         BLI_addhead(handlers, handler);
2245         handler->keymap= keymap;
2246         
2247         return handler;
2248 }
2249
2250 wmEventHandler *WM_event_add_keymap_handler_bb(ListBase *handlers, wmKeyMap *keymap, rcti *bblocal, rcti *bbwin)
2251 {
2252         wmEventHandler *handler= WM_event_add_keymap_handler(handlers, keymap);
2253         
2254         if(handler) {
2255                 handler->bblocal= bblocal;
2256                 handler->bbwin= bbwin;
2257         }
2258         return handler;
2259 }
2260
2261 void WM_event_remove_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2262 {
2263         wmEventHandler *handler;
2264         
2265         for(handler= handlers->first; handler; handler= handler->next) {
2266                 if(handler->keymap==keymap) {
2267                         BLI_remlink(handlers, handler);
2268                         wm_event_free_handler(handler);
2269                         break;
2270                 }
2271         }
2272 }
2273
2274 wmEventHandler *WM_event_add_ui_handler(const bContext *C, ListBase *handlers,
2275                                         wmUIHandlerFunc func, wmUIHandlerRemoveFunc remove, void *userdata)
2276 {
2277         wmEventHandler *handler= MEM_callocN(sizeof(wmEventHandler), "event ui handler");
2278         handler->ui_handle= func;
2279         handler->ui_remove= remove;
2280         handler->ui_userdata= userdata;
2281         handler->ui_area= (C)? CTX_wm_area(C): NULL;
2282         handler->ui_region= (C)? CTX_wm_region(C): NULL;
2283         handler->ui_menu= (C)? CTX_wm_menu(C): NULL;
2284         
2285         BLI_addhead(handlers, handler);
2286         
2287         return handler;
2288 }
2289
2290 /* set "postpone" for win->modalhandlers, this is in a running for() loop in wm_handlers_do() */
2291 void WM_event_remove_ui_handler(ListBase *handlers,
2292                                 wmUIHandlerFunc func, wmUIHandlerRemoveFunc remove, void *userdata, int postpone)
2293 {
2294         wmEventHandler *handler;
2295         
2296         for(handler= handlers->first; handler; handler= handler->next) {
2297                 if(handler->ui_handle == func && handler->ui_remove == remove && handler->ui_userdata == userdata) {
2298                         /* handlers will be freed in wm_handlers_do() */
2299                         if(postpone) {
2300                                 handler->flag |= WM_HANDLER_DO_FREE;
2301                         }
2302                         else {
2303                                 BLI_remlink(handlers, handler);
2304                                 wm_event_free_handler(handler);
2305                         }
2306                         break;
2307                 }
2308         }
2309 }
2310
2311 wmEventHandler *WM_event_add_dropbox_handler(ListBase *handlers, ListBase *dropboxes)
2312 {
2313         wmEventHandler *handler;
2314
2315         /* only allow same dropbox once */
2316         for(handler= handlers->first; handler; handler= handler->next)
2317                 if(handler->dropboxes==dropboxes)
2318                         return handler;
2319         
2320         handler= MEM_callocN(sizeof(wmEventHandler), "dropbox handler");
2321         
2322         /* dropbox stored static, no free or copy */
2323         handler->dropboxes= dropboxes;
2324         BLI_addhead(handlers, handler);
2325         
2326         return handler;
2327 }
2328
2329 /* XXX solution works, still better check the real cause (ton) */
2330 void WM_event_remove_area_handler(ListBase *handlers, void *area)
2331 {
2332         wmEventHandler *handler, *nexthandler;
2333
2334         for(handler = handlers->first; handler; handler= nexthandler) {
2335                 nexthandler = handler->next;
2336                 if (handler->type != WM_HANDLER_FILESELECT) {
2337                         if (handler->ui_area == area) {
2338                                 BLI_remlink(handlers, handler);
2339                                 wm_event_free_handler(handler);
2340                         }
2341                 }
2342         }
2343 }
2344
2345 #if 0
2346 static void WM_event_remove_handler(ListBase *handlers, wmEventHandler *handler)
2347 {
2348         BLI_remlink(handlers, handler);
2349         wm_event_free_handler(handler);
2350 }
2351 #endif
2352
2353 void WM_event_add_mousemove(bContext *C)
2354 {
2355         wmWindow *window= CTX_wm_window(C);
2356         
2357         window->addmousemove= 1;
2358 }
2359
2360 /* for modal callbacks, check configuration for how to interpret exit with tweaks  */
2361 int WM_modal_tweak_exit(wmEvent *evt, int tweak_event)
2362 {
2363         /* if the release-confirm userpref setting is enabled, 
2364          * tweak events can be canceled when mouse is released
2365          */
2366         if (U.flag & USER_RELEASECONFIRM) {
2367                 /* option on, so can exit with km-release */
2368                 if (evt->val == KM_RELEASE) {
2369                         switch (tweak_event) {
2370                                 case EVT_TWEAK_L:
2371                                 case EVT_TWEAK_M:
2372                                 case EVT_TWEAK_R:
2373                                         return 1;
2374                         }
2375                 }
2376                 else {
2377                         /* if the initial event wasn't a tweak event then
2378                          * ignore USER_RELEASECONFIRM setting: see [#26756] */
2379                         if(ELEM3(tweak_event, EVT_TWEAK_L, EVT_TWEAK_M, EVT_TWEAK_R) == 0) {
2380                                 return 1;
2381                         }
2382                 }
2383         }
2384         else {
2385                 /* this is fine as long as not doing km-release, otherwise
2386                  * some items (i.e. markers) being tweaked may end up getting
2387                  * dropped all over
2388                  */
2389                 if (evt->val != KM_RELEASE)
2390                         return 1;
2391         }
2392         
2393         return 0;
2394 }
2395
2396 /* ********************* ghost stuff *************** */
2397
2398 static int convert_key(GHOST_TKey key) 
2399 {
2400         if (key>=GHOST_kKeyA && key<=GHOST_kKeyZ) {
2401                 return (AKEY + ((int) key - GHOST_kKeyA));
2402         } else if (key>=GHOST_kKey0 && key<=GHOST_kKey9) {
2403                 return (ZEROKEY + ((int) key - GHOST_kKey0));
2404         } else if (key>=GHOST_kKeyNumpad0 && key<=GHOST_kKeyNumpad9) {
2405                 return (PAD0 + ((int) key - GHOST_kKeyNumpad0));
2406         } else if (key>=GHOST_kKeyF1 && key<=GHOST_kKeyF19) {
2407                 return (F1KEY + ((int) key - GHOST_kKeyF1));
2408         } else {
2409                 switch (key) {
2410                         case GHOST_kKeyBackSpace:               return BACKSPACEKEY;
2411                         case GHOST_kKeyTab:                             return TABKEY;
2412                         case GHOST_kKeyLinefeed:                return LINEFEEDKEY;
2413                         case GHOST_kKeyClear:                   return 0;
2414                         case GHOST_kKeyEnter:                   return RETKEY;
2415                                 
2416                         case GHOST_kKeyEsc:                             return ESCKEY;
2417                         case GHOST_kKeySpace:                   return SPACEKEY;
2418                         case GHOST_kKeyQuote:                   return QUOTEKEY;
2419                         case GHOST_kKeyComma:                   return COMMAKEY;
2420                         case GHOST_kKeyMinus:                   return MINUSKEY;
2421                         case GHOST_kKeyPeriod:                  return PERIODKEY;
2422                         case GHOST_kKeySlash:                   return SLASHKEY;
2423                                 
2424                         case GHOST_kKeySemicolon:               return SEMICOLONKEY;
2425                         case GHOST_kKeyEqual:                   return EQUALKEY;
2426                                 
2427                         case GHOST_kKeyLeftBracket:             return LEFTBRACKETKEY;
2428                         case GHOST_kKeyRightBracket:    return RIGHTBRACKETKEY;
2429                         case GHOST_kKeyBackslash:               return BACKSLASHKEY;
2430                         case GHOST_kKeyAccentGrave:             return ACCENTGRAVEKEY;
2431                                 
2432                         case GHOST_kKeyLeftShift:               return LEFTSHIFTKEY;
2433                         case GHOST_kKeyRightShift:              return RIGHTSHIFTKEY;
2434                         case GHOST_kKeyLeftControl:             return LEFTCTRLKEY;
2435                         case GHOST_kKeyRightControl:    return RIGHTCTRLKEY;
2436                         case GHOST_kKeyOS:                              return OSKEY;
2437                         case GHOST_kKeyLeftAlt:                 return LEFTALTKEY;
2438                         case GHOST_kKeyRightAlt:                return RIGHTALTKEY;
2439                                 
2440                         case GHOST_kKeyCapsLock:                return CAPSLOCKKEY;
2441                         case GHOST_kKeyNumLock:                 return 0;
2442                         case GHOST_kKeyScrollLock:              return 0;
2443                                 
2444                         case GHOST_kKeyLeftArrow:               return LEFTARROWKEY;
2445                         case GHOST_kKeyRightArrow:              return RIGHTARROWKEY;
2446                         case GHOST_kKeyUpArrow:                 return UPARROWKEY;
2447                         case GHOST_kKeyDownArrow:               return DOWNARROWKEY;
2448                                 
2449                         case GHOST_kKeyPrintScreen:             return 0;
2450                         case GHOST_kKeyPause:                   return PAUSEKEY;
2451                                 
2452                         case GHOST_kKeyInsert:                  return INSERTKEY;
2453                         case GHOST_kKeyDelete:                  return DELKEY;
2454                         case GHOST_kKeyHome:                    return HOMEKEY;
2455                         case GHOST_kKeyEnd:                             return ENDKEY;
2456                         case GHOST_kKeyUpPage:                  return PAGEUPKEY;
2457                         case GHOST_kKeyDownPage:                return PAGEDOWNKEY;
2458                                 
2459                         case GHOST_kKeyNumpadPeriod:    return PADPERIOD;
2460                         case GHOST_kKeyNumpadEnter:             return PADENTER;
2461                         case GHOST_kKeyNumpadPlus:              return PADPLUSKEY;
2462                         case GHOST_kKeyNumpadMinus:             return PADMINUS;
2463                         case GHOST_kKeyNumpadAsterisk:  return PADASTERKEY;
2464                         case GHOST_kKeyNumpadSlash:             return PADSLASHKEY;
2465                                 
2466                         case GHOST_kKeyGrLess:              return GRLESSKEY; 
2467                         
2468                         case GHOST_kKeyMediaPlay:               return MEDIAPLAY;
2469                         case GHOST_kKeyMediaStop:               return MEDIASTOP;
2470                         case GHOST_kKeyMediaFirst:              return MEDIAFIRST;
2471                         case GHOST_kKeyMediaLast:               return MEDIALAST;
2472                         
2473                         default:
2474                                 return UNKNOWNKEY;      /* GHOST_kKeyUnknown */
2475                 }
2476         }
2477 }
2478
2479 /* adds customdata to event */
2480 static void update_tablet_data(wmWindow *win, wmEvent *event)
2481 {
2482         const GHOST_TabletData *td= GHOST_GetTabletData(win->ghostwin);
2483         
2484         /* if there's tablet data from an active tablet device then add it */
2485         if ((td != NULL) && td->Active != GHOST_kTabletModeNone) {
2486                 struct wmTabletData *wmtab= MEM_mallocN(sizeof(wmTabletData), "customdata tablet");
2487                 
2488                 wmtab->Active = (int)td->Active;
2489                 wmtab->Pressure = td->Pressure;
2490                 wmtab->Xtilt = td->Xtilt;
2491                 wmtab->Ytilt = td->Ytilt;
2492                 
2493                 event->custom= EVT_DATA_TABLET;
2494                 event->customdata= wmtab;
2495                 event->customdatafree= 1;
2496         } 
2497 }
2498
2499 /* adds customdata to event */
2500 static void attach_ndof_data(wmEvent* event, const GHOST_TEventNDOFMotionData* ghost)
2501 {
2502         wmNDOFMotionData* data = MEM_mallocN(sizeof(wmNDOFMotionData), "customdata NDOF");
2503
2504         const float s = U.ndof_sensitivity;
2505
2506         data->tx = s * ghost->tx;
2507
2508         data->rx = s * ghost->rx;
2509         data->ry = s * ghost->ry;
2510         data->rz = s * ghost->rz;
2511
2512         if (U.ndof_flag & NDOF_ZOOM_UPDOWN) {
2513                 /* rotate so Y is where Z was */
2514                 data->ty = s * ghost->tz;
2515                 data->tz = s * ghost->ty;
2516                 /* maintain handed-ness? or just do what feels right? */
2517
2518                 /* should this affect rotation also?
2519                  * initial guess is 'yes', but get user feedback immediately!
2520                  */
2521 #if 0
2522                 /* after turning this on, my guess becomes 'no' */
2523                 data->ry = s * ghost->rz;
2524                 data->rz = s * ghost->ry;
2525 #endif
2526                 }
2527         else {
2528                 data->ty = s * ghost->ty;
2529                 data->tz = s * ghost->tz;
2530                 }
2531
2532         data->dt = ghost->dt;
2533
2534         data->progress = (wmProgress) ghost->progress;
2535
2536         event->custom = EVT_DATA_NDOF_MOTION;
2537         event->customdata = data;
2538         event->customdatafree = 1;
2539 }
2540
2541 /* imperfect but probably usable... draw/enable drags to other windows */
2542 static wmWindow *wm_event_cursor_other_windows(wmWindowManager *wm, wmWindow *win, wmEvent *evt)
2543 {
2544         int mx= evt->x, my= evt->y;
2545         
2546         if(wm->windows.first== wm->windows.last)
2547                 return NULL;
2548         
2549         /* top window bar... */
2550         if(mx<0 || my<0 || mx>win->sizex || my>win->sizey+30) { 
2551                 wmWindow *owin;
2552                 wmEventHandler *handler;
2553                 
2554                 /* let's skip windows having modal handlers now */
2555                 /* potential XXX ugly... I wouldn't have added a modalhandlers list (introduced in rev 23331, ton) */
2556                 for(handler= win->modalhandlers.first; handler; handler= handler->next)
2557                         if(handler->ui_handle || handler->op)
2558                                 return NULL;
2559                 
2560                 /* to desktop space */
2561                 mx += (int)win->posx;
2562                 my += (int)win->posy;
2563                 
2564                 /* check other windows to see if it has mouse inside */
2565                 for(owin= wm->windows.first; owin; owin= owin->next) {
2566                         
2567                         if(owin!=win) {
2568                                 if(mx-owin->posx >= 0 && my-owin->posy >= 0 &&
2569                                    mx-owin->posx <= owin->sizex && my-owin->posy <= owin->sizey) {
2570                                         evt->x= mx - (int)owin->posx;
2571                                         evt->y= my - (int)owin->posy;
2572                                         
2573                                         return owin;
2574                                 }
2575                         }
2576                 }
2577         }
2578         return NULL;
2579 }
2580
2581 /* windows store own event queues, no bContext here */
2582 /* time is in 1000s of seconds, from ghost */
2583 void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int UNUSED(time), void *customdata)
2584 {
2585         wmWindow *owin;
2586         wmEvent event, *evt= win->eventstate;
2587
2588         /* initialize and copy state (only mouse x y and modifiers) */
2589         event= *evt;
2590         
2591         switch (type) {
2592                 /* mouse move */
2593                 case GHOST_kEventCursorMove: {
2594                         if(win->active) {
2595                                 GHOST_TEventCursorData *cd= customdata;
2596                                 wmEvent *lastevent= win->queue.last;
2597                                 int cx, cy;
2598                                 
2599                                 GHOST_ScreenToClient(win->ghostwin, cd->x, cd->y, &cx, &cy);
2600                                 evt->x= cx;
2601                                 evt->y= (win->sizey-1) - cy;
2602                                 
2603                                 event.x= evt->x;
2604                                 event.y= evt->y;
2605
2606                                 event.type= MOUSEMOVE;
2607
2608                                 /* some painting operators want accurate mouse events, they can
2609                                  * handle in between mouse move moves, others can happily ignore
2610                                  * them for better performance */
2611                                 if(lastevent && lastevent->type == MOUSEMOVE)
2612                                         lastevent->type = INBETWEEN_MOUSEMOVE;
2613
2614                                 update_tablet_data(win, &event);
2615                                 wm_event_add(win, &event);
2616
2617                                 //printf("sending MOUSEMOVE %d %d\n", event.x, event.y);
2618                                 
2619                                 /* also add to other window if event is there, this makes overdraws disappear nicely */
2620                                 /* it remaps mousecoord to other window in event */
2621                                 owin= wm_event_cursor_other_windows(wm, win, &event);
2622                                 if(owin) {
2623                                         wmEvent oevent= *(owin->eventstate);
2624                                         
2625                                         oevent.x=owin->eventstate->x= event.x;
2626                                         oevent.y=owin->eventstate->y= event.y;
2627                                         oevent.type= MOUSEMOVE;
2628                                         
2629                                         update_tablet_data(owin, &oevent);
2630                                         wm_event_add(owin, &oevent);
2631                                 }
2632                                 
2633                         }
2634                         break;
2635                 }
2636                 case GHOST_kEventTrackpad: {
2637                         GHOST_TEventTrackpadData * pd = customdata;
2638                         switch (pd->subtype) {
2639                                 case GHOST_kTrackpadEventMagnify:
2640                                         event.type = MOUSEZOOM;
2641                                         break;
2642                                 case GHOST_kTrackpadEventRotate:
2643                                         event.type = MOUSEROTATE;
2644                                         break;
2645                                 case GHOST_kTrackpadEventScroll:
2646                                 default:
2647                                         event.type= MOUSEPAN;
2648                                         break;
2649                         }
2650
2651                         {
2652                                 int cx, cy;
2653                                 GHOST_ScreenToClient(win->ghostwin, pd->x, pd->y, &cx, &cy);
2654                                 event.x= evt->x= cx;
2655                                 event.y= evt->y= (win->sizey-1) - cy;
2656                         }
2657
2658                         // Use prevx/prevy so we can calculate the delta later
2659                         event.prevx= event.x - pd->deltaX;
2660                         event.prevy= event.y - (-pd->deltaY);
2661                         
2662                         update_tablet_data(win, &event);
2663                         wm_event_add(win, &event);
2664                         break;
2665                 }
2666                 /* mouse button */
2667                 case GHOST_kEventButtonDown:
2668                 case GHOST_kEventButtonUp: {
2669                         GHOST_TEventButtonData *bd= customdata;
2670
2671                         /* Note!, this starts as 0/1 but later is converted to KM_PRESS/KM_RELEASE by tweak */
2672                         event.val= (type==GHOST_kEventButtonDown) ? KM_PRESS:KM_RELEASE;
2673                         
2674                         if (bd->button == GHOST_kButtonMaskLeft)
2675                                 event.type= LEFTMOUSE;
2676                         else if (bd->button == GHOST_kButtonMaskRight)
2677                                 event.type= RIGHTMOUSE;
2678                         else if (bd->button == GHOST_kButtonMaskButton4)
2679                                 event.type= BUTTON4MOUSE;
2680                         else if (bd->button == GHOST_kButtonMaskButton5)
2681                                 event.type= BUTTON5MOUSE;
2682                         else
2683                                 event.type= MIDDLEMOUSE;
2684                         
2685                         if(win->active==0) {
2686                                 int cx, cy;
2687                                 
2688                                 /* entering window, update mouse pos. (ghost sends win-activate *after* the mouseclick in window!) */
2689                                 wm_get_cursor_position(win, &cx, &cy);
2690
2691                                 event.x= evt->x= cx;
2692                                 event.y= evt->y= cy;
2693                         }
2694                         
2695                         /* add to other window if event is there (not to both!) */
2696                         owin= wm_event_cursor_other_windows(wm, win, &event);
2697                         if(owin) {
2698                                 wmEvent oevent= *(owin->eventstate);
2699                                 
2700                                 oevent.x= event.x;
2701                                 oevent.y= event.y;
2702                                 oevent.type= event.type;
2703                                 oevent.val= event.val;
2704                                 
2705                                 update_tablet_data(owin, &oevent);
2706                                 wm_event_add(owin, &oevent);
2707                         }
2708                         else {
2709                                 update_tablet_data(win, &event);
2710                                 wm_event_add(win, &event);
2711                         }
2712                         
2713                         break;
2714                 }
2715                 /* keyboard */
2716                 case GHOST_kEventKeyDown:
2717                 case GHOST_kEventKeyUp: {
2718                         GHOST_TEventKeyData *kd= customdata;
2719                         event.type= convert_key(kd->key);
2720                         event.ascii= kd->ascii;
2721                         memcpy(event.utf8_buf, kd->utf8_buf,sizeof(event.utf8_buf));/* might be not null terminated*/
2722                         event.val= (type==GHOST_kEventKeyDown)?KM_PRESS:KM_RELEASE;
2723                         
2724                         /* exclude arrow keys, esc, etc from text input */
2725                         if(type==GHOST_kEventKeyUp) {
2726                                 event.ascii= '\0';
2727
2728                                 /* ghost should do this already for key up */
2729                                 if (event.utf8_buf[0]) {
2730                                         printf("%s: ghost on your platform is misbehaving, utf8 events on key up!\n", __func__);
2731                                 }
2732                                 event.utf8_buf[0]= '\0';
2733                         }
2734                         else {
2735                                 if (event.ascii<32 && event.ascii > 0)
2736                                         event.ascii= '\0';
2737                                 if (event.utf8_buf[0]<32 && event.utf8_buf[0] > 0)
2738                                         event.utf8_buf[0]= '\0';
2739                         }
2740
2741                         if (event.utf8_buf[0]) {
2742                                 if (BLI_str_utf8_size(event.utf8_buf) == -1) {
2743                                         printf("%s: ghost detected an invalid unicode character '%d'!\n",
2744                                                __func__, (int)(unsigned char)event.utf8_buf[0]);
2745                                         event.utf8_buf[0]= '\0';
2746                                 }
2747                         }
2748
2749                         /* modifiers */
2750                         /* assigning both first and second is strange - campbell */
2751                         switch(event.type) {
2752                         case LEFTSHIFTKEY: case RIGHTSHIFTKEY:
2753                                 event.shift = evt->shift = (event.val == KM_PRESS) ?
2754                                                 ((evt->ctrl || evt->alt || evt->oskey) ? (KM_MOD_FIRST | KM_MOD_SECOND) : KM_MOD_FIRST) :
2755                                                 FALSE;
2756                   &nb