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