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