1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
|
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/mahi/web_contents/mahi_content_extraction_delegate.h"
#include <algorithm>
#include <optional>
#include <string>
#include "base/check.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/metrics/histogram_functions.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/screen_ai/screen_ai_service_router.h"
#include "chrome/browser/screen_ai/screen_ai_service_router_factory.h"
#include "chromeos/components/mahi/public/cpp/mahi_browser_util.h"
#include "chromeos/components/mahi/public/cpp/mahi_util.h"
#include "chromeos/components/mahi/public/mojom/content_extraction.mojom.h"
#include "chromeos/constants/chromeos_features.h"
#include "chromeos/crosapi/mojom/mahi.mojom.h"
#include "content/public/browser/service_process_host.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/screen_ai/public/mojom/screen_ai_service.mojom.h"
#include "ui/accessibility/ax_tree_update.h"
#include "url/gurl.h"
#if DCHECK_IS_ON()
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/download/download_prefs.h"
#endif
namespace mahi {
namespace {
#if DCHECK_IS_ON()
// Save the contents to the `Download` directory. This function is used for
// debugging only, and should never be used in production.
void SaveContentToDiskOnWorker(const base::FilePath& download_path,
const GURL& url,
std::u16string contents) {
std::string file_name;
base::ReplaceChars(url.spec(), "/", "", &file_name);
const base::FilePath content_filepath =
download_path.Append("mahi/" + file_name);
base::CreateDirectory(content_filepath.DirName());
base::WriteFile(content_filepath, base::UTF16ToUTF8(contents));
}
#endif
} // namespace
MahiContentExtractionDelegate::MahiContentExtractionDelegate()
: io_task_runner_(base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {
// Do not bind to the services if mahi is not enabled.
if (!chromeos::features::IsMahiEnabled()) {
return;
}
// Builds connection with mahi content extraction service.
EnsureContentExtractionServiceIsSetUp();
EnsureServiceIsConnected();
// Builds connection with screen ai service.
screen_ai::ScreenAIServiceRouterFactory::GetForBrowserContext(
ProfileManager::GetActiveUserProfile())
->GetServiceStateAsync(
screen_ai::ScreenAIServiceRouter::Service::kMainContentExtraction,
base::BindOnce(
&MahiContentExtractionDelegate::OnScreenAIServiceInitialized,
weak_pointer_factory_.GetWeakPtr()));
}
MahiContentExtractionDelegate::~MahiContentExtractionDelegate() = default;
bool MahiContentExtractionDelegate::EnsureContentExtractionServiceIsSetUp() {
if (remote_content_extraction_service_factory_ &&
remote_content_extraction_service_factory_.is_bound()) {
return true;
}
content::ServiceProcessHost::Launch(
remote_content_extraction_service_factory_.BindNewPipeAndPassReceiver(),
content::ServiceProcessHost::Options()
.WithDisplayName("Mahi Content Extraction Service")
.Pass());
remote_content_extraction_service_factory_.reset_on_disconnect();
return remote_content_extraction_service_factory_ &&
remote_content_extraction_service_factory_.is_bound();
}
bool MahiContentExtractionDelegate::EnsureServiceIsConnected() {
if (remote_content_extraction_service_ &&
remote_content_extraction_service_.is_bound()) {
return true;
}
remote_content_extraction_service_factory_->BindContentExtractionService(
remote_content_extraction_service_.BindNewPipeAndPassReceiver());
remote_content_extraction_service_.reset_on_disconnect();
return remote_content_extraction_service_ &&
remote_content_extraction_service_.is_bound();
}
void MahiContentExtractionDelegate::ExtractContent(
const WebContentState& web_content_state,
const base::UnguessableToken& client_id,
GetContentCallback callback) {
// Early returns if the snapshot is not valid.
if (web_content_state.snapshot.root_id == ui::kInvalidAXNodeID) {
std::move(callback).Run(nullptr);
return;
}
// Generates the extraction request.
mojom::ExtractionRequestPtr extraction_request =
mojom::ExtractionRequest::New(
/*deprecated_ukm_source_id=*/ukm::kInvalidSourceId,
/*snapshot=*/std::make_optional(web_content_state.snapshot),
/*extraction_methods=*/
mojom::ExtractionMethods::New(/*use_algorithm=*/true,
/*use_screen2x=*/true),
/*updates=*/std::nullopt);
if (!EnsureContentExtractionServiceIsSetUp() || !EnsureServiceIsConnected()) {
std::move(callback).Run(nullptr);
LOG(ERROR) << "Remote content extraction service is not available.";
return;
}
MaybeBindScreenAIContentExtraction();
remote_content_extraction_service_->ExtractContent(
std::move(extraction_request),
base::BindOnce(&MahiContentExtractionDelegate::OnGetContent,
weak_pointer_factory_.GetWeakPtr(),
web_content_state.page_id, client_id,
web_content_state.url, std::move(callback)));
}
void MahiContentExtractionDelegate::ExtractContent(
const WebContentState& web_content_state,
const std::vector<ui::AXTreeUpdate>& updates,
const base::UnguessableToken& client_id,
GetContentCallback callback) {
// Generates the extraction request.
mojom::ExtractionRequestPtr extraction_request =
mojom::ExtractionRequest::New(
/*deprecated_ukm_source_id=*/ukm::kInvalidSourceId,
/*snapshot=*/std::nullopt,
/*extraction_methods=*/
mojom::ExtractionMethods::New(/*use_algorithm=*/true,
/*use_screen2x=*/true),
/*updates=*/std::make_optional(updates));
if (!EnsureContentExtractionServiceIsSetUp() || !EnsureServiceIsConnected()) {
std::move(callback).Run(nullptr);
LOG(ERROR) << "Remote content extraction service is not available.";
return;
}
MaybeBindScreenAIContentExtraction();
remote_content_extraction_service_->ExtractContent(
std::move(extraction_request),
base::BindOnce(&MahiContentExtractionDelegate::OnGetContent,
weak_pointer_factory_.GetWeakPtr(),
web_content_state.page_id, client_id,
web_content_state.url, std::move(callback)));
}
void MahiContentExtractionDelegate::OnGetContent(
const base::UnguessableToken& page_id,
const base::UnguessableToken& client_id,
const GURL& url,
GetContentCallback callback,
mojom::ExtractionResponsePtr response) {
#if DCHECK_IS_ON()
// It's for debugging purpose, and save the extracted contents into disk.
if (chromeos::features::IsMahiDebuggingEnabled()) {
base::FilePath download_path = DownloadPrefs::FromBrowserContext(
ProfileManager::GetActiveUserProfile())
->DownloadPath();
io_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&SaveContentToDiskOnWorker, download_path,
url, response->contents));
}
#endif
crosapi::mojom::MahiPageContentPtr page_content =
crosapi::mojom::MahiPageContent::New(
/*client_id=*/client_id,
/*page_id=*/page_id,
/*page_content=*/std::move(response->contents));
std::move(callback).Run(std::move(page_content));
}
void MahiContentExtractionDelegate::OnScreenAIServiceInitialized(
bool successful) {
screen_ai_service_initialized_ = successful;
if (!successful) {
LOG(ERROR) << "ScreenAI service was unsuccessfuly initialized.";
return;
}
MaybeBindScreenAIContentExtraction();
}
void MahiContentExtractionDelegate::MaybeBindScreenAIContentExtraction() {
// Screen AI service isn't initialize yet.
if (!screen_ai_service_initialized_) {
return;
}
if (!EnsureContentExtractionServiceIsSetUp()) {
LOG(ERROR) << "Content extraction service isn't available.";
return;
}
mojo::PendingReceiver<screen_ai::mojom::Screen2xMainContentExtractor>
screen_ai_receiver;
auto screen_ai_remote = screen_ai_receiver.InitWithNewPipeAndPassRemote();
screen_ai::ScreenAIServiceRouterFactory::GetForBrowserContext(
ProfileManager::GetActiveUserProfile())
->BindMainContentExtractor(std::move(screen_ai_receiver));
remote_content_extraction_service_factory_->OnScreen2xReady(
std::move(screen_ai_remote));
}
} // namespace mahi
|