~unity-team/unity/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/*
 * Copyright 2012 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3, as
 * published by the  Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the applicable version of the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of both the GNU Lesser General Public
 * License version 3 along with this program.  If not, see
 * <http://www.gnu.org/licenses/>
 *
 * Authored by: Nick Dedekind <nick.dedekind@canonical.com>
 *
 */

#include "PreviewContainer.h"
#include <NuxCore/Logger.h>
#include <Nux/HLayout.h>

#include "unity-shared/IntrospectableWrappers.h"
#include "unity-shared/TimeUtil.h"
#include "unity-shared/PreviewStyle.h"
#include "PreviewNavigator.h"
#include <boost/math/constants/constants.hpp>
#include "config.h"

namespace unity
{
namespace dash
{
namespace previews
{

Navigation operator&(const Navigation lhs, const Navigation rhs)
{
  return Navigation(int(lhs) & int(rhs));
}

namespace
{
nux::logging::Logger logger("unity.dash.previews.previewcontainer");



const int ANIM_DURATION_SHORT_SHORT = 100;
const int ANIM_DURATION = 200;
const int ANIM_DURATION_LONG = 500;

const std::string ANIMATION_IDLE = "animation-idle";
}

class PreviewContent : public nux::Layout, public debug::Introspectable
{
public:
  PreviewContent(PreviewContainer*const parent)
  : parent_(parent)
  , progress_(0.0)
  , curve_progress_(0.0)
  , animating_(false)
  , waiting_preview_(false)
  , rotation_(0.0)
  , preview_initiate_count_(0)
  , nav_complete_(0)
  , relative_nav_index_(0)
  {
    OnGeometryChanged.connect([&](nux::Area*, nux::Geometry& geo)
    {
      // Need to update the preview geometries when updating the container geo.
      UpdateAnimationProgress(progress_, curve_progress_);
    });
    Style& style = previews::Style::Instance();

    spin_= style.GetSearchSpinIcon(256);
  }

  // From debug::Introspectable
  std::string GetName() const
  {
    return "PreviewContent";
  }

  void AddProperties(GVariantBuilder* builder)
  {
    variant::BuilderWrapper(builder)
      .add("animating", animating_)
      .add("animation_progress", progress_)
      .add("waiting_preview", waiting_preview_)
      .add("preview-initiate-count", preview_initiate_count_)
      .add("navigation-complete-count", nav_complete_)
      .add("relative-nav-index", relative_nav_index_);
  }

  void PushPreview(previews::Preview::Ptr preview, Navigation direction)
  {
    preview_initiate_count_++;
    StopPreviewWait();

    if (preview)
    {
      // the parents layout will not change based on the previews.
      preview->SetReconfigureParentLayoutOnGeometryChange(false);
      
      AddChild(preview.GetPointer());
      AddView(preview.GetPointer());
      preview->SetVisible(false);
    }
    PreviewSwipe swipe;
    swipe.direction = direction;
    swipe.preview = preview;
    push_preview_.push(swipe);

    if (!animating_)
    {
      UpdateAnimationProgress(0.0, 0.0);
    }
    start_navigation.emit();
  }

  bool IsAnimating() { return animating_; }

  int SwipeQueueSize() const { return push_preview_.size(); }

  float GetAnimationProgress() const { return progress_; }

