~khurshid-alam/libunity/glib-2.59.3

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
/*
 * Copyright (C) 2011-2012 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>
 *             Michal Hruby <michal.hruby@canonical.com>
 *
 */

using GLib;
using Dee;
using Unity;
using Unity.Protocol;

namespace Unity.Internal {

internal enum ChannelState
{
  IDLE,
  SEARCH_ACTIVE
}

internal class ScopeChannel : Object
{
  private const uint METADATA_COLUMN = 8;

  public Utils.AsyncMutex model_lock;
  /* transfer_model must be a Dee.SharedModel */
  public Dee.SharedModel? transfer_model;
  /* backing model for the transfer_model (ie SequenceModel or FilterModel) */
  public Dee.SerializableModel backend_model;

  public FilterSet filters;

  public ChannelType channel_type;
  public string id;

  public ScopeSearchBase? last_search;
  public uint last_search_tag;

  private ChannelState state;
  private Utils.DelegateWrapper[] callbacks = {};

  private string last_push_search_string;
  private GLib.List<Dee.SerializableModel> pushed_models = new GLib.List<Dee.SerializableModel> ();
  private OwnerWatcher? watcher;

  public signal void owner_lost ();

  public ScopeChannel (ChannelType channel_type_)
  {
    channel_type = channel_type_;
    id = "%p".printf (this);
    filters = new FilterSet ();
    model_lock = new Utils.AsyncMutex ();
  }

  ~ScopeChannel ()
  {
    if (watcher != null)
    {
      watcher.unwatch ();
    }
  }

  public SearchType get_search_type ()
  {
    SearchType search_type = channel_type == ChannelType.DEFAULT ?
      SearchType.DEFAULT : SearchType.GLOBAL;
    return search_type;
  }

  private static Dee.SerializableModel create_filter_model (
      Dee.Model backend, HashTable<string, string> metadata_schema)
  {
    var types = new HashTable<string, VariantType> (str_hash, str_equal);
    metadata_schema.for_each ((field, schema) =>
    {
      types[field] = new VariantType (schema);
    });

    var model = new Dee.FilterModel (
      backend, Dee.Filter.new (
        () => {}, // no need for map func, the model is empty on creation
        (orig_model, iter, filter_model) =>
        {
          // check that the row contains all required metadata
          var metadata = orig_model.get_value (iter, METADATA_COLUMN);
          unowned string field_name;
          unowned VariantType schema;
          var ht_iter = HashTableIter<string, VariantType> (types);
          while (ht_iter.next (out field_name, out schema))
          {
            var field = metadata.lookup_value (field_name, schema);
            if (field == null)
            {
              warning ("Row doesn't contain required data: missing '%s'",
                       field_name);
              return false;
            }
          }

          filter_model.insert_iter_with_original_order (iter);
          return true;
        }));
    return model;
  }

  private Dee.SerializableModel create_backend_model (
      HashTable<string, string> metadata_schema,
      bool no_filtering,
      out Dee.SerializableModel real_backend)
  {
    var backend = new Dee.SequenceModel ();
    real_backend = backend;
    if (no_filtering || metadata_schema.size () == 0) return backend;

    return create_filter_model (backend, metadata_schema);
  }

  public string create_channel (string swarm_name,
                                HashTable<string, string> metadata_schema,
                                HashTable<string, string> optional_metadata,
                                Dee.SerializableModel filter_model,
                                ChannelFlags flags = 0)
  {
    unowned string field_name;
    unowned string schema;

    var vardict_schema =
      new HashTable<unowned string, unowned string> (str_hash, str_equal);
    var iter = HashTableIter<string, string> (optional_metadata);
    while (iter.next (out field_name, out schema))
    {
      vardict_schema[field_name] = schema;
    }
    /* ensure required metadata have higher prio */
    iter = HashTableIter<string, string> (metadata_schema);
    while (iter.next (out field_name, out schema))
    {
      vardict_schema[field_name] = schema;
    }

    var peer_type = ChannelFlags.PRIVATE in flags ?
      typeof (Dee.Server) : typeof (Dee.Peer);
    Dee.Peer peer = Object.new (peer_type,
                                "swarm-name", swarm_name,
                                "swarm-owner", true) as Dee.Peer;

    /* If NO_FILTERING is not specified, create_backend_model () will return
     * a FilterModel which will ensure that all required fields
     * from the schema are present, otherwise the row will be ignored.
     *
     * backend_model will then point to a simple SequenceModel which is used
     * as a backend for the FilterModel.
     */
    Dee.Model backend = create_backend_model (
      metadata_schema, ChannelFlags.NO_FILTERING in flags,
      out backend_model);

    /* Careful about using DiffModel, the ResultsSynchronizer doesn't play
     * nice with it, as the synchronized model gets cleared and listens
     * only to additions, if the provider model for the synchronizer only
     * removes a couple of results, and leaves the rest there,
     * the synchronizer will think that there are no results (cause there
     * were no additions).
     * Therefore AggregatorScopes can't use DiffModels. */
    if (ChannelFlags.DIFF_CHANGES in flags)
    {
      var sm = new DiffModel (peer, backend);
      sm.flush_mode = Dee.SharedModelFlushMode.MANUAL;
      sm.set_schema_full (RESULTS_SCHEMA);
      sm.set_column_names_full (RESULTS_COLUMN_NAMES);
      sm.register_vardict_schema (METADATA_COLUMN, vardict_schema);
      transfer_model = sm;
    }
    else
    {
      var mode_flag = Dee.SharedModelAccessMode.LEADER_WRITABLE;
      var sm = Object.new (typeof (Dee.SharedModel),
                           "peer", peer,
                           "back-end", backend,
                           "access-mode", mode_flag) as Dee.SharedModel;
      sm.flush_mode = Dee.SharedModelFlushMode.MANUAL;
      transfer_model = sm;
    }

    backend_model.set_schema_full (RESULTS_SCHEMA);
    backend_model.set_column_names_full (RESULTS_COLUMN_NAMES);
    backend_model.register_vardict_schema (METADATA_COLUMN, vardict_schema);

    set_filter_base (filter_model);

    return swarm_name;
  }

