~ubuntu-desktop/unity-lens-files/ubuntu

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
/*
 * 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>
 *
 */
using Dee;
using Zeitgeist;
using Zeitgeist.Timestamp;
using Config;
using Gee;

namespace Unity.FilesLens {
  
  const string ICON_PATH = Config.DATADIR + "/icons/unity-icon-theme/places/svg/";
  
  public class Daemon : GLib.Object
  {
    private Zeitgeist.Log log;
    private Zeitgeist.Index index;
    private Zeitgeist.Monitor monitor;

    private Bookmarks bookmarks;
    private UrlChecker urls;

    private Unity.Lens lens;
    private Unity.Scope scope;

    /* For each section we have a set of Zeitgeist.Event templates that
     * we use to query Zeitgeist */
    private HashTable<string, Event> type_templates;

    /* Keep track of the previous search, so we can determine when to
     * filter down the result set instead of rebuilding it */
    private LensSearch? previous_search;
    
    private bool is_dirty;
    
    construct
    {
      prepare_type_templates();

      scope = new Unity.Scope ("/com/canonical/unity/scope/files");
      scope.search_in_global = true;
      scope.activate_uri.connect (activate);

      lens = new Unity.Lens("/com/canonical/unity/lens/files", "files");
      lens.search_in_global = true;
      lens.search_hint = _("Search Files & Folders");
      lens.visible = true;
      populate_categories ();
      populate_filters();
      lens.add_local_scope (scope);
      
      previous_search = null;
      
      is_dirty = true;
      
      /* Bring up Zeitgeist interfaces */
      log = new Zeitgeist.Log();
      index = new Zeitgeist.Index();
      
      /* Listen for all file:// related events from Zeitgeist */
      var templates = new PtrArray();
      var event = new Zeitgeist.Event ();
      var subject = new Zeitgeist.Subject ();
      subject.set_uri ("file://*");
      event.add_subject (subject);
      templates.add (event.ref ());
      monitor = new Zeitgeist.Monitor (new Zeitgeist.TimeRange.from_now (),
                                       (owned) templates);
      monitor.events_inserted.connect (on_zeitgeist_changed);
      monitor.events_deleted.connect (on_zeitgeist_changed);
      log.install_monitor (monitor);
      
      bookmarks = new Bookmarks ();
      urls = new UrlChecker ();

      /* Listen for filter changes */
      scope.filters_changed.connect (
        () => {          
          if (scope.active_search != null)
            {
              is_dirty = true;
              scope.notify_property ("active-search");
            }
        }
      );

      /* Listen for changes to the lens entry search */
      scope.notify["active-search"].connect (
        (obj, pspec) => {
          var search = scope.active_search;
          
          if (!(Utils.search_has_really_changed (previous_search, search) || is_dirty))
            return;
          
          is_dirty = false;
          
          if (search_is_invalid (search))
            {
              update_without_search_async.begin(search);
            }
          else
            {
              update_search_async.begin (search);
             }
          previous_search = search;
        }
      );

      /* Listen for changes to the global search */
      scope.notify["active-global-search"].connect (
        (obj, pspec) => {

          var search = scope.active_global_search;
          
          if (search_is_invalid (search))
            return;
          
          if (!Utils.search_has_really_changed (previous_search, search))
            return;
          
          update_global_search_async.begin (search);
          previous_search = search;
        }
      );
     
      lens.export ();
    }

    private void populate_filters ()
    {
      Unity.Filter[] filters = {};

      /* Last modified */
      {
        var filter = new RadioOptionFilter ("modified", _("Last modified"));

        filter.add_option ("last-7-days", _("Last 7 days"));
        filter.add_option ("last-30-days", _("Last 30 days"));
        filter.add_option ("last-year", _("Last year"));

        filters += filter;
      }

      /* Type filter */
      {
        var filter = new RadioOptionFilter ("type", _("Type"));

        filter.add_option ("documents", _("Documents"));
        filter.add_option ("folders", _("Folders"));
        filter.add_option ("images", _("Images"));
        filter.add_option ("audio", _("Audio"));
        filter.add_option ("videos", _("Videos"));
        filter.add_option ("presentations", _("Presentations"));
        filter.add_option ("other", _("Other"));

        filters += filter;
      }

      /* Size filter */
      {
        var filter = new MultiRangeFilter ("size", _("Size"));

        filter.add_option ("1KB", _("1KB"));
        filter.add_option ("100KB", _("100KB"));
        filter.add_option ("1MB", _("1MB"));
        filter.add_option ("10MB", _("10MB"));
        filter.add_option ("100MB", _("100MB"));
        filter.add_option ("1GB", _("1GB"));
        filter.add_option (">1GB", _(">1GB"));

        filters += filter;
      }

      lens.filters = filters;
    }

