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