Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / interface / view2d.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  * Contributor(s): Blender Foundation, Joshua Leung
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/view2d.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_scene_types.h"
39 #include "DNA_userdef_types.h"
40
41 #include "BLI_utildefines.h"
42 #include "BLI_link_utils.h"
43 #include "BLI_rect.h"
44 #include "BLI_math.h"
45 #include "BLI_memarena.h"
46 #include "BLI_timecode.h"
47
48 #include "BKE_context.h"
49 #include "BKE_screen.h"
50 #include "BKE_global.h"
51
52 #include "GPU_immediate.h"
53 #include "GPU_matrix.h"
54
55 #include "WM_api.h"
56
57 #include "BLF_api.h"
58
59 #include "ED_screen.h"
60
61 #include "UI_interface.h"
62 #include "UI_view2d.h"
63
64 #include "interface_intern.h"
65
66 static void ui_view2d_curRect_validate_resize(View2D *v2d, bool resize, bool mask_scrollers);
67
68 /* *********************************************************************** */
69
70 BLI_INLINE int clamp_float_to_int(const float f)
71 {
72         const float min = INT_MIN;
73         const float max = INT_MAX;
74
75         if (UNLIKELY(f < min)) {
76                 return min;
77         }
78         else if (UNLIKELY(f > max)) {
79                 return max;
80         }
81         else {
82                 return (int)f;
83         }
84 }
85
86 /**
87  * use instead of #BLI_rcti_rctf_copy so we have consistent behavior
88  * with users of #clamp_float_to_int.
89  */
90 BLI_INLINE void clamp_rctf_to_rcti(rcti *dst, const rctf *src)
91 {
92         dst->xmin = clamp_float_to_int(src->xmin);
93         dst->xmax = clamp_float_to_int(src->xmax);
94         dst->ymin = clamp_float_to_int(src->ymin);
95         dst->ymax = clamp_float_to_int(src->ymax);
96 }
97
98
99 /* XXX still unresolved: scrolls hide/unhide vs region mask handling */
100 /* XXX there's V2D_SCROLL_HORIZONTAL_HIDE and V2D_SCROLL_HORIZONTAL_FULLR ... */
101
102 /**
103  * helper to allow scrollbars to dynamically hide
104  * - returns a copy of the scrollbar settings with the flags to display
105  *   horizontal/vertical scrollbars removed
106  * - input scroll value is the v2d->scroll var
107  * - hide flags are set per region at drawtime
108  */
109 static int view2d_scroll_mapped(int scroll)
110 {
111         if (scroll & V2D_SCROLL_HORIZONTAL_FULLR)
112                 scroll &= ~(V2D_SCROLL_HORIZONTAL);
113         if (scroll & V2D_SCROLL_VERTICAL_FULLR)
114                 scroll &= ~(V2D_SCROLL_VERTICAL);
115         return scroll;
116 }
117
118 /* called each time cur changes, to dynamically update masks */
119 static void view2d_masks(View2D *v2d, bool check_scrollers)
120 {
121         int scroll;
122         
123         /* mask - view frame */
124         v2d->mask.xmin = v2d->mask.ymin = 0;
125         v2d->mask.xmax = v2d->winx - 1; /* -1 yes! masks are pixels */
126         v2d->mask.ymax = v2d->winy - 1;
127
128         if (check_scrollers) {
129                 /* check size if hiding flag is set: */
130                 if (v2d->scroll & V2D_SCROLL_HORIZONTAL_HIDE) {
131                         if (!(v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL)) {
132                                 if (BLI_rctf_size_x(&v2d->tot) > BLI_rctf_size_x(&v2d->cur))
133                                         v2d->scroll &= ~V2D_SCROLL_HORIZONTAL_FULLR;
134                                 else
135                                         v2d->scroll |= V2D_SCROLL_HORIZONTAL_FULLR;
136                         }
137                 }
138                 if (v2d->scroll & V2D_SCROLL_VERTICAL_HIDE) {
139                         if (!(v2d->scroll & V2D_SCROLL_SCALE_VERTICAL)) {
140                                 if (BLI_rctf_size_y(&v2d->tot) + 0.01f > BLI_rctf_size_y(&v2d->cur))
141                                         v2d->scroll &= ~V2D_SCROLL_VERTICAL_FULLR;
142                                 else
143                                         v2d->scroll |= V2D_SCROLL_VERTICAL_FULLR;
144                         }
145                 }
146         }
147         
148         scroll = view2d_scroll_mapped(v2d->scroll);
149         
150         /* scrollers shrink mask area, but should be based off regionsize 
151          *      - they can only be on one to two edges of the region they define
152          *      - if they overlap, they must not occupy the corners (which are reserved for other widgets)
153          */
154         if (scroll) {
155                 /* vertical scroller */
156                 if (scroll & V2D_SCROLL_LEFT) {
157                         /* on left-hand edge of region */
158                         v2d->vert = v2d->mask;
159                         v2d->vert.xmax = V2D_SCROLL_WIDTH;
160                         v2d->mask.xmin = v2d->vert.xmax + 1;
161                 }
162                 else if (scroll & V2D_SCROLL_RIGHT) {
163                         /* on right-hand edge of region */
164                         v2d->vert = v2d->mask;
165                         v2d->vert.xmax++; /* one pixel extra... was leaving a minor gap... */
166                         v2d->vert.xmin = v2d->vert.xmax - V2D_SCROLL_WIDTH;
167                         v2d->mask.xmax = v2d->vert.xmin - 1;
168                 }
169                 
170                 /* horizontal scroller */
171                 if (scroll & (V2D_SCROLL_BOTTOM)) {
172                         /* on bottom edge of region */
173                         v2d->hor = v2d->mask;
174                         v2d->hor.ymax = V2D_SCROLL_HEIGHT;
175                         v2d->mask.ymin = v2d->hor.ymax + 1;
176                 }
177                 else if (scroll & V2D_SCROLL_TOP) {
178                         /* on upper edge of region */
179                         v2d->hor = v2d->mask;
180                         v2d->hor.ymin = v2d->hor.ymax - V2D_SCROLL_HEIGHT;
181                         v2d->mask.ymax = v2d->hor.ymin - 1;
182                 }
183                 
184                 /* adjust vertical scroller if there's a horizontal scroller, to leave corner free */
185                 if (scroll & V2D_SCROLL_VERTICAL) {
186                         /* just set y min/max for vertical scroller to y min/max of mask as appropriate */
187                         if (scroll & (V2D_SCROLL_BOTTOM)) {
188                                 /* on bottom edge of region */
189                                 v2d->vert.ymin = v2d->mask.ymin;
190                         }
191                         else if (scroll & V2D_SCROLL_TOP) {
192                                 /* on upper edge of region */
193                                 v2d->vert.ymax = v2d->mask.ymax;
194                         }
195                 }
196         }
197 }
198
199 /* Refresh and Validation */
200
201 /**
202  * Initialize all relevant View2D data (including view rects if first time) and/or refresh mask sizes after view resize
203  * - for some of these presets, it is expected that the region will have defined some
204  *   additional settings necessary for the customization of the 2D viewport to its requirements
205  * - this function should only be called from region init() callbacks, where it is expected that
206  *   this is called before UI_view2d_size_update(), as this one checks that the rects are properly initialized.
207  */
208 void UI_view2d_region_reinit(View2D *v2d, short type, int winx, int winy)
209 {
210         bool tot_changed = false, do_init;
211         uiStyle *style = UI_style_get();
212
213         do_init = (v2d->flag & V2D_IS_INITIALISED) == 0;
214
215         /* see eView2D_CommonViewTypes in UI_view2d.h for available view presets */
216         switch (type) {
217                 /* 'standard view' - optimum setup for 'standard' view behavior,
218                  *  that should be used new views as basis for their
219                  *  own unique View2D settings, which should be used instead of this in most cases...
220                  */
221                 case V2D_COMMONVIEW_STANDARD:
222                 {
223                         /* for now, aspect ratio should be maintained, and zoom is clamped within sane default limits */
224                         v2d->keepzoom = (V2D_KEEPASPECT | V2D_LIMITZOOM);
225                         v2d->minzoom = 0.01f;
226                         v2d->maxzoom = 1000.0f;
227                         
228                         /* tot rect and cur should be same size, and aligned using 'standard' OpenGL coordinates for now 
229                          *      - region can resize 'tot' later to fit other data
230                          *      - keeptot is only within bounds, as strict locking is not that critical
231                          *      - view is aligned for (0,0) -> (winx-1, winy-1) setup
232                          */
233                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_NEG_Y);
234                         v2d->keeptot = V2D_KEEPTOT_BOUNDS;
235                         
236                         if (do_init) {
237                                 v2d->tot.xmin = v2d->tot.ymin = 0.0f;
238                                 v2d->tot.xmax = (float)(winx - 1);
239                                 v2d->tot.ymax = (float)(winy - 1);
240                                 
241                                 v2d->cur = v2d->tot;
242                         }
243                         /* scrollers - should we have these by default? */
244                         /* XXX for now, we don't override this, or set it either! */
245                         break;
246                 }
247                 /* 'list/channel view' - zoom, aspect ratio, and alignment restrictions are set here */
248                 case V2D_COMMONVIEW_LIST:
249                 {
250                         /* zoom + aspect ratio are locked */
251                         v2d->keepzoom = (V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y | V2D_LIMITZOOM | V2D_KEEPASPECT);
252                         v2d->minzoom = v2d->maxzoom = 1.0f;
253                         
254                         /* tot rect has strictly regulated placement, and must only occur in +/- quadrant */
255                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_POS_Y);
256                         v2d->keeptot = V2D_KEEPTOT_STRICT;
257                         tot_changed = do_init;
258                         
259                         /* scroller settings are currently not set here... that is left for regions... */
260                         break;
261                 }
262                 /* 'stack view' - practically the same as list/channel view, except is located in the pos y half instead. 
263                  *  zoom, aspect ratio, and alignment restrictions are set here */
264                 case V2D_COMMONVIEW_STACK:
265                 {
266                         /* zoom + aspect ratio are locked */
267                         v2d->keepzoom = (V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y | V2D_LIMITZOOM | V2D_KEEPASPECT);
268                         v2d->minzoom = v2d->maxzoom = 1.0f;
269                         
270                         /* tot rect has strictly regulated placement, and must only occur in +/+ quadrant */
271                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_NEG_Y);
272                         v2d->keeptot = V2D_KEEPTOT_STRICT;
273                         tot_changed = do_init;
274                         
275                         /* scroller settings are currently not set here... that is left for regions... */
276                         break;
277                 }
278                 /* 'header' regions - zoom, aspect ratio, alignment, and panning restrictions are set here */
279                 case V2D_COMMONVIEW_HEADER:
280                 {
281                         /* zoom + aspect ratio are locked */
282                         v2d->keepzoom = (V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y | V2D_LIMITZOOM | V2D_KEEPASPECT);
283                         v2d->minzoom = v2d->maxzoom = 1.0f;
284                         
285                         if (do_init) {
286                                 v2d->tot.xmin = 0.0f;
287                                 v2d->tot.xmax = winx;
288                                 v2d->tot.ymin = 0.0f;
289                                 v2d->tot.ymax = winy;
290                                 v2d->cur = v2d->tot;
291                                 
292                                 v2d->min[0] = v2d->max[0] = (float)(winx - 1);
293                                 v2d->min[1] = v2d->max[1] = (float)(winy - 1);
294                         }
295                         /* tot rect has strictly regulated placement, and must only occur in +/+ quadrant */
296                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_NEG_Y);
297                         v2d->keeptot = V2D_KEEPTOT_STRICT;
298                         tot_changed = do_init;
299                         
300                         /* panning in y-axis is prohibited */
301                         v2d->keepofs = V2D_LOCKOFS_Y;
302                         
303                         /* absolutely no scrollers allowed */
304                         v2d->scroll = 0;
305                         break;
306                 }
307                 /* panels view, with horizontal/vertical align */
308                 case V2D_COMMONVIEW_PANELS_UI:
309                 {
310                         
311                         /* for now, aspect ratio should be maintained, and zoom is clamped within sane default limits */
312                         v2d->keepzoom = (V2D_KEEPASPECT | V2D_LIMITZOOM | V2D_KEEPZOOM);
313                         v2d->minzoom = 0.5f;
314                         v2d->maxzoom = 2.0f;
315                         
316                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_POS_Y);
317                         v2d->keeptot = V2D_KEEPTOT_BOUNDS;
318                         
319                         /* note, scroll is being flipped in ED_region_panels() drawing */
320                         v2d->scroll |= (V2D_SCROLL_HORIZONTAL_HIDE | V2D_SCROLL_VERTICAL_HIDE);
321
322                         /* initialize without scroll bars (interferes with zoom level see: T47047) */
323                         if (do_init) {
324                                 v2d->scroll |= (V2D_SCROLL_VERTICAL_FULLR | V2D_SCROLL_HORIZONTAL_FULLR);
325                         }
326
327                         if (do_init) {
328                                 float panelzoom = (style) ? style->panelzoom : 1.0f;
329                                 
330                                 v2d->tot.xmin = 0.0f;
331                                 v2d->tot.xmax = winx;
332                                 
333                                 v2d->tot.ymax = 0.0f;
334                                 v2d->tot.ymin = -winy;
335                                 
336                                 v2d->cur.xmin = 0.0f;
337                                 v2d->cur.xmax = (winx) * panelzoom;
338                                 
339                                 v2d->cur.ymax = 0.0f;
340                                 v2d->cur.ymin = (-winy) * panelzoom;
341                         }
342                         break;
343                 }
344                 /* other view types are completely defined using their own settings already */
345                 default:
346                         /* we don't do anything here, as settings should be fine, but just make sure that rect */
347                         break;
348         }
349         
350         /* set initialized flag so that View2D doesn't get reinitialised next time again */
351         v2d->flag |= V2D_IS_INITIALISED;
352
353         /* store view size */
354         v2d->winx = winx;
355         v2d->winy = winy;
356         
357         /* set masks (always do), but leave scroller scheck to totrect_set */
358         view2d_masks(v2d, 0);
359         
360         /* set 'tot' rect before setting cur? */
361         /* XXX confusing stuff here still - I made this function not check scroller hide - that happens in totrect_set */
362         if (tot_changed)
363                 UI_view2d_totRect_set_resize(v2d, winx, winy, !do_init);
364         else
365                 ui_view2d_curRect_validate_resize(v2d, !do_init, 0);
366         
367 }
368
369 /**
370  * Ensure View2D rects remain in a viable configuration
371  * 'cur' is not allowed to be: larger than max, smaller than min, or outside of 'tot'
372  */
373 // XXX pre2.5 -> this used to be called  test_view2d()
374 static void ui_view2d_curRect_validate_resize(View2D *v2d, bool resize, bool mask_scrollers)
375 {
376         float totwidth, totheight, curwidth, curheight, width, height;
377         float winx, winy;
378         rctf *cur, *tot;
379         
380         /* use mask as size of region that View2D resides in, as it takes into account
381          * scrollbars already - keep in sync with zoomx/zoomy in view_zoomstep_apply_ex! */
382         winx = (float)(BLI_rcti_size_x(&v2d->mask) + 1);
383         winy = (float)(BLI_rcti_size_y(&v2d->mask) + 1);
384         
385         /* get pointers to rcts for less typing */
386         cur = &v2d->cur;
387         tot = &v2d->tot;
388         
389         /* we must satisfy the following constraints (in decreasing order of importance):
390          *      - alignment restrictions are respected
391          *      - cur must not fall outside of tot
392          *      - axis locks (zoom and offset) must be maintained
393          *      - zoom must not be excessive (check either sizes or zoom values)
394          *      - aspect ratio should be respected (NOTE: this is quite closely related to zoom too)
395          */
396         
397         /* Step 1: if keepzoom, adjust the sizes of the rects only
398          *      - firstly, we calculate the sizes of the rects
399          *      - curwidth and curheight are saved as reference... modify width and height values here
400          */
401         totwidth  = BLI_rctf_size_x(tot);
402         totheight = BLI_rctf_size_y(tot);
403         /* keep in sync with zoomx/zoomy in view_zoomstep_apply_ex! */
404         curwidth  = width  = BLI_rctf_size_x(cur);
405         curheight = height = BLI_rctf_size_y(cur);
406         
407         /* if zoom is locked, size on the appropriate axis is reset to mask size */
408         if (v2d->keepzoom & V2D_LOCKZOOM_X)
409                 width = winx;
410         if (v2d->keepzoom & V2D_LOCKZOOM_Y)
411                 height = winy;
412                 
413         /* values used to divide, so make it safe 
414          * NOTE: width and height must use FLT_MIN instead of 1, otherwise it is impossible to
415          *       get enough resolution in Graph Editor for editing some curves
416          */
417         if (width < FLT_MIN) width = 1;
418         if (height < FLT_MIN) height = 1;
419         if (winx < 1) winx = 1;
420         if (winy < 1) winy = 1;
421         
422         /* V2D_LIMITZOOM indicates that zoom level should be preserved when the window size changes */
423         if (resize && (v2d->keepzoom & V2D_KEEPZOOM)) {
424                 float zoom, oldzoom;
425
426                 if ((v2d->keepzoom & V2D_LOCKZOOM_X) == 0) {
427                         zoom = winx / width;
428                         oldzoom = v2d->oldwinx / curwidth;
429
430                         if (oldzoom != zoom)
431                                 width *= zoom / oldzoom;
432                 }
433
434                 if ((v2d->keepzoom & V2D_LOCKZOOM_Y) == 0) {
435                         zoom = winy / height;
436                         oldzoom = v2d->oldwiny / curheight;
437
438                         if (oldzoom != zoom)
439                                 height *= zoom / oldzoom;
440                 }
441         }
442         /* keepzoom (V2D_LIMITZOOM set), indicates that zoom level on each axis must not exceed limits 
443          * NOTE: in general, it is not expected that the lock-zoom will be used in conjunction with this
444          */
445         else if (v2d->keepzoom & V2D_LIMITZOOM) {
446                 
447                 /* check if excessive zoom on x-axis */
448                 if ((v2d->keepzoom & V2D_LOCKZOOM_X) == 0) {
449                         const float zoom = winx / width;
450                         if (zoom < v2d->minzoom) {
451                                 width = winx / v2d->minzoom;
452                         }
453                         else if (zoom > v2d->maxzoom) {
454                                 width = winx / v2d->maxzoom;
455                         }
456                 }
457                 
458                 /* check if excessive zoom on y-axis */
459                 if ((v2d->keepzoom & V2D_LOCKZOOM_Y) == 0) {
460                         const float zoom = winy / height;
461                         if (zoom < v2d->minzoom) {
462                                 height = winy / v2d->minzoom;
463                         }
464                         else if (zoom > v2d->maxzoom) {
465                                 height = winy / v2d->maxzoom;
466                         }
467                 }
468         }
469         else {
470                 /* make sure sizes don't exceed that of the min/max sizes (even though we're not doing zoom clamping) */
471                 CLAMP(width, v2d->min[0], v2d->max[0]);
472                 CLAMP(height, v2d->min[1], v2d->max[1]);
473         }
474         
475         /* check if we should restore aspect ratio (if view size changed) */
476         if (v2d->keepzoom & V2D_KEEPASPECT) {
477                 bool do_x = false, do_y = false, do_cur /* , do_win */ /* UNUSED */;
478                 float curRatio, winRatio;
479                 
480                 /* when a window edge changes, the aspect ratio can't be used to
481                  * find which is the best new 'cur' rect. thats why it stores 'old' 
482                  */
483                 if (winx != v2d->oldwinx) do_x = true;
484                 if (winy != v2d->oldwiny) do_y = true;
485                 
486                 curRatio = height / width;
487                 winRatio = winy / winx;
488                 
489                 /* both sizes change (area/region maximized)  */
490                 if (do_x == do_y) {
491                         if (do_x && do_y) {
492                                 /* here is 1,1 case, so all others must be 0,0 */
493                                 if (fabsf(winx - v2d->oldwinx) > fabsf(winy - v2d->oldwiny)) do_y = false;
494                                 else do_x = false;
495                         }
496                         else if (winRatio > curRatio) {
497                                 do_x = false;
498                         }
499                         else {
500                                 do_x = true;
501                         }
502                 }
503                 do_cur = do_x;
504                 /* do_win = do_y; */ /* UNUSED */
505                 
506                 if (do_cur) {
507                         if ((v2d->keeptot == V2D_KEEPTOT_STRICT) && (winx != v2d->oldwinx)) {
508                                 /* special exception for Outliner (and later channel-lists):
509                                  *  - The view may be moved left to avoid contents being pushed out of view when view shrinks.
510                                  *      - The keeptot code will make sure cur->xmin will not be less than tot->xmin (which cannot be allowed)
511                                  *      - width is not adjusted for changed ratios here...
512                                  */
513                                 if (winx < v2d->oldwinx) {
514                                         float temp = v2d->oldwinx - winx;
515                                         
516                                         cur->xmin -= temp;
517                                         cur->xmax -= temp;
518                                         
519                                         /* width does not get modified, as keepaspect here is just set to make 
520                                          * sure visible area adjusts to changing view shape! 
521                                          */
522                                 }
523                         }
524                         else {
525                                 /* portrait window: correct for x */
526                                 width = height / winRatio;
527                         }
528                 }
529                 else {
530                         if ((v2d->keeptot == V2D_KEEPTOT_STRICT) && (winy != v2d->oldwiny)) {
531                                 /* special exception for Outliner (and later channel-lists):
532                                  *      - Currently, no actions need to be taken here...
533                                  */
534
535                                 if (winy < v2d->oldwiny) {
536                                         float temp = v2d->oldwiny - winy;
537                                         
538                                         if (v2d->align & V2D_ALIGN_NO_NEG_Y) {
539                                                 cur->ymin -= temp;
540                                                 cur->ymax -= temp;
541                                         }
542                                         else { /* Assume V2D_ALIGN_NO_POS_Y or combination */
543                                                 cur->ymin += temp;
544                                                 cur->ymax += temp;
545                                         }
546                                 }
547
548                         }
549                         else {
550                                 /* landscape window: correct for y */
551                                 height = width * winRatio;
552                         }
553                 }
554                 
555                 /* store region size for next time */
556                 v2d->oldwinx = (short)winx;
557                 v2d->oldwiny = (short)winy;
558         }
559         
560         /* Step 2: apply new sizes to cur rect, but need to take into account alignment settings here... */
561         if ((width != curwidth) || (height != curheight)) {
562                 float temp, dh;
563                 
564                 /* resize from centerpoint, unless otherwise specified */
565                 if (width != curwidth) {
566                         if (v2d->keepofs & V2D_LOCKOFS_X) {
567                                 cur->xmax += width - BLI_rctf_size_x(cur);
568                         }
569                         else if (v2d->keepofs & V2D_KEEPOFS_X) {
570                                 if (v2d->align & V2D_ALIGN_NO_POS_X)
571                                         cur->xmin -= width - BLI_rctf_size_x(cur);
572                                 else
573                                         cur->xmax += width - BLI_rctf_size_x(cur);
574                         }
575                         else {
576                                 temp = BLI_rctf_cent_x(cur);
577                                 dh = width * 0.5f;
578                                 
579                                 cur->xmin = temp - dh;
580                                 cur->xmax = temp + dh;
581                         }
582                 }
583                 if (height != curheight) {
584                         if (v2d->keepofs & V2D_LOCKOFS_Y) {
585                                 cur->ymax += height - BLI_rctf_size_y(cur);
586                         }
587                         else if (v2d->keepofs & V2D_KEEPOFS_Y) {
588                                 if (v2d->align & V2D_ALIGN_NO_POS_Y)
589                                         cur->ymin -= height - BLI_rctf_size_y(cur);
590                                 else
591                                         cur->ymax += height - BLI_rctf_size_y(cur);
592                         }
593                         else {
594                                 temp = BLI_rctf_cent_y(cur);
595                                 dh = height * 0.5f;
596                                 
597                                 cur->ymin = temp - dh;
598                                 cur->ymax = temp + dh;
599                         }
600                 }
601         }
602         
603         /* Step 3: adjust so that it doesn't fall outside of bounds of 'tot' */
604         if (v2d->keeptot) {
605                 float temp, diff;
606                 
607                 /* recalculate extents of cur */
608                 curwidth  = BLI_rctf_size_x(cur);
609                 curheight = BLI_rctf_size_y(cur);
610                 
611                 /* width */
612                 if ((curwidth > totwidth) && !(v2d->keepzoom & (V2D_KEEPZOOM | V2D_LOCKZOOM_X | V2D_LIMITZOOM))) {
613                         /* if zoom doesn't have to be maintained, just clamp edges */
614                         if (cur->xmin < tot->xmin) cur->xmin = tot->xmin;
615                         if (cur->xmax > tot->xmax) cur->xmax = tot->xmax;
616                 }
617                 else if (v2d->keeptot == V2D_KEEPTOT_STRICT) {
618                         /* This is an exception for the outliner (and later channel-lists, headers) 
619                          *      - must clamp within tot rect (absolutely no excuses)
620                          *      --> therefore, cur->xmin must not be less than tot->xmin
621                          */
622                         if (cur->xmin < tot->xmin) {
623                                 /* move cur across so that it sits at minimum of tot */
624                                 temp = tot->xmin - cur->xmin;
625                                 
626                                 cur->xmin += temp;
627                                 cur->xmax += temp;
628                         }
629                         else if (cur->xmax > tot->xmax) {
630                                 /* - only offset by difference of cur-xmax and tot-xmax if that would not move 
631                                  *  cur-xmin to lie past tot-xmin
632                                  * - otherwise, simply shift to tot-xmin???
633                                  */
634                                 temp = cur->xmax - tot->xmax;
635                                 
636                                 if ((cur->xmin - temp) < tot->xmin) {
637                                         /* only offset by difference from cur-min and tot-min */
638                                         temp = cur->xmin - tot->xmin;
639                                         
640                                         cur->xmin -= temp;
641                                         cur->xmax -= temp;
642                                 }
643                                 else {
644                                         cur->xmin -= temp;
645                                         cur->xmax -= temp;
646                                 }
647                         }
648                 }
649                 else {
650                         /* This here occurs when:
651                          *  - width too big, but maintaining zoom (i.e. widths cannot be changed)
652                          *      - width is OK, but need to check if outside of boundaries
653                          * 
654                          * So, resolution is to just shift view by the gap between the extremities.
655                          * We favour moving the 'minimum' across, as that's origin for most things
656                          * (XXX - in the past, max was favored... if there are bugs, swap!)
657                          */
658                         if ((cur->xmin < tot->xmin) && (cur->xmax > tot->xmax)) {
659                                 /* outside boundaries on both sides, so take middle-point of tot, and place in balanced way */
660                                 temp = BLI_rctf_cent_x(tot);
661                                 diff = curwidth * 0.5f;
662                                 
663                                 cur->xmin = temp - diff;
664                                 cur->xmax = temp + diff;
665                         }
666                         else if (cur->xmin < tot->xmin) {
667                                 /* move cur across so that it sits at minimum of tot */
668                                 temp = tot->xmin - cur->xmin;
669                                 
670                                 cur->xmin += temp;
671                                 cur->xmax += temp;
672                         }
673                         else if (cur->xmax > tot->xmax) {
674                                 /* - only offset by difference of cur-xmax and tot-xmax if that would not move 
675                                  *  cur-xmin to lie past tot-xmin
676                                  * - otherwise, simply shift to tot-xmin???
677                                  */
678                                 temp = cur->xmax - tot->xmax;
679                                 
680                                 if ((cur->xmin - temp) < tot->xmin) {
681                                         /* only offset by difference from cur-min and tot-min */
682                                         temp = cur->xmin - tot->xmin;
683                                         
684                                         cur->xmin -= temp;
685                                         cur->xmax -= temp;
686                                 }
687                                 else {
688                                         cur->xmin -= temp;
689                                         cur->xmax -= temp;
690                                 }
691                         }
692                 }
693                 
694                 /* height */
695                 if ((curheight > totheight) && !(v2d->keepzoom & (V2D_KEEPZOOM | V2D_LOCKZOOM_Y | V2D_LIMITZOOM))) {
696                         /* if zoom doesn't have to be maintained, just clamp edges */
697                         if (cur->ymin < tot->ymin) cur->ymin = tot->ymin;
698                         if (cur->ymax > tot->ymax) cur->ymax = tot->ymax;
699                 }
700                 else {
701                         /* This here occurs when:
702                          *  - height too big, but maintaining zoom (i.e. heights cannot be changed)
703                          *      - height is OK, but need to check if outside of boundaries
704                          * 
705                          * So, resolution is to just shift view by the gap between the extremities.
706                          * We favour moving the 'minimum' across, as that's origin for most things
707                          */
708                         if ((cur->ymin < tot->ymin) && (cur->ymax > tot->ymax)) {
709                                 /* outside boundaries on both sides, so take middle-point of tot, and place in balanced way */
710                                 temp = BLI_rctf_cent_y(tot);
711                                 diff = curheight * 0.5f;
712                                 
713                                 cur->ymin = temp - diff;
714                                 cur->ymax = temp + diff;
715                         }
716                         else if (cur->ymin < tot->ymin) {
717                                 /* there's still space remaining, so shift up */
718                                 temp = tot->ymin - cur->ymin;
719                                 
720                                 cur->ymin += temp;
721                                 cur->ymax += temp;
722                         }
723                         else if (cur->ymax > tot->ymax) {
724                                 /* there's still space remaining, so shift down */
725                                 temp = cur->ymax - tot->ymax;
726                                 
727                                 cur->ymin -= temp;
728                                 cur->ymax -= temp;
729                         }
730                 }
731         }
732         
733         /* Step 4: Make sure alignment restrictions are respected */
734         if (v2d->align) {
735                 /* If alignment flags are set (but keeptot is not), they must still be respected, as although
736                  * they don't specify any particular bounds to stay within, they do define ranges which are 
737                  * invalid.
738                  *
739                  * Here, we only check to make sure that on each axis, the 'cur' rect doesn't stray into these 
740                  * invalid zones, otherwise we offset.
741                  */
742                 
743                 /* handle width - posx and negx flags are mutually exclusive, so watch out */
744                 if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
745                         /* width is in negative-x half */
746                         if (v2d->cur.xmax > 0) {
747                                 v2d->cur.xmin -= v2d->cur.xmax;
748                                 v2d->cur.xmax = 0.0f;
749                         }
750                 }
751                 else if ((v2d->align & V2D_ALIGN_NO_NEG_X) && !(v2d->align & V2D_ALIGN_NO_POS_X)) {
752                         /* width is in positive-x half */
753                         if (v2d->cur.xmin < 0) {
754                                 v2d->cur.xmax -= v2d->cur.xmin;
755                                 v2d->cur.xmin = 0.0f;
756                         }
757                 }
758                 
759                 /* handle height - posx and negx flags are mutually exclusive, so watch out */
760                 if ((v2d->align & V2D_ALIGN_NO_POS_Y) && !(v2d->align & V2D_ALIGN_NO_NEG_Y)) {
761                         /* height is in negative-y half */
762                         if (v2d->cur.ymax > 0) {
763                                 v2d->cur.ymin -= v2d->cur.ymax;
764                                 v2d->cur.ymax = 0.0f;
765                         }
766                 }
767                 else if ((v2d->align & V2D_ALIGN_NO_NEG_Y) && !(v2d->align & V2D_ALIGN_NO_POS_Y)) {
768                         /* height is in positive-y half */
769                         if (v2d->cur.ymin < 0) {
770                                 v2d->cur.ymax -= v2d->cur.ymin;
771                                 v2d->cur.ymin = 0.0f;
772                         }
773                 }
774         }
775         
776         /* set masks */
777         view2d_masks(v2d, mask_scrollers);
778 }
779
780 void UI_view2d_curRect_validate(View2D *v2d)
781 {
782         ui_view2d_curRect_validate_resize(v2d, 0, 1);
783 }
784
785 /* ------------------ */
786
787 /* Called by menus to activate it, or by view2d operators to make sure 'related' views stay in synchrony */
788 void UI_view2d_sync(bScreen *screen, ScrArea *area, View2D *v2dcur, int flag)
789 {
790         ScrArea *sa;
791         ARegion *ar;
792         
793         /* don't continue if no view syncing to be done */
794         if ((v2dcur->flag & (V2D_VIEWSYNC_SCREEN_TIME | V2D_VIEWSYNC_AREA_VERTICAL)) == 0)
795                 return;
796                 
797         /* check if doing within area syncing (i.e. channels/vertical) */
798         if ((v2dcur->flag & V2D_VIEWSYNC_AREA_VERTICAL) && (area)) {
799                 for (ar = area->regionbase.first; ar; ar = ar->next) {
800                         /* don't operate on self */
801                         if (v2dcur != &ar->v2d) {
802                                 /* only if view has vertical locks enabled */
803                                 if (ar->v2d.flag & V2D_VIEWSYNC_AREA_VERTICAL) {
804                                         if (flag == V2D_LOCK_COPY) {
805                                                 /* other views with locks on must copy active */
806                                                 ar->v2d.cur.ymin = v2dcur->cur.ymin;
807                                                 ar->v2d.cur.ymax = v2dcur->cur.ymax;
808                                         }
809                                         else { /* V2D_LOCK_SET */
810                                                    /* active must copy others */
811                                                 v2dcur->cur.ymin = ar->v2d.cur.ymin;
812                                                 v2dcur->cur.ymax = ar->v2d.cur.ymax;
813                                         }
814                                         
815                                         /* region possibly changed, so refresh */
816                                         ED_region_tag_redraw(ar);
817                                 }
818                         }
819                 }
820         }
821         
822         /* check if doing whole screen syncing (i.e. time/horizontal) */
823         if ((v2dcur->flag & V2D_VIEWSYNC_SCREEN_TIME) && (screen)) {
824                 for (sa = screen->areabase.first; sa; sa = sa->next) {
825                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
826                                 /* don't operate on self */
827                                 if (v2dcur != &ar->v2d) {
828                                         /* only if view has horizontal locks enabled */
829                                         if (ar->v2d.flag & V2D_VIEWSYNC_SCREEN_TIME) {
830                                                 if (flag == V2D_LOCK_COPY) {
831                                                         /* other views with locks on must copy active */
832                                                         ar->v2d.cur.xmin = v2dcur->cur.xmin;
833                                                         ar->v2d.cur.xmax = v2dcur->cur.xmax;
834                                                 }
835                                                 else { /* V2D_LOCK_SET */
836                                                            /* active must copy others */
837                                                         v2dcur->cur.xmin = ar->v2d.cur.xmin;
838                                                         v2dcur->cur.xmax = ar->v2d.cur.xmax;
839                                                 }
840                                                 
841                                                 /* region possibly changed, so refresh */
842                                                 ED_region_tag_redraw(ar);
843                                         }
844                                 }
845                         }
846                 }
847         }
848 }
849
850
851 /**
852  * Restore 'cur' rect to standard orientation (i.e. optimal maximum view of tot)
853  * This does not take into account if zooming the view on an axis will improve the view (if allowed)
854  */
855 void UI_view2d_curRect_reset(View2D *v2d)
856 {
857         float width, height;
858         
859         /* assume width and height of 'cur' rect by default, should be same size as mask */
860         width  = (float)(BLI_rcti_size_x(&v2d->mask) + 1);
861         height = (float)(BLI_rcti_size_y(&v2d->mask) + 1);
862         
863         /* handle width - posx and negx flags are mutually exclusive, so watch out */
864         if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
865                 /* width is in negative-x half */
866                 v2d->cur.xmin = -width;
867                 v2d->cur.xmax = 0.0f;
868         }
869         else if ((v2d->align & V2D_ALIGN_NO_NEG_X) && !(v2d->align & V2D_ALIGN_NO_POS_X)) {
870                 /* width is in positive-x half */
871                 v2d->cur.xmin = 0.0f;
872                 v2d->cur.xmax = width;
873         }
874         else {
875                 /* width is centered around (x == 0) */
876                 const float dx = width / 2.0f;
877                 
878                 v2d->cur.xmin = -dx;
879                 v2d->cur.xmax = dx;
880         }
881         
882         /* handle height - posx and negx flags are mutually exclusive, so watch out */
883         if ((v2d->align & V2D_ALIGN_NO_POS_Y) && !(v2d->align & V2D_ALIGN_NO_NEG_Y)) {
884                 /* height is in negative-y half */
885                 v2d->cur.ymin = -height;
886                 v2d->cur.ymax = 0.0f;
887         }
888         else if ((v2d->align & V2D_ALIGN_NO_NEG_Y) && !(v2d->align & V2D_ALIGN_NO_POS_Y)) {
889                 /* height is in positive-y half */
890                 v2d->cur.ymin = 0.0f;
891                 v2d->cur.ymax = height;
892         }
893         else {
894                 /* height is centered around (y == 0) */
895                 const float dy = height / 2.0f;
896                 
897                 v2d->cur.ymin = -dy;
898                 v2d->cur.ymax = dy;
899         }
900 }
901
902 /* ------------------ */
903
904 /* Change the size of the maximum viewable area (i.e. 'tot' rect) */
905 void UI_view2d_totRect_set_resize(View2D *v2d, int width, int height, bool resize)
906 {
907 //      int scroll = view2d_scroll_mapped(v2d->scroll);
908         
909         /* don't do anything if either value is 0 */
910         width = abs(width);
911         height = abs(height);
912         
913         /* hrumf! */
914         /* XXX: there are work arounds for this in the panel and file browse code. */
915         /* round to int, because this is called with width + V2D_SCROLL_WIDTH */
916 //      if (scroll & V2D_SCROLL_HORIZONTAL)
917 //              width -= (int)V2D_SCROLL_WIDTH;
918 //      if (scroll & V2D_SCROLL_VERTICAL)
919 //              height -= (int)V2D_SCROLL_HEIGHT;
920         
921         if (ELEM(0, width, height)) {
922                 if (G.debug & G_DEBUG)
923                         printf("Error: View2D totRect set exiting: v2d=%p width=%d height=%d\n", (void *)v2d, width, height);  // XXX temp debug info
924                 return;
925         }
926         
927         /* handle width - posx and negx flags are mutually exclusive, so watch out */
928         if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
929                 /* width is in negative-x half */
930                 v2d->tot.xmin = (float)-width;
931                 v2d->tot.xmax = 0.0f;
932         }
933         else if ((v2d->align & V2D_ALIGN_NO_NEG_X) && !(v2d->align & V2D_ALIGN_NO_POS_X)) {
934                 /* width is in positive-x half */
935                 v2d->tot.xmin = 0.0f;
936                 v2d->tot.xmax = (float)width;
937         }
938         else {
939                 /* width is centered around (x == 0) */
940                 const float dx = (float)width / 2.0f;
941                 
942                 v2d->tot.xmin = -dx;
943                 v2d->tot.xmax = dx;
944         }
945         
946         /* handle height - posx and negx flags are mutually exclusive, so watch out */
947         if ((v2d->align & V2D_ALIGN_NO_POS_Y) && !(v2d->align & V2D_ALIGN_NO_NEG_Y)) {
948                 /* height is in negative-y half */
949                 v2d->tot.ymin = (float)-height;
950                 v2d->tot.ymax = 0.0f;
951         }
952         else if ((v2d->align & V2D_ALIGN_NO_NEG_Y) && !(v2d->align & V2D_ALIGN_NO_POS_Y)) {
953                 /* height is in positive-y half */
954                 v2d->tot.ymin = 0.0f;
955                 v2d->tot.ymax = (float)height;
956         }
957         else {
958                 /* height is centered around (y == 0) */
959                 const float dy = (float)height / 2.0f;
960                 
961                 v2d->tot.ymin = -dy;
962                 v2d->tot.ymax = dy;
963         }
964         
965         /* make sure that 'cur' rect is in a valid state as a result of these changes */
966         ui_view2d_curRect_validate_resize(v2d, resize, 1);
967         
968 }
969
970 void UI_view2d_totRect_set(View2D *v2d, int width, int height)
971 {
972         int scroll = view2d_scroll_mapped(v2d->scroll);
973
974         UI_view2d_totRect_set_resize(v2d, width, height, 0);
975         
976         /* solve bad recursion... if scroller state changed, mask is different, so you get different rects */
977         if (scroll != view2d_scroll_mapped(v2d->scroll)) {
978                 UI_view2d_totRect_set_resize(v2d, width, height, 0);
979         }
980         
981 }
982
983 bool UI_view2d_tab_set(View2D *v2d, int tab)
984 {
985         float default_offset[2] = {0.0f, 0.0f};
986         float *offset, *new_offset;
987         bool changed = false;
988
989         /* if tab changed, change offset */
990         if (tab != v2d->tab_cur && v2d->tab_offset) {
991                 if (tab < v2d->tab_num)
992                         offset = &v2d->tab_offset[tab * 2];
993                 else
994                         offset = default_offset;
995
996                 v2d->cur.xmax += offset[0] - v2d->cur.xmin;
997                 v2d->cur.xmin = offset[0];
998
999                 v2d->cur.ymin += offset[1] - v2d->cur.ymax;
1000                 v2d->cur.ymax = offset[1];
1001
1002                 /* validation should happen in subsequent totRect_set */
1003
1004                 changed = true;
1005         }
1006
1007         /* resize array if needed */
1008         if (tab >= v2d->tab_num) {
1009                 new_offset = MEM_callocN(sizeof(float) * (tab + 1) * 2, "view2d tab offset");
1010
1011                 if (v2d->tab_offset) {
1012                         memcpy(new_offset, v2d->tab_offset, sizeof(float) * v2d->tab_num * 2);
1013                         MEM_freeN(v2d->tab_offset);
1014                 }
1015
1016                 v2d->tab_offset = new_offset;
1017                 v2d->tab_num = tab + 1;
1018         }
1019
1020         /* set current tab and offset */
1021         v2d->tab_cur = tab;
1022         v2d->tab_offset[2 * tab + 0] = v2d->cur.xmin;
1023         v2d->tab_offset[2 * tab + 1] = v2d->cur.ymax;
1024
1025         return changed;
1026 }
1027
1028 void UI_view2d_zoom_cache_reset(void)
1029 {
1030         /* TODO(sergey): This way we avoid threading conflict with VSE rendering
1031          * text strip. But ideally we want to make glyph cache to be fully safe
1032          * for threading.
1033          */
1034         if (G.is_rendering) {
1035                 return;
1036         }
1037         /* While scaling we can accumulate fonts at many sizes (~20 or so).
1038          * Not an issue with embedded font, but can use over 500Mb with i18n ones! See [#38244]. */
1039
1040         /* note: only some views draw text, we could check for this case to avoid clearning cache */
1041         BLF_cache_clear();
1042 }
1043
1044 /* *********************************************************************** */
1045 /* View Matrix Setup */
1046
1047 /* mapping function to ensure 'cur' draws extended over the area where sliders are */
1048 static void view2d_map_cur_using_mask(View2D *v2d, rctf *curmasked)
1049 {
1050         *curmasked = v2d->cur;
1051         
1052         if (view2d_scroll_mapped(v2d->scroll)) {
1053                 float sizex = BLI_rcti_size_x(&v2d->mask);
1054                 float sizey = BLI_rcti_size_y(&v2d->mask);
1055                 
1056                 /* prevent tiny or narrow regions to get invalid coordinates - mask can get negative even... */
1057                 if (sizex > 0.0f && sizey > 0.0f) {
1058                         float dx = BLI_rctf_size_x(&v2d->cur) / (sizex + 1);
1059                         float dy = BLI_rctf_size_y(&v2d->cur) / (sizey + 1);
1060                         
1061                         if (v2d->mask.xmin != 0)
1062                                 curmasked->xmin -= dx * (float)v2d->mask.xmin;
1063                         if (v2d->mask.xmax + 1 != v2d->winx)
1064                                 curmasked->xmax += dx * (float)(v2d->winx - v2d->mask.xmax - 1);
1065                         
1066                         if (v2d->mask.ymin != 0)
1067                                 curmasked->ymin -= dy * (float)v2d->mask.ymin;
1068                         if (v2d->mask.ymax + 1 != v2d->winy)
1069                                 curmasked->ymax += dy * (float)(v2d->winy - v2d->mask.ymax - 1);
1070                 }
1071         }
1072 }
1073
1074 /* Set view matrices to use 'cur' rect as viewing frame for View2D drawing */
1075 void UI_view2d_view_ortho(View2D *v2d)
1076 {
1077         rctf curmasked;
1078         const int sizex = BLI_rcti_size_x(&v2d->mask);
1079         const int sizey = BLI_rcti_size_y(&v2d->mask);
1080         const float eps = 0.001f;
1081         float xofs = 0.0f, yofs = 0.0f;
1082         
1083         /* pixel offsets (-GLA_PIXEL_OFS) are needed to get 1:1 correspondence with pixels for smooth UI drawing,
1084          * but only applied where requested
1085          */
1086         /* XXX brecht: instead of zero at least use a tiny offset, otherwise
1087          * pixel rounding is effectively random due to float inaccuracy */
1088         if (sizex > 0)
1089                 xofs = eps * BLI_rctf_size_x(&v2d->cur) / sizex;
1090         if (sizey > 0)
1091                 yofs = eps * BLI_rctf_size_y(&v2d->cur) / sizey;
1092         
1093         /* apply mask-based adjustments to cur rect (due to scrollers), to eliminate scaling artifacts */
1094         view2d_map_cur_using_mask(v2d, &curmasked);
1095
1096         BLI_rctf_translate(&curmasked, -xofs, -yofs);
1097         
1098         /* XXX ton: this flag set by outliner, for icons */
1099         if (v2d->flag & V2D_PIXELOFS_X) {
1100                 curmasked.xmin = floorf(curmasked.xmin) - (eps + xofs);
1101                 curmasked.xmax = floorf(curmasked.xmax) - (eps + xofs);
1102         }
1103         if (v2d->flag & V2D_PIXELOFS_Y) {
1104                 curmasked.ymin = floorf(curmasked.ymin) - (eps + yofs);
1105                 curmasked.ymax = floorf(curmasked.ymax) - (eps + yofs);
1106         }
1107         
1108         /* set matrix on all appropriate axes */
1109         wmOrtho2(curmasked.xmin, curmasked.xmax, curmasked.ymin, curmasked.ymax);
1110 }
1111
1112 /**
1113  * Set view matrices to only use one axis of 'cur' only
1114  *
1115  * \param xaxis: if non-zero, only use cur x-axis, otherwise use cur-yaxis (mostly this will be used for x)
1116  */
1117 void UI_view2d_view_orthoSpecial(ARegion *ar, View2D *v2d, const bool xaxis)
1118 {
1119         rctf curmasked;
1120         float xofs, yofs;
1121         
1122         /* pixel offsets (-GLA_PIXEL_OFS) are needed to get 1:1 correspondence with pixels for smooth UI drawing,
1123          * but only applied where requested
1124          */
1125         /* XXX temp (ton) */
1126         xofs = 0.0f; // (v2d->flag & V2D_PIXELOFS_X) ? GLA_PIXEL_OFS : 0.0f;
1127         yofs = 0.0f; // (v2d->flag & V2D_PIXELOFS_Y) ? GLA_PIXEL_OFS : 0.0f;
1128         
1129         /* apply mask-based adjustments to cur rect (due to scrollers), to eliminate scaling artifacts */
1130         view2d_map_cur_using_mask(v2d, &curmasked);
1131         
1132         /* only set matrix with 'cur' coordinates on relevant axes */
1133         if (xaxis)
1134                 wmOrtho2(curmasked.xmin - xofs, curmasked.xmax - xofs, -yofs, ar->winy - yofs);
1135         else
1136                 wmOrtho2(-xofs, ar->winx - xofs, curmasked.ymin - yofs, curmasked.ymax - yofs);
1137
1138
1139
1140 /* Restore view matrices after drawing */
1141 void UI_view2d_view_restore(const bContext *C)
1142 {
1143         ARegion *ar = CTX_wm_region(C);
1144         int width  = BLI_rcti_size_x(&ar->winrct) + 1;
1145         int height = BLI_rcti_size_y(&ar->winrct) + 1;
1146         
1147         wmOrtho2(0.0f, (float)width, 0.0f, (float)height);
1148         gpuLoadIdentity();
1149         
1150         //      ED_region_pixelspace(CTX_wm_region(C));
1151 }
1152
1153 /* *********************************************************************** */
1154 /* Gridlines */
1155
1156 /* View2DGrid is typedef'd in UI_view2d.h */
1157 struct View2DGrid {
1158         float dx, dy;           /* stepsize (in pixels) between gridlines */
1159         float startx, starty;   /* initial coordinates to start drawing grid from */
1160         int powerx, powery;     /* step as power of 10 */
1161 };
1162
1163 /* --------------- */
1164
1165 /* try to write step as a power of 10 */
1166 static void step_to_grid(float *step, int *power, int unit)
1167 {
1168         const float loga = (float)log10(*step);
1169         float rem;
1170         
1171         *power = (int)(loga);
1172         
1173         rem = loga - (*power);
1174         rem = (float)pow(10.0, rem);
1175         
1176         if (loga < 0.0f) {
1177                 if (rem < 0.2f) rem = 0.2f;
1178                 else if (rem < 0.5f) rem = 0.5f;
1179                 else rem = 1.0f;
1180                 
1181                 *step = rem * (float)pow(10.0, (*power));
1182                 
1183                 /* for frames, we want 1.0 frame intervals only */
1184                 if (unit == V2D_UNIT_FRAMES) {
1185                         rem = 1.0f;
1186                         *step = 2.0f; /* use 2 since there are grid lines drawn in between, this way to get 1 line per frane */
1187                 }
1188                 
1189                 /* prevents printing 1.0 2.0 3.0 etc */
1190                 if (rem == 1.0f) (*power)++;
1191         }
1192         else {
1193                 if (rem < 2.0f) rem = 2.0f;
1194                 else if (rem < 5.0f) rem = 5.0f;
1195                 else rem = 10.0f;
1196                 
1197                 *step = rem * (float)pow(10.0, (*power));
1198                 
1199                 (*power)++;
1200                 /* prevents printing 1.0, 2.0, 3.0, etc. */
1201                 if (rem == 10.0f) (*power)++;
1202         }
1203 }
1204
1205 /**
1206  * Initialize settings necessary for drawing gridlines in a 2d-view
1207  *
1208  * - Currently, will return pointer to View2DGrid struct that needs to
1209  *   be freed with UI_view2d_grid_free()
1210  * - Is used for scrollbar drawing too (for units drawing)
1211  * - Units + clamping args will be checked, to make sure they are valid values that can be used
1212  *   so it is very possible that we won't return grid at all!
1213  *
1214  * - xunits,yunits      = V2D_UNIT_*  grid steps in seconds or frames
1215  * - xclamp,yclamp      = V2D_CLAMP_* only show whole-number intervals
1216  * - winx                       = width of region we're drawing to, note: not used but keeping for completeness.
1217  * - winy                       = height of region we're drawing into
1218  */
1219 View2DGrid *UI_view2d_grid_calc(
1220         Scene *scene, View2D *v2d,
1221         short xunits, short xclamp, short yunits, short yclamp, int UNUSED(winx), int winy)
1222 {
1223
1224         View2DGrid *grid;
1225         float space, seconddiv;
1226         
1227         /* check that there are at least some workable args */
1228         if (ELEM(V2D_ARG_DUMMY, xunits, xclamp) && ELEM(V2D_ARG_DUMMY, yunits, yclamp))
1229                 return NULL;
1230         
1231         /* grid here is allocated... */
1232         grid = MEM_callocN(sizeof(View2DGrid), "View2DGrid");
1233         
1234         /* rule: gridstep is minimal GRIDSTEP pixels */
1235         if (xunits == V2D_UNIT_SECONDS) {
1236                 seconddiv = (float)(0.01 * FPS);
1237         }
1238         else {
1239                 seconddiv = 1.0f;
1240         }
1241         
1242         /* calculate x-axis grid scale (only if both args are valid) */
1243         if (ELEM(V2D_ARG_DUMMY, xunits, xclamp) == 0) {
1244                 space = BLI_rctf_size_x(&v2d->cur);
1245
1246                 if (space != 0.0f) {
1247                         const float pixels = (float)BLI_rcti_size_x(&v2d->mask);
1248                         if (pixels != 0.0f) {
1249                                 grid->dx = (U.v2d_min_gridsize * UI_DPI_FAC * space) / (seconddiv * pixels);
1250                                 step_to_grid(&grid->dx, &grid->powerx, xunits);
1251                                 grid->dx *= seconddiv;
1252                         }
1253                 }
1254                 
1255                 if (xclamp == V2D_GRID_CLAMP) {
1256                         CLAMP_MIN(grid->dx, 0.1f);
1257                         CLAMP_MIN(grid->powerx, 0);
1258                         grid->powerx -= 2;
1259                 }
1260         }
1261         
1262         /* calculate y-axis grid scale (only if both args are valid) */
1263         if (ELEM(V2D_ARG_DUMMY, yunits, yclamp) == 0) {
1264                 space = BLI_rctf_size_y(&v2d->cur);
1265                 if (space != 0.0f) {
1266                         const float pixels = (float)winy;
1267                         if (pixels != 0.0f) {
1268                                 grid->dy = U.v2d_min_gridsize * UI_DPI_FAC * space / pixels;
1269                                 step_to_grid(&grid->dy, &grid->powery, yunits);
1270                         }
1271                 }
1272
1273                 if (yclamp == V2D_GRID_CLAMP) {
1274                         CLAMP_MIN(grid->dy, 1.0f);
1275                         CLAMP_MIN(grid->powery, 1);
1276                 }
1277         }
1278         
1279         /* calculate start position */
1280         if (ELEM(V2D_ARG_DUMMY, xunits, xclamp) == 0) {
1281                 grid->startx = seconddiv * (v2d->cur.xmin / seconddiv - (float)fmod(v2d->cur.xmin / seconddiv, grid->dx / seconddiv));
1282                 if (v2d->cur.xmin < 0.0f) grid->startx -= grid->dx;
1283         }
1284         else
1285                 grid->startx = v2d->cur.xmin;
1286                 
1287         if (ELEM(V2D_ARG_DUMMY, yunits, yclamp) == 0) {
1288                 grid->starty = (v2d->cur.ymin - (float)fmod(v2d->cur.ymin, grid->dy));
1289                 if (v2d->cur.ymin < 0.0f) grid->starty -= grid->dy;
1290         }
1291         else
1292                 grid->starty = v2d->cur.ymin;
1293         
1294         return grid;
1295 }
1296
1297 /* Draw gridlines in the given 2d-region */
1298 void UI_view2d_grid_draw(View2D *v2d, View2DGrid *grid, int flag)
1299 {
1300         float vec1[2], vec2[2];
1301         int a, step;
1302         int vertical_minor_step = (BLI_rcti_size_x(&v2d->mask) + 1) / (U.v2d_min_gridsize * UI_DPI_FAC),
1303                 horizontal_major_step = (BLI_rcti_size_y(&v2d->mask) + 1) / (U.v2d_min_gridsize * UI_DPI_FAC);
1304         unsigned char grid_line_color[3];
1305         
1306         /* check for grid first, as it may not exist */
1307         if (grid == NULL)
1308                 return;
1309
1310         /* Count the needed vertices for the gridlines */
1311         unsigned vertex_count = 0;
1312         if (flag & V2D_VERTICAL_LINES) {
1313                 /* vertical lines */
1314                 vertex_count += 2 * vertical_minor_step;                /* minor gridlines */
1315                 vertex_count += 2 * (vertical_minor_step + 2);  /* major gridlines */
1316         }
1317         if (flag & V2D_HORIZONTAL_LINES) {
1318                 /* horizontal lines */
1319                 vertex_count += 2 * (horizontal_major_step + 1);        /* major gridlines */
1320
1321                 /* fine lines */
1322                 if (flag & V2D_HORIZONTAL_FINELINES)
1323                         vertex_count += 2 * (horizontal_major_step + 1);
1324         }
1325         /* axes */
1326         if (flag & V2D_HORIZONTAL_AXIS)
1327                 vertex_count += 2;
1328         if (flag & V2D_VERTICAL_AXIS)
1329                 vertex_count += 2;
1330
1331         /* If there is nothing to render, exit early */
1332         if (vertex_count == 0)
1333                 return;
1334
1335         Gwn_VertFormat *format = immVertexFormat();
1336         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1337         unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
1338
1339         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1340         immBegin(GWN_PRIM_LINES, vertex_count);
1341
1342         /* vertical lines */
1343         if (flag & V2D_VERTICAL_LINES) {
1344                 /* initialize initial settings */
1345                 vec1[0] = vec2[0] = grid->startx;
1346                 vec1[1] = grid->starty;
1347                 vec2[1] = v2d->cur.ymax;
1348                 
1349                 /* minor gridlines */
1350                 step = vertical_minor_step;
1351                 if (step != 0) {
1352                         UI_GetThemeColor3ubv(TH_GRID, grid_line_color);
1353         
1354                         for (a = 0; a < step; a++) {
1355                                 immSkipAttrib(color);
1356                                 immVertex2fv(pos, vec1);
1357                                 immAttrib3ubv(color, grid_line_color);
1358                                 immVertex2fv(pos, vec2);
1359                                 
1360                                 vec2[0] = vec1[0] += grid->dx;
1361                         }
1362                 }
1363                 
1364                 /* major gridlines */
1365                 vec2[0] = vec1[0] -= 0.5f * grid->dx;
1366
1367                 UI_GetThemeColorShade3ubv(TH_GRID, 16, grid_line_color);
1368                 
1369                 step++;
1370                 for (a = 0; a <= step; a++) {
1371                         immSkipAttrib(color);
1372                         immVertex2fv(pos, vec1);
1373                         immAttrib3ubv(color, grid_line_color);
1374                         immVertex2fv(pos, vec2);
1375                         
1376                         vec2[0] = vec1[0] -= grid->dx;
1377                 }
1378         }
1379         
1380         /* horizontal lines */
1381         if (flag & V2D_HORIZONTAL_LINES) {
1382                 /* only major gridlines */
1383                 vec1[1] = vec2[1] = grid->starty;
1384                 vec1[0] = grid->startx;
1385                 vec2[0] = v2d->cur.xmax;
1386                 
1387                 step = horizontal_major_step;
1388         
1389                 UI_GetThemeColor3ubv(TH_GRID, grid_line_color);
1390
1391                 for (a = 0; a <= step; a++) {
1392                         immSkipAttrib(color);
1393                         immVertex2fv(pos, vec1);
1394                         immAttrib3ubv(color, grid_line_color);
1395                         immVertex2fv(pos, vec2);
1396                         
1397                         vec2[1] = vec1[1] += grid->dy;
1398                 }
1399                 
1400                 /* fine grid lines */
1401                 vec2[1] = vec1[1] -= 0.5f * grid->dy;
1402                 step++;
1403                 
1404                 if (flag & V2D_HORIZONTAL_FINELINES) {
1405                         UI_GetThemeColorShade3ubv(TH_GRID, 16, grid_line_color);
1406                         for (a = 0; a < step; a++) {
1407                                 immSkipAttrib(color);
1408                                 immVertex2fv(pos, vec1);
1409                                 immAttrib3ubv(color, grid_line_color);
1410                                 immVertex2fv(pos, vec2);
1411                                 
1412                                 vec2[1] = vec1[1] -= grid->dy;
1413                         }
1414                 }
1415         }
1416         
1417         /* Axes are drawn as darker lines */
1418         UI_GetThemeColorShade3ubv(TH_GRID, -50, grid_line_color);
1419         
1420         /* horizontal axis */
1421         if (flag & V2D_HORIZONTAL_AXIS) {
1422                 vec1[0] = v2d->cur.xmin;
1423                 vec2[0] = v2d->cur.xmax;
1424                 vec1[1] = vec2[1] = 0.0f;
1425                 
1426                 immSkipAttrib(color);
1427                 immVertex2fv(pos, vec1);
1428                 immAttrib3ubv(color, grid_line_color);
1429                 immVertex2fv(pos, vec2);
1430         }
1431         
1432         /* vertical axis */
1433         if (flag & V2D_VERTICAL_AXIS) {
1434                 vec1[1] = v2d->cur.ymin;
1435                 vec2[1] = v2d->cur.ymax;
1436                 vec1[0] = vec2[0] = 0.0f;
1437                 
1438                 immSkipAttrib(color);
1439                 immVertex2fv(pos, vec1);
1440                 immAttrib3ubv(color, grid_line_color);
1441                 immVertex2fv(pos, vec2);
1442         }
1443
1444         immEnd();
1445         immUnbindProgram();
1446 }
1447
1448 /* Draw a constant grid in given 2d-region */
1449 void UI_view2d_constant_grid_draw(View2D *v2d, float step)
1450 {
1451         float start_x, start_y;
1452         int count_x, count_y;
1453         
1454         start_x = v2d->cur.xmin;
1455         if (start_x < 0.0)
1456                 start_x += -(float)fmod(v2d->cur.xmin, step);
1457         else
1458                 start_x += (step - (float)fmod(v2d->cur.xmin, step));
1459
1460         if (start_x > v2d->cur.xmax)
1461                 count_x = 0;
1462         else
1463                 count_x = (v2d->cur.xmax - start_x) / step + 1;
1464
1465         start_y = v2d->cur.ymin;
1466         if (start_y < 0.0)
1467                 start_y += -(float)fmod(v2d->cur.ymin, step);
1468         else
1469                 start_y += (step - (float)fabs(fmod(v2d->cur.ymin, step)));
1470
1471         if (start_y > v2d->cur.ymax)
1472                 count_y = 0;
1473         else
1474                 count_y = (v2d->cur.ymax - start_y) / step + 1;
1475         
1476         if (count_x > 0 || count_y > 0) {
1477                 Gwn_VertFormat *format = immVertexFormat();
1478                 unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1479                 unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_F32, 3, GWN_FETCH_FLOAT);
1480                 float theme_color[3];
1481
1482                 UI_GetThemeColorShade3fv(TH_BACK, -10, theme_color);
1483                 
1484                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1485                 immBegin(GWN_PRIM_LINES, count_x * 2 + count_y * 2 + 4);
1486                 
1487                 immAttrib3fv(color, theme_color);
1488                 for (int i = 0; i < count_x ; start_x += step, i++) {
1489                         immVertex2f(pos, start_x, v2d->cur.ymin);
1490                         immVertex2f(pos, start_x, v2d->cur.ymax);
1491                 }
1492
1493                 for (int i = 0; i < count_y; start_y += step, i++) {
1494                         immVertex2f(pos, v2d->cur.xmin, start_y);
1495                         immVertex2f(pos, v2d->cur.xmax, start_y);
1496                 }
1497         
1498                 /* X and Y axis */
1499                 UI_GetThemeColorShade3fv(TH_BACK, -18, theme_color);
1500                 
1501                 immAttrib3fv(color, theme_color);
1502                 immVertex2f(pos, 0.0f, v2d->cur.ymin);
1503                 immVertex2f(pos, 0.0f, v2d->cur.ymax);
1504                 immVertex2f(pos, v2d->cur.xmin, 0.0f);
1505                 immVertex2f(pos, v2d->cur.xmax, 0.0f);
1506         
1507                 immEnd();
1508                 immUnbindProgram();
1509         }
1510 }
1511
1512 /* Draw a multi-level grid in given 2d-region */
1513 void UI_view2d_multi_grid_draw(View2D *v2d, int colorid, float step, int level_size, int totlevels)
1514 {
1515         /* Exit if there is nothing to draw */
1516         if (totlevels == 0)
1517                 return;
1518
1519         int offset = -10;
1520         float lstep = step;
1521         unsigned char grid_line_color[3];
1522
1523         /* Make an estimate of at least how many vertices will be needed */
1524         unsigned vertex_count = 4;
1525         vertex_count += 2 * ((int)((v2d->cur.xmax - v2d->cur.xmin) / lstep) + 1);
1526         vertex_count += 2 * ((int)((v2d->cur.ymax - v2d->cur.ymin) / lstep) + 1);
1527
1528         Gwn_VertFormat *format = immVertexFormat();
1529         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1530         unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
1531
1532         glLineWidth(1.0f);
1533
1534         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1535         immBeginAtMost(GWN_PRIM_LINES, vertex_count);
1536
1537         for (int level = 0; level < totlevels; ++level) {
1538                 UI_GetThemeColorShade3ubv(colorid, offset, grid_line_color);
1539                 
1540                 int i = (int)(v2d->cur.xmin / lstep);
1541                 if (v2d->cur.xmin > 0.0f)
1542                         i++;
1543                 float start = i * lstep;
1544                 
1545                 for (; start < v2d->cur.xmax; start += lstep, ++i) {
1546                         if (i == 0 || (level < totlevels - 1 && i % level_size == 0))
1547                                 continue;
1548
1549                         immSkipAttrib(color);
1550                         immVertex2f(pos, start, v2d->cur.ymin);
1551                         immAttrib3ubv(color, grid_line_color);
1552                         immVertex2f(pos, start, v2d->cur.ymax);
1553                 }
1554                 
1555                 i = (int)(v2d->cur.ymin / lstep);
1556                 if (v2d->cur.ymin > 0.0f)
1557                         i++;
1558                 start = i * lstep;
1559                 
1560                 for (; start < v2d->cur.ymax; start += lstep, ++i) {
1561                         if (i == 0 || (level < totlevels - 1 && i % level_size == 0))
1562                                 continue;
1563
1564                         immSkipAttrib(color);
1565                         immVertex2f(pos, v2d->cur.xmin, start);
1566                         immAttrib3ubv(color, grid_line_color);
1567                         immVertex2f(pos, v2d->cur.xmax, start);
1568                 }
1569                 
1570                 lstep *= level_size;
1571                 offset -= 6;
1572         }
1573
1574         /* X and Y axis */
1575         UI_GetThemeColorShade3ubv(colorid, -18 + ((totlevels - 1) * -6), grid_line_color);
1576
1577         immSkipAttrib(color);
1578         immVertex2f(pos, 0.0f, v2d->cur.ymin);
1579         immAttrib3ubv(color, grid_line_color);
1580         immVertex2f(pos, 0.0f, v2d->cur.ymax);
1581
1582         immSkipAttrib(color);
1583         immVertex2f(pos, v2d->cur.xmin, 0.0f);
1584         immAttrib3ubv(color, grid_line_color);
1585         immVertex2f(pos, v2d->cur.xmax, 0.0f);
1586
1587         immEnd();
1588         immUnbindProgram();
1589 }
1590
1591 /* the price we pay for not exposting structs :( */
1592 void UI_view2d_grid_size(View2DGrid *grid, float *r_dx, float *r_dy)
1593 {
1594         *r_dx = grid->dx;
1595         *r_dy = grid->dy;
1596 }
1597
1598 /* free temporary memory used for drawing grid */
1599 void UI_view2d_grid_free(View2DGrid *grid)
1600 {
1601         /* only free if there's a grid */
1602         if (grid) {
1603                 MEM_freeN(grid);
1604         }
1605 }
1606
1607 /* *********************************************************************** */
1608 /* Scrollers */
1609
1610 /**
1611  * View2DScrollers is typedef'd in UI_view2d.h
1612  *
1613  * \warning The start of this struct must not change, as view2d_ops.c uses this too.
1614  * For now, we don't need to have a separate (internal) header for structs like this...
1615  */
1616 struct View2DScrollers {
1617         /* focus bubbles */
1618         int vert_min, vert_max; /* vertical scrollbar */
1619         int hor_min, hor_max;   /* horizontal scrollbar */
1620         
1621         rcti hor, vert;         /* exact size of slider backdrop */
1622         int horfull, vertfull;  /* set if sliders are full, we don't draw them */
1623         
1624         /* scales */
1625         View2DGrid *grid;       /* grid for coordinate drawing */
1626         short xunits, xclamp;   /* units and clamping options for x-axis */
1627         short yunits, yclamp;   /* units and clamping options for y-axis */
1628 };
1629
1630 /* Calculate relevant scroller properties */
1631 View2DScrollers *UI_view2d_scrollers_calc(
1632         const bContext *C, View2D *v2d,
1633         short xunits, short xclamp, short yunits, short yclamp)
1634 {
1635         View2DScrollers *scrollers;
1636         rcti vert, hor;
1637         float fac1, fac2, totsize, scrollsize;
1638         int scroll = view2d_scroll_mapped(v2d->scroll);
1639         int smaller;
1640         
1641         /* scrollers is allocated here... */
1642         scrollers = MEM_callocN(sizeof(View2DScrollers), "View2DScrollers");
1643         
1644         vert = v2d->vert;
1645         hor = v2d->hor;
1646         
1647         /* slider rects need to be smaller than region */
1648         smaller = (int)(0.2f * U.widget_unit);
1649         hor.xmin += smaller;
1650         hor.xmax -= smaller;
1651         if (scroll & V2D_SCROLL_BOTTOM)
1652                 hor.ymin += smaller;
1653         else
1654                 hor.ymax -= smaller;
1655         
1656         if (scroll & V2D_SCROLL_LEFT)
1657                 vert.xmin += smaller;
1658         else
1659                 vert.xmax -= smaller;
1660         vert.ymin += smaller;
1661         vert.ymax -= smaller;
1662         
1663         CLAMP(vert.ymin, vert.ymin, vert.ymax - V2D_SCROLLER_HANDLE_SIZE);
1664         CLAMP(hor.xmin, hor.xmin, hor.xmax - V2D_SCROLLER_HANDLE_SIZE);
1665         
1666         /* store in scrollers, used for drawing */
1667         scrollers->vert = vert;
1668         scrollers->hor = hor;
1669         
1670         /* scroller 'buttons':
1671          *      - These should always remain within the visible region of the scrollbar
1672          *      - They represent the region of 'tot' that is visible in 'cur'
1673          */
1674         
1675         /* horizontal scrollers */
1676         if (scroll & V2D_SCROLL_HORIZONTAL) {
1677                 /* scroller 'button' extents */
1678                 totsize = BLI_rctf_size_x(&v2d->tot);
1679                 scrollsize = (float)BLI_rcti_size_x(&hor);
1680                 if (totsize == 0.0f) totsize = 1.0f;  /* avoid divide by zero */
1681
1682                 fac1 = (v2d->cur.xmin - v2d->tot.xmin) / totsize;
1683                 if (fac1 <= 0.0f)
1684                         scrollers->hor_min = hor.xmin;
1685                 else
1686                         scrollers->hor_min = (int)(hor.xmin + (fac1 * scrollsize));
1687                 
1688                 fac2 = (v2d->cur.xmax - v2d->tot.xmin) / totsize;
1689                 if (fac2 >= 1.0f)
1690                         scrollers->hor_max = hor.xmax;
1691                 else
1692                         scrollers->hor_max = (int)(hor.xmin + (fac2 * scrollsize));
1693                 
1694                 /* prevent inverted sliders */
1695                 if (scrollers->hor_min > scrollers->hor_max) 
1696                         scrollers->hor_min = scrollers->hor_max;
1697                 /* prevent sliders from being too small, and disappearing */
1698                 if ((scrollers->hor_max - scrollers->hor_min) < V2D_SCROLLER_HANDLE_SIZE) {
1699                         scrollers->hor_max = scrollers->hor_min + V2D_SCROLLER_HANDLE_SIZE;
1700
1701                         CLAMP(scrollers->hor_max, hor.xmin + V2D_SCROLLER_HANDLE_SIZE, hor.xmax);
1702                         CLAMP(scrollers->hor_min, hor.xmin, hor.xmax - V2D_SCROLLER_HANDLE_SIZE);
1703                 }
1704                 
1705         }
1706         
1707         /* vertical scrollers */
1708         if (scroll & V2D_SCROLL_VERTICAL) {
1709                 /* scroller 'button' extents */
1710                 totsize    =        BLI_rctf_size_y(&v2d->tot);
1711                 scrollsize = (float)BLI_rcti_size_y(&vert);
1712                 if (totsize == 0.0f) totsize = 1.0f;  /* avoid divide by zero */
1713
1714                 fac1 = (v2d->cur.ymin - v2d->tot.ymin) / totsize;
1715                 if (fac1 <= 0.0f)
1716                         scrollers->vert_min = vert.ymin;
1717                 else
1718                         scrollers->vert_min = (int)(vert.ymin + (fac1 * scrollsize));
1719                 
1720                 fac2 = (v2d->cur.ymax - v2d->tot.ymin) / totsize;
1721                 if (fac2 >= 1.0f)
1722                         scrollers->vert_max = vert.ymax;
1723                 else
1724                         scrollers->vert_max = (int)(vert.ymin + (fac2 * scrollsize));
1725                 
1726                 /* prevent inverted sliders */
1727                 if (scrollers->vert_min > scrollers->vert_max) 
1728                         scrollers->vert_min = scrollers->vert_max;
1729                 /* prevent sliders from being too small, and disappearing */
1730                 if ((scrollers->vert_max - scrollers->vert_min) < V2D_SCROLLER_HANDLE_SIZE) {
1731                         
1732                         scrollers->vert_max = scrollers->vert_min + V2D_SCROLLER_HANDLE_SIZE;
1733                         
1734                         CLAMP(scrollers->vert_max, vert.ymin + V2D_SCROLLER_HANDLE_SIZE, vert.ymax);
1735                         CLAMP(scrollers->vert_min, vert.ymin, vert.ymax - V2D_SCROLLER_HANDLE_SIZE);
1736                 }
1737
1738         }
1739         
1740         /* grid markings on scrollbars */
1741         if (scroll & (V2D_SCROLL_SCALE_HORIZONTAL | V2D_SCROLL_SCALE_VERTICAL)) {
1742                 /* store clamping */
1743                 scrollers->xclamp = xclamp;
1744                 scrollers->xunits = xunits;
1745                 scrollers->yclamp = yclamp;
1746                 scrollers->yunits = yunits;
1747                 
1748                 scrollers->grid = UI_view2d_grid_calc(CTX_data_scene(C), v2d,
1749                                                       xunits, xclamp, yunits, yclamp,
1750                                                       BLI_rcti_size_x(&hor), BLI_rcti_size_y(&vert));
1751         }
1752         
1753         /* return scrollers */
1754         return scrollers;
1755 }
1756
1757 /* Print scale marking along a time scrollbar */
1758 static void scroll_printstr(Scene *scene, float x, float y, float val, int power, short unit, char dir)
1759 {
1760         int len;
1761         char timecode_str[32];
1762         
1763         /* adjust the scale unit to work ok */
1764         if (dir == 'v') {
1765                 /* here we bump up the power by factor of 10, as 
1766                  * rotation values (hence 'degrees') are divided by 10 to 
1767                  * be able to show the curves at the same time
1768                  */
1769                 if (ELEM(unit, V2D_UNIT_DEGREES, V2D_UNIT_TIME)) {
1770                         power += 1;
1771                         val *= 10;
1772                 }
1773         }
1774         
1775         /* get string to print */
1776         if (unit == V2D_UNIT_SECONDS) {
1777                 /* not neces*/
1778                 BLI_timecode_string_from_time(timecode_str, sizeof(timecode_str), power, val, FPS, U.timecode_style);
1779         }
1780         else {
1781                 BLI_timecode_string_from_time_seconds(timecode_str, sizeof(timecode_str), power, val);
1782         }
1783         
1784         /* get length of string, and adjust printing location to fit it into the horizontal scrollbar */
1785         len = strlen(timecode_str);
1786         if (dir == 'h') {
1787                 /* seconds/timecode display has slightly longer strings... */
1788                 if (unit == V2D_UNIT_SECONDS)
1789                         x -= 3 * len;
1790                 else
1791                         x -= 4 * len;
1792         }
1793         
1794         /* Add degree sympbol to end of string for vertical scrollbar? */
1795         if ((dir == 'v') && (unit == V2D_UNIT_DEGREES)) {
1796                 timecode_str[len] = 186;
1797                 timecode_str[len + 1] = 0;
1798         }
1799         
1800         /* draw it */
1801         BLF_draw_default_ascii(x, y, 0.0f, timecode_str, sizeof(timecode_str));
1802 }
1803
1804 /* Draw scrollbars in the given 2d-region */
1805 void UI_view2d_scrollers_draw(const bContext *C, View2D *v2d, View2DScrollers *vs)
1806 {
1807         Scene *scene = CTX_data_scene(C);
1808         rcti vert, hor;
1809         int scroll = view2d_scroll_mapped(v2d->scroll);
1810         unsigned char scrollers_back_color[4];
1811
1812         /* Color for scrollbar backs */
1813         UI_GetThemeColor4ubv(TH_BACK, scrollers_back_color);
1814         
1815         /* make copies of rects for less typing */
1816         vert = vs->vert;
1817         hor = vs->hor;
1818         
1819         /* horizontal scrollbar */
1820         if (scroll & V2D_SCROLL_HORIZONTAL) {
1821                 bTheme *btheme = UI_GetTheme();
1822                 uiWidgetColors wcol = btheme->tui.wcol_scroll;
1823                 rcti slider;
1824                 int state;
1825                 
1826                 slider.xmin = vs->hor_min;
1827                 slider.xmax = vs->hor_max;
1828                 slider.ymin = hor.ymin;
1829                 slider.ymax = hor.ymax;
1830                 
1831                 state = (v2d->scroll_ui & V2D_SCROLL_H_ACTIVE) ? UI_SCROLL_PRESSED : 0;
1832                 
1833                 /* show zoom handles if:
1834                  *      - zooming on x-axis is allowed (no scroll otherwise)
1835                  *      - slider bubble is large enough (no overdraw confusion)
1836                  *      - scale is shown on the scroller 
1837                  *        (workaround to make sure that button windows don't show these, 
1838                  *              and only the time-grids with their zoomability can do so)
1839                  */
1840                 if ((v2d->keepzoom & V2D_LOCKZOOM_X) == 0 &&
1841                     (v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL) &&
1842                     (BLI_rcti_size_x(&slider) > V2D_SCROLLER_HANDLE_SIZE))
1843                 {
1844                         state |= UI_SCROLL_ARROWS;
1845                 }
1846                 
1847                 /* clean rect behind slider, but not with transparent background */
1848                 if (scrollers_back_color[3] == 255) {
1849                         Gwn_VertFormat *format = immVertexFormat();
1850                         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT);
1851
1852                         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1853
1854                         immUniformColor3ubv(scrollers_back_color);
1855                         immRecti(pos, v2d->hor.xmin, v2d->hor.ymin, v2d->hor.xmax, v2d->hor.ymax);
1856
1857                         immUnbindProgram();
1858                 }
1859                 
1860                 UI_draw_widget_scroll(&wcol, &hor, &slider, state);
1861                 
1862                 /* scale indicators */
1863                 if ((scroll & V2D_SCROLL_SCALE_HORIZONTAL) && (vs->grid)) {
1864                         const int font_id = BLF_default();
1865                         View2DGrid *grid = vs->grid;
1866                         float fac, dfac, fac2, val;
1867                         
1868                         /* the numbers: convert grid->startx and -dx to scroll coordinates 
1869                          *      - fac is x-coordinate to draw to
1870                          *      - dfac is gap between scale markings
1871                          */
1872                         fac = (grid->startx - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
1873                         fac = (float)hor.xmin + fac * BLI_rcti_size_x(&hor);
1874                         
1875                         dfac = grid->dx / BLI_rctf_size_x(&v2d->cur);
1876                         dfac = dfac * BLI_rcti_size_x(&hor);
1877                         
1878                         /* set starting value, and text color */
1879                         UI_FontThemeColor(font_id, TH_TEXT);
1880                         val = grid->startx;
1881                         
1882                         /* if we're clamping to whole numbers only, make sure entries won't be repeated */
1883                         if (vs->xclamp == V2D_GRID_CLAMP) {
1884                                 while (grid->dx < 0.9999f) {
1885                                         grid->dx *= 2.0f;
1886                                         dfac *= 2.0f;
1887                                 }
1888                         }
1889                         if (vs->xunits == V2D_UNIT_FRAMES)
1890                                 grid->powerx = 1;
1891
1892                         /* draw numbers in the appropriate range */
1893                         if (dfac > 0.0f) {
1894                                 float h = 0.1f * UI_UNIT_Y + (float)(hor.ymin);
1895                                 
1896                                 for (; fac < hor.xmax - 0.5f * U.widget_unit; fac += dfac, val += grid->dx) {
1897                                         
1898                                         /* make prints look nicer for scrollers */
1899                                         if (fac < hor.xmin + 0.5f * U.widget_unit)
1900                                                 continue;
1901                                         
1902                                         switch (vs->xunits) {
1903                                                 case V2D_UNIT_FRAMES:       /* frames (as whole numbers)*/
1904                                                         scroll_printstr(scene, fac, h, val, grid->powerx, V2D_UNIT_FRAMES, 'h');
1905                                                         break;
1906                                                         
1907                                                 case V2D_UNIT_FRAMESCALE:   /* frames (not always as whole numbers) */
1908                                                         scroll_printstr(scene, fac, h, val, grid->powerx, V2D_UNIT_FRAMESCALE, 'h');
1909                                                         break;
1910                                                 
1911                                                 case V2D_UNIT_SECONDS:      /* seconds */
1912                                                         fac2 = val / (float)FPS;
1913                                                         scroll_printstr(scene, fac, h, fac2, grid->powerx, V2D_UNIT_SECONDS, 'h');
1914                                                         break;
1915                                                         
1916                                                 case V2D_UNIT_DEGREES:      /* Graph Editor for rotation Drivers */
1917                                                         /* HACK: although we're drawing horizontal, we make this draw as 'vertical', just to get degree signs */
1918                                                         scroll_printstr(scene, fac, h, val, grid->powerx, V2D_UNIT_DEGREES, 'v');
1919                                                         break;
1920                                         }
1921                                 }
1922                         }
1923                 }
1924         }
1925         
1926         /* vertical scrollbar */
1927         if (scroll & V2D_SCROLL_VERTICAL) {
1928                 bTheme *btheme = UI_GetTheme();
1929                 uiWidgetColors wcol = btheme->tui.wcol_scroll;
1930                 rcti slider;
1931                 int state;
1932                 
1933                 slider.xmin = vert.xmin;
1934                 slider.xmax = vert.xmax;
1935                 slider.ymin = vs->vert_min;
1936                 slider.ymax = vs->vert_max;
1937                 
1938                 state = (v2d->scroll_ui & V2D_SCROLL_V_ACTIVE) ? UI_SCROLL_PRESSED : 0;
1939                 
1940                 /* show zoom handles if:
1941                  *      - zooming on y-axis is allowed (no scroll otherwise)
1942                  *      - slider bubble is large enough (no overdraw confusion)
1943                  *      - scale is shown on the scroller 
1944                  *        (workaround to make sure that button windows don't show these, 
1945                  *              and only the time-grids with their zoomability can do so)
1946                  */
1947                 if ((v2d->keepzoom & V2D_LOCKZOOM_Y) == 0 &&
1948                     (v2d->scroll & V2D_SCROLL_SCALE_VERTICAL) &&
1949                     (BLI_rcti_size_y(&slider) > V2D_SCROLLER_HANDLE_SIZE))
1950                 {
1951                         state |= UI_SCROLL_ARROWS;
1952                 }
1953                 
1954                 /* clean rect behind slider, but not with transparent background */
1955                 if (scrollers_back_color[3] == 255) {
1956                         Gwn_VertFormat *format = immVertexFormat();
1957                         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT);
1958
1959                         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1960
1961                         immUniformColor3ubv(scrollers_back_color);
1962                         immRecti(pos, v2d->vert.xmin, v2d->vert.ymin, v2d->vert.xmax, v2d->vert.ymax);
1963
1964                         immUnbindProgram();
1965                 }
1966                 
1967                 UI_draw_widget_scroll(&wcol, &vert, &slider, state);
1968                 
1969                 
1970                 /* scale indiators */
1971                 if ((scroll & V2D_SCROLL_SCALE_VERTICAL) && (vs->grid)) {
1972                         View2DGrid *grid = vs->grid;
1973                         float fac, dfac, val;
1974                         
1975                         /* the numbers: convert grid->starty and dy to scroll coordinates 
1976                          *      - fac is y-coordinate to draw to
1977                          *      - dfac is gap between scale markings
1978                          *      - these involve a correction for horizontal scrollbar
1979                          *        NOTE: it's assumed that that scrollbar is there if this is involved!
1980                          */
1981                         fac = (grid->starty - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
1982                         fac = vert.ymin + fac * BLI_rcti_size_y(&vert);
1983                         
1984                         dfac = grid->dy / BLI_rctf_size_y(&v2d->cur);
1985                         dfac = dfac     * BLI_rcti_size_y(&vert);
1986                         
1987                         /* set starting value, and text color */
1988                         const int font_id = BLF_default();
1989                         UI_FontThemeColor(font_id, TH_TEXT);
1990                         val = grid->starty;
1991                         
1992                         /* if vertical clamping (to whole numbers) is used (i.e. in Sequencer), apply correction */
1993                         if (vs->yclamp == V2D_GRID_CLAMP)
1994                                 fac += 0.5f * dfac;
1995                                 
1996                         /* draw vertical steps */
1997                         if (dfac > 0.0f) {
1998                                 BLF_rotation(font_id, M_PI_2);
1999                                 BLF_enable(font_id, BLF_ROTATION);
2000
2001                                 for (; fac < vert.ymax - 10; fac += dfac, val += grid->dy) {
2002                                         
2003                                         /* make prints look nicer for scrollers */
2004                                         if (fac < vert.ymin + 10)
2005                                                 continue;
2006                                         
2007                                         scroll_printstr(scene, (float)(vert.xmax) - 2.0f, fac, val, grid->powery, vs->yunits, 'v');
2008                                 }
2009                                 
2010                                 BLF_disable(font_id, BLF_ROTATION);
2011                         }
2012                 }
2013         }
2014         
2015 }
2016
2017 /* free temporary memory used for drawing scrollers */
2018 void UI_view2d_scrollers_free(View2DScrollers *scrollers)
2019 {
2020         /* need to free grid as well... */
2021         if (scrollers->grid) {
2022                 MEM_freeN(scrollers->grid);
2023         }
2024         MEM_freeN(scrollers);
2025 }
2026
2027 /* *********************************************************************** */
2028 /* List View Utilities */
2029
2030 /** Get the view-coordinates of the nominated cell
2031  *
2032  * \param columnwidth, rowheight: size of each 'cell'
2033  * \param startx, starty: coordinates (in 'tot' rect space) that the list starts from.
2034  * This should be (0,0) for most views. However, for those where the starting row was offsetted
2035  * (like for Animation Editor channel lists, to make the first entry more visible), these will be
2036  * the min-coordinates of the first item.
2037  * \param column, row: The 2d-coordinates
2038  * (in 2D-view / 'tot' rect space) the cell exists at
2039  * \param rect:  coordinates of the cell
2040  * (passed as single var instead of 4 separate, as it's more useful this way)
2041  */
2042 void UI_view2d_listview_cell_to_view(
2043         View2D *v2d, float columnwidth, float rowheight,
2044         float startx, float starty,
2045         int column, int row, rctf *rect)
2046 {
2047         /* sanity checks */
2048         if (ELEM(NULL, v2d, rect)) {
2049                 return;
2050         }
2051
2052         if ((columnwidth <= 0) && (rowheight <= 0)) {
2053                 rect->xmin = rect->xmax = 0.0f;
2054                 rect->ymin = rect->ymax = 0.0f;
2055                 return;
2056         }
2057         
2058         /* x-coordinates */
2059         rect->xmin = startx + (float)(columnwidth * column);
2060         rect->xmax = startx + (float)(columnwidth * (column + 1));
2061         
2062         if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
2063                 /* simply negate the values for the coordinates if in negative half */
2064                 rect->xmin = -rect->xmin;
2065                 rect->xmax = -rect->xmax;
2066         }
2067         
2068         /* y-coordinates */
2069         rect->ymin = starty + (float)(rowheight * row);
2070         rect->ymax = starty + (float)(rowheight * (row + 1));
2071         
2072         if ((v2d->align & V2D_ALIGN_NO_POS_Y) && !(v2d->align & V2D_ALIGN_NO_NEG_Y)) {
2073                 /* simply negate the values for the coordinates if in negative half */
2074                 rect->ymin = -rect->ymin;
2075                 rect->ymax = -rect->ymax;
2076         }
2077 }
2078
2079 /**
2080  * Get the 'cell' (row, column) that the given 2D-view coordinates (i.e. in 'tot' rect space) lie in.
2081  *
2082  * \param columnwidth, rowheight: size of each 'cell'
2083  * \param startx, starty: coordinates (in 'tot' rect space) that the list starts from.
2084  * This should be (0,0) for most views. However, for those where the starting row was offsetted
2085  * (like for Animation Editor channel lists, to make the first entry more visible), these will be
2086  * the min-coordinates of the first item.
2087  * \param viewx, viewy: 2D-coordinates (in 2D-view / 'tot' rect space) to get the cell for
2088  * \param column, row: the 'coordinates' of the relevant 'cell'
2089  */
2090 void UI_view2d_listview_view_to_cell(
2091         View2D *v2d, float columnwidth, float rowheight, float startx, float starty,
2092         float viewx, float viewy, int *column, int *row)
2093 {
2094         /* adjust view coordinates to be all positive ints, corrected for the start offset */
2095         const int x = (int)(floorf(fabsf(viewx) + 0.5f) - startx);
2096         const int y = (int)(floorf(fabsf(viewy) + 0.5f) - starty);
2097         
2098         /* sizes must not be negative */
2099         if ((v2d == NULL) || ((columnwidth <= 0) && (rowheight <= 0))) {
2100                 if (column) *column = 0;
2101                 if (row) *row = 0;
2102                 
2103                 return;
2104         }
2105         
2106         /* get column */
2107         if ((column) && (columnwidth > 0))
2108                 *column = x / columnwidth;
2109         else if (column)
2110                 *column = 0;
2111         
2112         /* get row */
2113         if ((row) && (rowheight > 0))
2114                 *row = y / rowheight;
2115         else if (row)
2116                 *row = 0;
2117 }
2118
2119 /**
2120  * Get the 'extreme' (min/max) column and row indices which are visible within the 'cur' rect
2121  *
2122  * \param columnwidth, rowheight: Size of each 'cell'
2123  * \param startx, starty: Coordinates that the list starts from, which should be (0,0) for most views
2124  * \param column_min, column_max, row_min, row_max: The starting and ending column/row indices
2125  */
2126 void UI_view2d_listview_visible_cells(
2127         View2D *v2d, float columnwidth, float rowheight, float startx, float starty,
2128         int *column_min, int *column_max, int *row_min, int *row_max)
2129 {
2130         /* using 'cur' rect coordinates, call the cell-getting function to get the cells for this */
2131         if (v2d) {
2132                 /* min */
2133                 UI_view2d_listview_view_to_cell(v2d, columnwidth, rowheight, startx, starty, 
2134                                                 v2d->cur.xmin, v2d->cur.ymin, column_min, row_min);
2135
2136                 /* max*/
2137                 UI_view2d_listview_view_to_cell(v2d, columnwidth, rowheight, startx, starty, 
2138                                                 v2d->cur.xmax, v2d->cur.ymax, column_max, row_max);
2139         }
2140 }
2141
2142 /* *********************************************************************** */
2143 /* Coordinate Conversions */
2144
2145 float UI_view2d_region_to_view_x(struct View2D *v2d, float x)
2146 {
2147         return (v2d->cur.xmin + (BLI_rctf_size_x(&v2d->cur) * (x - v2d->mask.xmin) / BLI_rcti_size_x(&v2d->mask)));
2148 }
2149 float UI_view2d_region_to_view_y(struct View2D *v2d, float y)
2150 {
2151         return (v2d->cur.ymin + (BLI_rctf_size_y(&v2d->cur) * (y - v2d->mask.ymin) / BLI_rcti_size_y(&v2d->mask)));
2152 }
2153
2154 /**
2155  * Convert from screen/region space to 2d-View space
2156  *
2157  * \param x, y: coordinates to convert
2158  * \param r_view_x, r_view_y: resultant coordinates
2159  */
2160 void UI_view2d_region_to_view(View2D *v2d, float x, float y, float *r_view_x, float *r_view_y)
2161 {
2162         *r_view_x = UI_view2d_region_to_view_x(v2d, x);
2163         *r_view_y = UI_view2d_region_to_view_y(v2d, y);
2164 }
2165
2166 void UI_view2d_region_to_view_rctf(View2D *v2d, const rctf *rect_src, rctf *rect_dst)
2167 {
2168         const float cur_size[2]  = {BLI_rctf_size_x(&v2d->cur),  BLI_rctf_size_y(&v2d->cur)};
2169         const float mask_size[2] = {BLI_rcti_size_x(&v2d->mask), BLI_rcti_size_y(&v2d->mask)};
2170
2171         rect_dst->xmin = (v2d->cur.xmin + (cur_size[0] * (rect_src->xmin - v2d->mask.xmin) / mask_size[0]));
2172         rect_dst->xmax = (v2d->cur.xmin + (cur_size[0] * (rect_src->xmax - v2d->mask.xmin) / mask_size[0]));
2173         rect_dst->ymin = (v2d->cur.ymin + (cur_size[1] * (rect_src->ymin - v2d->mask.ymin) / mask_size[1]));
2174         rect_dst->ymax = (v2d->cur.ymin + (cur_size[1] * (rect_src->ymax - v2d->mask.ymin) / mask_size[1]));
2175 }
2176
2177 float UI_view2d_view_to_region_x(View2D *v2d, float x)
2178 {
2179         return (v2d->mask.xmin + (((x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur)) * BLI_rcti_size_x(&v2d->mask)));
2180 }
2181 float UI_view2d_view_to_region_y(View2D *v2d, float y)
2182 {
2183         return (v2d->mask.ymin + (((y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur)) * BLI_rcti_size_y(&v2d->mask)));
2184 }
2185
2186 /**
2187  * Convert from 2d-View space to screen/region space
2188  * \note Coordinates are clamped to lie within bounds of region
2189  *
2190  * \param x, y: Coordinates to convert.
2191  * \param r_region_x, r_region_y: Resultant coordinates.
2192  */
2193 bool UI_view2d_view_to_region_clip(View2D *v2d, float x, float y, int *r_region_x, int *r_region_y)
2194 {
2195         /* express given coordinates as proportional values */
2196         x = (x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
2197         y = (y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
2198         
2199         /* check if values are within bounds */
2200         if ((x >= 0.0f) && (x <= 1.0f) && (y >= 0.0f) && (y <= 1.0f)) {
2201                 *r_region_x = (int)(v2d->mask.xmin + (x * BLI_rcti_size_x(&v2d->mask)));
2202                 *r_region_y = (int)(v2d->mask.ymin + (y * BLI_rcti_size_y(&v2d->mask)));
2203
2204                 return true;
2205         }
2206         else {
2207                 /* set initial value in case coordinate lies outside of bounds */
2208                 *r_region_x = *r_region_y = V2D_IS_CLIPPED;
2209
2210                 return false;
2211         }
2212 }
2213
2214 /**
2215  * Convert from 2d-view space to screen/region space
2216  *
2217  * \note Coordinates are NOT clamped to lie within bounds of region.
2218  *
2219  * \param x, y: Coordinates to convert.
2220  * \param r_region_x, r_region_y: Resultant coordinates.
2221  */
2222 void UI_view2d_view_to_region(View2D *v2d, float x, float y, int *r_region_x, int *r_region_y)
2223 {
2224         /* step 1: express given coordinates as proportional values */
2225         x = (x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
2226         y = (y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
2227
2228         /* step 2: convert proportional distances to screen coordinates  */
2229         x = v2d->mask.xmin + (x * BLI_rcti_size_x(&v2d->mask));
2230         y = v2d->mask.ymin + (y * BLI_rcti_size_y(&v2d->mask));
2231
2232         /* although we don't clamp to lie within region bounds, we must avoid exceeding size of ints */
2233         *r_region_x = clamp_float_to_int(x);
2234         *r_region_y = clamp_float_to_int(y);
2235 }
2236
2237 void UI_view2d_view_to_region_fl(View2D *v2d, float x, float y, float *r_region_x, float *r_region_y)
2238 {
2239         /* express given coordinates as proportional values */
2240         x = (x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
2241         y = (y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
2242
2243         /* convert proportional distances to screen coordinates */
2244         *r_region_x = v2d->mask.xmin + (x * BLI_rcti_size_x(&v2d->mask));
2245         *r_region_y = v2d->mask.ymin + (y * BLI_rcti_size_y(&v2d->mask));
2246 }
2247
2248 void UI_view2d_view_to_region_rcti(View2D *v2d, const rctf *rect_src, rcti *rect_dst)
2249 {
2250         const float cur_size[2]  = {BLI_rctf_size_x(&v2d->cur),  BLI_rctf_size_y(&v2d->cur)};
2251         const float mask_size[2] = {BLI_rcti_size_x(&v2d->mask), BLI_rcti_size_y(&v2d->mask)};
2252         rctf rect_tmp;
2253
2254         /* step 1: express given coordinates as proportional values */
2255         rect_tmp.xmin = (rect_src->xmin - v2d->cur.xmin) / cur_size[0];
2256         rect_tmp.xmax = (rect_src->xmax - v2d->cur.xmin) / cur_size[0];
2257         rect_tmp.ymin = (rect_src->ymin - v2d->cur.ymin) / cur_size[1];
2258         rect_tmp.ymax = (rect_src->ymax - v2d->cur.ymin) / cur_size[1];
2259
2260
2261         /* step 2: convert proportional distances to screen coordinates  */
2262         rect_tmp.xmin = v2d->mask.xmin + (rect_tmp.xmin * mask_size[0]);
2263         rect_tmp.xmax = v2d->mask.xmin + (rect_tmp.xmax * mask_size[0]);
2264         rect_tmp.ymin = v2d->mask.ymin + (rect_tmp.ymin * mask_size[1]);
2265         rect_tmp.ymax = v2d->mask.ymin + (rect_tmp.ymax * mask_size[1]);
2266
2267         clamp_rctf_to_rcti(rect_dst, &rect_tmp);
2268 }
2269
2270 void UI_view2d_view_to_region_m4(View2D *v2d, float matrix[4][4])
2271 {
2272         rctf mask;
2273         unit_m4(matrix);
2274         BLI_rctf_rcti_copy(&mask, &v2d->mask);
2275         BLI_rctf_transform_calc_m4_pivot_min(&v2d->cur, &mask, matrix);
2276 }
2277
2278 bool UI_view2d_view_to_region_rcti_clip(View2D *v2d, const rctf *rect_src, rcti *rect_dst)
2279 {
2280         const float cur_size[2]  = {BLI_rctf_size_x(&v2d->cur),  BLI_rctf_size_y(&v2d->cur)};
2281         const float mask_size[2] = {BLI_rcti_size_x(&v2d->mask), BLI_rcti_size_y(&v2d->mask)};
2282         rctf rect_tmp;
2283
2284         BLI_assert(rect_src->xmin <= rect_src->xmax && rect_src->ymin <= rect_src->ymax);
2285
2286         /* step 1: express given coordinates as proportional values */
2287         rect_tmp.xmin = (rect_src->xmin - v2d->cur.xmin) / cur_size[0];
2288         rect_tmp.xmax = (rect_src->xmax - v2d->cur.xmin) / cur_size[0];
2289         rect_tmp.ymin = (rect_src->ymin - v2d->cur.ymin) / cur_size[1];
2290         rect_tmp.ymax = (rect_src->ymax - v2d->cur.ymin) / cur_size[1];
2291
2292         if (((rect_tmp.xmax < 0.0f) || (rect_tmp.xmin > 1.0f) ||
2293              (rect_tmp.ymax < 0.0f) || (rect_tmp.ymin > 1.0f)) == 0)
2294         {
2295                 /* step 2: convert proportional distances to screen coordinates  */
2296                 rect_tmp.xmin = v2d->mask.xmin + (rect_tmp.xmin * mask_size[0]);
2297                 rect_tmp.xmax = v2d->mask.ymin + (rect_tmp.xmax * mask_size[0]);
2298                 rect_tmp.ymin = v2d->mask.ymin + (rect_tmp.ymin * mask_size[1]);
2299                 rect_tmp.ymax = v2d->mask.ymin + (rect_tmp.ymax * mask_size[1]);
2300
2301                 clamp_rctf_to_rcti(rect_dst, &rect_tmp);
2302
2303                 return true;
2304         }
2305         else {
2306                 rect_dst->xmin = rect_dst->xmax = rect_dst->ymin = rect_dst->ymax = V2D_IS_CLIPPED;
2307
2308                 return false;
2309         }
2310 }
2311
2312 /* *********************************************************************** */
2313 /* Utilities */
2314
2315 /* View2D data by default resides in region, so get from region stored in context */
2316 View2D *UI_view2d_fromcontext(const bContext *C)
2317 {
2318         ScrArea *area = CTX_wm_area(C);
2319         ARegion *region = CTX_wm_region(C);
2320
2321         if (area == NULL) return NULL;
2322         if (region == NULL) return NULL;
2323         return &(region->v2d);
2324 }
2325
2326 /* same as above, but it returns regionwindow. Utility for pulldowns or buttons */
2327 View2D *UI_view2d_fromcontext_rwin(const bContext *C)
2328 {
2329         ScrArea *sa = CTX_wm_area(C);
2330         ARegion *region = CTX_wm_region(C);
2331
2332         if (sa == NULL) return NULL;
2333         if (region == NULL) return NULL;
2334         if (region->regiontype != RGN_TYPE_WINDOW) {
2335                 ARegion *ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
2336                 return ar ? &(ar->v2d) : NULL;
2337         }
2338         return &(region->v2d);
2339 }
2340
2341
2342 /**
2343  * Calculate the scale per-axis of the drawing-area
2344  *
2345  * Is used to inverse correct drawing of icons, etc. that need to follow view
2346  * but not be affected by scale
2347  *
2348  * \param x, y: scale on each axis
2349  */
2350 void UI_view2d_scale_get(View2D *v2d, float *x, float *y) 
2351 {
2352         if (x) *x = BLI_rcti_size_x(&v2d->mask) / BLI_rctf_size_x(&v2d->cur);
2353         if (y) *y = BLI_rcti_size_y(&v2d->mask) / BLI_rctf_size_y(&v2d->cur);
2354 }
2355 /**
2356  * Same as ``UI_view2d_scale_get() - 1.0f / x, y``
2357  */
2358 void UI_view2d_scale_get_inverse(View2D *v2d, float *x, float *y)
2359 {
2360         if (x) *x = BLI_rctf_size_x(&v2d->cur) / BLI_rcti_size_x(&v2d->mask);
2361         if (y) *y = BLI_rctf_size_y(&v2d->cur) / BLI_rcti_size_y(&v2d->mask);
2362 }
2363
2364 /**
2365  * Simple functions for consistent center offset access.
2366  * Used by node editor to shift view center for each individual node tree.
2367  */
2368 void UI_view2d_center_get(struct View2D *v2d, float *x, float *y)
2369 {
2370         /* get center */
2371         if (x) *x = BLI_rctf_cent_x(&v2d->cur);
2372         if (y) *y = BLI_rctf_cent_y(&v2d->cur);
2373 }
2374 void UI_view2d_center_set(struct View2D *v2d, float x, float y)
2375 {
2376         BLI_rctf_recenter(&v2d->cur, x, y);
2377
2378         /* make sure that 'cur' rect is in a valid state as a result of these changes */
2379         UI_view2d_curRect_validate(v2d);
2380 }
2381
2382 /**
2383  * Simple pan function
2384  *  (0.0, 0.0) bottom left
2385  *  (0.5, 0.5) center
2386  *  (1.0, 1.0) top right.
2387  */
2388 void UI_view2d_offset(struct View2D *v2d, float xfac, float yfac)
2389 {
2390         if (xfac != -1.0f) {
2391                 const float xsize = BLI_rctf_size_x(&v2d->cur);
2392                 const float xmin = v2d->tot.xmin;
2393                 const float xmax = v2d->tot.xmax - xsize;
2394
2395                 v2d->cur.xmin = (xmin * (1.0f - xfac)) + (xmax * xfac);
2396                 v2d->cur.xmax = v2d->cur.xmin + xsize;
2397         }
2398
2399         if (yfac != -1.0f) {
2400                 const float ysize = BLI_rctf_size_y(&v2d->cur);
2401                 const float ymin = v2d->tot.ymin;
2402                 const float ymax = v2d->tot.ymax - ysize;
2403
2404                 v2d->cur.ymin = (ymin * (1.0f - yfac)) + (ymax * yfac);
2405                 v2d->cur.ymax = v2d->cur.ymin + ysize;
2406         }
2407
2408         UI_view2d_curRect_validate(v2d);
2409 }
2410
2411 /**
2412  * Check if mouse is within scrollers
2413  *
2414  * \param x, y: Mouse coordinates in screen (not region) space.
2415  *
2416  * \return appropriate code for match.
2417  * - 'h' = in horizontal scroller.
2418  * - 'v' = in vertical scroller.
2419  * - 0 = not in scroller.
2420  */
2421 short UI_view2d_mouse_in_scrollers(const bContext *C, View2D *v2d, int x, int y)
2422 {
2423         ARegion *ar = CTX_wm_region(C);
2424         int co[2];
2425         int scroll = view2d_scroll_mapped(v2d->scroll);
2426         
2427         /* clamp x,y to region-coordinates first */
2428         co[0] = x - ar->winrct.xmin;
2429         co[1] = y - ar->winrct.ymin;
2430         
2431         /* check if within scrollbars */
2432         if (scroll & V2D_SCROLL_HORIZONTAL) {
2433                 if (IN_2D_HORIZ_SCROLL(v2d, co)) return 'h';
2434         }
2435         if (scroll & V2D_SCROLL_VERTICAL) {
2436                 if (IN_2D_VERT_SCROLL(v2d, co)) return 'v';
2437         }
2438         
2439         /* not found */
2440         return 0;
2441 }
2442
2443 /* ******************* view2d text drawing cache ******************** */
2444
2445 typedef struct View2DString {
2446         struct View2DString *next;
2447         union {
2448                 unsigned char ub[4];
2449                 int pack;
2450         } col;
2451         rcti rect;
2452         int mval[2];
2453
2454         /* str is allocated past the end */
2455         char str[0];
2456 } View2DString;
2457
2458 /* assumes caches are used correctly, so for time being no local storage in v2d */
2459 static MemArena     *g_v2d_strings_arena = NULL;
2460 static View2DString *g_v2d_strings = NULL;
2461
2462 void UI_view2d_text_cache_add(
2463         View2D *v2d, float x, float y,
2464         const char *str, size_t str_len, const char col[4])
2465 {
2466         int mval[2];
2467         
2468         BLI_assert(str_len == strlen(str));
2469
2470         if (UI_view2d_view_to_region_clip(v2d, x, y, &mval[0], &mval[1])) {
2471                 int alloc_len = str_len + 1;
2472                 View2DString *v2s;
2473
2474                 if (g_v2d_strings_arena == NULL) {
2475                         g_v2d_strings_arena = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 14), __func__);
2476                 }
2477
2478                 v2s = BLI_memarena_alloc(g_v2d_strings_arena, sizeof(View2DString) + alloc_len);
2479
2480                 BLI_LINKS_PREPEND(g_v2d_strings, v2s);
2481
2482                 v2s->col.pack = *((const int *)col);
2483
2484                 memset(&v2s->rect, 0, sizeof(v2s->rect));
2485
2486                 v2s->mval[0] = mval[0];
2487                 v2s->mval[1] = mval[1];
2488
2489                 memcpy(v2s->str, str, alloc_len);
2490         }
2491 }
2492
2493 /* no clip (yet) */
2494 void UI_view2d_text_cache_add_rectf(
2495         View2D *v2d, const rctf *rect_view,
2496         const char *str, size_t str_len, const char col[4])
2497 {
2498         rcti rect;
2499
2500         BLI_assert(str_len == strlen(str));
2501
2502         if (UI_view2d_view_to_region_rcti_clip(v2d, rect_view, &rect)) {
2503                 int alloc_len = str_len + 1;
2504                 View2DString *v2s;
2505
2506                 if (g_v2d_strings_arena == NULL) {
2507                         g_v2d_strings_arena = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 14), __func__);
2508                 }
2509
2510                 v2s = BLI_memarena_alloc(g_v2d_strings_arena, sizeof(View2DString) + alloc_len);
2511
2512                 BLI_LINKS_PREPEND(g_v2d_strings, v2s);
2513
2514                 v2s->col.pack = *((const int *)col);
2515
2516                 v2s->rect = rect;
2517
2518                 v2s->mval[0] = v2s->rect.xmin;
2519                 v2s->mval[1] = v2s->rect.ymin;
2520
2521                 memcpy(v2s->str, str, alloc_len);
2522         }
2523 }
2524
2525
2526 void UI_view2d_text_cache_draw(ARegion *ar)
2527 {
2528         View2DString *v2s;
2529         int col_pack_prev = 0;
2530
2531         /* investigate using BLF_ascender() */
2532         const int font_id = BLF_default();
2533         const float default_height = g_v2d_strings ? BLF_height(font_id, "28", 3) : 0.0f;
2534
2535         wmOrtho2_region_pixelspace(ar);
2536
2537         for (v2s = g_v2d_strings; v2s; v2s = v2s->next) {
2538                 int xofs = 0, yofs;
2539
2540                 yofs = ceil(0.5f * (BLI_rcti_size_y(&v2s->rect) - default_height));
2541                 if (yofs < 1) yofs = 1;
2542
2543                 if (col_pack_prev != v2s->col.pack) {
2544                         BLF_color3ubv(font_id, v2s->col.ub);
2545                         col_pack_prev = v2s->col.pack;
2546                 }
2547
2548                 if (v2s->rect.xmin >= v2s->rect.xmax)
2549                         BLF_draw_default((float)(v2s->mval[0] + xofs), (float)(v2s->mval[1] + yofs), 0.0,
2550                                           v2s->str, BLF_DRAW_STR_DUMMY_MAX);
2551                 else {
2552                         BLF_enable(font_id, BLF_CLIPPING);
2553                         BLF_clipping(font_id, v2s->rect.xmin - 4, v2s->rect.ymin - 4, v2s->rect.xmax + 4, v2s->rect.ymax + 4);
2554                         BLF_draw_default(v2s->rect.xmin + xofs, v2s->rect.ymin + yofs, 0.0f,
2555                                          v2s->str, BLF_DRAW_STR_DUMMY_MAX);
2556                         BLF_disable(font_id, BLF_CLIPPING);
2557                 }
2558         }
2559         g_v2d_strings = NULL;
2560
2561         if (g_v2d_strings_arena) {
2562                 BLI_memarena_free(g_v2d_strings_arena);
2563                 g_v2d_strings_arena = NULL;
2564         }
2565 }
2566
2567
2568 /* ******************************************************** */
2569
2570