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