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