  public void set_filter_base (Dee.SerializableModel filter_model)
  {
    filters = new FilterSet ();

    // make a copy of filter_model, and handle the filter state there
    var fm_iter = filter_model.get_first_iter ();
    var end_iter = filter_model.get_last_iter ();
    while (fm_iter != end_iter)
    {
      var filter = Filter.for_filter_model_row (filter_model, fm_iter);
      if (filter != null) filters.add (filter);
      fm_iter = filter_model.next (fm_iter);
    }
  }

  public unowned Filter? get_filter_by_id (string filter_id)
  {
    return filters.get_filter_by_id (filter_id);
  }

  public async void wait_for_search ()
  {
    if (last_search == null) return;

    callbacks += new Utils.DelegateWrapper (wait_for_search.callback);
    yield;
  }

  public void set_state (ChannelState new_state)
  {
    if (new_state == state)
    {
      warning ("channel \"%s\", trying to change state to %s", id, new_state.to_string ());
      return;
    }

    var old_state = state;
    state = new_state;
    if (new_state == ChannelState.IDLE && old_state == ChannelState.SEARCH_ACTIVE)
    {
      // resume wait_for_search calls
      foreach (unowned Utils.DelegateWrapper wrapper in callbacks)
      {
        wrapper.callback ();
      }
      callbacks = {};
    }
  }

  public bool is_search_running ()
  {
    return state == ChannelState.SEARCH_ACTIVE;
  }

  public uint64 get_last_seqnum ()
  {
    if (transfer_model != null)
    {
      if (transfer_model is DiffModel)
      {
        (transfer_model as DiffModel).commit_changes ();
      }
      return transfer_model.get_seqnum ();
    }

    return backend_model.get_seqnum ();
  }

  public void register_pushed_model (string search_string,
                                     Dee.SerializableModel model)
  {
    if (search_string != last_push_search_string)
    {
      last_push_search_string = search_string;
      pushed_models = new GLib.List<Dee.SerializableModel> ();
    }

    pushed_models.append (model);
  }

  public GLib.List<unowned Dee.SerializableModel> get_pushed_models (string search_string)
  {
    if (last_push_search_string != search_string)
    {
      return new GLib.List<unowned Dee.SerializableModel> ();
    }

    return pushed_models.copy ();
  }

  /* Separate class to ensure we don't have reference cycles */
  private class OwnerWatcher
  {
    private uint owner_changed_signal_id;
    private unowned ScopeChannel owner_channel;
    private DBusConnection dbus_connection;
    
    public OwnerWatcher (ScopeChannel channel, DBusConnection connection, BusName owner)
    {
      owner_channel = channel;
      dbus_connection = connection;
      owner_changed_signal_id = dbus_connection.signal_subscribe (null,
          "org.freedesktop.DBus", "NameOwnerChanged", null, owner,
          DBusSignalFlags.NONE, this.owner_changed);
    }

    private void owner_changed (DBusConnection con, string sender_name,
                                string obj_path, string ifc_name,
                                string sig_name, Variant parameters)
    {
      string new_owner = parameters.get_child_value (2).get_string ();
      if (new_owner == "")
      {
        owner_channel.owner_lost ();
      }
    }

    public void unwatch ()
    {
      if (owner_changed_signal_id != 0)
      {
        dbus_connection.signal_unsubscribe (owner_changed_signal_id);
        owner_changed_signal_id = 0;
      }
    }
  }

  public void watch_owner (DBusConnection connection, BusName owner)
  {
    if (watcher != null) watcher.unwatch ();
    watcher = new OwnerWatcher (this, connection, owner);
  }
}

} /* namespace Unity.Internal */