a878632156fba5b08eb6e01bbb8afc8c8e72365e
[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_RCT_SIZE_X(&ar->winrct) + 1;
110         getsizey = BLI_RCT_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_RCT_SIZE_X(&ar->winrct) + 1;
156         getsizey = BLI_RCT_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_RCT_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_RCT_SIZE_X(&block->rect);
311         height = BLI_RCT_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_RCT_SIZE_X(&block->rect);
336         oldheight = BLI_RCT_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_RCT_SIZE_X(&block->rect);
352         height = BLI_RCT_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_RCT_CENTER_X(&line->from->rect);
499         rect.ymin = BLI_RCT_CENTER_Y(&line->from->rect);
500         rect.xmax = BLI_RCT_CENTER_X(&line->to->rect);
501         rect.ymax = BLI_RCT_CENTER_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 (!ELEM4(but->type, BUT, 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 COL:
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 == CHA) {
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 == FLO) {
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 == CHA) {
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 == FLO) {
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 == FLO && 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 == CHA) {
1471                 value = *(char *)but->poin;
1472         }
1473         else if (but->pointype == SHO) {
1474                 value = *(short *)but->poin;
1475         } 
1476         else if (but->pointype == INT) {
1477                 value = *(int *)but->poin;
1478         } 
1479         else if (but->pointype == FLO) {
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 == CHA)
1552                         value = (char)floor(value + 0.5);
1553                 else if (but->pointype == SHO) {
1554                         /* gcc 3.2.1 seems to have problems
1555                          * casting a double like 32772.0 to
1556                          * a short so we cast to an int, then
1557                          * to a short.
1558                          *
1559                          * Update: even in gcc.4.6 using intermediate int cast gives -32764,
1560                          * where as a direct cast from double to short gives -32768,
1561                          * if this difference isn't important we could remove this hack,
1562                          * since we dont support gcc3 anymore - Campbell */
1563                         int gcckludge;
1564                         gcckludge = (int) floor(value + 0.5);
1565                         value = (short)gcckludge;
1566                 }
1567                 else if (but->pointype == INT)
1568                         value = (int)floor(value + 0.5);
1569                 else if (but->pointype == FLO) {
1570                         float fval = (float)value;
1571                         if (fval >= -0.00001f && fval <= 0.00001f) fval = 0.0f;  /* prevent negative zero */
1572                         value = fval;
1573                 }
1574                 
1575                 /* then set value with possible edit override */
1576                 if (but->editval)
1577                         value = *but->editval = value;
1578                 else if (but->pointype == CHA)
1579                         value = *((char *)but->poin) = (char)value;
1580                 else if (but->pointype == SHO)
1581                         value = *((short *)but->poin) = (short)value;
1582                 else if (but->pointype == INT)
1583                         value = *((int *)but->poin) = (int)value;
1584                 else if (but->pointype == FLO)
1585                         value = *((float *)but->poin) = (float)value;
1586         }
1587
1588         /* update select flag */
1589         ui_is_but_sel(but, &value);
1590 }
1591
1592 int ui_get_but_string_max_length(uiBut *but)
1593 {
1594         if (ELEM(but->type, TEX, SEARCH_MENU))
1595                 return but->hardmax;
1596         else if (but->type == IDPOIN)
1597                 return MAX_ID_NAME - 2;
1598         else
1599                 return UI_MAX_DRAW_STR;
1600 }
1601
1602 static double ui_get_but_scale_unit(uiBut *but, double value)
1603 {
1604         UnitSettings *unit = but->block->unit;
1605         int unit_type = uiButGetUnitType(but);
1606
1607         if (unit_type == PROP_UNIT_LENGTH) {
1608                 return value * (double)unit->scale_length;
1609         }
1610         else if (unit_type == PROP_UNIT_AREA) {
1611                 return value * pow(unit->scale_length, 2);
1612         }
1613         else if (unit_type == PROP_UNIT_VOLUME) {
1614                 return value * pow(unit->scale_length, 3);
1615         }
1616         else if (unit_type == PROP_UNIT_TIME) { /* WARNING - using evil_C :| */
1617                 Scene *scene = CTX_data_scene(but->block->evil_C);
1618                 return FRA2TIME(value);
1619         }
1620         else {
1621                 return value;
1622         }
1623 }
1624
1625 /* str will be overwritten */
1626 void ui_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen)
1627 {
1628         if (ui_is_but_unit(but)) {
1629                 UnitSettings *unit = but->block->unit;
1630                 int unit_type = uiButGetUnitType(but);
1631                 char *orig_str;
1632                 
1633                 orig_str = MEM_callocN(sizeof(char) * maxlen + 1, "textedit sub str");
1634                 memcpy(orig_str, str, maxlen);
1635                 
1636                 bUnit_ToUnitAltName(str, maxlen, orig_str, unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1637                 
1638                 MEM_freeN(orig_str);
1639         }
1640 }
1641
1642 static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double value, int pad)
1643 {
1644         UnitSettings *unit = but->block->unit;
1645         int do_split = unit->flag & USER_UNIT_OPT_SPLIT;
1646         int unit_type = uiButGetUnitType(but);
1647         int precision = but->a2;
1648
1649         if (unit->scale_length < 0.0001f) unit->scale_length = 1.0f;  // XXX do_versions
1650
1651         /* Sanity checks */
1652         if (precision > PRECISION_FLOAT_MAX) precision = PRECISION_FLOAT_MAX;
1653         else if (precision == 0) precision = 2;
1654
1655         bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision,
1656                        unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad);
1657 }
1658
1659 static float ui_get_but_step_unit(uiBut *but, float step_default)
1660 {
1661         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
1662         float step;
1663
1664         step = bUnit_ClosestScalar(ui_get_but_scale_unit(but, step_default), but->block->unit->system, unit_type);
1665
1666         if (step > 0.0f) { /* -1 is an error value */
1667                 return (float)((double)step / ui_get_but_scale_unit(but, 1.0)) * 100.0f;
1668         }
1669         else {
1670                 return step_default;
1671         }
1672 }
1673
1674
1675 void ui_get_but_string(uiBut *but, char *str, size_t maxlen)
1676 {
1677         if (but->rnaprop && ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1678                 PropertyType type;
1679                 char *buf = NULL;
1680                 int buf_len;
1681
1682                 type = RNA_property_type(but->rnaprop);
1683
1684                 if (type == PROP_STRING) {
1685                         /* RNA string */
1686                         buf = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, str, maxlen, &buf_len);
1687                 }
1688                 else if (type == PROP_POINTER) {
1689                         /* RNA pointer */
1690                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
1691                         buf = RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
1692                 }
1693
1694                 if (!buf) {
1695                         str[0] = '\0';
1696                 }
1697                 else if (buf && buf != str) {
1698                         /* string was too long, we have to truncate */
1699                         memcpy(str, buf, MIN2(maxlen, buf_len + 1));
1700                         MEM_freeN(buf);
1701                 }
1702         }
1703         else if (but->type == IDPOIN) {
1704                 /* ID pointer */
1705                 if (but->idpoin_idpp) { /* Can be NULL for ID properties by python */
1706                         ID *id = *(but->idpoin_idpp);
1707                         if (id) {
1708                                 BLI_strncpy(str, id->name + 2, maxlen);
1709                                 return;
1710                         }
1711                 }
1712                 str[0] = '\0';
1713                 return;
1714         }
1715         else if (but->type == TEX) {
1716                 /* string */
1717                 BLI_strncpy(str, but->poin, maxlen);
1718                 return;
1719         }
1720         else if (but->type == SEARCH_MENU) {
1721                 /* string */
1722                 BLI_strncpy(str, but->poin, maxlen);
1723                 return;
1724         }
1725         else if (ui_but_anim_expression_get(but, str, maxlen))
1726                 ;  /* driver expression */
1727         else {
1728                 /* number editing */
1729                 double value;
1730
1731                 value = ui_get_but_val(but);
1732
1733                 if (ui_is_but_float(but)) {
1734                         if (ui_is_but_unit(but)) {
1735                                 ui_get_but_string_unit(but, str, maxlen, value, 0);
1736                         }
1737                         else {
1738                                 const int prec = ui_but_float_precision(but, value);
1739                                 BLI_snprintf(str, maxlen, "%.*f", prec, value);
1740                         }
1741                 }
1742                 else
1743                         BLI_snprintf(str, maxlen, "%d", (int)value);
1744         }
1745 }
1746
1747 #ifdef WITH_PYTHON
1748
1749 static int ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *value)
1750 {
1751         char str_unit_convert[256];
1752         const int unit_type = uiButGetUnitType(but);
1753
1754         BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert));
1755
1756         /* ugly, use the draw string to get the value,
1757          * this could cause problems if it includes some text which resolves to a unit */
1758         bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr,
1759                             ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1760
1761         return (BPY_button_exec(C, str_unit_convert, value, TRUE) != -1);
1762 }
1763
1764 #endif /* WITH_PYTHON */
1765
1766
1767 int ui_set_but_string_eval_num(bContext *C, uiBut *but, const char *str, double *value)
1768 {
1769         int ok = FALSE;
1770
1771 #ifdef WITH_PYTHON
1772
1773         if (str[0] != '\0') {
1774                 int is_unit_but = ui_is_but_unit(but);
1775                 /* only enable verbose if we won't run again with units */
1776                 if (BPY_button_exec(C, str, value, is_unit_but == FALSE) != -1) {
1777                         /* if the value parsed ok without unit conversion this button may still need a unit multiplier */
1778                         if (is_unit_but) {
1779                                 char str_new[128];
1780
1781                                 BLI_snprintf(str_new, sizeof(str_new), "%f", *value);
1782                                 ok = ui_set_but_string_eval_num_unit(C, but, str_new, value);
1783                         }
1784                         else {
1785                                 ok = TRUE; /* parse normal string via py (no unit conversion needed) */
1786                         }
1787                 }
1788                 else if (is_unit_but) {
1789                         /* parse failed, this is a unit but so run replacements and parse again */
1790                         ok = ui_set_but_string_eval_num_unit(C, but, str, value);
1791                 }
1792         }
1793
1794 #else /* WITH_PYTHON */
1795
1796         *value = atof(str);
1797         ok = TRUE;
1798
1799         (void)C;
1800         (void)but;
1801
1802 #endif /* WITH_PYTHON */
1803
1804         return ok;
1805 }
1806
1807
1808 int ui_set_but_string(bContext *C, uiBut *but, const char *str)
1809 {
1810         if (but->rnaprop && ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1811                 if (RNA_property_editable(&but->rnapoin, but->rnaprop)) {
1812                         PropertyType type;
1813
1814                         type = RNA_property_type(but->rnaprop);
1815
1816                         if (type == PROP_STRING) {
1817                                 /* RNA string */
1818                                 RNA_property_string_set(&but->rnapoin, but->rnaprop, str);
1819                                 return 1;
1820                         }
1821                         else if (type == PROP_POINTER) {
1822                                 /* RNA pointer */
1823                                 PointerRNA ptr, rptr;
1824                                 PropertyRNA *prop;
1825
1826                                 if (str == NULL || str[0] == '\0') {
1827                                         RNA_property_pointer_set(&but->rnapoin, but->rnaprop, PointerRNA_NULL);
1828                                         return 1;
1829                                 }
1830                                 else {
1831                                         ptr = but->rnasearchpoin;
1832                                         prop = but->rnasearchprop;
1833                                         
1834                                         if (prop && RNA_property_collection_lookup_string(&ptr, prop, str, &rptr))
1835                                                 RNA_property_pointer_set(&but->rnapoin, but->rnaprop, rptr);
1836
1837                                         return 1;
1838                                 }
1839
1840                                 return 0;
1841                         }
1842                 }
1843         }
1844         else if (but->type == IDPOIN) {
1845                 /* ID pointer */
1846                 but->idpoin_func(C, str, but->idpoin_idpp);
1847                 return 1;
1848         }
1849         else if (but->type == TEX) {
1850                 /* string */
1851                 if (ui_is_but_utf8(but)) BLI_strncpy_utf8(but->poin, str, but->hardmax);
1852                 else BLI_strncpy(but->poin, str, but->hardmax);
1853
1854                 return 1;
1855         }
1856         else if (but->type == SEARCH_MENU) {
1857                 /* string */
1858                 BLI_strncpy(but->poin, str, but->hardmax);
1859                 return 1;
1860         }
1861         else if (ui_but_anim_expression_set(but, str)) {
1862                 /* driver expression */
1863                 return 1;
1864         }
1865         else if (str[0] == '#') {
1866                 /* shortcut to create new driver expression (versus immediate Py-execution) */
1867                 return ui_but_anim_expression_create(but, str + 1);
1868         }
1869         else {
1870                 /* number editing */
1871                 double value;
1872
1873                 if (ui_set_but_string_eval_num(C, but, str, &value) == FALSE) {
1874                         return 0;
1875                 }
1876
1877                 if (!ui_is_but_float(but)) value = (int)floor(value + 0.5);
1878                 if (but->type == NUMABS) value = fabs(value);
1879
1880                 /* not that we use hard limits here */
1881                 if (value < (double)but->hardmin) value = but->hardmin;
1882                 if (value > (double)but->hardmax) value = but->hardmax;
1883
1884                 ui_set_but_val(but, value);
1885                 return 1;
1886         }
1887
1888         return 0;
1889 }
1890
1891 void ui_set_but_default(bContext *C, short all)
1892 {
1893         PointerRNA ptr;
1894
1895         WM_operator_properties_create(&ptr, "UI_OT_reset_default_button");
1896         RNA_boolean_set(&ptr, "all", all);
1897         WM_operator_name_call(C, "UI_OT_reset_default_button", WM_OP_EXEC_DEFAULT, &ptr);
1898         WM_operator_properties_free(&ptr);
1899 }
1900
1901 static double soft_range_round_up(double value, double max)
1902 {
1903         /* round up to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, .. */
1904         double newmax = pow(10.0, ceil(log(value) / M_LN10));
1905
1906         if (newmax * 0.2 >= max && newmax * 0.2 >= value)
1907                 return newmax * 0.2;
1908         else if (newmax * 0.5 >= max && newmax * 0.5 >= value)
1909                 return newmax * 0.5;
1910         else
1911                 return newmax;
1912 }
1913
1914 static double soft_range_round_down(double value, double max)
1915 {
1916         /* round down to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, .. */
1917         double newmax = pow(10.0, floor(log(value) / M_LN10));
1918
1919         if (newmax * 5.0 <= max && newmax * 5.0 <= value)
1920                 return newmax * 5.0;
1921         else if (newmax * 2.0 <= max && newmax * 2.0 <= value)
1922                 return newmax * 2.0;
1923         else
1924                 return newmax;
1925 }
1926
1927 void ui_set_but_soft_range(uiBut *but, double value)
1928 {
1929         /* ideally we would not limit this but practically, its more then
1930          * enough worst case is very long vectors wont use a smart soft-range
1931          * which isn't so bad. */
1932
1933         if (but->rnaprop) {
1934                 const PropertyType type = RNA_property_type(but->rnaprop);
1935                 double softmin, softmax /*, step, precision*/;
1936                 double value_min = value;
1937                 double value_max = value;
1938
1939                 /* clamp button range to something reasonable in case
1940                  * we get -inf/inf from RNA properties */
1941                 if (type == PROP_INT) {
1942                         int imin, imax, istep;
1943                         const int array_len = RNA_property_array_length(&but->rnapoin, but->rnaprop);
1944
1945                         RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
1946                         softmin = (imin == INT_MIN) ? -1e4 : imin;
1947                         softmax = (imin == INT_MAX) ? 1e4 : imax;
1948                         /*step= istep;*/ /*UNUSED*/
1949                         /*precision= 1;*/ /*UNUSED*/
1950
1951                         if (array_len >= 2) {
1952                                 int value_range[2];
1953                                 RNA_property_int_get_array_range(&but->rnapoin, but->rnaprop, value_range);
1954                                 value_min = (double)value_range[0];
1955                                 value_max = (double)value_range[1];
1956                         }
1957                 }
1958                 else if (type == PROP_FLOAT) {
1959                         float fmin, fmax, fstep, fprecision;
1960                         const int array_len = RNA_property_array_length(&but->rnapoin, but->rnaprop);
1961
1962                         RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
1963                         softmin = (fmin == -FLT_MAX) ? (float)-1e4 : fmin;
1964                         softmax = (fmax == FLT_MAX) ? (float)1e4 : fmax;
1965                         /*step= fstep;*/ /*UNUSED*/
1966                         /*precision= fprecision;*/ /*UNUSED*/
1967
1968                         if (array_len >= 2) {
1969                                 float value_range[2];
1970                                 RNA_property_float_get_array_range(&but->rnapoin, but->rnaprop, value_range);
1971                                 value_min = (double)value_range[0];
1972                                 value_max = (double)value_range[1];
1973                         }
1974                 }
1975                 else
1976                         return;
1977
1978                 /* if the value goes out of the soft/max range, adapt the range */
1979                 if (value_min + 1e-10 < softmin) {
1980                         if (value_min < 0.0)
1981                                 softmin = -soft_range_round_up(-value_min, -softmin);
1982                         else
1983                                 softmin = soft_range_round_down(value_min, softmin);
1984
1985                         if (softmin < (double)but->hardmin)
1986                                 softmin = (double)but->hardmin;
1987                 }
1988                 if (value_max - 1e-10 > softmax) {
1989                         if (value_max < 0.0)
1990                                 softmax = -soft_range_round_down(-value_max, -softmax);
1991                         else
1992                                 softmax = soft_range_round_up(value_max, softmax);
1993
1994                         if (softmax > (double)but->hardmax)
1995                                 softmax = but->hardmax;
1996                 }
1997
1998                 but->softmin = softmin;
1999                 but->softmax = softmax;
2000         }
2001 }
2002
2003 /* ******************* Free ********************/
2004
2005 static void ui_free_link(uiLink *link)
2006 {
2007         if (link) {     
2008                 BLI_freelistN(&link->lines);
2009                 MEM_freeN(link);
2010         }
2011 }
2012
2013 /* can be called with C==NULL */
2014 static void ui_free_but(const bContext *C, uiBut *but)
2015 {
2016         if (but->opptr) {
2017                 WM_operator_properties_free(but->opptr);
2018                 MEM_freeN(but->opptr);
2019         }
2020
2021         if (but->func_argN) {
2022                 MEM_freeN(but->func_argN);
2023         }
2024
2025         if (but->active) {
2026                 /* XXX solve later, buttons should be free-able without context ideally,
2027                  * however they may have open tooltips or popup windows, which need to
2028                  * be closed using a context pointer */
2029                 if (C) {
2030                         ui_button_active_free(C, but);
2031                 }
2032                 else {
2033                         if (but->active) {
2034                                 MEM_freeN(but->active);
2035                         }
2036                 }
2037         }
2038         if (but->str && but->str != but->strdata) {
2039                 MEM_freeN(but->str);
2040         }
2041         ui_free_link(but->link);
2042
2043         if ((but->type == BUT_IMAGE) && but->poin) {
2044                 IMB_freeImBuf((struct ImBuf *)but->poin);
2045         }
2046
2047         MEM_freeN(but);
2048 }
2049
2050 /* can be called with C==NULL */
2051 void uiFreeBlock(const bContext *C, uiBlock *block)
2052 {
2053         uiBut *but;
2054
2055         while ( (but = block->buttons.first) ) {
2056                 BLI_remlink(&block->buttons, but);      
2057                 ui_free_but(C, but);
2058         }
2059
2060         if (block->unit) {
2061                 MEM_freeN(block->unit);
2062         }
2063
2064         if (block->func_argN) {
2065                 MEM_freeN(block->func_argN);
2066         }
2067
2068         CTX_store_free_list(&block->contexts);
2069
2070         BLI_freelistN(&block->saferct);
2071         
2072         MEM_freeN(block);
2073 }
2074
2075 /* can be called with C==NULL */
2076 void uiFreeBlocks(const bContext *C, ListBase *lb)
2077 {
2078         uiBlock *block;
2079         
2080         while ( (block = lb->first) ) {
2081                 BLI_remlink(lb, block);
2082                 uiFreeBlock(C, block);
2083         }
2084 }
2085
2086 void uiFreeInactiveBlocks(const bContext *C, ListBase *lb)
2087 {
2088         uiBlock *block, *nextblock;
2089
2090         for (block = lb->first; block; block = nextblock) {
2091                 nextblock = block->next;
2092         
2093                 if (!block->handle) {
2094                         if (!block->active) {
2095                                 BLI_remlink(lb, block);
2096                                 uiFreeBlock(C, block);
2097                         }
2098                         else
2099                                 block->active = 0;
2100                 }
2101         }
2102 }
2103
2104 void uiBlockSetRegion(uiBlock *block, ARegion *region)
2105 {
2106         ListBase *lb = &region->uiblocks;
2107         uiBlock *oldblock = NULL;
2108
2109         /* each listbase only has one block with this name, free block
2110          * if is already there so it can be rebuilt from scratch */
2111         if (lb) {
2112                 oldblock = BLI_findstring(lb, block->name, offsetof(uiBlock, name));
2113
2114                 if (oldblock) {
2115                         oldblock->active = 0;
2116                         oldblock->panel = NULL;
2117                 }
2118
2119                 /* at the beginning of the list! for dynamical menus/blocks */
2120                 BLI_addhead(lb, block);
2121         }
2122
2123         block->oldblock = oldblock;
2124 }
2125
2126 uiBlock *uiBeginBlock(const bContext *C, ARegion *region, const char *name, short dt)
2127 {
2128         uiBlock *block;
2129         wmWindow *window;
2130         Scene *scn;
2131         int getsizex, getsizey;
2132
2133         window = CTX_wm_window(C);
2134         scn = CTX_data_scene(C);
2135
2136         block = MEM_callocN(sizeof(uiBlock), "uiBlock");
2137         block->active = 1;
2138         block->dt = dt;
2139         block->evil_C = (void *)C;  /* XXX */
2140
2141         if (scn) {
2142                 block->color_profile = TRUE;
2143
2144                 /* store display device name, don't lookup for transformations yet
2145                  * block could be used for non-color displays where looking up for transformation
2146                  * would slow down redraw, so only lookup for actual transform when it's indeed
2147                  * needed
2148                  */
2149                 block->display_device = scn->display_settings.display_device;
2150
2151                 /* copy to avoid crash when scene gets deleted with ui still open */
2152                 block->unit = MEM_mallocN(sizeof(scn->unit), "UI UnitSettings");
2153                 memcpy(block->unit, &scn->unit, sizeof(scn->unit));
2154         }
2155
2156         BLI_strncpy(block->name, name, sizeof(block->name));
2157
2158         if (region)
2159                 uiBlockSetRegion(block, region);
2160
2161         /* window matrix and aspect */
2162         if (region && region->swinid) {
2163                 wm_subwindow_getmatrix(window, region->swinid, block->winmat);
2164                 wm_subwindow_getsize(window, region->swinid, &getsizex, &getsizey);
2165
2166                 /* TODO - investigate why block->winmat[0][0] is negative
2167                  * in the image view when viewRedrawForce is called */
2168                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2169         }
2170         else {
2171                 /* no subwindow created yet, for menus for example, so we
2172                  * use the main window instead, since buttons are created
2173                  * there anyway */
2174                 wm_subwindow_getmatrix(window, window->screen->mainwin, block->winmat);
2175                 wm_subwindow_getsize(window, window->screen->mainwin, &getsizex, &getsizey);
2176
2177                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2178                 block->auto_open = TRUE;
2179                 block->flag |= UI_BLOCK_LOOP; /* tag as menu */
2180         }
2181
2182         return block;
2183 }
2184
2185 uiBlock *uiGetBlock(const char *name, ARegion *ar)
2186 {
2187         return BLI_findstring(&ar->uiblocks, name, offsetof(uiBlock, name));
2188 }
2189
2190 void uiBlockSetEmboss(uiBlock *block, char dt)
2191 {
2192         block->dt = dt;
2193 }
2194
2195 void ui_check_but(uiBut *but)
2196 {
2197         /* if something changed in the button */
2198         double value = UI_BUT_VALUE_UNSET;
2199 //      float okwidth; // UNUSED
2200         
2201         ui_is_but_sel(but, &value);
2202         
2203         /* only update soft range while not editing */
2204         if (but->rnaprop && !(but->editval || but->editstr || but->editvec)) {
2205                 UI_GET_BUT_VALUE_INIT(but, value);
2206                 ui_set_but_soft_range(but, value);
2207         }
2208
2209         /* test for min and max, icon sliders, etc */
2210         switch (but->type) {
2211                 case NUM:
2212                 case SLI:
2213                 case SCROLL:
2214                 case NUMSLI:
2215                 case HSVSLI:
2216                         UI_GET_BUT_VALUE_INIT(but, value);
2217                         if (value < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2218                         else if (value > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2219                         break;
2220                         
2221                 case NUMABS:
2222                 {
2223                         double value_abs;
2224                         UI_GET_BUT_VALUE_INIT(but, value);
2225                         value_abs = fabs(value);
2226                         if (value_abs < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2227                         else if (value_abs > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2228                         break;
2229                 }
2230                 case ICONTOG: 
2231                 case ICONTOGN:
2232                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2233                                 if (but->flag & UI_SELECT) but->iconadd = 1;
2234                                 else but->iconadd = 0;
2235                         }
2236                         break;
2237                         
2238                 case ICONROW:
2239                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2240                                 UI_GET_BUT_VALUE_INIT(but, value);
2241                                 but->iconadd = (int)value - (int)(but->hardmin);
2242                         }
2243                         break;
2244                         
2245                 case ICONTEXTROW:
2246                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2247                                 UI_GET_BUT_VALUE_INIT(but, value);
2248                                 but->iconadd = (int)value - (int)(but->hardmin);
2249                         }
2250                         break;
2251
2252                         /* quiet warnings for unhandled types */
2253                 default:
2254                         break;
2255         }
2256         
2257         
2258         /* safety is 4 to enable small number buttons (like 'users') */
2259         // okwidth= -4 + (BLI_RCT_SIZE_X(&but->rect)); // UNUSED
2260         
2261         /* name: */
2262         switch (but->type) {
2263         
2264                 case MENU:
2265                 case ICONTEXTROW:
2266                 
2267                         if (BLI_RCT_SIZE_X(&but->rect) > 24.0f) {
2268                                 UI_GET_BUT_VALUE_INIT(but, value);
2269                                 ui_set_name_menu(but, (int)value);
2270                         }
2271                         break;
2272         
2273                 case NUM:
2274                 case NUMSLI:
2275                 case HSVSLI:
2276                 case NUMABS:
2277
2278                         UI_GET_BUT_VALUE_INIT(but, value);
2279
2280                         if (ui_is_but_float(but)) {
2281                                 if (value == (double) FLT_MAX) {
2282                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%sinf", but->str);
2283                                 }
2284                                 else if (value == (double) -FLT_MAX) {
2285                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s-inf", but->str);
2286                                 }
2287                                 /* support length type buttons */
2288                                 else if (ui_is_but_unit(but)) {
2289                                         char new_str[sizeof(but->drawstr)];
2290                                         ui_get_but_string_unit(but, new_str, sizeof(new_str), value, TRUE);
2291                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, new_str);
2292                                 }
2293                                 else {
2294                                         const int prec = ui_but_float_precision(but, value);
2295                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2296                                 }
2297                         }
2298                         else {
2299                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%d", but->str, (int)value);
2300                         }
2301                         
2302                         if (but->rnaprop) {
2303                                 PropertySubType pstype = RNA_property_subtype(but->rnaprop);
2304                         
2305                                 if (pstype == PROP_PERCENTAGE)
2306                                         strcat(but->drawstr, "%");
2307                         }
2308                         break;
2309
2310                 case LABEL:
2311                         if (ui_is_but_float(but)) {
2312                                 int prec;
2313                                 UI_GET_BUT_VALUE_INIT(but, value);
2314                                 prec = ui_but_float_precision(but, value);
2315                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2316                         }
2317                         else {
2318                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2319                         }
2320                 
2321                         break;
2322
2323                 case IDPOIN:
2324                 case TEX:
2325                 case SEARCH_MENU:
2326                         if (!but->editstr) {
2327                                 char str[UI_MAX_DRAW_STR];
2328
2329                                 ui_get_but_string(but, str, UI_MAX_DRAW_STR - strlen(but->str));
2330
2331                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, str);
2332                         }
2333                         break;
2334         
2335                 case KEYEVT:
2336                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2337                         if (but->flag & UI_SELECT) {
2338                                 strcat(but->drawstr, "Press a key");
2339                         }
2340                         else {
2341                                 UI_GET_BUT_VALUE_INIT(but, value);
2342                                 strcat(but->drawstr, WM_key_event_string((short)value));
2343                         }
2344                         break;
2345                 
2346                 case HOTKEYEVT:
2347                         if (but->flag & UI_SELECT) {
2348                                 but->drawstr[0] = '\0';
2349
2350                                 if (but->modifier_key) {
2351                                         char *str = but->drawstr;
2352
2353                                         if (but->modifier_key & KM_SHIFT)
2354                                                 str = strcat(str, "Shift ");
2355                                         if (but->modifier_key & KM_CTRL)
2356                                                 str = strcat(str, "Ctrl ");
2357                                         if (but->modifier_key & KM_ALT)
2358                                                 str = strcat(str, "Alt ");
2359                                         if (but->modifier_key & KM_OSKEY)
2360                                                 str = strcat(str, "Cmd ");
2361
2362                                         (void)str; /* UNUSED */
2363                                 }
2364                                 else
2365                                         strcat(but->drawstr, "Press a key  ");
2366                         }
2367                         else
2368                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2369
2370                         break;
2371
2372                 case BUT_TOGDUAL:
2373                         /* trying to get the dual-icon to left of text... not very nice */
2374                         if (but->str[0]) {
2375                                 BLI_strncpy(but->drawstr, "  ", UI_MAX_DRAW_STR);
2376                                 BLI_strncpy(but->drawstr + 2, but->str, UI_MAX_DRAW_STR - 2);
2377                         }
2378                         break;
2379                 
2380                 case HSVCUBE:
2381                 case HSVCIRCLE:
2382                         break;
2383                 default:
2384                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2385                 
2386         }
2387
2388         /* if we are doing text editing, this will override the drawstr */
2389         if (but->editstr)
2390                 BLI_strncpy(but->drawstr, but->editstr, UI_MAX_DRAW_STR);
2391         
2392         /* text clipping moved to widget drawing code itself */
2393 }
2394
2395
2396 void uiBlockBeginAlign(uiBlock *block)
2397 {
2398         /* if other align was active, end it */
2399         if (block->flag & UI_BUT_ALIGN) uiBlockEndAlign(block);
2400
2401         block->flag |= UI_BUT_ALIGN_DOWN;       
2402         block->alignnr++;
2403
2404         /* buttons declared after this call will get this align nr */ // XXX flag?
2405 }
2406
2407 static int buts_are_horiz(uiBut *but1, uiBut *but2)
2408 {
2409         float dx, dy;
2410         
2411         dx = fabs(but1->rect.xmax - but2->rect.xmin);
2412         dy = fabs(but1->rect.ymin - but2->rect.ymax);
2413         
2414         if (dx > dy) return 0;
2415         return 1;
2416 }
2417
2418 void uiBlockEndAlign(uiBlock *block)
2419 {
2420         block->flag &= ~UI_BUT_ALIGN;  /* all 4 flags */
2421 }
2422
2423 int ui_but_can_align(uiBut *but)
2424 {
2425         return !ELEM3(but->type, LABEL, OPTION, OPTIONN);
2426 }
2427
2428 static void ui_block_do_align_but(uiBut *first, short nr)
2429 {
2430         uiBut *prev, *but = NULL, *next;
2431         int flag = 0, cols = 0, rows = 0;
2432         
2433         /* auto align */
2434
2435         for (but = first; but && but->alignnr == nr; but = but->next) {
2436                 if (but->next && but->next->alignnr == nr) {
2437                         if (buts_are_horiz(but, but->next)) cols++;
2438                         else rows++;
2439                 }
2440         }
2441
2442         /* rows==0: 1 row, cols==0: 1 column */
2443         
2444         /* note;  how it uses 'flag' in loop below (either set it, or OR it) is confusing */
2445         for (but = first, prev = NULL; but && but->alignnr == nr; prev = but, but = but->next) {
2446                 next = but->next;
2447                 if (next && next->alignnr != nr)
2448                         next = NULL;
2449
2450                 /* clear old flag */
2451                 but->flag &= ~UI_BUT_ALIGN;
2452                         
2453                 if (flag == 0) {  /* first case */
2454                         if (next) {
2455                                 if (buts_are_horiz(but, next)) {
2456                                         if (rows == 0)
2457                                                 flag = UI_BUT_ALIGN_RIGHT;
2458                                         else 
2459                                                 flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_RIGHT;
2460                                 }
2461                                 else {
2462                                         flag = UI_BUT_ALIGN_DOWN;
2463                                 }
2464                         }
2465                 }
2466                 else if (next == NULL) {  /* last case */
2467                         if (prev) {
2468                                 if (buts_are_horiz(prev, but)) {
2469                                         if (rows == 0)
2470                                                 flag = UI_BUT_ALIGN_LEFT;
2471                                         else
2472                                                 flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_LEFT;
2473                                 }
2474                                 else flag = UI_BUT_ALIGN_TOP;
2475                         }
2476                 }
2477                 else if (buts_are_horiz(but, next)) {
2478                         /* check if this is already second row */
2479                         if (prev && buts_are_horiz(prev, but) == 0) {
2480                                 flag &= ~UI_BUT_ALIGN_LEFT;
2481                                 flag |= UI_BUT_ALIGN_TOP;
2482                                 /* exception case: bottom row */
2483                                 if (rows > 0) {
2484                                         uiBut *bt = but;
2485                                         while (bt && bt->alignnr == nr) {
2486                                                 if (bt->next && bt->next->alignnr == nr && buts_are_horiz(bt, bt->next) == 0) break;
2487                                                 bt = bt->next;
2488                                         }
2489                                         if (bt == NULL || bt->alignnr != nr) flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_RIGHT;
2490                                 }
2491                         }
2492                         else flag |= UI_BUT_ALIGN_LEFT;
2493                 }
2494                 else {
2495                         if (cols == 0) {
2496                                 flag |= UI_BUT_ALIGN_TOP;
2497                         }
2498                         else {  /* next button switches to new row */
2499                                 
2500                                 if (prev && buts_are_horiz(prev, but))
2501                                         flag |= UI_BUT_ALIGN_LEFT;
2502                                 else {
2503                                         flag &= ~UI_BUT_ALIGN_LEFT;
2504                                         flag |= UI_BUT_ALIGN_TOP;
2505                                 }
2506                                 
2507                                 if ((flag & UI_BUT_ALIGN_TOP) == 0) {  /* stil top row */
2508                                         if (prev) {
2509                                                 if (next && buts_are_horiz(but, next))
2510                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT | UI_BUT_ALIGN_RIGHT;
2511                                                 else {
2512                                                         /* last button in top row */
2513                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT;
2514                                                 }
2515                                         }
2516                                         else 
2517                                                 flag |= UI_BUT_ALIGN_DOWN;
2518                                 }
2519                                 else 
2520                                         flag |= UI_BUT_ALIGN_TOP;
2521                         }
2522                 }
2523                 
2524                 but->flag |= flag;
2525                 
2526                 /* merge coordinates */
2527                 if (prev) {
2528                         /* simple cases */
2529                         if (rows == 0) {
2530                                 but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2531                                 prev->rect.xmax = but->rect.xmin;
2532                         }
2533                         else if (cols == 0) {
2534                                 but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2535                                 prev->rect.ymin = but->rect.ymax;
2536                         }
2537                         else {
2538                                 if (buts_are_horiz(prev, but)) {
2539                                         but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2540                                         prev->rect.xmax = but->rect.xmin;
2541                                         /* copy height too */
2542                                         but->rect.ymax = prev->rect.ymax;
2543                                 }
2544                                 else if (prev->prev && buts_are_horiz(prev->prev, prev) == 0) {
2545                                         /* the previous button is a single one in its row */
2546                                         but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2547                                         prev->rect.ymin = but->rect.ymax;
2548                                         
2549                                         but->rect.xmin = prev->rect.xmin;
2550                                         if (next && buts_are_horiz(but, next) == 0)
2551                                                 but->rect.xmax = prev->rect.xmax;
2552                                 }
2553                                 else {
2554                                         /* the previous button is not a single one in its row */
2555                                         but->rect.ymax = prev->rect.ymin;
2556                                 }
2557                         }
2558                 }
2559         }
2560 }
2561
2562 void ui_block_do_align(uiBlock *block)
2563 {
2564         uiBut *but;
2565         short nr;
2566
2567         /* align buttons with same align nr */
2568         for (but = block->buttons.first; but; ) {
2569                 if (but->alignnr) {
2570                         nr = but->alignnr;
2571                         ui_block_do_align_but(but, nr);
2572
2573                         /* skip with same number */
2574                         for (; but && but->alignnr == nr; but = but->next) ;
2575
2576                         if (!but) {
2577                                 break;
2578                         }
2579                 }
2580                 else {
2581                         but = but->next;
2582                 }
2583         }
2584 }
2585
2586 struct ColorManagedDisplay *ui_block_display_get(uiBlock *block)
2587 {
2588         return IMB_colormanagement_display_get_named(block->display_device);
2589 }
2590
2591 void ui_block_to_display_space_v3(uiBlock *block, float pixel[3])
2592 {
2593         struct ColorManagedDisplay *display = ui_block_display_get(block);
2594
2595         IMB_colormanagement_scene_linear_to_display_v3(pixel, display);
2596 }
2597
2598 void ui_block_to_scene_linear_v3(uiBlock *block, float pixel[3])
2599 {
2600         struct ColorManagedDisplay *display = ui_block_display_get(block);
2601
2602         IMB_colormanagement_display_to_scene_linear_v3(pixel, display);
2603 }
2604
2605 /**
2606  * \brief ui_def_but is the function that draws many button types
2607  *
2608  * \param x,y The lower left hand corner of the button (X axis)
2609  * \param width,height The size of the button.
2610  *
2611  * for float buttons:
2612  * - \a a1 Click Step (how much to change the value each click)
2613  * - \a a2 Number of decimal point values to display. 0 defaults to 3 (0.000)
2614  *      1,2,3, and a maximum of 4, all greater values will be clamped to 4.
2615  */
2616 static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str,
2617                          int x, int y, short width, short height,
2618                          void *poin, float min, float max, float a1, float a2, const char *tip)
2619 {
2620         uiBut *but;
2621         int slen;
2622         
2623         if (type & BUTPOIN) {       /* a pointer is required */
2624                 if (poin == NULL)
2625                         return NULL;
2626         }
2627
2628         but = MEM_callocN(sizeof(uiBut), "uiBut");
2629
2630         but->type = type & BUTTYPE;
2631         but->pointype = type & BUTPOIN;
2632         but->bit = type & BIT;
2633         but->bitnr = type & 31;
2634         but->icon = ICON_NONE;
2635         but->iconadd = 0;
2636
2637         but->retval = retval;
2638
2639         slen = strlen(str);
2640         if (slen >= UI_MAX_NAME_STR - 1) {
2641                 but->str = MEM_mallocN(slen + 2, "ui_def_but str"); /* why +2 ? */
2642         }
2643         else {
2644                 but->str = but->strdata;
2645         }
2646         memcpy(but->str, str, slen + 1);
2647
2648         but->rect.xmin = x;
2649         but->rect.ymin = y;
2650         but->rect.xmax = but->rect.xmin + width;
2651         but->rect.ymax = but->rect.ymin + height;
2652
2653         but->poin = poin;
2654         but->hardmin = but->softmin = min;
2655         but->hardmax = but->softmax = max;
2656         but->a1 = a1;
2657         but->a2 = a2;
2658         but->tip = tip;
2659
2660         but->lock = block->lock;
2661         but->lockstr = block->lockstr;
2662         but->dt = block->dt;
2663
2664         but->aspect = 1.0f;  /* XXX block->aspect; */
2665         but->block = block;  /* pointer back, used for frontbuffer status, and picker */
2666
2667         if ((block->flag & UI_BUT_ALIGN) && ui_but_can_align(but))
2668                 but->alignnr = block->alignnr;
2669
2670         but->func = block->func;
2671         but->func_arg1 = block->func_arg1;
2672         but->func_arg2 = block->func_arg2;
2673
2674         but->funcN = block->funcN;
2675         if (block->func_argN)
2676                 but->func_argN = MEM_dupallocN(block->func_argN);
2677         
2678         but->pos = -1;   /* cursor invisible */
2679
2680         if (ELEM4(but->type, NUM, NUMABS, NUMSLI, HSVSLI)) {    /* add a space to name */
2681                 /* slen remains unchanged from previous assignment, ensure this stays true */
2682                 if (slen > 0 && slen < UI_MAX_NAME_STR - 2) {
2683                         if (but->str[slen - 1] != ' ') {
2684                                 but->str[slen] = ' ';
2685                                 but->str[slen + 1] = 0;
2686                         }
2687                 }
2688         }
2689
2690         if ((block->flag & UI_BLOCK_LOOP) ||
2691             ELEM8(but->type, MENU, TEX, LABEL, IDPOIN, BLOCK, BUTM, SEARCH_MENU, PROGRESSBAR))
2692         {
2693                 but->flag |= (UI_TEXT_LEFT | UI_ICON_LEFT);
2694         }
2695         else if (but->type == BUT_TOGDUAL) {
2696                 but->flag |= UI_ICON_LEFT;
2697         }
2698
2699         but->flag |= (block->flag & UI_BUT_ALIGN);
2700
2701         if (but->lock == TRUE) {
2702                 if (but->lockstr) {
2703                         but->flag |= UI_BUT_DISABLED;
2704                 }
2705         }
2706
2707         /* keep track of UI_interface.h */
2708         if (ELEM7(but->type, BLOCK, BUT, LABEL, PULLDOWN, ROUNDBOX, LISTBOX, BUTM)) ;
2709         else if (ELEM(but->type, SCROLL, SEPR /* , FTPREVIEW */ )) ;
2710         else if (but->type >= SEARCH_MENU) ;
2711         else but->flag |= UI_BUT_UNDO;
2712
2713         BLI_addtail(&block->buttons, but);
2714         
2715         if (block->curlayout)
2716                 ui_layout_add_but(block->curlayout, but);
2717
2718 #ifdef WITH_PYTHON
2719         /* if the 'UI_OT_editsource' is running, extract the source info from the button  */
2720         if (UI_editsource_enable_check()) {
2721                 UI_editsource_active_but_test(but);
2722         }
2723 #endif
2724
2725         return but;
2726 }
2727
2728 /* ui_def_but_rna_propname and ui_def_but_rna
2729  * both take the same args except for propname vs prop, this is done so we can
2730  * avoid an extra lookup on 'prop' when its already available.
2731  *
2732  * When this kind of change won't disrupt branches, best look into making more
2733  * of our UI functions take prop rather then propname.
2734  */
2735
2736 #define UI_DEF_BUT_RNA_DISABLE(but)  { \
2737                 but->flag |= UI_BUT_DISABLED;  \
2738                 but->lock = TRUE;              \
2739                 but->lockstr = "";             \
2740         } (void)0
2741
2742
2743 static uiBut *ui_def_but_rna(uiBlock *block, int type, int retval, const char *str,
2744                                                          int x, int y, short width, short height,
2745                              PointerRNA *ptr, PropertyRNA *prop, int index,
2746                              float min, float max, float a1, float a2,  const char *tip)
2747 {
2748         const PropertyType proptype = RNA_property_type(prop);
2749         uiBut *but;
2750         int freestr = 0, icon = 0;
2751
2752         /* use rna values if parameters are not specified */
2753         if (!str) {
2754                 if (type == MENU && proptype == PROP_ENUM) {
2755                         EnumPropertyItem *item;
2756                         DynStr *dynstr;
2757                         int i, totitem, value, free;
2758
2759                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2760                         value = RNA_property_enum_get(ptr, prop);
2761
2762                         dynstr = BLI_dynstr_new();
2763                         BLI_dynstr_appendf(dynstr, "%s%%t", RNA_property_ui_name(prop));
2764                         for (i = 0; i < totitem; i++) {
2765                                 if (!item[i].identifier[0]) {
2766                                         if (item[i].name)
2767                                                 BLI_dynstr_appendf(dynstr, "|%s%%l", item[i].name);
2768                                         else
2769                                                 BLI_dynstr_append(dynstr, "|%l");
2770                                 }
2771                                 else if (item[i].icon)
2772                                         BLI_dynstr_appendf(dynstr, "|%s %%i%d %%x%d", item[i].name, item[i].icon, item[i].value);
2773                                 else
2774                                         BLI_dynstr_appendf(dynstr, "|%s %%x%d", item[i].name, item[i].value);
2775
2776                                 if (value == item[i].value)
2777                                         icon = item[i].icon;
2778                         }
2779                         str = BLI_dynstr_get_cstring(dynstr);
2780                         BLI_dynstr_free(dynstr);
2781
2782                         if (free) {
2783                                 MEM_freeN(item);
2784                         }
2785
2786                         freestr = 1;
2787                 }
2788                 else if (ELEM(type, ROW, LISTROW) && proptype == PROP_ENUM) {
2789                         EnumPropertyItem *item;
2790                         int i, totitem, free;
2791
2792                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2793                         for (i = 0; i < totitem; i++) {
2794                                 if (item[i].identifier[0] && item[i].value == (int)max) {
2795                                         str = item[i].name;
2796                                         icon = item[i].icon;
2797                                 }
2798                         }
2799
2800                         if (!str) {
2801                                 str = RNA_property_ui_name(prop);
2802                         }
2803                         if (free) {
2804                                 MEM_freeN(item);
2805                         }
2806                 }
2807                 else {
2808                         str = RNA_property_ui_name(prop);
2809                         icon = RNA_property_ui_icon(prop);
2810                 }
2811         }
2812
2813         if (!tip && proptype != PROP_ENUM)
2814                 tip = RNA_property_ui_description(prop);
2815
2816         if (min == max || a1 == -1 || a2 == -1) {
2817                 if (proptype == PROP_INT) {
2818                         int hardmin, hardmax, softmin, softmax, step;
2819
2820                         RNA_property_int_range(ptr, prop, &hardmin, &hardmax);
2821                         RNA_property_int_ui_range(ptr, prop, &softmin, &softmax, &step);
2822
2823                         if (!ELEM(type, ROW, LISTROW) && min == max) {
2824                                 min = hardmin;
2825                                 max = hardmax;
2826                         }
2827                         if (a1 == -1)
2828                                 a1 = step;
2829                         if (a2 == -1)
2830                                 a2 = 0;
2831                 }
2832                 else if (proptype == PROP_FLOAT) {
2833                         float hardmin, hardmax, softmin, softmax, step, precision;
2834
2835                         RNA_property_float_range(ptr, prop, &hardmin, &hardmax);
2836                         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2837
2838                         if (!ELEM(type, ROW, LISTROW) && min == max) {
2839                                 min = hardmin;
2840                                 max = hardmax;
2841                         }
2842                         if (a1 == -1)
2843                                 a1 = step;
2844                         if (a2 == -1)
2845                                 a2 = precision;
2846                 }
2847                 else if (proptype == PROP_STRING) {
2848                         min = 0;
2849                         max = RNA_property_string_maxlength(prop);
2850                         if (max == 0) /* interface code should ideally support unlimited length */
2851                                 max = UI_MAX_DRAW_STR;
2852                 }
2853         }
2854
2855         /* now create button */
2856         but = ui_def_but(block, type, retval, str, x, y, width, height, NULL, min, max, a1, a2, tip);
2857
2858         but->rnapoin = *ptr;
2859         but->rnaprop = prop;
2860
2861         if (RNA_property_array_length(&but->rnapoin, but->rnaprop))
2862                 but->rnaindex = index;
2863         else
2864                 but->rnaindex = 0;
2865
2866         if (icon) {
2867                 but->icon = (BIFIconID)icon;
2868                 but->flag |= UI_HAS_ICON;
2869                 but->flag |= UI_ICON_LEFT;
2870         }
2871         
2872         if (!RNA_property_editable(&but->rnapoin, prop)) {
2873                 UI_DEF_BUT_RNA_DISABLE(but);
2874         }
2875
2876         if (but->flag & UI_BUT_UNDO && (ui_but_is_rna_undo(but) == FALSE)) {
2877                 but->flag &= ~UI_BUT_UNDO;
2878         }
2879
2880         /* If this button uses units, calculate the step from this */
2881         if ((proptype == PROP_FLOAT) && ui_is_but_unit(but)) {
2882                 but->a1 = ui_get_but_step_unit(but, but->a1);
2883         }
2884
2885         if (freestr) {
2886                 MEM_freeN((void *)str);
2887         }
2888
2889         return but;
2890 }
2891
2892 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)
2893 {
2894         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2895         uiBut *but;
2896
2897         if (prop) {
2898                 but = ui_def_but_rna(block, type, retval, str, x, y, width, height, ptr, prop, index, min, max, a1, a2,  tip);
2899         }
2900         else {
2901                 but = ui_def_but(block, type, retval, propname, x, y, width, height, NULL, min, max, a1, a2, tip);
2902
2903                 UI_DEF_BUT_RNA_DISABLE(but);
2904         }
2905
2906         return but;
2907 }
2908
2909 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)
2910 {
2911         uiBut *but;
2912
2913         if (!str) {
2914                 if (ot && ot->srna)
2915                         str = RNA_struct_ui_name(ot->srna);
2916                 else
2917                         str = "";
2918         }
2919
2920         if ((!tip || tip[0] == '\0') && ot && ot->srna) {
2921                 tip = RNA_struct_ui_description(ot->srna);
2922         }
2923
2924         but = ui_def_but(block, type, -1, str, x, y, width, height, NULL, 0, 0, 0, 0, tip);
2925         but->optype = ot;
2926         but->opcontext = opcontext;
2927         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
2928
2929         if (!ot) {
2930                 but->flag |= UI_BUT_DISABLED;
2931                 but->lock = TRUE;
2932                 but->lockstr = "";
2933         }
2934
2935         return but;
2936 }
2937
2938 #if 0 /* UNUSED */
2939 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)
2940 {
2941         wmOperatorType *ot = WM_operatortype_find(opname, 0);
2942         if (str == NULL && ot == NULL) str = opname;
2943         return ui_def_but_operator_ptr(block, type, ot, opcontext, str, x, y, width, height, tip);
2944 }
2945 #endif
2946
2947 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)
2948 {
2949         uiBut *but;
2950         wmOperatorType *ot;
2951         
2952         ot = WM_operatortype_find(opname, 0);
2953
2954         if (!str) {
2955                 if (ot) str = ot->name;
2956                 else str = opname;
2957         }
2958         
2959         if ((!tip || tip[0] == '\0') && ot && ot->description) {
2960                 tip = ot->description;
2961         }
2962
2963         but = ui_def_but(block, type, -1, str, x, y, width, height, poin, min, max, a1, a2, tip);
2964         but->optype = ot;
2965         but->opcontext = opcontext;
2966         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
2967
2968         if (!ot) {
2969                 but->flag |= UI_BUT_DISABLED;
2970                 but->lock = TRUE;
2971                 but->lockstr = "";
2972         }
2973
2974         return but;
2975 }
2976
2977 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)
2978 {
2979         uiBut *but = ui_def_but(block, type, retval, str, x, y, width, height, poin, min, max, a1, a2, tip);
2980
2981         ui_check_but(but);
2982         
2983         return but;
2984 }
2985
2986 /* if _x_ is a power of two (only one bit) return the power,
2987  * otherwise return -1.
2988  * (1<<findBitIndex(x))==x for powers of two.
2989  */
2990 static int findBitIndex(unsigned int x)
2991 {
2992         if (!x || !is_power_of_2_i(x)) { /* is_power_of_2_i(x) strips lowest bit */
2993                 return -1;
2994         }
2995         else {
2996                 int idx = 0;
2997
2998                 if (x & 0xFFFF0000) idx += 16, x >>= 16;
2999                 if (x & 0xFF00) idx += 8, x >>= 8;
3000                 if (x & 0xF0) idx += 4, x >>= 4;
3001                 if (x & 0xC) idx += 2, x >>= 2;
3002                 if (x & 0x2) idx += 1;
3003
3004                 return idx;
3005         }
3006 }
3007
3008 /* autocomplete helper functions */
3009 struct AutoComplete {
3010         size_t maxlen;
3011         char *truncate;
3012         const char *startname;
3013 };
3014
3015 AutoComplete *autocomplete_begin(const char *startname, size_t maxlen)
3016 {
3017         AutoComplete *autocpl;
3018         
3019         autocpl = MEM_callocN(sizeof(AutoComplete), "AutoComplete");
3020         autocpl->maxlen = maxlen;
3021         autocpl->truncate = MEM_callocN(sizeof(char) * maxlen, "AutoCompleteTruncate");
3022         autocpl->startname = startname;
3023
3024         return autocpl;
3025 }
3026
3027 void autocomplete_do_name(AutoComplete *autocpl, const char *name)
3028 {
3029         char *truncate = autocpl->truncate;
3030         const char *startname = autocpl->startname;
3031         int a;
3032
3033         for (a = 0; a < autocpl->maxlen - 1; a++) {
3034                 if (startname[a] == 0 || startname[a] != name[a])
3035                         break;
3036         }
3037         /* found a match */
3038         if (startname[a] == 0) {
3039                 /* first match */
3040                 if (truncate[0] == 0)
3041                         BLI_strncpy(truncate, name, autocpl->maxlen);
3042                 else {
3043                         /* remove from truncate what is not in bone->name */
3044                         for (a = 0; a < autocpl->maxlen - 1; a++) {
3045                                 if (name[a] == 0) {
3046                                         truncate[a] = 0;
3047                                         break;
3048                                 }
3049                                 else if (truncate[a] != name[a])
3050                                         truncate[a] = 0;
3051                         }
3052                 }
3053         }
3054 }
3055
3056 void autocomplete_end(AutoComplete *autocpl, char *autoname)
3057 {       
3058         if (autocpl->truncate[0])
3059                 BLI_strncpy(autoname, autocpl->truncate, autocpl->maxlen);
3060         else {
3061                 if (autoname != autocpl->startname) /* don't copy a string over its self */
3062                         BLI_strncpy(autoname, autocpl->startname, autocpl->maxlen);
3063         }
3064         MEM_freeN(autocpl->truncate);
3065         MEM_freeN(autocpl);
3066 }
3067
3068 /* autocomplete callback for ID buttons */
3069 static void autocomplete_id(bContext *C, char *str, void *arg_v)
3070 {
3071         int blocktype = (intptr_t)arg_v;
3072         ListBase *listb = which_libbase(CTX_data_main(C), blocktype);
3073         
3074         if (listb == NULL) return;
3075         
3076         /* search if str matches the beginning of an ID struct */
3077         if (str[0]) {
3078                 AutoComplete *autocpl = autocomplete_begin(str, MAX_ID_NAME - 2);
3079                 ID *id;
3080                 
3081                 for (id = listb->first; id; id = id->next)
3082                         autocomplete_do_name(autocpl, id->name + 2);
3083
3084                 autocomplete_end(autocpl, str);
3085         }