~jamesh/unity-lens-applications/index-local-scopes

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
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
/*
 * 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 Mikkel Kamstrup Erlandsen <mikkel.kamstrup@canonical.com>
 *             Neil Jagdish Patel <neil.patel@canonical.com>
 *
 */
using Dee;
using Zeitgeist;
using Zeitgeist.Timestamp;
using Config;
using Gee;
using GMenu;

namespace Unity.ApplicationsLens {

  /* Number of 'Apps available for download' to show if no search query is provided AND a filter is active.
     It shouldn't be too high as this may impact lens performance.
   */
  const uint MAX_APP_FOR_DOWNLOAD_FOR_EMPTY_QUERY = 100;

  /* Number of top rated apps to show in 'Apps available for download' if no search query is provided AND NO filter is active. */
  const uint MAX_TOP_RATED_APPS_FOR_EMPTY_QUERY = 12;

  /* Number of "What's new" apps to show in 'Apps available for download' if no search query is provided AND NO filter is active. */
  const uint MAX_WHATS_NEW_APPS_FOR_EMPTY_QUERY = 10;

  /* Time between queries to SoftwareCenterDataProvider */
  const int64 TOP_RATED_ITEMS_CACHE_LIFETIME = 24*3600; // 24 hours

  const string ICON_PATH = Config.DATADIR + "/icons/unity-icon-theme/places/svg/";
  const string GENERIC_APP_ICON = "applications-other";
  const string GENERIC_SCOPE_ICON = ICON_PATH + "service-generic.svg";

  const string LIBUNITY_SCHEMA = "com.canonical.Unity.Lenses";

  public class Daemon : GLib.Object
  {
    private Variant empty_asv;
    private Zeitgeist.Log log;
    private Zeitgeist.Index zg_index;
    private Zeitgeist.Monitor monitor;

    private Map<string, int> popularity_map;
    private bool popularities_dirty;

    /* The searcher for online material may be null if it fails to load
     * the Xapian index from the Software Center */
    private Unity.Package.Searcher? pkgsearcher;
    private Unity.Package.Searcher? scopesearcher;
    public Unity.Package.Searcher appsearcher;

    /* Read the app ratings dumped by the Software Center */
    private bool ratings_db_initialized = false;
    private Unity.Ratings.Database? ratings = null;

    private Unity.DeprecatedScope scope;

    /* Support aptd dbus interface; created when application install/remove was requested by preview action */
    private AptdProxy aptdclient;
    private AptdTransactionProxy aptd_transaction;

    private SoftwareCenterUtils.MangledDesktopFileLookup sc_mangler;

    /* Used for adding launcher icon on app installation from the preview */
    private LauncherProxy launcherservice;

    /* Desktop file & icon name for unity-install:// install candidate displayed in last preview; we store
     * them here to avoid extra query for app details if app install action is activated */
    private string preview_installable_desktop_file;
    private string preview_installable_icon_file;

    private string preview_developer_website;

    /* SoftwareCenter data provider used for app preview details */
    private SoftwareCenterDataProviderProxy sc_data_provider;

    private Unity.ApplicationsLens.Runner runner;

    /* Keep references to the FilterOptions for sources */
    private FilterOption local_apps_option;
    private FilterOption usc_apps_option;

    private Gee.List<string> image_extensions;
    private HashTable<string,Icon> file_icon_cache;

    /* Monitor the favorite apps in the launcher, so we can filter them
     * out of the results for Recent Apps */
    private Unity.LauncherFavorites favorite_apps;
    private AppWatcher app_watcher;

    private PtrArray zg_templates;

    /* Gnome menu structure - also used to check whether apps are installed */
    private uint app_menu_changed_reindex_timeout = 0;
    private GMenu.Tree app_menu = null;

    private Regex? uri_regex;
    private Regex  mountable_regex;

    private Settings gp_settings;
    private HashTable<unowned string, unowned string> disabled_scope_ids;

    private const string DISPLAY_RECENT_APPS_KEY = "display-recent-apps";
    private const string DISPLAY_AVAILABLE_APPS_KEY = "display-available-apps";

    public bool display_recent_apps { get; set; default = true; }
    public bool display_available_apps { get; set; default = true; }
    public bool force_small_icons_for_suggestions { get; set; default = true; }

    private PurchaseInfoHelper purchase_info = null;
    private Dee.Model remote_scopes_model;
    private Dee.Index scopes_index;
    private Dee.Analyzer analyzer;

    construct
    {
      populate_zg_templates ();

      log = new Zeitgeist.Log();
      zg_index = new Zeitgeist.Index();
      empty_asv = new Variant.array (new VariantType ("{sv}"), {});
      monitor = new Zeitgeist.Monitor (new Zeitgeist.TimeRange.from_now (),
                                       zg_templates);
      monitor.events_inserted.connect (mark_dirty);
      monitor.events_deleted.connect (mark_dirty);
      log.install_monitor (monitor);

      popularity_map = new HashMap<string, int> ();
      popularities_dirty = true;
      // refresh the popularities every now and then
      Timeout.add_seconds (30 * 60, () =>
      {
        popularities_dirty = true;
        return true;
      });

      this.gp_settings = new Settings ("com.canonical.Unity.ApplicationsLens");
      this.gp_settings.bind(DISPLAY_RECENT_APPS_KEY, this, "display_recent_apps", SettingsBindFlags.GET);
      this.gp_settings.bind(DISPLAY_AVAILABLE_APPS_KEY, this, "display_available_apps", SettingsBindFlags.GET);

      pkgsearcher = new Unity.Package.Searcher ();
      if (pkgsearcher == null)
      {
        critical ("Failed to load Software Center index. 'Apps Available for Download' will not be listed");
      }

      /* Image file extensions in order of popularity */
      image_extensions = new Gee.ArrayList<string> ();
      image_extensions.add ("png");
      image_extensions.add ("xpm");
      image_extensions.add ("svg");
      image_extensions.add ("tiff");
      image_extensions.add ("ico");
      image_extensions.add ("tif");
      image_extensions.add ("jpg");

      build_app_menu_index ();
      build_scope_index.begin ();

      file_icon_cache = new HashTable<string,Icon>(str_hash, str_equal);
      sc_mangler = new SoftwareCenterUtils.MangledDesktopFileLookup ();

      scope = new Unity.DeprecatedScope ("/com/canonical/unity/scope/applications",
                               "applications");

      scope.search_hint = _("Search Applications");
      scope.search_in_global = true;
      // scope.sources_display_name = _("Sources");
      // TRANSLATORS: Please make sure this string is short enough to fit
      // into the filter button
      local_apps_option = scope.sources.add_option ("local", _("Local Apps"));
      if (display_available_apps)
      {
        // TRANSLATORS: Please make sure this string is short enough to fit
        // into the filter button
        usc_apps_option = scope.sources.add_option ("usc", _("Software Center"));
      }

      populate_categories ();
      populate_filters();
      //scope.icon = @"$(Config.PREFIX)/share/unity/themes/applications.png";

      scope.generate_search_key.connect ((lens_search) =>
      {
        return lens_search.search_string.strip ();
      });
      /* Listen for changes to the lens scope search */
      scope.search_changed.connect ((lens_search, search_type, cancellable) =>
      {
        dispatch_search.begin (lens_search, search_type, cancellable);
      });

      /* Re-do the search if the sources change */
      scope.active_sources_changed.connect (() =>
      {
        scope.queue_search_changed (SearchType.DEFAULT);
      });

      scope.activate_uri.connect (activate);
      scope.preview_uri.connect (preview);

      /* Listen for changes in the installed applications */
      AppInfoManager.get_default().changed.connect (mark_dirty);

      /* Now start the RunEntry */
      runner = new Unity.ApplicationsLens.Runner (this);

      try {
        uri_regex = new Regex ("^[a-z]+:.+$");
        mountable_regex = new Regex ("((ftp|ssh|sftp|smb|dav)://).+");
      } catch (RegexError e) {
        uri_regex = null;
        critical ("Failed to compile URI regex. URL launching will be disabled");
      }

      favorite_apps = Unity.LauncherFavorites.get_default ();
      favorite_apps.changed.connect(mark_dirty);

      app_watcher = new AppWatcher ();
      app_watcher.running_applications_changed.connect (mark_dirty);

      aptdclient = new AptdProxy ();
      launcherservice = new LauncherProxy ();

      scope.export ();

      remote_scopes_model = new Dee.SharedModel ("com.canonical.Unity.SmartScopes.RemoteScopesModel");
      remote_scopes_model.set_schema ("s", "s", "s", "s", "s", "as");

      scopes_index = Utils.prepare_index (remote_scopes_model,
                                          RemoteScopesColumn.NAME,
                                          (model, iter) =>
      {
        unowned string name = model.get_string (iter, RemoteScopesColumn.NAME);
        return "%s\n%s".printf (_("scope"), name);
      }, out analyzer);

      disabled_scope_ids = new HashTable<unowned string, unowned string> (str_hash, str_equal);
      update_disabled_scopes_hash ();

      var pref_man = PreferencesManager.get_default ();
      pref_man.notify["disabled-scopes"].connect (update_disabled_scopes_hash);
    }

