browser_win.cc 27 KB

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