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