style cleanup: mainly for mesh code, also some WM function use.
[blender.git] / source / blender / editors / interface / interface_regions.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) 2008 Blender Foundation.
19  * All rights reserved.
20  * 
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface_regions.c
27  *  \ingroup edinterface
28  */
29
30
31
32 #include <stdarg.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <assert.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_userdef_types.h"
40
41 #include "BLI_math.h"
42 #include "BLI_blenlib.h"
43 #include "BLI_utildefines.h"
44 #include "BLI_dynstr.h"
45 #include "BLI_ghash.h"
46
47 #include "BKE_context.h"
48 #include "BKE_screen.h"
49
50 #include "WM_api.h"
51 #include "WM_types.h"
52 #include "wm_draw.h"
53 #include "wm_subwindow.h"
54 #include "wm_window.h"
55
56 #include "RNA_access.h"
57
58 #include "BIF_gl.h"
59
60 #include "UI_interface.h"
61 #include "UI_interface_icons.h"
62 #include "UI_view2d.h"
63
64 #include "BLF_api.h"
65 #include "BLF_translation.h"
66
67 #include "ED_screen.h"
68
69 #include "interface_intern.h"
70
71 #define MENU_SEPR_HEIGHT        6
72 #define B_NOP                   -1
73 #define MENU_SHADOW_SIDE        8
74 #define MENU_SHADOW_BOTTOM      10
75 #define MENU_TOP                        8
76
77 /*********************** Menu Data Parsing ********************* */
78
79 typedef struct MenuEntry {
80         const char *str;
81         int retval;
82         int icon;
83         int sepr;
84 } MenuEntry;
85
86 typedef struct MenuData {
87         const char *instr;
88         const char *title;
89         int titleicon;
90         
91         MenuEntry *items;
92         int nitems, itemssize;
93 } MenuData;
94
95 static MenuData *menudata_new(const char *instr)
96 {
97         MenuData *md= MEM_mallocN(sizeof(*md), "MenuData");
98
99         md->instr= instr;
100         md->title= NULL;
101         md->titleicon= 0;
102         md->items= NULL;
103         md->nitems= md->itemssize= 0;
104         
105         return md;
106 }
107
108 static void menudata_set_title(MenuData *md, const char *title, int titleicon)
109 {
110         if (!md->title)
111                 md->title= title;
112         if (!md->titleicon)
113                 md->titleicon= titleicon;
114 }
115
116 static void menudata_add_item(MenuData *md, const char *str, int retval, int icon, int sepr)
117 {
118         if (md->nitems==md->itemssize) {
119                 int nsize= md->itemssize?(md->itemssize<<1):1;
120                 MenuEntry *oitems= md->items;
121                 
122                 md->items= MEM_mallocN(nsize*sizeof(*md->items), "md->items");
123                 if (oitems) {
124                         memcpy(md->items, oitems, md->nitems*sizeof(*md->items));
125                         MEM_freeN(oitems);
126                 }
127                 
128                 md->itemssize= nsize;
129         }
130         
131         md->items[md->nitems].str= str;
132         md->items[md->nitems].retval= retval;
133         md->items[md->nitems].icon= icon;
134         md->items[md->nitems].sepr= sepr;
135         md->nitems++;
136 }
137
138 static void menudata_free(MenuData *md)
139 {
140         MEM_freeN((void *)md->instr);
141         if (md->items) {
142                 MEM_freeN(md->items);
143         }
144         MEM_freeN(md);
145 }
146
147         /**
148          * Parse menu description strings, string is of the
149          * form "[sss%t|]{(sss[%xNN]|), (%l|), (sss%l|)}", ssss%t indicates the
150          * menu title, sss or sss%xNN indicates an option, 
151          * if %xNN is given then NN is the return value if
152          * that option is selected otherwise the return value
153          * is the index of the option (starting with 1). %l
154          * indicates a seperator, sss%l indicates a label and
155          * new column.
156          * 
157          * \param str String to be parsed.
158          * \retval new menudata structure, free with menudata_free()
159          */
160 static MenuData *decompose_menu_string(const char *str)
161 {
162         char *instr= BLI_strdup(str);
163         MenuData *md= menudata_new(instr);
164         const char *nitem= NULL;
165         char *s= instr;
166         int nicon=0, nretval= 1, nitem_is_title= 0, nitem_is_sepr= 0;
167         
168         while (1) {
169                 char c= *s;
170
171                 if (c=='%') {
172                         if (s[1]=='x') {
173                                 nretval= atoi(s+2);
174
175                                 *s= '\0';
176                                 s++;
177                         } else if (s[1]=='t') {
178                                 nitem_is_title= (s != instr); /* check for empty title */
179
180                                 *s= '\0';
181                                 s++;
182                         } else if (s[1]=='l') {
183                                 nitem_is_sepr= 1;
184                                 if(!nitem) nitem= "";
185
186                                 *s= '\0';
187                                 s++;
188                         } else if (s[1]=='i') {
189                                 nicon= atoi(s+2);
190                                 
191                                 *s= '\0';
192                                 s++;
193                         }
194                 } else if (c=='|' || c == '\n' || c=='\0') {
195                         if (nitem) {
196                                 *s= '\0';
197
198                                 if(nitem_is_title) {
199                                         menudata_set_title(md, nitem, nicon);
200                                         nitem_is_title= 0;
201                                 }
202                                 else if(nitem_is_sepr) {
203                                         /* prevent separator to get a value */
204                                         menudata_add_item(md, nitem, -1, nicon, 1);
205                                         nretval= md->nitems+1;
206                                         nitem_is_sepr= 0;
207                                 }
208                                 else {
209                                         menudata_add_item(md, nitem, nretval, nicon, 0);
210                                         nretval= md->nitems+1;
211                                 } 
212                                 
213                                 nitem= NULL;
214                                 nicon= 0;
215                         }
216                         
217                         if (c=='\0') {
218                                 break;
219                         }
220                 } else if (!nitem) {
221                         nitem= s;
222                 }
223
224                 s++;
225         }
226         
227         return md;
228 }
229
230 void ui_set_name_menu(uiBut *but, int value)
231 {
232         MenuData *md;
233         int i;
234         
235         md= decompose_menu_string(but->str);
236         for (i=0; i<md->nitems; i++) {
237                 if (md->items[i].retval==value) {
238                         BLI_strncpy(but->drawstr, md->items[i].str, sizeof(but->drawstr));
239                         break;
240                 }
241         }
242         
243         menudata_free(md);
244 }
245
246 int ui_step_name_menu(uiBut *but, int step)
247 {
248         MenuData *md;
249         int value= ui_get_but_val(but);
250         int i;
251         
252         md= decompose_menu_string(but->str);
253         for (i=0; i<md->nitems; i++)
254                 if (md->items[i].retval==value)
255                         break;
256         
257         if(step==1) {
258                 /* skip separators */
259                 for(; i<md->nitems-1; i++) {
260                         if(md->items[i+1].retval != -1) {
261                                 value= md->items[i+1].retval;
262                                 break;
263                         }
264                 }
265         }
266         else {
267                 if(i>0) {
268                         /* skip separators */
269                         for(; i>0; i--) {
270                                 if(md->items[i-1].retval != -1) {
271                                         value= md->items[i-1].retval;
272                                         break;
273                                 }
274                         }
275                 }
276         }
277         
278         menudata_free(md);
279                 
280         return value;
281 }
282
283
284 /******************** Creating Temporary regions ******************/
285
286 static ARegion *ui_add_temporary_region(bScreen *sc)
287 {
288         ARegion *ar;
289
290         ar= MEM_callocN(sizeof(ARegion), "area region");
291         BLI_addtail(&sc->regionbase, ar);
292
293         ar->regiontype= RGN_TYPE_TEMPORARY;
294         ar->alignment= RGN_ALIGN_FLOAT;
295
296         return ar;
297 }
298
299 static void ui_remove_temporary_region(bContext *C, bScreen *sc, ARegion *ar)
300 {
301         if(CTX_wm_window(C))
302                 wm_draw_region_clear(CTX_wm_window(C), ar);
303
304         ED_region_exit(C, ar);
305         BKE_area_region_free(NULL, ar);         /* NULL: no spacetype */
306         BLI_freelinkN(&sc->regionbase, ar);
307 }
308
309 /************************* Creating Tooltips **********************/
310
311 typedef enum {
312         UI_TIP_LC_MAIN,
313         UI_TIP_LC_NORMAL,
314         UI_TIP_LC_PYTHON,
315         UI_TIP_LC_ALERT,
316         UI_TIP_LC_SUBMENU
317 } uiTooltipLineColor;
318 #define UI_TIP_LC_MAX 5
319
320 #define MAX_TOOLTIP_LINES 8
321 typedef struct uiTooltipData {
322         rcti bbox;
323         uiFontStyle fstyle;
324         char lines[MAX_TOOLTIP_LINES][512];
325         uiTooltipLineColor color_id[MAX_TOOLTIP_LINES];
326         int totline;
327         int toth, spaceh, lineh;
328 } uiTooltipData;
329
330 static void rgb_tint(float col[3],
331                      float h, float h_strength,
332                      float v, float v_strength)
333 {
334         float col_hsv_from[3];
335         float col_hsv_to[3];
336
337         rgb_to_hsv(col[0], col[1], col[2],    col_hsv_from + 0, col_hsv_from + 1, col_hsv_from + 2);
338
339         col_hsv_to[0] = h;
340         col_hsv_to[1] = h_strength;
341         col_hsv_to[2] = (col_hsv_from[2] * (1.0f - v_strength)) + (v * v_strength);
342
343         hsv_to_rgb(col_hsv_to[0], col_hsv_to[1], col_hsv_to[2], col + 0, col + 1, col + 2);
344 }
345
346 static void ui_tooltip_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
347 {
348         uiTooltipData *data= ar->regiondata;
349         uiWidgetColors* theme = ui_tooltip_get_theme();
350         rcti bbox= data->bbox;
351         float tip_colors[UI_TIP_LC_MAX][3];
352
353         float *main_color    = tip_colors[UI_TIP_LC_MAIN]; /* the color from the theme */
354         float *normal_color  = tip_colors[UI_TIP_LC_NORMAL];
355         float *python_color  = tip_colors[UI_TIP_LC_PYTHON];
356         float *alert_color   = tip_colors[UI_TIP_LC_ALERT];
357         float *submenu_color = tip_colors[UI_TIP_LC_SUBMENU];
358
359         float background_color[3];
360         float tone_bg;
361         int i;
362
363         /* draw background */
364         ui_draw_tooltip_background(UI_GetStyle(), NULL, &bbox);
365
366         /* set background_color */
367         rgb_uchar_to_float(background_color, (const unsigned char *)theme->inner);
368
369         /* calculate normal_color */
370         rgb_uchar_to_float(main_color, (const unsigned char *)theme->text);
371         copy_v3_v3(normal_color, main_color);
372         copy_v3_v3(python_color, main_color);
373         copy_v3_v3(alert_color, main_color);
374         copy_v3_v3(submenu_color, main_color);
375
376         /* find the brightness difference between background and text colors */
377         
378         tone_bg = rgb_to_grayscale(background_color);
379         /* tone_fg = rgb_to_grayscale(main_color); */
380
381         rgb_tint(normal_color, 0.0f, 0.0f, tone_bg, 0.3f);   /* a shade darker (to bg) */
382         rgb_tint(python_color, 0.666f, 0.25f, tone_bg, 0.3f); /* blue */
383         rgb_tint(alert_color, 0.0f, 0.8f, tone_bg, 0.1f);    /* bright red */
384         rgb_tint(submenu_color, 0.0f, 0.0f, tone_bg, 0.3f);  /* a shade darker (to bg) */
385
386         /* draw text */
387         uiStyleFontSet(&data->fstyle);
388
389         bbox.ymax = bbox.ymax - 0.5f*((bbox.ymax - bbox.ymin) - data->toth);
390         bbox.ymin = bbox.ymax - data->lineh;
391
392         for (i = 0; i < data->totline; i++) {
393                 glColor3fv(tip_colors[data->color_id[i]]);
394                 uiStyleFontDraw(&data->fstyle, &bbox, data->lines[i]);
395                 bbox.ymin -= data->lineh + data->spaceh;
396                 bbox.ymax -= data->lineh + data->spaceh;
397         }
398 }
399
400 static void ui_tooltip_region_free_cb(ARegion *ar)
401 {
402         uiTooltipData *data;
403
404         data= ar->regiondata;
405         MEM_freeN(data);
406         ar->regiondata= NULL;
407 }
408
409 ARegion *ui_tooltip_create(bContext *C, ARegion *butregion, uiBut *but)
410 {
411         uiStyle *style= UI_GetStyle();
412         static ARegionType type;
413         ARegion *ar;
414         uiTooltipData *data;
415         IDProperty *prop;
416         char buf[512];
417         float fonth, fontw, aspect= but->block->aspect;
418         float x1f, x2f, y1f, y2f;
419         int x1, x2, y1, y2, winx, winy, ofsx, ofsy, w, h, a;
420
421         if(but->flag & UI_BUT_NO_TOOLTIP)
422                 return NULL;
423
424         /* create tooltip data */
425         data= MEM_callocN(sizeof(uiTooltipData), "uiTooltipData");
426
427         /* special case, enum rna buttons only have enum item description, use general enum description too before the specific one */
428         if(but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM) {
429                 const char *descr= RNA_property_description(but->rnaprop);
430                 if(descr && descr[0]) {
431                         BLI_strncpy(data->lines[data->totline], descr, sizeof(data->lines[0]));
432                         data->color_id[data->totline] = UI_TIP_LC_MAIN;
433                         data->totline++;
434                 }
435
436                 if(ELEM(but->type, ROW, MENU)) {
437                         EnumPropertyItem *item;
438                         int i, totitem, free;
439                         int value = (but->type == ROW)? but->hardmax: ui_get_but_val(but);
440
441                         RNA_property_enum_items_gettexted(C, &but->rnapoin, but->rnaprop, &item, &totitem, &free);
442
443                         for(i=0; i<totitem; i++) {
444                                 if(item[i].identifier[0] && item[i].value == value) {
445                                         if(item[i].description && item[i].description[0]) {
446                                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), "%s: %s", item[i].name, item[i].description);
447                         data->color_id[data->totline] = UI_TIP_LC_SUBMENU;
448                                                 data->totline++;
449                                         }
450                                         break;
451                                 }
452                         }
453
454                         if (free) {
455                                 MEM_freeN(item);
456                         }
457                 }
458         }
459         
460         if(but->tip && but->tip[0] != '\0') {
461                 BLI_strncpy(data->lines[data->totline], but->tip, sizeof(data->lines[0]));
462                 data->color_id[data->totline] = UI_TIP_LC_MAIN;
463                 data->totline++;
464         }
465
466         if(but->optype && !(but->block->flag & UI_BLOCK_LOOP)) {
467                 /* operator keymap (not menus, they already have it) */
468                 prop= (but->opptr)? but->opptr->data: NULL;
469
470                 if(WM_key_event_operator_string(C, but->optype->idname, but->opcontext, prop, TRUE,
471                                                 buf, sizeof(buf)))
472                 {
473                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Shortcut: %s"), buf);
474                         data->color_id[data->totline] = UI_TIP_LC_NORMAL;
475                         data->totline++;
476                 }
477         }
478
479         if(ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
480                 /* full string */
481                 ui_get_but_string(but, buf, sizeof(buf));
482                 if(buf[0]) {
483                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Value: %s"), buf);
484                         data->color_id[data->totline] = UI_TIP_LC_NORMAL;
485                         data->totline++;
486                 }
487         }
488
489         if(but->rnaprop) {
490                 int unit_type= uiButGetUnitType(but);
491                 
492                 if (unit_type == PROP_UNIT_ROTATION) {
493                         if (RNA_property_type(but->rnaprop) == PROP_FLOAT) {
494                                 float value= RNA_property_array_check(but->rnaprop) ? RNA_property_float_get_index(&but->rnapoin, but->rnaprop, but->rnaindex) : RNA_property_float_get(&but->rnapoin, but->rnaprop);
495                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Radians: %f"), value);
496                                 data->color_id[data->totline] = UI_TIP_LC_NORMAL;
497                                 data->totline++;
498                         }
499                 }
500                 
501                 if(but->flag & UI_BUT_DRIVEN) {
502                         if(ui_but_anim_expression_get(but, buf, sizeof(buf))) {
503                                 /* expression */
504                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Expression: %s"), buf);
505                                 data->color_id[data->totline] = UI_TIP_LC_NORMAL;
506                                 data->totline++;
507                         }
508                 }
509
510                 /* rna info */
511                 if ((U.flag & USER_TOOLTIPS_PYTHON) == 0) {
512                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Python: %s.%s"), RNA_struct_identifier(but->rnapoin.type), RNA_property_identifier(but->rnaprop));
513                         data->color_id[data->totline] = UI_TIP_LC_PYTHON;
514                         data->totline++;
515                 }
516                 
517                 if(but->rnapoin.id.data) {
518                         ID *id= but->rnapoin.id.data;
519                         if(id->lib && id->lib->name) {
520                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Library: %s"), id->lib->name);
521                                 data->color_id[data->totline] = UI_TIP_LC_NORMAL;
522                                 data->totline++;
523                         }
524                 }
525         }
526         else if (but->optype) {
527                 PointerRNA *opptr;
528                 char *str;
529                 opptr= uiButGetOperatorPtrRNA(but); /* allocated when needed, the button owns it */
530
531                 str= WM_operator_pystring(C, but->optype, opptr, 0);
532
533                 /* operator info */
534                 if ((U.flag & USER_TOOLTIPS_PYTHON) == 0) {
535                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Python: %s"), str);
536                         data->color_id[data->totline] = UI_TIP_LC_PYTHON;
537                         data->totline++;
538                 }
539
540                 MEM_freeN(str);
541
542                 /* second check if we are disabled - why */
543                 if(but->flag & UI_BUT_DISABLED) {
544                         const char *poll_msg;
545                         CTX_wm_operator_poll_msg_set(C, NULL);
546                         WM_operator_poll_context(C, but->optype, but->opcontext);
547                         poll_msg= CTX_wm_operator_poll_msg_get(C);
548                         if(poll_msg) {
549                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Disabled: %s"), poll_msg);
550                                 data->color_id[data->totline] = UI_TIP_LC_ALERT; /* alert */
551                                 data->totline++;                        
552                         }
553                 }
554         }
555         else if (ELEM(but->type, MENU, PULLDOWN)) {
556                 if ((U.flag & USER_TOOLTIPS_PYTHON) == 0) {
557                         MenuType *mt= uiButGetMenuType(but);
558                         if (mt) {
559                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Python: %s"), mt->idname);
560                                 data->color_id[data->totline] = UI_TIP_LC_PYTHON;
561                                 data->totline++;
562                         }
563                 }
564
565         }
566
567         assert(data->totline < MAX_TOOLTIP_LINES);
568         
569         if(data->totline == 0) {
570                 MEM_freeN(data);
571                 return NULL;
572         }
573
574         /* create area region */
575         ar= ui_add_temporary_region(CTX_wm_screen(C));
576
577         memset(&type, 0, sizeof(ARegionType));
578         type.draw= ui_tooltip_region_draw_cb;
579         type.free= ui_tooltip_region_free_cb;
580         ar->type= &type;
581         
582         /* set font, get bb */
583         data->fstyle= style->widget; /* copy struct */
584         data->fstyle.align= UI_STYLE_TEXT_CENTER;
585         uiStyleFontSet(&data->fstyle);
586
587         /* these defines may need to be tweaked depending on font */
588 #define TIP_MARGIN_Y 2
589 #define TIP_BORDER_X 16.0f
590 #define TIP_BORDER_Y 6.0f
591
592         h= BLF_height_max(data->fstyle.uifont_id);
593
594         for(a=0, fontw=0, fonth=0; a<data->totline; a++) {
595                 w= BLF_width(data->fstyle.uifont_id, data->lines[a]);
596                 fontw= MAX2(fontw, w);
597                 fonth += (a == 0)? h: h+TIP_MARGIN_Y;
598         }
599
600         fontw *= aspect;
601
602         ar->regiondata= data;
603
604         data->toth= fonth;
605         data->lineh= h;
606         data->spaceh= TIP_MARGIN_Y;
607
608
609         /* compute position */
610         ofsx= (but->block->panel)? but->block->panel->ofsx: 0;
611         ofsy= (but->block->panel)? but->block->panel->ofsy: 0;
612
613         x1f= (but->x1 + but->x2) * 0.5f + ofsx - (TIP_BORDER_X * aspect);
614         x2f= x1f + fontw + (TIP_BORDER_X * aspect);
615         y2f= but->y1 + ofsy - (TIP_BORDER_Y * aspect);
616         y1f= y2f - fonth*aspect - (TIP_BORDER_Y * aspect);
617         
618 #undef TIP_MARGIN_Y
619 #undef TIP_BORDER_X
620 #undef TIP_BORDER_Y
621
622         /* copy to int, gets projected if possible too */
623         x1= x1f; y1= y1f; x2= x2f; y2= y2f; 
624         
625         if(butregion) {
626                 /* XXX temp, region v2ds can be empty still */
627                 if(butregion->v2d.cur.xmin != butregion->v2d.cur.xmax) {
628                         UI_view2d_to_region_no_clip(&butregion->v2d, x1f, y1f, &x1, &y1);
629                         UI_view2d_to_region_no_clip(&butregion->v2d, x2f, y2f, &x2, &y2);
630                 }
631
632                 x1 += butregion->winrct.xmin;
633                 x2 += butregion->winrct.xmin;
634                 y1 += butregion->winrct.ymin;
635                 y2 += butregion->winrct.ymin;
636         }
637
638         wm_window_get_size(CTX_wm_window(C), &winx, &winy);
639
640         if(x2 > winx) {
641                 /* super size */
642                 if(x2 > winx + x1) {
643                         x2= winx;
644                         x1= 0;
645                 }
646                 else {
647                         x1 -= x2-winx;
648                         x2= winx;
649                 }
650         }
651         /* ensure at least 5 px above screen bounds
652          * 25 is just a guess to be above the menu item */
653         if(y1 < 5) {
654                 y2 += (-y1) + 30;
655                 y1 = 30;
656         }
657
658         /* widget rect, in region coords */
659         data->bbox.xmin = MENU_SHADOW_SIDE;
660         data->bbox.xmax = x2-x1 + MENU_SHADOW_SIDE;
661         data->bbox.ymin = MENU_SHADOW_BOTTOM;
662         data->bbox.ymax = y2-y1 + MENU_SHADOW_BOTTOM;
663         
664         /* region bigger for shadow */
665         ar->winrct.xmin = x1 - MENU_SHADOW_SIDE;
666         ar->winrct.xmax = x2 + MENU_SHADOW_SIDE;
667         ar->winrct.ymin = y1 - MENU_SHADOW_BOTTOM;
668         ar->winrct.ymax = y2 + MENU_TOP;
669
670         /* adds subwindow */
671         ED_region_init(C, ar);
672         
673         /* notify change and redraw */
674         ED_region_tag_redraw(ar);
675
676         return ar;
677 }
678
679 void ui_tooltip_free(bContext *C, ARegion *ar)
680 {
681         ui_remove_temporary_region(C, CTX_wm_screen(C), ar);
682 }
683
684
685 /************************* Creating Search Box **********************/
686
687 struct uiSearchItems {
688         int maxitem, totitem, maxstrlen;
689         
690         int offset, offset_i; /* offset for inserting in array */
691         int more;  /* flag indicating there are more items */
692         
693         char **names;
694         void **pointers;
695         int *icons;
696
697         AutoComplete *autocpl;
698         void *active;
699 };
700
701 typedef struct uiSearchboxData {
702         rcti bbox;
703         uiFontStyle fstyle;
704         uiSearchItems items;
705         int active;             /* index in items array */
706         int noback;             /* when menu opened with enough space for this */
707         int preview;    /* draw thumbnail previews, rather than list */
708         int prv_rows, prv_cols;
709 } uiSearchboxData;
710
711 #define SEARCH_ITEMS    10
712
713 /* exported for use by search callbacks */
714 /* returns zero if nothing to add */
715 int uiSearchItemAdd(uiSearchItems *items, const char *name, void *poin, int iconid)
716 {
717         /* hijack for autocomplete */
718         if(items->autocpl) {
719                 autocomplete_do_name(items->autocpl, name);
720                 return 1;
721         }
722         
723         /* hijack for finding active item */
724         if(items->active) {
725                 if(poin==items->active)
726                         items->offset_i= items->totitem;
727                 items->totitem++;
728                 return 1;
729         }
730         
731         if(items->totitem>=items->maxitem) {
732                 items->more= 1;
733                 return 0;
734         }
735         
736         /* skip first items in list */
737         if(items->offset_i > 0) {
738                 items->offset_i--;
739                 return 1;
740         }
741         
742         if(items->names)
743                 BLI_strncpy(items->names[items->totitem], name, items->maxstrlen);
744         if(items->pointers)
745                 items->pointers[items->totitem]= poin;
746         if(items->icons)
747                 items->icons[items->totitem]= iconid;
748         
749         items->totitem++;
750         
751         return 1;
752 }
753
754 int uiSearchBoxhHeight(void)
755 {
756         return SEARCH_ITEMS*UI_UNIT_Y + 2*MENU_TOP;
757 }
758
759 /* ar is the search box itself */
760 static void ui_searchbox_select(bContext *C, ARegion *ar, uiBut *but, int step)
761 {
762         uiSearchboxData *data= ar->regiondata;
763         
764         /* apply step */
765         data->active+= step;
766         
767         if(data->items.totitem==0)
768                 data->active= 0;
769         else if(data->active > data->items.totitem) {
770                 if(data->items.more) {
771                         data->items.offset++;
772                         data->active= data->items.totitem;
773                         ui_searchbox_update(C, ar, but, 0);
774                 }
775                 else
776                         data->active= data->items.totitem;
777         }
778         else if(data->active < 1) {
779                 if(data->items.offset) {
780                         data->items.offset--;
781                         data->active= 1;
782                         ui_searchbox_update(C, ar, but, 0);
783                 }
784                 else if(data->active < 0)
785                         data->active= 0;
786         }
787         
788         ED_region_tag_redraw(ar);
789 }
790
791 static void ui_searchbox_butrect(rcti *rect, uiSearchboxData *data, int itemnr)
792 {
793         /* thumbnail preview */
794         if (data->preview) {
795                 int buth = (data->bbox.ymax - data->bbox.ymin - 2*MENU_TOP) / data->prv_rows;
796                 int butw = (data->bbox.xmax - data->bbox.xmin) / data->prv_cols;
797                 int row, col;
798                 
799                 *rect= data->bbox;
800                 
801                 col = itemnr % data->prv_cols;
802                 row = itemnr / data->prv_cols;
803                 
804                 rect->xmin += col * butw;
805                 rect->xmax = rect->xmin + butw;
806                 
807                 rect->ymax = data->bbox.ymax - MENU_TOP - (row * buth);
808                 rect->ymin = rect->ymax - buth;
809         }
810         /* list view */
811         else {
812                 int buth= (data->bbox.ymax-data->bbox.ymin - 2*MENU_TOP)/SEARCH_ITEMS;
813                 
814                 *rect= data->bbox;
815                 rect->xmin = data->bbox.xmin + 3.0f;
816                 rect->xmax = data->bbox.xmax - 3.0f;
817                 
818                 rect->ymax = data->bbox.ymax - MENU_TOP - itemnr*buth;
819                 rect->ymin = rect->ymax - buth;
820         }
821         
822 }
823
824 /* x and y in screencoords */
825 int ui_searchbox_inside(ARegion *ar, int x, int y)
826 {
827         uiSearchboxData *data= ar->regiondata;
828         
829         return(BLI_in_rcti(&data->bbox, x-ar->winrct.xmin, y-ar->winrct.ymin));
830 }
831
832 /* string validated to be of correct length (but->hardmax) */
833 void ui_searchbox_apply(uiBut *but, ARegion *ar)
834 {
835         uiSearchboxData *data= ar->regiondata;
836
837         but->func_arg2= NULL;
838         
839         if(data->active) {
840                 char *name= data->items.names[data->active-1];
841                 char *cpoin= strchr(name, '|');
842                 
843                 if(cpoin) cpoin[0]= 0;
844                 BLI_strncpy(but->editstr, name, data->items.maxstrlen);
845                 if(cpoin) cpoin[0]= '|';
846                 
847                 but->func_arg2= data->items.pointers[data->active-1];
848         }
849 }
850
851 void ui_searchbox_event(bContext *C, ARegion *ar, uiBut *but, wmEvent *event)
852 {
853         uiSearchboxData *data= ar->regiondata;
854         
855         switch(event->type) {
856                 case WHEELUPMOUSE:
857                 case UPARROWKEY:
858                         ui_searchbox_select(C, ar, but, -1);
859                         break;
860                 case WHEELDOWNMOUSE:
861                 case DOWNARROWKEY:
862                         ui_searchbox_select(C, ar, but, 1);
863                         break;
864                 case MOUSEMOVE:
865                         if(BLI_in_rcti(&ar->winrct, event->x, event->y)) {
866                                 rcti rect;
867                                 int a;
868                                 
869                                 for(a=0; a<data->items.totitem; a++) {
870                                         ui_searchbox_butrect(&rect, data, a);
871                                         if(BLI_in_rcti(&rect, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin)) {
872                                                 if( data->active!= a+1) {
873                                                         data->active= a+1;
874                                                         ui_searchbox_select(C, ar, but, 0);
875                                                         break;
876                                                 }
877                                         }
878                                 }
879                         }
880                         break;
881         }
882 }
883
884 /* ar is the search box itself */
885 void ui_searchbox_update(bContext *C, ARegion *ar, uiBut *but, int reset)
886 {
887         uiSearchboxData *data= ar->regiondata;
888         
889         /* reset vars */
890         data->items.totitem= 0;
891         data->items.more= 0;
892         if(reset==0) {
893                 data->items.offset_i= data->items.offset;
894         }
895         else {
896                 data->items.offset_i= data->items.offset= 0;
897                 data->active= 0;
898                 
899                 /* handle active */
900                 if(but->search_func && but->func_arg2) {
901                         data->items.active= but->func_arg2;
902                         but->search_func(C, but->search_arg, but->editstr, &data->items);
903                         data->items.active= NULL;
904                         
905                         /* found active item, calculate real offset by centering it */
906                         if(data->items.totitem) {
907                                 /* first case, begin of list */
908                                 if(data->items.offset_i < data->items.maxitem) {
909                                         data->active= data->items.offset_i+1;
910                                         data->items.offset_i= 0;
911                                 }
912                                 else {
913                                         /* second case, end of list */
914                                         if(data->items.totitem - data->items.offset_i <= data->items.maxitem) {
915                                                 data->active= 1 + data->items.offset_i - data->items.totitem + data->items.maxitem;
916                                                 data->items.offset_i= data->items.totitem - data->items.maxitem;
917                                         }
918                                         else {
919                                                 /* center active item */
920                                                 data->items.offset_i -= data->items.maxitem/2;
921                                                 data->active= 1 + data->items.maxitem/2;
922                                         }
923                                 }
924                         }
925                         data->items.offset= data->items.offset_i;
926                         data->items.totitem= 0;
927                 }
928         }
929         
930         /* callback */
931         if(but->search_func)
932                 but->search_func(C, but->search_arg, but->editstr, &data->items);
933         
934         /* handle case where editstr is equal to one of items */
935         if(reset && data->active==0) {
936                 int a;
937                 
938                 for(a=0; a<data->items.totitem; a++) {
939                         char *cpoin= strchr(data->items.names[a], '|');
940                         
941                         if(cpoin) cpoin[0]= 0;
942                         if(0==strcmp(but->editstr, data->items.names[a]))
943                                 data->active= a+1;
944                         if(cpoin) cpoin[0]= '|';
945                 }
946                 if(data->items.totitem==1 && but->editstr[0])
947                         data->active= 1;
948         }
949
950         /* validate selected item */
951         ui_searchbox_select(C, ar, but, 0);
952         
953         ED_region_tag_redraw(ar);
954 }
955
956 void ui_searchbox_autocomplete(bContext *C, ARegion *ar, uiBut *but, char *str)
957 {
958         uiSearchboxData *data= ar->regiondata;
959
960         if(str[0]) {
961                 data->items.autocpl= autocomplete_begin(str, ui_get_but_string_max_length(but));
962
963                 but->search_func(C, but->search_arg, but->editstr, &data->items);
964
965                 autocomplete_end(data->items.autocpl, str);
966                 data->items.autocpl= NULL;
967         }
968 }
969
970 static void ui_searchbox_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
971 {
972         uiSearchboxData *data= ar->regiondata;
973         
974         /* pixel space */
975         wmOrtho2(-0.01f, ar->winx-0.01f, -0.01f, ar->winy-0.01f);
976
977         if(!data->noback)
978                 ui_draw_search_back(NULL, NULL, &data->bbox); /* style not used yet */
979         
980         /* draw text */
981         if(data->items.totitem) {
982                 rcti rect;
983                 int a;
984                 
985                 if (data->preview) {
986                         /* draw items */
987                         for(a=0; a<data->items.totitem; a++) {
988                                 ui_searchbox_butrect(&rect, data, a);
989                                 
990                                 /* widget itself */
991                                 if (data->preview)
992                                         ui_draw_preview_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a], (a+1)==data->active?UI_ACTIVE:0);
993                                 else 
994                                         ui_draw_menu_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a], (a+1)==data->active?UI_ACTIVE:0);
995                         }
996                         
997                         /* indicate more */
998                         if(data->items.more) {
999                                 ui_searchbox_butrect(&rect, data, data->items.maxitem-1);
1000                                 glEnable(GL_BLEND);
1001                                 UI_icon_draw(rect.xmax-18, rect.ymin-7, ICON_TRIA_DOWN);
1002                                 glDisable(GL_BLEND);
1003                         }
1004                         if(data->items.offset) {
1005                                 ui_searchbox_butrect(&rect, data, 0);
1006                                 glEnable(GL_BLEND);
1007                                 UI_icon_draw(rect.xmin, rect.ymax-9, ICON_TRIA_UP);
1008                                 glDisable(GL_BLEND);
1009                         }
1010                         
1011                 } else {
1012                         /* draw items */
1013                         for(a=0; a<data->items.totitem; a++) {
1014                                 ui_searchbox_butrect(&rect, data, a);
1015                                 
1016                                 /* widget itself */
1017                                 ui_draw_menu_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a], (a+1)==data->active?UI_ACTIVE:0);
1018                                 
1019                         }
1020                         /* indicate more */
1021                         if(data->items.more) {
1022                                 ui_searchbox_butrect(&rect, data, data->items.maxitem-1);
1023                                 glEnable(GL_BLEND);
1024                                 UI_icon_draw((rect.xmax-rect.xmin)/2, rect.ymin-9, ICON_TRIA_DOWN);
1025                                 glDisable(GL_BLEND);
1026                         }
1027                         if(data->items.offset) {
1028                                 ui_searchbox_butrect(&rect, data, 0);
1029                                 glEnable(GL_BLEND);
1030                                 UI_icon_draw((rect.xmax-rect.xmin)/2, rect.ymax-7, ICON_TRIA_UP);
1031                                 glDisable(GL_BLEND);
1032                         }
1033                 }
1034         }
1035 }
1036
1037 static void ui_searchbox_region_free_cb(ARegion *ar)
1038 {
1039         uiSearchboxData *data= ar->regiondata;
1040         int a;
1041
1042         /* free search data */
1043         for (a = 0; a < data->items.maxitem; a++) {
1044                 MEM_freeN(data->items.names[a]);
1045         }
1046         MEM_freeN(data->items.names);
1047         MEM_freeN(data->items.pointers);
1048         MEM_freeN(data->items.icons);
1049         
1050         MEM_freeN(data);
1051         ar->regiondata= NULL;
1052 }
1053
1054 ARegion *ui_searchbox_create(bContext *C, ARegion *butregion, uiBut *but)
1055 {
1056         uiStyle *style= UI_GetStyle();
1057         static ARegionType type;
1058         ARegion *ar;
1059         uiSearchboxData *data;
1060         float aspect= but->block->aspect;
1061         float x1f, x2f, y1f, y2f;
1062         int x1, x2, y1, y2, winx, winy, ofsx, ofsy;
1063         
1064         /* create area region */
1065         ar= ui_add_temporary_region(CTX_wm_screen(C));
1066         
1067         memset(&type, 0, sizeof(ARegionType));
1068         type.draw= ui_searchbox_region_draw_cb;
1069         type.free= ui_searchbox_region_free_cb;
1070         ar->type= &type;
1071         
1072         /* create searchbox data */
1073         data= MEM_callocN(sizeof(uiSearchboxData), "uiSearchboxData");
1074
1075         /* set font, get bb */
1076         data->fstyle= style->widget; /* copy struct */
1077         data->fstyle.align= UI_STYLE_TEXT_CENTER;
1078         ui_fontscale(&data->fstyle.points, aspect);
1079         uiStyleFontSet(&data->fstyle);
1080         
1081         ar->regiondata= data;
1082         
1083         /* special case, hardcoded feature, not draw backdrop when called from menus,
1084          * assume for design that popup already added it */
1085         if(but->block->flag & UI_BLOCK_LOOP)
1086                 data->noback= 1;
1087         
1088         if (but->a1 > 0 && but->a2 > 0) {
1089                 data->preview = 1;
1090                 data->prv_rows = but->a1;
1091                 data->prv_cols = but->a2;
1092         }
1093         
1094         /* compute position */
1095         if(but->block->flag & UI_BLOCK_LOOP) {
1096                 /* this case is search menu inside other menu */
1097                 /* we copy region size */
1098
1099                 ar->winrct= butregion->winrct;
1100                 
1101                 /* widget rect, in region coords */
1102                 data->bbox.xmin = MENU_SHADOW_SIDE;
1103                 data->bbox.xmax = (ar->winrct.xmax-ar->winrct.xmin) - MENU_SHADOW_SIDE;
1104                 data->bbox.ymin = MENU_SHADOW_BOTTOM;
1105                 data->bbox.ymax = (ar->winrct.ymax-ar->winrct.ymin) - MENU_SHADOW_BOTTOM;
1106                 
1107                 /* check if button is lower half */
1108                 if( but->y2 < (but->block->miny+but->block->maxy)/2 ) {
1109                         data->bbox.ymin += (but->y2-but->y1);
1110                 }
1111                 else {
1112                         data->bbox.ymax -= (but->y2-but->y1);
1113                 }
1114         }
1115         else {
1116                 x1f= but->x1 - 5;       /* align text with button */
1117                 x2f= but->x2 + 5;       /* symmetrical */
1118                 y2f= but->y1;
1119                 y1f= y2f - uiSearchBoxhHeight();
1120
1121                 ofsx= (but->block->panel)? but->block->panel->ofsx: 0;
1122                 ofsy= (but->block->panel)? but->block->panel->ofsy: 0;
1123
1124                 x1f += ofsx;
1125                 x2f += ofsx;
1126                 y1f += ofsy;
1127                 y2f += ofsy;
1128         
1129                 /* minimal width */
1130                 if(x2f - x1f < 150) x2f= x1f+150; // XXX arbitrary
1131                 
1132                 /* copy to int, gets projected if possible too */
1133                 x1= x1f; y1= y1f; x2= x2f; y2= y2f; 
1134                 
1135                 if(butregion->v2d.cur.xmin != butregion->v2d.cur.xmax) {
1136                         UI_view2d_to_region_no_clip(&butregion->v2d, x1f, y1f, &x1, &y1);
1137                         UI_view2d_to_region_no_clip(&butregion->v2d, x2f, y2f, &x2, &y2);
1138                 }
1139
1140                 x1 += butregion->winrct.xmin;
1141                 x2 += butregion->winrct.xmin;
1142                 y1 += butregion->winrct.ymin;
1143                 y2 += butregion->winrct.ymin;
1144
1145                 wm_window_get_size(CTX_wm_window(C), &winx, &winy);
1146                 
1147                 if(x2 > winx) {
1148                         /* super size */
1149                         if(x2 > winx + x1) {
1150                                 x2= winx;
1151                                 x1= 0;
1152                         }
1153                         else {
1154                                 x1 -= x2-winx;
1155                                 x2= winx;
1156                         }
1157                 }
1158
1159                 if(y1 < 0) {
1160                         int newy1;
1161                         UI_view2d_to_region_no_clip(&butregion->v2d, 0, but->y2 + ofsy, NULL, &newy1);
1162                         newy1 += butregion->winrct.ymin;
1163
1164                         y2= y2-y1 + newy1;
1165                         y1= newy1;
1166                 }
1167
1168                 /* widget rect, in region coords */
1169                 data->bbox.xmin = MENU_SHADOW_SIDE;
1170                 data->bbox.xmax = x2-x1 + MENU_SHADOW_SIDE;
1171                 data->bbox.ymin = MENU_SHADOW_BOTTOM;
1172                 data->bbox.ymax = y2-y1 + MENU_SHADOW_BOTTOM;
1173                 
1174                 /* region bigger for shadow */
1175                 ar->winrct.xmin = x1 - MENU_SHADOW_SIDE;
1176                 ar->winrct.xmax = x2 + MENU_SHADOW_SIDE;
1177                 ar->winrct.ymin = y1 - MENU_SHADOW_BOTTOM;
1178                 ar->winrct.ymax = y2;
1179         }
1180         
1181         /* adds subwindow */
1182         ED_region_init(C, ar);
1183         
1184         /* notify change and redraw */
1185         ED_region_tag_redraw(ar);
1186         
1187         /* prepare search data */
1188         if (data->preview) {
1189                 data->items.maxitem= data->prv_rows * data->prv_cols;
1190         } else {
1191                 data->items.maxitem= SEARCH_ITEMS;
1192         }
1193         data->items.maxstrlen= but->hardmax;
1194         data->items.totitem= 0;
1195         data->items.names= MEM_callocN(data->items.maxitem*sizeof(void *), "search names");
1196         data->items.pointers= MEM_callocN(data->items.maxitem*sizeof(void *), "search pointers");
1197         data->items.icons= MEM_callocN(data->items.maxitem*sizeof(int), "search icons");
1198         for(x1=0; x1<data->items.maxitem; x1++)
1199                 data->items.names[x1]= MEM_callocN(but->hardmax+1, "search pointers");
1200         
1201         return ar;
1202 }
1203
1204 void ui_searchbox_free(bContext *C, ARegion *ar)
1205 {
1206         ui_remove_temporary_region(C, CTX_wm_screen(C), ar);
1207 }
1208
1209 /* sets red alert if button holds a string it can't find */
1210 /* XXX weak: search_func adds all partial matches... */
1211 void ui_but_search_test(uiBut *but)
1212 {
1213         uiSearchItems *items;
1214         int x1;
1215
1216         /* possibly very large lists (such as ID datablocks) only
1217          * only validate string RNA buts (not pointers) */
1218         if(but->rnaprop && RNA_property_type(but->rnaprop) != PROP_STRING) {
1219                 return;
1220         }
1221
1222         items= MEM_callocN(sizeof(uiSearchItems), "search items");
1223
1224         /* setup search struct */
1225         items->maxitem= 10;
1226         items->maxstrlen= 256;
1227         items->names= MEM_callocN(items->maxitem*sizeof(void *), "search names");
1228         for(x1=0; x1<items->maxitem; x1++)
1229                 items->names[x1]= MEM_callocN(but->hardmax+1, "search names");
1230         
1231         but->search_func(but->block->evil_C, but->search_arg, but->drawstr, items);
1232         
1233         /* only redalert when we are sure of it, this can miss cases when >10 matches */
1234         if(items->totitem==0)
1235                 uiButSetFlag(but, UI_BUT_REDALERT);
1236         else if(items->more==0) {
1237                 for(x1= 0; x1<items->totitem; x1++)
1238                         if(strcmp(but->drawstr, items->names[x1])==0)
1239                                 break;
1240                 if(x1==items->totitem)
1241                         uiButSetFlag(but, UI_BUT_REDALERT);
1242         }
1243         
1244         for (x1 = 0; x1 < items->maxitem; x1++) {
1245                 MEM_freeN(items->names[x1]);
1246         }
1247         MEM_freeN(items->names);
1248         MEM_freeN(items);
1249 }
1250
1251
1252 /************************* Creating Menu Blocks **********************/
1253
1254 /* position block relative to but, result is in window space */
1255 static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but, uiBlock *block)
1256 {
1257         uiBut *bt;
1258         uiSafetyRct *saferct;
1259         rctf butrct;
1260         /*float aspect;*/ /*UNUSED*/
1261         int xsize, ysize, xof=0, yof=0, center;
1262         short dir1= 0, dir2=0;
1263         
1264         /* transform to window coordinates, using the source button region/block */
1265         butrct.xmin = but->x1; butrct.xmax = but->x2;
1266         butrct.ymin = but->y1; butrct.ymax = but->y2;
1267
1268         ui_block_to_window_fl(butregion, but->block, &butrct.xmin, &butrct.ymin);
1269         ui_block_to_window_fl(butregion, but->block, &butrct.xmax, &butrct.ymax);
1270
1271         /* calc block rect */
1272         if(block->minx == 0.0f && block->maxx == 0.0f) {
1273                 if(block->buttons.first) {
1274                         block->minx= block->miny= 10000;
1275                         block->maxx= block->maxy= -10000;
1276                         
1277                         bt= block->buttons.first;
1278                         while(bt) {
1279                                 if(bt->x1 < block->minx) block->minx= bt->x1;
1280                                 if(bt->y1 < block->miny) block->miny= bt->y1;
1281
1282                                 if(bt->x2 > block->maxx) block->maxx= bt->x2;
1283                                 if(bt->y2 > block->maxy) block->maxy= bt->y2;
1284                                 
1285                                 bt= bt->next;
1286                         }
1287                 }
1288                 else {
1289                         /* we're nice and allow empty blocks too */
1290                         block->minx= block->miny= 0;
1291                         block->maxx= block->maxy= 20;
1292                 }
1293         }
1294         
1295         /*aspect= (float)(block->maxx - block->minx + 4);*/ /*UNUSED*/
1296         ui_block_to_window_fl(butregion, but->block, &block->minx, &block->miny);
1297         ui_block_to_window_fl(butregion, but->block, &block->maxx, &block->maxy);
1298
1299         //block->minx-= 2.0; block->miny-= 2.0;
1300         //block->maxx+= 2.0; block->maxy+= 2.0;
1301         
1302         xsize= block->maxx - block->minx+4; // 4 for shadow
1303         ysize= block->maxy - block->miny+4;
1304         /*aspect/= (float)xsize;*/ /*UNUSED*/
1305
1306         {
1307                 int left=0, right=0, top=0, down=0;
1308                 int winx, winy;
1309                 // int offscreen;
1310
1311                 wm_window_get_size(window, &winx, &winy);
1312
1313                 if(block->direction & UI_CENTER) center= ysize/2;
1314                 else center= 0;
1315                 
1316                 /* check if there's space at all */
1317                 if( butrct.xmin-xsize > 0.0f) left= 1;
1318                 if( butrct.xmax+xsize < winx) right= 1;
1319                 if( butrct.ymin-ysize+center > 0.0f) down= 1;
1320                 if( butrct.ymax+ysize-center < winy) top= 1;
1321                 
1322                 if(top==0 && down==0) {
1323                         if (butrct.ymin-ysize < winy-butrct.ymax-ysize)
1324                                 top= 1;
1325                         else
1326                                 down= 1;
1327                 }
1328                 
1329                 dir1= block->direction & UI_DIRECTION;
1330
1331                 /* secundary directions */
1332                 if(dir1 & (UI_TOP|UI_DOWN)) {
1333                         if(dir1 & UI_LEFT) dir2= UI_LEFT;
1334                         else if(dir1 & UI_RIGHT) dir2= UI_RIGHT;
1335                         dir1 &= (UI_TOP|UI_DOWN);
1336                 }
1337
1338                 if(dir2==0) if(dir1==UI_LEFT || dir1==UI_RIGHT) dir2= UI_DOWN;
1339                 if(dir2==0) if(dir1==UI_TOP || dir1==UI_DOWN) dir2= UI_LEFT;
1340                 
1341                 /* no space at all? don't change */
1342                 if(left || right) {
1343                         if(dir1==UI_LEFT && left==0) dir1= UI_RIGHT;
1344                         if(dir1==UI_RIGHT && right==0) dir1= UI_LEFT;
1345                         /* this is aligning, not append! */
1346                         if(dir2==UI_LEFT && right==0) dir2= UI_RIGHT;
1347                         if(dir2==UI_RIGHT && left==0) dir2= UI_LEFT;
1348                 }
1349                 if(down || top) {
1350                         if(dir1==UI_TOP && top==0) dir1= UI_DOWN;
1351                         if(dir1==UI_DOWN && down==0) dir1= UI_TOP;
1352                         if(dir2==UI_TOP && top==0) dir2= UI_DOWN;
1353                         if(dir2==UI_DOWN && down==0) dir2= UI_TOP;
1354                 }
1355                 
1356                 if(dir1==UI_LEFT) {
1357                         xof= butrct.xmin - block->maxx;
1358                         if(dir2==UI_TOP) yof= butrct.ymin - block->miny-center;
1359                         else yof= butrct.ymax - block->maxy+center;
1360                 }
1361                 else if(dir1==UI_RIGHT) {
1362                         xof= butrct.xmax - block->minx;
1363                         if(dir2==UI_TOP) yof= butrct.ymin - block->miny-center;
1364                         else yof= butrct.ymax - block->maxy+center;
1365                 }
1366                 else if(dir1==UI_TOP) {
1367                         yof= butrct.ymax - block->miny;
1368                         if(dir2==UI_RIGHT) xof= butrct.xmax - block->maxx;
1369                         else xof= butrct.xmin - block->minx;
1370                         // changed direction? 
1371                         if((dir1 & block->direction)==0) {
1372                                 if(block->direction & UI_SHIFT_FLIPPED)
1373                                         xof+= dir2==UI_LEFT?25:-25;
1374                                 uiBlockFlipOrder(block);
1375                         }
1376                 }
1377                 else if(dir1==UI_DOWN) {
1378                         yof= butrct.ymin - block->maxy;
1379                         if(dir2==UI_RIGHT) xof= butrct.xmax - block->maxx;
1380                         else xof= butrct.xmin - block->minx;
1381                         // changed direction?
1382                         if((dir1 & block->direction)==0) {
1383                                 if(block->direction & UI_SHIFT_FLIPPED)
1384                                         xof+= dir2==UI_LEFT?25:-25;
1385                                 uiBlockFlipOrder(block);
1386                         }
1387                 }
1388
1389                 /* and now we handle the exception; no space below or to top */
1390                 if(top==0 && down==0) {
1391                         if(dir1==UI_LEFT || dir1==UI_RIGHT) {
1392                                 // align with bottom of screen 
1393                                 // yof= ysize; (not with menu scrolls)
1394                         }
1395                 }
1396                 
1397                 /* or no space left or right */
1398                 if(left==0 && right==0) {
1399                         if(dir1==UI_TOP || dir1==UI_DOWN) {
1400                                 // align with left size of screen 
1401                                 xof= -block->minx+5;
1402                         }
1403                 }
1404                 
1405                 // apply requested offset in the block
1406                 xof += block->xofs/block->aspect;
1407                 yof += block->yofs/block->aspect;
1408 #if 0
1409                 /* clamp to window bounds, could be made into an option if its ever annoying */
1410                 if(     (offscreen= (block->miny+yof)) < 0)      yof -= offscreen; /* bottom */
1411                 else if((offscreen= (block->maxy+yof)-winy) > 0) yof -= offscreen; /* top */
1412                 if(     (offscreen= (block->minx+xof)) < 0)      xof -= offscreen; /* left */
1413                 else if((offscreen= (block->maxx+xof)-winx) > 0) xof -= offscreen; /* right */
1414 #endif
1415         }
1416         
1417         /* apply offset, buttons in window coords */
1418         
1419         for(bt= block->buttons.first; bt; bt= bt->next) {
1420                 ui_block_to_window_fl(butregion, but->block, &bt->x1, &bt->y1);
1421                 ui_block_to_window_fl(butregion, but->block, &bt->x2, &bt->y2);
1422
1423                 bt->x1 += xof;
1424                 bt->x2 += xof;
1425                 bt->y1 += yof;
1426                 bt->y2 += yof;
1427
1428                 bt->aspect= 1.0;
1429                 // ui_check_but recalculates drawstring size in pixels
1430                 ui_check_but(bt);
1431         }
1432         
1433         block->minx += xof;
1434         block->miny += yof;
1435         block->maxx += xof;
1436         block->maxy += yof;
1437
1438         /* safety calculus */
1439         if(but) {
1440                 float midx= (butrct.xmin+butrct.xmax)/2.0f;
1441                 float midy= (butrct.ymin+butrct.ymax)/2.0f;
1442                 
1443                 /* when you are outside parent button, safety there should be smaller */
1444                 
1445                 // parent button to left
1446                 if( midx < block->minx ) block->safety.xmin = block->minx-3; 
1447                 else block->safety.xmin = block->minx-40;
1448                 // parent button to right
1449                 if( midx > block->maxx ) block->safety.xmax = block->maxx+3; 
1450                 else block->safety.xmax = block->maxx+40;
1451                 
1452                 // parent button on bottom
1453                 if( midy < block->miny ) block->safety.ymin = block->miny-3; 
1454                 else block->safety.ymin = block->miny-40;
1455                 // parent button on top
1456                 if( midy > block->maxy ) block->safety.ymax = block->maxy+3; 
1457                 else block->safety.ymax = block->maxy+40;
1458                 
1459                 // exception for switched pulldowns...
1460                 if(dir1 && (dir1 & block->direction)==0) {
1461                         if(dir2==UI_RIGHT) block->safety.xmax = block->maxx+3; 
1462                         if(dir2==UI_LEFT) block->safety.xmin = block->minx-3; 
1463                 }
1464                 block->direction= dir1;
1465         }
1466         else {
1467                 block->safety.xmin = block->minx-40;
1468                 block->safety.ymin = block->miny-40;
1469                 block->safety.xmax = block->maxx+40;
1470                 block->safety.ymax = block->maxy+40;
1471         }
1472
1473         /* keep a list of these, needed for pulldown menus */
1474         saferct= MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
1475         saferct->parent= butrct;
1476         saferct->safety= block->safety;
1477         BLI_freelistN(&block->saferct);
1478         if(but)
1479                 BLI_duplicatelist(&block->saferct, &but->block->saferct);
1480         BLI_addhead(&block->saferct, saferct);
1481 }
1482
1483 static void ui_block_region_draw(const bContext *C, ARegion *ar)
1484 {
1485         uiBlock *block;
1486
1487         for(block=ar->uiblocks.first; block; block=block->next)
1488                 uiDrawBlock(C, block);
1489 }
1490
1491 static void ui_popup_block_clip(wmWindow *window, uiBlock *block)
1492 {
1493         int winx, winy;
1494         
1495         wm_window_get_size(window, &winx, &winy);
1496         
1497         if(block->minx < MENU_SHADOW_SIDE)
1498                 block->minx= MENU_SHADOW_SIDE;
1499         if(block->maxx > winx-MENU_SHADOW_SIDE)
1500                 block->maxx= winx-MENU_SHADOW_SIDE;
1501         
1502         if(block->miny < MENU_SHADOW_BOTTOM)
1503                 block->miny= MENU_SHADOW_BOTTOM;
1504         if(block->maxy > winy-MENU_TOP)
1505                 block->maxy= winy-MENU_TOP;
1506 }
1507
1508 void ui_popup_block_scrolltest(uiBlock *block)
1509 {
1510         uiBut *bt;
1511         /* Knowing direction is necessary for multi-column menus... */
1512         int is_flip = (block->direction & UI_TOP) && !(block->flag & UI_BLOCK_NO_FLIP);
1513         
1514         block->flag &= ~(UI_BLOCK_CLIPBOTTOM|UI_BLOCK_CLIPTOP);
1515         
1516         for(bt= block->buttons.first; bt; bt= bt->next)
1517                 bt->flag &= ~UI_SCROLLED;
1518         
1519         if(block->buttons.first==block->buttons.last)
1520                 return;
1521         
1522         /* mark buttons that are outside boundary and the ones next to it for arrow(s) */
1523         for(bt= block->buttons.first; bt; bt= bt->next) {
1524                 if(bt->y1 < block->miny) {
1525                         bt->flag |= UI_SCROLLED;
1526                         block->flag |= UI_BLOCK_CLIPBOTTOM;
1527                         /* make space for arrow */
1528                         if(bt->y2 < block->miny +10) {
1529                                 if(is_flip && bt->next && bt->next->y1 > bt->y1)
1530                                         bt->next->flag |= UI_SCROLLED;
1531                                 else if(!is_flip && bt->prev && bt->prev->y1 > bt->y1)
1532                                         bt->prev->flag |= UI_SCROLLED;
1533                         }
1534                 }
1535                 if(bt->y2 > block->maxy) {
1536                         bt->flag |= UI_SCROLLED;
1537                         block->flag |= UI_BLOCK_CLIPTOP;
1538                         /* make space for arrow */
1539                         if(bt->y1 > block->maxy -10) {
1540                                 if(!is_flip && bt->next && bt->next->y2 < bt->y2)
1541                                         bt->next->flag |= UI_SCROLLED;
1542                                 else if(is_flip && bt->prev && bt->prev->y2 < bt->y2)
1543                                         bt->prev->flag |= UI_SCROLLED;
1544                         }
1545                 }
1546         }
1547 }
1548
1549 uiPopupBlockHandle *ui_popup_block_create(bContext *C, ARegion *butregion, uiBut *but, uiBlockCreateFunc create_func, uiBlockHandleCreateFunc handle_create_func, void *arg)
1550 {
1551         wmWindow *window= CTX_wm_window(C);
1552         static ARegionType type;
1553         ARegion *ar;
1554         uiBlock *block;
1555         uiBut *bt;
1556         uiPopupBlockHandle *handle;
1557         uiSafetyRct *saferct;
1558
1559         /* create handle */
1560         handle= MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
1561
1562         /* store context for operator */
1563         handle->ctx_area= CTX_wm_area(C);
1564         handle->ctx_region= CTX_wm_region(C);
1565         
1566         /* create area region */
1567         ar= ui_add_temporary_region(CTX_wm_screen(C));
1568         handle->region= ar;
1569
1570         memset(&type, 0, sizeof(ARegionType));
1571         type.draw= ui_block_region_draw;
1572         ar->type= &type;
1573
1574         UI_add_region_handlers(&ar->handlers);
1575
1576         /* create ui block */
1577         if(create_func)
1578                 block= create_func(C, handle->region, arg);
1579         else
1580                 block= handle_create_func(C, handle, arg);
1581         
1582         if(block->handle) {
1583                 memcpy(block->handle, handle, sizeof(uiPopupBlockHandle));
1584                 MEM_freeN(handle);
1585                 handle= block->handle;
1586         }
1587         else
1588                 block->handle= handle;
1589
1590         ar->regiondata= handle;
1591
1592         if(!block->endblock)
1593                 uiEndBlock(C, block);
1594
1595         /* if this is being created from a button */
1596         if(but) {
1597                 if(ELEM(but->type, BLOCK, PULLDOWN))
1598                         block->xofs = -2;       /* for proper alignment */
1599
1600                 block->aspect = but->block->aspect;
1601
1602                 ui_block_position(window, butregion, but, block);
1603         }
1604         else {
1605                 /* keep a list of these, needed for pulldown menus */
1606                 saferct= MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
1607                 saferct->safety= block->safety;
1608                 BLI_addhead(&block->saferct, saferct);
1609                 block->flag |= UI_BLOCK_POPUP|UI_BLOCK_NUMSELECT;
1610         }
1611
1612         /* clip block with window boundary */
1613         ui_popup_block_clip(window, block);
1614         
1615         /* the block and buttons were positioned in window space as in 2.4x, now
1616          * these menu blocks are regions so we bring it back to region space.
1617          * additionally we add some padding for the menu shadow or rounded menus */
1618         ar->winrct.xmin = block->minx - MENU_SHADOW_SIDE;
1619         ar->winrct.xmax = block->maxx + MENU_SHADOW_SIDE;
1620         ar->winrct.ymin = block->miny - MENU_SHADOW_BOTTOM;
1621         ar->winrct.ymax = block->maxy + MENU_TOP;
1622         
1623         block->minx -= ar->winrct.xmin;
1624         block->maxx -= ar->winrct.xmin;
1625         block->miny -= ar->winrct.ymin;
1626         block->maxy -= ar->winrct.ymin;
1627
1628         for(bt= block->buttons.first; bt; bt= bt->next) {
1629                 bt->x1 -= ar->winrct.xmin;
1630                 bt->x2 -= ar->winrct.xmin;
1631                 bt->y1 -= ar->winrct.ymin;
1632                 bt->y2 -= ar->winrct.ymin;
1633         }
1634         
1635         block->flag |= UI_BLOCK_LOOP;
1636
1637         /* adds subwindow */
1638         ED_region_init(C, ar);
1639
1640         /* checks which buttons are visible, sets flags to prevent draw (do after region init) */
1641         ui_popup_block_scrolltest(block);
1642         
1643         /* get winmat now that we actually have the subwindow */
1644         wmSubWindowSet(window, ar->swinid);
1645         
1646         wm_subwindow_getmatrix(window, ar->swinid, block->winmat);
1647         
1648         /* notify change and redraw */
1649         ED_region_tag_redraw(ar);
1650
1651         return handle;
1652 }
1653
1654 void ui_popup_block_free(bContext *C, uiPopupBlockHandle *handle)
1655 {
1656         ui_remove_temporary_region(C, CTX_wm_screen(C), handle->region);
1657         
1658         if(handle->scrolltimer)
1659                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), handle->scrolltimer);
1660         
1661         MEM_freeN(handle);
1662 }
1663
1664 /***************************** Menu Button ***************************/
1665
1666 static void ui_block_func_MENUSTR(bContext *UNUSED(C), uiLayout *layout, void *arg_str)
1667 {
1668         uiBlock *block= uiLayoutGetBlock(layout);
1669         uiPopupBlockHandle *handle= block->handle;
1670         uiLayout *split, *column=NULL;
1671         uiBut *bt;
1672         MenuData *md;
1673         MenuEntry *entry;
1674         const char *instr= arg_str;
1675         int columns, rows, a, b;
1676         int column_start= 0, column_end= 0;
1677
1678         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
1679         
1680         /* compute menu data */
1681         md= decompose_menu_string(instr);
1682
1683         /* columns and row estimation */
1684         columns= (md->nitems+20)/20;
1685         if(columns<1)
1686                 columns= 1;
1687         if(columns>8)
1688                 columns= (md->nitems+25)/25;
1689         
1690         rows= md->nitems/columns;
1691         if(rows<1)
1692                 rows= 1;
1693         while(rows*columns<md->nitems)
1694                 rows++;
1695
1696         /* create title */
1697         if(md->title) {
1698                 if(md->titleicon) {
1699                         uiItemL(layout, md->title, md->titleicon);
1700                 }
1701                 else {
1702                         uiItemL(layout, md->title, ICON_NONE);
1703                         bt= block->buttons.last;
1704                         bt->flag= UI_TEXT_LEFT;
1705                 }
1706         }
1707
1708         /* inconsistent, but menus with labels do not look good flipped */
1709         entry= md->items;
1710         for(a=0; a<md->nitems; a++, entry++) {
1711                 if(entry->sepr && entry->str[0]) {
1712                         block->flag |= UI_BLOCK_NO_FLIP;
1713                         break;
1714                 }
1715         }
1716
1717         /* create items */
1718         split= uiLayoutSplit(layout, 0, 0);
1719
1720         for(a=0; a<md->nitems; a++) {
1721                 if(a == column_end) {
1722                         /* start new column, and find out where it ends in advance, so we
1723                          * can flip the order of items properly per column */
1724                         column_start= a;
1725                         column_end= md->nitems;
1726
1727                         for(b=a+1; b<md->nitems; b++) {
1728                                 entry= &md->items[b];
1729
1730                                 /* new column on N rows or on separation label */
1731                                 if(((b-a) % rows == 0) || (entry->sepr && entry->str[0])) {
1732                                         column_end = b;
1733                                         break;
1734                                 }
1735                         }
1736
1737                         column= uiLayoutColumn(split, 0);
1738                 }
1739
1740                 if(block->flag & UI_BLOCK_NO_FLIP)
1741                         entry= &md->items[a];
1742                 else
1743                         entry= &md->items[column_start + column_end-1-a];
1744
1745                 if(entry->sepr) {
1746                         uiItemL(column, entry->str, entry->icon);
1747                         bt= block->buttons.last;
1748                         bt->flag= UI_TEXT_LEFT;
1749                 }
1750                 else if(entry->icon) {
1751                         uiDefIconTextButF(block, BUTM|FLO, B_NOP, entry->icon, entry->str, 0, 0,
1752                                 UI_UNIT_X*5, UI_UNIT_Y, &handle->retvalue, (float) entry->retval, 0.0, 0, 0, "");
1753                 }
1754                 else {
1755                         uiDefButF(block, BUTM|FLO, B_NOP, entry->str, 0, 0,
1756                                 UI_UNIT_X*5, UI_UNIT_X, &handle->retvalue, (float) entry->retval, 0.0, 0, 0, "");
1757                 }
1758         }
1759         
1760         menudata_free(md);
1761 }
1762
1763 void ui_block_func_ICONROW(bContext *UNUSED(C), uiLayout *layout, void *arg_but)
1764 {
1765         uiBlock *block= uiLayoutGetBlock(layout);
1766         uiPopupBlockHandle *handle= block->handle;
1767         uiBut *but= arg_but;
1768         int a;
1769         
1770         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
1771         
1772         for(a=(int)but->hardmin; a<=(int)but->hardmax; a++)
1773                 uiDefIconButF(block, BUTM|FLO, B_NOP, but->icon+(a-but->hardmin), 0, 0, UI_UNIT_X*5, UI_UNIT_Y,
1774                         &handle->retvalue, (float)a, 0.0, 0, 0, "");
1775 }
1776
1777 void ui_block_func_ICONTEXTROW(bContext *UNUSED(C), uiLayout *layout, void *arg_but)
1778 {
1779         uiBlock *block= uiLayoutGetBlock(layout);
1780         uiPopupBlockHandle *handle= block->handle;
1781         uiBut *but= arg_but, *bt;
1782         MenuData *md;
1783         MenuEntry *entry;
1784         int a;
1785         
1786         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
1787
1788         md= decompose_menu_string(but->str);
1789
1790         /* title */
1791         if(md->title) {
1792                 bt= uiDefBut(block, LABEL, 0, md->title, 0, 0, UI_UNIT_X*5, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
1793                 bt->flag= UI_TEXT_LEFT;
1794         }
1795
1796         /* loop through the menu options and draw them out with icons & text labels */
1797         for(a=0; a<md->nitems; a++) {
1798                 entry= &md->items[md->nitems-a-1];
1799
1800                 if(entry->sepr)
1801                         uiItemS(layout);
1802                 else
1803                         uiDefIconTextButF(block, BUTM|FLO, B_NOP, (short)((but->icon)+(entry->retval-but->hardmin)), entry->str,
1804                                 0, 0, UI_UNIT_X*5, UI_UNIT_Y, &handle->retvalue, (float) entry->retval, 0.0, 0, 0, "");
1805         }
1806
1807         menudata_free(md);
1808 }
1809
1810 #if 0
1811 static void ui_warp_pointer(int x, int y)
1812 {
1813         /* XXX 2.50 which function to use for this? */
1814         /* OSX has very poor mouse-warp support, it sends events;
1815          * this causes a menu being pressed immediately ... */
1816 #  ifndef __APPLE__
1817         warp_pointer(x, y);
1818 #  endif
1819 }
1820 #endif
1821
1822 /********************* Color Button ****************/
1823
1824 /* picker sizes S hsize, F full size, D spacer, B button/pallette height  */
1825 #define SPICK   110.0
1826 #define FPICK   180.0
1827 #define DPICK   6.0
1828 #define BPICK   24.0
1829
1830 /* for picker, while editing hsv */
1831 void ui_set_but_hsv(uiBut *but)
1832 {
1833         float col[3];
1834         float *hsv= ui_block_hsv_get(but->block);
1835         
1836         hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
1837         ui_set_but_vectorf(but, col);
1838 }
1839
1840 /* also used by small picker, be careful with name checks below... */
1841 static void ui_update_block_buts_rgb(uiBlock *block, float *rgb)
1842 {
1843         uiBut *bt;
1844         float *hsv= ui_block_hsv_get(block);
1845         
1846         /* this is to keep the H and S value when V is equal to zero
1847          * and we are working in HSV mode, of course!
1848          */
1849         rgb_to_hsv_compat(rgb[0], rgb[1], rgb[2], hsv, hsv+1, hsv+2);
1850         
1851         // this updates button strings, is hackish... but button pointers are on stack of caller function
1852         for(bt= block->buttons.first; bt; bt= bt->next) {
1853                 if (bt->rnaprop) {
1854                         
1855                         ui_set_but_vectorf(bt, rgb);
1856                         
1857                 }
1858                 else if(strcmp(bt->str, "Hex: ")==0) {
1859                         float rgb_gamma[3];
1860                         double intpart;
1861                         char col[16];
1862                         
1863                         /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
1864                         
1865                         if (block->color_profile == BLI_PR_NONE) {
1866                                 copy_v3_v3(rgb_gamma, rgb);
1867                         } else {
1868                                 /* make an sRGB version, for Hex code */
1869                                 linearrgb_to_srgb_v3_v3(rgb_gamma, rgb);
1870                         }
1871                         
1872                         if (rgb_gamma[0] > 1.0f) rgb_gamma[0] = modf(rgb_gamma[0], &intpart);
1873                         if (rgb_gamma[1] > 1.0f) rgb_gamma[1] = modf(rgb_gamma[1], &intpart);
1874                         if (rgb_gamma[2] > 1.0f) rgb_gamma[2] = modf(rgb_gamma[2], &intpart);
1875
1876                         BLI_snprintf(col, sizeof(col), "%02X%02X%02X", FTOCHAR(rgb_gamma[0]), FTOCHAR(rgb_gamma[1]), FTOCHAR(rgb_gamma[2]));
1877                         
1878                         strcpy(bt->poin, col);
1879                 }
1880                 else if(bt->str[1]==' ') {
1881                         if(bt->str[0]=='R') {
1882                                 ui_set_but_val(bt, rgb[0]);
1883                         }
1884                         else if(bt->str[0]=='G') {
1885                                 ui_set_but_val(bt, rgb[1]);
1886                         }
1887                         else if(bt->str[0]=='B') {
1888                                 ui_set_but_val(bt, rgb[2]);
1889                         }
1890                         else if(bt->str[0]=='H') {
1891                                 ui_set_but_val(bt, hsv[0]);
1892                         }
1893                         else if(bt->str[0]=='S') {
1894                                 ui_set_but_val(bt, hsv[1]);
1895                         }
1896                         else if(bt->str[0]=='V') {
1897                                 ui_set_but_val(bt, hsv[2]);
1898                         }
1899                 }               
1900
1901                 ui_check_but(bt);
1902         }
1903 }
1904
1905 static void do_picker_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
1906 {
1907         uiBut *but= (uiBut *)bt1;
1908         uiPopupBlockHandle *popup= but->block->handle;
1909         PropertyRNA *prop = but->rnaprop;
1910         PointerRNA ptr = but->rnapoin;
1911         float rgb[4];
1912         
1913         if (prop) {
1914                 RNA_property_float_get_array(&ptr, prop, rgb);
1915                 ui_update_block_buts_rgb(but->block, rgb);
1916         }
1917         
1918         if(popup)
1919                 popup->menuretval= UI_RETURN_UPDATE;
1920 }
1921
1922 static void do_hsv_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
1923 {
1924         uiBut *but= (uiBut *)bt1;
1925         uiPopupBlockHandle *popup= but->block->handle;
1926         float rgb[3];
1927         float *hsv= ui_block_hsv_get(but->block);
1928         
1929         hsv_to_rgb(hsv[0], hsv[1], hsv[2], rgb, rgb+1, rgb+2);
1930         
1931         ui_update_block_buts_rgb(but->block, rgb);
1932         
1933         if(popup)
1934                 popup->menuretval= UI_RETURN_UPDATE;
1935 }
1936
1937 static void do_hex_rna_cb(bContext *UNUSED(C), void *bt1, void *hexcl)
1938 {
1939         uiBut *but= (uiBut *)bt1;
1940         uiPopupBlockHandle *popup= but->block->handle;
1941         char *hexcol= (char *)hexcl;
1942         float rgb[3];
1943         
1944         hex_to_rgb(hexcol, rgb, rgb+1, rgb+2);
1945         
1946         /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
1947         if (but->block->color_profile != BLI_PR_NONE) {
1948                 /* so we need to linearise it for Blender */
1949                 srgb_to_linearrgb_v3_v3(rgb, rgb);
1950         }
1951         
1952         ui_update_block_buts_rgb(but->block, rgb);
1953         
1954         if(popup)
1955                 popup->menuretval= UI_RETURN_UPDATE;
1956 }
1957
1958 static void close_popup_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
1959 {
1960         uiBut *but= (uiBut *)bt1;
1961         uiPopupBlockHandle *popup= but->block->handle;
1962         
1963         if(popup)
1964                 popup->menuretval= UI_RETURN_OK;
1965 }
1966
1967 static void picker_new_hide_reveal(uiBlock *block, short colormode)
1968 {
1969         uiBut *bt;
1970         
1971         /* tag buttons */
1972         for(bt= block->buttons.first; bt; bt= bt->next) {
1973                 
1974                 if (bt->type == LABEL) {
1975                         if( bt->str[1]=='G') {
1976                                 if(colormode==2) bt->flag &= ~UI_HIDDEN;
1977                                 else bt->flag |= UI_HIDDEN;
1978                         }
1979                 }
1980                 
1981                 if(bt->type==NUMSLI || bt->type==TEX) {
1982                         if( bt->str[1]=='e') {
1983                                 if(colormode==2) bt->flag &= ~UI_HIDDEN;
1984                                 else bt->flag |= UI_HIDDEN;
1985                         }
1986                         else if( ELEM3(bt->str[0], 'R', 'G', 'B')) {
1987                                 if(colormode==0) bt->flag &= ~UI_HIDDEN;
1988                                 else bt->flag |= UI_HIDDEN;
1989                         }
1990                         else if( ELEM3(bt->str[0], 'H', 'S', 'V')) {
1991                                 if(colormode==1) bt->flag &= ~UI_HIDDEN;
1992                                 else bt->flag |= UI_HIDDEN;
1993                         }
1994                 }
1995         }
1996 }
1997
1998 static void do_picker_new_mode_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
1999 {
2000         uiBut *bt= bt1;
2001         short colormode= ui_get_but_val(bt);
2002         picker_new_hide_reveal(bt->block, colormode);
2003 }
2004
2005 /* picker sizes S hsize, F full size, D spacer, B button/pallette height  */
2006 #define SPICK1  150.0
2007 #define DPICK1  6.0
2008
2009 #define PICKER_H        150
2010 #define PICKER_W        150
2011 #define PICKER_SPACE    6
2012 #define PICKER_BAR              14
2013
2014 #define PICKER_TOTAL_W  (PICKER_W+PICKER_SPACE+PICKER_BAR)
2015
2016 static void circle_picker(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop)
2017 {
2018         uiBut *bt;
2019         
2020         /* HS circle */
2021         bt= uiDefButR_prop(block, HSVCIRCLE, 0, "",     0, 0, PICKER_H, PICKER_W, ptr, prop, 0, 0.0, 0.0, 0, 0, "Color");
2022         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2023         
2024         /* value */
2025         bt= uiDefButR_prop(block, HSVCUBE, 0, "", PICKER_W+PICKER_SPACE,0,PICKER_BAR,PICKER_H, ptr, prop, 0, 0.0, 0.0, UI_GRAD_V_ALT, 0, "Value");
2026         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2027 }
2028
2029
2030 static void square_picker(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, int type)
2031 {
2032         uiBut *bt;
2033         int bartype = type + 3;
2034         
2035         /* HS square */
2036         bt= uiDefButR_prop(block, HSVCUBE, 0, "",       0, PICKER_BAR+PICKER_SPACE, PICKER_TOTAL_W, PICKER_H, ptr, prop, 0, 0.0, 0.0, type, 0, "Color");
2037         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2038         
2039         /* value */
2040         bt= uiDefButR_prop(block, HSVCUBE, 0, "",               0, 0, PICKER_TOTAL_W, PICKER_BAR, ptr, prop, 0, 0.0, 0.0, bartype, 0, "Value");
2041         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2042 }
2043
2044
2045 /* a HS circle, V slider, rgb/hsv/hex sliders */
2046 static void uiBlockPicker(uiBlock *block, float *rgb, PointerRNA *ptr, PropertyRNA *prop)
2047 {
2048         static short colormode= 0;      /* temp? 0=rgb, 1=hsv, 2=hex */
2049         uiBut *bt;
2050         int width, butwidth;
2051         static char tip[50];
2052         static char hexcol[128];
2053         float rgb_gamma[3];
2054         float min, max, step, precision;
2055         float *hsv= ui_block_hsv_get(block);
2056         
2057         ui_block_hsv_get(block);
2058         
2059         width= PICKER_TOTAL_W;
2060         butwidth = width - UI_UNIT_X - 10;
2061         
2062         /* existence of profile means storage is in linear color space, with display correction */
2063         if (block->color_profile == BLI_PR_NONE) {
2064                 BLI_strncpy(tip, "Value in Display Color Space", sizeof(tip));
2065                 copy_v3_v3(rgb_gamma, rgb);
2066         } else {
2067                 BLI_strncpy(tip, "Value in Linear RGB Color Space", sizeof(tip));
2068                 /* make an sRGB version, for Hex code */
2069                 linearrgb_to_srgb_v3_v3(rgb_gamma, rgb);
2070         }
2071         
2072         /* sneaky way to check for alpha */
2073         rgb[3]= FLT_MAX;
2074
2075         RNA_property_float_ui_range(ptr, prop, &min, &max, &step, &precision);
2076         RNA_property_float_get_array(ptr, prop, rgb);
2077
2078         switch (U.color_picker_type) {
2079                 case USER_CP_CIRCLE:
2080                         circle_picker(block, ptr, prop);
2081                         break;
2082                 case USER_CP_SQUARE_SV:
2083                         square_picker(block, ptr, prop, UI_GRAD_SV);
2084                         break;
2085                 case USER_CP_SQUARE_HS:
2086                         square_picker(block, ptr, prop, UI_GRAD_HS);
2087                         break;
2088                 case USER_CP_SQUARE_HV:
2089                         square_picker(block, ptr, prop, UI_GRAD_HV);
2090                         break;
2091         }
2092         
2093         /* mode */
2094         uiBlockBeginAlign(block);
2095         bt= uiDefButS(block, ROW, 0, "RGB",     0, -30, width/3, UI_UNIT_Y, &colormode, 0.0, 0.0, 0, 0, "");
2096         uiButSetFunc(bt, do_picker_new_mode_cb, bt, NULL);
2097         bt= uiDefButS(block, ROW, 0, "HSV",     width/3, -30, width/3, UI_UNIT_Y, &colormode, 0.0, 1.0, 0, 0, "");
2098         uiButSetFunc(bt, do_picker_new_mode_cb, bt, NULL);
2099         bt= uiDefButS(block, ROW, 0, "Hex",     2*width/3, -30, width/3, UI_UNIT_Y, &colormode, 0.0, 2.0, 0, 0, "");
2100         uiButSetFunc(bt, do_picker_new_mode_cb, bt, NULL);
2101         uiBlockEndAlign(block);
2102
2103         bt= uiDefIconButO(block, BUT, "UI_OT_eyedropper", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, butwidth+10, -60, UI_UNIT_X, UI_UNIT_Y, NULL);
2104         uiButSetFunc(bt, close_popup_cb, bt, NULL);
2105         
2106         /* RGB values */
2107         uiBlockBeginAlign(block);
2108         bt= uiDefButR_prop(block, NUMSLI, 0, "R ",      0, -60, butwidth, UI_UNIT_Y, ptr, prop, 0, 0.0, 0.0, 0, 3, "Red");
2109         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2110         bt= uiDefButR_prop(block, NUMSLI, 0, "G ",      0, -80, butwidth, UI_UNIT_Y, ptr, prop, 1, 0.0, 0.0, 0, 3, "Green");
2111         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2112         bt= uiDefButR_prop(block, NUMSLI, 0, "B ",      0, -100, butwidth, UI_UNIT_Y, ptr, prop, 2, 0.0, 0.0, 0, 3, "Blue");
2113         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2114
2115         // could use uiItemFullR(col, ptr, prop, -1, 0, UI_ITEM_R_EXPAND|UI_ITEM_R_SLIDER, "", ICON_NONE);
2116         // but need to use uiButSetFunc for updating other fake buttons
2117         
2118         /* HSV values */
2119         uiBlockBeginAlign(block);
2120         bt= uiDefButF(block, NUMSLI, 0, "H ",   0, -60, butwidth, UI_UNIT_Y, hsv, 0.0, 1.0, 10, 3, "Hue");
2121         uiButSetFunc(bt, do_hsv_rna_cb, bt, hsv);
2122         bt= uiDefButF(block, NUMSLI, 0, "S ",   0, -80, butwidth, UI_UNIT_Y, hsv+1, 0.0, 1.0, 10, 3, "Saturation");
2123         uiButSetFunc(bt, do_hsv_rna_cb, bt, hsv);
2124         bt= uiDefButF(block, NUMSLI, 0, "V ",   0, -100, butwidth, UI_UNIT_Y, hsv+2, 0.0, max, 10, 3, "Value");
2125         uiButSetFunc(bt, do_hsv_rna_cb, bt, hsv);
2126         uiBlockEndAlign(block);
2127
2128         if(rgb[3] != FLT_MAX) {
2129                 bt= uiDefButR_prop(block, NUMSLI, 0, "A ",      0, -120, butwidth, UI_UNIT_Y, ptr, prop, 3, 0.0, 0.0, 0, 0, "Alpha");
2130                 uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2131         }
2132         else {
2133                 rgb[3]= 1.0f;
2134         }
2135
2136         BLI_snprintf(hexcol, sizeof(hexcol), "%02X%02X%02X", FTOCHAR(rgb_gamma[0]), FTOCHAR(rgb_gamma[1]), FTOCHAR(rgb_gamma[2]));
2137
2138         bt= uiDefBut(block, TEX, 0, "Hex: ", 0, -60, butwidth, UI_UNIT_Y, hexcol, 0, 8, 0, 0, "Hex triplet for color (#RRGGBB)");
2139         uiButSetFunc(bt, do_hex_rna_cb, bt, hexcol);
2140         uiDefBut(block, LABEL, 0, "(Gamma Corrected)", 0, -80, butwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2141
2142         rgb_to_hsv(rgb[0], rgb[1], rgb[2], hsv, hsv+1, hsv+2);
2143
2144         picker_new_hide_reveal(block, colormode);
2145 }
2146
2147
2148 static int ui_picker_small_wheel_cb(const bContext *UNUSED(C), uiBlock *block, wmEvent *event)
2149 {
2150         float add= 0.0f;
2151         
2152         if(event->type==WHEELUPMOUSE)
2153                 add= 0.05f;
2154         else if(event->type==WHEELDOWNMOUSE)
2155                 add= -0.05f;
2156         
2157         if(add!=0.0f) {
2158                 uiBut *but;
2159                 
2160                 for(but= block->buttons.first; but; but= but->next) {
2161                         if(but->type==HSVCUBE && but->active==NULL) {
2162                                 uiPopupBlockHandle *popup= block->handle;
2163                                 float col[3];
2164                                 float *hsv= ui_block_hsv_get(block);
2165                                 
2166                                 ui_get_but_vectorf(but, col);
2167                                 
2168                                 rgb_to_hsv_compat(col[0], col[1], col[2], hsv, hsv+1, hsv+2);
2169                                 hsv[2]= CLAMPIS(hsv[2]+add, 0.0f, 1.0f);
2170                                 hsv_to_rgb(hsv[0], hsv[1], hsv[2], col, col+1, col+2);
2171
2172                                 ui_set_but_vectorf(but, col);
2173                                 
2174                                 ui_update_block_buts_rgb(block, col);
2175                                 if(popup)
2176                                         popup->menuretval= UI_RETURN_UPDATE;
2177                                 
2178                                 return 1;
2179                         }
2180                 }
2181         }
2182         return 0;
2183 }
2184
2185 uiBlock *ui_block_func_COL(bContext *C, uiPopupBlockHandle *handle, void *arg_but)
2186 {
2187         uiBut *but= arg_but;
2188         uiBlock *block;
2189         
2190         block= uiBeginBlock(C, handle->region, __func__, UI_EMBOSS);
2191         
2192         if (but->rnaprop) {
2193                 if (RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
2194                         block->color_profile = BLI_PR_NONE;
2195                 }
2196         }
2197         
2198         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
2199         
2200         copy_v3_v3(handle->retvec, but->editvec);
2201         
2202         uiBlockPicker(block, handle->retvec, &but->rnapoin, but->rnaprop);
2203         
2204         block->flag= UI_BLOCK_LOOP|UI_BLOCK_REDRAW|UI_BLOCK_KEEP_OPEN|UI_BLOCK_OUT_1;
2205         uiBoundsBlock(block, 10);
2206         
2207         block->block_event_func= ui_picker_small_wheel_cb;
2208         
2209         /* and lets go */
2210         block->direction= UI_TOP;
2211         
2212         return block;
2213 }
2214
2215 /************************ Popup Menu Memory ****************************/
2216
2217 static int ui_popup_string_hash(char *str)
2218 {
2219         /* sometimes button contains hotkey, sometimes not, strip for proper compare */
2220         int hash;
2221         char *delimit= strchr(str, '|');
2222
2223         if(delimit) *delimit= 0;
2224         hash= BLI_ghashutil_strhash(str);
2225         if(delimit) *delimit= '|';
2226
2227         return hash;
2228 }
2229
2230 static int ui_popup_menu_hash(const char *str)
2231 {
2232         return BLI_ghashutil_strhash(str);
2233 }
2234
2235 /* but == NULL read, otherwise set */
2236 uiBut *ui_popup_menu_memory(uiBlock *block, uiBut *but)
2237 {
2238         static int mem[256], first=1;
2239         int hash= block->puphash;
2240         
2241         if(first) {
2242                 /* init */
2243                 memset(mem, -1, sizeof(mem));
2244                 first= 0;
2245         }
2246
2247         if(but) {
2248                 /* set */
2249                 mem[hash & 255 ]= ui_popup_string_hash(but->str);
2250                 return NULL;
2251         }
2252         else {
2253                 /* get */
2254                 for(but=block->buttons.first; but; but=but->next)
2255                         if(ui_popup_string_hash(but->str) == mem[hash & 255])
2256                                 return but;
2257
2258                 return NULL;
2259         }
2260 }
2261
2262 /******************** Popup Menu with callback or string **********************/
2263
2264 struct uiPopupMenu {
2265         uiBlock *block;
2266         uiLayout *layout;
2267         uiBut *but;
2268
2269         int mx, my, popup, slideout;
2270         int startx, starty, maxrow;
2271
2272         uiMenuCreateFunc menu_func;
2273         void *menu_arg;
2274 };
2275
2276 static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, void *arg_pup)
2277 {
2278         uiBlock *block;
2279         uiBut *bt;
2280         uiPopupMenu *pup= arg_pup;
2281         int offset[2], direction, minwidth, width, height, flip;
2282
2283         if(pup->menu_func) {
2284                 pup->block->handle= handle;
2285                 pup->menu_func(C, pup->layout, pup->menu_arg);
2286                 pup->block->handle= NULL;
2287         }
2288
2289         if(pup->but) {
2290                 /* minimum width to enforece */
2291                 minwidth= pup->but->x2 - pup->but->x1;
2292
2293                 if(pup->but->type == PULLDOWN || pup->but->menu_create_func) {
2294                         direction= UI_DOWN;
2295                         flip= 1;
2296                 }
2297                 else {
2298                         direction= UI_TOP;
2299                         flip= 0;
2300                 }
2301         }
2302         else {
2303                 minwidth= 50;
2304                 direction= UI_DOWN;
2305                 flip= 1;
2306         }
2307
2308         block= pup->block;
2309         
2310         /* in some cases we create the block before the region,
2311          * so we set it delayed here if necessary */
2312         if(BLI_findindex(&handle->region->uiblocks, block) == -1)
2313                 uiBlockSetRegion(block, handle->region);
2314
2315         block->direction= direction;
2316
2317         uiBlockLayoutResolve(block, &width, &height);
2318
2319         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
2320         
2321         if(pup->popup) {
2322                 uiBlockSetFlag(block, UI_BLOCK_LOOP|UI_BLOCK_REDRAW|UI_BLOCK_NUMSELECT|UI_BLOCK_RET_1);
2323                 uiBlockSetDirection(block, direction);
2324
2325                 /* offset the mouse position, possibly based on earlier selection */
2326                 if((block->flag & UI_BLOCK_POPUP_MEMORY) &&
2327                         (bt= ui_popup_menu_memory(block, NULL))) {
2328                         /* position mouse on last clicked item, at 0.8*width of the
2329                          * button, so it doesn't overlap the text too much, also note
2330                          * the offset is negative because we are inverse moving the
2331                          * block to be under the mouse */
2332                         offset[0]= -(bt->x1 + 0.8f*(bt->x2 - bt->x1));
2333                         offset[1]= -(bt->y1 + 0.5f*UI_UNIT_Y);
2334                 }
2335                 else {
2336                         /* position mouse at 0.8*width of the button and below the tile
2337                          * on the first item */
2338                         offset[0]= 0;
2339                         for(bt=block->buttons.first; bt; bt=bt->next)
2340                                 offset[0]= MIN2(offset[0], -(bt->x1 + 0.8f*(bt->x2 - bt->x1)));
2341
2342                         offset[1]= 1.5*UI_UNIT_Y;
2343                 }
2344
2345                 block->minbounds= minwidth;
2346                 uiMenuPopupBoundsBlock(block, 1, offset[0], offset[1]);
2347         }
2348         else {
2349                 /* for a header menu we set the direction automatic */
2350                 if(!pup->slideout && flip) {
2351                         ScrArea *sa= CTX_wm_area(C);
2352                         if(sa && sa->headertype==HEADERDOWN) {
2353                                 ARegion *ar= CTX_wm_region(C);
2354                                 if(ar && ar->regiontype == RGN_TYPE_HEADER) {
2355                                         uiBlockSetDirection(block, UI_TOP);
2356                                         uiBlockFlipOrder(block);
2357                                 }
2358                         }
2359                 }
2360
2361                 block->minbounds= minwidth;
2362                 uiTextBoundsBlock(block, 50);
2363         }
2364
2365         /* if menu slides out of other menu, override direction */
2366         if(pup->slideout)
2367                 uiBlockSetDirection(block, UI_RIGHT);
2368
2369         uiEndBlock(C, block);
2370
2371         return pup->block;
2372 }
2373
2374 uiPopupBlockHandle *ui_popup_menu_create(bContext *C, ARegion *butregion, uiBut *but, uiMenuCreateFunc menu_func, void *arg, char *str)
2375 {
2376         wmWindow *window= CTX_wm_window(C);
2377         uiStyle *style= UI_GetStyle();
2378         uiPopupBlockHandle *handle;
2379         uiPopupMenu *pup;
2380         pup= MEM_callocN(sizeof(uiPopupMenu), __func__);
2381         pup->block= uiBeginBlock(C, NULL, __func__, UI_EMBOSSP);
2382         pup->layout= uiBlockLayout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, style);
2383         pup->slideout= (but && (but->block->flag & UI_BLOCK_LOOP));
2384         pup->but= but;
2385         uiLayoutSetOperatorContext(pup->layout, WM_OP_INVOKE_REGION_WIN);
2386
2387         if(!but) {
2388                 /* no button to start from, means we are a popup */
2389                 pup->mx= window->eventstate->x;
2390                 pup->my= window->eventstate->y;
2391                 pup->popup= 1;
2392                 pup->block->flag |= UI_BLOCK_NO_FLIP;
2393         }
2394         /* some enums reversing is strange, currently we have no good way to
2395          * reverse some enum's but not others, so reverse all so the first menu
2396          * items are always close to the mouse cursor */
2397 #if 0
2398         else {
2399                 /* if this is an rna button then we can assume its an enum
2400                  * flipping enums is generally not good since the order can be
2401                  * important [#28786] */
2402                 if(but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM) {
2403                         pup->block->flag |= UI_BLOCK_NO_FLIP;
2404                 }
2405         }
2406 #endif
2407
2408         if(str) {
2409                 /* menu is created from a string */
2410                 pup->menu_func= ui_block_func_MENUSTR;
2411                 pup->menu_arg= str;
2412         }
2413         else {
2414                 /* menu is created from a callback */
2415                 pup->menu_func= menu_func;
2416                 pup->menu_arg= arg;
2417         }
2418         
2419         handle= ui_popup_block_create(C, butregion, but, NULL, ui_block_func_POPUP, pup);
2420
2421         if(!but) {
2422                 handle->popup= 1;
2423
2424                 UI_add_popup_handlers(C, &window->modalhandlers, handle);
2425                 WM_event_add_mousemove(C);
2426         }
2427         
2428         MEM_freeN(pup);
2429
2430         return handle;
2431 }
2432
2433 /******************** Popup Menu API with begin and end ***********************/
2434
2435 /* only return handler, and set optional title */
2436 uiPopupMenu *uiPupMenuBegin(bContext *C, const char *title, int icon)
2437 {
2438         uiStyle *style= UI_GetStyle();
2439         uiPopupMenu *pup= MEM_callocN(sizeof(uiPopupMenu), "popup menu");
2440         uiBut *but;
2441         
2442         pup->block= uiBeginBlock(C, NULL, __func__, UI_EMBOSSP);
2443         pup->block->flag |= UI_BLOCK_POPUP_MEMORY;
2444         pup->block->puphash= ui_popup_menu_hash(title);
2445         pup->layout= uiBlockLayout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, style);
2446         uiLayoutSetOperatorContext(pup->layout, WM_OP_EXEC_REGION_WIN);
2447
2448         /* create in advance so we can let buttons point to retval already */
2449         pup->block->handle= MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
2450         
2451         /* create title button */
2452         if(title && title[0]) {
2453                 char titlestr[256];
2454                 
2455                 if(icon) {
2456                         BLI_snprintf(titlestr, sizeof(titlestr), " %s", title);
2457                         uiDefIconTextBut(pup->block, LABEL, 0, icon, titlestr, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2458                 }
2459                 else {
2460                         but = uiDefBut(pup->block, LABEL, 0, title, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2461                         but->flag= UI_TEXT_LEFT;
2462                 }
2463         }
2464
2465         return pup;
2466 }
2467
2468 /* set the whole structure to work */
2469 void uiPupMenuEnd(bContext *C, uiPopupMenu *pup)
2470 {
2471         wmWindow *window= CTX_wm_window(C);
2472         uiPopupBlockHandle *menu;
2473         
2474         pup->popup= 1;
2475         pup->mx= window->eventstate->x;
2476         pup->my= window->eventstate->y;
2477         
2478         menu= ui_popup_block_create(C, NULL, NULL, NULL, ui_block_func_POPUP, pup);
2479         menu->popup= 1;
2480         
2481         UI_add_popup_handlers(C, &window->modalhandlers, menu);
2482         WM_event_add_mousemove(C);
2483         
2484         MEM_freeN(pup);
2485 }
2486
2487 uiLayout *uiPupMenuLayout(uiPopupMenu *pup)
2488 {
2489         return pup->layout;
2490 }
2491
2492 /*************************** Standard Popup Menus ****************************/
2493
2494 static void operator_name_cb(bContext *C, void *arg, int retval)
2495 {
2496         const char *opname= arg;
2497
2498         if(opname && retval > 0)
2499                 WM_operator_name_call(C, opname, WM_OP_EXEC_DEFAULT, NULL);
2500 }
2501
2502 static void operator_cb(bContext *C, void *arg, int retval)
2503 {
2504         wmOperator *op= arg;
2505         
2506         if(op && retval > 0)
2507                 WM_operator_call(C, op);
2508         else
2509                 WM_operator_free(op);
2510 }
2511
2512 static void confirm_cancel_operator(void *opv)
2513 {
2514         WM_operator_free(opv);
2515 }
2516
2517 static void vconfirm_opname(bContext *C, const char *opname, const char *title, const char *itemfmt, va_list ap)
2518 {
2519         uiPopupBlockHandle *handle;
2520         char *s, buf[512];
2521
2522         s= buf;
2523         if (title) s+= sprintf(s, "%s%%t|", title);
2524         vsnprintf(s, sizeof(buf) - (s - buf), itemfmt, ap);
2525         buf[sizeof(buf) - 1]= '\0';
2526
2527         handle= ui_popup_menu_create(C, NULL, NULL, NULL, NULL, buf);
2528
2529         handle->popup_func= operator_name_cb;
2530         handle->popup_arg= (void *)opname;
2531 }
2532
2533 static void confirm_operator(bContext *C, wmOperator *op, const char *title, const char *item)
2534 {
2535         uiPopupBlockHandle *handle;
2536         char *s, buf[512];
2537         
2538         s= buf;
2539         if (title) s+= BLI_snprintf(s, sizeof(buf), "%s%%t|%s", title, item);
2540         (void)s;
2541         
2542         handle= ui_popup_menu_create(C, NULL, NULL, NULL, NULL, buf);
2543
2544         handle->popup_func= operator_cb;
2545         handle->popup_arg= op;
2546         handle->cancel_func= confirm_cancel_operator;
2547 }
2548
2549 void uiPupMenuOkee(bContext *C, const char *opname, const char *str, ...)
2550 {
2551         va_list ap;
2552         char titlestr[256];
2553
2554         BLI_snprintf(titlestr, sizeof(titlestr), "OK? %%i%d", ICON_QUESTION);
2555
2556         va_start(ap, str);
2557         vconfirm_opname(C, opname, titlestr, str, ap);
2558         va_end(ap);
2559 }
2560
2561 /* note, only call this is the file exists,
2562  * the case where the file does not exist so can be saved without a
2563  * popup must be checked for already, since saving from here
2564  * will free the operator which will break invoke().
2565  * The operator state for this is implicitly OPERATOR_RUNNING_MODAL */
2566 void uiPupMenuSaveOver(bContext *C, wmOperator *op, const char *filename)
2567 {
2568         confirm_operator(C, op, "Save Over", filename);
2569 }
2570
2571 void uiPupMenuNotice(bContext *C, const char *str, ...)
2572 {
2573         va_list ap;
2574
2575         va_start(ap, str);
2576         vconfirm_opname(C, NULL, NULL, str, ap);
2577         va_end(ap);
2578 }
2579
2580 void uiPupMenuError(bContext *C, const char *str, ...)
2581 {
2582         va_list ap;
2583         char nfmt[256];
2584         char titlestr[256];
2585
2586         BLI_snprintf(titlestr, sizeof(titlestr), "Error %%i%d", ICON_ERROR);
2587
2588         BLI_strncpy(nfmt, str, sizeof(nfmt));
2589
2590         va_start(ap, str);
2591         vconfirm_opname(C, NULL, titlestr, nfmt, ap);
2592         va_end(ap);
2593 }
2594
2595 void uiPupMenuReports(bContext *C, ReportList *reports)
2596 {
2597         Report *report;
2598         DynStr *ds;
2599         char *str;
2600
2601         if(!reports || !reports->list.first)
2602                 return;
2603         if(!CTX_wm_window(C))
2604                 return;
2605
2606         ds= BLI_dynstr_new();
2607
2608         for(report=reports->list.first; report; report=report->next) {
2609                 if(report->type < reports->printlevel)
2610                         ; /* pass */
2611                 else if(report->type >= RPT_ERROR)
2612                         BLI_dynstr_appendf(ds, "Error %%i%d%%t|%s", ICON_ERROR, report->message);
2613                 else if(report->type >= RPT_WARNING)
2614                         BLI_dynstr_appendf(ds, "Warning %%i%d%%t|%s", ICON_ERROR, report->message);
2615                 else if(report->type >= RPT_INFO)
2616                         BLI_dynstr_appendf(ds, "Info %%i%d%%t|%s", ICON_INFO, report->message);
2617         }
2618
2619         str= BLI_dynstr_get_cstring(ds);
2620         if(str[0] != '\0')
2621                 ui_popup_menu_create(C, NULL, NULL, NULL, NULL, str);
2622         MEM_freeN(str);
2623
2624         BLI_dynstr_free(ds);
2625 }
2626
2627 void uiPupMenuInvoke(bContext *C, const char *idname)
2628 {
2629         uiPopupMenu *pup;
2630         uiLayout *layout;
2631         Menu menu;
2632         MenuType *mt = WM_menutype_find(idname, TRUE);
2633
2634         if(mt==NULL) {
2635                 printf("%s: named menu \"%s\" not found\n", __func__, idname);
2636                 return;
2637         }
2638
2639         if(mt->poll && mt->poll(C, mt)==0)
2640                 return;
2641
2642         pup= uiPupMenuBegin(C, mt->label, ICON_NONE);
2643         layout= uiPupMenuLayout(pup);
2644
2645         menu.layout= layout;
2646         menu.type= mt;
2647
2648         mt->draw(C, &menu);
2649
2650         uiPupMenuEnd(C, pup);
2651 }
2652
2653
2654 /*************************** Popup Block API **************************/
2655
2656 void uiPupBlockO(bContext *C, uiBlockCreateFunc func, void *arg, const char *opname, int opcontext)
2657 {
2658         wmWindow *window= CTX_wm_window(C);
2659         uiPopupBlockHandle *handle;
2660         
2661         handle= ui_popup_block_create(C, NULL, NULL, func, NULL, arg);
2662         handle->popup= 1;
2663         handle->optype= (opname)? WM_operatortype_find(opname, 0): NULL;
2664         handle->opcontext= opcontext;
2665         
2666         UI_add_popup_handlers(C, &window->modalhandlers, handle);
2667         WM_event_add_mousemove(C);
2668 }
2669
2670 void uiPupBlock(bContext *C, uiBlockCreateFunc func, void *arg)
2671 {
2672         uiPupBlockO(C, func, arg, NULL, 0);
2673 }
2674
2675 void uiPupBlockEx(bContext *C, uiBlockCreateFunc func, uiBlockHandleFunc popup_func, uiBlockCancelFunc cancel_func, void *arg)
2676 {
2677         wmWindow *window= CTX_wm_window(C);
2678         uiPopupBlockHandle *handle;
2679         
2680         handle= ui_popup_block_create(C, NULL, NULL, func, NULL, arg);
2681         handle->popup= 1;
2682         handle->retvalue= 1;
2683
2684         handle->popup_arg= arg;
2685         handle->popup_func= popup_func;
2686         handle->cancel_func= cancel_func;
2687         // handle->opcontext= opcontext;
2688         
2689         UI_add_popup_handlers(C, &window->modalhandlers, handle);
2690         WM_event_add_mousemove(C);
2691 }
2692
2693 #if 0 /* UNUSED */
2694 void uiPupBlockOperator(bContext *C, uiBlockCreateFunc func, wmOperator *op, int opcontext)
2695 {
2696         wmWindow *window= CTX_wm_window(C);
2697         uiPopupBlockHandle *handle;
2698         
2699         handle= ui_popup_block_create(C, NULL, NULL, func, NULL, op);
2700         handle->popup= 1;
2701         handle->retvalue= 1;
2702
2703         handle->popup_arg= op;
2704         handle->popup_func= operator_cb;
2705         handle->cancel_func= confirm_cancel_operator;
2706         handle->opcontext= opcontext;
2707         
2708         UI_add_popup_handlers(C, &window->modalhandlers, handle);
2709         WM_event_add_mousemove(C);
2710 }
2711 #endif
2712
2713 void uiPupBlockClose(bContext *C, uiBlock *block)
2714 {
2715         if(block->handle) {
2716                 wmWindow *win = CTX_wm_window(C);
2717
2718                 /* if loading new .blend while popup is open, window will be NULL */
2719                 if(win) {
2720                         UI_remove_popup_handlers(&win->modalhandlers, block->handle);
2721                         ui_popup_block_free(C, block->handle);
2722                 }
2723         }
2724 }
2725
2726 float *ui_block_hsv_get(uiBlock *block)
2727 {
2728         return block->_hsv;
2729 }