    private void populate_categories ()
    {
      Unity.Category[] categories = {};

      var cat = new Unity.Category (_("Recent"), ICON_PATH + "category-recent.svg");
      categories += cat;

      cat =  new Unity.Category (_("Downloads"), ICON_PATH + "category-downloads.svg");
      categories += cat;

      cat = new Unity.Category (_("Folders"), ICON_PATH + "category-favoritefolders.svg");
      categories += cat;

      lens.categories = categories;
    }

    private void prepare_type_templates ()
    {
      type_templates = new HashTable<string, Event> (str_hash, str_equal);
      Event event;

      /* HACK ALERT: All the (event as GLib.Object).ref() are needed because
       *             GPtrArray doesn't grab a ref to the event objects */

      /* Section.ALL_FILES */
      event = new Event.full("", ZG_USER_ACTIVITY, "",
                             new Subject.full ("file:*",
                                               "", "", "", "", "", ""));
      type_templates.insert ("all", (event as GLib.Object).ref() as Event);
      
      /* Section.DOCUMENTS
       * FIXME: Filter out presentations: https://bugs.launchpad.net/zeitgeist/+bug/592599 */
      event = new Event.full("", ZG_USER_ACTIVITY, "",
                             new Subject.full ("file:*",
                                               NFO_DOCUMENT,
                                               "", "", "", "", ""));
      type_templates.insert ("documents", (event as GLib.Object).ref() as Event);

      /* Section.FOLDERS.
       * FIXME: We probably need to be clever here and use something
       *       like subject.origin in stead of NFO_FOLDERS */
      event = new Event.full("", ZG_USER_ACTIVITY, "",
                             new Subject.full ("file:*",
                                               "", "", "", "", "", ""));
      type_templates.insert ("folders", (event as GLib.Object).ref() as Event);

      /* Section.IMAGES */
      event = new Event.full("", ZG_USER_ACTIVITY, "",
                             new Subject.full ("file:*",
                                               NFO_IMAGE, "", "", "", "", ""));
      type_templates.insert ("images", (event as GLib.Object).ref() as Event);
      
      /* Section.AUDIO */
      event = new Event.full("", ZG_USER_ACTIVITY, "",
                             new Subject.full ("file:*",
                                               NFO_AUDIO, "", "", "", "", ""));
      type_templates.insert ("audio", (event as GLib.Object).ref() as Event);

      /* Section.VIDEOS */
      event = new Event.full("", ZG_USER_ACTIVITY, "",
                             new Subject.full ("file:*",
                                               NFO_VIDEO, "", "", "", "", ""));
      type_templates.insert ("videos", (event as GLib.Object).ref() as Event);

      /* Section.PRESENTATIONS
       * FIXME: Zeitgeist logger needs to user finer granularity
       *        on classification as I am not sure it uses
       *        NFO_PRESENTATION yet */
      event = new Event.full("", ZG_USER_ACTIVITY, "",
                             new Subject.full ("file:*",
                                               NFO_PRESENTATION, "", "", "", "", ""));
      type_templates.insert ("presentations", (event as GLib.Object).ref() as Event);

      /* Section.OTHER 
       * Note that subject templates are joined with logical AND */
      event = new Event.full("", ZG_USER_ACTIVITY, "");
      event.add_subject (new Subject.full ("file:*",
                                           "!"+NFO_DOCUMENT, "", "", "", "", ""));
      event.add_subject (new Subject.full ("",
                                           "!"+NFO_IMAGE,
                                           "",
                                           "", "", "", ""));
      event.add_subject (new Subject.full ("",
                                           "!"+NFO_AUDIO,
                                           "",
                                           "", "", "", ""));
      event.add_subject (new Subject.full ("",
                                           "!"+NFO_VIDEO,
                                           "",
                                           "", "", "", ""));
      event.add_subject (new Subject.full ("",
                                           "!"+NFO_PRESENTATION,
                                           "",
                                           "", "", "", ""));
      type_templates.insert ("other", (event as GLib.Object).ref() as Event);
    }

