style chang, made mainly because I wanted to be able to add breakpoints to MEM_freeN...
[blender.git] / source / blender / editors / interface / interface.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation 2002-2008, full recode.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <string.h>
35 #include <ctype.h>
36  
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_scene_types.h"
40 #include "DNA_screen_types.h"
41 #include "DNA_userdef_types.h"
42
43 #include "BLI_math.h"
44 #include "BLI_blenlib.h"
45 #include "BLI_dynstr.h"
46 #include "BLI_utildefines.h"
47
48 #include "BKE_context.h"
49 #include "BKE_library.h"
50 #include "BKE_unit.h"
51 #include "BKE_screen.h"
52 #include "BKE_idprop.h"
53 #include "BKE_utildefines.h" /* FILE_MAX */
54
55 #include "BIF_gl.h"
56
57 #include "BLF_api.h"
58 #include "BLF_translation.h"
59
60 #include "UI_interface.h"
61
62 #include "IMB_imbuf.h"
63
64 #include "WM_api.h"
65 #include "WM_types.h"
66 #include "wm_subwindow.h"
67 #include "wm_window.h"
68
69 #include "RNA_access.h"
70
71 #include "BPY_extern.h"
72
73 #include "interface_intern.h"
74
75 #define MENU_WIDTH                      120
76 #define MENU_ITEM_HEIGHT        20
77 #define MENU_SEP_HEIGHT         6
78
79 #define PRECISION_FLOAT_MAX 6
80 #define PRECISION_FLOAT_MAX_POW 1000000 /* pow(10, PRECISION_FLOAT_MAX)  */
81
82 /* avoid unneeded calls to ui_get_but_val */
83 #define UI_BUT_VALUE_UNSET DBL_MAX
84 #define UI_GET_BUT_VALUE_INIT(_but, _value) if(_value == DBL_MAX) {  (_value)= ui_get_but_val(_but); }
85
86 /* 
87  * a full doc with API notes can be found in bf-blender/trunk/blender/doc/guides/interface_API.txt
88  * 
89  * uiBlahBlah()         external function
90  * ui_blah_blah()       internal function
91  */
92
93 static void ui_free_but(const bContext *C, uiBut *but);
94
95 /* ************* window matrix ************** */
96
97 void ui_block_to_window_fl(const ARegion *ar, uiBlock *block, float *x, float *y)
98 {
99         float gx, gy;
100         int sx, sy, getsizex, getsizey;
101
102         getsizex= ar->winrct.xmax-ar->winrct.xmin+1;
103         getsizey= ar->winrct.ymax-ar->winrct.ymin+1;
104         sx= ar->winrct.xmin;
105         sy= ar->winrct.ymin;
106
107         gx= *x;
108         gy= *y;
109
110         if(block->panel) {
111                 gx += block->panel->ofsx;
112                 gy += block->panel->ofsy;
113         }
114
115         *x= ((float)sx) + ((float)getsizex)*(0.5f+ 0.5f*(gx*block->winmat[0][0]+ gy*block->winmat[1][0]+ block->winmat[3][0]));
116         *y= ((float)sy) + ((float)getsizey)*(0.5f+ 0.5f*(gx*block->winmat[0][1]+ gy*block->winmat[1][1]+ block->winmat[3][1]));
117 }
118
119 void ui_block_to_window(const ARegion *ar, uiBlock *block, int *x, int *y)
120 {
121         float fx, fy;
122
123         fx= *x;
124         fy= *y;
125
126         ui_block_to_window_fl(ar, block, &fx, &fy);
127
128         *x= (int)(fx+0.5f);
129         *y= (int)(fy+0.5f);
130 }
131
132 void ui_block_to_window_rct(const ARegion *ar, uiBlock *block, rctf *graph, rcti *winr)
133 {
134         rctf tmpr;
135
136         tmpr= *graph;
137         ui_block_to_window_fl(ar, block, &tmpr.xmin, &tmpr.ymin);
138         ui_block_to_window_fl(ar, block, &tmpr.xmax, &tmpr.ymax);
139
140         winr->xmin= tmpr.xmin;
141         winr->ymin= tmpr.ymin;
142         winr->xmax= tmpr.xmax;
143         winr->ymax= tmpr.ymax;
144 }
145
146 void ui_window_to_block_fl(const ARegion *ar, uiBlock *block, float *x, float *y)       /* for mouse cursor */
147 {
148         float a, b, c, d, e, f, px, py;
149         int sx, sy, getsizex, getsizey;
150
151         getsizex= ar->winrct.xmax-ar->winrct.xmin+1;
152         getsizey= ar->winrct.ymax-ar->winrct.ymin+1;
153         sx= ar->winrct.xmin;
154         sy= ar->winrct.ymin;
155
156         a= 0.5f*((float)getsizex)*block->winmat[0][0];
157         b= 0.5f*((float)getsizex)*block->winmat[1][0];
158         c= 0.5f*((float)getsizex)*(1.0f+block->winmat[3][0]);
159
160         d= 0.5f*((float)getsizey)*block->winmat[0][1];
161         e= 0.5f*((float)getsizey)*block->winmat[1][1];
162         f= 0.5f*((float)getsizey)*(1.0f+block->winmat[3][1]);
163
164         px= *x - sx;
165         py= *y - sy;
166
167         *y=  (a*(py-f) + d*(c-px))/(a*e-d*b);
168         *x= (px- b*(*y)- c)/a;
169
170         if(block->panel) {
171                 *x -= block->panel->ofsx;
172                 *y -= block->panel->ofsy;
173         }
174 }
175
176 void ui_window_to_block(const ARegion *ar, uiBlock *block, int *x, int *y)
177 {
178         float fx, fy;
179
180         fx= *x;
181         fy= *y;
182
183         ui_window_to_block_fl(ar, block, &fx, &fy);
184
185         *x= (int)(fx+0.5f);
186         *y= (int)(fy+0.5f);
187 }
188
189 void ui_window_to_region(const ARegion *ar, int *x, int *y)
190 {
191         *x-= ar->winrct.xmin;
192         *y-= ar->winrct.ymin;
193 }
194
195 /* ******************* block calc ************************* */
196
197 void ui_block_translate(uiBlock *block, int x, int y)
198 {
199         uiBut *bt;
200
201         for(bt= block->buttons.first; bt; bt=bt->next) {
202                 bt->x1 += x;
203                 bt->y1 += y;
204                 bt->x2 += x;
205                 bt->y2 += y;
206         }
207
208         block->minx += x;
209         block->miny += y;
210         block->maxx += x;
211         block->maxy += y;
212 }
213
214 static void ui_text_bounds_block(uiBlock *block, float offset)
215 {
216         uiStyle *style=UI_GetStyle();
217         uiBut *bt;
218         int i = 0, j, x1addval= offset, nextcol;
219         int lastcol= 0, col= 0;
220         
221         uiStyleFontSet(&style->widget);
222         
223         for(bt= block->buttons.first; bt; bt= bt->next) {
224                 if(bt->type!=SEPR) {
225                         j= BLF_width(style->widget.uifont_id, bt->drawstr);
226
227                         if(j > i) i = j;
228                 }
229
230                 if(bt->next && bt->x1 < bt->next->x1)
231                         lastcol++;
232         }
233
234         /* cope with multi collumns */
235         bt= block->buttons.first;
236         while(bt) {
237                 if(bt->next && bt->x1 < bt->next->x1) {
238                         nextcol= 1;
239                         col++;
240                 }
241                 else nextcol= 0;
242                 
243                 bt->x1 = x1addval;
244                 bt->x2 = bt->x1 + i + block->bounds;
245                 
246                 if(col == lastcol)
247                         bt->x2= MAX2(bt->x2, offset + block->minbounds);
248
249                 ui_check_but(bt);       // clips text again
250                 
251                 if(nextcol)
252                         x1addval+= i + block->bounds;
253                 
254                 bt= bt->next;
255         }
256 }
257
258 void ui_bounds_block(uiBlock *block)
259 {
260         uiBut *bt;
261         int xof;
262         
263         if(block->buttons.first==NULL) {
264                 if(block->panel) {
265                         block->minx= 0.0; block->maxx= block->panel->sizex;
266                         block->miny= 0.0; block->maxy= block->panel->sizey;
267                 }
268         }
269         else {
270         
271                 block->minx= block->miny= 10000;
272                 block->maxx= block->maxy= -10000;
273                 
274                 bt= block->buttons.first;
275                 while(bt) {
276                         if(bt->x1 < block->minx) block->minx= bt->x1;
277                         if(bt->y1 < block->miny) block->miny= bt->y1;
278         
279                         if(bt->x2 > block->maxx) block->maxx= bt->x2;
280                         if(bt->y2 > block->maxy) block->maxy= bt->y2;
281
282                         bt= bt->next;
283                 }
284                 
285                 block->minx -= block->bounds;
286                 block->miny -= block->bounds;
287                 block->maxx += block->bounds;
288                 block->maxy += block->bounds;
289         }
290
291         block->maxx= block->minx + MAX2(block->maxx - block->minx, block->minbounds);
292
293         /* hardcoded exception... but that one is annoying with larger safety */ 
294         bt= block->buttons.first;
295         if(bt && strncmp(bt->str, "ERROR", 5)==0) xof= 10;
296         else xof= 40;
297         
298         block->safety.xmin= block->minx-xof;
299         block->safety.ymin= block->miny-xof;
300         block->safety.xmax= block->maxx+xof;
301         block->safety.ymax= block->maxy+xof;
302 }
303
304 static void ui_centered_bounds_block(const bContext *C, uiBlock *block)
305 {
306         wmWindow *window= CTX_wm_window(C);
307         int xmax, ymax;
308         int startx, starty;
309         int width, height;
310         
311         /* note: this is used for the splash where window bounds event has not been
312          * updated by ghost, get the window bounds from ghost directly */
313
314         // wm_window_get_size(window, &xmax, &ymax);
315         wm_window_get_size_ghost(window, &xmax, &ymax);
316         
317         ui_bounds_block(block);
318         
319         width= block->maxx - block->minx;
320         height= block->maxy - block->miny;
321         
322         startx = (xmax * 0.5f) - (width * 0.5f);
323         starty = (ymax * 0.5f) - (height * 0.5f);
324         
325         ui_block_translate(block, startx - block->minx, starty - block->miny);
326         
327         /* now recompute bounds and safety */
328         ui_bounds_block(block);
329         
330 }
331 static void ui_popup_bounds_block(const bContext *C, uiBlock *block, int bounds_calc)
332 {
333         wmWindow *window= CTX_wm_window(C);
334         int startx, starty, endx, endy, width, height, oldwidth, oldheight;
335         int oldbounds, xmax, ymax;
336
337         oldbounds= block->bounds;
338
339         /* compute mouse position with user defined offset */
340         ui_bounds_block(block);
341         
342         wm_window_get_size(window, &xmax, &ymax);
343
344         oldwidth= block->maxx - block->minx;
345         oldheight= block->maxy - block->miny;
346
347         /* first we ensure wide enough text bounds */
348         if(bounds_calc==UI_BLOCK_BOUNDS_POPUP_MENU) {
349                 if(block->flag & UI_BLOCK_LOOP) {
350                         block->bounds= 50;
351                         ui_text_bounds_block(block, block->minx);
352                 }
353         }
354
355         /* next we recompute bounds */
356         block->bounds= oldbounds;
357         ui_bounds_block(block);
358
359         /* and we adjust the position to fit within window */
360         width= block->maxx - block->minx;
361         height= block->maxy - block->miny;
362
363         /* avoid divide by zero below, caused by calling with no UI, but better not crash */
364         oldwidth= oldwidth > 0 ? oldwidth : MAX2(1, width);
365         oldheight= oldheight > 0 ? oldheight : MAX2(1, height);
366
367         /* offset block based on mouse position, user offset is scaled
368          * along in case we resized the block in ui_text_bounds_block */
369         startx= window->eventstate->x + block->minx + (block->mx*width)/oldwidth;
370         starty= window->eventstate->y + block->miny + (block->my*height)/oldheight;
371
372         if(startx<10)
373                 startx= 10;
374         if(starty<10)
375                 starty= 10;
376         
377         endx= startx+width;
378         endy= starty+height;
379         
380         if(endx>xmax) {
381                 endx= xmax-10;
382                 startx= endx-width;
383         }
384         if(endy>ymax-20) {
385                 endy= ymax-20;
386                 starty= endy-height;
387         }
388
389         ui_block_translate(block, startx - block->minx, starty - block->miny);
390
391         /* now recompute bounds and safety */
392         ui_bounds_block(block);
393 }
394
395 /* used for various cases */
396 void uiBoundsBlock(uiBlock *block, int addval)
397 {
398         if(block==NULL)
399                 return;
400         
401         block->bounds= addval;
402         block->dobounds= UI_BLOCK_BOUNDS;
403 }
404
405 /* used for pulldowns */
406 void uiTextBoundsBlock(uiBlock *block, int addval)
407 {
408         block->bounds= addval;
409         block->dobounds= UI_BLOCK_BOUNDS_TEXT;
410 }
411
412 /* used for block popups */
413 void uiPopupBoundsBlock(uiBlock *block, int addval, int mx, int my)
414 {
415         block->bounds= addval;
416         block->dobounds= UI_BLOCK_BOUNDS_POPUP_MOUSE;
417         block->mx= mx;
418         block->my= my;
419 }
420
421 /* used for menu popups */
422 void uiMenuPopupBoundsBlock(uiBlock *block, int addval, int mx, int my)
423 {
424         block->bounds= addval;
425         block->dobounds= UI_BLOCK_BOUNDS_POPUP_MENU;
426         block->mx= mx;
427         block->my= my;
428 }
429
430 /* used for centered popups, i.e. splash */
431 void uiCenteredBoundsBlock(uiBlock *block, int addval)
432 {
433         block->bounds= addval;
434         block->dobounds= UI_BLOCK_BOUNDS_POPUP_CENTER;
435 }
436
437 void uiExplicitBoundsBlock(uiBlock *block, int minx, int miny, int maxx, int maxy)
438 {
439         block->minx = minx;
440         block->miny = miny;
441         block->maxx = maxx;
442         block->maxy = maxy;
443         block->dobounds = 0;
444 }
445
446 /* ************** LINK LINE DRAWING  ************* */
447
448 /* link line drawing is not part of buttons or theme.. so we stick with it here */
449
450 static int ui_but_float_precision(uiBut *but, double value)
451 {
452         int prec;
453
454         /* first check if prec is 0 and fallback to a simple default */
455         if((prec= (int)but->a2) == 0) {
456                 prec= (but->hardmax < 10.001f) ? 3 : 2;
457         }
458
459         /* check on the number of decimal places neede to display
460          * the number, this is so 0.00001 is not displayed as 0.00,
461          * _but_, this is only for small values si 10.0001 will not get
462          * the same treatment */
463         if(value != 0.0 && (value= ABS(value)) < 0.1) {
464                 int value_i= (int)((value * PRECISION_FLOAT_MAX_POW) + 0.5);
465                 if(value_i != 0) {
466                         const int prec_span= 3; /* show: 0.01001, 5 would allow 0.0100001 for eg. */
467                         int test_prec;
468                         int prec_min= -1;
469                         int dec_flag= 0;
470                         int i= PRECISION_FLOAT_MAX;
471                         while(i && value_i) {
472                                 if(value_i % 10) {
473                                         dec_flag |= 1<<i;
474                                         prec_min= i;
475                                 }
476                                 value_i /= 10;
477                                 i--;
478                         }
479
480                         /* even though its a small value, if the second last digit is not 0, use it */
481                         test_prec = prec_min;
482
483                         dec_flag= (dec_flag >> (prec_min + 1)) & ((1 << prec_span) - 1);
484
485                         while(dec_flag) {
486                                 test_prec++;
487                                 dec_flag = dec_flag >> 1;
488                         }
489
490                         if(test_prec > prec) {
491                                 prec= test_prec;
492                         }
493                 }
494         }
495
496         CLAMP(prec, 1, PRECISION_FLOAT_MAX);
497
498         return prec;
499 }
500
501 static void ui_draw_linkline(uiLinkLine *line)
502 {
503         rcti rect;
504
505         if(line->from==NULL || line->to==NULL) return;
506         
507         rect.xmin= (line->from->x1+line->from->x2)/2.0f;
508         rect.ymin= (line->from->y1+line->from->y2)/2.0f;
509         rect.xmax= (line->to->x1+line->to->x2)/2.0f;
510         rect.ymax= (line->to->y1+line->to->y2)/2.0f;
511         
512         if(line->flag & UI_SELECT) 
513                 glColor3ub(100,100,100);
514         else 
515                 glColor3ub(0,0,0);
516
517         ui_draw_link_bezier(&rect);
518 }
519
520 static void ui_draw_links(uiBlock *block)
521 {
522         uiBut *but;
523         uiLinkLine *line;
524         
525         but= block->buttons.first;
526         while(but) {
527                 if(but->type==LINK && but->link) {
528                         line= but->link->lines.first;
529                         while(line) {
530                                 ui_draw_linkline(line);
531                                 line= line->next;
532                         }
533                 }
534                 but= but->next;
535         }       
536 }
537
538 /* ************** BLOCK ENDING FUNCTION ************* */
539
540 /* NOTE: if but->poin is allocated memory for every defbut, things fail... */
541 static int ui_but_equals_old(uiBut *but, uiBut *oldbut)
542 {
543         /* various properties are being compared here, hopefully sufficient
544          * to catch all cases, but it is simple to add more checks later */
545         if(but->retval != oldbut->retval) return 0;
546         if(but->rnapoin.data != oldbut->rnapoin.data) return 0;
547         if(but->rnaprop != oldbut->rnaprop)
548                 if(but->rnaindex != oldbut->rnaindex) return 0;
549         if(but->func != oldbut->func) return 0;
550         if(but->funcN != oldbut->funcN) return 0;
551         if(oldbut->func_arg1 != oldbut && but->func_arg1 != oldbut->func_arg1) return 0;
552         if(oldbut->func_arg2 != oldbut && but->func_arg2 != oldbut->func_arg2) return 0;
553         if(!but->funcN && ((but->poin != oldbut->poin && (uiBut*)oldbut->poin != oldbut) || but->pointype != oldbut->pointype)) return 0;
554         if(but->optype != oldbut->optype) return 0;
555
556         return 1;
557 }
558
559 /* oldbut is being inserted in new block, so we use the lines from new button, and replace button pointers */
560 static void ui_but_update_linklines(uiBlock *block, uiBut *oldbut, uiBut *newbut)
561 {
562         uiLinkLine *line;
563         uiBut *but;
564         
565         /* if active button is LINK */
566         if(newbut->type==LINK && newbut->link) {
567                 
568                 SWAP(uiLink *, oldbut->link, newbut->link);
569                 
570                 for(line= oldbut->link->lines.first; line; line= line->next) {
571                         if(line->to==newbut)
572                                 line->to= oldbut;
573                         if(line->from==newbut)
574                                 line->from= oldbut;
575                 }
576         }               
577         
578         /* check all other button links */
579         for(but= block->buttons.first; but; but= but->next) {
580                 if(but!=newbut && but->type==LINK && but->link) {
581                         for(line= but->link->lines.first; line; line= line->next) {
582                                 if(line->to==newbut)
583                                         line->to= oldbut;
584                                 if(line->from==newbut)
585                                         line->from= oldbut;
586                         }
587                 }
588         }
589 }
590
591 static int ui_but_update_from_old_block(const bContext *C, uiBlock *block, uiBut **butpp)
592 {
593         uiBlock *oldblock;
594         uiBut *oldbut, *but= *butpp;
595         int found= 0;
596
597         oldblock= block->oldblock;
598         if(!oldblock)
599                 return found;
600
601         for(oldbut=oldblock->buttons.first; oldbut; oldbut=oldbut->next) {
602                 if(ui_but_equals_old(oldbut, but)) {
603                         if(oldbut->active) {
604 #if 0
605 //                              but->flag= oldbut->flag;
606 #else
607                                 /* exception! redalert flag can't be update from old button. 
608                                  * perhaps it should only copy specific flags rather than all. */
609 //                              but->flag= (oldbut->flag & ~UI_BUT_REDALERT) | (but->flag & UI_BUT_REDALERT);
610 #endif
611 //                              but->active= oldbut->active;
612 //                              but->pos= oldbut->pos;
613 //                              but->ofs= oldbut->ofs;
614 //                              but->editstr= oldbut->editstr;
615 //                              but->editval= oldbut->editval;
616 //                              but->editvec= oldbut->editvec;
617 //                              but->editcoba= oldbut->editcoba;
618 //                              but->editcumap= oldbut->editcumap;
619 //                              but->selsta= oldbut->selsta;
620 //                              but->selend= oldbut->selend;
621 //                              but->softmin= oldbut->softmin;
622 //                              but->softmax= oldbut->softmax;
623 //                              but->linkto[0]= oldbut->linkto[0];
624 //                              but->linkto[1]= oldbut->linkto[1];
625                                 found= 1;
626 //                              oldbut->active= NULL;
627                         
628                                 /* move button over from oldblock to new block */
629                                 BLI_remlink(&oldblock->buttons, oldbut);
630                                 BLI_insertlink(&block->buttons, but, oldbut);
631                                 oldbut->block= block;
632                                 *butpp= oldbut;
633                                 
634                                 /* still stuff needs to be copied */
635                                 oldbut->x1= but->x1; oldbut->y1= but->y1;
636                                 oldbut->x2= but->x2; oldbut->y2= but->y2;
637                                 oldbut->context= but->context; /* set by Layout */
638                                 
639                                 /* typically the same pointers, but not on undo/redo */
640                                 /* XXX some menu buttons store button itself in but->poin. Ugly */
641                                 if(oldbut->poin != (char *)oldbut) {
642                                         SWAP(char *, oldbut->poin, but->poin)
643                                         SWAP(void *, oldbut->func_argN, but->func_argN)
644                                 }
645                                 
646                                 /* copy hardmin for list rows to prevent 'sticking' highlight to mouse position
647                                  * when scrolling without moving mouse (see [#28432]) */
648                                 if(ELEM(oldbut->type, ROW, LISTROW))
649                                         oldbut->hardmax= but->hardmax;
650                                 
651                                 ui_but_update_linklines(block, oldbut, but);
652                                 
653                                 BLI_remlink(&block->buttons, but);
654                                 ui_free_but(C, but);
655                                 
656                                 /* note: if layout hasn't been applied yet, it uses old button pointers... */
657                         }
658                         else {
659                                 /* ensures one button can get activated, and in case the buttons
660                                  * draw are the same this gives O(1) lookup for each button */
661                                 BLI_remlink(&oldblock->buttons, oldbut);
662                                 ui_free_but(C, oldbut);
663                         }
664                         
665                         break;
666                 }
667         }
668         
669         return found;
670 }
671
672 /* needed for temporarily rename buttons, such as in outliner or fileselect,
673  * they should keep calling uiDefButs to keep them alive */
674 /* returns 0 when button removed */
675 int uiButActiveOnly(const bContext *C, uiBlock *block, uiBut *but)
676 {
677         uiBlock *oldblock;
678         uiBut *oldbut;
679         int activate= 0, found= 0, isactive= 0;
680         
681         oldblock= block->oldblock;
682         if(!oldblock)
683                 activate= 1;
684         else {
685                 for(oldbut=oldblock->buttons.first; oldbut; oldbut=oldbut->next) {
686                         if(ui_but_equals_old(oldbut, but)) {
687                                 found= 1;
688                                 
689                                 if(oldbut->active)
690                                         isactive= 1;
691                                 
692                                 break;
693                         }
694                 }
695         }
696         if(activate || found==0) {
697                 ui_button_activate_do( (bContext *)C, CTX_wm_region(C), but);
698         }
699         else if(found && isactive==0) {
700                 
701                 BLI_remlink(&block->buttons, but);
702                 ui_free_but(C, but);
703                 return 0;
704         }
705         
706         return 1;
707 }
708
709 /* use to check if we need to disable undo, but dont make any changes
710  * returns FALSE if undo needs to be disabled. */
711 static int ui_but_is_rna_undo(uiBut *but)
712 {
713         if(but->rnapoin.id.data) {
714                 /* avoid undo push for buttons who's ID are screen or wm level
715                  * we could disable undo for buttons with no ID too but may have
716                  * unforeseen consequences, so best check for ID's we _know_ are not
717                  * handled by undo - campbell */
718                 ID *id= but->rnapoin.id.data;
719                 if(ID_CHECK_UNDO(id) == FALSE) {
720                         return FALSE;
721                 }
722                 else {
723                         return TRUE;
724                 }
725         }
726         else if (but->rnapoin.type && !RNA_struct_undo_check(but->rnapoin.type)) {
727                 return FALSE;
728         }
729
730         return TRUE;
731 }
732
733 /* assigns automatic keybindings to menu items for fast access
734  * (underline key in menu) */
735 static void ui_menu_block_set_keyaccels(uiBlock *block)
736 {
737         uiBut *but;
738
739         unsigned int menu_key_mask= 0;
740         unsigned char menu_key;
741         const char *str_pt;
742         int pass;
743         int tot_missing= 0;
744
745         /* only do it before bounding */
746         if(block->minx != block->maxx)
747                 return;
748
749         for(pass=0; pass<2; pass++) {
750                 /* 2 Passes, on for first letter only, second for any letter if first fails
751                  * fun first pass on all buttons so first word chars always get first priority */
752
753                 for(but=block->buttons.first; but; but=but->next) {
754                         if(!ELEM4(but->type, BUT, MENU, BLOCK, PULLDOWN) || (but->flag & UI_HIDDEN)) {
755                                 /* pass */
756                         }
757                         else if(but->menu_key=='\0') {
758                                 if(but->str) {
759                                         for(str_pt= but->str; *str_pt; ) {
760                                                 menu_key= tolower(*str_pt);
761                                                 if((menu_key >= 'a' && menu_key <= 'z') && !(menu_key_mask & 1<<(menu_key-'a'))) {
762                                                         menu_key_mask |= 1<<(menu_key-'a');
763                                                         break;
764                                                 }
765
766                                                 if(pass==0) {
767                                                         /* Skip to next delimeter on first pass (be picky) */
768                                                         while(isalpha(*str_pt))
769                                                                 str_pt++;
770
771                                                         if(*str_pt)
772                                                                 str_pt++;
773                                                 }
774                                                 else {
775                                                         /* just step over every char second pass and find first usable key */
776                                                         str_pt++;
777                                                 }
778                                         }
779
780                                         if(*str_pt) {
781                                                 but->menu_key= menu_key;
782                                         }
783                                         else {
784                                                 /* run second pass */
785                                                 tot_missing++;
786                                         }
787
788                                         /* if all keys have been used just exit, unlikely */
789                                         if(menu_key_mask == (1<<26)-1) {
790                                                 return;
791                                         }
792                                 }
793                         }
794                 }
795
796                 /* check if second pass is needed */
797                 if(!tot_missing) {
798                         break;
799                 }
800         }
801 }
802
803
804 static void ui_menu_block_set_keymaps(const bContext *C, uiBlock *block)
805 {
806         uiBut *but;
807         char buf[512];
808
809         /* for menu's */
810         MenuType *mt;
811         IDProperty *prop_menu= NULL;
812         IDProperty *prop_menu_name= NULL;
813
814         /* only do it before bounding */
815         if(block->minx != block->maxx)
816                 return;
817
818
819 #define UI_MENU_KEY_STR_CAT                                                   \
820         char *butstr_orig= BLI_strdup(but->str);                                  \
821         BLI_snprintf(but->strdata,                                                \
822                                  sizeof(but->strdata),                                        \
823                                  "%s|%s",                                                     \
824                                  butstr_orig, buf);                                           \
825         MEM_freeN(butstr_orig);                                                   \
826         but->str= but->strdata;                                                   \
827         ui_check_but(but);                                                        \
828
829
830         for(but=block->buttons.first; but; but=but->next) {
831                 if(but->optype) {
832                         IDProperty *prop= (but->opptr)? but->opptr->data: NULL;
833
834                         if(WM_key_event_operator_string(C, but->optype->idname, but->opcontext, prop, TRUE,
835                                                         buf, sizeof(buf)))
836                         {
837                                 UI_MENU_KEY_STR_CAT
838                         }
839                 }
840                 else if ((mt= uiButGetMenuType(but))) {
841                         /* only allocate menu property once */
842                         if (prop_menu == NULL) {
843                                 /* annoying, create a property */
844                                 IDPropertyTemplate val = {0};
845                                 prop_menu= IDP_New(IDP_GROUP, &val, __func__); /* dummy, name is unimportant  */
846                                 IDP_AddToGroup(prop_menu, (prop_menu_name= IDP_NewString("", "name", sizeof(mt->idname))));
847                         }
848
849                         IDP_AssignString(prop_menu_name, mt->idname, sizeof(mt->idname));
850
851                         if(WM_key_event_operator_string(C, "WM_OT_call_menu", WM_OP_INVOKE_REGION_WIN, prop_menu, FALSE,
852                                                         buf, sizeof(buf)))
853                         {
854                                 UI_MENU_KEY_STR_CAT
855                         }
856                 }
857         }
858
859         if (prop_menu) {
860                 IDP_FreeProperty(prop_menu);
861                 MEM_freeN(prop_menu);
862         }
863
864 #undef UI_MENU_KEY_STR_CAT
865
866 }
867
868 void uiEndBlock(const bContext *C, uiBlock *block)
869 {
870         uiBut *but;
871         Scene *scene= CTX_data_scene(C);
872
873         /* inherit flags from 'old' buttons that was drawn here previous, based
874          * on matching buttons, we need this to make button event handling non
875          * blocking, while still allowing buttons to be remade each redraw as it
876          * is expected by blender code */
877         for(but=block->buttons.first; but; but=but->next) {
878                 if(ui_but_update_from_old_block(C, block, &but))
879                         ui_check_but(but);
880                 
881                 /* temp? Proper check for greying out */
882                 if(but->optype) {
883                         wmOperatorType *ot= but->optype;
884
885                         if(but->context)
886                                 CTX_store_set((bContext*)C, but->context);
887
888                         if(ot == NULL || WM_operator_poll_context((bContext*)C, ot, but->opcontext)==0) {
889                                 but->flag |= UI_BUT_DISABLED;
890                                 but->lock = 1;
891                         }
892
893                         if(but->context)
894                                 CTX_store_set((bContext*)C, NULL);
895                 }
896
897                 ui_but_anim_flag(but, (scene)? scene->r.cfra: 0.0f);
898         }
899
900         if(block->oldblock) {
901                 block->auto_open= block->oldblock->auto_open;
902                 block->auto_open_last= block->oldblock->auto_open_last;
903                 block->tooltipdisabled= block->oldblock->tooltipdisabled;
904
905                 block->oldblock= NULL;
906         }
907
908         /* handle pending stuff */
909         if(block->layouts.first) uiBlockLayoutResolve(block, NULL, NULL);
910         ui_block_do_align(block);
911         if((block->flag & UI_BLOCK_LOOP) && (block->flag & UI_BLOCK_NUMSELECT)) {
912                 ui_menu_block_set_keyaccels(block); /* could use a different flag to check */
913         }
914         if(block->flag & UI_BLOCK_LOOP) ui_menu_block_set_keymaps(C, block);
915         
916         /* after keymaps! */
917         if(block->dobounds == UI_BLOCK_BOUNDS) ui_bounds_block(block);
918         else if(block->dobounds == UI_BLOCK_BOUNDS_TEXT) ui_text_bounds_block(block, 0.0f);
919         else if(block->dobounds == UI_BLOCK_BOUNDS_POPUP_CENTER) ui_centered_bounds_block(C, block);
920         else if(block->dobounds) ui_popup_bounds_block(C, block, block->dobounds);
921
922         if(block->minx==0.0f && block->maxx==0.0f) uiBoundsBlock(block, 0);
923         if(block->flag & UI_BUT_ALIGN) uiBlockEndAlign(block);
924
925         block->endblock= 1;
926 }
927
928 /* ************** BLOCK DRAWING FUNCTION ************* */
929
930 void ui_fontscale(short *points, float aspect)
931 {
932         if(aspect < 0.9f || aspect > 1.1f) {
933                 float pointsf= *points;
934                 
935                 /* for some reason scaling fonts goes too fast compared to widget size */
936                 aspect= sqrt(aspect);
937                 pointsf /= aspect;
938                 
939                 if(aspect > 1.0f)
940                         *points= ceilf(pointsf);
941                 else
942                         *points= floorf(pointsf);
943         }
944 }
945
946 /* project button or block (but==NULL) to pixels in regionspace */
947 static void ui_but_to_pixelrect(rcti *rect, const ARegion *ar, uiBlock *block, uiBut *but)
948 {
949         float gx, gy;
950         float getsizex, getsizey;
951         
952         getsizex= ar->winx;
953         getsizey= ar->winy;
954
955         gx= (but?but->x1:block->minx) + (block->panel?block->panel->ofsx:0.0f);
956         gy= (but?but->y1:block->miny) + (block->panel?block->panel->ofsy:0.0f);
957         
958         rect->xmin= floorf(getsizex*(0.5f+ 0.5f*(gx*block->winmat[0][0]+ gy*block->winmat[1][0]+ block->winmat[3][0])));
959         rect->ymin= floorf(getsizey*(0.5f+ 0.5f*(gx*block->winmat[0][1]+ gy*block->winmat[1][1]+ block->winmat[3][1])));
960         
961         gx= (but?but->x2:block->maxx) + (block->panel?block->panel->ofsx:0.0f);
962         gy= (but?but->y2:block->maxy) + (block->panel?block->panel->ofsy:0.0f);
963         
964         rect->xmax= floorf(getsizex*(0.5f+ 0.5f*(gx*block->winmat[0][0]+ gy*block->winmat[1][0]+ block->winmat[3][0])));
965         rect->ymax= floorf(getsizey*(0.5f+ 0.5f*(gx*block->winmat[0][1]+ gy*block->winmat[1][1]+ block->winmat[3][1])));
966
967 }
968
969 /* uses local copy of style, to scale things down, and allow widgets to change stuff */
970 void uiDrawBlock(const bContext *C, uiBlock *block)
971 {
972         uiStyle style= *UI_GetStyle();  // XXX pass on as arg
973         ARegion *ar;
974         uiBut *but;
975         rcti rect;
976         int multisample_enabled;
977         
978         /* get menu region or area region */
979         ar= CTX_wm_menu(C);
980         if(!ar)
981                 ar= CTX_wm_region(C);
982
983         if(!block->endblock)
984                 uiEndBlock(C, block);
985
986         /* disable AA, makes widgets too blurry */
987         multisample_enabled= glIsEnabled(GL_MULTISAMPLE_ARB);
988         if(multisample_enabled)
989                 glDisable(GL_MULTISAMPLE_ARB);
990
991         /* we set this only once */
992         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
993         
994         /* scale fonts */
995         ui_fontscale(&style.paneltitle.points, block->aspect);
996         ui_fontscale(&style.grouplabel.points, block->aspect);
997         ui_fontscale(&style.widgetlabel.points, block->aspect);
998         ui_fontscale(&style.widget.points, block->aspect);
999         
1000         /* scale block min/max to rect */
1001         ui_but_to_pixelrect(&rect, ar, block, NULL);
1002         
1003         /* pixel space for AA widgets */
1004         glMatrixMode(GL_PROJECTION);
1005         glPushMatrix();
1006         glMatrixMode(GL_MODELVIEW);
1007         glPushMatrix();
1008         glLoadIdentity();
1009         
1010         wmOrtho2(-0.01f, ar->winx-0.01f, -0.01f, ar->winy-0.01f);
1011         
1012         /* back */
1013         if(block->flag & UI_BLOCK_LOOP)
1014                 ui_draw_menu_back(&style, block, &rect);
1015         else if(block->panel)
1016                 ui_draw_aligned_panel(&style, block, &rect);
1017
1018         /* widgets */
1019         for(but= block->buttons.first; but; but= but->next) {
1020                 if(!(but->flag & (UI_HIDDEN|UI_SCROLLED))) {
1021                         ui_but_to_pixelrect(&rect, ar, block, but);
1022                 
1023                         /* XXX: figure out why invalid coordinates happen when closing render window */
1024                         /* and material preview is redrawn in main window (temp fix for bug #23848) */
1025                         if(rect.xmin < rect.xmax && rect.ymin < rect.ymax)
1026                                 ui_draw_but(C, ar, &style, but, &rect);
1027                 }
1028         }
1029         
1030         /* restore matrix */
1031         glMatrixMode(GL_PROJECTION);
1032         glPopMatrix();
1033         glMatrixMode(GL_MODELVIEW);
1034         glPopMatrix();
1035
1036         if(multisample_enabled)
1037                 glEnable(GL_MULTISAMPLE_ARB);
1038         
1039         ui_draw_links(block);
1040 }
1041
1042 /* ************* EVENTS ************* */
1043
1044 static void ui_is_but_sel(uiBut *but, double *value)
1045 {
1046         short is_push=0, is_true=1;
1047
1048         if(ELEM3(but->type, TOGN, ICONTOGN, OPTIONN)) is_true= 0;
1049
1050         if( but->bit ) {
1051                 int lvalue;
1052                 UI_GET_BUT_VALUE_INIT(but, *value)
1053                 lvalue= (int)*value;
1054                 if( BTST(lvalue, (but->bitnr)) ) is_push= is_true;
1055                 else is_push= !is_true;
1056         }
1057         else {
1058                 switch(but->type) {
1059                 case BUT:
1060                         is_push= 2;
1061                         break;
1062                 case HOTKEYEVT:
1063                 case KEYEVT:
1064                         is_push= 2;
1065                         break;
1066                 case TOGBUT:
1067                 case TOG:
1068                 case TOGR:
1069                 case TOG3:
1070                 case BUT_TOGDUAL:
1071                 case ICONTOG:
1072                 case OPTION:
1073                         UI_GET_BUT_VALUE_INIT(but, *value)
1074                         if(*value != (double)but->hardmin) is_push= 1;
1075                         break;
1076                 case ICONTOGN:
1077                 case TOGN:
1078                 case OPTIONN:
1079                         UI_GET_BUT_VALUE_INIT(but, *value)
1080                         if(*value==0.0) is_push= 1;
1081                         break;
1082                 case ROW:
1083                 case LISTROW:
1084                         UI_GET_BUT_VALUE_INIT(but, *value)
1085                         /* support for rna enum buts */
1086                         if(but->rnaprop && (RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG)) {
1087                                 if((int)*value & (int)but->hardmax) is_push= 1;
1088                         }
1089                         else {
1090                                 if(*value == (double)but->hardmax) is_push= 1;
1091                         }
1092                         break;
1093                 case COL:
1094                         is_push= 2;
1095                         break;
1096                 default:
1097                         is_push= 2;
1098                         break;
1099                 }
1100         }
1101         
1102         if(is_push==2);
1103         else if(is_push==1) but->flag |= UI_SELECT;
1104         else but->flag &= ~UI_SELECT;
1105 }
1106
1107 static uiBut *ui_find_inlink(uiBlock *block, void *poin)
1108 {
1109         uiBut *but;
1110         
1111         but= block->buttons.first;
1112         while(but) {
1113                 if(but->type==INLINK) {
1114                         if(but->poin == poin) return but;
1115                 }
1116                 but= but->next;
1117         }
1118         return NULL;
1119 }
1120
1121 static void ui_add_link_line(ListBase *listb, uiBut *but, uiBut *bt)
1122 {
1123         uiLinkLine *line;
1124         
1125         line= MEM_callocN(sizeof(uiLinkLine), "linkline");
1126         BLI_addtail(listb, line);
1127         line->from= but;
1128         line->to= bt;
1129 }
1130
1131 uiBut *uiFindInlink(uiBlock *block, void *poin)
1132 {
1133         return ui_find_inlink(block, poin);
1134 }
1135
1136 void uiComposeLinks(uiBlock *block)
1137 {
1138         uiBut *but, *bt;
1139         uiLink *link;
1140         void ***ppoin;
1141         int a;
1142         
1143         but= block->buttons.first;
1144         while(but) {
1145                 if(but->type==LINK) {
1146                         link= but->link;
1147                         
1148                         /* for all pointers in the array */
1149                         if(link) {
1150                                 if(link->ppoin) {
1151                                         ppoin= link->ppoin;
1152                                         for(a=0; a < *(link->totlink); a++) {
1153                                                 bt= ui_find_inlink(block, (*ppoin)[a] );
1154                                                 if(bt) {
1155                                                         ui_add_link_line(&link->lines, but, bt);
1156                                                 }
1157                                         }
1158                                 }
1159                                 else if(link->poin) {
1160                                         bt= ui_find_inlink(block, *(link->poin) );
1161                                         if(bt) {
1162                                                 ui_add_link_line(&link->lines, but, bt);
1163                                         }
1164                                 }
1165                         }
1166                 }
1167                 but= but->next;
1168         }
1169 }
1170
1171
1172 /* ************************************************ */
1173
1174 void uiBlockSetButLock(uiBlock *block, int val, const char *lockstr)
1175 {
1176         if(val) {
1177                 block->lock= val ? 1:0;
1178                 block->lockstr= lockstr;
1179         }
1180 }
1181
1182 void uiBlockClearButLock(uiBlock *block)
1183 {
1184         block->lock= 0;
1185         block->lockstr= NULL;
1186 }
1187
1188 /* *************************************************************** */
1189
1190 void ui_delete_linkline(uiLinkLine *line, uiBut *but)
1191 {
1192         uiLink *link;
1193         int a, b;
1194         
1195         BLI_remlink(&but->link->lines, line);
1196
1197         link= line->from->link;
1198
1199         /* are there more pointers allowed? */
1200         if(link->ppoin) {
1201                 
1202                 if(*(link->totlink)==1) {
1203                         *(link->totlink)= 0;
1204                         MEM_freeN(*(link->ppoin));
1205                         *(link->ppoin)= NULL;
1206                 }
1207                 else {
1208                         b= 0;
1209                         for(a=0; a< (*(link->totlink)); a++) {
1210                                 
1211                                 if( (*(link->ppoin))[a] != line->to->poin ) {
1212                                         (*(link->ppoin))[b]= (*(link->ppoin))[a];
1213                                         b++;
1214                                 }
1215                         }       
1216                         (*(link->totlink))--;
1217                 }
1218         }
1219         else {
1220                 *(link->poin)= NULL;
1221         }
1222
1223         MEM_freeN(line);
1224         //REDRAW
1225 }
1226
1227 /* *********************** data get/set ***********************
1228  * this either works with the pointed to data, or can work with
1229  * an edit override pointer while dragging for example */
1230
1231 /* for buttons pointing to color for example */
1232 void ui_get_but_vectorf(uiBut *but, float vec[3])
1233 {
1234         PropertyRNA *prop;
1235         int a, tot;
1236
1237         if(but->editvec) {
1238                 copy_v3_v3(vec, but->editvec);
1239         }
1240
1241         if(but->rnaprop) {
1242                 prop= but->rnaprop;
1243
1244                 vec[0]= vec[1]= vec[2]= 0.0f;
1245
1246                 if(RNA_property_type(prop) == PROP_FLOAT) {
1247                         tot= RNA_property_array_length(&but->rnapoin, prop);
1248                         tot= MIN2(tot, 3);
1249
1250                         for(a=0; a<tot; a++)
1251                                 vec[a]= RNA_property_float_get_index(&but->rnapoin, prop, a);
1252                 }
1253         }
1254         else if(but->pointype == CHA) {
1255                 char *cp= (char *)but->poin;
1256                 vec[0]= ((float)cp[0])/255.0f;
1257                 vec[1]= ((float)cp[1])/255.0f;
1258                 vec[2]= ((float)cp[2])/255.0f;
1259         }
1260         else if(but->pointype == FLO) {
1261                 float *fp= (float *)but->poin;
1262                 copy_v3_v3(vec, fp);
1263         }
1264         else {
1265                 if (but->editvec==NULL) {
1266                         fprintf(stderr, "ui_get_but_vectorf: can't get color, should never happen\n");
1267                         vec[0]= vec[1]= vec[2]= 0.0f;
1268                 }
1269         }
1270
1271         if (but->type == BUT_NORMAL) {
1272                 normalize_v3(vec);
1273         }
1274 }
1275
1276 /* for buttons pointing to color for example */
1277 void ui_set_but_vectorf(uiBut *but, const float vec[3])
1278 {
1279         PropertyRNA *prop;
1280
1281         if(but->editvec) {
1282                 copy_v3_v3(but->editvec, vec);
1283         }
1284
1285         if(but->rnaprop) {
1286                 prop= but->rnaprop;
1287
1288                 if(RNA_property_type(prop) == PROP_FLOAT) {
1289                         int tot;
1290                         int a;
1291
1292                         tot= RNA_property_array_length(&but->rnapoin, prop);
1293                         tot= MIN2(tot, 3);
1294
1295                         for (a=0; a<tot; a++) {
1296                                 RNA_property_float_set_index(&but->rnapoin, prop, a, vec[a]);
1297                         }
1298                 }
1299         }
1300         else if(but->pointype == CHA) {
1301                 char *cp= (char *)but->poin;
1302                 cp[0]= (char)(0.5f + vec[0]*255.0f);
1303                 cp[1]= (char)(0.5f + vec[1]*255.0f);
1304                 cp[2]= (char)(0.5f + vec[2]*255.0f);
1305         }
1306         else if(but->pointype == FLO) {
1307                 float *fp= (float *)but->poin;
1308                 copy_v3_v3(fp, vec);
1309         }
1310 }
1311
1312 int ui_is_but_float(uiBut *but)
1313 {
1314         if(but->pointype==FLO && but->poin)
1315                 return 1;
1316         
1317         if(but->rnaprop && RNA_property_type(but->rnaprop) == PROP_FLOAT)
1318                 return 1;
1319         
1320         return 0;
1321 }
1322
1323 int ui_is_but_unit(uiBut *but)
1324 {
1325         UnitSettings *unit= but->block->unit;
1326         const int unit_type= uiButGetUnitType(but);
1327
1328         if(unit_type == PROP_UNIT_NONE)
1329                 return 0;
1330
1331 #if 1 // removed so angle buttons get correct snapping
1332         if (unit->system_rotation == USER_UNIT_ROT_RADIANS && unit_type == PROP_UNIT_ROTATION)
1333                 return 0;
1334 #endif
1335         
1336         /* for now disable time unit conversion */      
1337         if (unit_type == PROP_UNIT_TIME)
1338                 return 0;
1339
1340         if (unit->system == USER_UNIT_NONE) {
1341                 if (unit_type != PROP_UNIT_ROTATION) {
1342                         return 0;
1343                 }
1344         }
1345
1346         return 1;
1347 }
1348
1349 int ui_is_but_rna_valid(uiBut *but)
1350 {
1351         if (but->rnaprop==NULL || RNA_struct_contains_property(&but->rnapoin, but->rnaprop)) {
1352                 return TRUE;
1353         }
1354         else {
1355                 printf("property removed %s: %p\n", but->drawstr, but->rnaprop);
1356                 return FALSE;
1357         }
1358 }
1359
1360 double ui_get_but_val(uiBut *but)
1361 {
1362         PropertyRNA *prop;
1363         double value = 0.0;
1364
1365         if(but->editval) { return *(but->editval); }
1366         if(but->poin==NULL && but->rnapoin.data==NULL) return 0.0;
1367
1368         if(but->rnaprop) {
1369                 prop= but->rnaprop;
1370
1371                 switch(RNA_property_type(prop)) {
1372                         case PROP_BOOLEAN:
1373                                 if(RNA_property_array_check(prop))
1374                                         value= RNA_property_boolean_get_index(&but->rnapoin, prop, but->rnaindex);
1375                                 else
1376                                         value= RNA_property_boolean_get(&but->rnapoin, prop);
1377                                 break;
1378                         case PROP_INT:
1379                                 if(RNA_property_array_check(prop))
1380                                         value= RNA_property_int_get_index(&but->rnapoin, prop, but->rnaindex);
1381                                 else
1382                                         value= RNA_property_int_get(&but->rnapoin, prop);
1383                                 break;
1384                         case PROP_FLOAT:
1385                                 if(RNA_property_array_check(prop))
1386                                         value= RNA_property_float_get_index(&but->rnapoin, prop, but->rnaindex);
1387                                 else
1388                                         value= RNA_property_float_get(&but->rnapoin, prop);
1389                                 break;
1390                         case PROP_ENUM:
1391                                 value= RNA_property_enum_get(&but->rnapoin, prop);
1392                                 break;
1393                         default:
1394                                 value= 0.0;
1395                                 break;
1396                 }
1397         }
1398         else if(but->type== HSVSLI) {
1399                 float h, s, v, *fp;
1400                 
1401                 fp= (but->editvec)? but->editvec: (float *)but->poin;
1402                 rgb_to_hsv(fp[0], fp[1], fp[2], &h, &s, &v);
1403
1404                 switch(but->str[0]) {
1405                         case 'H': value= h; break;
1406                         case 'S': value= s; break;
1407                         case 'V': value= v; break;
1408                 }
1409         } 
1410         else if( but->pointype == CHA ) {
1411                 value= *(char *)but->poin;
1412         }
1413         else if( but->pointype == SHO ) {
1414                 value= *(short *)but->poin;
1415         } 
1416         else if( but->pointype == INT ) {
1417                 value= *(int *)but->poin;
1418         } 
1419         else if( but->pointype == FLO ) {
1420                 value= *(float *)but->poin;
1421         }
1422
1423         return value;
1424 }
1425
1426 void ui_set_but_val(uiBut *but, double value)
1427 {
1428         PropertyRNA *prop;
1429
1430         /* value is a hsv value: convert to rgb */
1431         if(but->rnaprop) {
1432                 prop= but->rnaprop;
1433
1434                 if(RNA_property_editable(&but->rnapoin, prop)) {
1435                         switch(RNA_property_type(prop)) {
1436                                 case PROP_BOOLEAN:
1437                                         if(RNA_property_array_length(&but->rnapoin, prop))
1438                                                 RNA_property_boolean_set_index(&but->rnapoin, prop, but->rnaindex, value);
1439                                         else
1440                                                 RNA_property_boolean_set(&but->rnapoin, prop, value);
1441                                         break;
1442                                 case PROP_INT:
1443                                         if(RNA_property_array_length(&but->rnapoin, prop))
1444                                                 RNA_property_int_set_index(&but->rnapoin, prop, but->rnaindex, (int)value);
1445                                         else
1446                                                 RNA_property_int_set(&but->rnapoin, prop, (int)value);
1447                                         break;
1448                                 case PROP_FLOAT:
1449                                         if(RNA_property_array_length(&but->rnapoin, prop))
1450                                                 RNA_property_float_set_index(&but->rnapoin, prop, but->rnaindex, value);
1451                                         else
1452                                                 RNA_property_float_set(&but->rnapoin, prop, value);
1453                                         break;
1454                                 case PROP_ENUM:
1455                                         if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1456                                                 int ivalue= (int)value;
1457                                                 ivalue ^= RNA_property_enum_get(&but->rnapoin, prop); /* toggle for enum/flag buttons */
1458                                                 RNA_property_enum_set(&but->rnapoin, prop, ivalue);
1459                                         }
1460                                         else {
1461                                                 RNA_property_enum_set(&but->rnapoin, prop, value);
1462                                         }
1463                                         break;
1464                                 default:
1465                                         break;
1466                         }
1467                 }
1468
1469                 /* we can't be sure what RNA set functions actually do,
1470                  * so leave this unset */
1471                 value= UI_BUT_VALUE_UNSET;
1472         }
1473         else if(but->pointype==0);
1474         else if(but->type==HSVSLI ) {
1475                 float h, s, v, *fp;
1476                 
1477                 fp= (but->editvec)? but->editvec: (float *)but->poin;
1478                 rgb_to_hsv(fp[0], fp[1], fp[2], &h, &s, &v);
1479                 
1480                 switch(but->str[0]) {
1481                 case 'H': h= value; break;
1482                 case 'S': s= value; break;
1483                 case 'V': v= value; break;
1484                 }
1485                 
1486                 hsv_to_rgb(h, s, v, fp, fp+1, fp+2);
1487                 
1488         }
1489         else {
1490                 /* first do rounding */
1491                 if(but->pointype==CHA)
1492                         value= (char)floor(value+0.5);
1493                 else if(but->pointype==SHO ) {
1494                         /* gcc 3.2.1 seems to have problems 
1495                          * casting a double like 32772.0 to
1496                          * a short so we cast to an int, then 
1497                          to a short */
1498                         int gcckludge;
1499                         gcckludge = (int) floor(value+0.5);
1500                         value= (short)gcckludge;
1501                 }
1502                 else if(but->pointype==INT )
1503                         value= (int)floor(value+0.5);
1504                 else if(but->pointype==FLO ) {
1505                         float fval= (float)value;
1506                         if(fval>= -0.00001f && fval<= 0.00001f) fval= 0.0f;     /* prevent negative zero */
1507                         value= fval;
1508                 }
1509                 
1510                 /* then set value with possible edit override */
1511                 if(but->editval)
1512                         value= *but->editval= value;
1513                 else if(but->pointype==CHA)
1514                         value= *((char *)but->poin)= (char)value;
1515                 else if(but->pointype==SHO)
1516                         value= *((short *)but->poin)= (short)value;
1517                 else if(but->pointype==INT)
1518                         value= *((int *)but->poin)= (int)value;
1519                 else if(but->pointype==FLO)
1520                         value= *((float *)but->poin)= (float)value;
1521         }
1522
1523         /* update select flag */
1524         ui_is_but_sel(but, &value);
1525 }
1526
1527 int ui_get_but_string_max_length(uiBut *but)
1528 {
1529         if(ELEM(but->type, TEX, SEARCH_MENU))
1530                 return but->hardmax;
1531         else if(but->type == IDPOIN)
1532                 return MAX_ID_NAME-2;
1533         else
1534                 return UI_MAX_DRAW_STR;
1535 }
1536
1537 static double ui_get_but_scale_unit(uiBut *but, double value)
1538 {
1539         UnitSettings *unit= but->block->unit;
1540         int unit_type= uiButGetUnitType(but);
1541
1542         if(unit_type == PROP_UNIT_LENGTH) {
1543                 return value * (double)unit->scale_length;
1544         }
1545         else if(unit_type == PROP_UNIT_AREA) {
1546                 return value * pow(unit->scale_length, 2);
1547         }
1548         else if(unit_type == PROP_UNIT_VOLUME) {
1549                 return value * pow(unit->scale_length, 3);
1550         }
1551         else if(unit_type == PROP_UNIT_TIME) { /* WARNING - using evil_C :| */
1552                 Scene *scene= CTX_data_scene(but->block->evil_C);
1553                 return FRA2TIME(value);
1554         }
1555         else {
1556                 return value;
1557         }
1558 }
1559
1560 /* str will be overwritten */
1561 void ui_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen)
1562 {
1563         if(ui_is_but_unit(but)) {
1564                 UnitSettings *unit= but->block->unit;
1565                 int unit_type= uiButGetUnitType(but);
1566                 char *orig_str;
1567                 
1568                 orig_str= MEM_callocN(sizeof(char)*maxlen + 1, "textedit sub str");
1569                 memcpy(orig_str, str, maxlen);
1570                 
1571                 bUnit_ToUnitAltName(str, maxlen, orig_str, unit->system, unit_type>>16);
1572                 
1573                 MEM_freeN(orig_str);
1574         }
1575 }
1576
1577 static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double value, int pad)
1578 {
1579         UnitSettings *unit= but->block->unit;
1580         int do_split= unit->flag & USER_UNIT_OPT_SPLIT;
1581         int unit_type= uiButGetUnitType(but);
1582         int precision= but->a2;
1583
1584         if(unit->scale_length<0.0001f) unit->scale_length= 1.0f; // XXX do_versions
1585
1586         /* Sanity checks */
1587         if(precision > PRECISION_FLOAT_MAX)     precision= PRECISION_FLOAT_MAX;
1588         else if(precision==0)                           precision= 2;
1589
1590         bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision, unit->system, unit_type>>16, do_split, pad);
1591 }
1592
1593 static float ui_get_but_step_unit(uiBut *but, float step_default)
1594 {
1595         int unit_type= uiButGetUnitType(but)>>16;
1596         float step;
1597
1598         step = bUnit_ClosestScalar(ui_get_but_scale_unit(but, step_default), but->block->unit->system, unit_type);
1599
1600         if(step > 0.0f) { /* -1 is an error value */
1601                 return (float)((double)step/ui_get_but_scale_unit(but, 1.0))*100.0f;
1602         }
1603         else {
1604                 return step_default;
1605         }
1606 }
1607
1608
1609 void ui_get_but_string(uiBut *but, char *str, size_t maxlen)
1610 {
1611         if(but->rnaprop && ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1612                 PropertyType type;
1613                 char *buf= NULL;
1614                 int buf_len;
1615
1616                 type= RNA_property_type(but->rnaprop);
1617
1618                 if(type == PROP_STRING) {
1619                         /* RNA string */
1620                         buf= RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, str, maxlen, &buf_len);
1621                 }
1622                 else if(type == PROP_POINTER) {
1623                         /* RNA pointer */
1624                         PointerRNA ptr= RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
1625                         buf= RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
1626                 }
1627
1628                 if(!buf) {
1629                         str[0] = '\0';
1630                 }
1631                 else if(buf && buf != str) {
1632                         /* string was too long, we have to truncate */
1633                         memcpy(str, buf, MIN2(maxlen, buf_len+1));
1634                         MEM_freeN(buf);
1635                 }
1636         }
1637         else if(but->type == IDPOIN) {
1638                 /* ID pointer */
1639                 if(but->idpoin_idpp) { /* Can be NULL for ID properties by python */
1640                         ID *id= *(but->idpoin_idpp);
1641                         if(id) {
1642                                 BLI_strncpy(str, id->name+2, maxlen);
1643                                 return;
1644                         }
1645                 }
1646                 str[0] = '\0';
1647                 return;
1648         }
1649         else if(but->type == TEX) {
1650                 /* string */
1651                 BLI_strncpy(str, but->poin, maxlen);
1652                 return;
1653         }
1654         else if(but->type == SEARCH_MENU) {
1655                 /* string */
1656                 BLI_strncpy(str, but->poin, maxlen);
1657                 return;
1658         }
1659         else if(ui_but_anim_expression_get(but, str, maxlen))
1660                 ; /* driver expression */
1661         else {
1662                 /* number editing */
1663                 double value;
1664
1665                 value= ui_get_but_val(but);
1666
1667                 if(ui_is_but_float(but)) {
1668                         if(ui_is_but_unit(but)) {
1669                                 ui_get_but_string_unit(but, str, maxlen, value, 0);
1670                         }
1671                         else {
1672                                 const int prec= ui_but_float_precision(but, value);
1673                                 BLI_snprintf(str, maxlen, "%.*f", prec, value);
1674                         }
1675                 }
1676                 else
1677                         BLI_snprintf(str, maxlen, "%d", (int)value);
1678         }
1679 }
1680
1681 #ifdef WITH_PYTHON
1682
1683 static int ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *value)
1684 {
1685         char str_unit_convert[256];
1686         const int unit_type= uiButGetUnitType(but);
1687
1688         BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert));
1689
1690         /* ugly, use the draw string to get the value, this could cause problems if it includes some text which resolves to a unit */
1691         bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr, ui_get_but_scale_unit(but, 1.0), but->block->unit->system, unit_type>>16);
1692
1693         return (BPY_button_exec(C, str_unit_convert, value, TRUE) != -1);
1694 }
1695
1696 #endif /* WITH_PYTHON */
1697
1698
1699 int ui_set_but_string_eval_num(bContext *C, uiBut *but, const char *str, double *value)
1700 {
1701         int ok= FALSE;
1702
1703 #ifdef WITH_PYTHON
1704
1705         if(str[0] != '\0') {
1706                 int is_unit_but= ui_is_but_unit(but);
1707                 /* only enable verbose if we won't run again with units */
1708                 if(BPY_button_exec(C, str, value, is_unit_but==FALSE) != -1) {
1709                         /* if the value parsed ok without unit conversion this button may still need a unit multiplier */
1710                         if(is_unit_but) {
1711                                 char str_new[128];
1712
1713                                 BLI_snprintf(str_new, sizeof(str_new), "%f", *value);
1714                                 ok= ui_set_but_string_eval_num_unit(C, but, str_new, value);
1715                         }
1716                         else {
1717                                 ok= TRUE; /* parse normal string via py (no unit conversion needed) */
1718                         }
1719                 }
1720                 else if(is_unit_but) {
1721                         /* parse failed, this is a unit but so run replacements and parse again */
1722                         ok= ui_set_but_string_eval_num_unit(C, but, str, value);
1723                 }
1724         }
1725
1726 #else /* WITH_PYTHON */
1727
1728         value= atof(str);
1729         ok = TRUE;
1730
1731 #endif /* WITH_PYTHON */
1732
1733         return ok;
1734 }
1735
1736
1737 int ui_set_but_string(bContext *C, uiBut *but, const char *str)
1738 {
1739         if(but->rnaprop && ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1740                 if(RNA_property_editable(&but->rnapoin, but->rnaprop)) {
1741                         PropertyType type;
1742
1743                         type= RNA_property_type(but->rnaprop);
1744
1745                         if(type == PROP_STRING) {
1746                                 /* RNA string */
1747                                 RNA_property_string_set(&but->rnapoin, but->rnaprop, str);
1748                                 return 1;
1749                         }
1750                         else if(type == PROP_POINTER) {
1751                                 /* RNA pointer */
1752                                 PointerRNA ptr, rptr;
1753                                 PropertyRNA *prop;
1754
1755                                 if(str == NULL || str[0] == '\0') {
1756                                         RNA_property_pointer_set(&but->rnapoin, but->rnaprop, PointerRNA_NULL);
1757                                         return 1;
1758                                 }
1759                                 else {
1760                                         ptr= but->rnasearchpoin;
1761                                         prop= but->rnasearchprop;
1762                                         
1763                                         if(prop && RNA_property_collection_lookup_string(&ptr, prop, str, &rptr))
1764                                                 RNA_property_pointer_set(&but->rnapoin, but->rnaprop, rptr);
1765
1766                                         return 1;
1767                                 }
1768
1769                                 return 0;
1770                         }
1771                 }
1772         }
1773         else if(but->type == IDPOIN) {
1774                 /* ID pointer */
1775                 but->idpoin_func(C, str, but->idpoin_idpp);
1776                 return 1;
1777         }
1778         else if(but->type == TEX) {
1779                 /* string */
1780                 if(ui_is_but_utf8(but)) BLI_strncpy_utf8(but->poin, str, but->hardmax);
1781                 else                    BLI_strncpy(but->poin, str, but->hardmax);
1782
1783                 return 1;
1784         }
1785         else if(but->type == SEARCH_MENU) {
1786                 /* string */
1787                 BLI_strncpy(but->poin, str, but->hardmax);
1788                 return 1;
1789         }
1790         else if(ui_but_anim_expression_set(but, str)) {
1791                 /* driver expression */
1792                 return 1;
1793         }
1794         else if(str[0]=='#') {
1795                 /* shortcut to create new driver expression (versus immediate Py-execution) */
1796                 return ui_but_anim_expression_create(but, str+1);
1797         }
1798         else {
1799                 /* number editing */
1800                 double value;
1801
1802                 if(ui_set_but_string_eval_num(C, but, str, &value) == FALSE) {
1803                         return 0;
1804                 }
1805
1806                 if(!ui_is_but_float(but)) value= (int)floor(value + 0.5);
1807                 if(but->type==NUMABS) value= fabs(value);
1808
1809                 /* not that we use hard limits here */
1810                 if(value < (double)but->hardmin) value= but->hardmin;
1811                 if(value > (double)but->hardmax) value= but->hardmax;
1812
1813                 ui_set_but_val(but, value);
1814                 return 1;
1815         }
1816
1817         return 0;
1818 }
1819
1820 void ui_set_but_default(bContext *C, short all)
1821 {
1822         PointerRNA ptr;
1823
1824         WM_operator_properties_create(&ptr, "UI_OT_reset_default_button");
1825         RNA_boolean_set(&ptr, "all", all);
1826         WM_operator_name_call(C, "UI_OT_reset_default_button", WM_OP_EXEC_DEFAULT, &ptr);
1827         WM_operator_properties_free(&ptr);
1828 }
1829
1830 static double soft_range_round_up(double value, double max)
1831 {
1832         /* round up to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, .. */
1833         double newmax= pow(10.0, ceil(log(value)/M_LN10));
1834
1835         if(newmax*0.2 >= max && newmax*0.2 >= value)
1836                 return newmax*0.2;
1837         else if(newmax*0.5 >= max && newmax*0.5 >= value)
1838                 return newmax*0.5;
1839         else
1840                 return newmax;
1841 }
1842
1843 static double soft_range_round_down(double value, double max)
1844 {
1845         /* round down to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, .. */
1846         double newmax= pow(10.0, floor(log(value)/M_LN10));
1847
1848         if(newmax*5.0 <= max && newmax*5.0 <= value)
1849                 return newmax*5.0;
1850         else if(newmax*2.0 <= max && newmax*2.0 <= value)
1851                 return newmax*2.0;
1852         else
1853                 return newmax;
1854 }
1855
1856 void ui_set_but_soft_range(uiBut *but, double value)
1857 {
1858         /* ideally we would not limit this but practially, its more then
1859          * enough worst case is very long vectors wont use a smart soft-range
1860          * which isnt so bad. */
1861
1862         if(but->rnaprop) {
1863                 const PropertyType type= RNA_property_type(but->rnaprop);
1864                 double softmin, softmax /*, step, precision*/;
1865                 double value_min= value;
1866                 double value_max= value;
1867
1868                 /* clamp button range to something reasonable in case
1869                  * we get -inf/inf from RNA properties */
1870                 if(type == PROP_INT) {
1871                         int imin, imax, istep;
1872                         const int array_len= RNA_property_array_length(&but->rnapoin, but->rnaprop);
1873
1874                         RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
1875                         softmin= (imin == INT_MIN)? -1e4: imin;
1876                         softmax= (imin == INT_MAX)? 1e4: imax;
1877                         /*step= istep;*/ /*UNUSED*/
1878                         /*precision= 1;*/ /*UNUSED*/
1879
1880                         if(array_len >= 2) {
1881                                 int value_range[2];
1882                                 RNA_property_int_get_array_range(&but->rnapoin, but->rnaprop, value_range);
1883                                 value_min= (double)value_range[0];
1884                                 value_max= (double)value_range[1];
1885                         }
1886                 }
1887                 else if(type == PROP_FLOAT) {
1888                         float fmin, fmax, fstep, fprecision;
1889                         const int array_len= RNA_property_array_length(&but->rnapoin, but->rnaprop);
1890
1891                         RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
1892                         softmin= (fmin == -FLT_MAX)? (float)-1e4: fmin;
1893                         softmax= (fmax == FLT_MAX)? (float)1e4: fmax;
1894                         /*step= fstep;*/ /*UNUSED*/
1895                         /*precision= fprecision;*/ /*UNUSED*/
1896
1897                         if(array_len >= 2) {
1898                                 float value_range[2];
1899                                 RNA_property_float_get_array_range(&but->rnapoin, but->rnaprop, value_range);
1900                                 value_min= (double)value_range[0];
1901                                 value_max= (double)value_range[1];
1902                         }
1903                 }
1904                 else
1905                         return;
1906
1907                 /* if the value goes out of the soft/max range, adapt the range */
1908                 if(value_min+1e-10 < softmin) {
1909                         if(value_min < 0.0)
1910                                 softmin= -soft_range_round_up(-value_min, -softmin);
1911                         else
1912                                 softmin= soft_range_round_down(value_min, softmin);
1913
1914                         if(softmin < (double)but->hardmin)
1915                                 softmin= (double)but->hardmin;
1916                 }
1917                 if(value_max-1e-10 > softmax) {
1918                         if(value_max < 0.0)
1919                                 softmax= -soft_range_round_down(-value_max, -softmax);
1920                         else
1921                                 softmax= soft_range_round_up(value_max, softmax);
1922
1923                         if(softmax > (double)but->hardmax)
1924                                 softmax= but->hardmax;
1925                 }
1926
1927                 but->softmin= softmin;
1928                 but->softmax= softmax;
1929         }
1930 }
1931
1932 /* ******************* Free ********************/
1933
1934 static void ui_free_link(uiLink *link)
1935 {
1936         if(link) {      
1937                 BLI_freelistN(&link->lines);
1938                 MEM_freeN(link);
1939         }
1940 }
1941
1942 /* can be called with C==NULL */
1943 static void ui_free_but(const bContext *C, uiBut *but)
1944 {
1945         if(but->opptr) {
1946                 WM_operator_properties_free(but->opptr);
1947                 MEM_freeN(but->opptr);
1948         }
1949
1950         if(but->func_argN) {
1951                 MEM_freeN(but->func_argN);
1952         }
1953
1954         if(but->active) {
1955                 /* XXX solve later, buttons should be free-able without context ideally,
1956                  * however they may have open tooltips or popup windows, which need to
1957                  * be closed using a context pointer */
1958                 if (C) {
1959                         ui_button_active_free(C, but);
1960                 }
1961                 else {
1962                         if(but->active) {
1963                                 MEM_freeN(but->active);
1964                         }
1965                 }
1966         }
1967         if (but->str && but->str != but->strdata) {
1968                 MEM_freeN(but->str);
1969         }
1970         ui_free_link(but->link);
1971
1972         if ((but->type == BUT_IMAGE) && but->poin) {
1973                 IMB_freeImBuf((struct ImBuf *)but->poin);
1974         }
1975
1976         MEM_freeN(but);
1977 }
1978
1979 /* can be called with C==NULL */
1980 void uiFreeBlock(const bContext *C, uiBlock *block)
1981 {
1982         uiBut *but;
1983
1984         while( (but= block->buttons.first) ) {
1985                 BLI_remlink(&block->buttons, but);      
1986                 ui_free_but(C, but);
1987         }
1988
1989         if (block->unit) {
1990                 MEM_freeN(block->unit);
1991         }
1992
1993         if (block->func_argN) {
1994                 MEM_freeN(block->func_argN);
1995         }
1996
1997         CTX_store_free_list(&block->contexts);
1998
1999         BLI_freelistN(&block->saferct);
2000         
2001         MEM_freeN(block);
2002 }
2003
2004 /* can be called with C==NULL */
2005 void uiFreeBlocks(const bContext *C, ListBase *lb)
2006 {
2007         uiBlock *block;
2008         
2009         while( (block= lb->first) ) {
2010                 BLI_remlink(lb, block);
2011                 uiFreeBlock(C, block);
2012         }
2013 }
2014
2015 void uiFreeInactiveBlocks(const bContext *C, ListBase *lb)
2016 {
2017         uiBlock *block, *nextblock;
2018
2019         for(block=lb->first; block; block=nextblock) {
2020                 nextblock= block->next;
2021         
2022                 if(!block->handle) {
2023                         if(!block->active) {
2024                                 BLI_remlink(lb, block);
2025                                 uiFreeBlock(C, block);
2026                         }
2027                         else
2028                                 block->active= 0;
2029                 }
2030         }
2031 }
2032
2033 void uiBlockSetRegion(uiBlock *block, ARegion *region)
2034 {
2035         ListBase *lb= &region->uiblocks;
2036         uiBlock *oldblock= NULL;
2037
2038         /* each listbase only has one block with this name, free block
2039          * if is already there so it can be rebuilt from scratch */
2040         if(lb) {
2041                 oldblock= BLI_findstring(lb, block->name, offsetof(uiBlock, name));
2042
2043                 if (oldblock) {
2044                         oldblock->active= 0;
2045                         oldblock->panel= NULL;
2046                 }
2047
2048                 /* at the beginning of the list! for dynamical menus/blocks */
2049                 BLI_addhead(lb, block);
2050         }
2051
2052         block->oldblock= oldblock;
2053 }
2054
2055 uiBlock *uiBeginBlock(const bContext *C, ARegion *region, const char *name, short dt)
2056 {
2057         uiBlock *block;
2058         wmWindow *window;
2059         Scene *scn;
2060         int getsizex, getsizey;
2061
2062         window= CTX_wm_window(C);
2063         scn = CTX_data_scene(C);
2064
2065         block= MEM_callocN(sizeof(uiBlock), "uiBlock");
2066         block->active= 1;
2067         block->dt= dt;
2068         block->evil_C= (void*)C; // XXX
2069
2070         if (scn) {
2071                 block->color_profile= (scn->r.color_mgt_flag & R_COLOR_MANAGEMENT);
2072
2073                 /* copy to avoid crash when scene gets deleted with ui still open */
2074                 block->unit= MEM_mallocN(sizeof(scn->unit), "UI UnitSettings");
2075                 memcpy(block->unit, &scn->unit, sizeof(scn->unit));
2076         }
2077
2078         BLI_strncpy(block->name, name, sizeof(block->name));
2079
2080         if(region)
2081                 uiBlockSetRegion(block, region);
2082
2083         /* window matrix and aspect */
2084         if(region && region->swinid) {
2085                 wm_subwindow_getmatrix(window, region->swinid, block->winmat);
2086                 wm_subwindow_getsize(window, region->swinid, &getsizex, &getsizey);
2087
2088                 /* TODO - investigate why block->winmat[0][0] is negative
2089                  * in the image view when viewRedrawForce is called */
2090                 block->aspect= 2.0/fabs( (getsizex)*block->winmat[0][0]);
2091         }
2092         else {
2093                 /* no subwindow created yet, for menus for example, so we
2094                  * use the main window instead, since buttons are created
2095                  * there anyway */
2096                 wm_subwindow_getmatrix(window, window->screen->mainwin, block->winmat);
2097                 wm_subwindow_getsize(window, window->screen->mainwin, &getsizex, &getsizey);
2098
2099                 block->aspect= 2.0/fabs(getsizex*block->winmat[0][0]);
2100                 block->auto_open= TRUE;
2101                 block->flag |= UI_BLOCK_LOOP; /* tag as menu */
2102         }
2103
2104         return block;
2105 }
2106
2107 uiBlock *uiGetBlock(const char *name, ARegion *ar)
2108 {
2109         return BLI_findstring(&ar->uiblocks, name, offsetof(uiBlock, name));
2110 }
2111
2112 void uiBlockSetEmboss(uiBlock *block, char dt)
2113 {
2114         block->dt= dt;
2115 }
2116
2117 void ui_check_but(uiBut *but)
2118 {
2119         /* if something changed in the button */
2120         double value= UI_BUT_VALUE_UNSET;
2121 //      float okwidth; // UNUSED
2122         
2123         ui_is_but_sel(but, &value);
2124         
2125         /* only update soft range while not editing */
2126         if(but->rnaprop && !(but->editval || but->editstr || but->editvec)) {
2127                 UI_GET_BUT_VALUE_INIT(but, value)
2128                 ui_set_but_soft_range(but, value);
2129         }
2130
2131         /* test for min and max, icon sliders, etc */
2132         switch( but->type ) {
2133                 case NUM:
2134                 case SLI:
2135                 case SCROLL:
2136                 case NUMSLI:
2137                 case HSVSLI:
2138                         UI_GET_BUT_VALUE_INIT(but, value)
2139                         if(value < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2140                         else if(value > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2141                         break;
2142                         
2143                 case NUMABS:
2144                 {
2145                         double value_abs;
2146                         UI_GET_BUT_VALUE_INIT(but, value)
2147                         value_abs= fabs(value);
2148                         if(value_abs < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2149                         else if(value_abs > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2150                         break;
2151                 }
2152                 case ICONTOG: 
2153                 case ICONTOGN:
2154                         if(!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2155                                 if(but->flag & UI_SELECT) but->iconadd= 1;
2156                                 else but->iconadd= 0;
2157                         }
2158                         break;
2159                         
2160                 case ICONROW:
2161                         if(!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2162                                 UI_GET_BUT_VALUE_INIT(but, value)
2163                                 but->iconadd= (int)value- (int)(but->hardmin);
2164                         }
2165                         break;
2166                         
2167                 case ICONTEXTROW:
2168                         if(!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2169                                 UI_GET_BUT_VALUE_INIT(but, value)
2170                                 but->iconadd= (int)value- (int)(but->hardmin);
2171                         }
2172                         break;
2173         }
2174         
2175         
2176         /* safety is 4 to enable small number buttons (like 'users') */
2177         // okwidth= -4 + (but->x2 - but->x1); // UNUSED
2178         
2179         /* name: */
2180         switch( but->type ) {
2181         
2182         case MENU:
2183         case ICONTEXTROW:
2184                 
2185                 if(but->x2 - but->x1 > 24) {
2186                         UI_GET_BUT_VALUE_INIT(but, value)
2187                         ui_set_name_menu(but, (int)value);
2188                 }
2189                 break;
2190         
2191         case NUM:
2192         case NUMSLI:
2193         case HSVSLI:
2194         case NUMABS:
2195
2196                 UI_GET_BUT_VALUE_INIT(but, value)
2197
2198                 if(ui_is_but_float(but)) {
2199                         if(value == (double) FLT_MAX) BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%sinf", but->str);
2200                         else if(value == (double) -FLT_MAX) BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s-inf", but->str);
2201                         /* support length type buttons */
2202                         else if(ui_is_but_unit(but)) {
2203                                 char new_str[sizeof(but->drawstr)];
2204                                 ui_get_but_string_unit(but, new_str, sizeof(new_str), value, TRUE);
2205                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, new_str);
2206                         }
2207                         else {
2208                                 const int prec= ui_but_float_precision(but, value);
2209                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2210                         }
2211                 }
2212                 else {
2213                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%d", but->str, (int)value);
2214                 }
2215                         
2216                 if(but->rnaprop) {
2217                         PropertySubType pstype = RNA_property_subtype(but->rnaprop);
2218                         
2219                         if (pstype == PROP_PERCENTAGE)
2220                                 strcat(but->drawstr, "%");
2221                 }
2222                 break;
2223
2224         case LABEL:
2225                 if(ui_is_but_float(but)) {
2226                         int prec;
2227                         UI_GET_BUT_VALUE_INIT(but, value)
2228                         prec= ui_but_float_precision(but, value);
2229                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2230                 }
2231                 else {
2232                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2233                 }
2234                 
2235                 break;
2236
2237         case IDPOIN:
2238         case TEX:
2239         case SEARCH_MENU:
2240                 if(!but->editstr) {
2241                         char str[UI_MAX_DRAW_STR];
2242
2243                         ui_get_but_string(but, str, UI_MAX_DRAW_STR-strlen(but->str));
2244
2245                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, str);
2246                 }
2247                 break;
2248         
2249         case KEYEVT:
2250                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2251                 if (but->flag & UI_SELECT) {
2252                         strcat(but->drawstr, "Press a key");
2253                 }
2254                 else {
2255                         UI_GET_BUT_VALUE_INIT(but, value)
2256                         strcat(but->drawstr, WM_key_event_string((short)value));
2257                 }
2258                 break;
2259                 
2260         case HOTKEYEVT:
2261                 if (but->flag & UI_SELECT) {
2262                         but->drawstr[0]= '\0';
2263                         
2264                         if(but->modifier_key) {
2265                                 char *str= but->drawstr;
2266                                 
2267                                 if(but->modifier_key & KM_SHIFT)
2268                                         str= strcat(str, "Shift ");
2269                                 if(but->modifier_key & KM_CTRL)
2270                                         str= strcat(str, "Ctrl ");
2271                                 if(but->modifier_key & KM_ALT)
2272                                         str= strcat(str, "Alt ");
2273                                 if(but->modifier_key & KM_OSKEY)
2274                                         str= strcat(str, "Cmd ");
2275
2276                                 (void)str; /* UNUSED */
2277                         }
2278                         else
2279                                 strcat(but->drawstr, "Press a key  ");
2280                 }
2281                 else
2282                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2283
2284                 break;
2285                 
2286         case BUT_TOGDUAL:
2287                 /* trying to get the dual-icon to left of text... not very nice */
2288                 if(but->str[0]) {
2289                         BLI_strncpy(but->drawstr, "  ", UI_MAX_DRAW_STR);
2290                         BLI_strncpy(but->drawstr+2, but->str, UI_MAX_DRAW_STR-2);
2291                 }
2292                 break;
2293
2294         case HSVCUBE:
2295         case HSVCIRCLE:
2296                 break;
2297         default:
2298                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2299                 
2300         }
2301
2302         /* if we are doing text editing, this will override the drawstr */
2303         if(but->editstr)
2304                 BLI_strncpy(but->drawstr, but->editstr, UI_MAX_DRAW_STR);
2305         
2306         /* text clipping moved to widget drawing code itself */
2307 }
2308
2309
2310 void uiBlockBeginAlign(uiBlock *block)
2311 {
2312         /* if other align was active, end it */
2313         if(block->flag & UI_BUT_ALIGN) uiBlockEndAlign(block);
2314
2315         block->flag |= UI_BUT_ALIGN_DOWN;       
2316         block->alignnr++;
2317
2318         /* buttons declared after this call will get this align nr */ // XXX flag?
2319 }
2320
2321 static int buts_are_horiz(uiBut *but1, uiBut *but2)
2322 {
2323         float dx, dy;
2324         
2325         dx= fabs( but1->x2 - but2->x1);
2326         dy= fabs( but1->y1 - but2->y2);
2327         
2328         if(dx > dy) return 0;
2329         return 1;
2330 }
2331
2332 void uiBlockEndAlign(uiBlock *block)
2333 {
2334         block->flag &= ~UI_BUT_ALIGN;   // all 4 flags
2335 }
2336
2337 int ui_but_can_align(uiBut *but)
2338 {
2339         return !ELEM3(but->type, LABEL, OPTION, OPTIONN);
2340 }
2341
2342 static void ui_block_do_align_but(uiBut *first, short nr)
2343 {
2344         uiBut *prev, *but=NULL, *next;
2345         int flag= 0, cols=0, rows=0;
2346         
2347         /* auto align */
2348
2349         for(but=first; but && but->alignnr == nr; but=but->next) {
2350                 if(but->next && but->next->alignnr == nr) {
2351                         if(buts_are_horiz(but, but->next)) cols++;
2352                         else rows++;
2353                 }
2354         }
2355
2356         /* rows==0: 1 row, cols==0: 1 collumn */
2357         
2358         /* note;  how it uses 'flag' in loop below (either set it, or OR it) is confusing */
2359         for(but=first, prev=NULL; but && but->alignnr == nr; prev=but, but=but->next) {
2360                 next= but->next;
2361                 if(next && next->alignnr != nr)
2362                         next= NULL;
2363
2364                 /* clear old flag */
2365                 but->flag &= ~UI_BUT_ALIGN;
2366                         
2367                 if(flag==0) {   /* first case */
2368                         if(next) {
2369                                 if(buts_are_horiz(but, next)) {
2370                                         if(rows==0)
2371                                                 flag= UI_BUT_ALIGN_RIGHT;
2372                                         else 
2373                                                 flag= UI_BUT_ALIGN_DOWN|UI_BUT_ALIGN_RIGHT;
2374                                 }
2375                                 else {
2376                                         flag= UI_BUT_ALIGN_DOWN;
2377                                 }
2378                         }
2379                 }
2380                 else if(next==NULL) {   /* last case */
2381                         if(prev) {
2382                                 if(buts_are_horiz(prev, but)) {
2383                                         if(rows==0) 
2384                                                 flag= UI_BUT_ALIGN_LEFT;
2385                                         else
2386                                                 flag= UI_BUT_ALIGN_TOP|UI_BUT_ALIGN_LEFT;
2387                                 }
2388                                 else flag= UI_BUT_ALIGN_TOP;
2389                         }
2390                 }
2391                 else if(buts_are_horiz(but, next)) {
2392                         /* check if this is already second row */
2393                         if( prev && buts_are_horiz(prev, but)==0) {
2394                                 flag &= ~UI_BUT_ALIGN_LEFT;
2395                                 flag |= UI_BUT_ALIGN_TOP;
2396                                 /* exception case: bottom row */
2397                                 if(rows>0) {
2398                                         uiBut *bt= but;
2399                                         while(bt && bt->alignnr == nr) {
2400                                                 if(bt->next && bt->next->alignnr == nr && buts_are_horiz(bt, bt->next)==0 ) break; 
2401                                                 bt= bt->next;
2402                                         }
2403                                         if(bt==NULL || bt->alignnr != nr) flag= UI_BUT_ALIGN_TOP|UI_BUT_ALIGN_RIGHT;
2404                                 }
2405                         }
2406                         else flag |= UI_BUT_ALIGN_LEFT;
2407                 }
2408                 else {
2409                         if(cols==0) {
2410                                 flag |= UI_BUT_ALIGN_TOP;
2411                         }
2412                         else {  /* next button switches to new row */
2413                                 
2414                                 if(prev && buts_are_horiz(prev, but))
2415                                         flag |= UI_BUT_ALIGN_LEFT;
2416                                 else {
2417                                         flag &= ~UI_BUT_ALIGN_LEFT;
2418                                         flag |= UI_BUT_ALIGN_TOP;
2419                                 }
2420                                 
2421                                 if( (flag & UI_BUT_ALIGN_TOP)==0) {     /* stil top row */
2422                                         if(prev) {
2423                                                 if(next && buts_are_horiz(but, next))
2424                                                         flag = UI_BUT_ALIGN_DOWN|UI_BUT_ALIGN_LEFT|UI_BUT_ALIGN_RIGHT;
2425                                                 else {
2426                                                         /* last button in top row */
2427                                                         flag = UI_BUT_ALIGN_DOWN|UI_BUT_ALIGN_LEFT;
2428                                                 }
2429                                         }
2430                                         else 
2431                                                 flag |= UI_BUT_ALIGN_DOWN;
2432                                 }
2433                                 else 
2434                                         flag |= UI_BUT_ALIGN_TOP;
2435                         }
2436                 }
2437                 
2438                 but->flag |= flag;
2439                 
2440                 /* merge coordinates */
2441                 if(prev) {
2442                         // simple cases 
2443                         if(rows==0) {
2444                                 but->x1= (prev->x2+but->x1)/2.0f;
2445                                 prev->x2= but->x1;
2446                         }
2447                         else if(cols==0) {
2448                                 but->y2= (prev->y1+but->y2)/2.0f;
2449                                 prev->y1= but->y2;
2450                         }
2451                         else {
2452                                 if(buts_are_horiz(prev, but)) {
2453                                         but->x1= (prev->x2+but->x1)/2.0f;
2454                                         prev->x2= but->x1;
2455                                         /* copy height too */
2456                                         but->y2= prev->y2;
2457                                 }
2458                                 else if(prev->prev && buts_are_horiz(prev->prev, prev)==0) {
2459                                         /* the previous button is a single one in its row */
2460                                         but->y2= (prev->y1+but->y2)/2.0f;
2461                                         prev->y1= but->y2;
2462                                         
2463                                         but->x1= prev->x1;
2464                                         if(next && buts_are_horiz(but, next)==0)
2465                                                 but->x2= prev->x2;
2466                                 }
2467                                 else {
2468                                         /* the previous button is not a single one in its row */
2469                                         but->y2= prev->y1;
2470                                 }
2471                         }
2472                 }
2473         }
2474 }
2475
2476 void ui_block_do_align(uiBlock *block)
2477 {
2478         uiBut *but;
2479         short nr;
2480
2481         /* align buttons with same align nr */
2482         for(but=block->buttons.first; but;) {
2483                 if(but->alignnr) {
2484                         nr= but->alignnr;
2485                         ui_block_do_align_but(but, nr);
2486
2487                         /* skip with same number */
2488                         for(; but && but->alignnr == nr; but=but->next);
2489
2490                         if(!but)
2491                                 break;
2492                 }
2493                 else
2494                         but= but->next;
2495         }
2496 }
2497
2498 /*
2499  * ui_def_but is the function that draws many button types
2500
2501  * for float buttons:
2502  *   "a1" Click Step (how much to change the value each click)
2503  *   "a2" Number of decimal point values to display. 0 defaults to 3 (0.000)
2504  *        1,2,3, and a maximum of 4, all greater values will be clamped to 4.
2505  */
2506 static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2, const char *tip)
2507 {
2508         uiBut *but;
2509         int slen;
2510         
2511         if(type & BUTPOIN) {            /* a pointer is required */
2512                 if(poin==NULL)
2513                         return NULL;
2514         }
2515
2516         but= MEM_callocN(sizeof(uiBut), "uiBut");
2517
2518         but->type= type & BUTTYPE;
2519         but->pointype= type & BUTPOIN;
2520         but->bit= type & BIT;
2521         but->bitnr= type & 31;
2522         but->icon = ICON_NONE;
2523         but->iconadd=0;
2524
2525         but->retval= retval;
2526
2527         slen= strlen(str);
2528         if(slen >= UI_MAX_NAME_STR-1) {
2529                 but->str= MEM_mallocN(slen+2, "ui_def_but str"); /* why +2 ? */
2530         }
2531         else {
2532                 but->str= but->strdata;
2533         }
2534         memcpy(but->str, str, slen+1);
2535
2536         but->x1= x1; 
2537         but->y1= y1;
2538         but->x2= (x1+x2); 
2539         but->y2= (y1+y2);
2540         
2541         but->poin= poin;
2542         but->hardmin= but->softmin= min; 
2543         but->hardmax= but->softmax= max;
2544         but->a1= a1; 
2545         but->a2= a2;
2546         but->tip= tip;
2547         
2548         but->lock= block->lock;
2549         but->lockstr= block->lockstr;
2550         but->dt= block->dt;
2551
2552         but->aspect= 1.0f; //XXX block->aspect;
2553         but->block= block;              // pointer back, used for frontbuffer status, and picker
2554
2555         if((block->flag & UI_BUT_ALIGN) && ui_but_can_align(but))
2556                 but->alignnr= block->alignnr;
2557
2558         but->func= block->func;
2559         but->func_arg1= block->func_arg1;
2560         but->func_arg2= block->func_arg2;
2561
2562         but->funcN= block->funcN;
2563         if(block->func_argN)
2564                 but->func_argN= MEM_dupallocN(block->func_argN);
2565         
2566         but->pos= -1;   /* cursor invisible */
2567
2568         if(ELEM4(but->type, NUM, NUMABS, NUMSLI, HSVSLI)) {     /* add a space to name */
2569                 /* slen remains unchanged from previous assignment, ensure this stays true */
2570                 if(slen>0 && slen<UI_MAX_NAME_STR-2) {
2571                         if(but->str[slen-1]!=' ') {
2572                                 but->str[slen]= ' ';
2573                                 but->str[slen+1]= 0;
2574                         }
2575                 }
2576         }
2577
2578         if((block->flag & UI_BLOCK_LOOP) || ELEM8(but->type, MENU, TEX, LABEL, IDPOIN, BLOCK, BUTM, SEARCH_MENU, PROGRESSBAR))
2579                 but->flag |= (UI_TEXT_LEFT|UI_ICON_LEFT);
2580         else if(but->type==BUT_TOGDUAL)
2581                 but->flag |= UI_ICON_LEFT;
2582
2583         but->flag |= (block->flag & UI_BUT_ALIGN);
2584
2585         if (but->lock) {
2586                 if (but->lockstr) {
2587                         but->flag |= UI_BUT_DISABLED;
2588                 }
2589         }
2590
2591         /* keep track of UI_interface.h */
2592         if(ELEM7(but->type, BLOCK, BUT, LABEL, PULLDOWN, ROUNDBOX, LISTBOX, BUTM));
2593         else if(ELEM3(but->type, SCROLL, SEPR, FTPREVIEW));
2594         else if(but->type >= SEARCH_MENU);
2595         else but->flag |= UI_BUT_UNDO;
2596
2597         BLI_addtail(&block->buttons, but);
2598         
2599         if(block->curlayout)
2600                 ui_layout_add_but(block->curlayout, but);
2601
2602 #ifdef WITH_PYTHON
2603         /* if the 'UI_OT_editsource' is running, extract the source info from the button  */
2604         if (UI_editsource_enable_check()) {
2605                 UI_editsource_active_but_test(but);
2606         }
2607 #endif
2608
2609         return but;
2610 }
2611
2612 /* ui_def_but_rna_propname and ui_def_but_rna
2613  * both take the same args except for propname vs prop, this is done so we can
2614  * avoid an extra lookup on 'prop' when its already available.
2615  *
2616  * When this kind of change won't disrupt branches, best look into making more
2617  * of our UI functions take prop rather then propname.
2618  */
2619
2620 #define UI_DEF_BUT_RNA_DISABLE(but) \
2621         but->flag |= UI_BUT_DISABLED; \
2622         but->lock = 1; \
2623         but->lockstr = ""
2624
2625
2626 static uiBut *ui_def_but_rna(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, PointerRNA *ptr, PropertyRNA *prop, int index, float min, float max, float a1, float a2,  const char *tip)
2627 {
2628         const PropertyType proptype= RNA_property_type(prop);
2629         uiBut *but;
2630         int freestr= 0, icon= 0;
2631
2632         /* use rna values if parameters are not specified */
2633         if(!str) {
2634                 if(type == MENU && proptype == PROP_ENUM) {
2635                         EnumPropertyItem *item;
2636                         DynStr *dynstr;
2637                         int i, totitem, value, free;
2638
2639                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2640                         value= RNA_property_enum_get(ptr, prop);
2641
2642                         dynstr= BLI_dynstr_new();
2643                         BLI_dynstr_appendf(dynstr, "%s%%t", RNA_property_ui_name(prop));
2644                         for(i=0; i<totitem; i++) {
2645                                 if(!item[i].identifier[0]) {
2646                                         if(item[i].name)
2647                                                 BLI_dynstr_appendf(dynstr, "|%s%%l", item[i].name);
2648                                         else
2649                                                 BLI_dynstr_append(dynstr, "|%l");
2650                                 }
2651                                 else if(item[i].icon)
2652                                         BLI_dynstr_appendf(dynstr, "|%s %%i%d %%x%d", item[i].name, item[i].icon, item[i].value);
2653                                 else
2654                                         BLI_dynstr_appendf(dynstr, "|%s %%x%d", item[i].name, item[i].value);
2655
2656                                 if(value == item[i].value)
2657                                         icon= item[i].icon;
2658                         }
2659                         str= BLI_dynstr_get_cstring(dynstr);
2660                         BLI_dynstr_free(dynstr);
2661
2662                         if (free) {
2663                                 MEM_freeN(item);
2664                         }
2665
2666                         freestr= 1;
2667                 }
2668                 else if(ELEM(type, ROW, LISTROW) && proptype == PROP_ENUM) {
2669                         EnumPropertyItem *item;
2670                         int i, totitem, free;
2671
2672                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2673                         for(i=0; i<totitem; i++) {
2674                                 if(item[i].identifier[0] && item[i].value == (int)max) {
2675                                         str= item[i].name;
2676                                         icon= item[i].icon;
2677                                 }
2678                         }
2679
2680                         if (!str) {
2681                                 str = RNA_property_ui_name(prop);
2682                         }
2683                         if (free) {
2684                                 MEM_freeN(item);
2685                         }
2686                 }
2687                 else {
2688                         str= RNA_property_ui_name(prop);
2689                         icon= RNA_property_ui_icon(prop);
2690                 }
2691         }
2692
2693         if(!tip && proptype != PROP_ENUM)
2694                 tip= RNA_property_ui_description(prop);
2695
2696         if(min == max || a1 == -1 || a2 == -1) {
2697                 if(proptype == PROP_INT) {
2698                         int hardmin, hardmax, softmin, softmax, step;
2699
2700                         RNA_property_int_range(ptr, prop, &hardmin, &hardmax);
2701                         RNA_property_int_ui_range(ptr, prop, &softmin, &softmax, &step);
2702
2703                         if(!ELEM(type, ROW, LISTROW) && min == max) {
2704                                 min= hardmin;
2705                                 max= hardmax;
2706                         }
2707                         if(a1 == -1)
2708                                 a1= step;
2709                         if(a2 == -1)
2710                                 a2= 0;
2711                 }
2712                 else if(proptype == PROP_FLOAT) {
2713                         float hardmin, hardmax, softmin, softmax, step, precision;
2714
2715                         RNA_property_float_range(ptr, prop, &hardmin, &hardmax);
2716                         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2717
2718                         if(!ELEM(type, ROW, LISTROW) && min == max) {
2719                                 min= hardmin;
2720                                 max= hardmax;
2721                         }
2722                         if(a1 == -1)
2723                                 a1= step;
2724                         if(a2 == -1)
2725                                 a2= precision;
2726                 }
2727                 else if(proptype == PROP_STRING) {
2728                         min= 0;
2729                         max= RNA_property_string_maxlength(prop);
2730                         if(max == 0) /* interface code should ideally support unlimited length */
2731                                 max= UI_MAX_DRAW_STR;
2732                 }
2733         }
2734
2735         /* now create button */
2736         but= ui_def_but(block, type, retval, str, x1, y1, x2, y2, NULL, min, max, a1, a2, tip);
2737
2738         but->rnapoin= *ptr;
2739         but->rnaprop= prop;
2740
2741         if(RNA_property_array_length(&but->rnapoin, but->rnaprop))
2742                 but->rnaindex= index;
2743         else
2744                 but->rnaindex= 0;
2745
2746         if(icon) {
2747                 but->icon= (BIFIconID)icon;
2748                 but->flag |= UI_HAS_ICON;
2749                 but->flag|= UI_ICON_LEFT;
2750         }
2751         
2752         if (!RNA_property_editable(&but->rnapoin, prop)) {
2753                 UI_DEF_BUT_RNA_DISABLE(but);
2754         }
2755
2756         if (but->flag & UI_BUT_UNDO && (ui_but_is_rna_undo(but) == FALSE)) {
2757                 but->flag &= ~UI_BUT_UNDO;
2758         }
2759
2760         /* If this button uses units, calculate the step from this */
2761         if((proptype == PROP_FLOAT) && ui_is_but_unit(but)) {
2762                 but->a1= ui_get_but_step_unit(but, but->a1);
2763         }
2764
2765         if (freestr) {
2766                 MEM_freeN((void *)str);
2767         }
2768
2769         return but;
2770 }
2771
2772 static uiBut *ui_def_but_rna_propname(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, PointerRNA *ptr, const char *propname, int index, float min, float max, float a1, float a2,  const char *tip)
2773 {
2774         PropertyRNA *prop= RNA_struct_find_property(ptr, propname);
2775         uiBut *but;
2776
2777         if(prop) {
2778                 but= ui_def_but_rna(block, type, retval, str, x1, y1, x2, y2, ptr, prop, index, min, max, a1, a2,  tip);
2779         }
2780         else {
2781                 but= ui_def_but(block, type, retval, propname, x1, y1, x2, y2, NULL, min, max, a1, a2, tip);
2782
2783                 UI_DEF_BUT_RNA_DISABLE(but);
2784         }
2785
2786         return but;
2787 }
2788
2789 static uiBut *ui_def_but_operator(uiBlock *block, int type, const char *opname, int opcontext, const char *str, int x1, int y1, short x2, short y2, const char *tip)
2790 {
2791         uiBut *but;
2792         wmOperatorType *ot;
2793         
2794         ot= WM_operatortype_find(opname, 0);
2795
2796         if(!str) {
2797                 if(ot) str= ot->name;
2798                 else str= opname;
2799         }
2800         
2801         if ((!tip || tip[0]=='\0') && ot && ot->description) {
2802                 tip= ot->description;
2803
2804                 tip = TIP_(tip);
2805         }
2806
2807         but= ui_def_but(block, type, -1, str, x1, y1, x2, y2, NULL, 0, 0, 0, 0, tip);
2808         but->optype= ot;
2809         but->opcontext= opcontext;
2810         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
2811
2812         if(!ot) {
2813                 but->flag |= UI_BUT_DISABLED;
2814                 but->lock = 1;
2815                 but->lockstr = "";
2816         }
2817
2818         return but;
2819 }
2820
2821 static uiBut *ui_def_but_operator_text(uiBlock *block, int type, const char *opname, int opcontext, const char *str, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2, const char *tip)
2822 {
2823         uiBut *but;
2824         wmOperatorType *ot;
2825         
2826         ot= WM_operatortype_find(opname, 0);
2827
2828         if(!str) {
2829                 if(ot) str= ot->name;
2830                 else str= opname;
2831         }
2832         
2833         if ((!tip || tip[0]=='\0') && ot && ot->description) {
2834                 tip= ot->description;
2835         }
2836
2837         but= ui_def_but(block, type, -1, str, x1, y1, x2, y2, poin, min, max, a1, a2, tip);
2838         but->optype= ot;
2839         but->opcontext= opcontext;
2840         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
2841
2842         if(!ot) {
2843                 but->flag |= UI_BUT_DISABLED;
2844                 but->lock = 1;
2845                 but->lockstr = "";
2846         }
2847
2848         return but;
2849 }
2850
2851 uiBut *uiDefBut(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2, const char *tip)
2852 {
2853         uiBut *but= ui_def_but(block, type, retval, str, x1, y1, x2, y2, poin, min, max, a1, a2, tip);
2854
2855         ui_check_but(but);
2856         
2857         return but;
2858 }
2859
2860         /* if _x_ is a power of two (only one bit) return the power,
2861          * otherwise return -1. 
2862          * (1<<findBitIndex(x))==x for powers of two.
2863          */
2864 static int findBitIndex(unsigned int x)
2865 {
2866         if (!x || !is_power_of_2_i(x)) { /* is_power_of_2_i(x) strips lowest bit */
2867                 return -1;
2868         } else {
2869                 int idx= 0;
2870
2871                 if (x&0xFFFF0000)       idx+=16, x>>=16;
2872                 if (x&0xFF00)           idx+=8, x>>=8;
2873                 if (x&0xF0)                     idx+=4, x>>=4;
2874                 if (x&0xC)                      idx+=2, x>>=2;
2875                 if (x&0x2)                      idx+=1;
2876
2877                 return idx;
2878         }
2879 }
2880
2881 /* autocomplete helper functions */
2882 struct AutoComplete {
2883         size_t maxlen;
2884         char *truncate;
2885         const char *startname;
2886 };
2887
2888 AutoComplete *autocomplete_begin(const char *startname, size_t maxlen)
2889 {
2890         AutoComplete *autocpl;
2891         
2892         autocpl= MEM_callocN(sizeof(AutoComplete), "AutoComplete");
2893         autocpl->maxlen= maxlen;
2894         autocpl->truncate= MEM_callocN(sizeof(char)*maxlen, "AutoCompleteTruncate");
2895         autocpl->startname= startname;
2896
2897         return autocpl;
2898 }
2899
2900 void autocomplete_do_name(AutoComplete *autocpl, const char *name)
2901 {
2902         char *truncate= autocpl->truncate;
2903         const char *startname= autocpl->startname;
2904         int a;
2905
2906         for(a=0; a<autocpl->maxlen-1; a++) {
2907                 if(startname[a]==0 || startname[a]!=name[a])
2908                         break;
2909         }
2910         /* found a match */
2911         if(startname[a]==0) {
2912                 /* first match */
2913                 if(truncate[0]==0)
2914                         BLI_strncpy(truncate, name, autocpl->maxlen);
2915                 else {
2916                         /* remove from truncate what is not in bone->name */
2917                         for(a=0; a<autocpl->maxlen-1; a++) {
2918                                 if(name[a] == 0) {
2919                                         truncate[a]= 0;
2920                                         break;
2921                                 }
2922                                 else if(truncate[a]!=name[a])
2923                                         truncate[a]= 0;
2924                         }
2925                 }
2926         }
2927 }
2928
2929 void autocomplete_end(AutoComplete *autocpl, char *autoname)
2930 {       
2931         if(autocpl->truncate[0])
2932                 BLI_strncpy(autoname, autocpl->truncate, autocpl->maxlen);
2933         else {
2934                 if (autoname != autocpl->startname) /* dont copy a string over its self */
2935                         BLI_strncpy(autoname, autocpl->startname, autocpl->maxlen);
2936         }
2937         MEM_freeN(autocpl->truncate);
2938         MEM_freeN(autocpl);
2939 }
2940
2941 /* autocomplete callback for ID buttons */
2942 static void autocomplete_id(bContext *C, char *str, void *arg_v)
2943 {
2944         int blocktype= (intptr_t)arg_v;
2945         ListBase *listb= which_libbase(CTX_data_main(C), blocktype);
2946         
2947         if(listb==NULL) return;
2948         
2949         /* search if str matches the beginning of an ID struct */
2950         if(str[0]) {
2951                 AutoComplete *autocpl= autocomplete_begin(str, MAX_ID_NAME-2);
2952                 ID *id;
2953                 
2954                 for(id= listb->first; id; id= id->next)
2955                         autocomplete_do_name(autocpl, id->name+2);
2956
2957                 autocomplete_end(autocpl, str);
2958         }
2959 }
2960
2961 static void ui_check_but_and_iconize(uiBut *but, int icon)
2962 {
2963         if(icon) {
2964                 but->icon= (BIFIconID) icon;
2965                 but->flag|= UI_HAS_ICON;
2966         }
2967
2968         ui_check_but(but);
2969 }
2970
2971 static uiBut *uiDefButBit(uiBlock *block, int type, int bit, int retval, const char *str, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2,  const char *tip)
2972 {
2973         int bitIdx= findBitIndex(bit);
2974         if (bitIdx==-1) {
2975                 return NULL;
2976         } else {
2977                 return uiDefBut(block, type|BIT|bitIdx, retval, str, x1, y1, x2, y2, poin, min, max, a1, a2, tip);
2978         }
2979 }
2980 uiBut *uiDefButF(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, float *poin, float min, float max, float a1, float a2,  const char *tip)
2981 {
2982         return uiDefBut(block, type|FLO, retval, str, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
2983 }
2984 uiBut *uiDefButBitF(uiBlock *block, int type, int bit, int retval, const char *str, int x1, int y1, short x2, short y2, float *poin, float min, float max, float a1, float a2,  const char *tip)
2985 {
2986         return uiDefButBit(block, type|FLO, bit, retval, str, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
2987 }
2988 uiBut *uiDefButI(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, int *poin, float min, float max, float a1, float a2,  const char *tip)
2989 {
2990         return uiDefBut(block, type|INT, retval, str, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
2991 }
2992 uiBut *uiDefButBitI(uiBlock *block, int type, int bit, int retval, const char *str, int x1, int y1, short x2, short y2, int *poin, float min, float max, float a1, float a2,  const char *tip)
2993 {
2994         return uiDefButBit(block, type|INT, bit, retval, str, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
2995 }
2996 uiBut *uiDefButS(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, short *poin, float min, float max, float a1, float a2,  const char *tip)
2997 {
2998         return uiDefBut(block, type|SHO, retval, str, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
2999 }
3000 uiBut *uiDefButBitS(uiBlock *block, int type, int bit, int retval, const char *str, int x1, int y1, short x2, short y2, short *poin, float min, float max, float a1, float a2,  const char *tip)
3001 {
3002         return uiDefButBit(block, type|SHO, bit, retval, str, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3003 }
3004 uiBut *uiDefButC(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, char *poin, float min, float max, float a1, float a2,  const char *tip)
3005 {
3006         return uiDefBut(block, type|CHA, retval, str, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3007 }
3008 uiBut *uiDefButBitC(uiBlock *block, int type, int bit, int retval, const char *str, int x1, int y1, short x2, short y2, char *poin, float min, float max, float a1, float a2,  const char *tip)
3009 {
3010         return uiDefButBit(block, type|CHA, bit, retval, str, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3011 }
3012 uiBut *uiDefButR(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, PointerRNA *ptr, const char *propname, int index, float min, float max, float a1, float a2,  const char *tip)
3013 {
3014         uiBut *but;
3015         but= ui_def_but_rna_propname(block, type, retval, str, x1, y1, x2, y2, ptr, propname, index, min, max, a1, a2, tip);
3016         ui_check_but(but);
3017         return but;
3018 }
3019 uiBut *uiDefButR_prop(uiBlock *block, int type, int retval, const char *str, int x1, int y1, short x2, short y2, PointerRNA *ptr, PropertyRNA *prop, int index, float min, float max, float a1, float a2,  const char *tip)
3020 {
3021         uiBut *but;
3022         but= ui_def_but_rna(block, type, retval, str, x1, y1, x2, y2, ptr, prop, index, min, max, a1, a2, tip);
3023         ui_check_but(but);
3024         return but;
3025 }
3026 uiBut *uiDefButO(uiBlock *block, int type, const char *opname, int opcontext, const char *str, int x1, int y1, short x2, short y2, const char *tip)
3027 {
3028         uiBut *but;
3029         but= ui_def_but_operator(block, type, opname, opcontext, str, x1, y1, x2, y2, tip);
3030         ui_check_but(but);
3031         return but;
3032 }
3033
3034 uiBut *uiDefButTextO(uiBlock *block, int type, const char *opname, int opcontext, const char *str, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2,  const char *tip)
3035 {
3036         uiBut *but= ui_def_but_operator_text(block, type, opname, opcontext, str, x1, y1, x2, y2, poin, min, max, a1, a2, tip);
3037         ui_check_but(but);
3038         return but;
3039 }
3040
3041 /* if a1==1.0 then a2 is an extra icon blending factor (alpha 0.0 - 1.0) */
3042 uiBut *uiDefIconBut(uiBlock *block, int type, int retval, int icon, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2,  const char *tip)
3043 {
3044         uiBut *but= ui_def_but(block, type, retval, "", x1, y1, x2, y2, poin, min, max, a1, a2, tip);
3045         ui_check_but_and_iconize(but, icon);
3046         return but;
3047 }
3048 static uiBut *uiDefIconButBit(uiBlock *block, int type, int bit, int retval, int icon, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2, const char *tip)
3049 {
3050         int bitIdx= findBitIndex(bit);
3051         if (bitIdx==-1) {
3052                 return NULL;
3053         } else {
3054                 return uiDefIconBut(block, type|BIT|bitIdx, retval, icon, x1, y1, x2, y2, poin, min, max, a1, a2, tip);
3055         }
3056 }
3057
3058 uiBut *uiDefIconButF(uiBlock *block, int type, int retval, int icon, int x1, int y1, short x2, short y2, float *poin, float min, float max, float a1, float a2,  const char *tip)
3059 {
3060         return uiDefIconBut(block, type|FLO, retval, icon, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3061 }
3062 uiBut *uiDefIconButBitF(uiBlock *block, int type, int bit, int retval, int icon, int x1, int y1, short x2, short y2, float *poin, float min, float max, float a1, float a2,  const char *tip)
3063 {
3064         return uiDefIconButBit(block, type|FLO, bit, retval, icon, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3065 }
3066 uiBut *uiDefIconButI(uiBlock *block, int type, int retval, int icon, int x1, int y1, short x2, short y2, int *poin, float min, float max, float a1, float a2,  const char *tip)
3067 {
3068         return uiDefIconBut(block, type|INT, retval, icon, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3069 }
3070 uiBut *uiDefIconButBitI(uiBlock *block, int type, int bit, int retval, int icon, int x1, int y1, short x2, short y2, int *poin, float min, float max, float a1, float a2,  const char *tip)
3071 {
3072         return uiDefIconButBit(block, type|INT, bit, retval, icon, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3073 }
3074 uiBut *uiDefIconButS(uiBlock *block, int type, int retval, int icon, int x1, int y1, short x2, short y2, short *poin, float min, float max, float a1, float a2,  const char *tip)
3075 {
3076         return uiDefIconBut(block, type|SHO, retval, icon, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3077 }
3078 uiBut *uiDefIconButBitS(uiBlock *block, int type, int bit, int retval, int icon, int x1, int y1, short x2, short y2, short *poin, float min, float max, float a1, float a2,  const char *tip)
3079 {
3080         return uiDefIconButBit(block, type|SHO, bit, retval, icon, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3081 }
3082 uiBut *uiDefIconButC(uiBlock *block, int type, int retval, int icon, int x1, int y1, short x2, short y2, char *poin, float min, float max, float a1, float a2,  const char *tip)
3083 {
3084         return uiDefIconBut(block, type|CHA, retval, icon, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3085 }
3086 uiBut *uiDefIconButBitC(uiBlock *block, int type, int bit, int retval, int icon, int x1, int y1, short x2, short y2, char *poin, float min, float max, float a1, float a2,  const char *tip)
3087 {
3088         return uiDefIconButBit(block, type|CHA, bit, retval, icon, x1, y1, x2, y2, (void*) poin, min, max, a1, a2, tip);
3089 }
3090 uiBut *uiDefIconButR(uiBlock *block, int type, int retval, int icon, int x1, int y1, short x2, short y2, PointerRNA *ptr, const char *propname, int index, float min, float max, float a1, float a2,  const char *tip)
3091 {
3092         uiBut *but;
3093         but= ui_def_but_rna_propname(block, type, retval, "", x1, y1, x2, y2, ptr, propname, index, min, max, a1, a2, tip);
3094         ui_check_but_and_iconize(but, icon);
3095         return but;
3096 }
3097 uiBut *uiDefIconButR_prop(uiBlock *block, int type, int retval, int icon, int x1, int y1, short x2, short y2, PointerRNA *ptr, PropertyRNA *prop, int index, float min, float max, float a1, float a2,  const char *tip)
3098 {
3099         uiBut *but;
3100         but= ui_def_but_rna(block, type, retval, "", x1, y1, x2, y2, ptr, prop, index, min, max, a1, a2, tip);
3101         ui_check_but_and_iconize(but, icon);
3102         return but;
3103 }
3104 uiBut *uiDefIconButO(uiBlock *block, int type, const char *opname, int opcontext, int icon, int x1, int y1, short x2, short y2, const char *tip)
3105 {
3106         uiBut *but;
3107         but= ui_def_but_operator(block, type, opname, opcontext, "", x1, y1, x2, y2, tip);
3108         ui_check_but_and_iconize(but, icon);
3109         return but;
3110 }
3111
3112 /* Button containing both string label and icon */
3113 uiBut *uiDefIconTextBut(uiBlock *block, int type, int retval, int icon, const char *str, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2,  const char *tip)
3114 {
3115         uiBut *but= ui_def_but(block, type, retval, str, x1, y1, x2, y2, poin, min, max, a1, a2, tip);
3116         ui_check_but_and_iconize(but, icon);
3117         but->flag|= UI_ICON_LEFT;
3118         return but;
3119 }
3120 static uiBut *uiDefIconTextButBit(uiBlock *block, int type, int bit, int retval, int icon, const char *str, int x1, int y1, short x2, short y2, void *poin, float min, float max, float a1, float a2,  const char *tip)
3121 {
3122         int bitIdx= findBitIndex(bit);
3123         if (bitIdx==-1) {
3124                 return NULL;
3125         } else {
3126                 return uiDefIconTextBut(block, type|BIT|bitIdx, retval, icon, str, x1, y1, x2, y2, poin, min, max, a1, a2, tip);
3127         }