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