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