    private bool search_is_invalid (LensSearch? search)
    {
      /* This boolean expression is unfolded as we seem to get
       * some null dereference if we join them in a big || expression */
      if (search == null)
        return true;
      else if (search.search_string == null)
        return true;
      
      return search.search_string.strip() == "";
    }

    private string prepare_search_string (LensSearch? search)
    {
      var s = search.search_string;

      if (s.has_suffix (" "))
        s = s.strip ();

      if (!s.has_suffix ("*"))
        s = s + "*";

      /* The Xapian query parser (used by the Zeitgeist FTS Extension) seems to
       * handle hyphens in a special way, namely that it forces the joined
       * tokens into a phrase query no matter if it appears as the last word
       * in a query and we have the PARTIAL flag set on the query parser.
       * This makes 'unity-p' not match 'unity-package-search.cc' etc. */
      s = s.delimit ("-", ' ');

      return s;
    }
    
    private async void update_global_search_async (LensSearch search)
    {
      var results_model = scope.global_results_model;

      if (search_is_invalid (search))
        {
          results_model.clear ();
          return;
        }
      
      /* Prevent concurrent searches and concurrent updates of our models,
       * by preventing any notify signals from propagating to us.
       * Important: Remeber to thaw the notifys again! */
      scope.freeze_notify ();
      
      var search_string = prepare_search_string (search);

      var templates = new PtrArray.sized(1);
      templates.add (type_templates.lookup ("all"));

      try {
        /* Get results ranked by recency */
        var timer = new Timer ();
        var results = yield index.search (search_string,
                                          new Zeitgeist.TimeRange.anytime(),
                                          templates,
                                          Zeitgeist.StorageState.ANY,
                                          20,
                                          ResultType.MOST_RECENT_SUBJECTS,
                                          null);

        timer.stop ();
        debug ("Found %u/%u global results for search '%s' in %fms",
               results.size (), results.estimated_matches (),
               search_string, timer.elapsed()*1000);


        results_model.clear ();

        var checked_url = urls.check_url (search.search_string);
        if (checked_url != null)
          {
            results_model.append (checked_url, urls.icon, Categories.RECENT,
                                  "text/html", search.search_string,
                                  checked_url);
          }
        var bookmark_matches = bookmarks.prefix_search (search.search_string);
        append_bookmarks (bookmark_matches, results_model, Categories.FOLDERS);
        
        Unity.FilesLens.append_events_sorted (results, results_model);

      } catch (GLib.Error e) {
        warning ("Error performing global search '%s': %s",
                 search.search_string, e.message);
      }
      
      /* Allow new searches once we enter an idle again.
       * We don't do it directly from here as that could mean we start
       * changing the model even before we had flushed out current changes
       */
      Idle.add (() => {
        scope.thaw_notify ();
        return false;
      });
      
      search.finished ();
    }
    
