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