1 /*
2  * Copyright 2017 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "SkottieSlide.h"
9 
10 #include "SkAnimTimer.h"
11 #include "SkCanvas.h"
12 #include "Skottie.h"
13 
14 SkottieSlide::SkottieSlide(const SkString& name, const SkString& path)
15     : fPath(path) {
16     fName = name;
17 }
18 
19 void SkottieSlide::load(SkScalar w, SkScalar h) {
20     fAnimation = skottie::Animation::MakeFromFile(fPath.c_str());
21     fWinSize   = SkSize::Make(w, h);
22     fTimeBase  = 0; // force a time reset
23 
24     if (fAnimation) {
25         fAnimation->setShowInval(fShowAnimationInval);
26         SkDebugf("loaded Bodymovin animation v: %s, size: [%f %f], fr: %f\n",
27                  fAnimation->version().c_str(),
28                  fAnimation->size().width(),
29                  fAnimation->size().height(),
30                  fAnimation->frameRate());
31     } else {
32         SkDebugf("failed to load Bodymovin animation: %s\n", fPath.c_str());
33     }
34 }
35 
36 void SkottieSlide::unload() {
37     fAnimation.reset();
38 }
39 
40 SkISize SkottieSlide::getDimensions() const {
41     // We always scale to fill the window.
42     return fWinSize.toCeil();
43 }
44 
45 void SkottieSlide::draw(SkCanvas* canvas) {
46     if (fAnimation) {
47         SkAutoCanvasRestore acr(canvas, true);
48         const auto dstR = SkRect::MakeSize(fWinSize);
49         fAnimation->render(canvas, &dstR);
50     }
51 }
52 
53 bool SkottieSlide::animate(const SkAnimTimer& timer) {
54     if (fTimeBase == 0) {
55         // Reset the animation time.
56         fTimeBase = timer.msec();
57     }
58 
59     if (fAnimation) {
60         auto t = timer.msec() - fTimeBase;
61         fAnimation->animationTick(t);
62     }
63     return true;
64 }
65 
66 bool SkottieSlide::onChar(SkUnichar c) {
67     switch (c) {
68     case 'I':
69         if (fAnimation) {
70             fShowAnimationInval = !fShowAnimationInval;
71             fAnimation->setShowInval(fShowAnimationInval);
72         }
73         break;
74     default:
75         break;
76     }
77 
78     return INHERITED::onChar(c);
79 }
80 
81 bool SkottieSlide::onMouse(SkScalar x, SkScalar y, sk_app::Window::InputState state, uint32_t) {
82     switch (state) {
83     case sk_app::Window::kUp_InputState:
84         fShowAnimationInval = !fShowAnimationInval;
85         fAnimation->setShowInval(fShowAnimationInval);
86         break;
87     default:
88         break;
89     }
90 
91     return false;
92 }
93