Example #1
0
var cDump = function(obj) {
    var bstr = 'bstr:\n';
    var fstr = '';
    for (var b in obj) {
        try{
            bstr += b+'='+obj[b]+'\n';
        } catch (e) {
                fstr = b+'='+e+'\n';
        }
    }
    Cu.reportError(bstr);
    if (fstr != '') { Cu.reportError(fstr) }
};
Example #2
0
    start: function(options = {}) {
      let config = this._profilerStartOptions = {
        entries: options.entries || DEFAULT_PROFILER_OPTIONS.entries,
        interval: options.interval || DEFAULT_PROFILER_OPTIONS.interval,
        features: options.features || DEFAULT_PROFILER_OPTIONS.features,
        threadFilters: options.threadFilters || DEFAULT_PROFILER_OPTIONS.threadFilters,
      };

      // The start time should be before any samples we might be
      // interested in.
      let currentTime = Services.profiler.getElapsedTime();

      try {
        Services.profiler.StartProfiler(
          config.entries,
          config.interval,
          config.features,
          config.features.length,
          config.threadFilters,
          config.threadFilters.length
        );
      } catch (e) {
        // For some reason, the profiler couldn't be started. This could happen,
        // for example, when in private browsing mode.
        Cu.reportError(`Could not start the profiler module: ${e.message}`);
        return { started: false, reason: e, currentTime };
      }
      this.started = true;

      this._updateProfilerStatusPolling();

      let { position, totalSize, generation } = this.getBufferInfo();
      return { started: true, position, totalSize, generation, currentTime };
    },
 this.feeds.forEach(feed => {
   try {
     feed.onAction(store.getState(), action);
   } catch (e) {
     Cu.reportError(`Error caught in .onAction for ${feed.constructor.name}: ${e}`);
   }
 });
Example #4
0
  asyncGetSuggestions: Task.async(function*(browser, data) {
    const engine = Services.search.getEngineByName(data.engineName);
    if (!engine) {
      throw new Error(`Unknown engine name: ${data.engineName}`);
    }
    let {controller} = this._getSuggestionData(browser);
    let ok = SearchSuggestionController.engineOffersSuggestions(engine);
    controller.maxLocalResults = ok ? MAX_LOCAL_SUGGESTIONS : MAX_SUGGESTIONS;
    controller.maxRemoteResults = ok ? MAX_SUGGESTIONS : 0;
    controller.remoteTimeout = data.remoteTimeout || undefined;
    let isPrivate = PrivateBrowsingUtils.isBrowserPrivate(browser);

    let suggestions;
    try {
      // If fetch() rejects due to it's asynchronous behaviour, the suggestions
      // are null and is then handled.
      suggestions = yield controller.fetch(data.searchString, isPrivate, engine);
    } catch (e) {
      Cu.reportError(e);
    }

    let result = null;
    if (suggestions) {
      this._suggestionMap.get(browser).previousFormHistoryResult = suggestions.formHistoryResult;
      result = {
        engineName: data.engineName,
        searchString: suggestions.term,
        formHistory: suggestions.local,
        suggestions: suggestions.remote,
      };
    }
    return result;
  }),
Example #5
0
 return this.fetchHarData(options).then(jsonString => {
   if (!HarUtils.saveToFile(file, jsonString, options.compress)) {
     let msg = "Failed to save HAR file at: " + options.defaultFileName;
     Cu.reportError(msg);
   }
   return jsonString;
 });
Example #6
0
// Exports variables that will be accessed by the non-privileged scripts.
function exportData(win, headers) {
  const json = new win.Text();
  const JSONView = Cu.cloneInto({
    debugJsModules,
    headers,
    json,
    readyState: "uninitialized",
    Locale: {
      $STR: key => {
        try {
          return jsonViewStrings.GetStringFromName(key);
        } catch (err) {
          console.error(err);
          return undefined;
        }
      },
    },
  }, win, {
    cloneFunctions: true,
    wrapReflectors: true,
  });
  try {
    Object.defineProperty(Cu.waiveXrays(win), "JSONView", {
      value: JSONView,
      configurable: true,
      enumerable: true,
      writable: true,
    });
  } catch (error) {
    Cu.reportError(error);
  }
  return {json};
}
Example #7
0
  _onProfilerEvent: function (eventName, data) {
    // If this event already passed through once, don't repropagate
    if (data.relayed) {
      return;
    }
    data.relayed = true;

    if (eventName === "eventNotification") {
      // If this is `eventNotification`, this is coming from an older Gecko (<Fx42)
      // that doesn't use protocol.js style events. Massage it to emit a protocol.js
      // style event as well.
      events.emit(this, data.topic, data);
    } else {
      // Otherwise if a modern protocol.js event, emit it also as `eventNotification`
      // for compatibility reasons on the client (like for any add-ons/Gecko Profiler
      // using this event) and log a deprecation message if there is a listener.
      this.conn.emit("eventNotification", {
        subject: data.subject,
        topic: data.topic,
        data: data.data,
        details: data.details
      });
      if (this.conn._getListeners("eventNotification").length) {
        Cu.reportError(`
          ProfilerActor's "eventNotification" on the DebuggerClient has been deprecated.
          Use the ProfilerFront found in "devtools/server/actors/profiler".`);
      }
    }
  },
