~kees/libunity/remote-search-none

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
/*
 * Copyright (C) 2011 Canonical, Ltd.
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License
 * version 3.0 as published by the Free Software Foundation.
 *
 * This library 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 Lesser General Public License version 3.0 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Authored by Neil Jagdish Patel <neil.patel@canonical.com>
 *
 */

using GLib;
using Dee;
using Unity.Protocol;

namespace Unity {

/*
 * The private implementation of the Scope. This makes sure that none of the 
 * implementation details leak out into the public interface.
 */
private class ScopeImpl : GLib.Object, ScopeService
{
  public Scope owner { private get; construct; }
  private uint _dbus_id;
  private uint _info_changed_id;
  private uint _filters_changed_id;
  private HashTable<string, PreviewAction> _action_map;
  private Preview? _last_preview;

  public Dee.SerializableModel _results_model;
  public Dee.SerializableModel _global_results_model;
  public Dee.SerializableModel _filters_model;

  /* we need notifications on this property */
  public ViewType view_type { get; set; }

  public ScopeImpl (Scope owner)
  {
    Object (owner: owner);
  }

  construct
  {
    owner.notify["search-in-global"].connect (queue_info_changed);
    owner.notify["visible"].connect (queue_info_changed);
    owner.notify["provides-personal-content"].connect (queue_info_changed);
    owner.sources.changed.connect (queue_info_changed);

    _action_map = new HashTable<string, PreviewAction> (str_hash, str_equal);
    create_models ();
  }
  
  /* Create usable name prefix for the models */
  private string create_dbus_name ()
  {
    /* We randomize the names to avoid conflicts to ensure that we always
     * have a clean start (no processes hanging around that would cause our models
     * to not be the leaders)
     */
    uint t = (uint)time_t ();
    var dbus_path = owner.dbus_path;
    var dbus_name = "com.canonical.Unity.Scope";
    dbus_name += "." + Path.get_basename (dbus_path);
    dbus_name += ".T%u".printf (t);
    return dbus_name;
  }

  private void create_models ()
  {
    /* Schema definitions come from the Lens specification */
    _results_model = new Dee.SequenceModel ();
    _results_model.set_schema ("s", "s", "u", "s", "s", "s", "s");

    _global_results_model = new Dee.SequenceModel ();
    _global_results_model.set_schema ("s", "s", "u", "s", "s", "s", "s");

    _filters_model = new Dee.SequenceModel ();
    _filters_model.set_schema ("s", "s", "s", "s", "a{sv}", "b", "b", "b");
    _filters_model.row_added.connect (on_filter_added);
    _filters_model.row_changed.connect (on_filter_changed);
    _filters_model.row_removed.connect (on_filter_removed);
  }

  private void create_shared_models (string dbus_name)
  {
    var backend = _results_model;
    _results_model = new Dee.SharedModel.with_back_end (
        dbus_name + ".Results", backend);

    backend = _global_results_model;
    _global_results_model = new Dee.SharedModel.with_back_end (
        dbus_name + ".GlobalResults", backend);

    backend = _filters_model;
    backend.row_added.disconnect (on_filter_added);
    backend.row_changed.disconnect (on_filter_changed);
    backend.row_removed.disconnect (on_filter_removed);
    _filters_model = new Dee.SharedModel.with_back_end (
        dbus_name + ".Filters", backend);
    _filters_model.row_added.connect (on_filter_added);
    _filters_model.row_changed.connect (on_filter_changed);
    _filters_model.row_removed.connect (on_filter_removed);
  }

  public void export () throws IOError
  {
    create_shared_models (create_dbus_name ());
    var conn = Bus.get_sync (BusType.SESSION);
    _dbus_id = conn.register_object (owner.dbus_path, this as ScopeService);

    queue_info_changed ();
  }

  /* Queue up info-changed requests as we don't want to be spamming Unity with
   * them.
   */
  private void queue_info_changed ()
  {
    if (_info_changed_id == 0)
    {
      _info_changed_id = Idle.add (emit_info_changed);
    }
  }

  private void queue_filters_changed ()
  {
    if (_filters_changed_id == 0)
    {
      _filters_changed_id = Timeout.add(0, emit_filters_changed);
    }
  }

  private bool emit_filters_changed ()
  {
    owner.filters_changed ();
    _filters_changed_id = 0;

    return false;
  }

  private string get_model_name (Dee.SerializableModel model)
  {
    if (model is Dee.SharedModel)
    {
      var shared_model = model as Dee.SharedModel;
      return shared_model.get_swarm_name ();
    }
    else
      return "<local>";
  }

