electron/shell/browser/ui/gtk/app_indicator_icon.cc
electron-roller[bot] 28ada6ea8b
chore: bump chromium to 100.0.4857.0 (main) (#32419)
* chore: bump chromium in DEPS to 99.0.4819.0

* chore: update patches

* chore: bump chromium in DEPS to 99.0.4824.0

* chore: update patches

* chore: bump chromium in DEPS to 99.0.4827.0

* chore: update patches

* 3352511: PiP: Add inkdrop and pointer cursor to PiP window buttons

https://chromium-review.googlesource.com/c/chromium/src/+/3352511

* 3309164: webhid: Show FIDO devices in the chooser if allowed

https://chromium-review.googlesource.com/c/chromium/src/+/3309164

* 3297868: hid: Add experimental HIDDevice.forget()

https://chromium-review.googlesource.com/c/chromium/src/+/3297868

* 3362491: [Extensions] Move i18n API to //extensions

https://chromium-review.googlesource.com/c/chromium/src/+/3362491

* MCC Refactor step0: Allow embedders to register associated_interface binders with RenderFrameHostImpl::associated_registry_.

https://chromium-review.googlesource.com/c/chromium/src/+/3281481

* 3352616: [Gtk] Remove libgtk from the link-line

https://chromium-review.googlesource.com/c/chromium/src/+/3352616

* 3249211: Clear-Site-Data support for partitioned cookies

https://chromium-review.googlesource.com/c/chromium/src/+/3249211

* [Extensions][COIL] Use [allow|block]list in //extensions/common

https://chromium-review.googlesource.com/c/chromium/src/+/3372668

* Begin ScopedUserPrefUpdate migration to modern base::Value

https://chromium-review.googlesource.com/c/chromium/src/+/3376154

* [Code Health] Refactor PrefService GetDict + GetList to use base::Value

https://chromium-review.googlesource.com/c/chromium/src/+/3343526

* 3354997: [CodeHealth] Remove deprecated SetDictionary method

https://chromium-review.googlesource.com/c/chromium/src/+/3354997

* 3287323: Add LacrosPrefStore for lacros settings

https://chromium-review.googlesource.com/c/chromium/src/+/3287323

* 3365916: [PA] Clean up remaining lazy commit code

https://chromium-review.googlesource.com/c/chromium/src/+/3365916

* [MPArch] Target the external protocol error at the responsible frame.

https://chromium-review.googlesource.com/c/chromium/src/+/3011560

* Pass origin to RegisterNonNetworkSubresourceURLLoaderFactories

https://chromium-review.googlesource.com/c/chromium/src/+/3350608

* Linux: Send OSCrypt raw encryption key to the Network Service

https://chromium-review.googlesource.com/c/chromium/src/+/3320484

* [PlzServiceWorker] Remove remaining references to PlzServiceWorker.

https://chromium-review.googlesource.com/c/chromium/src/+/3359441

* chore: fixup for lint

* 3327621: Fix tablet mode detection for Win 11.

https://chromium-review.googlesource.com/c/chromium/src/+/3327621

* 3342428: ax_mac: move AXTextMarker conversion utils under ui umbrella

https://chromium-review.googlesource.com/c/chromium/src/+/3342428

* 3353974: Mac: Use base::Feature for overlay features

https://chromium-review.googlesource.com/c/chromium/src/+/3353974

* chore: bump chromium in DEPS to 99.0.4828.0

* chore: update patches

* chore: bump chromium in DEPS to 99.0.4837.0

* chore: update patches

* chore: update patches

* 3379142: Drop FALLTHROUGH macro
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3379142

* 3381749: C++17: Allow use of std::map::try_emplace and std::map::insert_or_assign
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/3381749

* chore: bump chromium in DEPS to 99.0.4839.0

* chore: update patches

* chore: bump chromium in DEPS to 99.0.4840.0

* chore: bump chromium in DEPS to 99.0.4844.0

* 3395881: [api] Deprecate Local<v8::Context> v8::Object::CreationContext()

Ref: https://chromium-review.googlesource.com/c/v8/v8/+/3395881

* chore: update patches

* chore: bump chromium in DEPS to 100.0.4845.0

* chore: update patches

* chore: bump chromium in DEPS to 100.0.4847.0

* chore: update patches

* chore: bump chromium in DEPS to 100.0.4849.0

* chore: update patches

* chore: bump chromium in DEPS to 100.0.4851.0

* chore: bump chromium in DEPS to 100.0.4853.0

* update patches

* chore: update patches

* update patches

* 3383599: Fonts Access: Remove prototype that uses a font picker.

https://chromium-review.googlesource.com/c/chromium/src/+/3383599

* 3404768: Remove ALLOW_UNUSED macros

https://chromium-review.googlesource.com/c/chromium/src/+/3404768

* 3374762: Remove ignore_result.h

https://chromium-review.googlesource.com/c/chromium/src/+/3374762

* 3399305: [unseasoned-pdf] Apply proper frame offsets for touch selections

https://chromium-review.googlesource.com/c/chromium/src/+/3399305

* 3402210: [Extensions] Don't trigger unload event for already unloaded extension

https://chromium-review.googlesource.com/c/chromium/src/+/3402210

* 3410912: Combine URLLoaderClient OnReceiveResponse and OnStartLoadingResponseBody.

https://chromium-review.googlesource.com/c/chromium/src/+/3410912

* 3370428: Make the AuthSchemes policy support dynamic refresh

https://chromium-review.googlesource.com/c/chromium/src/+/3370428

* 3407603: Finish ScopedUserPrefUpdate migration to modern base::Value

https://chromium-review.googlesource.com/c/chromium/src/+/3407603

* 3378352: ozone/x11: move code from //ui/p/x11 to //ui/ozone/p/x11

https://chromium-review.googlesource.com/c/chromium/src/+/3378352

* 3370810: Delete chrome/service, AKA the Cloud Print service process.

https://chromium-review.googlesource.com/c/chromium/src/+/3370810

* chore: bump chromium in DEPS to 100.0.4855.0

* chore: update patches

* fixup! 3370810: Delete chrome/service, AKA the Cloud Print service process.

* revert 3348007 to fix windows build

* 3318572: [Code health] Fix gn check errors in //extensions/browser:*

https://chromium-review.googlesource.com/c/chromium/src/+/3318572

* fix printing.patch

* fix iwyu issue

* 3408515: win: Make ShorcutOperation an enum class and modernize names

https://chromium-review.googlesource.com/c/chromium/src/+/3408515

* 3388333: [UIA] Remove dead code accessibility_misc_utils.h/cc

https://chromium-review.googlesource.com/c/chromium/src/+/3388333

* fix windows build? i hope

* patch gn visibility of //ui/ozone/platform/x11

* missing include base/logging.h

* use BUILDFLAG for USE_NSS_CERTS

https://chromium-review.googlesource.com/c/chromium/src/+/3379123

* defined(OS_*) ==> BUILDFLAG(IS_*)

https://bugs.chromium.org/p/chromium/issues/detail?id=1234043

* fixup! 3404768: Remove ALLOW_UNUSED macros

* another attempt to fix windows build

* temporarily disable the custom scheme service worker test

https://github.com/electron/electron/issues/32664

* fix loading mv3 extensions

not sure what cl broke this unfort.

* fixup! 3404768: Remove ALLOW_UNUSED macros

* patch nan

https://chromium-review.googlesource.com/c/v8/v8/+/3395880

* fix node test

* fix nullptr in FindPdfFrame

* patch perfetto to fix build issue on win-ia32

bc44c3c753

* fix build for linux-x64-testing-no-run-as-node

* fix patch

* skip <webview>.capturePage() test

https://github.com/electron/electron/issues/32705

* test: fix failing tests of focus/blur events of WebContents (#32711)

* inherit stdio from app module test child processes

this prevents them from timing out due to full stdout buffers

* test to see if we can get better logs on windows ci

* try again for appveyor log things

* skip contentTracing tests on ia32

* ci: disable gpu compositing

* drop applied patch

* fix merge fail

* Revert "ci: disable gpu compositing"

This reverts commit 0344129fcb19ea3e87e06c1110d751f22eba3fec.

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
Co-authored-by: John Kleinschmidt <jkleinsc@github.com>
Co-authored-by: VerteDinde <khammond@slack-corp.com>
Co-authored-by: VerteDinde <vertedinde@electronjs.org>
Co-authored-by: Jeremy Rose <jeremya@chromium.org>
Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
Co-authored-by: Cheng Zhao <zcbenz@gmail.com>
Co-authored-by: deepak1556 <hop2deep@gmail.com>
2022-02-09 18:58:52 -08:00

381 lines
13 KiB
C++

// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shell/browser/ui/gtk/app_indicator_icon.h"
#include <dlfcn.h>
#include <gtk/gtk.h>
#include <algorithm>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/environment.h"
#include "base/files/file_util.h"
#include "base/hash/md5.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "content/public/browser/browser_thread.h"
#include "shell/browser/ui/gtk/app_indicator_icon_menu.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "ui/base/models/menu_model.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
namespace {
typedef enum {
APP_INDICATOR_CATEGORY_APPLICATION_STATUS,
APP_INDICATOR_CATEGORY_COMMUNICATIONS,
APP_INDICATOR_CATEGORY_SYSTEM_SERVICES,
APP_INDICATOR_CATEGORY_HARDWARE,
APP_INDICATOR_CATEGORY_OTHER
} AppIndicatorCategory;
typedef enum {
APP_INDICATOR_STATUS_PASSIVE,
APP_INDICATOR_STATUS_ACTIVE,
APP_INDICATOR_STATUS_ATTENTION
} AppIndicatorStatus;
typedef AppIndicator* (*app_indicator_new_func)(const gchar* id,
const gchar* icon_name,
AppIndicatorCategory category);
typedef AppIndicator* (*app_indicator_new_with_path_func)(
const gchar* id,
const gchar* icon_name,
AppIndicatorCategory category,
const gchar* icon_theme_path);
typedef void (*app_indicator_set_status_func)(AppIndicator* self,
AppIndicatorStatus status);
typedef void (*app_indicator_set_attention_icon_full_func)(
AppIndicator* self,
const gchar* icon_name,
const gchar* icon_desc);
typedef void (*app_indicator_set_menu_func)(AppIndicator* self, GtkMenu* menu);
typedef void (*app_indicator_set_icon_full_func)(AppIndicator* self,
const gchar* icon_name,
const gchar* icon_desc);
typedef void (*app_indicator_set_icon_theme_path_func)(
AppIndicator* self,
const gchar* icon_theme_path);
bool g_attempted_load = false;
bool g_opened = false;
// Retrieved functions from libappindicator.
app_indicator_new_func app_indicator_new = nullptr;
app_indicator_new_with_path_func app_indicator_new_with_path = nullptr;
app_indicator_set_status_func app_indicator_set_status = nullptr;
app_indicator_set_attention_icon_full_func
app_indicator_set_attention_icon_full = nullptr;
app_indicator_set_menu_func app_indicator_set_menu = nullptr;
app_indicator_set_icon_full_func app_indicator_set_icon_full = nullptr;
app_indicator_set_icon_theme_path_func app_indicator_set_icon_theme_path =
nullptr;
void EnsureLibAppIndicatorLoaded() {
if (g_attempted_load)
return;
g_attempted_load = true;
std::string lib_name =
"libappindicator" + base::NumberToString(GTK_MAJOR_VERSION) + ".so";
void* indicator_lib = dlopen(lib_name.c_str(), RTLD_LAZY);
if (!indicator_lib) {
lib_name += ".1";
indicator_lib = dlopen(lib_name.c_str(), RTLD_LAZY);
}
if (!indicator_lib)
return;
g_opened = true;
app_indicator_new = reinterpret_cast<app_indicator_new_func>(
dlsym(indicator_lib, "app_indicator_new"));
app_indicator_new_with_path =
reinterpret_cast<app_indicator_new_with_path_func>(
dlsym(indicator_lib, "app_indicator_new_with_path"));
app_indicator_set_status = reinterpret_cast<app_indicator_set_status_func>(
dlsym(indicator_lib, "app_indicator_set_status"));
app_indicator_set_attention_icon_full =
reinterpret_cast<app_indicator_set_attention_icon_full_func>(
dlsym(indicator_lib, "app_indicator_set_attention_icon_full"));
app_indicator_set_menu = reinterpret_cast<app_indicator_set_menu_func>(
dlsym(indicator_lib, "app_indicator_set_menu"));
app_indicator_set_icon_full =
reinterpret_cast<app_indicator_set_icon_full_func>(
dlsym(indicator_lib, "app_indicator_set_icon_full"));
app_indicator_set_icon_theme_path =
reinterpret_cast<app_indicator_set_icon_theme_path_func>(
dlsym(indicator_lib, "app_indicator_set_icon_theme_path"));
}
// Writes |bitmap| to a file at |path|. Returns true if successful.
bool WriteFile(const base::FilePath& path, const SkBitmap& bitmap) {
std::vector<unsigned char> png_data;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
return false;
int bytes_written = base::WriteFile(
path, reinterpret_cast<char*>(&png_data[0]), png_data.size());
return (bytes_written == static_cast<int>(png_data.size()));
}
void DeleteTempDirectory(const base::FilePath& dir_path) {
if (dir_path.empty())
return;
base::DeletePathRecursively(dir_path);
}
} // namespace
namespace electron {
namespace gtkui {
AppIndicatorIcon::AppIndicatorIcon(std::string id,
const gfx::ImageSkia& image,
const std::u16string& tool_tip)
: id_(id) {
auto env = base::Environment::Create();
desktop_env_ = base::nix::GetDesktopEnvironment(env.get());
EnsureLibAppIndicatorLoaded();
tool_tip_ = base::UTF16ToUTF8(tool_tip);
SetIcon(image);
}
AppIndicatorIcon::~AppIndicatorIcon() {
if (icon_) {
app_indicator_set_status(icon_, APP_INDICATOR_STATUS_PASSIVE);
g_object_unref(icon_);
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&DeleteTempDirectory, temp_dir_));
}
}
// static
bool AppIndicatorIcon::CouldOpen() {
EnsureLibAppIndicatorLoaded();
return g_opened;
}
void AppIndicatorIcon::SetIcon(const gfx::ImageSkia& image) {
if (!g_opened)
return;
++icon_change_count_;
// Copy the bitmap because it may be freed by the time it's accessed in
// another thread.
SkBitmap safe_bitmap = *image.bitmap();
const base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN};
if (desktop_env_ == base::nix::DESKTOP_ENVIRONMENT_KDE4 ||
desktop_env_ == base::nix::DESKTOP_ENVIRONMENT_KDE5) {
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, kTraits,
base::BindOnce(AppIndicatorIcon::WriteKDE4TempImageOnWorkerThread,
safe_bitmap, temp_dir_),
base::BindOnce(&AppIndicatorIcon::SetImageFromFile,
weak_factory_.GetWeakPtr()));
} else {
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, kTraits,
base::BindOnce(AppIndicatorIcon::WriteUnityTempImageOnWorkerThread,
safe_bitmap, icon_change_count_, id_),
base::BindOnce(&AppIndicatorIcon::SetImageFromFile,
weak_factory_.GetWeakPtr()));
}
}
void AppIndicatorIcon::SetToolTip(const std::u16string& tool_tip) {
DCHECK(!tool_tip_.empty());
tool_tip_ = base::UTF16ToUTF8(tool_tip);
UpdateClickActionReplacementMenuItem();
}
void AppIndicatorIcon::UpdatePlatformContextMenu(ui::MenuModel* model) {
if (!g_opened)
return;
menu_model_ = model;
// The icon is created asynchronously so it might not exist when the menu is
// set.
if (icon_)
SetMenu();
}
void AppIndicatorIcon::RefreshPlatformContextMenu() {
menu_->Refresh();
}
// static
AppIndicatorIcon::SetImageFromFileParams
AppIndicatorIcon::WriteKDE4TempImageOnWorkerThread(
const SkBitmap& bitmap,
const base::FilePath& existing_temp_dir) {
base::FilePath temp_dir = existing_temp_dir;
if (temp_dir.empty() &&
!base::CreateNewTempDirectory(base::FilePath::StringType(), &temp_dir)) {
LOG(WARNING) << "Could not create temporary directory";
return SetImageFromFileParams();
}
base::FilePath icon_theme_path = temp_dir.AppendASCII("icons");
// On KDE4, an image located in a directory ending with
// "icons/hicolor/22x22/apps" can be used as the app indicator image because
// "/usr/share/icons/hicolor/22x22/apps" exists.
base::FilePath image_dir =
icon_theme_path.AppendASCII("hicolor").AppendASCII("22x22").AppendASCII(
"apps");
if (!base::CreateDirectory(image_dir))
return SetImageFromFileParams();
// On KDE4, the name of the image file for each different looking bitmap must
// be unique. It must also be unique across runs of Chrome.
std::vector<unsigned char> bitmap_png_data;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &bitmap_png_data)) {
LOG(WARNING) << "Could not encode icon";
return SetImageFromFileParams();
}
base::MD5Digest digest;
base::MD5Sum(reinterpret_cast<char*>(&bitmap_png_data[0]),
bitmap_png_data.size(), &digest);
std::string icon_name = base::StringPrintf(
"electron_app_indicator2_%s", base::MD5DigestToBase16(digest).c_str());
// If |bitmap| is smaller than 22x22, KDE does some really ugly resizing.
// Pad |bitmap| with transparent pixels to make it 22x22.
const int kMinimalSize = 22;
SkBitmap scaled_bitmap;
scaled_bitmap.allocN32Pixels(std::max(bitmap.width(), kMinimalSize),
std::max(bitmap.height(), kMinimalSize));
scaled_bitmap.eraseARGB(0, 0, 0, 0);
SkCanvas canvas(scaled_bitmap);
canvas.drawImage(bitmap.asImage(),
(scaled_bitmap.width() - bitmap.width()) / 2,
(scaled_bitmap.height() - bitmap.height()) / 2);
base::FilePath image_path = image_dir.Append(icon_name + ".png");
if (!WriteFile(image_path, scaled_bitmap))
return SetImageFromFileParams();
SetImageFromFileParams params;
params.parent_temp_dir = temp_dir;
params.icon_theme_path = icon_theme_path.value();
params.icon_name = icon_name;
return params;
}
// static
AppIndicatorIcon::SetImageFromFileParams
AppIndicatorIcon::WriteUnityTempImageOnWorkerThread(const SkBitmap& bitmap,
int icon_change_count,
const std::string& id) {
// Create a new temporary directory for each image on Unity since using a
// single temporary directory seems to have issues when changing icons in
// quick succession.
base::FilePath temp_dir;
if (!base::CreateNewTempDirectory(base::FilePath::StringType(), &temp_dir)) {
LOG(WARNING) << "Could not create temporary directory";
return SetImageFromFileParams();
}
std::string icon_name =
base::StringPrintf("%s_%d", id.c_str(), icon_change_count);
base::FilePath image_path = temp_dir.Append(icon_name + ".png");
SetImageFromFileParams params;
if (WriteFile(image_path, bitmap)) {
params.parent_temp_dir = temp_dir;
params.icon_theme_path = temp_dir.value();
params.icon_name = icon_name;
}
return params;
}
void AppIndicatorIcon::SetImageFromFile(const SetImageFromFileParams& params) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (params.icon_theme_path.empty())
return;
if (!icon_) {
icon_ =
app_indicator_new_with_path(id_.c_str(), params.icon_name.c_str(),
APP_INDICATOR_CATEGORY_APPLICATION_STATUS,
params.icon_theme_path.c_str());
app_indicator_set_status(icon_, APP_INDICATOR_STATUS_ACTIVE);
SetMenu();
} else {
app_indicator_set_icon_theme_path(icon_, params.icon_theme_path.c_str());
app_indicator_set_icon_full(icon_, params.icon_name.c_str(), "icon");
}
if (temp_dir_ != params.parent_temp_dir) {
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&DeleteTempDirectory, temp_dir_));
temp_dir_ = params.parent_temp_dir;
}
}
void AppIndicatorIcon::SetMenu() {
menu_ = std::make_unique<AppIndicatorIconMenu>(menu_model_);
UpdateClickActionReplacementMenuItem();
app_indicator_set_menu(icon_, menu_->GetGtkMenu());
}
void AppIndicatorIcon::UpdateClickActionReplacementMenuItem() {
// The menu may not have been created yet.
if (!menu_.get())
return;
if (!delegate()->HasClickAction() && menu_model_)
return;
DCHECK(!tool_tip_.empty());
menu_->UpdateClickActionReplacementMenuItem(
tool_tip_.c_str(),
base::BindRepeating(
&AppIndicatorIcon::OnClickActionReplacementMenuItemActivated,
base::Unretained(this)));
}
void AppIndicatorIcon::OnClickActionReplacementMenuItemActivated() {
if (delegate())
delegate()->OnClick();
}
} // namespace gtkui
} // namespace electron