UI: disallow splitting of temporary screens
[blender.git] / source / blender / editors / screen / area.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2008 Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup edscr
22  */
23
24
25 #include <string.h>
26 #include <stdio.h>
27
28 #include "MEM_guardedalloc.h"
29
30 #include "DNA_userdef_types.h"
31
32 #include "BLI_blenlib.h"
33 #include "BLI_math.h"
34 #include "BLI_utildefines.h"
35 #include "BLI_linklist_stack.h"
36
37 #include "BKE_context.h"
38 #include "BKE_global.h"
39 #include "BKE_image.h"
40 #include "BKE_screen.h"
41 #include "BKE_workspace.h"
42
43 #include "RNA_access.h"
44 #include "RNA_types.h"
45
46 #include "WM_api.h"
47 #include "WM_types.h"
48 #include "WM_message.h"
49 #include "WM_toolsystem.h"
50
51 #include "ED_screen.h"
52 #include "ED_screen_types.h"
53 #include "ED_space_api.h"
54
55 #include "GPU_immediate.h"
56 #include "GPU_immediate_util.h"
57 #include "GPU_matrix.h"
58 #include "GPU_draw.h"
59 #include "GPU_state.h"
60 #include "GPU_framebuffer.h"
61
62 #include "BLF_api.h"
63
64 #include "IMB_imbuf.h"
65 #include "IMB_imbuf_types.h"
66 #include "IMB_metadata.h"
67
68 #include "UI_interface.h"
69 #include "UI_interface_icons.h"
70 #include "UI_resources.h"
71 #include "UI_view2d.h"
72
73 #include "screen_intern.h"
74
75 enum RegionEmbossSide {
76         REGION_EMBOSS_LEFT   = (1 << 0),
77         REGION_EMBOSS_TOP    = (1 << 1),
78         REGION_EMBOSS_BOTTOM = (1 << 2),
79         REGION_EMBOSS_RIGHT  = (1 << 3),
80         REGION_EMBOSS_ALL    = REGION_EMBOSS_LEFT | REGION_EMBOSS_TOP | REGION_EMBOSS_RIGHT | REGION_EMBOSS_BOTTOM,
81 };
82
83 /* general area and region code */
84
85 static void region_draw_emboss(const ARegion *ar, const rcti *scirct, int sides)
86 {
87         rcti rect;
88
89         /* translate scissor rect to region space */
90         rect.xmin = scirct->xmin - ar->winrct.xmin;
91         rect.ymin = scirct->ymin - ar->winrct.ymin;
92         rect.xmax = scirct->xmax - ar->winrct.xmin;
93         rect.ymax = scirct->ymax - ar->winrct.ymin;
94
95         /* set transp line */
96         GPU_blend(true);
97         GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
98
99         float color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
100         UI_GetThemeColor3fv(TH_EDITOR_OUTLINE, color);
101
102         GPUVertFormat *format = immVertexFormat();
103         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
104         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
105         immUniformColor4fv(color);
106
107         immBeginAtMost(GPU_PRIM_LINES, 8);
108
109         /* right */
110         if (sides & REGION_EMBOSS_RIGHT) {
111                 immVertex2f(pos, rect.xmax, rect.ymax);
112                 immVertex2f(pos, rect.xmax, rect.ymin);
113         }
114
115         /* bottom */
116         if (sides & REGION_EMBOSS_BOTTOM) {
117                 immVertex2f(pos, rect.xmax, rect.ymin);
118                 immVertex2f(pos, rect.xmin, rect.ymin);
119         }
120
121         /* left */
122         if (sides & REGION_EMBOSS_LEFT) {
123                 immVertex2f(pos, rect.xmin, rect.ymin);
124                 immVertex2f(pos, rect.xmin, rect.ymax);
125         }
126
127         /* top */
128         if (sides & REGION_EMBOSS_TOP) {
129                 immVertex2f(pos, rect.xmin, rect.ymax);
130                 immVertex2f(pos, rect.xmax, rect.ymax);
131         }
132
133         immEnd();
134         immUnbindProgram();
135
136         GPU_blend(false);
137         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
138 }
139
140 void ED_region_pixelspace(ARegion *ar)
141 {
142         wmOrtho2_region_pixelspace(ar);
143         GPU_matrix_identity_set();
144 }
145
146 /* only exported for WM */
147 void ED_region_do_listen(wmWindow *win, ScrArea *sa, ARegion *ar, wmNotifier *note, const Scene *scene)
148 {
149         /* generic notes first */
150         switch (note->category) {
151                 case NC_WM:
152                         if (note->data == ND_FILEREAD)
153                                 ED_region_tag_redraw(ar);
154                         break;
155                 case NC_WINDOW:
156                         ED_region_tag_redraw(ar);
157                         break;
158         }
159
160         if (ar->type && ar->type->listener)
161                 ar->type->listener(win, sa, ar, note, scene);
162 }
163
164 /* only exported for WM */
165 void ED_area_do_listen(wmWindow *win, ScrArea *sa, wmNotifier *note, Scene *scene)
166 {
167         /* no generic notes? */
168         if (sa->type && sa->type->listener) {
169                 sa->type->listener(win, sa, note, scene);
170         }
171 }
172
173 /* only exported for WM */
174 void ED_area_do_refresh(bContext *C, ScrArea *sa)
175 {
176         /* no generic notes? */
177         if (sa->type && sa->type->refresh) {
178                 sa->type->refresh(C, sa);
179         }
180         sa->do_refresh = false;
181 }
182
183 /**
184  * \brief Corner widget use for quitting fullscreen.
185  */
186 static void area_draw_azone_fullscreen(short x1, short y1, short x2, short y2, float alpha)
187 {
188         int x = x2 - ((float) x2 - x1) * 0.5f / UI_DPI_FAC;
189         int y = y2 - ((float) y2 - y1) * 0.5f / UI_DPI_FAC;
190
191         /* adjust the icon distance from the corner */
192         x += 36.0f / UI_DPI_FAC;
193         y += 36.0f / UI_DPI_FAC;
194
195         /* draws from the left bottom corner of the icon */
196         x -= UI_DPI_ICON_SIZE;
197         y -= UI_DPI_ICON_SIZE;
198
199         alpha = min_ff(alpha, 0.75f);
200
201         UI_icon_draw_aspect(x, y, ICON_FULLSCREEN_EXIT, 0.7f / UI_DPI_FAC, alpha, NULL);
202
203         /* debug drawing :
204          * The click_rect is the same as defined in fullscreen_click_rcti_init
205          * Keep them both in sync */
206
207         if (G.debug_value == 101) {
208                 rcti click_rect;
209                 float icon_size = UI_DPI_ICON_SIZE + 7 * UI_DPI_FAC;
210
211                 BLI_rcti_init(&click_rect, x, x + icon_size, y, y + icon_size);
212
213                 GPUVertFormat *format = immVertexFormat();
214                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
215
216                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
217
218                 immUniformColor4f(1.0f, 0.0f, 0.0f, alpha);
219                 imm_draw_box_wire_2d(pos, click_rect.xmin, click_rect.ymin, click_rect.xmax, click_rect.ymax);
220
221                 immUniformColor4f(0.0f, 1.0f, 1.0f, alpha);
222                 immBegin(GPU_PRIM_LINES, 4);
223                 immVertex2f(pos, click_rect.xmin, click_rect.ymin);
224                 immVertex2f(pos, click_rect.xmax, click_rect.ymax);
225                 immVertex2f(pos, click_rect.xmin, click_rect.ymax);
226                 immVertex2f(pos, click_rect.xmax, click_rect.ymin);
227                 immEnd();
228
229                 immUnbindProgram();
230         }
231 }
232
233 /**
234  * \brief Corner widgets use for dragging and splitting the view.
235  */
236 static void area_draw_azone(short UNUSED(x1), short UNUSED(y1), short UNUSED(x2), short UNUSED(y2))
237 {
238         /* No drawing needed since all corners are action zone, and visually distinguishable. */
239 }
240
241 /**
242  * \brief Edge widgets to show hidden panels such as the toolbar and headers.
243  */
244 static void draw_azone_arrow(float x1, float y1, float x2, float y2, AZEdge edge)
245 {
246         const float size =  0.2f * U.widget_unit;
247         const float l = 1.0f;     /* arrow length */
248         const float s = 0.25f;    /* arrow thickness */
249         const float hl = l / 2.0f;
250         const float points[6][2] = {{0, -hl}, {l, hl}, {l - s, hl + s}, {0, s + s - hl}, {s - l, hl + s}, {-l, hl}};
251         const float center[2] = {(x1 + x2) / 2, (y1 + y2) / 2};
252
253         int axis;
254         int sign;
255         switch (edge) {
256                 case AE_BOTTOM_TO_TOPLEFT:
257                         axis = 0;
258                         sign = 1;
259                         break;
260                 case AE_TOP_TO_BOTTOMRIGHT:
261                         axis = 0;
262                         sign = -1;
263                         break;
264                 case AE_LEFT_TO_TOPRIGHT:
265                         axis = 1;
266                         sign = 1;
267                         break;
268                 case AE_RIGHT_TO_TOPLEFT:
269                         axis = 1;
270                         sign = -1;
271                         break;
272                 default:
273                         BLI_assert(0);
274                         return;
275         }
276
277         GPUVertFormat *format = immVertexFormat();
278         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
279
280         GPU_blend(true);
281         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
282         immUniformColor4f(0.8f, 0.8f, 0.8f, 0.4f);
283
284         immBegin(GPU_PRIM_TRI_FAN, 6);
285         for (int i = 0; i < 6; i++) {
286                 if (axis == 0) {
287                         immVertex2f(pos, center[0] + points[i][0] * size, center[1] + points[i][1] * sign * size);
288                 }
289                 else {
290                         immVertex2f(pos, center[0] + points[i][1] * sign * size, center[1] + points[i][0] * size);
291                 }
292         }
293         immEnd();
294
295         immUnbindProgram();
296         GPU_blend(false);
297 }
298
299 static void region_draw_azone_tab_arrow(AZone *az)
300 {
301         GPU_blend(true);
302
303         /* add code to draw region hidden as 'too small' */
304         switch (az->edge) {
305                 case AE_TOP_TO_BOTTOMRIGHT:
306                         UI_draw_roundbox_corner_set(UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT);
307                         break;
308                 case AE_BOTTOM_TO_TOPLEFT:
309                         UI_draw_roundbox_corner_set(UI_CNR_BOTTOM_RIGHT | UI_CNR_BOTTOM_LEFT);
310                         break;
311                 case AE_LEFT_TO_TOPRIGHT:
312                         UI_draw_roundbox_corner_set(UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT);
313                         break;
314                 case AE_RIGHT_TO_TOPLEFT:
315                         UI_draw_roundbox_corner_set(UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT);
316                         break;
317         }
318
319         float color[4] = {0.05f, 0.05f, 0.05f, 0.4f};
320         UI_draw_roundbox_aa(true, (float)az->x1, (float)az->y1, (float)az->x2, (float)az->y2, 4.0f, color);
321
322         draw_azone_arrow((float)az->x1, (float)az->y1, (float)az->x2, (float)az->y2, az->edge);
323 }
324
325 static void area_azone_tag_update(ScrArea *sa)
326 {
327         sa->flag |= AREA_FLAG_ACTIONZONES_UPDATE;
328 }
329
330 static void region_draw_azones(ScrArea *sa, ARegion *ar)
331 {
332         AZone *az;
333
334         if (!sa)
335                 return;
336
337         GPU_line_width(1.0f);
338         GPU_blend(true);
339         GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
340
341         GPU_matrix_push();
342         GPU_matrix_translate_2f(-ar->winrct.xmin, -ar->winrct.ymin);
343
344         for (az = sa->actionzones.first; az; az = az->next) {
345                 /* test if action zone is over this region */
346                 rcti azrct;
347                 BLI_rcti_init(&azrct, az->x1, az->x2, az->y1, az->y2);
348
349                 if (BLI_rcti_isect(&ar->drawrct, &azrct, NULL)) {
350                         if (az->type == AZONE_AREA) {
351                                 area_draw_azone(az->x1, az->y1, az->x2, az->y2);
352                         }
353                         else if (az->type == AZONE_REGION) {
354                                 if (az->ar) {
355                                         /* only display tab or icons when the region is hidden */
356                                         if (az->ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) {
357                                                 region_draw_azone_tab_arrow(az);
358                                         }
359                                 }
360                         }
361                         else if (az->type == AZONE_FULLSCREEN) {
362                                 area_draw_azone_fullscreen(az->x1, az->y1, az->x2, az->y2, az->alpha);
363                         }
364                 }
365                 if (!IS_EQF(az->alpha, 0.0f) && ELEM(az->type, AZONE_FULLSCREEN, AZONE_REGION_SCROLL)) {
366                         area_azone_tag_update(sa);
367                 }
368         }
369
370         GPU_matrix_pop();
371
372         GPU_blend(false);
373 }
374
375 static void region_draw_status_text(ScrArea *sa, ARegion *ar)
376 {
377         bool overlap = ED_region_is_overlap(sa->spacetype, ar->regiontype);
378
379         if (overlap) {
380                 GPU_clear_color(0.0, 0.0, 0.0, 0.0);
381                 glClear(GL_COLOR_BUFFER_BIT);
382         }
383         else {
384                 UI_ThemeClearColor(TH_HEADER);
385                 glClear(GL_COLOR_BUFFER_BIT);
386         }
387
388         int fontid = BLF_set_default();
389
390         const float width = BLF_width(fontid, ar->headerstr, BLF_DRAW_STR_DUMMY_MAX);
391         const float x = UI_UNIT_X;
392         const float y = 0.4f * UI_UNIT_Y;
393
394         if (overlap) {
395                 const float pad = 2.0f * UI_DPI_FAC;
396                 const float x1 = x - (UI_UNIT_X - pad);
397                 const float x2 = x + width + (UI_UNIT_X - pad);
398                 const float y1 = pad;
399                 const float y2 = ar->winy - pad;
400
401                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
402
403                 float color[4] = {0.0f, 0.0f, 0.0f, 0.5f};
404                 UI_GetThemeColor3fv(TH_BACK, color);
405                 UI_draw_roundbox_corner_set(UI_CNR_ALL);
406                 UI_draw_roundbox_aa(true, x1, y1, x2, y2, 4.0f, color);
407
408                 UI_FontThemeColor(fontid, TH_TEXT);
409         }
410         else {
411                 UI_FontThemeColor(fontid, TH_TEXT);
412         }
413
414         BLF_position(fontid, x, y, 0.0f);
415         BLF_draw(fontid, ar->headerstr, BLF_DRAW_STR_DUMMY_MAX);
416 }
417
418 /* Follow wmMsgNotifyFn spec */
419 void ED_region_do_msg_notify_tag_redraw(
420         bContext *UNUSED(C), wmMsgSubscribeKey *UNUSED(msg_key), wmMsgSubscribeValue *msg_val)
421 {
422         ARegion *ar = msg_val->owner;
423         ED_region_tag_redraw(ar);
424
425         /* This avoids _many_ situations where header/properties control display settings.
426          * the common case is space properties in the header */
427         if (ELEM(ar->regiontype, RGN_TYPE_HEADER, RGN_TYPE_UI)) {
428                 while (ar && ar->prev) {
429                         ar = ar->prev;
430                 }
431                 for (; ar; ar = ar->next) {
432                         if (ELEM(ar->regiontype, RGN_TYPE_WINDOW, RGN_TYPE_CHANNELS)) {
433                                 ED_region_tag_redraw(ar);
434                         }
435                 }
436         }
437 }
438 /* Follow wmMsgNotifyFn spec */
439 void ED_area_do_msg_notify_tag_refresh(
440         bContext *UNUSED(C), wmMsgSubscribeKey *UNUSED(msg_key), wmMsgSubscribeValue *msg_val)
441 {
442         ScrArea *sa = msg_val->user_data;
443         ED_area_tag_refresh(sa);
444 }
445
446 /**
447  * Although there's no general support for minimizing areas, the status-bar can
448  * be snapped to be only a few pixels high. A few pixels rather than 0 so it
449  * can be un-minimized again. We consider it pseudo-minimalized and don't draw
450  * it then.
451  */
452 static bool area_is_pseudo_minimized(const ScrArea *area)
453 {
454         return (area->winx < 3) || (area->winy < 3);
455 }
456
457 /* only exported for WM */
458 void ED_region_do_layout(bContext *C, ARegion *ar)
459 {
460         /* This is optional, only needed for dynamically sized regions. */
461         ScrArea *sa = CTX_wm_area(C);
462         ARegionType *at = ar->type;
463
464         if (!at->layout) {
465                 return;
466         }
467
468         if (at->do_lock || (sa && area_is_pseudo_minimized(sa))) {
469                 return;
470         }
471
472         ar->do_draw |= RGN_DRAWING;
473
474         UI_SetTheme(sa ? sa->spacetype : 0, at->regionid);
475         at->layout(C, ar);
476 }
477
478 /* only exported for WM */
479 void ED_region_do_draw(bContext *C, ARegion *ar)
480 {
481         wmWindow *win = CTX_wm_window(C);
482         ScrArea *sa = CTX_wm_area(C);
483         ARegionType *at = ar->type;
484
485         /* see BKE_spacedata_draw_locks() */
486         if (at->do_lock)
487                 return;
488
489         ar->do_draw |= RGN_DRAWING;
490
491         /* Set viewport, scissor, ortho and ar->drawrct. */
492         wmPartialViewport(&ar->drawrct, &ar->winrct, &ar->drawrct);
493
494         wmOrtho2_region_pixelspace(ar);
495
496         UI_SetTheme(sa ? sa->spacetype : 0, at->regionid);
497
498         if (sa && area_is_pseudo_minimized(sa)) {
499                 UI_ThemeClearColor(TH_EDITOR_OUTLINE);
500                 glClear(GL_COLOR_BUFFER_BIT);
501                 return;
502         }
503         /* optional header info instead? */
504         else if (ar->headerstr) {
505                 region_draw_status_text(sa, ar);
506         }
507         else if (at->draw) {
508                 at->draw(C, ar);
509         }
510
511         /* XXX test: add convention to end regions always in pixel space, for drawing of borders/gestures etc */
512         ED_region_pixelspace(ar);
513
514         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_PIXEL);
515
516         region_draw_azones(sa, ar);
517
518         /* for debugging unneeded area redraws and partial redraw */
519 #if 0
520         GPU_blend(true);
521         GPUVertFormat *format = immVertexFormat();
522         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
523         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
524         immUniformColor4f(drand48(), drand48(), drand48(), 0.1f);
525         immRectf(pos, ar->drawrct.xmin - ar->winrct.xmin, ar->drawrct.ymin - ar->winrct.ymin,
526                 ar->drawrct.xmax - ar->winrct.xmin, ar->drawrct.ymax - ar->winrct.ymin);
527         immUnbindProgram();
528         GPU_blend(false);
529 #endif
530
531         memset(&ar->drawrct, 0, sizeof(ar->drawrct));
532
533         UI_blocklist_free_inactive(C, &ar->uiblocks);
534
535         if (sa) {
536                 const bScreen *screen = WM_window_get_active_screen(win);
537
538                 /* Only draw region emboss for top-bar and quad-view. */
539                 if ((screen->state != SCREENFULL) && ED_area_is_global(sa)) {
540                         region_draw_emboss(ar, &ar->winrct, (REGION_EMBOSS_LEFT | REGION_EMBOSS_RIGHT));
541                 }
542                 else if ((ar->regiontype == RGN_TYPE_WINDOW) && (ar->alignment == RGN_ALIGN_QSPLIT)) {
543                         region_draw_emboss(ar, &ar->winrct, REGION_EMBOSS_ALL);
544                 }
545         }
546
547         /* We may want to detach message-subscriptions from drawing. */
548         {
549                 WorkSpace *workspace = CTX_wm_workspace(C);
550                 wmWindowManager *wm = CTX_wm_manager(C);
551                 bScreen *screen = WM_window_get_active_screen(win);
552                 Scene *scene = CTX_data_scene(C);
553                 struct wmMsgBus *mbus = wm->message_bus;
554                 WM_msgbus_clear_by_owner(mbus, ar);
555
556                 /* Cheat, always subscribe to this space type properties.
557                  *
558                  * This covers most cases and avoids copy-paste similar code for each space type.
559                  */
560                 if (ELEM(ar->regiontype, RGN_TYPE_WINDOW, RGN_TYPE_CHANNELS, RGN_TYPE_UI, RGN_TYPE_TOOLS)) {
561                         SpaceLink *sl = sa->spacedata.first;
562
563                         PointerRNA ptr;
564                         RNA_pointer_create(&screen->id, &RNA_Space, sl, &ptr);
565
566                         wmMsgSubscribeValue msg_sub_value_region_tag_redraw = {
567                                 .owner = ar,
568                                 .user_data = ar,
569                                 .notify = ED_region_do_msg_notify_tag_redraw,
570                         };
571                         /* All properties for this space type. */
572                         WM_msg_subscribe_rna(mbus, &ptr, NULL, &msg_sub_value_region_tag_redraw, __func__);
573                 }
574
575                 ED_region_message_subscribe(C, workspace, scene, screen, sa, ar, mbus);
576         }
577 }
578
579 /* **********************************
580  * maybe silly, but let's try for now
581  * to keep these tags protected
582  * ********************************** */
583
584 void ED_region_tag_redraw(ARegion *ar)
585 {
586         /* don't tag redraw while drawing, it shouldn't happen normally
587          * but python scripts can cause this to happen indirectly */
588         if (ar && !(ar->do_draw & RGN_DRAWING)) {
589                 /* zero region means full region redraw */
590                 ar->do_draw &= ~(RGN_DRAW_PARTIAL | RGN_DRAW_NO_REBUILD);
591                 ar->do_draw |= RGN_DRAW;
592                 memset(&ar->drawrct, 0, sizeof(ar->drawrct));
593         }
594 }
595
596 void ED_region_tag_redraw_overlay(ARegion *ar)
597 {
598         if (ar)
599                 ar->do_draw_overlay = RGN_DRAW;
600 }
601
602 void ED_region_tag_redraw_no_rebuild(ARegion *ar)
603 {
604         if (ar && !(ar->do_draw & (RGN_DRAWING | RGN_DRAW))) {
605                 ar->do_draw &= ~RGN_DRAW_PARTIAL;
606                 ar->do_draw |= RGN_DRAW_NO_REBUILD;
607                 memset(&ar->drawrct, 0, sizeof(ar->drawrct));
608         }
609 }
610
611 void ED_region_tag_refresh_ui(ARegion *ar)
612 {
613         if (ar) {
614                 ar->do_draw |= RGN_DRAW_REFRESH_UI;
615         }
616 }
617
618 void ED_region_tag_redraw_partial(ARegion *ar, const rcti *rct)
619 {
620         if (ar && !(ar->do_draw & RGN_DRAWING)) {
621                 if (!(ar->do_draw & (RGN_DRAW | RGN_DRAW_NO_REBUILD | RGN_DRAW_PARTIAL))) {
622                         /* no redraw set yet, set partial region */
623                         ar->do_draw |= RGN_DRAW_PARTIAL;
624                         ar->drawrct = *rct;
625                 }
626                 else if (ar->drawrct.xmin != ar->drawrct.xmax) {
627                         BLI_assert((ar->do_draw & RGN_DRAW_PARTIAL) != 0);
628                         /* partial redraw already set, expand region */
629                         BLI_rcti_union(&ar->drawrct, rct);
630                 }
631                 else {
632                         BLI_assert((ar->do_draw & (RGN_DRAW | RGN_DRAW_NO_REBUILD)) != 0);
633                         /* Else, full redraw is already requested, nothing to do here. */
634                 }
635         }
636 }
637
638 void ED_area_tag_redraw(ScrArea *sa)
639 {
640         ARegion *ar;
641
642         if (sa)
643                 for (ar = sa->regionbase.first; ar; ar = ar->next)
644                         ED_region_tag_redraw(ar);
645 }
646
647 void ED_area_tag_redraw_no_rebuild(ScrArea *sa)
648 {
649         ARegion *ar;
650
651         if (sa)
652                 for (ar = sa->regionbase.first; ar; ar = ar->next)
653                         ED_region_tag_redraw_no_rebuild(ar);
654 }
655
656 void ED_area_tag_redraw_regiontype(ScrArea *sa, int regiontype)
657 {
658         ARegion *ar;
659
660         if (sa) {
661                 for (ar = sa->regionbase.first; ar; ar = ar->next) {
662                         if (ar->regiontype == regiontype) {
663                                 ED_region_tag_redraw(ar);
664                         }
665                 }
666         }
667 }
668
669 void ED_area_tag_refresh(ScrArea *sa)
670 {
671         if (sa)
672                 sa->do_refresh = true;
673 }
674
675 /* *************************************************************** */
676
677 /* use NULL to disable it */
678 void ED_area_status_text(ScrArea *sa, const char *str)
679 {
680         ARegion *ar;
681
682         /* happens when running transform operators in background mode */
683         if (sa == NULL)
684                 return;
685
686         for (ar = sa->regionbase.first; ar; ar = ar->next) {
687                 if (ar->regiontype == RGN_TYPE_HEADER) {
688                         if (str) {
689                                 if (ar->headerstr == NULL)
690                                         ar->headerstr = MEM_mallocN(UI_MAX_DRAW_STR, "headerprint");
691                                 BLI_strncpy(ar->headerstr, str, UI_MAX_DRAW_STR);
692                                 BLI_str_rstrip(ar->headerstr);
693                         }
694                         else if (ar->headerstr) {
695                                 MEM_freeN(ar->headerstr);
696                                 ar->headerstr = NULL;
697                         }
698                         ED_region_tag_redraw(ar);
699                 }
700         }
701 }
702
703 void ED_workspace_status_text(bContext *C, const char *str)
704 {
705         wmWindow *win = CTX_wm_window(C);
706         WorkSpace *workspace = CTX_wm_workspace(C);
707
708         /* Can be NULL when running operators in background mode. */
709         if (workspace == NULL)
710                 return;
711
712         if (str) {
713                 if (workspace->status_text == NULL)
714                         workspace->status_text = MEM_mallocN(UI_MAX_DRAW_STR, "headerprint");
715                 BLI_strncpy(workspace->status_text, str, UI_MAX_DRAW_STR);
716         }
717         else if (workspace->status_text) {
718                 MEM_freeN(workspace->status_text);
719                 workspace->status_text = NULL;
720         }
721
722         /* Redraw status bar. */
723         for (ScrArea *sa = win->global_areas.areabase.first; sa; sa = sa->next) {
724                 if (sa->spacetype == SPACE_STATUSBAR) {
725                         ED_area_tag_redraw(sa);
726                         break;
727                 }
728         }
729 }
730
731 /* ************************************************************ */
732
733
734 static void area_azone_initialize(wmWindow *win, const bScreen *screen, ScrArea *sa)
735 {
736         AZone *az;
737
738         /* reinitialize entirely, regions and fullscreen add azones too */
739         BLI_freelistN(&sa->actionzones);
740
741         if (screen->state != SCREENNORMAL) {
742                 return;
743         }
744
745         if (U.app_flag & USER_APP_LOCK_UI_LAYOUT) {
746                 return;
747         }
748
749         if (ED_area_is_global(sa)) {
750                 return;
751         }
752
753         if (screen->temp) {
754                 return;
755         }
756
757         float coords[4][4] = {
758             /* Bottom-left. */
759             {sa->totrct.xmin - U.pixelsize,
760              sa->totrct.ymin - U.pixelsize,
761              sa->totrct.xmin + AZONESPOTW,
762              sa->totrct.ymin + AZONESPOTH},
763             /* Bottom-right. */
764             {sa->totrct.xmax - AZONESPOTW,
765              sa->totrct.ymin - U.pixelsize,
766              sa->totrct.xmax + U.pixelsize,
767              sa->totrct.ymin + AZONESPOTH},
768             /* Top-left. */
769             {sa->totrct.xmin - U.pixelsize,
770              sa->totrct.ymax - AZONESPOTH,
771              sa->totrct.xmin + AZONESPOTW,
772              sa->totrct.ymax + U.pixelsize},
773             /* Top-right. */
774             {sa->totrct.xmax - AZONESPOTW,
775              sa->totrct.ymax - AZONESPOTH,
776              sa->totrct.xmax + U.pixelsize,
777              sa->totrct.ymax + U.pixelsize}};
778
779         for (int i = 0; i < 4; i++) {
780                 /* can't click on bottom corners on OS X, already used for resizing */
781 #ifdef __APPLE__
782                 if (!WM_window_is_fullscreen(win) &&
783                     ((coords[i][0] == 0 && coords[i][1] == 0) ||
784                      (coords[i][0] == WM_window_pixels_x(win) && coords[i][1] == 0)))
785                 {
786                         continue;
787                 }
788 #else
789                 (void)win;
790 #endif
791
792                 /* set area action zones */
793                 az = (AZone *)MEM_callocN(sizeof(AZone), "actionzone");
794                 BLI_addtail(&(sa->actionzones), az);
795                 az->type = AZONE_AREA;
796                 az->x1 = coords[i][0];
797                 az->y1 = coords[i][1];
798                 az->x2 = coords[i][2];
799                 az->y2 = coords[i][3];
800                 BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
801         }
802 }
803
804 static void fullscreen_azone_initialize(ScrArea *sa, ARegion *ar)
805 {
806         AZone *az;
807
808         if (ED_area_is_global(sa) || (ar->regiontype != RGN_TYPE_WINDOW))
809                 return;
810
811         az = (AZone *)MEM_callocN(sizeof(AZone), "fullscreen action zone");
812         BLI_addtail(&(sa->actionzones), az);
813         az->type = AZONE_FULLSCREEN;
814         az->ar = ar;
815         az->alpha = 0.0f;
816
817         az->x1 = ar->winrct.xmax - (AZONEFADEOUT - 1);
818         az->y1 = ar->winrct.ymax - (AZONEFADEOUT - 1);
819         az->x2 = ar->winrct.xmax;
820         az->y2 = ar->winrct.ymax;
821         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
822 }
823
824 #define AZONEPAD_EDGE   (0.1f * U.widget_unit)
825 #define AZONEPAD_ICON   (0.45f * U.widget_unit)
826 static void region_azone_edge(AZone *az, ARegion *ar)
827 {
828         switch (az->edge) {
829                 case AE_TOP_TO_BOTTOMRIGHT:
830                         az->x1 = ar->winrct.xmin;
831                         az->y1 = ar->winrct.ymax - AZONEPAD_EDGE;
832                         az->x2 = ar->winrct.xmax;
833                         az->y2 = ar->winrct.ymax + AZONEPAD_EDGE;
834                         break;
835                 case AE_BOTTOM_TO_TOPLEFT:
836                         az->x1 = ar->winrct.xmin;
837                         az->y1 = ar->winrct.ymin + AZONEPAD_EDGE;
838                         az->x2 = ar->winrct.xmax;
839                         az->y2 = ar->winrct.ymin - AZONEPAD_EDGE;
840                         break;
841                 case AE_LEFT_TO_TOPRIGHT:
842                         az->x1 = ar->winrct.xmin - AZONEPAD_EDGE;
843                         az->y1 = ar->winrct.ymin;
844                         az->x2 = ar->winrct.xmin + AZONEPAD_EDGE;
845                         az->y2 = ar->winrct.ymax;
846                         break;
847                 case AE_RIGHT_TO_TOPLEFT:
848                         az->x1 = ar->winrct.xmax + AZONEPAD_EDGE;
849                         az->y1 = ar->winrct.ymin;
850                         az->x2 = ar->winrct.xmax - AZONEPAD_EDGE;
851                         az->y2 = ar->winrct.ymax;
852                         break;
853         }
854
855         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
856 }
857
858 /* region already made zero sized, in shape of edge */
859 static void region_azone_tab_plus(ScrArea *sa, AZone *az, ARegion *ar)
860 {
861         AZone *azt;
862         int tot = 0, add;
863         /* Edge offset multiplied by the  */
864
865         float edge_offset = 1.0f;
866         const float tab_size_x = 0.7f * U.widget_unit;
867         const float tab_size_y = 0.4f * U.widget_unit;
868
869
870         for (azt = sa->actionzones.first; azt; azt = azt->next) {
871                 if (azt->edge == az->edge) tot++;
872         }
873
874         switch (az->edge) {
875                 case AE_TOP_TO_BOTTOMRIGHT:
876                         add = (ar->winrct.ymax == sa->totrct.ymin) ? 1 : 0;
877                         az->x1 = ar->winrct.xmax - ((edge_offset + 1.0f) * tab_size_x);
878                         az->y1 = ar->winrct.ymax - add;
879                         az->x2 = ar->winrct.xmax - (edge_offset * tab_size_x);
880                         az->y2 = ar->winrct.ymax - add + tab_size_y;
881                         break;
882                 case AE_BOTTOM_TO_TOPLEFT:
883                         az->x1 = ar->winrct.xmax - ((edge_offset + 1.0f) * tab_size_x);
884                         az->y1 = ar->winrct.ymin - tab_size_y;
885                         az->x2 = ar->winrct.xmax - (edge_offset * tab_size_x);
886                         az->y2 = ar->winrct.ymin;
887                         break;
888                 case AE_LEFT_TO_TOPRIGHT:
889                         az->x1 = ar->winrct.xmin - tab_size_y;
890                         az->y1 = ar->winrct.ymax - ((edge_offset + 1.0f) * tab_size_x);
891                         az->x2 = ar->winrct.xmin;
892                         az->y2 = ar->winrct.ymax - (edge_offset * tab_size_x);
893                         break;
894                 case AE_RIGHT_TO_TOPLEFT:
895                         az->x1 = ar->winrct.xmax;
896                         az->y1 = ar->winrct.ymax - ((edge_offset + 1.0f) * tab_size_x);
897                         az->x2 = ar->winrct.xmax + tab_size_y;
898                         az->y2 = ar->winrct.ymax - (edge_offset * tab_size_x);
899                         break;
900         }
901         /* rect needed for mouse pointer test */
902         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
903 }
904
905 static bool region_azone_edge_poll(const ARegion *ar, const bool is_fullscreen)
906 {
907         const bool is_hidden = (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL));
908
909         if (is_hidden && is_fullscreen) {
910                 return false;
911         }
912         if (!is_hidden && ar->regiontype == RGN_TYPE_HEADER) {
913                 return false;
914         }
915
916         return true;
917 }
918
919 static void region_azone_edge_initialize(ScrArea *sa, ARegion *ar, AZEdge edge, const bool is_fullscreen)
920 {
921         AZone *az = NULL;
922         const bool is_hidden = (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL));
923
924         if (!region_azone_edge_poll(ar, is_fullscreen)) {
925                 return;
926         }
927
928         az = (AZone *)MEM_callocN(sizeof(AZone), "actionzone");
929         BLI_addtail(&(sa->actionzones), az);
930         az->type = AZONE_REGION;
931         az->ar = ar;
932         az->edge = edge;
933
934         if (is_hidden) {
935                 region_azone_tab_plus(sa, az, ar);
936         }
937         else {
938                 region_azone_edge(az, ar);
939         }
940 }
941
942 static void region_azone_scrollbar_initialize(ScrArea *sa, ARegion *ar, AZScrollDirection direction)
943 {
944         rcti scroller_vert = (direction == AZ_SCROLL_VERT) ? ar->v2d.vert : ar->v2d.hor;
945         AZone *az = MEM_callocN(sizeof(*az), __func__);
946
947         BLI_addtail(&sa->actionzones, az);
948         az->type = AZONE_REGION_SCROLL;
949         az->ar = ar;
950         az->direction = direction;
951
952         if (direction == AZ_SCROLL_VERT) {
953                 az->ar->v2d.alpha_vert = 0;
954         }
955         else if (direction == AZ_SCROLL_HOR) {
956                 az->ar->v2d.alpha_hor = 0;
957         }
958
959         BLI_rcti_translate(&scroller_vert, ar->winrct.xmin, ar->winrct.ymin);
960         az->x1 = scroller_vert.xmin - AZONEFADEIN;
961         az->y1 = scroller_vert.ymin - AZONEFADEIN;
962         az->x2 = scroller_vert.xmax + AZONEFADEIN;
963         az->y2 = scroller_vert.ymax + AZONEFADEIN;
964
965         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
966 }
967
968 static void region_azones_scrollbars_initialize(ScrArea *sa, ARegion *ar)
969 {
970         const View2D *v2d = &ar->v2d;
971
972         if ((v2d->scroll & V2D_SCROLL_VERTICAL)   && ((v2d->scroll & V2D_SCROLL_SCALE_VERTICAL)   == 0)) {
973                 region_azone_scrollbar_initialize(sa, ar, AZ_SCROLL_VERT);
974         }
975         if ((v2d->scroll & V2D_SCROLL_HORIZONTAL) && ((v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL) == 0)) {
976                 region_azone_scrollbar_initialize(sa, ar, AZ_SCROLL_HOR);
977         }
978 }
979
980
981 /* *************************************************************** */
982
983 static void region_azones_add(const bScreen *screen, ScrArea *sa, ARegion *ar, const int alignment)
984 {
985         const bool is_fullscreen = screen->state == SCREENFULL;
986
987         /* edge code (t b l r) is along which area edge azone will be drawn */
988
989         if (ar->regiontype == RGN_TYPE_HEADER && ar->winy + 6 > sa->winy) {
990                 /* The logic for this is: when the header takes up the full area,
991                  * disallow hiding it to view the main window.
992                  *
993                  * Without this, you can drag down the file selectors header and hide it
994                  * by accident very easily (highly annoying!), the value 6 is arbitrary
995                  * but accounts for small common rounding problems when scaling the UI,
996                  * must be minimum '4' */
997         }
998         else if (alignment == RGN_ALIGN_TOP)
999                 region_azone_edge_initialize(sa, ar, AE_BOTTOM_TO_TOPLEFT, is_fullscreen);
1000         else if (alignment == RGN_ALIGN_BOTTOM)
1001                 region_azone_edge_initialize(sa, ar, AE_TOP_TO_BOTTOMRIGHT, is_fullscreen);
1002         else if (alignment == RGN_ALIGN_RIGHT)
1003                 region_azone_edge_initialize(sa, ar, AE_LEFT_TO_TOPRIGHT, is_fullscreen);
1004         else if (alignment == RGN_ALIGN_LEFT)
1005                 region_azone_edge_initialize(sa, ar, AE_RIGHT_TO_TOPLEFT, is_fullscreen);
1006
1007         if (is_fullscreen) {
1008                 fullscreen_azone_initialize(sa, ar);
1009         }
1010
1011         region_azones_scrollbars_initialize(sa, ar);
1012 }
1013
1014 /* dir is direction to check, not the splitting edge direction! */
1015 static int rct_fits(const rcti *rect, char dir, int size)
1016 {
1017         if (dir == 'h') {
1018                 return BLI_rcti_size_x(rect) + 1 - size;
1019         }
1020         else {  /* 'v' */
1021                 return BLI_rcti_size_y(rect) + 1 - size;
1022         }
1023 }
1024
1025 /* *************************************************************** */
1026
1027 /* ar should be overlapping */
1028 /* function checks if some overlapping region was defined before - on same place */
1029 static void region_overlap_fix(ScrArea *sa, ARegion *ar)
1030 {
1031         ARegion *ar1;
1032         const int align = ar->alignment & ~RGN_SPLIT_PREV;
1033         int align1 = 0;
1034
1035         /* find overlapping previous region on same place */
1036         for (ar1 = ar->prev; ar1; ar1 = ar1->prev) {
1037                 if (ar1->flag & (RGN_FLAG_HIDDEN)) {
1038                         continue;
1039                 }
1040
1041                 if (ar1->overlap && ((ar1->alignment & RGN_SPLIT_PREV) == 0)) {
1042                         if (ELEM(ar1->alignment, RGN_ALIGN_FLOAT)) {
1043                                 continue;
1044                         }
1045                         align1 = ar1->alignment;
1046                         if (BLI_rcti_isect(&ar1->winrct, &ar->winrct, NULL)) {
1047                                 if (align1 != align) {
1048                                         /* Left overlapping right or vice-versa, forbid this! */
1049                                         ar->flag |= RGN_FLAG_TOO_SMALL;
1050                                         return;
1051                                 }
1052                                 /* Else, we have our previous region on same side. */
1053                                 break;
1054                         }
1055                 }
1056         }
1057
1058         /* translate or close */
1059         if (ar1) {
1060                 if (align1 == RGN_ALIGN_LEFT) {
1061                         if (ar->winrct.xmax + ar1->winx > sa->winx - U.widget_unit) {
1062                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1063                                 return;
1064                         }
1065                         else {
1066                                 BLI_rcti_translate(&ar->winrct, ar1->winx, 0);
1067                         }
1068                 }
1069                 else if (align1 == RGN_ALIGN_RIGHT) {
1070                         if (ar->winrct.xmin - ar1->winx < U.widget_unit) {
1071                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1072                                 return;
1073                         }
1074                         else {
1075                                 BLI_rcti_translate(&ar->winrct, -ar1->winx, 0);
1076                         }
1077                 }
1078         }
1079
1080         /* At this point, 'ar' is in its final position and still open.
1081          * Make a final check it does not overlap any previous 'other side' region. */
1082         for (ar1 = ar->prev; ar1; ar1 = ar1->prev) {
1083                 if (ar1->flag & (RGN_FLAG_HIDDEN)) {
1084                         continue;
1085                 }
1086                 if (ELEM(ar1->alignment, RGN_ALIGN_FLOAT)) {
1087                         continue;
1088                 }
1089
1090                 if (ar1->overlap && (ar1->alignment & RGN_SPLIT_PREV) == 0) {
1091                         if ((ar1->alignment != align) && BLI_rcti_isect(&ar1->winrct, &ar->winrct, NULL)) {
1092                                 /* Left overlapping right or vice-versa, forbid this! */
1093                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1094                                 return;
1095                         }
1096                 }
1097         }
1098 }
1099
1100 /* overlapping regions only in the following restricted cases */
1101 bool ED_region_is_overlap(int spacetype, int regiontype)
1102 {
1103         if (regiontype == RGN_TYPE_HUD) {
1104                 return true;
1105         }
1106         if (U.uiflag2 & USER_REGION_OVERLAP) {
1107                 if (spacetype == SPACE_NODE) {
1108                         if (regiontype == RGN_TYPE_TOOLS) {
1109                                 return true;
1110                         }
1111                 }
1112                 else if (ELEM(spacetype, SPACE_VIEW3D, SPACE_IMAGE)) {
1113                         if (ELEM(regiontype, RGN_TYPE_TOOLS, RGN_TYPE_UI, RGN_TYPE_TOOL_PROPS)) {
1114                                 return true;
1115                         }
1116
1117                         if (ELEM(spacetype, SPACE_VIEW3D, SPACE_IMAGE)) {
1118                                 if (regiontype == RGN_TYPE_HEADER) {
1119                                         return true;
1120                                 }
1121                         }
1122                 }
1123         }
1124
1125         return false;
1126 }
1127
1128 static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, rcti *overlap_remainder, int quad)
1129 {
1130         rcti *remainder_prev = remainder;
1131
1132         if (ar == NULL)
1133                 return;
1134
1135         int prev_winx = ar->winx;
1136         int prev_winy = ar->winy;
1137
1138         /* no returns in function, winrct gets set in the end again */
1139         BLI_rcti_init(&ar->winrct, 0, 0, 0, 0);
1140
1141         /* for test; allow split of previously defined region */
1142         if (ar->alignment & RGN_SPLIT_PREV)
1143                 if (ar->prev)
1144                         remainder = &ar->prev->winrct;
1145
1146         int alignment = ar->alignment & ~RGN_SPLIT_PREV;
1147
1148         /* set here, assuming userpref switching forces to call this again */
1149         ar->overlap = ED_region_is_overlap(sa->spacetype, ar->regiontype);
1150
1151         /* clear state flags first */
1152         ar->flag &= ~(RGN_FLAG_TOO_SMALL | RGN_FLAG_SIZE_CLAMP_X | RGN_FLAG_SIZE_CLAMP_Y);
1153         /* user errors */
1154         if ((ar->next == NULL) && !ELEM(alignment, RGN_ALIGN_QSPLIT, RGN_ALIGN_FLOAT)) {
1155                 alignment = RGN_ALIGN_NONE;
1156         }
1157
1158         /* prefsize, taking into account DPI */
1159         int prefsizex = UI_DPI_FAC * ((ar->sizex > 1) ? ar->sizex + 0.5f : ar->type->prefsizex);
1160         int prefsizey;
1161
1162         if (ar->flag & RGN_FLAG_PREFSIZE_OR_HIDDEN) {
1163                 prefsizex = UI_DPI_FAC * ar->type->prefsizex;
1164                 prefsizey = UI_DPI_FAC * ar->type->prefsizey;
1165         }
1166         else if (ar->regiontype == RGN_TYPE_HEADER) {
1167                 prefsizey = ED_area_headersize();
1168         }
1169         else if (ED_area_is_global(sa)) {
1170                 prefsizey = ED_region_global_size_y();
1171         }
1172         else if (ar->regiontype == RGN_TYPE_UI && sa->spacetype == SPACE_FILE) {
1173                 prefsizey = UI_UNIT_Y * 2 + (UI_UNIT_Y / 2);
1174         }
1175         else {
1176                 prefsizey = UI_DPI_FAC * (ar->sizey > 1 ? ar->sizey + 0.5f : ar->type->prefsizey);
1177         }
1178
1179
1180         if (ar->flag & RGN_FLAG_HIDDEN) {
1181                 /* hidden is user flag */
1182         }
1183         else if (alignment == RGN_ALIGN_FLOAT) {
1184                 /**
1185                  * \note Currently this window type is only used for #RGN_TYPE_HUD,
1186                  * We expect the panel to resize it's self to be larger.
1187                  *
1188                  * This aligns to the lower left of the area.
1189                  */
1190                 const int size_min[2] = {UI_UNIT_X, UI_UNIT_Y};
1191                 rcti overlap_remainder_margin = *overlap_remainder;
1192                 BLI_rcti_resize(
1193                         &overlap_remainder_margin,
1194                         max_ii(0, BLI_rcti_size_x(overlap_remainder) - UI_UNIT_X / 2),
1195                         max_ii(0, BLI_rcti_size_y(overlap_remainder) - UI_UNIT_Y / 2));
1196                 ar->winrct.xmin = overlap_remainder_margin.xmin;
1197                 ar->winrct.ymin = overlap_remainder_margin.ymin;
1198                 ar->winrct.xmax = ar->winrct.xmin + prefsizex - 1;
1199                 ar->winrct.ymax = ar->winrct.ymin + prefsizey - 1;
1200
1201                 BLI_rcti_isect(&ar->winrct, &overlap_remainder_margin, &ar->winrct);
1202
1203                 if (BLI_rcti_size_x(&ar->winrct) != prefsizex - 1) {
1204                         ar->flag |= RGN_FLAG_SIZE_CLAMP_X;
1205                 }
1206                 if (BLI_rcti_size_y(&ar->winrct) != prefsizey - 1) {
1207                         ar->flag |= RGN_FLAG_SIZE_CLAMP_Y;
1208                 }
1209
1210                 /* We need to use a test that wont have been previously clamped. */
1211                 rcti winrct_test = {
1212                         .xmin = ar->winrct.xmin,
1213                         .ymin = ar->winrct.ymin,
1214                         .xmax = ar->winrct.xmin + size_min[0],
1215                         .ymax = ar->winrct.ymin + size_min[1],
1216                 };
1217                 BLI_rcti_isect(&winrct_test, &overlap_remainder_margin, &winrct_test);
1218                 if (BLI_rcti_size_x(&winrct_test) < size_min[0] ||
1219                     BLI_rcti_size_y(&winrct_test) < size_min[1])
1220                 {
1221                         ar->flag |= RGN_FLAG_TOO_SMALL;
1222                 }
1223         }
1224         else if (rct_fits(remainder, 'v', 1) < 0 || rct_fits(remainder, 'h', 1) < 0) {
1225                 /* remainder is too small for any usage */
1226                 ar->flag |= RGN_FLAG_TOO_SMALL;
1227         }
1228         else if (alignment == RGN_ALIGN_NONE) {
1229                 /* typically last region */
1230                 ar->winrct = *remainder;
1231                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1232         }
1233         else if (alignment == RGN_ALIGN_TOP || alignment == RGN_ALIGN_BOTTOM) {
1234                 rcti *winrct = (ar->overlap) ? overlap_remainder : remainder;
1235
1236                 if (rct_fits(winrct, 'v', prefsizey) < 0) {
1237                         ar->flag |= RGN_FLAG_TOO_SMALL;
1238                 }
1239                 else {
1240                         int fac = rct_fits(winrct, 'v', prefsizey);
1241
1242                         if (fac < 0)
1243                                 prefsizey += fac;
1244
1245                         ar->winrct = *winrct;
1246
1247                         if (alignment == RGN_ALIGN_TOP) {
1248                                 ar->winrct.ymin = ar->winrct.ymax - prefsizey + 1;
1249                                 winrct->ymax = ar->winrct.ymin - 1;
1250                         }
1251                         else {
1252                                 ar->winrct.ymax = ar->winrct.ymin + prefsizey - 1;
1253                                 winrct->ymin = ar->winrct.ymax + 1;
1254                         }
1255                 }
1256         }
1257         else if (ELEM(alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
1258                 rcti *winrct = (ar->overlap) ? overlap_remainder : remainder;
1259
1260                 if (rct_fits(winrct, 'h', prefsizex) < 0) {
1261                         ar->flag |= RGN_FLAG_TOO_SMALL;
1262                 }
1263                 else {
1264                         int fac = rct_fits(winrct, 'h', prefsizex);
1265
1266                         if (fac < 0)
1267                                 prefsizex += fac;
1268
1269                         ar->winrct = *winrct;
1270
1271                         if (alignment == RGN_ALIGN_RIGHT) {
1272                                 ar->winrct.xmin = ar->winrct.xmax - prefsizex + 1;
1273                                 winrct->xmax = ar->winrct.xmin - 1;
1274                         }
1275                         else {
1276                                 ar->winrct.xmax = ar->winrct.xmin + prefsizex - 1;
1277                                 winrct->xmin = ar->winrct.xmax + 1;
1278                         }
1279                 }
1280         }
1281         else if (alignment == RGN_ALIGN_VSPLIT || alignment == RGN_ALIGN_HSPLIT) {
1282                 /* percentage subdiv*/
1283                 ar->winrct = *remainder;
1284
1285                 if (alignment == RGN_ALIGN_HSPLIT) {
1286                         if (rct_fits(remainder, 'h', prefsizex) > 4) {
1287                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1288                                 remainder->xmin = ar->winrct.xmax + 1;
1289                         }
1290                         else {
1291                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1292                         }
1293                 }
1294                 else {
1295                         if (rct_fits(remainder, 'v', prefsizey) > 4) {
1296                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1297                                 remainder->ymin = ar->winrct.ymax + 1;
1298                         }
1299                         else {
1300                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1301                         }
1302                 }
1303         }
1304         else if (alignment == RGN_ALIGN_QSPLIT) {
1305                 ar->winrct = *remainder;
1306
1307                 /* test if there's still 4 regions left */
1308                 if (quad == 0) {
1309                         ARegion *artest = ar->next;
1310                         int count = 1;
1311
1312                         while (artest) {
1313                                 artest->alignment = RGN_ALIGN_QSPLIT;
1314                                 artest = artest->next;
1315                                 count++;
1316                         }
1317
1318                         if (count != 4) {
1319                                 /* let's stop adding regions */
1320                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1321                                 if (G.debug & G_DEBUG)
1322                                         printf("region quadsplit failed\n");
1323                         }
1324                         else {
1325                                 quad = 1;
1326                         }
1327                 }
1328                 if (quad) {
1329                         if (quad == 1) { /* left bottom */
1330                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1331                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1332                         }
1333                         else if (quad == 2) { /* left top */
1334                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1335                                 ar->winrct.ymin = BLI_rcti_cent_y(remainder) + 1;
1336                         }
1337                         else if (quad == 3) { /* right bottom */
1338                                 ar->winrct.xmin = BLI_rcti_cent_x(remainder) + 1;
1339                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1340                         }
1341                         else {  /* right top */
1342                                 ar->winrct.xmin = BLI_rcti_cent_x(remainder) + 1;
1343                                 ar->winrct.ymin = BLI_rcti_cent_y(remainder) + 1;
1344                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1345                         }
1346
1347                         quad++;
1348                 }
1349         }
1350
1351         /* for speedup */
1352         ar->winx = BLI_rcti_size_x(&ar->winrct) + 1;
1353         ar->winy = BLI_rcti_size_y(&ar->winrct) + 1;
1354
1355         /* if region opened normally, we store this for hide/reveal usage */
1356         /* prevent rounding errors for UI_DPI_FAC mult and divide */
1357         if (ar->winx > 1) ar->sizex = (ar->winx + 0.5f) /  UI_DPI_FAC;
1358         if (ar->winy > 1) ar->sizey = (ar->winy + 0.5f) /  UI_DPI_FAC;
1359
1360         /* exception for multiple overlapping regions on same spot */
1361         if (ar->overlap && (alignment != RGN_ALIGN_FLOAT)) {
1362                 region_overlap_fix(sa, ar);
1363         }
1364
1365         /* set winrect for azones */
1366         if (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) {
1367                 ar->winrct = (ar->overlap) ? *overlap_remainder : *remainder;
1368
1369                 switch (alignment) {
1370                         case RGN_ALIGN_TOP:
1371                                 ar->winrct.ymin = ar->winrct.ymax;
1372                                 break;
1373                         case RGN_ALIGN_BOTTOM:
1374                                 ar->winrct.ymax = ar->winrct.ymin;
1375                                 break;
1376                         case RGN_ALIGN_RIGHT:
1377                                 ar->winrct.xmin = ar->winrct.xmax;
1378                                 break;
1379                         case RGN_ALIGN_LEFT:
1380                         default:
1381                                 /* prevent winrct to be valid */
1382                                 ar->winrct.xmax = ar->winrct.xmin;
1383                                 break;
1384                 }
1385         }
1386
1387         /* restore prev-split exception */
1388         if (ar->alignment & RGN_SPLIT_PREV) {
1389                 if (ar->prev) {
1390                         remainder = remainder_prev;
1391                         ar->prev->winx = BLI_rcti_size_x(&ar->prev->winrct) + 1;
1392                         ar->prev->winy = BLI_rcti_size_y(&ar->prev->winrct) + 1;
1393                 }
1394         }
1395
1396         /* After non-overlapping region, all following overlapping regions
1397          * fit within the remaining space again. */
1398         if (!ar->overlap) {
1399                 *overlap_remainder = *remainder;
1400         }
1401
1402         region_rect_recursive(sa, ar->next, remainder, overlap_remainder, quad);
1403
1404         /* Tag for redraw if size changes. */
1405         if (ar->winx != prev_winx || ar->winy != prev_winy) {
1406                 ED_region_tag_redraw(ar);
1407         }
1408 }
1409
1410 static void area_calc_totrct(ScrArea *sa, const rcti *window_rect)
1411 {
1412         short px = (short)U.pixelsize;
1413
1414         sa->totrct.xmin = sa->v1->vec.x;
1415         sa->totrct.xmax = sa->v4->vec.x;
1416         sa->totrct.ymin = sa->v1->vec.y;
1417         sa->totrct.ymax = sa->v2->vec.y;
1418
1419         /* scale down totrct by 1 pixel on all sides not matching window borders */
1420         if (sa->totrct.xmin > window_rect->xmin) {
1421                 sa->totrct.xmin += px;
1422         }
1423         if (sa->totrct.xmax < (window_rect->xmax - 1)) {
1424                 sa->totrct.xmax -= px;
1425         }
1426         if (sa->totrct.ymin > window_rect->ymin) {
1427                 sa->totrct.ymin += px;
1428         }
1429         if (sa->totrct.ymax < (window_rect->ymax - 1)) {
1430                 sa->totrct.ymax -= px;
1431         }
1432         /* Although the following asserts are correct they lead to a very unstable Blender.
1433          * And the asserts would fail even in 2.7x (they were added in 2.8x as part of the top-bar commit).
1434          * For more details see T54864. */
1435 #if 0
1436         BLI_assert(sa->totrct.xmin >= 0);
1437         BLI_assert(sa->totrct.xmax >= 0);
1438         BLI_assert(sa->totrct.ymin >= 0);
1439         BLI_assert(sa->totrct.ymax >= 0);
1440 #endif
1441
1442         /* for speedup */
1443         sa->winx = BLI_rcti_size_x(&sa->totrct) + 1;
1444         sa->winy = BLI_rcti_size_y(&sa->totrct) + 1;
1445 }
1446
1447
1448 /* used for area initialize below */
1449 static void region_subwindow(ARegion *ar)
1450 {
1451         bool hidden = (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) != 0;
1452
1453         if ((ar->alignment & RGN_SPLIT_PREV) && ar->prev)
1454                 hidden = hidden || (ar->prev->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL));
1455
1456         ar->visible = !hidden;
1457 }
1458
1459 /**
1460  * \param ar: Region, may be NULL when adding handlers for \a sa.
1461  */
1462 static void ed_default_handlers(wmWindowManager *wm, ScrArea *sa, ARegion *ar, ListBase *handlers, int flag)
1463 {
1464         BLI_assert(ar ? (&ar->handlers == handlers) : (&sa->handlers == handlers));
1465
1466         /* note, add-handler checks if it already exists */
1467
1468         /* XXX it would be good to have boundbox checks for some of these... */
1469         if (flag & ED_KEYMAP_UI) {
1470                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "User Interface", 0, 0);
1471                 WM_event_add_keymap_handler(handlers, keymap);
1472
1473                 /* user interface widgets */
1474                 UI_region_handlers_add(handlers);
1475         }
1476         if (flag & ED_KEYMAP_GIZMO) {
1477                 BLI_assert(ar && ar->type->regionid == RGN_TYPE_WINDOW);
1478                 if (ar) {
1479                         /* Anything else is confusing, only allow this. */
1480                         BLI_assert(&ar->handlers == handlers);
1481                         if (ar->gizmo_map == NULL) {
1482                                 ar->gizmo_map = WM_gizmomap_new_from_type(
1483                                         &(const struct wmGizmoMapType_Params){sa->spacetype, ar->type->regionid});
1484                         }
1485                         WM_gizmomap_add_handlers(ar, ar->gizmo_map);
1486                 }
1487         }
1488         if (flag & ED_KEYMAP_TOOL) {
1489                 WM_event_add_keymap_handler_dynamic(&ar->handlers, WM_event_get_keymap_from_toolsystem, sa);
1490         }
1491         if (flag & ED_KEYMAP_VIEW2D) {
1492                 /* 2d-viewport handling+manipulation */
1493                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "View2D", 0, 0);
1494                 WM_event_add_keymap_handler(handlers, keymap);
1495         }
1496         if (flag & ED_KEYMAP_MARKERS) {
1497                 /* time-markers */
1498                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Markers", 0, 0);
1499
1500                 /* use a boundbox restricted map */
1501                 /* same local check for all areas */
1502                 static rcti rect = {0, 10000, 0, -1};
1503                 rect.ymax = UI_MARKER_MARGIN_Y;
1504                 BLI_assert(ar->type->regionid == RGN_TYPE_WINDOW);
1505                 WM_event_add_keymap_handler_bb(handlers, keymap, &rect, &ar->winrct);
1506         }
1507         if (flag & ED_KEYMAP_ANIMATION) {
1508                 /* frame changing and timeline operators (for time spaces) */
1509                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Animation", 0, 0);
1510                 WM_event_add_keymap_handler(handlers, keymap);
1511         }
1512         if (flag & ED_KEYMAP_FRAMES) {
1513                 /* frame changing/jumping (for all spaces) */
1514                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Frames", 0, 0);
1515                 WM_event_add_keymap_handler(handlers, keymap);
1516         }
1517         if (flag & ED_KEYMAP_HEADER) {
1518                 /* standard keymap for headers regions */
1519                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Header", 0, 0);
1520                 WM_event_add_keymap_handler(handlers, keymap);
1521         }
1522
1523         /* Keep last because of LMB/RMB handling, see: T57527. */
1524         if (flag & ED_KEYMAP_GPENCIL) {
1525                 /* grease pencil */
1526                 /* NOTE: This is now 4 keymaps - One for basic functionality,
1527                  *       and others for special stroke modes (edit, paint and sculpt).
1528                  *
1529                  *       For now, it's easier to just include all,
1530                  *       since you hardly want one without the others.
1531                  */
1532                 wmKeyMap *keymap_general = WM_keymap_ensure(wm->defaultconf, "Grease Pencil", 0, 0);
1533                 WM_event_add_keymap_handler(handlers, keymap_general);
1534
1535                 wmKeyMap *keymap_edit = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Edit Mode", 0, 0);
1536                 WM_event_add_keymap_handler(handlers, keymap_edit);
1537
1538                 wmKeyMap *keymap_paint = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint Mode", 0, 0);
1539                 WM_event_add_keymap_handler(handlers, keymap_paint);
1540
1541                 wmKeyMap *keymap_paint_draw = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Draw brush)", 0, 0);
1542                 WM_event_add_keymap_handler(handlers, keymap_paint_draw);
1543
1544                 wmKeyMap *keymap_paint_erase = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Erase)", 0, 0);
1545                 WM_event_add_keymap_handler(handlers, keymap_paint_erase);
1546
1547                 wmKeyMap *keymap_paint_fill = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Fill)", 0, 0);
1548                 WM_event_add_keymap_handler(handlers, keymap_paint_fill);
1549
1550                 wmKeyMap *keymap_sculpt = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Sculpt Mode", 0, 0);
1551                 WM_event_add_keymap_handler(handlers, keymap_sculpt);
1552         }
1553 }
1554
1555 void ED_area_update_region_sizes(wmWindowManager *wm, wmWindow *win, ScrArea *area)
1556 {
1557         rcti rect, overlap_rect;
1558         rcti window_rect;
1559
1560         if (!(area->flag & AREA_FLAG_REGION_SIZE_UPDATE)) {
1561                 return;
1562         }
1563         const bScreen *screen = WM_window_get_active_screen(win);
1564
1565         WM_window_rect_calc(win, &window_rect);
1566         area_calc_totrct(area, &window_rect);
1567
1568         /* region rect sizes */
1569         rect = area->totrct;
1570         overlap_rect = rect;
1571         region_rect_recursive(area, area->regionbase.first, &rect, &overlap_rect, 0);
1572
1573         /* Dynamically sized regions may have changed region sizes, so we have to force azone update. */
1574         area_azone_initialize(win, screen, area);
1575
1576         for (ARegion *ar = area->regionbase.first; ar; ar = ar->next) {
1577                 region_subwindow(ar);
1578
1579                 /* region size may have changed, init does necessary adjustments */
1580                 if (ar->type->init) {
1581                         ar->type->init(wm, ar);
1582                 }
1583
1584                 /* Some AZones use View2D data which is only updated in region init, so call that first! */
1585                 region_azones_add(screen, area, ar, ar->alignment & ~RGN_SPLIT_PREV);
1586         }
1587         ED_area_azones_update(area, &win->eventstate->x);
1588
1589         area->flag &= ~AREA_FLAG_REGION_SIZE_UPDATE;
1590 }
1591
1592 /* called in screen_refresh, or screens_init, also area size changes */
1593 void ED_area_initialize(wmWindowManager *wm, wmWindow *win, ScrArea *sa)
1594 {
1595         WorkSpace *workspace = WM_window_get_active_workspace(win);
1596         const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);
1597         ViewLayer *view_layer = WM_window_get_active_view_layer(win);
1598         ARegion *ar;
1599         rcti rect, overlap_rect;
1600         rcti window_rect;
1601
1602         if (ED_area_is_global(sa) && (sa->global->flag & GLOBAL_AREA_IS_HIDDEN)) {
1603                 return;
1604         }
1605         WM_window_rect_calc(win, &window_rect);
1606
1607         /* set typedefinitions */
1608         sa->type = BKE_spacetype_from_id(sa->spacetype);
1609
1610         if (sa->type == NULL) {
1611                 sa->spacetype = SPACE_VIEW3D;
1612                 sa->type = BKE_spacetype_from_id(sa->spacetype);
1613         }
1614
1615         for (ar = sa->regionbase.first; ar; ar = ar->next)
1616                 ar->type = BKE_regiontype_from_id_or_first(sa->type, ar->regiontype);
1617
1618         /* area sizes */
1619         area_calc_totrct(sa, &window_rect);
1620
1621         /* region rect sizes */
1622         rect = sa->totrct;
1623         overlap_rect = rect;
1624         region_rect_recursive(sa, sa->regionbase.first, &rect, &overlap_rect, 0);
1625         sa->flag &= ~AREA_FLAG_REGION_SIZE_UPDATE;
1626
1627         /* default area handlers */
1628         ed_default_handlers(wm, sa, NULL, &sa->handlers, sa->type->keymapflag);
1629         /* checks spacedata, adds own handlers */
1630         if (sa->type->init)
1631                 sa->type->init(wm, sa);
1632
1633         /* clear all azones, add the area triangle widgets */
1634         area_azone_initialize(win, screen, sa);
1635
1636         /* region windows, default and own handlers */
1637         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1638                 region_subwindow(ar);
1639
1640                 if (ar->visible) {
1641                         /* default region handlers */
1642                         ed_default_handlers(wm, sa, ar, &ar->handlers, ar->type->keymapflag);
1643                         /* own handlers */
1644                         if (ar->type->init) {
1645                                 ar->type->init(wm, ar);
1646                         }
1647                 }
1648                 else {
1649                         /* prevent uiblocks to run */
1650                         UI_blocklist_free(NULL, &ar->uiblocks);
1651                 }
1652
1653                 /* Some AZones use View2D data which is only updated in region init, so call that first! */
1654                 region_azones_add(screen, sa, ar, ar->alignment & ~RGN_SPLIT_PREV);
1655         }
1656
1657
1658         /* Avoid re-initializing tools while resizing the window. */
1659         if ((G.moving & G_TRANSFORM_WM) == 0) {
1660                 if ((1 << sa->spacetype) & WM_TOOLSYSTEM_SPACE_MASK) {
1661                         WM_toolsystem_refresh_screen_area(workspace, view_layer, sa);
1662                         sa->flag |= AREA_FLAG_ACTIVE_TOOL_UPDATE;
1663                 }
1664                 else {
1665                         sa->runtime.tool = NULL;
1666                         sa->runtime.is_tool_set = true;
1667                 }
1668         }
1669 }
1670
1671 static void region_update_rect(ARegion *ar)
1672 {
1673         ar->winx = BLI_rcti_size_x(&ar->winrct) + 1;
1674         ar->winy = BLI_rcti_size_y(&ar->winrct) + 1;
1675
1676         /* v2d mask is used to subtract scrollbars from a 2d view. Needs initialize here. */
1677         BLI_rcti_init(&ar->v2d.mask, 0, ar->winx - 1, 0, ar->winy -1);
1678 }
1679
1680 /**
1681  * Call to move a popup window (keep OpenGL context free!)
1682  */
1683 void ED_region_update_rect(ARegion *ar)
1684 {
1685         region_update_rect(ar);
1686 }
1687
1688 /* externally called for floating regions like menus */
1689 void ED_region_init(ARegion *ar)
1690 {
1691         /* refresh can be called before window opened */
1692         region_subwindow(ar);
1693
1694         region_update_rect(ar);
1695 }
1696
1697 void ED_region_cursor_set(wmWindow *win, ScrArea *sa, ARegion *ar)
1698 {
1699         if (ar && sa && ar->type && ar->type->cursor) {
1700                 ar->type->cursor(win, sa, ar);
1701         }
1702         else {
1703                 if (WM_cursor_set_from_tool(win, sa, ar)) {
1704                         return;
1705                 }
1706                 WM_cursor_set(win, CURSOR_STD);
1707         }
1708 }
1709
1710 /* for use after changing visibility of regions */
1711 void ED_region_visibility_change_update(bContext *C, ARegion *ar)
1712 {
1713         ScrArea *sa = CTX_wm_area(C);
1714
1715         if (ar->flag & RGN_FLAG_HIDDEN)
1716                 WM_event_remove_handlers(C, &ar->handlers);
1717
1718         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa);
1719         ED_area_tag_redraw(sa);
1720 }
1721
1722 /* for quick toggle, can skip fades */
1723 void region_toggle_hidden(bContext *C, ARegion *ar, const bool do_fade)
1724 {
1725         ScrArea *sa = CTX_wm_area(C);
1726
1727         ar->flag ^= RGN_FLAG_HIDDEN;
1728
1729         if (do_fade && ar->overlap) {
1730                 /* starts a timer, and in end calls the stuff below itself (region_sblend_invoke()) */
1731                 region_blend_start(C, sa, ar);
1732         }
1733         else {
1734                 ED_region_visibility_change_update(C, ar);
1735         }
1736 }
1737
1738 /* exported to all editors, uses fading default */
1739 void ED_region_toggle_hidden(bContext *C, ARegion *ar)
1740 {
1741         region_toggle_hidden(C, ar, true);
1742 }
1743
1744 /**
1745  * we swap spaces for fullscreen to keep all allocated data area vertices were set
1746  */
1747 void ED_area_data_copy(ScrArea *sa_dst, ScrArea *sa_src, const bool do_free)
1748 {
1749         SpaceType *st;
1750         ARegion *ar;
1751         const char spacetype = sa_dst->spacetype;
1752         const short flag_copy = HEADER_NO_PULLDOWN;
1753
1754         sa_dst->spacetype = sa_src->spacetype;
1755         sa_dst->type = sa_src->type;
1756
1757         sa_dst->flag = (sa_dst->flag & ~flag_copy) | (sa_src->flag & flag_copy);
1758
1759         /* area */
1760         if (do_free) {
1761                 BKE_spacedata_freelist(&sa_dst->spacedata);
1762         }
1763         BKE_spacedata_copylist(&sa_dst->spacedata, &sa_src->spacedata);
1764
1765         /* Note; SPACE_EMPTY is possible on new screens */
1766
1767         /* regions */
1768         if (do_free) {
1769                 st = BKE_spacetype_from_id(spacetype);
1770                 for (ar = sa_dst->regionbase.first; ar; ar = ar->next)
1771                         BKE_area_region_free(st, ar);
1772                 BLI_freelistN(&sa_dst->regionbase);
1773         }
1774         st = BKE_spacetype_from_id(sa_src->spacetype);
1775         for (ar = sa_src->regionbase.first; ar; ar = ar->next) {
1776                 ARegion *newar = BKE_area_region_copy(st, ar);
1777                 BLI_addtail(&sa_dst->regionbase, newar);
1778         }
1779 }
1780
1781 void ED_area_data_swap(ScrArea *sa_dst, ScrArea *sa_src)
1782 {
1783         SWAP(char, sa_dst->spacetype, sa_src->spacetype);
1784         SWAP(SpaceType *, sa_dst->type, sa_src->type);
1785
1786
1787         SWAP(ListBase, sa_dst->spacedata, sa_src->spacedata);
1788         SWAP(ListBase, sa_dst->regionbase, sa_src->regionbase);
1789 }
1790
1791 /* *********** Space switching code *********** */
1792
1793 void ED_area_swapspace(bContext *C, ScrArea *sa1, ScrArea *sa2)
1794 {
1795         ScrArea *tmp = MEM_callocN(sizeof(ScrArea), "addscrarea");
1796
1797         ED_area_exit(C, sa1);
1798         ED_area_exit(C, sa2);
1799
1800         ED_area_data_copy(tmp, sa1, false);
1801         ED_area_data_copy(sa1, sa2, true);
1802         ED_area_data_copy(sa2, tmp, true);
1803         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa1);
1804         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa2);
1805
1806         BKE_screen_area_free(tmp);
1807         MEM_freeN(tmp);
1808
1809         /* tell WM to refresh, cursor types etc */
1810         WM_event_add_mousemove(C);
1811
1812         ED_area_tag_redraw(sa1);
1813         ED_area_tag_refresh(sa1);
1814         ED_area_tag_redraw(sa2);
1815         ED_area_tag_refresh(sa2);
1816 }
1817
1818 /**
1819  * \param skip_ar_exit: Skip calling area exit callback. Set for opening temp spaces.
1820  */
1821 void ED_area_newspace(bContext *C, ScrArea *sa, int type, const bool skip_ar_exit)
1822 {
1823         wmWindow *win = CTX_wm_window(C);
1824
1825         if (sa->spacetype != type) {
1826                 SpaceType *st;
1827                 SpaceLink *slold;
1828                 SpaceLink *sl;
1829                 /* store sa->type->exit callback */
1830                 void *sa_exit = sa->type ? sa->type->exit : NULL;
1831                 /* When the user switches between space-types from the type-selector,
1832                  * changing the header-type is jarring (especially when using Ctrl-MouseWheel).
1833                  *
1834                  * However, add-on install for example, forces the header to the top which shouldn't
1835                  * be applied back to the previous space type when closing - see: T57724
1836                  *
1837                  * Newly created windows wont have any space data, use the alignment
1838                  * the space type defaults to in this case instead
1839                  * (needed for preferences to have space-type on bottom).
1840                  */
1841                 int header_alignment = ED_area_header_alignment_or_fallback(sa, -1);
1842                 const bool sync_header_alignment = (
1843                         (header_alignment != -1) &&
1844                         (sa->flag & AREA_FLAG_TEMP_TYPE) == 0);
1845
1846                 /* in some cases (opening temp space) we don't want to
1847                  * call area exit callback, so we temporarily unset it */
1848                 if (skip_ar_exit && sa->type) {
1849                         sa->type->exit = NULL;
1850                 }
1851
1852                 ED_area_exit(C, sa);
1853
1854                 /* restore old area exit callback */
1855                 if (skip_ar_exit && sa->type) {
1856                         sa->type->exit = sa_exit;
1857                 }
1858
1859                 st = BKE_spacetype_from_id(type);
1860                 slold = sa->spacedata.first;
1861
1862                 sa->spacetype = type;
1863                 sa->type = st;
1864
1865                 /* If st->new may be called, don't use context until then. The
1866                  * sa->type->context() callback has changed but data may be invalid
1867                  * (e.g. with properties editor) until space-data is properly created */
1868
1869                 /* check previously stored space */
1870                 for (sl = sa->spacedata.first; sl; sl = sl->next)
1871                         if (sl->spacetype == type)
1872                                 break;
1873
1874                 /* old spacedata... happened during work on 2.50, remove */
1875                 if (sl && BLI_listbase_is_empty(&sl->regionbase)) {
1876                         st->free(sl);
1877                         BLI_freelinkN(&sa->spacedata, sl);
1878                         if (slold == sl) {
1879                                 slold = NULL;
1880                         }
1881                         sl = NULL;
1882                 }
1883
1884                 if (sl) {
1885                         /* swap regions */
1886                         slold->regionbase = sa->regionbase;
1887                         sa->regionbase = sl->regionbase;
1888                         BLI_listbase_clear(&sl->regionbase);
1889
1890                         /* put in front of list */
1891                         BLI_remlink(&sa->spacedata, sl);
1892                         BLI_addhead(&sa->spacedata, sl);
1893                 }
1894                 else {
1895                         /* new space */
1896                         if (st) {
1897                                 /* Don't get scene from context here which may depend on space-data. */
1898                                 Scene *scene = WM_window_get_active_scene(win);
1899                                 sl = st->new(sa, scene);
1900                                 BLI_addhead(&sa->spacedata, sl);
1901
1902                                 /* swap regions */
1903                                 if (slold)
1904                                         slold->regionbase = sa->regionbase;
1905                                 sa->regionbase = sl->regionbase;
1906                                 BLI_listbase_clear(&sl->regionbase);
1907                         }
1908                 }
1909
1910                 /* Sync header alignment. */
1911                 if (sync_header_alignment) {
1912                         for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) {
1913                                 if (ar->regiontype == RGN_TYPE_HEADER) {
1914                                         ar->alignment = header_alignment;
1915                                         break;
1916                                 }
1917                         }
1918                 }
1919
1920                 ED_area_initialize(CTX_wm_manager(C), win, sa);
1921
1922                 /* tell WM to refresh, cursor types etc */
1923                 WM_event_add_mousemove(C);
1924
1925                 /* send space change notifier */
1926                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_CHANGED, sa);
1927
1928                 ED_area_tag_refresh(sa);
1929         }
1930
1931         /* also redraw when re-used */
1932         ED_area_tag_redraw(sa);
1933 }
1934
1935 void ED_area_prevspace(bContext *C, ScrArea *sa)
1936 {
1937         SpaceLink *sl = sa->spacedata.first;
1938
1939         if (sl && sl->next) {
1940                 ED_area_newspace(C, sa, sl->next->spacetype, false);
1941
1942                 /* keep old spacedata but move it to end, so calling
1943                  * ED_area_prevspace once more won't open it again */
1944                 BLI_remlink(&sa->spacedata, sl);
1945                 BLI_addtail(&sa->spacedata, sl);
1946         }
1947         else {
1948                 /* no change */
1949                 return;
1950         }
1951         sa->flag &= ~(AREA_FLAG_STACKED_FULLSCREEN | AREA_FLAG_TEMP_TYPE);
1952
1953         ED_area_tag_redraw(sa);
1954
1955         /* send space change notifier */
1956         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_CHANGED, sa);
1957 }
1958
1959 /* returns offset for next button in header */
1960 int ED_area_header_switchbutton(const bContext *C, uiBlock *block, int yco)
1961 {
1962         ScrArea *sa = CTX_wm_area(C);
1963         bScreen *scr = CTX_wm_screen(C);
1964         PointerRNA areaptr;
1965         int xco = 0.4 * U.widget_unit;
1966
1967         RNA_pointer_create(&(scr->id), &RNA_Area, sa, &areaptr);
1968
1969         uiDefButR(block, UI_BTYPE_MENU, 0, "", xco, yco, 1.6 * U.widget_unit, U.widget_unit,
1970                   &areaptr, "ui_type", 0, 0.0f, 0.0f, 0.0f, 0.0f, "");
1971
1972         return xco + 1.7 * U.widget_unit;
1973 }
1974
1975 /************************ standard UI regions ************************/
1976
1977 static ThemeColorID region_background_color_id(const bContext *C, const ARegion *region)
1978 {
1979         ScrArea *area = CTX_wm_area(C);
1980
1981         switch (region->regiontype) {
1982                 case RGN_TYPE_HEADER:
1983                         if (ED_screen_area_active(C) || ED_area_is_global(area)) {
1984                                 return TH_HEADER;
1985                         }
1986                         else {
1987                                 return TH_HEADERDESEL;
1988                         }
1989                 case RGN_TYPE_PREVIEW:
1990                         return TH_PREVIEW_BACK;
1991                 default:
1992                         return TH_BACK;
1993         }
1994 }
1995
1996 static void region_clear_color(const bContext *C, const ARegion *ar, ThemeColorID colorid)
1997 {
1998         if (ar->alignment == RGN_ALIGN_FLOAT) {
1999                 /* handle our own drawing. */
2000         }
2001         else if (ar->overlap) {
2002                 /* view should be in pixelspace */
2003                 UI_view2d_view_restore(C);
2004
2005                 float back[4];
2006                 UI_GetThemeColor4fv(colorid, back);
2007                 GPU_clear_color(back[3] * back[0], back[3] * back[1], back[3] * back[2], back[3]);
2008                 GPU_clear(GPU_COLOR_BIT);
2009         }
2010         else {
2011                 UI_ThemeClearColor(colorid);
2012                 GPU_clear(GPU_COLOR_BIT);
2013         }
2014 }
2015
2016 BLI_INLINE bool streq_array_any(const char *s, const char *arr[])
2017 {
2018         for (uint i = 0; arr[i]; i++) {
2019                 if (STREQ(arr[i], s)) {
2020                         return true;
2021                 }
2022         }
2023         return false;
2024 }
2025
2026 static void ed_panel_draw(
2027         const bContext *C,
2028         ScrArea *sa,
2029         ARegion *ar,
2030         ListBase *lb,
2031         PanelType *pt,
2032         Panel *panel,
2033         int w,
2034         int em,
2035         bool vertical)
2036 {
2037         uiStyle *style = UI_style_get_dpi();
2038
2039         /* draw panel */
2040         uiBlock *block = UI_block_begin(C, ar, pt->idname, UI_EMBOSS);
2041
2042         bool open;
2043         panel = UI_panel_begin(sa, ar, lb, block, pt, panel, &open);
2044
2045         /* bad fixed values */
2046         int xco, yco, h = 0;
2047
2048         if (pt->draw_header_preset && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) {
2049                 /* for preset menu */
2050                 panel->layout = UI_block_layout(
2051                         block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER,
2052                         0, (UI_UNIT_Y * 1.1f) + style->panelspace, UI_UNIT_Y, 1, 0, style);
2053
2054                 pt->draw_header_preset(C, panel);
2055
2056                 int headerend = w - UI_UNIT_X;
2057
2058                 UI_block_layout_resolve(block, &xco, &yco);
2059                 UI_block_translate(block, headerend - xco, 0);
2060                 panel->layout = NULL;
2061         }
2062
2063         if (pt->draw_header && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) {
2064                 int labelx, labely;
2065                 UI_panel_label_offset(block, &labelx, &labely);
2066
2067                 /* for enabled buttons */
2068                 panel->layout = UI_block_layout(
2069                         block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER,
2070                         labelx, labely, UI_UNIT_Y, 1, 0, style);
2071
2072                 pt->draw_header(C, panel);
2073
2074                 UI_block_layout_resolve(block, &xco, &yco);
2075                 panel->labelofs = xco - labelx;
2076                 panel->layout = NULL;
2077         }
2078         else {
2079                 panel->labelofs = 0;
2080         }
2081
2082         if (open) {
2083                 short panelContext;
2084
2085                 /* panel context can either be toolbar region or normal panels region */
2086                 if (pt->flag & PNL_LAYOUT_VERT_BAR) {
2087                         panelContext = UI_LAYOUT_VERT_BAR;
2088                 }
2089                 else if (ar->regiontype == RGN_TYPE_TOOLS) {
2090                         panelContext = UI_LAYOUT_TOOLBAR;
2091                 }
2092                 else {
2093                         panelContext = UI_LAYOUT_PANEL;
2094                 }
2095
2096                 panel->layout = UI_block_layout(
2097                         block, UI_LAYOUT_VERTICAL, panelContext,
2098                         (pt->flag & PNL_LAYOUT_VERT_BAR) ? 0 : style->panelspace, 0,
2099                         (pt->flag & PNL_LAYOUT_VERT_BAR) ? 0 : w - 2 * style->panelspace,
2100                         em, 0, style);
2101
2102                 pt->draw(C, panel);
2103
2104                 UI_block_layout_resolve(block, &xco, &yco);
2105                 panel->layout = NULL;
2106
2107                 if (yco != 0) {
2108                         h = -yco + 2 * style->panelspace;
2109                 }
2110         }
2111
2112         UI_block_end(C, block);
2113
2114         /* Draw child panels. */
2115         if (open) {
2116                 for (LinkData *link = pt->children.first; link; link = link->next) {
2117                         PanelType *child_pt = link->data;
2118                         Panel *child_panel = UI_panel_find_by_type(&panel->children, child_pt);
2119
2120                         if (child_pt->draw && (!child_pt->poll || child_pt->poll(C, child_pt))) {
2121                                 ed_panel_draw(C, sa, ar, &panel->children, child_pt, child_panel, w, em, vertical);
2122                         }
2123                 }
2124         }
2125
2126         UI_panel_end(block, w, h);
2127 }
2128
2129 /**
2130  * \param contexts: A NULL terminated array of context strings to match against.
2131  * Matching against any of these strings will draw the panel.
2132  * Can be NULL to skip context checks.
2133  */
2134 void ED_region_panels_layout_ex(
2135         const bContext *C, ARegion *ar,
2136         const char *contexts[], int contextnr, const bool vertical)
2137 {
2138         ar->runtime.category = NULL;
2139
2140         const WorkSpace *workspace = CTX_wm_workspace(C);
2141         ScrArea *sa = CTX_wm_area(C);
2142         PanelType *pt;
2143         View2D *v2d = &ar->v2d;
2144         int x, y, w, em;
2145         bool is_context_new = 0;
2146         int scroll;
2147
2148         /* XXX, should use some better check? */
2149         /* For now also has hardcoded check for clip editor until it supports actual toolbar. */
2150         bool use_category_tabs = ((1 << ar->regiontype) & RGN_TYPE_HAS_CATEGORY_MASK) ||
2151                                  (ar->regiontype == RGN_TYPE_TOOLS && sa->spacetype == SPACE_CLIP);
2152         /* offset panels for small vertical tab area */
2153         const char *category = NULL;
2154         const int category_tabs_width = UI_PANEL_CATEGORY_MARGIN_WIDTH;
2155         int margin_x = 0;
2156         const bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE;
2157
2158         BLI_SMALLSTACK_DECLARE(pt_stack, PanelType *);
2159
2160         if (contextnr != -1)
2161                 is_context_new = UI_view2d_tab_set(v2d, contextnr);
2162
2163         /* before setting the view */
2164         if (vertical) {
2165                 /* only allow scrolling in vertical direction */
2166                 v2d->keepofs |= V2D_LOCKOFS_X | V2D_KEEPOFS_Y;
2167                 v2d->keepofs &= ~(V2D_LOCKOFS_Y | V2D_KEEPOFS_X);
2168                 v2d->scroll &= ~(V2D_SCROLL_BOTTOM);
2169                 v2d->scroll |= (V2D_SCROLL_RIGHT);
2170         }
2171         else {
2172                 /* for now, allow scrolling in both directions (since layouts are optimized for vertical,
2173                  * they often don't fit in horizontal layout)
2174                  */
2175                 v2d->keepofs &= ~(V2D_LOCKOFS_X | V2D_LOCKOFS_Y | V2D_KEEPOFS_X | V2D_KEEPOFS_Y);
2176                 v2d->scroll |= (V2D_SCROLL_BOTTOM);
2177                 v2d->scroll &= ~(V2D_SCROLL_RIGHT);
2178         }
2179
2180         scroll = v2d->scroll;
2181
2182
2183         /* collect panels to draw */
2184         for (pt = ar->type->paneltypes.last; pt; pt = pt->prev) {
2185                 /* Only draw top level panels. */
2186                 if (pt->parent) {
2187                         continue;
2188                 }
2189
2190                 /* verify context */
2191                 if (contexts && pt->context[0] && !streq_array_any(pt->context, contexts)) {
2192                         continue;
2193                 }
2194
2195                 /* If we're tagged, only use compatible. */
2196                 if (pt->owner_id[0] && BKE_workspace_owner_id_check(workspace, pt->owner_id) == false) {
2197                         continue;
2198                 }
2199
2200                 /* draw panel */
2201                 if (pt->draw && (!pt->poll || pt->poll(C, pt))) {
2202                         BLI_SMALLSTACK_PUSH(pt_stack, pt);
2203                 }
2204         }
2205
2206
2207         /* collect categories */
2208         if (use_category_tabs) {
2209                 UI_panel_category_clear_all(ar);
2210
2211                 /* gather unique categories */
2212                 BLI_SMALLSTACK_ITER_BEGIN(pt_stack, pt)
2213                 {
2214                         if (pt->category[0]) {
2215                                 if (!UI_panel_category_find(ar, pt->category)) {
2216                                         UI_panel_category_add(ar, pt->category);
2217                                 }
2218                         }
2219                 }
2220                 BLI_SMALLSTACK_ITER_END;
2221
2222                 if (!UI_panel_category_is_visible(ar)) {
2223                         use_category_tabs = false;
2224                 }
2225                 else {
2226                         category = UI_panel_category_active_get(ar, true);
2227                         margin_x = category_tabs_width;
2228                 }
2229         }
2230
2231
2232         if (vertical) {
2233                 w = BLI_rctf_size_x(&v2d->cur);
2234                 em = (ar->type->prefsizex) ? 10 : 20; /* works out to 10*UI_UNIT_X or 20*UI_UNIT_X */
2235         }
2236         else {
2237                 w = UI_PANEL_WIDTH;
2238                 em = (ar->type->prefsizex) ? 10 : 20;
2239         }
2240
2241         w -= margin_x;
2242
2243         /* create panels */
2244         UI_panels_begin(C, ar);
2245
2246         /* set view2d view matrix  - UI_block_begin() stores it */
2247         UI_view2d_view_ortho(v2d);
2248
2249         BLI_SMALLSTACK_ITER_BEGIN(pt_stack, pt)
2250         {
2251                 Panel *panel = UI_panel_find_by_type(&ar->panels, pt);
2252
2253                 if (use_category_tabs && pt->category[0] && !STREQ(category, pt->category)) {
2254                         if ((panel == NULL) || ((panel->flag & PNL_PIN) == 0)) {
2255                                 continue;
2256                         }
2257                 }
2258
2259                 ed_panel_draw(C, sa, ar, &ar->panels, pt, panel, w, em, vertical);
2260         }
2261         BLI_SMALLSTACK_ITER_END;
2262
2263         /* align panels and return size */
2264         UI_panels_end(C, ar, &x, &y);
2265
2266         /* before setting the view */
2267         if (region_layout_based) {
2268                 /* XXX, only single panel support atm.
2269                  * Can't use x/y values calculated above because they're not using the real height of panels,
2270                  * instead they calculate offsets for the next panel to start drawing. */
2271                 Panel *panel = ar->panels.last;
2272                 if (panel != NULL) {
2273                         int size_dyn[2] = {
2274                                 UI_UNIT_X * ((panel->flag & PNL_CLOSED) ? 8 : 14) / UI_DPI_FAC,
2275                                 UI_panel_size_y(panel) / UI_DPI_FAC,
2276                         };
2277                         /* region size is layout based and needs to be updated */
2278                         if ((ar->sizex != size_dyn[0]) ||
2279                             (ar->sizey != size_dyn[1]))
2280                         {
2281                                 ar->sizex = size_dyn[0];
2282                                 ar->sizey = size_dyn[1];
2283                                 sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE;
2284                         }
2285                         y = ABS(ar->sizey * UI_DPI_FAC - 1);
2286                 }
2287         }
2288         else if (vertical) {
2289                 /* we always keep the scroll offset - so the total view gets increased with the scrolled away part */
2290                 if (v2d->cur.ymax < -FLT_EPSILON) {
2291                         /* Clamp to lower view boundary */
2292                         if (v2d->tot.ymin < -v2d->winy) {
2293                                 y = min_ii(y, 0);
2294                         }
2295                         else {
2296                                 y = min_ii(y, v2d->cur.ymin);
2297                         }
2298                 }
2299
2300                 y = -y;
2301         }
2302         else {
2303                 /* don't jump back when panels close or hide */
2304                 if (!is_context_new) {
2305                         if (v2d->tot.xmax > v2d->winx) {
2306                                 x = max_ii(x, 0);
2307                         }
2308                         else {
2309                                 x = max_ii(x, v2d->cur.xmax);
2310                         }
2311                 }
2312
2313                 y = -y;
2314         }
2315
2316         /* this also changes the 'cur' */
2317         UI_view2d_totRect_set(v2d, x, y);
2318
2319         if (scroll != v2d->scroll) {
2320                 /* Note: this code scales fine, but because of rounding differences, positions of elements
2321                  * flip +1 or -1 pixel compared to redoing the entire layout again.
2322                  * Leaving in commented code for future tests */
2323 #if 0
2324                 UI_panels_scale(ar, BLI_rctf_size_x(&v2d->cur));
2325                 break;
2326 #endif
2327         }
2328
2329         if (use_category_tabs) {
2330                 ar->runtime.category = category;
2331         }
2332 }
2333 void ED_region_panels_layout(const bContext *C, ARegion *ar)
2334 {
2335         ED_region_panels_layout_ex(C, ar, NULL, -1, true);
2336 }
2337
2338 void ED_region_panels_draw(const bContext *C, ARegion *ar)
2339 {
2340         View2D *v2d = &ar->v2d;
2341
2342         if (ar->alignment != RGN_ALIGN_FLOAT) {
2343                 region_clear_color(C, ar, (ar->type->regionid == RGN_TYPE_PREVIEW) ? TH_PREVIEW_BACK : TH_BACK);
2344         }
2345
2346         /* reset line width for drawing tabs */
2347         GPU_line_width(1.0f);
2348
2349         /* set the view */
2350         UI_view2d_view_ortho(v2d);
2351
2352         /* View2D matrix might have changed due to dynamic sized regions. */
2353         UI_blocklist_update_window_matrix(C, &ar->uiblocks);
2354
2355         /* draw panels */
2356         UI_panels_draw(C, ar);
2357
2358         /* restore view matrix */
2359         UI_view2d_view_restore(C);
2360
2361         /* Set in layout. */
2362         if (ar->runtime.category) {
2363                 UI_panel_category_draw_all(ar, ar->runtime.category);
2364         }
2365
2366         /* scrollers */
2367         const rcti *mask = NULL;
2368         rcti        mask_buf;
2369         if (ar->runtime.category && (ar->alignment == RGN_ALIGN_RIGHT)) {
2370                 UI_view2d_mask_from_win(v2d, &mask_buf);
2371                 mask_buf.xmax -= UI_PANEL_CATEGORY_MARGIN_WIDTH;
2372                 mask = &mask_buf;
2373         }
2374         View2DScrollers *scrollers = UI_view2d_scrollers_calc(
2375                 C, v2d, mask, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY);
2376         UI_view2d_scrollers_draw(C, v2d, scrollers);
2377         UI_view2d_scrollers_free(scrollers);
2378 }
2379
2380 void ED_region_panels_ex(
2381         const bContext *C, ARegion *ar,
2382         const char *contexts[], int contextnr, const bool vertical)
2383 {
2384         /* TODO: remove? */
2385         ED_region_panels_layout_ex(C, ar, contexts, contextnr, vertical);
2386         ED_region_panels_draw(C, ar);
2387 }
2388
2389 void ED_region_panels(const bContext *C, ARegion *ar)
2390 {
2391         /* TODO: remove? */
2392         ED_region_panels_layout(C, ar);
2393         ED_region_panels_draw(C, ar);
2394 }
2395
2396 void ED_region_panels_init(wmWindowManager *wm, ARegion *ar)
2397 {
2398         wmKeyMap *keymap;
2399
2400         UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_PANELS_UI, ar->winx, ar->winy);
2401
2402         keymap = WM_keymap_ensure(wm->defaultconf, "View2D Buttons List", 0, 0);
2403         WM_event_add_keymap_handler(&ar->handlers, keymap);
2404 }
2405
2406 void ED_region_header_layout(const bContext *C, ARegion *ar)
2407 {
2408         uiStyle *style = UI_style_get_dpi();
2409         uiBlock *block;
2410         uiLayout *layout;
2411         HeaderType *ht;
2412         Header header = {NULL};
2413         bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE;
2414
2415         /* Height of buttons and scaling needed to achieve it. */
2416         const int buttony = min_ii(UI_UNIT_Y, ar->winy - 2 * UI_DPI_FAC);
2417         const float buttony_scale = buttony / (float)UI_UNIT_Y;
2418
2419         /* Vertically center buttons. */
2420         int xco = UI_HEADER_OFFSET;
2421         int yco = buttony + (ar->winy - buttony) / 2;
2422         int maxco = xco;
2423
2424         /* XXX workaround for 1 px alignment issue. Not sure what causes it... Would prefer a proper fix - Julian */
2425         if (!ELEM(CTX_wm_area(C)->spacetype, SPACE_TOPBAR, SPACE_STATUSBAR)) {
2426                 yco -= 1;
2427         }
2428
2429         /* set view2d view matrix for scrolling (without scrollers) */
2430         UI_view2d_view_ortho(&ar->v2d);
2431
2432         /* draw all headers types */
2433         for (ht = ar->type->headertypes.first; ht; ht = ht->next) {
2434                 if (ht->poll && !ht->poll(C, ht)) {
2435                         continue;
2436                 }
2437
2438                 block = UI_block_begin(C, ar, ht->idname, UI_EMBOSS);
2439                 layout = UI_block_layout(block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER, xco, yco, buttony, 1, 0, style);
2440
2441                 if (buttony_scale != 1.0f) {
2442                         uiLayoutSetScaleY(layout, buttony_scale);
2443                 }
2444
2445                 if (ht->draw) {
2446                         header.type = ht;
2447                         header.layout = layout;
2448                         ht->draw(C, &header);
2449                         if (ht->next) {
2450                                 uiItemS(layout);
2451                         }
2452
2453                         /* for view2d */
2454                         xco = uiLayoutGetWidth(layout);
2455                         if (xco > maxco)
2456                                 maxco = xco;
2457                 }
2458
2459                 UI_block_layout_resolve(block, &xco, &yco);
2460
2461                 /* for view2d */
2462                 if (xco > maxco)
2463                         maxco = xco;
2464
2465                 int new_sizex = (maxco + UI_HEADER_OFFSET) / UI_DPI_FAC;
2466
2467                 if (region_layout_based && (ar->sizex != new_sizex)) {
2468                         /* region size is layout based and needs to be updated */
2469                         ScrArea *sa = CTX_wm_area(C);
2470
2471                         ar->sizex = new_sizex;
2472                         sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE;
2473                 }
2474
2475                 UI_block_end(C, block);
2476         }
2477
2478         if (!region_layout_based) {
2479                 maxco += UI_HEADER_OFFSET;
2480         }
2481
2482         /* always as last  */
2483         UI_view2d_totRect_set(&ar->v2d, maxco, ar->winy);
2484
2485         /* restore view matrix */
2486         UI_view2d_view_restore(C);
2487 }
2488
2489 void ED_region_header_draw(const bContext *C, ARegion *ar)
2490 {
2491         /* clear */
2492         region_clear_color(C, ar, region_background_color_id(C, ar));
2493
2494         UI_view2d_view_ortho(&ar->v2d);
2495
2496         /* View2D matrix might have changed due to dynamic sized regions. */
2497         UI_blocklist_update_window_matrix(C, &ar->uiblocks);
2498
2499         /* draw blocks */
2500         UI_blocklist_draw(C, &ar->uiblocks);
2501
2502         /* restore view matrix */
2503         UI_view2d_view_restore(C);
2504 }
2505
2506 void ED_region_header(const bContext *C, ARegion *ar)
2507 {
2508         /* TODO: remove? */
2509         ED_region_header_layout(C, ar);
2510         ED_region_header_draw(C, ar);
2511 }
2512
2513 void ED_region_header_init(ARegion *ar)
2514 {
2515         UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_HEADER, ar->winx, ar->winy);
2516 }
2517
2518 int ED_area_headersize(void)
2519 {
2520         /* Accomodate widget and padding. */
2521         return U.widget_unit + (int)(UI_DPI_FAC * HEADER_PADDING_Y);
2522 }
2523
2524 int ED_area_header_alignment_or_fallback(const ScrArea *area, int fallback)
2525 {
2526         for (ARegion *ar = area->regionbase.first; ar; ar = ar->next) {
2527                 if (ar->regiontype == RGN_TYPE_HEADER) {
2528                         return ar->alignment;
2529                 }
2530         }
2531         return fallback;
2532 }
2533
2534 int ED_area_header_alignment(const ScrArea *area)
2535 {
2536         return ED_area_header_alignment_or_fallback(
2537                 area, (U.uiflag & USER_HEADER_BOTTOM) ? RGN_ALIGN_BOTTOM : RGN_ALIGN_TOP);
2538 }
2539
2540 /**
2541  * \return the final height of a global \a area, accounting for DPI.
2542  */
2543 int ED_area_global_size_y(const ScrArea *area)
2544 {
2545         BLI_assert(ED_area_is_global(area));
2546         return round_fl_to_int(area->global->cur_fixed_height * UI_DPI_FAC);
2547 }
2548 int ED_area_global_min_size_y(const ScrArea *area)
2549 {
2550         BLI_assert(ED_area_is_global(area));
2551         return round_fl_to_int(area->global->size_min * UI_DPI_FAC);
2552 }
2553 int ED_area_global_max_size_y(const ScrArea *area)
2554 {
2555         BLI_assert(ED_area_is_global(area));
2556         return round_fl_to_int(area->global->size_max * UI_DPI_FAC);
2557 }
2558
2559 bool ED_area_is_global(const ScrArea *area)
2560 {
2561         return area->global != NULL;
2562 }
2563
2564 ScrArea *ED_screen_areas_iter_first(const wmWindow *win, const bScreen *screen)
2565 {
2566         ScrArea *global_area = win->global_areas.areabase.first;
2567
2568         if (!global_area) {
2569                 return screen->areabase.first;
2570         }
2571         else if ((global_area->global->flag & GLOBAL_AREA_IS_HIDDEN) == 0) {
2572                 return global_area;
2573         }
2574         /* Find next visible area. */
2575         return ED_screen_areas_iter_next(screen, global_area);
2576 }
2577 ScrArea *ED_screen_areas_iter_next(const bScreen *screen, const ScrArea *area)
2578 {
2579         if (area->global) {
2580                 for (ScrArea *area_iter = area->next; area_iter; area_iter = area_iter->next) {
2581                         if ((area_iter->global->flag & GLOBAL_AREA_IS_HIDDEN) == 0) {
2582                                 return area_iter;
2583                         }
2584                 }
2585                 /* No visible next global area found, start iterating over layout areas. */
2586                 return screen->areabase.first;
2587         }
2588
2589         return area->next;
2590 }
2591
2592 /**
2593  * For now we just assume all global areas are made up out of horizontal bars
2594  * with the same size. A fixed size could be stored in ARegion instead if needed.
2595  *
2596  * \return the DPI aware height of a single bar/region in global areas.
2597  */
2598 int ED_region_global_size_y(void)
2599 {
2600         return ED_area_headersize(); /* same size as header */
2601 }
2602
2603 void ED_region_info_draw_multiline(ARegion *ar, const char *text_array[], float fill_color[4], const bool full_redraw)
2604 {
2605         const int header_height = UI_UNIT_Y;
2606         uiStyle *style = UI_style_get_dpi();
2607         int fontid = style->widget.uifont_id;
2608         int scissor[4];
2609         rcti rect;
2610         int num_lines = 0;
2611
2612         /* background box */
2613         ED_region_visible_rect(ar, &rect);
2614
2615         /* Box fill entire width or just around text. */
2616         if (!full_redraw) {
2617                 const char **text = &text_array[0];
2618                 while (*text) {
2619                         rect.xmax = min_ii(rect.xmax, rect.xmin + BLF_width(fontid, *text, BLF_DRAW_STR_DUMMY_MAX) + 1.2f * U.widget_unit);
2620                         text++;
2621                         num_lines++;
2622                 }
2623         }
2624         /* Just count the line number. */
2625         else {
2626                 const char **text = &text_array[0];
2627                 while (*text) {
2628                         text++;
2629                         num_lines++;
2630                 }
2631         }
2632
2633         rect.ymin = rect.ymax - header_height * num_lines;
2634
2635         /* setup scissor */
2636         GPU_scissor_get_i(scissor);
2637         GPU_scissor(rect.xmin, rect.ymin,
2638                   BLI_rcti_size_x(&rect) + 1, BLI_rcti_size_y(&rect) + 1);
2639
2640         GPU_blend(true);
2641         GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2642         GPUVertFormat *format = immVertexFormat();
2643         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
2644         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2645         immUniformColor4fv(fill_color);
2646         immRecti(pos, rect.xmin, rect.ymin, rect.xmax + 1, rect.ymax + 1);
2647         immUnbindProgram();
2648         GPU_blend(false);
2649
2650         /* text */
2651         UI_FontThemeColor(fontid, TH_TEXT_HI);
2652         BLF_clipping(fontid, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2653         BLF_enable(fontid, BLF_CLIPPING);
2654         int offset = num_lines - 1;
2655         {
2656                 const char **text = &text_array[0];
2657                 while (*text) {
2658                         BLF_position(fontid, rect.xmin + 0.6f * U.widget_unit, rect.ymin + 0.3f * U.widget_unit + offset * header_height, 0.0f);
2659                         BLF_draw(fontid, *text, BLF_DRAW_STR_DUMMY_MAX);
2660                         text++;
2661                         offset--;
2662                 }
2663         }
2664
2665         BLF_disable(fontid, BLF_CLIPPING);
2666
2667         /* restore scissor as it was before */
2668         GPU_scissor(scissor[0], scissor[1], scissor[2], scissor[3]);
2669 }
2670
2671 void ED_region_info_draw(ARegion *ar, const char *text, float fill_color[4], const bool full_redraw)
2672 {
2673         ED_region_info_draw_multiline(ar, (const char *[2]){text, NULL}, fill_color, full_redraw);
2674 }
2675
2676 #define MAX_METADATA_STR    1024
2677
2678 static const char *meta_data_list[] =
2679 {
2680         "File",
2681         "Strip",
2682         "Date",
2683         "RenderTime",
2684         "Note",
2685         "Marker",
2686         "Time",
2687         "Frame",
2688         "Camera",
2689         "Scene",
2690 };
2691
2692 BLI_INLINE bool metadata_is_valid(ImBuf *ibuf, char *r_str, short index, int offset)
2693 {
2694         return (IMB_metadata_get_field(ibuf->metadata, meta_data_list[index], r_str + offset, MAX_METADATA_STR - offset) && r_str[0]);
2695 }
2696
2697 BLI_INLINE bool metadata_is_custom_drawable(const char *field)
2698 {
2699         /* Metadata field stored by Blender for multilayer EXR images. Is rather
2700          * useless to be viewed all the time. Can still be seen in the Metadata
2701          * panel. */
2702         if (STREQ(field, "BlenderMultiChannel")) {
2703                 return false;
2704         }
2705         /* Is almost always has value "scanlineimage", also useless to be seen
2706          * all the time. */
2707         if (STREQ(field, "type")) {
2708                 return false;
2709         }
2710         return !BKE_stamp_is_known_field(field);
2711 }
2712
2713 typedef struct MetadataCustomDrawContext {
2714         int fontid;
2715         int xmin, ymin;
2716         int vertical_offset;
2717         int current_y;
2718 } MetadataCustomDrawContext;
2719
2720 static void metadata_custom_draw_fields(
2721         const char *field,
2722         const char *value,
2723         void *ctx_v)
2724 {
2725         if (!metadata_is_custom_drawable(field)) {
2726                 return;
2727         }
2728         MetadataCustomDrawContext *ctx = (MetadataCustomDrawContext *)ctx_v;
2729         char temp_str[MAX_METADATA_STR];
2730         BLI_snprintf(temp_str, MAX_METADATA_STR, "%s: %s", field, value);
2731         BLF_position(ctx->fontid, ctx->xmin, ctx->ymin + ctx->current_y, 0.0f);
2732         BLF_draw(ctx->fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2733         ctx->current_y += ctx->vertical_offset;
2734 }
2735
2736 static void metadata_draw_imbuf(ImBuf *ibuf, const rctf *rect, int fontid, const bool is_top)
2737 {
2738         char temp_str[MAX_METADATA_STR];
2739         int line_width;
2740         int ofs_y = 0;
2741         short i;
2742         int len;
2743         const float height = BLF_height_max(fontid);
2744         const float margin = height / 8;
2745         const float vertical_offset = (height + margin);
2746
2747         /* values taking margins into account */
2748         const float descender = BLF_descender(fontid);
2749         const float xmin = (rect->xmin + margin);
2750         const float xmax = (rect->xmax - margin);
2751         const float ymin = (rect->ymin + margin) - descender;
2752         const float ymax = (rect->ymax - margin) - descender;
2753
2754         if (is_top) {
2755                 for (i = 0; i < 4; i++) {
2756                         /* first line */
2757                         if (i == 0) {
2758                                 bool do_newline = false;
2759                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[0]);
2760                                 if (metadata_is_valid(ibuf, temp_str, 0, len)) {
2761                                         BLF_position(fontid, xmin, ymax - vertical_offset, 0.0f);
2762                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2763                                         do_newline = true;
2764                                 }
2765
2766                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[1]);
2767                                 if (metadata_is_valid(ibuf, temp_str, 1, len)) {
2768                                         line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2769                                         BLF_position(fontid, xmax - line_width, ymax - vertical_offset, 0.0f);
2770                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2771                                         do_newline = true;
2772                                 }
2773
2774                                 if (do_newline)
2775                                         ofs_y += vertical_offset;
2776                         } /* Strip */
2777                         else if (i == 1 || i == 2) {
2778                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2779                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2780                                         BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f);
2781                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2782                                         ofs_y += vertical_offset;
2783                                 }
2784                         } /* Note (wrapped) */
2785                         else if (i == 3) {
2786                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2787                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2788                                         struct ResultBLF info;
2789                                         BLF_enable(fontid, BLF_WORD_WRAP);
2790                                         BLF_wordwrap(fontid, ibuf->x - (margin * 2));
2791                                         BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f);
2792                                         BLF_draw_ex(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX, &info);
2793                                         BLF_wordwrap(fontid, 0);
2794                                         BLF_disable(fontid, BLF_WORD_WRAP);
2795                                         ofs_y += vertical_offset * info.lines;
2796                                 }
2797                         }
2798                         else {
2799                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2800                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2801                                         line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2802                                         BLF_position(fontid, xmax  - line_width, ymax - vertical_offset - ofs_y, 0.0f);
2803                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2804                                         ofs_y += vertical_offset;
2805                                 }
2806                         }
2807                 }
2808         }
2809         else {
2810                 MetadataCustomDrawContext ctx;
2811                 ctx.fontid = fontid;
2812                 ctx.xmin = xmin;
2813                 ctx.ymin = ymin;
2814                 ctx.vertical_offset = vertical_offset;
2815                 ctx.current_y = ofs_y;
2816                 ctx.vertical_offset = vertical_offset;
2817                 IMB_metadata_foreach(ibuf, metadata_custom_draw_fields, &ctx);
2818                 int ofs_x = 0;
2819                 ofs_y = ctx.current_y;
2820                 for (i = 5; i < 10; i++) {
2821                         len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i]);
2822                         if (metadata_is_valid(ibuf, temp_str, i, len)) {
2823                                 BLF_position(fontid, xmin + ofs_x, ymin + ofs_y, 0.0f);
2824                                 BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2825
2826                                 ofs_x += BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX) + UI_UNIT_X;
2827                         }
2828                 }
2829         }
2830 }
2831
2832 typedef struct MetadataCustomCountContext {
2833         int count;
2834 } MetadataCustomCountContext;
2835
2836 static void metadata_custom_count_fields(
2837         const char *field,
2838         const char *UNUSED(value),
2839         void *ctx_v)
2840 {
2841         if (!metadata_is_custom_drawable(field)) {
2842                 return;
2843         }
2844         MetadataCustomCountContext *ctx = (MetadataCustomCountContext *)ctx_v;
2845         ctx->count++;
2846 }
2847
2848
2849 static float metadata_box_height_get(ImBuf *ibuf, int fontid, const bool is_top)
2850 {
2851         const float height = BLF_height_max(fontid);
2852         const float margin = (height / 8);
2853         char str[MAX_METADATA_STR] = "";
2854         short i, count = 0;
2855
2856         if (is_top) {
2857                 if (metadata_is_valid(ibuf, str, 0, 0) || metadata_is_valid(ibuf, str, 1, 0)) {
2858                         count++;
2859                 }
2860                 for (i = 2; i < 5; i++) {
2861                         if (metadata_is_valid(ibuf, str, i, 0)) {
2862                                 if (i == 4) {
2863                                         struct {
2864                                                 struct ResultBLF info;
2865                                                 rctf rect;
2866                                         } wrap;
2867
2868                                         BLF_enable(fontid, BLF_WORD_WRAP);
2869                                         BLF_wordwrap(fontid, ibuf->x - (margin * 2));
2870                                         BLF_boundbox_ex(fontid, str, sizeof(str), &wrap.rect, &wrap.info);
2871                                         BLF_wordwrap(fontid, 0);
2872                                         BLF_disable(fontid, BLF_WORD_WRAP);
2873
2874                                         count += wrap.info.lines;
2875                                 }
2876                                 else {
2877                                         count++;
2878                                 }
2879                         }
2880                 }
2881         }
2882         else {
2883                 for (i = 5; i < 10; i++) {
2884                         if (metadata_is_valid(ibuf, str, i, 0)) {
2885                                 count = 1;
2886                                 break;
2887                         }
2888                 }
2889                 MetadataCustomCountContext ctx;
2890                 ctx.count = 0;
2891                 IMB_metadata_foreach(ibuf, metadata_custom_count_fields, &ctx);
2892                 count += ctx.count;
2893         }
2894
2895         if (count) {
2896                 return (height + margin) * count;
2897         }
2898
2899         return 0;
2900 }
2901
2902 #undef MAX_METADATA_STR
2903
2904 void ED_region_image_metadata_draw(int x, int y, ImBuf *ibuf, const rctf *frame, float zoomx, float zoomy)
2905 {
2906         float box_y;
2907         rctf rect;
2908         uiStyle *style = UI_style_get_dpi();
2909
2910         if (!ibuf->metadata)
2911                 return;
2912
2913         /* find window pixel coordinates of origin */
2914         GPU_matrix_push();
2915
2916         /* offset and zoom using ogl */
2917         GPU_matrix_translate_2f(x, y);
2918         GPU_matrix_scale_2f(zoomx, zoomy);
2919
2920         BLF_size(blf_mono_font, style->widgetlabel.points * 1.5f * U.pixelsize, U.dpi);
2921
2922         /* *** upper box*** */
2923
2924         /* get needed box height */
2925         box_y = metadata_box_height_get(ibuf, blf_mono_font, true);
2926
2927         if (box_y) {
2928                 /* set up rect */
2929                 BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymax, frame->ymax + box_y);
2930                 /* draw top box */
2931                 GPUVertFormat *format = immVertexFormat();
2932                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2933                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2934                 immUniformThemeColor(TH_METADATA_BG);
2935                 immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2936                 immUnbindProgram();
2937
2938                 BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2939                 BLF_enable(blf_mono_font, BLF_CLIPPING);
2940
2941                 UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT);
2942                 metadata_draw_imbuf(ibuf, &rect, blf_mono_font, true);
2943
2944                 BLF_disable(blf_mono_font, BLF_CLIPPING);
2945         }
2946
2947
2948         /* *** lower box*** */
2949
2950         box_y = metadata_box_height_get(ibuf, blf_mono_font, false);
2951
2952         if (box_y) {
2953                 /* set up box rect */
2954                 BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymin - box_y, frame->ymin);
2955                 /* draw top box */
2956                 GPUVertFormat *format = immVertexFormat();
2957                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2958                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2959                 immUniformThemeColor(TH_METADATA_BG);
2960                 immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2961                 immUnbindProgram();
2962
2963                 BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2964                 BLF_enable(blf_mono_font, BLF_CLIPPING);
2965
2966                 UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT);
2967                 metadata_draw_imbuf(ibuf, &rect, blf_mono_font, false);
2968
2969                 BLF_disable(blf_mono_font, BLF_CLIPPING);
2970         }
2971
2972         GPU_matrix_pop();
2973 }
2974
2975 typedef struct MetadataPanelDrawContext {
2976         uiLayout *layout;
2977 } MetadataPanelDrawContext;
2978
2979 static void metadata_panel_draw_field(
2980         const char *field,
2981         const char *value,
2982         void *ctx_v)
2983 {
2984         MetadataPanelDrawContext *ctx = (MetadataPanelDrawContext *)ctx_v;
2985         uiLayout *row = uiLayoutRow(ctx->layout, false);
2986         uiItemL(row, field, ICON_NONE);
2987         uiItemL(row, value, ICON_NONE);
2988 }
2989
2990 void ED_region_image_metadata_panel_draw(ImBuf *ibuf, uiLayout *layout)
2991 {
2992         MetadataPanelDrawContext ctx;
2993         ctx.layout = layout;
2994         IMB_metadata_foreach(ibuf, metadata_panel_draw_field, &ctx);
2995 }
2996
2997 void ED_region_grid_draw(ARegion *ar, float zoomx, float zoomy)
2998 {
2999         float gridsize, gridstep = 1.0f / 32.0f;
3000         float fac, blendfac;
3001         int x1, y1, x2, y2;
3002
3003         /* the image is located inside (0, 0), (1, 1) as set by view2d */
3004         UI_view2d_view_to_region(&ar->v2d, 0.0f, 0.0f, &x1, &y1);
3005         UI_view2d_view_to_region(&ar->v2d, 1.0f, 1.0f, &x2, &y2);
3006
3007         GPUVertFormat *format = immVertexFormat();
3008         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
3009
3010         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3011         immUniformThemeColorShade(TH_BACK, 20);
3012         immRectf(pos, x1, y1, x2, y2);
3013         immUnbindProgram();
3014
3015         /* gridsize adapted to zoom level */
3016         gridsize = 0.5f * (zoomx + zoomy);
3017         if (gridsize <= 0.0f)
3018                 return;
3019
3020         if (gridsize < 1.0f) {
3021                 while (gridsize < 1.0f) {
3022                         gridsize *= 4.0f;
3023                         gridstep *= 4.0f;
3024                 }
3025         }
3026         else {
3027                 while (gridsize >= 4.0f) {
3028                         gridsize /= 4.0f;
3029                         gridstep /= 4.0f;
3030                 }
3031         }
3032
3033         blendfac = 0.25f * gridsize - floorf(0.25f * gridsize);
3034         CLAMP(blendfac, 0.0f, 1.0f);
3035
3036         int count_fine = 1.0f / gridstep;
3037         int count_large = 1.0f / (4.0f * gridstep);
3038
3039         if (count_fine > 0) {
3040                 GPU_vertformat_clear(format);
3041                 pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
3042                 unsigned color = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
3043
3044                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
3045                 immBegin(GPU_PRIM_LINES, 4 * count_fine + 4 * count_large);
3046
3047                 float theme_color[3];
3048                 UI_GetThemeColorShade3fv(TH_BACK, (int)(20.0f * (1.0f - blendfac)), theme_color);
3049                 fac = 0.0f;
3050
3051                 /* the fine resolution level */
3052                 for (int i = 0; i < count_fine; i++) {
3053                         immAttr3fv(color, theme_color);
3054                         immVertex2f(pos, x1, y1 * (1.0f - fac) + y2 * fac);
3055                         immAttr3fv(color, theme_color);
3056                         immVertex2f(pos, x2, y1 * (1.0f - fac) + y2 * fac);
3057                         immAttr3fv(color, theme_color);
3058                         immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y1);
3059                         immAttr3fv(color, theme_color);
3060                         immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y2);
3061                         fac += gridstep;
3062                 }
3063
3064                 if (count_large > 0) {
3065                         UI_GetThemeColor3fv(TH_BACK, theme_color);
3066                         fac = 0.0f;
3067
3068                         /* the large resolution level */
3069                         for (int i = 0; i < count_large; i++) {
3070                                 immAttr3fv(color, theme_color);
3071                                 immVertex2f(pos, x1, y1 * (1.0f - fac) + y2 * fac);
3072                                 immAttr3fv(color, theme_color);
3073                                 immVertex2f(pos, x2, y1 * (1.0f - fac) + y2 * fac);
3074                                 immAttr3fv(color, theme_color);
3075                                 immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y1);
3076                                 immAttr3fv(color, theme_color);
3077                                 immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y2);
3078                                 fac += 4.0f * gridstep;
3079                         }
3080                 }
3081
3082                 immEnd();
3083                 immUnbindProgram();
3084         }
3085 }
3086
3087 /* If the area has overlapping regions, it returns visible rect for Region *ar */
3088 /* rect gets returned in local region coordinates */
3089 void ED_region_visible_rect(ARegion *ar, rcti *rect)
3090 {
3091         ARegion *arn = ar;
3092
3093         /* allow function to be called without area */
3094         while (arn->prev)
3095                 arn = arn->prev;
3096
3097         *rect = ar->winrct;
3098
3099         /* check if a region overlaps with the current one */
3100         for (; arn; arn = arn->next) {
3101                 if (ar != arn && arn->overlap) {
3102                         if (BLI_rcti_isect(rect, &arn->winrct, NULL)) {
3103                                 if (ELEM(arn->alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
3104                                         /* Overlap left, also check 1 pixel offset (2 regions on one side). */
3105                                         if (ABS(rect->xmin - arn->winrct.xmin) < 2) {
3106                                                 rect->xmin = arn->winrct.xmax;
3107                                         }
3108
3109                                         /* Overlap right. */
3110                                         if (ABS(rect->xmax - arn->winrct.xmax) < 2) {
3111                                                 rect->xmax = arn->winrct.xmin;
3112                                         }
3113                                 }
3114                                 else if (ELEM(arn->alignment, RGN_ALIGN_TOP, RGN_ALIGN_BOTTOM)) {
3115                                         /* Same logic as above for vertical regions. */
3116                                         if (ABS(rect->ymin - arn->winrct.ymin) < 2) {
3117                                                 rect->ymin = arn->winrct.ymax;
3118                                         }
3119                                         if (ABS(rect->ymax - arn->winrct.ymax) < 2) {
3120                                                 rect->ymax = arn->winrct.ymin;
3121                                         }
3122                                 }
3123                                 else if (arn->alignment == RGN_ALIGN_FLOAT) {
3124                                         /* Skip floating. */
3125                                 }
3126                                 else {
3127                                         BLI_assert(!"Region overlap with unknown alignment");
3128                                 }
3129                         }
3130                 }
3131         }
3132         BLI_rcti_translate(rect, -ar->winrct.xmin, -ar->winrct.ymin);
3133 }
3134
3135 /* Cache display helpers */
3136
3137 void ED_region_cache_draw_background(const ARegion *ar)
3138 {
3139         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3140         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3141         immUniformColor4ub(128, 128, 255, 64);
3142         immRecti(pos, 0, 0, ar->winx, 8 * UI_DPI_FAC);
3143         immUnbindProgram();
3144 }
3145
3146 void ED_region_cache_draw_curfra_label(const int framenr, const float x, const float y)
3147 {
3148         uiStyle *style = UI_style_get();
3149         int fontid = style->widget.uifont_id;
3150         char numstr[32];
3151         float font_dims[2] = {0.0f, 0.0f};
3152
3153         /* frame number */
3154         BLF_size(fontid, 11.0f * U.pixelsize, U.dpi);
3155         BLI_snprintf(numstr, sizeof(numstr), "%d", framenr);
3156
3157         BLF_width_and_height(fontid, numstr, sizeof(numstr), &font_dims[0], &font_dims[1]);
3158
3159         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3160         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3161         immUniformThemeColor(TH_CFRAME);
3162         immRecti(pos, x, y, x + font_dims[0] + 6.0f, y + font_dims[1] + 4.0f);
3163         immUnbindProgram();
3164
3165         UI_FontThemeColor(fontid, TH_TEXT);
3166         BLF_position(fontid, x + 2.0f, y + 2.0f, 0.0f);
3167         BLF_draw(fontid, numstr, sizeof(numstr));
3168 }
3169
3170 void ED_region_cache_draw_cached_segments(const ARegion *ar, const int num_segments, const int *points, const int sfra, const int efra)
3171 {
3172         if (num_segments) {
3173                 uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3174                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3175                 immUniformColor4ub(128, 128, 255, 128);
3176
3177                 for (int a = 0; a < num_segments; a++) {
3178                         float x1 = (float)(points[a * 2] - sfra) / (efra - sfra + 1) * ar->winx;
3179                         float x2 = (float)(points[a * 2 + 1] - sfra + 1) / (efra - sfra + 1) * ar->winx;
3180
3181                         immRecti(pos, x1, 0, x2, 8 * UI_DPI_FAC);
3182                         /* TODO(merwin): use primitive restart to draw multiple rects more efficiently */
3183                 }
3184
3185                 immUnbindProgram();
3186         }
3187 }
3188
3189 /**
3190  * Generate subscriptions for this region.
3191  */
3192 void ED_region_message_subscribe(
3193         bContext *C,
3194         struct WorkSpace *workspace, struct Scene *scene,
3195         struct bScreen *screen, struct ScrArea *sa, struct ARegion *ar,
3196         struct wmMsgBus *mbus)
3197 {
3198         if (ar->gizmo_map != NULL) {
3199                 WM_gizmomap_message_subscribe(C, ar->gizmo_map, ar, mbus);
3200         }
3201
3202         if (!BLI_listbase_is_empty(&ar->uiblocks)) {
3203                 UI_region_message_subscribe(ar, mbus);
3204         }
3205
3206         if (ar->type->message_subscribe != NULL) {
3207                 ar->type->message_subscribe(C, workspace, scene, screen, sa, ar, mbus);
3208         }
3209 }
3210
3211 int ED_region_snap_size_test(const ARegion *ar)
3212 {
3213         /* Use a larger value because toggling scrollbars can jump in size. */
3214         const int snap_match_threshold = 16;
3215         if (ar->type->snap_size != NULL) {
3216                 return ((((ar->sizex - ar->type->snap_size(ar, ar->sizex, 0)) <= snap_match_threshold) << 0) |
3217                         (((ar->sizey - ar->type->snap_size(ar, ar->sizey, 1)) <= snap_match_threshold) << 1));
3218         }
3219         return 0;
3220 }
3221
3222 bool ED_region_snap_size_apply(ARegion *ar, int snap_flag)
3223 {
3224         bool changed = false;
3225         if (ar->type->snap_size != NULL) {
3226                 if (snap_flag & (1 << 0)) {
3227                         short snap_size = ar->type->snap_size(ar, ar->sizex, 0);
3228                         if (snap_size != ar->sizex) {
3229                                 ar->sizex = snap_size;
3230                                 changed = true;
3231                         }
3232                 }
3233                 if (snap_flag & (1 << 1)) {
3234                         short snap_size = ar->type->snap_size(ar, ar->sizey, 1);
3235                         if (snap_size != ar->sizey) {
3236                                 ar->sizey = snap_size;
3237                                 changed = true;
3238                         }
3239                 }
3240         }
3241         return changed;
3242 }