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