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