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