    private void update_disabled_scopes_hash ()
    {
      disabled_scope_ids.remove_all ();
      var pref_man = PreferencesManager.get_default ();
      foreach (unowned string scope_id in pref_man.disabled_scopes)
      {
        // using HashTable as a set (optimized in glib when done like this)
        disabled_scope_ids[scope_id] = scope_id;
      }
    }

    private void init_ratings_db ()
    {
      if (ratings_db_initialized) return;
      try
      {
        ratings = new Unity.Ratings.Database ();
      }
      catch (FileError e)
      {
        warning ("%s", e.message);
        ratings = null;
      }
      ratings_db_initialized = true;
    }

    private async void dispatch_search (DeprecatedScopeSearch search,
                                        SearchType search_type,
                                        GLib.Cancellable cancellable)
    {
      if (popularities_dirty)
      {
        popularities_dirty = false;
        // we're not passing the cancellable, cause cancelling this search
        // shouldn't cancel getting most popular apps
        yield update_popularities ();
        if (cancellable.is_cancelled ()) return;
      }

      if (search_type == SearchType.DEFAULT)
        yield update_scope_search (search, cancellable);
      else
        yield update_global_search (search, cancellable);

      search.finished ();
    }

    private void populate_categories ()
    {
      Unity.CategorySet categories = new Unity.CategorySet ();
      File icon_dir = File.new_for_path (ICON_PATH);

      var cat = new Unity.Category ("apps", _("Applications"),
                                    new FileIcon (icon_dir.get_child ("group-apps.svg")));
      categories.add (cat);

      cat = new Unity.Category ("recently-used", _("Recently Used"),
                                new FileIcon (icon_dir.get_child ("group-recent.svg")));
      categories.add (cat);

      cat = new Unity.Category ("recent", _("Recent Apps"),
                                new FileIcon (icon_dir.get_child ("group-apps.svg")));
      categories.add (cat);

      cat = new Unity.Category ("installed", _("Installed"),
                                new FileIcon (icon_dir.get_child ("group-installed.svg")));
      categories.add (cat);

      cat = new Unity.Category ("more", _("More suggestions"),
                                new FileIcon (icon_dir.get_child ("group-treat-yourself.svg")),
                                Unity.CategoryRenderer.FLOW);
      categories.add (cat);

      scope.categories = categories;
    }

    private void populate_filters()
    {
      Unity.FilterSet filters = new Unity.FilterSet ();

      /* Type filter */
      {
        var filter = new CheckOptionFilter ("type", _("Type"));
        filter.sort_type = Unity.OptionsFilter.SortType.DISPLAY_NAME;

        filter.add_option ("accessories", _("Accessories"));
        filter.add_option ("education", _("Education"));
        filter.add_option ("game", _("Games"));
        filter.add_option ("graphics", _("Graphics"));
        filter.add_option ("internet", _("Internet"));
        filter.add_option ("fonts", _("Fonts"));
        filter.add_option ("office", _("Office"));
        filter.add_option ("media", _("Media"));
        filter.add_option ("customization", _("Customization"));
        filter.add_option ("accessibility", _("Accessibility"));
        filter.add_option ("developer", _("Developer"));
        filter.add_option ("science-and-engineering", _("Science & Engineering"));
        filter.add_option ("scopes", _("Search plugins"));
        filter.add_option ("system", _("System"));

        filters.add (filter);
      }

      scope.filters = filters;
    }

    private bool local_apps_active (DeprecatedScopeSearch search)
    {
      var filter = search.get_filter (scope.sources.id) as Unity.OptionsFilter;
      if (filter.filtering && local_apps_option != null)
        return filter.get_option (local_apps_option.id).active;
      return true;
    }

    private bool usc_apps_active (DeprecatedScopeSearch search)
    {
      var filter = search.get_filter (scope.sources.id) as Unity.OptionsFilter;
      if (filter.filtering && usc_apps_option != null)
        return filter.get_option (usc_apps_option.id).active;
      return true;
    }

    /* Load xdg menu info and build a Xapian index over it.
     * Do throttled re-index if the menu changes */
    private bool build_app_menu_index ()
    {
      if (app_menu == null)
      {
        debug ("Building initial application menu");

        /* We need INCLUDE_NODISPLAY to employ proper de-duping between
         * the Installed and Availabale categorys. If a NoDisplay app is installed,
         * eg. Evince, it wont otherwise be in the menu index, only in the
         * S-C index - thus show up in the Available category */
        app_menu = new GMenu.Tree ("unity-lens-applications.menu",
                                        GMenu.TreeFlags.INCLUDE_NODISPLAY);

        app_menu.changed.connect (() => {
            /* Reschedule the timeout if we already have one. The menu tree triggers
             * many change events during app installation. This way we wait the full
             * delay *after* the last change event has triggered */
            if (app_menu_changed_reindex_timeout != 0)
            {
              Source.remove (app_menu_changed_reindex_timeout);
            }

            app_menu_changed_reindex_timeout = Timeout.add_seconds (5, build_app_menu_index_and_result_models);
          });
      }

      // gnome menu tree needs to be loaded on startup and after receiving 'changed' signal - see gmenu-tree.c in gnome-menus-3.6.0.
      try
      {
        app_menu.load_sync (); //FIXME: libgnome-menu doesn't provide async method (yet?)
      }
      catch (GLib.Error e)
      {
        warning ("Failed to load menu entries: %s", e.message);
      }

      debug ("Indexing application menu");
      appsearcher = new Unity.Package.Searcher.for_menu (app_menu);
      app_menu_changed_reindex_timeout = 0;

      return false;
    }