  void UpdateAnimationProgress(float progress, float curve_progress)
  {
    progress_ = progress;
    curve_progress_ = curve_progress;

    if (!animating_)
    {
      if (!push_preview_.empty())
      {
        animating_= true;
        swipe_ = push_preview_.front();
        push_preview_.pop();

        if (current_preview_)
          current_preview_->OnNavigateOut();
        if (swipe_.preview)
          swipe_.preview->OnNavigateIn();
      }
    }

    nux::Geometry const& geometry = GetGeometry();
    if (animating_)
    { 
       // swipe out.
      if (current_preview_)
      {
        current_preview_->SetVisible(true);

        nux::Geometry swipeOut = geometry;
        if (swipe_.direction == Navigation::RIGHT)
          swipeOut.OffsetPosition(-(curve_progress * (parent_->GetGeometry().width - geometry.x)), 0);
        else if (swipe_.direction == Navigation::LEFT)
          swipeOut.OffsetPosition(curve_progress* (parent_->GetGeometry().width - geometry.x), 0);
        current_preview_->SetGeometry(swipeOut);
      }
 
       // swipe in
      if (swipe_.preview)
      {
        swipe_.preview->SetVisible(true);

        nux::Geometry swipeIn = geometry;
        if (swipe_.direction == Navigation::RIGHT)
          swipeIn.OffsetPosition(float(parent_->GetGeometry().width - geometry.x) - (curve_progress * (parent_->GetGeometry().width - geometry.x)), 0);
        else if (swipe_.direction == Navigation::LEFT)
          swipeIn.OffsetPosition(-((1.0-curve_progress)*(parent_->GetGeometry().width - geometry.x)), 0);
        swipe_.preview->SetGeometry(swipeIn);
      }
    }

    if (progress >= 1.0)
    {
      // if we were animating, we need to remove the old preview, and replace it with the new.
      if (animating_)
      {
        animating_ = false;
        if (current_preview_)
        {
          RemoveChild(current_preview_.GetPointer());
          RemoveChildObject(current_preview_.GetPointer());
          current_preview_.Release();
        }
        if (swipe_.preview)
        {
          if (swipe_.direction == Navigation::RIGHT)
            relative_nav_index_++;
          else if (swipe_.direction == Navigation::LEFT)
            relative_nav_index_--;

          current_preview_ = swipe_.preview;
          swipe_.preview.Release();
          if (current_preview_)
            current_preview_->OnNavigateInComplete();
        } 

        // another swipe?
        if (!push_preview_.empty())
        {
          progress_ = 0;
          continue_navigation.emit();
        }
        else
        {
          end_navigation.emit();
        }
      }

      // set the geometry to the whole layout.
      if (current_preview_)
      {
        current_preview_->SetGeometry(geometry);
      }
      nav_complete_++;
    }
  }

  void StartPreviewWait()
  {
    preview_wait_timer_.reset(new glib::Timeout(300, [&] () {

      if (waiting_preview_)
        return false;

      waiting_preview_ = true;

      rotate_matrix_.Rotate_z(0.0f);
      rotation_ = 0.0f;
      parent_->QueueDraw();
      return false;
    }));
  }

  void StopPreviewWait()
  {
    preview_wait_timer_.reset();
    waiting_preview_ = false;
    parent_->QueueDraw();
  }

  bool OnFrameTimeout()
  {
    frame_timeout_.reset();
    rotation_ += 0.1f;

    if (rotation_ >= 360.0f)
      rotation_ = 0.0f;

    rotate_matrix_.Rotate_z(rotation_);
    parent_->QueueDraw();

    return false;
  }

  // Dont draw in process draw. this is so we can control the z order.
  void ProcessDraw(nux::GraphicsEngine& gfx_engine, bool force_draw)
  {
  }

