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
;
34 class BookmarkCodecTest
;
35 class BookmarkExpandedStateTracker
;
37 class BookmarkLoadDetails
;
38 class BookmarkModelObserver
;
39 class BookmarkStorage
;
40 class ScopedGroupBookmarkActions
;
41 class TestBookmarkClient
;
45 namespace favicon_base
{
46 struct FaviconImageResult
;
49 namespace query_parser
{
50 enum class MatchingAlgorithm
;
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(bookmarks::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(bookmarks::BookmarkModelObserver
* observer
);
116 void RemoveObserver(bookmarks::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
<bookmarks::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(
250 const base::string16
& text
,
252 query_parser::MatchingAlgorithm matching_algorithm
,
253 std::vector
<bookmarks::BookmarkMatch
>* matches
);
255 // Sets the store to NULL, making it so the BookmarkModel does not persist
256 // any changes to disk. This is only useful during testing to speed up
260 // Returns the next node ID.
261 int64
next_node_id() const { return next_node_id_
; }
263 // Returns the object responsible for tracking the set of expanded nodes in
264 // the bookmark editor.
265 bookmarks::BookmarkExpandedStateTracker
* expanded_state_tracker() {
266 return expanded_state_tracker_
.get();
269 // Sets the visibility of one of the permanent nodes (unless the node must
270 // always be visible, see |BookmarkClient::IsPermanentNodeVisible| for more
271 // details). This is set by sync.
272 void SetPermanentNodeVisible(BookmarkNode::Type type
, bool value
);
274 // Returns the permanent node of type |type|.
275 const BookmarkPermanentNode
* PermanentNode(BookmarkNode::Type type
);
277 // Sets/deletes meta info of |node|.
278 void SetNodeMetaInfo(const BookmarkNode
* node
,
279 const std::string
& key
,
280 const std::string
& value
);
281 void SetNodeMetaInfoMap(const BookmarkNode
* node
,
282 const BookmarkNode::MetaInfoMap
& meta_info_map
);
283 void DeleteNodeMetaInfo(const BookmarkNode
* node
,
284 const std::string
& key
);
286 // Adds |key| to the set of meta info keys that are not copied when a node is
288 void AddNonClonedKey(const std::string
& key
);
290 // Returns the set of meta info keys that should not be copied when a node is
292 const std::set
<std::string
>& non_cloned_keys() const {
293 return non_cloned_keys_
;
296 // Sets the sync transaction version of |node|.
297 void SetNodeSyncTransactionVersion(const BookmarkNode
* node
,
298 int64 sync_transaction_version
);
300 // Notify BookmarkModel that the favicons for |urls| have changed and have to
301 // be refetched. This notification is sent by BookmarkClient.
302 void OnFaviconChanged(const std::set
<GURL
>& urls
);
304 // Returns the client used by this BookmarkModel.
305 bookmarks::BookmarkClient
* client() const { return client_
; }
308 friend class bookmarks::BookmarkCodecTest
;
309 friend class bookmarks::BookmarkStorage
;
310 friend class bookmarks::ScopedGroupBookmarkActions
;
311 friend class bookmarks::TestBookmarkClient
;
313 // Used to order BookmarkNodes by URL.
314 class NodeURLComparator
{
316 bool operator()(const BookmarkNode
* n1
, const BookmarkNode
* n2
) const {
317 return n1
->url() < n2
->url();
321 // Implementation of IsBookmarked. Before calling this the caller must obtain
322 // a lock on |url_lock_|.
323 bool IsBookmarkedNoLock(const GURL
& url
);
325 // Removes the node from internal maps and recurses through all children. If
326 // the node is a url, its url is added to removed_urls.
328 // This does NOT delete the node.
329 void RemoveNode(BookmarkNode
* node
, std::set
<GURL
>* removed_urls
);
331 // Invoked when loading is finished. Sets |loaded_| and notifies observers.
332 // BookmarkModel takes ownership of |details|.
333 void DoneLoading(scoped_ptr
<bookmarks::BookmarkLoadDetails
> details
);
335 // Populates |nodes_ordered_by_url_set_| from root.
336 void PopulateNodesByURL(BookmarkNode
* node
);
338 // Removes the node from its parent, but does not delete it. No notifications
339 // are sent. |removed_urls| is populated with the urls which no longer have
340 // any bookmarks associated with them.
341 // This method should be called after acquiring |url_lock_|.
342 void RemoveNodeAndGetRemovedUrls(BookmarkNode
* node
,
343 std::set
<GURL
>* removed_urls
);
345 // Removes the node from its parent, sends notification, and deletes it.
346 // type specifies how the node should be removed.
347 void RemoveAndDeleteNode(BookmarkNode
* delete_me
);
349 // Remove |node| from |nodes_ordered_by_url_set_| and |index_|.
350 void RemoveNodeFromInternalMaps(BookmarkNode
* node
);
352 // Adds the |node| at |parent| in the specified |index| and notifies its
354 BookmarkNode
* AddNode(BookmarkNode
* parent
,
358 // Adds the |node| to |nodes_ordered_by_url_set_| and |index_|.
359 void AddNodeToInternalMaps(BookmarkNode
* node
);
361 // Returns true if the parent and index are valid.
362 bool IsValidIndex(const BookmarkNode
* parent
, int index
, bool allow_end
);
364 // Creates one of the possible permanent nodes (bookmark bar node, other node
365 // and mobile node) from |type|.
366 BookmarkPermanentNode
* CreatePermanentNode(BookmarkNode::Type type
);
368 // Notification that a favicon has finished loading. If we can decode the
369 // favicon, FaviconLoaded is invoked.
370 void OnFaviconDataAvailable(
372 favicon_base::IconType icon_type
,
373 const favicon_base::FaviconImageResult
& image_result
);
375 // Invoked from the node to load the favicon. Requests the favicon from the
377 void LoadFavicon(BookmarkNode
* node
, favicon_base::IconType icon_type
);
379 // Called to notify the observers that the favicon has been loaded.
380 void FaviconLoaded(const BookmarkNode
* node
);
382 // If we're waiting on a favicon for node, the load request is canceled.
383 void CancelPendingFaviconLoadRequests(BookmarkNode
* node
);
385 // Notifies the observers that a set of changes initiated by a single user
386 // action is about to happen and has completed.
387 void BeginGroupedChanges();
388 void EndGroupedChanges();
390 // Generates and returns the next node ID.
391 int64
generate_next_node_id();
393 // Sets the maximum node ID to the given value.
394 // This is used by BookmarkCodec to report the maximum ID after it's done
395 // decoding since during decoding codec assigns node IDs.
396 void set_next_node_id(int64 id
) { next_node_id_
= id
; }
398 // Creates and returns a new BookmarkLoadDetails. It's up to the caller to
399 // delete the returned object.
400 scoped_ptr
<bookmarks::BookmarkLoadDetails
> CreateLoadDetails(
401 const std::string
& accept_languages
);
403 bookmarks::BookmarkClient
* const client_
;
405 // Whether the initial set of data has been loaded.
408 // The root node. This contains the bookmark bar node, the 'other' node and
409 // the mobile node as children.
412 BookmarkPermanentNode
* bookmark_bar_node_
;
413 BookmarkPermanentNode
* other_node_
;
414 BookmarkPermanentNode
* mobile_node_
;
416 // The maximum ID assigned to the bookmark nodes in the model.
420 ObserverList
<bookmarks::BookmarkModelObserver
> observers_
;
422 // Set of nodes ordered by URL. This is not a map to avoid copying the
424 // WARNING: |nodes_ordered_by_url_set_| is accessed on multiple threads. As
425 // such, be sure and wrap all usage of it around |url_lock_|.
426 typedef std::multiset
<BookmarkNode
*, NodeURLComparator
> NodesOrderedByURLSet
;
427 NodesOrderedByURLSet nodes_ordered_by_url_set_
;
428 base::Lock url_lock_
;
430 // Used for loading favicons.
431 base::CancelableTaskTracker cancelable_task_tracker_
;
433 // Reads/writes bookmarks to disk.
434 scoped_ptr
<bookmarks::BookmarkStorage
> store_
;
436 scoped_ptr
<bookmarks::BookmarkIndex
> index_
;
438 base::WaitableEvent loaded_signal_
;
440 // See description of IsDoingExtensiveChanges above.
441 int extensive_changes_
;
443 scoped_ptr
<bookmarks::BookmarkExpandedStateTracker
> expanded_state_tracker_
;
445 std::set
<std::string
> non_cloned_keys_
;
447 DISALLOW_COPY_AND_ASSIGN(BookmarkModel
);
450 #endif // COMPONENTS_BOOKMARKS_BROWSER_BOOKMARK_MODEL_H_