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