    /* Called when our app_menu structure changes - probably because something
     * has been installed or removed. We reload gnome menu tree,
     * rebuild the index and update the result models for global and scope.
     * We need to update both because
     * we can't know exactly what Unity may be showing */
    private bool build_app_menu_index_and_result_models ()
    {
      build_app_menu_index ();

      mark_dirty ();

      return false;
    }

    private async void build_scope_index ()
    {
      var scope_registry = yield Unity.Protocol.ScopeRegistry.find_scopes (
        Config.PKGDATADIR + "/scopes");

      debug ("Indexing scopes");
      scopesearcher = new Unity.Package.Searcher.for_scopes (scope_registry);
    }

    private void populate_zg_templates ()
    {
      /* Create a template that activation of applications */
      zg_templates = new PtrArray.sized(1);
      var ev = new Zeitgeist.Event.full (ZG_ACCESS_EVENT, ZG_USER_ACTIVITY, "",
                             new Subject.full ("application*",
                                               "", //NFO_SOFTWARE,
                                               "",
                                               "", "", "", ""));
      zg_templates.add ((ev as GLib.Object).ref());
    }

    private void mark_dirty ()
    {
      scope.queue_search_changed (SearchType.DEFAULT);
      scope.queue_search_changed (SearchType.GLOBAL);
    }

    private async void update_popularities ()
    {
      try
      {
        // simulate a kind of frecency
        var end_ts = Timestamp.now ();
        var start_ts = end_ts - Timestamp.WEEK * 3;
        var rs = yield log.find_events (new TimeRange (start_ts, end_ts),
                                        zg_templates,
                                        StorageState.ANY,
                                        256,
                                        Zeitgeist.ResultType.MOST_POPULAR_SUBJECTS,
                                        null);

        // most popular apps must have high value, so unknown apps (where
        // popularity_map[app] == 0 aren't considered super popular
        int relevancy = 256;
        foreach (unowned Event event in rs)
        {
          for (int i = 0; i < event.num_subjects (); i++)
          {
            unowned string uri = event.get_subject (i).get_uri ();
            if (uri == null) continue;
            popularity_map[uri] = relevancy;
          }
          relevancy--;
        }
      }
      catch (GLib.Error err)
      {
        warning ("%s", err.message);
      }
    }

    /* Returns TRUE if application is NOT installed */
    public bool filter_cb (Unity.Package.PackageInfo pkginfo)
    {
      var appmanager = AppInfoManager.get_default();
      AppInfo? app = appmanager.lookup (pkginfo.desktop_file);
      return app == null;
    }

    private async void update_scope_search (DeprecatedScopeSearch search,
                                            GLib.Cancellable cancellable)
    {
      var model = search.results_model;
      /* We'll clear the model once we finish waiting for the dbus-call
       * to finish, to prevent flicker. */

      var search_string = search.search_string.strip ();
      debug ("Searching for: %s", search_string);

      var type_filter = search.get_filter ("type") as OptionsFilter;

      string pkg_search_string = XapianUtils.prepare_pkg_search_string (search_string, type_filter);

      bool has_filter = (type_filter != null && type_filter.filtering);
      bool has_search = !Utils.is_search_empty (search_string);

      Timer timer = new Timer ();

      var transaction = new Dee.Transaction (model);
      transaction.clear ();

      /* Even though the Installed apps search is super fast, we wait here
       * for the Most Popular search to finish, because otherwise we'll update
       * the Installed category too soon and this will cause flicker
       * in the Dash. (lp:868192) */

      Set<string> installed_uris = new HashSet<string> ();
      Set<string> available_uris = new HashSet<string> ();
      var appresults = appsearcher.search (pkg_search_string, 0,
                                           Unity.Package.SearchType.PREFIX,
                                           has_search ?
                                              Unity.Package.Sort.BY_RELEVANCY :
                                              Unity.Package.Sort.BY_NAME);
      if (local_apps_active (search))
      {
        if (has_search) resort_pkg_search_results (appresults);
        add_pkg_search_result (appresults, installed_uris, available_uris,
                               transaction, Category.INSTALLED);
      }

      timer.stop ();
      debug ("Entry search listed %i Installed apps in %fms for query: %s",
             appresults.num_hits, timer.elapsed ()*1000, pkg_search_string);

      if (local_apps_active (search) && display_recent_apps)
      {
        try
        {
          timer.start ();
          /* Ignore the search string, we want to keep displaying the same apps
           * in the recent category and just filter out those that don't match
           * the search query */
          var zg_search_string = XapianUtils.prepare_zg_search_string ("", type_filter);

          var results = yield zg_index.search (zg_search_string,
                                               new Zeitgeist.TimeRange.anytime(),
                                               zg_templates,
                                               0,
                                               20,
                                               Zeitgeist.ResultType.MOST_RECENT_SUBJECTS,
                                               cancellable);

          append_events_with_category (results, transaction, Category.RECENT,
                                       false, 6, installed_uris);

          timer.stop ();
          debug ("Entry search found %u/%u Recently Used apps in %fms for query '%s'",
                 results.size (), results.estimated_matches (),
                 timer.elapsed()*1000, zg_search_string);

        } catch (IOError.CANCELLED ioe) {
          // no need to bother
          return;
        } catch (GLib.Error e) {
          warning ("Error performing search '%s': %s", search_string, e.message);
        }
      }

      transaction.commit ();

      // add scopes (if filter is active)
      if (!has_filter || type_filter.get_option ("scopes").active)
      {
        add_local_scopes_results (search_string, model, installed_uris);
        add_remote_scopes_results (search_string, model);
      }

      purchase_info = new PurchaseInfoHelper ();

      /* If we don't have a search we display 6 random apps */
      if (usc_apps_active (search) && display_available_apps && pkgsearcher != null)
      {
        if (has_search)
        {
          timer.start ();
          var pkgresults = pkgsearcher.search (pkg_search_string, 50,
                                               Unity.Package.SearchType.PREFIX,
                                               Unity.Package.Sort.BY_RELEVANCY);
          add_pkg_search_result (pkgresults, installed_uris, available_uris,
                                 model, Category.AVAILABLE);
          timer.stop ();
          debug ("Entry search listed %i Available apps in %fms for query: %s",
                 pkgresults.num_hits, timer.elapsed ()*1000, pkg_search_string);
        }
        else if (has_filter) /* Empty search string + active filters should get lots of results from selected categories */
        {
          timer.start ();
          string? filter_query = XapianUtils.prepare_pkg_search_string (search_string, type_filter);

          var pkgresults = pkgsearcher.get_apps (filter_query, MAX_APP_FOR_DOWNLOAD_FOR_EMPTY_QUERY, filter_cb);
          purchase_info.from_pkgresults (pkgresults);
          add_pkg_search_result (pkgresults, installed_uris, available_uris, model, Category.AVAILABLE, MAX_APP_FOR_DOWNLOAD_FOR_EMPTY_QUERY);
          timer.stop ();
          debug ("Entry search listed %i Available apps in %fms",
                 pkgresults.num_hits, timer.elapsed ()*1000);
        }
        else
        {
          timer.start ();

          uint hits = 0;
          try
          {
            Set<string> duplicates_lookup = new HashSet<string> ();

            if (sc_data_provider == null)
              sc_data_provider = new SoftwareCenterDataCache (TOP_RATED_ITEMS_CACHE_LIFETIME);

            var whats_new = sc_data_provider.get_items_for_category ("unity-whats-new");
            var query = purchase_info.create_pkgsearch_query (whats_new);
            var tmpresults = pkgsearcher.get_by_exact_names (query);
            purchase_info.from_pkgresults (tmpresults);
            hits = add_sc_category_results (whats_new, model, Category.AVAILABLE, ref duplicates_lookup, MAX_WHATS_NEW_APPS_FOR_EMPTY_QUERY);

            var top_rated = sc_data_provider.get_items_for_category ("unity-top-rated");
            query = purchase_info.create_pkgsearch_query (top_rated);
            tmpresults = pkgsearcher.get_by_exact_names (query);
            purchase_info.from_pkgresults (tmpresults);
            hits += add_sc_category_results (top_rated, model, Category.AVAILABLE, ref duplicates_lookup, MAX_TOP_RATED_APPS_FOR_EMPTY_QUERY);
          }
          catch (GLib.Error e)
          {
            warning ("Failed to get top rated apps: %s", e.message);
          }

          timer.stop ();
          debug ("Entry search listed %u top rated/new available apps in %fms",
                 hits, timer.elapsed ()*1000);
        }
      }

      if (model.get_n_rows () == 0)
      {
        search.set_reply_hint ("no-results-hint",
          _("Sorry, there are no applications that match your search."));
      }
    }

