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