  private bool emit_info_changed ()
  {
    var info = ScopeInfo ();
    info.dbus_path = owner.dbus_path;
    info.sources = owner.sources.get_hints ();
    info.search_in_global = owner.search_in_global;
    info.private_connection_name = "<not implemented>";
    info.results_model_name = get_model_name (_results_model);
    info.global_results_model_name = get_model_name (_global_results_model);
    info.filters_model_name = get_model_name (_filters_model);
    info.hints = new HashTable<string, Variant> (str_hash, str_equal);
    info.hints.insert ("provides-personal-content", new GLib.Variant.boolean (owner.provides_personal_content));

    changed (info);

    _info_changed_id = 0;
    return false;
  }

  private void on_filter_added (Dee.Model model, Dee.ModelIter iter)
  {
    if (model.get_string (iter, FilterColumn.ID) == Lens.SOURCES_FILTER_ID)
    {
      /* just make sure we directly update the properties on scope.sources
       * filter, the options are handled separately */
      owner.sources.filtering = model.get_bool (iter, FilterColumn.FILTERING);
      return;
    }

    string icon_hint_s = model.get_string (iter, FilterColumn.ICON_HINT);

    Icon? icon_hint = null;
    try
      {
        if (icon_hint_s != "")
          icon_hint = Icon.new_for_string (icon_hint_s);
      }
    catch (Error e)
      {
        warning ("Error parsing GIcon data '%s': %s", icon_hint_s, e.message);
      }
    
    Filter? filter = null;
    FilterRenderer renderer = Filter.renderer_for_name (
        model.get_string (iter, FilterColumn.RENDERER_NAME));

    switch (renderer)
    {
      case FilterRenderer.RATINGS:
        filter = new RatingsFilter (model.get_string (iter, FilterColumn.ID),
                                    model.get_string (iter, FilterColumn.NAME),
                                    icon_hint);
        break;
      case FilterRenderer.RADIO_OPTIONS:
        filter = new RadioOptionFilter (model.get_string (iter, FilterColumn.ID),
                                        model.get_string (iter, FilterColumn.NAME),
                                        icon_hint);
        break;
      case FilterRenderer.CHECK_OPTIONS:
        filter = new CheckOptionFilter (model.get_string (iter, FilterColumn.ID),
                                        model.get_string (iter, FilterColumn.NAME),
                                        icon_hint);
        break;
      case FilterRenderer.CHECK_OPTIONS_COMPACT:
        filter = new CheckOptionFilterCompact (model.get_string (iter, FilterColumn.ID),
                                               model.get_string (iter, FilterColumn.NAME),
                                               icon_hint);
        break;
      case FilterRenderer.MULTIRANGE:
        filter = new MultiRangeFilter (model.get_string (iter, FilterColumn.ID),
                                       model.get_string (iter, FilterColumn.NAME),
                                       icon_hint);
        break;
    }

    if (filter is Filter)
    {
      filter.set_model_and_iter (model, iter);
      owner._filters.append (filter);

      queue_filters_changed ();
    }
  }

  private void on_filter_changed (Dee.Model model, Dee.ModelIter iter)
  {
    if (model.get_string (iter, FilterColumn.ID) == Lens.SOURCES_FILTER_ID)
    {
      /* just make sure we directly update the properties on scope.sources
       * filter, the options are handled separately */
      owner.sources.filtering = model.get_bool (iter, FilterColumn.FILTERING);
      return;
    }

    queue_filters_changed ();
  }

  private void on_filter_removed (Dee.Model model, Dee.ModelIter iter)
  {
    bool dirty = false;

    foreach (Filter filter in owner._filters)
    {
      if (filter.id == model.get_string (iter, FilterColumn.ID))
      {
        dirty = true;
        owner._filters.remove (filter);
        break;
      }
    }

    if (dirty) queue_filters_changed ();
  }


  /*
   * DBus Interface Implementation
   */
  public async void info_request ()
  {
    queue_info_changed ();
  }

