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