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