    private async void update_global_search (DeprecatedScopeSearch search,
                                             GLib.Cancellable cancellable)
    {
      /*
       * In global search, with a non-empty search string, we collate all
       * hits under one Applications category
       */
      var search_string = search.search_string.strip ();

      if (Utils.is_search_empty (search_string))
      {
        yield update_global_without_search (search, cancellable);
        return;
      }

      var model = search.results_model;

      model.clear ();

      var pkg_search_string = XapianUtils.prepare_pkg_search_string (search_string, null);
      Set<string> installed_uris = new HashSet<string> ();
      Set<string> available_uris = new HashSet<string> ();
      var timer = new Timer ();
      var appresults = appsearcher.search (pkg_search_string, 0,
                                           Unity.Package.SearchType.PREFIX,
                                           Unity.Package.Sort.BY_RELEVANCY);
      resort_pkg_search_results (appresults);
      add_pkg_search_result (appresults, installed_uris, available_uris, model,
                             Category.APPLICATIONS);

      timer.stop ();
      debug ("Global search listed %i Installed apps in %fms for query: %s",
             appresults.num_hits, timer.elapsed ()*1000, pkg_search_string);
    }

    private async void update_global_without_search (DeprecatedScopeSearch search,
                                                     GLib.Cancellable cancellable)
    {
      /*
       * In global search, with an empty search string, we show just Recent Apps
       * Excluding apps with icons in the launcher (be they running or faves)
       */
      var model = search.results_model;

      Timer timer = new Timer ();

      if (local_apps_active (search) && display_recent_apps)
      {
        try
        {
          var zg_search_string = XapianUtils.prepare_zg_search_string ("",
                                                                       null);

          var time_range = new Zeitgeist.TimeRange.anytime ();
          var results = yield log.find_events (time_range,
                                               zg_templates,
                                               Zeitgeist.StorageState.ANY,
                                               40,
                                               Zeitgeist.ResultType.MOST_RECENT_SUBJECTS,
                                               cancellable);

          model.clear ();
          append_events_with_category (results, model, Category.RECENT_APPS,
                                       false);

          timer.stop ();
          debug ("Entry search found %u/%u Recently Used apps in %fms for query '%s'",
                 results.size (), results.estimated_matches (),
                 timer.elapsed()*1000, zg_search_string);

        } catch (IOError.CANCELLED ioe) {
          // no need to bother
          return;
        } catch (GLib.Error e) {
          warning ("Error performing search '%s': %s",
                   search.search_string, e.message);
        }
      }
    }

    public Icon find_pkg_icon (string? desktop_file, string icon_name)
    {
      if (desktop_file != null)
      {
        string desktop_id = Path.get_basename (desktop_file);
        bool installed = AppInfoManager.get_default().lookup (desktop_id) != null;

        /* If the app is already installed we should be able to pull the
         * icon from the theme */
        if (installed)
          return new ThemedIcon (icon_name);
      }

      /* App is not installed - we need to find the right icon in the bowels
       * of the software center */
      if (icon_name.has_prefix ("/"))
      {
        return new FileIcon (File.new_for_path (icon_name));
      }
      else
      {
        Icon icon = file_icon_cache.lookup (icon_name);

        if (icon != null)
          return icon;

        /* If the icon name contains a . it probably already have a
         * type postfix - so test icon name directly */
        string path;
        if ("." in icon_name)
        {
          path = @"$(Config.DATADIR)/app-install/icons/$(icon_name)";
          if (FileUtils.test (path, FileTest.EXISTS))
          {
            icon = new FileIcon (File.new_for_path (path));
            file_icon_cache.insert (icon_name, icon);
            return icon;
          }
          /* Try also software center cache dir */
          path = Path.build_filename (Environment.get_user_cache_dir (),
                                      "software-center",
                                      "icons",
                                      icon_name);
          if (FileUtils.test (path, FileTest.EXISTS))
          {
            icon = new FileIcon (File.new_for_path (path));
            file_icon_cache.insert (icon_name, icon);
            return icon;
          }
        }

        /* Now try appending all the image extensions we know */
        foreach (var ext in image_extensions)
        {
          path = @"$(Config.DATADIR)/app-install/icons/$(icon_name).$(ext)";
          if (FileUtils.test (path, FileTest.EXISTS))
          {
            /* Got it! Cache the icon path and return the icon */
            icon = new FileIcon (File.new_for_path (path));
            file_icon_cache.insert (icon_name, icon);
            return icon;
          }
        }
      }

      /* Cache the fact that we couldn't find this icon */
      var icon = new ThemedIcon (GENERIC_APP_ICON);
      file_icon_cache.insert (icon_name, icon);

      return icon;
    }