Example #8
0
JSONPacket.prototype.read = function(stream, scriptableStream) {
  dumpv("Reading JSON packet");

  // Read in more packet data.
  this._readData(stream, scriptableStream);

  if (!this.done) {
    // Don't have a complete packet yet.
    return;
  }

  let json = this._data;
  try {
    json = unicodeConverter.ConvertToUnicode(json);
    this._object = JSON.parse(json);
  } catch(e) {
    let msg = "Error parsing incoming packet: " + json + " (" + e +
              " - " + e.stack + ")";
    if (Cu.reportError) {
      Cu.reportError(msg);
    }
    dumpn(msg);
    return;
  }

  this._transport._onJSONObjectReady(this._object);
}
Example #9
0
  fetchStorageObjects: Task.async(function* (type, host, names, reason) {
    let fetchOpts = reason === REASON.NEXT_50_ITEMS ? {offset: this.itemOffset}
                                                    : {};
    let storageType = this.storageTypes[type];

    if (reason !== REASON.NEXT_50_ITEMS &&
        reason !== REASON.UPDATE &&
        reason !== REASON.NEW_ROW &&
        reason !== REASON.POPULATE) {
      throw new Error("Invalid reason specified");
    }

    try {
      let {data} = yield storageType.getStoreObjects(host, names, fetchOpts);
      if (data.length) {
        if (reason === REASON.POPULATE) {
          yield this.resetColumns(data[0], type, host);
        }
        this.populateTable(data, reason);
      }
      this.emit("store-objects-updated");
    } catch (ex) {
      Cu.reportError(ex);
    }
  }),
Example #10
0
  _onConsoleProfileEnd: Task.async(function* (data) {
    // If no data, abort; can occur if profiler isn't running and we get a surprise
    // call to console.profileEnd()
    if (!data) {
      return;
    }
    let { profileLabel, currentTime: endTime } = data;

    let pending = this._recordings.filter(r => r.isConsole() && r.isRecording());
    if (pending.length === 0) {
      return;
    }

    let model;
    // Try to find the corresponding `console.profile` call if
    // a label was used in profileEnd(). If no matches, abort.
    if (profileLabel) {
      model = pending.find(e => e.getLabel() === profileLabel);
    }
    // If no label supplied, pop off the most recent pending console recording
    else {
      model = pending[pending.length - 1];
    }

    // If `profileEnd()` was called with a label, and there are no matching
    // sessions, abort.
    if (!model) {
      Cu.reportError("console.profileEnd() called with label that does not match a recording.");
      return;
    }

    yield this.stopRecording(model);
  }),
Example #11
0
 $STR: key => {
   try {
     return jsonViewStrings.GetStringFromName(key);
   } catch (err) {
     Cu.reportError(err);
   }
 }
Example #12
0
 createValueGrip: function (value, objectWrapper) {
   switch (typeof value) {
     case "boolean":
       return value;
     case "string":
       return objectWrapper(value);
     case "number":
       if (value === Infinity) {
         return { type: "Infinity" };
       } else if (value === -Infinity) {
         return { type: "-Infinity" };
       } else if (Number.isNaN(value)) {
         return { type: "NaN" };
       } else if (!value && 1 / value === -Infinity) {
         return { type: "-0" };
       }
       return value;
     case "undefined":
       return { type: "undefined" };
     case "object":
       if (value === null) {
         return { type: "null" };
       }
       // Fall through.
     case "function":
       return objectWrapper(value);
     default:
       Cu.reportError("Failed to provide a grip for value of " + typeof value
                      + ": " + value);
       return null;
   }
 },
