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