1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_MODEL_H_
6 #define COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_MODEL_H_
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/observer_list.h"
17 #include "base/strings/string16.h"
18 #include "base/synchronization/lock.h"
19 #include "base/synchronization/waitable_event.h"
20 #include "components/bookmarks/browser/bookmark_client.h"
21 #include "components/bookmarks/browser/bookmark_node.h"
22 #include "components/keyed_service/core/keyed_service.h"
23 #include "ui/gfx/image/image.h"
30 class SequencedTaskRunner
;
33 namespace favicon_base
{
34 struct FaviconImageResult
;
37 namespace query_parser
{
38 enum class MatchingAlgorithm
;
43 class BookmarkCodecTest
;
44 class BookmarkExpandedStateTracker
;
46 class BookmarkLoadDetails
;
47 class BookmarkModelObserver
;
48 class BookmarkStorage
;
49 class ScopedGroupBookmarkActions
;
50 class TestBookmarkClient
;
53 // BookmarkModel --------------------------------------------------------------
55 // BookmarkModel provides a directed acyclic graph of URLs and folders.
56 // Three graphs are provided for the three entry points: those on the 'bookmarks
57 // bar', those in the 'other bookmarks' folder and those in the 'mobile' folder.
59 // An observer may be attached to observe relevant events.
61 // You should NOT directly create a BookmarkModel, instead go through the
62 // BookmarkModelFactory.
63 class BookmarkModel
: public KeyedService
{
70 explicit BookmarkModel(BookmarkClient
* client
);
71 ~BookmarkModel() override
;
74 void Shutdown() override
;
76 // Loads the bookmarks. This is called upon creation of the
77 // BookmarkModel. You need not invoke this directly.
78 // All load operations will be executed on |io_task_runner| and the completion
79 // callback will be called from |ui_task_runner|.
80 void Load(PrefService
* pref_service
,
81 const std::string
& accept_languages
,
82 const base::FilePath
& profile_path
,
83 const scoped_refptr
<base::SequencedTaskRunner
>& io_task_runner
,
84 const scoped_refptr
<base::SequencedTaskRunner
>& ui_task_runner
);
86 // Returns true if the model finished loading.
87 bool loaded() const { return loaded_
; }
89 // Returns the root node. The 'bookmark bar' node and 'other' node are
90 // children of the root node.
91 const BookmarkNode
* root_node() const { return &root_
; }
93 // Returns the 'bookmark bar' node. This is NULL until loaded.
94 const BookmarkNode
* bookmark_bar_node() const { return bookmark_bar_node_
; }
96 // Returns the 'other' node. This is NULL until loaded.
97 const BookmarkNode
* other_node() const { return other_node_
; }
99 // Returns the 'mobile' node. This is NULL until loaded.
100 const BookmarkNode
* mobile_node() const { return mobile_node_
; }
102 bool is_root_node(const BookmarkNode
* node
) const { return node
== &root_
; }
104 // Returns whether the given |node| is one of the permanent nodes - root node,
105 // 'bookmark bar' node, 'other' node or 'mobile' node, or one of the root
106 // nodes supplied by the |client_|.
107 bool is_permanent_node(const BookmarkNode
* node
) const {
108 return node
&& (node
== &root_
|| node
->parent() == &root_
);
111 // Returns the parent the last node was added to. This never returns NULL
112 // (as long as the model is loaded).
113 const BookmarkNode
* GetParentForNewNodes();
115 void AddObserver(BookmarkModelObserver
* observer
);
116 void RemoveObserver(BookmarkModelObserver
* observer
);
118 // Notifies the observers that an extensive set of changes is about to happen,
119 // such as during import or sync, so they can delay any expensive UI updates
120 // until it's finished.
121 void BeginExtensiveChanges();
122 void EndExtensiveChanges();
124 // Returns true if this bookmark model is currently in a mode where extensive
125 // changes might happen, such as for import and sync. This is helpful for
126 // observers that are created after the mode has started, and want to check
127 // state during their own initializer, such as the NTP.
128 bool IsDoingExtensiveChanges() const { return extensive_changes_
> 0; }
130 // Removes the node at the given |index| from |parent|. Removing a folder node
131 // recursively removes all nodes. Observers are notified immediately.
132 void Remove(const BookmarkNode
* parent
, int index
);
134 // Removes all the non-permanent bookmark nodes that are editable by the user.
135 // Observers are only notified when all nodes have been removed. There is no
136 // notification for individual node removals.
137 void RemoveAllUserBookmarks();
139 // Moves |node| to |new_parent| and inserts it at the given |index|.
140 void Move(const BookmarkNode
* node
,
141 const BookmarkNode
* new_parent
,
144 // Inserts a copy of |node| into |new_parent| at |index|.
145 void Copy(const BookmarkNode
* node
,
146 const BookmarkNode
* new_parent
,
149 // Returns the favicon for |node|. If the favicon has not yet been
150 // loaded it is loaded and the observer of the model notified when done.
151 const gfx::Image
& GetFavicon(const BookmarkNode
* node
);
153 // Returns the type of the favicon for |node|. If the favicon has not yet
154 // been loaded, it returns |favicon_base::INVALID_ICON|.
155 favicon_base::IconType
GetFaviconType(const BookmarkNode
* node
);
157 // Sets the title of |node|.
158 void SetTitle(const BookmarkNode
* node
, const base::string16
& title
);
160 // Sets the URL of |node|.
161 void SetURL(const BookmarkNode
* node
, const GURL
& url
);
163 // Sets the date added time of |node|.
164 void SetDateAdded(const BookmarkNode
* node
, base::Time date_added
);
166 // Returns the set of nodes with the |url|.
167 void GetNodesByURL(const GURL
& url
, std::vector
<const BookmarkNode
*>* nodes
);
169 // Returns the most recently added user node for the |url|; urls from any
170 // nodes that are not editable by the user are never returned by this call.
171 // Returns NULL if |url| is not bookmarked.
172 const BookmarkNode
* GetMostRecentlyAddedUserNodeForURL(const GURL
& url
);
174 // Returns true if there are bookmarks, otherwise returns false.
175 // This method is thread safe.
178 // Returns true if the specified URL is bookmarked.
180 // If not on the main thread you *must* invoke BlockTillLoaded first.
181 bool IsBookmarked(const GURL
& url
);
183 // Returns, by reference in |bookmarks|, the set of bookmarked urls and their
184 // titles. This returns the unique set of URLs. For example, if two bookmarks
185 // reference the same URL only one entry is added not matter the titles are
188 // If not on the main thread you *must* invoke BlockTillLoaded first.
189 void GetBookmarks(std::vector
<BookmarkModel::URLAndTitle
>* urls
);
191 // Blocks until loaded. This is intended for usage on a thread other than
193 void BlockTillLoaded();
195 // Adds a new folder node at the specified position.
196 const BookmarkNode
* AddFolder(const BookmarkNode
* parent
,
198 const base::string16
& title
);
200 // Adds a new folder with meta info.
201 const BookmarkNode
* AddFolderWithMetaInfo(
202 const BookmarkNode
* parent
,
204 const base::string16
& title
,
205 const BookmarkNode::MetaInfoMap
* meta_info
);
207 // Adds a url at the specified position.
208 const BookmarkNode
* AddURL(const BookmarkNode
* parent
,
210 const base::string16
& title
,
213 // Adds a url with a specific creation date and meta info.
214 const BookmarkNode
* AddURLWithCreationTimeAndMetaInfo(
215 const BookmarkNode
* parent
,
217 const base::string16
& title
,
219 const base::Time
& creation_time
,
220 const BookmarkNode::MetaInfoMap
* meta_info
);
222 // Sorts the children of |parent|, notifying observers by way of the
223 // BookmarkNodeChildrenReordered method.
224 void SortChildren(const BookmarkNode
* parent
);
226 // Order the children of |parent| as specified in |ordered_nodes|. This
227 // function should only be used to reorder the child nodes of |parent| and
228 // is not meant to move nodes between different parent. Notifies observers
229 // using the BookmarkNodeChildrenReordered method.
230 void ReorderChildren(const BookmarkNode
* parent
,
231 const std::vector
<const BookmarkNode
*>& ordered_nodes
);
233 // Sets the date when the folder was modified.
234 void SetDateFolderModified(const BookmarkNode
* node
, const base::Time time
);
236 // Resets the 'date modified' time of the node to 0. This is used during
237 // importing to exclude the newly created folders from showing up in the
238 // combobox of most recently modified folders.
239 void ResetDateFolderModified(const BookmarkNode
* node
);
241 // Returns up to |max_count| of bookmarks containing each term from |text|
242 // in either the title or the URL. It uses default matching algorithm.
243 void GetBookmarksMatching(const base::string16
& text
,
245 std::vector
<BookmarkMatch
>* matches
);
247 // Returns up to |max_count| of bookmarks containing each term from |text|
248 // in either the title or the URL.
249 void GetBookmarksMatching(const base::string16
& text
,
251 query_parser::MatchingAlgorithm matching_algorithm
,
252 std::vector
<BookmarkMatch
>* matches
);
254 // Sets the store to NULL, making it so the BookmarkModel does not persist
255 // any changes to disk. This is only useful during testing to speed up
259 // Returns the next node ID.
260 int64
next_node_id() const { return next_node_id_
; }
262 // Returns the object responsible for tracking the set of expanded nodes in
263 // the bookmark editor.
264 BookmarkExpandedStateTracker
* expanded_state_tracker() {
265 return expanded_state_tracker_
.get();
268 // Sets the visibility of one of the permanent nodes (unless the node must
269 // always be visible, see |BookmarkClient::IsPermanentNodeVisible| for more
270 // details). This is set by sync.
271 void SetPermanentNodeVisible(BookmarkNode::Type type
, bool value
);
273 // Returns the permanent node of type |type|.
274 const BookmarkPermanentNode
* PermanentNode(BookmarkNode::Type type
);
276 // Sets/deletes meta info of |node|.
277 void SetNodeMetaInfo(const BookmarkNode
* node
,
278 const std::string
& key
,
279 const std::string
& value
);
280 void SetNodeMetaInfoMap(const BookmarkNode
* node
,
281 const BookmarkNode::MetaInfoMap
& meta_info_map
);
282 void DeleteNodeMetaInfo(const BookmarkNode
* node
,
283 const std::string
& key
);
285 // Adds |key| to the set of meta info keys that are not copied when a node is
287 void AddNonClonedKey(const std::string
& key
);
289 // Returns the set of meta info keys that should not be copied when a node is
291 const std::set
<std::string
>& non_cloned_keys() const {
292 return non_cloned_keys_
;
295 // Sets the sync transaction version of |node|.
296 void SetNodeSyncTransactionVersion(const BookmarkNode
* node
,
297 int64 sync_transaction_version
);
299 // Notify BookmarkModel that the favicons for |urls| have changed and have to
300 // be refetched. This notification is sent by BookmarkClient.
301 void OnFaviconChanged(const std::set
<GURL
>& urls
);
303 // Returns the client used by this BookmarkModel.
304 BookmarkClient
* client() const { return client_
; }
307 friend class BookmarkCodecTest
;
308 friend class BookmarkStorage
;
309 friend class ScopedGroupBookmarkActions
;
310 friend class TestBookmarkClient
;
312 // Used to order BookmarkNodes by URL.
313 class NodeURLComparator
{
315 bool operator()(const BookmarkNode
* n1
, const BookmarkNode
* n2
) const {
316 return n1
->url() < n2
->url();
320 // Implementation of IsBookmarked. Before calling this the caller must obtain
321 // a lock on |url_lock_|.
322 bool IsBookmarkedNoLock(const GURL
& url
);
324 // Removes the node from internal maps and recurses through all children. If
325 // the node is a url, its url is added to removed_urls.
327 // This does NOT delete the node.
328 void RemoveNode(BookmarkNode
* node
, std::set
<GURL
>* removed_urls
);
330 // Invoked when loading is finished. Sets |loaded_| and notifies observers.
331 // BookmarkModel takes ownership of |details|.
332 void DoneLoading(scoped_ptr
<BookmarkLoadDetails
> details
);
334 // Populates |nodes_ordered_by_url_set_| from root.
335 void PopulateNodesByURL(BookmarkNode
* node
);
337 // Removes the node from its parent, but does not delete it. No notifications
338 // are sent. |removed_urls| is populated with the urls which no longer have
339 // any bookmarks associated with them.
340 // This method should be called after acquiring |url_lock_|.
341 void RemoveNodeAndGetRemovedUrls(BookmarkNode
* node
,
342 std::set
<GURL
>* removed_urls
);
344 // Removes the node from its parent, sends notification, and deletes it.
345 // type specifies how the node should be removed.
346 void RemoveAndDeleteNode(BookmarkNode
* delete_me
);
348 // Remove |node| from |nodes_ordered_by_url_set_| and |index_|.
349 void RemoveNodeFromInternalMaps(BookmarkNode
* node
);
351 // Adds the |node| at |parent| in the specified |index| and notifies its
353 BookmarkNode
* AddNode(BookmarkNode
* parent
,
357 // Adds the |node| to |nodes_ordered_by_url_set_| and |index_|.
358 void AddNodeToInternalMaps(BookmarkNode
* node
);
360 // Returns true if the parent and index are valid.
361 bool IsValidIndex(const BookmarkNode
* parent
, int index
, bool allow_end
);
363 // Creates one of the possible permanent nodes (bookmark bar node, other node
364 // and mobile node) from |type|.
365 BookmarkPermanentNode
* CreatePermanentNode(BookmarkNode::Type type
);
367 // Notification that a favicon has finished loading. If we can decode the
368 // favicon, FaviconLoaded is invoked.
369 void OnFaviconDataAvailable(
371 favicon_base::IconType icon_type
,
372 const favicon_base::FaviconImageResult
& image_result
);
374 // Invoked from the node to load the favicon. Requests the favicon from the
376 void LoadFavicon(BookmarkNode
* node
, favicon_base::IconType icon_type
);
378 // Called to notify the observers that the favicon has been loaded.
379 void FaviconLoaded(const BookmarkNode
* node
);
381 // If we're waiting on a favicon for node, the load request is canceled.
382 void CancelPendingFaviconLoadRequests(BookmarkNode
* node
);
384 // Notifies the observers that a set of changes initiated by a single user
385 // action is about to happen and has completed.
386 void BeginGroupedChanges();
387 void EndGroupedChanges();
389 // Generates and returns the next node ID.
390 int64
generate_next_node_id();
392 // Sets the maximum node ID to the given value.
393 // This is used by BookmarkCodec to report the maximum ID after it's done
394 // decoding since during decoding codec assigns node IDs.
395 void set_next_node_id(int64 id
) { next_node_id_
= id
; }
397 // Creates and returns a new BookmarkLoadDetails. It's up to the caller to
398 // delete the returned object.
399 scoped_ptr
<BookmarkLoadDetails
> CreateLoadDetails(
400 const std::string
& accept_languages
);
402 BookmarkClient
* const client_
;
404 // Whether the initial set of data has been loaded.
407 // The root node. This contains the bookmark bar node, the 'other' node and
408 // the mobile node as children.
411 BookmarkPermanentNode
* bookmark_bar_node_
;
412 BookmarkPermanentNode
* other_node_
;
413 BookmarkPermanentNode
* mobile_node_
;
415 // The maximum ID assigned to the bookmark nodes in the model.
419 ObserverList
<BookmarkModelObserver
> observers_
;
421 // Set of nodes ordered by URL. This is not a map to avoid copying the
423 // WARNING: |nodes_ordered_by_url_set_| is accessed on multiple threads. As
424 // such, be sure and wrap all usage of it around |url_lock_|.
425 typedef std::multiset
<BookmarkNode
*, NodeURLComparator
> NodesOrderedByURLSet
;
426 NodesOrderedByURLSet nodes_ordered_by_url_set_
;
427 base::Lock url_lock_
;
429 // Used for loading favicons.
430 base::CancelableTaskTracker cancelable_task_tracker_
;
432 // Reads/writes bookmarks to disk.
433 scoped_ptr
<BookmarkStorage
> store_
;
435 scoped_ptr
<BookmarkIndex
> index_
;
437 base::WaitableEvent loaded_signal_
;
439 // See description of IsDoingExtensiveChanges above.
440 int extensive_changes_
;
442 scoped_ptr
<BookmarkExpandedStateTracker
> expanded_state_tracker_
;
444 std::set
<std::string
> non_cloned_keys_
;
446 DISALLOW_COPY_AND_ASSIGN(BookmarkModel
);
449 } // namespace bookmarks
451 #endif // COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_MODEL_H_