Bug 465497, Wait for AUS to notice new snippets before testing them, r=bhearsum
[mozilla-1.9.git] / browser / components / distribution.js
blob722abe215f30204a67cda83d81b9bddd83dc0509
1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Mozilla Public License Version
5  * 1.1 (the "License"); you may not use this file except in compliance with
6  * the License. You may obtain a copy of the License at
7  * http://www.mozilla.org/MPL/
8  *
9  * Software distributed under the License is distributed on an "AS IS" basis,
10  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11  * for the specific language governing rights and limitations under the
12  * License.
13  *
14  * The Original Code is the Firefox Distribution Customizations.
15  *
16  * The Initial Developer of the Original Code is Mozilla Foundation.
17  * Portions created by the Initial Developer are Copyright (C) 2007
18  * the Initial Developer. All Rights Reserved.
19  *
20  * Contributor(s):
21  *   Dan Mills <thunder@mozilla.com>
22  *
23  * Alternatively, the contents of this file may be used under the terms of
24  * either the GNU General Public License Version 2 or later (the "GPL"), or
25  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
26  * in which case the provisions of the GPL or the LGPL are applicable instead
27  * of those above. If you wish to allow use of your version of this file only
28  * under the terms of either the GPL or the LGPL, and not to allow others to
29  * use your version of this file under the terms of the MPL, indicate your
30  * decision by deleting the provisions above and replace them with the notice
31  * and other provisions required by the GPL or the LGPL. If you do not delete
32  * the provisions above, a recipient may use your version of this file under
33  * the terms of any one of the MPL, the GPL or the LGPL.
34  *
35  * ***** END LICENSE BLOCK ***** */
37 EXPORTED_SYMBOLS = [ "DistributionCustomizer" ];
39 const Ci = Components.interfaces;
40 const Cc = Components.classes;
41 const Cr = Components.results;
42 const Cu = Components.utils;
44 function DistributionCustomizer() {
45   this._distroDir = this._dirSvc.get("XCurProcD", Ci.nsIFile);
46   this._distroDir.append("distribution");
48   let iniFile = this._distroDir.clone();
49   iniFile.append("distribution.ini");
50   this._iniExists = iniFile.exists();
52   if (!this._iniExists)
53     return;
55   this._ini = Cc["@mozilla.org/xpcom/ini-parser-factory;1"].
56     getService(Ci.nsIINIParserFactory).createINIParser(iniFile);
58   this._prefs = this._prefSvc.getBranch(null);
59   this._locale = this._prefs.getCharPref("general.useragent.locale");
62 DistributionCustomizer.prototype = {
63   __bmSvc: null,
64   get _bmSvc() {
65     if (!this.__bmSvc)
66       this.__bmSvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
67                    getService(Ci.nsINavBookmarksService);
68     return this.__bmSvc;
69   },
71   __annoSvc: null,
72   get _annoSvc() {
73     if (!this.__annoSvc)
74       this.__annoSvc = Cc["@mozilla.org/browser/annotation-service;1"].
75                    getService(Ci.nsIAnnotationService);
76     return this.__annoSvc;
77   },
79   __livemarkSvc: null,
80   get _livemarkSvc() {
81     if (!this.__livemarkSvc)
82       this.__livemarkSvc = Cc["@mozilla.org/browser/livemark-service;2"].
83                    getService(Ci.nsILivemarkService);
84     return this.__livemarkSvc;
85   },
87   __dirSvc: null,
88   get _dirSvc() {
89     if (!this.__dirSvc)
90       this.__dirSvc = Cc["@mozilla.org/file/directory_service;1"].
91         getService(Ci.nsIProperties);
92     return this.__dirSvc;
93   },
95   __prefSvc: null,
96   get _prefSvc() {
97     if (!this.__prefSvc)
98       this.__prefSvc = Cc["@mozilla.org/preferences-service;1"].
99         getService(Ci.nsIPrefService);
100     return this.__prefSvc;
101   },
103   __iosvc: null,
104   get _iosvc() {
105     if (!this.__iosvc)
106       this.__iosvc = Cc["@mozilla.org/network/io-service;1"].
107                    getService(Ci.nsIIOService);
108     return this.__iosvc;
109   },
111   _locale: "en-US",
112   _distroDir: null,
113   _iniExists: false,
114   _ini: null,
117   _makeURI: function DIST__makeURI(spec) {
118     return this._iosvc.newURI(spec, null, null);
119   },
120   _parseBookmarksSection: function DIST_parseBookmarksSection(parentId, section) {
121     let keys = [];
122     for (let i in enumerate(this._ini.getKeys(section)))
123       keys.push(i);
124     keys.sort();
125     let items = {};
126     let defaultItemId = -1;
127     let maxItemId = -1;
129     for (let i = 0; i < keys.length; i++) {
130       let m = /^item\.(\d+)\.(\w+)\.?(\w*)/.exec(keys[i]);
131       if (m) {
132         let [foo, iid, iprop, ilocale] = m;
134         if (ilocale)
135           continue;
137         if (!items[iid])
138           items[iid] = {};
139         if (keys.indexOf(keys[i] + "." + this._locale) >= 0) {
140           items[iid][iprop] = this._ini.getString(section, keys[i] + "." +
141                                                   this._locale);
142         } else {
143           items[iid][iprop] = this._ini.getString(section, keys[i]);
144         }
146         if (iprop == "type" && items[iid]["type"] == "default")
147           defaultItemId = iid;
149         if (maxItemId < iid)
150           maxItemId = iid;
151       } else {
152         dump("Key did not match: " + keys[i] + "\n");
153       }
154     }
156     let prependIndex = 0;
157     for (let iid = 0; iid <= maxItemId; iid++) {
158       if (!items[iid])
159         continue;
161       let index = -1;
162       let newId;
164       switch (items[iid]["type"]) {
165       case "default":
166         break;
168       case "folder":
169         if (iid < defaultItemId)
170           index = prependIndex++;
172         newId = this._bmSvc.createFolder(parentId, items[iid]["title"], index);
174         this._parseBookmarksSection(newId, "BookmarksFolder-" +
175                                     items[iid]["folderId"]);
177         if (items[iid]["description"])
178           this._annoSvc.setItemAnnotation(newId, "bookmarkProperties/description",
179                                           items[iid]["description"], 0,
180                                           this._annoSvc.EXPIRE_NEVER);
182         break;
184       case "separator":
185         if (iid < defaultItemId)
186           index = prependIndex++;
187         this._bmSvc.insertSeparator(parentId, index);
188         break;
190       case "livemark":
191         if (iid < defaultItemId)
192           index = prependIndex++;
194         newId = this._livemarkSvc.
195           createLivemark(parentId,
196                          items[iid]["title"],
197                          this._makeURI(items[iid]["siteLink"]),
198                          this._makeURI(items[iid]["feedLink"]),
199                          index);
200         break;
202       case "bookmark":
203       default:
204         if (iid < defaultItemId)
205           index = prependIndex++;
207         newId = this._bmSvc.insertBookmark(parentId,
208                                            this._makeURI(items[iid]["link"]),
209                                            index, items[iid]["title"]);
211         if (items[iid]["description"])
212           this._annoSvc.setItemAnnotation(newId, "bookmarkProperties/description",
213                                           items[iid]["description"], 0,
214                                           this._annoSvc.EXPIRE_NEVER);
216         break;
217       }
218     }
219   },
220   applyCustomizations: function DIST_applyCustomizations() {
221     if (!this._iniExists)
222       return;
224     // nsPrefService loads very early.  Reload prefs so we can set
225     // distribution defaults during the prefservice:after-app-defaults
226     // notification (see applyPrefDefaults below)
227     this._prefSvc.QueryInterface(Ci.nsIObserver);
228     this._prefSvc.observe(null, "reload-default-prefs", null);
230     let sections = enumToObject(this._ini.getSections());
232     // The global section, and several of its fields, is required
233     // (we also check here to be consistent with applyPrefDefaults below)
234     if (!sections["Global"])
235       return;
236     let globalPrefs = enumToObject(this._ini.getKeys("Global"));
237     if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"]))
238       return;
240     let bmProcessed = false;
241     let bmProcessedPref;
243     try {
244         bmProcessedPref = this._ini.getString("Global",
245                                               "bookmarks.initialized.pref");
246     } catch (e) {
247       bmProcessedPref = "distribution." +
248         this._ini.getString("Global", "id") + ".bookmarksProcessed";
249     }
251     try {
252       bmProcessed = this._prefs.getBoolPref(bmProcessedPref);
253     } catch (e) {}
255     if (!bmProcessed) {
256       if (sections["BookmarksMenu"])
257         this._parseBookmarksSection(this._bmSvc.bookmarksMenuFolder,
258                                     "BookmarksMenu");
259       if (sections["BookmarksToolbar"])
260         this._parseBookmarksSection(this._bmSvc.toolbarFolder,
261                                     "BookmarksToolbar");
262       this._prefs.setBoolPref(bmProcessedPref, true);
263     }
264   },
265   applyPrefDefaults: function DIST_applyPrefDefaults() {
266     if (!this._iniExists)
267       return;
269     let sections = enumToObject(this._ini.getSections());
271     // The global section, and several of its fields, is required
272     if (!sections["Global"])
273       return;
274     let globalPrefs = enumToObject(this._ini.getKeys("Global"));
275     if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"]))
276       return;
278     let defaults = this._prefSvc.getDefaultBranch(null);
280     // Global really contains info we set as prefs.  They're only
281     // separate because they are "special" (read: required)
283     defaults.setCharPref("distribution.id", this._ini.getString("Global", "id"));
284     defaults.setCharPref("distribution.version",
285                          this._ini.getString("Global", "version"));
287     let partnerAbout = Cc["@mozilla.org/supports-string;1"].
288       createInstance(Ci.nsISupportsString);
289     if (globalPrefs["about." + this._locale]) {
290       partnerAbout.data = this._ini.getString("Global", "about." + this._locale);
291     } else {
292       partnerAbout.data = this._ini.getString("Global", "about");
293     }
294     defaults.setComplexValue("distribution.about",
295                              Ci.nsISupportsString, partnerAbout);
297     if (sections["Preferences"]) {
298       for (let key in enumerate(this._ini.getKeys("Preferences"))) {
299         try {
300           let value = eval(this._ini.getString("Preferences", key));
301           switch (typeof value) {
302           case "boolean":
303             defaults.setBoolPref(key, value);
304             break;
305           case "number":
306             defaults.setIntPref(key, value);
307             break;
308           case "string":
309             defaults.setCharPref(key, value);
310             break;
311           case "undefined":
312             defaults.setCharPref(key, value);
313             break;
314           }
315         } catch (e) { /* ignore bad prefs and move on */ }
316       }
317     }
319     // We eval() the localizable prefs as well (even though they'll
320     // always get set as a string) to keep the INI format consistent:
321     // string prefs always need to be in quotes
323     let localizedStr = Cc["@mozilla.org/pref-localizedstring;1"].
324       createInstance(Ci.nsIPrefLocalizedString);
326     if (sections["LocalizablePreferences"]) {
327       for (let key in enumerate(this._ini.getKeys("LocalizablePreferences"))) {
328         try {
329           let value = eval(this._ini.getString("LocalizablePreferences", key));
330           value = value.replace("%LOCALE%", this._locale, "g");
331           localizedStr.data = "data:text/plain," + key + "=" + value;
332           defaults.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr);
333         } catch (e) { /* ignore bad prefs and move on */ }
334       }
335     }
337     if (sections["LocalizablePreferences-" + this._locale]) {
338       for (let key in enumerate(this._ini.getKeys("LocalizablePreferences-" + this._locale))) {
339         try {
340           let value = eval(this._ini.getString("LocalizablePreferences-" + this._locale, key));
341           localizedStr.data = "data:text/plain," + key + "=" + value;
342           defaults.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr);
343         } catch (e) { /* ignore bad prefs and move on */ }
344       }
345     }
346   }
349 function enumerate(UTF8Enumerator) {
350   while (UTF8Enumerator.hasMore())
351     yield UTF8Enumerator.getNext();
354 function enumToObject(UTF8Enumerator) {
355   let ret = {};
356   for (let i in enumerate(UTF8Enumerator))
357     ret[i] = 1;
358   return ret;