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