browser_win.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "base/functional/bind.h"
  5. #include "shell/browser/browser.h"
  6. // must come before other includes. fixes bad #defines from <shlwapi.h>.
  7. #include "base/win/shlwapi.h" // NOLINT(build/include_order)
  8. #include <windows.h> // NOLINT(build/include_order)
  9. #include <atlbase.h> // NOLINT(build/include_order)
  10. #include <shlobj.h> // NOLINT(build/include_order)
  11. #include <shobjidl.h> // NOLINT(build/include_order)
  12. #include "base/base_paths.h"
  13. #include "base/file_version_info.h"
  14. #include "base/files/file_path.h"
  15. #include "base/logging.h"
  16. #include "base/path_service.h"
  17. #include "base/strings/string_util.h"
  18. #include "base/strings/stringprintf.h"
  19. #include "base/strings/utf_string_conversions.h"
  20. #include "base/win/registry.h"
  21. #include "base/win/win_util.h"
  22. #include "base/win/windows_version.h"
  23. #include "chrome/browser/icon_manager.h"
  24. #include "electron/electron_version.h"
  25. #include "shell/browser/api/electron_api_app.h"
  26. #include "shell/browser/badging/badge_manager.h"
  27. #include "shell/browser/electron_browser_main_parts.h"
  28. #include "shell/browser/ui/message_box.h"
  29. #include "shell/browser/ui/win/jump_list.h"
  30. #include "shell/browser/window_list.h"
  31. #include "shell/common/application_info.h"
  32. #include "shell/common/gin_converters/file_path_converter.h"
  33. #include "shell/common/gin_converters/image_converter.h"
  34. #include "shell/common/gin_helper/arguments.h"
  35. #include "shell/common/gin_helper/dictionary.h"
  36. #include "shell/common/skia_util.h"
  37. #include "shell/common/thread_restrictions.h"
  38. #include "skia/ext/legacy_display_globals.h"
  39. #include "third_party/skia/include/core/SkCanvas.h"
  40. #include "third_party/skia/include/core/SkFont.h"
  41. #include "third_party/skia/include/core/SkPaint.h"
  42. #include "ui/base/l10n/l10n_util.h"
  43. #include "ui/events/keycodes/keyboard_code_conversion_win.h"
  44. #include "ui/strings/grit/ui_strings.h"
  45. namespace electron {
  46. namespace {
  47. bool GetProcessExecPath(std::wstring* exe) {
  48. base::FilePath path;
  49. if (!base::PathService::Get(base::FILE_EXE, &path)) {
  50. return false;
  51. }
  52. *exe = path.value();
  53. return true;
  54. }
  55. bool GetProtocolLaunchPath(gin::Arguments* args, std::wstring* exe) {
  56. if (!args->GetNext(exe) && !GetProcessExecPath(exe)) {
  57. return false;
  58. }
  59. // Read in optional args arg
  60. std::vector<std::wstring> launch_args;
  61. if (args->GetNext(&launch_args) && !launch_args.empty())
  62. *exe = base::StringPrintf(L"\"%ls\" \"%ls\" \"%%1\"", exe->c_str(),
  63. base::JoinString(launch_args, L"\" \"").c_str());
  64. else
  65. *exe = base::StringPrintf(L"\"%ls\" \"%%1\"", exe->c_str());
  66. return true;
  67. }
  68. // Windows treats a given scheme as an Internet scheme only if its registry
  69. // entry has a "URL Protocol" key. Check this, otherwise we allow ProgIDs to be
  70. // used as custom protocols which leads to security bugs.
  71. bool IsValidCustomProtocol(const std::wstring& scheme) {
  72. if (scheme.empty())
  73. return false;
  74. base::win::RegKey cmd_key(HKEY_CLASSES_ROOT, scheme.c_str(), KEY_QUERY_VALUE);
  75. return cmd_key.Valid() && cmd_key.HasValue(L"URL Protocol");
  76. }
  77. // Helper for GetApplicationInfoForProtocol().
  78. // takes in an assoc_str
  79. // (https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/ne-shlwapi-assocstr)
  80. // and returns the application name, icon and path that handles the protocol.
  81. std::wstring GetAppInfoHelperForProtocol(ASSOCSTR assoc_str, const GURL& url) {
  82. const std::wstring url_scheme = base::ASCIIToWide(url.scheme());
  83. if (!IsValidCustomProtocol(url_scheme))
  84. return std::wstring();
  85. wchar_t out_buffer[1024];
  86. DWORD buffer_size = std::size(out_buffer);
  87. HRESULT hr =
  88. AssocQueryString(ASSOCF_IS_PROTOCOL, assoc_str, url_scheme.c_str(), NULL,
  89. out_buffer, &buffer_size);
  90. if (FAILED(hr)) {
  91. DLOG(WARNING) << "AssocQueryString failed!";
  92. return std::wstring();
  93. }
  94. return std::wstring(out_buffer);
  95. }
  96. void OnIconDataAvailable(const base::FilePath& app_path,
  97. const std::wstring& app_display_name,
  98. gin_helper::Promise<gin_helper::Dictionary> promise,
  99. gfx::Image icon) {
  100. if (!icon.IsEmpty()) {
  101. v8::HandleScope scope(promise.isolate());
  102. auto dict = gin_helper::Dictionary::CreateEmpty(promise.isolate());
  103. dict.Set("path", app_path);
  104. dict.Set("name", app_display_name);
  105. dict.Set("icon", icon);
  106. promise.Resolve(dict);
  107. } else {
  108. promise.RejectWithErrorMessage("Failed to get file icon.");
  109. }
  110. }
  111. std::wstring GetAppDisplayNameForProtocol(const GURL& url) {
  112. return GetAppInfoHelperForProtocol(ASSOCSTR_FRIENDLYAPPNAME, url);
  113. }
  114. std::wstring GetAppPathForProtocol(const GURL& url) {
  115. return GetAppInfoHelperForProtocol(ASSOCSTR_EXECUTABLE, url);
  116. }
  117. bool FormatCommandLineString(std::wstring* exe,
  118. const std::vector<std::u16string>& launch_args) {
  119. if (exe->empty() && !GetProcessExecPath(exe)) {
  120. return false;
  121. }
  122. if (!launch_args.empty()) {
  123. std::u16string joined_launch_args = base::JoinString(launch_args, u" ");
  124. *exe = base::StringPrintf(L"%ls %ls", exe->c_str(),
  125. base::as_wcstr(joined_launch_args));
  126. }
  127. return true;
  128. }
  129. // Helper for GetLoginItemSettings().
  130. // iterates over all the entries in a windows registry path and returns
  131. // a list of launchItem with matching paths to our application.
  132. // if a launchItem with a matching path also has a matching entry within the
  133. // startup_approved_key_path, set executable_will_launch_at_login to be `true`
  134. std::vector<Browser::LaunchItem> GetLoginItemSettingsHelper(
  135. base::win::RegistryValueIterator* it,
  136. boolean* executable_will_launch_at_login,
  137. std::wstring scope,
  138. const Browser::LoginItemSettings& options) {
  139. std::vector<Browser::LaunchItem> launch_items;
  140. base::FilePath lookup_exe_path;
  141. if (options.path.empty()) {
  142. std::wstring process_exe_path;
  143. GetProcessExecPath(&process_exe_path);
  144. lookup_exe_path =
  145. base::CommandLine::FromString(process_exe_path).GetProgram();
  146. } else {
  147. lookup_exe_path =
  148. base::CommandLine::FromString(base::as_wcstr(options.path))
  149. .GetProgram();
  150. }
  151. if (!lookup_exe_path.empty()) {
  152. while (it->Valid()) {
  153. base::CommandLine registry_launch_cmd =
  154. base::CommandLine::FromString(it->Value());
  155. base::FilePath registry_launch_path = registry_launch_cmd.GetProgram();
  156. bool exe_match = base::FilePath::CompareEqualIgnoreCase(
  157. lookup_exe_path.value(), registry_launch_path.value());
  158. // add launch item to vector if it has a matching path (case-insensitive)
  159. if (exe_match) {
  160. Browser::LaunchItem launch_item;
  161. launch_item.name = it->Name();
  162. launch_item.path = registry_launch_path.value();
  163. launch_item.args = registry_launch_cmd.GetArgs();
  164. launch_item.scope = scope;
  165. launch_item.enabled = true;
  166. // attempt to update launch_item.enabled if there is a matching key
  167. // value entry in the StartupApproved registry
  168. HKEY hkey;
  169. // StartupApproved registry path
  170. LPCTSTR path = TEXT(
  171. "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp"
  172. "roved\\Run");
  173. LONG res;
  174. if (scope == L"user") {
  175. res =
  176. RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_QUERY_VALUE, &hkey);
  177. } else {
  178. res =
  179. RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, 0, KEY_QUERY_VALUE, &hkey);
  180. }
  181. if (res == ERROR_SUCCESS) {
  182. DWORD type, size;
  183. wchar_t startup_binary[12];
  184. LONG result =
  185. RegQueryValueEx(hkey, it->Name(), nullptr, &type,
  186. reinterpret_cast<BYTE*>(&startup_binary),
  187. &(size = sizeof(startup_binary)));
  188. if (result == ERROR_SUCCESS) {
  189. if (type == REG_BINARY) {
  190. // any other binary other than this indicates that the program is
  191. // not set to launch at login
  192. wchar_t binary_accepted[12] = {0x00, 0x00, 0x00, 0x00,
  193. 0x00, 0x00, 0x00, 0x00,
  194. 0x00, 0x00, 0x00, 0x00};
  195. wchar_t binary_accepted_alt[12] = {0x02, 0x00, 0x00, 0x00,
  196. 0x00, 0x00, 0x00, 0x00,
  197. 0x00, 0x00, 0x00, 0x00};
  198. std::string reg_binary(reinterpret_cast<char*>(binary_accepted));
  199. std::string reg_binary_alt(
  200. reinterpret_cast<char*>(binary_accepted_alt));
  201. std::string reg_startup_binary(
  202. reinterpret_cast<char*>(startup_binary));
  203. launch_item.enabled = (reg_startup_binary == reg_binary) ||
  204. (reg_startup_binary == reg_binary_alt);
  205. }
  206. }
  207. }
  208. *executable_will_launch_at_login =
  209. *executable_will_launch_at_login || launch_item.enabled;
  210. launch_items.push_back(launch_item);
  211. }
  212. it->operator++();
  213. }
  214. }
  215. return launch_items;
  216. }
  217. std::unique_ptr<FileVersionInfo> FetchFileVersionInfo() {
  218. base::FilePath path;
  219. if (base::PathService::Get(base::FILE_EXE, &path)) {
  220. electron::ScopedAllowBlockingForElectron allow_blocking;
  221. return FileVersionInfo::CreateFileVersionInfo(path);
  222. }
  223. return std::unique_ptr<FileVersionInfo>();
  224. }
  225. } // namespace
  226. Browser::UserTask::UserTask() = default;
  227. Browser::UserTask::UserTask(const UserTask&) = default;
  228. Browser::UserTask::~UserTask() = default;
  229. void GetFileIcon(const base::FilePath& path,
  230. v8::Isolate* isolate,
  231. base::CancelableTaskTracker* cancelable_task_tracker_,
  232. const std::wstring app_display_name,
  233. gin_helper::Promise<gin_helper::Dictionary> promise) {
  234. base::FilePath normalized_path = path.NormalizePathSeparators();
  235. IconLoader::IconSize icon_size = IconLoader::IconSize::LARGE;
  236. auto* icon_manager = ElectronBrowserMainParts::Get()->GetIconManager();
  237. gfx::Image* icon =
  238. icon_manager->LookupIconFromFilepath(normalized_path, icon_size, 1.0f);
  239. if (icon) {
  240. auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
  241. dict.Set("icon", *icon);
  242. dict.Set("name", app_display_name);
  243. dict.Set("path", normalized_path);
  244. promise.Resolve(dict);
  245. } else {
  246. icon_manager->LoadIcon(normalized_path, icon_size, 1.0f,
  247. base::BindOnce(&OnIconDataAvailable, normalized_path,
  248. app_display_name, std::move(promise)),
  249. cancelable_task_tracker_);
  250. }
  251. }
  252. // resolves `Promise<Object>` - Resolve with an object containing the following:
  253. // * `icon` NativeImage - the display icon of the app handling the protocol.
  254. // * `path` String - installation path of the app handling the protocol.
  255. // * `name` String - display name of the app handling the protocol.
  256. void GetApplicationInfoForProtocolUsingAssocQuery(
  257. v8::Isolate* isolate,
  258. const GURL& url,
  259. gin_helper::Promise<gin_helper::Dictionary> promise,
  260. base::CancelableTaskTracker* cancelable_task_tracker_) {
  261. std::wstring app_path = GetAppPathForProtocol(url);
  262. if (app_path.empty()) {
  263. promise.RejectWithErrorMessage(
  264. "Unable to retrieve installation path to app");
  265. return;
  266. }
  267. std::wstring app_display_name = GetAppDisplayNameForProtocol(url);
  268. if (app_display_name.empty()) {
  269. promise.RejectWithErrorMessage("Unable to retrieve display name of app");
  270. return;
  271. }
  272. base::FilePath app_path_file_path = base::FilePath(app_path);
  273. GetFileIcon(app_path_file_path, isolate, cancelable_task_tracker_,
  274. app_display_name, std::move(promise));
  275. }
  276. void Browser::AddRecentDocument(const base::FilePath& path) {
  277. CComPtr<IShellItem> item;
  278. HRESULT hr = SHCreateItemFromParsingName(path.value().c_str(), NULL,
  279. IID_PPV_ARGS(&item));
  280. if (SUCCEEDED(hr)) {
  281. SHARDAPPIDINFO info;
  282. info.psi = item;
  283. info.pszAppID = GetAppUserModelID();
  284. SHAddToRecentDocs(SHARD_APPIDINFO, &info);
  285. }
  286. }
  287. void Browser::ClearRecentDocuments() {
  288. SHAddToRecentDocs(SHARD_APPIDINFO, nullptr);
  289. }
  290. void Browser::SetAppUserModelID(const std::wstring& name) {
  291. electron::SetAppUserModelID(name);
  292. }
  293. bool Browser::SetUserTasks(const std::vector<UserTask>& tasks) {
  294. JumpList jump_list(GetAppUserModelID());
  295. if (!jump_list.Begin())
  296. return false;
  297. JumpListCategory category;
  298. category.type = JumpListCategory::Type::kTasks;
  299. category.items.reserve(tasks.size());
  300. JumpListItem item;
  301. item.type = JumpListItem::Type::kTask;
  302. for (const auto& task : tasks) {
  303. item.title = task.title;
  304. item.path = task.program;
  305. item.arguments = task.arguments;
  306. item.icon_path = task.icon_path;
  307. item.icon_index = task.icon_index;
  308. item.description = task.description;
  309. item.working_dir = task.working_dir;
  310. category.items.push_back(item);
  311. }
  312. jump_list.AppendCategory(category);
  313. return jump_list.Commit();
  314. }
  315. bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
  316. gin::Arguments* args) {
  317. if (protocol.empty())
  318. return false;
  319. // Main Registry Key
  320. HKEY root = HKEY_CURRENT_USER;
  321. std::wstring keyPath = L"Software\\Classes\\";
  322. // Command Key
  323. std::wstring wprotocol = base::UTF8ToWide(protocol);
  324. std::wstring shellPath = wprotocol + L"\\shell";
  325. std::wstring cmdPath = keyPath + shellPath + L"\\open\\command";
  326. base::win::RegKey classesKey;
  327. base::win::RegKey commandKey;
  328. if (FAILED(classesKey.Open(root, keyPath.c_str(), KEY_ALL_ACCESS)))
  329. // Classes key doesn't exist, that's concerning, but I guess
  330. // we're not the default handler
  331. return true;
  332. if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS)))
  333. // Key doesn't even exist, we can confirm that it is not set
  334. return true;
  335. std::wstring keyVal;
  336. if (FAILED(commandKey.ReadValue(L"", &keyVal)))
  337. // Default value not set, we can confirm that it is not set
  338. return true;
  339. std::wstring exe;
  340. if (!GetProtocolLaunchPath(args, &exe))
  341. return false;
  342. if (keyVal == exe) {
  343. // Let's kill the key
  344. if (FAILED(classesKey.DeleteKey(shellPath.c_str())))
  345. return false;
  346. // Let's clean up after ourselves
  347. base::win::RegKey protocolKey;
  348. std::wstring protocolPath = keyPath + wprotocol;
  349. if (SUCCEEDED(
  350. protocolKey.Open(root, protocolPath.c_str(), KEY_ALL_ACCESS))) {
  351. protocolKey.DeleteValue(L"URL Protocol");
  352. // Overwrite the default value to be empty, we can't delete it right away
  353. protocolKey.WriteValue(L"", L"");
  354. protocolKey.DeleteValue(L"");
  355. }
  356. // If now empty, delete the whole key
  357. if (protocolKey.GetValueCount().value_or(1) == 0) {
  358. classesKey.DeleteKey(wprotocol.c_str(),
  359. base::win::RegKey::RecursiveDelete(false));
  360. }
  361. return true;
  362. } else {
  363. return true;
  364. }
  365. }
  366. bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
  367. gin::Arguments* args) {
  368. // HKEY_CLASSES_ROOT
  369. // $PROTOCOL
  370. // (Default) = "URL:$NAME"
  371. // URL Protocol = ""
  372. // shell
  373. // open
  374. // command
  375. // (Default) = "$COMMAND" "%1"
  376. //
  377. // However, the "HKEY_CLASSES_ROOT" key can only be written by the
  378. // Administrator user. So, we instead write to "HKEY_CURRENT_USER\
  379. // Software\Classes", which is inherited by "HKEY_CLASSES_ROOT"
  380. // anyway, and can be written by unprivileged users.
  381. if (protocol.empty())
  382. return false;
  383. std::wstring exe;
  384. if (!GetProtocolLaunchPath(args, &exe))
  385. return false;
  386. // Main Registry Key
  387. HKEY root = HKEY_CURRENT_USER;
  388. std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol);
  389. std::wstring urlDecl = base::UTF8ToWide("URL:" + protocol);
  390. // Command Key
  391. std::wstring cmdPath = keyPath + L"\\shell\\open\\command";
  392. // Write information to registry
  393. base::win::RegKey key(root, keyPath.c_str(), KEY_ALL_ACCESS);
  394. if (FAILED(key.WriteValue(L"URL Protocol", L"")) ||
  395. FAILED(key.WriteValue(L"", urlDecl.c_str())))
  396. return false;
  397. base::win::RegKey commandKey(root, cmdPath.c_str(), KEY_ALL_ACCESS);
  398. if (FAILED(commandKey.WriteValue(L"", exe.c_str())))
  399. return false;
  400. return true;
  401. }
  402. bool Browser::IsDefaultProtocolClient(const std::string& protocol,
  403. gin::Arguments* args) {
  404. if (protocol.empty())
  405. return false;
  406. std::wstring exe;
  407. if (!GetProtocolLaunchPath(args, &exe))
  408. return false;
  409. // Main Registry Key
  410. HKEY root = HKEY_CURRENT_USER;
  411. std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol);
  412. // Command Key
  413. std::wstring cmdPath = keyPath + L"\\shell\\open\\command";
  414. base::win::RegKey key;
  415. base::win::RegKey commandKey;
  416. if (FAILED(key.Open(root, keyPath.c_str(), KEY_ALL_ACCESS)))
  417. // Key doesn't exist, we can confirm that it is not set
  418. return false;
  419. if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS)))
  420. // Key doesn't exist, we can confirm that it is not set
  421. return false;
  422. std::wstring keyVal;
  423. if (FAILED(commandKey.ReadValue(L"", &keyVal)))
  424. // Default value not set, we can confirm that it is not set
  425. return false;
  426. // Default value is the same as current file path
  427. return keyVal == exe;
  428. }
  429. std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
  430. return base::WideToUTF16(GetAppDisplayNameForProtocol(url));
  431. }
  432. v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
  433. v8::Isolate* isolate,
  434. const GURL& url) {
  435. gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
  436. v8::Local<v8::Promise> handle = promise.GetHandle();
  437. GetApplicationInfoForProtocolUsingAssocQuery(isolate, url, std::move(promise),
  438. &cancelable_task_tracker_);
  439. return handle;
  440. }
  441. bool Browser::SetBadgeCount(absl::optional<int> count) {
  442. absl::optional<std::string> badge_content;
  443. if (count.has_value() && count.value() == 0) {
  444. badge_content = absl::nullopt;
  445. } else {
  446. badge_content = badging::BadgeManager::GetBadgeString(count);
  447. }
  448. // There are 3 different cases when the badge has a value:
  449. // 1. |contents| is between 1 and 99 inclusive => Set the accessibility text
  450. // to a pluralized notification count (e.g. 4 Unread Notifications).
  451. // 2. |contents| is greater than 99 => Set the accessibility text to
  452. // More than |kMaxBadgeContent| unread notifications, so the
  453. // accessibility text matches what is displayed on the badge (e.g. More
  454. // than 99 notifications).
  455. // 3. The badge is set to 'flag' => Set the accessibility text to something
  456. // less specific (e.g. Unread Notifications).
  457. std::string badge_alt_string;
  458. if (count.has_value()) {
  459. badge_count_ = count.value();
  460. badge_alt_string = (uint64_t)badge_count_ <= badging::kMaxBadgeContent
  461. // Case 1.
  462. ? l10n_util::GetPluralStringFUTF8(
  463. IDS_BADGE_UNREAD_NOTIFICATIONS, badge_count_)
  464. // Case 2.
  465. : l10n_util::GetPluralStringFUTF8(
  466. IDS_BADGE_UNREAD_NOTIFICATIONS_SATURATED,
  467. badging::kMaxBadgeContent);
  468. } else {
  469. // Case 3.
  470. badge_alt_string =
  471. l10n_util::GetStringUTF8(IDS_BADGE_UNREAD_NOTIFICATIONS_UNSPECIFIED);
  472. badge_count_ = 0;
  473. }
  474. for (auto* window : WindowList::GetWindows()) {
  475. // On Windows set the badge on the first window found.
  476. UpdateBadgeContents(window->GetAcceleratedWidget(), badge_content,
  477. badge_alt_string);
  478. }
  479. return true;
  480. }
  481. void Browser::UpdateBadgeContents(
  482. HWND hwnd,
  483. const absl::optional<std::string>& badge_content,
  484. const std::string& badge_alt_string) {
  485. SkBitmap badge;
  486. if (badge_content) {
  487. std::string content = badge_content.value();
  488. constexpr int kOverlayIconSize = 16;
  489. // This is the color used by the Windows 10 Badge API, for platform
  490. // consistency.
  491. constexpr int kBackgroundColor = SkColorSetRGB(0x26, 0x25, 0x2D);
  492. constexpr int kForegroundColor = SK_ColorWHITE;
  493. constexpr int kRadius = kOverlayIconSize / 2;
  494. // The minimum gap to have between our content and the edge of the badge.
  495. constexpr int kMinMargin = 3;
  496. // The amount of space we have to render the icon.
  497. constexpr int kMaxBounds = kOverlayIconSize - 2 * kMinMargin;
  498. constexpr int kMaxTextSize = 24; // Max size for our text.
  499. constexpr int kMinTextSize = 7; // Min size for our text.
  500. badge.allocN32Pixels(kOverlayIconSize, kOverlayIconSize);
  501. SkCanvas canvas(badge, skia::LegacyDisplayGlobals::GetSkSurfaceProps());
  502. SkPaint paint;
  503. paint.setAntiAlias(true);
  504. paint.setColor(kBackgroundColor);
  505. canvas.clear(SK_ColorTRANSPARENT);
  506. canvas.drawCircle(kRadius, kRadius, kRadius, paint);
  507. paint.reset();
  508. paint.setColor(kForegroundColor);
  509. SkFont font;
  510. SkRect bounds;
  511. int text_size = kMaxTextSize;
  512. // Find the largest |text_size| larger than |kMinTextSize| in which
  513. // |content| fits into our 16x16px icon, with margins.
  514. do {
  515. font.setSize(text_size--);
  516. font.measureText(content.c_str(), content.size(), SkTextEncoding::kUTF8,
  517. &bounds);
  518. } while (text_size >= kMinTextSize &&
  519. (bounds.width() > kMaxBounds || bounds.height() > kMaxBounds));
  520. canvas.drawSimpleText(
  521. content.c_str(), content.size(), SkTextEncoding::kUTF8,
  522. kRadius - bounds.width() / 2 - bounds.x(),
  523. kRadius - bounds.height() / 2 - bounds.y(), font, paint);
  524. }
  525. taskbar_host_.SetOverlayIcon(hwnd, badge, badge_alt_string);
  526. }
  527. void Browser::SetLoginItemSettings(LoginItemSettings settings) {
  528. std::wstring key_path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  529. base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_ALL_ACCESS);
  530. std::wstring startup_approved_key_path =
  531. L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved"
  532. L"\\Run";
  533. base::win::RegKey startup_approved_key(
  534. HKEY_CURRENT_USER, startup_approved_key_path.c_str(), KEY_ALL_ACCESS);
  535. PCWSTR key_name =
  536. !settings.name.empty() ? settings.name.c_str() : GetAppUserModelID();
  537. if (settings.open_at_login) {
  538. std::wstring exe = base::UTF16ToWide(settings.path);
  539. if (FormatCommandLineString(&exe, settings.args)) {
  540. key.WriteValue(key_name, exe.c_str());
  541. if (settings.enabled) {
  542. startup_approved_key.DeleteValue(key_name);
  543. } else {
  544. HKEY hard_key;
  545. LPCTSTR path = TEXT(
  546. "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp"
  547. "roved\\Run");
  548. LONG res =
  549. RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_ALL_ACCESS, &hard_key);
  550. if (res == ERROR_SUCCESS) {
  551. UCHAR disable_startup_binary[] = {0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
  552. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  553. RegSetValueEx(hard_key, key_name, 0, REG_BINARY,
  554. reinterpret_cast<const BYTE*>(disable_startup_binary),
  555. sizeof(disable_startup_binary));
  556. }
  557. }
  558. }
  559. } else {
  560. // if open at login is false, delete both values
  561. startup_approved_key.DeleteValue(key_name);
  562. key.DeleteValue(key_name);
  563. }
  564. }
  565. Browser::LoginItemSettings Browser::GetLoginItemSettings(
  566. const LoginItemSettings& options) {
  567. LoginItemSettings settings;
  568. std::wstring keyPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  569. base::win::RegKey key(HKEY_CURRENT_USER, keyPath.c_str(), KEY_ALL_ACCESS);
  570. std::wstring keyVal;
  571. // keep old openAtLogin behaviour
  572. if (!FAILED(key.ReadValue(GetAppUserModelID(), &keyVal))) {
  573. std::wstring exe = base::UTF16ToWide(options.path);
  574. if (FormatCommandLineString(&exe, options.args)) {
  575. settings.open_at_login = keyVal == exe;
  576. }
  577. }
  578. // iterate over current user and machine registries and populate launch items
  579. // if there exists a launch entry with property enabled=='true',
  580. // set executable_will_launch_at_login to 'true'.
  581. boolean executable_will_launch_at_login = false;
  582. std::vector<Browser::LaunchItem> launch_items;
  583. base::win::RegistryValueIterator hkcu_iterator(HKEY_CURRENT_USER,
  584. keyPath.c_str());
  585. base::win::RegistryValueIterator hklm_iterator(HKEY_LOCAL_MACHINE,
  586. keyPath.c_str());
  587. launch_items = GetLoginItemSettingsHelper(
  588. &hkcu_iterator, &executable_will_launch_at_login, L"user", options);
  589. std::vector<Browser::LaunchItem> launch_items_hklm =
  590. GetLoginItemSettingsHelper(&hklm_iterator,
  591. &executable_will_launch_at_login, L"machine",
  592. options);
  593. launch_items.insert(launch_items.end(), launch_items_hklm.begin(),
  594. launch_items_hklm.end());
  595. settings.executable_will_launch_at_login = executable_will_launch_at_login;
  596. settings.launch_items = launch_items;
  597. return settings;
  598. }
  599. PCWSTR Browser::GetAppUserModelID() {
  600. return GetRawAppUserModelID();
  601. }
  602. std::string Browser::GetExecutableFileVersion() const {
  603. base::FilePath path;
  604. if (base::PathService::Get(base::FILE_EXE, &path)) {
  605. ScopedAllowBlockingForElectron allow_blocking;
  606. std::unique_ptr<FileVersionInfo> version_info = FetchFileVersionInfo();
  607. return base::UTF16ToUTF8(version_info->product_version());
  608. }
  609. return ELECTRON_VERSION_STRING;
  610. }
  611. std::string Browser::GetExecutableFileProductName() const {
  612. return GetApplicationName();
  613. }
  614. bool Browser::IsEmojiPanelSupported() {
  615. // emoji picker is supported on Windows 10's Spring 2018 update & above.
  616. return base::win::GetVersion() >= base::win::Version::WIN10_RS4;
  617. }
  618. void Browser::ShowEmojiPanel() {
  619. // This sends Windows Key + '.' (both keydown and keyup events).
  620. // "SendInput" is used because Windows needs to receive these events and
  621. // open the Emoji picker.
  622. INPUT input[4] = {};
  623. input[0].type = INPUT_KEYBOARD;
  624. input[0].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND);
  625. input[1].type = INPUT_KEYBOARD;
  626. input[1].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD);
  627. input[2].type = INPUT_KEYBOARD;
  628. input[2].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND);
  629. input[2].ki.dwFlags |= KEYEVENTF_KEYUP;
  630. input[3].type = INPUT_KEYBOARD;
  631. input[3].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD);
  632. input[3].ki.dwFlags |= KEYEVENTF_KEYUP;
  633. ::SendInput(4, input, sizeof(INPUT));
  634. }
  635. void Browser::ShowAboutPanel() {
  636. base::Value::Dict dict;
  637. std::string aboutMessage = "";
  638. gfx::ImageSkia image;
  639. // grab defaults from Windows .EXE file
  640. std::unique_ptr<FileVersionInfo> exe_info = FetchFileVersionInfo();
  641. dict.Set("applicationName", exe_info->file_description());
  642. dict.Set("applicationVersion", exe_info->product_version());
  643. // Merge user-provided options, overwriting any of the above
  644. dict.Merge(about_panel_options_.Clone());
  645. std::vector<std::string> stringOptions = {
  646. "applicationName", "applicationVersion", "copyright", "credits"};
  647. const std::string* str;
  648. for (std::string opt : stringOptions) {
  649. if ((str = dict.FindString(opt))) {
  650. aboutMessage.append(*str).append("\r\n");
  651. }
  652. }
  653. if ((str = dict.FindString("iconPath"))) {
  654. base::FilePath path = base::FilePath::FromUTF8Unsafe(*str);
  655. electron::util::PopulateImageSkiaRepsFromPath(&image, path);
  656. }
  657. electron::MessageBoxSettings settings = {};
  658. settings.message = aboutMessage;
  659. settings.icon = image;
  660. settings.type = electron::MessageBoxType::kInformation;
  661. electron::ShowMessageBox(settings,
  662. base::BindOnce([](int, bool) { /* do nothing. */ }));
  663. }
  664. void Browser::SetAboutPanelOptions(base::Value::Dict options) {
  665. about_panel_options_ = std::move(options);
  666. }
  667. } // namespace electron