Bug 1884265 - Expose pretty ApplicationName from the registry to file handlers r=nrishel,nalexander,necko-reviewers,barret,valentin

Some code to exercise this in the browser console:

```
{
  const printNames = async (appList) => {
    let buffer = "Start:\n";

    for (let index = 0; index < appList4.length; index++) {
      let app = appList4.queryElementAt(index, Ci.nsILocalHandlerApp);
      buffer += app.executable.leafName;
      buffer += "\n";
    }

    buffer += "\n";

    for (let index = 0; index < appList4.length; index++) {
      let app = appList4.queryElementAt(index, Ci.nsILocalHandlerApp);
      let prettyName = await app.prettyNameAsync();
      buffer += prettyName;
      buffer += "\n";
    }

    buffer += "\n";

    for (let index = 0; index < appList4.length; index++) {
      let app = appList4.queryElementAt(index, Ci.nsILocalHandlerApp);
      buffer += app.executable.displayName;
      buffer += "\n";
    }

    buffer += "\n";

    for (let index = 0; index < appList4.length; index++) {
      let app = appList4.queryElementAt(index, Ci.nsILocalHandlerApp);
      if (AppConstants.platform == "win") {
      	let file = app.executable;
        if (file instanceof Ci.nsILocalFileWin) {
          try {
          	buffer += file.getVersionInfoField("FileDescription");
          } catch (e) {
          }
        }
      }
      buffer += "\n";
    }

    buffer += "\nEnd\n";

    console.log(buffer);
  };

  const lazy4 = {};

  XPCOMUtils.defineLazyServiceGetters(lazy4, {
    gMIMEService: ["@mozilla.org/mime;1", "nsIMIMEService"],
  });

  let mimeInfo4 = lazy4.gMIMEService.getFromTypeAndExtension("text/html", "html");

  if (mimeInfo4.hasDefaultHandler) {
    console.log(`HasDefaultHandler = true`);
    console.log(`Description = ${mimeInfo4.defaultDescription}`);
  } else {
    console.log(`HasDefaultHandler = false`);
  }

  let appList4 = mimeInfo4.possibleLocalHandlers || [];
  console.log("appList4 = ");
  console.log(JSON.stringify(appList4));

  printNames(appList4);
}
```

That produces output that can be seen in a pretty form here:
https://docs.google.com/spreadsheets/d/1OvtrZgMlPMJO4Wgu6wwAYvm89orj9HdS_tsDxYn7yrA/edit#gid=0

This does not fix-up things so that all calls to getName() on the LocalHandlerApp are switched to prettyNameAsync. That work is tracked here: https://bugzilla.mozilla.org/show_bug.cgi?id=1884267

Differential Revision: https://phabricator.services.mozilla.com/D203876
This commit is contained in:
Michael Hughes 2024-03-25 23:19:17 +00:00
Родитель 75050b93a2
Коммит e66ab7ac30
10 изменённых файлов: 379 добавлений и 9 удалений

Просмотреть файл

@ -280,6 +280,24 @@ interface nsILocalHandlerApp : nsIHandlerApp {
*/
readonly attribute unsigned long parameterCount;
/**
* Asynchronously returns the pretty (user friendly) name of the
* executable.
*
* On Linux and Mac, this is the same as the name
* property. On Mac, that happens to be a nicer name than
* the executable's name without the file extension.
*
* On Windows, this name will be nicer, looked up from the
* registry when it exists and falling back to the FileDescription
* getVersionFieldInfo when the registry data doesn't exist.
* This has the side effect that the prettyName returned
* generally will match the text returned by defaultDescription in
* nsIHandlerInfo.
*/
[implicit_jscontext]
Promise prettyNameAsync();
/**
* Clears the current list of command line parameters.
*/

Просмотреть файл

@ -95,6 +95,7 @@ elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "android":
]
elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "windows":
UNIFIED_SOURCES += [
"win/nsLocalHandlerAppWin.cpp",
"win/nsMIMEInfoWin.cpp",
]

Просмотреть файл