    /*
     * Performs secondary level sorting of the results according to popularity
     * of individual desktop files.
     */
    private void resort_pkg_search_results (Unity.Package.SearchResult results)
    {
      results.results.sort_with_data ((a, b) =>
      {
        /* We'll cluster the relevancies into a couple of bins, because
         * there can be multiple terms adding to the relevancy (especially
         * when doing one/two character prefix searches - ie a "f*" search
         * will have slightly higher relevancy for item with name "Search
         * _f_or _f_iles" than "_F_irefox", and that's not what we want)
         */
        int rel_a = a.relevancy;
        int rel_b = b.relevancy;
        int delta = (rel_a - rel_b).abs ();
        if (delta < 10)
        {
          string id_a = sc_mangler.extract_desktop_id (a.desktop_file);
          string id_b = sc_mangler.extract_desktop_id (b.desktop_file);
          rel_a = popularity_map["application://" + id_a];
          rel_b = popularity_map["application://" + id_b];
        }
        return rel_b - rel_a; // we want higher relevancy first
      });
    }

    /**
     * Sanitize executable name -- make it suitable for Home Lens.
     */
    private static string sanitize_binary_name (string name)
    {
      return GLib.Path.get_basename (name);
    }

    private string get_annotated_icon (Icon app_icon, string price, bool paid,
                                       bool use_small_icon = true)
    {
      var annotated_icon = new AnnotatedIcon (app_icon);
      annotated_icon.category = CategoryType.APPLICATION;
      if (price != null && price != "")
      {
        if (paid)
          annotated_icon.ribbon = _("Paid");
        else
          annotated_icon.ribbon = price;
      }
      else
      {
        annotated_icon.ribbon = _("Free");
      }
      if (force_small_icons_for_suggestions || use_small_icon
          || app_icon.to_string () == GENERIC_APP_ICON)
      {
        annotated_icon.size_hint = IconSizeHint.SMALL;
      }

      return annotated_icon.to_string ();
    }

    /**
     * Add all results obtained from SoftwareCenterDataProvider
     */
    private uint add_sc_category_results (SoftwareCenterData.AppInfo?[] results,
                                          Dee.Model model,
                                          Category category,
                                          ref Set<string> duplicates_lookup,
                                          uint max_results)
    {
      uint i = 0;
      foreach (SoftwareCenterData.AppInfo app in results)
      {
        string uri = @"unity-install://$(app.package_name)/$(app.application_name)";
        if (uri in duplicates_lookup)
          continue;

        string icon_obj;
        Icon app_icon = find_pkg_icon (app.desktop_file, app.icon);
        var pinfo = purchase_info.find (app.application_name, app.package_name);
        if (pinfo != null)
        {
          // magazines need to use large icons
          bool use_small_icon = app.desktop_file.has_suffix (".desktop");
          var annotated_icon = get_annotated_icon (app_icon,
                                                   pinfo.formatted_price,
                                                   pinfo.paid,
                                                   use_small_icon);
          icon_obj = annotated_icon.to_string ();
        }
        else
        {
          warning ("No purchase info for: %s, %s", app.application_name, app.package_name);
          icon_obj = app_icon.to_string ();
        }

        model.append (uri, icon_obj,
                      category,
                      Unity.ResultType.PERSONAL,
                      "application/x-desktop",
                      app.application_name,
                      "", //comment
                      "file://" + app.desktop_file,
                      empty_asv);
        duplicates_lookup.add (uri);
        i++;
        if (i == max_results)
          break;
      }
      return i;
    }

    private void add_pkg_search_result (Unity.Package.SearchResult results,
                                        Set<string> installed_uris,
                                        Set<string> available_uris,
                                        Dee.Model model,
                                        Category category,
                                        uint max_add=0)
    {
      var appmanager = AppInfoManager.get_default();
      uint n_added = 0;

      foreach (unowned Unity.Package.PackageInfo pkginfo in results.results)
      {
        if (pkginfo.desktop_file == null)
          continue;

        string desktop_id = sc_mangler.extract_desktop_id (pkginfo.desktop_file,
                                                category == Category.AVAILABLE);
        string full_path;

        AppInfo? app = appmanager.lookup (desktop_id);
        full_path = appmanager.get_path (desktop_id);

        /* De-dupe by 'application://foo.desktop' URI. Also note that we need
         * to de-dupe before we chuck out NoDisplay app infos, otherwise they'd
         * show up from alternate sources */
        string uri = @"application://$(desktop_id)";
        if (uri in installed_uris || uri in available_uris)
          continue;

        /* Extract basic metadata and register de-dupe keys */
        string display_name;
        string comment;
        switch (category)
        {
          case Category.INSTALLED:
          case Category.APPLICATIONS:
            installed_uris.add (uri);
            display_name = app.get_display_name ();
            comment = sanitize_binary_name (app.get_executable ());
            break;
          case Category.AVAILABLE:
            available_uris.add (uri);
            display_name = pkginfo.application_name;
            comment = "";
            break;
          default:
            warning (@"Illegal category for package search $(category)");
            continue;
        }

        /* We can only chuck out NoDisplay and OnlyShowIn app infos after
         * we have registered a de-dupe key for them - which is done in the
         * switch block above) */
        if (app != null && !app.should_show ())
          continue;

        Icon icon = find_pkg_icon (pkginfo.desktop_file, pkginfo.icon);
        string icon_str;
        if (category == Category.AVAILABLE)
        {
          /* If we have an available item, which is not a dupe, but is
           * installed anyway, we weed it out here, because it's probably
           * left out from the Installed section because of some rule in the
           * .menu file */
          if (app != null)
            continue;

          /* Apps that are not installed, ie. in the Available category
           * use the 'unity-install://pkgname/Full App Name' URI scheme,
           * but only use that after we've de-duped the results.
           * But only change the URI *after* we've de-duped the results! */
          uri = @"unity-install://$(pkginfo.package_name)/$(pkginfo.application_name)";
          available_uris.add (uri);

          // magazines need to use large icons
          bool use_small_icon = pkginfo.desktop_file.has_suffix (".desktop");
          icon_str = get_annotated_icon (icon, pkginfo.price,
                                         !pkginfo.needs_purchase,
                                         use_small_icon);
        }
        else
        {
          icon_str = icon.to_string ();
        }

        var result_type = category == Category.INSTALLED ?
          Unity.ResultType.PERSONAL : Unity.ResultType.DEFAULT;
        model.append (uri, icon_str,
                      category,
                      result_type,
                      "application/x-desktop",
                      display_name != null ? display_name : "",
                      comment != null ? comment : "",
                      full_path != null ? "file://" + full_path : "",
                      empty_asv);

        /* Stop if we added the number of items requested */
        n_added++;
        if (max_add > 0 && n_added >= max_add)
          return;
      }
    }

    private static Icon? get_default_scope_icon ()
    {
      try
      {
        return Icon.new_for_string (GENERIC_SCOPE_ICON);
      }
      catch (Error err)
      {
        warning ("%s", err.message);
      }
      return null;
    }