Example #13
0
  push: function(item, suppressFlash) {
    if (!this.sortedOn || !this.columns) {
      Cu.reportError("Can't insert item without defining columns first");
      return;
    }

    if (this.items.has(item[this.uniqueId])) {
      this.update(item);
      return;
    }

    let index = this.columns.get(this.sortedOn).push(item);
    for (let [key, column] of this.columns) {
      if (key != this.sortedOn) {
        column.insertAt(item, index);
      }
      column.updateZebra();
    }
    this.items.set(item[this.uniqueId], item);
    this.tbody.removeAttribute("empty");

    if (!suppressFlash) {
      this.emit(EVENTS.ROW_UPDATED, item[this.uniqueId]);
    }

    this.emit(EVENTS.ROW_EDIT, item[this.uniqueId]);
  },
	handleNativeMenuState: function () {
		try {

			var tabInfo = this.UI.getCurrentTabInfo(true);

			var window = UiUtils.getMostRecentWindow();
			var menuItems = this.nativeMenuIds[window].items;
			var nativeMenu = window.NativeWindow.menu;

			for (var item in menuItems) {
				nativeMenu.update(menuItems[item], {visible: false})
			}

			if (tabInfo.applicationFilteringDisabled) {
				nativeMenu.update(menuItems.toggleFilteringEnabledItem, {visible: true, checked: true});
			} else if (tabInfo.urlFilteringDisabled) {
				//do nothing, already not visible
			} else {
				nativeMenu.update(menuItems.toggleFilteringEnabledItem, {visible: true, checked: false});
				if (tabInfo.documentWhiteListed && !tabInfo.userWhiteListed) {
					nativeMenu.update(menuItems.siteExceptionItem, {visible: true});
				} else if (tabInfo.canAddRemoveRule) {
					nativeMenu.update(menuItems.toggleWhiteListItem, {visible: true, checked: !tabInfo.userWhiteListed});
				}
				if (!tabInfo.documentWhiteListed) {
					nativeMenu.update(menuItems.blockAdsItem, {visible: true});
				}
				nativeMenu.update(menuItems.filteringLogItem, {visible: true});
				nativeMenu.update(menuItems.reportSiteItem, {visible: true});
			}
		} catch (ex) {
			Cu.reportError(ex);
		}
	},
Example #15
0
function doGetFile(path, allowNonexistent) {
  try {
    let lf = Cc["@mozilla.org/file/directory_service;1"]
      .getService(Ci.nsIProperties)
      .get("CurWorkD", Ci.nsILocalFile);

    let bits = path.split("/");
    for (let bit of bits.filter(bit => bit)) {
      if (bit !== "..") {
        lf.append(bit);
      } else {
        lf = lf.parent;
      }
    }

    if (!allowNonexistent && !lf.exists()) {
      // Not using do_throw(): caller will continue.
      let stack = Cs.caller;
      Cu.reportError(`[${stack.name} : ${stack.lineNumber}] ${lf.path} does not exist`);
    }

    return lf;
  }
  catch (ex) {
    doThrow(ex.toString(), Cs.caller);
  }

  return null;
}
Example #16
0
 createValueGrip: function WCU_createValueGrip(aValue, aObjectWrapper)
 {
   switch (typeof aValue) {
     case "boolean":
       return aValue;
     case "string":
       return aObjectWrapper(aValue);
     case "number":
       if (aValue === Infinity) {
         return { type: "Infinity" };
       }
       else if (aValue === -Infinity) {
         return { type: "-Infinity" };
       }
       else if (Number.isNaN(aValue)) {
         return { type: "NaN" };
       }
       else if (!aValue && 1 / aValue === -Infinity) {
         return { type: "-0" };
       }
       return aValue;
     case "undefined":
       return { type: "undefined" };
     case "object":
       if (aValue === null) {
         return { type: "null" };
       }
     case "function":
       return aObjectWrapper(aValue);
     default:
       Cu.reportError("Failed to provide a grip for value of " + typeof aValue
                      + ": " + aValue);
       return null;
   }
 },
Example #17
0
 get traits() {
   if (!this._traits) {
     Cu.reportError("Cannot access traits of PerformanceFront before " +
                    "calling `connect()`.");
   }
   return this._traits;
 }
Example #18
0
XPCOMUtils.defineLazyGetter(this, "HUDService", function () {
  Cu.import("resource:///modules/HUDService.jsm", self);
  try {
    return HUDService;
  }
  catch (ex) {
    Cu.reportError(ex);
  }
});
Example #19
0
  _initCSS: function()
  {
    function processCSSData(request)
    {
      if (onShutdown.done)
        return;

      let data = request.responseText;

      let rnd = [];
      let offset = "a".charCodeAt(0);
      for (let i = 0; i < 60; i++)
        rnd.push(offset + Math.random() * 26);

      this.objTabClassVisibleTop = String.fromCharCode.apply(String, rnd.slice(0, 20));
      this.objTabClassVisibleBottom = String.fromCharCode.apply(String, rnd.slice(20, 40));
      this.objTabClassHidden = String.fromCharCode.apply(String, rnd.slice(40, 60));

      let url = Utils.makeURI("data:text/css," + encodeURIComponent(data.replace(/%%CLASSVISIBLETOP%%/g, this.objTabClassVisibleTop)
                                                                        .replace(/%%CLASSVISIBLEBOTTOM%%/g, this.objTabClassVisibleBottom)
                                                                        .replace(/%%CLASSHIDDEN%%/g, this.objTabClassHidden)));
      Utils.styleService.loadAndRegisterSheet(url, Ci.nsIStyleSheetService.USER_SHEET);
      onShutdown.add(function()
      {
        Utils.styleService.unregisterSheet(url, Ci.nsIStyleSheetService.USER_SHEET);
      });

      this.initializing = false;
      this.initialized = true;

      if (this.delayedShowParams)
        this._showTab.apply(this, this.delayedShowParams);
    }

    this.delayedShowParams = arguments;

    if (!this.initializing)
    {
      this.initializing = true;

      // Load CSS asynchronously
      try {
        let request = new XMLHttpRequest();
        request.mozBackgroundRequest = true;
        request.open("GET", "chrome://adblockcash/content/objtabs.css");
        request.overrideMimeType("text/plain");

        request.addEventListener("load", processCSSData.bind(this, request), false);
        request.send(null);
      }
      catch (e)
      {
        Cu.reportError(e);
        this.initializing = false;
      }
    }
  },
  myActor.attach().then(() => {
    console.log("My actor is now attached");
    Cu.reportError("My actor is now attached");

    // Finally, execute remote method on the actor!
    myActor.hello().then(response => {
      console.log("Response from the actor: " + response.msg, response);
      Cu.reportError("Response from the actor: " + response.msg, response);
    });
  });
