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