Manipulator: tweak shape drawing
[blender.git] / source / blender / editors / screen / screen_ops.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) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/editors/screen/screen_ops.c
26  *  \ingroup edscr
27  */
28
29
30 #include <math.h>
31 #include <string.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BLI_math.h"
36 #include "BLI_blenlib.h"
37 #include "BLI_dlrbTree.h"
38 #include "BLI_utildefines.h"
39
40 #include "BLT_translation.h"
41
42 #include "DNA_armature_types.h"
43 #include "DNA_lattice_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_curve_types.h"
46 #include "DNA_gpencil_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_meta_types.h"
49 #include "DNA_mask_types.h"
50 #include "DNA_node_types.h"
51 #include "DNA_workspace_types.h"
52 #include "DNA_userdef_types.h"
53
54 #include "BKE_context.h"
55 #include "BKE_customdata.h"
56 #include "BKE_global.h"
57 #include "BKE_icons.h"
58 #include "BKE_main.h"
59 #include "BKE_object.h"
60 #include "BKE_report.h"
61 #include "BKE_scene.h"
62 #include "BKE_screen.h"
63 #include "BKE_editmesh.h"
64 #include "BKE_sound.h"
65 #include "BKE_mask.h"
66 #include "BKE_workspace.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70
71 #include "ED_armature.h"
72 #include "ED_clip.h"
73 #include "ED_image.h"
74 #include "ED_keyframes_draw.h"
75 #include "ED_object.h"
76 #include "ED_screen.h"
77 #include "ED_screen_types.h"
78 #include "ED_sequencer.h"
79 #include "ED_util.h"
80 #include "ED_view3d.h"
81
82 #include "RNA_access.h"
83 #include "RNA_define.h"
84
85 #include "UI_interface.h"
86 #include "UI_resources.h"
87 #include "UI_view2d.h"
88
89 #include "screen_intern.h"  /* own module include */
90
91 #define KM_MODAL_CANCEL     1
92 #define KM_MODAL_APPLY      2
93 #define KM_MODAL_SNAP_ON    3
94 #define KM_MODAL_SNAP_OFF   4
95
96 /* ************** Exported Poll tests ********************** */
97
98 int ED_operator_regionactive(bContext *C)
99 {
100         if (CTX_wm_window(C) == NULL) return 0;
101         if (CTX_wm_screen(C) == NULL) return 0;
102         if (CTX_wm_region(C) == NULL) return 0;
103         return 1;
104 }
105
106 int ED_operator_areaactive(bContext *C)
107 {
108         if (CTX_wm_window(C) == NULL) return 0;
109         if (CTX_wm_screen(C) == NULL) return 0;
110         if (CTX_wm_area(C) == NULL) return 0;
111         return 1;
112 }
113
114 int ED_operator_screenactive(bContext *C)
115 {
116         if (CTX_wm_window(C) == NULL) return 0;
117         if (CTX_wm_screen(C) == NULL) return 0;
118         return 1;
119 }
120
121 /* XXX added this to prevent anim state to change during renders */
122 static int ED_operator_screenactive_norender(bContext *C)
123 {
124         if (G.is_rendering) return 0;
125         if (CTX_wm_window(C) == NULL) return 0;
126         if (CTX_wm_screen(C) == NULL) return 0;
127         return 1;
128 }
129
130
131 static int screen_active_editable(bContext *C)
132 {
133         if (ED_operator_screenactive(C)) {
134                 /* no full window splitting allowed */
135                 if (CTX_wm_screen(C)->state != SCREENNORMAL)
136                         return 0;
137                 return 1;
138         }
139         return 0;
140 }
141
142 static ARegion *screen_find_region_type(bContext *C, int type)
143 {
144         ARegion *ar = CTX_wm_region(C);
145
146         /* find the header region
147          * - try context first, but upon failing, search all regions in area...
148          */
149         if ((ar == NULL) || (ar->regiontype != type)) {
150                 ScrArea *sa = CTX_wm_area(C);
151                 ar = BKE_area_find_region_type(sa, type);
152         }
153         else {
154                 ar = NULL;
155         }
156
157         return ar;
158 }
159
160 /* when mouse is over area-edge */
161 int ED_operator_screen_mainwinactive(bContext *C)
162 {
163         bScreen *screen;
164         if (CTX_wm_window(C) == NULL) return 0;
165         screen = CTX_wm_screen(C);
166         if (screen == NULL) return 0;
167         if (screen->subwinactive != screen->mainwin) return 0;
168         return 1;
169 }
170
171 int ED_operator_scene_editable(bContext *C)
172 {
173         Scene *scene = CTX_data_scene(C);
174         if (scene && !ID_IS_LINKED(scene))
175                 return 1;
176         return 0;
177 }
178
179 int ED_operator_objectmode(bContext *C)
180 {
181         Scene *scene = CTX_data_scene(C);
182         Object *obact = CTX_data_active_object(C);
183
184         if (scene == NULL || ID_IS_LINKED(scene))
185                 return 0;
186         if (CTX_data_edit_object(C))
187                 return 0;
188         
189         /* add a check for ob->mode too? */
190         if (obact && (obact->mode != OB_MODE_OBJECT))
191                 return 0;
192         
193         return 1;
194 }
195
196
197 static bool ed_spacetype_test(bContext *C, int type)
198 {
199         if (ED_operator_areaactive(C)) {
200                 SpaceLink *sl = (SpaceLink *)CTX_wm_space_data(C);
201                 return sl && (sl->spacetype == type);
202         }
203         return 0;
204 }
205
206 int ED_operator_view3d_active(bContext *C)
207 {
208         return ed_spacetype_test(C, SPACE_VIEW3D);
209 }
210
211 int ED_operator_region_view3d_active(bContext *C)
212 {
213         if (CTX_wm_region_view3d(C))
214                 return true;
215
216         CTX_wm_operator_poll_msg_set(C, "expected a view3d region");
217         return false;
218 }
219
220 /* generic for any view2d which uses anim_ops */
221 int ED_operator_animview_active(bContext *C)
222 {
223         if (ED_operator_areaactive(C)) {
224                 SpaceLink *sl = (SpaceLink *)CTX_wm_space_data(C);
225                 if (sl && (ELEM(sl->spacetype, SPACE_SEQ, SPACE_ACTION, SPACE_NLA, SPACE_IPO, SPACE_TIME)))
226                         return true;
227         }
228
229         CTX_wm_operator_poll_msg_set(C, "expected a timeline/animation area to be active");
230         return 0;
231 }
232
233 int ED_operator_timeline_active(bContext *C)
234 {
235         return ed_spacetype_test(C, SPACE_TIME);
236 }
237
238 int ED_operator_outliner_active(bContext *C)
239 {
240         return ed_spacetype_test(C, SPACE_OUTLINER);
241 }
242
243 int ED_operator_outliner_active_no_editobject(bContext *C)
244 {
245         if (ed_spacetype_test(C, SPACE_OUTLINER)) {
246                 Object *ob = ED_object_active_context(C);
247                 Object *obedit = CTX_data_edit_object(C);
248                 if (ob && ob == obedit)
249                         return 0;
250                 else
251                         return 1;
252         }
253         return 0;
254 }
255
256 int ED_operator_file_active(bContext *C)
257 {
258         return ed_spacetype_test(C, SPACE_FILE);
259 }
260
261 int ED_operator_action_active(bContext *C)
262 {
263         return ed_spacetype_test(C, SPACE_ACTION);
264 }
265
266 int ED_operator_buttons_active(bContext *C)
267 {
268         return ed_spacetype_test(C, SPACE_BUTS);
269 }
270
271 int ED_operator_node_active(bContext *C)
272 {
273         SpaceNode *snode = CTX_wm_space_node(C);
274         
275         if (snode && snode->edittree)
276                 return 1;
277         
278         return 0;
279 }
280
281 int ED_operator_node_editable(bContext *C)
282 {
283         SpaceNode *snode = CTX_wm_space_node(C);
284         
285         if (snode && snode->edittree && !ID_IS_LINKED(snode->edittree))
286                 return 1;
287         
288         return 0;
289 }
290
291 int ED_operator_graphedit_active(bContext *C)
292 {
293         return ed_spacetype_test(C, SPACE_IPO);
294 }
295
296 int ED_operator_sequencer_active(bContext *C)
297 {
298         return ed_spacetype_test(C, SPACE_SEQ);
299 }
300
301 int ED_operator_sequencer_active_editable(bContext *C)
302 {
303         return ed_spacetype_test(C, SPACE_SEQ) && ED_operator_scene_editable(C);
304 }
305
306 int ED_operator_image_active(bContext *C)
307 {
308         return ed_spacetype_test(C, SPACE_IMAGE);
309 }
310
311 int ED_operator_nla_active(bContext *C)
312 {
313         return ed_spacetype_test(C, SPACE_NLA);
314 }
315
316 int ED_operator_logic_active(bContext *C)
317 {
318         return ed_spacetype_test(C, SPACE_LOGIC);
319 }
320
321 int ED_operator_info_active(bContext *C)
322 {
323         return ed_spacetype_test(C, SPACE_INFO);
324 }
325
326
327 int ED_operator_console_active(bContext *C)
328 {
329         return ed_spacetype_test(C, SPACE_CONSOLE);
330 }
331
332 static int ed_object_hidden(Object *ob)
333 {
334         /* if hidden but in edit mode, we still display, can happen with animation */
335         return ((ob->restrictflag & OB_RESTRICT_VIEW) && !(ob->mode & OB_MODE_EDIT));
336 }
337
338 int ED_operator_object_active(bContext *C)
339 {
340         Object *ob = ED_object_active_context(C);
341         return ((ob != NULL) && !ed_object_hidden(ob));
342 }
343
344 int ED_operator_object_active_editable(bContext *C)
345 {
346         Object *ob = ED_object_active_context(C);
347         return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob));
348 }
349
350 int ED_operator_object_active_editable_mesh(bContext *C)
351 {
352         Object *ob = ED_object_active_context(C);
353         return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob) &&
354                 (ob->type == OB_MESH) && !ID_IS_LINKED(ob->data));
355 }
356
357 int ED_operator_object_active_editable_font(bContext *C)
358 {
359         Object *ob = ED_object_active_context(C);
360         return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob) &&
361                 (ob->type == OB_FONT));
362 }
363
364 int ED_operator_editmesh(bContext *C)
365 {
366         Object *obedit = CTX_data_edit_object(C);
367         if (obedit && obedit->type == OB_MESH)
368                 return NULL != BKE_editmesh_from_object(obedit);
369         return 0;
370 }
371
372 int ED_operator_editmesh_view3d(bContext *C)
373 {
374         return ED_operator_editmesh(C) && ED_operator_view3d_active(C);
375 }
376
377 int ED_operator_editmesh_region_view3d(bContext *C)
378 {
379         if (ED_operator_editmesh(C) && CTX_wm_region_view3d(C))
380                 return 1;
381
382         CTX_wm_operator_poll_msg_set(C, "expected a view3d region & editmesh");
383         return 0;
384 }
385
386 int ED_operator_editarmature(bContext *C)
387 {
388         Object *obedit = CTX_data_edit_object(C);
389         if (obedit && obedit->type == OB_ARMATURE)
390                 return NULL != ((bArmature *)obedit->data)->edbo;
391         return 0;
392 }
393
394 /**
395  * \brief check for pose mode (no mixed modes)
396  *
397  * We want to enable most pose operations in weight paint mode,
398  * when it comes to transforming bones, but managing bones layers/groups
399  * can be left for pose mode only. (not weight paint mode)
400  */
401 int ED_operator_posemode_exclusive(bContext *C)
402 {
403         Object *obact = CTX_data_active_object(C);
404
405         if (obact && !(obact->mode & OB_MODE_EDIT)) {
406                 Object *obpose;
407                 if ((obpose = BKE_object_pose_armature_get(obact))) {
408                         if (obact == obpose) {
409                                 return 1;
410                         }
411                 }
412         }
413
414         return 0;
415 }
416
417 /* allows for pinned pose objects to be used in the object buttons
418  * and the non-active pose object to be used in the 3D view */
419 int ED_operator_posemode_context(bContext *C)
420 {
421         Object *obpose = ED_pose_object_from_context(C);
422
423         if (obpose && !(obpose->mode & OB_MODE_EDIT)) {
424                 if (BKE_object_pose_context_check(obpose)) {
425                         return 1;
426                 }
427         }
428
429         return 0;
430 }
431
432 int ED_operator_posemode(bContext *C)
433 {
434         Object *obact = CTX_data_active_object(C);
435
436         if (obact && !(obact->mode & OB_MODE_EDIT)) {
437                 Object *obpose;
438                 if ((obpose = BKE_object_pose_armature_get(obact))) {
439                         if ((obact == obpose) || (obact->mode & OB_MODE_WEIGHT_PAINT)) {
440                                 return 1;
441                         }
442                 }
443         }
444
445         return 0;
446 }
447
448 int ED_operator_posemode_local(bContext *C)
449 {
450         if (ED_operator_posemode(C)) {
451                 Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
452                 bArmature *arm = ob->data;
453                 return !(ID_IS_LINKED(&ob->id) ||
454                          ID_IS_LINKED(&arm->id));
455         }
456         return false;
457 }
458
459 /* wrapper for ED_space_image_show_uvedit */
460 int ED_operator_uvedit(bContext *C)
461 {
462         SpaceImage *sima = CTX_wm_space_image(C);
463         Object *obedit = CTX_data_edit_object(C);
464         return ED_space_image_show_uvedit(sima, obedit);
465 }
466
467 int ED_operator_uvedit_space_image(bContext *C)
468 {
469         SpaceImage *sima = CTX_wm_space_image(C);
470         Object *obedit = CTX_data_edit_object(C);
471         return sima && ED_space_image_show_uvedit(sima, obedit);
472 }
473
474 int ED_operator_uvmap(bContext *C)
475 {
476         Object *obedit = CTX_data_edit_object(C);
477         BMEditMesh *em = NULL;
478         
479         if (obedit && obedit->type == OB_MESH) {
480                 em = BKE_editmesh_from_object(obedit);
481         }
482         
483         if (em && (em->bm->totface)) {
484                 return true;
485         }
486         
487         return false;
488 }
489
490 int ED_operator_editsurfcurve(bContext *C)
491 {
492         Object *obedit = CTX_data_edit_object(C);
493         if (obedit && ELEM(obedit->type, OB_CURVE, OB_SURF))
494                 return NULL != ((Curve *)obedit->data)->editnurb;
495         return 0;
496 }
497
498 int ED_operator_editsurfcurve_region_view3d(bContext *C)
499 {
500         if (ED_operator_editsurfcurve(C) && CTX_wm_region_view3d(C))
501                 return 1;
502
503         CTX_wm_operator_poll_msg_set(C, "expected a view3d region & editcurve");
504         return 0;
505 }
506
507 int ED_operator_editcurve(bContext *C)
508 {
509         Object *obedit = CTX_data_edit_object(C);
510         if (obedit && obedit->type == OB_CURVE)
511                 return NULL != ((Curve *)obedit->data)->editnurb;
512         return 0;
513 }
514
515 int ED_operator_editcurve_3d(bContext *C)
516 {
517         Object *obedit = CTX_data_edit_object(C);
518         if (obedit && obedit->type == OB_CURVE) {
519                 Curve *cu = (Curve *)obedit->data;
520
521                 return (cu->flag & CU_3D) && (NULL != cu->editnurb);
522         }
523         return 0;
524 }
525
526 int ED_operator_editsurf(bContext *C)
527 {
528         Object *obedit = CTX_data_edit_object(C);
529         if (obedit && obedit->type == OB_SURF)
530                 return NULL != ((Curve *)obedit->data)->editnurb;
531         return 0;
532 }
533
534 int ED_operator_editfont(bContext *C)
535 {
536         Object *obedit = CTX_data_edit_object(C);
537         if (obedit && obedit->type == OB_FONT)
538                 return NULL != ((Curve *)obedit->data)->editfont;
539         return 0;
540 }
541
542 int ED_operator_editlattice(bContext *C)
543 {
544         Object *obedit = CTX_data_edit_object(C);
545         if (obedit && obedit->type == OB_LATTICE)
546                 return NULL != ((Lattice *)obedit->data)->editlatt;
547         return 0;
548 }
549
550 int ED_operator_editmball(bContext *C)
551 {
552         Object *obedit = CTX_data_edit_object(C);
553         if (obedit && obedit->type == OB_MBALL)
554                 return NULL != ((MetaBall *)obedit->data)->editelems;
555         return 0;
556 }
557
558 int ED_operator_mask(bContext *C)
559 {
560         ScrArea *sa = CTX_wm_area(C);
561         if (sa && sa->spacedata.first) {
562                 switch (sa->spacetype) {
563                         case SPACE_CLIP:
564                         {
565                                 SpaceClip *sc = sa->spacedata.first;
566                                 return ED_space_clip_check_show_maskedit(sc);
567                         }
568                         case SPACE_SEQ:
569                         {
570                                 SpaceSeq *sseq = sa->spacedata.first;
571                                 Scene *scene = CTX_data_scene(C);
572                                 return ED_space_sequencer_check_show_maskedit(sseq, scene);
573                         }
574                         case SPACE_IMAGE:
575                         {
576                                 SpaceImage *sima = sa->spacedata.first;
577                                 ViewLayer *view_layer = CTX_data_view_layer(C);
578                                 return ED_space_image_check_show_maskedit(view_layer, sima);
579                         }
580                 }
581         }
582
583         return false;
584 }
585
586 int ED_operator_camera(bContext *C)
587 {
588         struct Camera *cam = CTX_data_pointer_get_type(C, "camera", &RNA_Camera).data;
589         return (cam != NULL);
590 }
591
592 /* *************************** action zone operator ************************** */
593
594 /* operator state vars used:  
595  * none
596  * 
597  * functions:
598  * 
599  * apply() set actionzone event
600  * 
601  * exit()       free customdata
602  * 
603  * callbacks:
604  * 
605  * exec()       never used
606  * 
607  * invoke() check if in zone  
608  * add customdata, put mouseco and area in it
609  * add modal handler
610  * 
611  * modal()      accept modal events while doing it
612  * call apply() with gesture info, active window, nonactive window
613  * call exit() and remove handler when LMB confirm
614  */
615
616 typedef struct sActionzoneData {
617         ScrArea *sa1, *sa2;
618         AZone *az;
619         int x, y, gesture_dir, modifier;
620 } sActionzoneData;
621
622 /* quick poll to save operators to be created and handled */
623 static int actionzone_area_poll(bContext *C)
624 {
625         wmWindow *win = CTX_wm_window(C);
626         ScrArea *sa = CTX_wm_area(C);
627         
628         if (sa && win && win->eventstate) {
629                 const int *xy = &win->eventstate->x;
630                 AZone *az;
631                 
632                 for (az = sa->actionzones.first; az; az = az->next)
633                         if (BLI_rcti_isect_pt_v(&az->rect, xy))
634                                 return 1;
635         }
636         return 0;
637 }
638
639 /* the debug drawing of the click_rect is in area_draw_azone_fullscreen, keep both in sync */
640 static void fullscreen_click_rcti_init(rcti *rect, const short x1, const short y1, const short x2, const short y2)
641 {
642         int x = x2 - ((float) x2 - x1) * 0.5f / UI_DPI_FAC;
643         int y = y2 - ((float) y2 - y1) * 0.5f / UI_DPI_FAC;
644         float icon_size = UI_DPI_ICON_SIZE + 7 * UI_DPI_FAC;
645
646         /* adjust the icon distance from the corner */
647         x += 36.0f / UI_DPI_FAC;
648         y += 36.0f / UI_DPI_FAC;
649
650         /* draws from the left bottom corner of the icon */
651         x -= UI_DPI_ICON_SIZE;
652         y -= UI_DPI_ICON_SIZE;
653
654         BLI_rcti_init(rect, x, x + icon_size, y, y + icon_size);
655 }
656
657 AZone *is_in_area_actionzone(ScrArea *sa, const int xy[2])
658 {
659         AZone *az = NULL;
660         
661         for (az = sa->actionzones.first; az; az = az->next) {
662                 if (BLI_rcti_isect_pt_v(&az->rect, xy)) {
663                         if (az->type == AZONE_AREA) {
664                                 /* no triangle intersect but a hotspot circle based on corner */
665                                 int radius = (xy[0] - az->x1) * (xy[0] - az->x1) + (xy[1] - az->y1) * (xy[1] - az->y1);
666                                 
667                                 if (radius <= AZONESPOT * AZONESPOT)
668                                         break;
669                         }
670                         else if (az->type == AZONE_REGION) {
671                                 break;
672                         }
673                         else if (az->type == AZONE_FULLSCREEN) {
674                                 int mouse_radius, spot_radius, fadein_radius, fadeout_radius;
675                                 rcti click_rect;
676
677                                 fullscreen_click_rcti_init(&click_rect, az->x1, az->y1, az->x2, az->y2);
678
679                                 if (BLI_rcti_isect_pt_v(&click_rect, xy)) {
680                                         az->alpha = 1.0f;
681                                 }
682                                 else {
683                                         mouse_radius = (xy[0] - az->x2) * (xy[0] - az->x2) + (xy[1] - az->y2) * (xy[1] - az->y2);
684                                         spot_radius = AZONESPOT * AZONESPOT;
685                                         fadein_radius = AZONEFADEIN * AZONEFADEIN;
686                                         fadeout_radius = AZONEFADEOUT * AZONEFADEOUT;
687
688                                         if (mouse_radius < spot_radius) {
689                                                 az->alpha = 1.0f;
690                                         }
691                                         else if (mouse_radius < fadein_radius) {
692                                                 az->alpha = 1.0f;
693                                         }
694                                         else if (mouse_radius < fadeout_radius) {
695                                                 az->alpha = 1.0f - ((float)(mouse_radius - fadein_radius)) / ((float)(fadeout_radius - fadein_radius));
696                                         }
697                                         else {
698                                                 az->alpha = 0.0f;
699                                         }
700
701                                         /* fade in/out but no click */
702                                         az = NULL;
703                                 }
704
705                                 /* XXX force redraw to show/hide the action zone */
706                                 ED_area_tag_redraw(sa);
707                                 break;
708                         }
709                 }
710         }
711         
712         return az;
713 }
714
715
716 static void actionzone_exit(wmOperator *op)
717 {
718         if (op->customdata)
719                 MEM_freeN(op->customdata);
720         op->customdata = NULL;
721 }
722
723 /* send EVT_ACTIONZONE event */
724 static void actionzone_apply(bContext *C, wmOperator *op, int type)
725 {
726         wmEvent event;
727         wmWindow *win = CTX_wm_window(C);
728         sActionzoneData *sad = op->customdata;
729         
730         sad->modifier = RNA_int_get(op->ptr, "modifier");
731         
732         wm_event_init_from_window(win, &event);
733
734         if (type == AZONE_AREA)
735                 event.type = EVT_ACTIONZONE_AREA;
736         else if (type == AZONE_FULLSCREEN)
737                 event.type = EVT_ACTIONZONE_FULLSCREEN;
738         else
739                 event.type = EVT_ACTIONZONE_REGION;
740
741         event.val = KM_NOTHING;
742         event.customdata = op->customdata;
743         event.customdatafree = true;
744         op->customdata = NULL;
745         
746         wm_event_add(win, &event);
747 }
748
749 static int actionzone_invoke(bContext *C, wmOperator *op, const wmEvent *event)
750 {
751         ScrArea *sa = CTX_wm_area(C);
752         AZone *az = is_in_area_actionzone(sa, &event->x);
753         sActionzoneData *sad;
754         
755         /* quick escape */
756         if (az == NULL)
757                 return OPERATOR_PASS_THROUGH;
758         
759         /* ok we do the actionzone */
760         sad = op->customdata = MEM_callocN(sizeof(sActionzoneData), "sActionzoneData");
761         sad->sa1 = sa;
762         sad->az = az;
763         sad->x = event->x; sad->y = event->y;
764         
765         /* region azone directly reacts on mouse clicks */
766         if (ELEM(sad->az->type, AZONE_REGION, AZONE_FULLSCREEN)) {
767                 actionzone_apply(C, op, sad->az->type);
768                 actionzone_exit(op);
769                 return OPERATOR_FINISHED;
770         }
771         else {
772                 /* add modal handler */
773                 WM_event_add_modal_handler(C, op);
774                 
775                 return OPERATOR_RUNNING_MODAL;
776         }
777 }
778
779
780 static int actionzone_modal(bContext *C, wmOperator *op, const wmEvent *event)
781 {
782         wmWindow *win = CTX_wm_window(C);
783         bScreen *sc = CTX_wm_screen(C);
784         sActionzoneData *sad = op->customdata;
785         const int winsize_x = WM_window_pixels_x(win);
786         const int winsize_y = WM_window_pixels_y(win);
787
788         switch (event->type) {
789                 case MOUSEMOVE:
790                 {
791                         bool is_gesture;
792
793                         const int delta_x = (event->x - sad->x);
794                         const int delta_y = (event->y - sad->y);
795
796                         /* calculate gesture direction */
797                         if (delta_y > ABS(delta_x))
798                                 sad->gesture_dir = 'n';
799                         else if (delta_x > ABS(delta_y))
800                                 sad->gesture_dir = 'e';
801                         else if (delta_y < -ABS(delta_x))
802                                 sad->gesture_dir = 's';
803                         else
804                                 sad->gesture_dir = 'w';
805                         
806                         if (sad->az->type == AZONE_AREA) {
807                                 /* once we drag outside the actionzone, register a gesture
808                                  * check we're not on an edge so join finds the other area */
809                                 is_gesture = ((is_in_area_actionzone(sad->sa1, &event->x) != sad->az) &&
810                                               (screen_find_active_scredge(sc, winsize_x, winsize_y, event->x, event->y) == NULL));
811                         }
812                         else {
813                                 const int delta_min = 1;
814                                 is_gesture = (ABS(delta_x) > delta_min || ABS(delta_y) > delta_min);
815                         }
816
817                         /* gesture is large enough? */
818                         if (is_gesture) {
819                                 /* second area, for join when (sa1 != sa2) */
820                                 sad->sa2 = BKE_screen_find_area_xy(sc, SPACE_TYPE_ANY, event->x, event->y);
821                                 /* apply sends event */
822                                 actionzone_apply(C, op, sad->az->type);
823                                 actionzone_exit(op);
824                                 
825                                 return OPERATOR_FINISHED;
826                         }
827                         break;
828                 }
829                 case ESCKEY:
830                         actionzone_exit(op);
831                         return OPERATOR_CANCELLED;
832                 case LEFTMOUSE:
833                         actionzone_exit(op);
834                         return OPERATOR_CANCELLED;
835                         
836         }
837         
838         return OPERATOR_RUNNING_MODAL;
839 }
840
841 static void actionzone_cancel(bContext *UNUSED(C), wmOperator *op)
842 {
843         actionzone_exit(op);
844 }
845
846 static void SCREEN_OT_actionzone(wmOperatorType *ot)
847 {
848         /* identifiers */
849         ot->name = "Handle Area Action Zones";
850         ot->description = "Handle area action zones for mouse actions/gestures";
851         ot->idname = "SCREEN_OT_actionzone";
852         
853         ot->invoke = actionzone_invoke;
854         ot->modal = actionzone_modal;
855         ot->poll = actionzone_area_poll;
856         ot->cancel = actionzone_cancel;
857         
858         /* flags */
859         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
860         
861         RNA_def_int(ot->srna, "modifier", 0, 0, 2, "Modifier", "Modifier state", 0, 2);
862 }
863
864 /* ************** swap area operator *********************************** */
865
866 /* operator state vars used:  
867  * sa1          start area
868  * sa2          area to swap with
869  * 
870  * functions:
871  * 
872  * init()   set custom data for operator, based on actionzone event custom data
873  * 
874  * cancel()     cancel the operator
875  * 
876  * exit()       cleanup, send notifier
877  * 
878  * callbacks:
879  * 
880  * invoke() gets called on shift+lmb drag in actionzone
881  * call init(), add handler
882  * 
883  * modal()  accept modal events while doing it
884  */
885
886 typedef struct sAreaSwapData {
887         ScrArea *sa1, *sa2;
888 } sAreaSwapData;
889
890 static int area_swap_init(wmOperator *op, const wmEvent *event)
891 {
892         sAreaSwapData *sd = NULL;
893         sActionzoneData *sad = event->customdata;
894         
895         if (sad == NULL || sad->sa1 == NULL)
896                 return 0;
897         
898         sd = MEM_callocN(sizeof(sAreaSwapData), "sAreaSwapData");
899         sd->sa1 = sad->sa1;
900         sd->sa2 = sad->sa2;
901         op->customdata = sd;
902         
903         return 1;
904 }
905
906
907 static void area_swap_exit(bContext *C, wmOperator *op)
908 {
909         WM_cursor_modal_restore(CTX_wm_window(C));
910         if (op->customdata)
911                 MEM_freeN(op->customdata);
912         op->customdata = NULL;
913 }
914
915 static void area_swap_cancel(bContext *C, wmOperator *op)
916 {
917         area_swap_exit(C, op);
918 }
919
920 static int area_swap_invoke(bContext *C, wmOperator *op, const wmEvent *event)
921 {
922         
923         if (!area_swap_init(op, event))
924                 return OPERATOR_PASS_THROUGH;
925         
926         /* add modal handler */
927         WM_cursor_modal_set(CTX_wm_window(C), BC_SWAPAREA_CURSOR);
928         WM_event_add_modal_handler(C, op);
929         
930         return OPERATOR_RUNNING_MODAL;
931         
932 }
933
934 static int area_swap_modal(bContext *C, wmOperator *op, const wmEvent *event)
935 {
936         sActionzoneData *sad = op->customdata;
937         
938         switch (event->type) {
939                 case MOUSEMOVE:
940                         /* second area, for join */
941                         sad->sa2 = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, event->x, event->y);
942                         break;
943                 case LEFTMOUSE: /* release LMB */
944                         if (event->val == KM_RELEASE) {
945                                 if (!sad->sa2 || sad->sa1 == sad->sa2) {
946                                         area_swap_cancel(C, op);
947                                         return OPERATOR_CANCELLED;
948                                 }
949
950                                 ED_area_tag_redraw(sad->sa1);
951                                 ED_area_tag_redraw(sad->sa2);
952
953                                 ED_area_swapspace(C, sad->sa1, sad->sa2);
954                                 
955                                 area_swap_exit(C, op);
956                                 
957                                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
958                                 
959                                 return OPERATOR_FINISHED;
960                         }
961                         break;
962                         
963                 case ESCKEY:
964                         area_swap_cancel(C, op);
965                         return OPERATOR_CANCELLED;
966         }
967         return OPERATOR_RUNNING_MODAL;
968 }
969
970 static void SCREEN_OT_area_swap(wmOperatorType *ot)
971 {
972         ot->name = "Swap Areas";
973         ot->description = "Swap selected areas screen positions";
974         ot->idname = "SCREEN_OT_area_swap";
975         
976         ot->invoke = area_swap_invoke;
977         ot->modal = area_swap_modal;
978         ot->poll = ED_operator_areaactive;
979         ot->cancel = area_swap_cancel;
980         
981         ot->flag = OPTYPE_BLOCKING;
982 }
983
984 /* *********** Duplicate area as new window operator ****************** */
985
986 /* operator callback */
987 static int area_dupli_invoke(bContext *C, wmOperator *op, const wmEvent *event)
988 {
989         wmWindow *newwin, *win = CTX_wm_window(C);
990         Scene *scene;
991         WorkSpace *workspace = WM_window_get_active_workspace(win);
992         WorkSpaceLayout *layout_old = WM_window_get_active_layout(win);
993         WorkSpaceLayout *layout_new;
994         bScreen *newsc;
995         ScrArea *sa;
996         rcti rect;
997         
998         win = CTX_wm_window(C);
999         scene = CTX_data_scene(C);
1000         sa = CTX_wm_area(C);
1001         
1002         /* XXX hrmf! */
1003         if (event->type == EVT_ACTIONZONE_AREA) {
1004                 sActionzoneData *sad = event->customdata;
1005                 
1006                 if (sad == NULL)
1007                         return OPERATOR_PASS_THROUGH;
1008                 
1009                 sa = sad->sa1;
1010         }
1011
1012         /* adds window to WM */
1013         rect = sa->totrct;
1014         BLI_rcti_translate(&rect, win->posx, win->posy);
1015         rect.xmax = rect.xmin + BLI_rcti_size_x(&rect) / U.pixelsize;
1016         rect.ymax = rect.ymin + BLI_rcti_size_y(&rect) / U.pixelsize;
1017
1018         newwin = WM_window_open(C, &rect);
1019         if (newwin == NULL) {
1020                 BKE_report(op->reports, RPT_ERROR, "Failed to open window!");
1021                 goto finally;
1022         }
1023
1024         *newwin->stereo3d_format = *win->stereo3d_format;
1025
1026         newwin->scene = scene;
1027
1028         WM_window_set_active_workspace(newwin, workspace);
1029         /* allocs new screen and adds to newly created window, using window size */
1030         layout_new = ED_workspace_layout_add(workspace, newwin, BKE_workspace_layout_name_get(layout_old));
1031         newsc = BKE_workspace_layout_screen_get(layout_new);
1032         WM_window_set_active_layout(newwin, workspace, layout_new);
1033
1034         /* copy area to new screen */
1035         ED_area_data_copy((ScrArea *)newsc->areabase.first, sa, true);
1036
1037         ED_area_tag_redraw((ScrArea *)newsc->areabase.first);
1038
1039         /* screen, areas init */
1040         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1041
1042
1043 finally:
1044         if (event->type == EVT_ACTIONZONE_AREA)
1045                 actionzone_exit(op);
1046         
1047         if (newwin) {
1048                 return OPERATOR_FINISHED;
1049         }
1050         else {
1051                 return OPERATOR_CANCELLED;
1052         }
1053 }
1054
1055 static void SCREEN_OT_area_dupli(wmOperatorType *ot)
1056 {
1057         ot->name = "Duplicate Area into New Window";
1058         ot->description = "Duplicate selected area into new window";
1059         ot->idname = "SCREEN_OT_area_dupli";
1060         
1061         ot->invoke = area_dupli_invoke;
1062         ot->poll = ED_operator_areaactive;
1063 }
1064
1065
1066 /* ************** move area edge operator *********************************** */
1067
1068 /* operator state vars used:  
1069  * x, y             mouse coord near edge
1070  * delta            movement of edge
1071  * 
1072  * functions:
1073  * 
1074  * init()   set default property values, find edge based on mouse coords, test
1075  * if the edge can be moved, select edges, calculate min and max movement
1076  * 
1077  * apply()      apply delta on selection
1078  * 
1079  * exit()       cleanup, send notifier
1080  * 
1081  * cancel() cancel moving
1082  * 
1083  * callbacks:
1084  * 
1085  * exec()   execute without any user interaction, based on properties
1086  * call init(), apply(), exit()
1087  * 
1088  * invoke() gets called on mouse click near edge
1089  * call init(), add handler
1090  * 
1091  * modal()  accept modal events while doing it
1092  * call apply() with delta motion
1093  * call exit() and remove handler
1094  */
1095
1096 typedef struct sAreaMoveData {
1097         int bigger, smaller, origval;
1098         char dir;
1099         bool do_snap;
1100 } sAreaMoveData;
1101
1102 /* helper call to move area-edge, sets limits
1103  * need window size in order to get correct limits */
1104 static void area_move_set_limits(bScreen *sc, int dir,
1105                                  const int winsize_x, const int winsize_y,
1106                                  int *bigger, int *smaller)
1107 {
1108         ScrArea *sa;
1109         int areaminy = ED_area_headersize();
1110         int areamin;
1111         
1112         /* we check all areas and test for free space with MINSIZE */
1113         *bigger = *smaller = 100000;
1114         
1115         for (sa = sc->areabase.first; sa; sa = sa->next) {
1116                 if (dir == 'h') {
1117                         int y1;
1118                         areamin = areaminy;
1119                         
1120                         if (sa->v1->vec.y > 0)
1121                                 areamin += U.pixelsize;
1122                         if (sa->v2->vec.y < winsize_y - 1)
1123                                 areamin += U.pixelsize;
1124                         
1125                         y1 = sa->v2->vec.y - sa->v1->vec.y + 1 - areamin;
1126                         
1127                         /* if top or down edge selected, test height */
1128                         if (sa->v1->editflag && sa->v4->editflag)
1129                                 *bigger = min_ii(*bigger, y1);
1130                         else if (sa->v2->editflag && sa->v3->editflag)
1131                                 *smaller = min_ii(*smaller, y1);
1132                 }
1133                 else {
1134                         int x1;
1135                         areamin = AREAMINX;
1136                         
1137                         if (sa->v1->vec.x > 0)
1138                                 areamin += U.pixelsize;
1139                         if (sa->v4->vec.x < winsize_x - 1)
1140                                 areamin += U.pixelsize;
1141                         
1142                         x1 = sa->v4->vec.x - sa->v1->vec.x + 1 - areamin;
1143                         
1144                         /* if left or right edge selected, test width */
1145                         if (sa->v1->editflag && sa->v2->editflag)
1146                                 *bigger = min_ii(*bigger, x1);
1147                         else if (sa->v3->editflag && sa->v4->editflag)
1148                                 *smaller = min_ii(*smaller, x1);
1149                 }
1150         }
1151 }
1152
1153 /* validate selection inside screen, set variables OK */
1154 /* return 0: init failed */
1155 static int area_move_init(bContext *C, wmOperator *op)
1156 {
1157         bScreen *sc = CTX_wm_screen(C);
1158         wmWindow *win = CTX_wm_window(C);
1159         ScrEdge *actedge;
1160         sAreaMoveData *md;
1161         ScrVert *v1;
1162         const int winsize_x = WM_window_pixels_x(win);
1163         const int winsize_y = WM_window_pixels_y(win);
1164         int x, y;
1165         
1166         /* required properties */
1167         x = RNA_int_get(op->ptr, "x");
1168         y = RNA_int_get(op->ptr, "y");
1169         
1170         /* setup */
1171         actedge = screen_find_active_scredge(sc, winsize_x, winsize_y, x, y);
1172         if (actedge == NULL) return 0;
1173         
1174         md = MEM_callocN(sizeof(sAreaMoveData), "sAreaMoveData");
1175         op->customdata = md;
1176         
1177         md->dir = scredge_is_horizontal(actedge) ? 'h' : 'v';
1178         if (md->dir == 'h') md->origval = actedge->v1->vec.y;
1179         else md->origval = actedge->v1->vec.x;
1180         
1181         select_connected_scredge(sc, actedge);
1182         /* now all vertices with 'flag==1' are the ones that can be moved. Move this to editflag */
1183         for (v1 = sc->vertbase.first; v1; v1 = v1->next)
1184                 v1->editflag = v1->flag;
1185         
1186         area_move_set_limits(sc, md->dir, winsize_x, winsize_y, &md->bigger, &md->smaller);
1187         
1188         return 1;
1189 }
1190
1191 static int area_snap_calc_location(
1192         const bScreen *sc, const int delta,
1193         const int origval, const int dir,
1194         const int bigger, const int smaller)
1195 {
1196         int final_loc = -1;
1197
1198         const int m_loc = origval + delta;
1199         const int axis = (dir == 'v') ? 0 : 1;
1200         int snap_dist;
1201         int dist;
1202         {
1203                 /* Test the snap to middle. */
1204                 int middle = origval + (bigger - smaller) / 2;
1205                 middle -= (middle % AREAGRID);
1206
1207                 snap_dist = abs(m_loc - middle);
1208                 final_loc = middle;
1209         }
1210
1211         for (const ScrVert *v1 = sc->vertbase.first; v1; v1 = v1->next) {
1212                 if (v1->editflag) {
1213                         const int v_loc = (&v1->vec.x)[!axis];
1214
1215                         for (const ScrVert *v2 = sc->vertbase.first; v2; v2 = v2->next) {
1216                                 if (!v2->editflag) {
1217                                         if (v_loc == (&v2->vec.x)[!axis]) {
1218                                                 const int v_loc2 = (&v2->vec.x)[axis];
1219                                                 /* Do not snap to the vertices at the ends. */
1220                                                 if ((origval - smaller) < v_loc2 && v_loc2 < (origval + bigger)) {
1221                                                         dist = abs(m_loc - v_loc2);
1222                                                         if (dist <= snap_dist) {
1223                                                                 snap_dist = dist;
1224                                                                 final_loc = v_loc2;
1225                                                         }
1226                                                 }
1227                                         }
1228                                 }
1229                         }
1230                 }
1231         }
1232
1233         return final_loc;
1234 }
1235
1236 /* moves selected screen edge amount of delta, used by split & move */
1237 static void area_move_apply_do(
1238         const bContext *C, int delta,
1239         const int origval, const int dir,
1240         const int bigger, const int smaller,
1241         const bool do_snap)
1242 {
1243         bScreen *sc = CTX_wm_screen(C);
1244         ScrVert *v1;
1245         bool doredraw = false;
1246         CLAMP(delta, -smaller, bigger);
1247
1248         short final_loc = -1;
1249
1250         if (do_snap) {
1251                 final_loc = area_snap_calc_location(sc, delta, origval, dir, bigger, smaller);
1252         }
1253         else {
1254                 final_loc = origval + delta;
1255                 if (delta != bigger && delta != -smaller) {
1256                         final_loc -= (final_loc % AREAGRID);
1257                 }
1258         }
1259
1260         BLI_assert(final_loc != -1);
1261         short axis = (dir == 'v') ? 0 : 1;
1262
1263         for (v1 = sc->vertbase.first; v1; v1 = v1->next) {
1264                 if (v1->editflag) {
1265                         short oldval = (&v1->vec.x)[axis];
1266                         (&v1->vec.x)[axis] = final_loc;
1267
1268                         if (oldval == final_loc) {
1269                                 /* nothing will change to the other vertices either. */
1270                                 break;
1271                         }
1272                         doredraw = true;
1273                 }
1274         }
1275
1276         /* only redraw if we actually moved a screen vert, for AREAGRID */
1277         if (doredraw) {
1278                 for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) {
1279                         if (sa->v1->editflag || sa->v2->editflag || sa->v3->editflag || sa->v4->editflag) {
1280                                 ED_area_tag_redraw(sa);
1281                         }
1282                 }
1283                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL); /* redraw everything */
1284                 /* Update preview thumbnail */
1285                 BKE_icon_changed(sc->id.icon_id);
1286         }
1287 }
1288
1289 static void area_move_apply(bContext *C, wmOperator *op)
1290 {
1291         sAreaMoveData *md = op->customdata;
1292         int delta = RNA_int_get(op->ptr, "delta");
1293
1294         area_move_apply_do(C, delta, md->origval, md->dir, md->bigger, md->smaller, md->do_snap);
1295 }
1296
1297 static void area_move_exit(bContext *C, wmOperator *op)
1298 {
1299         if (op->customdata)
1300                 MEM_freeN(op->customdata);
1301         op->customdata = NULL;
1302         
1303         /* this makes sure aligned edges will result in aligned grabbing */
1304         removedouble_scrverts(CTX_wm_screen(C));
1305         removedouble_scredges(CTX_wm_screen(C));
1306 }
1307
1308 static int area_move_exec(bContext *C, wmOperator *op)
1309 {
1310         if (!area_move_init(C, op))
1311                 return OPERATOR_CANCELLED;
1312         
1313         area_move_apply(C, op);
1314         area_move_exit(C, op);
1315         
1316         return OPERATOR_FINISHED;
1317 }
1318
1319 /* interaction callback */
1320 static int area_move_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1321 {
1322         RNA_int_set(op->ptr, "x", event->x);
1323         RNA_int_set(op->ptr, "y", event->y);
1324         
1325         if (!area_move_init(C, op)) 
1326                 return OPERATOR_PASS_THROUGH;
1327         
1328         /* add temp handler */
1329         WM_event_add_modal_handler(C, op);
1330         
1331         return OPERATOR_RUNNING_MODAL;
1332 }
1333
1334 static void area_move_cancel(bContext *C, wmOperator *op)
1335 {
1336         
1337         RNA_int_set(op->ptr, "delta", 0);
1338         area_move_apply(C, op);
1339         area_move_exit(C, op);
1340 }
1341
1342 /* modal callback for while moving edges */
1343 static int area_move_modal(bContext *C, wmOperator *op, const wmEvent *event)
1344 {
1345         sAreaMoveData *md = op->customdata;
1346         int delta, x, y;
1347         
1348         /* execute the events */
1349         switch (event->type) {
1350                 case MOUSEMOVE:
1351                 {
1352                         x = RNA_int_get(op->ptr, "x");
1353                         y = RNA_int_get(op->ptr, "y");
1354                         
1355                         delta = (md->dir == 'v') ? event->x - x : event->y - y;
1356                         RNA_int_set(op->ptr, "delta", delta);
1357                         
1358                         area_move_apply(C, op);
1359                         break;
1360                 }
1361                 case EVT_MODAL_MAP:
1362                 {
1363                         switch (event->val) {
1364                                 case KM_MODAL_APPLY:
1365                                         area_move_exit(C, op);
1366                                         return OPERATOR_FINISHED;
1367                                         
1368                                 case KM_MODAL_CANCEL:
1369                                         area_move_cancel(C, op);
1370                                         return OPERATOR_CANCELLED;
1371
1372                                 case KM_MODAL_SNAP_ON:
1373                                         md->do_snap = true;
1374                                         break;
1375                                 case KM_MODAL_SNAP_OFF:
1376                                         md->do_snap = false;
1377                                         break;
1378                         }
1379                         break;
1380                 }
1381         }
1382         
1383         return OPERATOR_RUNNING_MODAL;
1384 }
1385
1386 static void SCREEN_OT_area_move(wmOperatorType *ot)
1387 {
1388         /* identifiers */
1389         ot->name = "Move Area Edges";
1390         ot->description = "Move selected area edges";
1391         ot->idname = "SCREEN_OT_area_move";
1392         
1393         ot->exec = area_move_exec;
1394         ot->invoke = area_move_invoke;
1395         ot->cancel = area_move_cancel;
1396         ot->modal = area_move_modal;
1397         ot->poll = ED_operator_screen_mainwinactive; /* when mouse is over area-edge */
1398         
1399         /* flags */
1400         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
1401         
1402         /* rna */
1403         RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
1404         RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
1405         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
1406 }
1407
1408 /* ************** split area operator *********************************** */
1409
1410 /* 
1411  * operator state vars:  
1412  * fac              spit point
1413  * dir              direction 'v' or 'h'
1414  * 
1415  * operator customdata:
1416  * area             pointer to (active) area
1417  * x, y                 last used mouse pos
1418  * (more, see below)
1419  * 
1420  * functions:
1421  * 
1422  * init()   set default property values, find area based on context
1423  * 
1424  * apply()      split area based on state vars
1425  * 
1426  * exit()       cleanup, send notifier
1427  * 
1428  * cancel() remove duplicated area
1429  * 
1430  * callbacks:
1431  * 
1432  * exec()   execute without any user interaction, based on state vars
1433  * call init(), apply(), exit()
1434  * 
1435  * invoke() gets called on mouse click in action-widget
1436  * call init(), add modal handler
1437  * call apply() with initial motion
1438  * 
1439  * modal()  accept modal events while doing it
1440  * call move-areas code with delta motion
1441  * call exit() or cancel() and remove handler
1442  */
1443
1444 typedef struct sAreaSplitData {
1445         int x, y;   /* last used mouse position */
1446         
1447         int origval;            /* for move areas */
1448         int bigger, smaller;    /* constraints for moving new edge */
1449         int delta;              /* delta move edge */
1450         int origmin, origsize;  /* to calculate fac, for property storage */
1451         int previewmode;        /* draw previewline, then split */
1452         void *draw_callback;    /* call `ED_screen_draw_split_preview` */
1453         bool do_snap;
1454
1455         ScrEdge *nedge;         /* new edge */
1456         ScrArea *sarea;         /* start area */
1457         ScrArea *narea;         /* new area */
1458         
1459 } sAreaSplitData;
1460
1461 static void area_split_draw_cb(const struct wmWindow *UNUSED(win), void *userdata)
1462 {
1463         const wmOperator *op = userdata;
1464
1465         sAreaSplitData *sd = op->customdata;
1466         if (sd->sarea) {
1467                 int dir = RNA_enum_get(op->ptr, "direction");
1468                 float fac = RNA_float_get(op->ptr, "factor");
1469
1470                 ED_screen_draw_split_preview(sd->sarea, dir, fac);
1471         }
1472 }
1473
1474 /* generic init, menu case, doesn't need active area */
1475 static int area_split_menu_init(bContext *C, wmOperator *op)
1476 {
1477         sAreaSplitData *sd;
1478         
1479         /* custom data */
1480         sd = (sAreaSplitData *)MEM_callocN(sizeof(sAreaSplitData), "op_area_split");
1481         op->customdata = sd;
1482         
1483         sd->sarea = CTX_wm_area(C);
1484
1485         return 1;
1486 }
1487
1488 /* generic init, no UI stuff here, assumes active area */
1489 static int area_split_init(bContext *C, wmOperator *op)
1490 {
1491         ScrArea *sa = CTX_wm_area(C);
1492         sAreaSplitData *sd;
1493         int areaminy = ED_area_headersize() + 1;
1494         int dir;
1495         
1496         /* required context */
1497         if (sa == NULL) return 0;
1498         
1499         /* required properties */
1500         dir = RNA_enum_get(op->ptr, "direction");
1501         
1502         /* minimal size */
1503         if (dir == 'v' && sa->winx < 2 * AREAMINX) return 0;
1504         if (dir == 'h' && sa->winy < 2 * areaminy) return 0;
1505         
1506         /* custom data */
1507         sd = (sAreaSplitData *)MEM_callocN(sizeof(sAreaSplitData), "op_area_split");
1508         op->customdata = sd;
1509         
1510         sd->sarea = sa;
1511         sd->origsize = dir == 'v' ? sa->winx : sa->winy;
1512         sd->origmin = dir == 'v' ? sa->totrct.xmin : sa->totrct.ymin;
1513         
1514         return 1;
1515 }
1516
1517 /* with sa as center, sb is located at: 0=W, 1=N, 2=E, 3=S */
1518 /* used with split operator */
1519 static ScrEdge *area_findsharededge(bScreen *screen, ScrArea *sa, ScrArea *sb)
1520 {
1521         ScrVert *sav1 = sa->v1;
1522         ScrVert *sav2 = sa->v2;
1523         ScrVert *sav3 = sa->v3;
1524         ScrVert *sav4 = sa->v4;
1525         ScrVert *sbv1 = sb->v1;
1526         ScrVert *sbv2 = sb->v2;
1527         ScrVert *sbv3 = sb->v3;
1528         ScrVert *sbv4 = sb->v4;
1529         
1530         if (sav1 == sbv4 && sav2 == sbv3) { /* sa to right of sb = W */
1531                 return screen_findedge(screen, sav1, sav2);
1532         }
1533         else if (sav2 == sbv1 && sav3 == sbv4) { /* sa to bottom of sb = N */
1534                 return screen_findedge(screen, sav2, sav3);
1535         }
1536         else if (sav3 == sbv2 && sav4 == sbv1) { /* sa to left of sb = E */
1537                 return screen_findedge(screen, sav3, sav4);
1538         }
1539         else if (sav1 == sbv2 && sav4 == sbv3) { /* sa on top of sb = S*/
1540                 return screen_findedge(screen, sav1, sav4);
1541         }
1542         
1543         return NULL;
1544 }
1545
1546
1547 /* do the split, return success */
1548 static int area_split_apply(bContext *C, wmOperator *op)
1549 {
1550         bScreen *sc = CTX_wm_screen(C);
1551         sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
1552         float fac;
1553         int dir;
1554         
1555         fac = RNA_float_get(op->ptr, "factor");
1556         dir = RNA_enum_get(op->ptr, "direction");
1557         
1558         sd->narea = area_split(sc, sd->sarea, dir, fac, 0); /* 0 = no merge */
1559         
1560         if (sd->narea) {
1561                 ScrVert *sv;
1562                 
1563                 sd->nedge = area_findsharededge(sc, sd->sarea, sd->narea);
1564                 
1565                 /* select newly created edge, prepare for moving edge */
1566                 for (sv = sc->vertbase.first; sv; sv = sv->next)
1567                         sv->editflag = 0;
1568                 
1569                 sd->nedge->v1->editflag = 1;
1570                 sd->nedge->v2->editflag = 1;
1571                 
1572                 if (dir == 'h') sd->origval = sd->nedge->v1->vec.y;
1573                 else sd->origval = sd->nedge->v1->vec.x;
1574
1575                 ED_area_tag_redraw(sd->sarea);
1576                 ED_area_tag_redraw(sd->narea);
1577
1578                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1579                 /* Update preview thumbnail */
1580                 BKE_icon_changed(sc->id.icon_id);
1581
1582                 return 1;
1583         }
1584         
1585         return 0;
1586 }
1587
1588 static void area_split_exit(bContext *C, wmOperator *op)
1589 {
1590         if (op->customdata) {
1591                 sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
1592                 if (sd->sarea) ED_area_tag_redraw(sd->sarea);
1593                 if (sd->narea) ED_area_tag_redraw(sd->narea);
1594
1595                 if (sd->draw_callback)
1596                         WM_draw_cb_exit(CTX_wm_window(C), sd->draw_callback);
1597
1598                 MEM_freeN(op->customdata);
1599                 op->customdata = NULL;
1600         }
1601         
1602         WM_cursor_modal_restore(CTX_wm_window(C));
1603         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1604         
1605         /* this makes sure aligned edges will result in aligned grabbing */
1606         removedouble_scrverts(CTX_wm_screen(C));
1607         removedouble_scredges(CTX_wm_screen(C));
1608 }
1609
1610
1611 /* UI callback, adds new handler */
1612 static int area_split_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1613 {
1614         wmWindow *win = CTX_wm_window(C);
1615         bScreen *sc = CTX_wm_screen(C);
1616         sAreaSplitData *sd;
1617         const int winsize_x = WM_window_pixels_x(win);
1618         const int winsize_y = WM_window_pixels_y(win);
1619         int dir;
1620         
1621         /* no full window splitting allowed */
1622         if (sc->state != SCREENNORMAL)
1623                 return OPERATOR_CANCELLED;
1624         
1625         if (event->type == EVT_ACTIONZONE_AREA) {
1626                 sActionzoneData *sad = event->customdata;
1627                 
1628                 if (sad == NULL || sad->modifier > 0) {
1629                         return OPERATOR_PASS_THROUGH;
1630                 }
1631                 
1632                 /* verify *sad itself */
1633                 if (sad->sa1 == NULL || sad->az == NULL)
1634                         return OPERATOR_PASS_THROUGH;
1635                 
1636                 /* is this our *sad? if areas not equal it should be passed on */
1637                 if (CTX_wm_area(C) != sad->sa1 || sad->sa1 != sad->sa2)
1638                         return OPERATOR_PASS_THROUGH;
1639                 
1640                 /* prepare operator state vars */
1641                 if (sad->gesture_dir == 'n' || sad->gesture_dir == 's') {
1642                         dir = 'h';
1643                         RNA_float_set(op->ptr, "factor", ((float)(event->x - sad->sa1->v1->vec.x)) / (float)sad->sa1->winx);
1644                 }
1645                 else {
1646                         dir = 'v';
1647                         RNA_float_set(op->ptr, "factor", ((float)(event->y - sad->sa1->v1->vec.y)) / (float)sad->sa1->winy);
1648                 }
1649                 RNA_enum_set(op->ptr, "direction", dir);
1650                 
1651                 /* general init, also non-UI case, adds customdata, sets area and defaults */
1652                 if (!area_split_init(C, op))
1653                         return OPERATOR_PASS_THROUGH;
1654                 
1655         }
1656         else {
1657                 ScrEdge *actedge;
1658                 int x, y;
1659                 
1660                 /* retrieve initial mouse coord, so we can find the active edge */
1661                 if (RNA_struct_property_is_set(op->ptr, "mouse_x"))
1662                         x = RNA_int_get(op->ptr, "mouse_x");
1663                 else
1664                         x = event->x;
1665                 
1666                 if (RNA_struct_property_is_set(op->ptr, "mouse_y"))
1667                         y = RNA_int_get(op->ptr, "mouse_y");
1668                 else
1669                         y = event->x;
1670                 
1671                 actedge = screen_find_active_scredge(sc, winsize_x, winsize_y, x, y);
1672                 if (actedge == NULL)
1673                         return OPERATOR_CANCELLED;
1674                 
1675                 dir = scredge_is_horizontal(actedge) ? 'v' : 'h';
1676                 
1677                 RNA_enum_set(op->ptr, "direction", dir);
1678                 
1679                 /* special case, adds customdata, sets defaults */
1680                 if (!area_split_menu_init(C, op))
1681                         return OPERATOR_CANCELLED;
1682                 
1683         }
1684         
1685         sd = (sAreaSplitData *)op->customdata;
1686         
1687         sd->x = event->x;
1688         sd->y = event->y;
1689         
1690         if (event->type == EVT_ACTIONZONE_AREA) {
1691                 
1692                 /* do the split */
1693                 if (area_split_apply(C, op)) {
1694                         area_move_set_limits(sc, dir, winsize_x, winsize_y, &sd->bigger, &sd->smaller);
1695                         
1696                         /* add temp handler for edge move or cancel */
1697                         WM_event_add_modal_handler(C, op);
1698                         
1699                         return OPERATOR_RUNNING_MODAL;
1700                 }
1701         }
1702         else {
1703                 sd->previewmode = 1;
1704                 sd->draw_callback = WM_draw_cb_activate(win, area_split_draw_cb, op);
1705                 /* add temp handler for edge move or cancel */
1706                 WM_event_add_modal_handler(C, op);
1707                 
1708                 return OPERATOR_RUNNING_MODAL;
1709                 
1710         }
1711         
1712         return OPERATOR_PASS_THROUGH;
1713 }
1714
1715 /* function to be called outside UI context, or for redo */
1716 static int area_split_exec(bContext *C, wmOperator *op)
1717 {
1718         
1719         if (!area_split_init(C, op))
1720                 return OPERATOR_CANCELLED;
1721         
1722         area_split_apply(C, op);
1723         area_split_exit(C, op);
1724         
1725         return OPERATOR_FINISHED;
1726 }
1727
1728
1729 static void area_split_cancel(bContext *C, wmOperator *op)
1730 {
1731         sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
1732         
1733         if (sd->previewmode) {
1734         }
1735         else {
1736                 if (screen_area_join(C, CTX_wm_screen(C), sd->sarea, sd->narea)) {
1737                         if (CTX_wm_area(C) == sd->narea) {
1738                                 CTX_wm_area_set(C, NULL);
1739                                 CTX_wm_region_set(C, NULL);
1740                         }
1741                         sd->narea = NULL;
1742                 }
1743         }
1744         area_split_exit(C, op);
1745 }
1746
1747 static int area_split_modal(bContext *C, wmOperator *op, const wmEvent *event)
1748 {
1749         sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
1750         float fac;
1751         int dir;
1752         
1753         /* execute the events */
1754         switch (event->type) {
1755                 case MOUSEMOVE:
1756                         dir = RNA_enum_get(op->ptr, "direction");
1757                         
1758                         sd->delta = (dir == 'v') ? event->x - sd->origval : event->y - sd->origval;
1759                         if (sd->previewmode == 0)
1760                                 area_move_apply_do(C, sd->delta, sd->origval, dir, sd->bigger, sd->smaller, sd->do_snap);
1761                         else {
1762                                 if (sd->sarea) {
1763                                         ED_area_tag_redraw(sd->sarea);
1764                                 }
1765                                 /* area context not set */
1766                                 sd->sarea = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, event->x, event->y);
1767                                 
1768                                 if (sd->sarea) {
1769                                         ED_area_tag_redraw(sd->sarea);
1770                                         if (dir == 'v') {
1771                                                 sd->origsize = sd->sarea->winx;
1772                                                 sd->origmin = sd->sarea->totrct.xmin;
1773                                         }
1774                                         else {
1775                                                 sd->origsize = sd->sarea->winy;
1776                                                 sd->origmin = sd->sarea->totrct.ymin;
1777                                         }
1778
1779                                         if (sd->do_snap) {
1780                                                 ScrArea *sa = sd->sarea;
1781                                                 sa->v1->editflag = sa->v2->editflag = sa->v3->editflag = sa->v4->editflag = 1;
1782
1783                                                 int snap_loc = area_snap_calc_location(
1784                                                         CTX_wm_screen(C), sd->delta, sd->origval, dir, sd->origmin + sd->origsize, -sd->origmin);
1785
1786                                                 sa->v1->editflag = sa->v2->editflag = sa->v3->editflag = sa->v4->editflag = 0;
1787                                                 fac = snap_loc - sd->origmin;
1788                                         }
1789                                         else {
1790                                                 fac = (dir == 'v') ? event->x - sd->origmin : event->y - sd->origmin;
1791                                         }
1792                                         RNA_float_set(op->ptr, "factor", fac / (float)sd->origsize);
1793                                 }
1794
1795                                 CTX_wm_screen(C)->do_draw = true;
1796
1797                         }
1798                         break;
1799                         
1800                 case LEFTMOUSE:
1801                         if (sd->previewmode) {
1802                                 area_split_apply(C, op);
1803                                 area_split_exit(C, op);
1804                                 return OPERATOR_FINISHED;
1805                         }
1806                         else {
1807                                 if (event->val == KM_RELEASE) { /* mouse up */
1808                                         area_split_exit(C, op);
1809                                         return OPERATOR_FINISHED;
1810                                 }
1811                         }
1812                         break;
1813                         
1814                 case MIDDLEMOUSE:
1815                 case TABKEY:
1816                         if (sd->previewmode == 0) {
1817                         }
1818                         else {
1819                                 dir = RNA_enum_get(op->ptr, "direction");
1820                                 
1821                                 if (event->val == KM_PRESS) {
1822                                         if (sd->sarea) {
1823                                                 ED_area_tag_redraw(sd->sarea);
1824                                                 
1825                                                 if (dir == 'v') {
1826                                                         RNA_enum_set(op->ptr, "direction", 'h');
1827                                                         WM_cursor_set(CTX_wm_window(C), CURSOR_X_MOVE);
1828                                                 }
1829                                                 else {
1830                                                         RNA_enum_set(op->ptr, "direction", 'v');
1831                                                         WM_cursor_set(CTX_wm_window(C), CURSOR_Y_MOVE);
1832                                                 }
1833                                         }
1834                                 }
1835                         }
1836                         
1837                         break;
1838                         
1839                 case RIGHTMOUSE: /* cancel operation */
1840                 case ESCKEY:
1841                         area_split_cancel(C, op);
1842                         return OPERATOR_CANCELLED;
1843
1844                 case LEFTCTRLKEY:
1845                         sd->do_snap = event->val == KM_PRESS;
1846                         break;
1847         }
1848         
1849         return OPERATOR_RUNNING_MODAL;
1850 }
1851
1852 static const EnumPropertyItem prop_direction_items[] = {
1853         {'h', "HORIZONTAL", 0, "Horizontal", ""},
1854         {'v', "VERTICAL", 0, "Vertical", ""},
1855         {0, NULL, 0, NULL, NULL}
1856 };
1857
1858 static void SCREEN_OT_area_split(wmOperatorType *ot)
1859 {
1860         ot->name = "Split Area";
1861         ot->description = "Split selected area into new windows";
1862         ot->idname = "SCREEN_OT_area_split";
1863         
1864         ot->exec = area_split_exec;
1865         ot->invoke = area_split_invoke;
1866         ot->modal = area_split_modal;
1867         ot->cancel = area_split_cancel;
1868         
1869         ot->poll = screen_active_editable;
1870
1871         /* flags */
1872         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
1873         
1874         /* rna */
1875         RNA_def_enum(ot->srna, "direction", prop_direction_items, 'h', "Direction", "");
1876         RNA_def_float(ot->srna, "factor", 0.5f, 0.0, 1.0, "Factor", "", 0.0, 1.0);
1877         RNA_def_int(ot->srna, "mouse_x", -100, INT_MIN, INT_MAX, "Mouse X", "", INT_MIN, INT_MAX);
1878         RNA_def_int(ot->srna, "mouse_y", -100, INT_MIN, INT_MAX, "Mouse Y", "", INT_MIN, INT_MAX);
1879 }
1880
1881
1882
1883 /* ************** scale region edge operator *********************************** */
1884
1885 typedef struct RegionMoveData {
1886         AZone *az;
1887         ARegion *ar;
1888         ScrArea *sa;
1889         int bigger, smaller, origval;
1890         int origx, origy;
1891         int maxsize;
1892         AZEdge edge;
1893         
1894 } RegionMoveData;
1895
1896
1897 static int area_max_regionsize(ScrArea *sa, ARegion *scalear, AZEdge edge)
1898 {
1899         ARegion *ar;
1900         int dist;
1901         
1902         if (edge == AE_RIGHT_TO_TOPLEFT || edge == AE_LEFT_TO_TOPRIGHT) {
1903                 dist = BLI_rcti_size_x(&sa->totrct);
1904         }
1905         else {  /* AE_BOTTOM_TO_TOPLEFT, AE_TOP_TO_BOTTOMRIGHT */
1906                 dist = BLI_rcti_size_y(&sa->totrct);
1907         }
1908         
1909         /* subtractwidth of regions on opposite side 
1910          * prevents dragging regions into other opposite regions */
1911         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1912                 if (ar == scalear)
1913                         continue;
1914                 
1915                 if (scalear->alignment == RGN_ALIGN_TOP && ar->alignment == RGN_ALIGN_BOTTOM)
1916                         dist -= ar->winy;
1917                 else if (scalear->alignment == RGN_ALIGN_BOTTOM && ar->alignment == RGN_ALIGN_TOP)
1918                         dist -= ar->winy;
1919                 else if (scalear->alignment == RGN_ALIGN_LEFT && ar->alignment == RGN_ALIGN_RIGHT)
1920                         dist -= ar->winx;
1921                 else if (scalear->alignment == RGN_ALIGN_RIGHT && ar->alignment == RGN_ALIGN_LEFT)
1922                         dist -= ar->winx;
1923                 
1924                 /* case of regions in regions, like operator properties panel */
1925                 /* these can sit on top of other regions such as headers, so account for this */
1926                 else if (edge == AE_BOTTOM_TO_TOPLEFT && scalear->alignment & RGN_ALIGN_TOP &&
1927                          ar->alignment == RGN_ALIGN_TOP && ar->regiontype == RGN_TYPE_HEADER)
1928                 {
1929                         dist -= ar->winy;
1930                 }
1931                 else if (edge == AE_TOP_TO_BOTTOMRIGHT && scalear->alignment & RGN_ALIGN_BOTTOM &&
1932                          ar->alignment == RGN_ALIGN_BOTTOM && ar->regiontype == RGN_TYPE_HEADER)
1933                 {
1934                         dist -= ar->winy;
1935                 }
1936         }
1937
1938         return dist;
1939 }
1940
1941 static int region_scale_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1942 {
1943         sActionzoneData *sad = event->customdata;
1944         AZone *az;
1945         
1946         if (event->type != EVT_ACTIONZONE_REGION) {
1947                 BKE_report(op->reports, RPT_ERROR, "Can only scale region size from an action zone");
1948                 return OPERATOR_CANCELLED;
1949         }
1950         
1951         az = sad->az;
1952         
1953         if (az->ar) {
1954                 RegionMoveData *rmd = MEM_callocN(sizeof(RegionMoveData), "RegionMoveData");
1955                 int maxsize;
1956                 
1957                 op->customdata = rmd;
1958                 
1959                 rmd->az = az;
1960                 rmd->ar = az->ar;
1961                 rmd->sa = sad->sa1;
1962                 rmd->edge = az->edge;
1963                 rmd->origx = event->x;
1964                 rmd->origy = event->y;
1965                 rmd->maxsize = area_max_regionsize(rmd->sa, rmd->ar, rmd->edge);
1966                 
1967                 /* if not set we do now, otherwise it uses type */
1968                 if (rmd->ar->sizex == 0)
1969                         rmd->ar->sizex = rmd->ar->winx;
1970                 if (rmd->ar->sizey == 0)
1971                         rmd->ar->sizey = rmd->ar->winy;
1972                 
1973                 /* now copy to regionmovedata */
1974                 if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT) {
1975                         rmd->origval = rmd->ar->sizex;
1976                 }
1977                 else {
1978                         rmd->origval = rmd->ar->sizey;
1979                 }
1980                 
1981                 /* limit headers to standard height for now */
1982                 if (rmd->ar->regiontype == RGN_TYPE_HEADER)
1983                         maxsize = ED_area_headersize();
1984                 else
1985                         maxsize = 1000;
1986                 
1987                 CLAMP(rmd->maxsize, 0, maxsize);
1988                 
1989                 /* add temp handler */
1990                 WM_event_add_modal_handler(C, op);
1991                 
1992                 return OPERATOR_RUNNING_MODAL;
1993         }
1994         
1995         return OPERATOR_FINISHED;
1996 }
1997
1998 static int region_scale_get_maxsize(RegionMoveData *rmd)
1999 {
2000         int maxsize = 0;
2001
2002         if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT) {
2003                 return  (int) ( (rmd->sa->winx / UI_DPI_FAC) - UI_UNIT_X);
2004         }
2005
2006         if (rmd->ar->regiontype == RGN_TYPE_TOOL_PROPS) {
2007                 /* this calculation seems overly verbose
2008                  * can someone explain why this method is necessary? - campbell */
2009                 maxsize = rmd->maxsize - ((rmd->sa->headertype == HEADERTOP) ? UI_UNIT_Y * 2 : UI_UNIT_Y) - (UI_UNIT_Y / 4);
2010         }
2011
2012         return maxsize;
2013 }
2014
2015 static void region_scale_validate_size(RegionMoveData *rmd)
2016 {
2017         if ((rmd->ar->flag & RGN_FLAG_HIDDEN) == 0) {
2018                 short *size, maxsize = -1;
2019
2020
2021                 if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT)
2022                         size = &rmd->ar->sizex;
2023                 else
2024                         size = &rmd->ar->sizey;
2025
2026                 maxsize = region_scale_get_maxsize(rmd);
2027
2028                 if (*size > maxsize && maxsize > 0)
2029                         *size = maxsize;
2030         }
2031 }
2032
2033 static void region_scale_toggle_hidden(bContext *C, RegionMoveData *rmd)
2034 {
2035         /* hidden areas may have bad 'View2D.cur' value,
2036          * correct before displaying. see T45156 */
2037         if (rmd->ar->flag & RGN_FLAG_HIDDEN) {
2038                 UI_view2d_curRect_validate(&rmd->ar->v2d);
2039         }
2040
2041         region_toggle_hidden(C, rmd->ar, 0);
2042         region_scale_validate_size(rmd);
2043 }
2044
2045 static int region_scale_modal(bContext *C, wmOperator *op, const wmEvent *event)
2046 {
2047         RegionMoveData *rmd = op->customdata;
2048         int delta;
2049         
2050         /* execute the events */
2051         switch (event->type) {
2052                 case MOUSEMOVE:
2053                         
2054                         if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT) {
2055                                 delta = event->x - rmd->origx;
2056                                 if (rmd->edge == AE_LEFT_TO_TOPRIGHT) delta = -delta;
2057                                 
2058                                 /* region sizes now get multiplied */
2059                                 delta /= UI_DPI_FAC;
2060                                 
2061                                 rmd->ar->sizex = rmd->origval + delta;
2062                                 CLAMP(rmd->ar->sizex, 0, rmd->maxsize);
2063                                 
2064                                 if (rmd->ar->sizex < UI_UNIT_X) {
2065                                         rmd->ar->sizex = rmd->origval;
2066                                         if (!(rmd->ar->flag & RGN_FLAG_HIDDEN))
2067                                                 region_scale_toggle_hidden(C, rmd);
2068                                 }
2069                                 else if (rmd->ar->flag & RGN_FLAG_HIDDEN)
2070                                         region_scale_toggle_hidden(C, rmd);
2071                         }
2072                         else {
2073                                 int maxsize = region_scale_get_maxsize(rmd);
2074                                 delta = event->y - rmd->origy;
2075                                 if (rmd->edge == AE_BOTTOM_TO_TOPLEFT) delta = -delta;
2076                                 
2077                                 /* region sizes now get multiplied */
2078                                 delta /= UI_DPI_FAC;
2079
2080                                 rmd->ar->sizey = rmd->origval + delta;
2081                                 CLAMP(rmd->ar->sizey, 0, rmd->maxsize);
2082
2083                                 /* note, 'UI_UNIT_Y/4' means you need to drag the header almost
2084                                  * all the way down for it to become hidden, this is done
2085                                  * otherwise its too easy to do this by accident */
2086                                 if (rmd->ar->sizey < UI_UNIT_Y / 4) {
2087                                         rmd->ar->sizey = rmd->origval;
2088                                         if (!(rmd->ar->flag & RGN_FLAG_HIDDEN))
2089                                                 region_scale_toggle_hidden(C, rmd);
2090                                 }
2091                                 else if (maxsize > 0 && (rmd->ar->sizey > maxsize)) 
2092                                         rmd->ar->sizey = maxsize;
2093                                 else if (rmd->ar->flag & RGN_FLAG_HIDDEN)
2094                                         region_scale_toggle_hidden(C, rmd);
2095                         }
2096                         ED_area_tag_redraw(rmd->sa);
2097                         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
2098                         
2099                         break;
2100                         
2101                 case LEFTMOUSE:
2102                         if (event->val == KM_RELEASE) {
2103                                 
2104                                 if (ABS(event->x - rmd->origx) < 2 && ABS(event->y - rmd->origy) < 2) {
2105                                         if (rmd->ar->flag & RGN_FLAG_HIDDEN) {
2106                                                 region_scale_toggle_hidden(C, rmd);
2107                                         }
2108                                         else if (rmd->ar->flag & RGN_FLAG_TOO_SMALL) {
2109                                                 region_scale_validate_size(rmd);
2110                                         }
2111
2112                                         ED_area_tag_redraw(rmd->sa);
2113                                         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
2114                                 }
2115                                 MEM_freeN(op->customdata);
2116                                 op->customdata = NULL;
2117                                 
2118                                 return OPERATOR_FINISHED;
2119                         }
2120                         break;
2121                         
2122                 case ESCKEY:
2123                         break;
2124         }
2125         
2126         return OPERATOR_RUNNING_MODAL;
2127 }
2128
2129 static void region_scale_cancel(bContext *UNUSED(C), wmOperator *op)
2130 {
2131         MEM_freeN(op->customdata);
2132         op->customdata = NULL;
2133 }
2134
2135 static void SCREEN_OT_region_scale(wmOperatorType *ot)
2136 {
2137         /* identifiers */
2138         ot->name = "Scale Region Size";
2139         ot->description = "Scale selected area";
2140         ot->idname = "SCREEN_OT_region_scale";
2141         
2142         ot->invoke = region_scale_invoke;
2143         ot->modal = region_scale_modal;
2144         ot->cancel = region_scale_cancel;
2145         
2146         ot->poll = ED_operator_areaactive;
2147         
2148         /* flags */
2149         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
2150 }
2151
2152
2153 /* ************** frame change operator ***************************** */
2154
2155 static void areas_do_frame_follow(bContext *C, bool middle)
2156 {
2157         bScreen *scr = CTX_wm_screen(C);
2158         Scene *scene = CTX_data_scene(C);
2159         wmWindowManager *wm = CTX_wm_manager(C);
2160         for (wmWindow *window = wm->windows.first; window; window = window->next) {
2161                 const bScreen *screen = WM_window_get_active_screen(window);
2162
2163                 for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
2164                         for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) {
2165                                 /* do follow here if editor type supports it */
2166                                 if ((scr->redraws_flag & TIME_FOLLOW)) {
2167                                         if ((ar->regiontype == RGN_TYPE_WINDOW &&
2168                                              ELEM(sa->spacetype, SPACE_SEQ, SPACE_TIME, SPACE_IPO, SPACE_ACTION, SPACE_NLA)) ||
2169                                             (sa->spacetype == SPACE_CLIP && ar->regiontype == RGN_TYPE_PREVIEW))
2170                                         {
2171                                                 float w = BLI_rctf_size_x(&ar->v2d.cur);
2172
2173                                                 if (middle) {
2174                                                         if ((scene->r.cfra < ar->v2d.cur.xmin) || (scene->r.cfra > ar->v2d.cur.xmax)) {
2175                                                                 ar->v2d.cur.xmax = scene->r.cfra + (w / 2);
2176                                                                 ar->v2d.cur.xmin = scene->r.cfra - (w / 2);
2177                                                         }
2178                                                 }
2179                                                 else {
2180                                                         if (scene->r.cfra < ar->v2d.cur.xmin) {
2181                                                                 ar->v2d.cur.xmax = scene->r.cfra;
2182                                                                 ar->v2d.cur.xmin = ar->v2d.cur.xmax - w;
2183                                                         }
2184                                                         else if (scene->r.cfra > ar->v2d.cur.xmax) {
2185                                                                 ar->v2d.cur.xmin = scene->r.cfra;
2186                                                                 ar->v2d.cur.xmax = ar->v2d.cur.xmin + w;
2187                                                         }
2188                                                 }
2189                                         }
2190                                 }
2191                         }
2192                 }
2193         }
2194 }
2195
2196 /* function to be called outside UI context, or for redo */
2197 static int frame_offset_exec(bContext *C, wmOperator *op)
2198 {
2199         Main *bmain = CTX_data_main(C);
2200         Scene *scene = CTX_data_scene(C);
2201         int delta;
2202         
2203         delta = RNA_int_get(op->ptr, "delta");
2204
2205         CFRA += delta;
2206         FRAMENUMBER_MIN_CLAMP(CFRA);
2207         SUBFRA = 0.f;
2208         
2209         areas_do_frame_follow(C, false);
2210
2211         BKE_sound_seek_scene(bmain, scene);
2212
2213         WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2214         
2215         return OPERATOR_FINISHED;
2216 }
2217
2218 static void SCREEN_OT_frame_offset(wmOperatorType *ot)
2219 {
2220         ot->name = "Frame Offset";
2221         ot->idname = "SCREEN_OT_frame_offset";
2222         ot->description = "Move current frame forward/backward by a given number";
2223         
2224         ot->exec = frame_offset_exec;
2225         
2226         ot->poll = ED_operator_screenactive_norender;
2227         ot->flag = OPTYPE_UNDO_GROUPED;
2228         ot->undo_group = "FRAME_CHANGE";
2229         
2230         /* rna */
2231         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
2232 }
2233
2234
2235 /* function to be called outside UI context, or for redo */
2236 static int frame_jump_exec(bContext *C, wmOperator *op)
2237 {
2238         Main *bmain = CTX_data_main(C);
2239         Scene *scene = CTX_data_scene(C);
2240         wmTimer *animtimer = CTX_wm_screen(C)->animtimer;
2241
2242         /* Don't change CFRA directly if animtimer is running as this can cause
2243          * first/last frame not to be actually shown (bad since for example physics
2244          * simulations aren't reset properly).
2245          */
2246         if (animtimer) {
2247                 ScreenAnimData *sad = animtimer->customdata;
2248                 
2249                 sad->flag |= ANIMPLAY_FLAG_USE_NEXT_FRAME;
2250                 
2251                 if (RNA_boolean_get(op->ptr, "end"))
2252                         sad->nextfra = PEFRA;
2253                 else
2254                         sad->nextfra = PSFRA;
2255         }
2256         else {
2257                 if (RNA_boolean_get(op->ptr, "end"))
2258                         CFRA = PEFRA;
2259                 else
2260                         CFRA = PSFRA;
2261                 
2262                 areas_do_frame_follow(C, true);
2263
2264                 BKE_sound_seek_scene(bmain, scene);
2265
2266                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2267         }
2268         
2269         return OPERATOR_FINISHED;
2270 }
2271
2272 static void SCREEN_OT_frame_jump(wmOperatorType *ot)
2273 {
2274         ot->name = "Jump to Endpoint";
2275         ot->description = "Jump to first/last frame in frame range";
2276         ot->idname = "SCREEN_OT_frame_jump";
2277         
2278         ot->exec = frame_jump_exec;
2279         
2280         ot->poll = ED_operator_screenactive_norender;
2281         ot->flag = OPTYPE_UNDO_GROUPED;
2282         ot->undo_group = "FRAME_CHANGE";
2283         
2284         /* rna */
2285         RNA_def_boolean(ot->srna, "end", 0, "Last Frame", "Jump to the last frame of the frame range");
2286 }
2287
2288
2289 /* ************** jump to keyframe operator ***************************** */
2290
2291 /* function to be called outside UI context, or for redo */
2292 static int keyframe_jump_exec(bContext *C, wmOperator *op)
2293 {
2294         Main *bmain = CTX_data_main(C);
2295         Scene *scene = CTX_data_scene(C);
2296         Object *ob = CTX_data_active_object(C);
2297         bDopeSheet ads = {NULL};
2298         DLRBT_Tree keys;
2299         ActKeyColumn *ak;
2300         float cfra;
2301         const bool next = RNA_boolean_get(op->ptr, "next");
2302         bool done = false;
2303         
2304         /* sanity checks */
2305         if (scene == NULL)
2306                 return OPERATOR_CANCELLED;
2307
2308         cfra = (float)(CFRA);
2309
2310         /* init binarytree-list for getting keyframes */
2311         BLI_dlrbTree_init(&keys);
2312         
2313         /* seed up dummy dopesheet context with flags to perform necessary filtering */
2314         if ((scene->flag & SCE_KEYS_NO_SELONLY) == 0) {
2315                 /* only selected channels are included */
2316                 ads.filterflag |= ADS_FILTER_ONLYSEL;
2317         }
2318         
2319         /* populate tree with keyframe nodes */
2320         scene_to_keylist(&ads, scene, &keys, NULL);
2321         gpencil_to_keylist(&ads, scene->gpd, &keys);
2322
2323         if (ob) {
2324                 ob_to_keylist(&ads, ob, &keys, NULL);
2325                 gpencil_to_keylist(&ads, ob->gpd, &keys);
2326         }
2327         
2328         {
2329                 Mask *mask = CTX_data_edit_mask(C);
2330                 if (mask) {
2331                         MaskLayer *masklay = BKE_mask_layer_active(mask);
2332                         mask_to_keylist(&ads, masklay, &keys);
2333                 }
2334         }
2335
2336         /* build linked-list for searching */
2337         BLI_dlrbTree_linkedlist_sync(&keys);
2338         
2339         /* find matching keyframe in the right direction */
2340         if (next)
2341                 ak = (ActKeyColumn *)BLI_dlrbTree_search_next(&keys, compare_ak_cfraPtr, &cfra);
2342         else
2343                 ak = (ActKeyColumn *)BLI_dlrbTree_search_prev(&keys, compare_ak_cfraPtr, &cfra);
2344         
2345         while ((ak != NULL) && (done == false)) {
2346                 if (CFRA != (int)ak->cfra) {
2347                         /* this changes the frame, so set the frame and we're done */
2348                         CFRA = (int)ak->cfra;
2349                         done = true;
2350                 }
2351                 else {
2352                         /* take another step... */
2353                         if (next) {
2354                                 ak = ak->next;
2355                         }
2356                         else {
2357                                 ak = ak->prev;
2358                         }
2359                 }
2360         }
2361         
2362         /* free temp stuff */
2363         BLI_dlrbTree_free(&keys);
2364
2365         /* any success? */
2366         if (done == false) {
2367                 BKE_report(op->reports, RPT_INFO, "No more keyframes to jump to in this direction");
2368
2369                 return OPERATOR_CANCELLED;
2370         }
2371         else {
2372                 areas_do_frame_follow(C, true);
2373
2374                 BKE_sound_seek_scene(bmain, scene);
2375
2376                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2377
2378                 return OPERATOR_FINISHED;
2379         }
2380 }
2381
2382 static void SCREEN_OT_keyframe_jump(wmOperatorType *ot)
2383 {
2384         ot->name = "Jump to Keyframe";
2385         ot->description = "Jump to previous/next keyframe";
2386         ot->idname = "SCREEN_OT_keyframe_jump";
2387         
2388         ot->exec = keyframe_jump_exec;
2389         
2390         ot->poll = ED_operator_screenactive_norender;
2391         ot->flag = OPTYPE_UNDO_GROUPED;
2392         ot->undo_group = "FRAME_CHANGE";
2393         
2394         /* properties */
2395         RNA_def_boolean(ot->srna, "next", true, "Next Keyframe", "");
2396 }
2397
2398 /* ************** jump to marker operator ***************************** */
2399
2400 /* function to be called outside UI context, or for redo */
2401 static int marker_jump_exec(bContext *C, wmOperator *op)
2402 {
2403         Main *bmain = CTX_data_main(C);
2404         Scene *scene = CTX_data_scene(C);
2405         TimeMarker *marker;
2406         int closest = CFRA;
2407         const bool next = RNA_boolean_get(op->ptr, "next");
2408         bool found = false;
2409
2410         /* find matching marker in the right direction */
2411         for (marker = scene->markers.first; marker; marker = marker->next) {
2412                 if (next) {
2413                         if ((marker->frame > CFRA) && (!found || closest > marker->frame)) {
2414                                 closest = marker->frame;
2415                                 found = true;
2416                         }
2417                 }
2418                 else {
2419                         if ((marker->frame < CFRA) && (!found || closest < marker->frame)) {
2420                                 closest = marker->frame;
2421                                 found = true;
2422                         }
2423                 }
2424         }
2425
2426         /* any success? */
2427         if (!found) {
2428                 BKE_report(op->reports, RPT_INFO, "No more markers to jump to in this direction");
2429
2430                 return OPERATOR_CANCELLED;
2431         }
2432         else {
2433                 CFRA = closest;
2434
2435                 areas_do_frame_follow(C, true);
2436
2437                 BKE_sound_seek_scene(bmain, scene);
2438
2439                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2440
2441                 return OPERATOR_FINISHED;
2442         }
2443 }
2444
2445 static void SCREEN_OT_marker_jump(wmOperatorType *ot)
2446 {
2447         ot->name = "Jump to Marker";
2448         ot->description = "Jump to previous/next marker";
2449         ot->idname = "SCREEN_OT_marker_jump";
2450
2451         ot->exec = marker_jump_exec;
2452
2453         ot->poll = ED_operator_screenactive_norender;
2454         ot->flag = OPTYPE_UNDO_GROUPED;
2455         ot->undo_group = "FRAME_CHANGE";
2456
2457         /* properties */
2458         RNA_def_boolean(ot->srna, "next", true, "Next Marker", "");
2459 }
2460
2461 /* ************** switch screen operator ***************************** */
2462
2463 /* function to be called outside UI context, or for redo */
2464 static int screen_set_exec(bContext *C, wmOperator *op)
2465 {
2466         WorkSpace *workspace = CTX_wm_workspace(C);
2467         int delta = RNA_int_get(op->ptr, "delta");
2468
2469         if (ED_workspace_layout_cycle(workspace, delta, C)) {
2470                 return OPERATOR_FINISHED;
2471         }
2472
2473         return OPERATOR_CANCELLED;
2474 }
2475
2476 static void SCREEN_OT_screen_set(wmOperatorType *ot)
2477 {
2478         ot->name = "Set Screen";
2479         ot->description = "Cycle through available screens";
2480         ot->idname = "SCREEN_OT_screen_set";
2481         
2482         ot->exec = screen_set_exec;
2483         ot->poll = ED_operator_screenactive;
2484
2485         /* rna */
2486         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
2487 }
2488
2489 /* ************** screen full-area operator ***************************** */
2490
2491
2492 /* function to be called outside UI context, or for redo */
2493 static int screen_maximize_area_exec(bContext *C, wmOperator *op)
2494 {
2495         bScreen *screen = CTX_wm_screen(C);
2496         ScrArea *sa = NULL;
2497         const bool hide_panels = RNA_boolean_get(op->ptr, "use_hide_panels");
2498         
2499         /* search current screen for 'fullscreen' areas */
2500         /* prevents restoring info header, when mouse is over it */
2501         for (sa = screen->areabase.first; sa; sa = sa->next) {
2502                 if (sa->full) break;
2503         }
2504         
2505         if (sa == NULL) {
2506                 sa = CTX_wm_area(C);
2507         }
2508         
2509         if (hide_panels) {
2510                 if (!ELEM(screen->state, SCREENNORMAL, SCREENFULL)) {
2511                         return OPERATOR_CANCELLED;
2512                 }
2513                 ED_screen_state_toggle(C, CTX_wm_window(C), sa, SCREENFULL);
2514         }
2515         else {
2516                 if (!ELEM(screen->state, SCREENNORMAL, SCREENMAXIMIZED)) {
2517                         return OPERATOR_CANCELLED;
2518                 }
2519                 ED_screen_state_toggle(C, CTX_wm_window(C), sa, SCREENMAXIMIZED);
2520         }
2521
2522         return OPERATOR_FINISHED;
2523 }
2524
2525 static void SCREEN_OT_screen_full_area(wmOperatorType *ot)
2526 {
2527         PropertyRNA *prop;
2528
2529         ot->name = "Toggle Maximize Area";
2530         ot->description = "Toggle display selected area as fullscreen/maximized";
2531         ot->idname = "SCREEN_OT_screen_full_area";
2532         
2533         ot->exec = screen_maximize_area_exec;
2534         ot->poll = ED_operator_areaactive;
2535         ot->flag = 0;
2536
2537         prop = RNA_def_boolean(ot->srna, "use_hide_panels", false, "Hide Panels", "Hide all the panels");
2538         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2539 }
2540
2541 /* ************** join area operator ********************************************** */
2542
2543 /* operator state vars used:  
2544  * x1, y1     mouse coord in first area, which will disappear
2545  * x2, y2     mouse coord in 2nd area, which will become joined
2546  * 
2547  * functions:
2548  * 
2549  * init()   find edge based on state vars 
2550  * test if the edge divides two areas, 
2551  * store active and nonactive area,
2552  * 
2553  * apply()  do the actual join
2554  * 
2555  * exit()       cleanup, send notifier
2556  * 
2557  * callbacks:
2558  * 
2559  * exec()       calls init, apply, exit 
2560  * 
2561  * invoke() sets mouse coords in x,y
2562  * call init()
2563  * add modal handler
2564  * 
2565  * modal()      accept modal events while doing it
2566  * call apply() with active window and nonactive window
2567  * call exit() and remove handler when LMB confirm
2568  */
2569
2570 typedef struct sAreaJoinData {
2571         ScrArea *sa1;        /* first area to be considered */
2572         ScrArea *sa2;        /* second area to be considered */
2573         void *draw_callback; /* call `ED_screen_draw_join_shape` */
2574
2575 } sAreaJoinData;
2576
2577
2578 static void area_join_draw_cb(const struct wmWindow *UNUSED(win), void *userdata)
2579 {
2580         const wmOperator *op = userdata;
2581
2582         sAreaJoinData *sd = op->customdata;
2583         if (sd->sa1 && sd->sa2) {
2584                 ED_screen_draw_join_shape(sd->sa1, sd->sa2);
2585         }
2586 }
2587
2588 /* validate selection inside screen, set variables OK */
2589 /* return 0: init failed */
2590 /* XXX todo: find edge based on (x,y) and set other area? */
2591 static int area_join_init(bContext *C, wmOperator *op)
2592 {
2593         ScrArea *sa1, *sa2;
2594         sAreaJoinData *jd = NULL;
2595         int x1, y1;
2596         int x2, y2;
2597         int shared = 0;
2598         
2599         /* required properties, make negative to get return 0 if not set by caller */
2600         x1 = RNA_int_get(op->ptr, "min_x");
2601         y1 = RNA_int_get(op->ptr, "min_y");
2602         x2 = RNA_int_get(op->ptr, "max_x");
2603         y2 = RNA_int_get(op->ptr, "max_y");
2604         
2605         sa1 = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, x1, y1);
2606         sa2 = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, x2, y2);
2607         if (sa1 == NULL || sa2 == NULL || sa1 == sa2)
2608                 return 0;
2609         
2610         /* do areas share an edge? */
2611         if (sa1->v1 == sa2->v1 || sa1->v1 == sa2->v2 || sa1->v1 == sa2->v3 || sa1->v1 == sa2->v4) shared++;
2612         if (sa1->v2 == sa2->v1 || sa1->v2 == sa2->v2 || sa1->v2 == sa2->v3 || sa1->v2 == sa2->v4) shared++;
2613         if (sa1->v3 == sa2->v1 || sa1->v3 == sa2->v2 || sa1->v3 == sa2->v3 || sa1->v3 == sa2->v4) shared++;
2614         if (sa1->v4 == sa2->v1 || sa1->v4 == sa2->v2 || sa1->v4 == sa2->v3 || sa1->v4 == sa2->v4) shared++;
2615         if (shared != 2) {
2616                 printf("areas don't share edge\n");
2617                 return 0;
2618         }
2619         
2620         jd = (sAreaJoinData *)MEM_callocN(sizeof(sAreaJoinData), "op_area_join");
2621
2622         jd->sa1 = sa1;
2623         jd->sa2 = sa2;
2624
2625         op->customdata = jd;
2626
2627         jd->draw_callback = WM_draw_cb_activate(CTX_wm_window(C), area_join_draw_cb, op);
2628
2629         return 1;
2630 }
2631
2632 /* apply the join of the areas (space types) */
2633 static int area_join_apply(bContext *C, wmOperator *op)
2634 {
2635         sAreaJoinData *jd = (sAreaJoinData *)op->customdata;
2636         if (!jd) return 0;
2637         
2638         if (!screen_area_join(C, CTX_wm_screen(C), jd->sa1, jd->sa2)) {
2639                 return 0;
2640         }
2641         if (CTX_wm_area(C) == jd->sa2) {
2642                 CTX_wm_area_set(C, NULL);
2643                 CTX_wm_region_set(C, NULL);
2644         }
2645         
2646         return 1;
2647 }
2648
2649 /* finish operation */
2650 static void area_join_exit(bContext *C, wmOperator *op)
2651 {
2652         sAreaJoinData *jd = (sAreaJoinData *)op->customdata;
2653
2654         if (jd) {
2655                 if (jd->draw_callback)
2656                         WM_draw_cb_exit(CTX_wm_window(C), jd->draw_callback);
2657
2658                 MEM_freeN(jd);
2659                 op->customdata = NULL;
2660         }
2661         
2662         /* this makes sure aligned edges will result in aligned grabbing */
2663         removedouble_scredges(CTX_wm_screen(C));
2664         removenotused_scredges(CTX_wm_screen(C));
2665         removenotused_scrverts(CTX_wm_screen(C));
2666 }
2667
2668 static int area_join_exec(bContext *C, wmOperator *op)
2669 {
2670         if (!area_join_init(C, op)) 
2671                 return OPERATOR_CANCELLED;
2672         
2673         area_join_apply(C, op);
2674         area_join_exit(C, op);
2675         
2676         return OPERATOR_FINISHED;
2677 }
2678
2679 /* interaction callback */
2680 static int area_join_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2681 {
2682         
2683         if (event->type == EVT_ACTIONZONE_AREA) {
2684                 sActionzoneData *sad = event->customdata;
2685                 
2686                 if (sad == NULL || sad->modifier > 0) {
2687                         return OPERATOR_PASS_THROUGH;
2688                 }
2689                 
2690                 /* verify *sad itself */
2691                 if (sad->sa1 == NULL || sad->sa2 == NULL)
2692                         return OPERATOR_PASS_THROUGH;
2693                 
2694                 /* is this our *sad? if areas equal it should be passed on */
2695                 if (sad->sa1 == sad->sa2)
2696                         return OPERATOR_PASS_THROUGH;
2697                 
2698                 /* prepare operator state vars */
2699                 RNA_int_set(op->ptr, "min_x", sad->x);
2700                 RNA_int_set(op->ptr, "min_y", sad->y);
2701                 RNA_int_set(op->ptr, "max_x", event->x);
2702                 RNA_int_set(op->ptr, "max_y", event->y);
2703         }
2704         
2705         
2706         if (!area_join_init(C, op)) 
2707                 return OPERATOR_PASS_THROUGH;
2708         
2709         /* add temp handler */
2710         WM_event_add_modal_handler(C, op);
2711         
2712         return OPERATOR_RUNNING_MODAL;
2713 }
2714
2715 static void area_join_cancel(bContext *C, wmOperator *op)
2716 {
2717         WM_event_add_notifier(C, NC_WINDOW, NULL);
2718         
2719         area_join_exit(C, op);
2720 }
2721
2722 /* modal callback while selecting area (space) that will be removed */
2723 static int area_join_modal(bContext *C, wmOperator *op, const wmEvent *event)
2724 {
2725         bScreen *sc = CTX_wm_screen(C);
2726         sAreaJoinData *jd = (sAreaJoinData *)op->customdata;
2727         
2728         /* execute the events */
2729         switch (event->type) {
2730                         
2731                 case MOUSEMOVE: 
2732                 {
2733                         ScrArea *sa = BKE_screen_find_area_xy(sc, SPACE_TYPE_ANY, event->x, event->y);
2734                         int dir;
2735                         
2736                         if (sa) {
2737                                 if (jd->sa1 != sa) {
2738                                         dir = area_getorientation(jd->sa1, sa);
2739                                         if (dir != -1) {
2740                                                 jd->sa2 = sa;
2741                                         }
2742                                         else {
2743                                                 /* we are not bordering on the previously selected area 
2744                                                  * we check if area has common border with the one marked for removal
2745                                                  * in this case we can swap areas.
2746                                                  */
2747                                                 dir = area_getorientation(sa, jd->sa2);
2748                                                 if (dir != -1) {
2749                                                         jd->sa1 = jd->sa2;
2750                                                         jd->sa2 = sa;
2751                                                 }
2752                                                 else {
2753                                                         jd->sa2 = NULL;
2754                                                 }
2755                                         }
2756                                         WM_event_add_notifier(C, NC_WINDOW, NULL);
2757                                 }
2758                                 else {
2759                                         /* we are back in the area previously selected for keeping 
2760                                          * we swap the areas if possible to allow user to choose */
2761                                         if (jd->sa2 != NULL) {
2762                                                 jd->sa1 = jd->sa2;
2763                                                 jd->sa2 = sa;
2764                                                 dir = area_getorientation(jd->sa1, jd->sa2);
2765                                                 if (dir == -1) {
2766                                                         printf("oops, didn't expect that!\n");
2767                                                 }
2768                                         }
2769                                         else {
2770                                                 dir = area_getorientation(jd->sa1, sa);
2771                                                 if (dir != -1) {
2772                                                         jd->sa2 = sa;
2773                                                 }
2774                                         }
2775                                         WM_event_add_notifier(C, NC_WINDOW, NULL);
2776                                 }
2777                         }
2778                         break;
2779                 }
2780                 case LEFTMOUSE:
2781                         if (event->val == KM_RELEASE) {
2782                                 ED_area_tag_redraw(jd->sa1);
2783                                 ED_area_tag_redraw(jd->sa2);
2784
2785                                 area_join_apply(C, op);
2786                                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
2787                                 area_join_exit(C, op);
2788                                 return OPERATOR_FINISHED;
2789                         }
2790                         break;
2791                         
2792                 case RIGHTMOUSE:
2793                 case ESCKEY:
2794                         area_join_cancel(C, op);
2795                         return OPERATOR_CANCELLED;
2796         }
2797         
2798         return OPERATOR_RUNNING_MODAL;
2799 }
2800
2801 /* Operator for joining two areas (space types) */
2802 static void SCREEN_OT_area_join(wmOperatorType *ot)
2803 {
2804         /* identifiers */
2805         ot->name = "Join Area";
2806         ot->description = "Join selected areas into new window";
2807         ot->idname = "SCREEN_OT_area_join";
2808         
2809         /* api callbacks */
2810         ot->exec = area_join_exec;
2811         ot->invoke = area_join_invoke;
2812         ot->modal = area_join_modal;
2813         ot->poll = screen_active_editable;
2814         ot->cancel = area_join_cancel;
2815         
2816         /* flags */
2817         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
2818         
2819         /* rna */
2820         RNA_def_int(ot->srna, "min_x", -100, INT_MIN, INT_MAX, "X 1", "", INT_MIN, INT_MAX);
2821         RNA_def_int(ot->srna, "min_y", -100, INT_MIN, INT_MAX, "Y 1", "", INT_MIN, INT_MAX);
2822         RNA_def_int(ot->srna, "max_x", -100, INT_MIN, INT_MAX, "X 2", "", INT_MIN, INT_MAX);
2823         RNA_def_int(ot->srna, "max_y", -100, INT_MIN, INT_MAX, "Y 2", "", INT_MIN, INT_MAX);
2824 }
2825
2826 /* ******************************* */
2827
2828 static int screen_area_options_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2829 {
2830         wmWindow *win = CTX_wm_window(C);
2831         bScreen *sc = CTX_wm_screen(C);
2832         uiPopupMenu *pup;
2833         uiLayout *layout;
2834         PointerRNA ptr;
2835         ScrEdge *actedge;
2836         const int winsize_x = WM_window_pixels_x(win);
2837         const int winsize_y = WM_window_pixels_y(win);
2838
2839         actedge = screen_find_active_scredge(sc, winsize_x, winsize_y, event->x, event->y);
2840         
2841         if (actedge == NULL) return OPERATOR_CANCELLED;
2842         
2843         pup = UI_popup_menu_begin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
2844         layout = UI_popup_menu_layout(pup);
2845         
2846         uiItemFullO(layout, "SCREEN_OT_area_split", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr);
2847         /* store initial mouse cursor position */
2848         RNA_int_set(&ptr, "mouse_x", event->x);
2849         RNA_int_set(&ptr, "mouse_y", event->y);
2850
2851         uiItemFullO(layout, "SCREEN_OT_area_join", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr);
2852         /* mouse cursor on edge, '4' can fail on wide edges... */
2853         RNA_int_set(&ptr, "min_x", event->x + 4);
2854         RNA_int_set(&ptr, "min_y", event->y + 4);
2855         RNA_int_set(&ptr, "max_x", event->x - 4);
2856         RNA_int_set(&ptr, "max_y", event->y - 4);
2857         
2858         UI_popup_menu_end(C, pup);
2859         
2860         return OPERATOR_INTERFACE;
2861 }
2862
2863 static void SCREEN_OT_area_options(wmOperatorType *ot)
2864 {
2865         /* identifiers */
2866         ot->name = "Area Options";
2867         ot->description = "Operations for splitting and merging";
2868         ot->idname = "SCREEN_OT_area_options";
2869         
2870         /* api callbacks */
2871         ot->invoke = screen_area_options_invoke;
2872         
2873         ot->poll = ED_operator_screen_mainwinactive;
2874
2875         /* flags */
2876         ot->flag = OPTYPE_INTERNAL;
2877 }
2878
2879
2880 /* ******************************* */
2881
2882
2883 static int spacedata_cleanup_exec(bContext *C, wmOperator *op)
2884 {
2885         Main *bmain = CTX_data_main(C);
2886         bScreen *screen;
2887         ScrArea *sa;
2888         int tot = 0;
2889         
2890         for (screen = bmain->screen.first; screen; screen = screen->id.next) {
2891                 for (sa = screen->areabase.first; sa; sa = sa->next) {
2892                         if (sa->spacedata.first != sa->spacedata.last) {
2893                                 SpaceLink *sl = sa->spacedata.first;
2894
2895                                 BLI_remlink(&sa->spacedata, sl);
2896                                 tot += BLI_listbase_count(&sa->spacedata);
2897                                 BKE_spacedata_freelist(&sa->spacedata);
2898                                 BLI_addtail(&sa->spacedata, sl);
2899                         }
2900                 }
2901         }
2902         BKE_reportf(op->reports, RPT_INFO, "Removed amount of editors: %d", tot);
2903         
2904         return OPERATOR_FINISHED;
2905 }
2906
2907 static void SCREEN_OT_spacedata_cleanup(wmOperatorType *ot)
2908 {
2909         /* identifiers */
2910         ot->name = "Clean-up Space-data";
2911         ot->description = "Remove unused settings for invisible editors";
2912         ot->idname = "SCREEN_OT_spacedata_cleanup";
2913         
2914         /* api callbacks */
2915         ot->exec = spacedata_cleanup_exec;
2916         ot->poll = WM_operator_winactive;
2917         
2918 }
2919
2920 /* ************** repeat last operator ***************************** */
2921
2922 static int repeat_last_exec(bContext *C, wmOperator *UNUSED(op))
2923 {
2924         wmWindowManager *wm = CTX_wm_manager(C);
2925         wmOperator *lastop = wm->operators.last;
2926
2927         /* Seek last registered operator */
2928         while (lastop) {
2929                 if (lastop->type->flag & OPTYPE_REGISTER) {
2930                         break;
2931                 }
2932                 else {
2933                         lastop = lastop->prev;
2934                 }
2935         }
2936
2937         if (lastop) {
2938                 WM_operator_free_all_after(wm, lastop);
2939                 WM_operator_repeat(C, lastop);
2940         }
2941         
2942         return OPERATOR_CANCELLED;
2943 }
2944
2945 static void SCREEN_OT_repeat_last(wmOperatorType *ot)
2946 {
2947         /* identifiers */
2948         ot->name = "Repeat Last";
2949         ot->description = "Repeat last action";
2950         ot->idname = "SCREEN_OT_repeat_last";
2951         
2952         /* api callbacks */
2953         ot->exec = repeat_last_exec;
2954         
2955         ot->poll = ED_operator_screenactive;
2956         
2957 }
2958
2959 static int repeat_history_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2960 {
2961         wmWindowManager *wm = CTX_wm_manager(C);
2962         wmOperator *lastop;
2963         uiPopupMenu *pup;
2964         uiLayout *layout;
2965         int items, i;
2966         
2967         items = BLI_listbase_count(&wm->operators);
2968         if (items == 0)
2969                 return OPERATOR_CANCELLED;
2970         
2971         pup = UI_popup_menu_begin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
2972         layout = UI_popup_menu_layout(pup);
2973         
2974         for (i = items - 1, lastop = wm->operators.last; lastop; lastop = lastop->prev, i--)
2975                 if ((lastop->type->flag & OPTYPE_REGISTER) && WM_operator_repeat_check(C, lastop)) {
2976                         uiItemIntO(layout, RNA_struct_ui_name(lastop->type->srna), ICON_NONE, op->type->idname, "index", i);
2977                 }
2978         
2979         UI_popup_menu_end(C, pup);
2980         
2981         return OPERATOR_INTERFACE;
2982 }
2983
2984 static int repeat_history_exec(bContext *C, wmOperator *op)
2985 {
2986         wmWindowManager *wm = CTX_wm_manager(C);
2987         
2988         op = BLI_findlink(&wm->operators, RNA_int_get(op->ptr, "index"));
2989         if (op) {
2990                 /* let's put it as last operator in list */
2991                 BLI_remlink(&wm->operators, op);
2992                 BLI_addtail(&wm->operators, op);
2993                 
2994                 WM_operator_repeat(C, op);
2995         }
2996         
2997         return OPERATOR_FINISHED;
2998 }
2999
3000 static void SCREEN_OT_repeat_history(wmOperatorType *ot)
3001 {
3002         /* identifiers */
3003         ot->name = "Repeat History";
3004         ot->description = "Display menu for previous actions performed";
3005         ot->idname = "SCREEN_OT_repeat_history";
3006         
3007         /* api callbacks */
3008         ot->invoke = repeat_history_invoke;
3009         ot->exec = repeat_history_exec;
3010         
3011         ot->poll = ED_operator_screenactive;
3012         
3013         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, 1000);
3014 }
3015
3016 /* ********************** redo operator ***************************** */
3017
3018 static int redo_last_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
3019 {
3020         wmOperator *lastop = WM_operator_last_redo(C);
3021         
3022         if (lastop)
3023                 WM_operator_redo_popup(C, lastop);
3024         
3025         return OPERATOR_CANCELLED;
3026 }
3027
3028 static void SCREEN_OT_redo_last(wmOperatorType *ot)
3029 {
3030         /* identifiers */
3031         ot->name = "Redo Last";
3032         ot->description = "Display menu for last action performed";
3033         ot->idname = "SCREEN_OT_redo_last";
3034         
3035         /* api callbacks */
3036         ot->invoke = redo_last_invoke;
3037         
3038         ot->poll = ED_operator_screenactive;
3039 }
3040
3041 /* ************** region four-split operator ***************************** */
3042
3043 static void view3d_localview_update_rv3d(struct RegionView3D *rv3d)
3044 {
3045         if (rv3d->localvd) {
3046                 rv3d->localvd->view = rv3d->view;
3047                 rv3d->localvd->persp = rv3d->persp;
3048                 copy_qt_qt(rv3d->localvd->viewquat, rv3d->viewquat);
3049         }
3050 }
3051
3052 static void region_quadview_init_rv3d(ScrArea *sa, ARegion *ar,
3053                                       const char viewlock, const char view, const char persp)
3054 {
3055         RegionView3D *rv3d = ar->regiondata;
3056
3057         if (persp == RV3D_CAMOB) {
3058                 ED_view3d_lastview_store(rv3d);
3059         }
3060
3061         rv3d->viewlock = viewlock;
3062         rv3d->view = view;
3063         rv3d->persp = persp;
3064
3065         ED_view3d_lock(rv3d);
3066         view3d_localview_update_rv3d(rv3d);
3067         if ((viewlock & RV3D_BOXCLIP) && (persp == RV3D_ORTHO)) {
3068                 ED_view3d_quadview_update(sa, ar, true);
3069         }
3070 }
3071
3072 /* insert a region in the area region list */
3073 static int region_quadview_exec(bContext *C, wmOperator *op)
3074 {
3075         ARegion *ar = CTX_wm_region(C);
3076         
3077         /* some rules... */
3078         if (ar->regiontype != RGN_TYPE_WINDOW) {
3079                 BKE_report(op->reports, RPT_ERROR, "Only window region can be 4-splitted");
3080         }
3081         else if (ar->alignment == RGN_ALIGN_QSPLIT) {
3082                 /* Exit quad-view */
3083                 ScrArea *sa = CTX_wm_area(C);
3084                 ARegion *arn;
3085                 
3086                 /* keep current region */
3087                 ar->alignment = 0;
3088                 
3089                 if (sa->spacetype == SPACE_VIEW3D) {
3090                         ARegion *ar_iter;
3091                         RegionView3D *rv3d = ar->regiondata;
3092
3093                         /* if this is a locked view, use settings from 'User' view */
3094                         if (rv3d->viewlock) {
3095                                 View3D *v3d_user;
3096                                 ARegion *ar_user;
3097
3098                                 if (ED_view3d_context_user_region(C, &v3d_user, &ar_user)) {
3099                                         if (ar != ar_user) {
3100                                                 SWAP(void *, ar->regiondata, ar_user->regiondata);
3101                                                 rv3d = ar->regiondata;
3102                                         }
3103                                 }
3104                         }
3105
3106                         rv3d->viewlock_quad = RV3D_VIEWLOCK_INIT;
3107                         rv3d->viewlock = 0;
3108                         rv3d->rflag &= ~RV3D_CLIPPING;
3109
3110                         /* accumulate locks, incase they're mixed */
3111                         for (ar_iter = sa->regionbase.first; ar_iter; ar_iter = ar_iter->next) {
3112                                 if (ar_iter->regiontype == RGN_TYPE_WINDOW) {
3113                                         RegionView3D *rv3d_iter = ar_iter->regiondata;
3114                                         rv3d->viewlock_quad |= rv3d_iter->viewlock;
3115                                 }
3116                         }
3117                 }
3118                 
3119                 for (ar = sa->regionbase.first; ar; ar = arn) {
3120                         arn = ar->next;
3121                         if (ar->alignment == RGN_ALIGN_QSPLIT) {
3122                                 ED_region_exit(C, ar);
3123                                 BKE_area_region_free(sa->type, ar);
3124                                 BLI_remlink(&sa->regionbase, ar);
3125                                 MEM_freeN(ar);
3126                         }
3127                 }
3128                 ED_area_tag_redraw(sa);
3129                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
3130         }
3131         else if (ar->next) {
3132                 BKE_report(op->reports, RPT_ERROR, "Only last region can be 4-splitted");
3133         }
3134         else {
3135                 /* Enter quad-view */
3136                 ScrArea *sa = CTX_wm_area(C);
3137                 ARegion *newar;
3138                 int count;
3139                 
3140                 ar->alignment = RGN_ALIGN_QSPLIT;
3141                 
3142                 for (count = 0; count < 3; count++) {
3143                         newar = BKE_area_region_copy(sa->type, ar);
3144                         BLI_addtail(&sa->regionbase, newar);
3145                 }
3146                 
3147                 /* lock views and set them */
3148                 if (sa->spacetype == SPACE_VIEW3D) {
3149                         View3D *v3d = sa->spacedata.first;
3150                         int index_qsplit = 0;
3151
3152                         /* run ED_view3d_lock() so the correct 'rv3d->viewquat' is set,
3153                          * otherwise when restoring rv3d->localvd the 'viewquat' won't
3154                          * match the 'view', set on entering localview See: [#26315],
3155                          *
3156                          * We could avoid manipulating rv3d->localvd here if exiting
3157                          * localview with a 4-split would assign these view locks */
3158                         RegionView3D *rv3d = ar->regiondata;
3159                         const char viewlock = (rv3d->viewlock_quad & RV3D_VIEWLOCK_INIT) ?
3160                                               (rv3d->viewlock_quad & ~RV3D_VIEWLOCK_INIT) : RV3D_LOCKED;
3161
3162                         region_quadview_init_rv3d(sa, ar,              viewlock, ED_view3d_lock_view_from_index(index_qsplit++), RV3D_ORTHO);
3163                         region_quadview_init_rv3d(sa, (ar = ar->next), viewlock, ED_view3d_lock_view_from_index(index_qsplit++), RV3D_ORTHO);
3164                         region_quadview_init_rv3d(sa, (ar = ar->next), viewlock, ED_view3d_lock_view_from_index(index_qsplit++), RV3D_ORTHO);
3165                         /* forcing camera is distracting */
3166 #if 0
3167                         if (v3d->camera) region_quadview_init_rv3d(sa, (ar = ar->next), 0, RV3D_VIEW_CAMERA, RV3D_CAMOB);
3168                         else             region_quadview_init_rv3d(sa, (ar = ar->next), 0, RV3D_VIEW_USER,   RV3D_PERSP);
3169 #else
3170                         (void)v3d;
3171 #endif
3172                 }
3173                 ED_area_tag_redraw(sa);
3174                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
3175         }
3176         
3177         
3178         return OPERATOR_FINISHED;
3179 }
3180
3181 static void SCREEN_OT_region_quadview(wmOperatorType *ot)
3182 {
3183         /* identifiers */
3184         ot->name = "Toggle Quad View";
3185         ot->description = "Split selected area into camera, front, right & top views";
3186         ot->idname = "SCREEN_OT_region_quadview";
3187         
3188         /* api callbacks */
3189         ot->exec = region_quadview_exec;
3190         ot->poll = ED_operator_region_view3d_active;
3191         ot->flag = 0;
3192 }
3193
3194
3195 /* ************** region flip operator ***************************** */
3196
3197 /* flip a region alignment */
3198 static int region_flip_exec(bContext *C, wmOperator *UNUSED(op))
3199 {
3200         ARegion *ar = CTX_wm_region(C);
3201         
3202         if (!ar)
3203                 return OPERATOR_CANCELLED;
3204         
3205         if (ar->alignment == RGN_ALIGN_TOP)
3206                 ar->alignment = RGN_ALIGN_BOTTOM;
3207         else if (ar->alignment == RGN_ALIGN_BOTTOM)
3208                 ar->alignment = RGN_ALIGN_TOP;
3209         else if (ar->alignment == RGN_ALIGN_LEFT)
3210                 ar->alignment = RGN_ALIGN_RIGHT;
3211         else if (ar->alignment == RGN_ALIGN_RIGHT)
3212                 ar->alignment = RGN_ALIGN_LEFT;
3213
3214         ED_area_tag_redraw(CTX_wm_area(C));
3215         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
3216         
3217         return OPERATOR_FINISHED;
3218 }
3219
3220
3221 static void SCREEN_OT_region_flip(wmOperatorType *ot)
3222 {
3223         /* identifiers */
3224         ot->name = "Flip Region";
3225         ot->idname = "SCREEN_OT_region_flip";
3226         ot->description = "Toggle the region's alignment (left/right or top/bottom)";
3227         
3228         /* api callbacks */
3229         ot->exec = region_flip_exec;
3230         ot->poll = ED_operator_areaactive;
3231         ot->flag = 0;
3232 }
3233
3234 /* ************** header operator ***************************** */
3235
3236 static int header_exec(bContext *C, wmOperator *UNUSED(op))
3237 {
3238         ARegion *ar = screen_find_region_type(C, RGN_TYPE_HEADER);
3239
3240         if (ar == NULL) {
3241                 return OPERATOR_CANCELLED;
3242         }
3243
3244         ar->flag ^= RGN_FLAG_HIDDEN;
3245
3246         ED_area_tag_redraw(CTX_wm_area(C));
3247
3248         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
3249
3250         return OPERATOR_FINISHED;
3251 }
3252
3253 static void SCREEN_OT_header(wmOperatorType *ot)
3254 {
3255         /* identifiers */
3256         ot->name = "Toggle Header";
3257         ot->description = "Toggle header display";
3258         ot->idname = "SCREEN_OT_header";
3259
3260         /* api callbacks */