  public async ActivationReplyRaw activate (string uri,
                                            uint action_type,
                                            HashTable<string, Variant> hints) throws IOError
  {
    var reply = ActivationReplyRaw ();
    ActivationResponse? response = null;
    Preview? preview = null;
    string? stripped_uri = null;

    ActionType action = (ActionType) action_type;
    switch (action)
    {
      case ActionType.ACTIVATE_RESULT:
        response = owner.activate_uri (uri);
        break;
      case ActionType.PREVIEW_RESULT:
        preview = preview_internal (uri);
        break;
      case ActionType.PREVIEW_ACTION:
        string[] tokens = uri.split (":", 2);
        stripped_uri = tokens[1];
        response = activate_action (tokens[0], stripped_uri, hints);
        break;
      case ActionType.PREVIEW_BUILTIN_ACTION:
        // TODO: implement
        break;
      default:
        warning ("Unknown activation ActionType: %u", action_type);
        break;
    }

    if (response != null && response.handled == HandledType.SHOW_PREVIEW)
    {
      if (response.get_preview () == null)
      {
        // recurse to emit preview-uri if ActivationResponse was created
        // without a preview
        var new_uri = response.goto_uri;
        if (new_uri == null || new_uri[0] == '\0')
          new_uri = stripped_uri ?? uri;
        reply = yield activate (new_uri, ActionType.PREVIEW_RESULT, hints);
        return reply;
      }
    }

    if (preview != null)
    {
      // handle AsyncPreview properly
      var async_preview = preview as AsyncPreview;
      if (async_preview != null)
      {
        preview = yield async_preview.wait_for_signal ();
        if (preview == null) preview = GenericPreview.empty ();
      }

      /* Make sure the actions are registered. */
      var actions = preview.get_actions ();
      for (uint i = 0; i < actions.length; i++)
      {
        unowned PreviewAction preview_action = actions[i];
        _action_map[preview_action.id] = preview_action;
      }

      _last_preview = preview;
      // TODO: Preview will need a prop for the aggregation?!
      response = new ActivationResponse (HandledType.SHOW_PREVIEW);
      response.set_preview (preview);
    }

    if (response == null)
      response = new ActivationResponse (HandledType.NOT_HANDLED);

    // FIXME: pass goto_uri ?
    reply.uri = stripped_uri ?? uri;
    reply.handled = response.handled;
    reply.hints = response.get_hints ();

    return reply;
  }

  public async HashTable<string, Variant> update_preview_property (
      string uri, HashTable<string, Variant> values) throws IOError
  {
    HashTable<string, Variant> response;
    if (_last_preview != null)
    {
      response = yield _last_preview.update_property (values);
    }
    else
    {
      warning ("can't update preview property");
      response = new HashTable<string, Variant> (str_hash, str_equal);
    }

    return response;
  }

  private Cancellable[] cancellable_arr = new Cancellable[SearchType.N_TYPES];

  public async void schedule_search_changed (LensSearch search,
                                             SearchType search_type,
                                             bool wait_for_view)
  {
    /* don't use requires() here - valac 0.14 doesn't do the proper thing
     * with async methods */
    if (search_type >= SearchType.N_TYPES) return;

    bool waiting_needed = wait_for_view &&
      ((search_type == SearchType.GLOBAL && view_type != ViewType.HOME_VIEW) ||
       (search_type == SearchType.DEFAULT && view_type != ViewType.LENS_VIEW));

    /* Cancel any previous searches */
    if (cancellable_arr[search_type] != null)
    {
      cancellable_arr[search_type].cancel ();
    }

    var cancellable = new Cancellable ();
    cancellable_arr[search_type] = cancellable;

    if (waiting_needed)
    {
      var view_sig_id = this.notify["view-type"].connect (() =>
      {
        bool resume = (search_type == SearchType.DEFAULT && 
                       view_type == ViewType.LENS_VIEW)
                   || (search_type == SearchType.GLOBAL &&
                       view_type == ViewType.HOME_VIEW);
        if (resume) schedule_search_changed.callback ();
      });

      yield;
      SignalHandler.disconnect (this, view_sig_id);
    }

    /* We'll wait a bit to check if we don't get different search */
    Idle.add (schedule_search_changed.callback);
    yield;

    if (cancellable.is_cancelled ()) return;

    /* careful with the cancellable, the handler should ref it to use it */
    owner.search_changed (search, search_type, cancellable);
  }

  private string[] search_keys = new string[SearchType.N_TYPES];

  public void update_search_key (LensSearch ls, SearchType search_type)
    requires (search_type < SearchType.N_TYPES)
  {
    string? search_key = get_search_key (ls, search_type);

    search_keys[search_type] = search_key;
    owner.set_last_search (ls, search_type);
  }

  private string? get_search_key (LensSearch ls, SearchType search_type)
  {
    string? search_key = search_type == SearchType.DEFAULT ?
        owner.generate_search_key["default"] (ls) :
        owner.generate_search_key["global"] (ls);

    return search_key;
  }

  public void invalidate_search (SearchType search_type)
    requires (search_type < SearchType.N_TYPES)
  {
    search_keys[search_type] = null;
  }

