~ubuntu-tv-developers/ubuntutv/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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
/*
 * Copyright (C) 2010 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authored by: Neil Jagdish Patel <neil.patel@canonical.com>
 */


#include "DashView.h"
#include "DashViewPrivate.h"

#include <math.h>

#include <gio/gdesktopappinfo.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>

#include <NuxCore/Logger.h>
#include <UnityCore/GLibWrapper.h>
#include <UnityCore/RadioOptionFilter.h>

#include "FilterExpanderLabel.h"
#include "unity-shared/DashStyle.h"
#include "unity-shared/KeyboardUtil.h"
#include "unity-shared/UnitySettings.h"
#include "unity-shared/UBusMessages.h"
#include "unity-shared/PreviewStyle.h"

namespace unity
{
namespace dash
{
DECLARE_LOGGER(logger, "unity.dash.view");
namespace
{
previews::Style preview_style;
}

// This is so we can access some protected members in nux::VLayout and
// break the natural key navigation path.
class DashLayout: public nux::VLayout
{
public:
  DashLayout(NUX_FILE_LINE_DECL)
    : nux::VLayout(NUX_FILE_LINE_PARAM)
    , area_(nullptr)
  {}

  void SetSpecialArea(nux::Area* area)
  {
    area_ = area;
  }

protected:
  nux::Area* KeyNavIteration(nux::KeyNavDirection direction)
  {
    if (direction == nux::KEY_NAV_DOWN && area_ &&  area_->HasKeyFocus())
      return nullptr;
    else
      return nux::VLayout::KeyNavIteration(direction);
  }

private:
  nux::Area* area_;
};

NUX_IMPLEMENT_OBJECT_TYPE(DashView);

DashView::DashView()
  : nux::View(NUX_TRACKER_LOCATION)
  , home_lens_(new HomeLens(_("Home"), _("Home screen"), _("Search")))
  , preview_container_(nullptr)
  , preview_displaying_(false)
  , preview_navigation_mode_(previews::Navigation::NONE)
  , active_lens_view_(0)
  , last_activated_uri_("")
  , search_in_progress_(false)
  , activate_on_finish_(false)
  , visible_(false)
  , fade_out_value_(0.0f)
  , fade_in_value_(0.0f)
  , opening_row_y_(-1)
  , opening_row_height_(0)
{
  renderer_.SetOwner(this);
  renderer_.need_redraw.connect([this] () {
    QueueDraw();
  });

  SetupViews();
  SetupUBusConnections();

  lenses_.lens_added.connect(sigc::mem_fun(this, &DashView::OnLensAdded));
  mouse_down.connect(sigc::mem_fun(this, &DashView::OnMouseButtonDown));
  preview_state_machine_.PreviewActivated.connect(sigc::mem_fun(this, &DashView::BuildPreview));
  Relayout();

  home_lens_->AddLenses(lenses_);
  lens_bar_->Activate("home.lens");

  // we will special case when applications lens finishes global search
  // because we want to be able to launch applications immediately
  // without waiting for the search finished signal which will
  // be delayed by all the lenses we're searching
  home_lens_->lens_search_finished.connect(sigc::mem_fun(this, &DashView::OnAppsGlobalSearchFinished));

  // We are interested in the color of the desktop background.
  ubus_manager_.RegisterInterest(UBUS_BACKGROUND_COLOR_CHANGED, sigc::mem_fun(this, &DashView::OnBGColorChanged));

  // request the latest colour from bghash
  ubus_manager_.SendMessage(UBUS_BACKGROUND_REQUEST_COLOUR_EMIT);

}


DashView::~DashView()
{
  // Do this explicitely, otherwise dee will complain about invalid access
  // to the lens models
  RemoveLayout();
}

void DashView::OnBGColorChanged(GVariant *data)
{
  double red = 0.6f, green = 0.0f, blue = 0.0f, alpha = 0.0f;

  g_variant_get(data, "(dddd)", &red, &green, &blue, &alpha);
  background_color_ = nux::Color(red, green, blue, alpha);
  QueueDraw();
}

void DashView::SetMonitorOffset(int x, int y)
{
  renderer_.x_offset = x;
  renderer_.y_offset = y;
}

void DashView::ClosePreview()
{
  if (preview_displaying_)
  {
    layout_->SetPresentRedirectedView(true);
    animation_.Stop();
    fade_out_connection_.disconnect();
    fade_in_connection_.disconnect();
    // Set fade animation
    animation_.SetDuration(250);
    animation_.SetEasingCurve(na::EasingCurve(na::EasingCurve::Type::ExpoEaseIn));
    fade_in_connection_ = animation_.updated.connect(sigc::mem_fun(this, &DashView::FadeInCallBack));

    fade_in_value_ = 1.0f;
    animation_.SetStartValue(fade_in_value_);
    animation_.SetFinishValue(0.0f);
    animation_.Start();
  }

  preview_navigation_mode_ = previews::Navigation::NONE;
  preview_displaying_ = false;

  // re-focus dash view component.
  nux::GetWindowCompositor().SetKeyFocusArea(default_focus());
  QueueDraw();
}

void DashView::FadeOutCallBack(float const& fade_out_value)
{
  fade_out_value_ = fade_out_value;
  QueueDraw();
}

void DashView::FadeInCallBack(float const& fade_in_value)
{
  fade_in_value_ = fade_in_value;
  QueueDraw();

  if (fade_in_value_ == 0.0f)
  {
    // sanity check
    if (!preview_container_)
    {
      return;
    }
    RemoveChild(preview_container_.GetPointer());
    preview_container_->UnParentObject();
    preview_container_.Release(); // free resources
    preview_state_machine_.ClosePreview();

    // Closing the preview. Set  opening_row_y_ to -1;
    // opening_row_y_ is updated once when the preview
    opening_row_y_ = -1;
  }
}

void DashView::OnUriActivated(ResultView::ActivateType type, std::string const& uri, GVariant* data, std::string const& unique_id) 
{
  last_activated_uri_ = uri;
  stored_activated_unique_id_ = unique_id;

  if (data)
  {
    // Update positioning information.
    int position = -1;
    int row_height = 0;
    int results_to_the_left = 0;
    int results_to_the_right = 0;
    g_variant_get(data, "(iiii)", &position, &row_height, &results_to_the_left, &results_to_the_right);
    preview_state_machine_.SetSplitPosition(SplitPosition::CONTENT_AREA, position);
    preview_state_machine_.left_results = results_to_the_left;
    preview_state_machine_.right_results = results_to_the_right;

    if (opening_row_y_ == -1)
    {
      // Update only when opening the previews
      opening_row_y_ = position;
    }
    opening_row_height_ = row_height;
  }

  // we want immediate preview reaction on first opening.
  if (type == ResultView::ActivateType::PREVIEW && !preview_displaying_)
  {
    BuildPreview(Preview::Ptr(nullptr));
  }
}


void DashView::BuildPreview(Preview::Ptr model)
{
  if (!preview_displaying_)
  {
    // Make a copy of this DashView backup texture.
    if (layout_->RedirectRenderingToTexture())
    {
      nux::TexCoordXForm texxform;
      nux::ObjectPtr<nux::IOpenGLBaseTexture> src_texture;

      layout_copy_ = src_texture = layout_->BackupTexture();

      animation_.Stop();
      fade_out_connection_.disconnect();
      fade_in_connection_.disconnect();
      // Set fade animation
      animation_.SetDuration(250);
      animation_.SetEasingCurve(na::EasingCurve(na::EasingCurve::Type::ExpoEaseIn));
      fade_out_connection_ = animation_.updated.connect(sigc::mem_fun(this, &DashView::FadeOutCallBack));

      fade_out_value_ = 1.0f;
      animation_.SetStartValue(fade_out_value_);
      animation_.SetFinishValue(0.0f);
      animation_.Start();

      layout_->SetPresentRedirectedView(false);
    }

    preview_container_ = previews::PreviewContainer::Ptr(new previews::PreviewContainer());
    AddChild(preview_container_.GetPointer());
    preview_container_->SetParentObject(this);
    preview_container_->Preview(model, previews::Navigation::NONE); // no swipe left or right

    preview_container_->SetGeometry(layout_->GetGeometry());
    preview_displaying_ = true;

    // connect to nav left/right signals to request nav left/right movement.
    preview_container_->navigate_left.connect([&] () {
      preview_navigation_mode_ = previews::Navigation::LEFT;

      // sends a message to all result views, sending the the uri of the current preview result
      // and the unique id of the result view that should be handling the results
      ubus_manager_.SendMessage(UBUS_DASH_PREVIEW_NAVIGATION_REQUEST, g_variant_new("(iss)", -1, last_activated_uri_.c_str(), stored_activated_unique_id_.c_str()));
    });

    preview_container_->navigate_right.connect([&] () {
      preview_navigation_mode_ = previews::Navigation::RIGHT;

      // sends a message to all result views, sending the the uri of the current preview result
      // and the unique id of the result view that should be handling the results
      ubus_manager_.SendMessage(UBUS_DASH_PREVIEW_NAVIGATION_REQUEST, g_variant_new("(iss)", 1, last_activated_uri_.c_str(), stored_activated_unique_id_.c_str()));
    });

    preview_container_->request_close.connect([&] () { ClosePreview(); });
  }
  else
  {
    // got a new preview whilst already displaying, we probably clicked a navigation button.
    preview_container_->Preview(model, preview_navigation_mode_); // TODO
  }

  if (G_LIKELY(preview_state_machine_.left_results() > 0 && preview_state_machine_.right_results() > 0))
    preview_container_->DisableNavButton(previews::Navigation::NONE);
  else if (preview_state_machine_.left_results() > 0)
    preview_container_->DisableNavButton(previews::Navigation::RIGHT);
  else if (preview_state_machine_.right_results() > 0)
    preview_container_->DisableNavButton(previews::Navigation::LEFT);
  else
    preview_container_->DisableNavButton(previews::Navigation::BOTH);

  QueueDraw();
}

void DashView::AboutToShow()
{
  ubus_manager_.SendMessage(UBUS_BACKGROUND_REQUEST_COLOUR_EMIT);
  visible_ = true;
  search_bar_->text_entry()->SelectAll();

  /* Give the lenses a chance to prep data before we map them  */
  lens_bar_->Activate(active_lens_view_->lens()->id());
  if (active_lens_view_->lens()->id() == "home.lens")
  {
    for (auto lens : lenses_.GetLenses())
    {
      lens->view_type = ViewType::HOME_VIEW;
      LOG_DEBUG(logger) << "Setting ViewType " << ViewType::HOME_VIEW
                            << " on '" << lens->id() << "'";
    }

    home_lens_->view_type = ViewType::LENS_VIEW;
    LOG_DEBUG(logger) << "Setting ViewType " << ViewType::LENS_VIEW
                                << " on '" << home_lens_->id() << "'";
  }
  else if (active_lens_view_)
  {
    // careful here, the lens_view's view_type doesn't get reset when the dash
    // hides, but lens' view_type does, so we need to update the lens directly
    active_lens_view_->lens()->view_type = ViewType::LENS_VIEW;
  }

  // this will make sure the spinner animates if the search takes a while
  search_bar_->ForceSearchChanged();

  // if a preview is open, close it
  if (preview_displaying_) 
  {
    ClosePreview();
  }

  renderer_.AboutToShow();
}

void DashView::AboutToHide()
{
  visible_ = false;
  renderer_.AboutToHide();

  for (auto lens : lenses_.GetLenses())
  {
    lens->view_type = ViewType::HIDDEN;
    LOG_DEBUG(logger) << "Setting ViewType " << ViewType::HIDDEN
                          << " on '" << lens->id() << "'";
  }

  home_lens_->view_type = ViewType::HIDDEN;
  LOG_DEBUG(logger) << "Setting ViewType " << ViewType::HIDDEN
                            << " on '" << home_lens_->id() << "'";

  // if a preview is open, close it
  if (preview_displaying_) 
  {
    ClosePreview();
  }
}

void DashView::SetupViews()
{
  dash::Style& style = dash::Style::Instance();

  layout_ = new nux::HLayout();
  layout_->SetLeftAndRightPadding(style.GetVSeparatorSize(), 0);
  layout_->SetTopAndBottomPadding(style.GetHSeparatorSize(), 0);
  SetLayout(layout_);

  layout_->SetRedirectRenderingToTexture(true);
  content_layout_ = new DashLayout(NUX_TRACKER_LOCATION);
  content_layout_->SetTopAndBottomPadding(style.GetDashViewTopPadding(), 0);
  layout_->AddLayout(content_layout_, 1, nux::MINOR_POSITION_START, nux::MINOR_SIZE_FULL);


  lens_bar_ = new LensBar();
  AddChild(lens_bar_);
  lens_bar_->SetMaximumWidth(64);
  lens_bar_->SetMinimumWidth(64);

  lens_bar_->lens_activated.connect(sigc::mem_fun(this, &DashView::OnLensBarActivated));
  layout_->AddView(lens_bar_, 1, nux::MINOR_POSITION_START, nux::MINOR_SIZE_FIX);
  layout_->SetLeftAndRightPadding(0 ,0 );



  search_bar_layout_ = new nux::HLayout();
  search_bar_layout_->SetLeftAndRightPadding(style.GetSearchBarLeftPadding(), 0);
  content_layout_->AddLayout(search_bar_layout_, 0, nux::MINOR_POSITION_CENTER, nux::MINOR_SIZE_FULL);

  search_bar_ = new SearchBar();
  AddChild(search_bar_);
  search_bar_->SetMinimumHeight(style.GetSearchBarHeight());
  search_bar_->SetMaximumHeight(style.GetSearchBarHeight());
  search_bar_->activated.connect(sigc::mem_fun(this, &DashView::OnEntryActivated));
  search_bar_->search_changed.connect(sigc::mem_fun(this, &DashView::OnSearchChanged));
  search_bar_->live_search_reached.connect(sigc::mem_fun(this, &DashView::OnLiveSearchReached));
  search_bar_->showing_filters.changed.connect([&] (bool showing) { if (active_lens_view_) active_lens_view_->filters_expanded = showing; QueueDraw(); });
  search_bar_layout_->AddView(search_bar_, 1, nux::MINOR_POSITION_CENTER, nux::MINOR_SIZE_FULL);
  content_layout_->SetSpecialArea(search_bar_->show_filters());


  lenses_layout_ = new nux::HLayout();
  content_layout_->AddView(lenses_layout_, 1, nux::MINOR_POSITION_LEFT);

  home_view_ = new LensView(home_lens_, nullptr);
  home_view_->uri_activated.connect(sigc::mem_fun(this, &DashView::OnUriActivated));
  AddChild(home_view_);
  active_lens_view_ = home_view_;
  lens_views_[home_lens_->id] = home_view_;
  lenses_layout_->AddView(home_view_);
  content_layout_->SetLeftAndRightPadding(0,0);

  }

void DashView::SetupUBusConnections()
{
  ubus_manager_.RegisterInterest(UBUS_PLACE_ENTRY_ACTIVATE_REQUEST,
      sigc::mem_fun(this, &DashView::OnActivateRequest));
}

long DashView::PostLayoutManagement (long LayoutResult)
{
  Relayout();
  return LayoutResult;
}

void DashView::Relayout()
{
  nux::Geometry const& geo = GetGeometry();
  content_geo_ = GetBestFitGeometry(geo);
  dash::Style& style = dash::Style::Instance();

  if (style.always_maximised)
  {
    if (geo.width >= content_geo_.width && geo.height > content_geo_.height)
      content_geo_ = geo;
  }

  // kinda hacky, but it makes sure the content isn't so big that it throws
  // the bottom of the dash off the screen
  // not hugely happy with this, so FIXME
  lenses_layout_->SetMaximumHeight (content_geo_.height - search_bar_->GetGeometry().height - lens_bar_->GetGeometry().height - style.GetDashViewTopPadding());
  lenses_layout_->SetMinimumHeight (content_geo_.height - search_bar_->GetGeometry().height - lens_bar_->GetGeometry().height - style.GetDashViewTopPadding());

  layout_->SetMinMaxSize(content_geo_.width, content_geo_.height);

  // Minus the padding that gets added to the left
  float tile_width = style.GetTileWidth();
  style.SetDefaultNColumns(floorf((content_geo_.width - 32) / tile_width));

  ubus_manager_.SendMessage(UBUS_DASH_SIZE_CHANGED, g_variant_new("(ii)", content_geo_.width, content_geo_.height));

  if (preview_displaying_)
    preview_container_->SetGeometry(layout_->GetGeometry());

  QueueDraw();
}

// Gives us the width and height of the contents that will give us the best "fit",
// which means that the icons/views will not have unnecessary padding, everything will
// look tight
nux::Geometry DashView::GetBestFitGeometry(nux::Geometry const& for_geo)
{
  dash::Style& style = dash::Style::Instance();

  int width = 0, height = 0;
  int tile_width = style.GetTileWidth();
  int tile_height = style.GetTileHeight();
  int half = for_geo.width / 2;

  // if default dash size is bigger than half a screens worth of items, go for that.
  while ((width += tile_width) + (19 * 2) < half)
    ;

  width = MAX(width, tile_width * 6);

  width += 20 + 40; // add the left padding and the group plugin padding

  height = search_bar_->GetGeometry().height;
  height += tile_height * 3;
  height += (style.GetPlacesGroupTopSpace() - 2 + 24 + 2) * 3; // adding three group headers
  height += 1*2; // hseparator height
  height += style.GetDashViewTopPadding();
  height += lens_bar_->GetGeometry().height;

  if (for_geo.width > 800 && for_geo.height > 550)
  {
    width = MIN(width, for_geo.width-66);
    height = MIN(height, for_geo.height-24);
  }

  return nux::Geometry(0, 0, width, height);
}

void DashView::Draw(nux::GraphicsEngine& graphics_engine, bool force_draw)
{
  renderer_.DrawFull(graphics_engine, content_geo_, GetAbsoluteGeometry(), GetGeometry(), true);
}

/**
 * Parametrically interpolates a value in one of two consecutive closed intervals.
 *
 * @param[in] p
 * @param[in] start The left (least) value of the closed interval.
 * @param[in] end1  The right (greatest) value of the closed interval,
 *                  if start <= end1
 * @param[in] end2  The right (greatest) value of the closed interval,
 *                  if start > end1
 *
 * @returns the linear interpolation at @p p of the interval [start, end] where end
 * is @p end1 if start <= @p end1, otherwise end is @end2.
 */
static float Interpolate2(float p, int start, int end1, int end2)
{
  float result = end2;
  if (start < end2)
  {
    int end = start > end1 ? end2 : end1;
    result = start + p * (end - start);
  }

  return result;
}

void DashView::DrawContent(nux::GraphicsEngine& graphics_engine, bool force_draw)
{
  auto& style = dash::Style::Instance();

  renderer_.DrawInner(graphics_engine, content_geo_, GetAbsoluteGeometry(), GetGeometry());

  nux::Geometry clip_geo = layout_->GetGeometry();
  clip_geo.x += style.GetVSeparatorSize();
  graphics_engine.PushClippingRectangle(clip_geo);

  bool display_ghost = false;
  bool preview_redraw = false;
  if (preview_container_)
  {
    preview_redraw = preview_container_->IsRedrawNeeded();
  }

  if (!preview_displaying_ && layout_->RedirectRenderingToTexture() && (fade_in_value_ == 0.0f))
  {
    nux::Geometry layout_geo = layout_->GetGeometry();
    graphics_engine.PushClippingRectangle(layout_geo);
    nux::GetPainter().PaintBackground(graphics_engine, layout_geo);
    graphics_engine.PopClippingRectangle();
  }

  if (preview_displaying_ && (IsFullRedraw() || force_draw || preview_redraw) && layout_->RedirectRenderingToTexture())
  {
    display_ghost = true;
    nux::Geometry layout_geo = layout_->GetGeometry();
    graphics_engine.PushClippingRectangle(layout_geo);
    nux::GetPainter().PaintBackground(graphics_engine, layout_geo);
    graphics_engine.PopClippingRectangle();
  }

  if (IsFullRedraw())
  {
    nux::GetPainter().PushBackgroundStack();
  }


  if (preview_displaying_)
  {
    // Progressively reveal the preview.
    nux::Geometry preview_clip_geo = preview_container_->GetGeometry();
    preview_clip_geo.y = (preview_clip_geo.y + preview_clip_geo.height)/2.0f - 
      (1.0f - fade_out_value_) * (preview_clip_geo.height)/2.0f;
    preview_clip_geo.height = (1.0f - fade_out_value_) * (preview_clip_geo.height);

    graphics_engine.PushModelViewMatrix(nux::Matrix4::TRANSLATE(-preview_container_->GetWidth()/2.0f, -preview_container_->GetHeight()/2.0f, 0));
    graphics_engine.PushModelViewMatrix(nux::Matrix4::SCALE(1.0f - fade_out_value_, 1.0f - fade_out_value_, 1.0f));
    graphics_engine.PushModelViewMatrix(nux::Matrix4::TRANSLATE(preview_container_->GetWidth()/2.0f, preview_container_->GetHeight()/2.0f, 0));

    preview_container_->ProcessDraw(graphics_engine, (!force_draw) ? IsFullRedraw() : force_draw);

    graphics_engine.PopModelViewMatrix();
    graphics_engine.PopModelViewMatrix();
    graphics_engine.PopModelViewMatrix();
  }
  else if (fade_in_value_ > 0.0f && preview_container_ && preview_container_.IsValid())
  {
    graphics_engine.PushModelViewMatrix(nux::Matrix4::TRANSLATE(-preview_container_->GetWidth()/2.0f, -preview_container_->GetHeight()/2.0f, 0));
    graphics_engine.PushModelViewMatrix(nux::Matrix4::SCALE(fade_in_value_, fade_in_value_, 1.0f));
    graphics_engine.PushModelViewMatrix(nux::Matrix4::TRANSLATE(preview_container_->GetWidth()/2.0f, preview_container_->GetHeight()/2.0f, 0));

    preview_container_->ProcessDraw(graphics_engine, (!force_draw) ? IsFullRedraw() : force_draw);

    graphics_engine.PopModelViewMatrix();
    graphics_engine.PopModelViewMatrix();
    graphics_engine.PopModelViewMatrix();
  }
  else if (fade_in_value_ == 0.0f)
  {
    layout_->ProcessDraw(graphics_engine, force_draw);
  }

  // Animation effect rendering
  if (display_ghost || IsFullRedraw())
  {
    unsigned int current_alpha_blend;
    unsigned int current_src_blend_factor;
    unsigned int current_dest_blend_factor;
    graphics_engine.GetRenderStates().GetBlend(current_alpha_blend, current_src_blend_factor, current_dest_blend_factor);

    float ghost_opacity = 0.25f;
    float tint_factor = 1.2f;
    float saturation_ref = 0.4f;
    nux::Color bg_color = background_color_;

    int position_offset = 40;

    if (preview_displaying_ && layout_ && layout_->RedirectRenderingToTexture())
    {
      if (layout_copy_.IsValid())
      {
        graphics_engine.PushClippingRectangle(layout_->GetGeometry());
        graphics_engine.GetRenderStates().SetBlend(true, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
        nux::TexCoordXForm texxform;

        texxform.FlipVCoord(true);

        int filter_width = 10;
        if (active_lens_view_ && active_lens_view_->filters_expanded)
        {
          texxform.uoffset = (active_lens_view_->filter_bar()->GetX() -layout_->GetX())/(float)layout_->GetWidth();
          texxform.voffset = (active_lens_view_->filter_bar()->GetY() -layout_->GetY())/(float)layout_->GetHeight();

          texxform.SetTexCoordType(nux::TexCoordXForm::OFFSET_COORD);

          graphics_engine.QRP_1Tex(
            active_lens_view_->filter_bar()->GetX() + (1.0f - fade_out_value_)*(active_lens_view_->filter_bar()->GetWidth() + 10),
            active_lens_view_->filter_bar()->GetY(),
            active_lens_view_->filter_bar()->GetWidth(),
            active_lens_view_->filter_bar()->GetHeight(),
            layout_copy_, texxform,
            nux::Color(fade_out_value_, fade_out_value_, fade_out_value_, fade_out_value_)
            );
          filter_width += active_lens_view_->filter_bar()->GetWidth();
        }

        float saturation = fade_out_value_ + (1.0f - fade_out_value_) * saturation_ref;
        float opacity = fade_out_value_ < ghost_opacity ? ghost_opacity : fade_out_value_;
        nux::Color tint = nux::Color(
          fade_out_value_ + (1.0f - fade_out_value_) * tint_factor*bg_color.red,
          fade_out_value_ + (1.0f - fade_out_value_) * tint_factor*bg_color.green,
          fade_out_value_ + (1.0f - fade_out_value_) * tint_factor*bg_color.blue,
          1.0f);

        // Ghost row of items above the preview
        {
          int final_x = layout_->GetX();
          int final_y = layout_->GetY() - (opening_row_y_) - position_offset ;

          texxform.uoffset = 0.0f;
          texxform.voffset = 0.0f;
          texxform.SetTexCoordType(nux::TexCoordXForm::OFFSET_COORD);

          graphics_engine.QRP_TexDesaturate(
            fade_out_value_ * layout_->GetX() + (1.0f - fade_out_value_) * final_x,
            fade_out_value_ * layout_->GetY() + (1.0f - fade_out_value_) * final_y,
            layout_->GetWidth() - filter_width,
            opening_row_y_ + opening_row_height_,
            layout_copy_, texxform,
            nux::Color(tint.red, tint.green, tint.blue, opacity),
            saturation
            );
        }

        // Ghost row of items below the preview
        {
          int final_x = layout_->GetX();
          int final_y = layout_->GetY() + layout_->GetHeight() - (position_offset*1.9);

          texxform.uoffset = (layout_->GetX() - layout_->GetX())/(float)layout_->GetWidth();
          texxform.voffset = (opening_row_y_ + opening_row_height_ - layout_->GetY())/(float)layout_->GetHeight();
          texxform.SetTexCoordType(nux::TexCoordXForm::OFFSET_COORD);

          graphics_engine.QRP_TexDesaturate(
            fade_out_value_ * layout_->GetX() + (1 - fade_out_value_) * final_x,
            Interpolate2(1.0f - fade_out_value_, opening_row_y_ + opening_row_height_, final_y, layout_->GetHeight()),
            layout_->GetWidth() - filter_width,
            layout_->GetHeight() - opening_row_y_ - opening_row_height_,
            layout_copy_, texxform,
            nux::Color(tint.red, tint.green, tint.blue, opacity),
            saturation
            );
        }

        graphics_engine.GetRenderStates().SetBlend(false);
        graphics_engine.PopClippingRectangle();
      }


    }
    else if (layout_ && layout_->RedirectRenderingToTexture() && fade_in_value_ != 0.0f)
    {
      if (layout_copy_.IsValid())
      {
        graphics_engine.PushClippingRectangle(layout_->GetGeometry());
        graphics_engine.GetRenderStates().SetBlend(true, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
        nux::TexCoordXForm texxform;

        texxform.FlipVCoord(true);

        int filter_width = 10;
        if (active_lens_view_ && active_lens_view_->filters_expanded)
        {
          texxform.uoffset = (active_lens_view_->filter_bar()->GetX() -layout_->GetX())/(float)layout_->GetWidth();
          texxform.voffset = (active_lens_view_->filter_bar()->GetY() -layout_->GetY())/(float)layout_->GetHeight();

          texxform.SetTexCoordType(nux::TexCoordXForm::OFFSET_COORD);

          graphics_engine.QRP_1Tex(
            active_lens_view_->filter_bar()->GetX() + (fade_in_value_)*(active_lens_view_->filter_bar()->GetWidth() + 10),
            active_lens_view_->filter_bar()->GetY(),
            active_lens_view_->filter_bar()->GetWidth(),
            active_lens_view_->filter_bar()->GetHeight(),
            layout_copy_, texxform,
            nux::Color(1.0f - fade_in_value_, 1.0f - fade_in_value_, 1.0f - fade_in_value_, 1.0f - fade_in_value_)
            );
          filter_width += active_lens_view_->filter_bar()->GetWidth();
        }

        float saturation = fade_in_value_ * saturation_ref + (1.0f - fade_in_value_);
        float opacity = (1.0f - fade_in_value_) < ghost_opacity ? ghost_opacity : (1.0f - fade_in_value_);
        nux::Color tint = nux::Color(
          fade_in_value_ * tint_factor*bg_color.red + (1.0f - fade_in_value_),
          fade_in_value_ * tint_factor*bg_color.green + (1.0f - fade_in_value_),
          fade_in_value_ * tint_factor*bg_color.blue + (1.0f - fade_in_value_),
          1.0f);

        // Ghost row of items above the preview
        {
          int final_x = layout_->GetX();
          int final_y = layout_->GetY() - (opening_row_y_) - position_offset;

          texxform.uoffset = 0.0f;
          texxform.voffset = 0.0f;
          texxform.SetTexCoordType(nux::TexCoordXForm::OFFSET_COORD);

          graphics_engine.QRP_TexDesaturate(
            (1.0f - fade_in_value_) * layout_->GetX() + (fade_in_value_) * final_x,
            (1.0f - fade_in_value_) * layout_->GetY() + (fade_in_value_) * final_y,
            layout_->GetWidth() - filter_width,
            opening_row_y_ + opening_row_height_,
            layout_copy_, texxform,
            nux::Color(tint.red, tint.green, tint.blue, opacity),
            saturation
            );
        }

        // Ghost row of items below the preview
        {
          int final_x = layout_->GetX();
          int final_y = layout_->GetY() + layout_->GetHeight() -(position_offset*1.9);

          texxform.uoffset = (layout_->GetX() - layout_->GetX())/(float)layout_->GetWidth();
          texxform.voffset = (opening_row_y_ + opening_row_height_ - layout_->GetY())/(float)layout_->GetHeight();
          texxform.SetTexCoordType(nux::TexCoordXForm::OFFSET_COORD);

          graphics_engine.QRP_TexDesaturate(
            (1.0f - fade_in_value_) * layout_->GetX() + (fade_in_value_) * final_x,
            Interpolate2(fade_in_value_, opening_row_y_ + opening_row_height_, final_y, layout_->GetHeight()),
            layout_->GetWidth() - filter_width,
            layout_->GetHeight() - opening_row_y_ - opening_row_height_,
            layout_copy_, texxform,
            nux::Color(tint.red, tint.green, tint.blue, opacity),
            saturation
            );
        }
        graphics_engine.GetRenderStates().SetBlend(false);
        graphics_engine.PopClippingRectangle();
      }
    }

    graphics_engine.GetRenderStates().SetBlend(current_alpha_blend, current_src_blend_factor, current_dest_blend_factor);
  }

  if (IsFullRedraw())
  {
    nux::GetPainter().PopBackgroundStack();
  }

  graphics_engine.PopClippingRectangle();

  renderer_.DrawInnerCleanup(graphics_engine, content_geo_, GetAbsoluteGeometry(), GetGeometry());
}

void DashView::OnMouseButtonDown(int x, int y, unsigned long button, unsigned long key)
{
  dash::Style& style = dash::Style::Instance();
  nux::Geometry geo(content_geo_);

  if (Settings::Instance().form_factor() == FormFactor::DESKTOP)
  {
    geo.width += style.GetDashRightTileWidth();
    geo.height += style.GetDashBottomTileHeight();
  }

  if (!geo.IsPointInside(x, y))
  {
    ubus_manager_.SendMessage(UBUS_PLACE_VIEW_CLOSE_REQUEST);
  }
}

void DashView::OnActivateRequest(GVariant* args)
{
  glib::String uri;
  glib::String search_string;
  dash::HandledType handled_type;

  g_variant_get(args, "(sus)", &uri, &handled_type, &search_string);

  std::string id(AnalyseLensURI(uri.Str()));

  // we got an activation request, we should probably close the preview
  if (preview_displaying_)
  {
    ClosePreview();
  }

  if (!visible_)
  {
    lens_bar_->Activate(id);
    ubus_manager_.SendMessage(UBUS_DASH_EXTERNAL_ACTIVATION);
  }
  else if (/* visible_ && */ handled_type == NOT_HANDLED)
  {
    ubus_manager_.SendMessage(UBUS_PLACE_VIEW_CLOSE_REQUEST, NULL,
                              glib::Source::Priority::HIGH);
  }
  else if (/* visible_ && */ handled_type == GOTO_DASH_URI)
  {
    lens_bar_->Activate(id);
  }
}

std::string DashView::AnalyseLensURI(std::string const& uri)
{
  impl::LensFilter filter = impl::parse_lens_uri(uri);

  if (!filter.filters.empty())
  {
    lens_views_[filter.id]->filters_expanded = true;
    // update the lens for each filter
    for (auto p : filter.filters) {
      UpdateLensFilter(filter.id, p.first, p.second);
    }
  }

  return filter.id;
}

void DashView::UpdateLensFilter(std::string lens_id, std::string filter_name, std::string value)
{
  if (lenses_.GetLens(lens_id))
  {
    Lens::Ptr lens = lenses_.GetLens(lens_id);

    Filters::Ptr filters = lens->filters;

    for (unsigned int i = 0; i < filters->count(); ++i)
    {
      Filter::Ptr filter = filters->FilterAtIndex(i);

      if (filter->id() == filter_name)
      {
        UpdateLensFilterValue(filter, value);
      }
    }
  }
}

void DashView::UpdateLensFilterValue(Filter::Ptr filter, std::string value)
{
  if (filter->renderer_name == "filter-radiooption")
  {
    RadioOptionFilter::Ptr radio = std::static_pointer_cast<RadioOptionFilter>(filter);
    for (auto option: radio->options())
    {
      if (option->id == value)
        option->active = true;
    }
  }
}

void DashView::OnSearchChanged(std::string const& search_string)
{
  LOG_DEBUG(logger) << "Search changed: " << search_string;
  if (active_lens_view_)
  {
    search_in_progress_ = true;
    // it isn't guaranteed that we get a SearchFinished signal, so we need
    //                                         FIXME: it is now actually!!
    // to make sure this isn't set even though we aren't doing any search
    // 250ms for the Search method call, rest for the actual search
    searching_timeout_.reset(new glib::Timeout(500, [&] () {
      search_in_progress_ = false;
      activate_on_finish_ = false;
      return false;
    }));

    // 150ms to hide the no reults message if its take a while to return results
    hide_message_delay_.reset(new glib::Timeout(150, [&] () {
      active_lens_view_->HideResultsMessage();
      return false;
    }));
  }
}

void DashView::OnLiveSearchReached(std::string const& search_string)
{
  LOG_DEBUG(logger) << "Live search reached: " << search_string;
  if (active_lens_view_)
  {
    active_lens_view_->PerformSearch(search_string,
        sigc::mem_fun(this, &DashView::OnSearchFinished));
  }
}

void DashView::OnLensAdded(Lens::Ptr& lens)
{
  std::string id = lens->id;
  lens_bar_->AddLens(lens);

  LensView* view = new LensView(lens, search_bar_->show_filters());
  AddChild(view);
  view->SetVisible(false);
  view->uri_activated.connect(sigc::mem_fun(this, &DashView::OnUriActivated));

  lenses_layout_->AddView(view, 1);
  lens_views_[lens->id] = view;

  lens->activated.connect(sigc::mem_fun(this, &DashView::OnUriActivatedReply));
  lens->connected.changed.connect([&] (bool value)
  {
    std::string const& search_string = search_bar_->search_string;
    if (value && lens->search_in_global && active_lens_view_ == home_view_
        && !search_string.empty())
    {
      // force a (global!) search with the correct string
      lens->GlobalSearch(search_bar_->search_string,
        sigc::mem_fun(this, &DashView::OnSearchFinished));
    }
  });

  // Hook up to the new preview infrastructure
  lens->preview_ready.connect([&] (std::string const& uri, Preview::Ptr model)
  {
    LOG_DEBUG(logger) << "Got preview for: " << uri;
    preview_state_machine_.ActivatePreview(model); // this does not immediately display a preview - we now wait.
  });
}

void DashView::OnLensBarActivated(std::string const& id)
{
  if (lens_views_.find(id) == lens_views_.end())
  {
    LOG_WARN(logger) << "Unable to find Lens " << id;
    return;
  }

  LensView* view = active_lens_view_ = lens_views_[id];
  view->JumpToTop();

  for (auto it: lens_views_)
  {
    bool id_matches = it.first == id;
    ViewType view_type = id_matches ? LENS_VIEW : (view == home_view_ ? HOME_VIEW : HIDDEN);
    it.second->SetVisible(id_matches);
    it.second->view_type = view_type;

    LOG_DEBUG(logger) << "Setting ViewType " << view_type
                      << " on '" << it.first << "'";
  }

  search_bar_->SetVisible(true);
  QueueRelayout();
  search_bar_->search_string = view->search_string;
  search_bar_->search_hint = view->lens()->search_hint;
  // lenses typically return immediately from Search() if the search query
  // doesn't change, so SearchFinished will be called in a few ms
  // FIXME: if we're forcing a search here, why don't we get rid of view types?
  search_bar_->ForceSearchChanged();

  bool expanded = view->filters_expanded;
  search_bar_->showing_filters = expanded;

  nux::GetWindowCompositor().SetKeyFocusArea(default_focus());

  search_bar_->text_entry()->SelectAll();
  search_bar_->can_refine_search = view->can_refine_search();
  hide_message_delay_.reset();

  view->QueueDraw();
  QueueDraw();
}

void DashView::OnSearchFinished(Lens::Hints const& hints, glib::Error const& err)
{
  hide_message_delay_.reset();

  if (active_lens_view_ == NULL) return;

  // FIXME: bind the lens_view in PerformSearch
  active_lens_view_->CheckNoResults(hints);
  std::string const& search_string = search_bar_->search_string;

  if (active_lens_view_->search_string == search_string)
  {
    search_bar_->SearchFinished();
    search_in_progress_ = false;
    if (activate_on_finish_)
      this->OnEntryActivated();
  }
}

void DashView::OnGlobalSearchFinished(Lens::Hints const& hints, glib::Error const& error)
{
  if (active_lens_view_ == home_view_)
    OnSearchFinished(hints, error);
}

void DashView::OnAppsGlobalSearchFinished(Lens::Ptr const& lens)
{
  if (active_lens_view_ == home_view_ && lens->id() == "applications.lens")
  {
    /* HACKITY HACK! We're resetting the state of search_in_progress when
     * doing searches in the home lens and we get results from apps lens.
     * This way typing a search query and pressing enter immediately will
     * wait for the apps lens results and will run correct application.
     * See lp:966417 and lp:856206 for more info about why we do this.
     */
    search_in_progress_ = false;
    if (activate_on_finish_)
      this->OnEntryActivated();
  }
}

void DashView::OnUriActivatedReply(std::string const& uri, HandledType type, Lens::Hints const&)
{
  // We don't want to close the dash if there was another activation pending
  if (type == NOT_HANDLED)
  {
    if (!DoFallbackActivation(uri))
      return;
  }
  else if (type == SHOW_DASH)
  {
    return;
  }

  ubus_manager_.SendMessage(UBUS_PLACE_VIEW_CLOSE_REQUEST);
}

bool DashView::DoFallbackActivation(std::string const& fake_uri)
{
  size_t pos = fake_uri.find(":");
  std::string uri = fake_uri.substr(++pos);

  LOG_DEBUG(logger) << "Fallback activating " << uri;

  if (g_str_has_prefix(uri.c_str(), "application://"))
  {
    std::string appname = uri.substr(14);
    return LaunchApp(appname);
  }
  else if (g_str_has_prefix(uri.c_str(), "unity-runner://"))
  {
    std::string appname = uri.substr(15);
    return LaunchApp(appname);
  }
  else
    return gtk_show_uri(NULL, uri.c_str(), CurrentTime, NULL);

  return false;
}

bool DashView::LaunchApp(std::string const& appname)
{
  GDesktopAppInfo* info;
  bool ret = false;
  char *id = g_strdup(appname.c_str());
  int i = 0;

  LOG_DEBUG(logger) << "Launching " << appname;

  while (id != NULL)
  {
    info = g_desktop_app_info_new(id);
    if (info != NULL)
    {
      GError* error = NULL;

      g_app_info_launch(G_APP_INFO(info), NULL, NULL, &error);
      if (error)
      {
        g_warning("Unable to launch %s: %s", id,  error->message);
        g_error_free(error);
      }
      else
        ret = true;
      g_object_unref(info);
      break;
    }

    /* Try to replace the next - with a / and do the lookup again.
     * If we set id=NULL we'll exit the outer loop */
    for (i = 0; ; i++)
    {
      if (id[i] == '-')
      {
        id[i] = '/';
        break;
      }
      else if (id[i] == '\0')
      {
        g_free(id);
        id = NULL;
        break;
      }
    }
  }

  g_free(id);
  return ret;
}

void DashView::DisableBlur()
{
  renderer_.DisableBlur();
}
void DashView::OnEntryActivated()
{
  if (!search_in_progress_)
  {
    active_lens_view_->ActivateFirst();
  }
  // delay the activation until we get the SearchFinished signal
  activate_on_finish_ = search_in_progress_;
}

// Keyboard navigation
bool DashView::AcceptKeyNavFocus()
{
  return false;
}

std::string const DashView::GetIdForShortcutActivation(std::string const& shortcut) const
{
  Lens::Ptr lens = lenses_.GetLensForShortcut(shortcut);
  if (lens)
    return lens->id;
  return "";
}

std::vector<char> DashView::GetAllShortcuts()
{
  std::vector<char> result;

  for (Lens::Ptr lens: lenses_.GetLenses())
  {
    std::string shortcut = lens->shortcut;
    if(shortcut.size() > 0)
      result.push_back(shortcut.at(0));
  }
  return result;
}

bool DashView::InspectKeyEvent(unsigned int eventType,
                               unsigned int key_sym,
                               const char* character)
{
  if ((eventType == nux::NUX_KEYDOWN) && (key_sym == NUX_VK_ESCAPE))
  {
    if (preview_displaying_)
      ClosePreview();
    else if (search_bar_->search_string != "")
      search_bar_->search_string = "";
    else
      ubus_manager_.SendMessage(UBUS_PLACE_VIEW_CLOSE_REQUEST);

    return true;
  }
  return false;
}

nux::View* DashView::default_focus() const
{
  return search_bar_->text_entry();
}

// Introspectable
std::string DashView::GetName() const
{
  return "DashView";
}

void DashView::AddProperties(GVariantBuilder* builder)
{
  dash::Style& style = dash::Style::Instance();
  int num_rows = 1; // The search bar

  if (active_lens_view_)
    num_rows += active_lens_view_->GetNumRows();

  std::string form_factor("unknown");

  if (Settings::Instance().form_factor() == FormFactor::NETBOOK)
    form_factor = "netbook";
  else if (Settings::Instance().form_factor() == FormFactor::DESKTOP)
    form_factor = "desktop";
  else if (Settings::Instance().form_factor() == FormFactor::TV)
    form_factor = "tv";

  unity::variant::BuilderWrapper wrapper(builder);
  wrapper.add(nux::Geometry(GetAbsoluteX(), GetAbsoluteY(), content_geo_.width, content_geo_.height));
  wrapper.add("num_rows", num_rows);
  wrapper.add("form_factor", form_factor);
  wrapper.add("right-border-width", style.GetDashRightTileWidth());
  wrapper.add("bottom-border-height", style.GetDashBottomTileHeight());
  wrapper.add("preview_displaying", preview_displaying_);
}

nux::Area* DashView::KeyNavIteration(nux::KeyNavDirection direction)
{
  if (preview_displaying_)
  {
    return preview_container_->KeyNavIteration(direction);
  }
  else if (direction == nux::KEY_NAV_DOWN && search_bar_ && active_lens_view_)
  {
    auto show_filters = search_bar_->show_filters();
    auto fscroll_view = active_lens_view_->fscroll_view();

    if (show_filters && show_filters->HasKeyFocus())
    {
      if (fscroll_view->IsVisible() && fscroll_view)
        return fscroll_view->KeyNavIteration(direction);
      else
        return active_lens_view_->KeyNavIteration(direction);
    }
  }
  return this;
}

void DashView::ProcessDndEnter()
{
  ubus_manager_.SendMessage(UBUS_PLACE_VIEW_CLOSE_REQUEST);
}

nux::Area* DashView::FindKeyFocusArea(unsigned int key_symbol,
                                      unsigned long x11_key_code,
                                      unsigned long special_keys_state)
{
  // Only care about states of Alt, Ctrl, Super, Shift, not the lock keys
  special_keys_state &= (nux::NUX_STATE_ALT | nux::NUX_STATE_CTRL |
                         nux::NUX_STATE_SUPER | nux::NUX_STATE_SHIFT);

  // Do what nux::View does, but if the event isn't a key navigation,
  // designate the text entry to process it.

  using namespace nux;
  nux::KeyNavDirection direction = KEY_NAV_NONE;
  bool ctrl = (special_keys_state & NUX_STATE_CTRL);

  switch (x11_key_code)
  {
  case NUX_VK_UP:
    direction = KEY_NAV_UP;
    break;
  case NUX_VK_DOWN:
    direction = KEY_NAV_DOWN;
    break;
  case NUX_VK_LEFT:
    direction = KEY_NAV_LEFT;
    break;
  case NUX_VK_RIGHT:
    direction = KEY_NAV_RIGHT;
    break;
  case NUX_VK_LEFT_TAB:
  case NUX_VK_PAGE_UP:
    direction = KEY_NAV_TAB_PREVIOUS;
    break;
  case NUX_VK_TAB:
  case NUX_VK_PAGE_DOWN:
    direction = KEY_NAV_TAB_NEXT;
    break;
  case NUX_VK_ENTER:
  case NUX_KP_ENTER:
    // Not sure if Enter should be a navigation key
    direction = KEY_NAV_ENTER;
    break;
  case NUX_VK_F4:
    // Maybe we should not do it here, but it needs to be checked where
    // we are able to know if alt is pressed.
    if (special_keys_state == NUX_STATE_ALT)
    {
      ubus_manager_.SendMessage(UBUS_PLACE_VIEW_CLOSE_REQUEST);
    }
    break;
  default:
    direction = KEY_NAV_NONE;
  }

  if (preview_displaying_)
  {
    return preview_container_->FindKeyFocusArea(key_symbol, x11_key_code, special_keys_state);
  }

  // We should not do it here, but I really don't want to make DashView
  // focusable and I'm not able to know if ctrl is pressed in
  // DashView::KeyNavIteration.
   nux::InputArea* focus_area = nux::GetWindowCompositor().GetKeyFocusArea();

  if (direction != KEY_NAV_NONE && key_symbol == nux::NUX_KEYDOWN && !search_bar_->im_preedit)
  {
    std::list<nux::Area*> tabs;
    for (auto category : active_lens_view_->categories())
    {
      if (category->IsVisible())
        tabs.push_back(category);
    }

    if (search_bar_ && search_bar_->show_filters() &&
        search_bar_->show_filters()->IsVisible())
    {
      tabs.push_back(search_bar_->show_filters());
    }

    if (active_lens_view_->filter_bar() && active_lens_view_->fscroll_view() &&
        active_lens_view_->fscroll_view()->IsVisible())
    {
      for (auto child : active_lens_view_->filter_bar()->GetLayout()->GetChildren())
      {
        FilterExpanderLabel* filter = dynamic_cast<FilterExpanderLabel*>(child);
        if (filter)
          tabs.push_back(filter->expander_view());
      }
    }

    if (direction == KEY_NAV_TAB_PREVIOUS)
    {
      if (ctrl)
      {
        lens_bar_->ActivatePrevious();
      }
      else
      {
        auto rbegin = tabs.rbegin();
        auto rend = tabs.rend();

        bool use_the_prev = false;
        for (auto tab = rbegin; tab != rend; ++tab)
        {
          const auto& tab_ptr = *tab;

          if (use_the_prev)
            return tab_ptr;

          if (focus_area)
            use_the_prev = focus_area->IsChildOf(tab_ptr);
        }

        for (auto tab = rbegin; tab != rend; ++tab)
          return *tab;
      }
    }
    else if (direction == KEY_NAV_TAB_NEXT)
    {
      if (ctrl)
      {
        lens_bar_->ActivateNext();
      }
      else
      {
        bool use_the_next = false;
        for (auto tab : tabs)
        {
          if (use_the_next)
            return tab;

          if (focus_area)
            use_the_next = focus_area->IsChildOf(tab);
        }

        for (auto tab : tabs)
          return tab;
      }
    }
  }

  bool search_key = false;

  if (direction == KEY_NAV_NONE)
  {
    if (keyboard::is_printable_key_symbol(x11_key_code) ||
        keyboard::is_move_key_symbol(x11_key_code))
    {
      search_key = true;
    }
  }

  if (search_key || search_bar_->im_preedit)
  {
    // then send the event to the search entry
    return search_bar_->text_entry();
  }
  else if (next_object_to_key_focus_area_)
  {
    return next_object_to_key_focus_area_->FindKeyFocusArea(key_symbol, x11_key_code, special_keys_state);
  }

  return nullptr;
}

nux::Area* DashView::FindAreaUnderMouse(const nux::Point& mouse_position, nux::NuxEventType event_type)
{
  nux::Area* view = nullptr;
  if (preview_displaying_)
  {
    nux::Point newpos = mouse_position;
    view = dynamic_cast<nux::Area*>(preview_container_.GetPointer())->FindAreaUnderMouse(newpos, event_type);
  }
  else
  {
    view = View::FindAreaUnderMouse(mouse_position, event_type);
  }

  return (view == nullptr) ? this : view;
}

nux::Geometry const& DashView::GetContentGeometry() const
{
  return content_geo_;
}

}
}