services/cloudsync/CloudSyncAdapters.jsm
author Julian Seward <jseward@acm.org>
Tue, 24 Jan 2017 17:10:01 +0100
changeset 361633 a9f258d042482099bbbd9bfd235efbf742959df0
parent 360242 4a4bd6ca18c3860d74f5a3b63ce316b6e142ce94
child 387335 322fde2d53bf49266dbc293321e6b36a4c789c12
permissions -rw-r--r--
Bug 1232696 - Remove NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW as it causes segfaulting for GCC 6 builds (1 of 5, fixes for view/). r=tnikkel.

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

this.EXPORTED_SYMBOLS = ["Adapters"];

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/CloudSyncEventSource.jsm");

this.Adapters = function() {
  let eventTypes = [
    "sync",
  ];

  let suspended = true;

  let suspend = function() {
    if (!suspended) {
      Services.obs.removeObserver(observer, "cloudsync:user-sync");
      suspended = true;
    }
  };

  let resume = function() {
    if (suspended) {
      Services.obs.addObserver(observer, "cloudsync:user-sync", false);
      suspended = false;
    }
  };

  let eventSource = new EventSource(eventTypes, suspend, resume);
  let registeredAdapters = new Map();

  function register(name, opts) {
    opts = opts || {};
    registeredAdapters.set(name, opts);
  }

  function unregister(name) {
    if (!registeredAdapters.has(name)) {
      throw new Error("adapter is not registered: " + name)
    }
    registeredAdapters.delete(name);
  }

  function getAdapterNames() {
    let result = [];
    for (let name of registeredAdapters.keys()) {
      result.push(name);
    }
    return result;
  }

  function getAdapter(name) {
    if (!registeredAdapters.has(name)) {
      throw new Error("adapter is not registered: " + name)
    }
    return registeredAdapters.get(name);
  }

  function countAdapters() {
    return registeredAdapters.size;
  }

  let observer = {
    observe(subject, topic, data) {
      switch (topic) {
        case "cloudsync:user-sync":
          eventSource.emit("sync");
          break;
      }
    }
  };

  this.addEventListener = eventSource.addEventListener;
  this.removeEventListener = eventSource.removeEventListener;
  this.register = register.bind(this);
  this.get = getAdapter.bind(this);
  this.unregister = unregister.bind(this);
  this.__defineGetter__("names", getAdapterNames);
  this.__defineGetter__("count", countAdapters);
};

Adapters.prototype = {

};