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