Backed out 3 changesets (bug 1879975) for causing valgrind bustages. CLOSED TREE
[gecko.git] / browser / components / shell / nsWindowsShellService.cpp
blob86c7694bf87e2a6f4f765ce4ca351706c8102a63
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #define UNICODE
8 #include "nsWindowsShellService.h"
10 #include "BinaryPath.h"
11 #include "imgIContainer.h"
12 #include "imgIRequest.h"
13 #include "mozilla/RefPtr.h"
14 #include "nsComponentManagerUtils.h"
15 #include "nsIContent.h"
16 #include "nsIImageLoadingContent.h"
17 #include "nsIOutputStream.h"
18 #include "nsIPrefService.h"
19 #include "nsIStringBundle.h"
20 #include "nsIMIMEService.h"
21 #include "nsNetUtil.h"
22 #include "nsServiceManagerUtils.h"
23 #include "nsShellService.h"
24 #include "nsDirectoryServiceUtils.h"
25 #include "nsAppDirectoryServiceDefs.h"
26 #include "nsDirectoryServiceDefs.h"
27 #include "nsIWindowsRegKey.h"
28 #include "nsUnicharUtils.h"
29 #include "nsXULAppAPI.h"
30 #include "mozilla/WindowsVersion.h"
31 #include "mozilla/dom/Element.h"
32 #include "mozilla/dom/Promise.h"
33 #include "mozilla/ErrorResult.h"
34 #include "mozilla/gfx/2D.h"
35 #include "mozilla/intl/Localization.h"
36 #include "WindowsDefaultBrowser.h"
37 #include "WindowsUserChoice.h"
38 #include "nsLocalFile.h"
39 #include "nsIXULAppInfo.h"
40 #include "nsINIParser.h"
41 #include "nsNativeAppSupportWin.h"
43 #include <windows.h>
44 #include <shellapi.h>
45 #include <strsafe.h>
46 #include <propvarutil.h>
47 #include <propkey.h>
49 #ifdef __MINGW32__
50 // MinGW-w64 headers are missing PropVariantToString.
51 # include <propsys.h>
52 PSSTDAPI PropVariantToString(REFPROPVARIANT propvar, PWSTR psz, UINT cch);
53 # define UNLEN 256
54 #else
55 # include <Lmcons.h> // For UNLEN
56 #endif
58 #include <comutil.h>
59 #include <objbase.h>
60 #include <knownfolders.h>
61 #include "WinUtils.h"
62 #include "mozilla/widget/WinTaskbar.h"
64 #include <mbstring.h>
66 #define PRIVATE_BROWSING_BINARY L"private_browsing.exe"
68 #undef ACCESS_READ
70 #ifndef MAX_BUF
71 # define MAX_BUF 4096
72 #endif
74 #define REG_SUCCEEDED(val) (val == ERROR_SUCCESS)
76 #define REG_FAILED(val) (val != ERROR_SUCCESS)
78 #ifdef DEBUG
79 # define NS_ENSURE_HRESULT(hres, ret) \
80 do { \
81 HRESULT result = hres; \
82 if (MOZ_UNLIKELY(FAILED(result))) { \
83 mozilla::SmprintfPointer msg = mozilla::Smprintf( \
84 "NS_ENSURE_HRESULT(%s, %s) failed with " \
85 "result 0x%" PRIX32, \
86 #hres, #ret, static_cast<uint32_t>(result)); \
87 NS_WARNING(msg.get()); \
88 return ret; \
89 } \
90 } while (false)
91 #else
92 # define NS_ENSURE_HRESULT(hres, ret) \
93 if (MOZ_UNLIKELY(FAILED(hres))) return ret
94 #endif
96 using namespace mozilla;
97 using mozilla::intl::Localization;
99 struct SysFreeStringDeleter {
100 void operator()(BSTR aPtr) { ::SysFreeString(aPtr); }
102 using BStrPtr = mozilla::UniquePtr<OLECHAR, SysFreeStringDeleter>;
104 NS_IMPL_ISUPPORTS(nsWindowsShellService, nsIToolkitShellService,
105 nsIShellService, nsIWindowsShellService)
107 static nsresult OpenKeyForReading(HKEY aKeyRoot, const nsAString& aKeyName,
108 HKEY* aKey) {
109 const nsString& flatName = PromiseFlatString(aKeyName);
111 DWORD res = ::RegOpenKeyExW(aKeyRoot, flatName.get(), 0, KEY_READ, aKey);
112 switch (res) {
113 case ERROR_SUCCESS:
114 break;
115 case ERROR_ACCESS_DENIED:
116 return NS_ERROR_FILE_ACCESS_DENIED;
117 case ERROR_FILE_NOT_FOUND:
118 return NS_ERROR_NOT_AVAILABLE;
121 return NS_OK;
124 nsresult GetHelperPath(nsAutoString& aPath) {
125 nsresult rv;
126 nsCOMPtr<nsIProperties> directoryService =
127 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
128 NS_ENSURE_SUCCESS(rv, rv);
130 nsCOMPtr<nsIFile> appHelper;
131 rv = directoryService->Get(XRE_EXECUTABLE_FILE, NS_GET_IID(nsIFile),
132 getter_AddRefs(appHelper));
133 NS_ENSURE_SUCCESS(rv, rv);
135 rv = appHelper->SetNativeLeafName("uninstall"_ns);
136 NS_ENSURE_SUCCESS(rv, rv);
138 rv = appHelper->AppendNative("helper.exe"_ns);
139 NS_ENSURE_SUCCESS(rv, rv);
141 rv = appHelper->GetPath(aPath);
143 aPath.Insert(L'"', 0);
144 aPath.Append(L'"');
145 return rv;
148 nsresult LaunchHelper(nsAutoString& aPath) {
149 STARTUPINFOW si = {sizeof(si), 0};
150 PROCESS_INFORMATION pi = {0};
152 if (!CreateProcessW(nullptr, (LPWSTR)aPath.get(), nullptr, nullptr, FALSE, 0,
153 nullptr, nullptr, &si, &pi)) {
154 return NS_ERROR_FAILURE;
157 CloseHandle(pi.hProcess);
158 CloseHandle(pi.hThread);
159 return NS_OK;
162 static bool IsPathDefaultForClass(
163 const RefPtr<IApplicationAssociationRegistration>& pAAR, wchar_t* exePath,
164 LPCWSTR aClassName) {
165 LPWSTR registeredApp;
166 bool isProtocol = *aClassName != L'.';
167 ASSOCIATIONTYPE queryType = isProtocol ? AT_URLPROTOCOL : AT_FILEEXTENSION;
168 HRESULT hr = pAAR->QueryCurrentDefault(aClassName, queryType, AL_EFFECTIVE,
169 &registeredApp);
170 if (FAILED(hr)) {
171 return false;
174 nsAutoString regAppName(registeredApp);
175 CoTaskMemFree(registeredApp);
177 // Make sure the application path for this progID is this installation.
178 regAppName.AppendLiteral("\\shell\\open\\command");
179 HKEY theKey;
180 nsresult rv = OpenKeyForReading(HKEY_CLASSES_ROOT, regAppName, &theKey);
181 if (NS_FAILED(rv)) {
182 return false;
185 wchar_t cmdFromReg[MAX_BUF] = L"";
186 DWORD len = sizeof(cmdFromReg);
187 DWORD res = ::RegQueryValueExW(theKey, nullptr, nullptr, nullptr,
188 (LPBYTE)cmdFromReg, &len);
189 ::RegCloseKey(theKey);
190 if (REG_FAILED(res)) {
191 return false;
194 nsAutoString pathFromReg(cmdFromReg);
195 nsLocalFile::CleanupCmdHandlerPath(pathFromReg);
197 return _wcsicmp(exePath, pathFromReg.Data()) == 0;
200 NS_IMETHODIMP
201 nsWindowsShellService::IsDefaultBrowser(bool aForAllTypes,
202 bool* aIsDefaultBrowser) {
203 *aIsDefaultBrowser = false;
205 RefPtr<IApplicationAssociationRegistration> pAAR;
206 HRESULT hr = CoCreateInstance(
207 CLSID_ApplicationAssociationRegistration, nullptr, CLSCTX_INPROC,
208 IID_IApplicationAssociationRegistration, getter_AddRefs(pAAR));
209 if (FAILED(hr)) {
210 return NS_OK;
213 wchar_t exePath[MAXPATHLEN] = L"";
214 nsresult rv = BinaryPath::GetLong(exePath);
216 if (NS_FAILED(rv)) {
217 return NS_OK;
220 *aIsDefaultBrowser = IsPathDefaultForClass(pAAR, exePath, L"http");
221 if (*aIsDefaultBrowser && aForAllTypes) {
222 *aIsDefaultBrowser = IsPathDefaultForClass(pAAR, exePath, L".html");
224 return NS_OK;
227 NS_IMETHODIMP
228 nsWindowsShellService::IsDefaultHandlerFor(
229 const nsAString& aFileExtensionOrProtocol, bool* aIsDefaultHandlerFor) {
230 *aIsDefaultHandlerFor = false;
232 RefPtr<IApplicationAssociationRegistration> pAAR;
233 HRESULT hr = CoCreateInstance(
234 CLSID_ApplicationAssociationRegistration, nullptr, CLSCTX_INPROC,
235 IID_IApplicationAssociationRegistration, getter_AddRefs(pAAR));
236 if (FAILED(hr)) {
237 return NS_OK;
240 wchar_t exePath[MAXPATHLEN] = L"";
241 nsresult rv = BinaryPath::GetLong(exePath);
243 if (NS_FAILED(rv)) {
244 return NS_OK;
247 const nsString& flatClass = PromiseFlatString(aFileExtensionOrProtocol);
249 *aIsDefaultHandlerFor = IsPathDefaultForClass(pAAR, exePath, flatClass.get());
250 return NS_OK;
253 NS_IMETHODIMP
254 nsWindowsShellService::QueryCurrentDefaultHandlerFor(
255 const nsAString& aFileExtensionOrProtocol, nsAString& aResult) {
256 aResult.Truncate();
258 RefPtr<IApplicationAssociationRegistration> pAAR;
259 HRESULT hr = CoCreateInstance(
260 CLSID_ApplicationAssociationRegistration, nullptr, CLSCTX_INPROC,
261 IID_IApplicationAssociationRegistration, getter_AddRefs(pAAR));
262 if (FAILED(hr)) {
263 return NS_OK;
266 const nsString& flatClass = PromiseFlatString(aFileExtensionOrProtocol);
268 LPWSTR registeredApp;
269 bool isProtocol = flatClass.First() != L'.';
270 ASSOCIATIONTYPE queryType = isProtocol ? AT_URLPROTOCOL : AT_FILEEXTENSION;
271 hr = pAAR->QueryCurrentDefault(flatClass.get(), queryType, AL_EFFECTIVE,
272 &registeredApp);
273 if (hr == HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION)) {
274 return NS_OK;
276 NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
278 aResult = registeredApp;
279 CoTaskMemFree(registeredApp);
281 return NS_OK;
284 nsresult nsWindowsShellService::LaunchControlPanelDefaultsSelectionUI() {
285 IApplicationAssociationRegistrationUI* pAARUI;
286 HRESULT hr = CoCreateInstance(
287 CLSID_ApplicationAssociationRegistrationUI, NULL, CLSCTX_INPROC,
288 IID_IApplicationAssociationRegistrationUI, (void**)&pAARUI);
289 if (SUCCEEDED(hr)) {
290 mozilla::UniquePtr<wchar_t[]> appRegName;
291 GetAppRegName(appRegName);
292 hr = pAARUI->LaunchAdvancedAssociationUI(appRegName.get());
293 pAARUI->Release();
295 return SUCCEEDED(hr) ? NS_OK : NS_ERROR_FAILURE;
298 NS_IMETHODIMP
299 nsWindowsShellService::CheckAllProgIDsExist(bool* aResult) {
300 *aResult = false;
301 nsAutoString aumid;
302 if (!mozilla::widget::WinTaskbar::GetAppUserModelID(aumid)) {
303 return NS_OK;
306 if (widget::WinUtils::HasPackageIdentity()) {
307 UniquePtr<wchar_t[]> extraProgID;
308 nsresult rv;
309 bool result = true;
311 // "FirefoxURL".
312 rv = GetMsixProgId(L"https", extraProgID);
313 if (NS_WARN_IF(NS_FAILED(rv))) {
314 return rv;
316 result = result && CheckProgIDExists(extraProgID.get());
318 // "FirefoxHTML".
319 rv = GetMsixProgId(L".htm", extraProgID);
320 if (NS_WARN_IF(NS_FAILED(rv))) {
321 return rv;
323 result = result && CheckProgIDExists(extraProgID.get());
325 // "FirefoxPDF".
326 rv = GetMsixProgId(L".pdf", extraProgID);
327 if (NS_WARN_IF(NS_FAILED(rv))) {
328 return rv;
330 result = result && CheckProgIDExists(extraProgID.get());
332 *aResult = result;
333 } else {
334 *aResult =
335 CheckProgIDExists(FormatProgID(L"FirefoxURL", aumid.get()).get()) &&
336 CheckProgIDExists(FormatProgID(L"FirefoxHTML", aumid.get()).get()) &&
337 CheckProgIDExists(FormatProgID(L"FirefoxPDF", aumid.get()).get());
340 return NS_OK;
343 NS_IMETHODIMP
344 nsWindowsShellService::CheckBrowserUserChoiceHashes(bool* aResult) {
345 *aResult = ::CheckBrowserUserChoiceHashes();
346 return NS_OK;
349 NS_IMETHODIMP
350 nsWindowsShellService::CanSetDefaultBrowserUserChoice(bool* aResult) {
351 *aResult = false;
352 // If the WDBA is not available, this could never succeed.
353 #ifdef MOZ_DEFAULT_BROWSER_AGENT
354 bool progIDsExist = false;
355 bool hashOk = false;
356 *aResult = NS_SUCCEEDED(CheckAllProgIDsExist(&progIDsExist)) &&
357 progIDsExist &&
358 NS_SUCCEEDED(CheckBrowserUserChoiceHashes(&hashOk)) && hashOk;
359 #endif
360 return NS_OK;
363 nsresult nsWindowsShellService::LaunchModernSettingsDialogDefaultApps() {
364 return ::LaunchModernSettingsDialogDefaultApps() ? NS_OK : NS_ERROR_FAILURE;
367 NS_IMETHODIMP
368 nsWindowsShellService::SetDefaultBrowser(bool aForAllUsers) {
369 // If running from within a package, don't attempt to set default with
370 // the helper, as it will not work and will only confuse our package's
371 // virtualized registry.
372 nsresult rv = NS_OK;
373 if (!widget::WinUtils::HasPackageIdentity()) {
374 nsAutoString appHelperPath;
375 if (NS_FAILED(GetHelperPath(appHelperPath))) return NS_ERROR_FAILURE;
377 if (aForAllUsers) {
378 appHelperPath.AppendLiteral(" /SetAsDefaultAppGlobal");
379 } else {
380 appHelperPath.AppendLiteral(" /SetAsDefaultAppUser");
383 rv = LaunchHelper(appHelperPath);
386 if (NS_SUCCEEDED(rv)) {
387 rv = LaunchModernSettingsDialogDefaultApps();
388 // The above call should never really fail, but just in case
389 // fall back to showing control panel for all defaults
390 if (NS_FAILED(rv)) {
391 rv = LaunchControlPanelDefaultsSelectionUI();
395 nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
396 if (prefs) {
397 (void)prefs->SetBoolPref(PREF_CHECKDEFAULTBROWSER, true);
398 // Reset the number of times the dialog should be shown
399 // before it is silenced.
400 (void)prefs->SetIntPref(PREF_DEFAULTBROWSERCHECKCOUNT, 0);
403 return rv;
406 static nsresult WriteBitmap(nsIFile* aFile, imgIContainer* aImage) {
407 nsresult rv;
409 RefPtr<gfx::SourceSurface> surface = aImage->GetFrame(
410 imgIContainer::FRAME_FIRST, imgIContainer::FLAG_SYNC_DECODE);
411 NS_ENSURE_TRUE(surface, NS_ERROR_FAILURE);
413 // For either of the following formats we want to set the biBitCount member
414 // of the BITMAPINFOHEADER struct to 32, below. For that value the bitmap
415 // format defines that the A8/X8 WORDs in the bitmap byte stream be ignored
416 // for the BI_RGB value we use for the biCompression member.
417 MOZ_ASSERT(surface->GetFormat() == gfx::SurfaceFormat::B8G8R8A8 ||
418 surface->GetFormat() == gfx::SurfaceFormat::B8G8R8X8);
420 RefPtr<gfx::DataSourceSurface> dataSurface = surface->GetDataSurface();
421 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
423 int32_t width = dataSurface->GetSize().width;
424 int32_t height = dataSurface->GetSize().height;
425 int32_t bytesPerPixel = 4 * sizeof(uint8_t);
426 uint32_t bytesPerRow = bytesPerPixel * width;
428 // initialize these bitmap structs which we will later
429 // serialize directly to the head of the bitmap file
430 BITMAPINFOHEADER bmi;
431 bmi.biSize = sizeof(BITMAPINFOHEADER);
432 bmi.biWidth = width;
433 bmi.biHeight = height;
434 bmi.biPlanes = 1;
435 bmi.biBitCount = (WORD)bytesPerPixel * 8;
436 bmi.biCompression = BI_RGB;
437 bmi.biSizeImage = bytesPerRow * height;
438 bmi.biXPelsPerMeter = 0;
439 bmi.biYPelsPerMeter = 0;
440 bmi.biClrUsed = 0;
441 bmi.biClrImportant = 0;
443 BITMAPFILEHEADER bf;
444 bf.bfType = 0x4D42; // 'BM'
445 bf.bfReserved1 = 0;
446 bf.bfReserved2 = 0;
447 bf.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
448 bf.bfSize = bf.bfOffBits + bmi.biSizeImage;
450 // get a file output stream
451 nsCOMPtr<nsIOutputStream> stream;
452 rv = NS_NewLocalFileOutputStream(getter_AddRefs(stream), aFile);
453 NS_ENSURE_SUCCESS(rv, rv);
455 gfx::DataSourceSurface::MappedSurface map;
456 if (!dataSurface->Map(gfx::DataSourceSurface::MapType::READ, &map)) {
457 return NS_ERROR_FAILURE;
460 // write the bitmap headers and rgb pixel data to the file
461 rv = NS_ERROR_FAILURE;
462 if (stream) {
463 uint32_t written;
464 stream->Write((const char*)&bf, sizeof(BITMAPFILEHEADER), &written);
465 if (written == sizeof(BITMAPFILEHEADER)) {
466 stream->Write((const char*)&bmi, sizeof(BITMAPINFOHEADER), &written);
467 if (written == sizeof(BITMAPINFOHEADER)) {
468 // write out the image data backwards because the desktop won't
469 // show bitmaps with negative heights for top-to-bottom
470 uint32_t i = map.mStride * height;
471 do {
472 i -= map.mStride;
473 stream->Write(((const char*)map.mData) + i, bytesPerRow, &written);
474 if (written == bytesPerRow) {
475 rv = NS_OK;
476 } else {
477 rv = NS_ERROR_FAILURE;
478 break;
480 } while (i != 0);
484 stream->Close();
487 dataSurface->Unmap();
489 return rv;
492 NS_IMETHODIMP
493 nsWindowsShellService::SetDesktopBackground(dom::Element* aElement,
494 int32_t aPosition,
495 const nsACString& aImageName) {
496 if (!aElement || !aElement->IsHTMLElement(nsGkAtoms::img)) {
497 // XXX write background loading stuff!
498 return NS_ERROR_NOT_AVAILABLE;
501 nsresult rv;
502 nsCOMPtr<nsIImageLoadingContent> imageContent =
503 do_QueryInterface(aElement, &rv);
504 if (!imageContent) return rv;
506 // get the image container
507 nsCOMPtr<imgIRequest> request;
508 rv = imageContent->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
509 getter_AddRefs(request));
510 if (!request) return rv;
512 nsCOMPtr<imgIContainer> container;
513 rv = request->GetImage(getter_AddRefs(container));
514 if (!container) return NS_ERROR_FAILURE;
516 // get the file name from localized strings
517 nsCOMPtr<nsIStringBundleService> bundleService(
518 do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv));
519 NS_ENSURE_SUCCESS(rv, rv);
521 nsCOMPtr<nsIStringBundle> shellBundle;
522 rv = bundleService->CreateBundle(SHELLSERVICE_PROPERTIES,
523 getter_AddRefs(shellBundle));
524 NS_ENSURE_SUCCESS(rv, rv);
526 // e.g. "Desktop Background.bmp"
527 nsAutoString fileLeafName;
528 rv = shellBundle->GetStringFromName("desktopBackgroundLeafNameWin",
529 fileLeafName);
530 NS_ENSURE_SUCCESS(rv, rv);
532 // get the profile root directory
533 nsCOMPtr<nsIFile> file;
534 rv = NS_GetSpecialDirectory(NS_APP_APPLICATION_REGISTRY_DIR,
535 getter_AddRefs(file));
536 NS_ENSURE_SUCCESS(rv, rv);
538 // eventually, the path is "%APPDATA%\Mozilla\Firefox\Desktop Background.bmp"
539 rv = file->Append(fileLeafName);
540 NS_ENSURE_SUCCESS(rv, rv);
542 nsAutoString path;
543 rv = file->GetPath(path);
544 NS_ENSURE_SUCCESS(rv, rv);
546 // write the bitmap to a file in the profile directory.
547 // We have to write old bitmap format for Windows 7 wallpapar support.
548 rv = WriteBitmap(file, container);
550 // if the file was written successfully, set it as the system wallpaper
551 if (NS_SUCCEEDED(rv)) {
552 nsCOMPtr<nsIWindowsRegKey> regKey =
553 do_CreateInstance("@mozilla.org/windows-registry-key;1", &rv);
554 NS_ENSURE_SUCCESS(rv, rv);
556 rv = regKey->Create(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER,
557 u"Control Panel\\Desktop"_ns,
558 nsIWindowsRegKey::ACCESS_SET_VALUE);
559 NS_ENSURE_SUCCESS(rv, rv);
561 nsAutoString tile;
562 nsAutoString style;
563 switch (aPosition) {
564 case BACKGROUND_TILE:
565 style.Assign('0');
566 tile.Assign('1');
567 break;
568 case BACKGROUND_CENTER:
569 style.Assign('0');
570 tile.Assign('0');
571 break;
572 case BACKGROUND_STRETCH:
573 style.Assign('2');
574 tile.Assign('0');
575 break;
576 case BACKGROUND_FILL:
577 style.AssignLiteral("10");
578 tile.Assign('0');
579 break;
580 case BACKGROUND_FIT:
581 style.Assign('6');
582 tile.Assign('0');
583 break;
584 case BACKGROUND_SPAN:
585 style.AssignLiteral("22");
586 tile.Assign('0');
587 break;
590 rv = regKey->WriteStringValue(u"TileWallpaper"_ns, tile);
591 NS_ENSURE_SUCCESS(rv, rv);
592 rv = regKey->WriteStringValue(u"WallpaperStyle"_ns, style);
593 NS_ENSURE_SUCCESS(rv, rv);
594 rv = regKey->Close();
595 NS_ENSURE_SUCCESS(rv, rv);
597 ::SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (PVOID)path.get(),
598 SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
600 return rv;
603 NS_IMETHODIMP
604 nsWindowsShellService::GetDesktopBackgroundColor(uint32_t* aColor) {
605 uint32_t color = ::GetSysColor(COLOR_DESKTOP);
606 *aColor =
607 (GetRValue(color) << 16) | (GetGValue(color) << 8) | GetBValue(color);
608 return NS_OK;
611 NS_IMETHODIMP
612 nsWindowsShellService::SetDesktopBackgroundColor(uint32_t aColor) {
613 int aParameters[2] = {COLOR_BACKGROUND, COLOR_DESKTOP};
614 BYTE r = (aColor >> 16);
615 BYTE g = (aColor << 16) >> 24;
616 BYTE b = (aColor << 24) >> 24;
617 COLORREF colors[2] = {RGB(r, g, b), RGB(r, g, b)};
619 ::SetSysColors(sizeof(aParameters) / sizeof(int), aParameters, colors);
621 nsresult rv;
622 nsCOMPtr<nsIWindowsRegKey> regKey =
623 do_CreateInstance("@mozilla.org/windows-registry-key;1", &rv);
624 NS_ENSURE_SUCCESS(rv, rv);
626 rv = regKey->Create(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER,
627 u"Control Panel\\Colors"_ns,
628 nsIWindowsRegKey::ACCESS_SET_VALUE);
629 NS_ENSURE_SUCCESS(rv, rv);
631 wchar_t rgb[12];
632 _snwprintf(rgb, 12, L"%u %u %u", r, g, b);
634 rv = regKey->WriteStringValue(u"Background"_ns, nsDependentString(rgb));
635 NS_ENSURE_SUCCESS(rv, rv);
637 return regKey->Close();
641 * Writes information about a shortcut to a shortcuts log in
642 * %PROGRAMDATA%\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38.
643 * (This is the same directory used for update staging.)
644 * For more on the shortcuts log format and purpose, consult
645 * /toolkit/mozapps/installer/windows/nsis/common.nsh.
647 * The shortcuts log created or appended here is named after
648 * the currently running application and current user SID.
649 * For example: Firefox_$SID_shortcuts.ini.
651 * If it does not exist, it will be created. If it exists
652 * and a matching shortcut named already exists in the file,
653 * a new one will not be appended.
655 * In an ideal world this function would not need aShortcutsLogDir
656 * passed to it, but it is called by at least one function that runs
657 * asynchronously, and is therefore unable to use nsDirectoryService
658 * to look it up itself.
660 static nsresult WriteShortcutToLog(nsIFile* aShortcutsLogDir,
661 KNOWNFOLDERID aFolderId,
662 const nsAString& aShortcutName) {
663 // the section inside the shortcuts log
664 nsAutoCString section;
665 // the shortcuts log wants "Programs" shortcuts in its "STARTMENU" section
666 if (aFolderId == FOLDERID_CommonPrograms || aFolderId == FOLDERID_Programs) {
667 section.Assign("STARTMENU");
668 } else if (aFolderId == FOLDERID_PublicDesktop ||
669 aFolderId == FOLDERID_Desktop) {
670 section.Assign("DESKTOP");
671 } else {
672 return NS_ERROR_INVALID_ARG;
675 nsCOMPtr<nsIFile> shortcutsLog;
676 nsresult rv = aShortcutsLogDir->GetParent(getter_AddRefs(shortcutsLog));
677 NS_ENSURE_SUCCESS(rv, rv);
679 nsAutoCString appName;
680 nsCOMPtr<nsIXULAppInfo> appInfo =
681 do_GetService("@mozilla.org/xre/app-info;1");
682 rv = appInfo->GetName(appName);
683 NS_ENSURE_SUCCESS(rv, rv);
685 auto userSid = GetCurrentUserStringSid();
686 if (!userSid) {
687 return NS_ERROR_FILE_NOT_FOUND;
690 nsAutoString filename;
691 filename.AppendPrintf("%s_%ls_shortcuts.ini", appName.get(), userSid.get());
692 rv = shortcutsLog->Append(filename);
693 NS_ENSURE_SUCCESS(rv, rv);
695 nsINIParser parser;
696 bool fileExists = false;
697 bool shortcutsLogEntryExists = false;
698 nsAutoCString keyName, shortcutName;
699 shortcutName = NS_ConvertUTF16toUTF8(aShortcutName);
701 shortcutsLog->IsFile(&fileExists);
702 // if the shortcuts log exists, find either an existing matching
703 // entry, or the next available shortcut index
704 if (fileExists) {
705 rv = parser.Init(shortcutsLog);
706 NS_ENSURE_SUCCESS(rv, rv);
708 nsCString iniShortcut;
709 // surely we'll never need more than 10 shortcuts in one section...
710 for (int i = 0; i < 10; i++) {
711 keyName.AssignLiteral("Shortcut");
712 keyName.AppendInt(i);
713 rv = parser.GetString(section.get(), keyName.get(), iniShortcut);
714 if (NS_FAILED(rv)) {
715 // we found an unused index
716 break;
717 } else if (iniShortcut.Equals(shortcutName)) {
718 shortcutsLogEntryExists = true;
721 // otherwise, this is safe to use
722 } else {
723 keyName.AssignLiteral("Shortcut0");
726 if (!shortcutsLogEntryExists) {
727 parser.SetString(section.get(), keyName.get(), shortcutName.get());
728 // We write this ourselves instead of using parser->WriteToFile because
729 // the INI parser in our uninstaller needs to read this, and only supports
730 // UTF-16LE encoding. nsINIParser does not support UTF-16.
731 nsAutoCString formatted;
732 parser.WriteToString(formatted);
733 FILE* writeFile;
734 rv = shortcutsLog->OpenANSIFileDesc("w,ccs=UTF-16LE", &writeFile);
735 NS_ENSURE_SUCCESS(rv, rv);
736 NS_ConvertUTF8toUTF16 formattedUTF16(formatted);
737 if (fwrite(formattedUTF16.get(), sizeof(wchar_t), formattedUTF16.Length(),
738 writeFile) != formattedUTF16.Length()) {
739 fclose(writeFile);
740 return NS_ERROR_FAILURE;
742 fclose(writeFile);
745 return NS_OK;
748 static nsresult CreateShortcutImpl(
749 nsIFile* aBinary, const CopyableTArray<nsString>& aArguments,
750 const nsAString& aDescription, nsIFile* aIconFile, uint16_t aIconIndex,
751 const nsAString& aAppUserModelId, KNOWNFOLDERID aShortcutFolder,
752 const nsAString& aShortcutName, const nsString& aShortcutFile,
753 nsIFile* aShortcutsLogDir) {
754 NS_ENSURE_ARG(aBinary);
755 NS_ENSURE_ARG(aIconFile);
757 nsresult rv =
758 WriteShortcutToLog(aShortcutsLogDir, aShortcutFolder, aShortcutName);
759 NS_ENSURE_SUCCESS(rv, rv);
761 RefPtr<IShellLinkW> link;
762 HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
763 IID_IShellLinkW, getter_AddRefs(link));
764 NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
766 nsString path(aBinary->NativePath());
767 link->SetPath(path.get());
769 wchar_t workingDir[MAX_PATH + 1];
770 wcscpy_s(workingDir, MAX_PATH + 1, aBinary->NativePath().get());
771 PathRemoveFileSpecW(workingDir);
772 link->SetWorkingDirectory(workingDir);
774 if (!aDescription.IsEmpty()) {
775 link->SetDescription(PromiseFlatString(aDescription).get());
778 // TODO: Properly escape quotes in the string, see bug 1604287.
779 nsString arguments;
780 for (auto& arg : aArguments) {
781 arguments.AppendPrintf("\"%S\" ", static_cast<const wchar_t*>(arg.get()));
784 link->SetArguments(arguments.get());
786 if (aIconFile) {
787 nsString icon(aIconFile->NativePath());
788 link->SetIconLocation(icon.get(), aIconIndex);
791 if (!aAppUserModelId.IsEmpty()) {
792 RefPtr<IPropertyStore> propStore;
793 hr = link->QueryInterface(IID_IPropertyStore, getter_AddRefs(propStore));
794 NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
796 PROPVARIANT pv;
797 if (FAILED(InitPropVariantFromString(
798 PromiseFlatString(aAppUserModelId).get(), &pv))) {
799 return NS_ERROR_FAILURE;
802 hr = propStore->SetValue(PKEY_AppUserModel_ID, pv);
803 PropVariantClear(&pv);
804 NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
806 hr = propStore->Commit();
807 NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
810 RefPtr<IPersistFile> persist;
811 hr = link->QueryInterface(IID_IPersistFile, getter_AddRefs(persist));
812 NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
814 hr = persist->Save(aShortcutFile.get(), TRUE);
815 NS_ENSURE_HRESULT(hr, NS_ERROR_FAILURE);
817 return NS_OK;
820 NS_IMETHODIMP
821 nsWindowsShellService::CreateShortcut(
822 nsIFile* aBinary, const nsTArray<nsString>& aArguments,
823 const nsAString& aDescription, nsIFile* aIconFile, uint16_t aIconIndex,
824 const nsAString& aAppUserModelId, const nsAString& aShortcutFolder,
825 const nsAString& aShortcutName, JSContext* aCx, dom::Promise** aPromise) {
826 if (!NS_IsMainThread()) {
827 return NS_ERROR_NOT_SAME_THREAD;
830 ErrorResult rv;
831 RefPtr<dom::Promise> promise =
832 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
834 if (MOZ_UNLIKELY(rv.Failed())) {
835 return rv.StealNSResult();
837 // In an ideal world we'd probably send along nsIFile pointers
838 // here, but it's easier to determine the needed shortcuts log
839 // entry with a KNOWNFOLDERID - so we pass this along instead
840 // and let CreateShortcutImpl take care of converting it to
841 // an nsIFile.
842 KNOWNFOLDERID folderId;
843 if (aShortcutFolder.Equals(L"Programs")) {
844 folderId = FOLDERID_Programs;
845 } else if (aShortcutFolder.Equals(L"Desktop")) {
846 folderId = FOLDERID_Desktop;
847 } else {
848 return NS_ERROR_INVALID_ARG;
851 nsCOMPtr<nsIFile> updRoot, shortcutsLogDir;
852 nsresult nsrv =
853 NS_GetSpecialDirectory(XRE_UPDATE_ROOT_DIR, getter_AddRefs(updRoot));
854 NS_ENSURE_SUCCESS(nsrv, nsrv);
855 nsrv = updRoot->GetParent(getter_AddRefs(shortcutsLogDir));
856 NS_ENSURE_SUCCESS(nsrv, nsrv);
858 nsCOMPtr<nsIFile> shortcutFile;
859 if (folderId == FOLDERID_Programs) {
860 nsrv = NS_GetSpecialDirectory(NS_WIN_PROGRAMS_DIR,
861 getter_AddRefs(shortcutFile));
862 } else if (folderId == FOLDERID_Desktop) {
863 nsrv =
864 NS_GetSpecialDirectory(NS_OS_DESKTOP_DIR, getter_AddRefs(shortcutFile));
865 } else {
866 return NS_ERROR_FILE_NOT_FOUND;
868 if (NS_FAILED(nsrv)) {
869 return NS_ERROR_FILE_NOT_FOUND;
871 shortcutFile->Append(aShortcutName);
873 auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
874 "CreateShortcut promise", promise);
876 nsCOMPtr<nsIFile> binary(aBinary);
877 nsCOMPtr<nsIFile> iconFile(aIconFile);
878 NS_DispatchBackgroundTask(
879 NS_NewRunnableFunction(
880 "CreateShortcut",
881 [binary, aArguments = CopyableTArray<nsString>(aArguments),
882 aDescription = nsString{aDescription}, iconFile, aIconIndex,
883 aAppUserModelId = nsString{aAppUserModelId}, folderId,
884 aShortcutFolder = nsString{aShortcutFolder},
885 aShortcutName = nsString{aShortcutName}, shortcutsLogDir,
886 shortcutFile, promiseHolder = std::move(promiseHolder)] {
887 nsresult rv = NS_ERROR_FAILURE;
888 HRESULT hr = CoInitialize(nullptr);
890 if (SUCCEEDED(hr)) {
891 rv = CreateShortcutImpl(
892 binary.get(), aArguments, aDescription, iconFile.get(),
893 aIconIndex, aAppUserModelId, folderId, aShortcutName,
894 shortcutFile->NativePath(), shortcutsLogDir.get());
895 CoUninitialize();
898 NS_DispatchToMainThread(NS_NewRunnableFunction(
899 "CreateShortcut callback",
900 [rv, shortcutFile, promiseHolder = std::move(promiseHolder)] {
901 dom::Promise* promise = promiseHolder.get()->get();
903 if (NS_SUCCEEDED(rv)) {
904 promise->MaybeResolve(shortcutFile->NativePath());
905 } else {
906 promise->MaybeReject(rv);
908 }));
910 NS_DISPATCH_EVENT_MAY_BLOCK);
912 promise.forget(aPromise);
913 return NS_OK;
916 NS_IMETHODIMP
917 nsWindowsShellService::GetLaunchOnLoginShortcuts(
918 nsTArray<nsString>& aShortcutPaths) {
919 aShortcutPaths.Clear();
921 // Get AppData\\Roaming folder using a known folder ID
922 RefPtr<IKnownFolderManager> fManager;
923 RefPtr<IKnownFolder> roamingAppData;
924 LPWSTR roamingAppDataW;
925 nsString roamingAppDataNS;
926 HRESULT hr =
927 CoCreateInstance(CLSID_KnownFolderManager, nullptr, CLSCTX_INPROC_SERVER,
928 IID_IKnownFolderManager, getter_AddRefs(fManager));
929 if (FAILED(hr)) {
930 return NS_ERROR_ABORT;
932 fManager->GetFolder(FOLDERID_RoamingAppData,
933 roamingAppData.StartAssignment());
934 hr = roamingAppData->GetPath(0, &roamingAppDataW);
935 if (FAILED(hr)) {
936 return NS_ERROR_FILE_NOT_FOUND;
939 // Append startup folder to AppData\\Roaming
940 roamingAppDataNS.Assign(roamingAppDataW);
941 CoTaskMemFree(roamingAppDataW);
942 nsString startupFolder =
943 roamingAppDataNS +
944 u"\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"_ns;
945 nsString startupFolderWildcard = startupFolder + u"\\*.lnk"_ns;
947 // Get known path for binary file for later comparison with shortcuts.
948 // Returns lowercase file path which should be fine for Windows as all
949 // directories and files are case-insensitive by default.
950 RefPtr<nsIFile> binFile;
951 nsString binPath;
952 nsresult rv = XRE_GetBinaryPath(binFile.StartAssignment());
953 if (FAILED(rv)) {
954 return NS_ERROR_FAILURE;
956 rv = binFile->GetPath(binPath);
957 if (FAILED(rv)) {
958 return NS_ERROR_FILE_UNRECOGNIZED_PATH;
961 // Check for if first file exists with a shortcut extension (.lnk)
962 WIN32_FIND_DATAW ffd;
963 HANDLE fileHandle = INVALID_HANDLE_VALUE;
964 fileHandle = FindFirstFileW(startupFolderWildcard.get(), &ffd);
965 if (fileHandle == INVALID_HANDLE_VALUE) {
966 // This means that no files were found in the folder which
967 // doesn't imply an error. Most of the time the user won't
968 // have any shortcuts here.
969 return NS_OK;
972 do {
973 // Extract shortcut target path from every
974 // shortcut in the startup folder.
975 nsString fileName(ffd.cFileName);
976 RefPtr<IShellLinkW> link;
977 RefPtr<IPersistFile> ppf;
978 nsString target;
979 target.SetLength(MAX_PATH);
980 CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
981 IID_IShellLinkW, getter_AddRefs(link));
982 hr = link->QueryInterface(IID_IPersistFile, getter_AddRefs(ppf));
983 if (NS_WARN_IF(FAILED(hr))) {
984 continue;
986 nsString filePath = startupFolder + u"\\"_ns + fileName;
987 hr = ppf->Load(filePath.get(), STGM_READ);
988 if (NS_WARN_IF(FAILED(hr))) {
989 continue;
991 hr = link->GetPath(target.get(), MAX_PATH, nullptr, 0);
992 if (NS_WARN_IF(FAILED(hr))) {
993 continue;
996 // If shortcut target matches known binary file value
997 // then add the path to the shortcut as a valid
998 // startup shortcut. This has to be a substring search as
999 // the user could have added unknown command line arguments
1000 // to the shortcut.
1001 if (_wcsnicmp(target.get(), binPath.get(), binPath.Length()) == 0) {
1002 aShortcutPaths.AppendElement(filePath);
1004 } while (FindNextFile(fileHandle, &ffd) != 0);
1005 FindClose(fileHandle);
1006 return NS_OK;
1009 // Look for any installer-created shortcuts in the given location that match
1010 // the given AUMID and EXE Path. If one is found, output its path.
1012 // NOTE: DO NOT USE if a false negative (mismatch) is unacceptable.
1013 // aExePath is compared directly to the path retrieved from the shortcut.
1014 // Due to the presence of symlinks or other filesystem issues, it's possible
1015 // for different paths to refer to the same file, which would cause the check
1016 // to fail.
1017 // This should rarely be an issue as we are most likely to be run from a path
1018 // written by the installer (shortcut, association, launch from installer),
1019 // which also wrote the shortcuts. But it is possible.
1021 // aCSIDL the CSIDL of the directory to look for matching shortcuts in
1022 // aAUMID the AUMID to check for
1023 // aExePath the target exe path to check for, should be a long path where
1024 // possible
1025 // aShortcutSubstring a substring to limit which shortcuts in aCSIDL are
1026 // inspected for a match. Only shortcuts whose filename
1027 // contains this substring will be considered
1028 // aShortcutPath outparam, set to matching shortcut path if NS_OK is returned.
1030 // Returns
1031 // NS_ERROR_FAILURE on errors before any shortcuts were loaded
1032 // NS_ERROR_FILE_NOT_FOUND if no shortcuts matching aShortcutSubstring exist
1033 // NS_ERROR_FILE_ALREADY_EXISTS if shortcuts were found but did not match
1034 // aAUMID or aExePath
1035 // NS_OK if a matching shortcut is found
1036 static nsresult GetMatchingShortcut(int aCSIDL, const nsAString& aAUMID,
1037 const wchar_t aExePath[MAXPATHLEN],
1038 const nsAString& aShortcutSubstring,
1039 /* out */ nsAutoString& aShortcutPath) {
1040 nsresult result = NS_ERROR_FAILURE;
1042 wchar_t folderPath[MAX_PATH] = {};
1043 HRESULT hr = SHGetFolderPathW(nullptr, aCSIDL, nullptr, SHGFP_TYPE_CURRENT,
1044 folderPath);
1045 if (NS_WARN_IF(FAILED(hr))) {
1046 return NS_ERROR_FAILURE;
1048 if (wcscat_s(folderPath, MAX_PATH, L"\\") != 0) {
1049 return NS_ERROR_FAILURE;
1052 // Get list of shortcuts in aCSIDL
1053 nsAutoString pattern(folderPath);
1054 pattern.AppendLiteral("*.lnk");
1056 WIN32_FIND_DATAW findData = {};
1057 HANDLE hFindFile = FindFirstFileW(pattern.get(), &findData);
1058 if (hFindFile == INVALID_HANDLE_VALUE) {
1059 Unused << NS_WARN_IF(GetLastError() != ERROR_FILE_NOT_FOUND);
1060 return NS_ERROR_FILE_NOT_FOUND;
1062 // Past this point we don't return until the end of the function,
1063 // when FindClose() is called.
1065 // todo: improve return values here
1066 do {
1067 // Skip any that don't contain aShortcutSubstring
1068 // This is a case sensitive comparison, but that's probably fine for
1069 // the vast majority of cases -- and certainly for all the ones where
1070 // a shortcut was created by the installer.
1071 if (StrStrIW(findData.cFileName, aShortcutSubstring.Data()) == NULL) {
1072 continue;
1075 nsAutoString path(folderPath);
1076 path.Append(findData.cFileName);
1078 // Create a shell link object for loading the shortcut
1079 RefPtr<IShellLinkW> link;
1080 HRESULT hr =
1081 CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
1082 IID_IShellLinkW, getter_AddRefs(link));
1083 if (NS_WARN_IF(FAILED(hr))) {
1084 continue;
1087 // Load
1088 RefPtr<IPersistFile> persist;
1089 hr = link->QueryInterface(IID_IPersistFile, getter_AddRefs(persist));
1090 if (NS_WARN_IF(FAILED(hr))) {
1091 continue;
1094 hr = persist->Load(path.get(), STGM_READ);
1095 if (FAILED(hr)) {
1096 if (NS_WARN_IF(hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))) {
1097 // empty branch, result unchanged but warning issued
1098 } else {
1099 // If we've ever gotten past this block, result will already be
1100 // NS_ERROR_FILE_ALREADY_EXISTS, which is a more accurate error
1101 // than NS_ERROR_FILE_NOT_FOUND.
1102 if (result != NS_ERROR_FILE_ALREADY_EXISTS) {
1103 result = NS_ERROR_FILE_NOT_FOUND;
1106 continue;
1108 result = NS_ERROR_FILE_ALREADY_EXISTS;
1110 // Check the AUMID
1111 RefPtr<IPropertyStore> propStore;
1112 hr = link->QueryInterface(IID_IPropertyStore, getter_AddRefs(propStore));
1113 if (NS_WARN_IF(FAILED(hr))) {
1114 continue;
1117 PROPVARIANT pv;
1118 hr = propStore->GetValue(PKEY_AppUserModel_ID, &pv);
1119 if (NS_WARN_IF(FAILED(hr))) {
1120 continue;
1123 wchar_t storedAUMID[MAX_PATH];
1124 hr = PropVariantToString(pv, storedAUMID, MAX_PATH);
1125 PropVariantClear(&pv);
1126 if (NS_WARN_IF(FAILED(hr))) {
1127 continue;
1130 if (!aAUMID.Equals(storedAUMID)) {
1131 continue;
1134 // Check the exe path
1135 static_assert(MAXPATHLEN == MAX_PATH);
1136 wchar_t storedExePath[MAX_PATH] = {};
1137 // With no flags GetPath gets a long path
1138 hr = link->GetPath(storedExePath, ArrayLength(storedExePath), nullptr, 0);
1139 if (FAILED(hr) || hr == S_FALSE) {
1140 continue;
1142 // Case insensitive path comparison
1143 if (wcsnicmp(storedExePath, aExePath, MAXPATHLEN) == 0) {
1144 aShortcutPath.Assign(path);
1145 result = NS_OK;
1146 break;
1148 } while (FindNextFileW(hFindFile, &findData));
1150 FindClose(hFindFile);
1152 return result;
1155 static nsresult FindMatchingShortcut(const nsAString& aAppUserModelId,
1156 const nsAString& aShortcutSubstring,
1157 const bool aPrivateBrowsing,
1158 nsAutoString& aShortcutPath) {
1159 wchar_t exePath[MAXPATHLEN] = {};
1160 if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath)))) {
1161 return NS_ERROR_FAILURE;
1164 if (aPrivateBrowsing) {
1165 if (!PathRemoveFileSpecW(exePath)) {
1166 return NS_ERROR_FAILURE;
1168 if (!PathAppendW(exePath, L"private_browsing.exe")) {
1169 return NS_ERROR_FAILURE;
1173 int shortcutCSIDLs[] = {CSIDL_COMMON_PROGRAMS, CSIDL_PROGRAMS,
1174 CSIDL_COMMON_DESKTOPDIRECTORY,
1175 CSIDL_DESKTOPDIRECTORY};
1176 for (int shortcutCSIDL : shortcutCSIDLs) {
1177 // GetMatchingShortcut may fail when the exe path doesn't match, even
1178 // if it refers to the same file. This should be rare, and the worst
1179 // outcome would be failure to pin, so the risk is acceptable.
1180 nsresult rv = GetMatchingShortcut(shortcutCSIDL, aAppUserModelId, exePath,
1181 aShortcutSubstring, aShortcutPath);
1182 if (NS_SUCCEEDED(rv)) {
1183 return NS_OK;
1187 return NS_ERROR_FILE_NOT_FOUND;
1190 static bool HasMatchingShortcutImpl(const nsAString& aAppUserModelId,
1191 const bool aPrivateBrowsing,
1192 const nsAutoString& aShortcutSubstring) {
1193 // unused by us, but required
1194 nsAutoString shortcutPath;
1195 nsresult rv = FindMatchingShortcut(aAppUserModelId, aShortcutSubstring,
1196 aPrivateBrowsing, shortcutPath);
1197 if (SUCCEEDED(rv)) {
1198 return true;
1201 return false;
1204 NS_IMETHODIMP nsWindowsShellService::HasMatchingShortcut(
1205 const nsAString& aAppUserModelId, const bool aPrivateBrowsing,
1206 JSContext* aCx, dom::Promise** aPromise) {
1207 if (!NS_IsMainThread()) {
1208 return NS_ERROR_NOT_SAME_THREAD;
1211 ErrorResult rv;
1212 RefPtr<dom::Promise> promise =
1213 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
1215 if (MOZ_UNLIKELY(rv.Failed())) {
1216 return rv.StealNSResult();
1219 auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
1220 "HasMatchingShortcut promise", promise);
1222 NS_DispatchBackgroundTask(
1223 NS_NewRunnableFunction(
1224 "HasMatchingShortcut",
1225 [aAppUserModelId = nsString{aAppUserModelId}, aPrivateBrowsing,
1226 promiseHolder = std::move(promiseHolder)] {
1227 bool rv = false;
1228 HRESULT hr = CoInitialize(nullptr);
1230 if (SUCCEEDED(hr)) {
1231 nsAutoString shortcutSubstring;
1232 shortcutSubstring.AssignLiteral(MOZ_APP_DISPLAYNAME);
1233 rv = HasMatchingShortcutImpl(aAppUserModelId, aPrivateBrowsing,
1234 shortcutSubstring);
1235 CoUninitialize();
1238 NS_DispatchToMainThread(NS_NewRunnableFunction(
1239 "HasMatchingShortcut callback",
1240 [rv, promiseHolder = std::move(promiseHolder)] {
1241 dom::Promise* promise = promiseHolder.get()->get();
1243 promise->MaybeResolve(rv);
1244 }));
1246 NS_DISPATCH_EVENT_MAY_BLOCK);
1248 promise.forget(aPromise);
1249 return NS_OK;
1252 static bool IsCurrentAppPinnedToTaskbarSync(const nsAString& aumid) {
1253 // There are two shortcut targets that we created. One always matches the
1254 // binary we're running as (eg: firefox.exe). The other is the wrapper
1255 // for launching in Private Browsing mode. We need to inspect shortcuts
1256 // that point at either of these to accurately judge whether or not
1257 // the app is pinned with the given AUMID.
1258 wchar_t exePath[MAXPATHLEN] = {};
1259 wchar_t pbExePath[MAXPATHLEN] = {};
1261 if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath)))) {
1262 return false;
1265 wcscpy_s(pbExePath, MAXPATHLEN, exePath);
1266 if (!PathRemoveFileSpecW(pbExePath)) {
1267 return false;
1269 if (!PathAppendW(pbExePath, L"private_browsing.exe")) {
1270 return false;
1273 wchar_t folderChars[MAX_PATH] = {};
1274 HRESULT hr = SHGetFolderPathW(nullptr, CSIDL_APPDATA, nullptr,
1275 SHGFP_TYPE_CURRENT, folderChars);
1276 if (NS_WARN_IF(FAILED(hr))) {
1277 return false;
1280 nsAutoString folder;
1281 folder.Assign(folderChars);
1282 if (NS_WARN_IF(folder.IsEmpty())) {
1283 return false;
1285 if (folder[folder.Length() - 1] != '\\') {
1286 folder.AppendLiteral("\\");
1288 folder.AppendLiteral(
1289 "Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar");
1290 nsAutoString pattern;
1291 pattern.Assign(folder);
1292 pattern.AppendLiteral("\\*.lnk");
1294 WIN32_FIND_DATAW findData = {};
1295 HANDLE hFindFile = FindFirstFileW(pattern.get(), &findData);
1296 if (hFindFile == INVALID_HANDLE_VALUE) {
1297 Unused << NS_WARN_IF(GetLastError() != ERROR_FILE_NOT_FOUND);
1298 return false;
1300 // Past this point we don't return until the end of the function,
1301 // when FindClose() is called.
1303 // Check all shortcuts until a match is found
1304 bool isPinned = false;
1305 do {
1306 nsAutoString fileName;
1307 fileName.Assign(folder);
1308 fileName.AppendLiteral("\\");
1309 fileName.Append(findData.cFileName);
1311 // Create a shell link object for loading the shortcut
1312 RefPtr<IShellLinkW> link;
1313 HRESULT hr =
1314 CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
1315 IID_IShellLinkW, getter_AddRefs(link));
1316 if (NS_WARN_IF(FAILED(hr))) {
1317 continue;
1320 // Load
1321 RefPtr<IPersistFile> persist;
1322 hr = link->QueryInterface(IID_IPersistFile, getter_AddRefs(persist));
1323 if (NS_WARN_IF(FAILED(hr))) {
1324 continue;
1327 hr = persist->Load(fileName.get(), STGM_READ);
1328 if (NS_WARN_IF(FAILED(hr))) {
1329 continue;
1332 // Check the exe path
1333 static_assert(MAXPATHLEN == MAX_PATH);
1334 wchar_t storedExePath[MAX_PATH] = {};
1335 // With no flags GetPath gets a long path
1336 hr = link->GetPath(storedExePath, ArrayLength(storedExePath), nullptr, 0);
1337 if (FAILED(hr) || hr == S_FALSE) {
1338 continue;
1340 // Case insensitive path comparison
1341 // NOTE: Because this compares the path directly, it is possible to
1342 // have a false negative mismatch.
1343 if (wcsnicmp(storedExePath, exePath, MAXPATHLEN) == 0 ||
1344 wcsnicmp(storedExePath, pbExePath, MAXPATHLEN) == 0) {
1345 RefPtr<IPropertyStore> propStore;
1346 hr = link->QueryInterface(IID_IPropertyStore, getter_AddRefs(propStore));
1347 if (NS_WARN_IF(FAILED(hr))) {
1348 continue;
1351 PROPVARIANT pv;
1352 hr = propStore->GetValue(PKEY_AppUserModel_ID, &pv);
1353 if (NS_WARN_IF(FAILED(hr))) {
1354 continue;
1357 wchar_t storedAUMID[MAX_PATH];
1358 hr = PropVariantToString(pv, storedAUMID, MAX_PATH);
1359 PropVariantClear(&pv);
1360 if (NS_WARN_IF(FAILED(hr))) {
1361 continue;
1364 if (aumid.Equals(storedAUMID)) {
1365 isPinned = true;
1366 break;
1369 } while (FindNextFileW(hFindFile, &findData));
1371 FindClose(hFindFile);
1373 return isPinned;
1376 static nsresult ManageShortcutTaskbarPins(bool aCheckOnly, bool aPinType,
1377 const nsAString& aShortcutPath) {
1378 // This enum is likely only used for Windows telemetry, INT_MAX is chosen to
1379 // avoid confusion with existing uses.
1380 enum PINNEDLISTMODIFYCALLER { PLMC_INT_MAX = INT_MAX };
1382 // The types below, and the idea of using IPinnedList3::Modify,
1383 // are thanks to Gee Law <https://geelaw.blog/entries/msedge-pins/>
1384 static constexpr GUID CLSID_TaskbandPin = {
1385 0x90aa3a4e,
1386 0x1cba,
1387 0x4233,
1388 {0xb8, 0xbb, 0x53, 0x57, 0x73, 0xd4, 0x84, 0x49}};
1390 static constexpr GUID IID_IPinnedList3 = {
1391 0x0dd79ae2,
1392 0xd156,
1393 0x45d4,
1394 {0x9e, 0xeb, 0x3b, 0x54, 0x97, 0x69, 0xe9, 0x40}};
1396 struct IPinnedList3Vtbl;
1397 struct IPinnedList3 {
1398 IPinnedList3Vtbl* vtbl;
1401 typedef ULONG STDMETHODCALLTYPE ReleaseFunc(IPinnedList3 * that);
1402 typedef HRESULT STDMETHODCALLTYPE ModifyFunc(
1403 IPinnedList3 * that, PCIDLIST_ABSOLUTE unpin, PCIDLIST_ABSOLUTE pin,
1404 PINNEDLISTMODIFYCALLER caller);
1406 struct IPinnedList3Vtbl {
1407 void* QueryInterface; // 0
1408 void* AddRef; // 1
1409 ReleaseFunc* Release; // 2
1410 void* Other[13]; // 3-15
1411 ModifyFunc* Modify; // 16
1414 struct ILFreeDeleter {
1415 void operator()(LPITEMIDLIST aPtr) {
1416 if (aPtr) {
1417 ILFree(aPtr);
1422 mozilla::UniquePtr<__unaligned ITEMIDLIST, ILFreeDeleter> path(
1423 ILCreateFromPathW(nsString(aShortcutPath).get()));
1424 if (NS_WARN_IF(!path)) {
1425 return NS_ERROR_FILE_NOT_FOUND;
1428 IPinnedList3* pinnedList = nullptr;
1429 HRESULT hr = CoCreateInstance(CLSID_TaskbandPin, NULL, CLSCTX_INPROC_SERVER,
1430 IID_IPinnedList3, (void**)&pinnedList);
1431 if (FAILED(hr) || !pinnedList) {
1432 return NS_ERROR_NOT_AVAILABLE;
1435 if (!aCheckOnly) {
1436 hr = pinnedList->vtbl->Modify(pinnedList, aPinType ? NULL : path.get(),
1437 aPinType ? path.get() : NULL, PLMC_INT_MAX);
1440 pinnedList->vtbl->Release(pinnedList);
1442 if (FAILED(hr)) {
1443 return NS_ERROR_FILE_ACCESS_DENIED;
1445 return NS_OK;
1448 NS_IMETHODIMP
1449 nsWindowsShellService::PinShortcutToTaskbar(const nsAString& aShortcutPath) {
1450 const bool pinType = true; // true means pin
1451 const bool runInTestMode = false;
1452 return ManageShortcutTaskbarPins(runInTestMode, pinType, aShortcutPath);
1455 NS_IMETHODIMP
1456 nsWindowsShellService::UnpinShortcutFromTaskbar(
1457 const nsAString& aShortcutPath) {
1458 const bool pinType = false; // false means unpin
1459 const bool runInTestMode = false;
1460 return ManageShortcutTaskbarPins(runInTestMode, pinType, aShortcutPath);
1463 // Ensure that the supplied name doesn't have invalid characters.
1464 static void ValidateFilename(nsAString& aFilename) {
1465 nsCOMPtr<nsIMIMEService> mimeService = do_GetService("@mozilla.org/mime;1");
1466 if (NS_WARN_IF(!mimeService)) {
1467 aFilename.Truncate();
1468 return;
1471 uint32_t flags = nsIMIMEService::VALIDATE_SANITIZE_ONLY |
1472 nsIMIMEService::VALIDATE_DONT_COLLAPSE_WHITESPACE;
1474 nsAutoString outFilename;
1475 mimeService->ValidateFileNameForSaving(aFilename, EmptyCString(), flags,
1476 outFilename);
1477 aFilename = outFilename;
1480 NS_IMETHODIMP
1481 nsWindowsShellService::GetTaskbarTabShortcutPath(const nsAString& aShortcutName,
1482 nsAString& aRetPath) {
1483 nsAutoString sanitizedShortcutName(aShortcutName);
1484 ValidateFilename(sanitizedShortcutName);
1485 if (sanitizedShortcutName != aShortcutName) {
1486 return NS_ERROR_FILE_INVALID_PATH;
1489 // The taskbar tab shortcut will always be in
1490 // %APPDATA%\Microsoft\Windows\Start Menu\Programs
1491 RefPtr<IKnownFolderManager> fManager;
1492 RefPtr<IKnownFolder> progFolder;
1493 LPWSTR progFolderW;
1494 nsString progFolderNS;
1495 HRESULT hr =
1496 CoCreateInstance(CLSID_KnownFolderManager, nullptr, CLSCTX_INPROC_SERVER,
1497 IID_IKnownFolderManager, getter_AddRefs(fManager));
1498 if (NS_WARN_IF(FAILED(hr))) {
1499 return NS_ERROR_ABORT;
1501 fManager->GetFolder(FOLDERID_Programs, progFolder.StartAssignment());
1502 hr = progFolder->GetPath(0, &progFolderW);
1503 if (FAILED(hr)) {
1504 return NS_ERROR_FILE_NOT_FOUND;
1506 progFolderNS.Assign(progFolderW);
1507 aRetPath = progFolderNS + u"\\"_ns + aShortcutName + u".lnk"_ns;
1508 return NS_OK;
1511 NS_IMETHODIMP
1512 nsWindowsShellService::GetTaskbarTabPins(nsTArray<nsString>& aShortcutPaths) {
1513 #ifdef __MINGW32__
1514 return NS_ERROR_NOT_IMPLEMENTED;
1515 #else
1516 aShortcutPaths.Clear();
1518 // Get AppData\\Roaming folder using a known folder ID
1519 RefPtr<IKnownFolderManager> fManager;
1520 RefPtr<IKnownFolder> roamingAppData;
1521 LPWSTR roamingAppDataW;
1522 nsString roamingAppDataNS;
1523 HRESULT hr =
1524 CoCreateInstance(CLSID_KnownFolderManager, nullptr, CLSCTX_INPROC_SERVER,
1525 IID_IKnownFolderManager, getter_AddRefs(fManager));
1526 if (NS_WARN_IF(FAILED(hr))) {
1527 return NS_ERROR_ABORT;
1529 fManager->GetFolder(FOLDERID_RoamingAppData,
1530 roamingAppData.StartAssignment());
1531 hr = roamingAppData->GetPath(0, &roamingAppDataW);
1532 if (FAILED(hr)) {
1533 return NS_ERROR_FILE_NOT_FOUND;
1536 // Append taskbar pins folder to AppData\\Roaming
1537 roamingAppDataNS.Assign(roamingAppDataW);
1538 CoTaskMemFree(roamingAppDataW);
1539 nsString taskbarFolder =
1540 roamingAppDataNS + u"\\Microsoft\\Windows\\Start Menu\\Programs"_ns;
1541 nsString taskbarFolderWildcard = taskbarFolder + u"\\*.lnk"_ns;
1543 // Get known path for binary file for later comparison with shortcuts.
1544 // Returns lowercase file path which should be fine for Windows as all
1545 // directories and files are case-insensitive by default.
1546 RefPtr<nsIFile> binFile;
1547 nsString binPath;
1548 nsresult rv = XRE_GetBinaryPath(binFile.StartAssignment());
1549 if (NS_WARN_IF(FAILED(rv))) {
1550 return NS_ERROR_FAILURE;
1552 rv = binFile->GetPath(binPath);
1553 if (NS_WARN_IF(FAILED(rv))) {
1554 return NS_ERROR_FILE_UNRECOGNIZED_PATH;
1557 // Check for if first file exists with a shortcut extension (.lnk)
1558 WIN32_FIND_DATAW ffd;
1559 HANDLE fileHandle = INVALID_HANDLE_VALUE;
1560 fileHandle = FindFirstFileW(taskbarFolderWildcard.get(), &ffd);
1561 if (fileHandle == INVALID_HANDLE_VALUE) {
1562 // This means that no files were found in the folder which
1563 // doesn't imply an error.
1564 return NS_OK;
1567 do {
1568 // Extract shortcut target path from every
1569 // shortcut in the taskbar pins folder.
1570 nsString fileName(ffd.cFileName);
1571 RefPtr<IShellLinkW> link;
1572 RefPtr<IPropertyStore> pps;
1573 nsString target;
1574 target.SetLength(MAX_PATH);
1575 hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
1576 IID_IShellLinkW, getter_AddRefs(link));
1577 if (NS_WARN_IF(FAILED(hr))) {
1578 continue;
1580 nsString filePath = taskbarFolder + u"\\"_ns + fileName;
1581 if (NS_WARN_IF(FAILED(hr))) {
1582 continue;
1585 // After loading shortcut, search through arguments to find if
1586 // it is a taskbar tab shortcut.
1587 hr = SHGetPropertyStoreFromParsingName(filePath.get(), nullptr,
1588 GPS_READWRITE, IID_IPropertyStore,
1589 getter_AddRefs(pps));
1590 if (NS_WARN_IF(FAILED(hr)) || pps == nullptr) {
1591 continue;
1593 PROPVARIANT propVar;
1594 PropVariantInit(&propVar);
1595 auto cleanupPropVariant =
1596 MakeScopeExit([&] { PropVariantClear(&propVar); });
1597 // Get the PKEY_Link_Arguments property
1598 hr = pps->GetValue(PKEY_Link_Arguments, &propVar);
1599 if (NS_WARN_IF(FAILED(hr))) {
1600 continue;
1602 // Check if the argument matches
1603 if (!(propVar.vt == VT_LPWSTR && propVar.pwszVal != nullptr &&
1604 wcsstr(propVar.pwszVal, L"-taskbar-tab") != nullptr)) {
1605 continue;
1608 hr = link->GetPath(target.get(), MAX_PATH, nullptr, 0);
1609 if (NS_WARN_IF(FAILED(hr))) {
1610 continue;
1613 // If shortcut target matches known binary file value
1614 // then add the path to the shortcut as a valid
1615 // shortcut. This has to be a substring search as
1616 // the user could have added unknown command line arguments
1617 // to the shortcut.
1618 if (_wcsnicmp(target.get(), binPath.get(), binPath.Length()) == 0) {
1619 aShortcutPaths.AppendElement(filePath);
1621 } while (FindNextFile(fileHandle, &ffd) != 0);
1622 FindClose(fileHandle);
1623 return NS_OK;
1624 #endif
1627 static nsresult PinCurrentAppToTaskbarWin10(bool aCheckOnly,
1628 const nsAString& aAppUserModelId,
1629 nsAutoString aShortcutPath) {
1630 // The behavior here is identical if we're only checking or if we try to pin
1631 // but the app is already pinned so we update the variable accordingly.
1632 if (!aCheckOnly) {
1633 aCheckOnly = IsCurrentAppPinnedToTaskbarSync(aAppUserModelId);
1635 const bool pinType = true; // true means pin
1636 return ManageShortcutTaskbarPins(aCheckOnly, pinType, aShortcutPath);
1639 static nsresult PinCurrentAppToTaskbarImpl(
1640 bool aCheckOnly, bool aPrivateBrowsing, const nsAString& aAppUserModelId,
1641 const nsAString& aShortcutName, const nsAString& aShortcutSubstring,
1642 nsIFile* aShortcutsLogDir, nsIFile* aGreDir, nsIFile* aProgramsDir) {
1643 MOZ_DIAGNOSTIC_ASSERT(
1644 !NS_IsMainThread(),
1645 "PinCurrentAppToTaskbarImpl should be called off main thread only");
1647 nsAutoString shortcutPath;
1648 nsresult rv = FindMatchingShortcut(aAppUserModelId, aShortcutSubstring,
1649 aPrivateBrowsing, shortcutPath);
1650 if (NS_FAILED(rv)) {
1651 shortcutPath.Truncate();
1653 if (shortcutPath.IsEmpty()) {
1654 if (aCheckOnly) {
1655 // Later checks rely on a shortcut already existing.
1656 // We don't want to create a shortcut in check only mode
1657 // so the best we can do is assume those parts will work.
1658 return NS_OK;
1661 nsAutoString linkName(aShortcutName);
1663 nsCOMPtr<nsIFile> exeFile(aGreDir);
1664 if (aPrivateBrowsing) {
1665 nsAutoString pbExeStr(PRIVATE_BROWSING_BINARY);
1666 nsresult rv = exeFile->Append(pbExeStr);
1667 if (!NS_SUCCEEDED(rv)) {
1668 return NS_ERROR_FAILURE;
1670 } else {
1671 wchar_t exePath[MAXPATHLEN] = {};
1672 if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath)))) {
1673 return NS_ERROR_FAILURE;
1675 nsAutoString exeStr(exePath);
1676 nsresult rv = NS_NewLocalFile(exeStr, true, getter_AddRefs(exeFile));
1677 if (!NS_SUCCEEDED(rv)) {
1678 return NS_ERROR_FILE_NOT_FOUND;
1682 nsCOMPtr<nsIFile> shortcutFile(aProgramsDir);
1683 shortcutFile->Append(aShortcutName);
1684 shortcutPath.Assign(shortcutFile->NativePath());
1686 nsTArray<nsString> arguments;
1687 rv = CreateShortcutImpl(exeFile, arguments, aShortcutName, exeFile,
1688 // Icon indexes are defined as Resource IDs, but
1689 // CreateShortcutImpl needs an index.
1690 IDI_APPICON - 1, aAppUserModelId, FOLDERID_Programs,
1691 linkName, shortcutFile->NativePath(),
1692 aShortcutsLogDir);
1693 if (!NS_SUCCEEDED(rv)) {
1694 return NS_ERROR_FILE_NOT_FOUND;
1698 return PinCurrentAppToTaskbarWin10(aCheckOnly, aAppUserModelId, shortcutPath);
1701 static nsresult PinCurrentAppToTaskbarAsyncImpl(bool aCheckOnly,
1702 bool aPrivateBrowsing,
1703 JSContext* aCx,
1704 dom::Promise** aPromise) {
1705 if (!NS_IsMainThread()) {
1706 return NS_ERROR_NOT_SAME_THREAD;
1709 // First available on 1809
1710 if (!IsWin10Sep2018UpdateOrLater()) {
1711 return NS_ERROR_NOT_AVAILABLE;
1714 ErrorResult rv;
1715 RefPtr<dom::Promise> promise =
1716 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
1718 if (MOZ_UNLIKELY(rv.Failed())) {
1719 return rv.StealNSResult();
1722 nsAutoString aumid;
1723 if (NS_WARN_IF(!mozilla::widget::WinTaskbar::GenerateAppUserModelID(
1724 aumid, aPrivateBrowsing))) {
1725 return NS_ERROR_FAILURE;
1728 // NOTE: In the installer, non-private shortcuts are named
1729 // "${BrandShortName}.lnk". This is set from MOZ_APP_DISPLAYNAME in
1730 // defines.nsi.in. (Except in dev edition where it's explicitly set to
1731 // "Firefox Developer Edition" in branding.nsi, which matches
1732 // MOZ_APP_DISPLAYNAME in aurora/configure.sh.)
1734 // If this changes, we could expand this to check shortcuts_log.ini,
1735 // which records the name of the shortcuts as created by the installer.
1737 // Private shortcuts are not created by the installer (they're created
1738 // upon user request, ultimately by CreateShortcutImpl, and recorded in
1739 // a separate shortcuts log. As with non-private shortcuts they have a known
1740 // name - so there's no need to look through logs to find them.
1741 nsAutoString shortcutName;
1742 if (aPrivateBrowsing) {
1743 nsTArray<nsCString> resIds = {
1744 "branding/brand.ftl"_ns,
1745 "browser/browser.ftl"_ns,
1747 RefPtr<Localization> l10n = Localization::Create(resIds, true);
1748 nsAutoCString pbStr;
1749 IgnoredErrorResult rv;
1750 l10n->FormatValueSync("private-browsing-shortcut-text-2"_ns, {}, pbStr, rv);
1751 shortcutName.Append(NS_ConvertUTF8toUTF16(pbStr));
1752 shortcutName.AppendLiteral(".lnk");
1753 } else {
1754 shortcutName.AppendLiteral(MOZ_APP_DISPLAYNAME ".lnk");
1757 nsCOMPtr<nsIFile> greDir, updRoot, programsDir, shortcutsLogDir;
1758 nsresult nsrv = NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(greDir));
1759 NS_ENSURE_SUCCESS(nsrv, nsrv);
1760 nsrv = NS_GetSpecialDirectory(XRE_UPDATE_ROOT_DIR, getter_AddRefs(updRoot));
1761 NS_ENSURE_SUCCESS(nsrv, nsrv);
1762 rv = NS_GetSpecialDirectory(NS_WIN_PROGRAMS_DIR, getter_AddRefs(programsDir));
1763 NS_ENSURE_SUCCESS(nsrv, nsrv);
1764 nsrv = updRoot->GetParent(getter_AddRefs(shortcutsLogDir));
1765 NS_ENSURE_SUCCESS(nsrv, nsrv);
1767 auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
1768 "CheckPinCurrentAppToTaskbarAsync promise", promise);
1770 NS_DispatchBackgroundTask(
1771 NS_NewRunnableFunction(
1772 "CheckPinCurrentAppToTaskbarAsync",
1773 [aCheckOnly, aPrivateBrowsing, shortcutName, aumid = nsString{aumid},
1774 shortcutsLogDir, greDir, programsDir,
1775 promiseHolder = std::move(promiseHolder)] {
1776 nsresult rv = NS_ERROR_FAILURE;
1777 HRESULT hr = CoInitialize(nullptr);
1779 if (SUCCEEDED(hr)) {
1780 nsAutoString shortcutSubstring;
1781 shortcutSubstring.AssignLiteral(MOZ_APP_DISPLAYNAME);
1782 rv = PinCurrentAppToTaskbarImpl(
1783 aCheckOnly, aPrivateBrowsing, aumid, shortcutName,
1784 shortcutSubstring, shortcutsLogDir.get(), greDir.get(),
1785 programsDir.get());
1786 CoUninitialize();
1789 NS_DispatchToMainThread(NS_NewRunnableFunction(
1790 "CheckPinCurrentAppToTaskbarAsync callback",
1791 [rv, promiseHolder = std::move(promiseHolder)] {
1792 dom::Promise* promise = promiseHolder.get()->get();
1794 if (NS_SUCCEEDED(rv)) {
1795 promise->MaybeResolveWithUndefined();
1796 } else {
1797 promise->MaybeReject(rv);
1799 }));
1801 NS_DISPATCH_EVENT_MAY_BLOCK);
1803 promise.forget(aPromise);
1804 return NS_OK;
1807 NS_IMETHODIMP
1808 nsWindowsShellService::PinCurrentAppToTaskbarAsync(bool aPrivateBrowsing,
1809 JSContext* aCx,
1810 dom::Promise** aPromise) {
1811 // https://bugzilla.mozilla.org/show_bug.cgi?id=1712628 tracks implementing
1812 // this for MSIX packages.
1813 if (widget::WinUtils::HasPackageIdentity()) {
1814 return NS_ERROR_NOT_IMPLEMENTED;
1817 return PinCurrentAppToTaskbarAsyncImpl(
1818 /* aCheckOnly */ false, aPrivateBrowsing, aCx, aPromise);
1821 NS_IMETHODIMP
1822 nsWindowsShellService::CheckPinCurrentAppToTaskbarAsync(
1823 bool aPrivateBrowsing, JSContext* aCx, dom::Promise** aPromise) {
1824 // https://bugzilla.mozilla.org/show_bug.cgi?id=1712628 tracks implementing
1825 // this for MSIX packages.
1826 if (widget::WinUtils::HasPackageIdentity()) {
1827 return NS_ERROR_NOT_IMPLEMENTED;
1830 return PinCurrentAppToTaskbarAsyncImpl(
1831 /* aCheckOnly = */ true, aPrivateBrowsing, aCx, aPromise);
1834 NS_IMETHODIMP
1835 nsWindowsShellService::IsCurrentAppPinnedToTaskbarAsync(
1836 const nsAString& aumid, JSContext* aCx, /* out */ dom::Promise** aPromise) {
1837 // https://bugzilla.mozilla.org/show_bug.cgi?id=1712628 tracks implementing
1838 // this for MSIX packages.
1839 if (widget::WinUtils::HasPackageIdentity()) {
1840 return NS_ERROR_NOT_IMPLEMENTED;
1843 if (!NS_IsMainThread()) {
1844 return NS_ERROR_NOT_SAME_THREAD;
1847 ErrorResult rv;
1848 RefPtr<dom::Promise> promise =
1849 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx), rv);
1850 if (MOZ_UNLIKELY(rv.Failed())) {
1851 return rv.StealNSResult();
1854 // A holder to pass the promise through the background task and back to
1855 // the main thread when finished.
1856 auto promiseHolder = MakeRefPtr<nsMainThreadPtrHolder<dom::Promise>>(
1857 "IsCurrentAppPinnedToTaskbarAsync promise", promise);
1859 // nsAString can't be captured by a lambda because it does not have a
1860 // public copy constructor
1861 nsAutoString capturedAumid(aumid);
1862 NS_DispatchBackgroundTask(
1863 NS_NewRunnableFunction(
1864 "IsCurrentAppPinnedToTaskbarAsync",
1865 [capturedAumid, promiseHolder = std::move(promiseHolder)] {
1866 bool isPinned = false;
1868 HRESULT hr = CoInitialize(nullptr);
1869 if (SUCCEEDED(hr)) {
1870 isPinned = IsCurrentAppPinnedToTaskbarSync(capturedAumid);
1871 CoUninitialize();
1874 // Dispatch back to the main thread to resolve the promise.
1875 NS_DispatchToMainThread(NS_NewRunnableFunction(
1876 "IsCurrentAppPinnedToTaskbarAsync callback",
1877 [isPinned, promiseHolder = std::move(promiseHolder)] {
1878 promiseHolder.get()->get()->MaybeResolve(isPinned);
1879 }));
1881 NS_DISPATCH_EVENT_MAY_BLOCK);
1883 promise.forget(aPromise);
1884 return NS_OK;
1887 NS_IMETHODIMP
1888 nsWindowsShellService::ClassifyShortcut(const nsAString& aPath,
1889 nsAString& aResult) {
1890 aResult.Truncate();
1892 nsAutoString shortcutPath(PromiseFlatString(aPath));
1894 // NOTE: On Windows 7, Start Menu pin shortcuts are stored under
1895 // "<FOLDERID_User Pinned>\StartMenu", but on Windows 10 they are just normal
1896 // Start Menu shortcuts. These both map to "StartMenu" for consistency,
1897 // rather than having a separate "StartMenuPins" which would only apply on
1898 // Win7.
1899 struct {
1900 KNOWNFOLDERID folderId;
1901 const char16_t* postfix;
1902 const char16_t* classification;
1903 } folders[] = {{FOLDERID_CommonStartMenu, u"\\", u"StartMenu"},
1904 {FOLDERID_StartMenu, u"\\", u"StartMenu"},
1905 {FOLDERID_PublicDesktop, u"\\", u"Desktop"},
1906 {FOLDERID_Desktop, u"\\", u"Desktop"},
1907 {FOLDERID_UserPinned, u"\\TaskBar\\", u"Taskbar"},
1908 {FOLDERID_UserPinned, u"\\StartMenu\\", u"StartMenu"}};
1910 for (size_t i = 0; i < ArrayLength(folders); ++i) {
1911 nsAutoString knownPath;
1913 // These flags are chosen to avoid I/O, see bug 1363398.
1914 DWORD flags =
1915 KF_FLAG_SIMPLE_IDLIST | KF_FLAG_DONT_VERIFY | KF_FLAG_NO_ALIAS;
1916 PWSTR rawPath = nullptr;
1918 if (FAILED(SHGetKnownFolderPath(folders[i].folderId, flags, nullptr,
1919 &rawPath))) {
1920 continue;
1923 knownPath = nsDependentString(rawPath);
1924 CoTaskMemFree(rawPath);
1926 knownPath.Append(folders[i].postfix);
1927 // Check if the shortcut path starts with the shell folder path.
1928 if (wcsnicmp(shortcutPath.get(), knownPath.get(), knownPath.Length()) ==
1929 0) {
1930 aResult.Assign(folders[i].classification);
1931 nsTArray<nsCString> resIds = {
1932 "branding/brand.ftl"_ns,
1933 "browser/browser.ftl"_ns,
1935 RefPtr<Localization> l10n = Localization::Create(resIds, true);
1936 nsAutoCString pbStr;
1937 IgnoredErrorResult rv;
1938 l10n->FormatValueSync("private-browsing-shortcut-text-2"_ns, {}, pbStr,
1939 rv);
1940 NS_ConvertUTF8toUTF16 widePbStr(pbStr);
1941 if (wcsstr(shortcutPath.get(), widePbStr.get())) {
1942 aResult.AppendLiteral("Private");
1944 return NS_OK;
1948 // Nothing found, aResult is already "".
1949 return NS_OK;
1952 nsWindowsShellService::nsWindowsShellService() {}
1954 nsWindowsShellService::~nsWindowsShellService() {}