Example #21
0
      return client.request(request, (res) => {
        if (res.error) {
          Cu.reportError(res.message || res.error);
        }

        if (res.url) {
          a.iconURL = res.url;
        }
        getIcon();
      });
Example #22
0
    function trueUnregister() {

        categoryManager.deleteCategoryEntry('content-policy', CONTRACT_ID, false);

        try {
            xpcom.unregister(factory);
        } catch (exception) {
            Cu.reportError(exception);
        }
    }
Example #23
0
  content.setTimeout(function dispatchMouseEvents(self) {
    try {
      self.fireMouseEvent('mousedown', evt);
      self.fireMouseEvent('mousemove', evt);
      self.fireMouseEvent('mouseup', evt);
    } catch(e) {
      Cu.reportError('Exception in touch event helper: ' + e);
    }
    ignoreEvents = false;
 }, 0, this);
Example #24
0
 getStr: function (name) {
   let result;
   try {
     result = this.stringBundle.GetStringFromName(name);
   } catch (ex) {
     Cu.reportError("Failed to get string: " + name);
     throw ex;
   }
   return result;
 },
       (aResponse) =>
      {
        if (aResponse.error) {
          Cu.reportError("NP__onLongStringSubstring error: " + aResponse.error);
          return;
        }

        postData.text = postData.text.initial + aResponse.substring;
        this._updateRequestBody();
      });
Example #26
0
function dblclicked(e) {
	if (e.button != trigger) { return }
	Cu.reportError('dblclicked');
	var now = new Date().getTime();
	if (!dblClickedAfterZoom) {
		Cu.reportError('dblclick prevd - after zoomed');
		e.stopPropagation();
		e.preventDefault();
		e.returnValue = false;
		return false;
	} else if (!dblClickedAfterListen) {
		Cu.reportError('dblclick prevd - after listen');
		e.stopPropagation();
		e.preventDefault();
		e.returnValue = false;
		return false;
	} else {
		Cu.reportError('dblclicked dont know why here');
	}
}
Example #27
0
 getFormatStr: function (name, array) {
   let result;
   try {
     result = this.stringBundle.formatStringFromName(name, array,
                                                     array.length);
   } catch (ex) {
     Cu.reportError("Failed to format string: " + name);
     throw ex;
   }
   return result;
 },
Example #28
0
 worker.port.on("content-to-addon", msg => {
   if (!msg.type) {
     Cu.reportError("Application.dispatch error: unknown message type");
     return;
   }
   // This detaches workers if a new url is launched
   // it is important to remove the worker from the set, otherwise we will leak memory
   if (msg.type === "pagehide") {
     this._removeWorker(worker);
   }
   this.emit(msg.type, {msg, worker});
 });
 worker.port.on(CONTENT_TO_ADDON, msg => {
   if (!msg.type) {
     Cu.reportError("ActivityStreams.dispatch error: unknown message type");
     return;
   }
   // This detaches workers if a new url is launched
   // it is important to remove the worker from the set, otherwise we will leak memory
   if (msg.type === "pagehide") {
     this._removeWorker(worker);
   }
   this.emit(CONTENT_TO_ADDON, {msg, worker});
 });
  registry.registerActor(actorModuleUrl, options).then(actorRegistrar => {
    console.log("My tab actor is now registered");
    Cu.reportError("My tab actor is now registered");

    // Remember, so we can unregister the actor later.
    myActorRegistrar = actorRegistrar;

    target.client.listTabs(response => {
      let tab = response.tabs[response.selected];
      attachActor(target, tab);
    });
  });