Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / interface / interface_templates.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  * Contributor(s): Blender Foundation 2009.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/editors/interface/interface_templates.c
24  *  \ingroup edinterface
25  */
26
27
28 #include <ctype.h>
29 #include <stdlib.h>
30 #include <stddef.h>
31 #include <string.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_cachefile_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_scene_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_object_force.h"
40 #include "DNA_brush_types.h"
41 #include "DNA_texture_types.h"
42
43 #include "BLI_utildefines.h"
44 #include "BLI_alloca.h"
45 #include "BLI_string.h"
46 #include "BLI_ghash.h"
47 #include "BLI_rect.h"
48 #include "BLI_math.h"
49 #include "BLI_listbase.h"
50 #include "BLI_fnmatch.h"
51 #include "BLI_timecode.h"
52
53 #include "BLF_api.h"
54 #include "BLT_translation.h"
55
56 #include "BKE_colorband.h"
57 #include "BKE_colortools.h"
58 #include "BKE_context.h"
59 #include "BKE_global.h"
60 #include "BKE_idcode.h"
61 #include "BKE_idprop.h"
62 #include "BKE_layer.h"
63 #include "BKE_library.h"
64 #include "BKE_linestyle.h"
65 #include "BKE_main.h"
66 #include "BKE_modifier.h"
67 #include "BKE_object.h"
68 #include "BKE_packedFile.h"
69 #include "BKE_particle.h"
70 #include "BKE_paint.h"
71 #include "BKE_report.h"
72 #include "BKE_sca.h"
73 #include "BKE_screen.h"
74
75 #include "DEG_depsgraph.h"
76 #include "DEG_depsgraph_build.h"
77
78 #include "ED_screen.h"
79 #include "ED_object.h"
80 #include "ED_render.h"
81 #include "ED_util.h"
82
83 #include "RNA_access.h"
84
85 #include "WM_api.h"
86 #include "WM_types.h"
87
88 #include "UI_interface.h"
89 #include "UI_interface_icons.h"
90 #include "interface_intern.h"
91
92 #include "PIL_time.h"
93
94
95 // #define USE_OP_RESET_BUT  // we may want to make this optional, disable for now.
96
97 /* defines for templateID/TemplateSearch */
98 #define TEMPLATE_SEARCH_TEXTBUT_WIDTH  (UI_UNIT_X * 6)
99 #define TEMPLATE_SEARCH_TEXTBUT_HEIGHT  UI_UNIT_Y
100
101
102 void UI_template_fix_linking(void)
103 {
104 }
105
106 /**
107  * Add a block button for the search menu for templateID and templateSearch.
108  */
109 static void template_add_button_search_menu(
110         const bContext *C, uiLayout *layout, uiBlock *block,
111         PointerRNA *ptr, PropertyRNA *prop,
112         uiBlockCreateFunc block_func, void *block_argN, const char * const tip,
113         const bool use_previews, const bool editable)
114 {
115         PointerRNA active_ptr = RNA_property_pointer_get(ptr, prop);
116         ID *id = (active_ptr.data && RNA_struct_is_ID(active_ptr.type)) ? active_ptr.data : NULL;
117         const ID *idfrom = ptr->id.data;
118         const StructRNA *type = active_ptr.type ? active_ptr.type : RNA_property_pointer_type(ptr, prop);
119         uiBut *but;
120
121         if (use_previews) {
122                 ARegion *region = CTX_wm_region(C);
123                 const bool use_big_size = (region->regiontype != RGN_TYPE_HEADER); /* silly check, could be more generic */
124                 /* Ugly exception for screens here, drawing their preview in icon size looks ugly/useless */
125                 const bool use_preview_icon = use_big_size || (id && (GS(id->name) != ID_SCR));
126                 const short width = UI_UNIT_X * (use_big_size ? 6 : 1.6f);
127                 const short height = UI_UNIT_Y * (use_big_size ? 6 : 1);
128
129                 but = uiDefBlockButN(block, block_func, block_argN, "", 0, 0, width, height, tip);
130                 if (use_preview_icon) {
131                         int icon = id ? ui_id_icon_get(C, id, use_big_size) : RNA_struct_ui_icon(type);
132                         ui_def_but_icon(but, icon, UI_HAS_ICON | UI_BUT_ICON_PREVIEW);
133                 }
134                 else {
135                         ui_def_but_icon(but, RNA_struct_ui_icon(type), UI_HAS_ICON);
136                         UI_but_drawflag_enable(but, UI_BUT_ICON_LEFT);
137                 }
138
139                 if ((idfrom && idfrom->lib) || !editable)
140                         UI_but_flag_enable(but, UI_BUT_DISABLED);
141                 if (use_big_size) {
142                         uiLayoutRow(layout, true);
143                 }
144         }
145         else {
146                 but = uiDefBlockButN(block, block_func, block_argN, "", 0, 0, UI_UNIT_X * 1.6, UI_UNIT_Y, tip);
147                 ui_def_but_icon(but, RNA_struct_ui_icon(type), UI_HAS_ICON);
148                 if (id) {
149                         /* default dragging of icon for id browse buttons */
150                         UI_but_drag_set_id(but, id);
151                 }
152                 UI_but_drawflag_enable(but, UI_BUT_ICON_LEFT);
153
154                 if ((idfrom && idfrom->lib) || !editable)
155                         UI_but_flag_enable(but, UI_BUT_DISABLED);
156         }
157 }
158
159 static uiBlock *template_common_search_menu(
160         const bContext *C, ARegion *region,
161         uiButSearchFunc search_func, void *search_arg,
162         uiButHandleFunc handle_func, void *active_item,
163         const int preview_rows, const int preview_cols)
164 {
165         static char search[256];
166         wmWindow *win = CTX_wm_window(C);
167         uiBlock *block;
168         uiBut *but;
169
170         /* clear initial search string, then all items show */
171         search[0] = 0;
172
173         block = UI_block_begin(C, region, "_popup", UI_EMBOSS);
174         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_SEARCH_MENU);
175
176         /* preview thumbnails */
177         if (preview_rows > 0 && preview_cols > 0) {
178                 const int w = 4 * U.widget_unit * preview_cols;
179                 const int h = 5 * U.widget_unit * preview_rows;
180
181                 /* fake button, it holds space for search items */
182                 uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 26, w, h, NULL, 0, 0, 0, 0, NULL);
183
184                 but = uiDefSearchBut(
185                         block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 0, w, UI_UNIT_Y,
186                         preview_rows, preview_cols, "");
187         }
188         /* list view */
189         else {
190                 const int searchbox_width  = UI_searchbox_size_x();
191                 const int searchbox_height = UI_searchbox_size_y();
192
193                 /* fake button, it holds space for search items */
194                 uiDefBut(
195                         block, UI_BTYPE_LABEL, 0, "", 10, 15, searchbox_width, searchbox_height,
196                         NULL, 0, 0, 0, 0, NULL);
197                 but = uiDefSearchBut(
198                         block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 0,
199                         searchbox_width, UI_UNIT_Y - 1, 0, 0, "");
200         }
201         UI_but_func_search_set(
202                 but, ui_searchbox_create_generic, search_func,
203                 search_arg, handle_func, active_item);
204
205
206         UI_block_bounds_set_normal(block, 0.3f * U.widget_unit);
207         UI_block_direction_set(block, UI_DIR_DOWN);
208
209         /* give search-field focus */
210         UI_but_focus_on_enter_event(win, but);
211         /* this type of search menu requires undo */
212         but->flag |= UI_BUT_UNDO;
213
214         return block;
215 }
216
217 /********************** Header Template *************************/
218
219 void uiTemplateHeader(uiLayout *layout, bContext *C)
220 {
221         uiBlock *block;
222
223         block = uiLayoutAbsoluteBlock(layout);
224         ED_area_header_switchbutton(C, block, 0);
225 }
226
227 /********************** Search Callbacks *************************/
228
229 typedef struct TemplateID {
230         PointerRNA ptr;
231         PropertyRNA *prop;
232
233         ListBase *idlb;
234         int prv_rows, prv_cols;
235         bool preview;
236 } TemplateID;
237
238 /* Search browse menu, assign  */
239 static void id_search_call_cb(bContext *C, void *arg_template, void *item)
240 {
241         TemplateID *template = (TemplateID *)arg_template;
242
243         /* ID */
244         if (item) {
245                 PointerRNA idptr;
246
247                 RNA_id_pointer_create(item, &idptr);
248                 RNA_property_pointer_set(&template->ptr, template->prop, idptr);
249                 RNA_property_update(C, &template->ptr, template->prop);
250         }
251 }
252
253 /* ID Search browse menu, do the search */
254 static void id_search_cb(const bContext *C, void *arg_template, const char *str, uiSearchItems *items)
255 {
256         TemplateID *template = (TemplateID *)arg_template;
257         ListBase *lb = template->idlb;
258         ID *id, *id_from = template->ptr.id.data;
259         int iconid;
260         int flag = RNA_property_flag(template->prop);
261
262         /* ID listbase */
263         for (id = lb->first; id; id = id->next) {
264                 if (!((flag & PROP_ID_SELF_CHECK) && id == id_from)) {
265
266                         /* use filter */
267                         if (RNA_property_type(template->prop) == PROP_POINTER) {
268                                 PointerRNA ptr;
269                                 RNA_id_pointer_create(id, &ptr);
270                                 if (RNA_property_pointer_poll(&template->ptr, template->prop, &ptr) == 0)
271                                         continue;
272                         }
273
274                         /* hide dot-datablocks, but only if filter does not force it visible */
275                         if (U.uiflag & USER_HIDE_DOT)
276                                 if ((id->name[2] == '.') && (str[0] != '.'))
277                                         continue;
278
279                         if (*str == '\0' || BLI_strcasestr(id->name + 2, str)) {
280                                 /* +1 is needed because BKE_id_ui_prefix used 3 letter prefix
281                                  * followed by ID_NAME-2 characters from id->name
282                                  */
283                                 char name_ui[MAX_ID_NAME + 1];
284                                 BKE_id_ui_prefix(name_ui, id);
285
286                                 iconid = ui_id_icon_get(C, id, template->preview);
287
288                                 if (false == UI_search_item_add(items, name_ui, id, iconid))
289                                         break;
290                         }
291                 }
292         }
293 }
294
295 /* ID Search browse menu, open */
296 static uiBlock *id_search_menu(bContext *C, ARegion *ar, void *arg_litem)
297 {
298         static TemplateID template;
299         PointerRNA active_item_ptr;
300
301         /* arg_litem is malloced, can be freed by parent button */
302         template = *((TemplateID *)arg_litem);
303         active_item_ptr = RNA_property_pointer_get(&template.ptr, template.prop);
304
305         return template_common_search_menu(
306                        C, ar, id_search_cb, &template, id_search_call_cb, active_item_ptr.data,
307                        template.prv_rows, template.prv_cols);
308 }
309
310 /************************ ID Template ***************************/
311 /* This is for browsing and editing the ID-blocks used */
312
313 /* for new/open operators */
314 void UI_context_active_but_prop_get_templateID(
315         bContext *C,
316         PointerRNA *r_ptr, PropertyRNA **r_prop)
317 {
318         TemplateID *template;
319         ARegion *ar = CTX_wm_region(C);
320         uiBlock *block;
321         uiBut *but;
322
323         memset(r_ptr, 0, sizeof(*r_ptr));
324         *r_prop = NULL;
325
326         if (!ar)
327                 return;
328
329         for (block = ar->uiblocks.first; block; block = block->next) {
330                 for (but = block->buttons.first; but; but = but->next) {
331                         /* find the button before the active one */
332                         if ((but->flag & (UI_BUT_LAST_ACTIVE | UI_ACTIVE))) {
333                                 if (but->func_argN) {
334                                         template = but->func_argN;
335                                         *r_ptr = template->ptr;
336                                         *r_prop = template->prop;
337                                         return;
338                                 }
339                         }
340                 }
341         }
342 }
343
344
345 static void template_id_cb(bContext *C, void *arg_litem, void *arg_event)
346 {
347         TemplateID *template = (TemplateID *)arg_litem;
348         PointerRNA idptr = RNA_property_pointer_get(&template->ptr, template->prop);
349         ID *id = idptr.data;
350         int event = GET_INT_FROM_POINTER(arg_event);
351         
352         switch (event) {
353                 case UI_ID_BROWSE:
354                 case UI_ID_PIN:
355                         RNA_warning("warning, id event %d shouldnt come here", event);
356                         break;
357                 case UI_ID_OPEN:
358                 case UI_ID_ADD_NEW:
359                         /* these call UI_context_active_but_prop_get_templateID */
360                         break;
361                 case UI_ID_DELETE:
362                         memset(&idptr, 0, sizeof(idptr));
363                         RNA_property_pointer_set(&template->ptr, template->prop, idptr);
364                         RNA_property_update(C, &template->ptr, template->prop);
365
366                         if (id && CTX_wm_window(C)->eventstate->shift) {
367                                 /* only way to force-remove data (on save) */
368                                 id_fake_user_clear(id);
369                                 id->us = 0;
370                         }
371
372                         break;
373                 case UI_ID_FAKE_USER:
374                         if (id) {
375                                 if (id->flag & LIB_FAKEUSER) id_us_plus(id);
376                                 else id_us_min(id);
377                         }
378                         else {
379                                 return;
380                         }
381                         break;
382                 case UI_ID_LOCAL:
383                         if (id) {
384                                 Main *bmain = CTX_data_main(C);
385                                 if (id_make_local(bmain, id, false, false)) {
386                                         BKE_main_id_clear_newpoins(bmain);
387
388                                         /* reassign to get get proper updates/notifiers */
389                                         idptr = RNA_property_pointer_get(&template->ptr, template->prop);
390                                         RNA_property_pointer_set(&template->ptr, template->prop, idptr);
391                                         RNA_property_update(C, &template->ptr, template->prop);
392                                 }
393                         }
394                         break;
395                 case UI_ID_ALONE:
396                         if (id) {
397                                 const bool do_scene_obj = (GS(id->name) == ID_OB) &&
398                                                           (template->ptr.type == &RNA_SceneObjects);
399
400                                 /* make copy */
401                                 if (do_scene_obj) {
402                                         Main *bmain = CTX_data_main(C);
403                                         Scene *scene = CTX_data_scene(C);
404                                         ED_object_single_user(bmain, scene, (struct Object *)id);
405                                         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
406                                         DEG_relations_tag_update(bmain);
407                                 }
408                                 else {
409                                         if (id) {
410                                                 Main *bmain = CTX_data_main(C);
411                                                 id_single_user(C, id, &template->ptr, template->prop);
412                                                 DEG_relations_tag_update(bmain);
413                                         }
414                                 }
415                         }
416                         break;
417 #if 0
418                 case UI_ID_AUTO_NAME:
419                         break;
420 #endif
421         }
422 }
423
424 static const char *template_id_browse_tip(const StructRNA *type)
425 {
426         if (type) {
427                 switch (RNA_type_to_ID_code(type)) {
428                         case ID_SCE: return N_("Browse Scene to be linked");
429                         case ID_OB:  return N_("Browse Object to be linked");
430                         case ID_ME:  return N_("Browse Mesh Data to be linked");
431                         case ID_CU:  return N_("Browse Curve Data to be linked");
432                         case ID_MB:  return N_("Browse Metaball Data to be linked");
433                         case ID_MA:  return N_("Browse Material to be linked");
434                         case ID_TE:  return N_("Browse Texture to be linked");
435                         case ID_IM:  return N_("Browse Image to be linked");
436                         case ID_LS:  return N_("Browse Line Style Data to be linked");
437                         case ID_LT:  return N_("Browse Lattice Data to be linked");
438                         case ID_LA:  return N_("Browse Lamp Data to be linked");
439                         case ID_CA:  return N_("Browse Camera Data to be linked");
440                         case ID_WO:  return N_("Browse World Settings to be linked");
441                         case ID_SCR: return N_("Choose Screen layout");
442                         case ID_TXT: return N_("Browse Text to be linked");
443                         case ID_SPK: return N_("Browse Speaker Data to be linked");
444                         case ID_SO:  return N_("Browse Sound to be linked");
445                         case ID_AR:  return N_("Browse Armature data to be linked");
446                         case ID_AC:  return N_("Browse Action to be linked");
447                         case ID_NT:  return N_("Browse Node Tree to be linked");
448                         case ID_BR:  return N_("Browse Brush to be linked");
449                         case ID_PA:  return N_("Browse Particle Settings to be linked");
450                         case ID_GD:  return N_("Browse Grease Pencil Data to be linked");
451                         case ID_MC:  return N_("Browse Movie Clip to be linked");
452                         case ID_MSK: return N_("Browse Mask to be linked");
453                         case ID_PAL: return N_("Browse Palette Data to be linked");
454                         case ID_PC:  return N_("Browse Paint Curve Data to be linked");
455                         case ID_CF:  return N_("Browse Cache Files to be linked");
456                         case ID_WS:  return N_("Browse Workspace to be linked");
457                         case ID_LP:  return N_("Browse LightProbe to be linked");
458                 }
459         }
460         return N_("Browse ID data to be linked");
461 }
462
463 /**
464  * \return a type-based i18n context, needed e.g. by "New" button.
465  * In most languages, this adjective takes different form based on gender of type name...
466  */
467 #ifdef WITH_INTERNATIONAL
468 static const char *template_id_context(StructRNA *type)
469 {
470         if (type) {
471                 return BKE_idcode_to_translation_context(RNA_type_to_ID_code(type));
472         }
473         return BLT_I18NCONTEXT_DEFAULT;
474 }
475 #endif
476
477 static void template_ID(
478         bContext *C, uiLayout *layout, TemplateID *template, StructRNA *type, short idcode, int flag,
479         const char *newop, const char *openop, const char *unlinkop)
480 {
481         uiBut *but;
482         uiBlock *block;
483         PointerRNA idptr;
484         // ListBase *lb; // UNUSED
485         ID *id, *idfrom;
486         const bool editable = RNA_property_editable(&template->ptr, template->prop);
487         const bool use_previews = template->preview = (flag & UI_ID_PREVIEWS) != 0;
488
489         idptr = RNA_property_pointer_get(&template->ptr, template->prop);
490         id = idptr.data;
491         idfrom = template->ptr.id.data;
492         // lb = template->idlb;
493
494         block = uiLayoutGetBlock(layout);
495         UI_block_align_begin(block);
496
497         if (idptr.type)
498                 type = idptr.type;
499
500         if (flag & UI_ID_BROWSE) {
501                 template_add_button_search_menu(
502                         C, layout, block, &template->ptr, template->prop,
503                         id_search_menu, MEM_dupallocN(template), TIP_(template_id_browse_tip(type)),
504                         use_previews, editable);
505         }
506
507         /* text button with name */
508         if (id) {
509                 char name[UI_MAX_NAME_STR];
510                 const bool user_alert = (id->us <= 0);
511
512                 //text_idbutton(id, name);
513                 name[0] = '\0';
514                 but = uiDefButR(
515                         block, UI_BTYPE_TEXT, 0, name, 0, 0, TEMPLATE_SEARCH_TEXTBUT_WIDTH, TEMPLATE_SEARCH_TEXTBUT_HEIGHT,
516                         &idptr, "name", -1, 0, 0, -1, -1, RNA_struct_ui_description(type));
517                 UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_RENAME));
518                 if (user_alert) UI_but_flag_enable(but, UI_BUT_REDALERT);
519
520                 if (id->lib) {
521                         if (id->tag & LIB_TAG_INDIRECT) {
522                                 but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_LIBRARY_DATA_INDIRECT, 0, 0, UI_UNIT_X, UI_UNIT_Y,
523                                                    NULL, 0, 0, 0, 0, TIP_("Indirect library data-block, cannot change"));
524                                 UI_but_flag_enable(but, UI_BUT_DISABLED);
525                         }
526                         else {
527                                 but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_LIBRARY_DATA_DIRECT, 0, 0, UI_UNIT_X, UI_UNIT_Y,
528                                                    NULL, 0, 0, 0, 0, TIP_("Direct linked library data-block, click to make local"));
529                                 if (!id_make_local(CTX_data_main(C), id, true /* test */, false) || (idfrom && idfrom->lib))
530                                         UI_but_flag_enable(but, UI_BUT_DISABLED);
531                         }
532
533                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_LOCAL));
534                 }
535
536                 if (id->us > 1) {
537                         char numstr[32];
538                         short numstr_len;
539
540                         numstr_len = BLI_snprintf(numstr, sizeof(numstr), "%d", id->us);
541
542                         but = uiDefBut(block, UI_BTYPE_BUT, 0, numstr, 0, 0,
543                                        numstr_len * 0.2f * UI_UNIT_X + UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0,
544                                        TIP_("Display number of users of this data (click to make a single-user copy)"));
545                         but->flag |= UI_BUT_UNDO;
546
547                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ALONE));
548                         if (/* test only */
549                             (id_copy(CTX_data_main(C), id, NULL, true) == false) ||
550                             (idfrom && idfrom->lib) ||
551                             (!editable) ||
552                             /* object in editmode - don't change data */
553                             (idfrom && GS(idfrom->name) == ID_OB && (((Object *)idfrom)->mode & OB_MODE_EDIT)))
554                         {
555                                 UI_but_flag_enable(but, UI_BUT_DISABLED);
556                         }
557                 }
558         
559                 if (user_alert) UI_but_flag_enable(but, UI_BUT_REDALERT);
560                 
561                 if (id->lib == NULL && !(ELEM(GS(id->name), ID_GR, ID_SCE, ID_SCR, ID_TXT, ID_OB, ID_WS))) {
562                         uiDefButR(block, UI_BTYPE_TOGGLE, 0, "F", 0, 0, UI_UNIT_X, UI_UNIT_Y, &idptr, "use_fake_user", -1, 0, 0, -1, -1, NULL);
563                 }
564         }
565         
566         if (flag & UI_ID_ADD_NEW) {
567                 int w = id ? UI_UNIT_X : (flag & UI_ID_OPEN) ? UI_UNIT_X * 3 : UI_UNIT_X * 6;
568                 
569                 /* i18n markup, does nothing! */
570                 BLT_I18N_MSGID_MULTI_CTXT("New", BLT_I18NCONTEXT_DEFAULT,
571                                                  BLT_I18NCONTEXT_ID_SCENE,
572                                                  BLT_I18NCONTEXT_ID_OBJECT,
573                                                  BLT_I18NCONTEXT_ID_MESH,
574                                                  BLT_I18NCONTEXT_ID_CURVE,
575                                                  BLT_I18NCONTEXT_ID_METABALL,
576                                                  BLT_I18NCONTEXT_ID_MATERIAL,
577                                                  BLT_I18NCONTEXT_ID_TEXTURE,
578                                                  BLT_I18NCONTEXT_ID_IMAGE,
579                                                  BLT_I18NCONTEXT_ID_LATTICE,
580                                                  BLT_I18NCONTEXT_ID_LAMP,
581                                                  BLT_I18NCONTEXT_ID_CAMERA,
582                                                  BLT_I18NCONTEXT_ID_WORLD,
583                                                  BLT_I18NCONTEXT_ID_SCREEN,
584                                                  BLT_I18NCONTEXT_ID_TEXT,
585                 );
586                 BLT_I18N_MSGID_MULTI_CTXT("New", BLT_I18NCONTEXT_ID_SPEAKER,
587                                                  BLT_I18NCONTEXT_ID_SOUND,
588                                                  BLT_I18NCONTEXT_ID_ARMATURE,
589                                                  BLT_I18NCONTEXT_ID_ACTION,
590                                                  BLT_I18NCONTEXT_ID_NODETREE,
591                                                  BLT_I18NCONTEXT_ID_BRUSH,
592                                                  BLT_I18NCONTEXT_ID_PARTICLESETTINGS,
593                                                  BLT_I18NCONTEXT_ID_GPENCIL,
594                                                  BLT_I18NCONTEXT_ID_FREESTYLELINESTYLE,
595                                                  BLT_I18NCONTEXT_ID_WORKSPACE,
596                                                  BLT_I18NCONTEXT_ID_LIGHTPROBE,
597                 );
598                 
599                 if (newop) {
600                         but = uiDefIconTextButO(block, UI_BTYPE_BUT, newop, WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN,
601                                                 (id) ? "" : CTX_IFACE_(template_id_context(type), "New"), 0, 0, w, UI_UNIT_Y, NULL);
602                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ADD_NEW));
603                 }
604                 else {
605                         but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, (id) ? "" : CTX_IFACE_(template_id_context(type), "New"),
606                                                0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
607                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ADD_NEW));
608                 }
609
610                 if ((idfrom && idfrom->lib) || !editable)
611                         UI_but_flag_enable(but, UI_BUT_DISABLED);
612         }
613
614         /* Due to space limit in UI - skip the "open" icon for packed data, and allow to unpack.
615          * Only for images, sound and fonts */
616         if (id && BKE_pack_check(id)) {
617                 but = uiDefIconButO(block, UI_BTYPE_BUT, "FILE_OT_unpack_item", WM_OP_INVOKE_REGION_WIN, ICON_PACKAGE, 0, 0,
618                                     UI_UNIT_X, UI_UNIT_Y, TIP_("Packed File, click to unpack"));
619                 UI_but_operator_ptr_get(but);
620                 
621                 RNA_string_set(but->opptr, "id_name", id->name + 2);
622                 RNA_int_set(but->opptr, "id_type", GS(id->name));
623                 
624         }
625         else if (flag & UI_ID_OPEN) {
626                 int w = id ? UI_UNIT_X : (flag & UI_ID_ADD_NEW) ? UI_UNIT_X * 3 : UI_UNIT_X * 6;
627                 
628                 if (openop) {
629                         but = uiDefIconTextButO(block, UI_BTYPE_BUT, openop, WM_OP_INVOKE_DEFAULT, ICON_FILESEL, (id) ? "" : IFACE_("Open"),
630                                                 0, 0, w, UI_UNIT_Y, NULL);
631                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_OPEN));
632                 }
633                 else {
634                         but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_FILESEL, (id) ? "" : IFACE_("Open"), 0, 0, w, UI_UNIT_Y,
635                                                NULL, 0, 0, 0, 0, NULL);
636                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_OPEN));
637                 }
638
639                 if ((idfrom && idfrom->lib) || !editable)
640                         UI_but_flag_enable(but, UI_BUT_DISABLED);
641         }
642         
643         /* delete button */
644         /* don't use RNA_property_is_unlink here */
645         if (id && (flag & UI_ID_DELETE)) {
646                 /* allow unlink if 'unlinkop' is passed, even when 'PROP_NEVER_UNLINK' is set */
647                 but = NULL;
648
649                 if (unlinkop) {
650                         but = uiDefIconButO(block, UI_BTYPE_BUT, unlinkop, WM_OP_INVOKE_REGION_WIN, ICON_X, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
651                         /* so we can access the template from operators, font unlinking needs this */
652                         UI_but_funcN_set(but, NULL, MEM_dupallocN(template), NULL);
653                 }
654                 else {
655                         if ((RNA_property_flag(template->prop) & PROP_NEVER_UNLINK) == 0) {
656                                 but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_X, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0,
657                                                    TIP_("Unlink data-block "
658                                                         "(Shift + Click to set users to zero, data will then not be saved)"));
659                                 UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_DELETE));
660
661                                 if (RNA_property_flag(template->prop) & PROP_NEVER_NULL) {
662                                         UI_but_flag_enable(but, UI_BUT_DISABLED);
663                                 }
664                         }
665                 }
666
667                 if (but) {
668                         if ((idfrom && idfrom->lib) || !editable) {
669                                 UI_but_flag_enable(but, UI_BUT_DISABLED);
670                         }
671                 }
672         }
673
674         if (idcode == ID_TE)
675                 uiTemplateTextureShow(layout, C, &template->ptr, template->prop);
676         
677         UI_block_align_end(block);
678 }
679
680 static void ui_template_id(
681         uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
682         const char *openop, const char *unlinkop, int flag, int prv_rows, int prv_cols)
683 {
684         TemplateID *template;
685         PropertyRNA *prop;
686         StructRNA *type;
687         short idcode;
688
689         prop = RNA_struct_find_property(ptr, propname);
690
691         if (!prop || RNA_property_type(prop) != PROP_POINTER) {
692                 RNA_warning("pointer property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
693                 return;
694         }
695
696         template = MEM_callocN(sizeof(TemplateID), "TemplateID");
697         template->ptr = *ptr;
698         template->prop = prop;
699         template->prv_rows = prv_rows;
700         template->prv_cols = prv_cols;
701
702         if (newop)
703                 flag |= UI_ID_ADD_NEW;
704         if (openop)
705                 flag |= UI_ID_OPEN;
706
707         type = RNA_property_pointer_type(ptr, prop);
708         idcode = RNA_type_to_ID_code(type);
709         template->idlb = which_libbase(CTX_data_main(C), idcode);
710         
711         /* create UI elements for this template
712          *      - template_ID makes a copy of the template data and assigns it to the relevant buttons
713          */
714         if (template->idlb) {
715                 uiLayoutRow(layout, true);
716                 template_ID(C, layout, template, type, idcode, flag, newop, openop, unlinkop);
717         }
718
719         MEM_freeN(template);
720 }
721
722 void uiTemplateID(
723         uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
724         const char *openop, const char *unlinkop)
725 {
726         ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop,
727                        UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE, 0, 0);
728 }
729
730 void uiTemplateIDBrowse(
731         uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
732         const char *openop, const char *unlinkop)
733 {
734         ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop, UI_ID_BROWSE | UI_ID_RENAME, 0, 0);
735 }
736
737 void uiTemplateIDPreview(
738         uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
739         const char *openop, const char *unlinkop, int rows, int cols)
740 {
741         ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop,
742                        UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE | UI_ID_PREVIEWS, rows, cols);
743 }
744
745 /************************ ID Chooser Template ***************************/
746
747 /**
748  * This is for selecting the type of ID-block to use, and then from the relevant type choosing the block to use
749  *
750  * - propname: property identifier for property that ID-pointer gets stored to
751  * - proptypename: property identifier for property used to determine the type of ID-pointer that can be used
752  */
753 void uiTemplateAnyID(
754         uiLayout *layout, PointerRNA *ptr, const char *propname, const char *proptypename,
755         const char *text)
756 {
757         PropertyRNA *propID, *propType;
758         uiLayout *split, *row, *sub;
759         
760         /* get properties... */
761         propID = RNA_struct_find_property(ptr, propname);
762         propType = RNA_struct_find_property(ptr, proptypename);
763
764         if (!propID || RNA_property_type(propID) != PROP_POINTER) {
765                 RNA_warning("pointer property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
766                 return;
767         }
768         if (!propType || RNA_property_type(propType) != PROP_ENUM) {
769                 RNA_warning("pointer-type property not found: %s.%s", RNA_struct_identifier(ptr->type), proptypename);
770                 return;
771         }
772         
773         /* Start drawing UI Elements using standard defines */
774         split = uiLayoutSplit(layout, 0.33f, false);  /* NOTE: split amount here needs to be synced with normal labels */
775         
776         /* FIRST PART ................................................ */
777         row = uiLayoutRow(split, false);
778         
779         /* Label - either use the provided text, or will become "ID-Block:" */
780         if (text) {
781                 if (text[0])
782                         uiItemL(row, text, ICON_NONE);
783         }
784         else {
785                 uiItemL(row, IFACE_("ID-Block:"), ICON_NONE);
786         }
787         
788         /* SECOND PART ................................................ */
789         row = uiLayoutRow(split, true);
790         
791         /* ID-Type Selector - just have a menu of icons */
792         sub = uiLayoutRow(row, true);                     /* HACK: special group just for the enum, otherwise we */
793         uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);  /*       we get ugly layout with text included too...  */
794         
795         uiItemFullR(sub, ptr, propType, 0, 0, UI_ITEM_R_ICON_ONLY, "", ICON_NONE);
796         
797         /* ID-Block Selector - just use pointer widget... */
798         sub = uiLayoutRow(row, true);                       /* HACK: special group to counteract the effects of the previous */
799         uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_EXPAND);  /*       enum, which now pushes everything too far right         */
800         
801         uiItemFullR(sub, ptr, propID, 0, 0, 0, "", ICON_NONE);
802 }
803
804 /********************* Search Template ********************/
805
806 typedef struct TemplateSearch {
807         uiRNACollectionSearch search_data;
808
809         bool use_previews;
810         int preview_rows, preview_cols;
811 } TemplateSearch;
812
813 static void template_search_handle_cb(bContext *C, void *arg_template, void *item)
814 {
815         TemplateSearch *template_search = arg_template;
816         uiRNACollectionSearch *coll_search = &template_search->search_data;
817         StructRNA *type = RNA_property_pointer_type(&coll_search->target_ptr, coll_search->target_prop);
818         PointerRNA item_ptr;
819
820         RNA_pointer_create(NULL, type, item, &item_ptr);
821         RNA_property_pointer_set(&coll_search->target_ptr, coll_search->target_prop, item_ptr);
822         RNA_property_update(C, &coll_search->target_ptr, coll_search->target_prop);
823 }
824
825 static uiBlock *template_search_menu(bContext *C, ARegion *region, void *arg_template)
826 {
827         static TemplateSearch template_search;
828         PointerRNA active_ptr;
829
830         /* arg_template is malloced, can be freed by parent button */
831         template_search = *((TemplateSearch *)arg_template);
832         active_ptr = RNA_property_pointer_get(&template_search.search_data.target_ptr,
833                                               template_search.search_data.target_prop);
834
835         return template_common_search_menu(
836                        C, region, ui_rna_collection_search_cb, &template_search,
837                        template_search_handle_cb, active_ptr.data,
838                        template_search.preview_rows, template_search.preview_cols);
839 }
840
841 static void template_search_add_button_searchmenu(
842         const bContext *C, uiLayout *layout, uiBlock *block,
843         TemplateSearch *template_search, const bool editable)
844 {
845         const char *ui_description = RNA_property_ui_description(template_search->search_data.target_prop);
846
847         template_add_button_search_menu(
848                 C, layout, block,
849                 &template_search->search_data.target_ptr, template_search->search_data.target_prop,
850                 template_search_menu, MEM_dupallocN(template_search), ui_description,
851                 template_search->use_previews, editable);
852 }
853
854 static void template_search_add_button_name(
855         uiBlock *block, PointerRNA *active_ptr, const StructRNA *type)
856 {
857         uiDefAutoButR(
858                 block, active_ptr, RNA_struct_name_property(type), 0, "", ICON_NONE,
859                 0, 0, TEMPLATE_SEARCH_TEXTBUT_WIDTH, TEMPLATE_SEARCH_TEXTBUT_HEIGHT);
860 }
861
862 static void template_search_add_button_operator(
863         uiBlock *block, const char * const operator_name,
864         const int opcontext, const int icon, const bool editable)
865 {
866         if (!operator_name) {
867                 return;
868         }
869
870         uiBut *but = uiDefIconButO(
871                 block, UI_BTYPE_BUT, operator_name, opcontext, icon,
872                 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
873
874         if (!editable) {
875                 UI_but_drawflag_enable(but, UI_BUT_DISABLED);
876         }
877 }
878
879 static void template_search_buttons(
880         const bContext *C, uiLayout *layout, TemplateSearch *template_search,
881         const char *newop, const char *unlinkop)
882 {
883         uiBlock *block = uiLayoutGetBlock(layout);
884         uiRNACollectionSearch *search_data = &template_search->search_data;
885         StructRNA *type = RNA_property_pointer_type(&search_data->target_ptr, search_data->target_prop);
886         const bool editable = RNA_property_editable(&search_data->target_ptr, search_data->target_prop);
887         PointerRNA active_ptr = RNA_property_pointer_get(&search_data->target_ptr, search_data->target_prop);
888
889         if (active_ptr.type) {
890                 /* can only get correct type when there is an active item */
891                 type = active_ptr.type;
892         }
893
894         uiLayoutRow(layout, true);
895         UI_block_align_begin(block);
896
897         template_search_add_button_searchmenu(C, layout, block, template_search, editable);
898         template_search_add_button_name(block, &active_ptr, type);
899         template_search_add_button_operator(block, newop, WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN, editable);
900         template_search_add_button_operator(block, unlinkop, WM_OP_INVOKE_REGION_WIN, ICON_X, editable);
901
902         UI_block_align_end(block);
903 }
904
905 static PropertyRNA *template_search_get_searchprop(
906         PointerRNA *targetptr, PropertyRNA *targetprop,
907         PointerRNA *searchptr, const char * const searchpropname)
908 {
909         PropertyRNA *searchprop;
910
911         if (searchptr && !searchptr->data) {
912                 searchptr = NULL;
913         }
914
915         if (!searchptr && !searchpropname) {
916                 /* both NULL means we don't use a custom rna collection to search in */
917         }
918         else if (!searchptr && searchpropname) {
919                 RNA_warning("searchpropname defined (%s) but searchptr is missing", searchpropname);
920         }
921         else if (searchptr && !searchpropname) {
922                 RNA_warning("searchptr defined (%s) but searchpropname is missing", RNA_struct_identifier(searchptr->type));
923         }
924         else if (!(searchprop = RNA_struct_find_property(searchptr, searchpropname))) {
925                 RNA_warning("search collection property not found: %s.%s",
926                             RNA_struct_identifier(searchptr->type), searchpropname);
927         }
928         else if (RNA_property_type(searchprop) != PROP_COLLECTION) {
929                 RNA_warning("search collection property is not a collection type: %s.%s",
930                             RNA_struct_identifier(searchptr->type), searchpropname);
931         }
932         /* check if searchprop has same type as targetprop */
933         else if (RNA_property_pointer_type(searchptr, searchprop) != RNA_property_pointer_type(targetptr, targetprop)) {
934                 RNA_warning("search collection items from %s.%s are not of type %s",
935                             RNA_struct_identifier(searchptr->type), searchpropname,
936                             RNA_struct_identifier(RNA_property_pointer_type(targetptr, targetprop)));
937         }
938         else {
939                 return searchprop;
940         }
941
942         return NULL;
943 }
944
945 static TemplateSearch *template_search_setup(
946         PointerRNA *ptr, const char * const propname,
947         PointerRNA *searchptr, const char * const searchpropname)
948 {
949         TemplateSearch *template_search;
950         PropertyRNA *prop, *searchprop;
951
952         prop = RNA_struct_find_property(ptr, propname);
953
954         if (!prop || RNA_property_type(prop) != PROP_POINTER) {
955                 RNA_warning("pointer property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
956                 return NULL;
957         }
958         searchprop = template_search_get_searchprop(ptr, prop, searchptr, searchpropname);
959
960         template_search = MEM_callocN(sizeof(*template_search), __func__);
961         template_search->search_data.target_ptr = *ptr;
962         template_search->search_data.target_prop = prop;
963         template_search->search_data.search_ptr = *searchptr;
964         template_search->search_data.search_prop = searchprop;
965
966         return template_search;
967 }
968
969 /**
970  * Search menu to pick an item from a collection.
971  * A version of uiTemplateID that works for non-ID types.
972  */
973 void uiTemplateSearch(
974         uiLayout *layout, bContext *C,
975         PointerRNA *ptr, const char *propname,
976         PointerRNA *searchptr, const char *searchpropname,
977         const char *newop, const char *unlinkop)
978 {
979         TemplateSearch *template_search = template_search_setup(ptr, propname, searchptr, searchpropname);
980         if (template_search != NULL) {
981                 template_search_buttons(C, layout, template_search, newop, unlinkop);
982                 MEM_freeN(template_search);
983         }
984 }
985
986 void uiTemplateSearchPreview(
987         uiLayout *layout, bContext *C,
988         PointerRNA *ptr, const char *propname,
989         PointerRNA *searchptr, const char *searchpropname,
990         const char *newop, const char *unlinkop,
991         const int rows, const int cols)
992 {
993         TemplateSearch *template_search = template_search_setup(ptr, propname, searchptr, searchpropname);
994
995         if (template_search != NULL) {
996                 template_search->use_previews = true;
997                 template_search->preview_rows = rows;
998                 template_search->preview_cols = cols;
999
1000                 template_search_buttons(C, layout, template_search, newop, unlinkop);
1001
1002                 MEM_freeN(template_search);
1003         }
1004 }
1005
1006 /********************* RNA Path Builder Template ********************/
1007
1008 /* ---------- */
1009
1010 /**
1011  * This is creating/editing RNA-Paths
1012  *
1013  * - ptr: struct which holds the path property
1014  * - propname: property identifier for property that path gets stored to
1015  * - root_ptr: struct that path gets built from
1016  */
1017 void uiTemplatePathBuilder(uiLayout *layout, PointerRNA *ptr, const char *propname, PointerRNA *UNUSED(root_ptr),
1018                            const char *text)
1019 {
1020         PropertyRNA *propPath;
1021         uiLayout *row;
1022         
1023         /* check that properties are valid */
1024         propPath = RNA_struct_find_property(ptr, propname);
1025         if (!propPath || RNA_property_type(propPath) != PROP_STRING) {
1026                 RNA_warning("path property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
1027                 return;
1028         }
1029         
1030         /* Start drawing UI Elements using standard defines */
1031         row = uiLayoutRow(layout, true);
1032         
1033         /* Path (existing string) Widget */
1034         uiItemR(row, ptr, propname, 0, text, ICON_RNA);
1035         
1036         /* TODO: attach something to this to make allow searching of nested properties to 'build' the path */
1037 }
1038
1039 /************************ Modifier Template *************************/
1040
1041 #define ERROR_LIBDATA_MESSAGE IFACE_("Can't edit external libdata")
1042
1043 static void modifiers_convertToReal(bContext *C, void *ob_v, void *md_v)
1044 {
1045         Object *ob = ob_v;
1046         ModifierData *md = md_v;
1047         ModifierData *nmd = modifier_new(md->type);
1048
1049         modifier_copyData(md, nmd);
1050         nmd->mode &= ~eModifierMode_Virtual;
1051
1052         BLI_addhead(&ob->modifiers, nmd);
1053         
1054         modifier_unique_name(&ob->modifiers, nmd);
1055
1056         ob->partype = PAROBJECT;
1057
1058         WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob);
1059         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1060
1061         ED_undo_push(C, "Modifier convert to real");
1062 }
1063
1064 static int modifier_can_delete(ModifierData *md)
1065 {
1066         /* fluid particle modifier can't be deleted here */
1067         if (md->type == eModifierType_ParticleSystem)
1068                 if (((ParticleSystemModifierData *)md)->psys->part->type == PART_FLUID)
1069                         return 0;
1070
1071         return 1;
1072 }
1073
1074 /* Check whether Modifier is a simulation or not, this is used for switching to the physics/particles context tab */
1075 static int modifier_is_simulation(ModifierData *md)
1076 {
1077         /* Physic Tab */
1078         if (ELEM(md->type, eModifierType_Cloth, eModifierType_Collision, eModifierType_Fluidsim, eModifierType_Smoke,
1079                   eModifierType_Softbody, eModifierType_Surface, eModifierType_DynamicPaint))
1080         {
1081                 return 1;
1082         }
1083         /* Particle Tab */
1084         else if (md->type == eModifierType_ParticleSystem) {
1085                 return 2;
1086         }
1087         else {
1088                 return 0;
1089         }
1090 }
1091
1092 static uiLayout *draw_modifier(
1093         uiLayout *layout, Scene *scene, Object *ob,
1094         ModifierData *md, int index, int cageIndex, int lastCageIndex)
1095 {
1096         const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1097         PointerRNA ptr;
1098         uiBut *but;
1099         uiBlock *block;
1100         uiLayout *box, *column, *row, *sub;
1101         uiLayout *result = NULL;
1102         int isVirtual = (md->mode & eModifierMode_Virtual);
1103         char str[128];
1104
1105         /* create RNA pointer */
1106         RNA_pointer_create(&ob->id, &RNA_Modifier, md, &ptr);
1107
1108         column = uiLayoutColumn(layout, true);
1109         uiLayoutSetContextPointer(column, "modifier", &ptr);
1110
1111         /* rounded header ------------------------------------------------------------------- */
1112         box = uiLayoutBox(column);
1113         
1114         if (isVirtual) {
1115                 row = uiLayoutRow(box, false);
1116                 uiLayoutSetAlignment(row, UI_LAYOUT_ALIGN_EXPAND);
1117                 block = uiLayoutGetBlock(row);
1118                 /* VIRTUAL MODIFIER */
1119                 /* XXX this is not used now, since these cannot be accessed via RNA */
1120                 BLI_snprintf(str, sizeof(str), IFACE_("%s parent deform"), md->name);
1121                 uiDefBut(block, UI_BTYPE_LABEL, 0, str, 0, 0, 185, UI_UNIT_Y, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Modifier name"));
1122                 
1123                 but = uiDefBut(block, UI_BTYPE_BUT, 0, IFACE_("Make Real"), 0, 0, 80, 16, NULL, 0.0, 0.0, 0.0, 0.0,
1124                                TIP_("Convert virtual modifier to a real modifier"));
1125                 UI_but_func_set(but, modifiers_convertToReal, ob, md);
1126         }
1127         else {
1128                 /* REAL MODIFIER */
1129                 row = uiLayoutRow(box, false);
1130                 block = uiLayoutGetBlock(row);
1131                 
1132                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1133                 /* Open/Close .................................  */
1134                 uiItemR(row, &ptr, "show_expanded", 0, "", ICON_NONE);
1135                 
1136                 /* modifier-type icon */
1137                 uiItemL(row, "", RNA_struct_ui_icon(ptr.type));
1138                 UI_block_emboss_set(block, UI_EMBOSS);
1139                 
1140                 /* modifier name */
1141                 md->scene = scene;
1142                 if (mti->isDisabled && mti->isDisabled(md, 0)) {
1143                         uiLayoutSetRedAlert(row, true);
1144                 }
1145                 uiItemR(row, &ptr, "name", 0, "", ICON_NONE);
1146                 uiLayoutSetRedAlert(row, false);
1147                 
1148                 /* mode enabling buttons */
1149                 UI_block_align_begin(block);
1150                 /* Collision and Surface are always enabled, hide buttons! */
1151                 if (((md->type != eModifierType_Collision) || !(ob->pd && ob->pd->deflect)) &&
1152                     (md->type != eModifierType_Surface) )
1153                 {
1154                         uiItemR(row, &ptr, "show_render", 0, "", ICON_NONE);
1155                         uiItemR(row, &ptr, "show_viewport", 0, "", ICON_NONE);
1156                         
1157                         if (mti->flags & eModifierTypeFlag_SupportsEditmode) {
1158                                 sub = uiLayoutRow(row, true);
1159                                 if (!(md->mode & eModifierMode_Realtime)) {
1160                                         uiLayoutSetActive(sub, false);
1161                                 }
1162                                 uiItemR(sub, &ptr, "show_in_editmode", 0, "", ICON_NONE);
1163                         }
1164                 }
1165
1166                 if (ob->type == OB_MESH) {
1167                         if (modifier_supportsCage(scene, md) && (index <= lastCageIndex)) {
1168                                 sub = uiLayoutRow(row, true);
1169                                 if (index < cageIndex || !modifier_couldBeCage(scene, md)) {
1170                                         uiLayoutSetActive(sub, false);
1171                                 }
1172                                 uiItemR(sub, &ptr, "show_on_cage", 0, "", ICON_NONE);
1173                         }
1174                 } /* tessellation point for curve-typed objects */
1175                 else if (ELEM(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
1176                         /* some modifiers could work with pre-tessellated curves only */
1177                         if (ELEM(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_MeshDeform)) {
1178                                 /* add disabled pre-tessellated button, so users could have
1179                                  * message for this modifiers */
1180                                 but = uiDefIconButBitI(block, UI_BTYPE_TOGGLE, eModifierMode_ApplyOnSpline, 0, ICON_SURFACE_DATA, 0, 0,
1181                                                        UI_UNIT_X - 2, UI_UNIT_Y, &md->mode, 0.0, 0.0, 0.0, 0.0,
1182                                                        TIP_("This modifier can only be applied on splines' points"));
1183                                 UI_but_flag_enable(but, UI_BUT_DISABLED);
1184                         }
1185                         else if (mti->type != eModifierTypeType_Constructive) {
1186                                 /* constructive modifiers tessellates curve before applying */
1187                                 uiItemR(row, &ptr, "use_apply_on_spline", 0, "", ICON_NONE);
1188                         }
1189                 }
1190
1191                 UI_block_align_end(block);
1192                 
1193                 /* Up/Down + Delete ........................... */
1194                 UI_block_align_begin(block);
1195                 uiItemO(row, "", ICON_TRIA_UP, "OBJECT_OT_modifier_move_up");
1196                 uiItemO(row, "", ICON_TRIA_DOWN, "OBJECT_OT_modifier_move_down");
1197                 UI_block_align_end(block);
1198                 
1199                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1200                 /* When Modifier is a simulation, show button to switch to context rather than the delete button. */
1201                 if (modifier_can_delete(md) &&
1202                     (!modifier_is_simulation(md) ||
1203                      STREQ(scene->view_render.engine_id, RE_engine_id_BLENDER_GAME)))
1204                 {
1205                         uiItemO(row, "", ICON_X, "OBJECT_OT_modifier_remove");
1206                 }
1207                 else if (modifier_is_simulation(md) == 1) {
1208                         uiItemStringO(row, "", ICON_BUTS, "WM_OT_properties_context_change", "context", "PHYSICS");
1209                 }
1210                 else if (modifier_is_simulation(md) == 2) {
1211                         uiItemStringO(row, "", ICON_BUTS, "WM_OT_properties_context_change", "context", "PARTICLES");
1212                 }
1213                 UI_block_emboss_set(block, UI_EMBOSS);
1214         }
1215
1216         
1217         /* modifier settings (under the header) --------------------------------------------------- */
1218         if (!isVirtual && (md->mode & eModifierMode_Expanded)) {
1219                 /* apply/convert/copy */
1220                 box = uiLayoutBox(column);
1221                 row = uiLayoutRow(box, false);
1222                 
1223                 if (!ELEM(md->type, eModifierType_Collision, eModifierType_Surface)) {
1224                         /* only here obdata, the rest of modifiers is ob level */
1225                         UI_block_lock_set(block, BKE_object_obdata_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
1226                         
1227                         if (md->type == eModifierType_ParticleSystem) {
1228                                 ParticleSystem *psys = ((ParticleSystemModifierData *)md)->psys;
1229                                 
1230                                 if (!(ob->mode & OB_MODE_PARTICLE_EDIT)) {
1231                                         if (ELEM(psys->part->ren_as, PART_DRAW_GR, PART_DRAW_OB))
1232                                                 uiItemO(row, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Convert"), ICON_NONE,
1233                                                         "OBJECT_OT_duplicates_make_real");
1234                                         else if (psys->part->ren_as == PART_DRAW_PATH && psys->pathcache)
1235                                                 uiItemO(row, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Convert"), ICON_NONE,
1236                                                         "OBJECT_OT_modifier_convert");
1237                                 }
1238                         }
1239                         else {
1240                                 uiLayoutSetOperatorContext(row, WM_OP_INVOKE_DEFAULT);
1241                                 uiItemEnumO(row, "OBJECT_OT_modifier_apply", CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Apply"),
1242                                             0, "apply_as", MODIFIER_APPLY_DATA);
1243                                 
1244                                 if (modifier_isSameTopology(md) && !modifier_isNonGeometrical(md)) {
1245                                         uiItemEnumO(row, "OBJECT_OT_modifier_apply",
1246                                                     CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Apply as Shape Key"),
1247                                                     0, "apply_as", MODIFIER_APPLY_SHAPE);
1248                                 }
1249                         }
1250                         
1251                         UI_block_lock_clear(block);
1252                         UI_block_lock_set(block, ob && ID_IS_LINKED(ob), ERROR_LIBDATA_MESSAGE);
1253                         
1254                         if (!ELEM(md->type, eModifierType_Fluidsim, eModifierType_Softbody, eModifierType_ParticleSystem,
1255                                    eModifierType_Cloth, eModifierType_Smoke))
1256                         {
1257                                 uiItemO(row, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy"), ICON_NONE,
1258                                         "OBJECT_OT_modifier_copy");
1259                         }
1260                 }
1261                 
1262                 /* result is the layout block inside the box, that we return so that modifier settings can be drawn */
1263                 result = uiLayoutColumn(box, false);
1264                 block = uiLayoutAbsoluteBlock(box);
1265         }
1266         
1267         /* error messages */
1268         if (md->error) {
1269                 box = uiLayoutBox(column);
1270                 row = uiLayoutRow(box, false);
1271                 uiItemL(row, md->error, ICON_ERROR);
1272         }
1273         
1274         return result;
1275 }
1276
1277 uiLayout *uiTemplateModifier(uiLayout *layout, bContext *C, PointerRNA *ptr)
1278 {
1279         Scene *scene = CTX_data_scene(C);
1280         Object *ob;
1281         ModifierData *md, *vmd;
1282         VirtualModifierData virtualModifierData;
1283         int i, lastCageIndex, cageIndex;
1284
1285         /* verify we have valid data */
1286         if (!RNA_struct_is_a(ptr->type, &RNA_Modifier)) {
1287                 RNA_warning("Expected modifier on object");
1288                 return NULL;
1289         }
1290
1291         ob = ptr->id.data;
1292         md = ptr->data;
1293
1294         if (!ob || !(GS(ob->id.name) == ID_OB)) {
1295                 RNA_warning("Expected modifier on object");
1296                 return NULL;
1297         }
1298         
1299         UI_block_lock_set(uiLayoutGetBlock(layout), (ob && ID_IS_LINKED(ob)), ERROR_LIBDATA_MESSAGE);
1300         
1301         /* find modifier and draw it */
1302         cageIndex = modifiers_getCageIndex(scene, ob, &lastCageIndex, 0);
1303
1304         /* XXX virtual modifiers are not accesible for python */
1305         vmd = modifiers_getVirtualModifierList(ob, &virtualModifierData);
1306
1307         for (i = 0; vmd; i++, vmd = vmd->next) {
1308                 if (md == vmd)
1309                         return draw_modifier(layout, scene, ob, md, i, cageIndex, lastCageIndex);
1310                 else if (vmd->mode & eModifierMode_Virtual)
1311                         i--;
1312         }
1313
1314         return NULL;
1315 }
1316
1317 /************************ Constraint Template *************************/
1318
1319 #include "DNA_constraint_types.h"
1320
1321 #include "BKE_action.h"
1322 #include "BKE_constraint.h"
1323
1324 #define B_CONSTRAINT_TEST           5
1325 // #define B_CONSTRAINT_CHANGETARGET   6
1326
1327 static void do_constraint_panels(bContext *C, void *ob_pt, int event)
1328 {
1329         Object *ob = (Object *)ob_pt;
1330
1331         switch (event) {
1332                 case B_CONSTRAINT_TEST:
1333                         break; /* no handling */
1334 #if 0   /* UNUSED */
1335                 case B_CONSTRAINT_CHANGETARGET:
1336                 {
1337                         Main *bmain = CTX_data_main(C);
1338                         if (ob->pose)
1339                                 BKE_pose_tag_recalc(bmain, ob->pose); /* checks & sorts pose channels */
1340                         DEG_relations_tag_update(bmain);
1341                         break;
1342                 }
1343 #endif
1344                 default:
1345                         break;
1346         }
1347
1348         /* note: RNA updates now call this, commenting else it gets called twice.
1349          * if there are problems because of this, then rna needs changed update functions.
1350          *
1351          * object_test_constraints(ob);
1352          * if (ob->pose) BKE_pose_update_constraint_flags(ob->pose); */
1353         
1354         if (ob->type == OB_ARMATURE) DEG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1355         else DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1356
1357         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1358 }
1359
1360 static void constraint_active_func(bContext *UNUSED(C), void *ob_v, void *con_v)
1361 {
1362         ED_object_constraint_set_active(ob_v, con_v);
1363 }
1364
1365 /* draw panel showing settings for a constraint */
1366 static uiLayout *draw_constraint(uiLayout *layout, Object *ob, bConstraint *con)
1367 {
1368         bPoseChannel *pchan = BKE_pose_channel_active(ob);
1369         const bConstraintTypeInfo *cti;
1370         uiBlock *block;
1371         uiLayout *result = NULL, *col, *box, *row;
1372         PointerRNA ptr;
1373         char typestr[32];
1374         short proxy_protected, xco = 0, yco = 0;
1375         // int rb_col; // UNUSED
1376
1377         /* get constraint typeinfo */
1378         cti = BKE_constraint_typeinfo_get(con);
1379         if (cti == NULL) {
1380                 /* exception for 'Null' constraint - it doesn't have constraint typeinfo! */
1381                 BLI_strncpy(typestr, (con->type == CONSTRAINT_TYPE_NULL) ? IFACE_("Null") : IFACE_("Unknown"), sizeof(typestr));
1382         }
1383         else
1384                 BLI_strncpy(typestr, IFACE_(cti->name), sizeof(typestr));
1385                 
1386         /* determine whether constraint is proxy protected or not */
1387         if (BKE_constraints_proxylocked_owner(ob, pchan))
1388                 proxy_protected = (con->flag & CONSTRAINT_PROXY_LOCAL) == 0;
1389         else
1390                 proxy_protected = 0;
1391
1392         /* unless button has own callback, it adds this callback to button */
1393         block = uiLayoutGetBlock(layout);
1394         UI_block_func_handle_set(block, do_constraint_panels, ob);
1395         UI_block_func_set(block, constraint_active_func, ob, con);
1396
1397         RNA_pointer_create(&ob->id, &RNA_Constraint, con, &ptr);
1398
1399         col = uiLayoutColumn(layout, true);
1400         uiLayoutSetContextPointer(col, "constraint", &ptr);
1401
1402         box = uiLayoutBox(col);
1403         row = uiLayoutRow(box, false);
1404         block = uiLayoutGetBlock(box);
1405
1406         /* Draw constraint header */
1407
1408         /* open/close */
1409         UI_block_emboss_set(block, UI_EMBOSS_NONE);
1410         uiItemR(row, &ptr, "show_expanded", UI_ITEM_R_ICON_ONLY, "", ICON_NONE);
1411         UI_block_emboss_set(block, UI_EMBOSS);
1412
1413         /* name */
1414         uiDefBut(block, UI_BTYPE_LABEL, B_CONSTRAINT_TEST, typestr,
1415                  xco + 0.5f * UI_UNIT_X, yco, 5 * UI_UNIT_X, 0.9f * UI_UNIT_Y, NULL, 0.0, 0.0, 0.0, 0.0, "");
1416
1417         if (con->flag & CONSTRAINT_DISABLE)
1418                 uiLayoutSetRedAlert(row, true);
1419         
1420         if (proxy_protected == 0) {
1421                 uiItemR(row, &ptr, "name", 0, "", ICON_NONE);
1422         }
1423         else
1424                 uiItemL(row, con->name, ICON_NONE);
1425         
1426         uiLayoutSetRedAlert(row, false);
1427         
1428         /* proxy-protected constraints cannot be edited, so hide up/down + close buttons */
1429         if (proxy_protected) {
1430                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1431                 
1432                 /* draw a ghost icon (for proxy) and also a lock beside it, to show that constraint is "proxy locked" */
1433                 uiDefIconBut(block, UI_BTYPE_BUT, B_CONSTRAINT_TEST, ICON_GHOST, xco + 12.2f * UI_UNIT_X, yco, 0.95f * UI_UNIT_X, 0.95f * UI_UNIT_Y,
1434                              NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Proxy Protected"));
1435                 uiDefIconBut(block, UI_BTYPE_BUT, B_CONSTRAINT_TEST, ICON_LOCKED, xco + 13.1f * UI_UNIT_X, yco, 0.95f * UI_UNIT_X, 0.95f * UI_UNIT_Y,
1436                              NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Proxy Protected"));
1437                 
1438                 UI_block_emboss_set(block, UI_EMBOSS);
1439         }
1440         else {
1441                 short prev_proxylock, show_upbut, show_downbut;
1442                 
1443                 /* Up/Down buttons: 
1444                  *      Proxy-constraints are not allowed to occur after local (non-proxy) constraints
1445                  *      as that poses problems when restoring them, so disable the "up" button where
1446                  *      it may cause this situation. 
1447                  *
1448                  *  Up/Down buttons should only be shown (or not grayed - todo) if they serve some purpose.
1449                  */
1450                 if (BKE_constraints_proxylocked_owner(ob, pchan)) {
1451                         if (con->prev) {
1452                                 prev_proxylock = (con->prev->flag & CONSTRAINT_PROXY_LOCAL) ? 0 : 1;
1453                         }
1454                         else
1455                                 prev_proxylock = 0;
1456                 }
1457                 else
1458                         prev_proxylock = 0;
1459                         
1460                 show_upbut = ((prev_proxylock == 0) && (con->prev));
1461                 show_downbut = (con->next) ? 1 : 0;
1462                 
1463                 /* enabled */
1464                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1465                 uiItemR(row, &ptr, "mute", 0, "",
1466                         (con->flag & CONSTRAINT_OFF) ? ICON_RESTRICT_VIEW_ON : ICON_RESTRICT_VIEW_OFF);
1467                 UI_block_emboss_set(block, UI_EMBOSS);
1468                 
1469                 uiLayoutSetOperatorContext(row, WM_OP_INVOKE_DEFAULT);
1470                 
1471                 /* up/down */
1472                 if (show_upbut || show_downbut) {
1473                         UI_block_align_begin(block);
1474                         if (show_upbut)
1475                                 uiItemO(row, "", ICON_TRIA_UP, "CONSTRAINT_OT_move_up");
1476                                 
1477                         if (show_downbut)
1478                                 uiItemO(row, "", ICON_TRIA_DOWN, "CONSTRAINT_OT_move_down");
1479                         UI_block_align_end(block);
1480                 }
1481                 
1482                 /* Close 'button' - emboss calls here disable drawing of 'button' behind X */
1483                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1484                 uiItemO(row, "", ICON_X, "CONSTRAINT_OT_delete");
1485                 UI_block_emboss_set(block, UI_EMBOSS);
1486         }
1487
1488         /* Set but-locks for protected settings (magic numbers are used here!) */
1489         if (proxy_protected)
1490                 UI_block_lock_set(block, true, IFACE_("Cannot edit Proxy-Protected Constraint"));
1491
1492         /* Draw constraint data */
1493         if ((con->flag & CONSTRAINT_EXPAND) == 0) {
1494                 (yco) -= 10.5f * UI_UNIT_Y;
1495         }
1496         else {
1497                 box = uiLayoutBox(col);
1498                 block = uiLayoutAbsoluteBlock(box);
1499                 result = box;
1500         }
1501
1502         /* clear any locks set up for proxies/lib-linking */
1503         UI_block_lock_clear(block);
1504
1505         return result;
1506 }
1507
1508 uiLayout *uiTemplateConstraint(uiLayout *layout, PointerRNA *ptr)
1509 {
1510         Object *ob;
1511         bConstraint *con;
1512
1513         /* verify we have valid data */
1514         if (!RNA_struct_is_a(ptr->type, &RNA_Constraint)) {
1515                 RNA_warning("Expected constraint on object");
1516                 return NULL;
1517         }
1518
1519         ob = ptr->id.data;
1520         con = ptr->data;
1521
1522         if (!ob || !(GS(ob->id.name) == ID_OB)) {
1523                 RNA_warning("Expected constraint on object");
1524                 return NULL;
1525         }
1526         
1527         UI_block_lock_set(uiLayoutGetBlock(layout), (ob && ID_IS_LINKED(ob)), ERROR_LIBDATA_MESSAGE);
1528
1529         /* hrms, the temporal constraint should not draw! */
1530         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
1531                 bKinematicConstraint *data = con->data;
1532                 if (data->flag & CONSTRAINT_IK_TEMP)
1533                         return NULL;
1534         }
1535
1536         return draw_constraint(layout, ob, con);
1537 }
1538
1539
1540 /************************* Preview Template ***************************/
1541
1542 #include "DNA_lamp_types.h"
1543 #include "DNA_material_types.h"
1544 #include "DNA_world_types.h"
1545
1546 #define B_MATPRV 1
1547
1548 static void do_preview_buttons(bContext *C, void *arg, int event)
1549 {
1550         switch (event) {
1551                 case B_MATPRV:
1552                         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING_PREVIEW, arg);
1553                         break;
1554         }
1555 }
1556
1557 void uiTemplatePreview(
1558         uiLayout *layout, bContext *C, ID *id, int show_buttons, ID *parent, MTex *slot,
1559         const char *preview_id)
1560 {
1561         uiLayout *row, *col;
1562         uiBlock *block;
1563         uiPreview *ui_preview = NULL;
1564         ARegion *ar;
1565
1566         Material *ma = NULL;
1567         Tex *tex = (Tex *)id;
1568         ID *pid, *pparent;
1569         short *pr_texture = NULL;
1570         PointerRNA material_ptr;
1571         PointerRNA texture_ptr;
1572
1573         char _preview_id[UI_MAX_NAME_STR];
1574
1575         if (id && !ELEM(GS(id->name), ID_MA, ID_TE, ID_WO, ID_LA, ID_LS)) {
1576                 RNA_warning("Expected ID of type material, texture, lamp, world or line style");
1577                 return;
1578         }
1579
1580         /* decide what to render */
1581         pid = id;
1582         pparent = NULL;
1583
1584         if (id && (GS(id->name) == ID_TE)) {
1585                 if (parent && (GS(parent->name) == ID_MA))
1586                         pr_texture = &((Material *)parent)->pr_texture;
1587                 else if (parent && (GS(parent->name) == ID_WO))
1588                         pr_texture = &((World *)parent)->pr_texture;
1589                 else if (parent && (GS(parent->name) == ID_LA))
1590                         pr_texture = &((Lamp *)parent)->pr_texture;
1591                 else if (parent && (GS(parent->name) == ID_LS))
1592                         pr_texture = &((FreestyleLineStyle *)parent)->pr_texture;
1593
1594                 if (pr_texture) {
1595                         if (*pr_texture == TEX_PR_OTHER)
1596                                 pid = parent;
1597                         else if (*pr_texture == TEX_PR_BOTH)
1598                                 pparent = parent;
1599                 }
1600         }
1601
1602         if (!preview_id || (preview_id[0] == '\0')) {
1603                 /* If no identifier given, generate one from ID type. */
1604                 BLI_snprintf(_preview_id, UI_MAX_NAME_STR, "uiPreview_%s", BKE_idcode_to_name(GS(id->name)));
1605                 preview_id = _preview_id;
1606         }
1607
1608         /* Find or add the uiPreview to the current Region. */
1609         ar = CTX_wm_region(C);
1610         ui_preview = BLI_findstring(&ar->ui_previews, preview_id, offsetof(uiPreview, preview_id));
1611
1612         if (!ui_preview) {
1613                 ui_preview = MEM_callocN(sizeof(uiPreview), "uiPreview");
1614                 BLI_strncpy(ui_preview->preview_id, preview_id, sizeof(ui_preview->preview_id));
1615                 ui_preview->height = (short)(UI_UNIT_Y * 5.6f);
1616                 BLI_addtail(&ar->ui_previews, ui_preview);
1617         }
1618
1619         if (ui_preview->height < UI_UNIT_Y) {
1620                 ui_preview->height = UI_UNIT_Y;
1621         }
1622         else if (ui_preview->height > UI_UNIT_Y * 50) {  /* Rather high upper limit, yet not insane! */
1623                 ui_preview->height = UI_UNIT_Y * 50;
1624         }
1625
1626         /* layout */
1627         block = uiLayoutGetBlock(layout);
1628         row = uiLayoutRow(layout, false);
1629         col = uiLayoutColumn(row, false);
1630         uiLayoutSetKeepAspect(col, true);
1631
1632         /* add preview */
1633         uiDefBut(block, UI_BTYPE_EXTRA, 0, "", 0, 0, UI_UNIT_X * 10, ui_preview->height, pid, 0.0, 0.0, 0, 0, "");
1634         UI_but_func_drawextra_set(block, ED_preview_draw, pparent, slot);
1635         UI_block_func_handle_set(block, do_preview_buttons, NULL);
1636
1637         uiDefIconButS(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &ui_preview->height,
1638                       UI_UNIT_Y, UI_UNIT_Y * 50.0f, 0.0f, 0.0f, "");
1639
1640         /* add buttons */
1641         if (pid && show_buttons) {
1642                 if (GS(pid->name) == ID_MA || (pparent && GS(pparent->name) == ID_MA)) {
1643                         if (GS(pid->name) == ID_MA) ma = (Material *)pid;
1644                         else ma = (Material *)pparent;
1645                         
1646                         /* Create RNA Pointer */
1647                         RNA_pointer_create(&ma->id, &RNA_Material, ma, &material_ptr);
1648
1649                         col = uiLayoutColumn(row, true);
1650                         uiLayoutSetScaleX(col, 1.5);
1651                         uiItemR(col, &material_ptr, "preview_render_type", UI_ITEM_R_EXPAND, "", ICON_NONE);
1652                 }
1653
1654                 if (pr_texture) {
1655                         /* Create RNA Pointer */
1656                         RNA_pointer_create(id, &RNA_Texture, tex, &texture_ptr);
1657                         
1658                         uiLayoutRow(layout, true);
1659                         uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Texture"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1660                                   pr_texture, 10, TEX_PR_TEXTURE, 0, 0, "");
1661                         if (GS(parent->name) == ID_MA) {
1662                                 uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Material"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1663                                           pr_texture, 10, TEX_PR_OTHER, 0, 0, "");
1664                         }
1665                         else if (GS(parent->name) == ID_LA) {
1666                                 uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Lamp"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1667                                           pr_texture, 10, TEX_PR_OTHER, 0, 0, "");
1668                         }
1669                         else if (GS(parent->name) == ID_WO) {
1670                                 uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("World"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1671                                           pr_texture, 10, TEX_PR_OTHER, 0, 0, "");
1672                         }
1673                         else if (GS(parent->name) == ID_LS) {
1674                                 uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Line Style"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1675                                           pr_texture, 10, TEX_PR_OTHER, 0, 0, "");
1676                         }
1677                         uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Both"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1678                                   pr_texture, 10, TEX_PR_BOTH, 0, 0, "");
1679                         
1680                         /* Alpha button for texture preview */
1681                         if (*pr_texture != TEX_PR_OTHER) {
1682                                 row = uiLayoutRow(layout, false);
1683                                 uiItemR(row, &texture_ptr, "use_preview_alpha", 0, NULL, ICON_NONE);
1684                         }
1685                 }
1686         }
1687 }
1688
1689 /********************** ColorRamp Template **************************/
1690
1691
1692 typedef struct RNAUpdateCb {
1693         PointerRNA ptr;
1694         PropertyRNA *prop;
1695 } RNAUpdateCb;
1696
1697 static void rna_update_cb(bContext *C, void *arg_cb, void *UNUSED(arg))
1698 {
1699         RNAUpdateCb *cb = (RNAUpdateCb *)arg_cb;
1700
1701         /* we call update here on the pointer property, this way the
1702          * owner of the curve mapping can still define it's own update
1703          * and notifier, even if the CurveMapping struct is shared. */
1704         RNA_property_update(C, &cb->ptr, cb->prop);
1705 }
1706
1707 static void colorband_add_cb(bContext *C, void *cb_v, void *coba_v)
1708 {
1709         ColorBand *coba = coba_v;
1710         float pos = 0.5f;
1711
1712         if (coba->tot > 1) {
1713                 if (coba->cur > 0) pos = (coba->data[coba->cur - 1].pos + coba->data[coba->cur].pos) * 0.5f;
1714                 else pos = (coba->data[coba->cur + 1].pos + coba->data[coba->cur].pos) * 0.5f;
1715         }
1716
1717         if (BKE_colorband_element_add(coba, pos)) {
1718                 rna_update_cb(C, cb_v, NULL);
1719                 ED_undo_push(C, "Add colorband");
1720         }
1721 }
1722
1723 static void colorband_del_cb(bContext *C, void *cb_v, void *coba_v)
1724 {
1725         ColorBand *coba = coba_v;
1726
1727         if (BKE_colorband_element_remove(coba, coba->cur)) {
1728                 ED_undo_push(C, "Delete colorband");
1729                 rna_update_cb(C, cb_v, NULL);
1730         }
1731 }
1732
1733 static void colorband_flip_cb(bContext *C, void *cb_v, void *coba_v)
1734 {
1735         CBData data_tmp[MAXCOLORBAND];
1736
1737         ColorBand *coba = coba_v;
1738         int a;
1739
1740         for (a = 0; a < coba->tot; a++) {
1741                 data_tmp[a] = coba->data[coba->tot - (a + 1)];
1742         }
1743         for (a = 0; a < coba->tot; a++) {
1744                 data_tmp[a].pos = 1.0f - data_tmp[a].pos;
1745                 coba->data[a] = data_tmp[a];
1746         }
1747
1748         /* may as well flip the cur*/
1749         coba->cur = coba->tot - (coba->cur + 1);
1750
1751         ED_undo_push(C, "Flip colorband");
1752
1753         rna_update_cb(C, cb_v, NULL);
1754 }
1755
1756 static void colorband_update_cb(bContext *UNUSED(C), void *bt_v, void *coba_v)
1757 {
1758         uiBut *bt = bt_v;
1759         ColorBand *coba = coba_v;
1760
1761         /* sneaky update here, we need to sort the colorband points to be in order,
1762          * however the RNA pointer then is wrong, so we update it */
1763         BKE_colorband_update_sort(coba);
1764         bt->rnapoin.data = coba->data + coba->cur;
1765 }
1766
1767 static void colorband_buttons_layout(
1768         uiLayout *layout, uiBlock *block, ColorBand *coba, const rctf *butr,
1769         RNAUpdateCb *cb, int expand)
1770 {
1771         uiLayout *row, *split, *subsplit;
1772         uiBut *bt;
1773         float unit = BLI_rctf_size_x(butr) / 14.0f;
1774         float xs = butr->xmin;
1775         float ys = butr->ymin;
1776         PointerRNA ptr;
1777
1778         RNA_pointer_create(cb->ptr.id.data, &RNA_ColorRamp, coba, &ptr);
1779
1780         split = uiLayoutSplit(layout, 0.4f, false);
1781
1782         UI_block_emboss_set(block, UI_EMBOSS_NONE);
1783         UI_block_align_begin(block);
1784         row = uiLayoutRow(split, false);
1785
1786         bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, "", 0, 0, 2.0f * unit, UI_UNIT_Y, NULL,
1787                               0, 0, 0, 0, TIP_("Add a new color stop to the colorband"));
1788
1789         UI_but_funcN_set(bt, colorband_add_cb, MEM_dupallocN(cb), coba);
1790
1791         bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMOUT, "", xs +  2.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y,
1792                       NULL, 0, 0, 0, 0, TIP_("Delete the active position"));
1793         UI_but_funcN_set(bt, colorband_del_cb, MEM_dupallocN(cb), coba);
1794
1795         bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ARROW_LEFTRIGHT, "", xs + 4.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y,
1796                       NULL, 0, 0, 0, 0, TIP_("Flip the color ramp"));
1797         UI_but_funcN_set(bt, colorband_flip_cb, MEM_dupallocN(cb), coba);
1798         UI_block_align_end(block);
1799         UI_block_emboss_set(block, UI_EMBOSS);
1800
1801         row = uiLayoutRow(split, false);
1802
1803         UI_block_align_begin(block);
1804         uiItemR(row, &ptr, "color_mode", 0, "", ICON_NONE);
1805         if (ELEM(coba->color_mode, COLBAND_BLEND_HSV, COLBAND_BLEND_HSL)) {
1806                 uiItemR(row, &ptr, "hue_interpolation", 0, "", ICON_NONE);
1807         }
1808         else {  /* COLBAND_BLEND_RGB */
1809                 uiItemR(row, &ptr, "interpolation", 0, "", ICON_NONE);
1810         }
1811         UI_block_align_end(block);
1812
1813         row = uiLayoutRow(layout, false);
1814
1815         bt = uiDefBut(block, UI_BTYPE_COLORBAND, 0, "", xs, ys, BLI_rctf_size_x(butr), UI_UNIT_Y, coba, 0, 0, 0, 0, "");
1816         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1817
1818         row = uiLayoutRow(layout, false);
1819
1820         if (coba->tot) {
1821                 CBData *cbd = coba->data + coba->cur;
1822
1823                 RNA_pointer_create(cb->ptr.id.data, &RNA_ColorRampElement, cbd, &ptr);
1824
1825                 if (!expand) {
1826                         split = uiLayoutSplit(layout, 0.3f, false);
1827
1828                         row = uiLayoutRow(split, false);
1829                         uiDefButS(block, UI_BTYPE_NUM, 0, "", 0, 0, 5.0f * UI_UNIT_X, UI_UNIT_Y, &coba->cur, 0.0, (float)(MAX2(0, coba->tot - 1)),
1830                                   0, 0, TIP_("Choose active color stop"));
1831                         row = uiLayoutRow(split, false);
1832                         uiItemR(row, &ptr, "position", 0, IFACE_("Pos"), ICON_NONE);
1833                         bt = block->buttons.last;
1834                         bt->a1 = 1.0f; /* gives a bit more precision for modifying position */
1835                         UI_but_func_set(bt, colorband_update_cb, bt, coba);
1836
1837                         row = uiLayoutRow(layout, false);
1838                         uiItemR(row, &ptr, "color", 0, "", ICON_NONE);
1839                         bt = block->buttons.last;
1840                         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1841                 }
1842                 else {
1843                         split = uiLayoutSplit(layout, 0.5f, false);
1844                         subsplit = uiLayoutSplit(split, 0.35f, false);
1845
1846                         row = uiLayoutRow(subsplit, false);
1847                         uiDefButS(block, UI_BTYPE_NUM, 0, "", 0, 0, 5.0f * UI_UNIT_X, UI_UNIT_Y, &coba->cur, 0.0, (float)(MAX2(0, coba->tot - 1)),
1848                                   0, 0, TIP_("Choose active color stop"));
1849                         row = uiLayoutRow(subsplit, false);
1850                         uiItemR(row, &ptr, "position", UI_ITEM_R_SLIDER, IFACE_("Pos"), ICON_NONE);
1851                         bt = block->buttons.last;
1852                         bt->a1 = 1.0f; /* gives a bit more precision for modifying position */
1853                         UI_but_func_set(bt, colorband_update_cb, bt, coba);
1854
1855                         row = uiLayoutRow(split, false);
1856                         uiItemR(row, &ptr, "color", 0, "", ICON_NONE);
1857                         bt = block->buttons.last;
1858                         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1859                 }
1860         }
1861 }
1862
1863 void uiTemplateColorRamp(uiLayout *layout, PointerRNA *ptr, const char *propname, int expand)
1864 {
1865         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1866         PointerRNA cptr;
1867         RNAUpdateCb *cb;
1868         uiBlock *block;
1869         ID *id;
1870         rctf rect;
1871
1872         if (!prop || RNA_property_type(prop) != PROP_POINTER)
1873                 return;
1874
1875         cptr = RNA_property_pointer_get(ptr, prop);
1876         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_ColorRamp))
1877                 return;
1878
1879         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
1880         cb->ptr = *ptr;
1881         cb->prop = prop;
1882
1883         rect.xmin = 0; rect.xmax = 10.0f * UI_UNIT_X;
1884         rect.ymin = 0; rect.ymax = 19.5f * UI_UNIT_X;
1885
1886         block = uiLayoutAbsoluteBlock(layout);
1887
1888         id = cptr.id.data;
1889         UI_block_lock_set(block, (id && ID_IS_LINKED(id)), ERROR_LIBDATA_MESSAGE);
1890
1891         colorband_buttons_layout(layout, block, cptr.data, &rect, cb, expand);
1892
1893         UI_block_lock_clear(block);
1894
1895         MEM_freeN(cb);
1896 }
1897
1898
1899 /********************* Icon viewer Template ************************/
1900 typedef struct IconViewMenuArgs {
1901         PointerRNA ptr;
1902         PropertyRNA *prop;
1903         bool show_labels;
1904         float icon_scale;
1905 } IconViewMenuArgs;
1906
1907 /* ID Search browse menu, open */
1908 static uiBlock *ui_icon_view_menu_cb(bContext *C, ARegion *ar, void *arg_litem)
1909 {
1910         static IconViewMenuArgs args;
1911         uiBlock *block;
1912         uiBut *but;
1913         int icon, value;
1914         const EnumPropertyItem *item;
1915         int a;
1916         bool free;
1917         int w, h;
1918
1919         /* arg_litem is malloced, can be freed by parent button */
1920         args = *((IconViewMenuArgs *) arg_litem);
1921         w = UI_UNIT_X * (args.icon_scale);
1922         h = UI_UNIT_X * (args.icon_scale + args.show_labels);
1923
1924         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS_PULLDOWN);
1925         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_NO_FLIP);
1926
1927         RNA_property_enum_items(C, &args.ptr, args.prop, &item, NULL, &free);
1928
1929         for (a = 0; item[a].identifier; a++) {
1930                 int x, y;
1931
1932                 x = (a % 8) * w;
1933                 y = -(a / 8) * h;
1934
1935                 icon = item[a].icon;
1936                 value = item[a].value;
1937                 if (args.show_labels) {
1938                         but = uiDefIconTextButR_prop(
1939                                 block, UI_BTYPE_ROW, 0, icon, item[a].name, x, y, w, h,
1940                                 &args.ptr, args.prop, -1, 0, value, -1, -1, NULL);
1941                 }
1942                 else {
1943                         but = uiDefIconButR_prop(
1944                                 block, UI_BTYPE_ROW, 0, icon, x, y, w, h,
1945                                 &args.ptr, args.prop, -1, 0, value, -1, -1, NULL);
1946                 }
1947                 ui_def_but_icon(but, icon, UI_HAS_ICON | UI_BUT_ICON_PREVIEW);
1948         }
1949
1950         UI_block_bounds_set_normal(block, 0.3f * U.widget_unit);
1951         UI_block_direction_set(block, UI_DIR_DOWN);
1952
1953         if (free) {
1954                 MEM_freeN((void *)item);
1955         }
1956         
1957         return block;
1958 }
1959
1960 /**
1961  * \param icon_scale: Scale of the icon, 1x == button height.
1962  */
1963 void uiTemplateIconView(uiLayout *layout, PointerRNA *ptr, const char *propname, int show_labels, float icon_scale)
1964 {
1965         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1966         IconViewMenuArgs *cb_args;
1967         const EnumPropertyItem *items;
1968         uiBlock *block;
1969         uiBut *but;
1970         int value, icon = ICON_NONE, tot_items;
1971         bool free_items;
1972
1973         if (!prop || RNA_property_type(prop) != PROP_ENUM) {
1974                 RNA_warning("property of type Enum not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
1975                 return;
1976         }
1977
1978         block = uiLayoutAbsoluteBlock(layout);
1979
1980         RNA_property_enum_items(block->evil_C, ptr, prop, &items, &tot_items, &free_items);
1981         value = RNA_property_enum_get(ptr, prop);
1982         RNA_enum_icon_from_value(items, value, &icon);
1983
1984         cb_args = MEM_callocN(sizeof(IconViewMenuArgs), __func__);
1985         cb_args->ptr = *ptr;
1986         cb_args->prop = prop;
1987         cb_args->show_labels = show_labels;
1988         cb_args->icon_scale = icon_scale;
1989
1990         but = uiDefBlockButN(block, ui_icon_view_menu_cb, cb_args, "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6, "");
1991
1992         ui_def_but_icon(but, icon, UI_HAS_ICON | UI_BUT_ICON_PREVIEW);
1993
1994         if (free_items) {
1995                 MEM_freeN((void *)items);
1996         }
1997 }
1998
1999 /********************* Histogram Template ************************/
2000
2001 void uiTemplateHistogram(uiLayout *layout, PointerRNA *ptr, const char *propname)
2002 {
2003         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2004         PointerRNA cptr;
2005         uiBlock *block;
2006         uiLayout *col;
2007         Histogram *hist;
2008
2009         if (!prop || RNA_property_type(prop) != PROP_POINTER)
2010                 return;
2011
2012         cptr = RNA_property_pointer_get(ptr, prop);
2013         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Histogram))
2014                 return;
2015         hist = (Histogram *)cptr.data;
2016
2017         if (hist->height < UI_UNIT_Y) {
2018                 hist->height = UI_UNIT_Y;
2019         }
2020         else if (hist->height > UI_UNIT_Y * 20) {
2021                 hist->height = UI_UNIT_Y * 20;
2022         }
2023
2024         col = uiLayoutColumn(layout, true);
2025         block = uiLayoutGetBlock(col);
2026
2027         uiDefBut(block, UI_BTYPE_HISTOGRAM, 0, "", 0, 0, UI_UNIT_X * 10, hist->height, hist, 0, 0, 0, 0, "");
2028
2029         /* Resize grip. */
2030         uiDefIconButI(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &hist->height,
2031                       UI_UNIT_Y, UI_UNIT_Y * 20.0f, 0.0f, 0.0f, "");
2032 }
2033
2034 /********************* Waveform Template ************************/
2035
2036 void uiTemplateWaveform(uiLayout *layout, PointerRNA *ptr, const char *propname)
2037 {
2038         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2039         PointerRNA cptr;
2040         uiBlock *block;
2041         uiLayout *col;
2042         Scopes *scopes;
2043
2044         if (!prop || RNA_property_type(prop) != PROP_POINTER)
2045                 return;
2046
2047         cptr = RNA_property_pointer_get(ptr, prop);
2048         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Scopes))
2049                 return;
2050         scopes = (Scopes *)cptr.data;
2051
2052         col = uiLayoutColumn(layout, true);
2053         block = uiLayoutGetBlock(col);
2054
2055         if (scopes->wavefrm_height < UI_UNIT_Y) {
2056                 scopes->wavefrm_height = UI_UNIT_Y;
2057         }
2058         else if (scopes->wavefrm_height > UI_UNIT_Y * 20) {
2059                 scopes->wavefrm_height = UI_UNIT_Y * 20;
2060         }
2061
2062         uiDefBut(block, UI_BTYPE_WAVEFORM, 0, "", 0, 0, UI_UNIT_X * 10, scopes->wavefrm_height, scopes, 0, 0, 0, 0, "");
2063
2064         /* Resize grip. */
2065         uiDefIconButI(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &scopes->wavefrm_height,
2066                       UI_UNIT_Y, UI_UNIT_Y * 20.0f, 0.0f, 0.0f, "");
2067 }
2068
2069 /********************* Vectorscope Template ************************/
2070
2071 void uiTemplateVectorscope(uiLayout *layout, PointerRNA *ptr, const char *propname)
2072 {
2073         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2074         PointerRNA cptr;
2075         uiBlock *block;
2076         uiLayout *col;
2077         Scopes *scopes;
2078
2079         if (!prop || RNA_property_type(prop) != PROP_POINTER)
2080                 return;
2081
2082         cptr = RNA_property_pointer_get(ptr, prop);
2083         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Scopes))
2084                 return;
2085         scopes = (Scopes *)cptr.data;
2086
2087         if (scopes->vecscope_height < UI_UNIT_Y) {
2088                 scopes->vecscope_height = UI_UNIT_Y;
2089         }
2090         else if (scopes->vecscope_height > UI_UNIT_Y * 20) {
2091                 scopes->vecscope_height = UI_UNIT_Y * 20;
2092         }
2093
2094         col = uiLayoutColumn(layout, true);
2095         block = uiLayoutGetBlock(col);
2096
2097         uiDefBut(block, UI_BTYPE_VECTORSCOPE, 0, "", 0, 0, UI_UNIT_X * 10, scopes->vecscope_height, scopes, 0, 0, 0, 0, "");
2098
2099         /* Resize grip. */
2100         uiDefIconButI(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &scopes->vecscope_height,
2101                       UI_UNIT_Y, UI_UNIT_Y * 20.0f, 0.0f, 0.0f, "");
2102 }
2103
2104 /********************* CurveMapping Template ************************/
2105
2106
2107 static void curvemap_buttons_zoom_in(bContext *C, void *cumap_v, void *UNUSED(arg))
2108 {
2109         CurveMapping *cumap = cumap_v;
2110         float d;
2111
2112         /* we allow 20 times zoom */
2113         if (BLI_rctf_size_x(&cumap->curr) > 0.04f * BLI_rctf_size_x(&cumap->clipr)) {
2114                 d = 0.1154f * BLI_rctf_size_x(&cumap->curr);
2115                 cumap->curr.xmin += d;
2116                 cumap->curr.xmax -= d;
2117                 d = 0.1154f * BLI_rctf_size_y(&cumap->curr);
2118                 cumap->curr.ymin += d;
2119                 cumap->curr.ymax -= d;
2120         }
2121
2122         ED_region_tag_redraw(CTX_wm_region(C));
2123 }
2124
2125 static void curvemap_buttons_zoom_out(bContext *C, void *cumap_v, void *UNUSED(unused))
2126 {
2127         CurveMapping *cumap = cumap_v;
2128         float d, d1;
2129
2130         /* we allow 20 times zoom, but don't view outside clip */
2131         if (BLI_rctf_size_x(&cumap->curr) < 20.0f * BLI_rctf_size_x(&cumap->clipr)) {
2132                 d = d1 = 0.15f * BLI_rctf_size_x(&cumap->curr);
2133
2134                 if (cumap->flag & CUMA_DO_CLIP) 
2135                         if (cumap->curr.xmin - d < cumap->clipr.xmin)
2136                                 d1 = cumap->curr.xmin - cumap->clipr.xmin;
2137                 cumap->curr.xmin -= d1;
2138
2139                 d1 = d;
2140                 if (cumap->flag & CUMA_DO_CLIP) 
2141                         if (cumap->curr.xmax + d > cumap->clipr.xmax)
2142                                 d1 = -cumap->curr.xmax + cumap->clipr.xmax;
2143                 cumap->curr.xmax += d1;
2144
2145                 d = d1 = 0.15f * BLI_rctf_size_y(&cumap->curr);
2146
2147                 if (cumap->flag & CUMA_DO_CLIP) 
2148                         if (cumap->curr.ymin - d < cumap->clipr.ymin)
2149                                 d1 = cumap->curr.ymin - cumap->clipr.ymin;
2150                 cumap->curr.ymin -= d1;
2151
2152                 d1 = d;
2153                 if (cumap->flag & CUMA_DO_CLIP) 
2154                         if (cumap->curr.ymax + d > cumap->clipr.ymax)
2155                                 d1 = -cumap->curr.ymax + cumap->clipr.ymax;
2156                 cumap->curr.ymax += d1;
2157         }
2158
2159         ED_region_tag_redraw(CTX_wm_region(C));
2160 }
2161
2162 static void curvemap_buttons_setclip(bContext *UNUSED(C), void *cumap_v, void *UNUSED(arg))
2163 {
2164         CurveMapping *cumap = cumap_v;
2165
2166         curvemapping_changed(cumap, false);
2167 }       
2168
2169 static void curvemap_buttons_delete(bContext *C, void *cb_v, void *cumap_v)
2170 {
2171         CurveMapping *cumap = cumap_v;
2172
2173         curvemap_remove(cumap->cm + cumap->cur, SELECT);
2174         curvemapping_changed(cumap, false);
2175
2176         rna_update_cb(C, cb_v, NULL);
2177 }
2178
2179 /* NOTE: this is a block-menu, needs 0 events, otherwise the menu closes */
2180 static uiBlock *curvemap_clipping_func(bContext *C, ARegion *ar, void *cumap_v)
2181 {
2182         CurveMapping *cumap = cumap_v;
2183         uiBlock *block;
2184         uiBut *bt;
2185         float width = 8 * UI_UNIT_X;
2186
2187         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
2188
2189         /* use this for a fake extra empy space around the buttons */
2190         uiDefBut(block, UI_BTYPE_LABEL, 0, "",           -4, 16, width + 8, 6 * UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
2191
2192         bt = uiDefButBitI(block, UI_BTYPE_TOGGLE, CUMA_DO_CLIP, 1, IFACE_("Use Clipping"),
2193                           0, 5 * UI_UNIT_Y, width, UI_UNIT_Y, &cumap->flag, 0.0, 0.0, 10, 0, "");
2194         UI_but_func_set(bt, curvemap_buttons_setclip, cumap, NULL);
2195
2196         UI_block_align_begin(block);
2197         uiDefButF(block, UI_BTYPE_NUM, 0, IFACE_("Min X "),   0, 4 * UI_UNIT_Y, width, UI_UNIT_Y,
2198                   &cumap->clipr.xmin, -100.0, cumap->clipr.xmax, 10, 2, "");
2199         uiDefButF(block, UI_BTYPE_NUM, 0, IFACE_("Min Y "),   0, 3 * UI_UNIT_Y, width, UI_UNIT_Y,
2200                   &cumap->clipr.ymin, -100.0, cumap->clipr.ymax, 10, 2, "");
2201         uiDefButF(block, UI_BTYPE_NUM, 0, IFACE_("Max X "),   0, 2 * UI_UNIT_Y, width, UI_UNIT_Y,
2202                   &cumap->clipr.xmax, cumap->clipr.xmin, 100.0, 10, 2, "");
2203         uiDefButF(block, UI_BTYPE_NUM, 0, IFACE_("Max Y "),   0, UI_UNIT_Y, width, UI_UNIT_Y,
2204                   &cumap->clipr.ymax, cumap->clipr.ymin, 100.0, 10, 2, "");
2205
2206         UI_block_direction_set(block, UI_DIR_RIGHT);
2207
2208         return block;
2209 }
2210
2211 /* only for curvemap_tools_dofunc */
2212 enum {
2213         UICURVE_FUNC_RESET_NEG,
2214         UICURVE_FUNC_RESET_POS,
2215         UICURVE_FUNC_RESET_VIEW,
2216         UICURVE_FUNC_HANDLE_VECTOR,
2217         UICURVE_FUNC_HANDLE_AUTO,
2218         UICURVE_FUNC_HANDLE_AUTO_ANIM,
2219         UICURVE_FUNC_EXTEND_HOZ,
2220         UICURVE_FUNC_EXTEND_EXP,
2221 };
2222
2223 static void curvemap_tools_dofunc(bContext *C, void *cumap_v, int event)
2224 {
2225         CurveMapping *cumap = cumap_v;
2226         CurveMap *cuma = cumap->cm + cumap->cur;
2227
2228         switch (event) {
2229                 case UICURVE_FUNC_RESET_NEG:
2230                 case UICURVE_FUNC_RESET_POS: /* reset */
2231                         curvemap_reset(cuma, &cumap->clipr, cumap->preset,
2232                                        (event == UICURVE_FUNC_RESET_NEG) ? CURVEMAP_SLOPE_NEGATIVE : CURVEMAP_SLOPE_POSITIVE);
2233                         curvemapping_changed(cumap, false);
2234                         break;
2235                 case UICURVE_FUNC_RESET_VIEW:
2236                         cumap->curr = cumap->clipr;
2237                         break;
2238                 case UICURVE_FUNC_HANDLE_VECTOR: /* set vector */
2239                         curvemap_handle_set(cuma, HD_VECT);
2240                         curvemapping_changed(cumap, false);
2241                         break;
2242                 case UICURVE_FUNC_HANDLE_AUTO: /* set auto */
2243                         curvemap_handle_set(cuma, HD_AUTO);
2244                         curvemapping_changed(cumap, false);
2245                         break;
2246                 case UICURVE_FUNC_HANDLE_AUTO_ANIM: /* set auto-clamped */
2247                         curvemap_handle_set(cuma, HD_AUTO_ANIM);
2248                         curvemapping_changed(cumap, false);
2249                         break;
2250                 case UICURVE_FUNC_EXTEND_HOZ: /* extend horiz */
2251                         cuma->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
2252                         curvemapping_changed(cumap, false);
2253                         break;
2254                 case UICURVE_FUNC_EXTEND_EXP: /* extend extrapolate */
2255                         cuma->flag |= CUMA_EXTEND_EXTRAPOLATE;
2256                         curvemapping_changed(cumap, false);
2257                         break;
2258         }
2259         ED_undo_push(C, "CurveMap tools");
2260         ED_region_tag_redraw(CTX_wm_region(C));
2261 }
2262
2263 static uiBlock *curvemap_tools_func(
2264         bContext *C, ARegion *ar, CurveMapping *cumap,
2265         bool show_extend, int reset_mode)
2266 {
2267         uiBlock *block;
2268         short yco = 0, menuwidth = 10 * UI_UNIT_X;
2269
2270         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
2271         UI_block_func_butmenu_set(block, curvemap_tools_dofunc, cumap);
2272
2273         {
2274                 uiDefIconTextBut(
2275                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Reset View"),
2276                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_RESET_VIEW, "");
2277                 uiDefIconTextBut(
2278                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Vector Handle"),
2279                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_VECTOR, "");
2280                 uiDefIconTextBut(
2281                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Auto Handle"),
2282                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_AUTO, "");
2283                 uiDefIconTextBut(
2284                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Auto Clamped Handle"),
2285                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_AUTO_ANIM, "");
2286         }
2287
2288         if (show_extend) {
2289                 uiDefIconTextBut(
2290                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Extend Horizontal"),
2291                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_EXTEND_HOZ, "");
2292                 uiDefIconTextBut(
2293                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Extend Extrapolated"),
2294                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_EXTEND_EXP, "");
2295         }
2296
2297         {
2298                 uiDefIconTextBut(
2299                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Reset Curve"),
2300                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, reset_mode, "");
2301         }
2302
2303         UI_block_direction_set(block, UI_DIR_RIGHT);
2304         UI_block_bounds_set_text(block, 50);
2305
2306         return block;
2307 }
2308
2309 static uiBlock *curvemap_tools_posslope_func(bContext *C, ARegion *ar, void *cumap_v)
2310 {
2311         return curvemap_tools_func(C, ar, cumap_v, true, UICURVE_FUNC_RESET_POS);
2312 }
2313
2314 static uiBlock *curvemap_tools_negslope_func(bContext *C, ARegion *ar, void *cumap_v)
2315 {
2316         return curvemap_tools_func(C, ar, cumap_v, true, UICURVE_FUNC_RESET_NEG);
2317 }
2318
2319 static uiBlock *curvemap_brush_tools_func(bContext *C, ARegion *ar, void *cumap_v)
2320 {
2321         return curvemap_tools_func(C, ar, cumap_v, false, UICURVE_FUNC_RESET_NEG);
2322 }
2323
2324 static void curvemap_buttons_redraw(bContext *C, void *UNUSED(arg1), void *UNUSED(arg2))
2325 {
2326         ED_region_tag_redraw(CTX_wm_region(C));
2327 }
2328
2329 static void curvemap_buttons_update(bContext *C, void *arg1_v, void *cumap_v)
2330 {
2331         CurveMapping *cumap = cumap_v;
2332         curvemapping_changed(cumap, true);
2333         rna_update_cb(C, arg1_v, NULL);
2334 }
2335
2336 static void curvemap_buttons_reset(bContext *C, void *cb_v, void *cumap_v)
2337 {
2338         CurveMapping *cumap = cumap_v;
2339         int a;
2340         
2341         cumap->preset = CURVE_PRESET_LINE;
2342         for (a = 0; a < CM_TOT; a++)
2343                 curvemap_reset(cumap->cm + a, &cumap->clipr, cumap->preset, CURVEMAP_SLOPE_POSITIVE);
2344         
2345         cumap->black[0] = cumap->black[1] = cumap->black[2] = 0.0f;
2346         cumap->white[0] = cumap->white[1] = cumap->white[2] = 1.0f;
2347         curvemapping_set_black_white(cumap, NULL, NULL);
2348         
2349         curvemapping_changed(cumap, false);
2350
2351         rna_update_cb(C, cb_v, NULL);
2352 }
2353
2354 /* still unsure how this call evolves... we use labeltype for defining what curve-channels to show */
2355 static void curvemap_buttons_layout(
2356         uiLayout *layout, PointerRNA *ptr, char labeltype, int levels,
2357         int brush, int neg_slope, RNAUpdateCb *cb)
2358 {
2359         CurveMapping *cumap = ptr->data;
2360         CurveMap *cm = &cumap->cm[cumap->cur];
2361         CurveMapPoint *cmp = NULL;
2362         uiLayout *row, *sub, *split;
2363         uiBlock *block;
2364         uiBut *bt;
2365         float dx = UI_UNIT_X;
2366         int icon, size;
2367         int bg = -1, i;
2368
2369         block = uiLayoutGetBlock(layout);
2370
2371         /* curve chooser */
2372         row = uiLayoutRow(layout, false);
2373
2374         if (labeltype == 'v') {
2375                 /* vector */
2376                 sub = uiLayoutRow(row, true);
2377                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2378
2379                 if (cumap->cm[0].curve) {
2380                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "X", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2381                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2382                 }
2383                 if (cumap->cm[1].curve) {
2384                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "Y", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2385                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2386                 }
2387                 if (cumap->cm[2].curve) {
2388                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "Z", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2389                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2390                 }
2391         }
2392         else if (labeltype == 'c') {
2393                 /* color */
2394                 sub = uiLayoutRow(row, true);
2395                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2396
2397                 if (cumap->cm[3].curve) {
2398                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "C", 0, 0, dx, dx, &cumap->cur, 0.0, 3.0, 0.0, 0.0, "");
2399                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2400                 }
2401                 if (cumap->cm[0].curve) {
2402                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "R", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2403                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2404                 }
2405                 if (cumap->cm[1].curve) {
2406                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "G", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2407                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2408                 }
2409                 if (cumap->cm[2].curve) {
2410                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "B", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2411                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2412                 }
2413         }
2414         else if (labeltype == 'h') {
2415                 /* HSV */
2416                 sub = uiLayoutRow(row, true);
2417                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2418                 
2419                 if (cumap->cm[0].curve) {
2420                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "H", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2421                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2422                 }
2423                 if (cumap->cm[1].curve) {
2424                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "S", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2425                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2426                 }
2427                 if (cumap->cm[2].curve) {
2428                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "V", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2429                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2430                 }
2431         }
2432         else
2433                 uiLayoutSetAlignment(row, UI_LAYOUT_ALIGN_RIGHT);
2434         
2435         if (labeltype == 'h')
2436                 bg = UI_GRAD_H;
2437
2438         /* operation buttons */
2439         sub = uiLayoutRow(row, true);
2440
2441         UI_block_emboss_set(block, UI_EMBOSS_NONE);
2442
2443         bt = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_ZOOM_IN, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Zoom in"));
2444         UI_but_func_set(bt, curvemap_buttons_zoom_in, cumap, NULL);
2445
2446         bt = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_ZOOM_OUT, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Zoom out"));
2447         UI_but_func_set(bt, curvemap_buttons_zoom_out, cumap, NULL);
2448
2449         if (brush)
2450                 bt = uiDefIconBlockBut(block, curvemap_brush_tools_func, cumap, 0, ICON_MODIFIER, 0, 0, dx, dx, TIP_("Tools"));
2451         else if (neg_slope)
2452                 bt = uiDefIconBlockBut(block, curvemap_tools_negslope_func, cumap, 0, ICON_MODIFIER,
2453                                        0, 0, dx, dx, TIP_("Tools"));
2454         else
2455                 bt = uiDefIconBlockBut(block, curvemap_tools_posslope_func, cumap, 0, ICON_MODIFIER,
2456                                        0, 0, dx, dx, TIP_("Tools"));
2457
2458         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
2459
2460         icon = (cumap->flag & CUMA_DO_CLIP) ? ICON_CLIPUV_HLT : ICON_CLIPUV_DEHLT;
2461         bt = uiDefIconBlockBut(block, curvemap_clipping_func, cumap, 0, icon, 0, 0, dx, dx, TIP_("Clipping Options"));
2462         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
2463
2464         bt = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_X, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Delete points"));
2465         UI_but_funcN_set(bt, curvemap_buttons_delete, MEM_dupallocN(cb), cumap);
2466
2467         UI_block_emboss_set(block, UI_EMBOSS);
2468
2469         UI_block_funcN_set(block, rna_update_cb, MEM_dupallocN(cb), NULL);
2470
2471         /* curve itself */
2472         size = uiLayoutGetWidth(layout);
2473         row = uiLayoutRow(layout, false);
2474         uiDefBut(block, UI_BTYPE_CURVE, 0, "", 0, 0, size, 8.0f * UI_UNIT_X, cumap, 0.0f, 1.0f, bg, 0, "");
2475
2476         /* sliders for selected point */
2477         for (i = 0; i < cm->totpoint; i++) {
2478                 if (cm->curve[i].flag & CUMA_SELECT) {
2479                         cmp = &cm->curve[i];
2480                         break;
2481                 }
2482         }
2483
2484         if (cmp) {
2485                 rctf bounds;
2486
2487                 if (cumap->flag & CUMA_DO_CLIP) {
2488                         bounds = cumap->clipr;
2489                 }
2490                 else {
2491                         bounds.xmin = bounds.ymin = -1000.0;
2492                         bounds.xmax = bounds.ymax =  1000.0;
2493                 }
2494
2495                 uiLayoutRow(layout, true);
2496                 UI_block_funcN_set(block, curvemap_buttons_update, MEM_dupallocN(cb), cumap);
2497                 uiDefButF(block, UI_BTYPE_NUM, 0, "X", 0, 2 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y,
2498                           &cmp->x, bounds.xmin, bounds.xmax, 1, 5, "");
2499                 uiDefButF(block, UI_BTYPE_NUM, 0, "Y", 0, 1 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y,
2500                           &cmp->y, bounds.ymin, bounds.ymax, 1, 5, "");
2501         }
2502
2503         /* black/white levels */
2504         if (levels) {
2505                 split = uiLayoutSplit(layout, 0.0f, false);
2506                 uiItemR(uiLayoutColumn(split, false), ptr, "black_level", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
2507                 uiItemR(uiLayoutColumn(split, false), ptr, "white_level", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
2508
2509                 uiLayoutRow(layout, false);
2510                 bt = uiDefBut(block, UI_BTYPE_BUT, 0, IFACE_("Reset"), 0, 0, UI_UNIT_X * 10, UI_UNIT_Y, NULL, 0.0f, 0.0f, 0, 0,
2511                               TIP_("Reset Black/White point and curves"));
2512                 UI_but_funcN_set(bt, curvemap_buttons_reset, MEM_dupallocN(cb), cumap);
2513         }
2514
2515         UI_block_funcN_set(block, NULL, NULL, NULL);
2516 }
2517
2518 void uiTemplateCurveMapping(
2519         uiLayout *layout, PointerRNA *ptr, const char *propname, int type,
2520         int levels, int brush, int neg_slope)
2521 {
2522         RNAUpdateCb *cb;
2523         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2524         PointerRNA cptr;
2525         ID *id;
2526         uiBlock *block = uiLayoutGetBlock(layout);
2527
2528         if (!prop) {
2529                 RNA_warning("curve property not found: %s.%s",
2530                             RNA_struct_identifier(ptr->type), propname);
2531                 return;
2532         }
2533
2534         if (RNA_property_type(prop) != PROP_POINTER) {
2535                 RNA_warning("curve is not a pointer: %s.%s",
2536                             RNA_struct_identifier(ptr->type), propname);
2537                 return;
2538         }
2539
2540         cptr = RNA_property_pointer_get(ptr, prop);
2541         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_CurveMapping))
2542                 return;
2543
2544         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
2545         cb->ptr = *ptr;
2546         cb->prop = prop;
2547
2548         id = cptr.id.data;
2549         UI_block_lock_set(block, (id && ID_IS_LINKED(id)), ERROR_LIBDATA_MESSAGE);
2550
2551         curvemap_buttons_layout(layout, &cptr, type, levels, brush, neg_slope, cb);
2552
2553         UI_block_lock_clear(block);
2554
2555         MEM_freeN(cb);
2556 }
2557
2558 /********************* ColorPicker Template ************************/
2559
2560 #define WHEEL_SIZE  (5 * U.widget_unit)
2561
2562 /* This template now follows User Preference for type - name is not correct anymore... */
2563 void uiTemplateColorPicker(
2564         uiLayout *layout, PointerRNA *ptr, const char *propname, int value_slider,
2565         int lock, int lock_luminosity, int cubic)
2566 {
2567         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2568         uiBlock *block = uiLayoutGetBlock(layout);
2569         uiLayout *col, *row;
2570         uiBut *but = NULL;
2571         ColorPicker *cpicker = ui_block_colorpicker_create(block);
2572         float softmin, softmax, step, precision;
2573
2574         if (!prop) {
2575                 RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2576                 return;
2577         }
2578
2579         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2580
2581         col = uiLayoutColumn(layout, true);
2582         row = uiLayoutRow(col, true);
2583
2584         switch (U.color_picker_type) {
2585                 case USER_CP_SQUARE_SV:
2586                         but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2587                                              -1, 0.0, 0.0, UI_GRAD_SV, 0, "");
2588                         break;
2589                 case USER_CP_SQUARE_HS:
2590                         but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2591                                              -1, 0.0, 0.0, UI_GRAD_HS, 0, "");
2592                         break;
2593                 case USER_CP_SQUARE_HV:
2594                         but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2595                                              -1, 0.0, 0.0, UI_GRAD_HV, 0, "");
2596                         break;
2597
2598                 /* user default */
2599                 case USER_CP_CIRCLE_HSV:
2600                 case USER_CP_CIRCLE_HSL:
2601                 default:
2602                         but = uiDefButR_prop(block, UI_BTYPE_HSVCIRCLE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2603                                              -1, 0.0, 0.0, 0, 0, "");
2604                         break;
2605
2606         }
2607
2608         but->custom_data = cpicker;
2609
2610         if (lock) {
2611                 but->flag |= UI_BUT_COLOR_LOCK;
2612         }
2613
2614         if (lock_luminosity) {
2615                 float color[4]; /* in case of alpha */
2616                 but->flag |= UI_BUT_VEC_SIZE_LOCK;
2617                 RNA_property_float_get_array(ptr, prop, color);
2618                 but->a2 = len_v3(color);
2619         }
2620
2621         if (cubic)
2622                 but->flag |= UI_BUT_COLOR_CUBIC;
2623
2624         
2625         if (value_slider) {
2626                 switch (U.color_picker_type) {
2627                         case USER_CP_CIRCLE_HSL:
2628                                 uiItemS(row);
2629                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop,
2630                                                      -1, softmin, softmax, UI_GRAD_L_ALT, 0, "");
2631                                 break;
2632                         case USER_CP_SQUARE_SV:
2633                                 uiItemS(col);
2634                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2635                                                      -1, softmin, softmax, UI_GRAD_SV + 3, 0, "");
2636                                 break;
2637                         case USER_CP_SQUARE_HS:
2638                                 uiItemS(col);
2639                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2640                                                      -1, softmin, softmax, UI_GRAD_HS + 3, 0, "");
2641                                 break;
2642                         case USER_CP_SQUARE_HV:
2643                                 uiItemS(col);
2644                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2645                                                      -1, softmin, softmax, UI_GRAD_HV + 3, 0, "");
2646                                 break;
2647
2648                         /* user default */
2649                         case USER_CP_CIRCLE_HSV:
2650                         default:
2651                                 uiItemS(row);
2652                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop,
2653                                                      -1, softmin, softmax, UI_GRAD_V_ALT, 0, "");
2654                                 break;
2655                 }
2656
2657                 but->custom_data = cpicker;
2658         }
2659 }
2660
2661 void uiTemplatePalette(uiLayout *layout, PointerRNA *ptr, const char *propname, int UNUSED(colors))
2662 {
2663         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2664         PointerRNA cptr;
2665         Palette *palette;
2666         PaletteColor *color;
2667         uiBlock *block;
2668         uiLayout *col;
2669         int row_cols = 0, col_id = 0;
2670         int cols_per_row = MAX2(uiLayoutGetWidth(layout) / UI_UNIT_X, 1);
2671
2672         if (!prop) {
2673                 RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2674                 return;
2675         }
2676
2677         cptr = RNA_property_pointer_get(ptr, prop);
2678         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Palette))
2679                 return;
2680
2681         block = uiLayoutGetBlock(layout);
2682
2683         palette = cptr.data;
2684
2685         color = palette->colors.first;
2686
2687         col = uiLayoutColumn(layout, true);
2688         uiLayoutRow(col, true);
2689         uiDefIconButO(block, UI_BTYPE_BUT, "PALETTE_OT_color_add", WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
2690         uiDefIconButO(block, UI_BTYPE_BUT, "PALETTE_OT_color_delete", WM_OP_INVOKE_DEFAULT, ICON_ZOOMOUT, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
2691
2692         col = uiLayoutColumn(layout, true);
2693         uiLayoutRow(col, true);
2694
2695         for (; color; color = color->next) {
2696                 PointerRNA color_ptr;
2697
2698                 if (row_cols >= cols_per_row) {
2699                         uiLayoutRow(col, true);
2700                         row_cols = 0;
2701                 }
2702
2703                 RNA_pointer_create(&palette->id, &RNA_PaletteColor, color, &color_ptr);
2704                 uiDefButR(block, UI_BTYPE_COLOR, 0, "", 0, 0, UI_UNIT_X, UI_UNIT_Y, &color_ptr, "color", -1, 0.0, 1.0,
2705                           UI_PALETTE_COLOR, col_id, "");
2706                 row_cols++;
2707                 col_id++;
2708         }
2709 }
2710
2711
2712 /********************* Layer Buttons Template ************************/
2713
2714 static void handle_layer_buttons(bContext *C, void *arg1, void *arg2)
2715 {
2716         uiBut *but = arg1;
2717         int cur = GET_INT_FROM_POINTER(arg2);
2718         wmWindow *win = CTX_wm_window(C);
2719         int i, tot, shift = win->eventstate->shift;
2720
2721         if (!shift) {
2722                 tot = RNA_property_array_length(&but->rnapoin, but->rnaprop);
2723                 
2724                 /* Normally clicking only selects one layer */
2725                 RNA_property_boolean_set_index(&but->rnapoin, but->rnaprop, cur, true);
2726                 for (i = 0; i < tot; ++i) {
2727                         if (i != cur)
2728                                 RNA_property_boolean_set_index(&but->rnapoin, but->rnaprop, i, false);
2729                 }
2730         }
2731
2732         /* view3d layer change should update depsgraph (invisible object changed maybe) */
2733         /* see view3d_header.c */
2734 }
2735
2736 /**
2737  * \todo for now, grouping of layers is determined by dividing up the length of
2738  * the array of layer bitflags
2739  */
2740 void uiTemplateLayers(
2741         uiLayout *layout, PointerRNA *ptr, const char *propname,
2742         PointerRNA *used_ptr, const char *used_propname, int active_layer)
2743 {
2744         uiLayout *uRow, *uCol;
2745         PropertyRNA *prop, *used_prop = NULL;
2746         int groups, cols, layers;
2747         int group, col, layer, row;
2748         int cols_per_group = 5;
2749
2750         prop = RNA_struct_find_property(ptr, propname);
2751         if (!prop) {
2752                 RNA_warning("layers property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2753                 return;
2754         }
2755         
2756         /* the number of layers determines the way we group them 
2757          *      - we want 2 rows only (for now)
2758          *      - the number of columns (cols) is the total number of buttons per row
2759          *        the 'remainder' is added to this, as it will be ok to have first row slightly wider if need be
2760          *      - for now, only split into groups if group will have at least 5 items
2761          */
2762         layers = RNA_property_array_length(ptr, prop);
2763         cols = (layers / 2) + (layers % 2);
2764         groups = ((cols / 2) < cols_per_group) ? (1) : (cols / cols_per_group);
2765
2766         if (used_ptr && used_propname) {
2767                 used_prop = RNA_struct_find_property(used_ptr, used_propname);
2768                 if (!used_prop) {
2769                         RNA_warning("used layers property not found: %s.%s", RNA_struct_identifier(ptr->type), used_propname);
2770                         return;
2771                 }
2772
2773                 if (RNA_property_array_length(used_ptr, used_prop) < layers)
2774                         used_prop = NULL;
2775         }
2776         
2777         /* layers are laid out going across rows, with the columns being divided into groups */
2778         
2779         for (group = 0; group < groups; group++) {
2780                 uCol = uiLayoutColumn(layout, true);
2781                 
2782                 for (row = 0; row < 2; row++) {
2783                         uiBlock *block;
2784                         uiBut *but;
2785
2786                         uRow = uiLayoutRow(uCol, true);
2787                         block = uiLayoutGetBlock(uRow);
2788                         layer = groups * cols_per_group * row + cols_per_group * group;
2789                         
2790                         /* add layers as toggle buts */
2791                         for (col = 0; (col < cols_per_group) && (layer < layers); col++, layer++) {
2792                                 int icon = 0;
2793                                 int butlay = 1 << layer;
2794
2795                                 if (active_layer & butlay)
2796                                         icon = ICON_LAYER_ACTIVE;
2797                                 else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, layer))
2798                                         icon = ICON_LAYER_USED;
2799                                 
2800                                 but = uiDefAutoButR(block, ptr, prop, layer, "", icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2);
2801                                 UI_but_func_set(but, handle_layer_buttons, but, SET_INT_IN_POINTER(layer));
2802                                 but->type = UI_BTYPE_TOGGLE;
2803                         }
2804                 }
2805         }
2806 }
2807
2808 void uiTemplateGameStates(
2809         uiLayout *layout, PointerRNA *ptr, const char *propname,
2810         PointerRNA *used_ptr, const char *used_propname, int active_state)
2811 {
2812         uiLayout *uRow, *uCol;
2813         PropertyRNA *prop, *used_prop = NULL;
2814         int groups, cols, states;
2815         int group, col, state, row;
2816         int cols_per_group = 5;
2817         Object *ob = (Object *)ptr->id.data;
2818
2819         prop = RNA_struct_find_property(ptr, propname);
2820         if (!prop) {
2821                 RNA_warning("states property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2822                 return;
2823         }
2824         
2825         /* the number of states determines the way we group them 
2826          *      - we want 2 rows only (for now)
2827          *      - the number of columns (cols) is the total number of buttons per row
2828          *        the 'remainder' is added to this, as it will be ok to have first row slightly wider if need be
2829          *      - for now, only split into groups if group will have at least 5 items
2830          */
2831         states = RNA_property_array_length(ptr, prop);
2832         cols = (states / 2) + (states % 2);
2833         groups = ((cols / 2) < cols_per_group) ? (1) : (cols / cols_per_group);
2834
2835         if (used_ptr && used_propname) {
2836                 used_prop = RNA_struct_find_property(used_ptr, used_propname);
2837                 if (!used_prop) {
2838                         RNA_warning("used layers property not found: %s.%s", RNA_struct_identifier(ptr->type), used_propname);
2839                         return;
2840                 }
2841
2842                 if (RNA_property_array_length(used_ptr, used_prop) < states)
2843                         used_prop = NULL;
2844         }
2845         
2846         /* layers are laid out going across rows, with the columns being divided into groups */
2847         
2848         for (group = 0; group < groups; group++) {
2849                 uCol = uiLayoutColumn(layout, true);
2850                 
2851                 for (row = 0; row < 2; row++) {
2852                         uiBlock *block;
2853                         uiBut *but;
2854
2855                         uRow = uiLayoutRow(uCol, true);
2856                         block = uiLayoutGetBlock(uRow);
2857                         state = groups * cols_per_group * row + cols_per_group * group;
2858                         
2859                         /* add layers as toggle buts */
2860                         for (col = 0; (col < cols_per_group) && (state < states); col++, state++) {
2861                                 int icon = 0;
2862                                 int butlay = 1 << state;
2863
2864                                 if (active_state & butlay)
2865                                         icon = ICON_LAYER_ACTIVE;
2866                                 else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, state))
2867                                         icon = ICON_LAYER_USED;
2868                                 
2869                                 but = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2, ptr, prop,
2870                                                          state, 0, 0, -1, -1, sca_state_name_get(ob, state));
2871                                 UI_but_func_set(but, handle_layer_buttons, but, SET_INT_IN_POINTER(state));
2872                                 but->type = UI_BTYPE_TOGGLE;
2873                         }
2874                 }
2875         }
2876 }
2877
2878
2879 /************************* List Template **************************/
2880 static void uilist_draw_item_default(
2881         struct uiList *ui_list, struct bContext *UNUSED(C), struct uiLayout *layout,
2882         struct PointerRNA *UNUSED(dataptr), struct PointerRNA *itemptr, int icon,
2883         struct PointerRNA *UNUSED(active_dataptr), const char *UNUSED(active_propname),
2884         int UNUSED(index), int UNUSED(flt_flag))
2885 {
2886         PropertyRNA *nameprop = RNA_struct_name_property(itemptr->type);
2887
2888         /* Simplest one! */
2889         switch (ui_list->layout_type) {
2890                 case UILST_LAYOUT_GRID:
2891                         uiItemL(layout, "", icon);
2892                         break;
2893                 case UILST_LAYOUT_DEFAULT:
2894                 case UILST_LAYOUT_COMPACT:
2895                 default:
2896                         if (nameprop) {
2897                                 uiItemFullR(layout, itemptr, nameprop, RNA_NO_INDEX, 0, UI_ITEM_R_NO_BG, "", icon);
2898                         }
2899                         else {
2900                                 uiItemL(layout, "", icon);
2901                         }
2902                         break;
2903         }
2904 }
2905
2906 static void uilist_draw_filter_default(struct uiList *ui_list, struct bContext *UNUSED(C), struct uiLayout *layout)
2907 {
2908         PointerRNA listptr;
2909         uiLayout *row, *subrow;
2910
2911         RNA_pointer_create(NULL, &RNA_UIList, ui_list, &listptr);
2912
2913         row = uiLayoutRow(layout, false);
2914
2915         subrow = uiLayoutRow(row, true);
2916         uiItemR(subrow, &listptr, "filter_name", 0, "", ICON_NONE);
2917         uiItemR(subrow, &listptr, "use_filter_invert", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "",
2918                 (ui_list->filter_flag & UILST_FLT_EXCLUDE) ? ICON_ZOOM_OUT : ICON_ZOOM_IN);
2919
2920         subrow = uiLayoutRow(row, true);
2921         uiItemR(subrow, &listptr, "use_filter_sort_alpha", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "", ICON_NONE);
2922         uiItemR(subrow, &listptr, "use_filter_sort_reverse", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "",
2923                 (ui_list->filter_sort_flag & UILST_FLT_SORT_REVERSE) ? ICON_TRIA_UP : ICON_TRIA_DOWN);
2924 }
2925
2926 typedef struct {
2927         char name[MAX_IDPROP_NAME];
2928         int org_idx;
2929 } StringCmp;
2930
2931 static int cmpstringp(const void *p1, const void *p2)
2932 {
2933         /* Case-insensitive comparison. */
2934         return BLI_strcasecmp(((StringCmp *) p1)->name, ((StringCmp *) p2)->name);
2935 }
2936
2937 static void uilist_filter_items_default(struct uiList *ui_list, struct bContext *UNUSED(C), struct PointerRNA *dataptr,
2938                                         const char *propname)
2939 {
2940         uiListDyn *dyn_data = ui_list->dyn_data;
2941         PropertyRNA *prop = RNA_struct_find_property(dataptr, propname);
2942
2943         const char *filter_raw = ui_list->filter_byname;
2944         char *filter = (char *)filter_raw, filter_buff[32], *filter_dyn = NULL;
2945         const bool filter_exclude = (ui_list->filter_flag & UILST_FLT_EXCLUDE) != 0;
2946         const bool order_by_name = (ui_list->filter_sort_flag & UILST_FLT_SORT_ALPHA) != 0;
2947         int len = RNA_property_collection_length(dataptr, prop);
2948
2949         dyn_data->items_shown = dyn_data->items_len = len;
2950
2951         if (len && (order_by_name || filter_raw[0])) {
2952                 StringCmp *names = NULL;
2953                 int order_idx = 0, i = 0;
2954
2955                 if (order_by_name) {
2956                         names = MEM_callocN(sizeof(StringCmp) * len, "StringCmp");
2957                 }
2958                 if (filter_raw[0]) {
2959                         size_t slen = strlen(filter_raw);
2960
2961                         dyn_data->items_filter_flags = MEM_callocN(sizeof(int) * len, "items_filter_flags");
2962                         dyn_data->items_shown = 0;
2963
2964                         /* Implicitly add heading/trailing wildcards if needed. */
2965                         if (slen + 3 <= sizeof(filter_buff)) {
2966                                 filter = filter_buff;
2967                         }
2968                         else {
2969                                 filter = filter_dyn = MEM_mallocN((slen + 3) * sizeof(char), "filter_dyn");
2970                         }
2971                         BLI_strncpy_ensure_pad(filter, filter_raw, '*', slen + 3);
2972                 }
2973
2974                 RNA_PROP_BEGIN (dataptr, itemptr, prop)
2975                 {
2976                         char *namebuf;
2977                         const char *name;
2978                         bool do_order = false;
2979
2980                         namebuf = RNA_struct_name_get_alloc(&itemptr, NULL, 0, NULL);
2981                         name = namebuf ? namebuf : "";
2982
2983                         if (filter[0]) {
2984                                 /* Case-insensitive! */
2985                                 if (fnmatch(filter, name, FNM_CASEFOLD) == 0) {
2986                                         dyn_data->items_filter_flags[i] = UILST_FLT_ITEM;
2987                                         if (!filter_exclude) {
2988                                                 dyn_data->items_shown++;
2989                                                 do_order = order_by_name;
2990                                         }
2991                                         //printf("%s: '%s' matches '%s'\n", __func__, name, filter);
2992                                 }
2993                                 else if (filter_exclude) {
2994                                         dyn_data->items_shown++;
2995                                         do_order = order_by_name;
2996                                 }
2997                         }
2998                         else {
2999                                 do_order = order_by_name;
3000                         }
3001
3002                         if (do_order) {
3003                                 names[order_idx].org_idx = order_idx;
3004                                 BLI_strncpy(names[order_idx++].name, name, MAX_IDPROP_NAME);
3005                         }
3006
3007                         /* free name */
3008                         if (namebuf) {
3009                                 MEM_freeN(namebuf);
3010                    &n