    private async void update_search_async  (LensSearch search)
    {
      if (search_is_invalid (search))
        {
          update_without_search_async.begin (search);
          return;
        }

      var results_model = scope.results_model;

      /* Prevent concurrent searches and concurrent updates of our models,
       * by preventing any notify signals from propagating to us.
       * Important: Remeber to thaw the notifys again! */
      scope.freeze_notify ();
      
      var search_string = prepare_search_string (search);

      string type_id = get_current_type ();

      var result_type = type_id == "folder" ? ResultType.MOST_RECENT_ORIGIN
                                            : ResultType.MOST_RECENT_SUBJECTS;

      /* Grab the pre-compiled template we're going to use */
      var templates = new PtrArray.sized(1);
      templates.add (type_templates.lookup (type_id));


      try {
        /* Get results ranked by recency */
        var timer = new Timer ();
        var results = yield index.search (search_string,
                                          get_current_timerange (),
                                          templates,
                                          Zeitgeist.StorageState.ANY,
                                          50,
                                          result_type,
                                          null);

        timer.stop ();
        debug ("Found %u/%u results for search '%s' in %fms",
               results.size (), results.estimated_matches (),
               search_string, timer.elapsed()*1000);

        results_model.clear ();

        var checked_url = urls.check_url (search.search_string);
        if (checked_url != null)
          {
            results_model.append (checked_url, urls.icon, Categories.RECENT,
                                  "text/html", search.search_string,
                                  checked_url);
          }

        var bookmark_matches = bookmarks.prefix_search (search.search_string);
        append_bookmarks (bookmark_matches, results_model, Categories.FOLDERS);

        /* FIXME: Add downloads */
        
        Unity.FilesLens.append_events_sorted (results, results_model);

      } catch (GLib.Error e) {
        warning ("Error performing global search '%s': %s",
                 search.search_string, e.message);
      }
      
      /* Allow new searches once we enter an idle again.
       * We don't do it directly from here as that could mean we start
       * changing the model even before we had flushed out current changes
       */
      Idle.add (() => {
        scope.thaw_notify ();
        return false;
      });
      
      search.finished ();
    }

    private string get_current_type ()
    {
      /* Get the current type to filter by */
      var filter = scope.get_filter ("type") as RadioOptionFilter;
      Unity.FilterOption? option =  filter.get_active_option ();
      return option == null ? "all" : option.id;
    }

    private TimeRange get_current_timerange ()
    {
      var filter = scope.get_filter ("modified") as RadioOptionFilter;
      Unity.FilterOption? option = filter.get_active_option ();

      string date = option == null ? "all" : option.id;

      if (date == "last-7-days")
        return new TimeRange (Timestamp.now() - Timestamp.WEEK, Timestamp.now ());
      else if (date == "last-30-days")
        return new TimeRange (Timestamp.now() - (Timestamp.WEEK * 4), Timestamp.now());
      else if (date == "last-year")
        return new TimeRange (Timestamp.now() - Timestamp.YEAR, Timestamp.now ());
      else
        return new TimeRange.anytime ();
    }

    private async void update_without_search_async (LensSearch search)
    {
      var results_model = scope.results_model;

      /* Prevent concurrent searches and concurrent updates of our models,
       * by preventing any notify signals from propagating to us.
       * Important: Remeber to thaw the notifys again! */
      scope.freeze_notify ();
      
      string type_id = get_current_type ();

      var result_type = type_id == "folder" ? ResultType.MOST_RECENT_ORIGIN
                                            : ResultType.MOST_RECENT_SUBJECTS;

      /* Grab the pre-compiled template we're going to use */
      var templates = new PtrArray.sized(1);
      templates.add (type_templates.lookup (type_id));

      try {
        /* Get results ranked by recency */
        var timer = new Timer ();
        var results = yield log.find_events (get_current_timerange (),
                                             templates,
                                             Zeitgeist.StorageState.ANY,
                                             100,
                                             result_type,
                                             null);

        timer.stop ();
        debug ("Found %u/%u no search results in %fms",
               results.size (), results.estimated_matches (),
               timer.elapsed()*1000);

        results_model.clear ();

        if (type_id == "all" || type_id == "folder")
          append_bookmarks (bookmarks.list(), results_model);

        yield update_downloads_async (results_model);
       
        Unity.FilesLens.append_events_sorted (results, results_model);

      } catch (GLib.Error e) {
        warning ("Error performing empty search: %s",
                 e.message);
      }
      
      /* Allow new searches once we enter an idle again.
       * We don't do it directly from here as that could mean we start
       * changing the model even before we had flushed out current changes
       */
      Idle.add (() => {
        scope.thaw_notify ();
        return false;
      });
      
      search.finished ();
    }

