UI: better widget drawing with thick line width.
[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         float coords[4][4] = {
754             /* Bottom-left. */
755             {sa->totrct.xmin - U.pixelsize,
756              sa->totrct.ymin - U.pixelsize,
757              sa->totrct.xmin + AZONESPOTW,
758              sa->totrct.ymin + AZONESPOTH},
759             /* Bottom-right. */
760             {sa->totrct.xmax - AZONESPOTW,
761              sa->totrct.ymin - U.pixelsize,
762              sa->totrct.xmax + U.pixelsize,
763              sa->totrct.ymin + AZONESPOTH},
764             /* Top-left. */
765             {sa->totrct.xmin - U.pixelsize,
766              sa->totrct.ymax - AZONESPOTH,
767              sa->totrct.xmin + AZONESPOTW,
768              sa->totrct.ymax + U.pixelsize},
769             /* Top-right. */
770             {sa->totrct.xmax - AZONESPOTW,
771              sa->totrct.ymax - AZONESPOTH,
772              sa->totrct.xmax + U.pixelsize,
773              sa->totrct.ymax + U.pixelsize}};
774
775         for (int i = 0; i < 4; i++) {
776                 /* can't click on bottom corners on OS X, already used for resizing */
777 #ifdef __APPLE__
778                 if (!WM_window_is_fullscreen(win) &&
779                     ((coords[i][0] == 0 && coords[i][1] == 0) ||
780                      (coords[i][0] == WM_window_pixels_x(win) && coords[i][1] == 0)))
781                 {
782                         continue;
783                 }
784 #else
785                 (void)win;
786 #endif
787
788                 /* set area action zones */
789                 az = (AZone *)MEM_callocN(sizeof(AZone), "actionzone");
790                 BLI_addtail(&(sa->actionzones), az);
791                 az->type = AZONE_AREA;
792                 az->x1 = coords[i][0];
793                 az->y1 = coords[i][1];
794                 az->x2 = coords[i][2];
795                 az->y2 = coords[i][3];
796                 BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
797         }
798 }
799
800 static void fullscreen_azone_initialize(ScrArea *sa, ARegion *ar)
801 {
802         AZone *az;
803
804         if (ED_area_is_global(sa) || (ar->regiontype != RGN_TYPE_WINDOW))
805                 return;
806
807         az = (AZone *)MEM_callocN(sizeof(AZone), "fullscreen action zone");
808         BLI_addtail(&(sa->actionzones), az);
809         az->type = AZONE_FULLSCREEN;
810         az->ar = ar;
811         az->alpha = 0.0f;
812
813         az->x1 = ar->winrct.xmax - (AZONEFADEOUT - 1);
814         az->y1 = ar->winrct.ymax - (AZONEFADEOUT - 1);
815         az->x2 = ar->winrct.xmax;
816         az->y2 = ar->winrct.ymax;
817         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
818 }
819
820 #define AZONEPAD_EDGE   (0.1f * U.widget_unit)
821 #define AZONEPAD_ICON   (0.45f * U.widget_unit)
822 static void region_azone_edge(AZone *az, ARegion *ar)
823 {
824         switch (az->edge) {
825                 case AE_TOP_TO_BOTTOMRIGHT:
826                         az->x1 = ar->winrct.xmin;
827                         az->y1 = ar->winrct.ymax - AZONEPAD_EDGE;
828                         az->x2 = ar->winrct.xmax;
829                         az->y2 = ar->winrct.ymax + AZONEPAD_EDGE;
830                         break;
831                 case AE_BOTTOM_TO_TOPLEFT:
832                         az->x1 = ar->winrct.xmin;
833                         az->y1 = ar->winrct.ymin + AZONEPAD_EDGE;
834                         az->x2 = ar->winrct.xmax;
835                         az->y2 = ar->winrct.ymin - AZONEPAD_EDGE;
836                         break;
837                 case AE_LEFT_TO_TOPRIGHT:
838                         az->x1 = ar->winrct.xmin - AZONEPAD_EDGE;
839                         az->y1 = ar->winrct.ymin;
840                         az->x2 = ar->winrct.xmin + AZONEPAD_EDGE;
841                         az->y2 = ar->winrct.ymax;
842                         break;
843                 case AE_RIGHT_TO_TOPLEFT:
844                         az->x1 = ar->winrct.xmax + AZONEPAD_EDGE;
845                         az->y1 = ar->winrct.ymin;
846                         az->x2 = ar->winrct.xmax - AZONEPAD_EDGE;
847                         az->y2 = ar->winrct.ymax;
848                         break;
849         }
850
851         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
852 }
853
854 /* region already made zero sized, in shape of edge */
855 static void region_azone_tab_plus(ScrArea *sa, AZone *az, ARegion *ar)
856 {
857         AZone *azt;
858         int tot = 0, add;
859         /* Edge offset multiplied by the  */
860
861         float edge_offset = 1.0f;
862         const float tab_size_x = 0.7f * U.widget_unit;
863         const float tab_size_y = 0.4f * U.widget_unit;
864
865
866         for (azt = sa->actionzones.first; azt; azt = azt->next) {
867                 if (azt->edge == az->edge) tot++;
868         }
869
870         switch (az->edge) {
871                 case AE_TOP_TO_BOTTOMRIGHT:
872                         add = (ar->winrct.ymax == sa->totrct.ymin) ? 1 : 0;
873                         az->x1 = ar->winrct.xmax - ((edge_offset + 1.0f) * tab_size_x);
874                         az->y1 = ar->winrct.ymax - add;
875                         az->x2 = ar->winrct.xmax - (edge_offset * tab_size_x);
876                         az->y2 = ar->winrct.ymax - add + tab_size_y;
877                         break;
878                 case AE_BOTTOM_TO_TOPLEFT:
879                         az->x1 = ar->winrct.xmax - ((edge_offset + 1.0f) * tab_size_x);
880                         az->y1 = ar->winrct.ymin - tab_size_y;
881                         az->x2 = ar->winrct.xmax - (edge_offset * tab_size_x);
882                         az->y2 = ar->winrct.ymin;
883                         break;
884                 case AE_LEFT_TO_TOPRIGHT:
885                         az->x1 = ar->winrct.xmin - tab_size_y;
886                         az->y1 = ar->winrct.ymax - ((edge_offset + 1.0f) * tab_size_x);
887                         az->x2 = ar->winrct.xmin;
888                         az->y2 = ar->winrct.ymax - (edge_offset * tab_size_x);
889                         break;
890                 case AE_RIGHT_TO_TOPLEFT:
891                         az->x1 = ar->winrct.xmax;
892                         az->y1 = ar->winrct.ymax - ((edge_offset + 1.0f) * tab_size_x);
893                         az->x2 = ar->winrct.xmax + tab_size_y;
894                         az->y2 = ar->winrct.ymax - (edge_offset * tab_size_x);
895                         break;
896         }
897         /* rect needed for mouse pointer test */
898         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
899 }
900
901 static bool region_azone_edge_poll(const ARegion *ar, const bool is_fullscreen)
902 {
903         const bool is_hidden = (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL));
904
905         if (is_hidden && is_fullscreen) {
906                 return false;
907         }
908         if (!is_hidden && ar->regiontype == RGN_TYPE_HEADER) {
909                 return false;
910         }
911
912         return true;
913 }
914
915 static void region_azone_edge_initialize(ScrArea *sa, ARegion *ar, AZEdge edge, const bool is_fullscreen)
916 {
917         AZone *az = NULL;
918         const bool is_hidden = (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL));
919
920         if (!region_azone_edge_poll(ar, is_fullscreen)) {
921                 return;
922         }
923
924         az = (AZone *)MEM_callocN(sizeof(AZone), "actionzone");
925         BLI_addtail(&(sa->actionzones), az);
926         az->type = AZONE_REGION;
927         az->ar = ar;
928         az->edge = edge;
929
930         if (is_hidden) {
931                 region_azone_tab_plus(sa, az, ar);
932         }
933         else {
934                 region_azone_edge(az, ar);
935         }
936 }
937
938 static void region_azone_scrollbar_initialize(ScrArea *sa, ARegion *ar, AZScrollDirection direction)
939 {
940         rcti scroller_vert = (direction == AZ_SCROLL_VERT) ? ar->v2d.vert : ar->v2d.hor;
941         AZone *az = MEM_callocN(sizeof(*az), __func__);
942
943         BLI_addtail(&sa->actionzones, az);
944         az->type = AZONE_REGION_SCROLL;
945         az->ar = ar;
946         az->direction = direction;
947
948         if (direction == AZ_SCROLL_VERT) {
949                 az->ar->v2d.alpha_vert = 0;
950         }
951         else if (direction == AZ_SCROLL_HOR) {
952                 az->ar->v2d.alpha_hor = 0;
953         }
954
955         BLI_rcti_translate(&scroller_vert, ar->winrct.xmin, ar->winrct.ymin);
956         az->x1 = scroller_vert.xmin - AZONEFADEIN;
957         az->y1 = scroller_vert.ymin - AZONEFADEIN;
958         az->x2 = scroller_vert.xmax + AZONEFADEIN;
959         az->y2 = scroller_vert.ymax + AZONEFADEIN;
960
961         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
962 }
963
964 static void region_azones_scrollbars_initialize(ScrArea *sa, ARegion *ar)
965 {
966         const View2D *v2d = &ar->v2d;
967
968         if ((v2d->scroll & V2D_SCROLL_VERTICAL)   && ((v2d->scroll & V2D_SCROLL_SCALE_VERTICAL)   == 0)) {
969                 region_azone_scrollbar_initialize(sa, ar, AZ_SCROLL_VERT);
970         }
971         if ((v2d->scroll & V2D_SCROLL_HORIZONTAL) && ((v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL) == 0)) {
972                 region_azone_scrollbar_initialize(sa, ar, AZ_SCROLL_HOR);
973         }
974 }
975
976
977 /* *************************************************************** */
978
979 static void region_azones_add(const bScreen *screen, ScrArea *sa, ARegion *ar, const int alignment)
980 {
981         const bool is_fullscreen = screen->state == SCREENFULL;
982
983         /* edge code (t b l r) is along which area edge azone will be drawn */
984
985         if (ar->regiontype == RGN_TYPE_HEADER && ar->winy + 6 > sa->winy) {
986                 /* The logic for this is: when the header takes up the full area,
987                  * disallow hiding it to view the main window.
988                  *
989                  * Without this, you can drag down the file selectors header and hide it
990                  * by accident very easily (highly annoying!), the value 6 is arbitrary
991                  * but accounts for small common rounding problems when scaling the UI,
992                  * must be minimum '4' */
993         }
994         else if (alignment == RGN_ALIGN_TOP)
995                 region_azone_edge_initialize(sa, ar, AE_BOTTOM_TO_TOPLEFT, is_fullscreen);
996         else if (alignment == RGN_ALIGN_BOTTOM)
997                 region_azone_edge_initialize(sa, ar, AE_TOP_TO_BOTTOMRIGHT, is_fullscreen);
998         else if (alignment == RGN_ALIGN_RIGHT)
999                 region_azone_edge_initialize(sa, ar, AE_LEFT_TO_TOPRIGHT, is_fullscreen);
1000         else if (alignment == RGN_ALIGN_LEFT)
1001                 region_azone_edge_initialize(sa, ar, AE_RIGHT_TO_TOPLEFT, is_fullscreen);
1002
1003         if (is_fullscreen) {
1004                 fullscreen_azone_initialize(sa, ar);
1005         }
1006
1007         region_azones_scrollbars_initialize(sa, ar);
1008 }
1009
1010 /* dir is direction to check, not the splitting edge direction! */
1011 static int rct_fits(const rcti *rect, char dir, int size)
1012 {
1013         if (dir == 'h') {
1014                 return BLI_rcti_size_x(rect) + 1 - size;
1015         }
1016         else {  /* 'v' */
1017                 return BLI_rcti_size_y(rect) + 1 - size;
1018         }
1019 }
1020
1021 /* *************************************************************** */
1022
1023 /* ar should be overlapping */
1024 /* function checks if some overlapping region was defined before - on same place */
1025 static void region_overlap_fix(ScrArea *sa, ARegion *ar)
1026 {
1027         ARegion *ar1;
1028         const int align = ar->alignment & ~RGN_SPLIT_PREV;
1029         int align1 = 0;
1030
1031         /* find overlapping previous region on same place */
1032         for (ar1 = ar->prev; ar1; ar1 = ar1->prev) {
1033                 if (ar1->flag & (RGN_FLAG_HIDDEN)) {
1034                         continue;
1035                 }
1036
1037                 if (ar1->overlap && ((ar1->alignment & RGN_SPLIT_PREV) == 0)) {
1038                         if (ELEM(ar1->alignment, RGN_ALIGN_FLOAT)) {
1039                                 continue;
1040                         }
1041                         align1 = ar1->alignment;
1042                         if (BLI_rcti_isect(&ar1->winrct, &ar->winrct, NULL)) {
1043                                 if (align1 != align) {
1044                                         /* Left overlapping right or vice-versa, forbid this! */
1045                                         ar->flag |= RGN_FLAG_TOO_SMALL;
1046                                         return;
1047                                 }
1048                                 /* Else, we have our previous region on same side. */
1049                                 break;
1050                         }
1051                 }
1052         }
1053
1054         /* translate or close */
1055         if (ar1) {
1056                 if (align1 == RGN_ALIGN_LEFT) {
1057                         if (ar->winrct.xmax + ar1->winx > sa->winx - U.widget_unit) {
1058                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1059                                 return;
1060                         }
1061                         else {
1062                                 BLI_rcti_translate(&ar->winrct, ar1->winx, 0);
1063                         }
1064                 }
1065                 else if (align1 == RGN_ALIGN_RIGHT) {
1066                         if (ar->winrct.xmin - ar1->winx < U.widget_unit) {
1067                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1068                                 return;
1069                         }
1070                         else {
1071                                 BLI_rcti_translate(&ar->winrct, -ar1->winx, 0);
1072                         }
1073                 }
1074         }
1075
1076         /* At this point, 'ar' is in its final position and still open.
1077          * Make a final check it does not overlap any previous 'other side' region. */
1078         for (ar1 = ar->prev; ar1; ar1 = ar1->prev) {
1079                 if (ar1->flag & (RGN_FLAG_HIDDEN)) {
1080                         continue;
1081                 }
1082                 if (ELEM(ar1->alignment, RGN_ALIGN_FLOAT)) {
1083                         continue;
1084                 }
1085
1086                 if (ar1->overlap && (ar1->alignment & RGN_SPLIT_PREV) == 0) {
1087                         if ((ar1->alignment != align) && BLI_rcti_isect(&ar1->winrct, &ar->winrct, NULL)) {
1088                                 /* Left overlapping right or vice-versa, forbid this! */
1089                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1090                                 return;
1091                         }
1092                 }
1093         }
1094 }
1095
1096 /* overlapping regions only in the following restricted cases */
1097 bool ED_region_is_overlap(int spacetype, int regiontype)
1098 {
1099         if (regiontype == RGN_TYPE_HUD) {
1100                 return true;
1101         }
1102         if (U.uiflag2 & USER_REGION_OVERLAP) {
1103                 if (spacetype == SPACE_NODE) {
1104                         if (regiontype == RGN_TYPE_TOOLS) {
1105                                 return true;
1106                         }
1107                 }
1108                 else if (ELEM(spacetype, SPACE_VIEW3D, SPACE_SEQ, SPACE_IMAGE)) {
1109                         if (ELEM(regiontype, RGN_TYPE_TOOLS, RGN_TYPE_UI, RGN_TYPE_TOOL_PROPS)) {
1110                                 return true;
1111                         }
1112
1113                         if (ELEM(spacetype, SPACE_VIEW3D, SPACE_IMAGE)) {
1114                                 if (regiontype == RGN_TYPE_HEADER) {
1115                                         return true;
1116                                 }
1117                         }
1118                 }
1119         }
1120
1121         return false;
1122 }
1123
1124 static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, rcti *overlap_remainder, int quad)
1125 {
1126         rcti *remainder_prev = remainder;
1127
1128         if (ar == NULL)
1129                 return;
1130
1131         int prev_winx = ar->winx;
1132         int prev_winy = ar->winy;
1133
1134         /* no returns in function, winrct gets set in the end again */
1135         BLI_rcti_init(&ar->winrct, 0, 0, 0, 0);
1136
1137         /* for test; allow split of previously defined region */
1138         if (ar->alignment & RGN_SPLIT_PREV)
1139                 if (ar->prev)
1140                         remainder = &ar->prev->winrct;
1141
1142         int alignment = ar->alignment & ~RGN_SPLIT_PREV;
1143
1144         /* set here, assuming userpref switching forces to call this again */
1145         ar->overlap = ED_region_is_overlap(sa->spacetype, ar->regiontype);
1146
1147         /* clear state flags first */
1148         ar->flag &= ~RGN_FLAG_TOO_SMALL;
1149         /* user errors */
1150         if ((ar->next == NULL) && !ELEM(alignment, RGN_ALIGN_QSPLIT, RGN_ALIGN_FLOAT)) {
1151                 alignment = RGN_ALIGN_NONE;
1152         }
1153
1154         /* prefsize, taking into account DPI */
1155         int prefsizex = UI_DPI_FAC * ((ar->sizex > 1) ? ar->sizex + 0.5f : ar->type->prefsizex);
1156         int prefsizey;
1157
1158         if (ar->flag & RGN_FLAG_PREFSIZE_OR_HIDDEN) {
1159                 prefsizex = UI_DPI_FAC * ar->type->prefsizex;
1160                 prefsizey = UI_DPI_FAC * ar->type->prefsizey;
1161         }
1162         else if (ar->regiontype == RGN_TYPE_HEADER) {
1163                 prefsizey = ED_area_headersize();
1164         }
1165         else if (ED_area_is_global(sa)) {
1166                 prefsizey = ED_region_global_size_y();
1167         }
1168         else if (ar->regiontype == RGN_TYPE_UI && sa->spacetype == SPACE_FILE) {
1169                 prefsizey = UI_UNIT_Y * 2 + (UI_UNIT_Y / 2);
1170         }
1171         else {
1172                 prefsizey = UI_DPI_FAC * (ar->sizey > 1 ? ar->sizey + 0.5f : ar->type->prefsizey);
1173         }
1174
1175
1176         if (ar->flag & RGN_FLAG_HIDDEN) {
1177                 /* hidden is user flag */
1178         }
1179         else if (alignment == RGN_ALIGN_FLOAT) {
1180                 /**
1181                  * \note Currently this window type is only used for #RGN_TYPE_HUD,
1182                  * We expect the panel to resize it's self to be larger.
1183                  *
1184                  * This aligns to the lower left of the area.
1185                  */
1186                 const int size_min[2] = {UI_UNIT_X, UI_UNIT_Y};
1187                 rcti overlap_remainder_margin = *overlap_remainder;
1188                 BLI_rcti_resize(
1189                         &overlap_remainder_margin,
1190                         max_ii(0, BLI_rcti_size_x(overlap_remainder) - UI_UNIT_X / 2),
1191                         max_ii(0, BLI_rcti_size_y(overlap_remainder) - UI_UNIT_Y / 2));
1192                 ar->winrct.xmin = overlap_remainder_margin.xmin;
1193                 ar->winrct.ymin = overlap_remainder_margin.ymin;
1194                 ar->winrct.xmax = ar->winrct.xmin + prefsizex - 1;
1195                 ar->winrct.ymax = ar->winrct.ymin + prefsizey - 1;
1196
1197                 BLI_rcti_isect(&ar->winrct, &overlap_remainder_margin, &ar->winrct);
1198
1199                 /* We need to use a test that wont have been previously clamped. */
1200                 rcti winrct_test = {
1201                         .xmin = ar->winrct.xmin,
1202                         .ymin = ar->winrct.ymin,
1203                         .xmax = ar->winrct.xmin + size_min[0],
1204                         .ymax = ar->winrct.ymin + size_min[1],
1205                 };
1206                 BLI_rcti_isect(&winrct_test, &overlap_remainder_margin, &winrct_test);
1207                 if (BLI_rcti_size_x(&winrct_test) < size_min[0] ||
1208                     BLI_rcti_size_y(&winrct_test) < size_min[1])
1209                 {
1210                         ar->flag |= RGN_FLAG_TOO_SMALL;
1211                 }
1212         }
1213         else if (rct_fits(remainder, 'v', 1) < 0 || rct_fits(remainder, 'h', 1) < 0) {
1214                 /* remainder is too small for any usage */
1215                 ar->flag |= RGN_FLAG_TOO_SMALL;
1216         }
1217         else if (alignment == RGN_ALIGN_NONE) {
1218                 /* typically last region */
1219                 ar->winrct = *remainder;
1220                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1221         }
1222         else if (alignment == RGN_ALIGN_TOP || alignment == RGN_ALIGN_BOTTOM) {
1223                 rcti *winrct = (ar->overlap) ? overlap_remainder : remainder;
1224
1225                 if (rct_fits(winrct, 'v', prefsizey) < 0) {
1226                         ar->flag |= RGN_FLAG_TOO_SMALL;
1227                 }
1228                 else {
1229                         int fac = rct_fits(winrct, 'v', prefsizey);
1230
1231                         if (fac < 0)
1232                                 prefsizey += fac;
1233
1234                         ar->winrct = *winrct;
1235
1236                         if (alignment == RGN_ALIGN_TOP) {
1237                                 ar->winrct.ymin = ar->winrct.ymax - prefsizey + 1;
1238                                 winrct->ymax = ar->winrct.ymin - 1;
1239                         }
1240                         else {
1241                                 ar->winrct.ymax = ar->winrct.ymin + prefsizey - 1;
1242                                 winrct->ymin = ar->winrct.ymax + 1;
1243                         }
1244                 }
1245         }
1246         else if (ELEM(alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
1247                 rcti *winrct = (ar->overlap) ? overlap_remainder : remainder;
1248
1249                 if (rct_fits(winrct, 'h', prefsizex) < 0) {
1250                         ar->flag |= RGN_FLAG_TOO_SMALL;
1251                 }
1252                 else {
1253                         int fac = rct_fits(winrct, 'h', prefsizex);
1254
1255                         if (fac < 0)
1256                                 prefsizex += fac;
1257
1258                         ar->winrct = *winrct;
1259
1260                         if (alignment == RGN_ALIGN_RIGHT) {
1261                                 ar->winrct.xmin = ar->winrct.xmax - prefsizex + 1;
1262                                 winrct->xmax = ar->winrct.xmin - 1;
1263                         }
1264                         else {
1265                                 ar->winrct.xmax = ar->winrct.xmin + prefsizex - 1;
1266                                 winrct->xmin = ar->winrct.xmax + 1;
1267                         }
1268                 }
1269         }
1270         else if (alignment == RGN_ALIGN_VSPLIT || alignment == RGN_ALIGN_HSPLIT) {
1271                 /* percentage subdiv*/
1272                 ar->winrct = *remainder;
1273
1274                 if (alignment == RGN_ALIGN_HSPLIT) {
1275                         if (rct_fits(remainder, 'h', prefsizex) > 4) {
1276                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1277                                 remainder->xmin = ar->winrct.xmax + 1;
1278                         }
1279                         else {
1280                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1281                         }
1282                 }
1283                 else {
1284                         if (rct_fits(remainder, 'v', prefsizey) > 4) {
1285                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1286                                 remainder->ymin = ar->winrct.ymax + 1;
1287                         }
1288                         else {
1289                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1290                         }
1291                 }
1292         }
1293         else if (alignment == RGN_ALIGN_QSPLIT) {
1294                 ar->winrct = *remainder;
1295
1296                 /* test if there's still 4 regions left */
1297                 if (quad == 0) {
1298                         ARegion *artest = ar->next;
1299                         int count = 1;
1300
1301                         while (artest) {
1302                                 artest->alignment = RGN_ALIGN_QSPLIT;
1303                                 artest = artest->next;
1304                                 count++;
1305                         }
1306
1307                         if (count != 4) {
1308                                 /* let's stop adding regions */
1309                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1310                                 if (G.debug & G_DEBUG)
1311                                         printf("region quadsplit failed\n");
1312                         }
1313                         else {
1314                                 quad = 1;
1315                         }
1316                 }
1317                 if (quad) {
1318                         if (quad == 1) { /* left bottom */
1319                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1320                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1321                         }
1322                         else if (quad == 2) { /* left top */
1323                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1324                                 ar->winrct.ymin = BLI_rcti_cent_y(remainder) + 1;
1325                         }
1326                         else if (quad == 3) { /* right bottom */
1327                                 ar->winrct.xmin = BLI_rcti_cent_x(remainder) + 1;
1328                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1329                         }
1330                         else {  /* right top */
1331                                 ar->winrct.xmin = BLI_rcti_cent_x(remainder) + 1;
1332                                 ar->winrct.ymin = BLI_rcti_cent_y(remainder) + 1;
1333                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1334                         }
1335
1336                         quad++;
1337                 }
1338         }
1339
1340         /* for speedup */
1341         ar->winx = BLI_rcti_size_x(&ar->winrct) + 1;
1342         ar->winy = BLI_rcti_size_y(&ar->winrct) + 1;
1343
1344         /* if region opened normally, we store this for hide/reveal usage */
1345         /* prevent rounding errors for UI_DPI_FAC mult and divide */
1346         if (ar->winx > 1) ar->sizex = (ar->winx + 0.5f) /  UI_DPI_FAC;
1347         if (ar->winy > 1) ar->sizey = (ar->winy + 0.5f) /  UI_DPI_FAC;
1348
1349         /* exception for multiple overlapping regions on same spot */
1350         if (ar->overlap && (alignment != RGN_ALIGN_FLOAT)) {
1351                 region_overlap_fix(sa, ar);
1352         }
1353
1354         /* set winrect for azones */
1355         if (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) {
1356                 ar->winrct = (ar->overlap) ? *overlap_remainder : *remainder;
1357
1358                 switch (alignment) {
1359                         case RGN_ALIGN_TOP:
1360                                 ar->winrct.ymin = ar->winrct.ymax;
1361                                 break;
1362                         case RGN_ALIGN_BOTTOM:
1363                                 ar->winrct.ymax = ar->winrct.ymin;
1364                                 break;
1365                         case RGN_ALIGN_RIGHT:
1366                                 ar->winrct.xmin = ar->winrct.xmax;
1367                                 break;
1368                         case RGN_ALIGN_LEFT:
1369                         default:
1370                                 /* prevent winrct to be valid */
1371                                 ar->winrct.xmax = ar->winrct.xmin;
1372                                 break;
1373                 }
1374         }
1375
1376         /* restore prev-split exception */
1377         if (ar->alignment & RGN_SPLIT_PREV) {
1378                 if (ar->prev) {
1379                         remainder = remainder_prev;
1380                         ar->prev->winx = BLI_rcti_size_x(&ar->prev->winrct) + 1;
1381                         ar->prev->winy = BLI_rcti_size_y(&ar->prev->winrct) + 1;
1382                 }
1383         }
1384
1385         /* After non-overlapping region, all following overlapping regions
1386          * fit within the remaining space again. */
1387         if (!ar->overlap) {
1388                 *overlap_remainder = *remainder;
1389         }
1390
1391         region_rect_recursive(sa, ar->next, remainder, overlap_remainder, quad);
1392
1393         /* Tag for redraw if size changes. */
1394         if (ar->winx != prev_winx || ar->winy != prev_winy) {
1395                 ED_region_tag_redraw(ar);
1396         }
1397 }
1398
1399 static void area_calc_totrct(ScrArea *sa, const rcti *window_rect)
1400 {
1401         short px = (short)U.pixelsize;
1402
1403         sa->totrct.xmin = sa->v1->vec.x;
1404         sa->totrct.xmax = sa->v4->vec.x;
1405         sa->totrct.ymin = sa->v1->vec.y;
1406         sa->totrct.ymax = sa->v2->vec.y;
1407
1408         /* scale down totrct by 1 pixel on all sides not matching window borders */
1409         if (sa->totrct.xmin > window_rect->xmin) {
1410                 sa->totrct.xmin += px;
1411         }
1412         if (sa->totrct.xmax < (window_rect->xmax - 1)) {
1413                 sa->totrct.xmax -= px;
1414         }
1415         if (sa->totrct.ymin > window_rect->ymin) {
1416                 sa->totrct.ymin += px;
1417         }
1418         if (sa->totrct.ymax < (window_rect->ymax - 1)) {
1419                 sa->totrct.ymax -= px;
1420         }
1421         /* Although the following asserts are correct they lead to a very unstable Blender.
1422          * And the asserts would fail even in 2.7x (they were added in 2.8x as part of the top-bar commit).
1423          * For more details see T54864. */
1424 #if 0
1425         BLI_assert(sa->totrct.xmin >= 0);
1426         BLI_assert(sa->totrct.xmax >= 0);
1427         BLI_assert(sa->totrct.ymin >= 0);
1428         BLI_assert(sa->totrct.ymax >= 0);
1429 #endif
1430
1431         /* for speedup */
1432         sa->winx = BLI_rcti_size_x(&sa->totrct) + 1;
1433         sa->winy = BLI_rcti_size_y(&sa->totrct) + 1;
1434 }
1435
1436
1437 /* used for area initialize below */
1438 static void region_subwindow(ARegion *ar)
1439 {
1440         bool hidden = (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) != 0;
1441
1442         if ((ar->alignment & RGN_SPLIT_PREV) && ar->prev)
1443                 hidden = hidden || (ar->prev->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL));
1444
1445         ar->visible = !hidden;
1446 }
1447
1448 /**
1449  * \param ar: Region, may be NULL when adding handlers for \a sa.
1450  */
1451 static void ed_default_handlers(wmWindowManager *wm, ScrArea *sa, ARegion *ar, ListBase *handlers, int flag)
1452 {
1453         BLI_assert(ar ? (&ar->handlers == handlers) : (&sa->handlers == handlers));
1454
1455         /* note, add-handler checks if it already exists */
1456
1457         /* XXX it would be good to have boundbox checks for some of these... */
1458         if (flag & ED_KEYMAP_UI) {
1459                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "User Interface", 0, 0);
1460                 WM_event_add_keymap_handler(handlers, keymap);
1461
1462                 /* user interface widgets */
1463                 UI_region_handlers_add(handlers);
1464         }
1465         if (flag & ED_KEYMAP_GIZMO) {
1466                 BLI_assert(ar && ar->type->regionid == RGN_TYPE_WINDOW);
1467                 if (ar) {
1468                         /* Anything else is confusing, only allow this. */
1469                         BLI_assert(&ar->handlers == handlers);
1470                         if (ar->gizmo_map == NULL) {
1471                                 ar->gizmo_map = WM_gizmomap_new_from_type(
1472                                         &(const struct wmGizmoMapType_Params){sa->spacetype, ar->type->regionid});
1473                         }
1474                         WM_gizmomap_add_handlers(ar, ar->gizmo_map);
1475                 }
1476         }
1477         if (flag & ED_KEYMAP_TOOL) {
1478                 WM_event_add_keymap_handler_dynamic(&ar->handlers, WM_event_get_keymap_from_toolsystem, sa);
1479         }
1480         if (flag & ED_KEYMAP_VIEW2D) {
1481                 /* 2d-viewport handling+manipulation */
1482                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "View2D", 0, 0);
1483                 WM_event_add_keymap_handler(handlers, keymap);
1484         }
1485         if (flag & ED_KEYMAP_MARKERS) {
1486                 /* time-markers */
1487                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Markers", 0, 0);
1488
1489                 /* use a boundbox restricted map */
1490                 /* same local check for all areas */
1491                 static rcti rect = {0, 10000, 0, -1};
1492                 rect.ymax = UI_MARKER_MARGIN_Y;
1493                 BLI_assert(ar->type->regionid == RGN_TYPE_WINDOW);
1494                 WM_event_add_keymap_handler_bb(handlers, keymap, &rect, &ar->winrct);
1495         }
1496         if (flag & ED_KEYMAP_ANIMATION) {
1497                 /* frame changing and timeline operators (for time spaces) */
1498                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Animation", 0, 0);
1499                 WM_event_add_keymap_handler(handlers, keymap);
1500         }
1501         if (flag & ED_KEYMAP_FRAMES) {
1502                 /* frame changing/jumping (for all spaces) */
1503                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Frames", 0, 0);
1504                 WM_event_add_keymap_handler(handlers, keymap);
1505         }
1506         if (flag & ED_KEYMAP_HEADER) {
1507                 /* standard keymap for headers regions */
1508                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Header", 0, 0);
1509                 WM_event_add_keymap_handler(handlers, keymap);
1510         }
1511
1512         /* Keep last because of LMB/RMB handling, see: T57527. */
1513         if (flag & ED_KEYMAP_GPENCIL) {
1514                 /* grease pencil */
1515                 /* NOTE: This is now 4 keymaps - One for basic functionality,
1516                  *       and others for special stroke modes (edit, paint and sculpt).
1517                  *
1518                  *       For now, it's easier to just include all,
1519                  *       since you hardly want one without the others.
1520                  */
1521                 wmKeyMap *keymap_general = WM_keymap_ensure(wm->defaultconf, "Grease Pencil", 0, 0);
1522                 WM_event_add_keymap_handler(handlers, keymap_general);
1523
1524                 wmKeyMap *keymap_edit = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Edit Mode", 0, 0);
1525                 WM_event_add_keymap_handler(handlers, keymap_edit);
1526
1527                 wmKeyMap *keymap_paint = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint Mode", 0, 0);
1528                 WM_event_add_keymap_handler(handlers, keymap_paint);
1529
1530                 wmKeyMap *keymap_paint_draw = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Draw brush)", 0, 0);
1531                 WM_event_add_keymap_handler(handlers, keymap_paint_draw);
1532
1533                 wmKeyMap *keymap_paint_erase = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Erase)", 0, 0);
1534                 WM_event_add_keymap_handler(handlers, keymap_paint_erase);
1535
1536                 wmKeyMap *keymap_paint_fill = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Fill)", 0, 0);
1537                 WM_event_add_keymap_handler(handlers, keymap_paint_fill);
1538
1539                 wmKeyMap *keymap_sculpt = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Sculpt Mode", 0, 0);
1540                 WM_event_add_keymap_handler(handlers, keymap_sculpt);
1541         }
1542 }
1543
1544 void ED_area_update_region_sizes(wmWindowManager *wm, wmWindow *win, ScrArea *area)
1545 {
1546         rcti rect, overlap_rect;
1547         rcti window_rect;
1548
1549         if (!(area->flag & AREA_FLAG_REGION_SIZE_UPDATE)) {
1550                 return;
1551         }
1552         const bScreen *screen = WM_window_get_active_screen(win);
1553
1554         WM_window_rect_calc(win, &window_rect);
1555         area_calc_totrct(area, &window_rect);
1556
1557         /* region rect sizes */
1558         rect = area->totrct;
1559         overlap_rect = rect;
1560         region_rect_recursive(area, area->regionbase.first, &rect, &overlap_rect, 0);
1561
1562         /* Dynamically sized regions may have changed region sizes, so we have to force azone update. */
1563         area_azone_initialize(win, screen, area);
1564
1565         for (ARegion *ar = area->regionbase.first; ar; ar = ar->next) {
1566                 region_subwindow(ar);
1567
1568                 /* region size may have changed, init does necessary adjustments */
1569                 if (ar->type->init) {
1570                         ar->type->init(wm, ar);
1571                 }
1572
1573                 /* Some AZones use View2D data which is only updated in region init, so call that first! */
1574                 region_azones_add(screen, area, ar, ar->alignment & ~RGN_SPLIT_PREV);
1575         }
1576         ED_area_azones_update(area, &win->eventstate->x);
1577
1578         area->flag &= ~AREA_FLAG_REGION_SIZE_UPDATE;
1579 }
1580
1581 /* called in screen_refresh, or screens_init, also area size changes */
1582 void ED_area_initialize(wmWindowManager *wm, wmWindow *win, ScrArea *sa)
1583 {
1584         WorkSpace *workspace = WM_window_get_active_workspace(win);
1585         const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);
1586         ViewLayer *view_layer = WM_window_get_active_view_layer(win);
1587         ARegion *ar;
1588         rcti rect, overlap_rect;
1589         rcti window_rect;
1590
1591         if (ED_area_is_global(sa) && (sa->global->flag & GLOBAL_AREA_IS_HIDDEN)) {
1592                 return;
1593         }
1594         WM_window_rect_calc(win, &window_rect);
1595
1596         /* set typedefinitions */
1597         sa->type = BKE_spacetype_from_id(sa->spacetype);
1598
1599         if (sa->type == NULL) {
1600                 sa->spacetype = SPACE_VIEW3D;
1601                 sa->type = BKE_spacetype_from_id(sa->spacetype);
1602         }
1603
1604         for (ar = sa->regionbase.first; ar; ar = ar->next)
1605                 ar->type = BKE_regiontype_from_id_or_first(sa->type, ar->regiontype);
1606
1607         /* area sizes */
1608         area_calc_totrct(sa, &window_rect);
1609
1610         /* region rect sizes */
1611         rect = sa->totrct;
1612         overlap_rect = rect;
1613         region_rect_recursive(sa, sa->regionbase.first, &rect, &overlap_rect, 0);
1614         sa->flag &= ~AREA_FLAG_REGION_SIZE_UPDATE;
1615
1616         /* default area handlers */
1617         ed_default_handlers(wm, sa, NULL, &sa->handlers, sa->type->keymapflag);
1618         /* checks spacedata, adds own handlers */
1619         if (sa->type->init)
1620                 sa->type->init(wm, sa);
1621
1622         /* clear all azones, add the area triangle widgets */
1623         area_azone_initialize(win, screen, sa);
1624
1625         /* region windows, default and own handlers */
1626         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1627                 region_subwindow(ar);
1628
1629                 if (ar->visible) {
1630                         /* default region handlers */
1631                         ed_default_handlers(wm, sa, ar, &ar->handlers, ar->type->keymapflag);
1632                         /* own handlers */
1633                         if (ar->type->init) {
1634                                 ar->type->init(wm, ar);
1635                         }
1636                 }
1637                 else {
1638                         /* prevent uiblocks to run */
1639                         UI_blocklist_free(NULL, &ar->uiblocks);
1640                 }
1641
1642                 /* Some AZones use View2D data which is only updated in region init, so call that first! */
1643                 region_azones_add(screen, sa, ar, ar->alignment & ~RGN_SPLIT_PREV);
1644         }
1645
1646
1647         /* Avoid re-initializing tools while resizing the window. */
1648         if ((G.moving & G_TRANSFORM_WM) == 0) {
1649                 if ((1 << sa->spacetype) & WM_TOOLSYSTEM_SPACE_MASK) {
1650                         WM_toolsystem_refresh_screen_area(workspace, view_layer, sa);
1651                         sa->flag |= AREA_FLAG_ACTIVE_TOOL_UPDATE;
1652                 }
1653                 else {
1654                         sa->runtime.tool = NULL;
1655                         sa->runtime.is_tool_set = true;
1656                 }
1657         }
1658 }
1659
1660 static void region_update_rect(ARegion *ar)
1661 {
1662         ar->winx = BLI_rcti_size_x(&ar->winrct) + 1;
1663         ar->winy = BLI_rcti_size_y(&ar->winrct) + 1;
1664
1665         /* v2d mask is used to subtract scrollbars from a 2d view. Needs initialize here. */
1666         BLI_rcti_init(&ar->v2d.mask, 0, ar->winx - 1, 0, ar->winy -1);
1667 }
1668
1669 /**
1670  * Call to move a popup window (keep OpenGL context free!)
1671  */
1672 void ED_region_update_rect(ARegion *ar)
1673 {
1674         region_update_rect(ar);
1675 }
1676
1677 /* externally called for floating regions like menus */
1678 void ED_region_init(ARegion *ar)
1679 {
1680         /* refresh can be called before window opened */
1681         region_subwindow(ar);
1682
1683         region_update_rect(ar);
1684 }
1685
1686 void ED_region_cursor_set(wmWindow *win, ScrArea *sa, ARegion *ar)
1687 {
1688         if (ar && sa && ar->type && ar->type->cursor) {
1689                 ar->type->cursor(win, sa, ar);
1690         }
1691         else {
1692                 if (WM_cursor_set_from_tool(win, sa, ar)) {
1693                         return;
1694                 }
1695                 WM_cursor_set(win, CURSOR_STD);
1696         }
1697 }
1698
1699 /* for use after changing visibility of regions */
1700 void ED_region_visibility_change_update(bContext *C, ARegion *ar)
1701 {
1702         ScrArea *sa = CTX_wm_area(C);
1703
1704         if (ar->flag & RGN_FLAG_HIDDEN)
1705                 WM_event_remove_handlers(C, &ar->handlers);
1706
1707         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa);
1708         ED_area_tag_redraw(sa);
1709 }
1710
1711 /* for quick toggle, can skip fades */
1712 void region_toggle_hidden(bContext *C, ARegion *ar, const bool do_fade)
1713 {
1714         ScrArea *sa = CTX_wm_area(C);
1715
1716         ar->flag ^= RGN_FLAG_HIDDEN;
1717
1718         if (do_fade && ar->overlap) {
1719                 /* starts a timer, and in end calls the stuff below itself (region_sblend_invoke()) */
1720                 region_blend_start(C, sa, ar);
1721         }
1722         else {
1723                 ED_region_visibility_change_update(C, ar);
1724         }
1725 }
1726
1727 /* exported to all editors, uses fading default */
1728 void ED_region_toggle_hidden(bContext *C, ARegion *ar)
1729 {
1730         region_toggle_hidden(C, ar, true);
1731 }
1732
1733 /**
1734  * we swap spaces for fullscreen to keep all allocated data area vertices were set
1735  */
1736 void ED_area_data_copy(ScrArea *sa_dst, ScrArea *sa_src, const bool do_free)
1737 {
1738         SpaceType *st;
1739         ARegion *ar;
1740         const char spacetype = sa_dst->spacetype;
1741         const short flag_copy = HEADER_NO_PULLDOWN;
1742
1743         sa_dst->spacetype = sa_src->spacetype;
1744         sa_dst->type = sa_src->type;
1745
1746         sa_dst->flag = (sa_dst->flag & ~flag_copy) | (sa_src->flag & flag_copy);
1747
1748         /* area */
1749         if (do_free) {
1750                 BKE_spacedata_freelist(&sa_dst->spacedata);
1751         }
1752         BKE_spacedata_copylist(&sa_dst->spacedata, &sa_src->spacedata);
1753
1754         /* Note; SPACE_EMPTY is possible on new screens */
1755
1756         /* regions */
1757         if (do_free) {
1758                 st = BKE_spacetype_from_id(spacetype);
1759                 for (ar = sa_dst->regionbase.first; ar; ar = ar->next)
1760                         BKE_area_region_free(st, ar);
1761                 BLI_freelistN(&sa_dst->regionbase);
1762         }
1763         st = BKE_spacetype_from_id(sa_src->spacetype);
1764         for (ar = sa_src->regionbase.first; ar; ar = ar->next) {
1765                 ARegion *newar = BKE_area_region_copy(st, ar);
1766                 BLI_addtail(&sa_dst->regionbase, newar);
1767         }
1768 }
1769
1770 void ED_area_data_swap(ScrArea *sa_dst, ScrArea *sa_src)
1771 {
1772         SWAP(char, sa_dst->spacetype, sa_src->spacetype);
1773         SWAP(SpaceType *, sa_dst->type, sa_src->type);
1774
1775
1776         SWAP(ListBase, sa_dst->spacedata, sa_src->spacedata);
1777         SWAP(ListBase, sa_dst->regionbase, sa_src->regionbase);
1778 }
1779
1780 /* *********** Space switching code *********** */
1781
1782 void ED_area_swapspace(bContext *C, ScrArea *sa1, ScrArea *sa2)
1783 {
1784         ScrArea *tmp = MEM_callocN(sizeof(ScrArea), "addscrarea");
1785
1786         ED_area_exit(C, sa1);
1787         ED_area_exit(C, sa2);
1788
1789         ED_area_data_copy(tmp, sa1, false);
1790         ED_area_data_copy(sa1, sa2, true);
1791         ED_area_data_copy(sa2, tmp, true);
1792         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa1);
1793         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa2);
1794
1795         BKE_screen_area_free(tmp);
1796         MEM_freeN(tmp);
1797
1798         /* tell WM to refresh, cursor types etc */
1799         WM_event_add_mousemove(C);
1800
1801         ED_area_tag_redraw(sa1);
1802         ED_area_tag_refresh(sa1);
1803         ED_area_tag_redraw(sa2);
1804         ED_area_tag_refresh(sa2);
1805 }
1806
1807 /**
1808  * \param skip_ar_exit: Skip calling area exit callback. Set for opening temp spaces.
1809  */
1810 void ED_area_newspace(bContext *C, ScrArea *sa, int type, const bool skip_ar_exit)
1811 {
1812         wmWindow *win = CTX_wm_window(C);
1813
1814         if (sa->spacetype != type) {
1815                 SpaceType *st;
1816                 SpaceLink *slold;
1817                 SpaceLink *sl;
1818                 /* store sa->type->exit callback */
1819                 void *sa_exit = sa->type ? sa->type->exit : NULL;
1820                 /* When the user switches between space-types from the type-selector,
1821                  * changing the header-type is jarring (especially when using Ctrl-MouseWheel).
1822                  *
1823                  * However, add-on install for example, forces the header to the top which shouldn't
1824                  * be applied back to the previous space type when closing - see: T57724
1825                  *
1826                  * Newly created windows wont have any space data, use the alignment
1827                  * the space type defaults to in this case instead
1828                  * (needed for preferences to have space-type on bottom).
1829                  */
1830                 int header_alignment = ED_area_header_alignment_or_fallback(sa, -1);
1831                 const bool sync_header_alignment = (
1832                         (header_alignment != -1) &&
1833                         (sa->flag & AREA_FLAG_TEMP_TYPE) == 0);
1834
1835                 /* in some cases (opening temp space) we don't want to
1836                  * call area exit callback, so we temporarily unset it */
1837                 if (skip_ar_exit && sa->type) {
1838                         sa->type->exit = NULL;
1839                 }
1840
1841                 ED_area_exit(C, sa);
1842
1843                 /* restore old area exit callback */
1844                 if (skip_ar_exit && sa->type) {
1845                         sa->type->exit = sa_exit;
1846                 }
1847
1848                 st = BKE_spacetype_from_id(type);
1849                 slold = sa->spacedata.first;
1850
1851                 sa->spacetype = type;
1852                 sa->type = st;
1853
1854                 /* If st->new may be called, don't use context until then. The
1855                  * sa->type->context() callback has changed but data may be invalid
1856                  * (e.g. with properties editor) until space-data is properly created */
1857
1858                 /* check previously stored space */
1859                 for (sl = sa->spacedata.first; sl; sl = sl->next)
1860                         if (sl->spacetype == type)
1861                                 break;
1862
1863                 /* old spacedata... happened during work on 2.50, remove */
1864                 if (sl && BLI_listbase_is_empty(&sl->regionbase)) {
1865                         st->free(sl);
1866                         BLI_freelinkN(&sa->spacedata, sl);
1867                         if (slold == sl) {
1868                                 slold = NULL;
1869                         }
1870                         sl = NULL;
1871                 }
1872
1873                 if (sl) {
1874                         /* swap regions */
1875                         slold->regionbase = sa->regionbase;
1876                         sa->regionbase = sl->regionbase;
1877                         BLI_listbase_clear(&sl->regionbase);
1878
1879                         /* put in front of list */
1880                         BLI_remlink(&sa->spacedata, sl);
1881                         BLI_addhead(&sa->spacedata, sl);
1882                 }
1883                 else {
1884                         /* new space */
1885                         if (st) {
1886                                 /* Don't get scene from context here which may depend on space-data. */
1887                                 Scene *scene = WM_window_get_active_scene(win);
1888                                 sl = st->new(sa, scene);
1889                                 BLI_addhead(&sa->spacedata, sl);
1890
1891                                 /* swap regions */
1892                                 if (slold)
1893                                         slold->regionbase = sa->regionbase;
1894                                 sa->regionbase = sl->regionbase;
1895                                 BLI_listbase_clear(&sl->regionbase);
1896                         }
1897                 }
1898
1899                 /* Sync header alignment. */
1900                 if (sync_header_alignment) {
1901                         for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) {
1902                                 if (ar->regiontype == RGN_TYPE_HEADER) {
1903                                         ar->alignment = header_alignment;
1904                                         break;
1905                                 }
1906                         }
1907                 }
1908
1909                 ED_area_initialize(CTX_wm_manager(C), win, sa);
1910
1911                 /* tell WM to refresh, cursor types etc */
1912                 WM_event_add_mousemove(C);
1913
1914                 /* send space change notifier */
1915                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_CHANGED, sa);
1916
1917                 ED_area_tag_refresh(sa);
1918         }
1919
1920         /* also redraw when re-used */
1921         ED_area_tag_redraw(sa);
1922 }
1923
1924 void ED_area_prevspace(bContext *C, ScrArea *sa)
1925 {
1926         SpaceLink *sl = sa->spacedata.first;
1927
1928         if (sl && sl->next) {
1929                 ED_area_newspace(C, sa, sl->next->spacetype, false);
1930
1931                 /* keep old spacedata but move it to end, so calling
1932                  * ED_area_prevspace once more won't open it again */
1933                 BLI_remlink(&sa->spacedata, sl);
1934                 BLI_addtail(&sa->spacedata, sl);
1935         }
1936         else {
1937                 /* no change */
1938                 return;
1939         }
1940         sa->flag &= ~AREA_FLAG_STACKED_FULLSCREEN;
1941
1942         ED_area_tag_redraw(sa);
1943
1944         /* send space change notifier */
1945         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_CHANGED, sa);
1946 }
1947
1948 /* returns offset for next button in header */
1949 int ED_area_header_switchbutton(const bContext *C, uiBlock *block, int yco)
1950 {
1951         ScrArea *sa = CTX_wm_area(C);
1952         bScreen *scr = CTX_wm_screen(C);
1953         PointerRNA areaptr;
1954         int xco = 0.4 * U.widget_unit;
1955
1956         RNA_pointer_create(&(scr->id), &RNA_Area, sa, &areaptr);
1957
1958         uiDefButR(block, UI_BTYPE_MENU, 0, "", xco, yco, 1.6 * U.widget_unit, U.widget_unit,
1959                   &areaptr, "ui_type", 0, 0.0f, 0.0f, 0.0f, 0.0f, "");
1960
1961         return xco + 1.7 * U.widget_unit;
1962 }
1963
1964 /************************ standard UI regions ************************/
1965
1966 static ThemeColorID region_background_color_id(const bContext *C, const ARegion *region)
1967 {
1968         ScrArea *area = CTX_wm_area(C);
1969
1970         switch (region->regiontype) {
1971                 case RGN_TYPE_HEADER:
1972                         if (ED_screen_area_active(C) || ED_area_is_global(area)) {
1973                                 return TH_HEADER;
1974                         }
1975                         else {
1976                                 return TH_HEADERDESEL;
1977                         }
1978                 case RGN_TYPE_PREVIEW:
1979                         return TH_PREVIEW_BACK;
1980                 default:
1981                         return TH_BACK;
1982         }
1983 }
1984
1985 static void region_clear_color(const bContext *C, const ARegion *ar, ThemeColorID colorid)
1986 {
1987         if (ar->alignment == RGN_ALIGN_FLOAT) {
1988                 /* handle our own drawing. */
1989         }
1990         else if (ar->overlap) {
1991                 /* view should be in pixelspace */
1992                 UI_view2d_view_restore(C);
1993
1994                 float back[4];
1995                 UI_GetThemeColor4fv(colorid, back);
1996                 GPU_clear_color(back[3] * back[0], back[3] * back[1], back[3] * back[2], back[3]);
1997                 GPU_clear(GPU_COLOR_BIT);
1998         }
1999         else {
2000                 UI_ThemeClearColor(colorid);
2001                 GPU_clear(GPU_COLOR_BIT);
2002         }
2003 }
2004
2005 BLI_INLINE bool streq_array_any(const char *s, const char *arr[])
2006 {
2007         for (uint i = 0; arr[i]; i++) {
2008                 if (STREQ(arr[i], s)) {
2009                         return true;
2010                 }
2011         }
2012         return false;
2013 }
2014
2015 static void ed_panel_draw(
2016         const bContext *C,
2017         ScrArea *sa,
2018         ARegion *ar,
2019         ListBase *lb,
2020         PanelType *pt,
2021         Panel *panel,
2022         int w,
2023         int em,
2024         bool vertical)
2025 {
2026         uiStyle *style = UI_style_get_dpi();
2027
2028         /* draw panel */
2029         uiBlock *block = UI_block_begin(C, ar, pt->idname, UI_EMBOSS);
2030
2031         bool open;
2032         panel = UI_panel_begin(sa, ar, lb, block, pt, panel, &open);
2033
2034         /* bad fixed values */
2035         int xco, yco, h = 0;
2036
2037         if (pt->draw_header_preset && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) {
2038                 /* for preset menu */
2039                 panel->layout = UI_block_layout(
2040                         block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER,
2041                         0, (UI_UNIT_Y * 1.1f) + style->panelspace, UI_UNIT_Y, 1, 0, style);
2042
2043                 pt->draw_header_preset(C, panel);
2044
2045                 int headerend = w - UI_UNIT_X;
2046
2047                 UI_block_layout_resolve(block, &xco, &yco);
2048                 UI_block_translate(block, headerend - xco, 0);
2049                 panel->layout = NULL;
2050         }
2051
2052         if (pt->draw_header && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) {
2053                 int labelx, labely;
2054                 UI_panel_label_offset(block, &labelx, &labely);
2055
2056                 /* for enabled buttons */
2057                 panel->layout = UI_block_layout(
2058                         block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER,
2059                         labelx, labely, UI_UNIT_Y, 1, 0, style);
2060
2061                 pt->draw_header(C, panel);
2062
2063                 UI_block_layout_resolve(block, &xco, &yco);
2064                 panel->labelofs = xco - labelx;
2065                 panel->layout = NULL;
2066         }
2067         else {
2068                 panel->labelofs = 0;
2069         }
2070
2071         if (open) {
2072                 short panelContext;
2073
2074                 /* panel context can either be toolbar region or normal panels region */
2075                 if (pt->flag & PNL_LAYOUT_VERT_BAR) {
2076                         panelContext = UI_LAYOUT_VERT_BAR;
2077                 }
2078                 else if (ar->regiontype == RGN_TYPE_TOOLS) {
2079                         panelContext = UI_LAYOUT_TOOLBAR;
2080                 }
2081                 else {
2082                         panelContext = UI_LAYOUT_PANEL;
2083                 }
2084
2085                 panel->layout = UI_block_layout(
2086                         block, UI_LAYOUT_VERTICAL, panelContext,
2087                         (pt->flag & PNL_LAYOUT_VERT_BAR) ? 0 : style->panelspace, 0,
2088                         (pt->flag & PNL_LAYOUT_VERT_BAR) ? 0 : w - 2 * style->panelspace,
2089                         em, 0, style);
2090
2091                 pt->draw(C, panel);
2092
2093                 UI_block_layout_resolve(block, &xco, &yco);
2094                 panel->layout = NULL;
2095
2096                 if (yco != 0) {
2097                         h = -yco + 2 * style->panelspace;
2098                 }
2099         }
2100
2101         UI_block_end(C, block);
2102
2103         /* Draw child panels. */
2104         if (open) {
2105                 for (LinkData *link = pt->children.first; link; link = link->next) {
2106                         PanelType *child_pt = link->data;
2107                         Panel *child_panel = UI_panel_find_by_type(&panel->children, child_pt);
2108
2109                         if (child_pt->draw && (!child_pt->poll || child_pt->poll(C, child_pt))) {
2110                                 ed_panel_draw(C, sa, ar, &panel->children, child_pt, child_panel, w, em, vertical);
2111                         }
2112                 }
2113         }
2114
2115         UI_panel_end(block, w, h);
2116 }
2117
2118 /**
2119  * \param contexts: A NULL terminated array of context strings to match against.
2120  * Matching against any of these strings will draw the panel.
2121  * Can be NULL to skip context checks.
2122  */
2123 void ED_region_panels_layout_ex(
2124         const bContext *C, ARegion *ar,
2125         const char *contexts[], int contextnr, const bool vertical)
2126 {
2127         ar->runtime.category = NULL;
2128
2129         const WorkSpace *workspace = CTX_wm_workspace(C);
2130         ScrArea *sa = CTX_wm_area(C);
2131         PanelType *pt;
2132         View2D *v2d = &ar->v2d;
2133         int x, y, w, em;
2134         bool is_context_new = 0;
2135         int scroll;
2136
2137         /* XXX, should use some better check? */
2138         /* For now also has hardcoded check for clip editor until it supports actual toolbar. */
2139         bool use_category_tabs = ((1 << ar->regiontype) & RGN_TYPE_HAS_CATEGORY_MASK) ||
2140                                  (ar->regiontype == RGN_TYPE_TOOLS && sa->spacetype == SPACE_CLIP);
2141         /* offset panels for small vertical tab area */
2142         const char *category = NULL;
2143         const int category_tabs_width = UI_PANEL_CATEGORY_MARGIN_WIDTH;
2144         int margin_x = 0;
2145         const bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE;
2146
2147         BLI_SMALLSTACK_DECLARE(pt_stack, PanelType *);
2148
2149         if (contextnr != -1)
2150                 is_context_new = UI_view2d_tab_set(v2d, contextnr);
2151
2152         /* before setting the view */
2153         if (vertical) {
2154                 /* only allow scrolling in vertical direction */
2155                 v2d->keepofs |= V2D_LOCKOFS_X | V2D_KEEPOFS_Y;
2156                 v2d->keepofs &= ~(V2D_LOCKOFS_Y | V2D_KEEPOFS_X);
2157                 v2d->scroll &= ~(V2D_SCROLL_BOTTOM);
2158                 v2d->scroll |= (V2D_SCROLL_RIGHT);
2159         }
2160         else {
2161                 /* for now, allow scrolling in both directions (since layouts are optimized for vertical,
2162                  * they often don't fit in horizontal layout)
2163                  */
2164                 v2d->keepofs &= ~(V2D_LOCKOFS_X | V2D_LOCKOFS_Y | V2D_KEEPOFS_X | V2D_KEEPOFS_Y);
2165                 v2d->scroll |= (V2D_SCROLL_BOTTOM);
2166                 v2d->scroll &= ~(V2D_SCROLL_RIGHT);
2167         }
2168
2169         scroll = v2d->scroll;
2170
2171
2172         /* collect panels to draw */
2173         for (pt = ar->type->paneltypes.last; pt; pt = pt->prev) {
2174                 /* Only draw top level panels. */
2175                 if (pt->parent) {
2176                         continue;
2177                 }
2178
2179                 /* verify context */
2180                 if (contexts && pt->context[0] && !streq_array_any(pt->context, contexts)) {
2181                         continue;
2182                 }
2183
2184                 /* If we're tagged, only use compatible. */
2185                 if (pt->owner_id[0] && BKE_workspace_owner_id_check(workspace, pt->owner_id) == false) {
2186                         continue;
2187                 }
2188
2189                 /* draw panel */
2190                 if (pt->draw && (!pt->poll || pt->poll(C, pt))) {
2191                         BLI_SMALLSTACK_PUSH(pt_stack, pt);
2192                 }
2193         }
2194
2195
2196         /* collect categories */
2197         if (use_category_tabs) {
2198                 UI_panel_category_clear_all(ar);
2199
2200                 /* gather unique categories */
2201                 BLI_SMALLSTACK_ITER_BEGIN(pt_stack, pt)
2202                 {
2203                         if (pt->category[0]) {
2204                                 if (!UI_panel_category_find(ar, pt->category)) {
2205                                         UI_panel_category_add(ar, pt->category);
2206                                 }
2207                         }
2208                 }
2209                 BLI_SMALLSTACK_ITER_END;
2210
2211                 if (!UI_panel_category_is_visible(ar)) {
2212                         use_category_tabs = false;
2213                 }
2214                 else {
2215                         category = UI_panel_category_active_get(ar, true);
2216                         margin_x = category_tabs_width;
2217                 }
2218         }
2219
2220
2221         if (vertical) {
2222                 w = BLI_rctf_size_x(&v2d->cur);
2223                 em = (ar->type->prefsizex) ? 10 : 20; /* works out to 10*UI_UNIT_X or 20*UI_UNIT_X */
2224         }
2225         else {
2226                 w = UI_PANEL_WIDTH;
2227                 em = (ar->type->prefsizex) ? 10 : 20;
2228         }
2229
2230         w -= margin_x;
2231
2232         /* create panels */
2233         UI_panels_begin(C, ar);
2234
2235         /* set view2d view matrix  - UI_block_begin() stores it */
2236         UI_view2d_view_ortho(v2d);
2237
2238         BLI_SMALLSTACK_ITER_BEGIN(pt_stack, pt)
2239         {
2240                 Panel *panel = UI_panel_find_by_type(&ar->panels, pt);
2241
2242                 if (use_category_tabs && pt->category[0] && !STREQ(category, pt->category)) {
2243                         if ((panel == NULL) || ((panel->flag & PNL_PIN) == 0)) {
2244                                 continue;
2245                         }
2246                 }
2247
2248                 ed_panel_draw(C, sa, ar, &ar->panels, pt, panel, w, em, vertical);
2249         }
2250         BLI_SMALLSTACK_ITER_END;
2251
2252         /* align panels and return size */
2253         UI_panels_end(C, ar, &x, &y);
2254
2255         /* before setting the view */
2256         if (region_layout_based) {
2257                 /* XXX, only single panel support atm.
2258                  * Can't use x/y values calculated above because they're not using the real height of panels,
2259                  * instead they calculate offsets for the next panel to start drawing. */
2260                 Panel *panel = ar->panels.last;
2261                 if (panel != NULL) {
2262                         int size_dyn[2] = {
2263                                 UI_UNIT_X * ((panel->flag & PNL_CLOSED) ? 8 : 14) / UI_DPI_FAC,
2264                                 UI_panel_size_y(panel) / UI_DPI_FAC,
2265                         };
2266                         /* region size is layout based and needs to be updated */
2267                         if ((ar->sizex != size_dyn[0]) ||
2268                             (ar->sizey != size_dyn[1]))
2269                         {
2270                                 ar->sizex = size_dyn[0];
2271                                 ar->sizey = size_dyn[1];
2272                                 sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE;
2273                         }
2274                         y = ABS(ar->sizey * UI_DPI_FAC - 1);
2275                 }
2276         }
2277         else if (vertical) {
2278                 /* we always keep the scroll offset - so the total view gets increased with the scrolled away part */
2279                 if (v2d->cur.ymax < -FLT_EPSILON) {
2280                         /* Clamp to lower view boundary */
2281                         if (v2d->tot.ymin < -v2d->winy) {
2282                                 y = min_ii(y, 0);
2283                         }
2284                         else {
2285                                 y = min_ii(y, v2d->cur.ymin);
2286                         }
2287                 }
2288
2289                 y = -y;
2290         }
2291         else {
2292                 /* don't jump back when panels close or hide */
2293                 if (!is_context_new) {
2294                         if (v2d->tot.xmax > v2d->winx) {
2295                                 x = max_ii(x, 0);
2296                         }
2297                         else {
2298                                 x = max_ii(x, v2d->cur.xmax);
2299                         }
2300                 }
2301
2302                 y = -y;
2303         }
2304
2305         /* this also changes the 'cur' */
2306         UI_view2d_totRect_set(v2d, x, y);
2307
2308         if (scroll != v2d->scroll) {
2309                 /* Note: this code scales fine, but because of rounding differences, positions of elements
2310                  * flip +1 or -1 pixel compared to redoing the entire layout again.
2311                  * Leaving in commented code for future tests */
2312 #if 0
2313                 UI_panels_scale(ar, BLI_rctf_size_x(&v2d->cur));
2314                 break;
2315 #endif
2316         }
2317
2318         if (use_category_tabs) {
2319                 ar->runtime.category = category;
2320         }
2321 }
2322 void ED_region_panels_layout(const bContext *C, ARegion *ar)
2323 {
2324         ED_region_panels_layout_ex(C, ar, NULL, -1, true);
2325 }
2326
2327 void ED_region_panels_draw(const bContext *C, ARegion *ar)
2328 {
2329         View2D *v2d = &ar->v2d;
2330
2331         if (ar->alignment != RGN_ALIGN_FLOAT) {
2332                 region_clear_color(C, ar, (ar->type->regionid == RGN_TYPE_PREVIEW) ? TH_PREVIEW_BACK : TH_BACK);
2333         }
2334
2335         /* reset line width for drawing tabs */
2336         GPU_line_width(1.0f);
2337
2338         /* set the view */
2339         UI_view2d_view_ortho(v2d);
2340
2341         /* View2D matrix might have changed due to dynamic sized regions. */
2342         UI_blocklist_update_window_matrix(C, &ar->uiblocks);
2343
2344         /* draw panels */
2345         UI_panels_draw(C, ar);
2346
2347         /* restore view matrix */
2348         UI_view2d_view_restore(C);
2349
2350         /* Set in layout. */
2351         if (ar->runtime.category) {
2352                 UI_panel_category_draw_all(ar, ar->runtime.category);
2353         }
2354
2355         /* scrollers */
2356         const rcti *mask = NULL;
2357         rcti        mask_buf;
2358         if (ar->runtime.category && (ar->alignment == RGN_ALIGN_RIGHT)) {
2359                 UI_view2d_mask_from_win(v2d, &mask_buf);
2360                 mask_buf.xmax -= UI_PANEL_CATEGORY_MARGIN_WIDTH;
2361                 mask = &mask_buf;
2362         }
2363         View2DScrollers *scrollers = UI_view2d_scrollers_calc(
2364                 C, v2d, mask, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY);
2365         UI_view2d_scrollers_draw(C, v2d, scrollers);
2366         UI_view2d_scrollers_free(scrollers);
2367 }
2368
2369 void ED_region_panels_ex(
2370         const bContext *C, ARegion *ar,
2371         const char *contexts[], int contextnr, const bool vertical)
2372 {
2373         /* TODO: remove? */
2374         ED_region_panels_layout_ex(C, ar, contexts, contextnr, vertical);
2375         ED_region_panels_draw(C, ar);
2376 }
2377
2378 void ED_region_panels(const bContext *C, ARegion *ar)
2379 {
2380         /* TODO: remove? */
2381         ED_region_panels_layout(C, ar);
2382         ED_region_panels_draw(C, ar);
2383 }
2384
2385 void ED_region_panels_init(wmWindowManager *wm, ARegion *ar)
2386 {
2387         wmKeyMap *keymap;
2388
2389         UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_PANELS_UI, ar->winx, ar->winy);
2390
2391         keymap = WM_keymap_ensure(wm->defaultconf, "View2D Buttons List", 0, 0);
2392         WM_event_add_keymap_handler(&ar->handlers, keymap);
2393 }
2394
2395 void ED_region_header_layout(const bContext *C, ARegion *ar)
2396 {
2397         uiStyle *style = UI_style_get_dpi();
2398         uiBlock *block;
2399         uiLayout *layout;
2400         HeaderType *ht;
2401         Header header = {NULL};
2402         bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE;
2403
2404         /* Height of buttons and scaling needed to achieve it. */
2405         const int buttony = min_ii(UI_UNIT_Y, ar->winy - 2 * UI_DPI_FAC);
2406         const float buttony_scale = buttony / (float)UI_UNIT_Y;
2407
2408         /* Vertically center buttons. */
2409         int xco = UI_HEADER_OFFSET;
2410         int yco = buttony + (ar->winy - buttony) / 2;
2411         int maxco = xco;
2412
2413         /* XXX workaround for 1 px alignment issue. Not sure what causes it... Would prefer a proper fix - Julian */
2414         if (!ELEM(CTX_wm_area(C)->spacetype, SPACE_TOPBAR, SPACE_STATUSBAR)) {
2415                 yco -= 1;
2416         }
2417
2418         /* set view2d view matrix for scrolling (without scrollers) */
2419         UI_view2d_view_ortho(&ar->v2d);
2420
2421         /* draw all headers types */
2422         for (ht = ar->type->headertypes.first; ht; ht = ht->next) {
2423                 if (ht->poll && !ht->poll(C, ht)) {
2424                         continue;
2425                 }
2426
2427                 block = UI_block_begin(C, ar, ht->idname, UI_EMBOSS);
2428                 layout = UI_block_layout(block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER, xco, yco, buttony, 1, 0, style);
2429
2430                 if (buttony_scale != 1.0f) {
2431                         uiLayoutSetScaleY(layout, buttony_scale);
2432                 }
2433
2434                 if (ht->draw) {
2435                         header.type = ht;
2436                         header.layout = layout;
2437                         ht->draw(C, &header);
2438                         if (ht->next) {
2439                                 uiItemS(layout);
2440                         }
2441
2442                         /* for view2d */
2443                         xco = uiLayoutGetWidth(layout);
2444                         if (xco > maxco)
2445                                 maxco = xco;
2446                 }
2447
2448                 UI_block_layout_resolve(block, &xco, &yco);
2449
2450                 /* for view2d */
2451                 if (xco > maxco)
2452                         maxco = xco;
2453
2454                 int new_sizex = (maxco + UI_HEADER_OFFSET) / UI_DPI_FAC;
2455
2456                 if (region_layout_based && (ar->sizex != new_sizex)) {
2457                         /* region size is layout based and needs to be updated */
2458                         ScrArea *sa = CTX_wm_area(C);
2459
2460                         ar->sizex = new_sizex;
2461                         sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE;
2462                 }
2463
2464                 UI_block_end(C, block);
2465         }
2466
2467         if (!region_layout_based) {
2468                 maxco += UI_HEADER_OFFSET;
2469         }
2470
2471         /* always as last  */
2472         UI_view2d_totRect_set(&ar->v2d, maxco, ar->winy);
2473
2474         /* restore view matrix */
2475         UI_view2d_view_restore(C);
2476 }
2477
2478 void ED_region_header_draw(const bContext *C, ARegion *ar)
2479 {
2480         /* clear */
2481         region_clear_color(C, ar, region_background_color_id(C, ar));
2482
2483         UI_view2d_view_ortho(&ar->v2d);
2484
2485         /* View2D matrix might have changed due to dynamic sized regions. */
2486         UI_blocklist_update_window_matrix(C, &ar->uiblocks);
2487
2488         /* draw blocks */
2489         UI_blocklist_draw(C, &ar->uiblocks);
2490
2491         /* restore view matrix */
2492         UI_view2d_view_restore(C);
2493 }
2494
2495 void ED_region_header(const bContext *C, ARegion *ar)
2496 {
2497         /* TODO: remove? */
2498         ED_region_header_layout(C, ar);
2499         ED_region_header_draw(C, ar);
2500 }
2501
2502 void ED_region_header_init(ARegion *ar)
2503 {
2504         UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_HEADER, ar->winx, ar->winy);
2505 }
2506
2507 int ED_area_headersize(void)
2508 {
2509         /* Accomodate widget and padding. */
2510         return U.widget_unit + (int)(UI_DPI_FAC * HEADER_PADDING_Y);
2511 }
2512
2513 int ED_area_header_alignment_or_fallback(const ScrArea *area, int fallback)
2514 {
2515         for (ARegion *ar = area->regionbase.first; ar; ar = ar->next) {
2516                 if (ar->regiontype == RGN_TYPE_HEADER) {
2517                         return ar->alignment;
2518                 }
2519         }
2520         return fallback;
2521 }
2522
2523 int ED_area_header_alignment(const ScrArea *area)
2524 {
2525         return ED_area_header_alignment_or_fallback(
2526                 area, (U.uiflag & USER_HEADER_BOTTOM) ? RGN_ALIGN_BOTTOM : RGN_ALIGN_TOP);
2527 }
2528
2529 /**
2530  * \return the final height of a global \a area, accounting for DPI.
2531  */
2532 int ED_area_global_size_y(const ScrArea *area)
2533 {
2534         BLI_assert(ED_area_is_global(area));
2535         return round_fl_to_int(area->global->cur_fixed_height * UI_DPI_FAC);
2536 }
2537 int ED_area_global_min_size_y(const ScrArea *area)
2538 {
2539         BLI_assert(ED_area_is_global(area));
2540         return round_fl_to_int(area->global->size_min * UI_DPI_FAC);
2541 }
2542 int ED_area_global_max_size_y(const ScrArea *area)
2543 {
2544         BLI_assert(ED_area_is_global(area));
2545         return round_fl_to_int(area->global->size_max * UI_DPI_FAC);
2546 }
2547
2548 bool ED_area_is_global(const ScrArea *area)
2549 {
2550         return area->global != NULL;
2551 }
2552
2553 ScrArea *ED_screen_areas_iter_first(const wmWindow *win, const bScreen *screen)
2554 {
2555         ScrArea *global_area = win->global_areas.areabase.first;
2556
2557         if (!global_area) {
2558                 return screen->areabase.first;
2559         }
2560         else if ((global_area->global->flag & GLOBAL_AREA_IS_HIDDEN) == 0) {
2561                 return global_area;
2562         }
2563         /* Find next visible area. */
2564         return ED_screen_areas_iter_next(screen, global_area);
2565 }
2566 ScrArea *ED_screen_areas_iter_next(const bScreen *screen, const ScrArea *area)
2567 {
2568         if (area->global) {
2569                 for (ScrArea *area_iter = area->next; area_iter; area_iter = area_iter->next) {
2570                         if ((area_iter->global->flag & GLOBAL_AREA_IS_HIDDEN) == 0) {
2571                                 return area_iter;
2572                         }
2573                 }
2574                 /* No visible next global area found, start iterating over layout areas. */
2575                 return screen->areabase.first;
2576         }
2577
2578         return area->next;
2579 }
2580
2581 /**
2582  * For now we just assume all global areas are made up out of horizontal bars
2583  * with the same size. A fixed size could be stored in ARegion instead if needed.
2584  *
2585  * \return the DPI aware height of a single bar/region in global areas.
2586  */
2587 int ED_region_global_size_y(void)
2588 {
2589         return ED_area_headersize(); /* same size as header */
2590 }
2591
2592 void ED_region_info_draw_multiline(ARegion *ar, const char *text_array[], float fill_color[4], const bool full_redraw)
2593 {
2594         const int header_height = UI_UNIT_Y;
2595         uiStyle *style = UI_style_get_dpi();
2596         int fontid = style->widget.uifont_id;
2597         int scissor[4];
2598         rcti rect;
2599         int num_lines = 0;
2600
2601         /* background box */
2602         ED_region_visible_rect(ar, &rect);
2603
2604         /* Box fill entire width or just around text. */
2605         if (!full_redraw) {
2606                 const char **text = &text_array[0];
2607                 while (*text) {
2608                         rect.xmax = min_ii(rect.xmax, rect.xmin + BLF_width(fontid, *text, BLF_DRAW_STR_DUMMY_MAX) + 1.2f * U.widget_unit);
2609                         text++;
2610                         num_lines++;
2611                 }
2612         }
2613         /* Just count the line number. */
2614         else {
2615                 const char **text = &text_array[0];
2616                 while (*text) {
2617                         text++;
2618                         num_lines++;
2619                 }
2620         }
2621
2622         rect.ymin = rect.ymax - header_height * num_lines;
2623
2624         /* setup scissor */
2625         GPU_scissor_get_i(scissor);
2626         GPU_scissor(rect.xmin, rect.ymin,
2627                   BLI_rcti_size_x(&rect) + 1, BLI_rcti_size_y(&rect) + 1);
2628
2629         GPU_blend(true);
2630         GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2631         GPUVertFormat *format = immVertexFormat();
2632         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
2633         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2634         immUniformColor4fv(fill_color);
2635         immRecti(pos, rect.xmin, rect.ymin, rect.xmax + 1, rect.ymax + 1);
2636         immUnbindProgram();
2637         GPU_blend(false);
2638
2639         /* text */
2640         UI_FontThemeColor(fontid, TH_TEXT_HI);
2641         BLF_clipping(fontid, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2642         BLF_enable(fontid, BLF_CLIPPING);
2643         int offset = num_lines - 1;
2644         {
2645                 const char **text = &text_array[0];
2646                 while (*text) {
2647                         BLF_position(fontid, rect.xmin + 0.6f * U.widget_unit, rect.ymin + 0.3f * U.widget_unit + offset * header_height, 0.0f);
2648                         BLF_draw(fontid, *text, BLF_DRAW_STR_DUMMY_MAX);
2649                         text++;
2650                         offset--;
2651                 }
2652         }
2653
2654         BLF_disable(fontid, BLF_CLIPPING);
2655
2656         /* restore scissor as it was before */
2657         GPU_scissor(scissor[0], scissor[1], scissor[2], scissor[3]);
2658 }
2659
2660 void ED_region_info_draw(ARegion *ar, const char *text, float fill_color[4], const bool full_redraw)
2661 {
2662         ED_region_info_draw_multiline(ar, (const char *[2]){text, NULL}, fill_color, full_redraw);
2663 }
2664
2665 #define MAX_METADATA_STR    1024
2666
2667 static const char *meta_data_list[] =
2668 {
2669         "File",
2670         "Strip",
2671         "Date",
2672         "RenderTime",
2673         "Note",
2674         "Marker",
2675         "Time",
2676         "Frame",
2677         "Camera",
2678         "Scene",
2679 };
2680
2681 BLI_INLINE bool metadata_is_valid(ImBuf *ibuf, char *r_str, short index, int offset)
2682 {
2683         return (IMB_metadata_get_field(ibuf->metadata, meta_data_list[index], r_str + offset, MAX_METADATA_STR - offset) && r_str[0]);
2684 }
2685
2686 BLI_INLINE bool metadata_is_custom_drawable(const char *field)
2687 {
2688         /* Metadata field stored by Blender for multilayer EXR images. Is rather
2689          * useless to be viewed all the time. Can still be seen in the Metadata
2690          * panel. */
2691         if (STREQ(field, "BlenderMultiChannel")) {
2692                 return false;
2693         }
2694         /* Is almost always has value "scanlineimage", also useless to be seen
2695          * all the time. */
2696         if (STREQ(field, "type")) {
2697                 return false;
2698         }
2699         return !BKE_stamp_is_known_field(field);
2700 }
2701
2702 typedef struct MetadataCustomDrawContext {
2703         int fontid;
2704         int xmin, ymin;
2705         int vertical_offset;
2706         int current_y;
2707 } MetadataCustomDrawContext;
2708
2709 static void metadata_custom_draw_fields(
2710         const char *field,
2711         const char *value,
2712         void *ctx_v)
2713 {
2714         if (!metadata_is_custom_drawable(field)) {
2715                 return;
2716         }
2717         MetadataCustomDrawContext *ctx = (MetadataCustomDrawContext *)ctx_v;
2718         char temp_str[MAX_METADATA_STR];
2719         BLI_snprintf(temp_str, MAX_METADATA_STR, "%s: %s", field, value);
2720         BLF_position(ctx->fontid, ctx->xmin, ctx->ymin + ctx->current_y, 0.0f);
2721         BLF_draw(ctx->fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2722         ctx->current_y += ctx->vertical_offset;
2723 }
2724
2725 static void metadata_draw_imbuf(ImBuf *ibuf, const rctf *rect, int fontid, const bool is_top)
2726 {
2727         char temp_str[MAX_METADATA_STR];
2728         int line_width;
2729         int ofs_y = 0;
2730         short i;
2731         int len;
2732         const float height = BLF_height_max(fontid);
2733         const float margin = height / 8;
2734         const float vertical_offset = (height + margin);
2735
2736         /* values taking margins into account */
2737         const float descender = BLF_descender(fontid);
2738         const float xmin = (rect->xmin + margin);
2739         const float xmax = (rect->xmax - margin);
2740         const float ymin = (rect->ymin + margin) - descender;
2741         const float ymax = (rect->ymax - margin) - descender;
2742
2743         if (is_top) {
2744                 for (i = 0; i < 4; i++) {
2745                         /* first line */
2746                         if (i == 0) {
2747                                 bool do_newline = false;
2748                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[0]);
2749                                 if (metadata_is_valid(ibuf, temp_str, 0, len)) {
2750                                         BLF_position(fontid, xmin, ymax - vertical_offset, 0.0f);
2751                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2752                                         do_newline = true;
2753                                 }
2754
2755                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[1]);
2756                                 if (metadata_is_valid(ibuf, temp_str, 1, len)) {
2757                                         line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2758                                         BLF_position(fontid, xmax - line_width, ymax - vertical_offset, 0.0f);
2759                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2760                                         do_newline = true;
2761                                 }
2762
2763                                 if (do_newline)
2764                                         ofs_y += vertical_offset;
2765                         } /* Strip */
2766                         else if (i == 1 || i == 2) {
2767                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2768                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2769                                         BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f);
2770                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2771                                         ofs_y += vertical_offset;
2772                                 }
2773                         } /* Note (wrapped) */
2774                         else if (i == 3) {
2775                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2776                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2777                                         struct ResultBLF info;
2778                                         BLF_enable(fontid, BLF_WORD_WRAP);
2779                                         BLF_wordwrap(fontid, ibuf->x - (margin * 2));
2780                                         BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f);
2781                                         BLF_draw_ex(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX, &info);
2782                                         BLF_wordwrap(fontid, 0);
2783                                         BLF_disable(fontid, BLF_WORD_WRAP);
2784                                         ofs_y += vertical_offset * info.lines;
2785                                 }
2786                         }
2787                         else {
2788                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2789                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2790                                         line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2791                                         BLF_position(fontid, xmax  - line_width, ymax - vertical_offset - ofs_y, 0.0f);
2792                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2793                                         ofs_y += vertical_offset;
2794                                 }
2795                         }
2796                 }
2797         }
2798         else {
2799                 MetadataCustomDrawContext ctx;
2800                 ctx.fontid = fontid;
2801                 ctx.xmin = xmin;
2802                 ctx.ymin = ymin;
2803                 ctx.vertical_offset = vertical_offset;
2804                 ctx.current_y = ofs_y;
2805                 ctx.vertical_offset = vertical_offset;
2806                 IMB_metadata_foreach(ibuf, metadata_custom_draw_fields, &ctx);
2807                 int ofs_x = 0;
2808                 ofs_y = ctx.current_y;
2809                 for (i = 5; i < 10; i++) {
2810                         len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i]);
2811                         if (metadata_is_valid(ibuf, temp_str, i, len)) {
2812                                 BLF_position(fontid, xmin + ofs_x, ymin + ofs_y, 0.0f);
2813                                 BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2814
2815                                 ofs_x += BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX) + UI_UNIT_X;
2816                         }
2817                 }
2818         }
2819 }
2820
2821 typedef struct MetadataCustomCountContext {
2822         int count;
2823 } MetadataCustomCountContext;
2824
2825 static void metadata_custom_count_fields(
2826         const char *field,
2827         const char *UNUSED(value),
2828         void *ctx_v)
2829 {
2830         if (!metadata_is_custom_drawable(field)) {
2831                 return;
2832         }
2833         MetadataCustomCountContext *ctx = (MetadataCustomCountContext *)ctx_v;
2834         ctx->count++;
2835 }
2836
2837
2838 static float metadata_box_height_get(ImBuf *ibuf, int fontid, const bool is_top)
2839 {
2840         const float height = BLF_height_max(fontid);
2841         const float margin = (height / 8);
2842         char str[MAX_METADATA_STR] = "";
2843         short i, count = 0;
2844
2845         if (is_top) {
2846                 if (metadata_is_valid(ibuf, str, 0, 0) || metadata_is_valid(ibuf, str, 1, 0)) {
2847                         count++;
2848                 }
2849                 for (i = 2; i < 5; i++) {
2850                         if (metadata_is_valid(ibuf, str, i, 0)) {
2851                                 if (i == 4) {
2852                                         struct {
2853                                                 struct ResultBLF info;
2854                                                 rctf rect;
2855                                         } wrap;
2856
2857                                         BLF_enable(fontid, BLF_WORD_WRAP);
2858                                         BLF_wordwrap(fontid, ibuf->x - (margin * 2));
2859                                         BLF_boundbox_ex(fontid, str, sizeof(str), &wrap.rect, &wrap.info);
2860                                         BLF_wordwrap(fontid, 0);
2861                                         BLF_disable(fontid, BLF_WORD_WRAP);
2862
2863                                         count += wrap.info.lines;
2864                                 }
2865                                 else {
2866                                         count++;
2867                                 }
2868                         }
2869                 }
2870         }
2871         else {
2872                 for (i = 5; i < 10; i++) {
2873                         if (metadata_is_valid(ibuf, str, i, 0)) {
2874                                 count = 1;
2875                                 break;
2876                         }
2877                 }
2878                 MetadataCustomCountContext ctx;
2879                 ctx.count = 0;
2880                 IMB_metadata_foreach(ibuf, metadata_custom_count_fields, &ctx);
2881                 count += ctx.count;
2882         }
2883
2884         if (count) {
2885                 return (height + margin) * count;
2886         }
2887
2888         return 0;
2889 }
2890
2891 #undef MAX_METADATA_STR
2892
2893 void ED_region_image_metadata_draw(int x, int y, ImBuf *ibuf, const rctf *frame, float zoomx, float zoomy)
2894 {
2895         float box_y;
2896         rctf rect;
2897         uiStyle *style = UI_style_get_dpi();
2898
2899         if (!ibuf->metadata)
2900                 return;
2901
2902         /* find window pixel coordinates of origin */
2903         GPU_matrix_push();
2904
2905         /* offset and zoom using ogl */
2906         GPU_matrix_translate_2f(x, y);
2907         GPU_matrix_scale_2f(zoomx, zoomy);
2908
2909         BLF_size(blf_mono_font, style->widgetlabel.points * 1.5f * U.pixelsize, U.dpi);
2910
2911         /* *** upper box*** */
2912
2913         /* get needed box height */
2914         box_y = metadata_box_height_get(ibuf, blf_mono_font, true);
2915
2916         if (box_y) {
2917                 /* set up rect */
2918                 BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymax, frame->ymax + box_y);
2919                 /* draw top box */
2920                 GPUVertFormat *format = immVertexFormat();
2921                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2922                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2923                 immUniformThemeColor(TH_METADATA_BG);
2924                 immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2925                 immUnbindProgram();
2926
2927                 BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2928                 BLF_enable(blf_mono_font, BLF_CLIPPING);
2929
2930                 UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT);
2931                 metadata_draw_imbuf(ibuf, &rect, blf_mono_font, true);
2932
2933                 BLF_disable(blf_mono_font, BLF_CLIPPING);
2934         }
2935
2936
2937         /* *** lower box*** */
2938
2939         box_y = metadata_box_height_get(ibuf, blf_mono_font, false);
2940
2941         if (box_y) {
2942                 /* set up box rect */
2943                 BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymin - box_y, frame->ymin);
2944                 /* draw top box */
2945                 GPUVertFormat *format = immVertexFormat();
2946                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2947                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2948                 immUniformThemeColor(TH_METADATA_BG);
2949                 immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2950                 immUnbindProgram();
2951
2952                 BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2953                 BLF_enable(blf_mono_font, BLF_CLIPPING);
2954
2955                 UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT);
2956                 metadata_draw_imbuf(ibuf, &rect, blf_mono_font, false);
2957
2958                 BLF_disable(blf_mono_font, BLF_CLIPPING);
2959         }
2960
2961         GPU_matrix_pop();
2962 }
2963
2964 typedef struct MetadataPanelDrawContext {
2965         uiLayout *layout;
2966 } MetadataPanelDrawContext;
2967
2968 static void metadata_panel_draw_field(
2969         const char *field,
2970         const char *value,
2971         void *ctx_v)
2972 {
2973         MetadataPanelDrawContext *ctx = (MetadataPanelDrawContext *)ctx_v;
2974         uiLayout *row = uiLayoutRow(ctx->layout, false);
2975         uiItemL(row, field, ICON_NONE);
2976         uiItemL(row, value, ICON_NONE);
2977 }
2978
2979 void ED_region_image_metadata_panel_draw(ImBuf *ibuf, uiLayout *layout)
2980 {
2981         MetadataPanelDrawContext ctx;
2982         ctx.layout = layout;
2983         IMB_metadata_foreach(ibuf, metadata_panel_draw_field, &ctx);
2984 }
2985
2986 void ED_region_grid_draw(ARegion *ar, float zoomx, float zoomy)
2987 {
2988         float gridsize, gridstep = 1.0f / 32.0f;
2989         float fac, blendfac;
2990         int x1, y1, x2, y2;
2991
2992         /* the image is located inside (0, 0), (1, 1) as set by view2d */
2993         UI_view2d_view_to_region(&ar->v2d, 0.0f, 0.0f, &x1, &y1);
2994         UI_view2d_view_to_region(&ar->v2d, 1.0f, 1.0f, &x2, &y2);
2995
2996         GPUVertFormat *format = immVertexFormat();
2997         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2998
2999         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3000         immUniformThemeColorShade(TH_BACK, 20);
3001         immRectf(pos, x1, y1, x2, y2);
3002         immUnbindProgram();
3003
3004         /* gridsize adapted to zoom level */
3005         gridsize = 0.5f * (zoomx + zoomy);
3006         if (gridsize <= 0.0f)
3007                 return;
3008
3009         if (gridsize < 1.0f) {
3010                 while (gridsize < 1.0f) {
3011                         gridsize *= 4.0f;
3012                         gridstep *= 4.0f;
3013                 }
3014         }
3015         else {
3016                 while (gridsize >= 4.0f) {
3017                         gridsize /= 4.0f;
3018                         gridstep /= 4.0f;
3019                 }
3020         }
3021
3022         blendfac = 0.25f * gridsize - floorf(0.25f * gridsize);
3023         CLAMP(blendfac, 0.0f, 1.0f);
3024
3025         int count_fine = 1.0f / gridstep;
3026         int count_large = 1.0f / (4.0f * gridstep);
3027
3028         if (count_fine > 0) {
3029                 GPU_vertformat_clear(format);
3030                 pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
3031                 unsigned color = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
3032
3033                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
3034                 immBegin(GPU_PRIM_LINES, 4 * count_fine + 4 * count_large);
3035
3036                 float theme_color[3];
3037                 UI_GetThemeColorShade3fv(TH_BACK, (int)(20.0f * (1.0f - blendfac)), theme_color);
3038                 fac = 0.0f;
3039
3040                 /* the fine resolution level */
3041                 for (int i = 0; i < count_fine; i++) {
3042                         immAttr3fv(color, theme_color);
3043                         immVertex2f(pos, x1, y1 * (1.0f - fac) + y2 * fac);
3044                         immAttr3fv(color, theme_color);
3045                         immVertex2f(pos, x2, y1 * (1.0f - fac) + y2 * fac);
3046                         immAttr3fv(color, theme_color);
3047                         immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y1);
3048                         immAttr3fv(color, theme_color);
3049                         immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y2);
3050                         fac += gridstep;
3051                 }
3052
3053                 if (count_large > 0) {
3054                         UI_GetThemeColor3fv(TH_BACK, theme_color);
3055                         fac = 0.0f;
3056
3057                         /* the large resolution level */
3058                         for (int i = 0; i < count_large; i++) {
3059                                 immAttr3fv(color, theme_color);
3060                                 immVertex2f(pos, x1, y1 * (1.0f - fac) + y2 * fac);
3061                                 immAttr3fv(color, theme_color);
3062                                 immVertex2f(pos, x2, y1 * (1.0f - fac) + y2 * fac);
3063                                 immAttr3fv(color, theme_color);
3064                                 immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y1);
3065                                 immAttr3fv(color, theme_color);
3066                                 immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y2);
3067                                 fac += 4.0f * gridstep;
3068                         }
3069                 }
3070
3071                 immEnd();
3072                 immUnbindProgram();
3073         }
3074 }
3075
3076 /* If the area has overlapping regions, it returns visible rect for Region *ar */
3077 /* rect gets returned in local region coordinates */
3078 void ED_region_visible_rect(ARegion *ar, rcti *rect)
3079 {
3080         ARegion *arn = ar;
3081
3082         /* allow function to be called without area */
3083         while (arn->prev)
3084                 arn = arn->prev;
3085
3086         *rect = ar->winrct;
3087
3088         /* check if a region overlaps with the current one */
3089         for (; arn; arn = arn->next) {
3090                 if (ar != arn && arn->overlap) {
3091                         if (BLI_rcti_isect(rect, &arn->winrct, NULL)) {
3092                                 if (ELEM(arn->alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
3093                                         /* Overlap left, also check 1 pixel offset (2 regions on one side). */
3094                                         if (ABS(rect->xmin - arn->winrct.xmin) < 2) {
3095                                                 rect->xmin = arn->winrct.xmax;
3096                                         }
3097
3098                                         /* Overlap right. */
3099                                         if (ABS(rect->xmax - arn->winrct.xmax) < 2) {
3100                                                 rect->xmax = arn->winrct.xmin;
3101                                         }
3102                                 }
3103                                 else if (ELEM(arn->alignment, RGN_ALIGN_TOP, RGN_ALIGN_BOTTOM)) {
3104                                         /* Same logic as above for vertical regions. */
3105                                         if (ABS(rect->ymin - arn->winrct.ymin) < 2) {
3106                                                 rect->ymin = arn->winrct.ymax;
3107                                         }
3108                                         if (ABS(rect->ymax - arn->winrct.ymax) < 2) {
3109                                                 rect->ymax = arn->winrct.ymin;
3110                                         }
3111                                 }
3112                                 else if (arn->alignment == RGN_ALIGN_FLOAT) {
3113                                         /* Skip floating. */
3114                                 }
3115                                 else {
3116                                         BLI_assert(!"Region overlap with unknown alignment");
3117                                 }
3118                         }
3119                 }
3120         }
3121         BLI_rcti_translate(rect, -ar->winrct.xmin, -ar->winrct.ymin);
3122 }
3123
3124 /* Cache display helpers */
3125
3126 void ED_region_cache_draw_background(const ARegion *ar)
3127 {
3128         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3129         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3130         immUniformColor4ub(128, 128, 255, 64);
3131         immRecti(pos, 0, 0, ar->winx, 8 * UI_DPI_FAC);
3132         immUnbindProgram();
3133 }
3134
3135 void ED_region_cache_draw_curfra_label(const int framenr, const float x, const float y)
3136 {
3137         uiStyle *style = UI_style_get();
3138         int fontid = style->widget.uifont_id;
3139         char numstr[32];
3140         float font_dims[2] = {0.0f, 0.0f};
3141
3142         /* frame number */
3143         BLF_size(fontid, 11.0f * U.pixelsize, U.dpi);
3144         BLI_snprintf(numstr, sizeof(numstr), "%d", framenr);
3145
3146         BLF_width_and_height(fontid, numstr, sizeof(numstr), &font_dims[0], &font_dims[1]);
3147
3148         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3149         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3150         immUniformThemeColor(TH_CFRAME);
3151         immRecti(pos, x, y, x + font_dims[0] + 6.0f, y + font_dims[1] + 4.0f);
3152         immUnbindProgram();
3153
3154         UI_FontThemeColor(fontid, TH_TEXT);
3155         BLF_position(fontid, x + 2.0f, y + 2.0f, 0.0f);
3156         BLF_draw(fontid, numstr, sizeof(numstr));
3157 }
3158
3159 void ED_region_cache_draw_cached_segments(const ARegion *ar, const int num_segments, const int *points, const int sfra, const int efra)
3160 {
3161         if (num_segments) {
3162                 uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3163                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3164                 immUniformColor4ub(128, 128, 255, 128);
3165
3166                 for (int a = 0; a < num_segments; a++) {
3167                         float x1 = (float)(points[a * 2] - sfra) / (efra - sfra + 1) * ar->winx;
3168                         float x2 = (float)(points[a * 2 + 1] - sfra + 1) / (efra - sfra + 1) * ar->winx;
3169
3170                         immRecti(pos, x1, 0, x2, 8 * UI_DPI_FAC);
3171                         /* TODO(merwin): use primitive restart to draw multiple rects more efficiently */
3172                 }
3173
3174                 immUnbindProgram();
3175         }
3176 }
3177
3178 /**
3179  * Generate subscriptions for this region.
3180  */
3181 void ED_region_message_subscribe(
3182         bContext *C,
3183         struct WorkSpace *workspace, struct Scene *scene,
3184         struct bScreen *screen, struct ScrArea *sa, struct ARegion *ar,
3185         struct wmMsgBus *mbus)
3186 {
3187         if (ar->gizmo_map != NULL) {
3188                 WM_gizmomap_message_subscribe(C, ar->gizmo_map, ar, mbus);
3189         }
3190
3191         if (!BLI_listbase_is_empty(&ar->uiblocks)) {
3192                 UI_region_message_subscribe(ar, mbus);
3193         }
3194
3195         if (ar->type->message_subscribe != NULL) {
3196                 ar->type->message_subscribe(C, workspace, scene, screen, sa, ar, mbus);
3197         }
3198 }
3199
3200 int ED_region_snap_size_test(const ARegion *ar)
3201 {
3202         /* Use a larger value because toggling scrollbars can jump in size. */
3203         const int snap_match_threshold = 16;
3204         if (ar->type->snap_size != NULL) {
3205                 return ((((ar->sizex - ar->type->snap_size(ar, ar->sizex, 0)) <= snap_match_threshold) << 0) |
3206                         (((ar->sizey - ar->type->snap_size(ar, ar->sizey, 1)) <= snap_match_threshold) << 1));
3207         }
3208         return 0;
3209 }
3210
3211 bool ED_region_snap_size_apply(ARegion *ar, int snap_flag)
3212 {
3213         bool changed = false;
3214         if (ar->type->snap_size != NULL) {
3215                 if (snap_flag & (1 << 0)) {
3216                         short snap_size = ar->type->snap_size(ar, ar->sizex, 0);
3217                         if (snap_size != ar->sizex) {
3218                                 ar->sizex = snap_size;
3219                                 changed = true;
3220                         }
3221                 }
3222                 if (snap_flag & (1 << 1)) {
3223                         short snap_size = ar->type->snap_size(ar, ar->sizey, 1);
3224                         if (snap_size != ar->sizey) {
3225                                 ar->sizey = snap_size;
3226                                 changed = true;
3227                         }
3228                 }
3229         }
3230         return changed;
3231 }