  void ProcessDraw2(nux::GraphicsEngine& gfx_engine, bool force_draw)
  {
    if (swipe_.preview && swipe_.preview->IsVisible()) { swipe_.preview->ProcessDraw(gfx_engine, force_draw); }
    if (current_preview_ && current_preview_->IsVisible()) { current_preview_->ProcessDraw(gfx_engine, force_draw); }


    if (waiting_preview_)
    { 
      nux::Geometry const& base = GetGeometry(); 

      unsigned int alpha, src, dest = 0;
      gfx_engine.GetRenderStates().GetBlend(alpha, src, dest);
      gfx_engine.GetRenderStates().SetBlend(true, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

      nux::TexCoordXForm texxform;
      texxform.SetTexCoordType(nux::TexCoordXForm::OFFSET_COORD);
      texxform.SetWrap(nux::TEXWRAP_REPEAT, nux::TEXWRAP_REPEAT);
      texxform.min_filter = nux::TEXFILTER_LINEAR;
      texxform.mag_filter = nux::TEXFILTER_LINEAR;

      nux::Geometry spin_geo(base.x + ((base.width - spin_->GetWidth()) / 2),
                             base.y + ((base.height - spin_->GetHeight()) / 2),
                             spin_->GetWidth(),
                             spin_->GetHeight());
      // Geometry (== Rect) uses integers which were rounded above,
      // hence an extra 0.5 offset for odd sizes is needed
      // because pure floating point is not being used.
      int spin_offset_w = !(base.width % 2) ? 0 : 1;
      int spin_offset_h = !(base.height % 2) ? 0 : 1;

      gfx_engine.PushModelViewMatrix(nux::Matrix4::TRANSLATE(-spin_geo.x - (spin_geo.width + spin_offset_w) / 2.0f,
                                                             -spin_geo.y - (spin_geo.height + spin_offset_h) / 2.0f, 0));
      gfx_engine.PushModelViewMatrix(rotate_matrix_);
      gfx_engine.PushModelViewMatrix(nux::Matrix4::TRANSLATE(spin_geo.x + (spin_geo.width + spin_offset_w) / 2.0f,
                                                             spin_geo.y + (spin_geo.height + spin_offset_h) / 2.0f, 0));

      gfx_engine.QRP_1Tex(spin_geo.x,
                          spin_geo.y,
                          spin_geo.width,
                          spin_geo.height,
                          spin_->GetDeviceTexture(),
                          texxform,
                          nux::color::White);

      gfx_engine.PopModelViewMatrix();
      gfx_engine.PopModelViewMatrix();
      gfx_engine.PopModelViewMatrix();

      gfx_engine.GetRenderStates().SetBlend(alpha, src, dest);

      if (!frame_timeout_)
      {
        frame_timeout_.reset(new glib::Timeout(22, sigc::mem_fun(this, &PreviewContent::OnFrameTimeout)));
      }
    }

    _queued_draw = false;
  }

  sigc::signal<void> start_navigation;
  sigc::signal<void> continue_navigation;
  sigc::signal<void> end_navigation;

private:
  PreviewContainer*const parent_;

  // Swipe animation
  struct PreviewSwipe
  {
    Navigation direction;
    previews::Preview::Ptr preview;

    void reset() { preview.Release(); }
  };
  previews::Preview::Ptr current_preview_;
  std::queue<PreviewSwipe> push_preview_;
  PreviewSwipe swipe_;

  float progress_;
  float curve_progress_;
  bool animating_;
  // wait animation
  glib::Source::UniquePtr preview_wait_timer_;
  glib::Source::UniquePtr _frame_timeout;
  bool waiting_preview_;
  nux::ObjectPtr<nux::BaseTexture> spin_;

  glib::Source::UniquePtr frame_timeout_;
  nux::Matrix4 rotate_matrix_;
  float rotation_;

  // intropection data.
  int preview_initiate_count_;
  int nav_complete_;
  int relative_nav_index_;
};

NUX_IMPLEMENT_OBJECT_TYPE(PreviewContainer);

PreviewContainer::PreviewContainer(NUX_FILE_LINE_DECL)
  : View(NUX_FILE_LINE_PARAM)
  , content_layout_(nullptr)
  , nav_disabled_(Navigation::NONE)
  , navigation_progress_speed_(0.0)
  , navigation_count_(0)
{
  SetAcceptKeyNavFocusOnMouseDown(false);
  SetAcceptKeyNavFocusOnMouseEnter(true);

  SetupViews();
  last_progress_time_.tv_sec = 0;
  last_progress_time_.tv_nsec = 0;

  key_down.connect(sigc::mem_fun(this, &PreviewContainer::OnKeyDown));
}

PreviewContainer::~PreviewContainer()
{
}

void PreviewContainer::Preview(dash::Preview::Ptr preview_model, Navigation direction)
{
  previews::Preview::Ptr preview_view = previews::Preview::PreviewForModel(preview_model);
  content_layout_->PushPreview(preview_view, direction);
}

void PreviewContainer::DisableNavButton(Navigation button)
{
  nav_disabled_ = button;
  nav_right_->SetEnabled(IsNavigationDisabled(Navigation::RIGHT) == false);
  nav_left_->SetEnabled(IsNavigationDisabled(Navigation::LEFT) == false);
  QueueDraw();
}

bool PreviewContainer::IsNavigationDisabled(Navigation button) const
{
  return (nav_disabled_ & button) != Navigation::NONE;  
}

std::string PreviewContainer::GetName() const
{
  return "PreviewContainer";
}

void PreviewContainer::AddProperties(GVariantBuilder* builder)
{
  variant::BuilderWrapper(builder)
    .add(GetAbsoluteGeometry())
    .add("navigate-left-enabled", !IsNavigationDisabled(Navigation::LEFT))
    .add("navigate-right-enabled", !IsNavigationDisabled(Navigation::RIGHT));
}

void PreviewContainer::SetupViews()
{
  previews::Style& style = previews::Style::Instance();

  layout_ = new nux::HLayout();
  SetLayout(layout_);
  layout_->AddSpace(0, 1);

  nav_left_ = new PreviewNavigator(Orientation::LEFT, NUX_TRACKER_LOCATION);
  AddChild(nav_left_);
  nav_left_->SetMinimumWidth(style.GetNavigatorWidth());
  nav_left_->SetMaximumWidth(style.GetNavigatorWidth());
  nav_left_->activated.connect([&]() { navigate_left.emit(); });
  layout_->AddView(nav_left_, 0, nux::MINOR_POSITION_CENTER, nux::MINOR_SIZE_FULL);

  content_layout_ = new PreviewContent(this);
  content_layout_->SetMinMaxSize(style.GetPreviewWidth(), style.GetPreviewHeight());
  AddChild(content_layout_);
  layout_->AddLayout(content_layout_, 0, nux::MINOR_POSITION_CENTER, nux::MINOR_SIZE_FULL);

  nav_right_ = new PreviewNavigator(Orientation::RIGHT, NUX_TRACKER_LOCATION);
  AddChild(nav_right_);
  nav_right_->SetMinimumWidth(style.GetNavigatorWidth());
  nav_right_->SetMaximumWidth(style.GetNavigatorWidth());
  nav_right_->activated.connect([&]() { navigate_right.emit(); });
  layout_->AddView(nav_right_, 0, nux::MINOR_POSITION_CENTER, nux::MINOR_SIZE_FULL);

  layout_->AddSpace(0, 1);

  content_layout_->start_navigation.connect([&]()
  {
    // reset animation clock.
    if (navigation_count_ == 0)
      clock_gettime(CLOCK_MONOTONIC, &last_progress_time_);
  
    float navigation_progress_remaining = CLAMP((1.0 - content_layout_->GetAnimationProgress()) + navigation_count_, 1.0f, 10.0f);
    navigation_count_++;

    navigation_progress_speed_ = navigation_progress_remaining / ANIM_DURATION_LONG;
    QueueAnimation();
  });

  content_layout_->continue_navigation.connect([&]()
  {
    QueueAnimation(); 
  });

  content_layout_->end_navigation.connect([&]()
  {
    navigation_count_ = 0;
    navigation_progress_speed_ = 0;
  });

  navigate_right.connect( [&]() { content_layout_->StartPreviewWait(); } );
  navigate_left.connect( [&]() { content_layout_->StartPreviewWait(); } );
}

void PreviewContainer::Draw(nux::GraphicsEngine& gfx_engine, bool force_draw)
{
  nux::Geometry const& geo = GetGeometry();

  gfx_engine.PushClippingRectangle(geo);
  nux::GetPainter().PaintBackground(gfx_engine, geo);
  gfx_engine.PopClippingRectangle();
}

void PreviewContainer::DrawContent(nux::GraphicsEngine& gfx_engine, bool force_draw)
{
  nux::Geometry base = GetGeometry();
  gfx_engine.PushClippingRectangle(base);

    // rely on the compiz event loop to come back to us in a nice throttling
  if (AnimationInProgress())
  {
    if (!animation_timer_)
       animation_timer_.reset(new glib::Timeout(1000/60, sigc::mem_fun(this, &PreviewContainer::QueueAnimation)));
  }
  else if (content_layout_ && content_layout_->IsAnimating())
  {
    content_layout_->UpdateAnimationProgress(1.0f, 1.0f);
  }

  // Paint using ProcessDraw2. ProcessDraw is overrided  by empty impl so we can control z order.
  if (content_layout_)
  {
    content_layout_->ProcessDraw2(gfx_engine, force_draw);
  }
  if (GetCompositionLayout())
    GetCompositionLayout()->ProcessDraw(gfx_engine, force_draw);

  gfx_engine.PopClippingRectangle();
}

bool PreviewContainer::AnimationInProgress()
{
   // short circuit to avoid unneeded calculations
  struct timespec current;
  clock_gettime(CLOCK_MONOTONIC, &current);

  if (content_layout_ == nullptr)
    return false;

  // hover in animation
  if (navigation_progress_speed_ > 0)
    return true;

  return false;
}

static float easeInOutQuart(float t)
{
    t = CLAMP(t, 0.0, 1.0);
    t*=2.0f;
    if (t < 1.0) return 0.5f*pow(t, 4);
    else {
        t -= 2.0f;
        return -0.5f * (pow(t, 4)- 2);
    }
}

float PreviewContainer::GetSwipeAnimationProgress(struct timespec const& current) const
{
  int time_delta = TimeUtil::TimeDelta(&current, &last_progress_time_);
  float progress = content_layout_->GetAnimationProgress() + (navigation_progress_speed_ * time_delta);

  return progress;
}

bool PreviewContainer::QueueAnimation()
{
  animation_timer_.reset();
  
  timespec current;
  clock_gettime(CLOCK_MONOTONIC, &current);
  float progress = GetSwipeAnimationProgress(current);
  content_layout_->UpdateAnimationProgress(progress, easeInOutQuart(progress)); // ease in/out.
  last_progress_time_ = current;

  QueueDraw();
  return false;
}

bool PreviewContainer::AcceptKeyNavFocus()
{
  return true;
}

bool PreviewContainer::InspectKeyEvent(unsigned int eventType, unsigned int keysym, const char* character)
{
  nux::KeyNavDirection direction = nux::KEY_NAV_NONE;
  switch (keysym)
  {
    case NUX_VK_UP:
      direction = nux::KeyNavDirection::KEY_NAV_UP;
      break;
    case NUX_VK_DOWN:
      direction = nux::KeyNavDirection::KEY_NAV_DOWN;
      break;
    case NUX_VK_LEFT:
      direction = nux::KeyNavDirection::KEY_NAV_LEFT;
      break;
    case NUX_VK_RIGHT:
      direction = nux::KeyNavDirection::KEY_NAV_RIGHT;
      break;
    case NUX_VK_LEFT_TAB:
      direction = nux::KeyNavDirection::KEY_NAV_TAB_PREVIOUS;
      break;
    case NUX_VK_TAB:
      direction = nux::KeyNavDirection::KEY_NAV_TAB_NEXT;
      break;
    case NUX_VK_ENTER:
    case NUX_KP_ENTER:
      direction = nux::KeyNavDirection::KEY_NAV_ENTER;
      break;
    case NUX_VK_ESCAPE:
      return true;
    default:
      direction = nux::KeyNavDirection::KEY_NAV_NONE;
      break;
  }

  if (direction == nux::KeyNavDirection::KEY_NAV_NONE
      || direction == nux::KeyNavDirection::KEY_NAV_UP
      || direction == nux::KeyNavDirection::KEY_NAV_DOWN
      || direction == nux::KeyNavDirection::KEY_NAV_TAB_NEXT
      || direction == nux::KeyNavDirection::KEY_NAV_TAB_PREVIOUS
      || direction == nux::KeyNavDirection::KEY_NAV_ENTER)
  {
    // we don't handle these cases
    return false;
  }

   // check for edge cases where we want the keynav to bubble up
  if (direction == nux::KEY_NAV_LEFT && IsNavigationDisabled(Navigation::LEFT))
    return false; // pressed left on the first item, no diiice
  else if (direction == nux::KEY_NAV_RIGHT && IsNavigationDisabled(Navigation::RIGHT))
    return false; // pressed right on the last item, nope. nothing for you

  return true;
}

void PreviewContainer::OnKeyDown(unsigned long event_type, unsigned long event_keysym,
                                    unsigned long event_state, const TCHAR* character,
                                    unsigned short key_repeat_count)
{
  if (event_type == nux::NUX_KEYDOWN)
  {
    switch (event_keysym)
    {
      case NUX_VK_LEFT:
        navigate_left.emit();
        break;

      case NUX_VK_RIGHT:
        navigate_right.emit();
        break;

      case NUX_VK_ESCAPE:
        request_close.emit();
        break;

      default:
        return;
    }
  }
}

nux::Area* PreviewContainer::KeyNavIteration(nux::KeyNavDirection direction)
{
  return this;
}

} // namespace previews
} // namespace dash
} // namespace unity