1 // Copyright (c) 2012 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 #include "chrome/browser/android/provider/chrome_browser_provider.h"
11 #include "base/android/jni_android.h"
12 #include "base/android/jni_array.h"
13 #include "base/android/jni_string.h"
14 #include "base/logging.h"
15 #include "base/memory/ref_counted_memory.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/task/cancelable_task_tracker.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/android/provider/blocking_ui_thread_async_request.h"
20 #include "chrome/browser/android/provider/bookmark_model_observer_task.h"
21 #include "chrome/browser/android/provider/run_on_ui_thread_blocking.h"
22 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
23 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
24 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
25 #include "chrome/browser/browser_process.h"
26 #include "chrome/browser/favicon/favicon_service_factory.h"
27 #include "chrome/browser/history/android/sqlite_cursor.h"
28 #include "chrome/browser/history/history_service_factory.h"
29 #include "chrome/browser/history/top_sites_factory.h"
30 #include "chrome/browser/profiles/profile.h"
31 #include "chrome/browser/profiles/profile_manager.h"
32 #include "chrome/browser/search_engines/template_url_service_factory.h"
33 #include "components/bookmarks/browser/bookmark_model.h"
34 #include "components/bookmarks/browser/bookmark_utils.h"
35 #include "components/favicon/core/favicon_service.h"
36 #include "components/history/core/browser/android/android_history_types.h"
37 #include "components/history/core/browser/history_service.h"
38 #include "components/history/core/browser/top_sites.h"
39 #include "components/search_engines/template_url.h"
40 #include "components/search_engines/template_url_service.h"
41 #include "content/public/browser/browser_thread.h"
42 #include "jni/ChromeBrowserProvider_jni.h"
43 #include "sql/statement.h"
44 #include "ui/base/layout.h"
45 #include "ui/base/resource/resource_bundle.h"
46 #include "ui/gfx/favicon_size.h"
48 using base::android::AttachCurrentThread
;
49 using base::android::CheckException
;
50 using base::android::ClearException
;
51 using base::android::ConvertJavaStringToUTF16
;
52 using base::android::ConvertJavaStringToUTF8
;
53 using base::android::ConvertUTF8ToJavaString
;
54 using base::android::ConvertUTF16ToJavaString
;
55 using base::android::GetClass
;
56 using base::android::MethodID
;
57 using base::android::JavaRef
;
58 using base::android::ScopedJavaGlobalRef
;
59 using base::android::ScopedJavaLocalRef
;
60 using bookmarks::BookmarkModel
;
61 using bookmarks::BookmarkNode
;
62 using content::BrowserThread
;
64 // After refactoring the following class hierarchy has been created in order
65 // to avoid repeating code again for the same basic kind of tasks, to enforce
66 // the correct thread usage and to prevent known race conditions and deadlocks.
68 // - RunOnUIThreadBlocking: auxiliary class to run methods in the UI thread
69 // blocking the current one until finished. Because of the provider threading
70 // expectations this cannot be used from the UI thread.
72 // - BookmarkModelTask: base class for all tasks that operate in any way with
73 // the bookmark model. This class ensures that the model is loaded and
74 // prevents possible deadlocks. Derived classes should make use of
75 // RunOnUIThreadBlocking to perform any manipulation of the bookmark model in
76 // the UI thread. The Run method of these tasks cannot be invoked directly
77 // from the UI thread, but RunOnUIThread can be safely used from the UI
78 // thread code of other BookmarkModelTasks.
80 // - AsyncServiceRequest: base class for any asynchronous requests made to a
81 // Chromium service that require to block the current thread until completed.
82 // Derived classes should make use of RunAsyncRequestOnUIThreadBlocking to
83 // post their requests in the UI thread and return the results synchronously.
84 // All derived classes MUST ALWAYS call RequestCompleted when receiving the
85 // request response. These tasks cannot be invoked from the UI thread.
87 // - FaviconServiceTask: base class for asynchronous requests that make use of
88 // Chromium's favicon service. See AsyncServiceRequest for more details.
90 // - HistoryProviderTask: base class for asynchronous requests that make use of
91 // AndroidHistoryProviderService. See AsyncServiceRequest for mode details.
93 // - SearchTermTask: base class for asynchronous requests that involve the
94 // search term API. Works in the same way as HistoryProviderTask.
98 const char kDefaultUrlScheme
[] = "http://";
99 const int64 kInvalidContentProviderId
= 0;
100 const int64 kInvalidBookmarkId
= -1;
102 // ------------- Java-related utility methods ------------- //
104 // Convert a BookmarkNode, |node|, to the java representation of a bookmark node
105 // stored in |*jnode|. Parent node information is optional.
106 void ConvertBookmarkNode(
107 const BookmarkNode
* node
,
108 const JavaRef
<jobject
>& parent_node
,
109 ScopedJavaGlobalRef
<jobject
>* jnode
) {
114 JNIEnv
* env
= AttachCurrentThread();
115 ScopedJavaLocalRef
<jstring
> url
;
117 url
.Reset(ConvertUTF8ToJavaString(env
, node
->url().spec()));
118 ScopedJavaLocalRef
<jstring
> title(
119 ConvertUTF16ToJavaString(env
, node
->GetTitle()));
122 Java_BookmarkNode_create(
123 env
, node
->id(), (jint
) node
->type(), title
.obj(), url
.obj(),
127 jlong
ConvertJLongObjectToPrimitive(JNIEnv
* env
, jobject long_obj
) {
128 ScopedJavaLocalRef
<jclass
> jlong_clazz
= GetClass(env
, "java/lang/Long");
129 jmethodID long_value
= MethodID::Get
<MethodID::TYPE_INSTANCE
>(
130 env
, jlong_clazz
.obj(), "longValue", "()J");
131 return env
->CallLongMethod(long_obj
, long_value
, NULL
);
134 jboolean
ConvertJBooleanObjectToPrimitive(JNIEnv
* env
, jobject boolean_object
) {
135 ScopedJavaLocalRef
<jclass
> jboolean_clazz
=
136 GetClass(env
, "java/lang/Boolean");
137 jmethodID boolean_value
= MethodID::Get
<MethodID::TYPE_INSTANCE
>(
138 env
, jboolean_clazz
.obj(), "booleanValue", "()Z");
139 return env
->CallBooleanMethod(boolean_object
, boolean_value
, NULL
);
142 base::Time
ConvertJlongToTime(jlong value
) {
143 return base::Time::UnixEpoch() +
144 base::TimeDelta::FromMilliseconds((int64
)value
);
147 jint
ConvertJIntegerToJint(JNIEnv
* env
, jobject integer_obj
) {
148 ScopedJavaLocalRef
<jclass
> jinteger_clazz
=
149 GetClass(env
, "java/lang/Integer");
150 jmethodID int_value
= MethodID::Get
<MethodID::TYPE_INSTANCE
>(
151 env
, jinteger_clazz
.obj(), "intValue", "()I");
152 return env
->CallIntMethod(integer_obj
, int_value
, NULL
);
155 std::vector
<base::string16
> ConvertJStringArrayToString16Array(
157 jobjectArray array
) {
158 std::vector
<base::string16
> results
;
160 jsize len
= env
->GetArrayLength(array
);
161 for (int i
= 0; i
< len
; i
++) {
162 results
.push_back(ConvertJavaStringToUTF16(env
,
163 static_cast<jstring
>(env
->GetObjectArrayElement(array
, i
))));
169 // ------------- Utility methods used by tasks ------------- //
171 // Parse the given url and return a GURL, appending the default scheme
172 // if one is not present.
173 GURL
ParseAndMaybeAppendScheme(const base::string16
& url
,
174 const char* default_scheme
) {
176 if (!gurl
.is_valid() && !gurl
.has_scheme()) {
177 base::string16
refined_url(base::ASCIIToUTF16(default_scheme
));
178 refined_url
.append(url
);
179 gurl
= GURL(refined_url
);
184 const BookmarkNode
* GetChildFolderByTitle(const BookmarkNode
* parent
,
185 const base::string16
& title
) {
186 for (int i
= 0; i
< parent
->child_count(); ++i
) {
187 if (parent
->GetChild(i
)->is_folder() &&
188 parent
->GetChild(i
)->GetTitle() == title
) {
189 return parent
->GetChild(i
);
195 // ------------- Synchronous task classes ------------- //
197 // Utility task to add a bookmark.
198 class AddBookmarkTask
: public BookmarkModelTask
{
200 explicit AddBookmarkTask(BookmarkModel
* model
) : BookmarkModelTask(model
) {}
202 int64
Run(const base::string16
& title
,
203 const base::string16
& url
,
204 const bool is_folder
,
205 const int64 parent_id
) {
206 int64 result
= kInvalidBookmarkId
;
207 RunOnUIThreadBlocking::Run(
208 base::Bind(&AddBookmarkTask::RunOnUIThread
,
209 model(), title
, url
, is_folder
, parent_id
, &result
));
213 static void RunOnUIThread(BookmarkModel
* model
,
214 const base::string16
& title
,
215 const base::string16
& url
,
216 const bool is_folder
,
217 const int64 parent_id
,
219 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
221 GURL gurl
= ParseAndMaybeAppendScheme(url
, kDefaultUrlScheme
);
223 // Check if the bookmark already exists.
224 const BookmarkNode
* node
= model
->GetMostRecentlyAddedUserNodeForURL(gurl
);
226 const BookmarkNode
* parent_node
= NULL
;
228 parent_node
= bookmarks::GetBookmarkNodeByID(model
, parent_id
);
230 parent_node
= model
->bookmark_bar_node();
233 node
= model
->AddFolder(parent_node
, parent_node
->child_count(), title
);
235 node
= model
->AddURL(parent_node
, 0, title
, gurl
);
238 *result
= node
? node
->id() : kInvalidBookmarkId
;
242 DISALLOW_COPY_AND_ASSIGN(AddBookmarkTask
);
245 // Utility method to remove a bookmark.
246 class RemoveBookmarkTask
: public BookmarkModelObserverTask
{
248 explicit RemoveBookmarkTask(BookmarkModel
* model
)
249 : BookmarkModelObserverTask(model
),
251 id_to_delete_(kInvalidBookmarkId
) {}
252 ~RemoveBookmarkTask() override
{}
254 int Run(const int64 id
) {
256 RunOnUIThreadBlocking::Run(
257 base::Bind(&RemoveBookmarkTask::RunOnUIThread
, model(), id
));
261 static void RunOnUIThread(BookmarkModel
* model
, const int64 id
) {
262 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
263 const BookmarkNode
* node
= bookmarks::GetBookmarkNodeByID(model
, id
);
264 if (node
&& node
->parent()) {
265 const BookmarkNode
* parent_node
= node
->parent();
266 model
->Remove(parent_node
, parent_node
->GetIndexOf(node
));
270 // Verify that the bookmark was actually removed. Called synchronously.
271 void BookmarkNodeRemoved(BookmarkModel
* bookmark_model
,
272 const BookmarkNode
* parent
,
274 const BookmarkNode
* node
,
275 const std::set
<GURL
>& removed_urls
) override
{
276 if (bookmark_model
== model() && node
->id() == id_to_delete_
)
284 DISALLOW_COPY_AND_ASSIGN(RemoveBookmarkTask
);
287 // Utility method to remove all bookmarks that the user can edit.
288 class RemoveAllUserBookmarksTask
: public BookmarkModelObserverTask
{
290 explicit RemoveAllUserBookmarksTask(BookmarkModel
* model
)
291 : BookmarkModelObserverTask(model
) {}
293 ~RemoveAllUserBookmarksTask() override
{}
296 RunOnUIThreadBlocking::Run(
297 base::Bind(&RemoveAllUserBookmarksTask::RunOnUIThread
, model()));
300 static void RunOnUIThread(BookmarkModel
* model
) {
301 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
302 LOG(ERROR
) << "begin model->RemoveAllUserBookmarks";
303 model
->RemoveAllUserBookmarks();
304 LOG(ERROR
) << "after model->RemoveAllUserBookmarks";
308 DISALLOW_COPY_AND_ASSIGN(RemoveAllUserBookmarksTask
);
311 // Utility method to update a bookmark.
312 class UpdateBookmarkTask
: public BookmarkModelObserverTask
{
314 explicit UpdateBookmarkTask(BookmarkModel
* model
)
315 : BookmarkModelObserverTask(model
),
317 id_to_update_(kInvalidBookmarkId
){}
318 ~UpdateBookmarkTask() override
{}
320 int Run(const int64 id
,
321 const base::string16
& title
,
322 const base::string16
& url
,
323 const int64 parent_id
) {
325 RunOnUIThreadBlocking::Run(
326 base::Bind(&UpdateBookmarkTask::RunOnUIThread
,
327 model(), id
, title
, url
, parent_id
));
331 static void RunOnUIThread(BookmarkModel
* model
,
333 const base::string16
& title
,
334 const base::string16
& url
,
335 const int64 parent_id
) {
336 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
337 const BookmarkNode
* node
= bookmarks::GetBookmarkNodeByID(model
, id
);
339 if (node
->GetTitle() != title
)
340 model
->SetTitle(node
, title
);
342 if (node
->type() == BookmarkNode::URL
) {
343 GURL bookmark_url
= ParseAndMaybeAppendScheme(url
, kDefaultUrlScheme
);
344 if (bookmark_url
!= node
->url())
345 model
->SetURL(node
, bookmark_url
);
348 if (parent_id
>= 0 &&
349 (!node
->parent() || parent_id
!= node
->parent()->id())) {
350 const BookmarkNode
* new_parent
=
351 bookmarks::GetBookmarkNodeByID(model
, parent_id
);
354 model
->Move(node
, new_parent
, 0);
359 // Verify that the bookmark was actually updated. Called synchronously.
360 void BookmarkNodeChanged(BookmarkModel
* bookmark_model
,
361 const BookmarkNode
* node
) override
{
362 if (bookmark_model
== model() && node
->id() == id_to_update_
)
370 DISALLOW_COPY_AND_ASSIGN(UpdateBookmarkTask
);
373 // Checks if a node exists in the bookmark model.
374 class BookmarkNodeExistsTask
: public BookmarkModelTask
{
376 explicit BookmarkNodeExistsTask(BookmarkModel
* model
)
377 : BookmarkModelTask(model
) {
380 bool Run(const int64 id
) {
382 RunOnUIThreadBlocking::Run(
383 base::Bind(&BookmarkNodeExistsTask::RunOnUIThread
,
384 model(), id
, &result
));
388 static void RunOnUIThread(BookmarkModel
* model
,
391 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
393 *result
= bookmarks::GetBookmarkNodeByID(model
, id
) != NULL
;
397 DISALLOW_COPY_AND_ASSIGN(BookmarkNodeExistsTask
);
400 // Checks if a node belongs to the Mobile Bookmarks hierarchy branch.
401 class IsInMobileBookmarksBranchTask
: public BookmarkModelTask
{
403 explicit IsInMobileBookmarksBranchTask(BookmarkModel
* model
)
404 : BookmarkModelTask(model
) {}
406 bool Run(const int64 id
) {
408 RunOnUIThreadBlocking::Run(
409 base::Bind(&IsInMobileBookmarksBranchTask::RunOnUIThread
,
410 model(), id
, &result
));
414 static void RunOnUIThread(BookmarkModel
* model
,
417 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
419 const BookmarkNode
* node
= bookmarks::GetBookmarkNodeByID(model
, id
);
420 const BookmarkNode
* mobile_node
= model
->mobile_node();
421 while (node
&& node
!= mobile_node
)
422 node
= node
->parent();
424 *result
= node
== mobile_node
;
428 DISALLOW_COPY_AND_ASSIGN(IsInMobileBookmarksBranchTask
);
431 // Creates folder or retrieves its id if already exists.
432 // An invalid parent id is assumed to represent the Mobile Bookmarks folder.
433 // Can only be used to create folders inside the Mobile Bookmarks branch.
434 class CreateBookmarksFolderOnceTask
: public BookmarkModelTask
{
436 explicit CreateBookmarksFolderOnceTask(BookmarkModel
* model
)
437 : BookmarkModelTask(model
) {}
439 int64
Run(const base::string16
& title
, const int64 parent_id
) {
440 int64 result
= kInvalidBookmarkId
;
441 RunOnUIThreadBlocking::Run(
442 base::Bind(&CreateBookmarksFolderOnceTask::RunOnUIThread
,
443 model(), title
, parent_id
, &result
));
447 static void RunOnUIThread(BookmarkModel
* model
,
448 const base::string16
& title
,
449 const int64 parent_id
,
451 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
454 // Invalid ids are assumed to refer to the Mobile Bookmarks folder.
455 const BookmarkNode
* parent
=
456 parent_id
>= 0 ? bookmarks::GetBookmarkNodeByID(model
, parent_id
)
457 : model
->mobile_node();
460 bool in_mobile_bookmarks
;
461 IsInMobileBookmarksBranchTask::RunOnUIThread(model
, parent
->id(),
462 &in_mobile_bookmarks
);
463 if (!in_mobile_bookmarks
) {
464 // The parent folder must be inside the Mobile Bookmarks folder.
465 *result
= kInvalidBookmarkId
;
469 const BookmarkNode
* node
= GetChildFolderByTitle(parent
, title
);
471 *result
= node
->id();
475 AddBookmarkTask::RunOnUIThread(model
, title
, base::string16(), true,
476 parent
->id(), result
);
480 DISALLOW_COPY_AND_ASSIGN(CreateBookmarksFolderOnceTask
);
483 // Creates a Java BookmarkNode object for a node given its id.
484 class GetEditableBookmarkFoldersTask
: public BookmarkModelTask
{
486 GetEditableBookmarkFoldersTask(ChromeBookmarkClient
* client
,
487 BookmarkModel
* model
)
488 : BookmarkModelTask(model
), client_(client
) {}
490 void Run(ScopedJavaGlobalRef
<jobject
>* jroot
) {
491 RunOnUIThreadBlocking::Run(
492 base::Bind(&GetEditableBookmarkFoldersTask::RunOnUIThread
,
493 client_
, model(), jroot
));
496 static void RunOnUIThread(ChromeBookmarkClient
* client
,
497 BookmarkModel
* model
,
498 ScopedJavaGlobalRef
<jobject
>* jroot
) {
499 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
500 const BookmarkNode
* root
= model
->root_node();
501 if (!root
|| !root
->is_folder())
504 // The iterative approach is not possible because ScopedGlobalJavaRefs
505 // cannot be copy-constructed, and therefore not used in STL containers.
506 ConvertFolderSubtree(client
, AttachCurrentThread(), root
,
507 ScopedJavaLocalRef
<jobject
>(), jroot
);
511 static void ConvertFolderSubtree(ChromeBookmarkClient
* client
,
513 const BookmarkNode
* node
,
514 const JavaRef
<jobject
>& parent_folder
,
515 ScopedJavaGlobalRef
<jobject
>* jfolder
) {
517 DCHECK(node
->is_folder());
520 // Global refs should be used here for thread-safety reasons as this task
521 // might be invoked from a thread other than UI. All refs are scoped.
522 ConvertBookmarkNode(node
, parent_folder
, jfolder
);
524 for (int i
= 0; i
< node
->child_count(); ++i
) {
525 const BookmarkNode
* child
= node
->GetChild(i
);
526 if (child
->is_folder() && client
->CanBeEditedByUser(child
)) {
527 ScopedJavaGlobalRef
<jobject
> jchild
;
528 ConvertFolderSubtree(client
, env
, child
, *jfolder
, &jchild
);
530 Java_BookmarkNode_addChild(env
, jfolder
->obj(), jchild
.obj());
531 if (ClearException(env
)) {
532 LOG(WARNING
) << "Java exception while adding child node.";
539 ChromeBookmarkClient
* client_
;
541 DISALLOW_COPY_AND_ASSIGN(GetEditableBookmarkFoldersTask
);
544 // Creates a Java BookmarkNode object for a node given its id.
545 class GetBookmarkNodeTask
: public BookmarkModelTask
{
547 explicit GetBookmarkNodeTask(BookmarkModel
* model
)
548 : BookmarkModelTask(model
) {
551 void Run(const int64 id
,
554 ScopedJavaGlobalRef
<jobject
>* jnode
) {
555 return RunOnUIThreadBlocking::Run(
556 base::Bind(&GetBookmarkNodeTask::RunOnUIThread
,
557 model(), id
, get_parent
, get_children
, jnode
));
560 static void RunOnUIThread(BookmarkModel
* model
,
564 ScopedJavaGlobalRef
<jobject
>* jnode
) {
565 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
566 const BookmarkNode
* node
= bookmarks::GetBookmarkNodeByID(model
, id
);
570 ScopedJavaGlobalRef
<jobject
> jparent
;
572 ConvertBookmarkNode(node
->parent(), ScopedJavaLocalRef
<jobject
>(),
576 ConvertBookmarkNode(node
, jparent
, jnode
);
578 JNIEnv
* env
= AttachCurrentThread();
579 if (!jparent
.is_null()) {
580 Java_BookmarkNode_addChild(env
, jparent
.obj(), jnode
->obj());
581 if (ClearException(env
)) {
582 LOG(WARNING
) << "Java exception while adding child node.";
588 for (int i
= 0; i
< node
->child_count(); ++i
) {
589 ScopedJavaGlobalRef
<jobject
> jchild
;
590 ConvertBookmarkNode(node
->GetChild(i
), *jnode
, &jchild
);
591 Java_BookmarkNode_addChild(env
, jnode
->obj(), jchild
.obj());
592 if (ClearException(env
)) {
593 LOG(WARNING
) << "Java exception while adding child node.";
601 DISALLOW_COPY_AND_ASSIGN(GetBookmarkNodeTask
);
604 // Gets the Mobile Bookmarks node. Using this task ensures the correct
605 // initialization of the bookmark model.
606 class GetMobileBookmarksNodeTask
: public BookmarkModelTask
{
608 explicit GetMobileBookmarksNodeTask(BookmarkModel
* model
)
609 : BookmarkModelTask(model
) {}
611 const BookmarkNode
* Run() {
612 const BookmarkNode
* result
= NULL
;
613 RunOnUIThreadBlocking::Run(
614 base::Bind(&GetMobileBookmarksNodeTask::RunOnUIThread
,
619 static void RunOnUIThread(BookmarkModel
* model
, const BookmarkNode
** result
) {
620 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
622 *result
= model
->mobile_node();
626 DISALLOW_COPY_AND_ASSIGN(GetMobileBookmarksNodeTask
);
629 // ------------- Aynchronous requests classes ------------- //
631 // Base class for asynchronous blocking requests to Chromium services.
632 // Service: type of the service to use (e.g. HistoryService, FaviconService).
633 template <typename Service
>
634 class AsyncServiceRequest
: protected BlockingUIThreadAsyncRequest
{
636 AsyncServiceRequest(Service
* service
,
637 base::CancelableTaskTracker
* cancelable_tracker
)
638 : service_(service
), cancelable_tracker_(cancelable_tracker
) {}
640 Service
* service() const { return service_
; }
642 base::CancelableTaskTracker
* cancelable_tracker() const {
643 return cancelable_tracker_
;
648 base::CancelableTaskTracker
* cancelable_tracker_
;
650 DISALLOW_COPY_AND_ASSIGN(AsyncServiceRequest
);
653 // Base class for all asynchronous blocking tasks that use the favicon service.
654 class FaviconServiceTask
: public AsyncServiceRequest
<favicon::FaviconService
> {
656 FaviconServiceTask(base::CancelableTaskTracker
* cancelable_tracker
,
658 favicon::FaviconService
* favicon_service
)
659 : AsyncServiceRequest
<favicon::FaviconService
>(favicon_service
,
663 Profile
* profile() const { return profile_
; }
668 DISALLOW_COPY_AND_ASSIGN(FaviconServiceTask
);
671 // Retrieves the favicon or touch icon for a URL from the FaviconService.
672 class BookmarkIconFetchTask
: public FaviconServiceTask
{
674 BookmarkIconFetchTask(base::CancelableTaskTracker
* cancelable_tracker
,
676 favicon::FaviconService
* favicon_service
)
677 : FaviconServiceTask(cancelable_tracker
, profile
, favicon_service
) {}
679 favicon_base::FaviconRawBitmapResult
Run(const GURL
& url
) {
680 float max_scale
= ui::GetScaleForScaleFactor(
681 ResourceBundle::GetSharedInstance().GetMaxScaleFactor());
682 int desired_size_in_pixel
= std::ceil(gfx::kFaviconSize
* max_scale
);
684 if (service() == NULL
)
685 return favicon_base::FaviconRawBitmapResult();
687 RunAsyncRequestOnUIThreadBlocking(base::Bind(
688 &favicon::FaviconService::GetRawFaviconForPageURL
,
689 base::Unretained(service()), url
,
690 favicon_base::FAVICON
| favicon_base::TOUCH_ICON
, desired_size_in_pixel
,
691 base::Bind(&BookmarkIconFetchTask::OnFaviconRetrieved
,
692 base::Unretained(this)),
693 cancelable_tracker()));
698 void OnFaviconRetrieved(
699 const favicon_base::FaviconRawBitmapResult
& bitmap_result
) {
700 result_
= bitmap_result
;
704 favicon_base::FaviconRawBitmapResult result_
;
706 DISALLOW_COPY_AND_ASSIGN(BookmarkIconFetchTask
);
709 // Base class for all asynchronous blocking tasks that use the Android history
711 class HistoryProviderTask
712 : public AsyncServiceRequest
<AndroidHistoryProviderService
> {
714 HistoryProviderTask(AndroidHistoryProviderService
* service
,
715 base::CancelableTaskTracker
* cancelable_tracker
)
716 : AsyncServiceRequest
<AndroidHistoryProviderService
>(service
,
717 cancelable_tracker
) {
721 DISALLOW_COPY_AND_ASSIGN(HistoryProviderTask
);
724 // Adds a bookmark from the API.
725 class AddBookmarkFromAPITask
: public HistoryProviderTask
{
727 AddBookmarkFromAPITask(AndroidHistoryProviderService
* service
,
728 base::CancelableTaskTracker
* cancelable_tracker
)
729 : HistoryProviderTask(service
, cancelable_tracker
) {}
731 history::URLID
Run(const history::HistoryAndBookmarkRow
& row
) {
732 RunAsyncRequestOnUIThreadBlocking(
733 base::Bind(&AndroidHistoryProviderService::InsertHistoryAndBookmark
,
734 base::Unretained(service()),
736 base::Bind(&AddBookmarkFromAPITask::OnBookmarkInserted
,
737 base::Unretained(this)),
738 cancelable_tracker()));
743 void OnBookmarkInserted(history::URLID id
) {
744 // Note that here 0 means an invalid id.
745 // This is because it represents a SQLite database row id.
750 history::URLID result_
;
752 DISALLOW_COPY_AND_ASSIGN(AddBookmarkFromAPITask
);
755 // Queries bookmarks from the API.
756 class QueryBookmarksFromAPITask
: public HistoryProviderTask
{
758 QueryBookmarksFromAPITask(AndroidHistoryProviderService
* service
,
759 base::CancelableTaskTracker
* cancelable_tracker
)
760 : HistoryProviderTask(service
, cancelable_tracker
), result_(NULL
) {}
762 history::AndroidStatement
* Run(
763 const std::vector
<history::HistoryAndBookmarkRow::ColumnID
>& projections
,
764 const std::string
& selection
,
765 const std::vector
<base::string16
>& selection_args
,
766 const std::string
& sort_order
) {
767 RunAsyncRequestOnUIThreadBlocking(
768 base::Bind(&AndroidHistoryProviderService::QueryHistoryAndBookmarks
,
769 base::Unretained(service()),
774 base::Bind(&QueryBookmarksFromAPITask::OnBookmarksQueried
,
775 base::Unretained(this)),
776 cancelable_tracker()));
781 void OnBookmarksQueried(history::AndroidStatement
* statement
) {
786 history::AndroidStatement
* result_
;
788 DISALLOW_COPY_AND_ASSIGN(QueryBookmarksFromAPITask
);
791 // Updates bookmarks from the API.
792 class UpdateBookmarksFromAPITask
: public HistoryProviderTask
{
794 UpdateBookmarksFromAPITask(AndroidHistoryProviderService
* service
,
795 base::CancelableTaskTracker
* cancelable_tracker
)
796 : HistoryProviderTask(service
, cancelable_tracker
), result_(0) {}
798 int Run(const history::HistoryAndBookmarkRow
& row
,
799 const std::string
& selection
,
800 const std::vector
<base::string16
>& selection_args
) {
801 RunAsyncRequestOnUIThreadBlocking(
802 base::Bind(&AndroidHistoryProviderService::UpdateHistoryAndBookmarks
,
803 base::Unretained(service()),
807 base::Bind(&UpdateBookmarksFromAPITask::OnBookmarksUpdated
,
808 base::Unretained(this)),
809 cancelable_tracker()));
814 void OnBookmarksUpdated(int updated_row_count
) {
815 result_
= updated_row_count
;
821 DISALLOW_COPY_AND_ASSIGN(UpdateBookmarksFromAPITask
);
824 // Removes bookmarks from the API.
825 class RemoveBookmarksFromAPITask
: public HistoryProviderTask
{
827 RemoveBookmarksFromAPITask(AndroidHistoryProviderService
* service
,
828 base::CancelableTaskTracker
* cancelable_tracker
)
829 : HistoryProviderTask(service
, cancelable_tracker
), result_(0) {}
831 int Run(const std::string
& selection
,
832 const std::vector
<base::string16
>& selection_args
) {
833 RunAsyncRequestOnUIThreadBlocking(
834 base::Bind(&AndroidHistoryProviderService::DeleteHistoryAndBookmarks
,
835 base::Unretained(service()),
838 base::Bind(&RemoveBookmarksFromAPITask::OnBookmarksRemoved
,
839 base::Unretained(this)),
840 cancelable_tracker()));
845 void OnBookmarksRemoved(int removed_row_count
) {
846 result_
= removed_row_count
;
852 DISALLOW_COPY_AND_ASSIGN(RemoveBookmarksFromAPITask
);
855 // Removes history from the API.
856 class RemoveHistoryFromAPITask
: public HistoryProviderTask
{
858 RemoveHistoryFromAPITask(AndroidHistoryProviderService
* service
,
859 base::CancelableTaskTracker
* cancelable_tracker
)
860 : HistoryProviderTask(service
, cancelable_tracker
), result_(0) {}
862 int Run(const std::string
& selection
,
863 const std::vector
<base::string16
>& selection_args
) {
864 RunAsyncRequestOnUIThreadBlocking(
865 base::Bind(&AndroidHistoryProviderService::DeleteHistory
,
866 base::Unretained(service()),
869 base::Bind(&RemoveHistoryFromAPITask::OnHistoryRemoved
,
870 base::Unretained(this)),
871 cancelable_tracker()));
876 void OnHistoryRemoved(int removed_row_count
) {
877 result_
= removed_row_count
;
883 DISALLOW_COPY_AND_ASSIGN(RemoveHistoryFromAPITask
);
886 // This class provides the common method for the SearchTermAPIHelper.
887 class SearchTermTask
: public HistoryProviderTask
{
889 SearchTermTask(AndroidHistoryProviderService
* service
,
890 base::CancelableTaskTracker
* cancelable_tracker
,
892 : HistoryProviderTask(service
, cancelable_tracker
), profile_(profile
) {}
894 // Fill SearchRow's keyword_id and url fields according the given
895 // search_term. Return true if succeeded.
896 void BuildSearchRow(history::SearchRow
* row
) {
897 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
899 TemplateURLService
* template_service
=
900 TemplateURLServiceFactory::GetForProfile(profile_
);
901 template_service
->Load();
903 const TemplateURL
* search_engine
=
904 template_service
->GetDefaultSearchProvider();
906 const TemplateURLRef
* search_url
= &search_engine
->url_ref();
907 TemplateURLRef::SearchTermsArgs
search_terms_args(row
->search_term());
908 search_terms_args
.append_extra_query_params
= true;
909 std::string url
= search_url
->ReplaceSearchTerms(
910 search_terms_args
, template_service
->search_terms_data());
912 row
->set_url(GURL(url
));
913 row
->set_keyword_id(search_engine
->id());
921 DISALLOW_COPY_AND_ASSIGN(SearchTermTask
);
924 // Adds a search term from the API.
925 class AddSearchTermFromAPITask
: public SearchTermTask
{
927 AddSearchTermFromAPITask(AndroidHistoryProviderService
* service
,
928 base::CancelableTaskTracker
* cancelable_tracker
,
930 : SearchTermTask(service
, cancelable_tracker
, profile
) {}
932 history::URLID
Run(const history::SearchRow
& row
) {
933 RunAsyncRequestOnUIThreadBlocking(
934 base::Bind(&AddSearchTermFromAPITask::MakeRequestOnUIThread
,
935 base::Unretained(this), row
));
940 void MakeRequestOnUIThread(const history::SearchRow
& row
) {
941 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
942 history::SearchRow internal_row
= row
;
943 BuildSearchRow(&internal_row
);
944 service()->InsertSearchTerm(
946 base::Bind(&AddSearchTermFromAPITask::OnSearchTermInserted
,
947 base::Unretained(this)),
948 cancelable_tracker());
951 void OnSearchTermInserted(history::URLID id
) {
952 // Note that here 0 means an invalid id.
953 // This is because it represents a SQLite database row id.
958 history::URLID result_
;
960 DISALLOW_COPY_AND_ASSIGN(AddSearchTermFromAPITask
);
963 // Queries search terms from the API.
964 class QuerySearchTermsFromAPITask
: public SearchTermTask
{
966 QuerySearchTermsFromAPITask(AndroidHistoryProviderService
* service
,
967 base::CancelableTaskTracker
* cancelable_tracker
,
969 : SearchTermTask(service
, cancelable_tracker
, profile
), result_(NULL
) {}
971 history::AndroidStatement
* Run(
972 const std::vector
<history::SearchRow::ColumnID
>& projections
,
973 const std::string
& selection
,
974 const std::vector
<base::string16
>& selection_args
,
975 const std::string
& sort_order
) {
976 RunAsyncRequestOnUIThreadBlocking(base::Bind(
977 &AndroidHistoryProviderService::QuerySearchTerms
,
978 base::Unretained(service()),
983 base::Bind(&QuerySearchTermsFromAPITask::OnSearchTermsQueried
,
984 base::Unretained(this)),
985 cancelable_tracker()));
990 // Callback to return the result.
991 void OnSearchTermsQueried(history::AndroidStatement
* statement
) {
996 history::AndroidStatement
* result_
;
998 DISALLOW_COPY_AND_ASSIGN(QuerySearchTermsFromAPITask
);
1001 // Updates search terms from the API.
1002 class UpdateSearchTermsFromAPITask
: public SearchTermTask
{
1004 UpdateSearchTermsFromAPITask(AndroidHistoryProviderService
* service
,
1005 base::CancelableTaskTracker
* cancelable_tracker
,
1007 : SearchTermTask(service
, cancelable_tracker
, profile
), result_(0) {}
1009 int Run(const history::SearchRow
& row
,
1010 const std::string
& selection
,
1011 const std::vector
<base::string16
>& selection_args
) {
1012 RunAsyncRequestOnUIThreadBlocking(
1013 base::Bind(&UpdateSearchTermsFromAPITask::MakeRequestOnUIThread
,
1014 base::Unretained(this), row
, selection
, selection_args
));
1019 void MakeRequestOnUIThread(
1020 const history::SearchRow
& row
,
1021 const std::string
& selection
,
1022 const std::vector
<base::string16
>& selection_args
) {
1023 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1024 history::SearchRow internal_row
= row
;
1025 BuildSearchRow(&internal_row
);
1026 service()->UpdateSearchTerms(
1030 base::Bind(&UpdateSearchTermsFromAPITask::OnSearchTermsUpdated
,
1031 base::Unretained(this)),
1032 cancelable_tracker());
1035 void OnSearchTermsUpdated(int updated_row_count
) {
1036 result_
= updated_row_count
;
1042 DISALLOW_COPY_AND_ASSIGN(UpdateSearchTermsFromAPITask
);
1045 // Removes search terms from the API.
1046 class RemoveSearchTermsFromAPITask
: public SearchTermTask
{
1048 RemoveSearchTermsFromAPITask(AndroidHistoryProviderService
* service
,
1049 base::CancelableTaskTracker
* cancelable_tracker
,
1051 : SearchTermTask(service
, cancelable_tracker
, profile
), result_() {}
1053 int Run(const std::string
& selection
,
1054 const std::vector
<base::string16
>& selection_args
) {
1055 RunAsyncRequestOnUIThreadBlocking(base::Bind(
1056 &AndroidHistoryProviderService::DeleteSearchTerms
,
1057 base::Unretained(service()),
1060 base::Bind(&RemoveSearchTermsFromAPITask::OnSearchTermsDeleted
,
1061 base::Unretained(this)),
1062 cancelable_tracker()));
1067 void OnSearchTermsDeleted(int deleted_row_count
) {
1068 result_
= deleted_row_count
;
1074 DISALLOW_COPY_AND_ASSIGN(RemoveSearchTermsFromAPITask
);
1077 // ------------- Other utility methods (may use tasks) ------------- //
1079 // Fills the bookmark |row| with the given java objects.
1080 void FillBookmarkRow(JNIEnv
* env
,
1090 history::HistoryAndBookmarkRow
* row
,
1091 BookmarkModel
* model
) {
1092 // Needed because of the internal bookmark model task invocation.
1093 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI
));
1096 base::string16 raw_url
= ConvertJavaStringToUTF16(env
, url
);
1097 // GURL doesn't accept the URL without protocol, but the Android CTS
1098 // allows it. We are trying to prefix with 'http://' to see whether
1099 // GURL thinks it is a valid URL. The original url will be stored in
1100 // history::BookmarkRow.raw_url_.
1101 GURL gurl
= ParseAndMaybeAppendScheme(raw_url
, kDefaultUrlScheme
);
1103 row
->set_raw_url(base::UTF16ToUTF8(raw_url
));
1107 row
->set_created(ConvertJlongToTime(
1108 ConvertJLongObjectToPrimitive(env
, created
)));
1111 row
->set_is_bookmark(ConvertJBooleanObjectToPrimitive(env
, isBookmark
));
1114 row
->set_last_visit_time(ConvertJlongToTime(ConvertJLongObjectToPrimitive(
1118 std::vector
<uint8
> bytes
;
1119 base::android::JavaByteArrayToByteVector(env
, favicon
, &bytes
);
1120 row
->set_favicon(base::RefCountedBytes::TakeVector(&bytes
));
1124 row
->set_title(ConvertJavaStringToUTF16(env
, title
));
1127 row
->set_visit_count(ConvertJIntegerToJint(env
, visits
));
1129 // Make sure parent_id is always in the mobile_node branch.
1130 IsInMobileBookmarksBranchTask
task(model
);
1131 if (task
.Run(parent_id
))
1132 row
->set_parent_id(parent_id
);
1135 // Fills the bookmark |row| with the given java objects if it is not null.
1136 void FillSearchRow(JNIEnv
* env
,
1138 jstring search_term
,
1140 history::SearchRow
* row
) {
1142 row
->set_search_term(ConvertJavaStringToUTF16(env
, search_term
));
1145 row
->set_search_time(ConvertJlongToTime(ConvertJLongObjectToPrimitive(
1151 // ------------- Native initialization and destruction ------------- //
1153 static jlong
Init(JNIEnv
* env
, jobject obj
) {
1154 ChromeBrowserProvider
* provider
= new ChromeBrowserProvider(env
, obj
);
1155 return reinterpret_cast<intptr_t>(provider
);
1158 bool ChromeBrowserProvider::RegisterChromeBrowserProvider(JNIEnv
* env
) {
1159 return RegisterNativesImpl(env
);
1162 ChromeBrowserProvider::ChromeBrowserProvider(JNIEnv
* env
, jobject obj
)
1163 : weak_java_provider_(env
, obj
),
1164 history_service_observer_(this),
1165 handling_extensive_changes_(false) {
1166 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1167 profile_
= g_browser_process
->profile_manager()->GetLastUsedProfile();
1168 bookmark_model_
= BookmarkModelFactory::GetForProfile(profile_
);
1169 top_sites_
= TopSitesFactory::GetForProfile(profile_
);
1170 favicon_service_
= FaviconServiceFactory::GetForProfile(
1171 profile_
, ServiceAccessType::EXPLICIT_ACCESS
),
1172 service_
.reset(new AndroidHistoryProviderService(profile_
));
1174 // Register as observer for service we are interested.
1175 bookmark_model_
->AddObserver(this);
1176 history_service_observer_
.Add(HistoryServiceFactory::GetForProfile(
1177 profile_
, ServiceAccessType::EXPLICIT_ACCESS
));
1178 TemplateURLService
* template_service
=
1179 TemplateURLServiceFactory::GetForProfile(profile_
);
1180 if (!template_service
->loaded())
1181 template_service
->Load();
1184 ChromeBrowserProvider::~ChromeBrowserProvider() {
1185 bookmark_model_
->RemoveObserver(this);
1188 void ChromeBrowserProvider::Destroy(JNIEnv
*, jobject
) {
1189 history_service_observer_
.RemoveAll();
1193 // ------------- Provider public APIs ------------- //
1195 jlong
ChromeBrowserProvider::AddBookmark(JNIEnv
* env
,
1203 url
= ConvertJavaStringToUTF16(env
, jurl
);
1204 base::string16 title
= ConvertJavaStringToUTF16(env
, jtitle
);
1206 AddBookmarkTask
task(bookmark_model_
);
1207 return task
.Run(title
, url
, is_folder
, parent_id
);
1210 jint
ChromeBrowserProvider::RemoveBookmark(JNIEnv
*, jobject
, jlong id
) {
1211 RemoveBookmarkTask
task(bookmark_model_
);
1212 return task
.Run(id
);
1215 jint
ChromeBrowserProvider::UpdateBookmark(JNIEnv
* env
,
1223 url
= ConvertJavaStringToUTF16(env
, jurl
);
1224 base::string16 title
= ConvertJavaStringToUTF16(env
, jtitle
);
1226 UpdateBookmarkTask
task(bookmark_model_
);
1227 return task
.Run(id
, title
, url
, parent_id
);
1230 // Add the bookmark with the given column values.
1231 jlong
ChromeBrowserProvider::AddBookmarkFromAPI(JNIEnv
* env
,
1243 history::HistoryAndBookmarkRow row
;
1244 FillBookmarkRow(env
, obj
, url
, created
, isBookmark
, date
, favicon
, title
,
1245 visits
, parent_id
, &row
, bookmark_model_
);
1247 // URL must be valid.
1248 if (row
.url().is_empty()) {
1249 LOG(ERROR
) << "Not a valid URL " << row
.raw_url();
1250 return kInvalidContentProviderId
;
1253 AddBookmarkFromAPITask
task(service_
.get(), &cancelable_task_tracker_
);
1254 return task
.Run(row
);
1257 ScopedJavaLocalRef
<jobject
> ChromeBrowserProvider::QueryBookmarkFromAPI(
1260 jobjectArray projection
,
1262 jobjectArray selection_args
,
1263 jstring sort_order
) {
1264 // Converts the projection to array of ColumnID and column name.
1265 // Used to store the projection column ID according their sequence.
1266 std::vector
<history::HistoryAndBookmarkRow::ColumnID
> query_columns
;
1267 // Used to store the projection column names according their sequence.
1268 std::vector
<std::string
> columns_name
;
1270 jsize len
= env
->GetArrayLength(projection
);
1271 for (int i
= 0; i
< len
; i
++) {
1272 std::string name
= ConvertJavaStringToUTF8(env
, static_cast<jstring
>(
1273 env
->GetObjectArrayElement(projection
, i
)));
1274 history::HistoryAndBookmarkRow::ColumnID id
=
1275 history::HistoryAndBookmarkRow::GetColumnID(name
);
1276 if (id
== history::HistoryAndBookmarkRow::COLUMN_END
) {
1277 // Ignore the unknown column; As Android platform will send us
1278 // the non public column.
1281 query_columns
.push_back(id
);
1282 columns_name
.push_back(name
);
1286 std::vector
<base::string16
> where_args
=
1287 ConvertJStringArrayToString16Array(env
, selection_args
);
1289 std::string where_clause
;
1291 where_clause
= ConvertJavaStringToUTF8(env
, selections
);
1294 std::string sort_clause
;
1296 sort_clause
= ConvertJavaStringToUTF8(env
, sort_order
);
1299 QueryBookmarksFromAPITask
task(service_
.get(), &cancelable_task_tracker_
);
1300 history::AndroidStatement
* statement
= task
.Run(
1301 query_columns
, where_clause
, where_args
, sort_clause
);
1303 return ScopedJavaLocalRef
<jobject
>();
1305 // Creates and returns org.chromium.chrome.browser.database.SQLiteCursor
1307 return SQLiteCursor::NewJavaSqliteCursor(env
, columns_name
, statement
,
1311 // Updates the bookmarks with the given column values. The value is not given if
1313 jint
ChromeBrowserProvider::UpdateBookmarkFromAPI(JNIEnv
* env
,
1324 jobjectArray selection_args
) {
1325 history::HistoryAndBookmarkRow row
;
1326 FillBookmarkRow(env
, obj
, url
, created
, isBookmark
, date
, favicon
, title
,
1327 visits
, parent_id
, &row
, bookmark_model_
);
1329 std::vector
<base::string16
> where_args
=
1330 ConvertJStringArrayToString16Array(env
, selection_args
);
1332 std::string where_clause
;
1334 where_clause
= ConvertJavaStringToUTF8(env
, selections
);
1336 UpdateBookmarksFromAPITask
task(service_
.get(), &cancelable_task_tracker_
);
1337 return task
.Run(row
, where_clause
, where_args
);
1340 jint
ChromeBrowserProvider::RemoveBookmarkFromAPI(JNIEnv
* env
,
1343 jobjectArray selection_args
) {
1344 std::vector
<base::string16
> where_args
=
1345 ConvertJStringArrayToString16Array(env
, selection_args
);
1347 std::string where_clause
;
1349 where_clause
= ConvertJavaStringToUTF8(env
, selections
);
1351 RemoveBookmarksFromAPITask
task(service_
.get(), &cancelable_task_tracker_
);
1352 return task
.Run(where_clause
, where_args
);
1355 jint
ChromeBrowserProvider::RemoveHistoryFromAPI(JNIEnv
* env
,
1358 jobjectArray selection_args
) {
1359 std::vector
<base::string16
> where_args
=
1360 ConvertJStringArrayToString16Array(env
, selection_args
);
1362 std::string where_clause
;
1364 where_clause
= ConvertJavaStringToUTF8(env
, selections
);
1366 RemoveHistoryFromAPITask
task(service_
.get(), &cancelable_task_tracker_
);
1367 return task
.Run(where_clause
, where_args
);
1370 // Add the search term with the given column values. The value is not given if
1372 jlong
ChromeBrowserProvider::AddSearchTermFromAPI(JNIEnv
* env
,
1374 jstring search_term
,
1376 DCHECK(search_term
);
1378 history::SearchRow row
;
1379 FillSearchRow(env
, obj
, search_term
, date
, &row
);
1381 // URL must be valid.
1382 if (row
.search_term().empty()) {
1383 LOG(ERROR
) << "Search term is empty.";
1384 return kInvalidContentProviderId
;
1387 AddSearchTermFromAPITask
task(service_
.get(),
1388 &cancelable_task_tracker_
,
1390 return task
.Run(row
);
1393 ScopedJavaLocalRef
<jobject
> ChromeBrowserProvider::QuerySearchTermFromAPI(
1396 jobjectArray projection
,
1398 jobjectArray selection_args
,
1399 jstring sort_order
) {
1400 // Converts the projection to array of ColumnID and column name.
1401 // Used to store the projection column ID according their sequence.
1402 std::vector
<history::SearchRow::ColumnID
> query_columns
;
1403 // Used to store the projection column names according their sequence.
1404 std::vector
<std::string
> columns_name
;
1406 jsize len
= env
->GetArrayLength(projection
);
1407 for (int i
= 0; i
< len
; i
++) {
1408 std::string name
= ConvertJavaStringToUTF8(env
, static_cast<jstring
>(
1409 env
->GetObjectArrayElement(projection
, i
)));
1410 history::SearchRow::ColumnID id
=
1411 history::SearchRow::GetColumnID(name
);
1412 if (id
== history::SearchRow::COLUMN_END
) {
1413 LOG(ERROR
) << "Can not find " << name
;
1414 return ScopedJavaLocalRef
<jobject
>();
1416 query_columns
.push_back(id
);
1417 columns_name
.push_back(name
);
1421 std::vector
<base::string16
> where_args
=
1422 ConvertJStringArrayToString16Array(env
, selection_args
);
1424 std::string where_clause
;
1426 where_clause
= ConvertJavaStringToUTF8(env
, selections
);
1429 std::string sort_clause
;
1431 sort_clause
= ConvertJavaStringToUTF8(env
, sort_order
);
1434 QuerySearchTermsFromAPITask
task(service_
.get(),
1435 &cancelable_task_tracker_
,
1437 history::AndroidStatement
* statement
= task
.Run(
1438 query_columns
, where_clause
, where_args
, sort_clause
);
1440 return ScopedJavaLocalRef
<jobject
>();
1441 // Creates and returns org.chromium.chrome.browser.database.SQLiteCursor
1443 return SQLiteCursor::NewJavaSqliteCursor(env
, columns_name
, statement
,
1447 // Updates the search terms with the given column values. The value is not
1448 // given if it is NULL.
1449 jint
ChromeBrowserProvider::UpdateSearchTermFromAPI(
1450 JNIEnv
* env
, jobject obj
, jstring search_term
, jobject date
,
1451 jstring selections
, jobjectArray selection_args
) {
1452 history::SearchRow row
;
1453 FillSearchRow(env
, obj
, search_term
, date
, &row
);
1455 std::vector
<base::string16
> where_args
= ConvertJStringArrayToString16Array(
1456 env
, selection_args
);
1458 std::string where_clause
;
1460 where_clause
= ConvertJavaStringToUTF8(env
, selections
);
1462 UpdateSearchTermsFromAPITask
task(service_
.get(),
1463 &cancelable_task_tracker_
,
1465 return task
.Run(row
, where_clause
, where_args
);
1468 jint
ChromeBrowserProvider::RemoveSearchTermFromAPI(
1469 JNIEnv
* env
, jobject obj
, jstring selections
, jobjectArray selection_args
) {
1470 std::vector
<base::string16
> where_args
=
1471 ConvertJStringArrayToString16Array(env
, selection_args
);
1473 std::string where_clause
;
1475 where_clause
= ConvertJavaStringToUTF8(env
, selections
);
1477 RemoveSearchTermsFromAPITask
task(service_
.get(),
1478 &cancelable_task_tracker_
,
1480 return task
.Run(where_clause
, where_args
);
1483 // ------------- Provider custom APIs ------------- //
1485 jboolean
ChromeBrowserProvider::BookmarkNodeExists(
1489 BookmarkNodeExistsTask
task(bookmark_model_
);
1490 return task
.Run(id
);
1493 jlong
ChromeBrowserProvider::CreateBookmarksFolderOnce(
1498 base::string16 title
= ConvertJavaStringToUTF16(env
, jtitle
);
1500 return kInvalidBookmarkId
;
1502 CreateBookmarksFolderOnceTask
task(bookmark_model_
);
1503 return task
.Run(title
, parent_id
);
1506 ScopedJavaLocalRef
<jobject
> ChromeBrowserProvider::GetEditableBookmarkFolders(
1509 ScopedJavaGlobalRef
<jobject
> jroot
;
1510 ChromeBookmarkClient
* client
=
1511 ChromeBookmarkClientFactory::GetForProfile(profile_
);
1512 BookmarkModel
* model
= BookmarkModelFactory::GetForProfile(profile_
);
1513 GetEditableBookmarkFoldersTask
task(client
, model
);
1515 return ScopedJavaLocalRef
<jobject
>(jroot
);
1518 void ChromeBrowserProvider::RemoveAllUserBookmarks(JNIEnv
* env
, jobject obj
) {
1519 LOG(ERROR
) << "begin ChromeBrowserProvider::RemoveAllUserBookmarks";
1520 RemoveAllUserBookmarksTask
task(bookmark_model_
);
1522 LOG(ERROR
) << "end ChromeBrowserProvider::RemoveAllUserBookmarks";
1525 ScopedJavaLocalRef
<jobject
> ChromeBrowserProvider::GetBookmarkNode(
1526 JNIEnv
* env
, jobject obj
, jlong id
, jboolean get_parent
,
1527 jboolean get_children
) {
1528 ScopedJavaGlobalRef
<jobject
> jnode
;
1529 GetBookmarkNodeTask
task(bookmark_model_
);
1530 task
.Run(id
, get_parent
, get_children
, &jnode
);
1531 return ScopedJavaLocalRef
<jobject
>(jnode
);
1534 ScopedJavaLocalRef
<jobject
> ChromeBrowserProvider::GetMobileBookmarksFolder(
1537 ScopedJavaGlobalRef
<jobject
> jnode
;
1538 GetMobileBookmarksNodeTask
task(bookmark_model_
);
1539 ConvertBookmarkNode(task
.Run(), ScopedJavaLocalRef
<jobject
>(), &jnode
);
1540 return ScopedJavaLocalRef
<jobject
>(jnode
);
1543 jboolean
ChromeBrowserProvider::IsBookmarkInMobileBookmarksBranch(
1547 IsInMobileBookmarksBranchTask
task(bookmark_model_
);
1548 return task
.Run(id
);
1551 ScopedJavaLocalRef
<jbyteArray
> ChromeBrowserProvider::GetFaviconOrTouchIcon(
1552 JNIEnv
* env
, jobject obj
, jstring jurl
) {
1554 return ScopedJavaLocalRef
<jbyteArray
>();
1556 GURL url
= GURL(ConvertJavaStringToUTF16(env
, jurl
));
1557 BookmarkIconFetchTask
favicon_task(&cancelable_task_tracker_
, profile_
,
1559 favicon_base::FaviconRawBitmapResult bitmap_result
= favicon_task
.Run(url
);
1561 if (!bitmap_result
.is_valid() || !bitmap_result
.bitmap_data
.get())
1562 return ScopedJavaLocalRef
<jbyteArray
>();
1564 return base::android::ToJavaByteArray(env
, bitmap_result
.bitmap_data
->front(),
1565 bitmap_result
.bitmap_data
->size());
1568 ScopedJavaLocalRef
<jbyteArray
> ChromeBrowserProvider::GetThumbnail(
1569 JNIEnv
* env
, jobject obj
, jstring jurl
) {
1571 return ScopedJavaLocalRef
<jbyteArray
>();
1572 GURL url
= GURL(ConvertJavaStringToUTF16(env
, jurl
));
1574 // GetPageThumbnail is synchronous and can be called from any thread.
1575 scoped_refptr
<base::RefCountedMemory
> thumbnail
;
1577 top_sites_
->GetPageThumbnail(url
, false, &thumbnail
);
1579 if (!thumbnail
.get() || !thumbnail
->front()) {
1580 return ScopedJavaLocalRef
<jbyteArray
>();
1583 return base::android::ToJavaByteArray(env
, thumbnail
->front(),
1587 // ------------- Observer-related methods ------------- //
1589 void ChromeBrowserProvider::ExtensiveBookmarkChangesBeginning(
1590 BookmarkModel
* model
) {
1591 handling_extensive_changes_
= true;
1594 void ChromeBrowserProvider::ExtensiveBookmarkChangesEnded(
1595 BookmarkModel
* model
) {
1596 handling_extensive_changes_
= false;
1597 BookmarkModelChanged();
1600 void ChromeBrowserProvider::BookmarkModelChanged() {
1601 if (handling_extensive_changes_
)
1604 JNIEnv
* env
= AttachCurrentThread();
1605 ScopedJavaLocalRef
<jobject
> obj
= weak_java_provider_
.get(env
);
1609 Java_ChromeBrowserProvider_onBookmarkChanged(env
, obj
.obj());
1612 void ChromeBrowserProvider::OnHistoryChanged() {
1613 JNIEnv
* env
= AttachCurrentThread();
1614 ScopedJavaLocalRef
<jobject
> obj
= weak_java_provider_
.get(env
);
1617 Java_ChromeBrowserProvider_onHistoryChanged(env
, obj
.obj());
1620 void ChromeBrowserProvider::OnURLVisited(
1621 history::HistoryService
* history_service
,
1622 ui::PageTransition transition
,
1623 const history::URLRow
& row
,
1624 const history::RedirectList
& redirects
,
1625 base::Time visit_time
) {
1629 void ChromeBrowserProvider::OnURLsDeleted(
1630 history::HistoryService
* history_service
,
1633 const history::URLRows
& deleted_rows
,
1634 const std::set
<GURL
>& favicon_urls
) {
1638 void ChromeBrowserProvider::OnKeywordSearchTermUpdated(
1639 history::HistoryService
* history_service
,
1640 const history::URLRow
& row
,
1641 history::KeywordID keyword_id
,
1642 const base::string16
& term
) {
1643 JNIEnv
* env
= AttachCurrentThread();
1644 ScopedJavaLocalRef
<jobject
> obj
= weak_java_provider_
.get(env
);
1647 Java_ChromeBrowserProvider_onSearchTermChanged(env
, obj
.obj());
1650 void ChromeBrowserProvider::OnKeywordSearchTermDeleted(
1651 history::HistoryService
* history_service
,
1652 history::URLID url_id
) {