code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
include_rules = [
# The WebUI examples currently depends on HTML in the chrome directory.
# Production code outside of //chrome should not depend on //chrome.
# This is a one-time exception as the WebUI examples is a non-production app.
"+chrome/grit/webui_gallery_resources.h",
"+chrome/grit/webui_gallery_resources_map.h",
# The WebUI examples is a simple embedder, so it only uses content's public API.
"+content/public",
# Devtools relies on IPC definitions.
"+ipc/ipc_channel.h",
# Devtools relies on various net APIs.
"+net",
# Sandbox is part of the main initialization.
"+sandbox",
# The WebUI examples uses Chromium's UI libraries.
"+ui/aura",
"+ui/display",
"+ui/platform_window",
"+ui/wm",
# The WebUI examples is an embedder so it must work with resource bundles.
"+ui/base/l10n",
"+ui/base/resource",
]
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/DEPS | Python | unknown | 864 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "build/build_config.h"
#include "content/public/app/content_main.h"
#include "ui/webui/examples/app/main_delegate.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "content/public/app/sandbox_helper_win.h"
#include "sandbox/win/src/sandbox_types.h"
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_WIN)
int wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) {
base::CommandLine::Init(0, nullptr);
sandbox::SandboxInterfaceInfo sandbox_info{};
content::InitializeSandboxInfo(&sandbox_info);
webui_examples::MainDelegate delegate;
content::ContentMainParams params(&delegate);
params.instance = instance;
params.sandbox_info = &sandbox_info;
return content::ContentMain(std::move(params));
}
#else
int main(int argc, const char** argv) {
base::CommandLine::Init(argc, argv);
webui_examples::MainDelegate delegate;
content::ContentMainParams params(&delegate);
return content::ContentMain(std::move(params));
}
#endif // BUILDFLAG(IS_WIN)
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/app/main.cc | C++ | unknown | 1,157 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/app/main_delegate.h"
#include "base/check.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/webui/examples/browser/content_browser_client.h"
#include "ui/webui/examples/common/content_client.h"
namespace webui_examples {
MainDelegate::MainDelegate() = default;
MainDelegate::~MainDelegate() = default;
absl::optional<int> MainDelegate::BasicStartupComplete() {
logging::LoggingSettings settings;
settings.logging_dest =
logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
CHECK(logging::InitLogging(settings));
content_client_ = std::make_unique<ContentClient>();
content::SetContentClient(content_client_.get());
return absl::nullopt;
}
void MainDelegate::PreSandboxStartup() {
base::FilePath pak_file;
bool res = base::PathService::Get(base::DIR_ASSETS, &pak_file);
CHECK(res);
pak_file = pak_file.Append(FILE_PATH_LITERAL("webui_examples.pak"));
ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
}
content::ContentBrowserClient* MainDelegate::CreateContentBrowserClient() {
content_browser_client_ = std::make_unique<ContentBrowserClient>();
return content_browser_client_.get();
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/app/main_delegate.cc | C++ | unknown | 1,450 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_APP_MAIN_DELEGATE_H_
#define UI_WEBUI_EXAMPLES_APP_MAIN_DELEGATE_H_
#include "content/public/app/content_main_delegate.h"
namespace content {
class ContentBrowserClient;
class ContentClient;
} // namespace content
namespace webui_examples {
class MainDelegate : public content::ContentMainDelegate {
public:
MainDelegate();
MainDelegate(const MainDelegate&) = delete;
MainDelegate& operator=(const MainDelegate&) = delete;
~MainDelegate() override;
private:
// content::ContentMainDelegate:
absl::optional<int> BasicStartupComplete() override;
void PreSandboxStartup() override;
content::ContentBrowserClient* CreateContentBrowserClient() override;
std::unique_ptr<content::ContentClient> content_client_;
std::unique_ptr<content::ContentBrowserClient> content_browser_client_;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_APP_MAIN_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/app/main_delegate.h | C++ | unknown | 1,063 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_context.h"
namespace webui_examples {
BrowserContext::BrowserContext(const base::FilePath& temp_dir_path)
: temp_dir_path_(temp_dir_path),
resource_context_(std::make_unique<content::ResourceContext>()) {}
BrowserContext::~BrowserContext() {
NotifyWillBeDestroyed();
content::BrowserThread::DeleteSoon(content::BrowserThread::IO, FROM_HERE,
resource_context_.release());
ShutdownStoragePartitions();
}
// Creates a delegate to initialize a HostZoomMap and persist its information.
// This is called during creation of each StoragePartition.
std::unique_ptr<content::ZoomLevelDelegate>
BrowserContext::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
return nullptr;
}
base::FilePath BrowserContext::GetPath() {
return temp_dir_path_;
}
bool BrowserContext::IsOffTheRecord() {
return false;
}
content::ResourceContext* BrowserContext::GetResourceContext() {
return resource_context_.get();
}
content::DownloadManagerDelegate* BrowserContext::GetDownloadManagerDelegate() {
return nullptr;
}
content::BrowserPluginGuestManager* BrowserContext::GetGuestManager() {
return nullptr;
}
storage::SpecialStoragePolicy* BrowserContext::GetSpecialStoragePolicy() {
return nullptr;
}
content::PlatformNotificationService*
BrowserContext::GetPlatformNotificationService() {
return nullptr;
}
content::PushMessagingService* BrowserContext::GetPushMessagingService() {
return nullptr;
}
content::StorageNotificationService*
BrowserContext::GetStorageNotificationService() {
return nullptr;
}
content::SSLHostStateDelegate* BrowserContext::GetSSLHostStateDelegate() {
return nullptr;
}
content::PermissionControllerDelegate*
BrowserContext::GetPermissionControllerDelegate() {
return nullptr;
}
content::ReduceAcceptLanguageControllerDelegate*
BrowserContext::GetReduceAcceptLanguageControllerDelegate() {
return nullptr;
}
content::ClientHintsControllerDelegate*
BrowserContext::GetClientHintsControllerDelegate() {
return nullptr;
}
content::BackgroundFetchDelegate* BrowserContext::GetBackgroundFetchDelegate() {
return nullptr;
}
content::BackgroundSyncController*
BrowserContext::GetBackgroundSyncController() {
return nullptr;
}
content::BrowsingDataRemoverDelegate*
BrowserContext::GetBrowsingDataRemoverDelegate() {
return nullptr;
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/browser_context.cc | C++ | unknown | 2,674 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_BROWSER_CONTEXT_H_
#define UI_WEBUI_EXAMPLES_BROWSER_BROWSER_CONTEXT_H_
#include <memory>
#include "base/files/file_path.h"
#include "build/build_config.h"
#include "content/public/browser/browser_context.h"
namespace content {
class ResourceContext;
}
namespace webui_examples {
class BrowserContext : public content::BrowserContext {
public:
explicit BrowserContext(const base::FilePath& temp_dir_path);
BrowserContext(const BrowserContext&) = delete;
BrowserContext& operator=(const BrowserContext&) = delete;
~BrowserContext() override;
private:
// content::BrowserContext:
std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate(
const base::FilePath& partition_path) override;
base::FilePath GetPath() override;
bool IsOffTheRecord() override;
content::ResourceContext* GetResourceContext() override;
content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
content::BrowserPluginGuestManager* GetGuestManager() override;
storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override;
content::PlatformNotificationService* GetPlatformNotificationService()
override;
content::PushMessagingService* GetPushMessagingService() override;
content::StorageNotificationService* GetStorageNotificationService() override;
content::SSLHostStateDelegate* GetSSLHostStateDelegate() override;
content::PermissionControllerDelegate* GetPermissionControllerDelegate()
override;
content::ReduceAcceptLanguageControllerDelegate*
GetReduceAcceptLanguageControllerDelegate() override;
content::ClientHintsControllerDelegate* GetClientHintsControllerDelegate()
override;
content::BackgroundFetchDelegate* GetBackgroundFetchDelegate() override;
content::BackgroundSyncController* GetBackgroundSyncController() override;
content::BrowsingDataRemoverDelegate* GetBrowsingDataRemoverDelegate()
override;
const base::FilePath temp_dir_path_;
std::unique_ptr<content::ResourceContext> resource_context_;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_BROWSER_CONTEXT_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/browser_context.h | C++ | unknown | 2,274 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/browser_main_parts.h"
#include <tuple>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents_view_delegate.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/webui/examples/browser/browser_context.h"
#include "ui/webui/examples/browser/devtools/devtools_frontend.h"
#include "ui/webui/examples/browser/devtools/devtools_manager_delegate.h"
#include "ui/webui/examples/browser/devtools/devtools_server.h"
#include "ui/webui/examples/browser/ui/aura/aura_context.h"
#include "ui/webui/examples/browser/ui/aura/content_window.h"
#include "ui/webui/examples/browser/webui_controller_factory.h"
#include "ui/webui/examples/grit/webui_examples_resources.h"
namespace webui_examples {
namespace {
class WebContentsViewDelegate : public content::WebContentsViewDelegate {
public:
using CreateContentWindowFunc =
base::RepeatingCallback<content::WebContents*(const GURL&)>;
WebContentsViewDelegate(content::WebContents* web_contents,
CreateContentWindowFunc create_window_func)
: web_contents_(web_contents),
create_window_func_(std::move(create_window_func)) {}
WebContentsViewDelegate(const WebContentsViewDelegate&) = delete;
WebContentsViewDelegate& operator=(const WebContentsViewDelegate&) = delete;
~WebContentsViewDelegate() override = default;
private:
// content::WebContentsViewDelegate:
void ShowContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) override {
DevToolsFrontend* frontend = DevToolsFrontend::CreateAndGet(web_contents_);
frontend->SetDevtoolsWebContents(
create_window_func_.Run(frontend->frontend_url()));
}
const raw_ptr<content::WebContents> web_contents_;
CreateContentWindowFunc create_window_func_;
};
} // namespace
BrowserMainParts::BrowserMainParts() = default;
BrowserMainParts::~BrowserMainParts() = default;
std::unique_ptr<content::WebContentsViewDelegate>
BrowserMainParts::CreateWebContentsViewDelegate(
content::WebContents* web_contents) {
return std::make_unique<WebContentsViewDelegate>(
web_contents,
base::BindRepeating(
[](BrowserMainParts* browser_main_parts, const GURL& url) {
return browser_main_parts->CreateAndShowContentWindow(
url, l10n_util::GetStringUTF16(IDS_DEVTOOLS_WINDOW_TITLE));
},
base::Unretained(this)));
}
std::unique_ptr<content::DevToolsManagerDelegate>
BrowserMainParts::CreateDevToolsManagerDelegate() {
return std::make_unique<DevToolsManagerDelegate>(
browser_context_.get(),
base::BindRepeating(
[](BrowserMainParts* browser_main_parts,
content::BrowserContext* browser_context, const GURL& url) {
return browser_main_parts->CreateAndShowContentWindow(
url, l10n_util::GetStringUTF16(IDS_DEVTOOLS_WINDOW_TITLE));
},
base::Unretained(this)));
}
int BrowserMainParts::PreMainMessageLoopRun() {
std::ignore = temp_dir_.CreateUniqueTempDir();
browser_context_ = std::make_unique<BrowserContext>(temp_dir_.GetPath());
devtools::StartHttpHandler(browser_context_.get());
web_ui_controller_factory_ = std::make_unique<WebUIControllerFactory>();
content::WebUIControllerFactory::RegisterFactory(
web_ui_controller_factory_.get());
aura_context_ = std::make_unique<AuraContext>();
CreateAndShowContentWindow(
GURL("chrome://main/"),
l10n_util::GetStringUTF16(IDS_WEBUI_EXAMPLES_WINDOW_TITLE));
return 0;
}
void BrowserMainParts::WillRunMainMessageLoop(
std::unique_ptr<base::RunLoop>& run_loop) {
quit_run_loop_ = run_loop->QuitClosure();
}
void BrowserMainParts::PostMainMessageLoopRun() {
devtools::StopHttpHandler();
browser_context_.reset();
}
content::WebContents* BrowserMainParts::CreateAndShowContentWindow(
GURL url,
const std::u16string& title) {
auto content_window = std::make_unique<ContentWindow>(aura_context_.get(),
browser_context_.get());
ContentWindow* content_window_ptr = content_window.get();
content_window_ptr->SetTitle(title);
content_window_ptr->NavigateToURL(url);
content_window_ptr->Show();
content_window_ptr->SetCloseCallback(
base::BindOnce(&BrowserMainParts::OnWindowClosed,
weak_factory_.GetWeakPtr(), std::move(content_window)));
++content_windows_outstanding_;
return content_window_ptr->web_contents();
}
void BrowserMainParts::OnWindowClosed(
std::unique_ptr<ContentWindow> content_window) {
--content_windows_outstanding_;
auto task_runner = content::GetUIThreadTaskRunner({});
// We are dispatching a callback that originates from the content_window.
// Deleting soon instead of now eliminates the chance of a crash in case the
// content_window or associated objects have more work to do after this
// callback.
task_runner->DeleteSoon(FROM_HERE, std::move(content_window));
if (content_windows_outstanding_ == 0) {
task_runner->PostTask(FROM_HERE,
base::BindOnce(&BrowserMainParts::QuitMessageLoop,
weak_factory_.GetWeakPtr()));
}
}
void BrowserMainParts::QuitMessageLoop() {
aura_context_.reset();
web_ui_controller_factory_.reset();
quit_run_loop_.Run();
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/browser_main_parts.cc | C++ | unknown | 5,845 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_BROWSER_MAIN_PARTS_H_
#define UI_WEBUI_EXAMPLES_BROWSER_BROWSER_MAIN_PARTS_H_
#include <string>
#include "base/files/scoped_temp_dir.h"
#include "content/public/browser/browser_main_parts.h"
class GURL;
namespace content {
class BrowserContext;
class DevToolsManagerDelegate;
class WebContents;
class WebContentsViewDelegate;
} // namespace content
namespace webui_examples {
class AuraContext;
class BrowserContext;
class ContentWindow;
class WebUIControllerFactory;
class BrowserMainParts : public content::BrowserMainParts {
public:
BrowserMainParts();
BrowserMainParts(const BrowserMainParts&) = delete;
BrowserMainParts& operator=(const BrowserMainParts&) = delete;
~BrowserMainParts() override;
std::unique_ptr<content::WebContentsViewDelegate>
CreateWebContentsViewDelegate(content::WebContents* web_contents);
std::unique_ptr<content::DevToolsManagerDelegate>
CreateDevToolsManagerDelegate();
private:
// content::BrowserMainParts:
int PreMainMessageLoopRun() override;
void WillRunMainMessageLoop(
std::unique_ptr<base::RunLoop>& run_loop) override;
void PostMainMessageLoopRun() override;
// content::WebContents is associated and bound to the lifetime of the window.
content::WebContents* CreateAndShowContentWindow(GURL url,
const std::u16string& title);
void OnWindowClosed(std::unique_ptr<ContentWindow> content_window);
void QuitMessageLoop();
base::ScopedTempDir temp_dir_;
std::unique_ptr<WebUIControllerFactory> web_ui_controller_factory_;
std::unique_ptr<content::BrowserContext> browser_context_;
std::unique_ptr<AuraContext> aura_context_;
int content_windows_outstanding_ = 0;
base::RepeatingClosure quit_run_loop_;
base::WeakPtrFactory<BrowserMainParts> weak_factory_{this};
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_BROWSER_MAIN_PARTS_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/browser_main_parts.h | C++ | unknown | 2,091 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/content_browser_client.h"
#include "content/public/browser/devtools_manager_delegate.h"
#include "content/public/browser/web_contents_view_delegate.h"
#include "ui/webui/examples/browser/browser_main_parts.h"
namespace webui_examples {
ContentBrowserClient::ContentBrowserClient() = default;
ContentBrowserClient::~ContentBrowserClient() = default;
std::unique_ptr<content::BrowserMainParts>
ContentBrowserClient::CreateBrowserMainParts(bool is_integration_test) {
auto browser_main_parts = std::make_unique<BrowserMainParts>();
browser_main_parts_ = browser_main_parts.get();
return browser_main_parts;
}
std::unique_ptr<content::WebContentsViewDelegate>
ContentBrowserClient::GetWebContentsViewDelegate(
content::WebContents* web_contents) {
return browser_main_parts_->CreateWebContentsViewDelegate(web_contents);
}
std::unique_ptr<content::DevToolsManagerDelegate>
ContentBrowserClient::CreateDevToolsManagerDelegate() {
return browser_main_parts_->CreateDevToolsManagerDelegate();
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/content_browser_client.cc | C++ | unknown | 1,221 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_CONTENT_BROWSER_CLIENT_H_
#define UI_WEBUI_EXAMPLES_BROWSER_CONTENT_BROWSER_CLIENT_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "content/public/browser/content_browser_client.h"
namespace webui_examples {
class BrowserMainParts;
class ContentBrowserClient : public content::ContentBrowserClient {
public:
ContentBrowserClient();
ContentBrowserClient(const ContentBrowserClient&) = delete;
ContentBrowserClient& operator=(const ContentBrowserClient&) = delete;
~ContentBrowserClient() override;
private:
// content::ContentBrowserClient:
std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts(
bool is_integration_test) override;
std::unique_ptr<content::WebContentsViewDelegate> GetWebContentsViewDelegate(
content::WebContents* web_contents) override;
std::unique_ptr<content::DevToolsManagerDelegate>
CreateDevToolsManagerDelegate() override;
raw_ptr<BrowserMainParts> browser_main_parts_ = nullptr;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_CONTENT_BROWSER_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/content_browser_client.h | C++ | unknown | 1,249 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/devtools/devtools_frontend.h"
#include <map>
#include <memory>
#include "base/guid.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_frontend_host.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "ipc/ipc_channel.h"
#include "ui/webui/examples/browser/devtools/devtools_server.h"
#include "url/gurl.h"
namespace webui_examples {
namespace {
static GURL GetFrontendURL() {
return GURL(
base::StringPrintf("http://127.0.0.1:%d/devtools/devtools_app.html",
devtools::GetHttpHandlerPort()));
}
// This constant should be in sync with
// the constant
// kMaxMessageChunkSize in chrome/browser/devtools/devtools_ui_bindings.cc.
constexpr size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4;
} // namespace
class DevToolsFrontend::AgentHostClient
: public content::WebContentsObserver,
public content::DevToolsAgentHostClient {
public:
AgentHostClient(content::WebContents* devtools_contents,
content::WebContents* inspected_contents)
: content::WebContentsObserver(devtools_contents),
devtools_contents_(devtools_contents),
inspected_contents_(inspected_contents) {}
AgentHostClient(const AgentHostClient&) = delete;
AgentHostClient& operator=(const AgentHostClient&) = delete;
~AgentHostClient() override = default;
// content::DevToolsAgentHostClient
void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host,
base::span<const uint8_t> message) override {
base::StringPiece str_message(reinterpret_cast<const char*>(message.data()),
message.size());
if (str_message.length() < kMaxMessageChunkSize) {
CallClientFunction("DevToolsAPI", "dispatchMessage",
base::Value(std::string(str_message)));
} else {
size_t total_size = str_message.length();
for (size_t pos = 0; pos < str_message.length();
pos += kMaxMessageChunkSize) {
base::StringPiece str_message_chunk =
str_message.substr(pos, kMaxMessageChunkSize);
CallClientFunction(
"DevToolsAPI", "dispatchMessageChunk",
base::Value(std::string(str_message_chunk)),
base::Value(base::NumberToString(pos ? 0 : total_size)));
}
}
}
void AgentHostClosed(content::DevToolsAgentHost* agent_host) override {}
void Attach() {
if (agent_host_)
agent_host_->DetachClient(this);
agent_host_ =
content::DevToolsAgentHost::GetOrCreateFor(inspected_contents_);
agent_host_->AttachClient(this);
}
void CallClientFunction(
const std::string& object_name,
const std::string& method_name,
base::Value arg1 = {},
base::Value arg2 = {},
base::Value arg3 = {},
base::OnceCallback<void(base::Value)> cb = base::NullCallback()) {
content::RenderFrameHost* host = devtools_contents_->GetPrimaryMainFrame();
host->AllowInjectingJavaScript();
base::Value::List arguments;
if (!arg1.is_none()) {
arguments.Append(std::move(arg1));
if (!arg2.is_none()) {
arguments.Append(std::move(arg2));
if (!arg3.is_none()) {
arguments.Append(std::move(arg3));
}
}
}
host->ExecuteJavaScriptMethod(base::ASCIIToUTF16(object_name),
base::ASCIIToUTF16(method_name),
std::move(arguments), std::move(cb));
}
private:
// content::WebContentsObserver:
void ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) override {
content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost();
// TODO(https://crbug.com/1218946): With MPArch there may be multiple main
// frames. This caller was converted automatically to the primary main frame
// to preserve its semantics. Follow up to confirm correctness.
if (navigation_handle->IsInPrimaryMainFrame()) {
frontend_host_ = content::DevToolsFrontendHost::Create(
frame, base::BindRepeating(
&AgentHostClient::HandleMessageFromDevToolsFrontend,
base::Unretained(this)));
return;
}
std::string origin =
navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec();
auto it = extensions_api_.find(origin);
if (it == extensions_api_.end())
return;
std::string script = base::StringPrintf("%s(\"%s\")", it->second.c_str(),
base::GenerateGUID().c_str());
content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script);
}
void HandleMessageFromDevToolsFrontend(base::Value::Dict message) {
const std::string* method = message.FindString("method");
if (!method)
return;
int request_id = message.FindInt("id").value_or(0);
base::Value::List* params_value = message.FindList("params");
// Since we've received message by value, we can take the list.
base::Value::List params;
if (params_value) {
params = std::move(*params_value);
}
if (*method == "dispatchProtocolMessage" && params.size() == 1) {
const std::string* protocol_message = params[0].GetIfString();
if (!agent_host_ || !protocol_message)
return;
agent_host_->DispatchProtocolMessage(
this, base::as_bytes(base::make_span(*protocol_message)));
} else if (*method == "loadCompleted") {
CallClientFunction("DevToolsAPI", "setUseSoftMenu", base::Value(true));
} else if (*method == "loadNetworkResource" && params.size() == 3) {
// TODO(robliao): Add support for this if necessary.
NOTREACHED();
return;
} else if (*method == "getPreferences") {
SendMessageAck(request_id, base::Value(std::move(preferences_)));
return;
} else if (*method == "setPreference") {
if (params.size() < 2)
return;
const std::string* name = params[0].GetIfString();
// We're just setting params[1] as a value anyways, so just make sure it's
// the type we want, but don't worry about getting it.
if (!name || !params[1].is_string())
return;
preferences_.Set(*name, std::move(params[1]));
} else if (*method == "removePreference") {
const std::string* name = params[0].GetIfString();
if (!name)
return;
preferences_.Remove(*name);
} else if (*method == "requestFileSystems") {
CallClientFunction("DevToolsAPI", "fileSystemsLoaded",
base::Value(base::Value::Type::LIST));
} else if (*method == "reattach") {
if (!agent_host_)
return;
agent_host_->DetachClient(this);
agent_host_->AttachClient(this);
} else if (*method == "registerExtensionsAPI") {
if (params.size() < 2)
return;
const std::string* origin = params[0].GetIfString();
const std::string* script = params[1].GetIfString();
if (!origin || !script)
return;
extensions_api_[*origin + "/"] = *script;
} else {
return;
}
if (request_id)
SendMessageAck(request_id, {});
}
void SendMessageAck(int request_id, base::Value arg) {
CallClientFunction("DevToolsAPI", "embedderMessageAck",
base::Value(request_id), std::move(arg));
}
content::WebContents* const devtools_contents_;
content::WebContents* const inspected_contents_;
scoped_refptr<content::DevToolsAgentHost> agent_host_;
std::unique_ptr<content::DevToolsFrontendHost> frontend_host_;
std::map<std::string, std::string> extensions_api_;
base::Value::Dict preferences_;
};
class DevToolsFrontend::Pointer : public content::WebContentsUserData<Pointer> {
public:
~Pointer() override = default;
static DevToolsFrontend* Create(content::WebContents* web_contents) {
CreateForWebContents(web_contents);
Pointer* ptr = FromWebContents(web_contents);
return ptr->Get();
}
DevToolsFrontend* Get() { return ptr_.get(); }
private:
friend class content::WebContentsUserData<Pointer>;
Pointer(content::WebContents* web_contents)
: content::WebContentsUserData<Pointer>(*web_contents),
ptr_(new DevToolsFrontend(web_contents)) {}
Pointer(const Pointer*) = delete;
Pointer& operator=(const Pointer&) = delete;
WEB_CONTENTS_USER_DATA_KEY_DECL();
std::unique_ptr<DevToolsFrontend> ptr_;
};
WEB_CONTENTS_USER_DATA_KEY_IMPL(DevToolsFrontend::Pointer);
DevToolsFrontend::DevToolsFrontend(content::WebContents* inspected_contents)
: frontend_url_(GetFrontendURL()),
inspected_contents_(inspected_contents) {}
DevToolsFrontend::~DevToolsFrontend() = default;
// static
DevToolsFrontend* DevToolsFrontend::CreateAndGet(
content::WebContents* inspected_contents) {
return DevToolsFrontend::Pointer::Create(inspected_contents);
}
void DevToolsFrontend::SetDevtoolsWebContents(
content::WebContents* devtools_contents) {
devtools_contents_ = devtools_contents;
agent_host_client_ = std::make_unique<AgentHostClient>(devtools_contents_,
inspected_contents_);
agent_host_client_->Attach();
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/devtools/devtools_frontend.cc | C++ | unknown | 9,812 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_FRONTEND_H_
#define UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_FRONTEND_H_
#include "url/gurl.h"
namespace content {
class WebContents;
}
namespace webui_examples {
class DevToolsFrontend {
public:
DevToolsFrontend(const DevToolsFrontend&) = delete;
DevToolsFrontend& operator=(const DevToolsFrontend&) = delete;
~DevToolsFrontend();
static DevToolsFrontend* CreateAndGet(
content::WebContents* inspected_contents);
const GURL& frontend_url() { return frontend_url_; }
void SetDevtoolsWebContents(content::WebContents* devtools_contents);
private:
class AgentHostClient;
class Pointer;
DevToolsFrontend(content::WebContents* inspected_contents);
const GURL frontend_url_;
content::WebContents* inspected_contents_;
content::WebContents* devtools_contents_;
std::unique_ptr<AgentHostClient> agent_host_client_;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_FRONTEND_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/devtools/devtools_frontend.h | C++ | unknown | 1,153 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/devtools/devtools_manager_delegate.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/devtools_agent_host.h"
namespace webui_examples {
DevToolsManagerDelegate::DevToolsManagerDelegate(
content::BrowserContext* browser_context,
CreateContentWindowFunc create_content_window_func)
: browser_context_(browser_context),
create_content_window_func_(std::move(create_content_window_func)) {}
DevToolsManagerDelegate::~DevToolsManagerDelegate() = default;
content::BrowserContext* DevToolsManagerDelegate::GetDefaultBrowserContext() {
return browser_context_;
}
scoped_refptr<content::DevToolsAgentHost>
DevToolsManagerDelegate::CreateNewTarget(const GURL& url, bool for_tab) {
content::WebContents* web_content =
create_content_window_func_.Run(browser_context_, url);
return for_tab ? content::DevToolsAgentHost::GetOrCreateForTab(web_content)
: content::DevToolsAgentHost::GetOrCreateFor(web_content);
}
std::string DevToolsManagerDelegate::GetDiscoveryPageHTML() {
return std::string();
}
bool DevToolsManagerDelegate::HasBundledFrontendResources() {
return true;
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/devtools/devtools_manager_delegate.cc | C++ | unknown | 1,372 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_MANAGER_DELEGATE_H_
#define UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_MANAGER_DELEGATE_H_
#include "base/functional/callback.h"
#include "content/public/browser/devtools_manager_delegate.h"
#include "url/gurl.h"
namespace content {
class BrowserContext;
class WebContents;
} // namespace content
namespace webui_examples {
class DevToolsManagerDelegate : public content::DevToolsManagerDelegate {
public:
using CreateContentWindowFunc =
base::RepeatingCallback<content::WebContents*(content::BrowserContext*,
const GURL&)>;
DevToolsManagerDelegate(content::BrowserContext* browser_context,
CreateContentWindowFunc create_content_window_func);
DevToolsManagerDelegate(const DevToolsManagerDelegate&) = delete;
DevToolsManagerDelegate& operator=(const DevToolsManagerDelegate&) = delete;
~DevToolsManagerDelegate() override;
// DevToolsManagerDelegate:
content::BrowserContext* GetDefaultBrowserContext() override;
scoped_refptr<content::DevToolsAgentHost> CreateNewTarget(
const GURL& url,
bool for_tab) override;
std::string GetDiscoveryPageHTML() override;
bool HasBundledFrontendResources() override;
private:
content::BrowserContext* const browser_context_;
CreateContentWindowFunc create_content_window_func_;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_MANAGER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/devtools/devtools_manager_delegate.h | C++ | unknown | 1,653 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/devtools/devtools_server.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_socket_factory.h"
#include "content/public/common/content_switches.h"
#include "net/base/net_errors.h"
#include "net/socket/tcp_server_socket.h"
namespace webui_examples::devtools {
namespace {
base::subtle::Atomic32 g_last_used_port;
class TCPServerSocketFactory : public content::DevToolsSocketFactory {
public:
static std::unique_ptr<content::DevToolsSocketFactory> Create() {
return std::make_unique<TCPServerSocketFactory>("127.0.0.1", 0);
}
TCPServerSocketFactory(const std::string& address, uint16_t port)
: address_(address), port_(port) {}
TCPServerSocketFactory(const TCPServerSocketFactory&) = delete;
TCPServerSocketFactory& operator=(const TCPServerSocketFactory&) = delete;
private:
// content::DevToolsSocketFactory.
std::unique_ptr<net::ServerSocket> CreateForHttpServer() override {
constexpr int kBackLog = 10;
std::unique_ptr<net::ServerSocket> socket =
std::make_unique<net::TCPServerSocket>(nullptr, net::NetLogSource());
if (socket->ListenWithAddressAndPort(address_, port_, kBackLog) != net::OK)
return nullptr;
net::IPEndPoint endpoint;
if (socket->GetLocalAddress(&endpoint) == net::OK)
base::subtle::NoBarrier_Store(&g_last_used_port, endpoint.port());
return socket;
}
std::unique_ptr<net::ServerSocket> CreateForTethering(
std::string* out_name) override {
return nullptr;
}
const std::string address_;
const uint16_t port_;
};
} // namespace
void StartHttpHandler(content::BrowserContext* browser_context) {
content::DevToolsAgentHost::StartRemoteDebuggingServer(
TCPServerSocketFactory::Create(), browser_context->GetPath(),
base::FilePath());
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kRemoteDebuggingPipe)) {
content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler(
base::OnceClosure());
}
}
void StopHttpHandler() {
content::DevToolsAgentHost::StopRemoteDebuggingServer();
}
int GetHttpHandlerPort() {
return base::subtle::NoBarrier_Load(&g_last_used_port);
}
} // namespace webui_examples::devtools
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/devtools/devtools_server.cc | C++ | unknown | 2,615 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_SERVER_H_
#define UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_SERVER_H_
namespace content {
class BrowserContext;
} // namespace content
namespace webui_examples::devtools {
void StartHttpHandler(content::BrowserContext* browser_context);
void StopHttpHandler();
int GetHttpHandlerPort();
} // namespace webui_examples::devtools
#endif // UI_WEBUI_EXAMPLES_BROWSER_DEVTOOLS_DEVTOOLS_MANAGER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/devtools/devtools_server.h | C++ | unknown | 607 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/ui/aura/aura_context.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/test/test_screen.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/platform_window/platform_window_init_properties.h"
#include "ui/webui/examples/browser/ui/aura/fill_layout.h"
#include "ui/wm/core/base_focus_rules.h"
#include "ui/wm/core/cursor_loader.h"
#include "ui/wm/core/cursor_manager.h"
#include "ui/wm/core/focus_controller.h"
#include "ui/wm/core/native_cursor_manager.h"
#include "ui/wm/public/activation_client.h"
namespace webui_examples {
namespace {
class FocusRules : public wm::BaseFocusRules {
public:
FocusRules() = default;
FocusRules(const FocusRules&) = delete;
FocusRules& operator=(const FocusRules&) = delete;
~FocusRules() override = default;
private:
// wm::BaseFocusRules:
bool SupportsChildActivation(const aura::Window* window) const override {
return true;
}
};
} // namespace
class AuraContext::NativeCursorManager : public wm::NativeCursorManager {
public:
NativeCursorManager() = default;
~NativeCursorManager() override = default;
void AddHost(aura::WindowTreeHost* host) { hosts_.insert(host); }
void RemoveHost(aura::WindowTreeHost* host) { hosts_.erase(host); }
private:
// wm::NativeCursorManager:
void SetDisplay(const display::Display& display,
wm::NativeCursorManagerDelegate* delegate) override {
if (cursor_loader_.SetDisplay(display)) {
SetCursor(delegate->GetCursor(), delegate);
}
}
void SetCursor(gfx::NativeCursor cursor,
wm::NativeCursorManagerDelegate* delegate) override {
gfx::NativeCursor new_cursor = cursor;
cursor_loader_.SetPlatformCursor(&new_cursor);
delegate->CommitCursor(new_cursor);
if (delegate->IsCursorVisible()) {
for (auto* host : hosts_)
host->SetCursor(new_cursor);
}
}
void SetVisibility(bool visible,
wm::NativeCursorManagerDelegate* delegate) override {
delegate->CommitVisibility(visible);
if (visible) {
SetCursor(delegate->GetCursor(), delegate);
} else {
gfx::NativeCursor invisible_cursor(ui::mojom::CursorType::kNone);
cursor_loader_.SetPlatformCursor(&invisible_cursor);
for (auto* host : hosts_)
host->SetCursor(invisible_cursor);
}
for (auto* host : hosts_)
host->OnCursorVisibilityChanged(visible);
}
void SetCursorSize(ui::CursorSize cursor_size,
wm::NativeCursorManagerDelegate* delegate) override {
NOTIMPLEMENTED();
}
void SetMouseEventsEnabled(
bool enabled,
wm::NativeCursorManagerDelegate* delegate) override {
delegate->CommitMouseEventsEnabled(enabled);
SetVisibility(delegate->IsCursorVisible(), delegate);
for (auto* host : hosts_)
host->dispatcher()->OnMouseEventsEnableStateChanged(enabled);
}
// The set of hosts to notify of changes in cursor state.
base::flat_set<aura::WindowTreeHost*> hosts_;
wm::CursorLoader cursor_loader_;
};
AuraContext::ContextualizedWindowTreeHost::ContextualizedWindowTreeHost(
base::PassKey<AuraContext>,
AuraContext* context,
std::unique_ptr<aura::WindowTreeHost> window_tree_host)
: context_(context), window_tree_host_(std::move(window_tree_host)) {
context_->InitializeWindowTreeHost(window_tree_host_.get());
}
AuraContext::ContextualizedWindowTreeHost::~ContextualizedWindowTreeHost() {
context_->UninitializeWindowTreeHost(window_tree_host_.get());
}
AuraContext::AuraContext()
: screen_(aura::TestScreen::Create(gfx::Size(1024, 768))) {
DCHECK(!display::Screen::GetScreen());
display::Screen::SetScreenInstance(screen_.get());
focus_controller_ = std::make_unique<wm::FocusController>(new FocusRules());
auto native_cursor_manager = std::make_unique<NativeCursorManager>();
native_cursor_manager_ = native_cursor_manager.get();
cursor_manager_ =
std::make_unique<wm::CursorManager>(std::move(native_cursor_manager));
}
AuraContext::~AuraContext() = default;
std::unique_ptr<AuraContext::ContextualizedWindowTreeHost>
AuraContext::CreateWindowTreeHost() {
ui::PlatformWindowInitProperties properties;
properties.bounds = gfx::Rect(gfx::Size(1024, 768));
auto host = aura::WindowTreeHost::Create(std::move(properties));
return std::make_unique<ContextualizedWindowTreeHost>(
base::PassKey<AuraContext>(), this, std::move(host));
}
void AuraContext::InitializeWindowTreeHost(aura::WindowTreeHost* host) {
host->InitHost();
aura::client::SetFocusClient(host->window(), focus_controller_.get());
wm::SetActivationClient(host->window(), focus_controller_.get());
host->window()->AddPreTargetHandler(focus_controller_.get());
host->window()->SetLayoutManager(
std::make_unique<FillLayout>(host->window()));
native_cursor_manager_->AddHost(host);
aura::client::SetCursorClient(host->window(), cursor_manager_.get());
}
void AuraContext::UninitializeWindowTreeHost(aura::WindowTreeHost* host) {
native_cursor_manager_->RemoveHost(host);
host->window()->RemovePreTargetHandler(focus_controller_.get());
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/ui/aura/aura_context.cc | C++ | unknown | 5,462 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_AURA_CONTEXT_H_
#define UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_AURA_CONTEXT_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/types/pass_key.h"
namespace aura {
class WindowTreeHost;
}
namespace display {
class Screen;
}
namespace wm {
class CursorManager;
class FocusController;
} // namespace wm
namespace webui_examples {
// Holds the necessary services so that a Aura WindowTreeHost behaves like a
// normal application window, responding to focus and cursor events for example.
class AuraContext {
public:
// Represents a WindowTreeHost with customizations and cleanup necessary for
// normal application window interaction.]
class ContextualizedWindowTreeHost {
public:
ContextualizedWindowTreeHost(
base::PassKey<AuraContext>,
AuraContext* context,
std::unique_ptr<aura::WindowTreeHost> window_tree_host);
~ContextualizedWindowTreeHost();
aura::WindowTreeHost* window_tree_host() { return window_tree_host_.get(); }
private:
base::raw_ptr<AuraContext> const context_;
std::unique_ptr<aura::WindowTreeHost> const window_tree_host_;
};
AuraContext();
AuraContext(const AuraContext&) = delete;
AuraContext& operator=(const AuraContext&) = delete;
~AuraContext();
std::unique_ptr<ContextualizedWindowTreeHost> CreateWindowTreeHost();
private:
class NativeCursorManager;
void InitializeWindowTreeHost(aura::WindowTreeHost* host);
void UninitializeWindowTreeHost(aura::WindowTreeHost* host);
std::unique_ptr<display::Screen> screen_;
std::unique_ptr<wm::FocusController> focus_controller_;
std::unique_ptr<wm::CursorManager> cursor_manager_;
base::raw_ptr<NativeCursorManager> native_cursor_manager_;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_AURA_CONTEXT_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/ui/aura/aura_context.h | C++ | unknown | 1,998 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/ui/aura/content_window.h"
#include "base/containers/flat_set.h"
#include "base/no_destructor.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/web_contents.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/aura/window_tree_host_observer.h"
#include "ui/aura/window_tree_host_platform.h"
#include "ui/platform_window/platform_window.h"
#include "ui/wm/core/compound_event_filter.h"
namespace webui_examples {
namespace {
class QuitOnClose : public aura::WindowTreeHostObserver {
public:
explicit QuitOnClose(base::OnceClosure window_close_requested)
: window_close_requested_(std::move(window_close_requested)) {}
QuitOnClose(const QuitOnClose&) = delete;
QuitOnClose& operator=(const QuitOnClose&) = delete;
~QuitOnClose() override = default;
void OnHostCloseRequested(aura::WindowTreeHost* host) override {
std::move(window_close_requested_).Run();
}
private:
base::OnceClosure window_close_requested_;
};
} // namespace
ContentWindow::ContentWindow(AuraContext* aura_context,
content::BrowserContext* browser_context) {
host_ = aura_context->CreateWindowTreeHost();
// Cursor support.
root_window_event_filter_ = std::make_unique<wm::CompoundEventFilter>();
content::WebContents::CreateParams params(browser_context);
web_contents_ = content::WebContents::Create(params);
aura::Window* web_contents_window = web_contents_->GetNativeView();
aura::WindowTreeHost* window_tree_host = host_->window_tree_host();
window_tree_host->window()->GetRootWindow()->AddChild(web_contents_window);
window_tree_host->window()->GetRootWindow()->AddPreTargetHandler(
root_window_event_filter_.get());
}
ContentWindow::~ContentWindow() = default;
void ContentWindow::SetTitle(const std::u16string& title) {
aura::WindowTreeHost* window_tree_host = host_->window_tree_host();
window_tree_host->window()->SetTitle(title);
static_cast<aura::WindowTreeHostPlatform*>(window_tree_host)
->platform_window()
->SetTitle(title);
}
void ContentWindow::Show() {
web_contents_->GetNativeView()->Show();
aura::WindowTreeHost* window_tree_host = host_->window_tree_host();
window_tree_host->window()->Show();
window_tree_host->Show();
}
void ContentWindow::NavigateToURL(GURL url) {
content::NavigationController::LoadURLParams url_params(url);
web_contents_->GetController().LoadURLWithParams(url_params);
}
void ContentWindow::SetCloseCallback(base::OnceClosure on_close) {
host_->window_tree_host()->AddObserver(new QuitOnClose(std::move(on_close)));
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/ui/aura/content_window.cc | C++ | unknown | 2,893 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_CONTENT_WINDOW_H_
#define UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_CONTENT_WINDOW_H_
#include "base/functional/callback.h"
#include "ui/webui/examples/browser/ui/aura/aura_context.h"
#include "url/gurl.h"
namespace content {
class BrowserContext;
class WebContents;
} // namespace content
namespace wm {
class CompoundEventFilter;
} // namespace wm
namespace webui_examples {
// Represents a single window that hosts one WebContents stretched to the
// window's size.
class ContentWindow {
public:
ContentWindow(AuraContext* aura_context,
content::BrowserContext* browser_context);
ContentWindow(const ContentWindow&) = delete;
ContentWindow& operator=(const ContentWindow&) = delete;
~ContentWindow();
void SetTitle(const std::u16string& title);
void Show();
void NavigateToURL(GURL url);
void SetCloseCallback(base::OnceClosure on_close);
content::WebContents* web_contents() { return web_contents_.get(); }
private:
std::unique_ptr<AuraContext::ContextualizedWindowTreeHost> host_;
std::unique_ptr<content::WebContents> web_contents_;
std::unique_ptr<wm::CompoundEventFilter> root_window_event_filter_;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_CONTENT_WINDOW_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/ui/aura/content_window.h | C++ | unknown | 1,437 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/ui/aura/fill_layout.h"
#include "ui/aura/window.h"
namespace webui_examples {
FillLayout::FillLayout(aura::Window* root) : root_(root) {}
FillLayout::~FillLayout() = default;
void FillLayout::OnWindowResized() {
if (root_->bounds().IsEmpty())
return;
for (aura::Window* child : root_->children())
SetChildBoundsDirect(child, gfx::Rect(root_->bounds().size()));
}
void FillLayout::OnWindowAddedToLayout(aura::Window* child) {
child->SetBounds(root_->bounds());
}
void FillLayout::OnWillRemoveWindowFromLayout(aura::Window* child) {}
void FillLayout::OnWindowRemovedFromLayout(aura::Window* child) {}
void FillLayout::OnChildWindowVisibilityChanged(aura::Window* child,
bool visible) {}
void FillLayout::SetChildBounds(aura::Window* child,
const gfx::Rect& requested_bounds) {
SetChildBoundsDirect(child, requested_bounds);
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/ui/aura/fill_layout.cc | C++ | unknown | 1,142 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_FILL_LAYOUT_H_
#define UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_FILL_LAYOUT_H_
#include "base/memory/raw_ptr.h"
#include "ui/aura/layout_manager.h"
namespace aura {
class Window;
}
namespace webui_examples {
class FillLayout : public aura::LayoutManager {
public:
explicit FillLayout(aura::Window* root);
FillLayout(const FillLayout&) = delete;
FillLayout& operator=(const FillLayout&) = delete;
~FillLayout() override;
private:
// aura::LayoutManager:
void OnWindowResized() override;
void OnWindowAddedToLayout(aura::Window* child) override;
void OnWillRemoveWindowFromLayout(aura::Window* child) override;
void OnWindowRemovedFromLayout(aura::Window* child) override;
void OnChildWindowVisibilityChanged(aura::Window* child,
bool visible) override;
void SetChildBounds(aura::Window* child,
const gfx::Rect& requested_bounds) override;
raw_ptr<aura::Window> const root_;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_UI_AURA_FILL_LAYOUT_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/ui/aura/fill_layout.h | C++ | unknown | 1,240 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/ui/web/webui.h"
#include "chrome/grit/webui_gallery_resources.h"
#include "chrome/grit/webui_gallery_resources_map.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "ui/base/ui_base_features.h"
#include "ui/webui/examples/grit/webui_examples_resources.h"
namespace webui_examples {
namespace {
void EnableTrustedTypesCSP(content::WebUIDataSource* source) {
source->OverrideContentSecurityPolicy(
network::mojom::CSPDirectiveName::RequireTrustedTypesFor,
"require-trusted-types-for 'script';");
source->OverrideContentSecurityPolicy(
network::mojom::CSPDirectiveName::TrustedTypes,
"trusted-types parse-html-subset sanitize-inner-html static-types "
// Add TrustedTypes policies for cr-lottie.
"lottie-worker-script-loader "
// Add TrustedTypes policies necessary for using Polymer.
"polymer-html-literal polymer-template-event-attribute-policy;");
}
void SetJSModuleDefaults(content::WebUIDataSource* source) {
source->OverrideContentSecurityPolicy(
network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources 'self';");
source->OverrideContentSecurityPolicy(
network::mojom::CSPDirectiveName::FrameSrc, "frame-src 'self';");
source->OverrideContentSecurityPolicy(
network::mojom::CSPDirectiveName::FrameAncestors,
"frame-ancestors 'self';");
}
void SetupWebUIDataSource(content::WebUIDataSource* source,
base::span<const webui::ResourcePath> resources,
int default_resource) {
SetJSModuleDefaults(source);
EnableTrustedTypesCSP(source);
source->AddString(
"chromeRefresh2023Attribute",
features::IsChromeWebuiRefresh2023() ? "chrome-refresh-2023" : "");
source->AddResourcePaths(resources);
source->AddResourcePath("", default_resource);
}
} // namespace
WebUI::WebUI(content::WebUI* web_ui) : content::WebUIController(web_ui) {
content::WebUIDataSource* source = content::WebUIDataSource::CreateAndAdd(
web_ui->GetWebContents()->GetBrowserContext(), kHost);
SetupWebUIDataSource(
source,
base::make_span(kWebuiGalleryResources, kWebuiGalleryResourcesSize),
IDR_WEBUI_GALLERY_WEBUI_GALLERY_HTML);
}
WebUI::~WebUI() = default;
WEB_UI_CONTROLLER_TYPE_IMPL(WebUI)
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/ui/web/webui.cc | C++ | unknown | 2,600 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_UI_WEB_WEBUI_H_
#define UI_WEBUI_EXAMPLES_BROWSER_UI_WEB_WEBUI_H_
#include "content/public/browser/web_ui_controller.h"
namespace webui_examples {
class WebUI : public content::WebUIController {
public:
static constexpr char kHost[] = "main";
explicit WebUI(content::WebUI* web_ui);
WebUI(const WebUI&) = delete;
WebUI& operator=(const WebUI&) = delete;
~WebUI() override;
private:
WEB_UI_CONTROLLER_TYPE_DECL();
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_UI_WEB_WEBUI_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/ui/web/webui.h | C++ | unknown | 699 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/browser/webui_controller_factory.h"
#include "content/public/browser/web_ui_controller.h"
#include "ui/webui/examples/browser/ui/web/webui.h"
#include "url/gurl.h"
namespace {
static constexpr char kChromeScheme[] = "chrome";
} // namespace
namespace webui_examples {
WebUIControllerFactory::WebUIControllerFactory() = default;
WebUIControllerFactory::~WebUIControllerFactory() = default;
std::unique_ptr<content::WebUIController>
WebUIControllerFactory::CreateWebUIControllerForURL(content::WebUI* web_ui,
const GURL& url) {
if (url.SchemeIs(kChromeScheme) && url.host_piece() == WebUI::kHost)
return std::make_unique<WebUI>(web_ui);
return nullptr;
}
content::WebUI::TypeID WebUIControllerFactory::GetWebUIType(
content::BrowserContext* browser_context,
const GURL& url) {
if (url.SchemeIs(kChromeScheme) && url.host_piece() == WebUI::kHost)
return reinterpret_cast<content::WebUI::TypeID>(0x1);
return content::WebUI::kNoWebUI;
}
bool WebUIControllerFactory::UseWebUIForURL(
content::BrowserContext* browser_context,
const GURL& url) {
return GetWebUIType(browser_context, url) != content::WebUI::kNoWebUI;
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/webui_controller_factory.cc | C++ | unknown | 1,413 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_BROWSER_WEBUI_CONTROLLER_FACTORY_H_
#define UI_WEBUI_EXAMPLES_BROWSER_WEBUI_CONTROLLER_FACTORY_H_
#include "content/public/browser/web_ui_controller_factory.h"
namespace webui_examples {
class WebUIControllerFactory : public content::WebUIControllerFactory {
public:
WebUIControllerFactory();
WebUIControllerFactory(const WebUIControllerFactory&) = delete;
WebUIControllerFactory& operator=(const WebUIControllerFactory&) = delete;
~WebUIControllerFactory() override;
private:
// content::WebUIControllerFactory:
std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL(
content::WebUI* web_ui,
const GURL& url) override;
content::WebUI::TypeID GetWebUIType(content::BrowserContext* browser_context,
const GURL& url) override;
bool UseWebUIForURL(content::BrowserContext* browser_context,
const GURL& url) override;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_BROWSER_WEBUI_CONTROLLER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/browser/webui_controller_factory.h | C++ | unknown | 1,194 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/examples/common/content_client.h"
#include "ui/base/resource/resource_bundle.h"
namespace webui_examples {
ContentClient::ContentClient() = default;
ContentClient::~ContentClient() = default;
base::StringPiece ContentClient::GetDataResource(
int resource_id,
ui::ResourceScaleFactor scale_factor) {
return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
resource_id, scale_factor);
}
base::RefCountedMemory* ContentClient::GetDataResourceBytes(int resource_id) {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
resource_id);
}
} // namespace webui_examples
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/common/content_client.cc | C++ | unknown | 793 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_EXAMPLES_COMMON_CONTENT_CLIENT_H_
#define UI_WEBUI_EXAMPLES_COMMON_CONTENT_CLIENT_H_
#include "content/public/common/content_client.h"
namespace webui_examples {
class ContentClient : public content::ContentClient {
public:
ContentClient();
ContentClient(const ContentClient&) = delete;
ContentClient& operator=(const ContentClient&) = delete;
~ContentClient() override;
private:
// content::ContentClient:
base::StringPiece GetDataResource(
int resource_id,
ui::ResourceScaleFactor scale_factor) override;
base::RefCountedMemory* GetDataResourceBytes(int resource_id) override;
};
} // namespace webui_examples
#endif // UI_WEBUI_EXAMPLES_COMMON_CONTENT_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/examples/common/content_client.h | C++ | unknown | 862 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/mojo_bubble_web_ui_controller.h"
#include "content/public/browser/web_ui.h"
namespace ui {
MojoBubbleWebUIController::MojoBubbleWebUIController(content::WebUI* contents,
bool enable_chrome_send)
: MojoWebUIController(contents, enable_chrome_send) {}
MojoBubbleWebUIController::~MojoBubbleWebUIController() = default;
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/webui/mojo_bubble_web_ui_controller.cc | C++ | unknown | 561 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_MOJO_BUBBLE_WEB_UI_CONTROLLER_H_
#define UI_WEBUI_MOJO_BUBBLE_WEB_UI_CONTROLLER_H_
#include "base/memory/weak_ptr.h"
#include "ui/webui/mojo_web_ui_controller.h"
namespace gfx {
class Point;
}
namespace content {
class WebUI;
} // namespace content
namespace ui {
class MenuModel;
class MojoBubbleWebUIController : public MojoWebUIController {
public:
class Embedder {
public:
virtual void ShowUI() = 0;
virtual void CloseUI() = 0;
virtual void ShowContextMenu(gfx::Point point,
std::unique_ptr<ui::MenuModel> menu_model) = 0;
virtual void HideContextMenu() = 0;
};
// By default MojoBubbleWebUIController do not have normal WebUI bindings.
// Pass |enable_chrome_send| as true if these are needed.
explicit MojoBubbleWebUIController(content::WebUI* contents,
bool enable_chrome_send = false);
MojoBubbleWebUIController(const MojoBubbleWebUIController&) = delete;
MojoBubbleWebUIController& operator=(const MojoBubbleWebUIController&) =
delete;
~MojoBubbleWebUIController() override;
void set_embedder(base::WeakPtr<Embedder> embedder) { embedder_ = embedder; }
base::WeakPtr<Embedder> embedder() { return embedder_; }
private:
base::WeakPtr<Embedder> embedder_;
};
} // namespace ui
#endif // UI_WEBUI_MOJO_BUBBLE_WEB_UI_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/mojo_bubble_web_ui_controller.h | C++ | unknown | 1,530 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/mojo_web_ui_controller.h"
#include "content/public/common/bindings_policy.h"
namespace ui {
MojoWebUIController::MojoWebUIController(content::WebUI* contents,
bool enable_chrome_send)
: content::WebUIController(contents) {
int bindings = content::BINDINGS_POLICY_MOJO_WEB_UI;
if (enable_chrome_send)
bindings |= content::BINDINGS_POLICY_WEB_UI;
contents->SetBindings(bindings);
}
MojoWebUIController::~MojoWebUIController() = default;
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/webui/mojo_web_ui_controller.cc | C++ | unknown | 676 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_MOJO_WEB_UI_CONTROLLER_H_
#define UI_WEBUI_MOJO_WEB_UI_CONTROLLER_H_
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_controller.h"
namespace ui {
// MojoWebUIController is intended for WebUI pages that use Mojo. It is
// expected that subclasses will:
// . Add all Mojo Bindings Resources via AddResourcePath(), eg:
// source->AddResourcePath("chrome/browser/ui/webui/omnibox/omnibox.mojom",
// IDR_OMNIBOX_MOJO_JS);
// . Overload void BindInterface(mojo::PendingReceiver<InterfaceName>) for all
// Mojo Interfaces it wishes to handle.
// . Use WEB_UI_CONTROLLER_TYPE_DECL macro in .h file and
// WEB_UI_CONTROLLER_TYPE_IMPL macro in .cc file.
// . Register all Mojo Interfaces it wishes to handle in the appropriate
// BinderMap:
// - chrome/browser/chrome_browser_interface_binders.cc for chrome/ WebUIs;
// - content/browser/browser_interface_binders.cc for content/ WebUIs.
class MojoWebUIController : public content::WebUIController {
public:
// By default MojoWebUIControllers do not have normal WebUI bindings. Pass
// |enable_chrome_send| as true if these are needed.
explicit MojoWebUIController(content::WebUI* contents,
bool enable_chrome_send = false);
MojoWebUIController(const MojoWebUIController&) = delete;
MojoWebUIController& operator=(const MojoWebUIController&) = delete;
~MojoWebUIController() override;
};
} // namespace ui
#endif // UI_WEBUI_MOJO_WEB_UI_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/mojo_web_ui_controller.h | C++ | unknown | 1,687 |
# Copyright 2016 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
USE_PYTHON3 = True
PRESUBMIT_VERSION = '2.0.0'
def CheckForTranslations(input_api, output_api):
shared_keywords = ['i18n(']
html_keywords = shared_keywords + ['$118n{']
js_keywords = shared_keywords + ['I18nBehavior', 'loadTimeData.get']
errors = []
for f in input_api.AffectedFiles():
local_path = f.LocalPath()
# Allow translation in i18n_behavior.js.
if local_path.endswith('i18n_behavior.js'):
continue
# Allow translation in the cr_components directory.
if 'cr_components' in local_path:
continue
keywords = None
if local_path.endswith('.js'):
keywords = js_keywords
elif local_path.endswith('.html'):
keywords = html_keywords
if not keywords:
continue
for lnum, line in f.ChangedContents():
if any(line for keyword in keywords if keyword in line):
errors.append("%s:%d\n%s" % (f.LocalPath(), lnum, line))
if not errors:
return []
return [output_api.PresubmitError("\n".join(errors) + """
Don't embed translations directly in shared UI code. Instead, inject your
translation from the place using the shared code. For an example: see
<cr-dialog>#closeText (http://bit.ly/2eLEsqh).""")]
def CheckSvgsOptimized(input_api, output_api):
results = []
try:
import sys
old_sys_path = sys.path[:]
cwd = input_api.PresubmitLocalPath()
sys.path += [input_api.os_path.join(cwd, '..', '..', '..', 'tools')]
from resources import svgo_presubmit
results += svgo_presubmit.CheckOptimized(input_api, output_api)
finally:
sys.path = old_sys_path
return results
def CheckWebDevStyle(input_api, output_api):
results = []
try:
import sys
old_sys_path = sys.path[:]
cwd = input_api.PresubmitLocalPath()
sys.path += [input_api.os_path.join(cwd, '..', '..', '..', 'tools')]
from web_dev_style import presubmit_support
results += presubmit_support.CheckStyle(input_api, output_api)
finally:
sys.path = old_sys_path
return results
def CheckNoDisallowedJS(input_api, output_api):
# Ignore legacy files from the js/ subfolder along with tools/.
EXCLUDE_PATH_PREFIXES = [
'ui/webui/resources/js/dom_automation_controller.js',
'ui/webui/resources/js/ios/',
'ui/webui/resources/js/load_time_data_deprecated.js',
'ui/webui/resources/js/util_deprecated.js',
'ui/webui/resources/tools/',
]
normalized_excluded_prefixes = []
for path in EXCLUDE_PATH_PREFIXES:
normalized_excluded_prefixes.append(input_api.os_path.normpath(path))
# Also exempt any externs or eslint files, which must be in JS.
EXCLUDE_PATH_SUFFIXES = [
'_externs.js',
'.eslintrc.js',
]
def allow_js(f):
path = f.LocalPath()
for prefix in normalized_excluded_prefixes:
if path.startswith(prefix):
return True
for suffix in EXCLUDE_PATH_SUFFIXES:
if path.endswith(suffix):
return True
return False
from web_dev_style import presubmit_support
return presubmit_support.DisallowNewJsFiles(input_api, output_api,
lambda f: not allow_js(f))
def CheckPatchFormatted(input_api, output_api):
return input_api.canned_checks.CheckPatchFormatted(input_api, output_api,
check_js=True)
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/PRESUBMIT.py | Python | unknown | 3,442 |
specific_include_rules = {
"app_management_mojom_traits\.*": [
"+components/services/app_service/public",
],
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/DEPS | Python | unknown | 119 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/webui/resources/cr_components/app_management/app_management_mojom_traits.h"
#include <utility>
namespace mojo {
AppType EnumTraits<AppType, apps::AppType>::ToMojom(apps::AppType input) {
switch (input) {
case apps::AppType::kUnknown:
return AppType::kUnknown;
case apps::AppType::kArc:
return AppType::kArc;
case apps::AppType::kBuiltIn:
return AppType::kBuiltIn;
case apps::AppType::kCrostini:
return AppType::kCrostini;
case apps::AppType::kChromeApp:
return AppType::kChromeApp;
case apps::AppType::kWeb:
return AppType::kWeb;
case apps::AppType::kMacOs:
return AppType::kMacOs;
case apps::AppType::kPluginVm:
return AppType::kPluginVm;
case apps::AppType::kStandaloneBrowser:
return AppType::kStandaloneBrowser;
case apps::AppType::kRemote:
return AppType::kRemote;
case apps::AppType::kBorealis:
return AppType::kBorealis;
case apps::AppType::kSystemWeb:
return AppType::kSystemWeb;
case apps::AppType::kStandaloneBrowserChromeApp:
return AppType::kStandaloneBrowserChromeApp;
case apps::AppType::kExtension:
return AppType::kExtension;
case apps::AppType::kStandaloneBrowserExtension:
return AppType::kStandaloneBrowserExtension;
case apps::AppType::kBruschetta:
return AppType::kBruschetta;
}
}
bool EnumTraits<AppType, apps::AppType>::FromMojom(AppType input,
apps::AppType* output) {
switch (input) {
case AppType::kUnknown:
*output = apps::AppType::kUnknown;
return true;
case AppType::kArc:
*output = apps::AppType::kArc;
return true;
case AppType::kBuiltIn:
*output = apps::AppType::kBuiltIn;
return true;
case AppType::kCrostini:
*output = apps::AppType::kCrostini;
return true;
case AppType::kChromeApp:
*output = apps::AppType::kChromeApp;
return true;
case AppType::kWeb:
*output = apps::AppType::kWeb;
return true;
case AppType::kMacOs:
*output = apps::AppType::kMacOs;
return true;
case AppType::kPluginVm:
*output = apps::AppType::kPluginVm;
return true;
case AppType::kStandaloneBrowser:
*output = apps::AppType::kStandaloneBrowser;
return true;
case AppType::kRemote:
*output = apps::AppType::kRemote;
return true;
case AppType::kBorealis:
*output = apps::AppType::kBorealis;
return true;
case AppType::kSystemWeb:
*output = apps::AppType::kSystemWeb;
return true;
case AppType::kStandaloneBrowserChromeApp:
*output = apps::AppType::kStandaloneBrowserChromeApp;
return true;
case AppType::kExtension:
*output = apps::AppType::kExtension;
return true;
case AppType::kStandaloneBrowserExtension:
*output = apps::AppType::kStandaloneBrowserExtension;
return true;
case AppType::kBruschetta:
*output = apps::AppType::kBruschetta;
return true;
}
}
bool StructTraits<PermissionDataView, apps::PermissionPtr>::Read(
PermissionDataView data,
apps::PermissionPtr* out) {
apps::PermissionType permission_type;
if (!data.ReadPermissionType(&permission_type))
return false;
apps::PermissionValuePtr value;
if (!data.ReadValue(&value))
return false;
*out = std::make_unique<apps::Permission>(permission_type, std::move(value),
data.is_managed());
return true;
}
PermissionType EnumTraits<PermissionType, apps::PermissionType>::ToMojom(
apps::PermissionType input) {
switch (input) {
case apps::PermissionType::kUnknown:
return PermissionType::kUnknown;
case apps::PermissionType::kCamera:
return PermissionType::kCamera;
case apps::PermissionType::kLocation:
return PermissionType::kLocation;
case apps::PermissionType::kMicrophone:
return PermissionType::kMicrophone;
case apps::PermissionType::kNotifications:
return PermissionType::kNotifications;
case apps::PermissionType::kContacts:
return PermissionType::kContacts;
case apps::PermissionType::kStorage:
return PermissionType::kStorage;
case apps::PermissionType::kPrinting:
return PermissionType::kPrinting;
case apps::PermissionType::kFileHandling:
return PermissionType::kFileHandling;
}
}
bool EnumTraits<PermissionType, apps::PermissionType>::FromMojom(
PermissionType input,
apps::PermissionType* output) {
switch (input) {
case PermissionType::kUnknown:
*output = apps::PermissionType::kUnknown;
return true;
case PermissionType::kCamera:
*output = apps::PermissionType::kCamera;
return true;
case PermissionType::kLocation:
*output = apps::PermissionType::kLocation;
return true;
case PermissionType::kMicrophone:
*output = apps::PermissionType::kMicrophone;
return true;
case PermissionType::kNotifications:
*output = apps::PermissionType::kNotifications;
return true;
case PermissionType::kContacts:
*output = apps::PermissionType::kContacts;
return true;
case PermissionType::kStorage:
*output = apps::PermissionType::kStorage;
return true;
case PermissionType::kPrinting:
*output = apps::PermissionType::kPrinting;
return true;
case PermissionType::kFileHandling:
*output = apps::PermissionType::kFileHandling;
return true;
}
}
TriState EnumTraits<TriState, apps::TriState>::ToMojom(apps::TriState input) {
switch (input) {
case apps::TriState::kAllow:
return TriState::kAllow;
case apps::TriState::kBlock:
return TriState::kBlock;
case apps::TriState::kAsk:
return TriState::kAsk;
}
}
bool EnumTraits<TriState, apps::TriState>::FromMojom(TriState input,
apps::TriState* output) {
switch (input) {
case TriState::kAllow:
*output = apps::TriState::kAllow;
return true;
case TriState::kBlock:
*output = apps::TriState::kBlock;
return true;
case TriState::kAsk:
*output = apps::TriState::kAsk;
return true;
}
}
PermissionValueDataView::Tag
UnionTraits<PermissionValueDataView, apps::PermissionValuePtr>::GetTag(
const apps::PermissionValuePtr& r) {
if (absl::holds_alternative<bool>(r->value)) {
return PermissionValueDataView::Tag::kBoolValue;
} else if (absl::holds_alternative<apps::TriState>(r->value)) {
return PermissionValueDataView::Tag::kTristateValue;
}
NOTREACHED();
return PermissionValueDataView::Tag::kBoolValue;
}
bool UnionTraits<PermissionValueDataView, apps::PermissionValuePtr>::Read(
PermissionValueDataView data,
apps::PermissionValuePtr* out) {
switch (data.tag()) {
case PermissionValueDataView::Tag::kBoolValue: {
*out = std::make_unique<apps::PermissionValue>(data.bool_value());
return true;
}
case PermissionValueDataView::Tag::kTristateValue: {
apps::TriState tristate_value;
if (!data.ReadTristateValue(&tristate_value))
return false;
*out = std::make_unique<apps::PermissionValue>(tristate_value);
return true;
}
}
NOTREACHED();
return false;
}
InstallReason EnumTraits<InstallReason, apps::InstallReason>::ToMojom(
apps::InstallReason input) {
switch (input) {
case apps::InstallReason::kUnknown:
return InstallReason::kUnknown;
case apps::InstallReason::kSystem:
return InstallReason::kSystem;
case apps::InstallReason::kPolicy:
return InstallReason::kPolicy;
case apps::InstallReason::kOem:
return InstallReason::kOem;
case apps::InstallReason::kDefault:
return InstallReason::kDefault;
case apps::InstallReason::kSync:
return InstallReason::kSync;
case apps::InstallReason::kUser:
return InstallReason::kUser;
case apps::InstallReason::kSubApp:
return InstallReason::kSubApp;
case apps::InstallReason::kKiosk:
return InstallReason::kKiosk;
case apps::InstallReason::kCommandLine:
return InstallReason::kCommandLine;
}
}
bool EnumTraits<InstallReason, apps::InstallReason>::FromMojom(
InstallReason input,
apps::InstallReason* output) {
switch (input) {
case InstallReason::kUnknown:
*output = apps::InstallReason::kUnknown;
return true;
case InstallReason::kSystem:
*output = apps::InstallReason::kSystem;
return true;
case InstallReason::kPolicy:
*output = apps::InstallReason::kPolicy;
return true;
case InstallReason::kOem:
*output = apps::InstallReason::kOem;
return true;
case InstallReason::kDefault:
*output = apps::InstallReason::kDefault;
return true;
case InstallReason::kSync:
*output = apps::InstallReason::kSync;
return true;
case InstallReason::kUser:
*output = apps::InstallReason::kUser;
return true;
case InstallReason::kSubApp:
*output = apps::InstallReason::kSubApp;
return true;
case InstallReason::kKiosk:
*output = apps::InstallReason::kKiosk;
return true;
case InstallReason::kCommandLine:
*output = apps::InstallReason::kCommandLine;
return true;
}
}
InstallSource EnumTraits<InstallSource, apps::InstallSource>::ToMojom(
apps::InstallSource input) {
switch (input) {
case apps::InstallSource::kUnknown:
return InstallSource::kUnknown;
case apps::InstallSource::kSystem:
return InstallSource::kSystem;
case apps::InstallSource::kSync:
return InstallSource::kSync;
case apps::InstallSource::kPlayStore:
return InstallSource::kPlayStore;
case apps::InstallSource::kChromeWebStore:
return InstallSource::kChromeWebStore;
case apps::InstallSource::kBrowser:
return InstallSource::kBrowser;
}
}
bool EnumTraits<InstallSource, apps::InstallSource>::FromMojom(
InstallSource input,
apps::InstallSource* output) {
switch (input) {
case InstallSource::kUnknown:
*output = apps::InstallSource::kUnknown;
return true;
case InstallSource::kSystem:
*output = apps::InstallSource::kSystem;
return true;
case InstallSource::kSync:
*output = apps::InstallSource::kSync;
return true;
case InstallSource::kPlayStore:
*output = apps::InstallSource::kPlayStore;
return true;
case InstallSource::kChromeWebStore:
*output = apps::InstallSource::kChromeWebStore;
return true;
case InstallSource::kBrowser:
*output = apps::InstallSource::kBrowser;
return true;
}
}
WindowMode EnumTraits<WindowMode, apps::WindowMode>::ToMojom(
apps::WindowMode input) {
switch (input) {
case apps::WindowMode::kUnknown:
return WindowMode::kUnknown;
case apps::WindowMode::kWindow:
return WindowMode::kWindow;
case apps::WindowMode::kBrowser:
return WindowMode::kBrowser;
case apps::WindowMode::kTabbedWindow:
return WindowMode::kTabbedWindow;
}
}
bool EnumTraits<WindowMode, apps::WindowMode>::FromMojom(
WindowMode input,
apps::WindowMode* output) {
switch (input) {
case WindowMode::kUnknown:
*output = apps::WindowMode::kUnknown;
return true;
case WindowMode::kWindow:
*output = apps::WindowMode::kWindow;
return true;
case WindowMode::kBrowser:
*output = apps::WindowMode::kBrowser;
return true;
case WindowMode::kTabbedWindow:
*output = apps::WindowMode::kTabbedWindow;
return true;
}
}
RunOnOsLoginMode EnumTraits<RunOnOsLoginMode, apps::RunOnOsLoginMode>::ToMojom(
apps::RunOnOsLoginMode input) {
switch (input) {
case apps::RunOnOsLoginMode::kUnknown:
return RunOnOsLoginMode::kUnknown;
case apps::RunOnOsLoginMode::kNotRun:
return RunOnOsLoginMode::kNotRun;
case apps::RunOnOsLoginMode::kWindowed:
return RunOnOsLoginMode::kWindowed;
}
}
bool EnumTraits<RunOnOsLoginMode, apps::RunOnOsLoginMode>::FromMojom(
RunOnOsLoginMode input,
apps::RunOnOsLoginMode* output) {
switch (input) {
case RunOnOsLoginMode::kUnknown:
*output = apps::RunOnOsLoginMode::kUnknown;
return true;
case RunOnOsLoginMode::kNotRun:
*output = apps::RunOnOsLoginMode::kNotRun;
return true;
case RunOnOsLoginMode::kWindowed:
*output = apps::RunOnOsLoginMode::kWindowed;
return true;
}
}
bool StructTraits<RunOnOsLoginDataView, apps::RunOnOsLoginPtr>::Read(
RunOnOsLoginDataView data,
apps::RunOnOsLoginPtr* out) {
apps::RunOnOsLoginMode login_mode;
if (!data.ReadLoginMode(&login_mode))
return false;
*out = std::make_unique<apps::RunOnOsLogin>(login_mode, data.is_managed());
return true;
}
} // namespace mojo
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/app_management_mojom_traits.cc | C++ | unknown | 12,999 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_WEBUI_RESOURCES_CR_COMPONENTS_APP_MANAGEMENT_APP_MANAGEMENT_MOJOM_TRAITS_H_
#define UI_WEBUI_RESOURCES_CR_COMPONENTS_APP_MANAGEMENT_APP_MANAGEMENT_MOJOM_TRAITS_H_
#include "components/services/app_service/public/cpp/app_types.h"
#include "components/services/app_service/public/cpp/permission.h"
#include "components/services/app_service/public/cpp/run_on_os_login_types.h"
#include "third_party/abseil-cpp/absl/types/variant.h"
#include "ui/webui/resources/cr_components/app_management/app_management.mojom.h"
namespace mojo {
namespace {
using AppType = app_management::mojom::AppType;
using PermissionDataView = app_management::mojom::PermissionDataView;
using PermissionType = app_management::mojom::PermissionType;
using TriState = app_management::mojom::TriState;
using PermissionValueDataView = app_management::mojom::PermissionValueDataView;
using InstallReason = app_management::mojom::InstallReason;
using InstallSource = app_management::mojom::InstallSource;
using WindowMode = app_management::mojom::WindowMode;
using RunOnOsLoginMode = app_management::mojom::RunOnOsLoginMode;
using RunOnOsLoginDataView = app_management::mojom::RunOnOsLoginDataView;
} // namespace
template <>
struct EnumTraits<AppType, apps::AppType> {
static AppType ToMojom(apps::AppType input);
static bool FromMojom(AppType input, apps::AppType* output);
};
template <>
struct StructTraits<PermissionDataView, apps::PermissionPtr> {
static apps::PermissionType permission_type(const apps::PermissionPtr& r) {
return r->permission_type;
}
static const apps::PermissionValuePtr& value(const apps::PermissionPtr& r) {
return r->value;
}
static bool is_managed(const apps::PermissionPtr& r) { return r->is_managed; }
static bool Read(PermissionDataView, apps::PermissionPtr* out);
};
template <>
struct EnumTraits<PermissionType, apps::PermissionType> {
static PermissionType ToMojom(apps::PermissionType input);
static bool FromMojom(PermissionType input, apps::PermissionType* output);
};
template <>
struct EnumTraits<TriState, apps::TriState> {
static TriState ToMojom(apps::TriState input);
static bool FromMojom(TriState input, apps::TriState* output);
};
template <>
struct UnionTraits<PermissionValueDataView, apps::PermissionValuePtr> {
static PermissionValueDataView::Tag GetTag(const apps::PermissionValuePtr& r);
static bool IsNull(const apps::PermissionValuePtr& r) {
return !absl::holds_alternative<bool>(r->value) &&
!absl::holds_alternative<apps::TriState>(r->value);
}
static void SetToNull(apps::PermissionValuePtr* out) { out->reset(); }
static bool bool_value(const apps::PermissionValuePtr& r) {
if (absl::holds_alternative<bool>(r->value)) {
return absl::get<bool>(r->value);
}
return false;
}
static apps::TriState tristate_value(const apps::PermissionValuePtr& r) {
if (absl::holds_alternative<apps::TriState>(r->value)) {
return absl::get<apps::TriState>(r->value);
}
return apps::TriState::kBlock;
}
static bool Read(PermissionValueDataView data, apps::PermissionValuePtr* out);
};
template <>
struct EnumTraits<InstallReason, apps::InstallReason> {
static InstallReason ToMojom(apps::InstallReason input);
static bool FromMojom(InstallReason input, apps::InstallReason* output);
};
template <>
struct EnumTraits<InstallSource, apps::InstallSource> {
static InstallSource ToMojom(apps::InstallSource input);
static bool FromMojom(InstallSource input, apps::InstallSource* output);
};
template <>
struct EnumTraits<WindowMode, apps::WindowMode> {
static WindowMode ToMojom(apps::WindowMode input);
static bool FromMojom(WindowMode input, apps::WindowMode* output);
};
template <>
struct EnumTraits<RunOnOsLoginMode, apps::RunOnOsLoginMode> {
static RunOnOsLoginMode ToMojom(apps::RunOnOsLoginMode input);
static bool FromMojom(RunOnOsLoginMode input, apps::RunOnOsLoginMode* output);
};
template <>
struct StructTraits<RunOnOsLoginDataView, apps::RunOnOsLoginPtr> {
static apps::RunOnOsLoginMode login_mode(const apps::RunOnOsLoginPtr& r) {
return r->login_mode;
}
static bool is_managed(const apps::RunOnOsLoginPtr& r) {
return r->is_managed;
}
static bool Read(RunOnOsLoginDataView, apps::RunOnOsLoginPtr* out);
};
} // namespace mojo
#endif // UI_WEBUI_RESOURCES_CR_COMPONENTS_APP_MANAGEMENT_APP_MANAGEMENT_MOJOM_TRAITS_H_
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/app_management_mojom_traits.h | C++ | unknown | 4,553 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <utility>
#include "components/services/app_service/public/cpp/app_types.h"
#include "components/services/app_service/public/cpp/permission.h"
#include "components/services/app_service/public/cpp/run_on_os_login_types.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/webui/resources/cr_components/app_management/app_management.mojom.h"
#include "ui/webui/resources/cr_components/app_management/app_management_mojom_traits.h"
TEST(AppManagementMojomTraitsTest, RoundTripAppType) {
static constexpr apps::AppType kTestAppType[] = {
apps::AppType::kUnknown,
apps::AppType::kArc,
apps::AppType::kBuiltIn,
apps::AppType::kCrostini,
apps::AppType::kChromeApp,
apps::AppType::kWeb,
apps::AppType::kMacOs,
apps::AppType::kPluginVm,
apps::AppType::kStandaloneBrowser,
apps::AppType::kRemote,
apps::AppType::kBorealis,
apps::AppType::kSystemWeb,
apps::AppType::kStandaloneBrowserChromeApp,
apps::AppType::kExtension};
for (auto app_type_in : kTestAppType) {
apps::AppType app_type_out;
app_management::mojom::AppType serialized_app_type =
mojo::EnumTraits<app_management::mojom::AppType,
apps::AppType>::ToMojom(app_type_in);
ASSERT_TRUE((mojo::EnumTraits<app_management::mojom::AppType,
apps::AppType>::FromMojom(serialized_app_type,
&app_type_out)));
EXPECT_EQ(app_type_in, app_type_out);
}
}
TEST(AppManagementMojomTraitsTest, RoundTripPermissions) {
{
auto permission = std::make_unique<apps::Permission>(
apps::PermissionType::kUnknown,
std::make_unique<apps::PermissionValue>(true),
/*is_managed=*/false);
apps::PermissionPtr output;
ASSERT_TRUE(
mojo::test::SerializeAndDeserialize<app_management::mojom::Permission>(
permission, output));
EXPECT_EQ(*permission, *output);
}
{
auto permission = std::make_unique<apps::Permission>(
apps::PermissionType::kCamera,
std::make_unique<apps::PermissionValue>(true),
/*is_managed=*/true);
apps::PermissionPtr output;
ASSERT_TRUE(
mojo::test::SerializeAndDeserialize<app_management::mojom::Permission>(
permission, output));
EXPECT_EQ(*permission, *output);
}
{
auto permission = std::make_unique<apps::Permission>(
apps::PermissionType::kLocation,
std::make_unique<apps::PermissionValue>(apps::TriState::kAllow),
/*is_managed=*/false);
apps::PermissionPtr output;
ASSERT_TRUE(
mojo::test::SerializeAndDeserialize<app_management::mojom::Permission>(
permission, output));
EXPECT_EQ(*permission, *output);
}
{
auto permission = std::make_unique<apps::Permission>(
apps::PermissionType::kMicrophone,
std::make_unique<apps::PermissionValue>(apps::TriState::kBlock),
/*is_managed=*/true);
apps::PermissionPtr output;
ASSERT_TRUE(
mojo::test::SerializeAndDeserialize<app_management::mojom::Permission>(
permission, output));
EXPECT_EQ(*permission, *output);
}
{
auto permission = std::make_unique<apps::Permission>(
apps::PermissionType::kNotifications,
std::make_unique<apps::PermissionValue>(apps::TriState::kAsk),
/*is_managed=*/false);
apps::PermissionPtr output;
ASSERT_TRUE(
mojo::test::SerializeAndDeserialize<app_management::mojom::Permission>(
permission, output));
EXPECT_EQ(*permission, *output);
}
{
auto permission = std::make_unique<apps::Permission>(
apps::PermissionType::kContacts,
std::make_unique<apps::PermissionValue>(apps::TriState::kAllow),
/*is_managed=*/true);
apps::PermissionPtr output;
ASSERT_TRUE(
mojo::test::SerializeAndDeserialize<app_management::mojom::Permission>(
permission, output));
EXPECT_EQ(*permission, *output);
}
{
auto permission = std::make_unique<apps::Permission>(
apps::PermissionType::kStorage,
std::make_unique<apps::PermissionValue>(apps::TriState::kBlock),
/*is_managed=*/false);
apps::PermissionPtr output;
ASSERT_TRUE(
mojo::test::SerializeAndDeserialize<app_management::mojom::Permission>(
permission, output));
EXPECT_EQ(*permission, *output);
}
{
auto permission = std::make_unique<apps::Permission>(
apps::PermissionType::kPrinting,
std::make_unique<apps::PermissionValue>(apps::TriState::kBlock),
/*is_managed=*/false);
apps::PermissionPtr output;
ASSERT_TRUE(
mojo::test::SerializeAndDeserialize<app_management::mojom::Permission>(
permission, output));
EXPECT_EQ(*permission, *output);
}
}
TEST(AppManagementMojomTraitsTest, RoundTripInstallReason) {
static constexpr apps::InstallReason kTestInstallReason[] = {
apps::InstallReason::kUnknown, apps::InstallReason::kSystem,
apps::InstallReason::kPolicy, apps::InstallReason::kOem,
apps::InstallReason::kDefault, apps::InstallReason::kSync,
apps::InstallReason::kUser, apps::InstallReason::kSubApp,
apps::InstallReason::kKiosk, apps::InstallReason::kCommandLine};
for (auto install_reason_in : kTestInstallReason) {
apps::InstallReason install_reason_out;
app_management::mojom::InstallReason serialized_install_reason =
mojo::EnumTraits<app_management::mojom::InstallReason,
apps::InstallReason>::ToMojom(install_reason_in);
ASSERT_TRUE((mojo::EnumTraits<
app_management::mojom::InstallReason,
apps::InstallReason>::FromMojom(serialized_install_reason,
&install_reason_out)));
EXPECT_EQ(install_reason_in, install_reason_out);
}
}
TEST(AppManagementMojomTraitsTest, RoundTripInstallSource) {
static constexpr apps::InstallSource kTestInstallSource[] = {
apps::InstallSource::kUnknown, apps::InstallSource::kSystem,
apps::InstallSource::kSync, apps::InstallSource::kPlayStore,
apps::InstallSource::kChromeWebStore, apps::InstallSource::kBrowser};
for (auto install_source_in : kTestInstallSource) {
apps::InstallSource install_source_out;
app_management::mojom::InstallSource serialized_install_source =
mojo::EnumTraits<app_management::mojom::InstallSource,
apps::InstallSource>::ToMojom(install_source_in);
ASSERT_TRUE((mojo::EnumTraits<
app_management::mojom::InstallSource,
apps::InstallSource>::FromMojom(serialized_install_source,
&install_source_out)));
EXPECT_EQ(install_source_in, install_source_out);
}
}
TEST(AppManagementMojomTraitsTest, RoundTripWindowMode) {
static constexpr apps::WindowMode kTestWindowMode[] = {
apps::WindowMode::kUnknown, apps::WindowMode::kWindow,
apps::WindowMode::kBrowser, apps::WindowMode::kTabbedWindow};
for (auto window_mode_in : kTestWindowMode) {
apps::WindowMode window_mode_out;
app_management::mojom::WindowMode serialized_window_mode =
mojo::EnumTraits<app_management::mojom::WindowMode,
apps::WindowMode>::ToMojom(window_mode_in);
ASSERT_TRUE(
(mojo::EnumTraits<app_management::mojom::WindowMode,
apps::WindowMode>::FromMojom(serialized_window_mode,
&window_mode_out)));
EXPECT_EQ(window_mode_in, window_mode_out);
}
}
TEST(AppManagementMojomTraitsTest, RoundTripRunOnOsLogin) {
{
auto run_on_os_login =
std::make_unique<apps::RunOnOsLogin>(apps::RunOnOsLoginMode::kUnknown,
/*is_managed=*/false);
apps::RunOnOsLoginPtr output;
ASSERT_TRUE(mojo::test::SerializeAndDeserialize<
app_management::mojom::RunOnOsLogin>(run_on_os_login, output));
EXPECT_EQ(*run_on_os_login, *output);
}
{
auto run_on_os_login =
std::make_unique<apps::RunOnOsLogin>(apps::RunOnOsLoginMode::kNotRun,
/*is_managed=*/true);
apps::RunOnOsLoginPtr output;
ASSERT_TRUE(mojo::test::SerializeAndDeserialize<
app_management::mojom::RunOnOsLogin>(run_on_os_login, output));
EXPECT_EQ(*run_on_os_login, *output);
}
{
auto run_on_os_login =
std::make_unique<apps::RunOnOsLogin>(apps::RunOnOsLoginMode::kWindowed,
/*is_managed=*/false);
apps::RunOnOsLoginPtr output;
ASSERT_TRUE(mojo::test::SerializeAndDeserialize<
app_management::mojom::RunOnOsLogin>(run_on_os_login, output));
EXPECT_EQ(*run_on_os_login, *output);
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/app_management_mojom_traits_unittests.cc | C++ | unknown | 9,129 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=./shared_vars.css.js
* #import=//resources/cr_elements/cr_shared_style.css.js
* #import=//resources/cr_elements/cr_shared_vars.css.js
<if expr='not chromeos_ash'>
* #include=cr-shared-style
</if>
<if expr='chromeos_ash'>
* #import=chrome://resources/cr_elements/chromeos/cros_color_overrides.css.js
* #include=cr-shared-style cros-color-overrides
</if>
* #css_wrapper_metadata_end */
.card-container {
border-radius: var(--cr-card-border-radius);
box-shadow: var(--cr-card-shadow);
display: flex;
flex-direction: column;
margin: 24px auto;
max-width: var(--card-max-width);
min-width: var(--card-min-width);
}
.separated-row {
align-items: center;
display: inline-flex;
justify-content: space-between;
}
.card-row {
border-top: var(--card-separator);
padding: 0 24px;
}
.permission-card-row {
border-bottom: var(--card-separator);
padding: 0 20px;
}
.permission-text-row {
border-top: var(--card-separator);
display: flex;
flex-direction: column;
height: var(--text-permission-list-row-height);
justify-content: center;
}
.permission-section-header {
line-height: 48px;
}
.clickable {
cursor: pointer;
}
.permission-card-row:last-child {
border-style: none;
}
.permission-card-row[hide-bottom-border] {
border-bottom: none;
}
.header-text {
color: var(--header-text-color);
font-weight: var(--header-font-weight);
}
.permission-row-controls {
align-items: center;
display: inline-flex;
}
.permission-list {
display: flex;
flex-direction: column;
}
.permission-list > * {
flex: 0 0 var(--permission-list-item-height);
}
.row-with-description {
flex: 0 0 var(--permission-list-item-with-description-height);
}
.native-settings-icon {
display: flex;
margin-inline-start: 0;
}
.subpermission-row {
border-bottom: var(--card-separator);
height: 48px;
}
.subpermission-row[available_]:last-of-type {
border-bottom: none;
}
.secondary-text {
color: var(--secondary-text-color);
font-weight: var(--secondary-font-weight);
}
.expand-button {
height: 36px;
margin-inline-end: 12px;
width: 36px;
}
.horizontal-align {
align-items: center;
display: flex;
}
.expander-list-row {
align-items: center;
border-top: var(--card-separator);
color: var(--secondary-text-color);
display: flex;
height: 50px;
justify-content: space-between;
padding-inline-end: 8px;
padding-inline-start: 24px;
}
.page-title {
flex: 1;
font-size: 16px;
overflow: hidden;
text-overflow: ellipsis;
}
.indented-permission-block {
padding-inline-start: 36px;
}
.info-text-row {
display: flex;
flex: 0 0 var(--info-text-row-height);
}
#info-icon {
float: inline-block;
height: var(--help-icon-size);
padding-inline-end: var(--help-icon-padding);
width: var(--help-icon-size);
}
#info-text {
float: inline-block;
overflow-wrap: break-word;
}
.indented-app-details {
margin-inline-start: 20px;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/app_management_shared_style.css | CSS | unknown | 3,117 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {PageCallbackRouter, PageHandlerFactory, PageHandlerInterface, PageHandlerRemote} from './app_management.mojom-webui.js';
export class BrowserProxy {
callbackRouter: PageCallbackRouter;
handler: PageHandlerInterface;
constructor() {
this.callbackRouter = new PageCallbackRouter();
this.handler = new PageHandlerRemote();
const factory = PageHandlerFactory.getRemote();
factory.createPageHandler(
this.callbackRouter.$.bindNewPipeAndPassRemote(),
(this.handler as PageHandlerRemote).$.bindNewPipeAndPassReceiver());
}
recordEnumerationValue(metricName: string, value: number, enumSize: number) {
chrome.metricsPrivate.recordEnumerationValue(metricName, value, enumSize);
}
static getInstance(): BrowserProxy {
return instance || (instance = new BrowserProxy());
}
static setInstance(obj: BrowserProxy) {
instance = obj;
}
}
let instance: BrowserProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/browser_proxy.ts | TypeScript | unknown | 1,086 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export {AppType, InstallReason, InstallSource, OptionalBool, RunOnOsLogin, RunOnOsLoginMode, WindowMode} from './app_management.mojom-webui.js';
/**
* The number of apps displayed in app list in the main view before expanding.
*/
export const NUMBER_OF_APPS_DISPLAYED_DEFAULT = 4;
// Enumeration of the different subpage types within the app management page.
export enum PageType {
MAIN = 0,
DETAIL = 1,
}
// This histogram is also declared and used at chrome/browser/ui/webui/settings/
// chromeos/app_management/app_management_uma.h.
export const AppManagementEntryPointsHistogramName =
'AppManagement.EntryPoints';
/**
* These values are persisted to logs and should not be renumbered or re-used.
* See tools/metrics/histograms/enums.xml.
*/
export enum AppManagementEntryPoint {
APP_LIST_CONTEXT_MENU_APP_INFO_ARC = 0,
APP_LIST_CONTEXT_MENU_APP_INFO_CHROME_APP = 1,
APP_LIST_CONTEXT_MENU_APP_INFO_WEB_APP = 2,
SHELF_CONTEXT_MENU_APP_INFO_ARC = 3,
SHELF_CONTEXT_MENU_APP_INFO_CHROME_APP = 4,
SHELF_CONTEXT_MENU_APP_INFO_WEB_APP = 5,
MAIN_VIEW_ARC = 6,
MAIN_VIEW_CHROME_APP = 7,
MAIN_VIEW_WEB_APP = 8,
OS_SETTINGS_MAIN_PAGE = 9,
MAIN_VIEW_PLUGIN_VM = 10,
D_BUS_SERVICE_PLUGIN_VM = 11,
MAIN_VIEW_BOREALIS = 12,
}
/**
* These values are persisted to logs and should not be renumbered or re-used.
* See tools/metrics/histograms/enums.xml.
*/
export enum AppManagementUserAction {
VIEW_OPENED = 0,
NATIVE_SETTINGS_OPENED = 1,
UNINSTALL_DIALOG_LAUNCHED = 2,
PIN_TO_SHELF_TURNED_ON = 3,
PIN_TO_SHELF_TURNED_OFF = 4,
NOTIFICATIONS_TURNED_ON = 5,
NOTIFICATIONS_TURNED_OFF = 6,
LOCATION_TURNED_ON = 7,
LOCATION_TURNED_OFF = 8,
CAMERA_TURNED_ON = 9,
CAMERA_TURNED_OFF = 10,
MICROPHONE_TURNED_ON = 11,
MICROPHONE_TURNED_OFF = 12,
CONTACTS_TURNED_ON = 13,
CONTACTS_TURNED_OFF = 14,
STORAGE_TURNED_ON = 15,
STORAGE_TURNED_OFF = 16,
PRINTING_TURNED_ON = 17,
PRINTING_TURNED_OFF = 18,
RESIZE_LOCK_TURNED_ON = 19,
RESIZE_LOCK_TURNED_OFF = 20,
PREFERRED_APP_TURNED_ON = 21,
PREFERRED_APP_TURNED_OFF = 22,
SUPPORTED_LINKS_LIST_SHOWN = 23,
OVERLAPPING_APPS_DIALOG_SHOWN = 24,
WINDOW_MODE_CHANGED_TO_BROWSER = 25,
WINDOW_MODE_CHANGED_TO_WINDOW = 26,
RUN_ON_OS_LOGIN_MODE_TURNED_ON = 27,
RUN_ON_OS_LOGIN_MODE_TURNED_OFF = 28,
FILE_HANDLING_TURNED_ON = 29,
FILE_HANDLING_TURNED_OFF = 30,
FILE_HANDLING_OVERFLOW_SHOWN = 31,
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/constants.ts | TypeScript | unknown | 2,560 |
<style include="app-management-shared-style">
:host(:not([available_])) {
display: none;
}
#file-handling-item {
margin: var(--row-item-vertical-padding) 0;
width: 100%;
}
#toggle-row:not([disabled_]) {
cursor: pointer;
}
#dialog-body {
user-select: text;
}
</style>
<div id="file-handling-item">
<app-management-toggle-row
id="toggle-row"
label="[[i18n('appManagementFileHandlingHeader')]]"
managed="[[isManaged_(app)]]"
value="[[getValue_(app)]]"
class="header-text">
</app-management-toggle-row>
<p>
<localized-link id="type-list"
localized-string="[[userVisibleTypesLabel_(app)]]"
on-link-clicked="launchDialog_">
</localized-link>
</p>
<localized-link id="learn-more"
localized-string="[[i18nAdvanced('fileHandlingSetDefaults')]]"
link-url="[[getLearnMoreLinkUrl_(app)]]"
on-link-clicked="onLearnMoreLinkClicked_">
</localized-link>
</div>
<template is="dom-if" if="[[showOverflowDialog]]" restamp>
<cr-dialog id="dialog" show-on-attach
on-close="onDialogClose_">
<div slot="title">[[i18n('fileHandlingOverflowDialogTitle')]]</div>
<div id="dialog-body" slot="body">
[[userVisibleTypes_(app)]]
</div>
<div slot="button-container">
<cr-button class="action-button" on-click="onCloseButtonClicked_">
[[i18n('close')]]
</cr-button>
</div>
</cr-dialog>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/file_handling_item.html | HTML | unknown | 1,431 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './app_management_shared_style.css.js';
import './toggle_row.js';
import {assert} from '//resources/js/assert_ts.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {focusWithoutInk} from 'chrome://resources/js/focus_without_ink.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {App} from './app_management.mojom-webui.js';
import {BrowserProxy} from './browser_proxy.js';
import {AppManagementUserAction} from './constants.js';
import {getTemplate} from './file_handling_item.html.js';
import {AppManagementToggleRowElement} from './toggle_row.js';
import {recordAppManagementUserAction} from './util.js';
const AppManagementFileHandlingItemBase = I18nMixin(PolymerElement);
export class AppManagementFileHandlingItemElement extends
AppManagementFileHandlingItemBase {
static get is() {
return 'app-management-file-handling-item';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
app: Object,
/**
* @type {boolean}
*/
showOverflowDialog: {
type: Boolean,
value: false,
},
/**
* @type {boolean}
*/
hidden: {
type: Boolean,
computed: 'isHidden_(app)',
reflectToAttribute: true,
},
};
}
app: App;
showOverflowDialog: boolean;
override ready() {
super.ready();
this.addEventListener('change', this.onChanged_);
}
private isHidden_(app: App): boolean {
if (app && app.fileHandlingState) {
return !app.fileHandlingState.userVisibleTypes;
}
return false;
}
private isManaged_(app: App): boolean {
if (app && app.fileHandlingState) {
return app.fileHandlingState.isManaged;
}
return false;
}
private userVisibleTypes_(app: App): string {
if (app && app.fileHandlingState) {
return app.fileHandlingState.userVisibleTypes;
}
return '';
}
private userVisibleTypesLabel_(app: App): string {
if (app && app.fileHandlingState) {
return app.fileHandlingState.userVisibleTypesLabel;
}
return '';
}
private getLearnMoreLinkUrl_(app: App): string {
if (app && app.fileHandlingState && app.fileHandlingState.learnMoreUrl) {
return app.fileHandlingState.learnMoreUrl.url;
}
return '';
}
private onLearnMoreLinkClicked_(e: CustomEvent): void {
if (!this.getLearnMoreLinkUrl_(this.app)) {
// Currently, this branch should only be used on Windows.
e.detail.event.preventDefault();
e.stopPropagation();
BrowserProxy.getInstance().handler.showDefaultAppAssociationsUi();
}
}
private launchDialog_(e: CustomEvent): void {
// A place holder href with the value "#" is used to have a compliant link.
// This prevents the browser from navigating the window to "#"
e.detail.event.preventDefault();
e.stopPropagation();
this.showOverflowDialog = true;
recordAppManagementUserAction(
this.app.type, AppManagementUserAction.FILE_HANDLING_OVERFLOW_SHOWN);
}
private onCloseButtonClicked_() {
this.shadowRoot!.querySelector<CrDialogElement>('#dialog')!.close();
}
private onDialogClose_(): void {
this.showOverflowDialog = false;
const toFocus = this.shadowRoot!.querySelector<HTMLElement>('#type-list');
assert(toFocus);
focusWithoutInk(toFocus);
}
private getValue_(app: App): boolean {
if (app && app.fileHandlingState) {
return app.fileHandlingState.enabled;
}
return false;
}
private onChanged_() {
assert(this.app);
const enabled = this.shadowRoot!
.querySelector<AppManagementToggleRowElement>(
'#toggle-row')!.isChecked();
BrowserProxy.getInstance().handler.setFileHandlingEnabled(
this.app.id,
enabled,
);
const fileHandlingChangeAction = enabled ?
AppManagementUserAction.FILE_HANDLING_TURNED_ON :
AppManagementUserAction.FILE_HANDLING_TURNED_OFF;
recordAppManagementUserAction(this.app.type, fileHandlingChangeAction);
}
}
declare global {
interface HTMLElementTagNameMap {
'app-management-file-handling-item': AppManagementFileHandlingItemElement;
}
}
customElements.define(
AppManagementFileHandlingItemElement.is,
AppManagementFileHandlingItemElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/file_handling_item.ts | TypeScript | unknown | 4,640 |
<style include="app-management-shared-style">
:host {
align-items: center;
cursor: pointer;
display: flex;
flex: 1;
justify-content: space-between;
}
</style>
<div id="label" aria-hidden="true">
[[morePermissionsLabel]]
</div>
<div class="permission-row-controls">
<cr-icon-button class="native-settings-icon icon-external" role="link"
tabindex="0" aria-labelledby="label">
</cr-icon-button>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/more_permissions_item.html | HTML | unknown | 435 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './app_management_shared_style.css.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {App} from './app_management.mojom-webui.js';
import {BrowserProxy} from './browser_proxy.js';
import {AppManagementUserAction} from './constants.js';
import {getTemplate} from './more_permissions_item.html.js';
import {recordAppManagementUserAction} from './util.js';
export class AppManagementMorePermissionsItemElement extends PolymerElement {
static get is() {
return 'app-management-more-permissions-item';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
app: Object,
morePermissionsLabel: String,
};
}
app: App;
morePermissionsLabel: string;
override ready() {
super.ready();
this.addEventListener('click', this.onClick_);
}
private onClick_() {
BrowserProxy.getInstance().handler.openNativeSettings(this.app.id);
recordAppManagementUserAction(
this.app.type, AppManagementUserAction.NATIVE_SETTINGS_OPENED);
}
}
declare global {
interface HTMLElementTagNameMap {
'app-management-more-permissions-item':
AppManagementMorePermissionsItemElement;
}
}
customElements.define(
AppManagementMorePermissionsItemElement.is,
AppManagementMorePermissionsItemElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/more_permissions_item.ts | TypeScript | unknown | 1,571 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {PermissionType} from './app_management.mojom-webui.js';
export type PermissionTypeIndex = keyof typeof PermissionType;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/permission_constants.ts | TypeScript | unknown | 272 |
<style include="app-management-shared-style">
:host {
align-items: center;
display: flex;
justify-content: space-between;
}
:host(:not([disabled_])) {
cursor: pointer;
}
:host(:not([available_])) {
display: none;
}
</style>
<!-- permission-item does not include any icon-set, so containing
elements should import the icon-set needed for the specified |icon|. -->
<template is="dom-if" if="[[available_]]">
<app-management-toggle-row
id="toggle-row"
icon="[[icon]]"
label="[[permissionLabel]]"
managed="[[isManaged_(app, permissionType)]]"
value="[[getValue_(app, permissionType)]]"
aria-description="Click to toggle [[permissionLabel]] permissions."
i18n-aria-descrirption="Label for toggle button to change [[permissionLabel]] permissions.">
</app-management-toggle-row>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/permission_item.html | HTML | unknown | 866 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './app_management_shared_style.css.js';
import './toggle_row.js';
import {assert, assertNotReached} from '//resources/js/assert_ts.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {App, Permission, PermissionType, TriState} from './app_management.mojom-webui.js';
import {BrowserProxy} from './browser_proxy.js';
import {AppManagementUserAction} from './constants.js';
import {PermissionTypeIndex} from './permission_constants.js';
import {getTemplate} from './permission_item.html.js';
import {createBoolPermission, createTriStatePermission, getBoolPermissionValue, getTriStatePermissionValue, isBoolValue, isTriStateValue} from './permission_util.js';
import {AppManagementToggleRowElement} from './toggle_row.js';
import {getPermission, getPermissionValueBool, recordAppManagementUserAction} from './util.js';
export class AppManagementPermissionItemElement extends PolymerElement {
static get is() {
return 'app-management-permission-item';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* The name of the permission, to be displayed to the user.
*/
permissionLabel: String,
/**
* A string version of the permission type. Must be a value of the
* permission type enum in appManagement.mojom.PermissionType.
*/
permissionType: String,
icon: String,
/**
* If set to true, toggling the permission item will not set the
* permission in the backend. Call `syncPermission()` to set the
* permission to reflect the current UI state.
*/
syncPermissionManually: Boolean,
app: Object,
/**
* True if the permission type is available for the app.
*/
available_: {
type: Boolean,
computed: 'isAvailable_(app, permissionType)',
reflectToAttribute: true,
},
disabled_: {
type: Boolean,
computed: 'isManaged_(app, permissionType)',
reflectToAttribute: true,
},
};
}
app: App;
permissionLabel: string;
permissionType: PermissionTypeIndex;
icon: string;
private syncPermissionManually: boolean;
private available_: boolean;
private disabled_: boolean;
override ready() {
super.ready();
this.addEventListener('click', this.onClick_);
this.addEventListener('change', this.togglePermission_);
}
private isAvailable_(
app: App|undefined,
permissionType: PermissionTypeIndex|undefined): boolean {
if (app === undefined || permissionType === undefined) {
return false;
}
return getPermission(app, permissionType) !== undefined;
}
private isManaged_(app: App|undefined, permissionType: PermissionTypeIndex):
boolean {
if (app === undefined || permissionType === undefined ||
!this.isAvailable_(app, permissionType)) {
return false;
}
const permission = getPermission(app, permissionType);
assert(permission);
return permission.isManaged;
}
private getValue_(
app: App|undefined,
permissionType: PermissionTypeIndex|undefined): boolean {
if (app === undefined || permissionType === undefined) {
return false;
}
return getPermissionValueBool(app, permissionType);
}
resetToggle() {
const currentValue = this.getValue_(this.app, this.permissionType);
this.shadowRoot!
.querySelector<AppManagementToggleRowElement>('#toggle-row')!.setToggle(
currentValue);
}
private onClick_() {
this.shadowRoot!
.querySelector<AppManagementToggleRowElement>('#toggle-row')!.click();
}
private togglePermission_() {
if (!this.syncPermissionManually) {
this.syncPermission();
}
}
/**
* Set the permission to match the current UI state. This only needs to be
* called when `syncPermissionManually` is set.
*/
syncPermission() {
let newPermission: Permission|undefined = undefined;
let newBoolState = false;
const permission = getPermission(this.app, this.permissionType);
assert(permission);
const permissionValue = permission.value;
if (isBoolValue(permissionValue)) {
newPermission =
this.getUiPermissionBoolean_(this.app, this.permissionType);
newBoolState = getBoolPermissionValue(newPermission.value);
} else if (isTriStateValue(permissionValue)) {
newPermission =
this.getUiPermissionTriState_(this.app, this.permissionType);
newBoolState =
getTriStatePermissionValue(newPermission.value) === TriState.kAllow;
} else {
assertNotReached();
}
BrowserProxy.getInstance().handler.setPermission(
this.app.id, newPermission!);
recordAppManagementUserAction(
this.app.type,
this.getUserMetricActionForPermission_(
newBoolState, this.permissionType));
}
/**
* Gets the permission boolean based on the toggle's UI state.
*/
private getUiPermissionBoolean_(
app: App, permissionType: PermissionTypeIndex): Permission {
const currentPermission = getPermission(app, permissionType);
assert(currentPermission);
assert(isBoolValue(currentPermission.value));
const newPermissionValue = !getBoolPermissionValue(currentPermission.value);
return createBoolPermission(
PermissionType[permissionType], newPermissionValue,
currentPermission.isManaged);
}
/**
* Gets the permission tristate based on the toggle's UI state.
*/
private getUiPermissionTriState_(
app: App, permissionType: PermissionTypeIndex): Permission {
let newPermissionValue;
const currentPermission = getPermission(app, permissionType);
assert(currentPermission);
assert(isTriStateValue(currentPermission.value));
switch (getTriStatePermissionValue(currentPermission.value)) {
case TriState.kBlock:
newPermissionValue = TriState.kAllow;
break;
case TriState.kAsk:
newPermissionValue = TriState.kAllow;
break;
case TriState.kAllow:
// TODO(rekanorman): Eventually TriState.kAsk, but currently changing a
// permission to kAsk then opening the site settings page for the app
// produces the error:
// "Only extensions or enterprise policy can change the setting to ASK."
newPermissionValue = TriState.kBlock;
break;
default:
assertNotReached();
}
return createTriStatePermission(
PermissionType[permissionType], newPermissionValue,
currentPermission.isManaged);
}
private getUserMetricActionForPermission_(
permissionValue: boolean,
permissionType: PermissionTypeIndex): AppManagementUserAction {
switch (permissionType) {
case 'kNotifications':
return permissionValue ?
AppManagementUserAction.NOTIFICATIONS_TURNED_ON :
AppManagementUserAction.NOTIFICATIONS_TURNED_OFF;
case 'kLocation':
return permissionValue ? AppManagementUserAction.LOCATION_TURNED_ON :
AppManagementUserAction.LOCATION_TURNED_OFF;
case 'kCamera':
return permissionValue ? AppManagementUserAction.CAMERA_TURNED_ON :
AppManagementUserAction.CAMERA_TURNED_OFF;
case 'kMicrophone':
return permissionValue ? AppManagementUserAction.MICROPHONE_TURNED_ON :
AppManagementUserAction.MICROPHONE_TURNED_OFF;
case 'kContacts':
return permissionValue ? AppManagementUserAction.CONTACTS_TURNED_ON :
AppManagementUserAction.CONTACTS_TURNED_OFF;
case 'kStorage':
return permissionValue ? AppManagementUserAction.STORAGE_TURNED_ON :
AppManagementUserAction.STORAGE_TURNED_OFF;
case 'kPrinting':
return permissionValue ? AppManagementUserAction.PRINTING_TURNED_ON :
AppManagementUserAction.PRINTING_TURNED_OFF;
default:
assertNotReached();
}
}
}
declare global {
interface HTMLElementTagNameMap {
'app-management-permission-item': AppManagementPermissionItemElement;
}
}
customElements.define(
AppManagementPermissionItemElement.is, AppManagementPermissionItemElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/permission_item.ts | TypeScript | unknown | 8,521 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert, assertNotReached} from 'chrome://resources/js/assert_ts.js';
import {Permission, PermissionType, PermissionValue, TriState} from './app_management.mojom-webui.js';
export function createPermission(
permissionType: PermissionType, value: PermissionValue,
isManaged: boolean): Permission {
return {
permissionType,
value,
isManaged,
};
}
export function createTriStatePermissionValue(value: TriState):
PermissionValue {
return {tristateValue: value} as PermissionValue;
}
export function getTriStatePermissionValue(permissionValue: PermissionValue):
TriState {
assert(isTriStateValue(permissionValue));
return permissionValue.tristateValue!;
}
export function createBoolPermissionValue(value: boolean): PermissionValue {
return {boolValue: value} as PermissionValue;
}
export function getBoolPermissionValue(permissionValue: PermissionValue):
boolean {
assert(isBoolValue(permissionValue));
return permissionValue.boolValue!;
}
export function isTriStateValue(permissionValue: PermissionValue): boolean {
return permissionValue['tristateValue'] !== undefined &&
permissionValue['boolValue'] === undefined;
}
export function isBoolValue(permissionValue: PermissionValue): boolean {
return permissionValue['boolValue'] !== undefined &&
permissionValue['tristateValue'] === undefined;
}
export function createBoolPermission(
permissionType: PermissionType, value: boolean,
isManaged: boolean): Permission {
return createPermission(
permissionType, createBoolPermissionValue(value), isManaged);
}
export function createTriStatePermission(
permissionType: PermissionType, value: TriState,
isManaged: boolean): Permission {
return createPermission(
permissionType, createTriStatePermissionValue(value), isManaged);
}
export function isPermissionEnabled(permissionValue: PermissionValue): boolean {
if (isBoolValue(permissionValue)) {
return getBoolPermissionValue(permissionValue)!;
}
if (isTriStateValue(permissionValue)) {
return getTriStatePermissionValue(permissionValue) === TriState.kAllow;
}
assertNotReached();
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/permission_util.ts | TypeScript | unknown | 2,300 |
<app-management-toggle-row
id="toggle-row"
label="[[loginModeLabel]]"
managed="[[isManaged_(app)]]"
value="[[getValue_(app)]]">
</app-management-toggle-row>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/run_on_os_login_item.html | HTML | unknown | 169 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './app_management_shared_style.css.js';
import './toggle_row.js';
import {assert, assertNotReached} from '//resources/js/assert_ts.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {App} from './app_management.mojom-webui.js';
import {BrowserProxy} from './browser_proxy.js';
import {AppManagementUserAction, RunOnOsLoginMode} from './constants.js';
import {getTemplate} from './run_on_os_login_item.html.js';
import {AppManagementToggleRowElement} from './toggle_row.js';
import {recordAppManagementUserAction} from './util.js';
function convertModeToBoolean(runOnOsLoginMode: RunOnOsLoginMode): boolean {
switch (runOnOsLoginMode) {
case RunOnOsLoginMode.kNotRun:
return false;
case RunOnOsLoginMode.kWindowed:
return true;
default:
assertNotReached();
}
}
function getRunOnOsLoginModeBoolean(runOnOsLoginMode: RunOnOsLoginMode):
boolean {
assert(
runOnOsLoginMode !== RunOnOsLoginMode.kUnknown,
'Run on OS Login Mode is not set');
return convertModeToBoolean(runOnOsLoginMode);
}
export class AppManagementRunOnOsLoginItemElement extends PolymerElement {
static get is() {
return 'app-management-run-on-os-login-item';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
loginModeLabel: String,
app: Object,
};
}
loginModeLabel: string;
app: App;
override ready() {
super.ready();
this.addEventListener('click', this.onClick_);
this.addEventListener('change', this.toggleOsLoginMode_);
}
private isManaged_(): boolean {
const loginData = this.app.runOnOsLogin;
if (loginData) {
return loginData.isManaged;
}
return false;
}
private getValue_(): boolean {
const loginMode = this.getRunOnOsLoginMode();
assert(loginMode);
if (loginMode) {
return getRunOnOsLoginModeBoolean(loginMode);
}
return false;
}
private onClick_() {
this.shadowRoot!
.querySelector<AppManagementToggleRowElement>('#toggle-row')!.click();
}
private toggleOsLoginMode_() {
assert(this.app);
const currentRunOnOsLoginData = this.app.runOnOsLogin;
if (currentRunOnOsLoginData) {
const currentRunOnOsLoginMode = currentRunOnOsLoginData.loginMode;
if (currentRunOnOsLoginMode === RunOnOsLoginMode.kUnknown) {
assertNotReached();
}
const newRunOnOsLoginMode =
(currentRunOnOsLoginMode === RunOnOsLoginMode.kNotRun) ?
RunOnOsLoginMode.kWindowed :
RunOnOsLoginMode.kNotRun;
BrowserProxy.getInstance().handler.setRunOnOsLoginMode(
this.app.id,
newRunOnOsLoginMode,
);
const booleanRunOnOsLoginMode =
getRunOnOsLoginModeBoolean(newRunOnOsLoginMode);
const runOnOsLoginModeChangeAction = booleanRunOnOsLoginMode ?
AppManagementUserAction.RUN_ON_OS_LOGIN_MODE_TURNED_ON :
AppManagementUserAction.RUN_ON_OS_LOGIN_MODE_TURNED_OFF;
recordAppManagementUserAction(this.app.type, runOnOsLoginModeChangeAction);
}
}
private getRunOnOsLoginMode(): RunOnOsLoginMode|null {
if (this.app.runOnOsLogin) {
return this.app.runOnOsLogin.loginMode;
}
return null;
}
}
declare global {
interface HTMLElementTagNameMap {
'app-management-run-on-os-login-item': AppManagementRunOnOsLoginItemElement;
}
}
customElements.define(
AppManagementRunOnOsLoginItemElement.is,
AppManagementRunOnOsLoginItemElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/run_on_os_login_item.ts | TypeScript | unknown | 3,694 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=vars
* #import=//resources/cr_elements/cr_shared_vars.css.js
* #css_wrapper_metadata_end */
html {
--app-management-font-size: 13px;
--app-management-line-height: 1.54; /* 20px */
--card-max-width: 676px;
--card-min-width: 550px;
--card-separator: 1px solid var(--cr-separator-color);
--expanded-permission-row-height: 48px;
--header-font-weight: 500;
--header-text-color: var(--cr-title-text-color);
--permission-icon-padding: 20px;
--permission-list-item-height: 48px;
--permission-list-item-with-description-height: 64px;
--primary-text-color: var(--cr-primary-text-color);
--row-item-icon-padding: 12px;
--row-item-vertical-padding: 16px;
--secondary-font-weight: 400;
--secondary-text-color: var(--cr-secondary-text-color);
--text-permission-list-row-height: 40px;
--help-icon-padding: 6px;
--info-text-row-height: 48px;
--help-icon-size: 20px;
--app-management-controlled-by-spacing: var(--cr-controlled-by-spacing);
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/shared_vars.css | CSS | unknown | 1,157 |
<style include="app-management-shared-style">
:host {
align-items: center;
display: flex;
flex: 1;
justify-content: space-between;
}
#icon {
padding-inline-end: var(--row-item-icon-padding);
}
#policyIndicator {
padding-inline-end: var(--app-management-controlled-by-spacing);
}
</style>
<div id="left-content" aria-hidden="true">
<div class="horizontal-align">
<template is="dom-if" if="[[icon]]">
<iron-icon id="icon" icon="[[icon]]"></iron-icon>
</template>
<div class="vertical-align">
<div id="label">[[label]]</div>
<template is="dom-if" if="[[description]]">
<div id="description" class="secondary-text">
[[description]]
</div>
</template>
</div>
</div>
</div>
<div id="right-content" class="horizontal-align">
<template is="dom-if" if="[[managed]]">
<cr-policy-indicator id="policyIndicator"
indicator-type="devicePolicy">
</cr-policy-indicator>
</template>
<cr-toggle id="toggle"
checked="[[value]]"
disabled$="[[managed]]"
role="button"
tabindex="0"
aria-pressed="[[value]]"
aria-label="[[label]]">
</cr-toggle>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/toggle_row.html | HTML | unknown | 1,204 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './app_management_shared_style.css.js';
import '//resources/cr_elements/cr_toggle/cr_toggle.js';
import '//resources/cr_elements/policy/cr_policy_indicator.js';
import '//resources/cr_elements/icons.html.js';
import {CrToggleElement} from '//resources/cr_elements/cr_toggle/cr_toggle.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './toggle_row.html.js';
export interface AppManagementToggleRowElement {
$: {toggle: CrToggleElement};
}
export class AppManagementToggleRowElement extends PolymerElement {
static get is() {
return 'app-management-toggle-row';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
icon: String,
label: String,
managed: {type: Boolean, value: false, reflectToAttribute: true},
value: {type: Boolean, value: false, reflectToAttribute: true},
description: String,
};
}
override ready() {
super.ready();
this.addEventListener('click', this.onClick_);
}
isChecked(): boolean {
return this.$.toggle.checked;
}
setToggle(value: boolean) {
this.$.toggle.checked = value;
}
private onClick_(event: Event) {
event.stopPropagation();
this.$.toggle.click();
}
}
customElements.define(
AppManagementToggleRowElement.is, AppManagementToggleRowElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/toggle_row.ts | TypeScript | unknown | 1,545 |
<style include="app-management-shared-style">
:host {
align-items: center;
display: flex;
flex-direction: row;
}
#policyIndicator {
padding-inline-end: var(--app-management-controlled-by-spacing);
}
</style>
<template is="dom-if" if="[[showPolicyIndicator_(app)]]">
<cr-tooltip-icon
id="policyIndicator"
icon-class="cr20:domain"
tooltip-text="[[policyLabel]]"
icon-aria-label="[[policyLabel]]"
tooltip-position="bottom">
</cr-tooltip-icon>
</template>
<template is="dom-if" if="[[showUninstallButton_(app)]]">
<cr-button id="uninstallButton" on-click="onClick_"
disabled$="[[getDisableState_(app)]]">
[[uninstallLabel]]
</cr-button>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/uninstall_button.html | HTML | unknown | 718 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './app_management_shared_style.css.js';
import '//resources/cr_elements/cr_button/cr_button.js';
import '//resources/cr_elements/policy/cr_tooltip_icon.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {App} from './app_management.mojom-webui.js';
import {BrowserProxy} from './browser_proxy.js';
import {AppManagementUserAction, InstallReason} from './constants.js';
import {getTemplate} from './uninstall_button.html.js';
import {recordAppManagementUserAction} from './util.js';
export class AppManamentUninstallButtonElement extends PolymerElement {
static get is() {
return 'app-management-uninstall-button';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
app: Object,
uninstallLabel: String,
policyLabel: String,
};
}
app: App;
uninstallLabel: string;
policyLabel: string;
/**
* Returns true if the button should be disabled due to app install type.
*
* If the compiler complains about the "lack of ending return statement",
* you maybe just added a new InstallReason and need to add a new case.
*/
private getDisableState_(): boolean {
switch (this.app.installReason) {
case InstallReason.kSystem:
case InstallReason.kPolicy:
case InstallReason.kKiosk:
return true;
case InstallReason.kUnknown:
case InstallReason.kOem:
case InstallReason.kDefault:
case InstallReason.kSync:
case InstallReason.kUser:
case InstallReason.kSubApp:
case InstallReason.kCommandLine:
return false;
}
}
/**
* Returns true if the app was installed by a policy.
*/
private showPolicyIndicator_(): boolean {
return this.app.installReason === InstallReason.kPolicy;
}
/**
* Returns true if the uninstall button should be shown.
*/
private showUninstallButton_(): boolean {
return this.app.installReason !== InstallReason.kSystem;
}
private onClick_() {
BrowserProxy.getInstance().handler.uninstall(this.app.id);
recordAppManagementUserAction(
this.app.type, AppManagementUserAction.UNINSTALL_DIALOG_LAUNCHED);
}
}
declare global {
interface HTMLElementTagNameMap {
'app-management-uninstall-button': AppManamentUninstallButtonElement;
}
}
customElements.define(
AppManamentUninstallButtonElement.is, AppManamentUninstallButtonElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/uninstall_button.ts | TypeScript | unknown | 2,594 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert, assertNotReached} from 'chrome://resources/js/assert_ts.js';
import {App, Permission, PermissionType} from './app_management.mojom-webui.js';
import {BrowserProxy} from './browser_proxy.js';
import {AppManagementUserAction, AppType, OptionalBool} from './constants.js';
import {PermissionTypeIndex} from './permission_constants.js';
import {isPermissionEnabled} from './permission_util.js';
/**
* @fileoverview Utility functions for the App Management page.
*/
interface AppManagementPageState {
apps: Record<string, App>;
selectedAppId: string|null;
}
export function createEmptyState(): AppManagementPageState {
return {
apps: {},
selectedAppId: null,
};
}
export function createInitialState(apps: App[]): AppManagementPageState {
const initialState = createEmptyState();
for (const app of apps) {
initialState.apps[app.id] = app;
}
return initialState;
}
export function getAppIcon(app: App): string {
return `chrome://app-icon/${app.id}/64`;
}
export function getPermissionValueBool(
app: App, permissionType: PermissionTypeIndex): boolean {
const permission = getPermission(app, permissionType);
assert(permission);
return isPermissionEnabled(permission.value);
}
/**
* Undefined is returned when the app does not request a permission.
*/
export function getPermission(
app: App, permissionType: PermissionTypeIndex): Permission|undefined {
return app.permissions[PermissionType[permissionType]];
}
export function getSelectedApp(state: AppManagementPageState): App|null {
const selectedAppId = state.selectedAppId;
return selectedAppId ? state.apps[selectedAppId] : null;
}
/**
* A comparator function to sort strings alphabetically.
*/
export function alphabeticalSort(a: string, b: string) {
return a.localeCompare(b);
}
/**
* Toggles an OptionalBool
*/
export function toggleOptionalBool(bool: OptionalBool): OptionalBool {
switch (bool) {
case OptionalBool.kFalse:
return OptionalBool.kTrue;
case OptionalBool.kTrue:
return OptionalBool.kFalse;
default:
assertNotReached();
}
}
export function convertOptionalBoolToBool(optionalBool: OptionalBool): boolean {
switch (optionalBool) {
case OptionalBool.kTrue:
return true;
case OptionalBool.kFalse:
return false;
default:
assertNotReached();
}
}
function getUserActionHistogramNameForAppType(appType: AppType): string {
switch (appType) {
case AppType.kArc:
return 'AppManagement.AppDetailViews.ArcApp';
case AppType.kChromeApp:
case AppType.kStandaloneBrowser:
case AppType.kStandaloneBrowserChromeApp:
// TODO(https://crbug.com/1225848): Figure out appropriate behavior for
// Lacros-hosted chrome-apps.
return 'AppManagement.AppDetailViews.ChromeApp';
case AppType.kWeb:
return 'AppManagement.AppDetailViews.WebApp';
case AppType.kPluginVm:
return 'AppManagement.AppDetailViews.PluginVmApp';
case AppType.kBorealis:
return 'AppManagement.AppDetailViews.BorealisApp';
default:
assertNotReached();
}
}
export function recordAppManagementUserAction(
appType: AppType, userAction: AppManagementUserAction) {
const histogram = getUserActionHistogramNameForAppType(appType);
const enumLength = Object.keys(AppManagementUserAction).length;
BrowserProxy.getInstance().recordEnumerationValue(
histogram, userAction, enumLength);
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/util.ts | TypeScript | unknown | 3,588 |
<app-management-toggle-row
id="toggle-row"
label="[[windowModeLabel]]"
value="[[getValue_(app)]]">
</app-management-toggle-row>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/window_mode_item.html | HTML | unknown | 140 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './app_management_shared_style.css.js';
import './toggle_row.js';
import {assert, assertNotReached} from '//resources/js/assert_ts.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {App} from './app_management.mojom-webui.js';
import {BrowserProxy} from './browser_proxy.js';
import {AppManagementUserAction, WindowMode} from './constants.js';
import {AppManagementToggleRowElement} from './toggle_row.js';
import {recordAppManagementUserAction} from './util.js';
import {getTemplate} from './window_mode_item.html.js';
function convertWindowModeToBool(windowMode: WindowMode): boolean {
switch (windowMode) {
case WindowMode.kBrowser:
return false;
case WindowMode.kWindow:
return true;
default:
assertNotReached();
}
}
function getWindowModeBoolean(windowMode: WindowMode): boolean {
assert(windowMode !== WindowMode.kUnknown, 'Window Mode Not Set');
return convertWindowModeToBool(windowMode);
}
export class AppManagementWindowModeElement extends PolymerElement {
static get is() {
return 'app-management-window-mode-item';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
windowModeLabel: String,
app: Object,
hidden: {
type: Boolean,
computed: 'isHidden_(app)',
reflectToAttribute: true,
},
};
}
windowModeLabel: string;
app: App;
override ready() {
super.ready();
this.addEventListener('click', this.onClick_);
this.addEventListener('change', this.toggleWindowMode_);
}
private getValue_(): boolean {
return getWindowModeBoolean(this.app.windowMode);
}
private onClick_() {
this.shadowRoot!
.querySelector<AppManagementToggleRowElement>('#toggle-row')!.click();
}
private toggleWindowMode_() {
const currentWindowMode = this.app.windowMode;
if (currentWindowMode === WindowMode.kUnknown) {
assertNotReached();
}
const newWindowMode = (currentWindowMode === WindowMode.kBrowser) ?
WindowMode.kWindow :
WindowMode.kBrowser;
BrowserProxy.getInstance().handler.setWindowMode(
this.app.id,
newWindowMode,
);
const booleanWindowMode = getWindowModeBoolean(newWindowMode);
const windowModeChangeAction = booleanWindowMode ?
AppManagementUserAction.WINDOW_MODE_CHANGED_TO_WINDOW :
AppManagementUserAction.WINDOW_MODE_CHANGED_TO_BROWSER;
recordAppManagementUserAction(this.app.type, windowModeChangeAction);
}
private isHidden_(): boolean {
return this.app.hideWindowMode;
}
}
declare global {
interface HTMLElementTagNameMap {
'app-management-window-mode-item': AppManagementWindowModeElement;
}
}
customElements.define(
AppManagementWindowModeElement.is, AppManagementWindowModeElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/app_management/window_mode_item.ts | TypeScript | unknown | 3,021 |
<style include="certificate-shared">
cr-checkbox,
#description {
margin: 15px 0;
}
</style>
<cr-dialog id="dialog" close-text="[[i18n('close')]]">
<div slot="title">
[[i18n('certificateManagerCaTrustEditDialogTitle')]]
</div>
<div slot="body">
<div>[[explanationText_]]</div>
<div id="description">
[[i18n('certificateManagerCaTrustEditDialogDescription')]]
</div>
<cr-checkbox id="ssl" checked="[[trustInfo_.ssl]]">
[[i18n('certificateManagerCaTrustEditDialogSsl')]]
</cr-checkbox>
<cr-checkbox id="email" checked="[[trustInfo_.email]]">
[[i18n('certificateManagerCaTrustEditDialogEmail')]]
</cr-checkbox>
<cr-checkbox id="objSign" checked="[[trustInfo_.objSign]]">
[[i18n('certificateManagerCaTrustEditDialogObjSign')]]
</cr-checkbox>
</div>
<div slot="button-container">
<paper-spinner-lite id="spinner"></paper-spinner-lite>
<cr-button class="cancel-button" on-click="onCancelTap_">
[[i18n('cancel')]]
</cr-button>
<cr-button id="ok" class="action-button" on-click="onOkTap_">
[[i18n('ok')]]
</cr-button>
</div>
</cr-dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/ca_trust_edit_dialog.html | HTML | unknown | 1,288 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'ca-trust-edit-dialog' allows the user to:
* - specify the trust level of a certificate authority that is being
* imported.
* - edit the trust level of an already existing certificate authority.
*/
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
import './certificate_shared.css.js';
import {CrCheckboxElement} from 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {PaperSpinnerLiteElement} from 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './ca_trust_edit_dialog.html.js';
import {CaTrustInfo, CertificatesBrowserProxy, CertificatesBrowserProxyImpl, CertificateSubnode, NewCertificateSubNode} from './certificates_browser_proxy.js';
export interface CaTrustEditDialogElement {
$: {
dialog: CrDialogElement,
email: CrCheckboxElement,
objSign: CrCheckboxElement,
ok: HTMLElement,
spinner: PaperSpinnerLiteElement,
ssl: CrCheckboxElement,
};
}
const CaTrustEditDialogElementBase = I18nMixin(PolymerElement);
export class CaTrustEditDialogElement extends CaTrustEditDialogElementBase {
static get is() {
return 'ca-trust-edit-dialog';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
model: Object,
trustInfo_: Object,
explanationText_: String,
};
}
model: CertificateSubnode|NewCertificateSubNode;
private trustInfo_: CaTrustInfo|null;
private explanationText_: string;
private browserProxy_: CertificatesBrowserProxy|null = null;
override ready() {
super.ready();
this.browserProxy_ = CertificatesBrowserProxyImpl.getInstance();
}
override connectedCallback() {
super.connectedCallback();
this.explanationText_ = loadTimeData.getStringF(
'certificateManagerCaTrustEditDialogExplanation', this.model.name);
// A non existing |model.id| indicates that a new certificate is being
// imported, otherwise an existing certificate is being edited.
if ((this.model as CertificateSubnode).id) {
this.browserProxy_!
.getCaCertificateTrust((this.model as CertificateSubnode).id)
.then(trustInfo => {
this.trustInfo_ = trustInfo;
this.$.dialog.showModal();
});
} else {
this.$.dialog.showModal();
}
}
private onCancelTap_() {
this.$.dialog.close();
}
private onOkTap_() {
this.$.spinner.active = true;
const whenDone = (this.model as CertificateSubnode).id ?
this.browserProxy_!.editCaCertificateTrust(
(this.model as CertificateSubnode).id, this.$.ssl.checked,
this.$.email.checked, this.$.objSign.checked) :
this.browserProxy_!.importCaCertificateTrustSelected(
this.$.ssl.checked, this.$.email.checked, this.$.objSign.checked);
whenDone.then(
() => {
this.$.spinner.active = false;
this.$.dialog.close();
},
error => {
if (error === null) {
return;
}
this.$.dialog.close();
this.dispatchEvent(new CustomEvent('certificates-error', {
bubbles: true,
composed: true,
detail: {error: error, anchor: null},
}));
});
}
}
declare global {
interface HTMLElementTagNameMap {
'ca-trust-edit-dialog': CaTrustEditDialogElement;
}
}
customElements.define(CaTrustEditDialogElement.is, CaTrustEditDialogElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/ca_trust_edit_dialog.ts | TypeScript | unknown | 4,172 |
<style include="certificate-shared"></style>
<cr-dialog id="dialog" close-text="[[i18n('close')]]">
<div slot="title">
[[getTitleText_(model, certificateType)]]
</div>
<div slot="body">
<div>[[getDescriptionText_(model, certificateType)]]</div>
</div>
<div slot="button-container">
<cr-button class="cancel-button" on-click="onCancelTap_">
[[i18n('cancel')]]
</cr-button>
<cr-button id="ok" class="action-button" on-click="onOkTap_">
[[i18n('ok')]]
</cr-button>
</div>
</cr-dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_delete_confirmation_dialog.html | HTML | unknown | 598 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A confirmation dialog allowing the user to delete various types
* of certificates.
*/
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import './certificate_shared.css.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {assertNotReached} from 'chrome://resources/js/assert_ts.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './certificate_delete_confirmation_dialog.html.js';
import {CertificatesBrowserProxyImpl, CertificateSubnode, CertificateType} from './certificates_browser_proxy.js';
export interface CertificateDeleteConfirmationDialogElement {
$: {
dialog: CrDialogElement,
ok: HTMLElement,
};
}
const CertificateDeleteConfirmationDialogElementBase =
I18nMixin(PolymerElement);
export class CertificateDeleteConfirmationDialogElement extends
CertificateDeleteConfirmationDialogElementBase {
static get is() {
return 'certificate-delete-confirmation-dialog';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
model: Object,
certificateType: String,
};
}
model: CertificateSubnode;
certificateType: CertificateType;
override connectedCallback() {
super.connectedCallback();
this.$.dialog.showModal();
}
private getTitleText_(): string {
const getString = (localizedMessageId: string) =>
loadTimeData.getStringF(localizedMessageId, this.model.name);
switch (this.certificateType) {
case CertificateType.PERSONAL:
return getString('certificateManagerDeleteUserTitle');
case CertificateType.SERVER:
return getString('certificateManagerDeleteServerTitle');
case CertificateType.CA:
return getString('certificateManagerDeleteCaTitle');
case CertificateType.OTHER:
return getString('certificateManagerDeleteOtherTitle');
default:
assertNotReached();
}
}
private getDescriptionText_(): string {
const getString = loadTimeData.getString.bind(loadTimeData);
switch (this.certificateType) {
case CertificateType.PERSONAL:
return getString('certificateManagerDeleteUserDescription');
case CertificateType.SERVER:
return getString('certificateManagerDeleteServerDescription');
case CertificateType.CA:
return getString('certificateManagerDeleteCaDescription');
case CertificateType.OTHER:
return '';
default:
assertNotReached();
}
}
private onCancelTap_() {
this.$.dialog.close();
}
private onOkTap_() {
CertificatesBrowserProxyImpl.getInstance()
.deleteCertificate(this.model.id)
.then(
() => {
this.$.dialog.close();
},
error => {
if (error === null) {
return;
}
this.$.dialog.close();
this.dispatchEvent(new CustomEvent('certificates-error', {
bubbles: true,
composed: true,
detail: {error: error, anchor: null},
}));
});
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-delete-confirmation-dialog':
CertificateDeleteConfirmationDialogElement;
}
}
customElements.define(
CertificateDeleteConfirmationDialogElement.is,
CertificateDeleteConfirmationDialogElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_delete_confirmation_dialog.ts | TypeScript | unknown | 3,853 |
<style include="certificate-shared iron-flex">
.expand-box {
align-items: center;
border-top: var(--cr-separator-line);
display: flex;
min-height: 48px;
padding: 0 20px;
}
</style>
<div class="expand-box">
<div class="flex">[[model.id]]</div>
<cr-policy-indicator indicator-type="[[getPolicyIndicatorType_(model)]]">
</cr-policy-indicator>
<cr-expand-button no-hover expanded="{{expanded_}}"
aria-label="[[i18n('certificateManagerExpandA11yLabel')]]">
</cr-expand-button>
</div>
<template is="dom-if" if="[[expanded_]]">
<div class="list-frame">
<template is="dom-repeat" items="[[model.subnodes]]">
<certificate-subentry model="[[item]]"
certificate-type="[[certificateType]]"
is-last$="[[isLast_(index, model)]]">
</certificate-subentry>
</template>
</div>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_entry.html | HTML | unknown | 963 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview An element that represents an SSL certificate entry.
*/
import 'chrome://resources/cr_elements/cr_expand_button/cr_expand_button.js';
import 'chrome://resources/cr_elements/policy/cr_policy_indicator.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import './certificate_shared.css.js';
import './certificate_subentry.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {CrPolicyIndicatorType} from 'chrome://resources/cr_elements/policy/cr_policy_indicator_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './certificate_entry.html.js';
import {CertificatesOrgGroup, CertificateType} from './certificates_browser_proxy.js';
const CertificateEntryElementBase = I18nMixin(PolymerElement);
class CertificateEntryElement extends CertificateEntryElementBase {
static get is() {
return 'certificate-entry';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
model: Object,
certificateType: String,
};
}
model: CertificatesOrgGroup;
certificateType: CertificateType;
/**
* @return Whether the given index corresponds to the last sub-node.
*/
private isLast_(index: number): boolean {
return index === this.model.subnodes.length - 1;
}
private getPolicyIndicatorType_(): CrPolicyIndicatorType {
return this.model.containsPolicyCerts ? CrPolicyIndicatorType.USER_POLICY :
CrPolicyIndicatorType.NONE;
}
}
customElements.define(CertificateEntryElement.is, CertificateEntryElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_entry.ts | TypeScript | unknown | 1,852 |
<style include="certificate-shared iron-flex">
.button-box {
align-items: center;
display: flex;
margin-bottom: 24px;
min-height: 48px;
padding: 0 20px;
}
/* TODO(aee): add platform conditional after crbug/964506 is fixed. */
#importAndBind {
margin-inline-start: 8px;
}
</style>
<div class="button-box">
<span class="flex">
[[getDescription_(certificateType, certificates)]]</span>
<cr-button id="import" on-click="onImportTap_"
hidden="[[!canImport_(certificateType, importAllowed, isKiosk_)]]">
[[i18n('certificateManagerImport')]]</cr-button>
<if expr="is_chromeos">
<cr-button id="importAndBind" on-click="onImportAndBindTap_"
hidden="[[!canImportAndBind_(certificateType, importAllowed,
isGuest_)]]">
[[i18n('certificateManagerImportAndBind')]]</cr-button>
</if>
</div>
<template is="dom-repeat" items="[[certificates]]">
<certificate-entry model="[[item]]"
certificate-type="[[certificateType]]">
</certificate-entry>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_list.html | HTML | unknown | 1,143 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'certificate-list' is an element that displays a list of
* certificates.
*/
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import './certificate_entry.js';
import './certificate_shared.css.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {assertNotReached} from 'chrome://resources/js/assert_ts.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './certificate_list.html.js';
import {CertificateAction, CertificateActionEvent} from './certificate_manager_types.js';
import {CertificatesBrowserProxyImpl, CertificatesError, CertificatesImportError, CertificatesOrgGroup, CertificateType, NewCertificateSubNode} from './certificates_browser_proxy.js';
export interface CertificateListElement {
$: {
import: HTMLElement,
// <if expr="is_chromeos">
importAndBind: HTMLElement,
// </if>
};
}
const CertificateListElementBase = I18nMixin(PolymerElement);
export class CertificateListElement extends CertificateListElementBase {
static get is() {
return 'certificate-list';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
certificates: {
type: Array,
value() {
return [];
},
},
certificateType: String,
importAllowed: Boolean,
// <if expr="is_chromeos">
isGuest_: {
type: Boolean,
value() {
return loadTimeData.valueExists('isGuest') &&
loadTimeData.getBoolean('isGuest');
},
},
// </if>
isKiosk_: {
type: Boolean,
value() {
return loadTimeData.valueExists('isKiosk') &&
loadTimeData.getBoolean('isKiosk');
},
},
};
}
certificates: CertificatesOrgGroup[];
certificateType: CertificateType;
importAllowed: boolean;
// <if expr="is_chromeos">
private isGuest_: boolean;
// </if>
private isKiosk_: boolean;
private getDescription_(): string {
if (this.certificates.length === 0) {
return this.i18n('certificateManagerNoCertificates');
}
switch (this.certificateType) {
case CertificateType.PERSONAL:
return this.i18n('certificateManagerYourCertificatesDescription');
case CertificateType.SERVER:
return this.i18n('certificateManagerServersDescription');
case CertificateType.CA:
return this.i18n('certificateManagerAuthoritiesDescription');
case CertificateType.OTHER:
return this.i18n('certificateManagerOthersDescription');
default:
assertNotReached();
}
}
private canImport_(): boolean {
return !this.isKiosk_ && this.certificateType !== CertificateType.OTHER &&
this.importAllowed;
}
// <if expr="is_chromeos">
private canImportAndBind_(): boolean {
return !this.isGuest_ &&
this.certificateType === CertificateType.PERSONAL && this.importAllowed;
}
// </if>
/**
* Handles a rejected Promise returned from |browserProxy_|.
*/
private onRejected_(
anchor: HTMLElement,
error: CertificatesError|CertificatesImportError|null) {
if (error === null) {
// Nothing to do here. Null indicates that the user clicked "cancel" on a
// native file chooser dialog or that the request was ignored by the
// handler due to being received while another was still being processed.
return;
}
// Otherwise propagate the error to the parents, such that a dialog
// displaying the error will be shown.
this.dispatchEvent(new CustomEvent('certificates-error', {
bubbles: true,
composed: true,
detail: {error, anchor},
}));
}
private dispatchImportActionEvent_(
subnode: NewCertificateSubNode|null, anchor: HTMLElement) {
this.dispatchEvent(new CustomEvent(CertificateActionEvent, {
bubbles: true,
composed: true,
detail: {
action: CertificateAction.IMPORT,
subnode: subnode,
certificateType: this.certificateType,
anchor: anchor,
},
}));
}
private onImportTap_(e: Event) {
this.handleImport_(false, e.target as HTMLElement);
}
// <if expr="is_chromeos">
private onImportAndBindTap_(e: Event) {
this.handleImport_(true, e.target as HTMLElement);
}
// </if>
private handleImport_(useHardwareBacked: boolean, anchor: HTMLElement) {
const browserProxy = CertificatesBrowserProxyImpl.getInstance();
if (this.certificateType === CertificateType.PERSONAL) {
browserProxy.importPersonalCertificate(useHardwareBacked)
.then(showPasswordPrompt => {
if (showPasswordPrompt) {
this.dispatchImportActionEvent_(null, anchor);
}
}, this.onRejected_.bind(this, anchor));
} else if (this.certificateType === CertificateType.CA) {
browserProxy.importCaCertificate().then(certificateName => {
this.dispatchImportActionEvent_({name: certificateName}, anchor);
}, this.onRejected_.bind(this, anchor));
} else if (this.certificateType === CertificateType.SERVER) {
browserProxy.importServerCertificate().catch(
this.onRejected_.bind(this, anchor));
} else {
assertNotReached();
}
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-list': CertificateListElement;
}
}
customElements.define(CertificateListElement.is, CertificateListElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_list.ts | TypeScript | unknown | 5,828 |
<style include="cr-hidden-style">
cr-tabs {
--cr-tabs-font-size: inherit;
--cr-tabs-height: 40px;
margin-bottom: 24px;
}
</style>
<template is="dom-if" if="[[showCaTrustEditDialog_]]" restamp>
<ca-trust-edit-dialog model="[[dialogModel_]]">
</ca-trust-edit-dialog>
</template>
<template is="dom-if" if="[[showDeleteConfirmationDialog_]]" restamp>
<certificate-delete-confirmation-dialog
model="[[dialogModel_]]"
certificate-type="[[dialogModelCertificateType_]]">
</certificate-delete-confirmation-dialog>
</template>
<template is="dom-if" if="[[showPasswordEncryptionDialog_]]" restamp>
<certificate-password-encryption-dialog>
</certificate-password-encryption-dialog>
</template>
<template is="dom-if" if="[[showPasswordDecryptionDialog_]]" restamp>
<certificate-password-decryption-dialog>
</certificate-password-decryption-dialog>
</template>
<template is="dom-if" if="[[showErrorDialog_]]" restamp>
<certificates-error-dialog model="[[errorDialogModel_]]">
</certificates-error-dialog>
</template>
<cr-tabs selected="{{selected}}" tab-names="[[tabNames_]]"></cr-tabs>
<iron-pages selected="[[selected]]">
<div>
<certificate-list id="personalCerts"
certificates="[[personalCerts]]"
certificate-type="[[certificateTypeEnum_.PERSONAL]]"
import-allowed="[[clientImportAllowed]]">
</certificate-list>
<if expr="is_chromeos">
<certificate-provisioning-list></certificate-provisioning-list>
</if>
</div>
<div>
<template is="dom-if" if="[[isTabSelected_(selected, 1)]]">
<certificate-list id="serverCerts"
certificates="[[serverCerts]]"
certificate-type="[[certificateTypeEnum_.SERVER]]"
import-allowed="true">
</certificate-list>
</template>
</div>
<div>
<template is="dom-if" if="[[isTabSelected_(selected, 2)]]">
<certificate-list id="caCerts"
certificates="[[caCerts]]"
certificate-type="[[certificateTypeEnum_.CA]]"
import-allowed="[[caImportAllowed]]">
</certificate-list>
</template>
</div>
<div>
<template is="dom-if" if="[[isTabSelected_(selected, 3)]]">
<certificate-list id="otherCerts"
certificates="[[otherCerts]]"
certificate-type="[[certificateTypeEnum_.OTHER]]"
import-allowed="false">
</certificate-list>
</template>
</div>
</iron-pages>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_manager.html | HTML | unknown | 2,673 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview The 'certificate-manager' component manages SSL certificates.
*/
import 'chrome://resources/cr_elements/cr_tabs/cr_tabs.js';
import 'chrome://resources/cr_elements/cr_hidden_style.css.js';
import 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js';
import './ca_trust_edit_dialog.js';
import './certificate_delete_confirmation_dialog.js';
import './certificate_list.js';
import './certificate_password_decryption_dialog.js';
import './certificate_password_encryption_dialog.js';
import './certificates_error_dialog.js';
// <if expr="is_chromeos">
import './certificate_provisioning_list.js';
// </if>
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {WebUiListenerMixin} from 'chrome://resources/cr_elements/web_ui_listener_mixin.js';
import {focusWithoutInk} from 'chrome://resources/js/focus_without_ink.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './certificate_manager.html.js';
import {CertificateAction, CertificateActionEvent} from './certificate_manager_types.js';
import {CertificatesBrowserProxyImpl, CertificatesError, CertificatesImportError, CertificatesOrgGroup, CertificateSubnode, CertificateType, NewCertificateSubNode} from './certificates_browser_proxy.js';
const CertificateManagerElementBase =
WebUiListenerMixin(I18nMixin(PolymerElement));
export class CertificateManagerElement extends CertificateManagerElementBase {
static get is() {
return 'certificate-manager';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
selected: {
type: Number,
value: 0,
},
personalCerts: {
type: Array,
value() {
return [];
},
},
serverCerts: {
type: Array,
value() {
return [];
},
},
caCerts: {
type: Array,
value() {
return [];
},
},
otherCerts: {
type: Array,
value() {
return [];
},
},
/**
* Indicates if client certificate import is allowed
* by Chrome OS specific policy ClientCertificateManagementAllowed.
* Value exists only for Chrome OS.
*/
clientImportAllowed: {
type: Boolean,
value: false,
},
/**
* Indicates if CA certificate import is allowed
* by Chrome OS specific policy CACertificateManagementAllowed.
* Value exists only for Chrome OS.
*/
caImportAllowed: {
type: Boolean,
value: false,
},
certificateTypeEnum_: {
type: Object,
value: CertificateType,
readOnly: true,
},
showCaTrustEditDialog_: Boolean,
showDeleteConfirmationDialog_: Boolean,
showPasswordEncryptionDialog_: Boolean,
showPasswordDecryptionDialog_: Boolean,
showErrorDialog_: Boolean,
/**
* The model to be passed to dialogs that refer to a given certificate.
*/
dialogModel_: Object,
/**
* The certificate type to be passed to dialogs that refer to a given
* certificate.
*/
dialogModelCertificateType_: String,
/**
* The model to be passed to the error dialog.
*/
errorDialogModel_: Object,
/**
* The element to return focus to, when the currently shown dialog is
* closed.
*/
activeDialogAnchor_: Object,
isKiosk_: {
type: Boolean,
value() {
return loadTimeData.valueExists('isKiosk') &&
loadTimeData.getBoolean('isKiosk');
},
},
tabNames_: {
type: Array,
computed: 'computeTabNames_(isKiosk_)',
},
};
}
selected: number;
personalCerts: CertificatesOrgGroup[];
serverCerts: CertificatesOrgGroup[];
caCerts: CertificatesOrgGroup[];
otherCerts: CertificatesOrgGroup[];
clientImportAllowed: boolean;
caImportAllowed: boolean;
private showCaTrustEditDialog_: boolean;
private showDeleteConfirmationDialog_: boolean;
private showPasswordEncryptionDialog_: boolean;
private showPasswordDecryptionDialog_: boolean;
private showErrorDialog_: boolean;
private dialogModel_: CertificateSubnode|NewCertificateSubNode|null;
private dialogModelCertificateType_: CertificateType|null;
private errorDialogModel_: CertificatesError|CertificatesImportError|null;
private activeDialogAnchor_: HTMLElement|null;
private isKiosk_: boolean;
override connectedCallback() {
super.connectedCallback();
this.addWebUiListener('certificates-changed', this.set.bind(this));
this.addWebUiListener(
'client-import-allowed-changed',
this.setClientImportAllowed.bind(this));
this.addWebUiListener(
'ca-import-allowed-changed', this.setCaImportAllowed.bind(this));
CertificatesBrowserProxyImpl.getInstance().refreshCertificates();
}
private setClientImportAllowed(allowed: boolean) {
this.clientImportAllowed = allowed;
}
private setCaImportAllowed(allowed: boolean) {
this.caImportAllowed = allowed;
}
/**
* @return Whether to show tab at |tabIndex|.
*/
private isTabSelected_(selectedIndex: number, tabIndex: number): boolean {
return selectedIndex === tabIndex;
}
override ready() {
super.ready();
this.addEventListener(CertificateActionEvent, event => {
this.dialogModel_ = event.detail.subnode;
this.dialogModelCertificateType_ = event.detail.certificateType;
if (event.detail.action === CertificateAction.IMPORT) {
if (event.detail.certificateType === CertificateType.PERSONAL) {
this.openDialog_(
'certificate-password-decryption-dialog',
'showPasswordDecryptionDialog_', event.detail.anchor);
} else if (event.detail.certificateType === CertificateType.CA) {
this.openDialog_(
'ca-trust-edit-dialog', 'showCaTrustEditDialog_',
event.detail.anchor);
}
} else {
if (event.detail.action === CertificateAction.EDIT) {
this.openDialog_(
'ca-trust-edit-dialog', 'showCaTrustEditDialog_',
event.detail.anchor);
} else if (event.detail.action === CertificateAction.DELETE) {
this.openDialog_(
'certificate-delete-confirmation-dialog',
'showDeleteConfirmationDialog_', event.detail.anchor);
} else if (event.detail.action === CertificateAction.EXPORT_PERSONAL) {
this.openDialog_(
'certificate-password-encryption-dialog',
'showPasswordEncryptionDialog_', event.detail.anchor);
}
}
event.stopPropagation();
});
this.addEventListener('certificates-error', event => {
const detail = event.detail;
this.errorDialogModel_ = detail.error;
this.openDialog_(
'certificates-error-dialog', 'showErrorDialog_', detail.anchor);
event.stopPropagation();
});
}
/**
* Opens a dialog and registers a listener for removing the dialog from the
* DOM once is closed. The listener is destroyed when the dialog is removed
* (because of 'restamp').
*
* @param dialogTagName The tag name of the dialog to be shown.
* @param domIfBooleanName The name of the boolean variable
* corresponding to the dialog.
* @param anchor The element to focus when the dialog is
* closed. If null, the previous anchor element should be reused. This
* happens when a 'certificates-error-dialog' is opened, which when closed
* should focus the anchor of the previous dialog (the one that generated
* the error).
*/
private openDialog_(
dialogTagName: string, domIfBooleanName: string,
anchor: HTMLElement|null) {
if (anchor) {
this.activeDialogAnchor_ = anchor;
}
this.set(domIfBooleanName, true);
window.setTimeout(() => {
const dialog = this.shadowRoot!.querySelector(dialogTagName)!;
dialog.addEventListener('close', () => {
this.set(domIfBooleanName, false);
focusWithoutInk(this.activeDialogAnchor_!);
});
}, 0);
}
private computeTabNames_(): string[] {
return [
loadTimeData.getString('certificateManagerYourCertificates'),
...(this.isKiosk_ ?
[] :
[
loadTimeData.getString('certificateManagerServers'),
loadTimeData.getString('certificateManagerAuthorities'),
]),
loadTimeData.getString('certificateManagerOthers'),
];
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-manager': CertificateManagerElement;
}
}
customElements.define(CertificateManagerElement.is, CertificateManagerElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_manager.ts | TypeScript | unknown | 9,101 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Closure compiler typedefs.
*/
// clang-format off
// <if expr="is_chromeos">
import {CertificateProvisioningProcess} from './certificate_provisioning_browser_proxy.js';
// </if>
import {CertificatesError, CertificatesImportError,CertificateSubnode, CertificateType, NewCertificateSubNode} from './certificates_browser_proxy.js';
// clang-format on
/**
* The payload of the 'certificate-action' event.
*/
export interface CertificateActionEventDetail {
action: CertificateAction;
subnode: CertificateSubnode|NewCertificateSubNode|null;
certificateType: CertificateType;
anchor: HTMLElement;
}
/**
* The payload of the 'certificates-error' event.
*/
export interface CertificatesErrorEventDetail {
error: CertificatesError|CertificatesImportError|null;
anchor: HTMLElement|null;
}
/**
* Enumeration of actions that require a popup menu to be shown to the user.
*/
export enum CertificateAction {
DELETE = 0,
EDIT = 1,
EXPORT_PERSONAL = 2,
IMPORT = 3,
}
/**
* The name of the event fired when a certificate action is selected from the
* dropdown menu. CertificateActionEventDetail is passed as the event detail.
*/
export const CertificateActionEvent = 'certificate-action';
// <if expr="is_chromeos">
/**
* The payload of the 'certificate-provisioning-view-details-action' event.
*/
export interface CertificateProvisioningActionEventDetail {
model: CertificateProvisioningProcess;
anchor: HTMLElement;
}
// </if>
/**
* The name of the event fired when a the "View Details" action is selected on
* the dropdown menu next to a certificate provisioning process.
* CertificateActionEventDetail is passed as the event detail.
*/
export const CertificateProvisioningViewDetailsActionEvent =
'certificate-provisioning-view-details-action';
declare global {
interface HTMLElementEventMap {
'certificates-error': CustomEvent<CertificatesErrorEventDetail>;
'certificate-action': CustomEvent<CertificateActionEventDetail>;
// <if expr="is_chromeos">
'certificate-provisioning-view-details-action':
CustomEvent<CertificateProvisioningActionEventDetail>;
// </if>
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_manager_types.ts | TypeScript | unknown | 2,303 |
<style include="certificate-shared">
cr-input {
--cr-input-error-display: none;
}
</style>
<cr-dialog id="dialog" close-text="[[i18n('close')]]">
<div slot="title">
[[i18n('certificateManagerDecryptPasswordTitle')]]
</div>
<div slot="body">
<cr-input type="password" id="password"
label="[[i18n('certificateManagerPassword')]]"
value="{{password_}}" autofocus>
</cr-input>
</div>
<div slot="button-container">
<cr-button class="cancel-button" on-click="onCancelTap_">
[[i18n('cancel')]]
</cr-button>
<cr-button id="ok" class="action-button" on-click="onOkTap_">
[[i18n('ok')]]
</cr-button>
</div>
</cr-dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_password_decryption_dialog.html | HTML | unknown | 782 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A dialog prompting the user for a decryption password such that
* a previously exported personal certificate can be imported.
*/
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.js';
import './certificate_shared.css.js';
import {CrButtonElement} from 'chrome://resources/cr_elements/cr_button/cr_button.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './certificate_password_decryption_dialog.html.js';
import {CertificatesBrowserProxyImpl} from './certificates_browser_proxy.js';
export interface CertificatePasswordDecryptionDialogElement {
$: {
dialog: CrDialogElement,
ok: CrButtonElement,
};
}
const CertificatePasswordDecryptionDialogElementBase =
I18nMixin(PolymerElement);
export class CertificatePasswordDecryptionDialogElement extends
CertificatePasswordDecryptionDialogElementBase {
static get is() {
return 'certificate-password-decryption-dialog';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
password_: {
type: String,
value: '',
},
};
}
private password_: string;
override connectedCallback() {
super.connectedCallback();
this.$.dialog.showModal();
}
private onCancelTap_() {
this.$.dialog.close();
}
private onOkTap_() {
CertificatesBrowserProxyImpl.getInstance()
.importPersonalCertificatePasswordSelected(this.password_)
.then(
() => {
this.$.dialog.close();
},
error => {
if (error === null) {
return;
}
this.$.dialog.close();
this.dispatchEvent(new CustomEvent('certificates-error', {
bubbles: true,
composed: true,
detail: {error: error, anchor: null},
}));
});
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-password-decryption-dialog':
CertificatePasswordDecryptionDialogElement;
}
}
customElements.define(
CertificatePasswordDecryptionDialogElement.is,
CertificatePasswordDecryptionDialogElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_password_decryption_dialog.ts | TypeScript | unknown | 2,678 |
<style include="certificate-shared">
cr-input {
--cr-input-error-display: none;
margin-top: var(--cr-form-field-bottom-spacing);
}
.password-buttons {
margin-bottom: 20px;
}
</style>
<cr-dialog id="dialog" close-text="[[i18n('close')]]">
<div slot="title">
[[i18n('certificateManagerEncryptPasswordTitle')]]
</div>
<div slot="body">
<div>[[i18n('certificateManagerEncryptPasswordDescription')]]</div>
<div class="password-buttons">
<cr-input type="password" value="{{password_}}" id="password"
label="[[i18n('certificateManagerPassword')]]"
on-input="validate_" autofocus></cr-input>
<cr-input type="password"
value="{{confirmPassword_}}" id="confirmPassword"
label="[[i18n('certificateManagerConfirmPassword')]]"
on-input="validate_"></cr-input>
</div>
</div>
<div slot="button-container">
<cr-button class="cancel-button" on-click="onCancelTap_">
[[i18n('cancel')]]
</cr-button>
<cr-button id="ok" class="action-button" on-click="onOkTap_" disabled>
[[i18n('ok')]]
</cr-button>
</div>
</cr-dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_password_encryption_dialog.html | HTML | unknown | 1,275 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A dialog prompting the user to encrypt a personal certificate
* before it is exported to disk.
*/
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.js';
import 'chrome://resources/cr_elements/cr_shared_vars.css.js';
import './certificate_shared.css.js';
import {CrButtonElement} from 'chrome://resources/cr_elements/cr_button/cr_button.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './certificate_password_encryption_dialog.html.js';
import {CertificatesBrowserProxyImpl} from './certificates_browser_proxy.js';
export interface CertificatePasswordEncryptionDialogElement {
$: {
dialog: CrDialogElement,
ok: CrButtonElement,
};
}
const CertificatePasswordEncryptionDialogElementBase =
I18nMixin(PolymerElement);
export class CertificatePasswordEncryptionDialogElement extends
CertificatePasswordEncryptionDialogElementBase {
static get is() {
return 'certificate-password-encryption-dialog';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
password_: {
type: String,
value: '',
},
confirmPassword_: {
type: String,
value: '',
},
};
}
private password_: string;
private confirmPassword_: string;
override connectedCallback() {
super.connectedCallback();
this.$.dialog.showModal();
}
private onCancelTap_() {
this.$.dialog.close();
}
private onOkTap_() {
CertificatesBrowserProxyImpl.getInstance()
.exportPersonalCertificatePasswordSelected(this.password_)
.then(
() => {
this.$.dialog.close();
},
error => {
if (error === null) {
return;
}
this.$.dialog.close();
this.dispatchEvent(new CustomEvent('certificates-error', {
bubbles: true,
composed: true,
detail: {error: error, anchor: null},
}));
});
}
private validate_() {
const isValid =
this.password_ !== '' && this.password_ === this.confirmPassword_;
this.$.ok.disabled = !isValid;
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-password-encryption-dialog':
CertificatePasswordEncryptionDialogElement;
}
}
customElements.define(
CertificatePasswordEncryptionDialogElement.is,
CertificatePasswordEncryptionDialogElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_password_encryption_dialog.ts | TypeScript | unknown | 2,982 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A helper object used on Chrome OS from the "Manage
* certificates" section to interact with certificate provisioining processes.
*/
/**
* The 'certificate-provisioning-processes-changed' event will have an array of
* CertificateProvisioningProcesses as its argument. This typedef is currently
* declared here to be consistent with certificates_browser_proxy.js, but it is
* not specific to CertificateProvisioningBrowserProxy.
*
* @see chrome/browser/ui/webui/settings/certificates_handler.cc
*/
export interface CertificateProvisioningProcess {
certProfileId: string;
certProfileName: string;
isDeviceWide: boolean;
lastUnsuccessfulMessage: string;
status: string;
stateId: number;
timeSinceLastUpdate: string;
publicKey: string;
}
export interface CertificateProvisioningBrowserProxy {
/**
* Refreshes the list of client certificate processes.
* Triggers the 'certificate-provisioning-processes-changed' event.
* This is Chrome OS specific, but always present for simplicity.
*/
refreshCertificateProvisioningProcesses(): void;
/**
* Attempts to manually advance/refresh the status of the client certificate
* provisioning process identified by |certProfileId|.
* This is Chrome OS specific, but always present for simplicity.
*/
triggerCertificateProvisioningProcessUpdate(certProfileId: string): void;
}
export class CertificateProvisioningBrowserProxyImpl implements
CertificateProvisioningBrowserProxy {
refreshCertificateProvisioningProcesses() {
chrome.send('refreshCertificateProvisioningProcessses');
}
triggerCertificateProvisioningProcessUpdate(certProfileId: string) {
chrome.send('triggerCertificateProvisioningProcessUpdate', [certProfileId]);
}
static getInstance(): CertificateProvisioningBrowserProxy {
return instance ||
(instance = new CertificateProvisioningBrowserProxyImpl());
}
static setInstance(obj: CertificateProvisioningBrowserProxy) {
instance = obj;
}
}
// The singleton instance_ is replaced with a test version of this wrapper
// during testing.
let instance: CertificateProvisioningBrowserProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_browser_proxy.ts | TypeScript | unknown | 2,316 |
<style include="iron-flex">
.button-box {
align-items: center;
display: flex;
min-height: 48px;
}
.label {
color: var(--cr-secondary-text-color);
font-size: 85%;
}
/* A row with two lines of text.
* Consistnt with chrome/browser/resources/settings/settings_shared_css.html
* (which can not be imported here because this is in cr_components).
*/
.two-line {
min-height: var(--settings-row-two-line-min-height);
}
.value {
color: var(--cr-primary-text-color);
}
</style>
<cr-dialog id="dialog" show-on-attach show-close-button close-text="[[i18n('close')]]">
<div slot="title">
[[i18n('certificateProvisioningDetails')]]
</div>
<div slot="body">
<div class="two-line">
<div class="label" aria-describedby="certProfileName">
[[i18n('certificateProvisioningProfileName')]]
</div>
<div class="value" id="certProfileName" aria-hidden="true">
[[model.certProfileName]]
</div>
</div>
<div class="two-line">
<div class="label" aria-describedby="certProfileId">
[[i18n('certificateProvisioningProfileId')]]
</div>
<div class="value" id="certProfileId" aria-hidden="true">
[[model.certProfileId]]
</div>
</div>
<div class="button-box">
<div class="two-line flex">
<div class="label" aria-describedby="status">
[[i18n('certificateProvisioningStatus')]]
</div>
<span class="value" id="status" aria-hidden="true">
[[model.status]]
</span>
</div>
<cr-button id="refresh" role="button" on-click="onRefresh_">
[[i18n('certificateProvisioningRefresh')]]
</cr-button>
</div>
<div class="two-line">
<div class="label" aria-describedby="timeSinceLastUpdate">
[[i18n('certificateProvisioningLastUpdate')]]
</div>
<div class="value" id="timeSinceLastUpdate" aria-hidden="true">
[[model.timeSinceLastUpdate]]
</div>
</div>
<div class="two-line" hidden$="[[shouldHideLastFailedStatus_(model.lastUnsuccessfulMessage)]]">
<div class="label" aria-describedby="lastFailedStatus">
[[i18n('certificateProvisioningLastUnsuccessfulStatus')]]
</div>
<div class="value" id="lastFailedStatus" aria-hidden="true">
[[model.lastUnsuccessfulMessage]]
</div>
</div>
<hr></hr>
<cr-expand-button expanded="{{advancedExpanded_}}"
aria-expanded$="[[boolToString_(advancedOpened)]]">
<div>[[i18n('certificateProvisioningAdvancedSectionTitle')]]</div>
</cr-expand-button>
<iron-collapse id="advancedInfo" opened="[[advancedExpanded_]]">
<div class="two-line">
<div class="label" aria-describedby="stateId">
[[i18n('certificateProvisioningStatusId')]]
</div>
<div class="value" id="stateId" aria-hidden="true">
[[model.stateId]]
</div>
</div>
<div class="two-line">
<div class="label" aria-describedby="publicKey">
[[i18n('certificateProvisioningPublicKey')]]
</div>
<div class="value" id="publicKey" aria-hidden="true">
[[model.publicKey]]
</div>
</div>
</iron-collapse>
</div>
</cr-dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_details_dialog.html | HTML | unknown | 3,261 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'certificate-provisioning-details-dialog' allows the user to
* view the details of an in-progress certiifcate provisioning process.
*/
import 'chrome://resources/cr_elements/cr_expand_button/cr_expand_button.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CertificateProvisioningBrowserProxyImpl, CertificateProvisioningProcess} from './certificate_provisioning_browser_proxy.js';
import {getTemplate} from './certificate_provisioning_details_dialog.html.js';
export interface CertificateProvisioningDetailsDialogElement {
$: {
dialog: CrDialogElement,
refresh: HTMLElement,
};
}
const CertificateProvisioningDetailsDialogElementBase =
I18nMixin(PolymerElement);
export class CertificateProvisioningDetailsDialogElement extends
CertificateProvisioningDetailsDialogElementBase {
static get is() {
return 'certificate-provisioning-details-dialog';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
model: Object,
advancedExpanded_: Boolean,
};
}
model: CertificateProvisioningProcess;
private advancedExpanded_: boolean;
close() {
this.$.dialog.close();
}
private onRefresh_() {
CertificateProvisioningBrowserProxyImpl.getInstance()
.triggerCertificateProvisioningProcessUpdate(this.model.certProfileId);
}
private shouldHideLastFailedStatus_(): boolean {
return this.model.lastUnsuccessfulMessage.length === 0;
}
private arrowState_(opened: boolean): string {
return opened ? 'cr:arrow-drop-up' : 'cr:arrow-drop-down';
}
private boolToString_(bool: boolean): string {
return bool.toString();
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-provisioning-details-dialog':
CertificateProvisioningDetailsDialogElement;
}
}
customElements.define(
CertificateProvisioningDetailsDialogElement.is,
CertificateProvisioningDetailsDialogElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_details_dialog.ts | TypeScript | unknown | 2,478 |
<style include="certificate-shared iron-flex">
.cert-box {
align-items: center;
border-top: var(--cr-separator-line);
display: flex;
min-height: 48px;
padding: 0 20px;
}
</style>
<div class="cert-box">
<div class="flex" tabindex="0">[[model.certProfileName]]</div>
<cr-icon-button class="icon-more-vert" id="dots"
title="[[i18n('moreActions')]]" on-click="onDotsClick_">
</cr-icon-button>
<cr-lazy-render id="menu">
<template>
<cr-action-menu role-description="[[i18n('menu')]]">
<button class="dropdown-item" id="details"
on-click="onDetailsClick_">
[[i18n('certificateProvisioningDetails')]]
</button>
</cr-action-menu>
</template>
</cr-lazy-render>
</div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_entry.html | HTML | unknown | 757 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'certificate-provisioning-entry' is an element that displays
* one certificate provisioning processes.
*/
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js';
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import './certificate_shared.css.js';
import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CertificateProvisioningViewDetailsActionEvent} from './certificate_manager_types.js';
import {CertificateProvisioningProcess} from './certificate_provisioning_browser_proxy.js';
import {getTemplate} from './certificate_provisioning_entry.html.js';
export interface CertificateProvisioningEntryElement {
$: {
dots: HTMLElement,
menu: CrLazyRenderElement<CrActionMenuElement>,
};
}
const CertificateProvisioningEntryElementBase = I18nMixin(PolymerElement);
export class CertificateProvisioningEntryElement extends
CertificateProvisioningEntryElementBase {
static get is() {
return 'certificate-provisioning-entry';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
model: Object,
};
}
model: CertificateProvisioningProcess;
private closePopupMenu_() {
this.shadowRoot!.querySelector('cr-action-menu')!.close();
}
private onDotsClick_() {
this.$.menu.get().showAt(this.$.dots);
}
private onDetailsClick_() {
this.closePopupMenu_();
this.dispatchEvent(
new CustomEvent(CertificateProvisioningViewDetailsActionEvent, {
bubbles: true,
composed: true,
detail: {
model: this.model,
anchor: this.$.dots,
},
}));
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-provisioning-entry': CertificateProvisioningEntryElement;
}
}
customElements.define(
CertificateProvisioningEntryElement.is,
CertificateProvisioningEntryElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_entry.ts | TypeScript | unknown | 2,555 |
<style include="cr-shared-style iron-flex ">
.header-box {
align-items: center;
display: flex;
margin-top: 16px;
min-height: 24px;
padding: 0 20px;
}
.hidden {
display: none;
}
</style>
<template is="dom-if" if="[[showProvisioningDetailsDialog_]]" restamp>
<certificate-provisioning-details-dialog model="[[provisioningDetailsDialogModel_]]"
on-close="onDialogClose_">
</certificate-provisioning-details-dialog>
</template>
<div class="header-box" aria-role="heading" aria-labelledby="headingLabel"
hidden="[[!hasCertificateProvisioningEntries_(provisioningProcesses_)]]">
<span id="headingLabel" class="flex">
[[i18n('certificateProvisioningListHeader')]]
</span>
</div>
<template is="dom-repeat" items="[[provisioningProcesses_]]">
<certificate-provisioning-entry model="[[item]]">
</certificate-provisioning-entry>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_list.html | HTML | unknown | 891 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'certificate-provisioning-list' is an element that displays a
* list of certificate provisioning processes.
*/
import 'chrome://resources/cr_elements/cr_shared_style.css.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import './certificate_provisioning_details_dialog.js';
import './certificate_provisioning_entry.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {WebUiListenerMixin} from 'chrome://resources/cr_elements/web_ui_listener_mixin.js';
import {focusWithoutInk} from 'chrome://resources/js/focus_without_ink.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CertificateProvisioningViewDetailsActionEvent} from './certificate_manager_types.js';
import {CertificateProvisioningBrowserProxyImpl, CertificateProvisioningProcess} from './certificate_provisioning_browser_proxy.js';
import {getTemplate} from './certificate_provisioning_list.html.js';
const CertificateProvisioningListElementBase =
WebUiListenerMixin(I18nMixin(PolymerElement));
export class CertificateProvisioningListElement extends
CertificateProvisioningListElementBase {
static get is() {
return 'certificate-provisioning-list';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
provisioningProcesses_: {
type: Array,
value() {
return [];
},
},
/**
* The model to be passed to certificate provisioning details dialog.
*/
provisioningDetailsDialogModel_: Object,
showProvisioningDetailsDialog_: Boolean,
};
}
private provisioningProcesses_: CertificateProvisioningProcess[];
private provisioningDetailsDialogModel_: CertificateProvisioningProcess|null;
private showProvisioningDetailsDialog_: boolean;
private previousAnchor_: HTMLElement|null = null;
/**
* @param provisioningProcesses The list of certificate provisioning
* processes.
* @return Whether |provisioningProcesses| contains at least one entry.
*/
private hasCertificateProvisioningEntries_(
provisioningProcesses: CertificateProvisioningProcess[]): boolean {
return provisioningProcesses.length !== 0;
}
/**
* @param certProvisioningProcesses The currently active certificate
* provisioning processes
*/
private onCertificateProvisioningProcessesChanged_(
certProvisioningProcesses: CertificateProvisioningProcess[]) {
this.provisioningProcesses_ = certProvisioningProcesses;
// If a cert provisioning process details dialog is being shown, update its
// model.
if (!this.provisioningDetailsDialogModel_) {
return;
}
const certProfileId = this.provisioningDetailsDialogModel_.certProfileId;
const newDialogModel = this.provisioningProcesses_.find((process) => {
return process.certProfileId === certProfileId;
});
if (newDialogModel) {
this.provisioningDetailsDialogModel_ = newDialogModel;
} else {
// Close cert provisioning process details dialog if the process is no
// longer in the list eg. when process completed successfully.
this.shadowRoot!.querySelector(
'certificate-provisioning-details-dialog')!.close();
}
}
override connectedCallback() {
super.connectedCallback();
this.addWebUiListener(
'certificate-provisioning-processes-changed',
this.onCertificateProvisioningProcessesChanged_.bind(this));
CertificateProvisioningBrowserProxyImpl.getInstance()
.refreshCertificateProvisioningProcesses();
}
override ready() {
super.ready();
this.addEventListener(
CertificateProvisioningViewDetailsActionEvent, event => {
const detail = event.detail;
this.provisioningDetailsDialogModel_ = detail.model;
this.previousAnchor_ = detail.anchor;
this.showProvisioningDetailsDialog_ = true;
event.stopPropagation();
CertificateProvisioningBrowserProxyImpl.getInstance()
.refreshCertificateProvisioningProcesses();
});
}
private onDialogClose_() {
this.showProvisioningDetailsDialog_ = false;
focusWithoutInk(this.previousAnchor_!);
this.previousAnchor_ = null;
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-provisioning-list': CertificateProvisioningListElement;
}
}
customElements.define(
CertificateProvisioningListElement.is, CertificateProvisioningListElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_provisioning_list.ts | TypeScript | unknown | 4,739 |
/* Copyright 2022 The Chromium Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/* #css_wrapper_metadata_start
* #type=style
* #import=chrome://resources/cr_elements/cr_shared_style.css.js
* #include=cr-shared-style
* #css_wrapper_metadata_end */
/* .list-frame and .list-item match the styling in settings_shared_css. */
.list-frame {
align-items: center;
display: block;
padding-inline-end: 20px;
padding-inline-start: 60px;
}
.list-item {
align-items: center;
display: flex;
min-height: 48px;
}
.list-item.underbar {
border-bottom: var(--cr-separator-line);
}
.list-item.selected {
font-weight: 500;
}
.list-item > .start {
flex: 1;
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_shared.css | CSS | unknown | 734 |
<style include="certificate-shared cr-icons">
.name {
flex: auto;
}
.untrusted {
color: var(--paper-red-700);
font-weight: 500;
margin-inline-end: 16px;
text-transform: uppercase;
}
:host([is-last]) .list-item {
border-bottom: none;
}
</style>
<div class="list-item underbar">
<div class="untrusted" hidden$="[[!model.untrusted]]">
[[i18n('certificateManagerUntrusted')]]
</div>
<div class="name">[[model.name]]</div>
<cr-policy-indicator indicator-type="[[getPolicyIndicatorType_(model)]]">
</cr-policy-indicator>
<cr-icon-button class="icon-more-vert" id="dots"
title="[[i18n('moreActions')]]" on-click="onDotsClick_">
</cr-icon-button>
<cr-lazy-render id="menu">
<template>
<cr-action-menu role-description="[[i18n('menu')]]">
<button class="dropdown-item" id="view"
on-click="onViewClick_">
[[i18n('certificateManagerView')]]
</button>
<button class="dropdown-item" id="edit"
hidden$="[[!canEdit_(model)]]"
on-click="onEditClick_">
[[i18n('edit')]]
</button>
<button class="dropdown-item" id="export"
hidden$="[[!canExport_(certificateType, model)]]"
on-click="onExportClick_">
[[i18n('certificateManagerExport')]]
</button>
<button class="dropdown-item" id="delete"
hidden$="[[!canDelete_(model)]]"
on-click="onDeleteClick_">
[[i18n('certificateManagerDelete')]]
</button>
</cr-action-menu>
</template>
</cr-lazy-render>
<div>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_subentry.html | HTML | unknown | 1,806 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview certificate-subentry represents an SSL certificate sub-entry.
*/
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js';
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import 'chrome://resources/cr_elements/policy/cr_policy_indicator.js';
import 'chrome://resources/cr_elements/icons.html.js';
import './certificate_shared.css.js';
import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {CrPolicyIndicatorType} from 'chrome://resources/cr_elements/policy/cr_policy_indicator_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CertificateAction, CertificateActionEvent} from './certificate_manager_types.js';
import {getTemplate} from './certificate_subentry.html.js';
import {CertificatesBrowserProxy, CertificatesBrowserProxyImpl, CertificatesError, CertificateSubnode, CertificateType} from './certificates_browser_proxy.js';
export interface CertificateSubentryElement {
$: {
menu: CrLazyRenderElement<CrActionMenuElement>,
dots: HTMLElement,
};
}
const CertificateSubentryElementBase = I18nMixin(PolymerElement);
export class CertificateSubentryElement extends CertificateSubentryElementBase {
static get is() {
return 'certificate-subentry';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
model: Object,
certificateType: String,
};
}
model: CertificateSubnode;
certificateType: CertificateType;
private browserProxy_: CertificatesBrowserProxy =
CertificatesBrowserProxyImpl.getInstance();
/**
* Dispatches an event indicating which certificate action was tapped. It is
* used by the parent of this element to display a modal dialog accordingly.
*/
private dispatchCertificateActionEvent_(action: CertificateAction) {
this.dispatchEvent(new CustomEvent(CertificateActionEvent, {
bubbles: true,
composed: true,
detail: {
action: action,
subnode: this.model,
certificateType: this.certificateType,
anchor: this.$.dots,
},
}));
}
/**
* Handles the case where a call to the browser resulted in a rejected
* promise.
*/
private onRejected_(error: CertificatesError|null) {
if (error === null) {
// Nothing to do here. Null indicates that the user clicked "cancel" on a
// native file chooser dialog or that the request was ignored by the
// handler due to being received while another was still being processed.
return;
}
// Otherwise propagate the error to the parents, such that a dialog
// displaying the error will be shown.
this.dispatchEvent(new CustomEvent('certificates-error', {
bubbles: true,
composed: true,
detail: {error, anchor: null},
}));
}
private onViewClick_() {
this.closePopupMenu_();
this.browserProxy_.viewCertificate(this.model.id);
}
private onEditClick_() {
this.closePopupMenu_();
this.dispatchCertificateActionEvent_(CertificateAction.EDIT);
}
private onDeleteClick_() {
this.closePopupMenu_();
this.dispatchCertificateActionEvent_(CertificateAction.DELETE);
}
private onExportClick_() {
this.closePopupMenu_();
if (this.certificateType === CertificateType.PERSONAL) {
this.browserProxy_.exportPersonalCertificate(this.model.id).then(() => {
this.dispatchCertificateActionEvent_(CertificateAction.EXPORT_PERSONAL);
}, this.onRejected_.bind(this));
} else {
this.browserProxy_.exportCertificate(this.model.id);
}
}
/**
* @return Whether the certificate can be edited.
*/
private canEdit_(model: CertificateSubnode): boolean {
return model.canBeEdited;
}
/**
* @return Whether the certificate can be exported.
*/
private canExport_(
certificateType: CertificateType, model: CertificateSubnode): boolean {
if (certificateType === CertificateType.PERSONAL) {
return model.extractable;
}
return true;
}
/**
* @return Whether the certificate can be deleted.
*/
private canDelete_(model: CertificateSubnode): boolean {
return model.canBeDeleted;
}
private closePopupMenu_() {
this.shadowRoot!.querySelector('cr-action-menu')!.close();
}
private onDotsClick_() {
this.$.menu.get().showAt(this.$.dots);
}
private getPolicyIndicatorType_(model: CertificateSubnode):
CrPolicyIndicatorType {
return model.policy ? CrPolicyIndicatorType.USER_POLICY :
CrPolicyIndicatorType.NONE;
}
}
declare global {
interface HTMLElementTagNameMap {
'certificate-subentry': CertificateSubentryElement;
}
}
customElements.define(
CertificateSubentryElement.is, CertificateSubentryElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificate_subentry.ts | TypeScript | unknown | 5,265 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A helper object used from the "Manage certificates" section
* to interact with the browser.
*/
import {sendWithPromise} from 'chrome://resources/js/cr.js';
/**
* @see chrome/browser/ui/webui/settings/certificates_handler.cc
*/
export interface CertificateSubnode {
extractable: boolean;
id: string;
name: string;
policy: boolean;
webTrustAnchor: boolean;
canBeDeleted: boolean;
canBeEdited: boolean;
untrusted: boolean;
}
/**
* A data structure describing a certificate that is currently being imported,
* therefore it has no ID yet, but it has a name. Used within JS only.
*/
export interface NewCertificateSubNode {
name: string;
}
/**
* Top-level grouping node in a certificate list, representing an organization
* and containing certs that belong to the organization in |subnodes|. If a
* certificate does not have an organization name, it will be grouped under its
* own CertificatesOrgGroup with |name| set to its display name.
* @see chrome/browser/ui/webui/settings/certificates_handler.cc
*/
export interface CertificatesOrgGroup {
id: string;
name: string;
containsPolicyCerts: boolean;
subnodes: CertificateSubnode[];
}
export interface CaTrustInfo {
ssl: boolean;
email: boolean;
objSign: boolean;
}
/**
* Generic error returned from C++ via a Promise reject callback.
* @see chrome/browser/ui/webui/settings/certificates_handler.cc
*/
export interface CertificatesError {
title: string;
description: string;
}
/**
* Enumeration of all possible certificate types.
*/
export enum CertificateType {
CA = 'ca',
OTHER = 'other',
PERSONAL = 'personal',
SERVER = 'server',
}
/**
* Error returned from C++ via a Promise reject callback, when some certificates
* fail to be imported.
* @see chrome/browser/ui/webui/settings/certificates_handler.cc
*/
export interface CertificatesImportError {
title: string;
description: string;
certificateErrors: Array<{name: string, error: string}>;
}
export interface CertificatesBrowserProxy {
/**
* Triggers 5 events in the following order
* 1x 'client-import-allowed-changed' event.
* 1x 'ca-import-allowed-changed' event.
* 4x 'certificates-changed' event, one for each certificate category.
*/
refreshCertificates(): void;
viewCertificate(id: string): void;
exportCertificate(id: string): void;
/**
* @return A promise resolved when the certificate has been
* deleted successfully or rejected with a CertificatesError.
*/
deleteCertificate(id: string): Promise<void>;
getCaCertificateTrust(id: string): Promise<CaTrustInfo>;
editCaCertificateTrust(
id: string, ssl: boolean, email: boolean,
objSign: boolean): Promise<void>;
cancelImportExportCertificate(): void;
/**
* @return A promise firing once the user has selected
* the export location. A prompt should be shown to asking for a
* password to use for encrypting the file. The password should be
* passed back via a call to
* exportPersonalCertificatePasswordSelected().
*/
exportPersonalCertificate(id: string): Promise<void>;
exportPersonalCertificatePasswordSelected(password: string): Promise<void>;
/**
* @return A promise firing once the user has selected
* the file to be imported. If true a password prompt should be shown to
* the user, and the password should be passed back via a call to
* importPersonalCertificatePasswordSelected().
*/
importPersonalCertificate(useHardwareBacked: boolean): Promise<boolean>;
importPersonalCertificatePasswordSelected(password: string): Promise<void>;
/**
* @return A promise firing once the user has selected
* the file to be imported, or failing with CertificatesError.
* Upon success, a prompt should be shown to the user to specify the
* trust levels, and that information should be passed back via a call
* to importCaCertificateTrustSelected().
*/
importCaCertificate(): Promise<string>;
/**
* @return A promise firing once the trust level for the imported
* certificate has been successfully set. The promise is rejected if an
* error occurred with either a CertificatesError or
* CertificatesImportError.
*/
importCaCertificateTrustSelected(
ssl: boolean, email: boolean, objSign: boolean): Promise<void>;
/**
* @return A promise firing once the certificate has been
* imported. The promise is rejected if an error occurred, with either
* a CertificatesError or CertificatesImportError.
*/
importServerCertificate(): Promise<void>;
}
export class CertificatesBrowserProxyImpl implements CertificatesBrowserProxy {
refreshCertificates() {
chrome.send('refreshCertificates');
}
viewCertificate(id: string) {
chrome.send('viewCertificate', [id]);
}
exportCertificate(id: string) {
chrome.send('exportCertificate', [id]);
}
deleteCertificate(id: string) {
return sendWithPromise('deleteCertificate', id);
}
exportPersonalCertificate(id: string) {
return sendWithPromise('exportPersonalCertificate', id);
}
exportPersonalCertificatePasswordSelected(password: string) {
return sendWithPromise(
'exportPersonalCertificatePasswordSelected', password);
}
importPersonalCertificate(useHardwareBacked: boolean) {
return sendWithPromise('importPersonalCertificate', useHardwareBacked);
}
importPersonalCertificatePasswordSelected(password: string) {
return sendWithPromise(
'importPersonalCertificatePasswordSelected', password);
}
getCaCertificateTrust(id: string) {
return sendWithPromise('getCaCertificateTrust', id);
}
editCaCertificateTrust(
id: string, ssl: boolean, email: boolean, objSign: boolean) {
return sendWithPromise('editCaCertificateTrust', id, ssl, email, objSign);
}
importCaCertificateTrustSelected(
ssl: boolean, email: boolean, objSign: boolean) {
return sendWithPromise(
'importCaCertificateTrustSelected', ssl, email, objSign);
}
cancelImportExportCertificate() {
chrome.send('cancelImportExportCertificate');
}
importCaCertificate() {
return sendWithPromise('importCaCertificate');
}
importServerCertificate() {
return sendWithPromise('importServerCertificate');
}
static getInstance(): CertificatesBrowserProxy {
return instance || (instance = new CertificatesBrowserProxyImpl());
}
static setInstance(obj: CertificatesBrowserProxy) {
instance = obj;
}
}
// The singleton instance_ is replaced with a test version of this wrapper
// during testing.
let instance: CertificatesBrowserProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificates_browser_proxy.ts | TypeScript | unknown | 6,843 |
<style include="certificate-shared"></style>
<cr-dialog id="dialog" close-text="[[i18n('close')]]">
<div slot="title">[[model.title]]</div>
<div slot="body">
<div>[[model.description]]</div>
<template is="dom-if" if="[[model.certificateErrors]]">
<template is="dom-repeat" items="[[model.certificateErrors]]">
<div>[[getCertificateErrorText_(item)]]</div>
</template>
</template>
</div>
<div slot="button-container">
<cr-button id="ok" class="action-button" on-click="onOkTap_">
[[i18n('ok')]]
</cr-button>
</div>
</cr-dialog>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificates_error_dialog.html | HTML | unknown | 651 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A dialog for showing SSL certificate related error messages.
* The user can only close the dialog, there is no other possible interaction.
*/
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import './certificate_shared.css.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CertificatesError, CertificatesImportError} from './certificates_browser_proxy.js';
import {getTemplate} from './certificates_error_dialog.html.js';
interface CertificatesErrorDialogElement {
$: {
dialog: CrDialogElement,
};
}
const CertificatesErrorDialogElementBase = I18nMixin(PolymerElement);
class CertificatesErrorDialogElement extends
CertificatesErrorDialogElementBase {
static get is() {
return 'certificates-error-dialog';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
model: Object,
};
}
model: CertificatesError|CertificatesImportError;
override connectedCallback() {
super.connectedCallback();
this.$.dialog.showModal();
}
private onOkTap_() {
this.$.dialog.close();
}
private getCertificateErrorText_(importError: {name: string, error: string}):
string {
return loadTimeData.getStringF(
'certificateImportErrorFormat', importError.name, importError.error);
}
}
customElements.define(
CertificatesErrorDialogElement.is, CertificatesErrorDialogElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/certificate_manager/certificates_error_dialog.ts | TypeScript | unknown | 1,918 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview This file provides a singleton class that exposes the Mojo
* handler interface used for one way communication between the JS and the
* browser.
* TODO(tluk): Convert this into typescript once all dependencies have been
* fully migrated.
*/
import {PageCallbackRouter, PageHandler} from './color_change_listener.mojom-webui.js';
let instance: BrowserProxy|null = null;
export class BrowserProxy {
callbackRouter: PageCallbackRouter;
constructor() {
this.callbackRouter = new PageCallbackRouter();
const pageHandlerRemote = PageHandler.getRemote();
pageHandlerRemote.setPage(this.callbackRouter.$.bindNewPipeAndPassRemote());
}
static getInstance(): BrowserProxy {
return instance || (instance = new BrowserProxy());
}
static setInstance(newInstance: BrowserProxy) {
instance = newInstance;
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/color_change_listener/browser_proxy.ts | TypeScript | unknown | 1,004 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview This file holds the functions that allow WebUI to update its
* colors CSS stylesheet when a ColorProvider change in the browser is detected.
*/
import {BrowserProxy} from './browser_proxy.js';
/**
* The CSS selector used to get the <link> node with the colors.css stylesheet.
* The wildcard is needed since the URL ends with a timestamp.
*/
export const COLORS_CSS_SELECTOR: string = 'link[href*=\'//theme/colors.css\']';
/**
* Forces the document to refresh its colors.css stylesheet. This is used to
* fetch an updated stylesheet when the ColorProvider associated with the WebUI
* has changed.
* Returns a promise which resolves to true once the new colors are loaded and
* installed into the DOM. In the case of an error returns false.
*/
export async function refreshColorCss(): Promise<boolean> {
const colorCssNode = document.querySelector(COLORS_CSS_SELECTOR);
if (!colorCssNode) {
return false;
}
const href = colorCssNode.getAttribute('href');
if (!href) {
return false;
}
const hrefURL = new URL(href, location.href);
const params = new URLSearchParams(hrefURL.search);
params.set('version', new Date().getTime().toString());
const newHref = `${hrefURL.origin}${hrefURL.pathname}?${params.toString()}`;
// A flickering effect may take place when setting the href property of the
// existing color css node with a new value. In order to avoid flickering, we
// create a new link element and once it is loaded we remove the old one. See
// crbug.com/1365320 for additional details.
const newColorsCssLink = document.createElement('link');
newColorsCssLink.setAttribute('href', newHref);
newColorsCssLink.rel = 'stylesheet';
newColorsCssLink.type = 'text/css';
const newColorsLoaded = new Promise(resolve => {
newColorsCssLink.onload = resolve;
});
document.getElementsByTagName('body')[0]!.appendChild(newColorsCssLink);
await newColorsLoaded;
const oldColorCssNode = document.querySelector(COLORS_CSS_SELECTOR);
if (oldColorCssNode) {
oldColorCssNode.remove();
}
return true;
}
let listenerId: number|null = null;
let clientColorChangeListeners: Array<() => void> = [];
/**
* Calls `refreshColorCss()` and any listeners previously registered via
* `addColorChangeListener()`
*/
export async function colorProviderChangeHandler() {
// The webui's current css variables may now be stale, force update them.
await refreshColorCss();
// Notify any interested javascript that the color scheme has changed.
for (const listener of clientColorChangeListeners) {
listener();
}
}
/**
* Register a function to be called every time the page's color provider
* changes. Note that the listeners will only be invoked AFTER
* startColorChangeUpdater() is called.
*/
export function addColorChangeListener(changeListener: () => void) {
clientColorChangeListeners.push(changeListener);
}
/**
* Remove a listener that was previously registered via addColorChangeListener.
* If provided with a listener that was not previously registered does nothing.
*/
export function removeColorChangeListener(changeListener: () => void) {
clientColorChangeListeners = clientColorChangeListeners.filter(
listener => listener !== changeListener);
}
/** Starts listening for ColorProvider change updates from the browser. */
export function startColorChangeUpdater() {
if (listenerId === null) {
listenerId = BrowserProxy.getInstance()
.callbackRouter.onColorProviderChanged.addListener(
colorProviderChangeHandler);
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/color_change_listener/colors_css_updater.ts | TypeScript | unknown | 3,741 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A helper object used by the customize-themes component to
* interact with the browser.
*/
import {CustomizeThemesClientCallbackRouter, CustomizeThemesHandlerFactory, CustomizeThemesHandlerInterface, CustomizeThemesHandlerRemote} from './customize_themes.mojom-webui.js';
export interface CustomizeThemesBrowserProxy {
handler(): CustomizeThemesHandlerInterface;
callbackRouter(): CustomizeThemesClientCallbackRouter;
open(url: string): void;
}
export class CustomizeThemesBrowserProxyImpl implements
CustomizeThemesBrowserProxy {
private handler_: CustomizeThemesHandlerRemote;
private callbackRouter_: CustomizeThemesClientCallbackRouter;
constructor() {
this.handler_ = new CustomizeThemesHandlerRemote();
this.callbackRouter_ = new CustomizeThemesClientCallbackRouter();
const factory = CustomizeThemesHandlerFactory.getRemote();
factory.createCustomizeThemesHandler(
this.callbackRouter_.$.bindNewPipeAndPassRemote(),
this.handler_.$.bindNewPipeAndPassReceiver());
}
handler() {
return this.handler_;
}
callbackRouter() {
return this.callbackRouter_;
}
open(url: string) {
window.open(url, '_blank');
}
static getInstance(): CustomizeThemesBrowserProxy {
return instance || (instance = new CustomizeThemesBrowserProxyImpl());
}
static setInstance(obj: CustomizeThemesBrowserProxy) {
instance = obj;
}
}
let instance: CustomizeThemesBrowserProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/customize_themes/browser_proxy.ts | TypeScript | unknown | 1,631 |
<style include="cr-hidden-style cr-icons cr-shared-style">
:host {
--cr-customize-themes-grid-gap: 20px;
--cr-customize-themes-icon-size: 72px;
display: inline-block;
}
#thirdPartyThemeContainer {
max-width: 544px;
width: 100%;
}
#thirdPartyTheme {
align-items: center;
border: 1px solid var(--google-grey-300);
border-radius: 5px;
color: var(--cr-primary-text-color);
display: flex;
flex-direction: row;
margin-bottom: 24px;
padding: 0 16px;
}
@media (prefers-color-scheme: dark) {
#thirdPartyTheme {
border-color: var(--google-grey-700);
}
}
#thirdPartyBrushIcon {
-webkit-mask-image: url(chrome://resources/cr_components/customize_themes/brush.svg);
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 100%;
background-color: var(--cr-primary-text-color);
margin-inline-end: 20px;
min-height: 24px;
min-width: 24px;
}
#thirdPartyThemeNameContainer {
flex-grow: 1;
margin-inline-end: 24px;
}
#thirdPartyThemeName {
font-weight: bold;
}
#thirdPartyLink {
--cr-icon-button-fill-color: var(--cr-primary-text-color);
margin-inline-end: 24px;
}
#uninstallThirdPartyButton {
margin: 16px 0;
}
#themesContainer {
--cr-grid-gap: var(--cr-customize-themes-grid-gap);
}
#themesContainer > * {
outline-width: 0;
}
:host-context(.focus-outline-visible) #themesContainer > *:focus {
box-shadow: 0 0 0 2px rgba(var(--google-blue-600-rgb), .4);
}
#autogeneratedThemeContainer {
cursor: pointer;
position: relative;
}
/* colorPicker is placed on top of the theme icon to work around
https://crbug.com/1162053 */
#colorPicker {
border: 0;
height: var(--cr-customize-themes-icon-size);
left: 0;
margin: 0;
opacity: 0;
padding: 0;
position: absolute;
top: 0;
width: var(--cr-customize-themes-icon-size);
}
#colorPickerIcon {
-webkit-mask-image: url(chrome://resources/cr_components/customize_themes/colorize.svg);
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: 100%;
background-color: var(--google-grey-700);
height: 20px;
left: calc(50% - 10px);
position: absolute;
top: calc(50% - 10px);
width: 20px;
}
cr-theme-icon {
--cr-theme-icon-size: var(--cr-customize-themes-icon-size);
}
#autogeneratedTheme {
--cr-theme-icon-frame-color: var(--google-grey-100);
--cr-theme-icon-active-tab-color: white;
--cr-theme-icon-stroke-color: var(--google-grey-300);
}
#defaultTheme {
--cr-theme-icon-frame-color: rgb(222, 225, 230);
--cr-theme-icon-active-tab-color: white;
}
@media (prefers-color-scheme: dark) {
#defaultTheme {
--cr-theme-icon-frame-color: rgb(var(--google-grey-900-rgb));
--cr-theme-icon-active-tab-color: rgb(50, 54, 57);
}
}
paper-tooltip {
--paper-tooltip-delay-in: 100ms;
--paper-tooltip-duration-in: 100ms;
--paper-tooltip-duration-out: 100ms;
--paper-tooltip-min-width: none;
--paper-tooltip-padding: 5px 4px;
}
</style>
<div id="thirdPartyThemeContainer" hidden="[[!isThirdPartyTheme_(selectedTheme)]]">
<div id="thirdPartyTheme">
<div id="thirdPartyBrushIcon"></div>
<div id="thirdPartyThemeNameContainer">
<div id="thirdPartyThemeName" >
[[selectedTheme.info.thirdPartyThemeInfo.name]]
</div>
<div>[[i18n('thirdPartyThemeDescription')]]</div>
</div>
<cr-icon-button id="thirdPartyLink" class="icon-external" role="link"
on-click="onThirdPartyLinkButtonClick_">
</cr-icon-button>
<cr-button id="uninstallThirdPartyButton"
on-click="onUninstallThirdPartyThemeClick_">
[[i18n('uninstallThirdPartyThemeButton')]]
</cr-button>
</div>
</div>
<cr-grid id="themesContainer" aria-label="[[i18n('themesContainerLabel')]]"
columns="6" role="radiogroup">
<div aria-label="[[i18n('colorPickerLabel')]]"
tabindex$="[[getTabIndex_('autogenerated', selectedTheme)]]"
on-click="onAutogeneratedThemeClick_" role="radio"
aria-checked$="[[getThemeIconCheckedStatus_('autogenerated', selectedTheme)]]">
<div id="autogeneratedThemeContainer">
<cr-theme-icon id="autogeneratedTheme"
selected$="[[isThemeIconSelected_('autogenerated', selectedTheme)]]">
</cr-theme-icon>
<div id="colorPickerIcon" hidden="[[isForcedTheme_(selectedTheme)]]"></div>
<input id="colorPicker" type="color" tabindex="-1" aria-hidden="true"
on-change="onCustomFrameColorChange_">
</div>
<paper-tooltip offset="0" fit-to-visible-bounds>
[[i18n('colorPickerLabel')]]
</paper-tooltip>
</div>
<div aria-label="[[i18n('defaultThemeLabel')]]"
tabindex$="[[getTabIndex_('default', selectedTheme)]]"
on-click="onDefaultThemeClick_" role="radio"
aria-checked$="[[getThemeIconCheckedStatus_('default', selectedTheme)]]">
<cr-theme-icon id="defaultTheme"
selected$="[[isThemeIconSelected_('default', selectedTheme)]]">
</cr-theme-icon>
<paper-tooltip offset="0" fit-to-visible-bounds>
[[i18n('defaultThemeLabel')]]
</paper-tooltip>
</div>
<template is="dom-repeat" id="themes" items="[[chromeThemes_]]">
<div aria-label="[[item.label]]"
tabindex$="[[getTabIndex_(item.id, selectedTheme)]]"
on-click="onChromeThemeClick_" class="chrome-theme-wrapper" role="radio"
aria-checked$="[[getThemeIconCheckedStatus_(item.id, selectedTheme)]]">
<cr-theme-icon
style="--cr-theme-icon-frame-color:
[[skColorToRgba_(item.colors.frame)]];
--cr-theme-icon-active-tab-color:
[[skColorToRgba_(item.colors.activeTab)]];"
selected$="[[isThemeIconSelected_(item.id, selectedTheme)]]">
</cr-theme-icon>
<paper-tooltip offset="0" fit-to-visible-bounds>
[[item.label]]
</paper-tooltip>
</div>
</template>
</cr-grid>
<template is="dom-if" if="[[showManagedThemeDialog_]]" restamp>
<managed-dialog on-close="onManagedDialogClosed_"
title="[[i18n('themeManagedDialogTitle')]]"
body="[[i18n('themeManagedDialogBody')]]">
</managed-dialog>
</template>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/customize_themes/customize_themes.html | HTML | unknown | 6,220 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_components/managed_dialog/managed_dialog.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.js';
import 'chrome://resources/cr_elements/cr_icons.css.js';
import 'chrome://resources/cr_elements/cr_grid/cr_grid.js';
import 'chrome://resources/cr_elements/cr_shared_vars.css.js';
import 'chrome://resources/cr_elements/cr_shared_style.css.js';
import './theme_icon.js';
import '//resources/polymer/v3_0/paper-tooltip/paper-tooltip.js';
import {I18nMixin} from 'chrome://resources/cr_elements/i18n_mixin.js';
import {assert} from 'chrome://resources/js/assert_ts.js';
import {hexColorToSkColor, skColorToRgba} from 'chrome://resources/js/color_utils.js';
import {SkColor} from 'chrome://resources/mojo/skia/public/mojom/skcolor.mojom-webui.js';
import {DomRepeat} from 'chrome://resources/polymer/v3_0/polymer/lib/elements/dom-repeat.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {CustomizeThemesBrowserProxyImpl} from './browser_proxy.js';
import {getTemplate} from './customize_themes.html.js';
import {ChromeTheme, CustomizeThemesClientCallbackRouter, CustomizeThemesHandlerInterface, Theme, ThemeType} from './customize_themes.mojom-webui.js';
import {ThemeIconElement} from './theme_icon.js';
export interface CustomizeThemesElement {
$: {
autogeneratedTheme: ThemeIconElement,
colorPicker: HTMLInputElement,
colorPickerIcon: HTMLElement,
defaultTheme: ThemeIconElement,
themes: DomRepeat,
};
}
const CustomizeThemesElementBase = I18nMixin(PolymerElement);
/**
* Element that lets the user configure the autogenerated theme.
*/
export class CustomizeThemesElement extends CustomizeThemesElementBase {
static get is() {
return 'cr-customize-themes';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* An object describing the currently selected theme.
*/
selectedTheme: {
type: Object,
value: null,
observer: 'onThemeChange_',
notify: true,
},
/**
* If false, confirmThemeChanges() should be called after applying a theme
* to permanently apply the change. Otherwise, theme changes are confirmed
* automatically.
*/
autoConfirmThemeChanges: {
type: Boolean,
value: false,
},
chromeThemes_: Array,
showManagedThemeDialog_: {
type: Boolean,
value: false,
},
};
}
selectedTheme: Theme|null;
autoConfirmThemeChanges: boolean;
private chromeThemes_: ChromeTheme[];
private showManagedThemeDialog_: boolean;
private handler_: CustomizeThemesHandlerInterface =
CustomizeThemesBrowserProxyImpl.getInstance().handler();
private callbackRouter_: CustomizeThemesClientCallbackRouter =
CustomizeThemesBrowserProxyImpl.getInstance().callbackRouter();
private setThemeListenerId_: number|null = null;
override connectedCallback() {
super.connectedCallback();
this.handler_.initializeTheme();
this.handler_.getChromeThemes().then(({chromeThemes}) => {
this.chromeThemes_ = chromeThemes;
});
this.setThemeListenerId_ =
this.callbackRouter_.setTheme.addListener((theme: Theme) => {
this.selectedTheme = theme;
});
}
override disconnectedCallback() {
this.revertThemeChanges();
assert(this.setThemeListenerId_);
this.callbackRouter_.removeListener(this.setThemeListenerId_);
super.disconnectedCallback();
}
confirmThemeChanges() {
this.handler_.confirmThemeChanges();
}
revertThemeChanges() {
this.handler_.revertThemeChanges();
}
private onCustomFrameColorChange_(e: Event) {
this.handler_.applyAutogeneratedTheme(
hexColorToSkColor((e.target as HTMLInputElement).value));
if (this.autoConfirmThemeChanges) {
this.handler_.confirmThemeChanges();
}
}
private onAutogeneratedThemeClick_() {
if (this.isForcedTheme_()) {
// If the applied theme is managed, show a dialog to inform the user.
this.showManagedThemeDialog_ = true;
return;
}
this.$.colorPicker.focus();
this.$.colorPicker.click();
}
private onDefaultThemeClick_() {
if (this.isForcedTheme_()) {
// If the applied theme is managed, show a dialog to inform the user.
this.showManagedThemeDialog_ = true;
return;
}
this.handler_.applyDefaultTheme();
if (this.autoConfirmThemeChanges) {
this.handler_.confirmThemeChanges();
}
}
private onChromeThemeClick_(e: Event) {
if (this.isForcedTheme_()) {
// If the applied theme is managed, show a dialog to inform the user.
this.showManagedThemeDialog_ = true;
return;
}
this.handler_.applyChromeTheme(
this.$.themes.itemForElement((e.target as HTMLElement)).id);
if (this.autoConfirmThemeChanges) {
this.handler_.confirmThemeChanges();
}
}
private onThemeChange_() {
if (!this.selectedTheme ||
this.selectedTheme.type !== ThemeType.kAutogenerated) {
return;
}
const rgbaFrameColor =
skColorToRgba(this.selectedTheme.info.autogeneratedThemeColors!.frame);
const rgbaActiveTabColor = skColorToRgba(
this.selectedTheme.info.autogeneratedThemeColors!.activeTab);
this.$.autogeneratedTheme.style.setProperty(
'--cr-theme-icon-frame-color', rgbaFrameColor);
this.$.autogeneratedTheme.style.setProperty(
'--cr-theme-icon-stroke-color', rgbaFrameColor);
this.$.autogeneratedTheme.style.setProperty(
'--cr-theme-icon-active-tab-color', rgbaActiveTabColor);
this.$.colorPickerIcon.style.setProperty(
'background-color',
skColorToRgba(
this.selectedTheme.info.autogeneratedThemeColors!.activeTabText));
}
private onUninstallThirdPartyThemeClick_() {
this.handler_.applyDefaultTheme();
this.handler_.confirmThemeChanges();
}
private onThirdPartyLinkButtonClick_() {
CustomizeThemesBrowserProxyImpl.getInstance().open(
`https://chrome.google.com/webstore/detail/${
this.selectedTheme!.info.thirdPartyThemeInfo!.id}`);
}
private isThemeIconSelected_(id: string|number): boolean {
if (!this.selectedTheme) {
return false;
}
if (id === 'autogenerated') {
return this.selectedTheme.type === ThemeType.kAutogenerated;
} else if (id === 'default') {
return this.selectedTheme.type === ThemeType.kDefault;
} else {
return this.selectedTheme.type === ThemeType.kChrome &&
id === this.selectedTheme.info.chromeThemeId;
}
}
private getTabIndex_(id: string|number): string {
if (!this.selectedTheme ||
this.selectedTheme.type === ThemeType.kThirdParty) {
return id === 'autogenerated' ? '0' : '-1';
}
return this.isThemeIconSelected_(id) ? '0' : '-1';
}
private getThemeIconCheckedStatus_(id: string|number): string {
return this.isThemeIconSelected_(id) ? 'true' : 'false';
}
private isThirdPartyTheme_(): boolean {
return !!this.selectedTheme &&
this.selectedTheme.type === ThemeType.kThirdParty;
}
private isForcedTheme_(): boolean {
return !!this.selectedTheme && this.selectedTheme.isForced;
}
private skColorToRgba_(skColor: SkColor): string {
return skColorToRgba(skColor);
}
private onManagedDialogClosed_() {
this.showManagedThemeDialog_ = false;
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-customize-themes': CustomizeThemesElement;
}
}
customElements.define(CustomizeThemesElement.is, CustomizeThemesElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/customize_themes/customize_themes.ts | TypeScript | unknown | 7,901 |
<style>
:host {
--cr-theme-icon-size: 72px;
cursor: pointer;
display: block;
}
:host,
svg {
display: block;
height: var(--cr-theme-icon-size);
width: var(--cr-theme-icon-size);
}
#ring {
fill: rgba(var(--google-blue-600-rgb), 0.4);
visibility: hidden;
}
#checkMark {
visibility: hidden;
}
:host([selected]) #ring,
:host([selected]) #checkMark {
visibility: visible;
}
#circle {
fill: url(#gradient);
stroke: var(--cr-theme-icon-stroke-color,
var(--cr-theme-icon-frame-color));
stroke-width: 1;
}
#leftColor {
stop-color: var(--cr-theme-icon-active-tab-color);
}
#rightColor {
stop-color: var(--cr-theme-icon-frame-color);
}
#checkMark circle {
fill: var(--google-blue-600);
}
#checkMark path {
fill: white;
}
@media (prefers-color-scheme: dark) {
#checkMark circle {
fill: var(--google-blue-300);
}
#checkMark path {
fill: var(--google-grey-900);
}
}
:host-context([dir='rtl']) #checkMark {
transform: translateX(3.5px);
}
</style>
<svg viewBox="0 0 72 72" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="gradient" gradientUnits="objectBoundingBox"
x1="50%" y1="0" x2="50.01%" y2="0">
<stop id="leftColor" offset="0%"></stop>
<stop id="rightColor" offset="100%"></stop>
</linearGradient>
</defs>
<circle id="ring" cx="36" cy="36" r="36"></circle>
<circle id="circle" cx="36" cy="36" r="32"></circle>
<g id="checkMark" transform="translate(48.5, 3.5)">
<circle cx="10" cy="10" r="10"></circle>
<path d="m 2.9885708,9.99721 5.0109458,4.98792 0.00275,-0.003
0.024151,0.0227 8.9741604,-9.01557 -1.431323,-1.42476 -7.5742214,7.6092
-3.6031671,-3.58665 z">
</path>
</g>
</svg>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/customize_themes/theme_icon.html | HTML | unknown | 1,873 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_elements/cr_shared_vars.css.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './theme_icon.html.js';
/**
* Represents a theme. Displayed as a circle with each half colored based on
* the custom CSS properties |--cr-theme-icon-frame-color| and
* |--cr-theme-icon-active-tab-color|. Can be selected by setting the
* |selected| attribute.
*/
export class ThemeIconElement extends PolymerElement {
static get is() {
return 'cr-theme-icon';
}
static get template() {
return getTemplate();
}
}
declare global {
interface HTMLElementTagNameMap {
'cr-theme-icon': ThemeIconElement;
}
}
customElements.define(ThemeIconElement.is, ThemeIconElement);
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/customize_themes/theme_icon.ts | TypeScript | unknown | 926 |
<style include="cr-hidden-style">
:host {
border-radius: 8px;
box-shadow: 0 6px 10px 4px rgba(60, 64, 67, 0.15), 0 2px 3px rgba(60, 64, 67, 0.3);
box-sizing: border-box;
position: absolute;
z-index: 1;
}
#arrow {
--help-bubble-arrow-size: 11.3px;
--help-bubble-arrow-size-half: calc(var(--help-bubble-arrow-size) / 2);
--help-bubble-arrow-diameter: 16px;
/* approx. */
--help-bubble-arrow-radius: calc(var(--help-bubble-arrow-diameter) / 2);
--help-bubble-arrow-edge-offset: 22px;
--help-bubble-arrow-offset: calc(var(--help-bubble-arrow-edge-offset) + var(--help-bubble-arrow-radius));
--help-bubble-arrow-border-radius: 2px;
position: absolute;
}
/* #inner-arrow is rotated and positioned in a container to simplify positioning */
#inner-arrow {
background-color: var(--help-bubble-background);
height: var(--help-bubble-arrow-size);
left: calc(0px - var(--help-bubble-arrow-size-half));
position: absolute;
top: calc(0px - var(--help-bubble-arrow-size-half));
transform: rotate(45deg);
width: var(--help-bubble-arrow-size);
z-index: -1;
}
#arrow.bottom-edge {
bottom: 0;
}
#arrow.bottom-edge #inner-arrow {
border-bottom-right-radius: var(--help-bubble-arrow-border-radius);
}
#arrow.top-edge {
top: 0;
}
#arrow.top-edge #inner-arrow {
border-top-left-radius: var(--help-bubble-arrow-border-radius);
}
#arrow.right-edge {
right: 0;
}
#arrow.right-edge #inner-arrow {
border-top-right-radius: var(--help-bubble-arrow-border-radius);
}
#arrow.left-edge {
left: 0;
}
#arrow.left-edge #inner-arrow {
border-bottom-left-radius: var(--help-bubble-arrow-border-radius);
}
#arrow.top-position {
top: var(--help-bubble-arrow-offset);
}
#arrow.vertical-center-position {
top: 50%;
}
#arrow.bottom-position {
bottom: var(--help-bubble-arrow-offset);
}
#arrow.left-position {
left: var(--help-bubble-arrow-offset);
}
#arrow.horizontal-center-position {
left: 50%;
}
#arrow.right-position {
right: var(--help-bubble-arrow-offset);
}
#topContainer {
display: flex;
flex-direction: row;
}
#progress {
display: inline-block;
flex: auto;
}
#progress div {
--help-bubble-progress-size: 8px;
background-color: var(--help-bubble-text-color);
border: 1px solid var(--help-bubble-text-color);
border-radius: 50%;
display: inline-block;
height: var(--help-bubble-progress-size);
margin-inline-end: var(--help-bubble-element-spacing);
margin-top: 5px;
width: var(--help-bubble-progress-size);
}
#progress .total-progress {
background-color: var(--help-bubble-background);
}
#topBody,
#mainBody {
flex: 1;
font-size: 14px;
font-style: normal;
font-weight: 500;
letter-spacing: 0.3px;
line-height: 20px;
margin: 0;
}
#title {
flex: 1;
font-size: 18px;
font-style: normal;
font-weight: 500;
line-height: 22px;
margin: 0;
}
/* Note: help bubbles have the same color treatment in both light and dark
* themes, which is why the values below do not change based on theme
* preference. */
.help-bubble {
--help-bubble-background: var(--google-blue-700);
--help-bubble-element-spacing: 8px;
--help-bubble-text-color: var(--google-grey-200);
background-color: var(--help-bubble-background);
border-radius: 8px;
box-sizing: border-box;
color: var(--help-bubble-text-color);
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 16px 20px;
position: relative;
width: 340px;
}
#main {
display: flex;
flex-direction: row;
justify-content: flex-start;
margin-top: var(--help-bubble-element-spacing);
}
#middleRowSpacer {
margin-inline-start: 32px;
}
cr-icon-button {
--cr-icon-button-fill-color: var(--help-bubble-text-color);
--cr-icon-button-hover-background-color:
rgba(var(--google-blue-300-rgb), .3);
--cr-icon-button-icon-size: 16px;
--cr-icon-button-size: 24px;
--cr-icon-button-stroke-color: var(--help-bubble-text-color);
box-sizing: border-box;
display: block;
flex: none;
float: right;
height: var(--cr-icon-button-size);
margin: 0;
margin-inline-start: var(--help-bubble-element-spacing);
order: 2;
width: var(--cr-icon-button-size);
}
cr-icon-button:focus {
border: 2px solid var(--help-bubble-text-color);
}
#bodyIcon {
--body-icon-button-size: 24px;
--iron-icon-height: 18px;
--iron-icon-width: 18px;
background-color: var(--help-bubble-text-color);
border-radius: 50%;
box-sizing: border-box;
color: var(--help-bubble-background);
height: var(--body-icon-button-size);
margin-inline-end: var(--help-bubble-element-spacing);
padding: 3px;
text-align: center;
width: var(--body-icon-button-size);
}
#buttons {
display: flex;
flex-direction: row;
justify-content: flex-end;
margin-top: 24px;
}
cr-button {
--text-color: var(--help-bubble-text-color);
border-color: var(--help-bubble-text-color);
}
cr-button:not(:first-child) {
margin-inline-start: var(--help-bubble-element-spacing);
}
cr-button:focus {
border-color: var(--help-bubble-background);
box-shadow: 0 0 0 2px var(--help-bubble-text-color);
}
cr-button.default-button {
--text-color: var(--help-bubble-background);
background-color: var(--help-bubble-text-color);
}
cr-button.default-button:focus {
border: 2px solid var(--help-bubble-background);
box-shadow: 0 0 0 1px var(--help-bubble-text-color);
}
</style>
<div class="help-bubble" role="alertdialog" aria-modal="true"
aria-labelledby="title" aria-describedby="body" aria-live="assertive"
on-keydown="onKeyDown_" on-click="blockPropagation_">
<div id="topContainer">
<div id="bodyIcon" hidden$="[[!shouldShowBodyIcon_(bodyIconName)]]"
aria-label$="[[bodyIconAltText]]">
<iron-icon icon="iph:[[bodyIconName]]"></iron-icon>
</div>
<div id="progress" hidden$="[[!progress]]" role="progressbar"
aria-valuenow$="[[progress.current]]" aria-valuemin="1"
aria-valuemax$="[[progress.total]]">
<template is="dom-repeat" items="[[progressData_]]">
<div class$="[[getProgressClass_(index)]]"></div>
</template>
</div>
<h1 id="title"
hidden$="[[!shouldShowTitleInTopContainer_(progress, titleText)]]">
[[titleText]]
</h1>
<p id="topBody"
hidden$="[[!shouldShowBodyInTopContainer_(progress, titleText)]]">
[[bodyText]]
</p>
<cr-icon-button id="close" iron-icon="cr:close"
aria-label$="[[closeButtonAltText]]" on-click="dismiss_"
tabindex$="[[closeButtonTabIndex]]">
</cr-icon-button>
</div>
<div id="main" hidden$="[[!shouldShowBodyInMain_(progress, titleText)]]">
<div id="middleRowSpacer" hidden$="[[!shouldShowBodyIcon_(bodyIconName)]]">
</div>
<p id="mainBody">[[bodyText]]</p>
</div>
<div id="buttons" hidden$="[[!buttons.length]]">
<template is="dom-repeat" id="buttonlist" items="[[buttons]]"
sort="buttonSortFunc_">
<cr-button id$="[[getButtonId_(itemsIndex)]]"
tabindex$="[[getButtonTabIndex_(itemsIndex, item.isDefault)]]"
class$="[[getButtonClass_(item.isDefault)]]" on-click="onButtonClick_"
role="button" aria-label="[[item.text]]">[[item.text]]</cr-button>
</template>
</div>
<div id="arrow" class$="[[getArrowClass_(position)]]">
<div id="inner-arrow"></div>
</div>
</div> | Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/help_bubble/help_bubble.html | HTML | unknown | 7,696 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A bubble for displaying in-product help. These are created
* dynamically by HelpBubbleMixin, and their API should be considered an
* implementation detail and subject to change (you should not add them to your
* components directly).
*/
import '//resources/cr_elements/cr_button/cr_button.js';
import '//resources/cr_elements/cr_hidden_style.css.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.js';
import '//resources/cr_elements/cr_shared_vars.css.js';
import '//resources/cr_elements/icons.html.js';
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import './help_bubble_icons.html.js';
import {CrButtonElement} from '//resources/cr_elements/cr_button/cr_button.js';
import {CrIconButtonElement} from '//resources/cr_elements/cr_icon_button/cr_icon_button.js';
import {assert, assertNotReached} from '//resources/js/assert_ts.js';
import {isWindows} from '//resources/js/platform.js';
import {DomRepeat, DomRepeatEvent, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {InsetsF} from 'chrome://resources/mojo/ui/gfx/geometry/mojom/geometry.mojom-webui.js';
import {getTemplate} from './help_bubble.html.js';
import {HelpBubbleArrowPosition, HelpBubbleButtonParams, Progress} from './help_bubble.mojom-webui.js';
const ACTION_BUTTON_ID_PREFIX = 'action-button-';
export const HELP_BUBBLE_DISMISSED_EVENT = 'help-bubble-dismissed';
export const HELP_BUBBLE_TIMED_OUT_EVENT = 'help-bubble-timed-out';
export const HELP_BUBBLE_SCROLL_ANCHOR_OPTIONS: ScrollIntoViewOptions = {
behavior: 'smooth',
block: 'center',
};
export type HelpBubbleDismissedEvent = CustomEvent<{
nativeId: any,
fromActionButton: boolean,
buttonIndex?: number,
}>;
export type HelpBubbleTimedOutEvent = CustomEvent<{
nativeId: any,
}>;
export function debounceEnd(fn: Function, time: number = 50): () => void {
let timerId: number|undefined;
return () => {
clearTimeout(timerId);
timerId = setTimeout(fn, time);
};
}
export interface HelpBubbleElement {
$: {
arrow: HTMLElement,
bodyIcon: HTMLElement,
buttons: HTMLElement,
buttonlist: DomRepeat,
close: CrIconButtonElement,
main: HTMLElement,
mainBody: HTMLElement,
progress: HTMLElement,
title: HTMLElement,
topBody: HTMLElement,
topContainer: HTMLElement,
};
}
export class HelpBubbleElement extends PolymerElement {
static get is() {
return 'help-bubble';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
nativeId: {
type: String,
value: '',
reflectToAttribute: true,
},
position: {
type: HelpBubbleArrowPosition,
value: HelpBubbleArrowPosition.TOP_CENTER,
reflectToAttribute: true,
},
};
}
nativeId: any;
bodyText: string;
titleText: string;
closeButtonAltText: string;
closeButtonTabIndex: number = 0;
position: HelpBubbleArrowPosition;
buttons: HelpBubbleButtonParams[] = [];
progress: Progress|null = null;
bodyIconName: string|null;
bodyIconAltText: string;
timeoutMs: number|null = null;
timeoutTimerId: number|null = null;
debouncedUpdate: (() => void)|null = null;
padding: InsetsF = new InsetsF();
fixed: boolean = false;
/**
* HTMLElement corresponding to |this.nativeId|.
*/
private anchorElement_: HTMLElement|null = null;
/**
* Backing data for the dom-repeat that generates progress indicators.
* The elements are placeholders only.
*/
private progressData_: void[] = [];
/**
* Watches the offsetParent for resize events, allowing the bubble to be
* repositioned in response. Useful for when the content around a help bubble
* target can be filtered/expanded/repositioned.
*/
private resizeObserver_: ResizeObserver|null = null;
/**
* Shows the bubble.
*/
show(anchorElement: HTMLElement) {
this.anchorElement_ = anchorElement;
// Set up the progress track.
if (this.progress) {
this.progressData_ = new Array(this.progress.total);
} else {
this.progressData_ = [];
}
this.closeButtonTabIndex =
this.buttons.length ? this.buttons.length + 2 : 1;
assert(
this.anchorElement_,
'Tried to show a help bubble but anchorElement does not exist');
// Reset the aria-hidden attribute as screen readers need to access the
// contents of an opened bubble.
this.style.display = 'block';
this.style.position = this.fixed ? 'fixed' : 'absolute';
this.removeAttribute('aria-hidden');
this.updatePosition_();
this.debouncedUpdate = debounceEnd(() => {
if (this.anchorElement_) {
this.updatePosition_();
}
}, 50);
this.$.buttonlist.addEventListener(
'rendered-item-count-changed', this.debouncedUpdate);
window.addEventListener('resize', this.debouncedUpdate);
if (this.timeoutMs !== null) {
const timedOutCallback = () => {
this.dispatchEvent(new CustomEvent(HELP_BUBBLE_TIMED_OUT_EVENT, {
detail: {
nativeId: this.nativeId,
},
}));
};
this.timeoutTimerId = setTimeout(timedOutCallback, this.timeoutMs);
}
if (this.offsetParent && !this.fixed) {
this.resizeObserver_ = new ResizeObserver(() => {
this.updatePosition_();
this.anchorElement_?.scrollIntoView(HELP_BUBBLE_SCROLL_ANCHOR_OPTIONS);
});
this.resizeObserver_.observe(this.offsetParent);
}
}
/**
* Hides the bubble, clears out its contents, and ensures that screen readers
* ignore it while hidden.
*
* TODO(dfried): We are moving towards formalizing help bubbles as single-use;
* in which case most of this tear-down logic can be removed since the entire
* bubble will go away on hide.
*/
hide() {
if (this.resizeObserver_) {
this.resizeObserver_.disconnect();
this.resizeObserver_ = null;
}
this.style.display = 'none';
this.setAttribute('aria-hidden', 'true');
this.anchorElement_ = null;
if (this.timeoutTimerId !== null) {
clearInterval(this.timeoutTimerId);
this.timeoutTimerId = null;
}
if (this.debouncedUpdate) {
window.removeEventListener('resize', this.debouncedUpdate);
this.$.buttonlist.removeEventListener(
'rendered-item-count-changed', this.debouncedUpdate);
this.debouncedUpdate = null;
}
}
/**
* Retrieves the current anchor element, if set and the bubble is showing,
* otherwise null.
*/
getAnchorElement(): HTMLElement|null {
return this.anchorElement_;
}
/**
* Returns the button with the given `buttonIndex`, or null if not found.
*/
getButtonForTesting(buttonIndex: number): CrButtonElement|null {
return this.$.buttons.querySelector<CrButtonElement>(
`[id="${ACTION_BUTTON_ID_PREFIX + buttonIndex}"]`);
}
/**
* Focuses a button in the bubble.
*/
override focus() {
this.$.buttonlist.render();
const button: HTMLElement =
this.$.buttons.querySelector('cr-button.default-button') ||
this.$.buttons.querySelector('cr-button') || this.$.close;
assert(button);
button.focus();
}
/**
* Returns whether the default button is leading (true on Windows) vs trailing
* (all other platforms).
*/
static isDefaultButtonLeading(): boolean {
return isWindows;
}
private dismiss_() {
assert(this.nativeId, 'Dismiss: expected help bubble to have a native id.');
this.dispatchEvent(new CustomEvent(HELP_BUBBLE_DISMISSED_EVENT, {
detail: {
nativeId: this.nativeId,
fromActionButton: false,
},
}));
}
/**
* Handles ESC keypress (dismiss bubble) and prevents it from propagating up
* to parent elements.
*/
private onKeyDown_(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.stopPropagation();
this.dismiss_();
}
}
/**
* Prevent event propagation. Attach to any event that should not bubble up
* out of the help bubble.
*/
private blockPropagation_(e: Event) {
e.stopPropagation();
}
private getProgressClass_(index: number): string {
return index < this.progress!.current ? 'current-progress' :
'total-progress';
}
private shouldShowTitleInTopContainer_(
progress: Progress|null, titleText: string): boolean {
return !!titleText && !progress;
}
private shouldShowBodyInTopContainer_(
progress: Progress|null, titleText: string): boolean {
return !progress && !titleText;
}
private shouldShowBodyInMain_(progress: Progress|null, titleText: string):
boolean {
return !!progress || !!titleText;
}
private shouldShowBodyIcon_(bodyIconName: string): boolean {
return bodyIconName !== null && bodyIconName !== '';
}
private onButtonClick_(e: DomRepeatEvent<HelpBubbleButtonParams>) {
assert(
this.nativeId,
'Action button clicked: expected help bubble to have a native ID.');
// There is no access to the model index here due to limitations of
// dom-repeat. However, the index is stored in the node's identifier.
const index: number = parseInt(
(e.target as Element).id.substring(ACTION_BUTTON_ID_PREFIX.length));
this.dispatchEvent(new CustomEvent(HELP_BUBBLE_DISMISSED_EVENT, {
detail: {
nativeId: this.nativeId,
fromActionButton: true,
buttonIndex: index,
},
}));
}
private getButtonId_(index: number): string {
return ACTION_BUTTON_ID_PREFIX + index;
}
private getButtonClass_(isDefault: boolean): string {
return isDefault ? 'default-button' : '';
}
private getButtonTabIndex_(index: number, isDefault: boolean): number {
return isDefault ? 1 : index + 2;
}
private buttonSortFunc_(
button1: HelpBubbleButtonParams,
button2: HelpBubbleButtonParams): number {
// Default button is leading on Windows, trailing on other platforms.
if (button1.isDefault) {
return isWindows ? -1 : 1;
}
if (button2.isDefault) {
return isWindows ? 1 : -1;
}
return 0;
}
/**
* Determine classes that describe the arrow position relative to the
* HelpBubble
*/
private getArrowClass_(position: HelpBubbleArrowPosition): string {
let classList = '';
// `*-edge` classes move arrow to a HelpBubble edge
switch (position) {
case HelpBubbleArrowPosition.TOP_LEFT:
case HelpBubbleArrowPosition.TOP_CENTER:
case HelpBubbleArrowPosition.TOP_RIGHT:
classList = 'top-edge ';
break;
case HelpBubbleArrowPosition.BOTTOM_LEFT:
case HelpBubbleArrowPosition.BOTTOM_CENTER:
case HelpBubbleArrowPosition.BOTTOM_RIGHT:
classList = 'bottom-edge ';
break;
case HelpBubbleArrowPosition.LEFT_TOP:
case HelpBubbleArrowPosition.LEFT_CENTER:
case HelpBubbleArrowPosition.LEFT_BOTTOM:
classList = 'left-edge ';
break;
case HelpBubbleArrowPosition.RIGHT_TOP:
case HelpBubbleArrowPosition.RIGHT_CENTER:
case HelpBubbleArrowPosition.RIGHT_BOTTOM:
classList = 'right-edge ';
break;
default:
assertNotReached('Unknown help bubble position: ' + position);
}
// `*-position` classes move arrow along the HelpBubble edge
switch (position) {
case HelpBubbleArrowPosition.TOP_LEFT:
case HelpBubbleArrowPosition.BOTTOM_LEFT:
classList += 'left-position';
break;
case HelpBubbleArrowPosition.TOP_CENTER:
case HelpBubbleArrowPosition.BOTTOM_CENTER:
classList += 'horizontal-center-position';
break;
case HelpBubbleArrowPosition.TOP_RIGHT:
case HelpBubbleArrowPosition.BOTTOM_RIGHT:
classList += 'right-position';
break;
case HelpBubbleArrowPosition.LEFT_TOP:
case HelpBubbleArrowPosition.RIGHT_TOP:
classList += 'top-position';
break;
case HelpBubbleArrowPosition.LEFT_CENTER:
case HelpBubbleArrowPosition.RIGHT_CENTER:
classList += 'vertical-center-position';
break;
case HelpBubbleArrowPosition.LEFT_BOTTOM:
case HelpBubbleArrowPosition.RIGHT_BOTTOM:
classList += 'bottom-position';
break;
default:
assertNotReached('Unknown help bubble position: ' + position);
}
return classList;
}
/**
* Sets the bubble position, as relative to that of the anchor element and
* |this.position|.
*/
private updatePosition_() {
assert(
this.anchorElement_, 'Update position: expected valid anchor element.');
// How far HelpBubble is from anchorElement
const ANCHOR_OFFSET = 16;
const ARROW_WIDTH = 16;
// The nearest an arrow can be to the adjacent HelpBubble edge
const ARROW_OFFSET_FROM_EDGE = 22 + (ARROW_WIDTH / 2);
// Inclusive of 8px visible arrow and 8px margin.
const anchorRect = this.anchorElement_.getBoundingClientRect();
const anchorRectCenter = {
x: anchorRect.left + (anchorRect.width / 2),
y: anchorRect.top + (anchorRect.height / 2),
};
const helpBubbleRect = this.getBoundingClientRect();
// component is inserted at mixin root so start with anchor offsets
let offsetX = this.anchorElement_.offsetLeft;
let offsetY = this.anchorElement_.offsetTop;
// Move HelpBubble to correct side of the anchorElement
switch (this.position) {
case HelpBubbleArrowPosition.TOP_LEFT:
case HelpBubbleArrowPosition.TOP_CENTER:
case HelpBubbleArrowPosition.TOP_RIGHT:
offsetY += anchorRect.height + ANCHOR_OFFSET + this.padding.bottom;
break;
case HelpBubbleArrowPosition.BOTTOM_LEFT:
case HelpBubbleArrowPosition.BOTTOM_CENTER:
case HelpBubbleArrowPosition.BOTTOM_RIGHT:
offsetY -= (helpBubbleRect.height + ANCHOR_OFFSET + this.padding.top);
break;
case HelpBubbleArrowPosition.LEFT_TOP:
case HelpBubbleArrowPosition.LEFT_CENTER:
case HelpBubbleArrowPosition.LEFT_BOTTOM:
offsetX += anchorRect.width + ANCHOR_OFFSET + this.padding.right;
break;
case HelpBubbleArrowPosition.RIGHT_TOP:
case HelpBubbleArrowPosition.RIGHT_CENTER:
case HelpBubbleArrowPosition.RIGHT_BOTTOM:
offsetX -= (helpBubbleRect.width + ANCHOR_OFFSET + this.padding.left);
break;
default:
assertNotReached();
}
// Move HelpBubble along the anchorElement edge according to arrow position
switch (this.position) {
case HelpBubbleArrowPosition.TOP_LEFT:
case HelpBubbleArrowPosition.BOTTOM_LEFT:
// If anchor element width is small, point arrow to center of anchor
// element
if ((anchorRect.left + ARROW_OFFSET_FROM_EDGE) > anchorRectCenter.x) {
offsetX += (anchorRect.width / 2) - ARROW_OFFSET_FROM_EDGE;
}
break;
case HelpBubbleArrowPosition.TOP_CENTER:
case HelpBubbleArrowPosition.BOTTOM_CENTER:
offsetX += (anchorRect.width / 2) - (helpBubbleRect.width / 2);
break;
case HelpBubbleArrowPosition.TOP_RIGHT:
case HelpBubbleArrowPosition.BOTTOM_RIGHT:
// If anchor element width is small, point arrow to center of anchor
// element
if ((anchorRect.right - ARROW_OFFSET_FROM_EDGE) < anchorRectCenter.x) {
offsetX += (anchorRect.width / 2) - helpBubbleRect.width +
ARROW_OFFSET_FROM_EDGE;
} else {
// Right-align bubble and anchor elements
offsetX += anchorRect.width - helpBubbleRect.width;
}
break;
case HelpBubbleArrowPosition.LEFT_TOP:
case HelpBubbleArrowPosition.RIGHT_TOP:
// If anchor element height is small, point arrow to center of anchor
// element
if ((anchorRect.top + ARROW_OFFSET_FROM_EDGE) > anchorRectCenter.y) {
offsetY += (anchorRect.height / 2) - ARROW_OFFSET_FROM_EDGE;
}
break;
case HelpBubbleArrowPosition.LEFT_CENTER:
case HelpBubbleArrowPosition.RIGHT_CENTER:
offsetY += (anchorRect.height / 2) - (helpBubbleRect.height / 2);
break;
case HelpBubbleArrowPosition.LEFT_BOTTOM:
case HelpBubbleArrowPosition.RIGHT_BOTTOM:
// If anchor element height is small, point arrow to center of anchor
// element
if ((anchorRect.bottom - ARROW_OFFSET_FROM_EDGE) < anchorRectCenter.y) {
offsetY += (anchorRect.height / 2) - helpBubbleRect.height +
ARROW_OFFSET_FROM_EDGE;
} else {
// Bottom-align bubble and anchor elements
offsetY += anchorRect.height - helpBubbleRect.height;
}
break;
default:
assertNotReached();
}
this.style.top = offsetY.toString() + 'px';
this.style.left = offsetX.toString() + 'px';
}
}
customElements.define(HelpBubbleElement.is, HelpBubbleElement);
declare global {
interface HTMLElementTagNameMap {
'help-bubble': HelpBubbleElement;
}
interface HTMLElementEventMap {
[HELP_BUBBLE_DISMISSED_EVENT]: HelpBubbleDismissedEvent;
[HELP_BUBBLE_TIMED_OUT_EVENT]: HelpBubbleTimedOutEvent;
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/help_bubble/help_bubble.ts | TypeScript | unknown | 17,384 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert, assertNotReached} from 'chrome://resources/js/assert_ts.js';
import {InsetsF, RectF} from 'chrome://resources/mojo/ui/gfx/geometry/mojom/geometry.mojom-webui.js';
import {HELP_BUBBLE_SCROLL_ANCHOR_OPTIONS, HelpBubbleElement} from './help_bubble.js';
import {HelpBubbleArrowPosition, HelpBubbleParams} from './help_bubble.mojom-webui.js';
type Root = HTMLElement|ShadowRoot&{shadowRoot?: ShadowRoot};
export type Trackable = string|string[]|HTMLElement|Element;
export const ANCHOR_HIGHLIGHT_CLASS = 'help-anchor-highlight';
interface Options {
padding: InsetsF;
fixed: boolean;
}
// Return whether the current language is right-to-left
function isRtlLang(element: HTMLElement) {
return window.getComputedStyle(element).direction === 'rtl';
}
// Reflect arrow position across y-axis
function reflectArrowPosition(position: HelpBubbleArrowPosition) {
switch (position) {
case HelpBubbleArrowPosition.TOP_LEFT:
return HelpBubbleArrowPosition.TOP_RIGHT;
case HelpBubbleArrowPosition.TOP_RIGHT:
return HelpBubbleArrowPosition.TOP_LEFT;
case HelpBubbleArrowPosition.BOTTOM_LEFT:
return HelpBubbleArrowPosition.BOTTOM_RIGHT;
case HelpBubbleArrowPosition.BOTTOM_RIGHT:
return HelpBubbleArrowPosition.BOTTOM_LEFT;
case HelpBubbleArrowPosition.LEFT_TOP:
return HelpBubbleArrowPosition.RIGHT_TOP;
case HelpBubbleArrowPosition.LEFT_CENTER:
return HelpBubbleArrowPosition.RIGHT_CENTER;
case HelpBubbleArrowPosition.LEFT_BOTTOM:
return HelpBubbleArrowPosition.RIGHT_BOTTOM;
case HelpBubbleArrowPosition.RIGHT_TOP:
return HelpBubbleArrowPosition.LEFT_TOP;
case HelpBubbleArrowPosition.RIGHT_CENTER:
return HelpBubbleArrowPosition.LEFT_CENTER;
case HelpBubbleArrowPosition.RIGHT_BOTTOM:
return HelpBubbleArrowPosition.LEFT_BOTTOM;
default:
return position;
}
}
/**
* HelpBubble controller class
* - There should exist only one HelpBubble instance for each nativeId
* - The mapping between nativeId and htmlId is held within this instance
* - The rest of the parameters are passed to createBubble
*/
export class HelpBubbleController {
private nativeId_: string;
private root_: ShadowRoot;
private anchor_: HTMLElement|null = null;
private bubble_: HelpBubbleElement|null = null;
private options_: Options = {padding: new InsetsF(), fixed: false};
/**
* Whether a help bubble (webui or external) is being shown for this
* controller
*/
private isBubbleShowing_: boolean = false;
/** Keep track of last known anchor visibility status. */
private isAnchorVisible_: boolean = false;
/** Keep track of last known anchor bounds. */
private lastAnchorBounds_: RectF = new RectF();
/*
* This flag is used to know whether to send position updates for
* external bubbles
*/
private isExternal_: boolean = false;
constructor(nativeId: string, root: ShadowRoot) {
assert(
nativeId,
'HelpBubble: nativeId was not defined when registering help bubble');
assert(
root,
'HelpBubble: shadowRoot was not defined when registering help bubble');
this.nativeId_ = nativeId;
this.root_ = root;
}
isBubbleShowing() {
return this.isBubbleShowing_;
}
canShowBubble() {
return this.hasAnchor();
}
hasBubble() {
return !!this.bubble_;
}
getBubble() {
return this.bubble_;
}
hasAnchor() {
return !!this.anchor_;
}
getAnchor() {
return this.anchor_;
}
getNativeId() {
return this.nativeId_;
}
getPadding() {
return this.options_.padding;
}
getAnchorVisibility() {
return this.isAnchorVisible_;
}
getLastAnchorBounds() {
return this.lastAnchorBounds_;
}
updateAnchorVisibility(isVisible: boolean, bounds: RectF): boolean {
const changed = isVisible !== this.isAnchorVisible_ ||
bounds.x !== this.lastAnchorBounds_.x ||
bounds.y !== this.lastAnchorBounds_.y ||
bounds.width !== this.lastAnchorBounds_.width ||
bounds.height !== this.lastAnchorBounds_.height;
this.isAnchorVisible_ = isVisible;
this.lastAnchorBounds_ = bounds;
return changed;
}
isAnchorFixed(): boolean {
return this.options_.fixed;
}
isExternal() {
return this.isExternal_;
}
updateExternalShowingStatus(isShowing: boolean) {
this.isExternal_ = true;
this.isBubbleShowing_ = isShowing;
this.setAnchorHighlight_(isShowing);
}
track(trackable: Trackable, options: Options): boolean {
assert(!this.anchor_);
let anchor: HTMLElement|null = null;
if (typeof trackable === 'string') {
anchor = this.root_.querySelector<HTMLElement>(trackable);
} else if (Array.isArray(trackable)) {
anchor = this.deepQuery(trackable);
} else if (trackable instanceof HTMLElement) {
anchor = trackable;
} else {
assertNotReached(
'HelpBubble: anchor argument was unrecognized when registering ' +
'help bubble');
}
if (!anchor) {
return false;
}
anchor.dataset['nativeId'] = this.nativeId_;
this.anchor_ = anchor;
this.options_ = options;
return true;
}
deepQuery(selectors: string[]): HTMLElement|null {
let cur: Root = this.root_;
for (const selector of selectors) {
if (cur.shadowRoot) {
cur = cur.shadowRoot;
}
const el: HTMLElement|null = cur.querySelector(selector);
if (!el) {
return null;
} else {
cur = el;
}
}
return cur as HTMLElement;
}
show() {
this.isExternal_ = false;
if (!(this.bubble_ && this.anchor_)) {
return;
}
this.bubble_.show(this.anchor_);
this.isBubbleShowing_ = true;
this.setAnchorHighlight_(true);
}
hide() {
if (!this.bubble_) {
return;
}
this.bubble_.hide();
this.bubble_.remove();
this.bubble_ = null;
this.isBubbleShowing_ = false;
this.setAnchorHighlight_(false);
}
createBubble(params: HelpBubbleParams): HelpBubbleElement {
assert(
this.anchor_,
'HelpBubble: anchor was not defined when showing help bubble');
assert(this.anchor_.parentNode, 'HelpBubble: anchor element not in DOM');
this.bubble_ = document.createElement('help-bubble');
this.bubble_.nativeId = this.nativeId_;
this.bubble_.position = isRtlLang(this.anchor_) ?
reflectArrowPosition(params.position) :
params.position;
this.bubble_.closeButtonAltText = params.closeButtonAltText;
this.bubble_.bodyText = params.bodyText;
this.bubble_.bodyIconName = params.bodyIconName || null;
this.bubble_.bodyIconAltText = params.bodyIconAltText;
this.bubble_.titleText = params.titleText || '';
this.bubble_.progress = params.progress || null;
this.bubble_.buttons = params.buttons;
this.bubble_.padding = this.options_.padding;
if (params.timeout) {
this.bubble_.timeoutMs = Number(params.timeout!.microseconds / 1000n);
assert(this.bubble_.timeoutMs > 0);
}
assert(
!this.bubble_.progress ||
this.bubble_.progress.total >= this.bubble_.progress.current);
assert(this.root_);
// Because the help bubble uses either absolute or fixed positioning, it
// need only be placed within the offset parent of the anchor. However it is
// placed as a sibling to the anchor because that guarantees proper tab
// order.
if (getComputedStyle(this.anchor_).getPropertyValue('position') ===
'fixed') {
this.bubble_.fixed = true;
}
this.anchor_.parentNode.insertBefore(this.bubble_, this.anchor_);
return this.bubble_;
}
/**
* Styles the anchor element to appear highlighted while the bubble is open,
* or removes the highlight.
*/
private setAnchorHighlight_(highlight: boolean) {
assert(
this.anchor_, 'Set anchor highlight: expected valid anchor element.');
this.anchor_.classList.toggle(ANCHOR_HIGHLIGHT_CLASS, highlight);
if (highlight) {
(this.bubble_ || this.anchor_).focus();
this.anchor_.scrollIntoView(HELP_BUBBLE_SCROLL_ANCHOR_OPTIONS);
}
}
/**
* Gets the immediate ancestor element of `element` in the DOM, or null if
* none. This steps out of shadow DOMs as it finds them.
*/
private static getImmediateAncestor(element: Element): Element|null {
if (element.parentElement) {
return element.parentElement;
}
if (element.parentNode instanceof ShadowRoot) {
return (element.parentNode as ShadowRoot).host;
}
return null;
}
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/help_bubble/help_bubble_controller.ts | TypeScript | unknown | 8,740 |
<iron-iconset-svg name="iph" size="24">
<svg>
<defs>
<!--
These icons are copied from Material UI and optimized through SVGOMG
See http://goo.gl/Y1OdAq for instructions on adding additional icons.
-->
<g id="celebration">
<path fill="none" d="M0 0h20v20H0z"></path>
<path fill-rule="evenodd"
d="m2 22 14-5-9-9-5 14Zm10.35-5.82L5.3 18.7l2.52-7.05 4.53 4.53ZM14.53 12.53l5.59-5.59a1.25 1.25 0 0 1 1.77 0l.59.59 1.06-1.06-.59-.59a2.758 2.758 0 0 0-3.89 0l-5.59 5.59 1.06 1.06ZM10.06 6.88l-.59.59 1.06 1.06.59-.59a2.758 2.758 0 0 0 0-3.89l-.59-.59-1.06 1.07.59.59c.48.48.48 1.28 0 1.76ZM17.06 11.88l-1.59 1.59 1.06 1.06 1.59-1.59a1.25 1.25 0 0 1 1.77 0l1.61 1.61 1.06-1.06-1.61-1.61a2.758 2.758 0 0 0-3.89 0ZM15.06 5.88l-3.59 3.59 1.06 1.06 3.59-3.59a2.758 2.758 0 0 0 0-3.89l-1.59-1.59-1.06 1.06 1.59 1.59c.48.49.48 1.29 0 1.77Z">
</path>
</g>
<g id="lightbulb_outline">
<path fill="none" d="M0 0h24v24H0z"></path>
<path
d="M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9v1zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7zm2 11.7V16h-4v-2.3C8.48 12.63 7 11.53 7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 2.49-1.51 3.65-3 4.7z">
</path>
</g>
</defs>
</svg>
</iron-iconset-svg>
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/help_bubble/help_bubble_icons.html | HTML | unknown | 1,372 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Logic common to components that support a help bubble.
*
* A component implementing this mixin should call
* registerHelpBubble() to associate specific element identifiers
* referenced in an IPH or Tutorials journey with the ids of the HTML elements
* that journey cares about (typically, points for help bubbles to anchor to).
*
* Multiple components in the same WebUI may have this mixin. Each mixin will
* receive ALL help bubble-related messages from its associated WebUIController
* and determines if any given message is relevant. This is done by checking
* against registered identifier.
*
* See README.md for more information.
*/
import {assert} from 'chrome://resources/js/assert_ts.js';
import {EventTracker} from 'chrome://resources/js/event_tracker.js';
import {InsetsF, RectF} from 'chrome://resources/mojo/ui/gfx/geometry/mojom/geometry.mojom-webui.js';
import {dedupingMixin, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {debounceEnd, HELP_BUBBLE_DISMISSED_EVENT, HELP_BUBBLE_TIMED_OUT_EVENT, HelpBubbleDismissedEvent, HelpBubbleElement} from './help_bubble.js';
import {HelpBubbleClientCallbackRouter, HelpBubbleClosedReason, HelpBubbleHandlerInterface, HelpBubbleParams} from './help_bubble.mojom-webui.js';
import {HelpBubbleController, Trackable} from './help_bubble_controller.js';
import {HelpBubbleProxyImpl} from './help_bubble_proxy.js';
type Constructor<T> = new (...args: any[]) => T;
export const HelpBubbleMixin = dedupingMixin(
<T extends Constructor<PolymerElement>>(superClass: T): T&
Constructor<HelpBubbleMixinInterface> => {
class HelpBubbleMixin extends superClass implements
HelpBubbleMixinInterface {
private helpBubbleHandler_: HelpBubbleHandlerInterface;
private helpBubbleCallbackRouter_: HelpBubbleClientCallbackRouter;
/**
* A map from the name of the native identifier used in the tutorial or
* IPH definition to the target element's HTML ID.
*
* Example entry:
* "kHeightenSecuritySettingsElementId" => "toggleSecureMode"
*/
private helpBubbleControllerById_: Map<string, HelpBubbleController> =
new Map();
private helpBubbleListenerIds_: number[] = [];
private helpBubbleFixedAnchorObserver_: IntersectionObserver|null =
null;
private helpBubbleResizeObserver_: ResizeObserver|null = null;
private helpBubbleDismissedEventTracker_: EventTracker =
new EventTracker();
private debouncedAnchorMayHaveChangedCallback_:
(() => void)|null = null;
constructor(...args: any[]) {
super(...args);
this.helpBubbleHandler_ =
HelpBubbleProxyImpl.getInstance().getHandler();
this.helpBubbleCallbackRouter_ =
HelpBubbleProxyImpl.getInstance().getCallbackRouter();
}
override connectedCallback() {
super.connectedCallback();
const router = this.helpBubbleCallbackRouter_;
this.helpBubbleListenerIds_.push(
router.showHelpBubble.addListener(
this.onShowHelpBubble_.bind(this)),
router.toggleFocusForAccessibility.addListener(
this.onToggleHelpBubbleFocusForAccessibility_.bind(this)),
router.hideHelpBubble.addListener(
this.onHideHelpBubble_.bind(this)),
router.externalHelpBubbleUpdated.addListener(
this.onExternalHelpBubbleUpdated_.bind(this)));
const isVisible = (element: Element) => {
const rect = element.getBoundingClientRect();
return rect.height > 0 && rect.width > 0;
};
this.debouncedAnchorMayHaveChangedCallback_ =
debounceEnd(this.onAnchorBoundsMayHaveChanged_.bind(this), 50);
this.helpBubbleResizeObserver_ =
new ResizeObserver(entries => entries.forEach(({target}) => {
if (target === document.body) {
if (this.debouncedAnchorMayHaveChangedCallback_) {
this.debouncedAnchorMayHaveChangedCallback_();
}
} else {
this.onAnchorVisibilityChanged_(
target as HTMLElement, isVisible(target));
}
}));
this.helpBubbleFixedAnchorObserver_ = new IntersectionObserver(
entries => entries.forEach(
({target, isIntersecting}) => this.onAnchorVisibilityChanged_(
target as HTMLElement, isIntersecting)),
{root: null});
document.addEventListener(
'scroll', this.debouncedAnchorMayHaveChangedCallback_,
{passive: true});
this.helpBubbleResizeObserver_.observe(document.body);
// When the component is connected, if the target elements were
// already registered, they should be observed now. Any targets
// registered from this point forward will observed on registration.
this.controllers.forEach(ctrl => this.observeControllerAnchor_(ctrl));
}
private get controllers(): HelpBubbleController[] {
return Array.from(this.helpBubbleControllerById_.values());
}
override disconnectedCallback() {
super.disconnectedCallback();
for (const listenerId of this.helpBubbleListenerIds_) {
this.helpBubbleCallbackRouter_.removeListener(listenerId);
}
this.helpBubbleListenerIds_ = [];
assert(this.helpBubbleResizeObserver_);
this.helpBubbleResizeObserver_.disconnect();
this.helpBubbleResizeObserver_ = null;
assert(this.helpBubbleFixedAnchorObserver_);
this.helpBubbleFixedAnchorObserver_.disconnect();
this.helpBubbleFixedAnchorObserver_ = null;
this.helpBubbleControllerById_.clear();
if (this.debouncedAnchorMayHaveChangedCallback_) {
document.removeEventListener(
'scroll', this.debouncedAnchorMayHaveChangedCallback_);
this.debouncedAnchorMayHaveChangedCallback_ = null;
}
}
/**
* Maps `nativeId`, which should be the name of a ui::ElementIdentifier
* referenced by the WebUIController, with either:
* - a selector
* - an array of selectors (will traverse shadow DOM elements)
* - an arbitrary HTMLElement
*
* The referenced element should have block display and non-zero size
* when visible (inline elements may be supported in the future).
*
* Example:
* registerHelpBubble(
* 'kMyComponentTitleLabelElementIdentifier',
* '#title');
*
* Example:
* registerHelpBubble(
* 'kMyComponentTitleLabelElementIdentifier',
* ['#child-component', '#child-component-button']);
*
* Example:
* registerHelpBubble(
* 'kMyComponentTitleLabelElementIdentifier',
* this.$.list.childNodes[0]);
*
* See README.md for full instructions.
*
* This method can be called multiple times to re-register the
* nativeId to a new element/selector. If the help bubble is already
* showing, the registration will fail and return null. If successful,
* this method returns the new controller.
*
* Optionally, an options object may be supplied to change the
* default behavior of the help bubble.
*
* - Fixed positioning detection:
* e.g. `{fixed: true}`
* By default, this mixin detects anchor elements when
* rendered within the document. This breaks with
* fix-positioned elements since they are not in the regular
* flow of the document but they are always visible. Passing
* {"fixed": true} will detect the anchor element when it is
* visible.
*
* - Add padding around anchor element:
* e.g. `{anchorPaddingTop: 5}`
* To add to the default margin around the anchor element in all
* 4 directions, e.g. {"anchorPaddingTop": 5} adds 5 pixels to
* the margin at the top off the anchor element. The margin is
* used when calculating how far the help bubble should be spaced
* from the anchor element. Larger values equate to a larger visual
* gap. These values must be positive integers in the range [0, 20].
* This option should be used sparingly where the help bubble would
* otherwise conceal important UI.
*/
registerHelpBubble(
nativeId: string, trackable: Trackable,
options: Options = {}): HelpBubbleController|null {
if (this.helpBubbleControllerById_.has(nativeId)) {
const ctrl = this.helpBubbleControllerById_.get(nativeId);
if (ctrl && ctrl.isBubbleShowing()) {
return null;
}
this.unregisterHelpBubble(nativeId);
}
const controller =
new HelpBubbleController(nativeId, this.shadowRoot!);
controller.track(trackable, parseOptions(options));
this.helpBubbleControllerById_.set(nativeId, controller);
// This can be called before or after `connectedCallback()`, so if the
// component isn't connected and the observer set up yet, delay
// observation until it is.
if (this.helpBubbleResizeObserver_) {
this.observeControllerAnchor_(controller);
}
return controller;
}
/**
* Unregisters a help bubble nativeId.
*
* This method will remove listeners, hide the help bubble if
* showing, and forget the nativeId.
*/
unregisterHelpBubble(nativeId: string): void {
const ctrl = this.helpBubbleControllerById_.get(nativeId);
if (ctrl && ctrl.hasAnchor()) {
this.onAnchorVisibilityChanged_(ctrl.getAnchor()!, false);
this.unobserveControllerAnchor_(ctrl);
}
this.helpBubbleControllerById_.delete(nativeId);
}
private observeControllerAnchor_(controller: HelpBubbleController) {
const anchor = controller.getAnchor();
assert(anchor, 'Help bubble does not have anchor');
if (controller.isAnchorFixed()) {
assert(this.helpBubbleFixedAnchorObserver_);
this.helpBubbleFixedAnchorObserver_.observe(anchor);
} else {
assert(this.helpBubbleResizeObserver_);
this.helpBubbleResizeObserver_.observe(anchor);
}
}
private unobserveControllerAnchor_(controller: HelpBubbleController) {
const anchor = controller.getAnchor();
assert(anchor, 'Help bubble does not have anchor');
if (controller.isAnchorFixed()) {
assert(this.helpBubbleFixedAnchorObserver_);
this.helpBubbleFixedAnchorObserver_.unobserve(anchor);
} else {
assert(this.helpBubbleResizeObserver_);
this.helpBubbleResizeObserver_.unobserve(anchor);
}
}
/**
* Returns whether any help bubble is currently showing in this
* component.
*/
isHelpBubbleShowing(): boolean {
return this.controllers.some(ctrl => ctrl.isBubbleShowing());
}
/**
* Returns whether any help bubble is currently showing on a tag
* with this id.
*/
isHelpBubbleShowingForTesting(id: string): boolean {
const ctrls =
this.controllers.filter(this.filterMatchingIdForTesting_(id));
return !!ctrls[0];
}
/**
* Returns the help bubble currently showing on a tag with this
* id.
*/
getHelpBubbleForTesting(id: string): HelpBubbleElement|null {
const ctrls =
this.controllers.filter(this.filterMatchingIdForTesting_(id));
return ctrls[0] ? ctrls[0].getBubble() : null;
}
private filterMatchingIdForTesting_(anchorId: string):
(ctrl: HelpBubbleController) => boolean {
return ctrl => ctrl.isBubbleShowing() && ctrl.getAnchor() !== null &&
ctrl.getAnchor()!.id === anchorId;
}
/**
* Testing method to validate that anchors will be properly
* located at runtime
*
* Call this method in your browser_tests after your help
* bubbles have been registered. Results are sorted to be
* deterministic.
*/
getSortedAnchorStatusesForTesting(): Array<[string, boolean]> {
return this.controllers
.sort((a, b) => a.getNativeId().localeCompare(b.getNativeId()))
.map(ctrl => ([ctrl.getNativeId(), ctrl.hasAnchor()]));
}
/**
* Returns whether a help bubble can be shown
* This requires:
* - the mixin is tracking this controller
* - the controller is in a state to be shown, e.g.
* `.canShowBubble()`
* - no other showing bubbles are anchored to the same element
*/
canShowHelpBubble(controller: HelpBubbleController): boolean {
if (!this.helpBubbleControllerById_.has(controller.getNativeId())) {
return false;
}
if (!controller.canShowBubble()) {
return false;
}
const anchor = controller.getAnchor();
// Make sure no other help bubble is showing for this anchor.
const anchorIsUsed = this.controllers.some(
otherCtrl => otherCtrl.isBubbleShowing() &&
otherCtrl.getAnchor() === anchor);
return !anchorIsUsed;
}
/**
* Displays a help bubble with `params` anchored to the HTML element
* with id `anchorId`. Note that `params.nativeIdentifier` is ignored by
* this method, since the anchor is already specified.
*/
showHelpBubble(
controller: HelpBubbleController, params: HelpBubbleParams): void {
assert(this.canShowHelpBubble(controller), 'Can\'t show help bubble');
const bubble = controller.createBubble(params);
this.helpBubbleDismissedEventTracker_.add(
bubble, HELP_BUBBLE_DISMISSED_EVENT,
this.onHelpBubbleDismissed_.bind(this));
this.helpBubbleDismissedEventTracker_.add(
bubble, HELP_BUBBLE_TIMED_OUT_EVENT,
this.onHelpBubbleTimedOut_.bind(this));
controller.show();
}
/**
* Hides a help bubble anchored to element with id `anchorId` if there
* is one. Returns true if a bubble was hidden.
*/
hideHelpBubble(nativeId: string): boolean {
const ctrl = this.helpBubbleControllerById_.get(nativeId);
if (!ctrl || !ctrl.hasBubble()) {
// `!ctrl` means this identifier is not handled by this mixin
return false;
}
this.helpBubbleDismissedEventTracker_.remove(
ctrl.getBubble()!, HELP_BUBBLE_DISMISSED_EVENT);
this.helpBubbleDismissedEventTracker_.remove(
ctrl.getBubble()!, HELP_BUBBLE_TIMED_OUT_EVENT);
ctrl.hide();
return true;
}
/**
* Sends an "activated" event to the ElementTracker system for the
* element with id `anchorId`, which must have been registered as a help
* bubble anchor. This event will be processed in the browser and may
* e.g. cause a Tutorial or interactive test to advance to the next
* step.
*
* TODO(crbug.com/1376262): Figure out how to automatically send the
* activated event when an anchor element is clicked.
*/
notifyHelpBubbleAnchorActivated(nativeId: string): boolean {
const ctrl = this.helpBubbleControllerById_.get(nativeId);
if (!ctrl || !ctrl.isBubbleShowing()) {
return false;
}
this.helpBubbleHandler_.helpBubbleAnchorActivated(nativeId);
return true;
}
/**
* Sends a custom event to the ElementTracker system for the element
* with id `anchorId`, which must have been registered as a help bubble
* anchor. This event will be processed in the browser and may e.g.
* cause a Tutorial or interactive test to advance to the next step.
*
* The `customEvent` string should correspond to the name of a
* ui::CustomElementEventType declared in the browser code.
*/
notifyHelpBubbleAnchorCustomEvent(
nativeId: string, customEvent: string): boolean {
const ctrl = this.helpBubbleControllerById_.get(nativeId);
if (!ctrl || !ctrl.isBubbleShowing()) {
return false;
}
this.helpBubbleHandler_.helpBubbleAnchorCustomEvent(
nativeId, customEvent);
return true;
}
/**
* This event is emitted by the mojo router
*/
private onAnchorVisibilityChanged_(
target: HTMLElement, isVisible: boolean) {
const nativeId = target.dataset['nativeId'];
assert(nativeId);
const ctrl = this.helpBubbleControllerById_.get(nativeId);
const hidden = this.hideHelpBubble(nativeId);
if (hidden) {
this.helpBubbleHandler_.helpBubbleClosed(
nativeId, HelpBubbleClosedReason.kPageChanged);
}
const bounds =
isVisible ? this.getElementBounds_(target) : new RectF();
if (!ctrl || ctrl.updateAnchorVisibility(isVisible, bounds)) {
this.helpBubbleHandler_.helpBubbleAnchorVisibilityChanged(
nativeId, isVisible, bounds);
}
}
/**
* When the document scrolls or resizes, we need to update cached
* positions of bubble anchors.
*/
private onAnchorBoundsMayHaveChanged_() {
for (const ctrl of this.controllers) {
if (ctrl.hasAnchor() && ctrl.getAnchorVisibility()) {
const bounds = this.getElementBounds_(ctrl.getAnchor()!);
if (ctrl.updateAnchorVisibility(true, bounds)) {
this.helpBubbleHandler_.helpBubbleAnchorVisibilityChanged(
ctrl.getNativeId(), true, bounds);
}
}
}
}
/**
* Returns bounds of the anchor element
*/
private getElementBounds_(element: HTMLElement) {
const rect = new RectF();
const bounds = element.getBoundingClientRect();
rect.x = bounds.x;
rect.y = bounds.y;
rect.width = bounds.width;
rect.height = bounds.height;
const nativeId = element.dataset['nativeId'];
if (!nativeId) {
return rect;
}
const ctrl = this.helpBubbleControllerById_.get(nativeId);
if (ctrl) {
const padding = ctrl.getPadding();
rect.x -= padding.left;
rect.y -= padding.top;
rect.width += padding.left + padding.right;
rect.height += padding.top + padding.bottom;
}
return rect;
}
/**
* This event is emitted by the mojo router
*/
private onShowHelpBubble_(params: HelpBubbleParams): void {
if (!this.helpBubbleControllerById_.has(params.nativeIdentifier)) {
// Identifier not handled by this mixin.
return;
}
const ctrl =
this.helpBubbleControllerById_.get(params.nativeIdentifier)!;
this.showHelpBubble(ctrl, params);
}
/**
* This event is emitted by the mojo router
*/
private onToggleHelpBubbleFocusForAccessibility_(nativeId: string) {
if (!this.helpBubbleControllerById_.has(nativeId)) {
// Identifier not handled by this mixin.
return;
}
const ctrl = this.helpBubbleControllerById_.get(nativeId)!;
if (ctrl) {
const anchor = ctrl.getAnchor();
if (anchor) {
anchor.focus();
}
}
}
/**
* This event is emitted by the mojo router
*/
private onHideHelpBubble_(nativeId: string): void {
// This may be called with nativeId not handled by this mixin
// Ignore return value to silently fail
this.hideHelpBubble(nativeId);
}
/**
* This event is emitted by the mojo router.
*/
private onExternalHelpBubbleUpdated_(nativeId: string, shown: boolean) {
if (!this.helpBubbleControllerById_.has(nativeId)) {
// Identifier not handled by this mixin.
return;
}
// Get the associated bubble and update status
const ctrl = this.helpBubbleControllerById_.get(nativeId)!;
ctrl.updateExternalShowingStatus(shown);
}
/**
* This event is emitted by the help-bubble component
*/
private onHelpBubbleDismissed_(e: HelpBubbleDismissedEvent) {
const nativeId = e.detail.nativeId;
assert(nativeId);
const hidden = this.hideHelpBubble(nativeId);
assert(hidden);
if (nativeId) {
if (e.detail.fromActionButton) {
this.helpBubbleHandler_.helpBubbleButtonPressed(
nativeId, e.detail.buttonIndex!);
} else {
this.helpBubbleHandler_.helpBubbleClosed(
nativeId, HelpBubbleClosedReason.kDismissedByUser);
}
}
}
/**
* This event is emitted by the help-bubble component
*/
private onHelpBubbleTimedOut_(e: HelpBubbleDismissedEvent) {
const nativeId = e.detail.nativeId;
const ctrl = this.helpBubbleControllerById_.get(nativeId);
assert(ctrl);
const hidden = this.hideHelpBubble(nativeId);
assert(hidden);
if (nativeId) {
this.helpBubbleHandler_.helpBubbleClosed(
nativeId, HelpBubbleClosedReason.kTimedOut);
}
}
}
return HelpBubbleMixin;
});
export interface HelpBubbleMixinInterface {
registerHelpBubble(nativeId: string, trackable: Trackable, options?: Options):
HelpBubbleController|null;
unregisterHelpBubble(nativeId: string): void;
isHelpBubbleShowing(): boolean;
isHelpBubbleShowingForTesting(id: string): boolean;
getHelpBubbleForTesting(id: string): HelpBubbleElement|null;
getSortedAnchorStatusesForTesting(): Array<[string, boolean]>;
canShowHelpBubble(controller: HelpBubbleController): boolean;
showHelpBubble(controller: HelpBubbleController, params: HelpBubbleParams):
void;
hideHelpBubble(nativeId: string): boolean;
notifyHelpBubbleAnchorActivated(anchorId: string): boolean;
notifyHelpBubbleAnchorCustomEvent(anchorId: string, customEvent: string):
boolean;
}
export interface Options {
anchorPaddingTop?: number;
anchorPaddingLeft?: number;
anchorPaddingBottom?: number;
anchorPaddingRight?: number;
fixed?: boolean;
}
export function parseOptions(options: Options) {
const padding = new InsetsF();
padding.top = clampPadding(options.anchorPaddingTop);
padding.left = clampPadding(options.anchorPaddingLeft);
padding.bottom = clampPadding(options.anchorPaddingBottom);
padding.right = clampPadding(options.anchorPaddingRight);
return {
padding,
fixed: !!options.fixed,
};
}
function clampPadding(n: number = 0) {
return Math.max(0, Math.min(20, n));
}
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/help_bubble/help_bubble_mixin.ts | TypeScript | unknown | 24,314 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {HelpBubbleClientCallbackRouter, HelpBubbleHandlerFactory, HelpBubbleHandlerInterface, HelpBubbleHandlerRemote} from './help_bubble.mojom-webui.js';
export interface HelpBubbleProxy {
getHandler(): HelpBubbleHandlerInterface;
getCallbackRouter(): HelpBubbleClientCallbackRouter;
}
export class HelpBubbleProxyImpl implements HelpBubbleProxy {
private callbackRouter_ = new HelpBubbleClientCallbackRouter();
private handler_ = new HelpBubbleHandlerRemote();
constructor() {
const factory = HelpBubbleHandlerFactory.getRemote();
factory.createHelpBubbleHandler(
this.callbackRouter_.$.bindNewPipeAndPassRemote(),
this.handler_.$.bindNewPipeAndPassReceiver());
}
static getInstance(): HelpBubbleProxy {
return instance || (instance = new HelpBubbleProxyImpl());
}
static setInstance(obj: HelpBubbleProxy) {
instance = obj;
}
getHandler(): HelpBubbleHandlerRemote {
return this.handler_;
}
getCallbackRouter(): HelpBubbleClientCallbackRouter {
return this.callbackRouter_;
}
}
let instance: HelpBubbleProxy|null = null; | Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/help_bubble/help_bubble_proxy.ts | TypeScript | unknown | 1,242 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {PageCallbackRouter, PageHandler, PageHandlerRemote} from './history_clusters.mojom-webui.js';
/**
* @fileoverview This file provides a singleton class that exposes the Mojo
* handler interface used for bidirectional communication between the page and
* the browser.
*/
export interface BrowserProxy {
handler: PageHandlerRemote;
callbackRouter: PageCallbackRouter;
}
export class BrowserProxyImpl implements BrowserProxy {
handler: PageHandlerRemote;
callbackRouter: PageCallbackRouter;
constructor(handler: PageHandlerRemote, callbackRouter: PageCallbackRouter) {
this.handler = handler;
this.callbackRouter = callbackRouter;
}
static getInstance(): BrowserProxy {
if (instance) {
return instance;
}
const handler = PageHandler.getRemote();
const callbackRouter = new PageCallbackRouter();
handler.setPage(callbackRouter.$.bindNewPipeAndPassRemote());
return instance = new BrowserProxyImpl(handler, callbackRouter);
}
static setInstance(obj: BrowserProxy) {
instance = obj;
}
}
let instance: BrowserProxy|null = null;
| Zhao-PengFei35/chromium_src_4 | ui/webui/resources/cr_components/history_clusters/browser_proxy.ts | TypeScript | unknown | 1,246 |