Switch global error menu icon to vectorized MD asset
[chromium-blink-merge.git] / chrome / browser / android / provider / chrome_browser_provider.cc
blob9040bae2cb8028f048586f4cb8939bef53f28dc7
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"
7 #include <cmath>
8 #include <list>
9 #include <utility>
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/managed_bookmark_service_factory.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/favicon/favicon_service_factory.h"
26 #include "chrome/browser/history/android/sqlite_cursor.h"
27 #include "chrome/browser/history/history_service_factory.h"
28 #include "chrome/browser/history/top_sites_factory.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/profiles/profile_manager.h"
31 #include "chrome/browser/search_engines/template_url_service_factory.h"
32 #include "components/bookmarks/browser/bookmark_model.h"
33 #include "components/bookmarks/browser/bookmark_utils.h"
34 #include "components/bookmarks/managed/managed_bookmark_service.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 "ui/base/layout.h"
44 #include "ui/base/resource/resource_bundle.h"
45 #include "ui/gfx/favicon_size.h"
47 using base::android::AttachCurrentThread;
48 using base::android::CheckException;
49 using base::android::ClearException;
50 using base::android::ConvertJavaStringToUTF16;
51 using base::android::ConvertJavaStringToUTF8;
52 using base::android::ConvertUTF8ToJavaString;
53 using base::android::ConvertUTF16ToJavaString;
54 using base::android::GetClass;
55 using base::android::MethodID;
56 using base::android::JavaRef;
57 using base::android::ScopedJavaGlobalRef;
58 using base::android::ScopedJavaLocalRef;
59 using bookmarks::BookmarkModel;
60 using bookmarks::BookmarkNode;
61 using bookmarks::ManagedBookmarkService;
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.
96 namespace {
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) {
110 DCHECK(jnode);
111 if (!node)
112 return;
114 JNIEnv* env = AttachCurrentThread();
115 ScopedJavaLocalRef<jstring> url;
116 if (node->is_url())
117 url.Reset(ConvertUTF8ToJavaString(env, node->url().spec()));
118 ScopedJavaLocalRef<jstring> title(
119 ConvertUTF16ToJavaString(env, node->GetTitle()));
121 jnode->Reset(
122 Java_BookmarkNode_create(
123 env, node->id(), (jint) node->type(), title.obj(), url.obj(),
124 parent_node.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(
156 JNIEnv* env,
157 jobjectArray array) {
158 std::vector<base::string16> results;
159 if (array) {
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))));
166 return results;
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) {
175 GURL gurl(url);
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);
181 return gurl;
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);
192 return NULL;
195 // ------------- Synchronous task classes ------------- //
197 // Utility task to add a bookmark.
198 class AddBookmarkTask : public BookmarkModelTask {
199 public:
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));
210 return 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,
218 int64* result) {
219 DCHECK_CURRENTLY_ON(BrowserThread::UI);
220 DCHECK(result);
221 GURL gurl = ParseAndMaybeAppendScheme(url, kDefaultUrlScheme);
223 // Check if the bookmark already exists.
224 const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(gurl);
225 if (!node) {
226 const BookmarkNode* parent_node = NULL;
227 if (parent_id >= 0)
228 parent_node = bookmarks::GetBookmarkNodeByID(model, parent_id);
229 if (!parent_node)
230 parent_node = model->bookmark_bar_node();
232 if (is_folder)
233 node = model->AddFolder(parent_node, parent_node->child_count(), title);
234 else
235 node = model->AddURL(parent_node, 0, title, gurl);
238 *result = node ? node ->id() : kInvalidBookmarkId;
241 private:
242 DISALLOW_COPY_AND_ASSIGN(AddBookmarkTask);
245 // Utility method to remove a bookmark.
246 class RemoveBookmarkTask : public BookmarkModelObserverTask {
247 public:
248 explicit RemoveBookmarkTask(BookmarkModel* model)
249 : BookmarkModelObserverTask(model),
250 deleted_(0),
251 id_to_delete_(kInvalidBookmarkId) {}
252 ~RemoveBookmarkTask() override {}
254 int Run(const int64 id) {
255 id_to_delete_ = id;
256 RunOnUIThreadBlocking::Run(
257 base::Bind(&RemoveBookmarkTask::RunOnUIThread, model(), id));
258 return deleted_;
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 model->Remove(node);
268 // Verify that the bookmark was actually removed. Called synchronously.
269 void BookmarkNodeRemoved(BookmarkModel* bookmark_model,
270 const BookmarkNode* parent,
271 int old_index,
272 const BookmarkNode* node,
273 const std::set<GURL>& removed_urls) override {
274 if (bookmark_model == model() && node->id() == id_to_delete_)
275 ++deleted_;
278 private:
279 int deleted_;
280 int64 id_to_delete_;
282 DISALLOW_COPY_AND_ASSIGN(RemoveBookmarkTask);
285 // Utility method to remove all bookmarks that the user can edit.
286 class RemoveAllUserBookmarksTask : public BookmarkModelObserverTask {
287 public:
288 explicit RemoveAllUserBookmarksTask(BookmarkModel* model)
289 : BookmarkModelObserverTask(model) {}
291 ~RemoveAllUserBookmarksTask() override {}
293 void Run() {
294 RunOnUIThreadBlocking::Run(
295 base::Bind(&RemoveAllUserBookmarksTask::RunOnUIThread, model()));
298 static void RunOnUIThread(BookmarkModel* model) {
299 DCHECK_CURRENTLY_ON(BrowserThread::UI);
300 LOG(ERROR) << "begin model->RemoveAllUserBookmarks";
301 model->RemoveAllUserBookmarks();
302 LOG(ERROR) << "after model->RemoveAllUserBookmarks";
305 private:
306 DISALLOW_COPY_AND_ASSIGN(RemoveAllUserBookmarksTask);
309 // Utility method to update a bookmark.
310 class UpdateBookmarkTask : public BookmarkModelObserverTask {
311 public:
312 explicit UpdateBookmarkTask(BookmarkModel* model)
313 : BookmarkModelObserverTask(model),
314 updated_(0),
315 id_to_update_(kInvalidBookmarkId){}
316 ~UpdateBookmarkTask() override {}
318 int Run(const int64 id,
319 const base::string16& title,
320 const base::string16& url,
321 const int64 parent_id) {
322 id_to_update_ = id;
323 RunOnUIThreadBlocking::Run(
324 base::Bind(&UpdateBookmarkTask::RunOnUIThread,
325 model(), id, title, url, parent_id));
326 return updated_;
329 static void RunOnUIThread(BookmarkModel* model,
330 const int64 id,
331 const base::string16& title,
332 const base::string16& url,
333 const int64 parent_id) {
334 DCHECK_CURRENTLY_ON(BrowserThread::UI);
335 const BookmarkNode* node = bookmarks::GetBookmarkNodeByID(model, id);
336 if (node) {
337 if (node->GetTitle() != title)
338 model->SetTitle(node, title);
340 if (node->type() == BookmarkNode::URL) {
341 GURL bookmark_url = ParseAndMaybeAppendScheme(url, kDefaultUrlScheme);
342 if (bookmark_url != node->url())
343 model->SetURL(node, bookmark_url);
346 if (parent_id >= 0 &&
347 (!node->parent() || parent_id != node->parent()->id())) {
348 const BookmarkNode* new_parent =
349 bookmarks::GetBookmarkNodeByID(model, parent_id);
351 if (new_parent)
352 model->Move(node, new_parent, 0);
357 // Verify that the bookmark was actually updated. Called synchronously.
358 void BookmarkNodeChanged(BookmarkModel* bookmark_model,
359 const BookmarkNode* node) override {
360 if (bookmark_model == model() && node->id() == id_to_update_)
361 ++updated_;
364 private:
365 int updated_;
366 int64 id_to_update_;
368 DISALLOW_COPY_AND_ASSIGN(UpdateBookmarkTask);
371 // Checks if a node exists in the bookmark model.
372 class BookmarkNodeExistsTask : public BookmarkModelTask {
373 public:
374 explicit BookmarkNodeExistsTask(BookmarkModel* model)
375 : BookmarkModelTask(model) {
378 bool Run(const int64 id) {
379 bool result = false;
380 RunOnUIThreadBlocking::Run(
381 base::Bind(&BookmarkNodeExistsTask::RunOnUIThread,
382 model(), id, &result));
383 return result;
386 static void RunOnUIThread(BookmarkModel* model,
387 const int64 id,
388 bool* result) {
389 DCHECK_CURRENTLY_ON(BrowserThread::UI);
390 DCHECK(result);
391 *result = bookmarks::GetBookmarkNodeByID(model, id) != NULL;
394 private:
395 DISALLOW_COPY_AND_ASSIGN(BookmarkNodeExistsTask);
398 // Checks if a node belongs to the Mobile Bookmarks hierarchy branch.
399 class IsInMobileBookmarksBranchTask : public BookmarkModelTask {
400 public:
401 explicit IsInMobileBookmarksBranchTask(BookmarkModel* model)
402 : BookmarkModelTask(model) {}
404 bool Run(const int64 id) {
405 bool result = false;
406 RunOnUIThreadBlocking::Run(
407 base::Bind(&IsInMobileBookmarksBranchTask::RunOnUIThread,
408 model(), id, &result));
409 return result;
412 static void RunOnUIThread(BookmarkModel* model,
413 const int64 id,
414 bool *result) {
415 DCHECK_CURRENTLY_ON(BrowserThread::UI);
416 DCHECK(result);
417 const BookmarkNode* node = bookmarks::GetBookmarkNodeByID(model, id);
418 const BookmarkNode* mobile_node = model->mobile_node();
419 while (node && node != mobile_node)
420 node = node->parent();
422 *result = node == mobile_node;
425 private:
426 DISALLOW_COPY_AND_ASSIGN(IsInMobileBookmarksBranchTask);
429 // Creates folder or retrieves its id if already exists.
430 // An invalid parent id is assumed to represent the Mobile Bookmarks folder.
431 // Can only be used to create folders inside the Mobile Bookmarks branch.
432 class CreateBookmarksFolderOnceTask : public BookmarkModelTask {
433 public:
434 explicit CreateBookmarksFolderOnceTask(BookmarkModel* model)
435 : BookmarkModelTask(model) {}
437 int64 Run(const base::string16& title, const int64 parent_id) {
438 int64 result = kInvalidBookmarkId;
439 RunOnUIThreadBlocking::Run(
440 base::Bind(&CreateBookmarksFolderOnceTask::RunOnUIThread,
441 model(), title, parent_id, &result));
442 return result;
445 static void RunOnUIThread(BookmarkModel* model,
446 const base::string16& title,
447 const int64 parent_id,
448 int64* result) {
449 DCHECK_CURRENTLY_ON(BrowserThread::UI);
450 DCHECK(result);
452 // Invalid ids are assumed to refer to the Mobile Bookmarks folder.
453 const BookmarkNode* parent =
454 parent_id >= 0 ? bookmarks::GetBookmarkNodeByID(model, parent_id)
455 : model->mobile_node();
456 DCHECK(parent);
458 bool in_mobile_bookmarks;
459 IsInMobileBookmarksBranchTask::RunOnUIThread(model, parent->id(),
460 &in_mobile_bookmarks);
461 if (!in_mobile_bookmarks) {
462 // The parent folder must be inside the Mobile Bookmarks folder.
463 *result = kInvalidBookmarkId;
464 return;
467 const BookmarkNode* node = GetChildFolderByTitle(parent, title);
468 if (node) {
469 *result = node->id();
470 return;
473 AddBookmarkTask::RunOnUIThread(model, title, base::string16(), true,
474 parent->id(), result);
477 private:
478 DISALLOW_COPY_AND_ASSIGN(CreateBookmarksFolderOnceTask);
481 // Creates a Java BookmarkNode object for a node given its id.
482 class GetEditableBookmarkFoldersTask : public BookmarkModelTask {
483 public:
484 GetEditableBookmarkFoldersTask(
485 ManagedBookmarkService* managed_bookmark_service,
486 BookmarkModel* model)
487 : BookmarkModelTask(model),
488 managed_bookmark_service_(managed_bookmark_service) {}
490 void Run(ScopedJavaGlobalRef<jobject>* jroot) {
491 RunOnUIThreadBlocking::Run(
492 base::Bind(&GetEditableBookmarkFoldersTask::RunOnUIThread,
493 managed_bookmark_service_, model(), jroot));
496 static void RunOnUIThread(ManagedBookmarkService* managed,
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())
502 return;
504 // The iterative approach is not possible because ScopedGlobalJavaRefs
505 // cannot be copy-constructed, and therefore not used in STL containers.
506 ConvertFolderSubtree(managed, AttachCurrentThread(), root,
507 ScopedJavaLocalRef<jobject>(), jroot);
510 private:
511 static void ConvertFolderSubtree(ManagedBookmarkService* managed,
512 JNIEnv* env,
513 const BookmarkNode* node,
514 const JavaRef<jobject>& parent_folder,
515 ScopedJavaGlobalRef<jobject>* jfolder) {
516 DCHECK(node);
517 DCHECK(node->is_folder());
518 DCHECK(jfolder);
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() && managed->CanBeEditedByUser(child)) {
527 ScopedJavaGlobalRef<jobject> jchild;
528 ConvertFolderSubtree(managed, 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.";
533 return;
539 ManagedBookmarkService* managed_bookmark_service_;
541 DISALLOW_COPY_AND_ASSIGN(GetEditableBookmarkFoldersTask);
544 // Creates a Java BookmarkNode object for a node given its id.
545 class GetBookmarkNodeTask : public BookmarkModelTask {
546 public:
547 explicit GetBookmarkNodeTask(BookmarkModel* model)
548 : BookmarkModelTask(model) {
551 void Run(const int64 id,
552 bool get_parent,
553 bool get_children,
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,
561 const int64 id,
562 bool get_parent,
563 bool get_children,
564 ScopedJavaGlobalRef<jobject>* jnode) {
565 DCHECK_CURRENTLY_ON(BrowserThread::UI);
566 const BookmarkNode* node = bookmarks::GetBookmarkNodeByID(model, id);
567 if (!node || !jnode)
568 return;
570 ScopedJavaGlobalRef<jobject> jparent;
571 if (get_parent) {
572 ConvertBookmarkNode(node->parent(), ScopedJavaLocalRef<jobject>(),
573 &jparent);
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.";
583 return;
587 if (get_children) {
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.";
594 return;
600 private:
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 {
607 public:
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,
615 model(), &result));
616 return result;
619 static void RunOnUIThread(BookmarkModel* model, const BookmarkNode** result) {
620 DCHECK_CURRENTLY_ON(BrowserThread::UI);
621 DCHECK(result);
622 *result = model->mobile_node();
625 private:
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 {
635 public:
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_;
646 private:
647 Service* service_;
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> {
655 public:
656 FaviconServiceTask(base::CancelableTaskTracker* cancelable_tracker,
657 Profile* profile,
658 favicon::FaviconService* favicon_service)
659 : AsyncServiceRequest<favicon::FaviconService>(favicon_service,
660 cancelable_tracker),
661 profile_(profile) {}
663 Profile* profile() const { return profile_; }
665 private:
666 Profile* 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 {
673 public:
674 BookmarkIconFetchTask(base::CancelableTaskTracker* cancelable_tracker,
675 Profile* profile,
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()));
694 return result_;
697 private:
698 void OnFaviconRetrieved(
699 const favicon_base::FaviconRawBitmapResult& bitmap_result) {
700 result_ = bitmap_result;
701 RequestCompleted();
704 favicon_base::FaviconRawBitmapResult result_;
706 DISALLOW_COPY_AND_ASSIGN(BookmarkIconFetchTask);
709 // Base class for all asynchronous blocking tasks that use the Android history
710 // provider service.
711 class HistoryProviderTask
712 : public AsyncServiceRequest<AndroidHistoryProviderService> {
713 public:
714 HistoryProviderTask(AndroidHistoryProviderService* service,
715 base::CancelableTaskTracker* cancelable_tracker)
716 : AsyncServiceRequest<AndroidHistoryProviderService>(service,
717 cancelable_tracker) {
720 private:
721 DISALLOW_COPY_AND_ASSIGN(HistoryProviderTask);
724 // Adds a bookmark from the API.
725 class AddBookmarkFromAPITask : public HistoryProviderTask {
726 public:
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()),
735 row,
736 base::Bind(&AddBookmarkFromAPITask::OnBookmarkInserted,
737 base::Unretained(this)),
738 cancelable_tracker()));
739 return result_;
742 private:
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.
746 result_ = id;
747 RequestCompleted();
750 history::URLID result_;
752 DISALLOW_COPY_AND_ASSIGN(AddBookmarkFromAPITask);
755 // Queries bookmarks from the API.
756 class QueryBookmarksFromAPITask : public HistoryProviderTask {
757 public:
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()),
770 projections,
771 selection,
772 selection_args,
773 sort_order,
774 base::Bind(&QueryBookmarksFromAPITask::OnBookmarksQueried,
775 base::Unretained(this)),
776 cancelable_tracker()));
777 return result_;
780 private:
781 void OnBookmarksQueried(history::AndroidStatement* statement) {
782 result_ = statement;
783 RequestCompleted();
786 history::AndroidStatement* result_;
788 DISALLOW_COPY_AND_ASSIGN(QueryBookmarksFromAPITask);
791 // Updates bookmarks from the API.
792 class UpdateBookmarksFromAPITask : public HistoryProviderTask {
793 public:
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()),
804 row,
805 selection,
806 selection_args,
807 base::Bind(&UpdateBookmarksFromAPITask::OnBookmarksUpdated,
808 base::Unretained(this)),
809 cancelable_tracker()));
810 return result_;
813 private:
814 void OnBookmarksUpdated(int updated_row_count) {
815 result_ = updated_row_count;
816 RequestCompleted();
819 int result_;
821 DISALLOW_COPY_AND_ASSIGN(UpdateBookmarksFromAPITask);
824 // Removes bookmarks from the API.
825 class RemoveBookmarksFromAPITask : public HistoryProviderTask {
826 public:
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()),
836 selection,
837 selection_args,
838 base::Bind(&RemoveBookmarksFromAPITask::OnBookmarksRemoved,
839 base::Unretained(this)),
840 cancelable_tracker()));
841 return result_;
844 private:
845 void OnBookmarksRemoved(int removed_row_count) {
846 result_ = removed_row_count;
847 RequestCompleted();
850 int result_;
852 DISALLOW_COPY_AND_ASSIGN(RemoveBookmarksFromAPITask);
855 // Removes history from the API.
856 class RemoveHistoryFromAPITask : public HistoryProviderTask {
857 public:
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()),
867 selection,
868 selection_args,
869 base::Bind(&RemoveHistoryFromAPITask::OnHistoryRemoved,
870 base::Unretained(this)),
871 cancelable_tracker()));
872 return result_;
875 private:
876 void OnHistoryRemoved(int removed_row_count) {
877 result_ = removed_row_count;
878 RequestCompleted();
881 int result_;
883 DISALLOW_COPY_AND_ASSIGN(RemoveHistoryFromAPITask);
886 // This class provides the common method for the SearchTermAPIHelper.
887 class SearchTermTask : public HistoryProviderTask {
888 protected:
889 SearchTermTask(AndroidHistoryProviderService* service,
890 base::CancelableTaskTracker* cancelable_tracker,
891 Profile* profile)
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();
905 if (search_engine) {
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());
911 if (!url.empty()) {
912 row->set_url(GURL(url));
913 row->set_keyword_id(search_engine->id());
918 private:
919 Profile* profile_;
921 DISALLOW_COPY_AND_ASSIGN(SearchTermTask);
924 // Adds a search term from the API.
925 class AddSearchTermFromAPITask : public SearchTermTask {
926 public:
927 AddSearchTermFromAPITask(AndroidHistoryProviderService* service,
928 base::CancelableTaskTracker* cancelable_tracker,
929 Profile* profile)
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));
936 return result_;
939 private:
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(
945 internal_row,
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.
954 result_ = id;
955 RequestCompleted();
958 history::URLID result_;
960 DISALLOW_COPY_AND_ASSIGN(AddSearchTermFromAPITask);
963 // Queries search terms from the API.
964 class QuerySearchTermsFromAPITask : public SearchTermTask {
965 public:
966 QuerySearchTermsFromAPITask(AndroidHistoryProviderService* service,
967 base::CancelableTaskTracker* cancelable_tracker,
968 Profile* profile)
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()),
979 projections,
980 selection,
981 selection_args,
982 sort_order,
983 base::Bind(&QuerySearchTermsFromAPITask::OnSearchTermsQueried,
984 base::Unretained(this)),
985 cancelable_tracker()));
986 return result_;
989 private:
990 // Callback to return the result.
991 void OnSearchTermsQueried(history::AndroidStatement* statement) {
992 result_ = statement;
993 RequestCompleted();
996 history::AndroidStatement* result_;
998 DISALLOW_COPY_AND_ASSIGN(QuerySearchTermsFromAPITask);
1001 // Updates search terms from the API.
1002 class UpdateSearchTermsFromAPITask : public SearchTermTask {
1003 public:
1004 UpdateSearchTermsFromAPITask(AndroidHistoryProviderService* service,
1005 base::CancelableTaskTracker* cancelable_tracker,
1006 Profile* profile)
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));
1015 return result_;
1018 private:
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(
1027 internal_row,
1028 selection,
1029 selection_args,
1030 base::Bind(&UpdateSearchTermsFromAPITask::OnSearchTermsUpdated,
1031 base::Unretained(this)),
1032 cancelable_tracker());
1035 void OnSearchTermsUpdated(int updated_row_count) {
1036 result_ = updated_row_count;
1037 RequestCompleted();
1040 int result_;
1042 DISALLOW_COPY_AND_ASSIGN(UpdateSearchTermsFromAPITask);
1045 // Removes search terms from the API.
1046 class RemoveSearchTermsFromAPITask : public SearchTermTask {
1047 public:
1048 RemoveSearchTermsFromAPITask(AndroidHistoryProviderService* service,
1049 base::CancelableTaskTracker* cancelable_tracker,
1050 Profile* profile)
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()),
1058 selection,
1059 selection_args,
1060 base::Bind(&RemoveSearchTermsFromAPITask::OnSearchTermsDeleted,
1061 base::Unretained(this)),
1062 cancelable_tracker()));
1063 return result_;
1066 private:
1067 void OnSearchTermsDeleted(int deleted_row_count) {
1068 result_ = deleted_row_count;
1069 RequestCompleted();
1072 int result_;
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,
1081 jobject obj,
1082 jstring url,
1083 jobject created,
1084 jobject isBookmark,
1085 jobject date,
1086 jbyteArray favicon,
1087 jstring title,
1088 jobject visits,
1089 jlong parent_id,
1090 history::HistoryAndBookmarkRow* row,
1091 BookmarkModel* model) {
1092 // Needed because of the internal bookmark model task invocation.
1093 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
1095 if (url) {
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);
1102 row->set_url(gurl);
1103 row->set_raw_url(base::UTF16ToUTF8(raw_url));
1106 if (created)
1107 row->set_created(ConvertJlongToTime(
1108 ConvertJLongObjectToPrimitive(env, created)));
1110 if (isBookmark)
1111 row->set_is_bookmark(ConvertJBooleanObjectToPrimitive(env, isBookmark));
1113 if (date)
1114 row->set_last_visit_time(ConvertJlongToTime(ConvertJLongObjectToPrimitive(
1115 env, date)));
1117 if (favicon) {
1118 std::vector<uint8> bytes;
1119 base::android::JavaByteArrayToByteVector(env, favicon, &bytes);
1120 row->set_favicon(base::RefCountedBytes::TakeVector(&bytes));
1123 if (title)
1124 row->set_title(ConvertJavaStringToUTF16(env, title));
1126 if (visits)
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,
1137 jobject obj,
1138 jstring search_term,
1139 jobject date,
1140 history::SearchRow* row) {
1141 if (search_term)
1142 row->set_search_term(ConvertJavaStringToUTF16(env, search_term));
1144 if (date)
1145 row->set_search_time(ConvertJlongToTime(ConvertJLongObjectToPrimitive(
1146 env, date)));
1149 } // namespace
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();
1190 delete this;
1193 // ------------- Provider public APIs ------------- //
1195 jlong ChromeBrowserProvider::AddBookmark(JNIEnv* env,
1196 jobject,
1197 jstring jurl,
1198 jstring jtitle,
1199 jboolean is_folder,
1200 jlong parent_id) {
1201 base::string16 url;
1202 if (jurl)
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,
1216 jobject,
1217 jlong id,
1218 jstring jurl,
1219 jstring jtitle,
1220 jlong parent_id) {
1221 base::string16 url;
1222 if (jurl)
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,
1232 jobject obj,
1233 jstring url,
1234 jobject created,
1235 jobject isBookmark,
1236 jobject date,
1237 jbyteArray favicon,
1238 jstring title,
1239 jobject visits,
1240 jlong parent_id) {
1241 DCHECK(url);
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(
1258 JNIEnv* env,
1259 jobject obj,
1260 jobjectArray projection,
1261 jstring selections,
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;
1269 if (projection) {
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.
1279 continue;
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;
1290 if (selections) {
1291 where_clause = ConvertJavaStringToUTF8(env, selections);
1294 std::string sort_clause;
1295 if (sort_order) {
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);
1302 if (!statement)
1303 return ScopedJavaLocalRef<jobject>();
1305 // Creates and returns org.chromium.chrome.browser.database.SQLiteCursor
1306 // Java object.
1307 return SQLiteCursor::NewJavaSqliteCursor(env, columns_name, statement,
1308 service_.get());
1311 // Updates the bookmarks with the given column values. The value is not given if
1312 // it is NULL.
1313 jint ChromeBrowserProvider::UpdateBookmarkFromAPI(JNIEnv* env,
1314 jobject obj,
1315 jstring url,
1316 jobject created,
1317 jobject isBookmark,
1318 jobject date,
1319 jbyteArray favicon,
1320 jstring title,
1321 jobject visits,
1322 jlong parent_id,
1323 jstring selections,
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;
1333 if (selections)
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,
1341 jobject obj,
1342 jstring selections,
1343 jobjectArray selection_args) {
1344 std::vector<base::string16> where_args =
1345 ConvertJStringArrayToString16Array(env, selection_args);
1347 std::string where_clause;
1348 if (selections)
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,
1356 jobject obj,
1357 jstring selections,
1358 jobjectArray selection_args) {
1359 std::vector<base::string16> where_args =
1360 ConvertJStringArrayToString16Array(env, selection_args);
1362 std::string where_clause;
1363 if (selections)
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
1371 // it is NULL.
1372 jlong ChromeBrowserProvider::AddSearchTermFromAPI(JNIEnv* env,
1373 jobject obj,
1374 jstring search_term,
1375 jobject date) {
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_,
1389 profile_);
1390 return task.Run(row);
1393 ScopedJavaLocalRef<jobject> ChromeBrowserProvider::QuerySearchTermFromAPI(
1394 JNIEnv* env,
1395 jobject obj,
1396 jobjectArray projection,
1397 jstring selections,
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;
1405 if (projection) {
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;
1425 if (selections) {
1426 where_clause = ConvertJavaStringToUTF8(env, selections);
1429 std::string sort_clause;
1430 if (sort_order) {
1431 sort_clause = ConvertJavaStringToUTF8(env, sort_order);
1434 QuerySearchTermsFromAPITask task(service_.get(),
1435 &cancelable_task_tracker_,
1436 profile_);
1437 history::AndroidStatement* statement = task.Run(
1438 query_columns, where_clause, where_args, sort_clause);
1439 if (!statement)
1440 return ScopedJavaLocalRef<jobject>();
1441 // Creates and returns org.chromium.chrome.browser.database.SQLiteCursor
1442 // Java object.
1443 return SQLiteCursor::NewJavaSqliteCursor(env, columns_name, statement,
1444 service_.get());
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;
1459 if (selections)
1460 where_clause = ConvertJavaStringToUTF8(env, selections);
1462 UpdateSearchTermsFromAPITask task(service_.get(),
1463 &cancelable_task_tracker_,
1464 profile_);
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;
1474 if (selections)
1475 where_clause = ConvertJavaStringToUTF8(env, selections);
1477 RemoveSearchTermsFromAPITask task(service_.get(),
1478 &cancelable_task_tracker_,
1479 profile_);
1480 return task.Run(where_clause, where_args);
1483 // ------------- Provider custom APIs ------------- //
1485 jboolean ChromeBrowserProvider::BookmarkNodeExists(
1486 JNIEnv* env,
1487 jobject obj,
1488 jlong id) {
1489 BookmarkNodeExistsTask task(bookmark_model_);
1490 return task.Run(id);
1493 jlong ChromeBrowserProvider::CreateBookmarksFolderOnce(
1494 JNIEnv* env,
1495 jobject obj,
1496 jstring jtitle,
1497 jlong parent_id) {
1498 base::string16 title = ConvertJavaStringToUTF16(env, jtitle);
1499 if (title.empty())
1500 return kInvalidBookmarkId;
1502 CreateBookmarksFolderOnceTask task(bookmark_model_);
1503 return task.Run(title, parent_id);
1506 ScopedJavaLocalRef<jobject> ChromeBrowserProvider::GetEditableBookmarkFolders(
1507 JNIEnv* env,
1508 jobject obj) {
1509 ScopedJavaGlobalRef<jobject> jroot;
1510 ManagedBookmarkService* managed =
1511 ManagedBookmarkServiceFactory::GetForProfile(profile_);
1512 BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
1513 GetEditableBookmarkFoldersTask task(managed, model);
1514 task.Run(&jroot);
1515 return ScopedJavaLocalRef<jobject>(jroot);
1518 void ChromeBrowserProvider::RemoveAllUserBookmarks(JNIEnv* env, jobject obj) {
1519 LOG(ERROR) << "begin ChromeBrowserProvider::RemoveAllUserBookmarks";
1520 RemoveAllUserBookmarksTask task(bookmark_model_);
1521 task.Run();
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(
1535 JNIEnv* env,
1536 jobject obj) {
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(
1544 JNIEnv* env,
1545 jobject obj,
1546 jlong id) {
1547 IsInMobileBookmarksBranchTask task(bookmark_model_);
1548 return task.Run(id);
1551 ScopedJavaLocalRef<jbyteArray> ChromeBrowserProvider::GetFaviconOrTouchIcon(
1552 JNIEnv* env, jobject obj, jstring jurl) {
1553 if (!jurl)
1554 return ScopedJavaLocalRef<jbyteArray>();
1556 GURL url = GURL(ConvertJavaStringToUTF16(env, jurl));
1557 BookmarkIconFetchTask favicon_task(&cancelable_task_tracker_, profile_,
1558 favicon_service_);
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) {
1570 if (!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;
1576 if (top_sites_)
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(),
1584 thumbnail->size());
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_)
1602 return;
1604 JNIEnv* env = AttachCurrentThread();
1605 ScopedJavaLocalRef<jobject> obj = weak_java_provider_.get(env);
1606 if (obj.is_null())
1607 return;
1609 Java_ChromeBrowserProvider_onBookmarkChanged(env, obj.obj());
1612 void ChromeBrowserProvider::OnHistoryChanged() {
1613 JNIEnv* env = AttachCurrentThread();
1614 ScopedJavaLocalRef<jobject> obj = weak_java_provider_.get(env);
1615 if (obj.is_null())
1616 return;
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) {
1626 OnHistoryChanged();
1629 void ChromeBrowserProvider::OnURLsDeleted(
1630 history::HistoryService* history_service,
1631 bool all_history,
1632 bool expired,
1633 const history::URLRows& deleted_rows,
1634 const std::set<GURL>& favicon_urls) {
1635 OnHistoryChanged();
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);
1645 if (obj.is_null())
1646 return;
1647 Java_ChromeBrowserProvider_onSearchTermChanged(env, obj.obj());
1650 void ChromeBrowserProvider::OnKeywordSearchTermDeleted(
1651 history::HistoryService* history_service,
1652 history::URLID url_id) {