    private void add_local_scopes_results (string search_string,
                                           Dee.Model model,
                                           Set<string> installed_uris)
    {
      // If the local scopes Xapian index hasn't been built, return.
      if (scopesearcher == null)
        return;

      bool has_search = !Utils.is_search_empty (search_string);

      var results = scopesearcher.search (search_string, 0,
                                          Unity.Package.SearchType.PREFIX,
                                          has_search ?
                                            Unity.Package.Sort.BY_RELEVANCY :
                                            Unity.Package.Sort.BY_NAME);

      foreach (unowned Unity.Package.PackageInfo info in results.results) {
        /* De-dupe by "application://foo.scope", since that is what is
         * used for software-center results. */
        string dedup_key = @"application://$(info.desktop_file)";
        if (dedup_key in installed_uris)
          continue;
        installed_uris.add(dedup_key);

        var uri = @"scope://$(info.desktop_file)";
        var name = info.application_name;
        var icon_hint = info.icon;

        try
        {
          Icon base_icon = icon_hint == null || icon_hint == "" ?
            get_default_scope_icon () : Icon.new_for_string (icon_hint);
          var anno_icon = new AnnotatedIcon (base_icon);
          anno_icon.size_hint = IconSizeHint.SMALL;
          icon_hint = anno_icon.to_string ();
        }
        catch (Error err)
        {
          icon_hint = "";
        }

        model.append (uri,
                      icon_hint,
                      Category.AVAILABLE,
                      ResultType.DEFAULT,
                      "application/x-unity-scope",
                      name != "" ? name : uri,
                      "",
                      "", // dnd_uri ?!
                      empty_asv);
      }
    }

    private void add_remote_scopes_results (string search_string,
                                            Dee.Model model)
    {
      var results = Utils.search_index (scopes_index, analyzer, search_string);
      foreach (var iter in results)
      {
        unowned string scope_id =
          remote_scopes_model.get_string (iter, RemoteScopesColumn.SCOPE_ID);
        var uri = "scope://%s".printf (scope_id);
        var name =
          remote_scopes_model.get_string (iter, RemoteScopesColumn.NAME);
        var icon_hint = 
          remote_scopes_model.get_string (iter, RemoteScopesColumn.ICON_HINT);

        try
        {
          Icon base_icon = icon_hint == null || icon_hint == "" ?
            get_default_scope_icon () : Icon.new_for_string (icon_hint);
          var anno_icon = new AnnotatedIcon (base_icon);
          anno_icon.size_hint = IconSizeHint.SMALL;
          icon_hint = anno_icon.to_string ();
        }
        catch (Error err)
        {
          icon_hint = "";
        }

        var category = scope_id in disabled_scope_ids ?
          Category.AVAILABLE : Category.INSTALLED;

        model.append (uri,
                      icon_hint,
                      category,
                      ResultType.DEFAULT,
                      "application/x-unity-scope",
                      name != "" ? name : uri,
                      "",
                      "", // dnd_uri ?!
                      empty_asv);
      }
    }
    private async void call_install_packages (string package_name, out string tid) throws IOError
    {
      tid = yield aptdclient.install_packages ({package_name});
    }

    private async void call_remove_packages (string package_name, out string tid) throws IOError
    {
      tid = yield aptdclient.remove_packages ({package_name});
    }

    /**
     * Handler for free apps installation.
     * Triggers package installation via apt-daemon DBus service
     */
    private Unity.ActivationResponse app_preview_install (string uri)
    {
      if (uri.has_prefix ("unity-install://"))
      {
        string app = uri.substring (16); // trim "unity-install://"
        string[] parts = app.split ("/");

        if (parts.length > 1)
        {
          string pkgname = parts[0];
          string appname = parts[1];
          try
          {
            aptdclient.connect_to_aptd ();
          }
          catch (IOError e)
          {
            warning ("Failed to connect to aptd: '%s'", e.message);
            return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
          }
          call_install_packages.begin (pkgname, (obj, res) =>
          {
            try {
              string tid;
              call_install_packages.end (res, out tid);
              debug ("transaction started: %s, pkg: %s\n", tid, pkgname);
              aptd_transaction = new AptdTransactionProxy ();
              aptd_transaction.connect_to_aptd (tid);
              aptd_transaction.simulate ();
              aptd_transaction.run ();

              launcherservice.connect_to_launcher ();
              string desktop_file = preview_installable_desktop_file;
              Icon icon = find_pkg_icon (null, preview_installable_icon_file);
              launcherservice.add_launcher_item_from_position (appname, icon.to_string (), 0, 0, 32, desktop_file, tid);
            }
            catch (IOError e)
            {
              warning ("Package '%s' installation failed: %s", pkgname, e.message);
            }
          });
        }
        else
        {
          warning ("Bad install uri: '%s'", uri);
        }
      }
      else
      {
        warning ("Can't handle '%s' in app_preview_install handler", uri);
        return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
      }
      return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
    }

    private Unity.ActivationResponse start_software_center (string uri)
    {
      unowned string pkg = uri.offset (16); // strip off "unity-install://" prefix
      debug ("Installing: %s", pkg);

      var args = new string[2];
      args[0] = "software-center";
      args[1] = pkg;

      try
      {
        Process.spawn_async (GLib.Environment.get_home_dir (), args, null, SpawnFlags.SEARCH_PATH, null, null);
      }
      catch (SpawnError e)
      {
        warning ("Failed to spawn software-center for uri '%s': %s", uri, e.message);
        return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
      }

      return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
    }

    private Unity.ActivationResponse app_preview_website (string uri)
    {
      try
      {
        AppInfo.launch_default_for_uri (preview_developer_website, null);
        return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
      }
      catch (Error e)
      {
        warning ("Failed to launch a web browser for uri '%s': '%s'", uri, e.message);
      }
      return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
    }

    private Unity.ActivationResponse app_preview_uninstall (string uri)
    {
      if (uri.has_prefix ("application://"))
      {
        string desktopfile = uri.substring (14); // trim "application://"

        // de-mangle desktop file names back to what S-C expects
        if (sc_mangler.contains (desktopfile))
        {
          desktopfile = sc_mangler.get (desktopfile);
        }

        var pkginfo = pkgsearcher.get_by_desktop_file (desktopfile);

        if (pkginfo != null && pkginfo.package_name != null)
        {
          try
          {
            aptdclient.connect_to_aptd ();
          }
          catch (IOError e)
          {
            warning ("Failed to connect to aptd: '%s'", e.message);
            return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
          }

          call_remove_packages.begin (pkginfo.package_name, (obj, res) =>
          {
            try {
              string tid;
              call_remove_packages.end (res, out tid);
              debug ("transaction started: %s, pkg: %s\n", tid, pkginfo.package_name);
              aptd_transaction = new AptdTransactionProxy ();
              aptd_transaction.connect_to_aptd (tid);
              aptd_transaction.simulate ();
              aptd_transaction.run ();
            }
            catch (IOError e)
            {
              warning (@"Package '$(pkginfo.package_name)' removal failed: $(e.message)");
            }
          });
          return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
        }
        else
        {
          warning (@"Cannot find package info for $uri");
        }
      }
      warning (@"Can't handle '%s' in app_preview_uninstall handler", uri);
      return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
    }

