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