  private async HashTable<string, Variant> search_internal (
      string search_string, HashTable<string, Variant> hints,
      SearchType search_type) throws ScopeError
  {
    HashTable<string, Variant> result =
        new HashTable<string, Variant> (str_hash, str_equal);
    bool is_global_search = search_type == SearchType.GLOBAL;

    // prepare new LensSearch instance
    var s = new LensSearch (search_string, hints, is_global_search ?
        _global_results_model : _results_model);

    // wait for the finished signal
    ulong sig_id = s.finished.connect ((lens_search) =>
    {
      HashTable<string, Variant>? reply_hints = lens_search.get_reply_hints ();
      if (reply_hints != null)
      {
        HashTableIter<string, Variant> iter = HashTableIter<string, Variant> (reply_hints);
        unowned string key;
        unowned Variant variant;
        while (iter.next (out key, out variant))
        {
          result.insert (key, variant);
        }
      }
      result.insert ("model-seqnum", new Variant.uint64 (lens_search.results_model.get_seqnum ()));
      search_internal.callback ();
    });

    LensSearch? last_search = null;
    ulong ls_sig_id = 0;

    string search_key = get_search_key (s, search_type);
    if ((search_key != null && search_key != search_keys[search_type]) ||
        (search_key == null && !s.equals (owner.get_last_search (search_type))))
    {
      schedule_search_changed.begin (s, search_type, false);
      search_keys[search_type] = search_key;

      owner.set_last_search (s, search_type);
    }
    else
    {
      // search key didn't change, but the last search might not have finished
      // yet, let's wait for it if that's the case
      last_search = owner.get_last_search (search_type);
      if (last_search != null && !last_search.was_finished ())
      {
        // wait for the last search to finish
        ls_sig_id = last_search.finished.connect (() =>
        {
          s.finished ();
        });

        // update view_type if necessary, because schedule_search_changed
        // might be waiting for it
        ViewType current_view = is_global_search ?
          ViewType.HOME_VIEW : ViewType.LENS_VIEW;
        if (view_type != current_view)
        {
          var old_view = view_type;
          // unblocks the suspended search
          set_view_type (current_view);
          // makes sure we don't remain in wrong state
          set_view_type (old_view);
        }
      }
      else
      {
        // returning empty HashTable in this case (search_key didn't change)
        return result;
      }
    }

    // now we have a Cancellable associated with this search
    // (from schedule_search_changed)
    var cancellable = cancellable_arr[search_type];
    ulong canc_id = cancellable.connect (() =>
    {
      SignalHandler.block (s, sig_id);
      // we can't directly call callback (), because we're inside cancel ()
      // which means the Cancellable's lock is held, so we wouldn't be able
      // to disconnect the handler
      Idle.add (search_internal.callback);
    });

    yield;
    // we just got finished signal, or the cancellable was cancelled

    if (ls_sig_id != 0) SignalHandler.disconnect (last_search, ls_sig_id);
    SignalHandler.disconnect (s, sig_id);
    cancellable.disconnect (canc_id);

    if (cancellable.is_cancelled ())
    {
      throw new ScopeError.SEARCH_CANCELLED ("Search '%s' was cancelled",
                                             search_string);
    }

    return result;
  }

  public async HashTable<string, Variant> search (string search_string,
      HashTable<string, Variant> hints) throws IOError, ScopeError
  {
    HashTable<string, Variant> result;

    result = yield search_internal (search_string, hints, SearchType.DEFAULT);

    return result;
  }

  public async HashTable<string, Variant> global_search (string search_string,
      HashTable<string, Variant> hints) throws IOError, ScopeError
  {
    HashTable<string, Variant> result;

    result = yield search_internal (search_string, hints, SearchType.GLOBAL);

    return result;
  }

  public Preview preview_internal (string uri)
  {
    Preview? response = owner.preview_uri (uri);
    if (response == null)
      response = GenericPreview.empty ();

    return response;
  }

  public ActivationResponse? activate_action (string action_id, string uri,
                                              HashTable<string, Variant> hints)
  {
    ActivationResponse? response = null;
    var action = _action_map[action_id];
    if (action != null)
    {
      var action_hints = action.hints;
      action_hints.remove_all ();
      if (hints.size () > 0)
      {
        HashTableIter<string, Variant> iter = HashTableIter<string, Variant> (hints);
        unowned string key;
        unowned Variant value;
        while (iter.next (out key, out value))
        {
          action_hints[key] = value;
        }
      }
      response = action.activated (uri);
    }
    else
      warning ("Cannot find PreviewAction with id: %s", action_id);

    return response;
  }

  public async void set_view_type (uint view_type_id) throws IOError
  {
    ViewType view_type = (ViewType) view_type_id;
    this.view_type = view_type;

    owner.active = view_type == ViewType.LENS_VIEW ||
        (view_type == ViewType.HOME_VIEW && owner.search_in_global);
  }

  public async void set_active_sources (string[] sources) throws IOError
  {
    owner.set_active_sources_internal (sources);
  }
}

} /* namespace */