    public Unity.Preview preview (string uri)
    {
      Unity.ApplicationPreview? preview = null;

      string pkgname = "";
      string appname = "";
      bool installed = uri.has_prefix ("application://");
      bool is_scope = uri.has_prefix ("scope://");

      if (installed || uri.has_prefix ("unity-install://"))
      {
        string desktopfile = null;
        if (installed)
        {
          desktopfile = uri.substring (14); //remove "application://" prefix

          // de-mangle desktop file names back to what S-C expects
          if (sc_mangler.contains (desktopfile))
          {
            desktopfile = sc_mangler.get (desktopfile);
          }

          Unity.Package.PackageInfo pkginfo = pkgsearcher.get_by_desktop_file (desktopfile);
          if (pkginfo != null)
          {
            appname = pkginfo.application_name;
            pkgname = pkginfo.package_name;
          }
        }
        else // unity-install
        {
          string app = uri.substring (16); //remove "unity-install://" prefix
          string[] parts = app.split ("/");
          if (parts.length > 1)
          {
            pkgname = parts[0];
            appname = parts[1];
          }
        }

        if (pkgname != "")
        {
          try {
            if (sc_data_provider == null)
            {
              sc_data_provider = new SoftwareCenterDataCache (TOP_RATED_ITEMS_CACHE_LIFETIME);
              sc_data_provider.connect_to ();
            }

            debug ("Requesting pkg info: %s, %s\n", pkgname, appname);
            var details = sc_data_provider.get_app_details (appname, pkgname);

            Icon? icon = null;
            if (installed)
              icon = new GLib.ThemedIcon (details.icon);
            else
            {
              icon = find_pkg_icon (null, details.icon);
              if (icon.to_string () == GENERIC_APP_ICON && details.icon_url != null && details.icon_url != "")
              {
                icon = new GLib.FileIcon (File.new_for_uri (details.icon_url));
              }
            }

            Icon? screenshot = null;

            if (details.screenshot != null)
            {
              File scr_file = File.new_for_uri (details.screenshot);
              screenshot = new FileIcon (scr_file);
            }

            string subtitle = "";
            if (details.version != "")
              subtitle = _("Version %s").printf (details.version);
            if (details.size > 0)
            {
              if (subtitle != "")
                subtitle += ", ";
              subtitle += ("Size %s").printf (GLib.format_size (details.size));
            }
            preview = new Unity.ApplicationPreview (details.name, subtitle, details.description, icon, screenshot);
            preview.license = details.license;

            init_ratings_db ();
            if (ratings != null)
            {
              Unity.Ratings.Result result;
              ratings.query (pkgname, out result);
              preview.set_rating (result.average_rating / 5.0f, result.total_rating);
            }

            if (details.hardware_requirements != "")
              preview.add_info (new InfoHint ("hardware-requirements", _("Hardware requirements"), null, details.hardware_requirements));

            if (uri.has_prefix ("unity-install://")) // application needs to be purchased/installed
            {
              // uninstalled and not purchased before
              if (details.pkg_state == SoftwareCenterData.PackageState.NEEDS_PURCHASE)
              {
                var buy_action = new Unity.PreviewAction ("buy", _("Buy"), null);
                if (details.price != null && details.price != "")
                {
                  buy_action.extra_text = details.price;
                }

                buy_action.activated.connect (start_software_center);
                preview.add_action (buy_action);
              }
              else // uninstalled, purchased before
              {

                Unity.PreviewAction install_action = null;
                if (details.raw_price == null || details.raw_price == "")
                {
                  install_action = new Unity.PreviewAction ("install", _("Free Download"), null);
                  install_action.activated.connect (app_preview_install);
                }
                else
                {
                  install_action = new Unity.PreviewAction ("install", _("Install"), null);
                  install_action.activated.connect (start_software_center);
                }
                preview.add_action (install_action);
              }

              if (details.website != null && details.website != "")
              {
                preview_developer_website = details.website;
                var website_action = new Unity.PreviewAction ("website", _("Developer Site"), null);
                website_action.activated.connect (app_preview_website);
                preview.add_action (website_action);
              }
            }
            else // application is already installed
            {
              preview.add_info (new InfoHint ("date-installed", _("Installed on"), null, details.installation_date));
              var launch_action = new Unity.PreviewAction ("launch", _("Launch"), null);
              preview.add_action (launch_action);
              if (!details.is_desktop_dependency)
              {
                var uninstall_action = new Unity.PreviewAction ("uninstall", _("Uninstall"), null);
                uninstall_action.activated.connect (app_preview_uninstall);
                preview.add_action (uninstall_action);
              }
            }

            preview_installable_desktop_file = details.desktop_file;
            preview_installable_icon_file = details.icon;
          }
          catch (Error e)
          {
            warning ("Failed to get package details for '%s': %s", uri, e.message);
            preview = null;
          }
        }

        // xapian db doesn't know this .desktop file or S-C dbus data provider fails,
        // fallback to DesktopAppInfo (based on installed .desktop file) if available
        if (preview == null && desktopfile != null)
        {
          var app_info = new DesktopAppInfo (desktopfile);
          if (app_info != null)
          {
            preview = new Unity.ApplicationPreview (app_info.get_display_name (), "", app_info.get_description () ?? "", app_info.get_icon (), null);
            var launch_action = new Unity.PreviewAction ("launch", _("Launch"), null);
            preview.add_action (launch_action);
          }
        }

        if (preview == null)
        {
          warning ("No pksearcher nor desktop app info for '%s'", uri);
        }
      }
      else if (is_scope)
      {
        var scope_id = uri.substring (8);
        bool scope_disabled = scope_id in disabled_scope_ids;

        // figure out if the scope is remote
        bool is_remote_scope = false;
        var info = scopesearcher.get_by_desktop_file (scope_id);

        Dee.ModelIter found_iter = null;
        if (info == null)
        {
          var iter = remote_scopes_model.get_first_iter ();
          var end_iter = remote_scopes_model.get_last_iter ();
          while (iter != end_iter)
          {
            if (remote_scopes_model.get_string (iter, 0) == scope_id)
            {
              is_remote_scope = true;
              found_iter = iter;
              break;
            }
            iter = remote_scopes_model.next (iter);
          }
        }

        if (is_remote_scope)
        {
          var name = remote_scopes_model.get_string (found_iter, 1);
          if (name == null || name == "")
            name = remote_scopes_model.get_string (found_iter, 0);
          var description = remote_scopes_model.get_string (found_iter, 2);
          Icon? icon = null;
          Icon? screenshot = null;
          var icon_hint = remote_scopes_model.get_string (found_iter, 3);
          var screenshot_url = remote_scopes_model.get_string (found_iter, 4);
          try
          {
            if (icon_hint != "") icon = Icon.new_for_string (icon_hint);
            if (screenshot_url != "") screenshot = Icon.new_for_string (screenshot_url);
          }
          catch (Error err)
          {
            warning ("%s", err.message);
          }

          if (icon == null) icon = get_default_scope_icon ();

          preview = new Unity.ApplicationPreview (name,
                                                  "",
                                                  description,
                                                  icon,
                                                  screenshot);
        }
        else if (info != null)
        {
          var name = info.application_name;
          if (name == null || name == "")
            name = info.desktop_file;
          // XXX: add this to package info.
          var description = "";
          Icon? icon = null;
          try
          {
            if (info.icon != null && info.icon != "")
              icon = Icon.new_for_string (info.icon);
          }
          catch (Error err)
          {
            warning ("%s", err.message);
          }
          if (icon == null)
            icon = get_default_scope_icon ();

          preview = new Unity.ApplicationPreview (name,
                                                  "",
                                                  description,
                                                  icon,
                                                  null);
        }
        if (preview != null) {
          PreviewAction action;
          if (scope_disabled)
          {
            action = new Unity.PreviewAction ("enable-scope", _("Enable"), null);
            action.activated.connect (() =>
            {
              enable_scope (scope_id);
              return new ActivationResponse.with_preview (this.preview (uri));
            });
          }
          else
          {
            action = new Unity.PreviewAction ("disable-scope", _("Disable"), null);
            action.activated.connect (() =>
            {
              disable_scope (scope_id);
              return new ActivationResponse.with_preview (this.preview (uri));
            });
          }
          preview.add_action (action);
        }
      }
      return preview;
    }

