]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/bookmarkcache.jsm
Import r6923 from upstream hg supporting Firefox up to 22.0a1
[dactyl.git] / common / modules / bookmarkcache.jsm
1 // Copyright ©2008-2010 Kris Maglione <maglione.k at Gmail>
2 //
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
5 "use strict";
6
7 defineModule("bookmarkcache", {
8     exports: ["Bookmark", "BookmarkCache", "Keyword", "bookmarkcache"],
9     require: ["services", "util"]
10 });
11
12 this.lazyRequire("storage", ["storage"]);
13
14 function newURI(url, charset, base) {
15     try {
16         return services.io.newURI(url, charset, base);
17     }
18     catch (e) {
19         throw Error(e);
20     }
21 }
22
23 var Bookmark = Struct("url", "title", "icon", "post", "keyword", "tags", "charset", "id");
24 var Keyword = Struct("keyword", "title", "icon", "url");
25 Bookmark.defaultValue("icon", function () BookmarkCache.getFavicon(this.url));
26 update(Bookmark.prototype, {
27     get extra() [
28         ["keyword", this.keyword,         "Keyword"],
29         ["tags",    this.tags.join(", "), "Tag"]
30     ].filter(function (item) item[1]),
31
32     get uri() newURI(this.url),
33     set uri(uri) {
34         let tags = this.tags;
35         this.tags = null;
36         services.bookmarks.changeBookmarkURI(this.id, uri);
37         this.tags = tags;
38     },
39
40     encodeURIComponent: function _encodeURIComponent(str) {
41         if (!this.charset || this.charset === "UTF-8")
42             return encodeURIComponent(str);
43         let conv = services.CharsetConv(this.charset);
44         return escape(conv.ConvertFromUnicode(str) + conv.Finish()).replace(/\+/g, encodeURIComponent);
45     },
46
47     get folder() {
48         let res = [];
49         res.toString = function () this.join("/");
50
51         let id = this.id, parent, title;
52         while ((id    = services.bookmarks.getFolderIdForItem(id)) &&
53                (title = services.bookmarks.getItemTitle(id)))
54             res.push(title);
55
56         return res.reverse();
57     }
58 })
59 Bookmark.prototype.members.uri = Bookmark.prototype.members.url;
60 Bookmark.setter = function (key, func) this.prototype.__defineSetter__(key, func);
61 Bookmark.setter("url", function (val) { this.uri = isString(val) ? newURI(val) : val; });
62 Bookmark.setter("title", function (val) { services.bookmarks.setItemTitle(this.id, val); });
63 Bookmark.setter("post", function (val) { bookmarkcache.annotate(this.id, bookmarkcache.POST, val); });
64 Bookmark.setter("charset", function (val) { bookmarkcache.annotate(this.id, bookmarkcache.CHARSET, val); });
65 Bookmark.setter("keyword", function (val) { services.bookmarks.setKeywordForBookmark(this.id, val); });
66 Bookmark.setter("tags", function (val) {
67     services.tagging.untagURI(this.uri, null);
68     if (val)
69         services.tagging.tagURI(this.uri, val);
70 });
71
72 var name = "bookmark-cache";
73
74 var BookmarkCache = Module("BookmarkCache", XPCOM(Ci.nsINavBookmarkObserver), {
75     POST: "bookmarkProperties/POSTData",
76     CHARSET: "dactyl/charset",
77
78     init: function init() {
79         services.bookmarks.addObserver(this, false);
80     },
81
82     cleanup: function cleanup() {
83         services.bookmarks.removeObserver(this);
84     },
85
86     __iterator__: function () (val for ([, val] in Iterator(bookmarkcache.bookmarks))),
87
88     bookmarks: Class.Memoize(function () this.load()),
89
90     keywords: Class.Memoize(function () array.toObject([[b.keyword, b] for (b in this) if (b.keyword)])),
91
92     rootFolders: ["toolbarFolder", "bookmarksMenuFolder", "unfiledBookmarksFolder"]
93         .map(function (s) services.bookmarks[s]),
94
95     _deleteBookmark: function deleteBookmark(id) {
96         let result = this.bookmarks[id] || null;
97         delete this.bookmarks[id];
98         return result;
99     },
100
101     _loadBookmark: function loadBookmark(node) {
102         if (node.uri == null) // How does this happen?
103             return false;
104
105         let uri = newURI(node.uri);
106         let keyword = services.bookmarks.getKeywordForBookmark(node.itemId);
107
108         let tags = "tags" in node ? (node.tags ? node.tags.split(/, /g) : [])
109                                   : services.tagging.getTagsForURI(uri, {}) || [];
110
111         let post = BookmarkCache.getAnnotation(node.itemId, this.POST);
112         let charset = BookmarkCache.getAnnotation(node.itemId, this.CHARSET);
113         return Bookmark(node.uri, node.title, node.icon && node.icon.spec, post, keyword, tags, charset, node.itemId);
114     },
115
116     annotate: function (id, key, val, timespan) {
117         if (val)
118             services.annotation.setItemAnnotation(id, key, val, 0,
119                                                   timespan || services.annotation.EXPIRE_NEVER);
120         else if (services.annotation.itemHasAnnotation(id, key))
121             services.annotation.removeItemAnnotation(id, key);
122     },
123
124     get: function (url) {
125         let ids = services.bookmarks.getBookmarkIdsForURI(newURI(url), {});
126         for (let id in values(ids))
127             if (id in this.bookmarks)
128                 return this.bookmarks[id];
129         return null;
130     },
131
132     readBookmark: function readBookmark(id) ({
133         itemId: id,
134         uri:    services.bookmarks.getBookmarkURI(id).spec,
135         title:  services.bookmarks.getItemTitle(id)
136     }),
137
138     findRoot: function findRoot(id) {
139         do {
140             var root = id;
141             id = services.bookmarks.getFolderIdForItem(id);
142         } while (id != services.bookmarks.placesRoot && id != root);
143         return root;
144     },
145
146     isBookmark: function (id) this.rootFolders.indexOf(this.findRoot(id)) >= 0,
147
148     /**
149      * Returns true if the given URL is bookmarked and that bookmark is
150      * not a Live Bookmark.
151      *
152      * @param {nsIURI|string} url The URL of which to check the bookmarked
153      *     state.
154      * @returns {boolean}
155      */
156     isBookmarked: function isBookmarked(uri) {
157         if (isString(uri))
158             uri = newURI(uri);
159
160         try {
161             return services.bookmarks
162                            .getBookmarkIdsForURI(uri, {})
163                            .some(this.closure.isRegularBookmark);
164         }
165         catch (e) {
166             return false;
167         }
168     },
169
170     isRegularBookmark: function isRegularBookmark(id) {
171         do {
172             var root = id;
173             if (services.livemark && services.livemark.isLivemark(id))
174                 return false;
175             id = services.bookmarks.getFolderIdForItem(id);
176         } while (id != services.bookmarks.placesRoot && id != root);
177         return this.rootFolders.indexOf(root) >= 0;
178     },
179
180     load: function load() {
181         let bookmarks = {};
182
183         let query = services.history.getNewQuery();
184         let options = services.history.getNewQueryOptions();
185         options.queryType = options.QUERY_TYPE_BOOKMARKS;
186         try {
187             // https://bugzil.la/702639
188             options.excludeItemIfParentHasAnnotation = "livemark/feedURI";
189         }
190         catch (e) {}
191
192         let { root } = services.history.executeQuery(query, options);
193         root.containerOpen = true;
194         try {
195             // iterate over the immediate children of this folder
196             for (let i = 0; i < root.childCount; i++) {
197                 let node = root.getChild(i);
198                 if (node.type == node.RESULT_TYPE_URI) // bookmark
199                     bookmarks[node.itemId] = this._loadBookmark(node);
200             }
201         }
202         finally {
203             root.containerOpen = false;
204         }
205
206         return bookmarks;
207     },
208
209     onItemAdded: function onItemAdded(itemId, folder, index) {
210         if (services.bookmarks.getItemType(itemId) == services.bookmarks.TYPE_BOOKMARK) {
211             if (this.isBookmark(itemId)) {
212                 let bmark = this._loadBookmark(this.readBookmark(itemId));
213                 this.bookmarks[bmark.id] = bmark;
214                 storage.fireEvent(name, "add", bmark);
215                 delete this.keywords;
216             }
217         }
218     },
219     onItemRemoved: function onItemRemoved(itemId, folder, index) {
220         let result = this._deleteBookmark(itemId);
221         delete this.keywords;
222         if (result)
223             storage.fireEvent(name, "remove", result);
224     },
225     onItemChanged: function onItemChanged(itemId, property, isAnnotation, value) {
226         if (isAnnotation)
227             if (property === this.POST)
228                 [property, value] = ["post", BookmarkCache.getAnnotation(itemId, property)];
229             else if (property === this.CHARSET)
230                 [property, value] = ["charset", BookmarkCache.getAnnotation(itemId, property)];
231             else
232                 return;
233
234         let bookmark = this.bookmarks[itemId];
235         if (bookmark) {
236             if (property == "keyword")
237                 delete this.keywords;
238             if (property == "tags")
239                 value = services.tagging.getTagsForURI(bookmark.uri, {});
240             if (property in bookmark) {
241                 bookmark[bookmark.members[property]] = value;
242                 storage.fireEvent(name, "change", { __proto__: bookmark, changed: property });
243             }
244         }
245     }
246 }, {
247     DEFAULT_FAVICON: "chrome://mozapps/skin/places/defaultFavicon.png",
248
249     getAnnotation: function getAnnotation(item, anno)
250         services.annotation.itemHasAnnotation(item, anno) ?
251         services.annotation.getItemAnnotation(item, anno) : null,
252
253     getFavicon: function getFavicon(uri) {
254         try {
255             return services.favicon.getFaviconImageForPage(newURI(uri)).spec;
256         }
257         catch (e) {
258             return "";
259         }
260     }
261 });
262
263 endModule();
264
265 // vim: set fdm=marker sw=4 sts=4 et ft=javascript: