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