    private void disable_scope (string scope_id)
    {
      if (scope_id in disabled_scope_ids) return;

      var pref_man = PreferencesManager.get_default ();
      var disabled_scopes = pref_man.disabled_scopes;
      disabled_scopes += scope_id;

      var settings = new Settings (LIBUNITY_SCHEMA);
      settings.set_strv ("disabled-scopes", disabled_scopes);
    }

    private void enable_scope (string scope_id)
    {
      if (!(scope_id in disabled_scope_ids)) return;

      var pref_man = PreferencesManager.get_default ();
      string[] disabled_scopes = {};
      foreach (unowned string disabled_scope_id in pref_man.disabled_scopes)
      {
        if (disabled_scope_id != scope_id)
          disabled_scopes += disabled_scope_id;
      }

      var settings = new Settings (LIBUNITY_SCHEMA);
      settings.set_strv ("disabled-scopes", disabled_scopes);
    }
    /**
     * Override of the default activation handler. The apps lens daemon
     * can handle activation of installable apps using the Software Center
     */
    public Unity.ActivationResponse activate (string uri)
    {
      string[] args;
      string exec_or_dir = null;
      if (uri.has_prefix ("unity-install://") || uri.has_prefix ("scope://"))
      {
        var prv = preview (uri);
        if (prv != null)
        {
          return new Unity.ActivationResponse.with_preview (prv);
        }
        else
        {
          warning ("Failed to generate preview for %s", uri);
          return new Unity.ActivationResponse (Unity.HandledType.NOT_HANDLED);
        }
      }
      else if (uri.has_prefix ("unity-runner://"))
      {
        string orig;
        orig = uri.offset (15);
        if (orig.has_prefix("\\\\"))
          orig = orig.replace ("\\\\","smb://");
        if (uri_regex != null && uri_regex.match (orig)) {
          try {
            /* this code ensures that a file manager will be used
             * if uri it's a remote location that should be mounted */
            if (mountable_regex.match (orig)) {
              var muris = new GLib.List<string>();
              muris.prepend (orig);
              var file_manager = AppInfo.get_default_for_type("inode/directory", true);
              file_manager.launch_uris(muris,null);
            } else {
              AppInfo.launch_default_for_uri (orig, null);
            }
          } catch (GLib.Error error) {
            warning ("Failed to launch URI %s", orig);
            return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
          }
          return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);

        } else {
          exec_or_dir = Utils.subst_tilde (orig);
          args = exec_or_dir.split (" ", 0);
          for (int i = 0; i < args.length; i++)
            args[i] = Utils.subst_tilde (args[i]);
        }
        this.runner.add_history (orig);
      }
      else
      {
        /* Activation of standard application:// uris */

        /* Make sure fresh install learns quickly */
        if (popularity_map.size <= 5) popularities_dirty = true;

        return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
      }

      if ((exec_or_dir != null) && FileUtils.test (exec_or_dir, FileTest.IS_DIR))
      {
        try {
          AppInfo.launch_default_for_uri ("file://" + exec_or_dir, null);
        } catch (GLib.Error err) {
          warning ("Failed to open current folder '%s' in file manager: %s",
                   exec_or_dir, err.message);
          return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
        }
      }
      else
      {
        try {
          unowned string home_dir = GLib.Environment.get_home_dir ();
          Process.spawn_async (home_dir, args, null, SpawnFlags.SEARCH_PATH, null, null);
        } catch (SpawnError e) {
          warning ("Failed to spawn software-center or direct URI activation '%s': %s",
                   uri, e.message);
          return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
        }
      }

      return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);

    }

    /* Appends the subject URIs from a set of Zeitgeist.Events to our Dee.Model
     * assuming that these events are already sorted */
    public void append_events_with_category (Zeitgeist.ResultSet events,
                                             Dee.Model results,
                                             uint category_id,
                                             bool include_favorites,
                                             int max_results = int.MAX,
                                             Set<string>? allowed_uris = null)
    {
      int num_results = 0;
      foreach (var ev in events)
      {
        string? app_uri = null;
        if (ev.num_subjects () > 0)
          app_uri = ev.get_subject (0).get_uri ();

        if (app_uri == null)
        {
          warning ("Unexpected event without subject");
          continue;
        }

        /* Assert that we indeed have a known application as actor */
        string desktop_id = Utils.get_desktop_id_for_actor (app_uri);

        /* Discard Recently Used apps that are in the launcher */
        if ((category_id == Category.RECENT ||
             category_id == Category.RECENT_APPS) &&
            !include_favorites &&
            (favorite_apps.has_app_id (desktop_id)
            || app_watcher.has_app_id (desktop_id)))
          continue;

        var appmanager = AppInfoManager.get_default ();
        AppInfo? app = appmanager.lookup (desktop_id);

        if (app == null)
          continue;

        if (!app.should_show ())
          continue;

        /* HACK! when using the max_results together with allowed_uris,
         * the limit serves as a truncation point - therefore results which
         * are not displayed the first time won't be displayed later
         * (consider results A, B, C - all of them are allowed and we use
         *  limit 2 - so only A and B is displayed, later we change allowed to
         *  B and C, so normally we would display both B and C, but that's not
         *  desired because C wasn't shown in the first place, so we display
         *  only B) */
        if (num_results++ >= max_results) break;

        if (allowed_uris != null && !(app_uri in allowed_uris)) continue;

        string full_path = appmanager.get_path (desktop_id);
        string full_uri = full_path != null ? "file://" + full_path : app_uri;

        results.append (app_uri, app.get_icon().to_string(),
                        category_id, Unity.ResultType.DEFAULT,
                        "application/x-desktop", app.get_display_name (),
                        sanitize_binary_name (app.get_executable ()),
                        full_uri,
                        empty_asv);
      }
    }

  } /* END: class Daemon */

} /* namespace */