    private void append_bookmarks (GLib.List<Bookmark> bookmarks,
                                   Dee.Model results_model,
                                   Categories category = Categories.FOLDERS)
    {
      foreach (var bookmark in bookmarks)
      {
        results_model.append (bookmark.uri, bookmark.icon, category,
                              bookmark.mimetype, bookmark.display_name,
                              bookmark.uri);
      }
    }

    private async void update_downloads_async (Dee.Model results_model)
    {
      // FIXME: Store the Downloads folder and update on changes
      unowned string download_path =
                 Environment.get_user_special_dir (UserDirectory.DOWNLOAD);
      var download_dir = File.new_for_path (download_path);
      SList<FileInfo> downloads;
      
      try {
        downloads = yield Utils.list_dir (download_dir);
      } catch (GLib.Error e) {
        warning ("Failed to list downloads from directory '%s': %s",
                 download_path, e.message);
        return;
      }
      
      /* Sort files by mtime, we do an ugly nested ternary
       * to avoid potential long/int overflow */
      downloads.sort ((CompareFunc) Utils.cmp_file_info_by_mtime);
      
      foreach (var info in downloads)
      {
        var uri = download_dir.get_child (info.get_name ()).get_uri ();
        var mimetype = info.get_content_type ();
        var icon_hint = Utils.check_icon_string (uri, mimetype, info);
        results_model.append (uri, icon_hint, Categories.DOWNLOADS,
                              mimetype, info.get_display_name (), uri);
      }
    }

    public Unity.ActivationResponse activate (string uri)
    {
      debug (@"Activating: $uri");
      try {
        AppInfo.launch_default_for_uri (uri, null);
        return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
      } catch (GLib.Error error) {
        warning ("Failed to launch URI %s", uri);
        return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
      }
    }

    private void on_zeitgeist_changed ()
    {
      /* Emitting notify here will make us recheck if the search results
       * need update. In the negative case this is a noop */
      is_dirty = true;
      scope.notify_property ("active-search");
    }
    
  }  

  /* Appends a set of Zeitgeist.Events to our Dee.Model assuming that
   * these events are already sorted with descending timestamps */
  public void append_events_sorted (Zeitgeist.ResultSet events,
                                    Dee.Model results)
  {
     foreach (var ev in events)
      {
        if (ev.num_subjects() > 0)
          {
            // FIXME: We only use the first subject...
            Zeitgeist.Subject su = ev.get_subject(0);
            
            string uri = su.get_uri ();
            string display_name = su.get_text ();
            string mimetype = su.get_mimetype () != null ?
                          su.get_mimetype () : "application/octet-stream";
            File file = File.new_for_uri (uri);
            
            /* Don't check existence on non-native files as http:// and
             * friends are *very* expensive to query */
            if (file.is_native()) {
              // hidden files should be ignored
              try {
                FileInfo info = file.query_info(FILE_ATTRIBUTE_STANDARD_IS_HIDDEN, 0, null);
                if (info.get_is_hidden())
                  continue;
              } catch (GLib.Error e) {
                // as error occurred file must be missing therefore ignoring it
                continue;
              }
            }
#if 0    
            if (section == Section.FOLDERS)
              {
                File dir = File.new_for_uri(uri).get_parent();
                uri = dir.get_uri ();
                try{
                  FileInfo info = dir.query_info (FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
                                                FileQueryInfoFlags.NONE);
                display_name = info.get_display_name ();
              } catch (GLib.Error e) {
                /* Bugger, we fall back to basename, which might not be
                 * valid UTF8... */
                warning ("Unable to get display name for %s", uri);
                display_name = dir.get_basename ();
              }
              mimetype = "inode/directory";
              }
#endif           
            string icon = Utils.get_icon_for_uri (uri, mimetype);
            
            uint category_id;
            string comment = "";
            
            category_id = file.query_file_type (0, null) == FileType.DIRECTORY ? Categories.FOLDERS
                                                                          : Categories.RECENT;
            results.append (uri, icon, category_id, mimetype,
                            display_name, comment);
            
          }          
      }
   }
} /* namespace */