@ -8,11 +8,15 @@
#include "nsIURI.h"
#include "nsIProcess.h"
#include "nsComponentManagerUtils.h"
#include "mozilla/dom/Promise.h"
#include "nsProxyRelease.h"
// XXX why does nsMIMEInfoImpl have a threadsafe nsISupports? do we need one
// here too?
NS_IMPL_ISUPPORTS(nsLocalHandlerApp, nsILocalHandlerApp, nsIHandlerApp)
using namespace mozilla;
////////////////////////////////////////////////////////////////////////////////
//// nsIHandlerApp
@ -28,6 +32,100 @@ NS_IMETHODIMP nsLocalHandlerApp::GetName(nsAString& aName) {
return NS_OK;
}
/**
* This method returns a std::function that will be executed on a thread other
* than the main thread. To facilitate things, it should effectively be a global
* function that does not maintain a reference to the this pointer. There should
* be no reference to any objects that will be shared across threads. Sub-class
* implementations should make local copies of everything they need and capture
* those in the callback.
*/
std::function<nsresult(nsString&)>
nsLocalHandlerApp::GetPrettyNameOnNonMainThreadCallback() {
nsString name;
// Calculate the name now, on the main thread, so as to avoid
// doing anything with the this pointer on the other thread
auto result = GetName(name);
return [name, result](nsString& aName) -> nsresult {
aName = name;
return result;
};
}
NS_IMETHODIMP
nsLocalHandlerApp::PrettyNameAsync(JSContext* aCx, dom::Promise** aPromise) {
NS_ENSURE_ARG_POINTER(aPromise);
*aPromise = nullptr;
if (!mExecutable) {
return NS_ERROR_FAILURE;
}
nsIGlobalObject* global = xpc::CurrentNativeGlobal(aCx);
if (NS_WARN_IF(!global)) {
return NS_ERROR_FAILURE;
}
ErrorResult err;
RefPtr<dom::Promise> outer = dom::Promise::Create(global, err);
if (NS_WARN_IF(err.Failed())) {
return err.StealNSResult();
}
outer.forget(aPromise);
nsAutoString executablePath;
nsresult result = mExecutable->GetPath(executablePath);
if (NS_FAILED(result) || executablePath.IsEmpty()) {
(*aPromise)->MaybeReject(result);
return NS_OK;
}
nsMainThreadPtrHandle<dom::Promise> promiseHolder(
new nsMainThreadPtrHolder<dom::Promise>(
"nsLocalHandlerApp::prettyExecutableName Promise", *aPromise));
auto prettyNameGetter = GetPrettyNameOnNonMainThreadCallback();
result = NS_DispatchBackgroundTask(
NS_NewRunnableFunction(
__func__,
[promiseHolder /* can't move this because if the dispatch fails, we
call reject on the promiseHolder */
,
prettyNameGetter = std::move(prettyNameGetter)]() mutable -> void {
nsAutoString prettyExecutableName;
nsresult result = prettyNameGetter(prettyExecutableName);
DebugOnly<nsresult> rv =
NS_DispatchToMainThread(NS_NewRunnableFunction(
__func__,
[promiseHolder = std::move(promiseHolder),
prettyExecutableName = std::move(prettyExecutableName),
result]() {
if (NS_FAILED(result)) {
promiseHolder.get()->MaybeReject(result);
} else {
promiseHolder.get()->MaybeResolve(prettyExecutableName);
}
}));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"NS_DispatchToMainThread failed");
}),
NS_DISPATCH_EVENT_MAY_BLOCK);
if (NS_FAILED(result)) {
promiseHolder.get()->MaybeReject(result);
}
return NS_OK;
}
NS_IMETHODIMP nsLocalHandlerApp::SetName(const nsAString& aName) {
mName.Assign(aName);

Просмотреть файл

@ -12,6 +12,8 @@
#include "nsIFile.h"
#include "nsTArray.h"
#include <functional>
class nsLocalHandlerApp : public nsILocalHandlerApp {
public:
NS_DECL_ISUPPORTS
@ -29,6 +31,9 @@ class nsLocalHandlerApp : public nsILocalHandlerApp {
protected:
virtual ~nsLocalHandlerApp() {}
virtual std::function<nsresult(nsString&)>
GetPrettyNameOnNonMainThreadCallback();
nsString mName;
nsString mDetailedDescription;
nsTArray<nsString> mParameters;
@ -52,6 +57,11 @@ class nsLocalHandlerApp : public nsILocalHandlerApp {
# include "mac/nsLocalHandlerAppMac.h"
typedef nsLocalHandlerAppMac PlatformLocalHandlerApp_t;
# endif
#elif XP_WIN
# ifndef NSLOCALHANDLERAPPWIN_H_
# include "win/nsLocalHandlerAppWin.h"
typedef nsLocalHandlerAppWin PlatformLocalHandlerApp_t;
# endif
#else
typedef nsLocalHandlerApp PlatformLocalHandlerApp_t;
#endif

Просмотреть файл

@ -15,3 +15,87 @@ add_task(async function test_utf8_extension() {
Assert.equal(someMIME.primaryExtension, ".тест");
}
});
add_task(async function test_pretty_name_for_edge() {
if (AppConstants.platform == "win" && !AppConstants.IS_ESR) {
const mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
let mimeInfo = mimeService.getFromTypeAndExtension("text/html", "html");
let appList = [];
try {
appList = mimeInfo?.possibleLocalHandlers || [];
} catch (err) {
// if the mime info on this platform doesn't support getting local handlers,
// we don't need to test
if (err.result == Cr.NS_ERROR_NOT_IMPLEMENTED) {
return;
}
// otherwise, throw the err because the test is broken
throw err;
}
for (let index = 0; index < appList.length; index++) {
let app = appList.queryElementAt(index, Ci.nsILocalHandlerApp);
if (app) {
let executableName = app.executable?.displayName;
if (executableName) {
let prettyName = await app.prettyNameAsync();
// Hardcode Edge, as an extra test, when it's installed
if (executableName == "msedge.exe") {
Assert.equal(
prettyName,
"Microsoft Edge",
"The generated pretty name for MS Edge should match the expectation."
);
}
// The pretty name should always be something nicer than the executable name.
// This isn't testing that's nice, but should be good enough to validate that
// something other than the executable is found.
Assert.notEqual(executableName, prettyName);
}
}
}
}
});
add_task(async function test_pretty_names_match_names_on_non_windows() {
if (AppConstants.platform != "win") {
const mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
let mimeInfo = mimeService.getFromTypeAndExtension("text/html", "html");
let appList = [];
try {
appList = mimeInfo?.possibleLocalHandlers || [];
} catch (err) {
// if the mime info on this platform doesn't support getting local handlers,
// we don't need to test
if (err.result == Cr.NS_ERROR_NOT_IMPLEMENTED) {
return;
}
// otherwise, throw the err because the test is broken
throw err;
}
for (let index = 0; index < appList.length; index++) {
let app = appList.queryElementAt(index, Ci.nsILocalHandlerApp);
if (app) {
if (app.executable) {
let name = app.executable.name;
let prettyName = await app.prettyNameAsync();
Assert.equal(
prettyName,
name,
"On platforms other than windows, the prettyName and the name of file handlers should be the same."
);
}
}
}
}
});

Просмотреть файл

@ -18,6 +18,7 @@ skip-if = [
skip-if = ["os == 'mac'"] # Bug 1817727
["test_getFromTypeAndExtension.js"]
skip-if = ["os == 'android'"]
["test_getMIMEInfo_pdf.js"]

Просмотреть файл

@ -0,0 +1,119 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsLocalHandlerAppWin.h"
#include "nsString.h"
#include "nsIWindowsRegKey.h"
#include "nsILocalFileWin.h"
#include "nsComponentManagerUtils.h"
static nsresult GetPrettyNameFromFileDescription(
const nsCOMPtr<nsILocalFileWin>& executableOnWindows,
const nsString& assignedName, nsString& aName) {
nsresult result = NS_ERROR_FAILURE;
if (executableOnWindows) {
result = executableOnWindows->GetVersionInfoField("FileDescription", aName);
if (NS_FAILED(result) || aName.IsEmpty()) {
if (!assignedName.IsEmpty()) {
aName = assignedName;
} else {
result = executableOnWindows->GetLeafName(aName);
}
if (!aName.IsEmpty()) {
result = NS_OK;
} else {
result = NS_ERROR_FAILURE;
}
}
}
return result;
}
static nsresult GetValueFromRegistry(nsString& aName,
const nsCOMPtr<nsIWindowsRegKey>& appKey,
const nsString& registryPath,
const nsString& valueName) {
nsresult rv =
appKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, registryPath,
nsIWindowsRegKey::ACCESS_QUERY_VALUE);
if (NS_SUCCEEDED(rv)) {
nsAutoString applicationName;
if (NS_SUCCEEDED(appKey->ReadStringValue(valueName, applicationName))) {
aName = applicationName;
return NS_OK;
}
}
return NS_ERROR_FAILURE;
};
std::function<nsresult(nsString&)>
nsLocalHandlerAppWin::GetPrettyNameOnNonMainThreadCallback() {
// Make a copy of executable so that we don't have to worry about any other
// threads
nsCOMPtr<nsIFile> executable;
mExecutable->Clone(getter_AddRefs(executable));
// Get the windows interface to the file
nsCOMPtr<nsILocalFileWin> executableOnWindows(do_QueryInterface(executable));
auto appIdOrName = mAppIdOrName;
auto assignedName = mName;
std::function<nsresult(nsString&)> callback =
[assignedName, appIdOrName,
executableOnWindows =
std::move(executableOnWindows)](nsString& aName) -> nsresult {
// On all platforms, we want a human readable name for an application.
// For example: msedge -> Microsoft Edge Browser
//
// This is generated on mac directly in nsLocalHandlerAppMac::GetName.
// The auto-test coverage for GetName isn't thorough enough to be
// confident that changing GetName on Windows won't cause problems.
//
// Besides that, this is a potentially slow thing to execute, and making
// it asynchronous is preferable. There's a fallback to GetName() in the
// nsLocalHandlerApp::PrettyNameAsync to cover Mac and Linux.
if (appIdOrName.IsEmpty()) {
return GetPrettyNameFromFileDescription(executableOnWindows, assignedName,
aName);
}
nsCOMPtr<nsIWindowsRegKey> appKey =
do_CreateInstance("@mozilla.org/windows-registry-key;1");
if (!appKey) {
return GetPrettyNameFromFileDescription(executableOnWindows, assignedName,
aName);
}
// Check for ApplicationName first. Path:
// HKEY_CLASSES_ROOT\${APP_ID}\Application, Value entry: ApplicationName
nsresult rv =
GetValueFromRegistry(aName, appKey, appIdOrName + u"\\Application"_ns,
u"ApplicationName"_ns);
if (NS_SUCCEEDED(rv) && !aName.IsEmpty()) {
return rv;
}
// Check for the default on the Applications entry next.
// Path: HKEY_CLASSES_ROOT\Applications\${APP_ID}, Value entry: ""
// (default)
rv = GetValueFromRegistry(aName, appKey, u"Applications\\"_ns + appIdOrName,
u""_ns);
if (NS_SUCCEEDED(rv) && !aName.IsEmpty()) {
return rv;
}
// Fallthrough to getting the name from the file description
return GetPrettyNameFromFileDescription(executableOnWindows, assignedName,
aName);
};
return callback;
}

Просмотреть файл

@ -0,0 +1,34 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef NSLOCALHANDLERAPPWIN_H_
#define NSLOCALHANDLERAPPWIN_H_
#include "nsLocalHandlerApp.h"
#include "nsString.h"
class nsLocalHandlerAppWin : public nsLocalHandlerApp {
public:
nsLocalHandlerAppWin() {}
nsLocalHandlerAppWin(const char16_t* aName, nsIFile* aExecutable)
: nsLocalHandlerApp(aName, aExecutable) {}
nsLocalHandlerAppWin(const nsAString& aName, nsIFile* aExecutable)
: nsLocalHandlerApp(aName, aExecutable) {}
virtual ~nsLocalHandlerAppWin() {}
void SetAppIdOrName(const nsString& appIdOrName) {
mAppIdOrName = appIdOrName;
}
protected:
std::function<nsresult(nsString&)> GetPrettyNameOnNonMainThreadCallback()
override;
private:
nsString mAppIdOrName;
};
#endif /*NSLOCALHANDLERAPPMAC_H_*/

Просмотреть файл

@ -9,6 +9,7 @@
#include "nsCOMArray.h"
#include "nsLocalFile.h"
#include "nsMIMEInfoWin.h"
#include "nsLocalHandlerAppWin.h"
#include "nsIMIMEService.h"
#include "nsNetUtil.h"
#include <windows.h>
@ -554,6 +555,7 @@ bool nsMIMEInfoWin::GetProgIDVerbCommandHandler(const nsAString& appProgIDName,
// entries to lower case and stores them in the trackList array.
void nsMIMEInfoWin::ProcessPath(nsCOMPtr<nsIMutableArray>& appList,
nsTArray<nsString>& trackList,
const nsAutoString& appIdOrName,
const nsAString& appFilesystemCommand) {
nsAutoString lower(appFilesystemCommand);
ToLowerCase(lower);
@ -569,6 +571,9 @@ void nsMIMEInfoWin::ProcessPath(nsCOMPtr<nsIMutableArray>& appList,
nsCOMPtr<nsILocalHandlerApp> aApp;
if (!GetLocalHandlerApp(appFilesystemCommand, aApp)) return;
// Track the app id so that the pretty name can be determined later
(static_cast<nsLocalHandlerAppWin*>(aApp.get()))->SetAppIdOrName(appIdOrName);
// Save in our main tracking arrays
appList->AppendElement(aApp);
trackList.AppendElement(lower);
@ -673,7 +678,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) {
if (GetProgIDVerbCommandHandler(appProgId, appFilesystemCommand,
false) &&
!IsPathInList(appFilesystemCommand, trackList)) {
ProcessPath(appList, trackList, appFilesystemCommand);
ProcessPath(appList, trackList, appProgId, appFilesystemCommand);
}
}
}
@ -701,7 +706,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) {
false) ||
IsPathInList(appFilesystemCommand, trackList))
continue;
ProcessPath(appList, trackList, appFilesystemCommand);
ProcessPath(appList, trackList, appName, appFilesystemCommand);
}
}
regKey->Close();
@ -729,7 +734,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) {
false) ||
IsPathInList(appFilesystemCommand, trackList))
continue;
ProcessPath(appList, trackList, appFilesystemCommand);
ProcessPath(appList, trackList, appProgId, appFilesystemCommand);
}
}
regKey->Close();
@ -762,7 +767,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) {
false) ||
IsPathInList(appFilesystemCommand, trackList))
continue;
ProcessPath(appList, trackList, appFilesystemCommand);
ProcessPath(appList, trackList, appValue, appFilesystemCommand);
}
}
}
@ -791,7 +796,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) {
false) ||
IsPathInList(appFilesystemCommand, trackList))
continue;
ProcessPath(appList, trackList, appFilesystemCommand);
ProcessPath(appList, trackList, appProgId, appFilesystemCommand);
}
}
regKey->Close();
@ -829,7 +834,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) {
false) ||
IsPathInList(appFilesystemCommand, trackList))
continue;
ProcessPath(appList, trackList, appFilesystemCommand);
ProcessPath(appList, trackList, appName, appFilesystemCommand);
}
}
}
@ -857,7 +862,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) {
if (!GetAppsVerbCommandHandler(appName, appFilesystemCommand, false) ||
IsPathInList(appFilesystemCommand, trackList))
continue;
ProcessPath(appList, trackList, appFilesystemCommand);
ProcessPath(appList, trackList, appName, appFilesystemCommand);
}
}
regKey->Close();
@ -882,7 +887,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) {
if (!GetAppsVerbCommandHandler(appName, appFilesystemCommand, false) ||
IsPathInList(appFilesystemCommand, trackList))
continue;
ProcessPath(appList, trackList, appFilesystemCommand);
ProcessPath(appList, trackList, appName, appFilesystemCommand);
}
}
}

Просмотреть файл

@ -68,7 +68,7 @@ class nsMIMEInfoWin : public nsMIMEInfoBase, public nsIPropertyBag {
// Helper routine used in tracking app lists
void ProcessPath(nsCOMPtr<nsIMutableArray>& appList,
nsTArray<nsString>& trackList,
nsTArray<nsString>& trackList, const nsAutoString& appId,
const nsAString& appFilesystemCommand);
// Helper routine to call mozilla::ShellExecuteByExplorer