5cdb9c763960410cfb8ec68b115ff3b3d3382f55
[blender.git] / source / blender / editors / armature / poselib.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007, Blender Foundation
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/armature/poselib.c
27  *  \ingroup edarmature
28  */
29
30  
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <stddef.h>
34 #include <string.h>
35 #include <math.h>
36 #include <float.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_math.h"
41 #include "BLI_blenlib.h"
42 #include "BLI_dynstr.h"
43 #include "BLI_dlrbTree.h"
44 #include "BLI_utildefines.h"
45
46 #include "BLF_translation.h"
47
48 #include "DNA_anim_types.h"
49 #include "DNA_armature_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_scene_types.h"
52
53 #include "BKE_animsys.h"
54 #include "BKE_action.h"
55 #include "BKE_armature.h"
56 #include "BKE_depsgraph.h"
57 #include "BKE_idprop.h"
58 #include "BKE_library.h"
59 #include "BKE_object.h"
60
61 #include "BKE_context.h"
62 #include "BKE_report.h"
63
64 #include "RNA_access.h"
65 #include "RNA_define.h"
66 #include "RNA_enum_types.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70
71 #include "UI_interface.h"
72 #include "UI_resources.h"
73
74 #include "ED_anim_api.h"
75 #include "ED_armature.h"
76 #include "ED_keyframes_draw.h"
77 #include "ED_keyframing.h"
78 #include "ED_keyframes_edit.h"
79 #include "ED_screen.h"
80 #include "ED_object.h"
81
82 #include "armature_intern.h"
83
84 /* ******* XXX ********** */
85
86 static void action_set_activemarker(void *UNUSED(a), void *UNUSED(b), void *UNUSED(c)) {}
87
88 /* ************************************************************* */
89 /* == POSE-LIBRARY TOOL FOR BLENDER == 
90  *      
91  * Overview: 
92  *      This tool allows animators to store a set of frequently used poses to dump into
93  *      the active action to help in "budget" productions to quickly block out new actions.
94  *      It acts as a kind of "glorified clipboard for poses", allowing for naming of poses.
95  *
96  * Features:
97  *      - PoseLibs are simply normal Actions
98  *      - Each "pose" is simply a set of keyframes that occur on a particular frame
99  *              -> a set of TimeMarkers that belong to each Action, help 'label' where a 'pose' can be
100  *                 found in the Action
101  *      - The Scrollwheel or PageUp/Down buttons when used in a special mode or after pressing/holding
102  *        [a modifier] key, cycles through the poses available for the active pose's poselib, allowing the
103  *        animator to preview what action best suits that pose
104  */
105 /* ************************************************************* */
106
107
108 /* gets the first available frame in poselib to store a pose on 
109  *      - frames start from 1, and a pose should occur on every frame... 0 is error!
110  */
111 static int poselib_get_free_index (bAction *act)
112 {
113         TimeMarker *marker;
114         int low=0, high=0;
115         short changed = 0;
116         
117         /* sanity checks */
118         if (ELEM(NULL, act, act->markers.first)) return 1;
119         
120         /* As poses are not stored in chronological order, we must iterate over this list 
121          * a few times until we don't make any new discoveries (mostly about the lower bound).
122          * Prevents problems with deleting then trying to add new poses [#27412]
123          */
124         do {
125                 changed = 0;
126                 
127                 for (marker= act->markers.first; marker; marker= marker->next) {
128                         /* only increase low if value is 1 greater than low, to find "gaps" where
129                          * poses were removed from the poselib
130                          */
131                         if (marker->frame == (low + 1)) {
132                                 low++;
133                                 changed = 1;
134                         }
135                         
136                         /* value replaces high if it is the highest value encountered yet */
137                         if (marker->frame > high) {
138                                 high= marker->frame;
139                                 changed = 1;
140                         }
141                 }
142         } while (changed != 0);
143         
144         /* - if low is not equal to high, then low+1 is a gap 
145          * - if low is equal to high, then high+1 is the next index (add at end) 
146          */
147         if (low < high) 
148                 return (low + 1);
149         else 
150                 return (high + 1);
151 }
152
153 /* returns the active pose for a poselib */
154 static TimeMarker *poselib_get_active_pose (bAction *act)
155 {       
156         if ((act) && (act->active_marker))
157                 return BLI_findlink(&act->markers, act->active_marker-1);
158         else
159                 return NULL;
160 }
161
162 /* Get object that Pose Lib should be found on */
163  /* XXX C can be zero */
164 static Object *get_poselib_object (bContext *C)
165 {
166         ScrArea *sa;
167         
168         /* sanity check */
169         if (C == NULL)
170                 return NULL;
171         
172         sa = CTX_wm_area(C);
173         
174         if (sa && (sa->spacetype == SPACE_BUTS)) 
175                 return ED_object_context(C);
176         else
177                 return object_pose_armature_get(CTX_data_active_object(C));
178 }
179
180 /* Poll callback for operators that require existing PoseLib data (with poses) to work */
181 static int has_poselib_pose_data_poll (bContext *C)
182 {
183         Object *ob = get_poselib_object(C);
184         return (ob && ob->poselib);
185 }
186
187 /* ----------------------------------- */
188
189 /* Initialise a new poselib (whether it is needed or not) */
190 static bAction *poselib_init_new (Object *ob)
191 {
192         /* sanity checks - only for armatures */
193         if (ELEM(NULL, ob, ob->pose))
194                 return NULL;
195         
196         /* init object's poselib action (unlink old one if there) */
197         if (ob->poselib)
198                 id_us_min(&ob->poselib->id);
199         ob->poselib= add_empty_action("PoseLib");
200         
201         return ob->poselib;
202 }
203
204 /* Initialise a new poselib (checks if that needs to happen) */
205 static bAction *poselib_validate (Object *ob)
206 {
207         if (ELEM(NULL, ob, ob->pose))
208                 return NULL;
209         else if (ob->poselib == NULL)
210                 return poselib_init_new(ob);
211         else
212                 return ob->poselib;
213 }
214
215 /* ************************************************************* */
216 /* Pose Lib UI Operators */
217
218 static int poselib_new_exec (bContext *C, wmOperator *UNUSED(op))
219 {
220         Object *ob = get_poselib_object(C);
221         
222         /* sanity checks */
223         if (ob == NULL)
224                 return OPERATOR_CANCELLED;
225                 
226         /* new method here deals with the rest... */
227         poselib_init_new(ob);
228         
229         /* notifier here might evolve? */
230         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, NULL);
231         
232         return OPERATOR_FINISHED;
233 }
234
235 void POSELIB_OT_new (wmOperatorType *ot)
236 {
237         /* identifiers */
238         ot->name = "New Pose Library";
239         ot->idname = "POSELIB_OT_new";
240         ot->description = "Add New Pose Library to active Object";
241         
242         /* callbacks */
243         ot->exec = poselib_new_exec;
244         ot->poll= ED_operator_posemode;
245         
246         /* flags */
247         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
248 }
249
250 /* ------------------------------------------------ */
251
252 static int poselib_unlink_exec (bContext *C, wmOperator *UNUSED(op))
253 {
254         Object *ob = get_poselib_object(C);
255         
256         /* sanity checks */
257         if (ELEM(NULL, ob, ob->poselib))
258                 return OPERATOR_CANCELLED;
259                 
260         /* there should be a poselib (we just checked above!), so just lower its user count and remove */
261         id_us_min(&ob->poselib->id);
262         ob->poselib = NULL;
263         
264         /* notifier here might evolve? */
265         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, NULL);
266         
267         return OPERATOR_FINISHED;
268 }
269
270 void POSELIB_OT_unlink (wmOperatorType *ot)
271 {
272         /* identifiers */
273         ot->name = "Unlink Pose Library";
274         ot->idname = "POSELIB_OT_unlink";
275         ot->description = "Remove Pose Library from active Object";
276         
277         /* callbacks */
278         ot->exec = poselib_unlink_exec;
279         ot->poll= has_poselib_pose_data_poll;
280         
281         /* flags */
282         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
283 }
284
285 /* ************************************************************* */
286 /* Pose Editing Operators */
287
288 /* This tool automagically generates/validates poselib data so that it corresponds to the data 
289  * in the action. This is for use in making existing actions usable as poselibs.
290  */
291 static int poselib_sanitise_exec (bContext *C, wmOperator *op)
292 {
293         Object *ob = get_poselib_object(C);
294         bAction *act = (ob)? ob->poselib : NULL;
295         DLRBT_Tree keys;
296         ActKeyColumn *ak;
297         TimeMarker *marker, *markern;
298         
299         /* validate action */
300         if (act == NULL)  {
301                 BKE_report(op->reports, RPT_WARNING, "No Action to validate");
302                 return OPERATOR_CANCELLED;
303         }
304         
305         /* determine which frames have keys */
306         BLI_dlrbTree_init(&keys);
307                 action_to_keylist(NULL, act, &keys, NULL);
308         BLI_dlrbTree_linkedlist_sync(&keys);
309         
310         /* for each key, make sure there is a corresponding pose */
311         for (ak= keys.first; ak; ak= ak->next) {
312                 /* check if any pose matches this */
313                 // TODO: don't go looking through the list like this every time...
314                 for (marker= act->markers.first; marker; marker= marker->next) {
315                         if (IS_EQ(marker->frame, (double)ak->cfra)) {
316                                 marker->flag = -1;
317                                 break;
318                         }
319                 }
320                 
321                 /* add new if none found */
322                 if (marker == NULL) {
323                         /* add pose to poselib */
324                         marker= MEM_callocN(sizeof(TimeMarker), "ActionMarker");
325                         
326                         BLI_strncpy(marker->name, "Pose", sizeof(marker->name));
327                         
328                         marker->frame= (int)ak->cfra;
329                         marker->flag= -1;
330                         
331                         BLI_addtail(&act->markers, marker);
332                 }
333         }
334         
335         /* remove all untagged poses (unused), and remove all tags */
336         for (marker= act->markers.first; marker; marker= markern) {
337                 markern= marker->next;
338                 
339                 if (marker->flag != -1)
340                         BLI_freelinkN(&act->markers, marker);
341                 else
342                         marker->flag = 0;
343         }
344         
345         /* free temp memory */
346         BLI_dlrbTree_free(&keys);
347         
348         /* send notifiers for this - using keyframe editing notifiers, since action 
349          * may be being shown in anim editors as active action 
350          */
351         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
352         
353         return OPERATOR_FINISHED;
354 }
355
356 void POSELIB_OT_action_sanitise (wmOperatorType *ot)
357 {
358         /* identifiers */
359         ot->name = "Sanitise Pose Library Action";
360         ot->idname = "POSELIB_OT_action_sanitise";
361         ot->description = "Make action suitable for use as a Pose Library";
362         
363         /* callbacks */
364         ot->exec = poselib_sanitise_exec;
365         ot->poll = has_poselib_pose_data_poll;
366         
367         /* flags */
368         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
369 }
370
371 /* ------------------------------------------ */
372
373 static void poselib_add_menu_invoke__replacemenu (bContext *C, uiLayout *layout, void *UNUSED(arg))
374 {
375         Object *ob= get_poselib_object(C);
376         bAction *act= ob->poselib; /* never NULL */
377         TimeMarker *marker;
378         
379         /* set the operator execution context correctly */
380         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_DEFAULT);
381         
382         /* add each marker to this menu */
383         for (marker= act->markers.first; marker; marker= marker->next) {
384                 PointerRNA props_ptr;
385                 
386                 props_ptr = uiItemFullO(layout, "POSELIB_OT_pose_add", 
387                                                 marker->name, ICON_ARMATURE_DATA, NULL, 
388                                                 WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
389                 
390                 RNA_int_set(&props_ptr, "frame", marker->frame);
391                 RNA_string_set(&props_ptr, "name", marker->name);
392         }
393 }
394
395 static int poselib_add_menu_invoke (bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
396 {
397         Scene *scene= CTX_data_scene(C);
398         Object *ob= get_poselib_object(C);
399         bPose *pose= (ob) ? ob->pose : NULL;
400         uiPopupMenu *pup;
401         uiLayout *layout;
402         
403         /* sanity check */
404         if (ELEM(NULL, ob, pose)) 
405                 return OPERATOR_CANCELLED;
406         
407         /* start building */
408         pup= uiPupMenuBegin(C, op->type->name, ICON_NONE);
409         layout= uiPupMenuLayout(pup);
410         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_DEFAULT);
411         
412         /* add new (adds to the first unoccupied frame) */
413         uiItemIntO(layout, IFACE_("Add New"), ICON_NONE, "POSELIB_OT_pose_add", "frame", poselib_get_free_index(ob->poselib));
414         
415         /* check if we have any choices to add a new pose in any other way */
416         if ((ob->poselib) && (ob->poselib->markers.first)) {
417                 /* add new (on current frame) */
418                 uiItemIntO(layout, IFACE_("Add New (Current Frame)"), ICON_NONE, "POSELIB_OT_pose_add", "frame", CFRA);
419                 
420                 /* replace existing - submenu */
421                 uiItemMenuF(layout, IFACE_("Replace Existing..."), 0, poselib_add_menu_invoke__replacemenu, NULL);
422         }
423         
424         uiPupMenuEnd(C, pup);
425         
426         /* this operator is only for a menu, not used further */
427         return OPERATOR_CANCELLED;
428 }
429
430
431 static int poselib_add_exec (bContext *C, wmOperator *op)
432 {
433         Object *ob= get_poselib_object(C);
434         bAction *act = poselib_validate(ob);
435         bPose *pose= (ob) ? ob->pose : NULL;
436         TimeMarker *marker;
437         KeyingSet *ks= ANIM_builtin_keyingset_get_named(NULL, ANIM_KS_WHOLE_CHARACTER_ID); /* this includes custom props :)*/
438         int frame= RNA_int_get(op->ptr, "frame");
439         char name[64];
440         
441         /* sanity check (invoke should have checked this anyway) */
442         if (ELEM(NULL, ob, pose)) 
443                 return OPERATOR_CANCELLED;
444         
445         /* get name to give to pose */
446         RNA_string_get(op->ptr, "name", name);
447         
448         /* add pose to poselib - replaces any existing pose there
449          *      - for the 'replace' option, this should end up finding the appropriate marker,
450          *        so no new one will be added
451          */
452         for (marker= act->markers.first; marker; marker= marker->next) {
453                 if (marker->frame == frame) {
454                         BLI_strncpy(marker->name, name, sizeof(marker->name));
455                         break;
456                 }
457         }
458         if (marker == NULL) {
459                 marker= MEM_callocN(sizeof(TimeMarker), "ActionMarker");
460                 
461                 BLI_strncpy(marker->name, name, sizeof(marker->name));
462                 marker->frame= frame;
463                 
464                 BLI_addtail(&act->markers, marker);
465         }
466         
467         /* validate name */
468         BLI_uniquename(&act->markers, marker, "Pose", '.', offsetof(TimeMarker, name), sizeof(marker->name));
469         
470         /* use Keying Set to determine what to store for the pose */
471         // FIXME: in the past, the Keying Set respected selections (LocRotScale), but the current one doesn't (Whole Character)
472         // so perhaps we need either a new Keying Set, or just to add overrides here...
473         ANIM_apply_keyingset(C, NULL, act, ks, MODIFYKEY_MODE_INSERT, (float)frame);
474         
475         /* store new 'active' pose number */
476         act->active_marker= BLI_countlist(&act->markers);
477         
478         /* done */
479         return OPERATOR_FINISHED;
480 }
481
482 void POSELIB_OT_pose_add (wmOperatorType *ot)
483 {
484         /* identifiers */
485         ot->name= "PoseLib Add Pose";
486         ot->idname= "POSELIB_OT_pose_add";
487         ot->description= "Add the current Pose to the active Pose Library";
488         
489         /* api callbacks */
490         ot->invoke= poselib_add_menu_invoke;
491         ot->exec= poselib_add_exec;
492         ot->poll= ED_operator_posemode;
493         
494         /* flags */
495         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
496         
497         /* properties */
498         RNA_def_int(ot->srna, "frame", 1, 0, INT_MAX, "Frame", "Frame to store pose on", 0, INT_MAX);
499         RNA_def_string(ot->srna, "name", "Pose", 64, "Pose Name", "Name of newly added Pose");
500 }
501
502 /* ----- */
503
504 /* can be called with C == NULL */
505 static EnumPropertyItem *poselib_stored_pose_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
506 {
507         Object *ob = get_poselib_object(C);
508         bAction *act = (ob) ? ob->poselib : NULL;
509         TimeMarker *marker;
510         EnumPropertyItem *item= NULL, item_tmp= {0};
511         int totitem= 0;
512         int i= 0;
513
514         if (C == NULL) {
515                 return DummyRNA_DEFAULT_items;
516         }
517         
518         /* check that the action exists */
519         if (act) {
520                 /* add each marker to the list */
521                 for (marker=act->markers.first, i=0; marker; marker= marker->next, i++) {
522                         item_tmp.identifier= item_tmp.name= marker->name;
523                         item_tmp.icon= ICON_ARMATURE_DATA;
524                         item_tmp.value= i;
525                         RNA_enum_item_add(&item, &totitem, &item_tmp);
526                 }
527         }
528
529         RNA_enum_item_end(&item, &totitem);
530         *free= 1;
531
532         return item;
533 }
534
535 static int poselib_remove_exec (bContext *C, wmOperator *op)
536 {
537         Object *ob= get_poselib_object(C);
538         bAction *act= (ob) ? ob->poselib : NULL;
539         TimeMarker *marker;
540         FCurve *fcu;
541         
542         /* check if valid poselib */
543         if (act == NULL) {
544                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
545                 return OPERATOR_CANCELLED;
546         }
547         
548         /* get index (and pointer) of pose to remove */
549         marker= BLI_findlink(&act->markers, RNA_enum_get(op->ptr, "pose"));
550         if (marker == NULL) {
551                 BKE_reportf(op->reports, RPT_ERROR, "Invalid Pose specified %d", RNA_int_get(op->ptr, "pose"));
552                 return OPERATOR_CANCELLED;
553         }
554         
555         /* remove relevant keyframes */
556         for (fcu= act->curves.first; fcu; fcu= fcu->next) {
557                 BezTriple *bezt;
558                 unsigned int i;
559                 
560                 if (fcu->bezt) {
561                         for (i=0, bezt=fcu->bezt; i < fcu->totvert; i++, bezt++) {
562                                 /* check if remove */
563                                 if (IS_EQ(bezt->vec[1][0], marker->frame)) {
564                                         delete_fcurve_key(fcu, i, 1);
565                                         break;
566                                 }
567                         }
568                 }
569         }
570         
571         /* remove poselib from list */
572         BLI_freelinkN(&act->markers, marker);
573         
574         /* fix active pose number */
575         act->active_marker= 0;
576         
577         /* send notifiers for this - using keyframe editing notifiers, since action 
578          * may be being shown in anim editors as active action 
579          */
580         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
581         
582         /* done */
583         return OPERATOR_FINISHED;
584 }
585
586 void POSELIB_OT_pose_remove (wmOperatorType *ot)
587 {
588         PropertyRNA *prop;
589         
590         /* identifiers */
591         ot->name= "PoseLib Remove Pose";
592         ot->idname= "POSELIB_OT_pose_remove";
593         ot->description= "Remove nth pose from the active Pose Library";
594         
595         /* api callbacks */
596         ot->invoke= WM_menu_invoke;
597         ot->exec= poselib_remove_exec;
598         ot->poll= has_poselib_pose_data_poll;
599         
600         /* flags */
601         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
602         
603         /* properties */
604         prop= RNA_def_enum(ot->srna, "pose", DummyRNA_DEFAULT_items, 0, "Pose", "The pose to remove");
605                 RNA_def_enum_funcs(prop, poselib_stored_pose_itemf);
606         ot->prop= prop;
607 }
608
609 static int poselib_rename_invoke (bContext *C, wmOperator *op, wmEvent *evt)
610 {
611         Object *ob= get_poselib_object(C);
612         bAction *act= (ob) ? ob->poselib : NULL;
613         TimeMarker *marker;
614         
615         /* check if valid poselib */
616         if (act == NULL) {
617                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
618                 return OPERATOR_CANCELLED;
619         }
620         
621         /* get index (and pointer) of pose to remove */
622         marker= BLI_findlink(&act->markers, act->active_marker-1);
623         if (marker == NULL) {
624                 BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
625                 return OPERATOR_CANCELLED;
626         }
627         else {
628                 /* use the existing name of the marker as the name, and use the active marker as the one to rename */
629                 RNA_enum_set(op->ptr, "pose", act->active_marker-1);
630                 RNA_string_set(op->ptr, "name", marker->name);
631         }
632         
633         /* part to sync with other similar operators... */
634         return WM_operator_props_popup(C, op, evt);
635 }
636
637 static int poselib_rename_exec (bContext *C, wmOperator *op)
638 {
639         Object *ob= object_pose_armature_get(CTX_data_active_object(C));
640         bAction *act= (ob) ? ob->poselib : NULL;
641         TimeMarker *marker;
642         char newname[64];
643         
644         /* check if valid poselib */
645         if (act == NULL) {
646                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
647                 return OPERATOR_CANCELLED;
648         }
649         
650         /* get index (and pointer) of pose to remove */
651         marker= BLI_findlink(&act->markers, RNA_int_get(op->ptr, "pose"));
652         if (marker == NULL) {
653                 BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
654                 return OPERATOR_CANCELLED;
655         }
656         
657         /* get new name */
658         RNA_string_get(op->ptr, "name", newname);
659         
660         /* copy name and validate it */
661         BLI_strncpy(marker->name, newname, sizeof(marker->name));
662         BLI_uniquename(&act->markers, marker, "Pose", '.', offsetof(TimeMarker, name), sizeof(marker->name));
663         
664         /* send notifiers for this - using keyframe editing notifiers, since action 
665          * may be being shown in anim editors as active action 
666          */
667         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
668         
669         /* done */
670         return OPERATOR_FINISHED;
671 }
672
673 void POSELIB_OT_pose_rename (wmOperatorType *ot)
674 {
675         PropertyRNA *prop;
676         static EnumPropertyItem prop_poses_dummy_types[] = {
677                 {0, NULL, 0, NULL, NULL}
678         };
679         
680         /* identifiers */
681         ot->name= "PoseLib Rename Pose";
682         ot->idname= "POSELIB_OT_pose_rename";
683         ot->description= "Rename specified pose from the active Pose Library";
684         
685         /* api callbacks */
686         ot->invoke= poselib_rename_invoke;
687         ot->exec= poselib_rename_exec;
688         ot->poll= has_poselib_pose_data_poll;
689         
690         /* flags */
691         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
692         
693         /* properties */
694                 /* NOTE: name not pose is the operator's "main" property, so that it will get activated in the popup for easy renaming */
695         ot->prop= RNA_def_string(ot->srna, "name", "RenamedPose", 64, "New Pose Name", "New name for pose");
696         prop= RNA_def_enum(ot->srna, "pose", prop_poses_dummy_types, 0, "Pose", "The pose to rename");
697                 RNA_def_enum_funcs(prop, poselib_stored_pose_itemf);
698 }
699
700 /* ************************************************************* */
701 /* Pose-Lib Browsing/Previewing Operator */
702
703 /* Simple struct for storing settings/data for use during PoseLib preview */
704 typedef struct tPoseLib_PreviewData {
705         ListBase backups;               /* tPoseLib_Backup structs for restoring poses */
706         ListBase searchp;               /* LinkData structs storing list of poses which match the current search-string */
707         
708         Scene *scene;                   /* active scene */
709         ScrArea *sa;                    /* active area */
710         
711         PointerRNA rna_ptr;             /* RNA-Pointer to Object 'ob' */
712         Object *ob;                             /* object to work on */
713         bArmature *arm;                 /* object's armature data */
714         bPose *pose;                    /* object's pose */
715         bAction *act;                   /* poselib to use */
716         TimeMarker *marker;             /* 'active' pose */
717         
718         int selcount;                   /* number of selected elements to work on */
719         int totcount;                   /* total number of elements to work on */
720         
721         short state;                    /* state of main loop */
722         short redraw;                   /* redraw/update settings during main loop */
723         short flag;                             /* flags for various settings */
724         
725         short search_cursor;    /* position of cursor in searchstr (cursor occurs before the item at the nominated index) */
726         char searchstr[64];             /* (Part of) Name to search for to filter poses that get shown */
727         char searchold[64];             /* Previously set searchstr (from last loop run), so that we can detected when to rebuild searchp */
728         
729         char headerstr[200];    /* Info-text to print in header */
730 } tPoseLib_PreviewData;
731
732 /* defines for tPoseLib_PreviewData->state values */
733 enum {
734         PL_PREVIEW_ERROR = -1,
735         PL_PREVIEW_RUNNING,
736         PL_PREVIEW_CONFIRM,
737         PL_PREVIEW_CANCEL,
738         PL_PREVIEW_RUNONCE 
739 };
740
741 /* defines for tPoseLib_PreviewData->redraw values */
742 enum {
743         PL_PREVIEW_NOREDRAW = 0,
744         PL_PREVIEW_REDRAWALL,
745         PL_PREVIEW_REDRAWHEADER,
746 };
747
748 /* defines for tPoseLib_PreviewData->flag values */
749 enum {
750         PL_PREVIEW_FIRSTTIME    = (1<<0),
751         PL_PREVIEW_SHOWORIGINAL = (1<<1)
752 };
753
754 /* ---------------------------- */
755
756 /* simple struct for storing backup info */
757 typedef struct tPoseLib_Backup {
758         struct tPoseLib_Backup *next, *prev;
759         
760         bPoseChannel *pchan;            /* pose channel backups are for */
761         
762         bPoseChannel olddata;           /* copy of pose channel's old data (at start) */
763         IDProperty *oldprops;           /* copy (needs freeing) of pose channel's properties (at start) */
764 } tPoseLib_Backup;
765
766 /* Makes a copy of the current pose for restoration purposes - doesn't do constraints currently */
767 static void poselib_backup_posecopy (tPoseLib_PreviewData *pld)
768 {
769         bActionGroup *agrp;
770         bPoseChannel *pchan;
771         
772         /* for each posechannel that has an actionchannel in */
773         for (agrp= pld->act->groups.first; agrp; agrp= agrp->next) {
774                 /* try to find posechannel */
775                 pchan= get_pose_channel(pld->pose, agrp->name);
776                 
777                 /* backup data if available */
778                 if (pchan) {
779                         tPoseLib_Backup *plb;
780                         
781                         /* store backup */
782                         plb= MEM_callocN(sizeof(tPoseLib_Backup), "tPoseLib_Backup");
783                         
784                         plb->pchan= pchan;
785                         memcpy(&plb->olddata, plb->pchan, sizeof(bPoseChannel));
786                         
787                         if (pchan->prop)
788                                 plb->oldprops= IDP_CopyProperty(pchan->prop);
789                         
790                         BLI_addtail(&pld->backups, plb);
791                         
792                         /* mark as being affected */
793                         if ((pchan->bone) && (pchan->bone->flag & BONE_SELECTED))
794                                 pld->selcount++;
795                         pld->totcount++;
796                 }
797         }
798 }
799
800 /* Restores original pose */
801 static void poselib_backup_restore (tPoseLib_PreviewData *pld)
802 {
803         tPoseLib_Backup *plb;
804         
805         for (plb= pld->backups.first; plb; plb= plb->next) {
806                 /* copy most of data straight back */
807                 memcpy(plb->pchan, &plb->olddata, sizeof(bPoseChannel));
808                 
809                 /* just overwrite values of properties from the stored copies (there should be some) */
810                 if (plb->oldprops)
811                         IDP_SyncGroupValues(plb->pchan->prop, plb->oldprops);
812                         
813                 // TODO: constraints settings aren't restored yet, even though these could change (though not that likely)
814         }
815 }
816
817 /* Free list of backups, including any side data it may use */
818 static void poselib_backup_free_data (tPoseLib_PreviewData *pld)
819 {
820         tPoseLib_Backup *plb, *plbn;
821         
822         for (plb= pld->backups.first; plb; plb= plbn) {
823                 plbn= plb->next;
824                 
825                 /* free custom data */
826                 if (plb->oldprops) {
827                         IDP_FreeProperty(plb->oldprops);
828                         MEM_freeN(plb->oldprops);
829                 }
830                 
831                 /* free backup element now */
832                 BLI_freelinkN(&pld->backups, plb);
833         }
834 }
835
836 /* ---------------------------- */
837
838 /* Applies the appropriate stored pose from the pose-library to the current pose
839  *      - assumes that a valid object, with a poselib has been supplied
840  *      - gets the string to print in the header
841  *      - this code is based on the code for extract_pose_from_action in blenkernel/action.c
842  */
843 static void poselib_apply_pose (tPoseLib_PreviewData *pld)
844 {
845         PointerRNA *ptr= &pld->rna_ptr;
846         bArmature *arm= pld->arm;
847         bPose *pose= pld->pose;
848         bPoseChannel *pchan;
849         bAction *act= pld->act;
850         bActionGroup *agrp;
851         
852         KeyframeEditData ked= {{NULL}};
853         KeyframeEditFunc group_ok_cb;
854         int frame= 1;
855         
856         /* get the frame */
857         if (pld->marker)
858                 frame= pld->marker->frame;
859         else
860                 return; 
861         
862         
863         /* init settings for testing groups for keyframes */
864         group_ok_cb= ANIM_editkeyframes_ok(BEZT_OK_FRAMERANGE);
865         ked.f1= ((float)frame) - 0.5f;
866         ked.f2= ((float)frame) + 0.5f;
867         
868         
869         /* start applying - only those channels which have a key at this point in time! */
870         for (agrp= act->groups.first; agrp; agrp= agrp->next) {
871                 /* check if group has any keyframes */
872                 if (ANIM_animchanneldata_keyframes_loop(&ked, NULL, agrp, ALE_GROUP, NULL, group_ok_cb, NULL)) {
873                         /* has keyframe on this frame, so try to get a PoseChannel with this name */
874                         pchan= get_pose_channel(pose, agrp->name);
875                         
876                         if (pchan) {    
877                                 short ok= 0;
878                                 
879                                 /* check if this bone should get any animation applied */
880                                 if (pld->selcount == 0) {
881                                         /* if no bones are selected, then any bone is ok */
882                                         ok= 1;
883                                 }
884                                 else if (pchan->bone) {
885                                         /* only ok if bone is visible and selected */
886                                         if ( (pchan->bone->flag & BONE_SELECTED) &&
887                                                  (pchan->bone->flag & BONE_HIDDEN_P)==0 &&
888                                                  (pchan->bone->layer & arm->layer) )
889                                                 ok = 1;
890                                 }
891                                 
892                                 if (ok) 
893                                         animsys_evaluate_action_group(ptr, act, agrp, NULL, (float)frame);
894                         }
895                 }
896         }
897 }
898
899 /* Auto-keys/tags bones affected by the pose used from the poselib */
900 static void poselib_keytag_pose (bContext *C, Scene *scene, tPoseLib_PreviewData *pld)
901 {
902         bPose *pose= pld->pose;
903         bPoseChannel *pchan;
904         bAction *act= pld->act;
905         bActionGroup *agrp;
906         
907         KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_WHOLE_CHARACTER_ID);
908         ListBase dsources = {NULL, NULL};
909         short autokey = autokeyframe_cfra_can_key(scene, &pld->ob->id);
910         
911         /* start tagging/keying */
912         for (agrp= act->groups.first; agrp; agrp= agrp->next) {
913                 /* only for selected bones unless there aren't any selected, in which case all are included  */
914                 pchan= get_pose_channel(pose, agrp->name);
915                 
916                 if (pchan) {
917                         if ( (pld->selcount == 0) || ((pchan->bone) && (pchan->bone->flag & BONE_SELECTED)) ) {
918                                 if (autokey) {
919                                         /* add datasource override for the PoseChannel, to be used later */
920                                         ANIM_relative_keyingset_add_source(&dsources, &pld->ob->id, &RNA_PoseBone, pchan); 
921                                         
922                                         /* clear any unkeyed tags */
923                                         if (pchan->bone)
924                                                 pchan->bone->flag &= ~BONE_UNKEYED;
925                                 }
926                                 else {
927                                         /* add unkeyed tags */
928                                         if (pchan->bone)
929                                                 pchan->bone->flag |= BONE_UNKEYED;
930                                 }
931                         }
932                 }
933         }
934         
935         /* perform actual auto-keying now */
936         if (autokey) {
937                 /* insert keyframes for all relevant bones in one go */
938                 ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, (float)CFRA);
939                 BLI_freelistN(&dsources);
940         }
941         
942         /* send notifiers for this */
943         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
944 }
945
946 /* Apply the relevant changes to the pose */
947 static void poselib_preview_apply (bContext *C, wmOperator *op)
948 {
949         tPoseLib_PreviewData *pld= (tPoseLib_PreviewData *)op->customdata;
950         
951         /* only recalc pose (and its dependencies) if pose has changed */
952         if (pld->redraw == PL_PREVIEW_REDRAWALL) {
953                 /* don't clear pose if firsttime */
954                 if ((pld->flag & PL_PREVIEW_FIRSTTIME)==0)
955                         poselib_backup_restore(pld);
956                 else
957                         pld->flag &= ~PL_PREVIEW_FIRSTTIME;
958                         
959                 /* pose should be the right one to draw (unless we're temporarily not showing it) */
960                 if ((pld->flag & PL_PREVIEW_SHOWORIGINAL)==0) {
961                         RNA_int_set(op->ptr, "pose_index", BLI_findindex(&pld->act->markers, pld->marker));
962                         poselib_apply_pose(pld);
963                 }
964                 else
965                         RNA_int_set(op->ptr, "pose_index", -2); /* -2 means don't apply any pose */
966                 
967                 /* old optimize trick... this enforces to bypass the depgraph 
968                  *      - note: code copied from transform_generics.c -> recalcData()
969                  */
970                 // FIXME: shouldn't this use the builtin stuff?
971                 if ((pld->arm->flag & ARM_DELAYDEFORM)==0)
972                         DAG_id_tag_update(&pld->ob->id, OB_RECALC_DATA);  /* sets recalc flags */
973                 else
974                         where_is_pose(pld->scene, pld->ob);
975         }
976         
977         /* do header print - if interactively previewing */
978         if (pld->state == PL_PREVIEW_RUNNING) {
979                 if (pld->flag & PL_PREVIEW_SHOWORIGINAL) {
980                         sprintf(pld->headerstr, "PoseLib Previewing Pose: [Showing Original Pose] | Use Tab to start previewing poses again");
981                         ED_area_headerprint(pld->sa, pld->headerstr);
982                 }
983                 else if (pld->searchstr[0]) {
984                         char tempstr[65];
985                         char markern[64];
986                         short index;
987                         
988                         /* get search-string */
989                         index= pld->search_cursor;
990                         
991                         if (index >= 0 && index <= 64) {
992                                 memcpy(&tempstr[0], &pld->searchstr[0], index);
993                                 tempstr[index]= '|';
994                                 memcpy(&tempstr[index+1], &pld->searchstr[index], 64-index);
995                         }
996                         else {
997                                 BLI_strncpy(tempstr, pld->searchstr, sizeof(tempstr));
998                         }
999                         
1000                         /* get marker name */
1001                         BLI_strncpy(markern, pld->marker ? pld->marker->name : "No Matches", sizeof(markern));
1002
1003                         sprintf(pld->headerstr, "PoseLib Previewing Pose: Filter - [%s] | Current Pose - \"%s\"  | Use ScrollWheel or PageUp/Down to change", tempstr, markern);
1004                         ED_area_headerprint(pld->sa, pld->headerstr);
1005                 }
1006                 else {
1007                         sprintf(pld->headerstr, "PoseLib Previewing Pose: \"%s\"  | Use ScrollWheel or PageUp/Down to change", pld->marker->name);
1008                         ED_area_headerprint(pld->sa, pld->headerstr);
1009                 }
1010         }
1011         
1012         /* request drawing of view + clear redraw flag */
1013         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, pld->ob);
1014         pld->redraw= PL_PREVIEW_NOREDRAW;
1015 }
1016
1017 /* ---------------------------- */
1018
1019 /* This helper function is called during poselib_preview_poses to find the 
1020  * pose to preview next (after a change event)
1021  */
1022 static void poselib_preview_get_next (tPoseLib_PreviewData *pld, int step)
1023 {
1024         /* stop if not going anywhere, as we assume that there is a direction to move in */
1025         if (step == 0)
1026                 return;
1027         
1028         /* search-string dictates a special approach */
1029         if (pld->searchstr[0]) {
1030                 TimeMarker *marker;
1031                 LinkData *ld, *ldn, *ldc;
1032                 
1033                 /* free and rebuild if needed (i.e. if search-str changed) */
1034                 if (strcmp(pld->searchstr, pld->searchold)) {
1035                         /* free list of temporary search matches */
1036                         BLI_freelistN(&pld->searchp);
1037                         
1038                         /* generate a new list of search matches */
1039                         for (marker= pld->act->markers.first; marker; marker= marker->next) {
1040                                 /* does the name partially match? 
1041                                  *      - don't worry about case, to make it easier for users to quickly input a name (or 
1042                                  *        part of one), which is the whole point of this feature
1043                                  */
1044                                 if (BLI_strcasestr(marker->name, pld->searchstr)) {
1045                                         /* make link-data to store reference to it */
1046                                         ld= MEM_callocN(sizeof(LinkData), "PoseMatch");
1047                                         ld->data= marker;
1048                                         BLI_addtail(&pld->searchp, ld);
1049                                 }
1050                         }
1051                         
1052                         /* set current marker to NULL (so that we start from first) */
1053                         pld->marker= NULL;
1054                 }
1055                 
1056                 /* check if any matches */
1057                 if (pld->searchp.first == NULL) { 
1058                         pld->marker= NULL;
1059                         return;
1060                 }
1061                 
1062                 /* find first match */
1063                 for (ldc= pld->searchp.first; ldc; ldc= ldc->next) {
1064                         if (ldc->data == pld->marker)
1065                                 break;
1066                 }
1067                 if (ldc == NULL)
1068                         ldc= pld->searchp.first;
1069                         
1070                 /* Loop through the matches in a cyclic fashion, incrementing/decrementing step as appropriate 
1071                  * until step == 0. At this point, marker should be the correct marker.
1072                  */
1073                 if (step > 0) {
1074                         for (ld=ldc; ld && step; ld=ldn, step--)
1075                                 ldn= (ld->next) ? ld->next : pld->searchp.first;
1076                 }
1077                 else {
1078                         for (ld=ldc; ld && step; ld=ldn, step++)
1079                                 ldn= (ld->prev) ? ld->prev : pld->searchp.last;
1080                 }
1081                 
1082                 /* set marker */
1083                 if (ld)
1084                         pld->marker= ld->data;
1085         }
1086         else {
1087                 TimeMarker *marker, *next;
1088                 
1089                 /* if no marker, because we just ended searching, then set that to the start of the list */
1090                 if (pld->marker == NULL)
1091                         pld->marker= pld->act->markers.first;
1092                 
1093                 /* Loop through the markers in a cyclic fashion, incrementing/decrementing step as appropriate 
1094                  * until step == 0. At this point, marker should be the correct marker.
1095                  */
1096                 if (step > 0) {
1097                         for (marker=pld->marker; marker && step; marker=next, step--)
1098                                 next= (marker->next) ? marker->next : pld->act->markers.first;
1099                 }
1100                 else {
1101                         for (marker=pld->marker; marker && step; marker=next, step++)
1102                                 next= (marker->prev) ? marker->prev : pld->act->markers.last;
1103                 }
1104                 
1105                 /* it should be fairly impossible for marker to be NULL */
1106                 if (marker)
1107                         pld->marker= marker;
1108         }
1109 }
1110
1111 /* specially handle events for searching */
1112 static void poselib_preview_handle_search (tPoseLib_PreviewData *pld, unsigned short event, char ascii)
1113 {
1114         /* try doing some form of string manipulation first */
1115         switch (event) {
1116                 case BACKSPACEKEY:
1117                         if (pld->searchstr[0] && pld->search_cursor) {
1118                                 short len= strlen(pld->searchstr);
1119                                 short index= pld->search_cursor;
1120                                 short i;
1121                                 
1122                                 for (i = index; i <= len; i++) 
1123                                         pld->searchstr[i-1] = pld->searchstr[i];
1124                                 
1125                                 pld->search_cursor--;
1126                                 
1127                                 poselib_preview_get_next(pld, 1);
1128                                 pld->redraw = PL_PREVIEW_REDRAWALL;
1129                                 return;
1130                         }       
1131                         break;
1132                         
1133                 case DELKEY:
1134                         if (pld->searchstr[0] && pld->searchstr[1]) {
1135                                 short len= strlen(pld->searchstr);
1136                                 short index= pld->search_cursor;
1137                                 int i;
1138                                 
1139                                 if (index < len) {
1140                                         for (i = index; i < len; i++) 
1141                                                 pld->searchstr[i] = pld->searchstr[i+1];
1142                                                 
1143                                         poselib_preview_get_next(pld, 1);
1144                                         pld->redraw = PL_PREVIEW_REDRAWALL;
1145                                         return;
1146                                 }
1147                         }
1148                         break;
1149         }
1150         
1151         if (ascii) {
1152                 /* character to add to the string */
1153                 short index= pld->search_cursor;
1154                 short len= (pld->searchstr[0]) ? strlen(pld->searchstr) : 0;
1155                 short i;
1156                 
1157                 if (len) {
1158                         for (i = len; i > index; i--)  
1159                                 pld->searchstr[i]= pld->searchstr[i-1];
1160                 }
1161                 else
1162                         pld->searchstr[1]= 0;
1163                         
1164                 pld->searchstr[index]= ascii;
1165                 pld->search_cursor++;
1166                 
1167                 poselib_preview_get_next(pld, 1);
1168                 pld->redraw = PL_PREVIEW_REDRAWALL;
1169         }
1170 }
1171
1172 /* handle events for poselib_preview_poses */
1173 static int poselib_preview_handle_event (bContext *UNUSED(C), wmOperator *op, wmEvent *event)
1174 {
1175         tPoseLib_PreviewData *pld= op->customdata; 
1176         int ret = OPERATOR_RUNNING_MODAL;
1177         
1178         /* only accept 'press' event, and ignore 'release', so that we don't get double actions */
1179         if (ELEM(event->val, KM_PRESS, KM_NOTHING) == 0) {
1180                 //printf("PoseLib: skipping event with type '%s' and val %d\n", WM_key_event_string(event->type), event->val);
1181                 return ret; 
1182         }
1183         
1184         /* backup stuff that needs to occur before every operation
1185          *      - make a copy of searchstr, so that we know if cache needs to be rebuilt
1186          */
1187         BLI_strncpy(pld->searchold, pld->searchstr, sizeof(pld->searchold));
1188         
1189         /* if we're currently showing the original pose, only certain events are handled */
1190         if (pld->flag & PL_PREVIEW_SHOWORIGINAL) {
1191                 switch (event->type) {
1192                         /* exit - cancel */
1193                         case ESCKEY:
1194                         case RIGHTMOUSE:
1195                                 pld->state= PL_PREVIEW_CANCEL;
1196                                 break;
1197                                 
1198                         /* exit - confirm */
1199                         case LEFTMOUSE:
1200                         case RETKEY:
1201                         case PADENTER:
1202                         case SPACEKEY:
1203                                 pld->state= PL_PREVIEW_CONFIRM;
1204                                 break;
1205                         
1206                         /* view manipulation */
1207                         /* we add pass through here, so that the operators responsible for these can still run, 
1208                          * even though we still maintain control (as RUNNING_MODAL flag is still set too)
1209                          */
1210                         case PAD0: case PAD1: case PAD2: case PAD3: case PAD4:
1211                         case PAD5: case PAD6: case PAD7: case PAD8: case PAD9:
1212                         case PADPLUSKEY: case PADMINUS: 
1213                         case MIDDLEMOUSE: case MOUSEMOVE:
1214                                 //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1215                                 ret = OPERATOR_PASS_THROUGH;
1216                                 break;
1217                                 
1218                         /* quicky compare to original */
1219                         case TABKEY:
1220                                 pld->flag &= ~PL_PREVIEW_SHOWORIGINAL;
1221                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1222                                 break;
1223                 }
1224                 
1225                 /* EXITS HERE... */
1226                 return ret;
1227         }
1228         
1229         /* NORMAL EVENT HANDLING... */
1230         /* searching takes priority over normal activity */
1231         switch (event->type) {
1232                 /* exit - cancel */
1233                 case ESCKEY:
1234                 case RIGHTMOUSE:
1235                         pld->state= PL_PREVIEW_CANCEL;
1236                         break;
1237                         
1238                 /* exit - confirm */
1239                 case LEFTMOUSE:
1240                 case RETKEY:
1241                 case PADENTER:
1242                 case SPACEKEY:
1243                         pld->state= PL_PREVIEW_CONFIRM;
1244                         break;
1245                         
1246                 /* toggle between original pose and poselib pose*/
1247                 case TABKEY:
1248                         pld->flag |= PL_PREVIEW_SHOWORIGINAL;
1249                         pld->redraw= PL_PREVIEW_REDRAWALL;
1250                         break;
1251                 
1252                 /* change to previous pose (cyclic) */
1253                 case PAGEUPKEY:
1254                 case WHEELUPMOUSE:
1255                         poselib_preview_get_next(pld, -1);
1256                         pld->redraw= PL_PREVIEW_REDRAWALL;
1257                         break;
1258                 
1259                 /* change to next pose (cyclic) */
1260                 case PAGEDOWNKEY:
1261                 case WHEELDOWNMOUSE:
1262                         poselib_preview_get_next(pld, 1);
1263                         pld->redraw= PL_PREVIEW_REDRAWALL;
1264                         break;
1265                 
1266                 /* jump 5 poses (cyclic, back) */
1267                 case DOWNARROWKEY:
1268                         poselib_preview_get_next(pld, -5);
1269                         pld->redraw= PL_PREVIEW_REDRAWALL;
1270                         break;
1271                 
1272                 /* jump 5 poses (cyclic, forward) */
1273                 case UPARROWKEY:
1274                         poselib_preview_get_next(pld, 5);
1275                         pld->redraw= PL_PREVIEW_REDRAWALL;
1276                         break;
1277                 
1278                 /* change to next pose or searching cursor control */
1279                 case RIGHTARROWKEY:
1280                         if (pld->searchstr[0]) {
1281                                 /* move text-cursor to the right */
1282                                 if (pld->search_cursor < strlen(pld->searchstr))
1283                                         pld->search_cursor++;
1284                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1285                         }
1286                         else {
1287                                 /* change to next pose (cyclic) */
1288                                 poselib_preview_get_next(pld, 1);
1289                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1290                         }
1291                         break;
1292                         
1293                 /* change to next pose or searching cursor control */
1294                 case LEFTARROWKEY:
1295                         if (pld->searchstr[0]) {
1296                                 /* move text-cursor to the left */
1297                                 if (pld->search_cursor)
1298                                         pld->search_cursor--;
1299                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1300                         }
1301                         else {
1302                                 /* change to previous pose (cyclic) */
1303                                 poselib_preview_get_next(pld, -1);
1304                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1305                         }
1306                         break;
1307                         
1308                 /* change to first pose or start of searching string */
1309                 case HOMEKEY:
1310                         if (pld->searchstr[0]) {
1311                                 pld->search_cursor= 0;
1312                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1313                         }
1314                         else {
1315                                 /* change to first pose */
1316                                 pld->marker= pld->act->markers.first;
1317                                 pld->act->active_marker= 1;
1318                                 
1319                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1320                         }
1321                         break;
1322                         
1323                 /* change to last pose or start of searching string */
1324                 case ENDKEY:
1325                         if (pld->searchstr[0]) {
1326                                 pld->search_cursor= strlen(pld->searchstr);
1327                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1328                         }
1329                         else {
1330                                 /* change to last pose */
1331                                 pld->marker= pld->act->markers.last;
1332                                 pld->act->active_marker= BLI_countlist(&pld->act->markers);
1333                                 
1334                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1335                         }
1336                         break;
1337                 
1338                 /* view manipulation */
1339                 /* we add pass through here, so that the operators responsible for these can still run, 
1340                  * even though we still maintain control (as RUNNING_MODAL flag is still set too)
1341                  */
1342                 case MIDDLEMOUSE: case MOUSEMOVE:
1343                         //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1344                         ret = OPERATOR_PASS_THROUGH;
1345                         break;
1346                         
1347                 /* view manipulation, or searching */
1348                 case PAD0: case PAD1: case PAD2: case PAD3: case PAD4:
1349                 case PAD5: case PAD6: case PAD7: case PAD8: case PAD9:
1350                 case PADPLUSKEY: case PADMINUS:
1351                         if (pld->searchstr[0]) {
1352                                 /* searching... */
1353                                 poselib_preview_handle_search(pld, event->type, event->ascii);
1354                         }
1355                         else {
1356                                 /* view manipulation (see above) */
1357                                 //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1358                                 ret = OPERATOR_PASS_THROUGH;
1359                         }
1360                         break;
1361                         
1362                 /* otherwise, assume that searching might be able to handle it */
1363                 default:
1364                         poselib_preview_handle_search(pld, event->type, event->ascii);
1365                         break;
1366         }
1367         
1368         return ret;
1369 }
1370
1371 /* ---------------------------- */
1372
1373 /* Init PoseLib Previewing data */
1374 static void poselib_preview_init_data (bContext *C, wmOperator *op)
1375 {
1376         tPoseLib_PreviewData *pld;
1377         Object *ob= get_poselib_object(C);
1378         int pose_index = RNA_int_get(op->ptr, "pose_index");
1379         
1380         /* set up preview state info */
1381         op->customdata= pld= MEM_callocN(sizeof(tPoseLib_PreviewData), "PoseLib Preview Data");
1382         
1383         /* get basic data */
1384         pld->ob= ob;
1385         pld->arm= (ob) ? (ob->data) : NULL;
1386         pld->pose= (ob) ? (ob->pose) : NULL;
1387         pld->act= (ob) ? (ob->poselib) : NULL;
1388         
1389         pld->scene= CTX_data_scene(C);
1390         pld->sa= CTX_wm_area(C);
1391         
1392         /* get starting pose based on RNA-props for this operator */
1393         if (pose_index == -1)
1394                 pld->marker= poselib_get_active_pose(pld->act);
1395         else if (pose_index == -2)
1396                 pld->flag |= PL_PREVIEW_SHOWORIGINAL;
1397         else
1398                 pld->marker= (pld->act) ? BLI_findlink(&pld->act->markers, pose_index) : NULL;
1399         
1400         /* check if valid poselib */
1401         if (ELEM3(NULL, pld->ob, pld->pose, pld->arm)) {
1402                 BKE_report(op->reports, RPT_ERROR, "PoseLib is only for Armatures in PoseMode");
1403                 pld->state= PL_PREVIEW_ERROR;
1404                 return;
1405         }
1406         if (pld->act == NULL) {
1407                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have a valid PoseLib");
1408                 pld->state= PL_PREVIEW_ERROR;
1409                 return;
1410         }
1411         if (pld->marker == NULL) {
1412                 if (pld->act->markers.first) {
1413                         /* just use first one then... */
1414                         pld->marker= pld->act->markers.first;
1415                         if (pose_index > -2) 
1416                                 BKE_report(op->reports, RPT_WARNING, "PoseLib had no active pose");
1417                 }
1418                 else {
1419                         BKE_report(op->reports, RPT_ERROR, "PoseLib has no poses to preview/apply");
1420                         pld->state= PL_PREVIEW_ERROR;
1421                         return;
1422                 }
1423         }
1424         
1425         /* get ID pointer for applying poses */
1426         RNA_id_pointer_create(&ob->id, &pld->rna_ptr);
1427         
1428         /* make backups for restoring pose */
1429         poselib_backup_posecopy(pld);
1430         
1431         /* set flags for running */
1432         pld->state= PL_PREVIEW_RUNNING;
1433         pld->redraw= PL_PREVIEW_REDRAWALL;
1434         pld->flag |= PL_PREVIEW_FIRSTTIME;
1435         
1436         /* set depsgraph flags */
1437                 /* make sure the lock is set OK, unlock can be accidentally saved? */
1438         pld->pose->flag |= POSE_LOCKED;
1439         pld->pose->flag &= ~POSE_DO_UNLOCK;
1440         
1441         /* clear strings + search */
1442         pld->headerstr[0]= pld->searchstr[0]= pld->searchold[0]= '\0';
1443         pld->search_cursor= 0;
1444 }
1445
1446 /* After previewing poses */
1447 static void poselib_preview_cleanup (bContext *C, wmOperator *op)
1448 {
1449         tPoseLib_PreviewData *pld= (tPoseLib_PreviewData *)op->customdata;
1450         Scene *scene= pld->scene;
1451         Object *ob= pld->ob;
1452         bPose *pose= pld->pose;
1453         bArmature *arm= pld->arm;
1454         bAction *act= pld->act;
1455         TimeMarker *marker= pld->marker;
1456         
1457         /* redraw the header so that it doesn't show any of our stuff anymore */
1458         ED_area_headerprint(pld->sa, NULL);
1459         
1460         /* this signal does one recalc on pose, then unlocks, so ESC or edit will work */
1461         pose->flag |= POSE_DO_UNLOCK;
1462         
1463         /* clear pose if cancelled */
1464         if (pld->state == PL_PREVIEW_CANCEL) {
1465                 poselib_backup_restore(pld);
1466                 
1467                 /* old optimize trick... this enforces to bypass the depgraph 
1468                  *      - note: code copied from transform_generics.c -> recalcData()
1469                  */
1470                 if ((arm->flag & ARM_DELAYDEFORM)==0)
1471                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);  /* sets recalc flags */
1472                 else
1473                         where_is_pose(scene, ob);
1474                 
1475         }
1476         else if (pld->state == PL_PREVIEW_CONFIRM) {
1477                 /* tag poses as appropriate */
1478                 poselib_keytag_pose(C, scene, pld);
1479                 
1480                 /* change active pose setting */
1481                 act->active_marker= BLI_findindex(&act->markers, marker) + 1;
1482                 action_set_activemarker(act, marker, NULL);
1483                 
1484                 /* Update event for pose and deformation children */
1485                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1486                 
1487                 /* updates */
1488                 if (IS_AUTOKEY_MODE(scene, NORMAL)) {
1489                         //remake_action_ipos(ob->action);
1490                 }
1491                 else
1492                         where_is_pose(scene, ob);
1493         }
1494         
1495         /* free memory used for backups and searching */
1496         poselib_backup_free_data(pld);
1497         BLI_freelistN(&pld->searchp);
1498         
1499         /* free temp data for operator */
1500         MEM_freeN(pld);
1501         op->customdata= NULL;
1502 }
1503
1504 /* End previewing operation */
1505 static int poselib_preview_exit (bContext *C, wmOperator *op)
1506 {
1507         tPoseLib_PreviewData *pld= op->customdata;
1508         int exit_state = pld->state;
1509         
1510         /* finish up */
1511         poselib_preview_cleanup(C, op);
1512         
1513         if (ELEM(exit_state, PL_PREVIEW_CANCEL, PL_PREVIEW_ERROR))
1514                 return OPERATOR_CANCELLED;
1515         else
1516                 return OPERATOR_FINISHED;
1517 }
1518
1519 /* Cancel previewing operation (called when exiting Blender) */
1520 static int poselib_preview_cancel (bContext *C, wmOperator *op)
1521 {
1522         poselib_preview_exit(C, op);
1523         return OPERATOR_CANCELLED;
1524 }
1525
1526 /* main modal status check */
1527 static int poselib_preview_modal (bContext *C, wmOperator *op, wmEvent *event)
1528 {
1529         tPoseLib_PreviewData *pld= op->customdata;
1530         int ret;
1531         
1532         /* 1) check state to see if we're still running */
1533         if (pld->state != PL_PREVIEW_RUNNING)
1534                 return poselib_preview_exit(C, op);
1535         
1536         /* 2) handle events */
1537         ret= poselib_preview_handle_event(C, op, event);
1538         
1539         /* 3) apply changes and redraw, otherwise, confirming goes wrong */
1540         if (pld->redraw)
1541                 poselib_preview_apply(C, op);
1542         
1543         return ret;
1544 }
1545
1546 /* Modal Operator init */
1547 static int poselib_preview_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1548 {
1549         tPoseLib_PreviewData *pld;
1550         
1551         /* check if everything is ok, and init settings for modal operator */
1552         poselib_preview_init_data(C, op);
1553         pld= (tPoseLib_PreviewData *)op->customdata;
1554         
1555         if (pld->state == PL_PREVIEW_ERROR) {
1556                 /* an error occurred, so free temp mem used */
1557                 poselib_preview_cleanup(C, op);
1558                 return OPERATOR_CANCELLED;
1559         }
1560         
1561         /* do initial apply to have something to look at */
1562         poselib_preview_apply(C, op);
1563         
1564         /* add temp handler if we're running as a modal operator */
1565         WM_event_add_modal_handler(C, op);
1566
1567         return OPERATOR_RUNNING_MODAL;
1568 }
1569
1570 /* Repeat operator */
1571 static int poselib_preview_exec (bContext *C, wmOperator *op)
1572 {
1573         tPoseLib_PreviewData *pld;
1574         
1575         /* check if everything is ok, and init settings for modal operator */
1576         poselib_preview_init_data(C, op);
1577         pld= (tPoseLib_PreviewData *)op->customdata;
1578         
1579         if (pld->state == PL_PREVIEW_ERROR) {
1580                 /* an error occurred, so free temp mem used */
1581                 poselib_preview_cleanup(C, op);
1582                 return OPERATOR_CANCELLED;
1583         }
1584         
1585         /* the exec() callback is effectively a 'run-once' scenario, so set the state to that
1586          * so that everything draws correctly
1587          */
1588         pld->state = PL_PREVIEW_RUNONCE;
1589         
1590         /* apply the active pose */
1591         poselib_preview_apply(C, op);
1592         
1593         /* now, set the status to exit */
1594         pld->state = PL_PREVIEW_CONFIRM;
1595         
1596         /* cleanup */
1597         return poselib_preview_exit(C, op);
1598 }
1599
1600 void POSELIB_OT_browse_interactive (wmOperatorType *ot)
1601 {
1602         /* identifiers */
1603         ot->name= "PoseLib Browse Poses";
1604         ot->idname= "POSELIB_OT_browse_interactive";
1605         ot->description= "Interactively browse poses in 3D-View";
1606         
1607         /* callbacks */
1608         ot->invoke= poselib_preview_invoke;
1609         ot->modal= poselib_preview_modal;
1610         ot->cancel= poselib_preview_cancel;
1611         ot->exec= poselib_preview_exec;
1612         ot->poll= has_poselib_pose_data_poll;
1613         
1614         /* flags */
1615         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1616         
1617         /* properties */        
1618                 // TODO: make the pose_index into a proper enum instead of a cryptic int...
1619         ot->prop= RNA_def_int(ot->srna, "pose_index", -1, -2, INT_MAX, "Pose", "Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)", 0, INT_MAX);
1620         
1621         // XXX: percentage vs factor?
1622         /* not used yet */
1623         /* RNA_def_float_factor(ot->srna, "blend_factor", 1.0f, 0.0f, 1.0f, "Blend Factor", "Amount that the pose is applied on top of the existing poses", 0.0f, 1.0f); */
1624 }
1625
1626 void POSELIB_OT_apply_pose (wmOperatorType *ot)
1627 {
1628         /* identifiers */
1629         ot->name = "Apply Pose Library Pose";
1630         ot->idname = "POSELIB_OT_apply_pose";
1631         ot->description = "Apply specified Pose Library pose to the rig";
1632         
1633         /* callbacks */
1634         ot->exec= poselib_preview_exec;
1635         ot->poll= has_poselib_pose_data_poll;
1636         
1637         /* flags */
1638         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1639         
1640         /* properties */        
1641                 // TODO: make the pose_index into a proper enum instead of a cryptic int...
1642         ot->prop= RNA_def_int(ot->srna, "pose_index", -1, -2, INT_MAX, "Pose", "Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)", 0, INT_MAX);
1643 }