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/. */
8 #include "nsWindowsShellService.h"
9 #include "nsWindowsShellServiceInternal.h"
11 #include "BinaryPath.h"
12 #include "imgIContainer.h"
13 #include "imgIRequest.h"
14 #include "mozilla/RefPtr.h"
15 #include "nsComponentManagerUtils.h"
16 #include "nsIContent.h"
17 #include "nsIImageLoadingContent.h"
18 #include "nsIOutputStream.h"
19 #include "nsIPrefService.h"
20 #include "nsIStringBundle.h"
21 #include "nsIMIMEService.h"
22 #include "nsNetUtil.h"
23 #include "nsProxyRelease.h"
24 #include "nsServiceManagerUtils.h"
25 #include "nsShellService.h"
26 #include "nsDirectoryServiceUtils.h"
27 #include "nsAppDirectoryServiceDefs.h"
28 #include "nsDirectoryServiceDefs.h"
29 #include "nsIWindowsRegKey.h"
30 #include "nsUnicharUtils.h"
31 #include "nsWindowsHelpers.h"
32 #include "nsXULAppAPI.h"
33 #include "mozilla/WindowsVersion.h"
34 #include "mozilla/dom/Element.h"
35 #include "mozilla/dom/Promise.h"
36 #include "mozilla/ErrorResult.h"
37 #include "mozilla/gfx/2D.h"
38 #include "mozilla/intl/Localization.h"
39 #include "WindowsDefaultBrowser.h"
40 #include "WindowsUserChoice.h"
41 #include "nsLocalFile.h"
42 #include "nsIXULAppInfo.h"
43 #include "nsINIParser.h"
44 #include "nsNativeAppSupportWin.h"
45 #include "Windows11TaskbarPinning.h"
50 #include <propvarutil.h>
54 // MinGW-w64 headers are missing PropVariantToString.
56 PSSTDAPI
PropVariantToString(REFPROPVARIANT propvar
, PWSTR psz
, UINT cch
);
59 # include <Lmcons.h> // For UNLEN
61 # include <wrl/wrappers/corewrappers.h>
62 # include <windows.applicationmodel.h>
63 # include <windows.applicationmodel.core.h>
64 # include <windows.applicationmodel.activation.h>
65 # include <windows.foundation.h>
66 # include <windows.ui.startscreen.h>
67 using namespace Microsoft::WRL
;
68 using namespace ABI::Windows
;
69 using namespace ABI::Windows::Foundation
;
70 using namespace ABI::Windows::Foundation::Collections
;
71 using namespace ABI::Windows::ApplicationModel
;
72 using namespace ABI::Windows::ApplicationModel::Core
;
73 using namespace ABI::Windows::UI::StartScreen
;
74 using namespace Microsoft::WRL::Wrappers
;
79 #include <knownfolders.h>
81 #include "mozilla/widget/WinTaskbar.h"
85 #define PRIVATE_BROWSING_BINARY L"private_browsing.exe"
93 #define REG_SUCCEEDED(val) (val == ERROR_SUCCESS)
95 #define REG_FAILED(val) (val != ERROR_SUCCESS)
98 # define NS_ENSURE_HRESULT(hres, ret) \
100 HRESULT result = hres; \
101 if (MOZ_UNLIKELY(FAILED(result))) { \
102 mozilla::SmprintfPointer msg = mozilla::Smprintf( \
103 "NS_ENSURE_HRESULT(%s, %s) failed with " \
104 "result 0x%" PRIX32, \
105 #hres, #ret, static_cast<uint32_t>(result)); \
106 NS_WARNING(msg.get()); \
111 # define NS_ENSURE_HRESULT(hres, ret) \
112 if (MOZ_UNLIKELY(FAILED(hres))) return ret
115 using namespace mozilla
;
116 using mozilla::intl::Localization
;
118 struct SysFreeStringDeleter
{
119 void operator()(BSTR aPtr
) { ::SysFreeString(aPtr
); }
121 using BStrPtr
= mozilla::UniquePtr
<OLECHAR
, SysFreeStringDeleter
>;
123 NS_IMPL_ISUPPORTS(nsWindowsShellService
, nsIToolkitShellService
,
124 nsIShellService
, nsIWindowsShellService
)
126 static nsresult
OpenKeyForReading(HKEY aKeyRoot
, const nsAString
& aKeyName
,
128 const nsString
& flatName
= PromiseFlatString(aKeyName
);
130 DWORD res
= ::RegOpenKeyExW(aKeyRoot
, flatName
.get(), 0, KEY_READ
, aKey
);
134 case ERROR_ACCESS_DENIED
:
135 return NS_ERROR_FILE_ACCESS_DENIED
;
136 case ERROR_FILE_NOT_FOUND
:
137 return NS_ERROR_NOT_AVAILABLE
;
143 nsresult
GetHelperPath(nsAutoString
& aPath
) {
145 nsCOMPtr
<nsIProperties
> directoryService
=
146 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
, &rv
);
147 NS_ENSURE_SUCCESS(rv
, rv
);
149 nsCOMPtr
<nsIFile
> appHelper
;
150 rv
= directoryService
->Get(XRE_EXECUTABLE_FILE
, NS_GET_IID(nsIFile
),
151 getter_AddRefs(appHelper
));
152 NS_ENSURE_SUCCESS(rv
, rv
);
154 rv
= appHelper
->SetNativeLeafName("uninstall"_ns
);
155 NS_ENSURE_SUCCESS(rv
, rv
);
157 rv
= appHelper
->AppendNative("helper.exe"_ns
);
158 NS_ENSURE_SUCCESS(rv
, rv
);
160 rv
= appHelper
->GetPath(aPath
);
162 aPath
.Insert(L
'"', 0);
167 nsresult
LaunchHelper(nsAutoString
& aPath
) {
168 STARTUPINFOW si
= {sizeof(si
), 0};
169 PROCESS_INFORMATION pi
= {0};
171 if (!CreateProcessW(nullptr, (LPWSTR
)aPath
.get(), nullptr, nullptr, FALSE
, 0,
172 nullptr, nullptr, &si
, &pi
)) {
173 return NS_ERROR_FAILURE
;
176 CloseHandle(pi
.hProcess
);
177 CloseHandle(pi
.hThread
);
181 static bool IsPathDefaultForClass(
182 const RefPtr
<IApplicationAssociationRegistration
>& pAAR
, wchar_t* exePath
,
183 LPCWSTR aClassName
) {
184 LPWSTR registeredApp
;
185 bool isProtocol
= *aClassName
!= L
'.';
186 ASSOCIATIONTYPE queryType
= isProtocol
? AT_URLPROTOCOL
: AT_FILEEXTENSION
;
187 HRESULT hr
= pAAR
->QueryCurrentDefault(aClassName
, queryType
, AL_EFFECTIVE
,
193 nsAutoString
regAppName(registeredApp
);
194 CoTaskMemFree(registeredApp
);
196 // Make sure the application path for this progID is this installation.
197 regAppName
.AppendLiteral("\\shell\\open\\command");
199 nsresult rv
= OpenKeyForReading(HKEY_CLASSES_ROOT
, regAppName
, &theKey
);
204 wchar_t cmdFromReg
[MAX_BUF
] = L
"";
205 DWORD len
= sizeof(cmdFromReg
);
206 DWORD res
= ::RegQueryValueExW(theKey
, nullptr, nullptr, nullptr,
207 (LPBYTE
)cmdFromReg
, &len
);
208 ::RegCloseKey(theKey
);
209 if (REG_FAILED(res
)) {
213 nsAutoString
pathFromReg(cmdFromReg
);
214 nsLocalFile::CleanupCmdHandlerPath(pathFromReg
);
216 return _wcsicmp(exePath
, pathFromReg
.Data()) == 0;
220 nsWindowsShellService::IsDefaultBrowser(bool aForAllTypes
,
221 bool* aIsDefaultBrowser
) {
222 *aIsDefaultBrowser
= false;
224 RefPtr
<IApplicationAssociationRegistration
> pAAR
;
225 HRESULT hr
= CoCreateInstance(
226 CLSID_ApplicationAssociationRegistration
, nullptr, CLSCTX_INPROC
,
227 IID_IApplicationAssociationRegistration
, getter_AddRefs(pAAR
));
232 wchar_t exePath
[MAXPATHLEN
] = L
"";
233 nsresult rv
= BinaryPath::GetLong(exePath
);
239 *aIsDefaultBrowser
= IsPathDefaultForClass(pAAR
, exePath
, L
"http");
240 if (*aIsDefaultBrowser
&& aForAllTypes
) {
241 *aIsDefaultBrowser
= IsPathDefaultForClass(pAAR
, exePath
, L
".html");
247 nsWindowsShellService::IsDefaultHandlerFor(
248 const nsAString
& aFileExtensionOrProtocol
, bool* aIsDefaultHandlerFor
) {
249 *aIsDefaultHandlerFor
= false;
251 RefPtr
<IApplicationAssociationRegistration
> pAAR
;
252 HRESULT hr
= CoCreateInstance(
253 CLSID_ApplicationAssociationRegistration
, nullptr, CLSCTX_INPROC
,
254 IID_IApplicationAssociationRegistration
, getter_AddRefs(pAAR
));
259 wchar_t exePath
[MAXPATHLEN
] = L
"";
260 nsresult rv
= BinaryPath::GetLong(exePath
);
266 const nsString
& flatClass
= PromiseFlatString(aFileExtensionOrProtocol
);
268 *aIsDefaultHandlerFor
= IsPathDefaultForClass(pAAR
, exePath
, flatClass
.get());
273 nsWindowsShellService::QueryCurrentDefaultHandlerFor(
274 const nsAString
& aFileExtensionOrProtocol
, nsAString
& aResult
) {
277 RefPtr
<IApplicationAssociationRegistration
> pAAR
;
278 HRESULT hr
= CoCreateInstance(
279 CLSID_ApplicationAssociationRegistration
, nullptr, CLSCTX_INPROC
,
280 IID_IApplicationAssociationRegistration
, getter_AddRefs(pAAR
));
285 const nsString
& flatClass
= PromiseFlatString(aFileExtensionOrProtocol
);
287 LPWSTR registeredApp
;
288 bool isProtocol
= flatClass
.First() != L
'.';
289 ASSOCIATIONTYPE queryType
= isProtocol
? AT_URLPROTOCOL
: AT_FILEEXTENSION
;
290 hr
= pAAR
->QueryCurrentDefault(flatClass
.get(), queryType
, AL_EFFECTIVE
,
292 if (hr
== HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION
)) {
295 NS_ENSURE_HRESULT(hr
, NS_ERROR_FAILURE
);
297 aResult
= registeredApp
;
298 CoTaskMemFree(registeredApp
);
303 nsresult
nsWindowsShellService::LaunchControlPanelDefaultsSelectionUI() {
304 IApplicationAssociationRegistrationUI
* pAARUI
;
305 HRESULT hr
= CoCreateInstance(
306 CLSID_ApplicationAssociationRegistrationUI
, NULL
, CLSCTX_INPROC
,
307 IID_IApplicationAssociationRegistrationUI
, (void**)&pAARUI
);
309 mozilla::UniquePtr
<wchar_t[]> appRegName
;
310 GetAppRegName(appRegName
);
311 hr
= pAARUI
->LaunchAdvancedAssociationUI(appRegName
.get());
314 return SUCCEEDED(hr
) ? NS_OK
: NS_ERROR_FAILURE
;
318 nsWindowsShellService::CheckAllProgIDsExist(bool* aResult
) {
321 if (!mozilla::widget::WinTaskbar::GetAppUserModelID(aumid
)) {
325 if (widget::WinUtils::HasPackageIdentity()) {
326 UniquePtr
<wchar_t[]> extraProgID
;
331 rv
= GetMsixProgId(L
"https", extraProgID
);
332 if (NS_WARN_IF(NS_FAILED(rv
))) {
335 result
= result
&& CheckProgIDExists(extraProgID
.get());
338 rv
= GetMsixProgId(L
".htm", extraProgID
);
339 if (NS_WARN_IF(NS_FAILED(rv
))) {
342 result
= result
&& CheckProgIDExists(extraProgID
.get());
345 rv
= GetMsixProgId(L
".pdf", extraProgID
);
346 if (NS_WARN_IF(NS_FAILED(rv
))) {
349 result
= result
&& CheckProgIDExists(extraProgID
.get());
354 CheckProgIDExists(FormatProgID(L
"FirefoxURL", aumid
.get()).get()) &&
355 CheckProgIDExists(FormatProgID(L
"FirefoxHTML", aumid
.get()).get()) &&
356 CheckProgIDExists(FormatProgID(L
"FirefoxPDF", aumid
.get()).get());
363 nsWindowsShellService::CheckBrowserUserChoiceHashes(bool* aResult
) {
364 *aResult
= ::CheckBrowserUserChoiceHashes();
369 nsWindowsShellService::CanSetDefaultBrowserUserChoice(bool* aResult
) {
371 // If the WDBA is not available, this could never succeed.
372 #ifdef MOZ_DEFAULT_BROWSER_AGENT
373 bool progIDsExist
= false;
375 *aResult
= NS_SUCCEEDED(CheckAllProgIDsExist(&progIDsExist
)) &&
377 NS_SUCCEEDED(CheckBrowserUserChoiceHashes(&hashOk
)) && hashOk
;
382 nsresult
nsWindowsShellService::LaunchModernSettingsDialogDefaultApps() {
383 return ::LaunchModernSettingsDialogDefaultApps() ? NS_OK
: NS_ERROR_FAILURE
;
387 nsWindowsShellService::SetDefaultBrowser(bool aForAllUsers
) {
388 // If running from within a package, don't attempt to set default with
389 // the helper, as it will not work and will only confuse our package's
390 // virtualized registry.
392 if (!widget::WinUtils::HasPackageIdentity()) {
393 nsAutoString appHelperPath
;
394 if (NS_FAILED(GetHelperPath(appHelperPath
))) return NS_ERROR_FAILURE
;
397 appHelperPath
.AppendLiteral(" /SetAsDefaultAppGlobal");
399 appHelperPath
.AppendLiteral(" /SetAsDefaultAppUser");
402 rv
= LaunchHelper(appHelperPath
);
405 if (NS_SUCCEEDED(rv
)) {
406 rv
= LaunchModernSettingsDialogDefaultApps();
407 // The above call should never really fail, but just in case
408 // fall back to showing control panel for all defaults
410 rv
= LaunchControlPanelDefaultsSelectionUI();
414 nsCOMPtr
<nsIPrefBranch
> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID
));
416 (void)prefs
->SetBoolPref(PREF_CHECKDEFAULTBROWSER
, true);
417 // Reset the number of times the dialog should be shown
418 // before it is silenced.
419 (void)prefs
->SetIntPref(PREF_DEFAULTBROWSERCHECKCOUNT
, 0);
425 static nsresult
WriteBitmap(nsIFile
* aFile
, imgIContainer
* aImage
) {
428 RefPtr
<gfx::SourceSurface
> surface
= aImage
->GetFrame(
429 imgIContainer::FRAME_FIRST
, imgIContainer::FLAG_SYNC_DECODE
);
430 NS_ENSURE_TRUE(surface
, NS_ERROR_FAILURE
);
432 // For either of the following formats we want to set the biBitCount member
433 // of the BITMAPINFOHEADER struct to 32, below. For that value the bitmap
434 // format defines that the A8/X8 WORDs in the bitmap byte stream be ignored
435 // for the BI_RGB value we use for the biCompression member.
436 MOZ_ASSERT(surface
->GetFormat() == gfx::SurfaceFormat::B8G8R8A8
||
437 surface
->GetFormat() == gfx::SurfaceFormat::B8G8R8X8
);
439 RefPtr
<gfx::DataSourceSurface
> dataSurface
= surface
->GetDataSurface();
440 NS_ENSURE_TRUE(dataSurface
, NS_ERROR_FAILURE
);
442 int32_t width
= dataSurface
->GetSize().width
;
443 int32_t height
= dataSurface
->GetSize().height
;
444 int32_t bytesPerPixel
= 4 * sizeof(uint8_t);
445 uint32_t bytesPerRow
= bytesPerPixel
* width
;
447 // initialize these bitmap structs which we will later
448 // serialize directly to the head of the bitmap file
449 BITMAPINFOHEADER bmi
;
450 bmi
.biSize
= sizeof(BITMAPINFOHEADER
);
452 bmi
.biHeight
= height
;
454 bmi
.biBitCount
= (WORD
)bytesPerPixel
* 8;
455 bmi
.biCompression
= BI_RGB
;
456 bmi
.biSizeImage
= bytesPerRow
* height
;
457 bmi
.biXPelsPerMeter
= 0;
458 bmi
.biYPelsPerMeter
= 0;
460 bmi
.biClrImportant
= 0;
463 bf
.bfType
= 0x4D42; // 'BM'
466 bf
.bfOffBits
= sizeof(BITMAPFILEHEADER
) + sizeof(BITMAPINFOHEADER
);
467 bf
.bfSize
= bf
.bfOffBits
+ bmi
.biSizeImage
;
469 // get a file output stream
470 nsCOMPtr
<nsIOutputStream
> stream
;
471 rv
= NS_NewLocalFileOutputStream(getter_AddRefs(stream
), aFile
);
472 NS_ENSURE_SUCCESS(rv
, rv
);
474 gfx::DataSourceSurface::MappedSurface map
;
475 if (!dataSurface
->Map(gfx::DataSourceSurface::MapType::READ
, &map
)) {
476 return NS_ERROR_FAILURE
;
479 // write the bitmap headers and rgb pixel data to the file
480 rv
= NS_ERROR_FAILURE
;
483 stream
->Write((const char*)&bf
, sizeof(BITMAPFILEHEADER
), &written
);
484 if (written
== sizeof(BITMAPFILEHEADER
)) {
485 stream
->Write((const char*)&bmi
, sizeof(BITMAPINFOHEADER
), &written
);
486 if (written
== sizeof(BITMAPINFOHEADER
)) {
487 // write out the image data backwards because the desktop won't
488 // show bitmaps with negative heights for top-to-bottom
489 uint32_t i
= map
.mStride
* height
;
492 stream
->Write(((const char*)map
.mData
) + i
, bytesPerRow
, &written
);
493 if (written
== bytesPerRow
) {
496 rv
= NS_ERROR_FAILURE
;
506 dataSurface
->Unmap();
512 nsWindowsShellService::SetDesktopBackground(dom::Element
* aElement
,
514 const nsACString
& aImageName
) {
515 if (!aElement
|| !aElement
->IsHTMLElement(nsGkAtoms::img
)) {
516 // XXX write background loading stuff!
517 return NS_ERROR_NOT_AVAILABLE
;
521 nsCOMPtr
<nsIImageLoadingContent
> imageContent
=
522 do_QueryInterface(aElement
, &rv
);
523 if (!imageContent
) return rv
;
525 // get the image container
526 nsCOMPtr
<imgIRequest
> request
;
527 rv
= imageContent
->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST
,
528 getter_AddRefs(request
));
529 if (!request
) return rv
;
531 nsCOMPtr
<imgIContainer
> container
;
532 rv
= request
->GetImage(getter_AddRefs(container
));
533 if (!container
) return NS_ERROR_FAILURE
;
535 // get the file name from localized strings
536 nsCOMPtr
<nsIStringBundleService
> bundleService(
537 do_GetService(NS_STRINGBUNDLE_CONTRACTID
, &rv
));
538 NS_ENSURE_SUCCESS(rv
, rv
);
540 nsCOMPtr
<nsIStringBundle
> shellBundle
;
541 rv
= bundleService
->CreateBundle(SHELLSERVICE_PROPERTIES
,
542 getter_AddRefs(shellBundle
));
543 NS_ENSURE_SUCCESS(rv
, rv
);
545 // e.g. "Desktop Background.bmp"
546 nsAutoString fileLeafName
;
547 rv
= shellBundle
->GetStringFromName("desktopBackgroundLeafNameWin",
549 NS_ENSURE_SUCCESS(rv
, rv
);
551 // get the profile root directory
552 nsCOMPtr
<nsIFile
> file
;
553 rv
= NS_GetSpecialDirectory(NS_APP_APPLICATION_REGISTRY_DIR
,
554 getter_AddRefs(file
));
555 NS_ENSURE_SUCCESS(rv
, rv
);
557 // eventually, the path is "%APPDATA%\Mozilla\Firefox\Desktop Background.bmp"
558 rv
= file
->Append(fileLeafName
);
559 NS_ENSURE_SUCCESS(rv
, rv
);
562 rv
= file
->GetPath(path
);
563 NS_ENSURE_SUCCESS(rv
, rv
);
565 // write the bitmap to a file in the profile directory.
566 // We have to write old bitmap format for Windows 7 wallpapar support.
567 rv
= WriteBitmap(file
, container
);
569 // if the file was written successfully, set it as the system wallpaper
570 if (NS_SUCCEEDED(rv
)) {
571 nsCOMPtr
<nsIWindowsRegKey
> regKey
=
572 do_CreateInstance("@mozilla.org/windows-registry-key;1", &rv
);
573 NS_ENSURE_SUCCESS(rv
, rv
);
575 rv
= regKey
->Create(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER
,
576 u
"Control Panel\\Desktop"_ns
,
577 nsIWindowsRegKey::ACCESS_SET_VALUE
);
578 NS_ENSURE_SUCCESS(rv
, rv
);
583 case BACKGROUND_TILE
:
587 case BACKGROUND_CENTER
:
591 case BACKGROUND_STRETCH
:
595 case BACKGROUND_FILL
:
596 style
.AssignLiteral("10");
603 case BACKGROUND_SPAN
:
604 style
.AssignLiteral("22");
609 rv
= regKey
->WriteStringValue(u
"TileWallpaper"_ns
, tile
);
610 NS_ENSURE_SUCCESS(rv
, rv
);
611 rv
= regKey
->WriteStringValue(u
"WallpaperStyle"_ns
, style
);
612 NS_ENSURE_SUCCESS(rv
, rv
);
613 rv
= regKey
->Close();
614 NS_ENSURE_SUCCESS(rv
, rv
);
616 ::SystemParametersInfoW(SPI_SETDESKWALLPAPER
, 0, (PVOID
)path
.get(),
617 SPIF_UPDATEINIFILE
| SPIF_SENDCHANGE
);
623 nsWindowsShellService::GetDesktopBackgroundColor(uint32_t* aColor
) {
624 uint32_t color
= ::GetSysColor(COLOR_DESKTOP
);
626 (GetRValue(color
) << 16) | (GetGValue(color
) << 8) | GetBValue(color
);
631 nsWindowsShellService::SetDesktopBackgroundColor(uint32_t aColor
) {
632 int aParameters
[2] = {COLOR_BACKGROUND
, COLOR_DESKTOP
};
633 BYTE r
= (aColor
>> 16);
634 BYTE g
= (aColor
<< 16) >> 24;
635 BYTE b
= (aColor
<< 24) >> 24;
636 COLORREF colors
[2] = {RGB(r
, g
, b
), RGB(r
, g
, b
)};
638 ::SetSysColors(sizeof(aParameters
) / sizeof(int), aParameters
, colors
);
641 nsCOMPtr
<nsIWindowsRegKey
> regKey
=
642 do_CreateInstance("@mozilla.org/windows-registry-key;1", &rv
);
643 NS_ENSURE_SUCCESS(rv
, rv
);
645 rv
= regKey
->Create(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER
,
646 u
"Control Panel\\Colors"_ns
,
647 nsIWindowsRegKey::ACCESS_SET_VALUE
);
648 NS_ENSURE_SUCCESS(rv
, rv
);
651 _snwprintf(rgb
, 12, L
"%u %u %u", r
, g
, b
);
653 rv
= regKey
->WriteStringValue(u
"Background"_ns
, nsDependentString(rgb
));
654 NS_ENSURE_SUCCESS(rv
, rv
);
656 return regKey
->Close();
660 * Writes information about a shortcut to a shortcuts log in
661 * %PROGRAMDATA%\Mozilla-1de4eec8-1241-4177-a864-e594e8d1fb38.
662 * (This is the same directory used for update staging.)
663 * For more on the shortcuts log format and purpose, consult
664 * /toolkit/mozapps/installer/windows/nsis/common.nsh.
666 * The shortcuts log created or appended here is named after
667 * the currently running application and current user SID.
668 * For example: Firefox_$SID_shortcuts.ini.
670 * If it does not exist, it will be created. If it exists
671 * and a matching shortcut named already exists in the file,
672 * a new one will not be appended.
674 * In an ideal world this function would not need aShortcutsLogDir
675 * passed to it, but it is called by at least one function that runs
676 * asynchronously, and is therefore unable to use nsDirectoryService
677 * to look it up itself.
679 static nsresult
WriteShortcutToLog(nsIFile
* aShortcutsLogDir
,
680 KNOWNFOLDERID aFolderId
,
681 const nsAString
& aShortcutName
) {
682 // the section inside the shortcuts log
683 nsAutoCString section
;
684 // the shortcuts log wants "Programs" shortcuts in its "STARTMENU" section
685 if (aFolderId
== FOLDERID_CommonPrograms
|| aFolderId
== FOLDERID_Programs
) {
686 section
.Assign("STARTMENU");
687 } else if (aFolderId
== FOLDERID_PublicDesktop
||
688 aFolderId
== FOLDERID_Desktop
) {
689 section
.Assign("DESKTOP");
691 return NS_ERROR_INVALID_ARG
;
694 nsCOMPtr
<nsIFile
> shortcutsLog
;
695 nsresult rv
= aShortcutsLogDir
->GetParent(getter_AddRefs(shortcutsLog
));
696 NS_ENSURE_SUCCESS(rv
, rv
);
698 nsAutoCString appName
;
699 nsCOMPtr
<nsIXULAppInfo
> appInfo
=
700 do_GetService("@mozilla.org/xre/app-info;1");
701 rv
= appInfo
->GetName(appName
);
702 NS_ENSURE_SUCCESS(rv
, rv
);
704 auto userSid
= GetCurrentUserStringSid();
706 return NS_ERROR_FILE_NOT_FOUND
;
709 nsAutoString filename
;
710 filename
.AppendPrintf("%s_%ls_shortcuts.ini", appName
.get(), userSid
.get());
711 rv
= shortcutsLog
->Append(filename
);
712 NS_ENSURE_SUCCESS(rv
, rv
);
715 bool fileExists
= false;
716 bool shortcutsLogEntryExists
= false;
717 nsAutoCString keyName
, shortcutName
;
718 shortcutName
= NS_ConvertUTF16toUTF8(aShortcutName
);
720 shortcutsLog
->IsFile(&fileExists
);
721 // if the shortcuts log exists, find either an existing matching
722 // entry, or the next available shortcut index
724 rv
= parser
.Init(shortcutsLog
);
725 NS_ENSURE_SUCCESS(rv
, rv
);
727 nsCString iniShortcut
;
728 // surely we'll never need more than 10 shortcuts in one section...
729 for (int i
= 0; i
< 10; i
++) {
730 keyName
.AssignLiteral("Shortcut");
731 keyName
.AppendInt(i
);
732 rv
= parser
.GetString(section
.get(), keyName
.get(), iniShortcut
);
734 // we found an unused index
736 } else if (iniShortcut
.Equals(shortcutName
)) {
737 shortcutsLogEntryExists
= true;
740 // otherwise, this is safe to use
742 keyName
.AssignLiteral("Shortcut0");
745 if (!shortcutsLogEntryExists
) {
746 parser
.SetString(section
.get(), keyName
.get(), shortcutName
.get());
747 // We write this ourselves instead of using parser->WriteToFile because
748 // the INI parser in our uninstaller needs to read this, and only supports
749 // UTF-16LE encoding. nsINIParser does not support UTF-16.
750 nsAutoCString formatted
;
751 parser
.WriteToString(formatted
);
753 rv
= shortcutsLog
->OpenANSIFileDesc("w,ccs=UTF-16LE", &writeFile
);
754 NS_ENSURE_SUCCESS(rv
, rv
);
755 NS_ConvertUTF8toUTF16
formattedUTF16(formatted
);
756 if (fwrite(formattedUTF16
.get(), sizeof(wchar_t), formattedUTF16
.Length(),
757 writeFile
) != formattedUTF16
.Length()) {
759 return NS_ERROR_FAILURE
;
767 nsresult
CreateShellLinkObject(nsIFile
* aBinary
,
768 const CopyableTArray
<nsString
>& aArguments
,
769 const nsAString
& aDescription
,
770 nsIFile
* aIconFile
, uint16_t aIconIndex
,
771 const nsAString
& aAppUserModelId
,
772 IShellLinkW
** aLink
) {
773 RefPtr
<IShellLinkW
> link
;
774 HRESULT hr
= CoCreateInstance(CLSID_ShellLink
, nullptr, CLSCTX_INPROC_SERVER
,
775 IID_IShellLinkW
, getter_AddRefs(link
));
776 NS_ENSURE_HRESULT(hr
, NS_ERROR_FAILURE
);
778 nsString
path(aBinary
->NativePath());
779 link
->SetPath(path
.get());
781 wchar_t workingDir
[MAX_PATH
+ 1];
782 wcscpy_s(workingDir
, MAX_PATH
+ 1, aBinary
->NativePath().get());
783 PathRemoveFileSpecW(workingDir
);
784 link
->SetWorkingDirectory(workingDir
);
786 if (!aDescription
.IsEmpty()) {
787 link
->SetDescription(PromiseFlatString(aDescription
).get());
790 // TODO: Properly escape quotes in the string, see bug 1604287.
792 for (const auto& arg
: aArguments
) {
793 arguments
+= u
"\""_ns
+ arg
+ u
"\" "_ns
;
796 link
->SetArguments(arguments
.get());
799 nsString
icon(aIconFile
->NativePath());
800 link
->SetIconLocation(icon
.get(), aIconIndex
);
803 if (!aAppUserModelId
.IsEmpty()) {
804 RefPtr
<IPropertyStore
> propStore
;
805 hr
= link
->QueryInterface(IID_IPropertyStore
, getter_AddRefs(propStore
));
806 NS_ENSURE_HRESULT(hr
, NS_ERROR_FAILURE
);
809 if (FAILED(InitPropVariantFromString(
810 PromiseFlatString(aAppUserModelId
).get(), &pv
))) {
811 return NS_ERROR_FAILURE
;
814 hr
= propStore
->SetValue(PKEY_AppUserModel_ID
, pv
);
815 PropVariantClear(&pv
);
816 NS_ENSURE_HRESULT(hr
, NS_ERROR_FAILURE
);
818 hr
= propStore
->Commit();
819 NS_ENSURE_HRESULT(hr
, NS_ERROR_FAILURE
);
826 static nsresult
CreateShortcutImpl(
827 nsIFile
* aBinary
, const CopyableTArray
<nsString
>& aArguments
,
828 const nsAString
& aDescription
, nsIFile
* aIconFile
, uint16_t aIconIndex
,
829 const nsAString
& aAppUserModelId
, KNOWNFOLDERID aShortcutFolder
,
830 const nsAString
& aShortcutName
, const nsString
& aShortcutFile
,
831 nsIFile
* aShortcutsLogDir
) {
832 NS_ENSURE_ARG(aBinary
);
833 NS_ENSURE_ARG(aIconFile
);
836 WriteShortcutToLog(aShortcutsLogDir
, aShortcutFolder
, aShortcutName
);
837 NS_ENSURE_SUCCESS(rv
, rv
);
839 RefPtr
<IShellLinkW
> link
;
840 rv
= CreateShellLinkObject(aBinary
, aArguments
, aDescription
, aIconFile
,
841 aIconIndex
, aAppUserModelId
, getter_AddRefs(link
));
842 NS_ENSURE_SUCCESS(rv
, rv
);
844 RefPtr
<IPersistFile
> persist
;
845 HRESULT hr
= link
->QueryInterface(IID_IPersistFile
, getter_AddRefs(persist
));
846 NS_ENSURE_HRESULT(hr
, NS_ERROR_FAILURE
);
848 hr
= persist
->Save(aShortcutFile
.get(), TRUE
);
849 NS_ENSURE_HRESULT(hr
, NS_ERROR_FAILURE
);
855 nsWindowsShellService::CreateShortcut(
856 nsIFile
* aBinary
, const nsTArray
<nsString
>& aArguments
,
857 const nsAString
& aDescription
, nsIFile
* aIconFile
, uint16_t aIconIndex
,
858 const nsAString
& aAppUserModelId
, const nsAString
& aShortcutFolder
,
859 const nsAString
& aShortcutName
, JSContext
* aCx
, dom::Promise
** aPromise
) {
860 if (!NS_IsMainThread()) {
861 return NS_ERROR_NOT_SAME_THREAD
;
865 RefPtr
<dom::Promise
> promise
=
866 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
868 if (MOZ_UNLIKELY(rv
.Failed())) {
869 return rv
.StealNSResult();
871 // In an ideal world we'd probably send along nsIFile pointers
872 // here, but it's easier to determine the needed shortcuts log
873 // entry with a KNOWNFOLDERID - so we pass this along instead
874 // and let CreateShortcutImpl take care of converting it to
876 KNOWNFOLDERID folderId
;
877 if (aShortcutFolder
.Equals(L
"Programs")) {
878 folderId
= FOLDERID_Programs
;
879 } else if (aShortcutFolder
.Equals(L
"Desktop")) {
880 folderId
= FOLDERID_Desktop
;
882 return NS_ERROR_INVALID_ARG
;
885 nsCOMPtr
<nsIFile
> updRoot
, shortcutsLogDir
;
887 NS_GetSpecialDirectory(XRE_UPDATE_ROOT_DIR
, getter_AddRefs(updRoot
));
888 NS_ENSURE_SUCCESS(nsrv
, nsrv
);
889 nsrv
= updRoot
->GetParent(getter_AddRefs(shortcutsLogDir
));
890 NS_ENSURE_SUCCESS(nsrv
, nsrv
);
892 nsCOMPtr
<nsIFile
> shortcutFile
;
893 if (folderId
== FOLDERID_Programs
) {
894 nsrv
= NS_GetSpecialDirectory(NS_WIN_PROGRAMS_DIR
,
895 getter_AddRefs(shortcutFile
));
896 } else if (folderId
== FOLDERID_Desktop
) {
898 NS_GetSpecialDirectory(NS_OS_DESKTOP_DIR
, getter_AddRefs(shortcutFile
));
900 return NS_ERROR_FILE_NOT_FOUND
;
902 if (NS_FAILED(nsrv
)) {
903 return NS_ERROR_FILE_NOT_FOUND
;
905 shortcutFile
->Append(aShortcutName
);
907 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
908 "CreateShortcut promise", promise
);
910 nsCOMPtr
<nsIFile
> binary(aBinary
);
911 nsCOMPtr
<nsIFile
> iconFile(aIconFile
);
912 NS_DispatchBackgroundTask(
913 NS_NewRunnableFunction(
915 [binary
, aArguments
= CopyableTArray
<nsString
>(aArguments
),
916 aDescription
= nsString
{aDescription
}, iconFile
, aIconIndex
,
917 aAppUserModelId
= nsString
{aAppUserModelId
}, folderId
,
918 aShortcutFolder
= nsString
{aShortcutFolder
},
919 aShortcutName
= nsString
{aShortcutName
}, shortcutsLogDir
,
920 shortcutFile
, promiseHolder
= std::move(promiseHolder
)] {
921 nsresult rv
= NS_ERROR_FAILURE
;
922 HRESULT hr
= CoInitialize(nullptr);
925 rv
= CreateShortcutImpl(
926 binary
.get(), aArguments
, aDescription
, iconFile
.get(),
927 aIconIndex
, aAppUserModelId
, folderId
, aShortcutName
,
928 shortcutFile
->NativePath(), shortcutsLogDir
.get());
932 NS_DispatchToMainThread(NS_NewRunnableFunction(
933 "CreateShortcut callback",
934 [rv
, shortcutFile
, promiseHolder
= std::move(promiseHolder
)] {
935 dom::Promise
* promise
= promiseHolder
.get()->get();
937 if (NS_SUCCEEDED(rv
)) {
938 promise
->MaybeResolve(shortcutFile
->NativePath());
940 promise
->MaybeReject(rv
);
944 NS_DISPATCH_EVENT_MAY_BLOCK
);
946 promise
.forget(aPromise
);
951 nsWindowsShellService::GetLaunchOnLoginShortcuts(
952 nsTArray
<nsString
>& aShortcutPaths
) {
953 aShortcutPaths
.Clear();
955 // Get AppData\\Roaming folder using a known folder ID
956 RefPtr
<IKnownFolderManager
> fManager
;
957 RefPtr
<IKnownFolder
> roamingAppData
;
958 LPWSTR roamingAppDataW
;
959 nsString roamingAppDataNS
;
961 CoCreateInstance(CLSID_KnownFolderManager
, nullptr, CLSCTX_INPROC_SERVER
,
962 IID_IKnownFolderManager
, getter_AddRefs(fManager
));
964 return NS_ERROR_ABORT
;
966 fManager
->GetFolder(FOLDERID_RoamingAppData
,
967 roamingAppData
.StartAssignment());
968 hr
= roamingAppData
->GetPath(0, &roamingAppDataW
);
970 return NS_ERROR_FILE_NOT_FOUND
;
973 // Append startup folder to AppData\\Roaming
974 roamingAppDataNS
.Assign(roamingAppDataW
);
975 CoTaskMemFree(roamingAppDataW
);
976 nsString startupFolder
=
978 u
"\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"_ns
;
979 nsString startupFolderWildcard
= startupFolder
+ u
"\\*.lnk"_ns
;
981 // Get known path for binary file for later comparison with shortcuts.
982 // Returns lowercase file path which should be fine for Windows as all
983 // directories and files are case-insensitive by default.
984 RefPtr
<nsIFile
> binFile
;
986 nsresult rv
= XRE_GetBinaryPath(binFile
.StartAssignment());
988 return NS_ERROR_FAILURE
;
990 rv
= binFile
->GetPath(binPath
);
992 return NS_ERROR_FILE_UNRECOGNIZED_PATH
;
995 // Check for if first file exists with a shortcut extension (.lnk)
996 WIN32_FIND_DATAW ffd
;
997 HANDLE fileHandle
= INVALID_HANDLE_VALUE
;
998 fileHandle
= FindFirstFileW(startupFolderWildcard
.get(), &ffd
);
999 if (fileHandle
== INVALID_HANDLE_VALUE
) {
1000 // This means that no files were found in the folder which
1001 // doesn't imply an error. Most of the time the user won't
1002 // have any shortcuts here.
1007 // Extract shortcut target path from every
1008 // shortcut in the startup folder.
1009 nsString
fileName(ffd
.cFileName
);
1010 RefPtr
<IShellLinkW
> link
;
1011 RefPtr
<IPersistFile
> ppf
;
1013 target
.SetLength(MAX_PATH
);
1014 CoCreateInstance(CLSID_ShellLink
, nullptr, CLSCTX_INPROC_SERVER
,
1015 IID_IShellLinkW
, getter_AddRefs(link
));
1016 hr
= link
->QueryInterface(IID_IPersistFile
, getter_AddRefs(ppf
));
1017 if (NS_WARN_IF(FAILED(hr
))) {
1020 nsString filePath
= startupFolder
+ u
"\\"_ns
+ fileName
;
1021 hr
= ppf
->Load(filePath
.get(), STGM_READ
);
1022 if (NS_WARN_IF(FAILED(hr
))) {
1025 hr
= link
->GetPath(target
.get(), MAX_PATH
, nullptr, 0);
1026 if (NS_WARN_IF(FAILED(hr
))) {
1030 // If shortcut target matches known binary file value
1031 // then add the path to the shortcut as a valid
1032 // startup shortcut. This has to be a substring search as
1033 // the user could have added unknown command line arguments
1035 if (_wcsnicmp(target
.get(), binPath
.get(), binPath
.Length()) == 0) {
1036 aShortcutPaths
.AppendElement(filePath
);
1038 } while (FindNextFile(fileHandle
, &ffd
) != 0);
1039 FindClose(fileHandle
);
1043 // Look for any installer-created shortcuts in the given location that match
1044 // the given AUMID and EXE Path. If one is found, output its path.
1046 // NOTE: DO NOT USE if a false negative (mismatch) is unacceptable.
1047 // aExePath is compared directly to the path retrieved from the shortcut.
1048 // Due to the presence of symlinks or other filesystem issues, it's possible
1049 // for different paths to refer to the same file, which would cause the check
1051 // This should rarely be an issue as we are most likely to be run from a path
1052 // written by the installer (shortcut, association, launch from installer),
1053 // which also wrote the shortcuts. But it is possible.
1055 // aCSIDL the CSIDL of the directory to look for matching shortcuts in
1056 // aAUMID the AUMID to check for
1057 // aExePath the target exe path to check for, should be a long path where
1059 // aShortcutSubstring a substring to limit which shortcuts in aCSIDL are
1060 // inspected for a match. Only shortcuts whose filename
1061 // contains this substring will be considered
1062 // aShortcutPath outparam, set to matching shortcut path if NS_OK is returned.
1065 // NS_ERROR_FAILURE on errors before any shortcuts were loaded
1066 // NS_ERROR_FILE_NOT_FOUND if no shortcuts matching aShortcutSubstring exist
1067 // NS_ERROR_FILE_ALREADY_EXISTS if shortcuts were found but did not match
1068 // aAUMID or aExePath
1069 // NS_OK if a matching shortcut is found
1070 static nsresult
GetMatchingShortcut(int aCSIDL
, const nsAString
& aAUMID
,
1071 const wchar_t aExePath
[MAXPATHLEN
],
1072 const nsAString
& aShortcutSubstring
,
1073 /* out */ nsAutoString
& aShortcutPath
) {
1074 nsresult result
= NS_ERROR_FAILURE
;
1076 wchar_t folderPath
[MAX_PATH
] = {};
1077 HRESULT hr
= SHGetFolderPathW(nullptr, aCSIDL
, nullptr, SHGFP_TYPE_CURRENT
,
1079 if (NS_WARN_IF(FAILED(hr
))) {
1080 return NS_ERROR_FAILURE
;
1082 if (wcscat_s(folderPath
, MAX_PATH
, L
"\\") != 0) {
1083 return NS_ERROR_FAILURE
;
1086 // Get list of shortcuts in aCSIDL
1087 nsAutoString
pattern(folderPath
);
1088 pattern
.AppendLiteral("*.lnk");
1090 WIN32_FIND_DATAW findData
= {};
1091 HANDLE hFindFile
= FindFirstFileW(pattern
.get(), &findData
);
1092 if (hFindFile
== INVALID_HANDLE_VALUE
) {
1093 Unused
<< NS_WARN_IF(GetLastError() != ERROR_FILE_NOT_FOUND
);
1094 return NS_ERROR_FILE_NOT_FOUND
;
1096 // Past this point we don't return until the end of the function,
1097 // when FindClose() is called.
1099 // todo: improve return values here
1101 // Skip any that don't contain aShortcutSubstring
1102 // This is a case sensitive comparison, but that's probably fine for
1103 // the vast majority of cases -- and certainly for all the ones where
1104 // a shortcut was created by the installer.
1105 if (StrStrIW(findData
.cFileName
, aShortcutSubstring
.Data()) == NULL
) {
1109 nsAutoString
path(folderPath
);
1110 path
.Append(findData
.cFileName
);
1112 // Create a shell link object for loading the shortcut
1113 RefPtr
<IShellLinkW
> link
;
1115 CoCreateInstance(CLSID_ShellLink
, nullptr, CLSCTX_INPROC_SERVER
,
1116 IID_IShellLinkW
, getter_AddRefs(link
));
1117 if (NS_WARN_IF(FAILED(hr
))) {
1122 RefPtr
<IPersistFile
> persist
;
1123 hr
= link
->QueryInterface(IID_IPersistFile
, getter_AddRefs(persist
));
1124 if (NS_WARN_IF(FAILED(hr
))) {
1128 hr
= persist
->Load(path
.get(), STGM_READ
);
1130 if (NS_WARN_IF(hr
!= HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND
))) {
1131 // empty branch, result unchanged but warning issued
1133 // If we've ever gotten past this block, result will already be
1134 // NS_ERROR_FILE_ALREADY_EXISTS, which is a more accurate error
1135 // than NS_ERROR_FILE_NOT_FOUND.
1136 if (result
!= NS_ERROR_FILE_ALREADY_EXISTS
) {
1137 result
= NS_ERROR_FILE_NOT_FOUND
;
1142 result
= NS_ERROR_FILE_ALREADY_EXISTS
;
1145 RefPtr
<IPropertyStore
> propStore
;
1146 hr
= link
->QueryInterface(IID_IPropertyStore
, getter_AddRefs(propStore
));
1147 if (NS_WARN_IF(FAILED(hr
))) {
1152 hr
= propStore
->GetValue(PKEY_AppUserModel_ID
, &pv
);
1153 if (NS_WARN_IF(FAILED(hr
))) {
1157 wchar_t storedAUMID
[MAX_PATH
];
1158 hr
= PropVariantToString(pv
, storedAUMID
, MAX_PATH
);
1159 PropVariantClear(&pv
);
1160 if (NS_WARN_IF(FAILED(hr
))) {
1164 if (!aAUMID
.Equals(storedAUMID
)) {
1168 // Check the exe path
1169 static_assert(MAXPATHLEN
== MAX_PATH
);
1170 wchar_t storedExePath
[MAX_PATH
] = {};
1171 // With no flags GetPath gets a long path
1172 hr
= link
->GetPath(storedExePath
, ArrayLength(storedExePath
), nullptr, 0);
1173 if (FAILED(hr
) || hr
== S_FALSE
) {
1176 // Case insensitive path comparison
1177 if (wcsnicmp(storedExePath
, aExePath
, MAXPATHLEN
) == 0) {
1178 aShortcutPath
.Assign(path
);
1182 } while (FindNextFileW(hFindFile
, &findData
));
1184 FindClose(hFindFile
);
1189 static nsresult
FindMatchingShortcut(const nsAString
& aAppUserModelId
,
1190 const nsAString
& aShortcutSubstring
,
1191 const bool aPrivateBrowsing
,
1192 nsAutoString
& aShortcutPath
) {
1193 wchar_t exePath
[MAXPATHLEN
] = {};
1194 if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath
)))) {
1195 return NS_ERROR_FAILURE
;
1198 if (aPrivateBrowsing
) {
1199 if (!PathRemoveFileSpecW(exePath
)) {
1200 return NS_ERROR_FAILURE
;
1202 if (!PathAppendW(exePath
, L
"private_browsing.exe")) {
1203 return NS_ERROR_FAILURE
;
1207 int shortcutCSIDLs
[] = {CSIDL_COMMON_PROGRAMS
, CSIDL_PROGRAMS
,
1208 CSIDL_COMMON_DESKTOPDIRECTORY
,
1209 CSIDL_DESKTOPDIRECTORY
};
1210 for (int shortcutCSIDL
: shortcutCSIDLs
) {
1211 // GetMatchingShortcut may fail when the exe path doesn't match, even
1212 // if it refers to the same file. This should be rare, and the worst
1213 // outcome would be failure to pin, so the risk is acceptable.
1214 nsresult rv
= GetMatchingShortcut(shortcutCSIDL
, aAppUserModelId
, exePath
,
1215 aShortcutSubstring
, aShortcutPath
);
1216 if (NS_SUCCEEDED(rv
)) {
1221 return NS_ERROR_FILE_NOT_FOUND
;
1224 static bool HasMatchingShortcutImpl(const nsAString
& aAppUserModelId
,
1225 const bool aPrivateBrowsing
,
1226 const nsAutoString
& aShortcutSubstring
) {
1227 // unused by us, but required
1228 nsAutoString shortcutPath
;
1229 nsresult rv
= FindMatchingShortcut(aAppUserModelId
, aShortcutSubstring
,
1230 aPrivateBrowsing
, shortcutPath
);
1231 if (SUCCEEDED(rv
)) {
1238 NS_IMETHODIMP
nsWindowsShellService::HasMatchingShortcut(
1239 const nsAString
& aAppUserModelId
, const bool aPrivateBrowsing
,
1240 JSContext
* aCx
, dom::Promise
** aPromise
) {
1241 if (!NS_IsMainThread()) {
1242 return NS_ERROR_NOT_SAME_THREAD
;
1246 RefPtr
<dom::Promise
> promise
=
1247 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
1249 if (MOZ_UNLIKELY(rv
.Failed())) {
1250 return rv
.StealNSResult();
1253 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
1254 "HasMatchingShortcut promise", promise
);
1256 NS_DispatchBackgroundTask(
1257 NS_NewRunnableFunction(
1258 "HasMatchingShortcut",
1259 [aAppUserModelId
= nsString
{aAppUserModelId
}, aPrivateBrowsing
,
1260 promiseHolder
= std::move(promiseHolder
)] {
1262 HRESULT hr
= CoInitialize(nullptr);
1264 if (SUCCEEDED(hr
)) {
1265 nsAutoString shortcutSubstring
;
1266 shortcutSubstring
.AssignLiteral(MOZ_APP_DISPLAYNAME
);
1267 rv
= HasMatchingShortcutImpl(aAppUserModelId
, aPrivateBrowsing
,
1272 NS_DispatchToMainThread(NS_NewRunnableFunction(
1273 "HasMatchingShortcut callback",
1274 [rv
, promiseHolder
= std::move(promiseHolder
)] {
1275 dom::Promise
* promise
= promiseHolder
.get()->get();
1277 promise
->MaybeResolve(rv
);
1280 NS_DISPATCH_EVENT_MAY_BLOCK
);
1282 promise
.forget(aPromise
);
1286 static bool IsCurrentAppPinnedToTaskbarSync(const nsAString
& aumid
) {
1287 // Use new Windows pinning APIs to determine whether or not we're pinned.
1288 // If these fail we can safely fall back to the old method for regular
1289 // installs however MSIX will always return false.
1291 // Bug 1911343: Add a check for whether we're looking for a regular pin
1292 // or PB pin based on the AUMID value once private browser pinning
1293 // is supported on MSIX.
1294 // Right now only run this check on MSIX to avoid
1295 // false positives when only private browsing is pinned.
1296 if (widget::WinUtils::HasPackageIdentity()) {
1297 auto pinWithWin11TaskbarAPIResults
=
1298 IsCurrentAppPinnedToTaskbarWin11(false);
1299 switch (pinWithWin11TaskbarAPIResults
.result
) {
1300 case Win11PinToTaskBarResultStatus::NotPinned
:
1303 case Win11PinToTaskBarResultStatus::AlreadyPinned
:
1307 // Fall through to the old mechanism.
1308 // The old mechanism should continue working for non-MSIX
1314 // There are two shortcut targets that we created. One always matches the
1315 // binary we're running as (eg: firefox.exe). The other is the wrapper
1316 // for launching in Private Browsing mode. We need to inspect shortcuts
1317 // that point at either of these to accurately judge whether or not
1318 // the app is pinned with the given AUMID.
1319 wchar_t exePath
[MAXPATHLEN
] = {};
1320 wchar_t pbExePath
[MAXPATHLEN
] = {};
1322 if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath
)))) {
1326 wcscpy_s(pbExePath
, MAXPATHLEN
, exePath
);
1327 if (!PathRemoveFileSpecW(pbExePath
)) {
1330 if (!PathAppendW(pbExePath
, L
"private_browsing.exe")) {
1334 wchar_t folderChars
[MAX_PATH
] = {};
1335 HRESULT hr
= SHGetFolderPathW(nullptr, CSIDL_APPDATA
, nullptr,
1336 SHGFP_TYPE_CURRENT
, folderChars
);
1337 if (NS_WARN_IF(FAILED(hr
))) {
1341 nsAutoString folder
;
1342 folder
.Assign(folderChars
);
1343 if (NS_WARN_IF(folder
.IsEmpty())) {
1346 if (folder
[folder
.Length() - 1] != '\\') {
1347 folder
.AppendLiteral("\\");
1349 folder
.AppendLiteral(
1350 "Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar");
1351 nsAutoString pattern
;
1352 pattern
.Assign(folder
);
1353 pattern
.AppendLiteral("\\*.lnk");
1355 WIN32_FIND_DATAW findData
= {};
1356 HANDLE hFindFile
= FindFirstFileW(pattern
.get(), &findData
);
1357 if (hFindFile
== INVALID_HANDLE_VALUE
) {
1358 Unused
<< NS_WARN_IF(GetLastError() != ERROR_FILE_NOT_FOUND
);
1361 // Past this point we don't return until the end of the function,
1362 // when FindClose() is called.
1364 // Check all shortcuts until a match is found
1365 bool isPinned
= false;
1367 nsAutoString fileName
;
1368 fileName
.Assign(folder
);
1369 fileName
.AppendLiteral("\\");
1370 fileName
.Append(findData
.cFileName
);
1372 // Create a shell link object for loading the shortcut
1373 RefPtr
<IShellLinkW
> link
;
1375 CoCreateInstance(CLSID_ShellLink
, nullptr, CLSCTX_INPROC_SERVER
,
1376 IID_IShellLinkW
, getter_AddRefs(link
));
1377 if (NS_WARN_IF(FAILED(hr
))) {
1382 RefPtr
<IPersistFile
> persist
;
1383 hr
= link
->QueryInterface(IID_IPersistFile
, getter_AddRefs(persist
));
1384 if (NS_WARN_IF(FAILED(hr
))) {
1388 hr
= persist
->Load(fileName
.get(), STGM_READ
);
1389 if (NS_WARN_IF(FAILED(hr
))) {
1393 // Check the exe path
1394 static_assert(MAXPATHLEN
== MAX_PATH
);
1395 wchar_t storedExePath
[MAX_PATH
] = {};
1396 // With no flags GetPath gets a long path
1397 hr
= link
->GetPath(storedExePath
, ArrayLength(storedExePath
), nullptr, 0);
1398 if (FAILED(hr
) || hr
== S_FALSE
) {
1401 // Case insensitive path comparison
1402 // NOTE: Because this compares the path directly, it is possible to
1403 // have a false negative mismatch.
1404 if (wcsnicmp(storedExePath
, exePath
, MAXPATHLEN
) == 0 ||
1405 wcsnicmp(storedExePath
, pbExePath
, MAXPATHLEN
) == 0) {
1406 RefPtr
<IPropertyStore
> propStore
;
1407 hr
= link
->QueryInterface(IID_IPropertyStore
, getter_AddRefs(propStore
));
1408 if (NS_WARN_IF(FAILED(hr
))) {
1413 hr
= propStore
->GetValue(PKEY_AppUserModel_ID
, &pv
);
1414 if (NS_WARN_IF(FAILED(hr
))) {
1418 wchar_t storedAUMID
[MAX_PATH
];
1419 hr
= PropVariantToString(pv
, storedAUMID
, MAX_PATH
);
1420 PropVariantClear(&pv
);
1421 if (NS_WARN_IF(FAILED(hr
))) {
1425 if (aumid
.Equals(storedAUMID
)) {
1430 } while (FindNextFileW(hFindFile
, &findData
));
1432 FindClose(hFindFile
);
1437 static nsresult
ManageShortcutTaskbarPins(bool aCheckOnly
, bool aPinType
,
1438 const nsAString
& aShortcutPath
) {
1439 // This enum is likely only used for Windows telemetry, INT_MAX is chosen to
1440 // avoid confusion with existing uses.
1441 enum PINNEDLISTMODIFYCALLER
{ PLMC_INT_MAX
= INT_MAX
};
1443 // The types below, and the idea of using IPinnedList3::Modify,
1444 // are thanks to Gee Law <https://geelaw.blog/entries/msedge-pins/>
1445 static constexpr GUID CLSID_TaskbandPin
= {
1449 {0xb8, 0xbb, 0x53, 0x57, 0x73, 0xd4, 0x84, 0x49}};
1451 static constexpr GUID IID_IPinnedList3
= {
1455 {0x9e, 0xeb, 0x3b, 0x54, 0x97, 0x69, 0xe9, 0x40}};
1457 struct IPinnedList3Vtbl
;
1458 struct IPinnedList3
{
1459 IPinnedList3Vtbl
* vtbl
;
1462 typedef ULONG STDMETHODCALLTYPE
ReleaseFunc(IPinnedList3
* that
);
1463 typedef HRESULT STDMETHODCALLTYPE
ModifyFunc(
1464 IPinnedList3
* that
, PCIDLIST_ABSOLUTE unpin
, PCIDLIST_ABSOLUTE pin
,
1465 PINNEDLISTMODIFYCALLER caller
);
1467 struct IPinnedList3Vtbl
{
1468 void* QueryInterface
; // 0
1470 ReleaseFunc
* Release
; // 2
1471 void* Other
[13]; // 3-15
1472 ModifyFunc
* Modify
; // 16
1475 struct ILFreeDeleter
{
1476 void operator()(LPITEMIDLIST aPtr
) {
1483 mozilla::UniquePtr
<__unaligned ITEMIDLIST
, ILFreeDeleter
> path(
1484 ILCreateFromPathW(nsString(aShortcutPath
).get()));
1485 if (NS_WARN_IF(!path
)) {
1486 return NS_ERROR_FILE_NOT_FOUND
;
1489 IPinnedList3
* pinnedList
= nullptr;
1490 HRESULT hr
= CoCreateInstance(CLSID_TaskbandPin
, NULL
, CLSCTX_INPROC_SERVER
,
1491 IID_IPinnedList3
, (void**)&pinnedList
);
1492 if (FAILED(hr
) || !pinnedList
) {
1493 return NS_ERROR_NOT_AVAILABLE
;
1497 hr
= pinnedList
->vtbl
->Modify(pinnedList
, aPinType
? NULL
: path
.get(),
1498 aPinType
? path
.get() : NULL
, PLMC_INT_MAX
);
1501 pinnedList
->vtbl
->Release(pinnedList
);
1504 return NS_ERROR_FILE_ACCESS_DENIED
;
1510 nsWindowsShellService::PinShortcutToTaskbar(const nsAString
& aShortcutPath
) {
1511 const bool pinType
= true; // true means pin
1512 const bool runInTestMode
= false;
1513 return ManageShortcutTaskbarPins(runInTestMode
, pinType
, aShortcutPath
);
1517 nsWindowsShellService::UnpinShortcutFromTaskbar(
1518 const nsAString
& aShortcutPath
) {
1519 const bool pinType
= false; // false means unpin
1520 const bool runInTestMode
= false;
1521 return ManageShortcutTaskbarPins(runInTestMode
, pinType
, aShortcutPath
);
1524 // Ensure that the supplied name doesn't have invalid characters.
1525 static void ValidateFilename(nsAString
& aFilename
) {
1526 nsCOMPtr
<nsIMIMEService
> mimeService
= do_GetService("@mozilla.org/mime;1");
1527 if (NS_WARN_IF(!mimeService
)) {
1528 aFilename
.Truncate();
1532 uint32_t flags
= nsIMIMEService::VALIDATE_SANITIZE_ONLY
|
1533 nsIMIMEService::VALIDATE_DONT_COLLAPSE_WHITESPACE
;
1535 nsAutoString outFilename
;
1536 mimeService
->ValidateFileNameForSaving(aFilename
, EmptyCString(), flags
,
1538 aFilename
= outFilename
;
1542 nsWindowsShellService::GetTaskbarTabShortcutPath(const nsAString
& aShortcutName
,
1543 nsAString
& aRetPath
) {
1544 nsAutoString
sanitizedShortcutName(aShortcutName
);
1545 ValidateFilename(sanitizedShortcutName
);
1546 if (sanitizedShortcutName
!= aShortcutName
) {
1547 return NS_ERROR_FILE_INVALID_PATH
;
1550 // The taskbar tab shortcut will always be in
1551 // %APPDATA%\Microsoft\Windows\Start Menu\Programs
1552 RefPtr
<IKnownFolderManager
> fManager
;
1553 RefPtr
<IKnownFolder
> progFolder
;
1555 nsString progFolderNS
;
1557 CoCreateInstance(CLSID_KnownFolderManager
, nullptr, CLSCTX_INPROC_SERVER
,
1558 IID_IKnownFolderManager
, getter_AddRefs(fManager
));
1559 if (NS_WARN_IF(FAILED(hr
))) {
1560 return NS_ERROR_ABORT
;
1562 fManager
->GetFolder(FOLDERID_Programs
, progFolder
.StartAssignment());
1563 hr
= progFolder
->GetPath(0, &progFolderW
);
1565 return NS_ERROR_FILE_NOT_FOUND
;
1567 progFolderNS
.Assign(progFolderW
);
1568 aRetPath
= progFolderNS
+ u
"\\"_ns
+ aShortcutName
+ u
".lnk"_ns
;
1573 nsWindowsShellService::GetTaskbarTabPins(nsTArray
<nsString
>& aShortcutPaths
) {
1575 return NS_ERROR_NOT_IMPLEMENTED
;
1577 aShortcutPaths
.Clear();
1579 // Get AppData\\Roaming folder using a known folder ID
1580 RefPtr
<IKnownFolderManager
> fManager
;
1581 RefPtr
<IKnownFolder
> roamingAppData
;
1582 LPWSTR roamingAppDataW
;
1583 nsString roamingAppDataNS
;
1585 CoCreateInstance(CLSID_KnownFolderManager
, nullptr, CLSCTX_INPROC_SERVER
,
1586 IID_IKnownFolderManager
, getter_AddRefs(fManager
));
1587 if (NS_WARN_IF(FAILED(hr
))) {
1588 return NS_ERROR_ABORT
;
1590 fManager
->GetFolder(FOLDERID_RoamingAppData
,
1591 roamingAppData
.StartAssignment());
1592 hr
= roamingAppData
->GetPath(0, &roamingAppDataW
);
1594 return NS_ERROR_FILE_NOT_FOUND
;
1597 // Append taskbar pins folder to AppData\\Roaming
1598 roamingAppDataNS
.Assign(roamingAppDataW
);
1599 CoTaskMemFree(roamingAppDataW
);
1600 nsString taskbarFolder
=
1601 roamingAppDataNS
+ u
"\\Microsoft\\Windows\\Start Menu\\Programs"_ns
;
1602 nsString taskbarFolderWildcard
= taskbarFolder
+ u
"\\*.lnk"_ns
;
1604 // Get known path for binary file for later comparison with shortcuts.
1605 // Returns lowercase file path which should be fine for Windows as all
1606 // directories and files are case-insensitive by default.
1607 RefPtr
<nsIFile
> binFile
;
1609 nsresult rv
= XRE_GetBinaryPath(binFile
.StartAssignment());
1610 if (NS_WARN_IF(FAILED(rv
))) {
1611 return NS_ERROR_FAILURE
;
1613 rv
= binFile
->GetPath(binPath
);
1614 if (NS_WARN_IF(FAILED(rv
))) {
1615 return NS_ERROR_FILE_UNRECOGNIZED_PATH
;
1618 // Check for if first file exists with a shortcut extension (.lnk)
1619 WIN32_FIND_DATAW ffd
;
1620 HANDLE fileHandle
= INVALID_HANDLE_VALUE
;
1621 fileHandle
= FindFirstFileW(taskbarFolderWildcard
.get(), &ffd
);
1622 if (fileHandle
== INVALID_HANDLE_VALUE
) {
1623 // This means that no files were found in the folder which
1624 // doesn't imply an error.
1629 // Extract shortcut target path from every
1630 // shortcut in the taskbar pins folder.
1631 nsString
fileName(ffd
.cFileName
);
1632 RefPtr
<IShellLinkW
> link
;
1633 RefPtr
<IPropertyStore
> pps
;
1635 target
.SetLength(MAX_PATH
);
1636 hr
= CoCreateInstance(CLSID_ShellLink
, nullptr, CLSCTX_INPROC_SERVER
,
1637 IID_IShellLinkW
, getter_AddRefs(link
));
1638 if (NS_WARN_IF(FAILED(hr
))) {
1641 nsString filePath
= taskbarFolder
+ u
"\\"_ns
+ fileName
;
1642 if (NS_WARN_IF(FAILED(hr
))) {
1646 // After loading shortcut, search through arguments to find if
1647 // it is a taskbar tab shortcut.
1648 hr
= SHGetPropertyStoreFromParsingName(filePath
.get(), nullptr,
1649 GPS_READWRITE
, IID_IPropertyStore
,
1650 getter_AddRefs(pps
));
1651 if (NS_WARN_IF(FAILED(hr
)) || pps
== nullptr) {
1654 PROPVARIANT propVar
;
1655 PropVariantInit(&propVar
);
1656 auto cleanupPropVariant
=
1657 MakeScopeExit([&] { PropVariantClear(&propVar
); });
1658 // Get the PKEY_Link_Arguments property
1659 hr
= pps
->GetValue(PKEY_Link_Arguments
, &propVar
);
1660 if (NS_WARN_IF(FAILED(hr
))) {
1663 // Check if the argument matches
1664 if (!(propVar
.vt
== VT_LPWSTR
&& propVar
.pwszVal
!= nullptr &&
1665 wcsstr(propVar
.pwszVal
, L
"-taskbar-tab") != nullptr)) {
1669 hr
= link
->GetPath(target
.get(), MAX_PATH
, nullptr, 0);
1670 if (NS_WARN_IF(FAILED(hr
))) {
1674 // If shortcut target matches known binary file value
1675 // then add the path to the shortcut as a valid
1676 // shortcut. This has to be a substring search as
1677 // the user could have added unknown command line arguments
1679 if (_wcsnicmp(target
.get(), binPath
.get(), binPath
.Length()) == 0) {
1680 aShortcutPaths
.AppendElement(filePath
);
1682 } while (FindNextFile(fileHandle
, &ffd
) != 0);
1683 FindClose(fileHandle
);
1688 static nsresult
PinCurrentAppToTaskbarWin10(bool aCheckOnly
,
1689 const nsAString
& aAppUserModelId
,
1690 const nsAString
& aShortcutPath
) {
1691 // The behavior here is identical if we're only checking or if we try to pin
1692 // but the app is already pinned so we update the variable accordingly.
1694 aCheckOnly
= IsCurrentAppPinnedToTaskbarSync(aAppUserModelId
);
1696 const bool pinType
= true; // true means pin
1697 return ManageShortcutTaskbarPins(aCheckOnly
, pinType
, aShortcutPath
);
1700 static nsresult
PinCurrentAppToTaskbarImpl(
1701 bool aCheckOnly
, bool aPrivateBrowsing
, const nsAString
& aAppUserModelId
,
1702 const nsAString
& aShortcutName
, const nsAString
& aShortcutSubstring
,
1703 nsIFile
* aShortcutsLogDir
, nsIFile
* aGreDir
, nsIFile
* aProgramsDir
) {
1704 MOZ_DIAGNOSTIC_ASSERT(
1706 "PinCurrentAppToTaskbarImpl should be called off main thread only");
1708 nsAutoString shortcutPath
;
1709 nsresult rv
= FindMatchingShortcut(aAppUserModelId
, aShortcutSubstring
,
1710 aPrivateBrowsing
, shortcutPath
);
1711 if (NS_FAILED(rv
)) {
1712 shortcutPath
.Truncate();
1714 if (shortcutPath
.IsEmpty()) {
1716 // Later checks rely on a shortcut already existing.
1717 // We don't want to create a shortcut in check only mode
1718 // so the best we can do is assume those parts will work.
1722 nsAutoString
linkName(aShortcutName
);
1724 nsCOMPtr
<nsIFile
> exeFile(aGreDir
);
1725 if (aPrivateBrowsing
) {
1726 nsAutoString
pbExeStr(PRIVATE_BROWSING_BINARY
);
1727 nsresult rv
= exeFile
->Append(pbExeStr
);
1728 if (!NS_SUCCEEDED(rv
)) {
1729 return NS_ERROR_FAILURE
;
1732 wchar_t exePath
[MAXPATHLEN
] = {};
1733 if (NS_WARN_IF(NS_FAILED(BinaryPath::GetLong(exePath
)))) {
1734 return NS_ERROR_FAILURE
;
1736 nsAutoString
exeStr(exePath
);
1737 nsresult rv
= NS_NewLocalFile(exeStr
, true, getter_AddRefs(exeFile
));
1738 if (!NS_SUCCEEDED(rv
)) {
1739 return NS_ERROR_FILE_NOT_FOUND
;
1743 nsCOMPtr
<nsIFile
> shortcutFile(aProgramsDir
);
1744 shortcutFile
->Append(aShortcutName
);
1745 shortcutPath
.Assign(shortcutFile
->NativePath());
1747 nsTArray
<nsString
> arguments
;
1748 rv
= CreateShortcutImpl(exeFile
, arguments
, aShortcutName
, exeFile
,
1749 // Icon indexes are defined as Resource IDs, but
1750 // CreateShortcutImpl needs an index.
1751 IDI_APPICON
- 1, aAppUserModelId
, FOLDERID_Programs
,
1752 linkName
, shortcutFile
->NativePath(),
1754 if (!NS_SUCCEEDED(rv
)) {
1755 return NS_ERROR_FILE_NOT_FOUND
;
1759 auto pinWithWin11TaskbarAPIResults
=
1760 PinCurrentAppToTaskbarWin11(aCheckOnly
, aAppUserModelId
);
1761 switch (pinWithWin11TaskbarAPIResults
.result
) {
1762 case Win11PinToTaskBarResultStatus::NotSupported
:
1763 // Fall through to the win 10 mechanism
1766 case Win11PinToTaskBarResultStatus::Success
:
1767 case Win11PinToTaskBarResultStatus::AlreadyPinned
:
1770 case Win11PinToTaskBarResultStatus::NotPinned
:
1771 case Win11PinToTaskBarResultStatus::NotCurrentlyAllowed
:
1772 case Win11PinToTaskBarResultStatus::Failed
:
1773 // return NS_ERROR_FAILURE;
1775 // Fall through to the old mechanism for now
1776 // In future, we should be sending telemetry for when
1777 // an error occurs or for when pinning is not allowed
1778 // with the Win 11 APIs.
1782 return PinCurrentAppToTaskbarWin10(aCheckOnly
, aAppUserModelId
, shortcutPath
);
1785 static nsresult
PinCurrentAppToTaskbarAsyncImpl(bool aCheckOnly
,
1786 bool aPrivateBrowsing
,
1788 dom::Promise
** aPromise
) {
1789 if (!NS_IsMainThread()) {
1790 return NS_ERROR_NOT_SAME_THREAD
;
1793 // First available on 1809
1794 if (!IsWin10Sep2018UpdateOrLater()) {
1795 return NS_ERROR_NOT_AVAILABLE
;
1799 RefPtr
<dom::Promise
> promise
=
1800 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
1802 if (MOZ_UNLIKELY(rv
.Failed())) {
1803 return rv
.StealNSResult();
1807 if (NS_WARN_IF(!mozilla::widget::WinTaskbar::GetAppUserModelID(
1808 aumid
, aPrivateBrowsing
))) {
1809 return NS_ERROR_FAILURE
;
1812 // NOTE: In the installer, non-private shortcuts are named
1813 // "${BrandShortName}.lnk". This is set from MOZ_APP_DISPLAYNAME in
1814 // defines.nsi.in. (Except in dev edition where it's explicitly set to
1815 // "Firefox Developer Edition" in branding.nsi, which matches
1816 // MOZ_APP_DISPLAYNAME in aurora/configure.sh.)
1818 // If this changes, we could expand this to check shortcuts_log.ini,
1819 // which records the name of the shortcuts as created by the installer.
1821 // Private shortcuts are not created by the installer (they're created
1822 // upon user request, ultimately by CreateShortcutImpl, and recorded in
1823 // a separate shortcuts log. As with non-private shortcuts they have a known
1824 // name - so there's no need to look through logs to find them.
1825 nsAutoString shortcutName
;
1826 if (aPrivateBrowsing
) {
1827 nsTArray
<nsCString
> resIds
= {
1828 "branding/brand.ftl"_ns
,
1829 "browser/browser.ftl"_ns
,
1831 RefPtr
<Localization
> l10n
= Localization::Create(resIds
, true);
1832 nsAutoCString pbStr
;
1833 IgnoredErrorResult rv
;
1834 l10n
->FormatValueSync("private-browsing-shortcut-text-2"_ns
, {}, pbStr
, rv
);
1835 shortcutName
.Append(NS_ConvertUTF8toUTF16(pbStr
));
1836 shortcutName
.AppendLiteral(".lnk");
1838 shortcutName
.AppendLiteral(MOZ_APP_DISPLAYNAME
".lnk");
1841 nsCOMPtr
<nsIFile
> greDir
, updRoot
, programsDir
, shortcutsLogDir
;
1842 nsresult nsrv
= NS_GetSpecialDirectory(NS_GRE_DIR
, getter_AddRefs(greDir
));
1843 NS_ENSURE_SUCCESS(nsrv
, nsrv
);
1844 nsrv
= NS_GetSpecialDirectory(XRE_UPDATE_ROOT_DIR
, getter_AddRefs(updRoot
));
1845 NS_ENSURE_SUCCESS(nsrv
, nsrv
);
1846 rv
= NS_GetSpecialDirectory(NS_WIN_PROGRAMS_DIR
, getter_AddRefs(programsDir
));
1847 NS_ENSURE_SUCCESS(nsrv
, nsrv
);
1848 nsrv
= updRoot
->GetParent(getter_AddRefs(shortcutsLogDir
));
1849 NS_ENSURE_SUCCESS(nsrv
, nsrv
);
1851 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
1852 "CheckPinCurrentAppToTaskbarAsync promise", promise
);
1854 NS_DispatchBackgroundTask(
1855 NS_NewRunnableFunction(
1856 "CheckPinCurrentAppToTaskbarAsync",
1857 [aCheckOnly
, aPrivateBrowsing
, shortcutName
, aumid
= nsString
{aumid
},
1858 shortcutsLogDir
, greDir
, programsDir
,
1859 promiseHolder
= std::move(promiseHolder
)] {
1860 nsresult rv
= NS_ERROR_FAILURE
;
1861 HRESULT hr
= CoInitialize(nullptr);
1863 if (SUCCEEDED(hr
)) {
1864 nsAutoString shortcutSubstring
;
1865 shortcutSubstring
.AssignLiteral(MOZ_APP_DISPLAYNAME
);
1866 rv
= PinCurrentAppToTaskbarImpl(
1867 aCheckOnly
, aPrivateBrowsing
, aumid
, shortcutName
,
1868 shortcutSubstring
, shortcutsLogDir
.get(), greDir
.get(),
1873 NS_DispatchToMainThread(NS_NewRunnableFunction(
1874 "CheckPinCurrentAppToTaskbarAsync callback",
1875 [rv
, promiseHolder
= std::move(promiseHolder
)] {
1876 dom::Promise
* promise
= promiseHolder
.get()->get();
1878 if (NS_SUCCEEDED(rv
)) {
1879 promise
->MaybeResolveWithUndefined();
1881 promise
->MaybeReject(rv
);
1885 NS_DISPATCH_EVENT_MAY_BLOCK
);
1887 promise
.forget(aPromise
);
1892 nsWindowsShellService::PinCurrentAppToTaskbarAsync(bool aPrivateBrowsing
,
1894 dom::Promise
** aPromise
) {
1895 return PinCurrentAppToTaskbarAsyncImpl(
1896 /* aCheckOnly */ false, aPrivateBrowsing
, aCx
, aPromise
);
1900 nsWindowsShellService::CheckPinCurrentAppToTaskbarAsync(
1901 bool aPrivateBrowsing
, JSContext
* aCx
, dom::Promise
** aPromise
) {
1902 return PinCurrentAppToTaskbarAsyncImpl(
1903 /* aCheckOnly = */ true, aPrivateBrowsing
, aCx
, aPromise
);
1907 nsWindowsShellService::IsCurrentAppPinnedToTaskbarAsync(
1908 const nsAString
& aumid
, JSContext
* aCx
, /* out */ dom::Promise
** aPromise
) {
1909 if (!NS_IsMainThread()) {
1910 return NS_ERROR_NOT_SAME_THREAD
;
1914 RefPtr
<dom::Promise
> promise
=
1915 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
1916 if (MOZ_UNLIKELY(rv
.Failed())) {
1917 return rv
.StealNSResult();
1920 // A holder to pass the promise through the background task and back to
1921 // the main thread when finished.
1922 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
1923 "IsCurrentAppPinnedToTaskbarAsync promise", promise
);
1925 // nsAString can't be captured by a lambda because it does not have a
1926 // public copy constructor
1927 nsAutoString
capturedAumid(aumid
);
1928 NS_DispatchBackgroundTask(
1929 NS_NewRunnableFunction(
1930 "IsCurrentAppPinnedToTaskbarAsync",
1931 [capturedAumid
, promiseHolder
= std::move(promiseHolder
)] {
1932 bool isPinned
= false;
1934 HRESULT hr
= CoInitialize(nullptr);
1935 if (SUCCEEDED(hr
)) {
1936 isPinned
= IsCurrentAppPinnedToTaskbarSync(capturedAumid
);
1940 // Dispatch back to the main thread to resolve the promise.
1941 NS_DispatchToMainThread(NS_NewRunnableFunction(
1942 "IsCurrentAppPinnedToTaskbarAsync callback",
1943 [isPinned
, promiseHolder
= std::move(promiseHolder
)] {
1944 promiseHolder
.get()->get()->MaybeResolve(isPinned
);
1947 NS_DISPATCH_EVENT_MAY_BLOCK
);
1949 promise
.forget(aPromise
);
1954 # define RESOLVE_AND_RETURN(HOLDER, RESOLVE, RETURN) \
1955 NS_DispatchToMainThread(NS_NewRunnableFunction( \
1956 __func__, [resolveVal = (RESOLVE), promiseHolder = HOLDER] { \
1957 promiseHolder.get()->get()->MaybeResolve(resolveVal); \
1961 # define REJECT_AND_RETURN(HOLDER, REJECT, RETURN) \
1962 NS_DispatchToMainThread( \
1963 NS_NewRunnableFunction(__func__, [promiseHolder = HOLDER] { \
1964 promiseHolder.get()->get()->MaybeReject(REJECT); \
1968 static void EnableLaunchOnLoginMSIXAsyncImpl(
1969 const nsString
& capturedTaskId
,
1970 const RefPtr
<nsMainThreadPtrHolder
<dom::Promise
>> promiseHolder
) {
1971 ComPtr
<IStartupTaskStatics
> startupTaskStatics
;
1972 HRESULT hr
= GetActivationFactory(
1973 HStringReference(RuntimeClass_Windows_ApplicationModel_StartupTask
).Get(),
1974 &startupTaskStatics
);
1976 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
1978 ComPtr
<IAsyncOperation
<StartupTask
*>> getTaskOperation
= nullptr;
1979 hr
= startupTaskStatics
->GetAsync(
1980 HStringReference(capturedTaskId
.get()).Get(), &getTaskOperation
);
1982 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
1984 auto getTaskCallback
=
1985 Callback
<IAsyncOperationCompletedHandler
<StartupTask
*>>(
1986 [promiseHolder
](IAsyncOperation
<StartupTask
*>* operation
,
1987 AsyncStatus status
) -> HRESULT
{
1988 if (status
!= AsyncStatus::Completed
) {
1989 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
1991 ComPtr
<IStartupTask
> startupTask
;
1992 HRESULT hr
= operation
->GetResults(&startupTask
);
1994 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
1996 ComPtr
<IAsyncOperation
<StartupTaskState
>> enableOperation
;
1997 hr
= startupTask
->RequestEnableAsync(&enableOperation
);
1999 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2001 // Set another callback for enabling the startup task
2002 auto enableHandler
=
2003 Callback
<IAsyncOperationCompletedHandler
<StartupTaskState
>>(
2005 IAsyncOperation
<StartupTaskState
>* operation
,
2006 AsyncStatus status
) -> HRESULT
{
2007 StartupTaskState resultState
;
2008 HRESULT hr
= operation
->GetResults(&resultState
);
2009 if (SUCCEEDED(hr
) && status
== AsyncStatus::Completed
) {
2010 RESOLVE_AND_RETURN(promiseHolder
, true, S_OK
);
2012 RESOLVE_AND_RETURN(promiseHolder
, false, S_OK
);
2014 hr
= enableOperation
->put_Completed(enableHandler
.Get());
2016 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, hr
);
2020 hr
= getTaskOperation
->put_Completed(getTaskCallback
.Get());
2022 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2026 static void DisableLaunchOnLoginMSIXAsyncImpl(
2027 const nsString
& capturedTaskId
,
2028 const RefPtr
<nsMainThreadPtrHolder
<dom::Promise
>> promiseHolder
) {
2029 ComPtr
<IStartupTaskStatics
> startupTaskStatics
;
2030 HRESULT hr
= GetActivationFactory(
2031 HStringReference(RuntimeClass_Windows_ApplicationModel_StartupTask
).Get(),
2032 &startupTaskStatics
);
2034 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2036 ComPtr
<IAsyncOperation
<StartupTask
*>> getTaskOperation
= nullptr;
2037 hr
= startupTaskStatics
->GetAsync(
2038 HStringReference(capturedTaskId
.get()).Get(), &getTaskOperation
);
2040 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2042 auto getTaskCallback
=
2043 Callback
<IAsyncOperationCompletedHandler
<StartupTask
*>>(
2044 [promiseHolder
](IAsyncOperation
<StartupTask
*>* operation
,
2045 AsyncStatus status
) -> HRESULT
{
2046 if (status
!= AsyncStatus::Completed
) {
2047 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2049 ComPtr
<IStartupTask
> startupTask
;
2050 HRESULT hr
= operation
->GetResults(&startupTask
);
2052 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2054 hr
= startupTask
->Disable();
2056 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2058 RESOLVE_AND_RETURN(promiseHolder
, true, S_OK
);
2060 hr
= getTaskOperation
->put_Completed(getTaskCallback
.Get());
2062 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2066 static void GetLaunchOnLoginEnabledMSIXAsyncImpl(
2067 const nsString
& capturedTaskId
,
2068 const RefPtr
<nsMainThreadPtrHolder
<dom::Promise
>> promiseHolder
) {
2069 ComPtr
<IStartupTaskStatics
> startupTaskStatics
;
2070 HRESULT hr
= GetActivationFactory(
2071 HStringReference(RuntimeClass_Windows_ApplicationModel_StartupTask
).Get(),
2072 &startupTaskStatics
);
2074 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2076 ComPtr
<IAsyncOperation
<StartupTask
*>> getTaskOperation
= nullptr;
2077 hr
= startupTaskStatics
->GetAsync(
2078 HStringReference(capturedTaskId
.get()).Get(), &getTaskOperation
);
2080 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2082 auto getTaskCallback
=
2083 Callback
<IAsyncOperationCompletedHandler
<StartupTask
*>>(
2084 [promiseHolder
](IAsyncOperation
<StartupTask
*>* operation
,
2085 AsyncStatus status
) -> HRESULT
{
2086 if (status
!= AsyncStatus::Completed
) {
2087 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2089 ComPtr
<IStartupTask
> startupTask
;
2090 HRESULT hr
= operation
->GetResults(&startupTask
);
2092 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2094 StartupTaskState state
;
2095 hr
= startupTask
->get_State(&state
);
2097 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2100 case StartupTaskState_EnabledByPolicy
:
2103 nsIWindowsShellService::LaunchOnLoginEnabledEnumerator::
2104 LAUNCH_ON_LOGIN_ENABLED_BY_POLICY
,
2107 case StartupTaskState_Enabled
:
2110 nsIWindowsShellService::LaunchOnLoginEnabledEnumerator::
2111 LAUNCH_ON_LOGIN_ENABLED
,
2114 case StartupTaskState_DisabledByUser
:
2115 case StartupTaskState_DisabledByPolicy
:
2118 nsIWindowsShellService::LaunchOnLoginEnabledEnumerator::
2119 LAUNCH_ON_LOGIN_DISABLED_BY_SETTINGS
,
2125 nsIWindowsShellService::LaunchOnLoginEnabledEnumerator::
2126 LAUNCH_ON_LOGIN_DISABLED
,
2130 hr
= getTaskOperation
->put_Completed(getTaskCallback
.Get());
2132 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2137 nsWindowsShellService::EnableLaunchOnLoginMSIXAsync(
2138 const nsAString
& aTaskId
, JSContext
* aCx
,
2139 /* out */ dom::Promise
** aPromise
) {
2140 if (!widget::WinUtils::HasPackageIdentity()) {
2141 return NS_ERROR_NOT_AVAILABLE
;
2144 if (!NS_IsMainThread()) {
2145 return NS_ERROR_NOT_SAME_THREAD
;
2148 RefPtr
<dom::Promise
> promise
=
2149 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
2150 if (MOZ_UNLIKELY(rv
.Failed())) {
2151 return rv
.StealNSResult();
2154 // A holder to pass the promise through the background task and back to
2155 // the main thread when finished.
2156 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
2157 "EnableLaunchOnLoginMSIXAsync promise", promise
);
2159 NS_DispatchBackgroundTask(NS_NewRunnableFunction(
2160 "EnableLaunchOnLoginMSIXAsync",
2161 [taskId
= nsString(aTaskId
), promiseHolder
] {
2162 EnableLaunchOnLoginMSIXAsyncImpl(taskId
, promiseHolder
);
2165 promise
.forget(aPromise
);
2170 nsWindowsShellService::DisableLaunchOnLoginMSIXAsync(
2171 const nsAString
& aTaskId
, JSContext
* aCx
,
2172 /* out */ dom::Promise
** aPromise
) {
2173 if (!widget::WinUtils::HasPackageIdentity()) {
2174 return NS_ERROR_NOT_AVAILABLE
;
2177 if (!NS_IsMainThread()) {
2178 return NS_ERROR_NOT_SAME_THREAD
;
2181 RefPtr
<dom::Promise
> promise
=
2182 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
2183 if (MOZ_UNLIKELY(rv
.Failed())) {
2184 return rv
.StealNSResult();
2187 // A holder to pass the promise through the background task and back to
2188 // the main thread when finished.
2189 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
2190 "DisableLaunchOnLoginMSIXAsync promise", promise
);
2192 NS_DispatchBackgroundTask(NS_NewRunnableFunction(
2193 "DisableLaunchOnLoginMSIXAsync",
2194 [taskId
= nsString(aTaskId
), promiseHolder
] {
2195 DisableLaunchOnLoginMSIXAsyncImpl(taskId
, promiseHolder
);
2198 promise
.forget(aPromise
);
2203 nsWindowsShellService::GetLaunchOnLoginEnabledMSIXAsync(
2204 const nsAString
& aTaskId
, JSContext
* aCx
,
2205 /* out */ dom::Promise
** aPromise
) {
2206 if (!widget::WinUtils::HasPackageIdentity()) {
2207 return NS_ERROR_NOT_AVAILABLE
;
2210 if (!NS_IsMainThread()) {
2211 return NS_ERROR_NOT_SAME_THREAD
;
2214 RefPtr
<dom::Promise
> promise
=
2215 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
2216 if (MOZ_UNLIKELY(rv
.Failed())) {
2217 return rv
.StealNSResult();
2220 // A holder to pass the promise through the background task and back to
2221 // the main thread when finished.
2222 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
2223 "GetLaunchOnLoginEnabledMSIXAsync promise", promise
);
2225 NS_DispatchBackgroundTask(NS_NewRunnableFunction(
2226 "GetLaunchOnLoginEnabledMSIXAsync",
2227 [taskId
= nsString(aTaskId
), promiseHolder
] {
2228 GetLaunchOnLoginEnabledMSIXAsyncImpl(taskId
, promiseHolder
);
2231 promise
.forget(aPromise
);
2235 static HRESULT
GetPackage3(ComPtr
<IPackage3
>& package3
) {
2236 // Get the current package and cast it to IPackage3 so we can
2237 // check for AppListEntries
2238 ComPtr
<IPackageStatics
> packageStatics
;
2239 HRESULT hr
= GetActivationFactory(
2240 HStringReference(RuntimeClass_Windows_ApplicationModel_Package
).Get(),
2246 ComPtr
<IPackage
> package
;
2247 hr
= packageStatics
->get_Current(&package
);
2251 hr
= package
.As(&package3
);
2255 static HRESULT
GetStartScreenManager(
2256 ComPtr
<IVectorView
<AppListEntry
*>>& appListEntries
,
2257 ComPtr
<IAppListEntry
>& entry
,
2258 ComPtr
<IStartScreenManager
>& startScreenManager
) {
2259 unsigned int numEntries
= 0;
2260 HRESULT hr
= appListEntries
->get_Size(&numEntries
);
2261 if (FAILED(hr
) || numEntries
== 0) {
2264 // There's only one AppListEntry in the Firefox package and by
2265 // convention our main executable should be the first in the
2267 hr
= appListEntries
->GetAt(0, &entry
);
2269 // Create and init a StartScreenManager and check if we're already
2271 ComPtr
<IStartScreenManagerStatics
> startScreenManagerStatics
;
2272 hr
= GetActivationFactory(
2273 HStringReference(RuntimeClass_Windows_UI_StartScreen_StartScreenManager
)
2275 &startScreenManagerStatics
);
2280 hr
= startScreenManagerStatics
->GetDefault(&startScreenManager
);
2284 static void PinCurrentAppToStartMenuAsyncImpl(
2286 const RefPtr
<nsMainThreadPtrHolder
<dom::Promise
>> promiseHolder
) {
2287 ComPtr
<IPackage3
> package3
;
2288 HRESULT hr
= GetPackage3(package3
);
2290 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2293 // Get the AppList entries
2294 ComPtr
<IVectorView
<AppListEntry
*>> appListEntries
;
2295 ComPtr
<IAsyncOperation
<IVectorView
<AppListEntry
*>*>>
2296 getAppListEntriesOperation
;
2297 hr
= package3
->GetAppListEntriesAsync(&getAppListEntriesOperation
);
2299 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2301 auto getAppListEntriesCallback
=
2302 Callback
<IAsyncOperationCompletedHandler
<IVectorView
<AppListEntry
*>*>>(
2303 [promiseHolder
, aCheckOnly
](
2304 IAsyncOperation
<IVectorView
<AppListEntry
*>*>* operation
,
2305 AsyncStatus status
) -> HRESULT
{
2306 if (status
!= AsyncStatus::Completed
) {
2307 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2309 ComPtr
<IVectorView
<AppListEntry
*>> appListEntries
;
2310 HRESULT hr
= operation
->GetResults(&appListEntries
);
2312 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2314 ComPtr
<IStartScreenManager
> startScreenManager
;
2315 ComPtr
<IAppListEntry
> entry
;
2316 hr
= GetStartScreenManager(appListEntries
, entry
,
2317 startScreenManager
);
2319 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2321 ComPtr
<IAsyncOperation
<bool>> getPinnedOperation
;
2322 hr
= startScreenManager
->ContainsAppListEntryAsync(
2323 entry
.Get(), &getPinnedOperation
);
2325 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2327 auto getPinnedCallback
=
2328 Callback
<IAsyncOperationCompletedHandler
<bool>>(
2329 [promiseHolder
, entry
, startScreenManager
, aCheckOnly
](
2330 IAsyncOperation
<bool>* operation
,
2331 AsyncStatus status
) -> HRESULT
{
2332 if (status
!= AsyncStatus::Completed
) {
2333 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
,
2336 boolean isAlreadyPinned
;
2337 HRESULT hr
= operation
->GetResults(&isAlreadyPinned
);
2339 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
,
2342 // If we're already pinned we can return early
2343 // Ditto if we're just checking whether we *can* pin
2344 if (isAlreadyPinned
|| aCheckOnly
) {
2345 RESOLVE_AND_RETURN(promiseHolder
, true, S_OK
);
2347 ComPtr
<IAsyncOperation
<bool>> pinOperation
;
2348 startScreenManager
->RequestAddAppListEntryAsync(
2349 entry
.Get(), &pinOperation
);
2350 // Set another callback for pinning to the start menu
2351 auto pinOperationCallback
=
2352 Callback
<IAsyncOperationCompletedHandler
<bool>>(
2353 [promiseHolder
](IAsyncOperation
<bool>* operation
,
2354 AsyncStatus status
) -> HRESULT
{
2355 if (status
!= AsyncStatus::Completed
) {
2356 REJECT_AND_RETURN(promiseHolder
,
2357 NS_ERROR_FAILURE
, E_FAIL
);
2360 HRESULT hr
= operation
->GetResults(&pinSuccess
);
2362 REJECT_AND_RETURN(promiseHolder
,
2363 NS_ERROR_FAILURE
, E_FAIL
);
2365 RESOLVE_AND_RETURN(promiseHolder
,
2366 pinSuccess
? true : false,
2369 hr
= pinOperation
->put_Completed(
2370 pinOperationCallback
.Get());
2372 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, hr
);
2376 hr
= getPinnedOperation
->put_Completed(getPinnedCallback
.Get());
2378 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, hr
);
2382 hr
= getAppListEntriesOperation
->put_Completed(
2383 getAppListEntriesCallback
.Get());
2385 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2390 nsWindowsShellService::PinCurrentAppToStartMenuAsync(bool aCheckOnly
,
2392 dom::Promise
** aPromise
) {
2393 if (!NS_IsMainThread()) {
2394 return NS_ERROR_NOT_SAME_THREAD
;
2396 // Unfortunately pinning to the Start Menu requires IAppListEntry
2397 // which is only implemented for packaged applications.
2398 if (!widget::WinUtils::HasPackageIdentity()) {
2399 return NS_ERROR_NOT_AVAILABLE
;
2402 RefPtr
<dom::Promise
> promise
=
2403 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
2404 if (MOZ_UNLIKELY(rv
.Failed())) {
2405 return rv
.StealNSResult();
2408 // A holder to pass the promise through the background task and back to
2409 // the main thread when finished.
2410 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
2411 "PinCurrentAppToStartMenuAsync promise", promise
);
2412 NS_DispatchBackgroundTask(NS_NewRunnableFunction(
2413 "PinCurrentAppToStartMenuAsync", [aCheckOnly
, promiseHolder
] {
2414 PinCurrentAppToStartMenuAsyncImpl(aCheckOnly
, promiseHolder
);
2416 promise
.forget(aPromise
);
2420 static void IsCurrentAppPinnedToStartMenuAsyncImpl(
2421 const RefPtr
<nsMainThreadPtrHolder
<dom::Promise
>> promiseHolder
) {
2422 ComPtr
<IPackage3
> package3
;
2423 HRESULT hr
= GetPackage3(package3
);
2425 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2428 // Get the AppList entries
2429 ComPtr
<IVectorView
<AppListEntry
*>> appListEntries
;
2430 ComPtr
<IAsyncOperation
<IVectorView
<AppListEntry
*>*>>
2431 getAppListEntriesOperation
;
2432 hr
= package3
->GetAppListEntriesAsync(&getAppListEntriesOperation
);
2434 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2436 auto getAppListEntriesCallback
=
2437 Callback
<IAsyncOperationCompletedHandler
<IVectorView
<AppListEntry
*>*>>(
2439 IAsyncOperation
<IVectorView
<AppListEntry
*>*>* operation
,
2440 AsyncStatus status
) -> HRESULT
{
2441 if (status
!= AsyncStatus::Completed
) {
2442 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2444 ComPtr
<IVectorView
<AppListEntry
*>> appListEntries
;
2445 HRESULT hr
= operation
->GetResults(&appListEntries
);
2447 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2449 ComPtr
<IStartScreenManager
> startScreenManager
;
2450 ComPtr
<IAppListEntry
> entry
;
2451 hr
= GetStartScreenManager(appListEntries
, entry
,
2452 startScreenManager
);
2454 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2456 ComPtr
<IAsyncOperation
<bool>> getPinnedOperation
;
2457 hr
= startScreenManager
->ContainsAppListEntryAsync(
2458 entry
.Get(), &getPinnedOperation
);
2460 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, E_FAIL
);
2462 auto getPinnedCallback
=
2463 Callback
<IAsyncOperationCompletedHandler
<bool>>(
2464 [promiseHolder
, entry
, startScreenManager
](
2465 IAsyncOperation
<bool>* operation
,
2466 AsyncStatus status
) -> HRESULT
{
2467 if (status
!= AsyncStatus::Completed
) {
2468 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
,
2471 boolean isAlreadyPinned
;
2472 HRESULT hr
= operation
->GetResults(&isAlreadyPinned
);
2474 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
,
2477 RESOLVE_AND_RETURN(promiseHolder
,
2478 isAlreadyPinned
? true : false, S_OK
);
2480 hr
= getPinnedOperation
->put_Completed(getPinnedCallback
.Get());
2482 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, hr
);
2486 hr
= getAppListEntriesOperation
->put_Completed(
2487 getAppListEntriesCallback
.Get());
2489 REJECT_AND_RETURN(promiseHolder
, NS_ERROR_FAILURE
, /* void */);
2494 nsWindowsShellService::IsCurrentAppPinnedToStartMenuAsync(
2495 JSContext
* aCx
, dom::Promise
** aPromise
) {
2496 if (!NS_IsMainThread()) {
2497 return NS_ERROR_NOT_SAME_THREAD
;
2499 // Unfortunately pinning to the Start Menu requires IAppListEntry
2500 // which is only implemented for packaged applications.
2501 if (!widget::WinUtils::HasPackageIdentity()) {
2502 return NS_ERROR_NOT_AVAILABLE
;
2505 RefPtr
<dom::Promise
> promise
=
2506 dom::Promise::Create(xpc::CurrentNativeGlobal(aCx
), rv
);
2507 if (MOZ_UNLIKELY(rv
.Failed())) {
2508 return rv
.StealNSResult();
2511 // A holder to pass the promise through the background task and back to
2512 // the main thread when finished.
2513 auto promiseHolder
= MakeRefPtr
<nsMainThreadPtrHolder
<dom::Promise
>>(
2514 "IsCurrentAppPinnedToStartMenuAsync promise", promise
);
2515 NS_DispatchBackgroundTask(NS_NewRunnableFunction(
2516 "IsCurrentAppPinnedToStartMenuAsync", [promiseHolder
] {
2517 IsCurrentAppPinnedToStartMenuAsyncImpl(promiseHolder
);
2519 promise
.forget(aPromise
);
2525 nsWindowsShellService::EnableLaunchOnLoginMSIXAsync(
2526 const nsAString
& aTaskId
, JSContext
* aCx
,
2527 /* out */ dom::Promise
** aPromise
) {
2528 return NS_ERROR_NOT_IMPLEMENTED
;
2532 nsWindowsShellService::DisableLaunchOnLoginMSIXAsync(
2533 const nsAString
& aTaskId
, JSContext
* aCx
,
2534 /* out */ dom::Promise
** aPromise
) {
2535 return NS_ERROR_NOT_IMPLEMENTED
;
2539 nsWindowsShellService::GetLaunchOnLoginEnabledMSIXAsync(
2540 const nsAString
& aTaskId
, JSContext
* aCx
,
2541 /* out */ dom::Promise
** aPromise
) {
2542 return NS_ERROR_NOT_IMPLEMENTED
;
2546 nsWindowsShellService::PinCurrentAppToStartMenuAsync(bool aCheckOnly
,
2548 dom::Promise
** aPromise
) {
2549 return NS_ERROR_NOT_IMPLEMENTED
;
2553 nsWindowsShellService::IsCurrentAppPinnedToStartMenuAsync(
2554 JSContext
* aCx
, dom::Promise
** aPromise
) {
2555 return NS_ERROR_NOT_IMPLEMENTED
;
2560 nsWindowsShellService::ClassifyShortcut(const nsAString
& aPath
,
2561 nsAString
& aResult
) {
2564 nsAutoString
shortcutPath(PromiseFlatString(aPath
));
2566 // NOTE: On Windows 7, Start Menu pin shortcuts are stored under
2567 // "<FOLDERID_User Pinned>\StartMenu", but on Windows 10 they are just normal
2568 // Start Menu shortcuts. These both map to "StartMenu" for consistency,
2569 // rather than having a separate "StartMenuPins" which would only apply on
2572 KNOWNFOLDERID folderId
;
2573 const char16_t
* postfix
;
2574 const char16_t
* classification
;
2575 } folders
[] = {{FOLDERID_CommonStartMenu
, u
"\\", u
"StartMenu"},
2576 {FOLDERID_StartMenu
, u
"\\", u
"StartMenu"},
2577 {FOLDERID_PublicDesktop
, u
"\\", u
"Desktop"},
2578 {FOLDERID_Desktop
, u
"\\", u
"Desktop"},
2579 {FOLDERID_UserPinned
, u
"\\TaskBar\\", u
"Taskbar"},
2580 {FOLDERID_UserPinned
, u
"\\StartMenu\\", u
"StartMenu"}};
2582 for (size_t i
= 0; i
< ArrayLength(folders
); ++i
) {
2583 nsAutoString knownPath
;
2585 // These flags are chosen to avoid I/O, see bug 1363398.
2587 KF_FLAG_SIMPLE_IDLIST
| KF_FLAG_DONT_VERIFY
| KF_FLAG_NO_ALIAS
;
2588 PWSTR rawPath
= nullptr;
2590 if (FAILED(SHGetKnownFolderPath(folders
[i
].folderId
, flags
, nullptr,
2595 knownPath
= nsDependentString(rawPath
);
2596 CoTaskMemFree(rawPath
);
2598 knownPath
.Append(folders
[i
].postfix
);
2599 // Check if the shortcut path starts with the shell folder path.
2600 if (wcsnicmp(shortcutPath
.get(), knownPath
.get(), knownPath
.Length()) ==
2602 aResult
.Assign(folders
[i
].classification
);
2603 nsTArray
<nsCString
> resIds
= {
2604 "branding/brand.ftl"_ns
,
2605 "browser/browser.ftl"_ns
,
2607 RefPtr
<Localization
> l10n
= Localization::Create(resIds
, true);
2608 nsAutoCString pbStr
;
2609 IgnoredErrorResult rv
;
2610 l10n
->FormatValueSync("private-browsing-shortcut-text-2"_ns
, {}, pbStr
,
2612 NS_ConvertUTF8toUTF16
widePbStr(pbStr
);
2613 if (wcsstr(shortcutPath
.get(), widePbStr
.get())) {
2614 aResult
.AppendLiteral("Private");
2620 // Nothing found, aResult is already "".
2624 nsWindowsShellService::nsWindowsShellService() {}
2626 nsWindowsShellService::~nsWindowsShellService() {}