UI: Use bool rather then int/short's where possible
[blender.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 Settings 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         const bool editable = RNA_property_editable(&template->ptr, template->prop);
409
410         idptr = RNA_property_pointer_get(&template->ptr, template->prop);
411         id = idptr.data;
412         idfrom = template->ptr.id.data;
413         // lb = template->idlb;
414
415         block = uiLayoutGetBlock(layout);
416         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) ||
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 if (modifier_supportsCage(scene, md)) {
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 static void colorband_buttons_layout(uiLayout *layout, uiBlock *block, ColorBand *coba, const rctf *butr,
1468                                     RNAUpdateCb *cb, int expand)
1469 {
1470         uiLayout *row, *split, *subsplit;
1471         uiBut *bt;
1472         float unit = BLI_rctf_size_x(butr) / 14.0f;
1473         float xs = butr->xmin;
1474         float ys = butr->ymin;
1475
1476         split = uiLayoutSplit(layout, 0.4f, false);
1477
1478         uiBlockSetEmboss(block, UI_EMBOSSN);
1479         uiBlockBeginAlign(block);
1480         row = uiLayoutRow(split, false);
1481
1482         bt = uiDefIconTextBut(block, BUT, 0, ICON_ZOOMIN, "", 0, 0, 2.0f * unit, UI_UNIT_Y, NULL,
1483                               0, 0, 0, 0, TIP_("Add a new color stop to the colorband"));
1484
1485         uiButSetNFunc(bt, colorband_add_cb, MEM_dupallocN(cb), coba);
1486
1487         bt = uiDefIconTextBut(block, BUT, 0, ICON_ZOOMOUT, "", xs +  2.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y,
1488                       NULL, 0, 0, 0, 0, TIP_("Delete the active position"));
1489         uiButSetNFunc(bt, colorband_del_cb, MEM_dupallocN(cb), coba);
1490
1491         bt = uiDefIconTextBut(block, BUT, 0, ICON_ARROW_LEFTRIGHT, "", xs + 4.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y,
1492                       NULL, 0, 0, 0, 0, TIP_("Flip the color ramp"));
1493         uiButSetNFunc(bt, colorband_flip_cb, MEM_dupallocN(cb), coba);
1494         uiBlockEndAlign(block);
1495         uiBlockSetEmboss(block, UI_EMBOSS);
1496
1497         row = uiLayoutRow(split, false);
1498         bt = uiDefButS(block, MENU, 0, IFACE_("Interpolation %t|Ease %x1|Cardinal %x3|Linear %x0|B-Spline %x2|Constant %x4"),
1499                        0, ys + UI_UNIT_Y, 8.0f * unit, UI_UNIT_Y, &coba->ipotype, 0.0, 0.0, 0, 0,
1500                        TIP_("Set interpolation between color stops"));
1501         uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1502
1503         row = uiLayoutRow(layout, false);
1504
1505         bt = uiDefBut(block, BUT_COLORBAND, 0, "", xs, ys, BLI_rctf_size_x(butr), UI_UNIT_Y, coba, 0, 0, 0, 0, "");
1506         uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1507
1508         row = uiLayoutRow(layout, false);
1509
1510         if (coba->tot) {
1511                 CBData *cbd = coba->data + coba->cur;
1512                 PointerRNA ptr;
1513
1514                 RNA_pointer_create(cb->ptr.id.data, &RNA_ColorRampElement, cbd, &ptr);
1515
1516                 if (!expand) {
1517                         split = uiLayoutSplit(layout, 0.3f, false);
1518
1519                         row = uiLayoutRow(split, false);
1520                         uiDefButS(block, NUM, 0, "", 0, 0, 5.0f * UI_UNIT_X, UI_UNIT_Y, &coba->cur, 0.0, (float)(MAX2(0, coba->tot - 1)),
1521                                   0, 0, TIP_("Choose active color stop"));
1522                         row = uiLayoutRow(split, false);
1523                         uiItemR(row, &ptr, "position", 0, IFACE_("Pos"), ICON_NONE);
1524                         bt = block->buttons.last;
1525                         uiButSetFunc(bt, colorband_update_cb, bt, coba);
1526
1527                         row = uiLayoutRow(layout, false);
1528                         uiItemR(row, &ptr, "color", 0, "", ICON_NONE);
1529                 }
1530                 else {
1531                         split = uiLayoutSplit(layout, 0.5f, false);
1532                         subsplit = uiLayoutSplit(split, 0.35f, false);
1533
1534                         row = uiLayoutRow(subsplit, false);
1535                         uiDefButS(block, NUM, 0, "", 0, 0, 5.0f * UI_UNIT_X, UI_UNIT_Y, &coba->cur, 0.0, (float)(MAX2(0, coba->tot - 1)),
1536                                   0, 0, TIP_("Choose active color stop"));
1537                         row = uiLayoutRow(subsplit, false);
1538                         uiItemR(row, &ptr, "position", 0, IFACE_("Pos"), ICON_NONE);
1539                         bt = block->buttons.last;
1540                         uiButSetFunc(bt, colorband_update_cb, bt, coba);
1541
1542                         row = uiLayoutRow(split, false);
1543                         uiItemR(row, &ptr, "color", 0, "", ICON_NONE);
1544                 }
1545         }
1546 }
1547
1548 void uiTemplateColorRamp(uiLayout *layout, PointerRNA *ptr, const char *propname, int expand)
1549 {
1550         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1551         PointerRNA cptr;
1552         RNAUpdateCb *cb;
1553         uiBlock *block;
1554         rctf rect;
1555
1556         if (!prop || RNA_property_type(prop) != PROP_POINTER)
1557                 return;
1558
1559         cptr = RNA_property_pointer_get(ptr, prop);
1560         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_ColorRamp))
1561                 return;
1562
1563         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
1564         cb->ptr = *ptr;
1565         cb->prop = prop;
1566
1567         rect.xmin = 0; rect.xmax = 10.0f * UI_UNIT_X;
1568         rect.ymin = 0; rect.ymax = 19.5f * UI_UNIT_X;
1569
1570         block = uiLayoutAbsoluteBlock(layout);
1571         colorband_buttons_layout(layout, block, cptr.data, &rect, cb, expand);
1572
1573         MEM_freeN(cb);
1574 }
1575
1576
1577 /********************* Icon viewer Template ************************/
1578
1579 /* ID Search browse menu, open */
1580 static uiBlock *icon_view_menu(bContext *C, ARegion *ar, void *arg_litem)
1581 {
1582         static RNAUpdateCb cb;
1583         uiBlock *block;
1584         uiBut *but;
1585         int icon;
1586         EnumPropertyItem *item;
1587         int a, free;
1588
1589         /* arg_litem is malloced, can be freed by parent button */
1590         cb = *((RNAUpdateCb *)arg_litem);
1591         
1592         /* unused */
1593         // icon = RNA_property_enum_get(&cb.ptr, cb.prop);
1594         
1595         block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
1596         uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW);
1597         
1598         
1599         RNA_property_enum_items(C, &cb.ptr, cb.prop, &item, NULL, &free);
1600         
1601         for (a = 0; item[a].identifier; a++) {
1602                 int x, y;
1603                 
1604                 /* XXX hardcoded size to 5 x unit */
1605                 x = (a % 8) * UI_UNIT_X * 5;
1606                 y = (a / 8) * UI_UNIT_X * 5;
1607                 
1608                 icon = item[a].icon;
1609                 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);
1610                 uiButSetFlag(but, UI_HAS_ICON | UI_ICON_PREVIEW);
1611         }
1612
1613         uiBoundsBlock(block, 0.3f * U.widget_unit);
1614         uiBlockSetDirection(block, UI_TOP);
1615         uiEndBlock(C, block);
1616                 
1617         if (free) {
1618                 MEM_freeN(item);
1619         }
1620         
1621         return block;
1622 }
1623
1624 void uiTemplateIconView(uiLayout *layout, PointerRNA *ptr, const char *propname)
1625 {
1626         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1627         RNAUpdateCb *cb;
1628         uiBlock *block;
1629         uiBut *but;
1630 //      rctf rect;  /* UNUSED */
1631         int icon;
1632         
1633         if (!prop || RNA_property_type(prop) != PROP_ENUM)
1634                 return;
1635         
1636         icon = RNA_property_enum_get(ptr, prop);
1637         
1638         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
1639         cb->ptr = *ptr;
1640         cb->prop = prop;
1641         
1642 //      rect.xmin = 0; rect.xmax = 10.0f * UI_UNIT_X;
1643 //      rect.ymin = 0; rect.ymax = 10.0f * UI_UNIT_X;
1644         
1645         block = uiLayoutAbsoluteBlock(layout);
1646
1647         but = uiDefBlockButN(block, icon_view_menu, MEM_dupallocN(cb), "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6, "");
1648
1649         
1650 //      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);
1651         
1652         but->icon = icon;
1653         uiButSetFlag(but, UI_HAS_ICON | UI_ICON_PREVIEW);
1654         
1655         uiButSetNFunc(but, rna_update_cb, MEM_dupallocN(cb), NULL);
1656         
1657         MEM_freeN(cb);
1658 }
1659
1660 /********************* Histogram Template ************************/
1661
1662 void uiTemplateHistogram(uiLayout *layout, PointerRNA *ptr, const char *propname)
1663 {
1664         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1665         PointerRNA cptr;
1666         RNAUpdateCb *cb;
1667         uiBlock *block;
1668         uiBut *bt;
1669         Histogram *hist;
1670         rctf rect;
1671         
1672         if (!prop || RNA_property_type(prop) != PROP_POINTER)
1673                 return;
1674         
1675         cptr = RNA_property_pointer_get(ptr, prop);
1676         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Histogram))
1677                 return;
1678         
1679         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
1680         cb->ptr = *ptr;
1681         cb->prop = prop;
1682         
1683         rect.xmin = 0; rect.xmax = 10.0f * UI_UNIT_X;
1684         rect.ymin = 0; rect.ymax = 9.5f * UI_UNIT_Y;
1685         
1686         block = uiLayoutAbsoluteBlock(layout);
1687         //colorband_buttons_layout(layout, block, cptr.data, &rect, !expand, cb);
1688
1689         hist = (Histogram *)cptr.data;
1690
1691         hist->height = (hist->height <= 20) ? 20 : hist->height;
1692
1693         bt = uiDefBut(block, HISTOGRAM, 0, "", rect.xmin, rect.ymin, BLI_rctf_size_x(&rect), UI_DPI_FAC * hist->height,
1694                       hist, 0, 0, 0, 0, "");
1695
1696         uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1697
1698         MEM_freeN(cb);
1699 }
1700
1701 /********************* Waveform Template ************************/
1702
1703 void uiTemplateWaveform(uiLayout *layout, PointerRNA *ptr, const char *propname)
1704 {
1705         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1706         PointerRNA cptr;
1707         RNAUpdateCb *cb;
1708         uiBlock *block;
1709         uiBut *bt;
1710         Scopes *scopes;
1711         rctf rect;
1712         
1713         if (!prop || RNA_property_type(prop) != PROP_POINTER)
1714                 return;
1715         
1716         cptr = RNA_property_pointer_get(ptr, prop);
1717         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Scopes))
1718                 return;
1719         scopes = (Scopes *)cptr.data;
1720         
1721         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
1722         cb->ptr = *ptr;
1723         cb->prop = prop;
1724         
1725         rect.xmin = 0; rect.xmax = 10.0f * UI_UNIT_X;
1726         rect.ymin = 0; rect.ymax = 9.5f * UI_UNIT_Y;
1727         
1728         block = uiLayoutAbsoluteBlock(layout);
1729         
1730         scopes->wavefrm_height = (scopes->wavefrm_height <= 20) ? 20 : scopes->wavefrm_height;
1731
1732         bt = uiDefBut(block, WAVEFORM, 0, "", rect.xmin, rect.ymin, BLI_rctf_size_x(&rect), UI_DPI_FAC * scopes->wavefrm_height,
1733                       scopes, 0, 0, 0, 0, "");
1734         (void)bt;  /* UNUSED */
1735         
1736         MEM_freeN(cb);
1737 }
1738
1739 /********************* Vectorscope Template ************************/
1740
1741 void uiTemplateVectorscope(uiLayout *layout, PointerRNA *ptr, const char *propname)
1742 {
1743         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1744         PointerRNA cptr;
1745         RNAUpdateCb *cb;
1746         uiBlock *block;
1747         uiBut *bt;
1748         Scopes *scopes;
1749         rctf rect;
1750         
1751         if (!prop || RNA_property_type(prop) != PROP_POINTER)
1752                 return;
1753         
1754         cptr = RNA_property_pointer_get(ptr, prop);
1755         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Scopes))
1756                 return;
1757         scopes = (Scopes *)cptr.data;
1758
1759         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
1760         cb->ptr = *ptr;
1761         cb->prop = prop;
1762         
1763         rect.xmin = 0; rect.xmax = 10.0f * UI_UNIT_X;
1764         rect.ymin = 0; rect.ymax = 9.5f * UI_UNIT_Y;
1765         
1766         block = uiLayoutAbsoluteBlock(layout);
1767
1768         scopes->vecscope_height = (scopes->vecscope_height <= 20) ? 20 : scopes->vecscope_height;
1769         
1770         bt = uiDefBut(block, VECTORSCOPE, 0, "", rect.xmin, rect.ymin, BLI_rctf_size_x(&rect),
1771                       UI_DPI_FAC * scopes->vecscope_height, scopes, 0, 0, 0, 0, "");
1772         uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1773         
1774         MEM_freeN(cb);
1775 }
1776
1777 /********************* CurveMapping Template ************************/
1778
1779
1780 static void curvemap_buttons_zoom_in(bContext *C, void *cumap_v, void *UNUSED(arg))
1781 {
1782         CurveMapping *cumap = cumap_v;
1783         float d;
1784
1785         /* we allow 20 times zoom */
1786         if (BLI_rctf_size_x(&cumap->curr) > 0.04f * BLI_rctf_size_x(&cumap->clipr)) {
1787                 d = 0.1154f * BLI_rctf_size_x(&cumap->curr);
1788                 cumap->curr.xmin += d;
1789                 cumap->curr.xmax -= d;
1790                 d = 0.1154f * BLI_rctf_size_y(&cumap->curr);
1791                 cumap->curr.ymin += d;
1792                 cumap->curr.ymax -= d;
1793         }
1794
1795         ED_region_tag_redraw(CTX_wm_region(C));
1796 }
1797
1798 static void curvemap_buttons_zoom_out(bContext *C, void *cumap_v, void *UNUSED(unused))
1799 {
1800         CurveMapping *cumap = cumap_v;
1801         float d, d1;
1802
1803         /* we allow 20 times zoom, but don't view outside clip */
1804         if (BLI_rctf_size_x(&cumap->curr) < 20.0f * BLI_rctf_size_x(&cumap->clipr)) {
1805                 d = d1 = 0.15f * BLI_rctf_size_x(&cumap->curr);
1806
1807                 if (cumap->flag & CUMA_DO_CLIP) 
1808                         if (cumap->curr.xmin - d < cumap->clipr.xmin)
1809                                 d1 = cumap->curr.xmin - cumap->clipr.xmin;
1810                 cumap->curr.xmin -= d1;
1811
1812                 d1 = d;
1813                 if (cumap->flag & CUMA_DO_CLIP) 
1814                         if (cumap->curr.xmax + d > cumap->clipr.xmax)
1815                                 d1 = -cumap->curr.xmax + cumap->clipr.xmax;
1816                 cumap->curr.xmax += d1;
1817
1818                 d = d1 = 0.15f * BLI_rctf_size_y(&cumap->curr);
1819
1820                 if (cumap->flag & CUMA_DO_CLIP) 
1821                         if (cumap->curr.ymin - d < cumap->clipr.ymin)
1822                                 d1 = cumap->curr.ymin - cumap->clipr.ymin;
1823                 cumap->curr.ymin -= d1;
1824
1825                 d1 = d;
1826                 if (cumap->flag & CUMA_DO_CLIP) 
1827                         if (cumap->curr.ymax + d > cumap->clipr.ymax)
1828                                 d1 = -cumap->curr.ymax + cumap->clipr.ymax;
1829                 cumap->curr.ymax += d1;
1830         }
1831
1832         ED_region_tag_redraw(CTX_wm_region(C));
1833 }
1834
1835 static void curvemap_buttons_setclip(bContext *UNUSED(C), void *cumap_v, void *UNUSED(arg))
1836 {
1837         CurveMapping *cumap = cumap_v;
1838
1839         curvemapping_changed(cumap, false);
1840 }       
1841
1842 static void curvemap_buttons_delete(bContext *C, void *cb_v, void *cumap_v)
1843 {
1844         CurveMapping *cumap = cumap_v;
1845
1846         curvemap_remove(cumap->cm + cumap->cur, SELECT);
1847         curvemapping_changed(cumap, false);
1848
1849         rna_update_cb(C, cb_v, NULL);
1850 }
1851
1852 /* NOTE: this is a block-menu, needs 0 events, otherwise the menu closes */
1853 static uiBlock *curvemap_clipping_func(bContext *C, ARegion *ar, void *cumap_v)
1854 {
1855         CurveMapping *cumap = cumap_v;
1856         uiBlock *block;
1857         uiBut *bt;
1858         float width = 8 * UI_UNIT_X;
1859
1860         block = uiBeginBlock(C, ar, __func__, UI_EMBOSS);
1861
1862         /* use this for a fake extra empy space around the buttons */
1863         uiDefBut(block, LABEL, 0, "",           -4, 16, width + 8, 6 * UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
1864
1865         bt = uiDefButBitI(block, TOG, CUMA_DO_CLIP, 1, IFACE_("Use Clipping"),
1866                           0, 5 * UI_UNIT_Y, width, UI_UNIT_Y, &cumap->flag, 0.0, 0.0, 10, 0, "");
1867         uiButSetFunc(bt, curvemap_buttons_setclip, cumap, NULL);
1868
1869         uiBlockBeginAlign(block);
1870         uiDefButF(block, NUM, 0, IFACE_("Min X "),   0, 4 * UI_UNIT_Y, width, UI_UNIT_Y,
1871                   &cumap->clipr.xmin, -100.0, cumap->clipr.xmax, 10, 2, "");
1872         uiDefButF(block, NUM, 0, IFACE_("Min Y "),   0, 3 * UI_UNIT_Y, width, UI_UNIT_Y,
1873                   &cumap->clipr.ymin, -100.0, cumap->clipr.ymax, 10, 2, "");
1874         uiDefButF(block, NUM, 0, IFACE_("Max X "),   0, 2 * UI_UNIT_Y, width, UI_UNIT_Y,
1875                   &cumap->clipr.xmax, cumap->clipr.xmin, 100.0, 10, 2, "");
1876         uiDefButF(block, NUM, 0, IFACE_("Max Y "),   0, UI_UNIT_Y, width, UI_UNIT_Y,
1877                   &cumap->clipr.ymax, cumap->clipr.ymin, 100.0, 10, 2, "");
1878
1879         uiBlockSetDirection(block, UI_RIGHT);
1880
1881         uiEndBlock(C, block);
1882         return block;
1883 }
1884
1885 /* only for curvemap_tools_dofunc */
1886 enum {
1887         UICURVE_FUNC_RESET_NEG,
1888         UICURVE_FUNC_RESET_POS,
1889         UICURVE_FUNC_RESET_VIEW,
1890         UICURVE_FUNC_HANDLE_VECTOR,
1891         UICURVE_FUNC_HANDLE_AUTO,
1892         UICURVE_FUNC_EXTEND_HOZ,
1893         UICURVE_FUNC_EXTEND_EXP,
1894 };
1895
1896 static void curvemap_tools_dofunc(bContext *C, void *cumap_v, int event)
1897 {
1898         CurveMapping *cumap = cumap_v;
1899         CurveMap *cuma = cumap->cm + cumap->cur;
1900
1901         switch (event) {
1902                 case UICURVE_FUNC_RESET_NEG:
1903                 case UICURVE_FUNC_RESET_POS: /* reset */
1904                         curvemap_reset(cuma, &cumap->clipr, cumap->preset,
1905                                        (event == UICURVE_FUNC_RESET_NEG) ? CURVEMAP_SLOPE_NEGATIVE : CURVEMAP_SLOPE_POSITIVE);
1906                         curvemapping_changed(cumap, false);
1907                         break;
1908                 case UICURVE_FUNC_RESET_VIEW:
1909                         cumap->curr = cumap->clipr;
1910                         break;
1911                 case UICURVE_FUNC_HANDLE_VECTOR: /* set vector */
1912                         curvemap_sethandle(cuma, 1);
1913                         curvemapping_changed(cumap, false);
1914                         break;
1915                 case UICURVE_FUNC_HANDLE_AUTO: /* set auto */
1916                         curvemap_sethandle(cuma, 0);
1917                         curvemapping_changed(cumap, false);
1918                         break;
1919                 case UICURVE_FUNC_EXTEND_HOZ: /* extend horiz */
1920                         cuma->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
1921                         curvemapping_changed(cumap, false);
1922                         break;
1923                 case UICURVE_FUNC_EXTEND_EXP: /* extend extrapolate */
1924                         cuma->flag |= CUMA_EXTEND_EXTRAPOLATE;
1925                         curvemapping_changed(cumap, false);
1926                         break;
1927         }
1928         ED_region_tag_redraw(CTX_wm_region(C));
1929 }
1930
1931 static uiBlock *curvemap_tools_func(bContext *C, ARegion *ar, void *cumap_v)
1932 {
1933         uiBlock *block;
1934         short yco = 0, menuwidth = 10 * UI_UNIT_X;
1935
1936         block = uiBeginBlock(C, ar, __func__, UI_EMBOSS);
1937         uiBlockSetButmFunc(block, curvemap_tools_dofunc, cumap_v);
1938
1939         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Reset View"),          0, yco -= UI_UNIT_Y,
1940                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_RESET_VIEW, "");
1941         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Vector Handle"),       0, yco -= UI_UNIT_Y,
1942                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_VECTOR, "");
1943         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Auto Handle"),         0, yco -= UI_UNIT_Y,
1944                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_AUTO, "");
1945         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Extend Horizontal"),   0, yco -= UI_UNIT_Y,
1946                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_EXTEND_HOZ, "");
1947         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Extend Extrapolated"), 0, yco -= UI_UNIT_Y,
1948                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_EXTEND_EXP, "");
1949         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Reset Curve"),         0, yco -= UI_UNIT_Y,
1950                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_RESET_POS, "");
1951
1952         uiBlockSetDirection(block, UI_RIGHT);
1953         uiTextBoundsBlock(block, 50);
1954
1955         uiEndBlock(C, block);
1956         return block;
1957 }
1958
1959 static uiBlock *curvemap_brush_tools_func(bContext *C, ARegion *ar, void *cumap_v)
1960 {
1961         uiBlock *block;
1962         short yco = 0, menuwidth = 10 * UI_UNIT_X;
1963
1964         block = uiBeginBlock(C, ar, __func__, UI_EMBOSS);
1965         uiBlockSetButmFunc(block, curvemap_tools_dofunc, cumap_v);
1966
1967         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Reset View"),    0, yco -= UI_UNIT_Y,
1968                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_RESET_VIEW, "");
1969         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Vector Handle"), 0, yco -= UI_UNIT_Y,
1970                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_VECTOR, "");
1971         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Auto Handle"),   0, yco -= UI_UNIT_Y,
1972                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_AUTO, "");
1973         uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, IFACE_("Reset Curve"),   0, yco -= UI_UNIT_Y,
1974                          menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_RESET_NEG, "");
1975
1976         uiBlockSetDirection(block, UI_RIGHT);
1977         uiTextBoundsBlock(block, 50);
1978
1979         uiEndBlock(C, block);
1980         return block;
1981 }
1982
1983 static void curvemap_buttons_redraw(bContext *C, void *UNUSED(arg1), void *UNUSED(arg2))
1984 {
1985         ED_region_tag_redraw(CTX_wm_region(C));
1986 }
1987
1988 static void curvemap_buttons_update(bContext *C, void *arg1_v, void *cumap_v)
1989 {
1990         CurveMapping *cumap = cumap_v;
1991         curvemapping_changed(cumap, true);
1992         rna_update_cb(C, arg1_v, NULL);
1993 }
1994
1995 static void curvemap_buttons_reset(bContext *C, void *cb_v, void *cumap_v)
1996 {
1997         CurveMapping *cumap = cumap_v;
1998         int a;
1999         
2000         cumap->preset = CURVE_PRESET_LINE;
2001         for (a = 0; a < CM_TOT; a++)
2002                 curvemap_reset(cumap->cm + a, &cumap->clipr, cumap->preset, CURVEMAP_SLOPE_POSITIVE);
2003         
2004         cumap->black[0] = cumap->black[1] = cumap->black[2] = 0.0f;
2005         cumap->white[0] = cumap->white[1] = cumap->white[2] = 1.0f;
2006         curvemapping_set_black_white(cumap, NULL, NULL);
2007         
2008         curvemapping_changed(cumap, false);
2009
2010         rna_update_cb(C, cb_v, NULL);
2011 }
2012
2013 /* still unsure how this call evolves... we use labeltype for defining what curve-channels to show */
2014 static void curvemap_buttons_layout(uiLayout *layout, PointerRNA *ptr, char labeltype, int levels,
2015                                     int brush, RNAUpdateCb *cb)
2016 {
2017         CurveMapping *cumap = ptr->data;
2018         CurveMap *cm = &cumap->cm[cumap->cur];
2019         CurveMapPoint *cmp = NULL;
2020         uiLayout *row, *sub, *split;
2021         uiBlock *block;
2022         uiBut *bt;
2023         float dx = UI_UNIT_X;
2024         int icon, size;
2025         int bg = -1, i;
2026
2027         block = uiLayoutGetBlock(layout);
2028
2029         /* curve chooser */
2030         row = uiLayoutRow(layout, false);
2031
2032         if (labeltype == 'v') {
2033                 /* vector */
2034                 sub = uiLayoutRow(row, true);
2035                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2036
2037                 if (cumap->cm[0].curve) {
2038                         bt = uiDefButI(block, ROW, 0, "X", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2039                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2040                 }
2041                 if (cumap->cm[1].curve) {
2042                         bt = uiDefButI(block, ROW, 0, "Y", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2043                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2044                 }
2045                 if (cumap->cm[2].curve) {
2046                         bt = uiDefButI(block, ROW, 0, "Z", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2047                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2048                 }
2049         }
2050         else if (labeltype == 'c') {
2051                 /* color */
2052                 sub = uiLayoutRow(row, true);
2053                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2054
2055                 if (cumap->cm[3].curve) {
2056                         bt = uiDefButI(block, ROW, 0, "C", 0, 0, dx, dx, &cumap->cur, 0.0, 3.0, 0.0, 0.0, "");
2057                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2058                 }
2059                 if (cumap->cm[0].curve) {
2060                         bt = uiDefButI(block, ROW, 0, "R", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2061                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2062                 }
2063                 if (cumap->cm[1].curve) {
2064                         bt = uiDefButI(block, ROW, 0, "G", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2065                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2066                 }
2067                 if (cumap->cm[2].curve) {
2068                         bt = uiDefButI(block, ROW, 0, "B", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2069                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2070                 }
2071         }
2072         else if (labeltype == 'h') {
2073                 /* HSV */
2074                 sub = uiLayoutRow(row, true);
2075                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2076                 
2077                 if (cumap->cm[0].curve) {
2078                         bt = uiDefButI(block, ROW, 0, "H", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2079                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2080                 }
2081                 if (cumap->cm[1].curve) {
2082                         bt = uiDefButI(block, ROW, 0, "S", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2083                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2084                 }
2085                 if (cumap->cm[2].curve) {
2086                         bt = uiDefButI(block, ROW, 0, "V", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2087                         uiButSetFunc(bt, curvemap_buttons_redraw, NULL, NULL);
2088                 }
2089         }
2090         else
2091                 uiLayoutSetAlignment(row, UI_LAYOUT_ALIGN_RIGHT);
2092         
2093         if (labeltype == 'h')
2094                 bg = UI_GRAD_H;
2095
2096         /* operation buttons */
2097         sub = uiLayoutRow(row, true);
2098
2099         uiBlockSetEmboss(block, UI_EMBOSSN);
2100
2101         bt = uiDefIconBut(block, BUT, 0, ICON_ZOOMIN, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Zoom in"));
2102         uiButSetFunc(bt, curvemap_buttons_zoom_in, cumap, NULL);
2103
2104         bt = uiDefIconBut(block, BUT, 0, ICON_ZOOMOUT, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Zoom out"));
2105         uiButSetFunc(bt, curvemap_buttons_zoom_out, cumap, NULL);
2106
2107         if (brush)
2108                 bt = uiDefIconBlockBut(block, curvemap_brush_tools_func, cumap, 0, ICON_MODIFIER, 0, 0, dx, dx, TIP_("Tools"));
2109         else
2110                 bt = uiDefIconBlockBut(block, curvemap_tools_func, cumap, 0, ICON_MODIFIER, 0, 0, dx, dx, TIP_("Tools"));
2111
2112         uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
2113
2114         icon = (cumap->flag & CUMA_DO_CLIP) ? ICON_CLIPUV_HLT : ICON_CLIPUV_DEHLT;
2115         bt = uiDefIconBlockBut(block, curvemap_clipping_func, cumap, 0, icon, 0, 0, dx, dx, TIP_("Clipping Options"));
2116         uiButSetNFunc(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
2117
2118         bt = uiDefIconBut(block, BUT, 0, ICON_X, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Delete points"));
2119         uiButSetNFunc(bt, curvemap_buttons_delete, MEM_dupallocN(cb), cumap);
2120
2121         uiBlockSetEmboss(block, UI_EMBOSS);
2122
2123         uiBlockSetNFunc(block, rna_update_cb, MEM_dupallocN(cb), NULL);
2124
2125         /* curve itself */
2126         size = uiLayoutGetWidth(layout);
2127         row = uiLayoutRow(layout, false);
2128         uiDefBut(block, BUT_CURVE, 0, "", 0, 0, size, 8.0f * UI_UNIT_X, cumap, 0.0f, 1.0f, bg, 0, "");
2129
2130         /* sliders for selected point */
2131         for (i = 0; i < cm->totpoint; i++) {
2132                 if (cm->curve[i].flag & CUMA_SELECT) {
2133                         cmp = &cm->curve[i];
2134                         break;
2135                 }
2136         }
2137
2138         if (cmp) {
2139                 rctf bounds;
2140
2141                 if (cumap->flag & CUMA_DO_CLIP) {
2142                         bounds = cumap->clipr;
2143                 }
2144                 else {
2145                         bounds.xmin = bounds.ymin = -1000.0;
2146                         bounds.xmax = bounds.ymax =  1000.0;
2147                 }
2148
2149                 uiLayoutRow(layout, true);
2150                 uiBlockSetNFunc(block, curvemap_buttons_update, MEM_dupallocN(cb), cumap);
2151                 uiDefButF(block, NUM, 0, "X", 0, 2 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y,
2152                           &cmp->x, bounds.xmin, bounds.xmax, 1, 5, "");
2153                 uiDefButF(block, NUM, 0, "Y", 0, 1 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y,
2154                           &cmp->y, bounds.ymin, bounds.ymax, 1, 5, "");
2155         }
2156
2157         /* black/white levels */
2158         if (levels) {
2159                 split = uiLayoutSplit(layout, 0.0f, false);
2160                 uiItemR(uiLayoutColumn(split, false), ptr, "black_level", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
2161                 uiItemR(uiLayoutColumn(split, false), ptr, "white_level", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
2162
2163                 uiLayoutRow(layout, false);
2164                 bt = uiDefBut(block, BUT, 0, IFACE_("Reset"), 0, 0, UI_UNIT_X * 10, UI_UNIT_Y, NULL, 0.0f, 0.0f, 0, 0,
2165                               TIP_("Reset Black/White point and curves"));
2166                 uiButSetNFunc(bt, curvemap_buttons_reset, MEM_dupallocN(cb), cumap);
2167         }
2168
2169         uiBlockSetNFunc(block, NULL, NULL, NULL);
2170 }
2171
2172 void uiTemplateCurveMapping(uiLayout *layout, PointerRNA *ptr, const char *propname, int type, int levels, int brush)
2173 {
2174         RNAUpdateCb *cb;
2175         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2176         PointerRNA cptr;
2177
2178         if (!prop) {
2179                 RNA_warning("curve property not found: %s.%s",
2180                             RNA_struct_identifier(ptr->type), propname);
2181                 return;
2182         }
2183
2184         if (RNA_property_type(prop) != PROP_POINTER) {
2185                 RNA_warning("curve is not a pointer: %s.%s",
2186                             RNA_struct_identifier(ptr->type), propname);
2187                 return;
2188         }
2189
2190         cptr = RNA_property_pointer_get(ptr, prop);
2191         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_CurveMapping))
2192                 return;
2193
2194         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
2195         cb->ptr = *ptr;
2196         cb->prop = prop;
2197
2198         curvemap_buttons_layout(layout, &cptr, type, levels, brush, cb);
2199
2200         MEM_freeN(cb);
2201 }
2202
2203 /********************* ColorPicker Template ************************/
2204
2205 #define WHEEL_SIZE  (5 * U.widget_unit)
2206
2207 /* This template now follows User Preference for type - name is not correct anymore... */
2208 void uiTemplateColorPicker(uiLayout *layout, PointerRNA *ptr, const char *propname, int value_slider,
2209                            int lock, int lock_luminosity, int cubic)
2210 {
2211         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2212         uiBlock *block = uiLayoutGetBlock(layout);
2213         uiLayout *col, *row;
2214         uiBut *but = NULL;
2215         float softmin, softmax, step, precision;
2216
2217         if (!prop) {
2218                 RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2219                 return;
2220         }
2221
2222         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2223
2224         col = uiLayoutColumn(layout, true);
2225         row = uiLayoutRow(col, true);
2226
2227         switch (U.color_picker_type) {
2228                 case USER_CP_CIRCLE:
2229                         but = uiDefButR_prop(block, HSVCIRCLE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2230                                              -1, 0.0, 0.0, 0, 0, "");
2231                         break;
2232                 case USER_CP_SQUARE_SV:
2233                         but = uiDefButR_prop(block, HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2234                                              -1, 0.0, 0.0, UI_GRAD_SV, 0, "");
2235                         break;
2236                 case USER_CP_SQUARE_HS:
2237                         but = uiDefButR_prop(block, HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2238                                              -1, 0.0, 0.0, UI_GRAD_HS, 0, "");
2239                         break;
2240                 case USER_CP_SQUARE_HV:
2241                         but = uiDefButR_prop(block, HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2242                                              -1, 0.0, 0.0, UI_GRAD_HV, 0, "");
2243                         break;
2244         }
2245
2246         if (lock) {
2247                 but->flag |= UI_BUT_COLOR_LOCK;
2248         }
2249
2250         if (lock_luminosity) {
2251                 float color[4]; /* in case of alpha */
2252                 but->flag |= UI_BUT_VEC_SIZE_LOCK;
2253                 RNA_property_float_get_array(ptr, prop, color);
2254                 but->a2 = len_v3(color);
2255         }
2256
2257         if (cubic)
2258                 but->flag |= UI_BUT_COLOR_CUBIC;
2259
2260         
2261         if (value_slider) {
2262                 switch (U.color_picker_type) {
2263                         case USER_CP_CIRCLE:
2264                                 uiItemS(row);
2265                                 uiDefButR_prop(block, HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop,
2266                                                -1, softmin, softmax, UI_GRAD_V_ALT, 0, "");
2267                                 break;
2268                         case USER_CP_SQUARE_SV:
2269                                 uiItemS(col);
2270                                 uiDefButR_prop(block, HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2271                                                -1, softmin, softmax, UI_GRAD_SV + 3, 0, "");
2272                                 break;
2273                         case USER_CP_SQUARE_HS:
2274                                 uiItemS(col);
2275                                 uiDefButR_prop(block, HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2276                                                -1, softmin, softmax, UI_GRAD_HS + 3, 0, "");
2277                                 break;
2278                         case USER_CP_SQUARE_HV:
2279                                 uiItemS(col);
2280                                 uiDefButR_prop(block, HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2281                                                -1, softmin, softmax, UI_GRAD_HV + 3, 0, "");
2282                                 break;
2283                 }
2284         }
2285 }
2286
2287 /********************* Layer Buttons Template ************************/
2288
2289 static void handle_layer_buttons(bContext *C, void *arg1, void *arg2)
2290 {
2291         uiBut *but = arg1;
2292         int cur = GET_INT_FROM_POINTER(arg2);
2293         wmWindow *win = CTX_wm_window(C);
2294         int i, tot, shift = win->eventstate->shift;
2295
2296         if (!shift) {
2297                 tot = RNA_property_array_length(&but->rnapoin, but->rnaprop);
2298                 
2299                 /* Normally clicking only selects one layer */
2300                 RNA_property_boolean_set_index(&but->rnapoin, but->rnaprop, cur, true);
2301                 for (i = 0; i < tot; ++i) {
2302                         if (i != cur)
2303                                 RNA_property_boolean_set_index(&but->rnapoin, but->rnaprop, i, false);
2304                 }
2305         }
2306
2307         /* view3d layer change should update depsgraph (invisible object changed maybe) */
2308         /* see view3d_header.c */
2309 }
2310
2311 /* TODO:
2312  * - for now, grouping of layers is determined by dividing up the length of
2313  *   the array of layer bitflags */
2314
2315 void uiTemplateLayers(uiLayout *layout, PointerRNA *ptr, const char *propname,
2316                       PointerRNA *used_ptr, const char *used_propname, int active_layer)
2317 {
2318         uiLayout *uRow, *uCol;
2319         PropertyRNA *prop, *used_prop = NULL;
2320         int groups, cols, layers;
2321         int group, col, layer, row;
2322         int cols_per_group = 5;
2323
2324         prop = RNA_struct_find_property(ptr, propname);
2325         if (!prop) {
2326                 RNA_warning("layers property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2327                 return;
2328         }
2329         
2330         /* the number of layers determines the way we group them 
2331          *      - we want 2 rows only (for now)
2332          *      - the number of columns (cols) is the total number of buttons per row
2333          *        the 'remainder' is added to this, as it will be ok to have first row slightly wider if need be
2334          *      - for now, only split into groups if group will have at least 5 items
2335          */
2336         layers = RNA_property_array_length(ptr, prop);
2337         cols = (layers / 2) + (layers % 2);
2338         groups = ((cols / 2) < cols_per_group) ? (1) : (cols / cols_per_group);
2339
2340         if (used_ptr && used_propname) {
2341                 used_prop = RNA_struct_find_property(used_ptr, used_propname);
2342                 if (!used_prop) {
2343                         RNA_warning("used layers property not found: %s.%s", RNA_struct_identifier(ptr->type), used_propname);
2344                         return;
2345                 }
2346
2347                 if (RNA_property_array_length(used_ptr, used_prop) < layers)
2348                         used_prop = NULL;
2349         }
2350         
2351         /* layers are laid out going across rows, with the columns being divided into groups */
2352         
2353         for (group = 0; group < groups; group++) {
2354                 uCol = uiLayoutColumn(layout, true);
2355                 
2356                 for (row = 0; row < 2; row++) {
2357                         uiBlock *block;
2358                         uiBut *but;
2359
2360                         uRow = uiLayoutRow(uCol, true);
2361                         block = uiLayoutGetBlock(uRow);
2362                         layer = groups * cols_per_group * row + cols_per_group * group;
2363                         
2364                         /* add layers as toggle buts */
2365                         for (col = 0; (col < cols_per_group) && (layer < layers); col++, layer++) {
2366                                 int icon = 0;
2367                                 int butlay = 1 << layer;
2368
2369                                 if (active_layer & butlay)
2370                                         icon = ICON_LAYER_ACTIVE;
2371                                 else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, layer))
2372                                         icon = ICON_LAYER_USED;
2373                                 
2374                                 but = uiDefAutoButR(block, ptr, prop, layer, "", icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2);
2375                                 uiButSetFunc(but, handle_layer_buttons, but, SET_INT_IN_POINTER(layer));
2376                                 but->type = TOG;
2377                         }
2378                 }
2379         }
2380 }
2381
2382 void uiTemplateGameStates(uiLayout *layout, PointerRNA *ptr, const char *propname,
2383                       PointerRNA *used_ptr, const char *used_propname, int active_state)
2384 {
2385         uiLayout *uRow, *uCol;
2386         PropertyRNA *prop, *used_prop = NULL;
2387         int groups, cols, states;
2388         int group, col, state, row;
2389         int cols_per_group = 5;
2390         Object *ob = (Object *)ptr->id.data;
2391
2392         prop = RNA_struct_find_property(ptr, propname);
2393         if (!prop) {
2394                 RNA_warning("states property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2395                 return;
2396         }
2397         
2398         /* the number of states determines the way we group them 
2399          *      - we want 2 rows only (for now)
2400          *      - the number of columns (cols) is the total number of buttons per row
2401          *        the 'remainder' is added to this, as it will be ok to have first row slightly wider if need be
2402          *      - for now, only split into groups if group will have at least 5 items
2403          */
2404         states = RNA_property_array_length(ptr, prop);
2405         cols = (states / 2) + (states % 2);
2406         groups = ((cols / 2) < cols_per_group) ? (1) : (cols / cols_per_group);
2407
2408         if (used_ptr && used_propname) {
2409                 used_prop = RNA_struct_find_property(used_ptr, used_propname);
2410                 if (!used_prop) {
2411                         RNA_warning("used layers property not found: %s.%s", RNA_struct_identifier(ptr->type), used_propname);
2412                         return;
2413                 }
2414
2415                 if (RNA_property_array_length(used_ptr, used_prop) < states)
2416                         used_prop = NULL;
2417         }
2418         
2419         /* layers are laid out going across rows, with the columns being divided into groups */
2420         
2421         for (group = 0; group < groups; group++) {
2422                 uCol = uiLayoutColumn(layout, true);
2423                 
2424                 for (row = 0; row < 2; row++) {
2425                         uiBlock *block;
2426                         uiBut *but;
2427
2428                         uRow = uiLayoutRow(uCol, true);
2429                         block = uiLayoutGetBlock(uRow);
2430                         state = groups * cols_per_group * row + cols_per_group * group;
2431                         
2432                         /* add layers as toggle buts */
2433                         for (col = 0; (col < cols_per_group) && (state < states); col++, state++) {
2434                                 int icon = 0;
2435                                 int butlay = 1 << state;
2436
2437                                 if (active_state & butlay)
2438                                         icon = ICON_LAYER_ACTIVE;
2439                                 else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, state))
2440                                         icon = ICON_LAYER_USED;
2441                                 
2442                                 but = uiDefIconButR_prop(block, ICONTOG, 0, icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2, ptr, prop,
2443                                                          state, 0, 0, -1, -1, sca_state_name_get(ob, state));
2444                                 uiButSetFunc(but, handle_layer_buttons, but, SET_INT_IN_POINTER(state));
2445                                 but->type = TOG;
2446                         }
2447                 }
2448         }
2449 }
2450
2451
2452 /************************* List Template **************************/
2453 static void uilist_draw_item_default(struct uiList *ui_list, struct bContext *UNUSED(C), struct uiLayout *layout,
2454                                      struct PointerRNA *UNUSED(dataptr), struct PointerRNA *itemptr, int icon,
2455                                      struct PointerRNA *UNUSED(active_dataptr), const char *UNUSED(active_propname),
2456                                      int UNUSED(index), int UNUSED(flt_flag))
2457 {
2458         PropertyRNA *nameprop = RNA_struct_name_property(itemptr->type);
2459
2460         /* Simplest one! */
2461         switch (ui_list->layout_type) {
2462                 case UILST_LAYOUT_GRID:
2463                         uiItemL(layout, "", icon);
2464                         break;
2465                 case UILST_LAYOUT_DEFAULT:
2466                 case UILST_LAYOUT_COMPACT:
2467                 default:
2468                         if (nameprop) {
2469                                 uiItemFullR(layout, itemptr, nameprop, RNA_NO_INDEX, 0, UI_ITEM_R_NO_BG, "", icon);
2470                         }
2471                         else {
2472                                 uiItemL(layout, "", icon);
2473                         }
2474                         break;
2475         }
2476 }
2477
2478 static void uilist_draw_filter_default(struct uiList *ui_list, struct bContext *UNUSED(C), struct uiLayout *layout)
2479 {
2480         PointerRNA listptr;
2481         uiLayout *row, *subrow;
2482
2483         RNA_pointer_create(NULL, &RNA_UIList, ui_list, &listptr);
2484
2485         row = uiLayoutRow(layout, false);
2486
2487         subrow = uiLayoutRow(row, true);
2488         uiItemR(subrow, &listptr, "filter_name", 0, "", ICON_NONE);
2489         uiItemR(subrow, &listptr, "use_filter_invert", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "",
2490                 (ui_list->filter_flag & UILST_FLT_EXCLUDE) ? ICON_ZOOM_OUT : ICON_ZOOM_IN);
2491
2492         subrow = uiLayoutRow(row, true);
2493         uiItemR(subrow, &listptr, "use_filter_sort_alpha", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "", ICON_NONE);
2494         uiItemR(subrow, &listptr, "use_filter_sort_reverse", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "",
2495                 (ui_list->filter_sort_flag & UILST_FLT_SORT_REVERSE) ? ICON_TRIA_UP : ICON_TRIA_DOWN);
2496 }
2497
2498 typedef struct {
2499         char name[MAX_IDPROP_NAME];
2500         int org_idx;
2501 } StringCmp;
2502
2503 static int cmpstringp(const void *p1, const void *p2)
2504 {
2505         /* Case-insensitive comparison. */
2506         return BLI_strcasecmp(((StringCmp *) p1)->name, ((StringCmp *) p2)->name);
2507 }
2508
2509 static void uilist_filter_items_default(struct uiList *ui_list, struct bContext *UNUSED(C), struct PointerRNA *dataptr,
2510                                         const char *propname)
2511 {
2512         uiListDyn *dyn_data = ui_list->dyn_data;
2513         PropertyRNA *prop = RNA_struct_find_property(dataptr, propname);
2514
2515         const char *filter_raw = ui_list->filter_byname;
2516         char *filter = (char *)filter_raw, filter_buff[32], *filter_dyn = NULL;
2517         bool filter_exclude = (ui_list->filter_flag & UILST_FLT_EXCLUDE) != 0;
2518         bool order_by_name = (ui_list->filter_sort_flag & UILST_FLT_SORT_ALPHA) != 0;
2519         int len = RNA_property_collection_length(dataptr, prop);
2520
2521         dyn_data->items_shown = dyn_data->items_len = len;
2522
2523         if (len && (order_by_name || filter_raw[0])) {
2524                 StringCmp *names = NULL;
2525                 int order_idx = 0, i = 0;
2526
2527                 if (order_by_name) {
2528                         names = MEM_callocN(sizeof(StringCmp) * len, "StringCmp");
2529                 }
2530                 if (filter_raw[0]) {
2531                         size_t idx = 0, slen = strlen(filter_raw);
2532
2533                         dyn_data->items_filter_flags = MEM_callocN(sizeof(int) * len, "items_filter_flags");
2534                         dyn_data->items_shown = 0;
2535
2536                         /* Implicitly add heading/trailing wildcards if needed. */
2537                         if (slen + 3 <= sizeof(filter_buff)) {
2538                                 filter = filter_buff;
2539                         }
2540                         else {
2541                                 filter = filter_dyn = MEM_mallocN((slen + 3) * sizeof(char), "filter_dyn");
2542                         }
2543                         if (filter_raw[idx] != '*') {
2544                                 filter[idx++] = '*';
2545                         }
2546                         memcpy(filter + idx, filter_raw, slen);
2547                         idx += slen;
2548                         if (filter[idx - 1] != '*') {
2549                                 filter[idx++] = '*';
2550                         }
2551                         filter[idx] = '\0';
2552                 }
2553
2554                 RNA_PROP_BEGIN (dataptr, itemptr, prop)
2555                 {
2556                         char *namebuf;
2557                         const char *name;
2558                         bool do_order = false;
2559
2560                         namebuf = RNA_struct_name_get_alloc(&itemptr, NULL, 0, NULL);
2561                         name = namebuf ? namebuf : "";
2562
2563                         if (filter[0]) {
2564                                 /* Case-insensitive! */
2565                                 if (fnmatch(filter, name, FNM_CASEFOLD) == 0) {
2566                                         dyn_data->items_filter_flags[i] = UILST_FLT_ITEM;
2567                                         if (!filter_exclude) {
2568                                                 dyn_data->items_shown++;
2569                                                 do_order = order_by_name;
2570                                         }
2571                                         //printf("%s: '%s' matches '%s'\n", __func__, name, filter);
2572                                 }
2573                                 else if (filter_exclude) {
2574                                         dyn_data->items_shown++;
2575                                         do_order = order_by_name;
2576                                 }
2577                         }
2578                         else {
2579                                 do_order = order_by_name;
2580                         }
2581
2582                         if (do_order) {
2583                                 names[order_idx].org_idx = order_idx;
2584                                 BLI_strncpy(names[order_idx++].name, name, MAX_IDPROP_NAME);
2585                         }
2586
2587                         /* free name */
2588                         if (namebuf) {
2589                                 MEM_freeN(namebuf);
2590                         }
2591                         i++;
2592                 }
2593                 RNA_PROP_END;
2594
2595                 if (order_by_name) {
2596                         int new_idx;
2597                         /* note: order_idx equals either to ui_list->items_len if no filtering done,
2598                          *       or to ui_list->items_shown if filter is enabled,
2599                          *       or to (ui_list->items_len - ui_list->items_shown) if filtered items are excluded.
2600                          *       This way, we only sort items we actually intend to draw!
2601                          */
2602                         qsort(names, order_idx, sizeof(StringCmp), cmpstringp);
2603
2604                         dyn_data->items_filter_neworder = MEM_mallocN(sizeof(int) * order_idx, "items_filter_neworder");
2605                         for (new_idx = 0; new_idx < order_idx; new_idx++) {
2606                                 dyn_data->items_filter_neworder[names[new_idx].org_idx] = new_idx;
2607                         }
2608                 }
2609
2610                 if (filter_dyn) {
2611                         MEM_freeN(filter_dyn);
2612                 }
2613                 if (names) {
2614                         MEM_freeN(names);
2615                 }
2616         }
2617 }
2618
2619 typedef struct {
2620         PointerRNA item;
2621         int org_idx;
2622         int flt_flag;
2623 } _uilist_item;
2624
2625 typedef struct {
2626         int visual_items;  /* Visual number of items (i.e. number of items we have room to display). */
2627         int start_idx;     /* Index of first item to display. */
2628         int end_idx;       /* Index of last item to display + 1. */
2629 } uiListLayoutdata;
2630
2631 static void prepare_list(uiList *ui_list, int len, int activei, int rows, int maxrows, int columns,
2632                          uiListLayoutdata *layoutdata)
2633 {
2634         uiListDyn *dyn_data = ui_list->dyn_data;
2635         int activei_row, max_scroll;
2636
2637         /* default rows */
2638         if (rows == 0)
2639                 rows = 5;
2640         dyn_data->visual_height_min = rows;
2641         if (maxrows == 0)
2642                 maxrows = 5;
2643         if (columns == 0)
2644                 columns = 9;
2645
2646         if (ui_list->list_grip >= (rows - 1) && ui_list->list_grip != 0) {
2647                 /* Only enable auto-size mode when we have dragged one row away from minimum size.
2648                  * Avoids to switch too easily to auto-size mode when resizing to minimum size...
2649                  */
2650                 maxrows = rows = max_ii(ui_list->list_grip, rows);
2651         }
2652         else {
2653                 ui_list->list_grip = 0;  /* Reset to auto-size mode. */
2654                 /* Prevent auto-size mode to take effect while grab-resizing! */
2655                 if (ui_list->flag & UILST_RESIZING) {
2656                         maxrows = rows;
2657                 }
2658         }
2659
2660         if (columns > 1) {
2661                 dyn_data->height = (int)ceil((double)len / (double)columns);
2662                 activei_row = (int)floor((double)activei / (double)columns);
2663         }
2664         else {
2665                 dyn_data->height = len;
2666                 activei_row = activei;
2667         }
2668
2669         /* Expand size if needed and possible. */
2670         if ((ui_list->list_grip == 0) && (rows != maxrows) && (dyn_data->height > rows)) {
2671                 rows = min_ii(dyn_data->height, maxrows);
2672         }
2673
2674         /* If list length changes or list is tagged to check this, and active is out of view, scroll to it .*/
2675         if (ui_list->list_last_len != len || ui_list->flag & UILST_SCROLL_TO_ACTIVE_ITEM) {
2676                 if (activei_row < ui_list->list_scroll) {
2677                         ui_list->list_scroll = activei_row;
2678                 }
2679                 else if (activei_row >= ui_list->list_scroll + rows) {
2680                         ui_list->list_scroll = activei_row - rows + 1;
2681                 }
2682                 ui_list->flag &= ~UILST_SCROLL_TO_ACTIVE_ITEM;
2683         }
2684
2685         max_scroll = max_ii(0, dyn_data->height - rows);
2686         CLAMP(ui_list->list_scroll, 0, max_scroll);
2687         ui_list->list_last_len = len;
2688         dyn_data->visual_height = rows;
2689         layoutdata->visual_items = rows * columns;
2690         layoutdata->start_idx = ui_list->list_scroll * columns;
2691         layoutdata->end_idx = min_ii(layoutdata->start_idx + rows * columns, len);
2692 }
2693
2694 void uiTemplateList(uiLayout *layout, bContext *C, const char *listtype_name, const char *list_id,
2695                     PointerRNA *dataptr, const char *propname, PointerRNA *active_dataptr, const char *active_propname,
2696                     int rows, int maxrows, int layout_type, int columns)
2697 {
2698         uiListType *ui_list_type;
2699         uiList *ui_list = NULL;
2700         uiListDyn *dyn_data;
2701         ARegion *ar;
2702         uiListDrawItemFunc draw_item;
2703         uiListDrawFilterFunc draw_filter;
2704         uiListFilterItemsFunc filter_items;
2705
2706         PropertyRNA *prop = NULL, *activeprop;
2707         PropertyType type, activetype;
2708         _uilist_item *items_ptr = NULL;
2709         StructRNA *ptype;
2710         uiLayout *glob = NULL, *box, *row, *col, *subrow, *sub, *overlap;
2711         uiBlock *block, *subblock;
2712         uiBut *but;
2713
2714         uiListLayoutdata layoutdata;
2715         char ui_list_id[UI_MAX_NAME_STR];
2716         char numstr[32];
2717         int rnaicon = ICON_NONE, icon = ICON_NONE;
2718         int i = 0, activei = 0;
2719         int len = 0;
2720
2721         /* validate arguments */
2722         /* Forbid default UI_UL_DEFAULT_CLASS_NAME list class without a custom list_id! */
2723         if (!strcmp(UI_UL_DEFAULT_CLASS_NAME, listtype_name) && !(list_id && list_id[0])) {
2724                 RNA_warning("template_list using default '%s' UIList class must provide a custom list_id",
2725                             UI_UL_DEFAULT_CLASS_NAME);
2726                 return;
2727         }
2728
2729         block = uiLayoutGetBlock(layout);
2730
2731         if (!active_dataptr->data) {
2732                 RNA_warning("No active data");
2733                 return;
2734         }
2735
2736         if (dataptr->data) {
2737                 prop = RNA_struct_find_property(dataptr, propname);
2738                 if (!prop) {
2739                         RNA_warning("Property not found: %s.%s", RNA_struct_identifier(dataptr->type), propname);
2740                         return;
2741                 }
2742         }
2743
2744         activeprop = RNA_struct_find_property(active_dataptr, active_propname);
2745         if (!activeprop) {
2746                 RNA_warning("Property not found: %s.%s", RNA_struct_identifier(active_dataptr->type), active_propname);
2747                 return;
2748         }
2749
2750         if (prop) {
2751                 type = RNA_property_type(prop);
2752                 if (type != PROP_COLLECTION) {
2753                         RNA_warning("Expected a collection data property");
2754                         return;
2755                 }
2756         }
2757
2758         activetype = RNA_property_type(activeprop);
2759         if (activetype != PROP_INT) {
2760                 RNA_warning("Expected an integer active data property");
2761                 return;
2762         }
2763
2764         /* get icon */
2765         if (dataptr->data && prop) {
2766                 ptype = RNA_property_pointer_type(dataptr, prop);
2767                 rnaicon = RNA_struct_ui_icon(ptype);
2768         }
2769
2770         /* get active data */
2771         activei = RNA_property_int_get(active_dataptr, activeprop);
2772
2773         /* Find the uiList type. */
2774         ui_list_type = WM_uilisttype_find(listtype_name, false);
2775
2776         if (ui_list_type == NULL) {
2777                 RNA_warning("List type %s not found", listtype_name);
2778                 return;
2779         }
2780
2781         draw_item = ui_list_type->draw_item ? ui_list_type->draw_item : uilist_draw_item_default;
2782         draw_filter = ui_list_type->draw_filter ? ui_list_type->draw_filter : uilist_draw_filter_default;
2783         filter_items = ui_list_type->filter_items ? ui_list_type->filter_items : uilist_filter_items_default;
2784
2785         /* Find or add the uiList to the current Region. */
2786         /* We tag the list id with the list type... */
2787         BLI_snprintf(ui_list_id, sizeof(ui_list_id), "%s_%s", ui_list_type->idname, list_id ? list_id : "");
2788
2789         ar = CTX_wm_region(C);
2790         ui_list = BLI_findstring(&ar->ui_lists, ui_list_id, offsetof(uiList, list_id));
2791
2792         if (!ui_list) {
2793                 ui_list = MEM_callocN(sizeof(uiList), "uiList");
2794                 BLI_strncpy(ui_list->list_id, ui_list_id, sizeof(ui_list->list_id));
2795                 BLI_addtail(&ar->ui_lists, ui_list);
2796         }
2797
2798         if (!ui_list->dyn_data) {
2799                 ui_list->dyn_data = MEM_callocN(sizeof(uiListDyn), "uiList.dyn_data");
2800         }
2801         dyn_data = ui_list->dyn_data;
2802
2803         /* Because we can't actually pass type across save&load... */
2804         ui_list->type = ui_list_type;
2805         ui_list->layout_type = layout_type;
2806
2807         /* Reset filtering data. */
2808         if (dyn_data->items_filter_flags) {
2809                 MEM_freeN(dyn_data->items_filter_flags);
2810                 dyn_data->items_filter_flags = NULL;
2811         }
2812         if (dyn_data->items_filter_neworder) {
2813                 MEM_freeN(dyn_data->items_filter_neworder);
2814                 dyn_data->items_filter_neworder = NULL;
2815         }
2816         dyn_data->items_len = dyn_data->items_shown = -1;
2817
2818         /* Filter list items! (not for compact layout, though) */
2819         if (dataptr->data && prop) {
2820                 int filter_exclude = ui_list->filter_flag & UILST_FLT_EXCLUDE;
2821                 bool order_reverse = (ui_list->filter_sort_flag & UILST_FLT_SORT_REVERSE) != 0;
2822                 int items_shown, idx = 0;
2823 #if 0
2824                 int prev_ii = -1, prev_i;
2825 #endif
2826
2827                 if (layout_type == UILST_LAYOUT_COMPACT) {
2828                         dyn_data->items_len = dyn_data->items_shown = RNA_property_collection_length(dataptr, prop);
2829                 }
2830                 else {
2831                         //printf("%s: filtering...\n", __func__);
2832                         filter_items(ui_list, C, dataptr, propname);
2833                         //printf("%s: filtering done.\n", __func__);
2834                 }
2835
2836                 items_shown = dyn_data->items_shown;
2837                 if (items_shown >= 0) {
2838                         bool activei_mapping_pending = true;
2839                         items_ptr = MEM_mallocN(sizeof(_uilist_item) * items_shown, __func__);
2840                         //printf("%s: items shown: %d.\n", __func__, items_shown);
2841                         RNA_PROP_BEGIN (dataptr, itemptr, prop)
2842                         {
2843                                 if (!dyn_data->items_filter_flags ||
2844                                         ((dyn_data->items_filter_flags[i] & UILST_FLT_ITEM) ^ filter_exclude))
2845                                 {
2846                                         int ii;
2847                                         if (dyn_data->items_filter_neworder) {
2848                                                 ii = dyn_data->items_filter_neworder[idx++];
2849                                                 ii = order_reverse ? items_shown - ii - 1 : ii;
2850                                         }
2851                                         else {
2852                                                 ii = order_reverse ? items_shown - ++idx : idx++;
2853                                         }
2854                                         //printf("%s: ii: %d\n", __func__, ii);
2855                                         items_ptr[ii].item = itemptr;
2856                                         items_ptr[ii].org_idx = i;
2857                                         items_ptr[ii].flt_flag = dyn_data->items_filter_flags ? dyn_data->items_filter_flags[i] : 0;
2858
2859                                         if (activei_mapping_pending && activei == i) {
2860                                                 activei = ii;
2861                                                 /* So that we do not map again activei! */
2862                                                 activei_mapping_pending = false;
2863                                         }
2864 # if 0 /* For now, do not alter active element, even if it will be hidden... */
2865                                         else if (activei < i) {
2866                                                 /* We do not want an active but invisible item!
2867                                                  * Only exception is when all items are filtered out...
2868                                                  */
2869                                                 if (prev_ii >= 0) {
2870                                                         activei = prev_ii;
2871                                                         RNA_property_int_set(active_dataptr, activeprop, prev_i);
2872                                                 }
2873                                                 else {
2874                                                         activei = ii;
2875                                                         RNA_property_int_set(active_dataptr, activeprop, i);
2876                                                 }
2877                                         }
2878                                         prev_i = i;
2879                                         prev_ii = ii;
2880 #endif
2881                                 }
2882                                 i++;
2883                         }
2884                         RNA_PROP_END;
2885                 }
2886                 if (dyn_data->items_shown >= 0) {
2887                         len = dyn_data->items_shown;
2888                 }
2889                 else {
2890                         len = dyn_data->items_len;
2891                 }
2892         }
2893
2894         switch (layout_type) {
2895                 case UILST_LAYOUT_DEFAULT:
2896                         /* layout */
2897                         box = uiLayoutListBox(layout, ui_list, dataptr, prop, active_dataptr, activeprop);
2898                         glob = uiLayoutColumn(box, true);
2899                         row = uiLayoutRow(glob, false);
2900                         col = uiLayoutColumn(row, true);
2901
2902                         /* init numbers */
2903                         prepare_list(ui_list, len, activei, rows, maxrows, 1, &layoutdata);
2904
2905                         if (dataptr->data && prop) {
2906                                 /* create list items */
2907                                 for (i = layoutdata.start_idx; i < layoutdata.end_idx; i++) {
2908                                         PointerRNA *itemptr = &items_ptr[i].item;
2909                                         int org_i = items_ptr[i].org_idx;
2910                                         int flt_flag = items_ptr[i].flt_flag;
2911                                         subblock = uiLayoutGetBlock(col);
2912
2913                                         overlap = uiLayoutOverlap(col);
2914
2915                                         uiBlockSetFlag(subblock, UI_BLOCK_LIST_ITEM);
2916
2917                                         /* list item behind label & other buttons */
2918                                         sub = uiLayoutRow(overlap, false);
2919
2920                                         but = uiDefButR_prop(subblock, LISTROW, 0, "", 0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
2921                                                              active_dataptr, activeprop, 0, 0, org_i, 0, 0, NULL);
2922                                         uiButSetDrawFlag(but, UI_BUT_NO_TOOLTIP);
2923
2924                                         sub = uiLayoutRow(overlap, false);
2925
2926                                         icon = UI_rnaptr_icon_get(C, itemptr, rnaicon, false);
2927                                         if (icon == ICON_DOT)
2928                                                 icon = ICON_NONE;
2929                                         draw_item(ui_list, C, sub, dataptr, itemptr, icon, active_dataptr, active_propname,
2930                                                   org_i, flt_flag);
2931
2932                                         /* If we are "drawing" active item, set all labels as active. */
2933                                         if (i == activei) {
2934                                                 ui_layout_list_set_labels_active(sub);
2935                                         }
2936
2937                                         uiBlockClearFlag(subblock, UI_BLOCK_LIST_ITEM);
2938                                 }
2939                         }
2940
2941                         /* add dummy buttons to fill space */
2942                         for (; i < layoutdata.start_idx + layoutdata.visual_items; i++) {
2943                                 uiItemL(col, "", ICON_NONE);
2944                         }
2945
2946                         /* add scrollbar */
2947                         if (len > layoutdata.visual_items) {
2948                                 col = uiLayoutColumn(row, false);
2949                                 uiDefButI(block, SCROLL, 0, "", 0, 0, UI_UNIT_X * 0.75, UI_UNIT_Y * dyn_data-