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