Bug 1239694 Implemenet Gnome search provider, r=jhorak,mak

Implement org.gnome.Shell.SearchProvider2 D-Bus interface and enable it when
widget.gnome-search-provider.enabled pref is set, so this feature is disabled
by default.

Differential Revision: https://phabricator.services.mozilla.com/D69181
This commit is contained in:
Martin Stransky
2020-04-29 18:02:23 +00:00
parent 05de0715f6
commit 02d6c61742
11 changed files with 919 additions and 1 deletions

View File

@@ -40,6 +40,13 @@ elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gtk':
SOURCES += [
'nsGNOMEShellService.cpp',
]
if CONFIG['MOZ_ENABLE_DBUS']:
SOURCES += [
'nsGNOMEShellDBusHelper.cpp',
'nsGNOMEShellSearchProvider.cpp',
]
include('/ipc/chromium/chromium-config.mozbuild')
elif CONFIG['OS_ARCH'] == 'WINNT':
XPIDL_SOURCES += [
'nsIWindowsShellService.idl',
@@ -66,6 +73,8 @@ for var in ('MOZ_APP_NAME', 'MOZ_APP_VERSION'):
DEFINES[var] = '"%s"' % CONFIG[var]
CXXFLAGS += CONFIG['TK_CFLAGS']
if CONFIG['MOZ_ENABLE_DBUS']:
CXXFLAGS += CONFIG['MOZ_DBUS_GLIB_CFLAGS']
with Files('**'):
BUG_COMPONENT = ('Firefox', 'Shell Integration')

View File

@@ -0,0 +1,442 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:expandtab:shiftwidth=2:tabstop=2:
*/
/* 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 "nsGNOMEShellSearchProvider.h"
#include "nsGNOMEShellDBusHelper.h"
#include "nsPrintfCString.h"
#include "RemoteUtils.h"
#include "nsServiceManagerUtils.h"
static bool GetGnomeSearchTitle(const char* aSearchedTerm,
nsAutoCString& aGnomeSearchTitle) {
static nsCOMPtr<nsIStringBundle> bundle;
if (!bundle) {
nsCOMPtr<nsIStringBundleService> sbs =
do_GetService(NS_STRINGBUNDLE_CONTRACTID);
if (NS_WARN_IF(!sbs)) {
return false;
}
sbs->CreateBundle("chrome://browser/locale/browser.properties",
getter_AddRefs(bundle));
if (NS_WARN_IF(!bundle)) {
return false;
}
}
AutoTArray<nsString, 1> formatStrings;
CopyASCIItoUTF16(nsCString(aSearchedTerm), *formatStrings.AppendElement());
nsAutoString gnomeSearchTitle;
bundle->FormatStringFromName("gnomeSearchProviderSearch", formatStrings,
gnomeSearchTitle);
AppendUTF16toUTF8(gnomeSearchTitle, aGnomeSearchTitle);
return true;
}
static const char* introspect_template =
"<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection "
"1.0//EN\"\n"
"\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\";>\n"
"<node>\n"
" <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
" <method name=\"Introspect\">\n"
" <arg name=\"data\" direction=\"out\" type=\"s\"/>\n"
" </method>\n"
" </interface>\n"
" <interface name=\"org.gnome.Shell.SearchProvider2\">\n"
" <method name=\"GetInitialResultSet\">\n"
" <arg type=\"as\" name=\"terms\" direction=\"in\" />\n"
" <arg type=\"as\" name=\"results\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"GetSubsearchResultSet\">\n"
" <arg type=\"as\" name=\"previous_results\" direction=\"in\" />\n"
" <arg type=\"as\" name=\"terms\" direction=\"in\" />\n"
" <arg type=\"as\" name=\"results\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"GetResultMetas\">\n"
" <arg type=\"as\" name=\"identifiers\" direction=\"in\" />\n"
" <arg type=\"aa{sv}\" name=\"metas\" direction=\"out\" />\n"
" </method>\n"
" <method name=\"ActivateResult\">\n"
" <arg type=\"s\" name=\"identifier\" direction=\"in\" />\n"
" <arg type=\"as\" name=\"terms\" direction=\"in\" />\n"
" <arg type=\"u\" name=\"timestamp\" direction=\"in\" />\n"
" </method>\n"
" <method name=\"LaunchSearch\">\n"
" <arg type=\"as\" name=\"terms\" direction=\"in\" />\n"
" <arg type=\"u\" name=\"timestamp\" direction=\"in\" />\n"
" </method>\n"
"</interface>\n"
"</node>\n";
DBusHandlerResult DBusIntrospect(DBusConnection* aConnection,
DBusMessage* aMsg) {
DBusMessage* reply;
reply = dbus_message_new_method_return(aMsg);
if (!reply) {
return DBUS_HANDLER_RESULT_NEED_MEMORY;
}
dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspect_template,
DBUS_TYPE_INVALID);
dbus_connection_send(aConnection, reply, nullptr);
dbus_message_unref(reply);
return DBUS_HANDLER_RESULT_HANDLED;
}
int DBusGetIndexFromIDKey(const char* aIDKey) {
// ID is NN:URL where NN is index to our current history
// result container.
char tmp[] = {aIDKey[0], aIDKey[1], '\0'};
return atoi(tmp);
}
DBusHandlerResult DBusHandleInitialResultSet(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg) {
DBusMessage* reply;
char** stringArray = nullptr;
int elements;
if (!dbus_message_get_args(aMsg, nullptr, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING,
&stringArray, &elements, DBUS_TYPE_INVALID) ||
elements == 0) {
reply = dbus_message_new_error(aMsg, DBUS_BUS_NAME, "Wrong argument");
dbus_connection_send(aSearchResult->GetDBusConnection(), reply, nullptr);
dbus_message_unref(reply);
} else {
aSearchResult->SetReply(dbus_message_new_method_return(aMsg));
aSearchResult->SetSearchTerm(stringArray[0]);
GetGNOMEShellHistoryService()->QueryHistory(aSearchResult);
// DBus reply will be send asynchronously by
// nsGNOMEShellHistorySearchResult::SendDBusSearchResultReply()
// when GetGNOMEShellHistoryService() has the results.
}
if (stringArray) {
dbus_free_string_array(stringArray);
}
return DBUS_HANDLER_RESULT_HANDLED;
}
DBusHandlerResult DBusHandleSubsearchResultSet(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg) {
DBusMessage* reply;
char **unusedArray = nullptr, **stringArray = nullptr;
int unusedNum, elements;
if (!dbus_message_get_args(aMsg, nullptr, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING,
&unusedArray, &unusedNum, DBUS_TYPE_ARRAY,
DBUS_TYPE_STRING, &stringArray, &elements,
DBUS_TYPE_INVALID) ||
elements == 0) {
reply = dbus_message_new_error(aMsg, DBUS_BUS_NAME, "Wrong argument");
dbus_connection_send(aSearchResult->GetDBusConnection(), reply, nullptr);
dbus_message_unref(reply);
} else {
aSearchResult->SetReply(dbus_message_new_method_return(aMsg));
aSearchResult->SetSearchTerm(stringArray[0]);
GetGNOMEShellHistoryService()->QueryHistory(aSearchResult);
// DBus reply will be send asynchronously by
// nsGNOMEShellHistorySearchResult::SendDBusSearchResultReply()
// when GetGNOMEShellHistoryService() has the results.
}
if (unusedArray) {
dbus_free_string_array(unusedArray);
}
if (stringArray) {
dbus_free_string_array(stringArray);
}
return DBUS_HANDLER_RESULT_HANDLED;
}
static void appendStringDictionary(DBusMessageIter* aIter, const char* aKey,
const char* aValue) {
DBusMessageIter iterDict, iterVar;
dbus_message_iter_open_container(aIter, DBUS_TYPE_DICT_ENTRY, nullptr,
&iterDict);
dbus_message_iter_append_basic(&iterDict, DBUS_TYPE_STRING, &aKey);
dbus_message_iter_open_container(&iterDict, DBUS_TYPE_VARIANT, "s", &iterVar);
dbus_message_iter_append_basic(&iterVar, DBUS_TYPE_STRING, &aValue);
dbus_message_iter_close_container(&iterDict, &iterVar);
dbus_message_iter_close_container(aIter, &iterDict);
}
/* Appends history search results to the DBUS reply.
We can return those fields at GetResultMetas:
"id": the result ID
"name": the display name for the result
"icon": a serialized GIcon (see g_icon_serialize()), or alternatively,
"gicon": a textual representation of a GIcon (see g_icon_to_string()),
or alternativly,
"icon-data": a tuple of type (iiibiiay) describing a pixbuf with width,
height, rowstride, has-alpha, bits-per-sample, and image data
"description": an optional short description (1-2 lines)
*/
static void DBusAppendResultID(
nsCOMPtr<nsINavHistoryContainerResultNode> aHistResultContainer,
DBusMessageIter* aIter, const char* aID) {
nsCOMPtr<nsINavHistoryResultNode> child;
aHistResultContainer->GetChild(DBusGetIndexFromIDKey(aID),
getter_AddRefs(child));
nsAutoCString title;
if (NS_FAILED(child->GetTitle(title))) {
return;
}
if (title.IsEmpty()) {
if (NS_FAILED(child->GetUri(title)) || title.IsEmpty()) {
return;
}
}
const char* titleStr = title.get();
appendStringDictionary(aIter, "id", aID);
appendStringDictionary(aIter, "name", titleStr);
appendStringDictionary(aIter, "gicon", "text-html");
}
/* Search the web for: "searchTerm" to the DBUS reply.
*/
static void DBusAppendSearchID(DBusMessageIter* aIter, const char* aID) {
/* aID contains:
KEYWORD_SEARCH_STRING:ssssss
KEYWORD_SEARCH_STRING is a 'special:search' keyword
ssssss is a searched term, must be at least one character long
*/
// aID contains only 'KEYWORD_SEARCH_STRING:' so we're missing searched
// string.
if (strlen(aID) <= KEYWORD_SEARCH_STRING_LEN + 1) {
return;
}
appendStringDictionary(aIter, "id", KEYWORD_SEARCH_STRING);
// Extract ssssss part from aID
auto searchTerm = nsAutoCStringN<32>(aID + KEYWORD_SEARCH_STRING_LEN + 1);
nsAutoCString gnomeSearchTitle;
if (GetGnomeSearchTitle(searchTerm.get(), gnomeSearchTitle)) {
appendStringDictionary(aIter, "name", gnomeSearchTitle.get());
appendStringDictionary(aIter, "gicon", "org.mozilla.Firefox");
}
}
DBusHandlerResult DBusHandleResultMetas(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg) {
DBusMessage* reply;
char** stringArray;
int elements;
if (!dbus_message_get_args(aMsg, nullptr, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING,
&stringArray, &elements, DBUS_TYPE_INVALID) ||
elements == 0) {
reply = dbus_message_new_error(aMsg, DBUS_BUS_NAME, "Wrong argument");
} else {
reply = dbus_message_new_method_return(aMsg);
DBusMessageIter iter;
dbus_message_iter_init_append(reply, &iter);
DBusMessageIter iterArray;
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "a{sv}",
&iterArray);
DBusMessageIter iterArray2;
for (int i = 0; i < elements; i++) {
dbus_message_iter_open_container(&iterArray, DBUS_TYPE_ARRAY, "{sv}",
&iterArray2);
if (strncmp(stringArray[i], KEYWORD_SEARCH_STRING,
KEYWORD_SEARCH_STRING_LEN) == 0) {
DBusAppendSearchID(&iterArray2, stringArray[i]);
} else {
DBusAppendResultID(aSearchResult->GetSearchResultContainer(),
&iterArray2, stringArray[i]);
}
dbus_message_iter_close_container(&iterArray, &iterArray2);
}
dbus_message_iter_close_container(&iter, &iterArray);
dbus_free_string_array(stringArray);
}
dbus_connection_send(aSearchResult->GetDBusConnection(), reply, nullptr);
dbus_message_unref(reply);
return DBUS_HANDLER_RESULT_HANDLED;
} // namespace mozilla
static void ActivateResultID(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult,
const char* aResultID, uint32_t aTimeStamp) {
char* commandLine = nullptr;
int tmp;
if (strncmp(aResultID, KEYWORD_SEARCH_STRING, KEYWORD_SEARCH_STRING_LEN) ==
0) {
const char* urlList[3] = {"unused", "--search",
aSearchResult->GetSearchTerm().get()};
commandLine = ConstructCommandLine(3, (char**)urlList, nullptr, &tmp);
} else {
int keyIndex = atoi(aResultID);
nsCOMPtr<nsINavHistoryResultNode> child;
aSearchResult->GetSearchResultContainer()->GetChild(keyIndex,
getter_AddRefs(child));
if (!child) {
return;
}
nsAutoCString uri;
nsresult rv = child->GetUri(uri);
if (NS_FAILED(rv)) {
return;
}
const char* urlList[2] = {"unused", uri.get()};
commandLine = ConstructCommandLine(2, (char**)urlList, nullptr, &tmp);
}
if (commandLine) {
aSearchResult->HandleCommandLine(commandLine, aTimeStamp);
free(commandLine);
}
}
static void DBusLaunchWithAllResults(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult,
uint32_t aTimeStamp) {
uint32_t childCount = 0;
nsresult rv =
aSearchResult->GetSearchResultContainer()->GetChildCount(&childCount);
if (NS_FAILED(rv) || childCount == 0) {
return;
}
if (childCount > MAX_SEARCH_RESULTS_NUM) {
childCount = MAX_SEARCH_RESULTS_NUM;
}
// Allocate space for all found results, "unused", "--search" and
// potential search request.
char** urlList = (char**)moz_xmalloc(sizeof(char*) * (childCount + 3));
int urlListElements = 0;
urlList[urlListElements++] = strdup("unused");
for (uint32_t i = 0; i < childCount; i++) {
nsCOMPtr<nsINavHistoryResultNode> child;
aSearchResult->GetSearchResultContainer()->GetChild(i,
getter_AddRefs(child));
if (!IsHistoryResultNodeURI(child)) {
continue;
}
nsAutoCString uri;
nsresult rv = child->GetUri(uri);
if (NS_FAILED(rv)) {
continue;
}
urlList[urlListElements++] = strdup(uri.get());
}
// When there isn't any uri to open pass search at least.
if (!childCount) {
urlList[urlListElements++] = strdup("--search");
urlList[urlListElements++] = strdup(aSearchResult->GetSearchTerm().get());
}
int tmp;
char* commandLine =
ConstructCommandLine(urlListElements, urlList, nullptr, &tmp);
if (commandLine) {
aSearchResult->HandleCommandLine(commandLine, aTimeStamp);
free(commandLine);
}
for (int i = 0; i < urlListElements; i++) {
free(urlList[i]);
}
free(urlList);
}
DBusHandlerResult DBusActivateResult(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg) {
DBusMessage* reply;
char* resultID;
char** stringArray;
int elements;
uint32_t timestamp;
if (!dbus_message_get_args(aMsg, nullptr, DBUS_TYPE_STRING, &resultID,
DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &stringArray,
&elements, DBUS_TYPE_UINT32, &timestamp,
DBUS_TYPE_INVALID) ||
resultID == nullptr) {
reply = dbus_message_new_error(aMsg, DBUS_BUS_NAME, "Wrong argument");
} else {
reply = dbus_message_new_method_return(aMsg);
ActivateResultID(aSearchResult, resultID, timestamp);
dbus_free_string_array(stringArray);
}
dbus_connection_send(aSearchResult->GetDBusConnection(), reply, nullptr);
dbus_message_unref(reply);
return DBUS_HANDLER_RESULT_HANDLED;
}
DBusHandlerResult DBusLaunchSearch(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg) {
DBusMessage* reply;
char** stringArray;
int elements;
uint32_t timestamp;
if (!dbus_message_get_args(aMsg, nullptr, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING,
&stringArray, &elements, DBUS_TYPE_UINT32,
&timestamp, DBUS_TYPE_INVALID) ||
elements == 0) {
reply = dbus_message_new_error(aMsg, DBUS_BUS_NAME, "Wrong argument");
} else {
reply = dbus_message_new_method_return(aMsg);
DBusLaunchWithAllResults(aSearchResult, timestamp);
dbus_free_string_array(stringArray);
}
dbus_connection_send(aSearchResult->GetDBusConnection(), reply, nullptr);
dbus_message_unref(reply);
return DBUS_HANDLER_RESULT_HANDLED;
}
bool IsHistoryResultNodeURI(nsINavHistoryResultNode* aHistoryNode) {
uint32_t type;
nsresult rv = aHistoryNode->GetType(&type);
if (NS_FAILED(rv) || type != nsINavHistoryResultNode::RESULT_TYPE_URI)
return false;
nsAutoCString title;
rv = aHistoryNode->GetTitle(title);
if (NS_SUCCEEDED(rv) && !title.IsEmpty()) {
return true;
}
rv = aHistoryNode->GetUri(title);
return NS_SUCCEEDED(rv) && !title.IsEmpty();
}

View File

@@ -0,0 +1,36 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:expandtab:shiftwidth=2:tabstop=2:
*/
/* 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 __nsGNOMEShellDBusHelper_h__
#define __nsGNOMEShellDBusHelper_h__
#include "mozilla/DBusHelpers.h"
#include "nsIStringBundle.h"
#include "nsINavHistoryService.h"
#define MAX_SEARCH_RESULTS_NUM 9
#define KEYWORD_SEARCH_STRING "special:search"
#define KEYWORD_SEARCH_STRING_LEN 14
#define DBUS_BUS_NAME "org.mozilla.Firefox.SearchProvider"
#define DBUS_OBJECT_PATH "/org/mozilla/Firefox/SearchProvider"
DBusHandlerResult DBusIntrospect(DBusConnection* aConnection,
DBusMessage* aMsg);
DBusHandlerResult DBusHandleInitialResultSet(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg);
DBusHandlerResult DBusHandleSubsearchResultSet(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg);
DBusHandlerResult DBusHandleResultMetas(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg);
DBusHandlerResult DBusActivateResult(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg);
DBusHandlerResult DBusLaunchSearch(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult, DBusMessage* aMsg);
bool IsHistoryResultNodeURI(nsINavHistoryResultNode* aHistoryNode);
#endif // __nsGNOMEShellDBusHelper_h__

View File

@@ -0,0 +1,306 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:expandtab:shiftwidth=2:tabstop=2:
*/
/* 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 "nsGNOMEShellSearchProvider.h"
#include "nsGNOMEShellDBusHelper.h"
#include "nsIWidget.h"
#include "nsToolkitCompsCID.h"
#include "nsIFaviconService.h"
#include "RemoteUtils.h"
#include "base/message_loop.h" // for MessageLoop
#include "base/task.h" // for NewRunnableMethod, etc
#include <dbus/dbus.h>
#include <dbus/dbus-glib-lowlevel.h>
DBusHandlerResult nsGNOMEShellSearchProvider::HandleSearchResultSet(
DBusMessage* aMsg, bool aInitialSearch) {
// Discard any existing search results.
mSearchResult = nullptr;
RefPtr<nsGNOMEShellHistorySearchResult> newSearch =
new nsGNOMEShellHistorySearchResult(this, mConnection,
mSearchResultTimeStamp);
mSearchResultTimeStamp++;
newSearch->SetTimeStamp(mSearchResultTimeStamp);
// Send the search request over DBus. We'll get reply over DBus it will be
// set to mSearchResult by nsGNOMEShellSearchProvider::SetSearchResult().
return aInitialSearch
? DBusHandleInitialResultSet(newSearch.forget(), aMsg)
: DBusHandleSubsearchResultSet(newSearch.forget(), aMsg);
}
DBusHandlerResult nsGNOMEShellSearchProvider::HandleResultMetas(
DBusMessage* aMsg) {
if (!mSearchResult) {
NS_WARNING("Missing nsGNOMEShellHistorySearchResult.");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
return DBusHandleResultMetas(mSearchResult, aMsg);
}
DBusHandlerResult nsGNOMEShellSearchProvider::ActivateResult(
DBusMessage* aMsg) {
if (!mSearchResult) {
NS_WARNING("Missing nsGNOMEShellHistorySearchResult.");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
return DBusActivateResult(mSearchResult, aMsg);
}
DBusHandlerResult nsGNOMEShellSearchProvider::LaunchSearch(DBusMessage* aMsg) {
if (!mSearchResult) {
NS_WARNING("Missing nsGNOMEShellHistorySearchResult.");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
return DBusLaunchSearch(mSearchResult, aMsg);
}
DBusHandlerResult nsGNOMEShellSearchProvider::HandleDBusMessage(
DBusConnection* aConnection, DBusMessage* aMsg) {
NS_ASSERTION(mConnection == aConnection, "Wrong D-Bus connection.");
const char* method = dbus_message_get_member(aMsg);
const char* iface = dbus_message_get_interface(aMsg);
if ((strcmp("Introspect", method) == 0) &&
(strcmp("org.freedesktop.DBus.Introspectable", iface) == 0)) {
return DBusIntrospect(mConnection, aMsg);
}
if (strcmp("org.gnome.Shell.SearchProvider2", iface) == 0) {
if (strcmp("GetInitialResultSet", method) == 0) {
return HandleSearchResultSet(aMsg, /* aInitialSearch */ true);
}
if (strcmp("GetSubsearchResultSet", method) == 0) {
return HandleSearchResultSet(aMsg, /* aInitialSearch */ false);
}
if (strcmp("GetResultMetas", method) == 0) {
return HandleResultMetas(aMsg);
}
if (strcmp("ActivateResult", method) == 0) {
return ActivateResult(aMsg);
}
if (strcmp("LaunchSearch", method) == 0) {
return LaunchSearch(aMsg);
}
}
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
void nsGNOMEShellSearchProvider::UnregisterDBusInterface(
DBusConnection* aConnection) {
NS_ASSERTION(mConnection == aConnection, "Wrong D-Bus connection.");
// Not implemented
}
static DBusHandlerResult message_handler(DBusConnection* conn,
DBusMessage* aMsg, void* user_data) {
auto interface = static_cast<nsGNOMEShellSearchProvider*>(user_data);
return interface->HandleDBusMessage(conn, aMsg);
}
static void unregister(DBusConnection* conn, void* user_data) {
auto interface = static_cast<nsGNOMEShellSearchProvider*>(user_data);
interface->UnregisterDBusInterface(conn);
}
static DBusObjectPathVTable remoteHandlersTable = {
.unregister_function = unregister,
.message_function = message_handler,
};
nsresult nsGNOMEShellSearchProvider::Startup() {
if (mConnection && dbus_connection_get_is_connected(mConnection)) {
// We're already connected so we don't need to reconnect
return NS_ERROR_ALREADY_INITIALIZED;
}
mConnection =
already_AddRefed<DBusConnection>(dbus_bus_get(DBUS_BUS_SESSION, nullptr));
if (!mConnection) {
return NS_ERROR_FAILURE;
}
dbus_connection_set_exit_on_disconnect(mConnection, false);
dbus_connection_setup_with_g_main(mConnection, nullptr);
DBusError err;
dbus_error_init(&err);
dbus_bus_request_name(mConnection, DBUS_BUS_NAME, DBUS_NAME_FLAG_DO_NOT_QUEUE,
&err);
// The interface is already owned - there is another application/profile
// instance already running.
if (dbus_error_is_set(&err)) {
dbus_error_free(&err);
mConnection = nullptr;
return NS_ERROR_FAILURE;
}
if (!dbus_connection_register_object_path(mConnection, DBUS_OBJECT_PATH,
&remoteHandlersTable, this)) {
mConnection = nullptr;
return NS_ERROR_FAILURE;
}
mSearchResultTimeStamp = 0;
return NS_OK;
}
void nsGNOMEShellSearchProvider::Shutdown() {
if (!mConnection) {
return;
}
dbus_connection_unregister_object_path(mConnection, DBUS_OBJECT_PATH);
// dbus_connection_unref() will be called by RefPtr here.
mConnection = nullptr;
}
bool nsGNOMEShellSearchProvider::SetSearchResult(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult) {
MOZ_ASSERT(!mSearchResult);
if (mSearchResultTimeStamp != aSearchResult->GetTimeStamp()) {
NS_WARNING("Time stamp mismatch.");
return false;
}
mSearchResult = aSearchResult;
return true;
}
static void DispatchSearchResults(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult,
nsCOMPtr<nsINavHistoryContainerResultNode> aHistResultContainer) {
aSearchResult->SetSearchResultContainer(aHistResultContainer);
}
nsresult nsGNOMEShellHistoryService::QueryHistory(
RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult) {
if (!mHistoryService) {
mHistoryService = do_GetService(NS_NAVHISTORYSERVICE_CONTRACTID);
if (!mHistoryService) {
return NS_ERROR_FAILURE;
}
}
nsresult rv;
nsCOMPtr<nsINavHistoryQuery> histQuery;
rv = mHistoryService->GetNewQuery(getter_AddRefs(histQuery));
NS_ENSURE_SUCCESS(rv, rv);
rv = histQuery->SetSearchTerms(
NS_ConvertUTF8toUTF16(aSearchResult->GetSearchTerm()));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsINavHistoryQueryOptions> histQueryOpts;
rv = mHistoryService->GetNewQueryOptions(getter_AddRefs(histQueryOpts));
NS_ENSURE_SUCCESS(rv, rv);
rv = histQueryOpts->SetSortingMode(
nsINavHistoryQueryOptions::SORT_BY_FRECENCY_DESCENDING);
NS_ENSURE_SUCCESS(rv, rv);
rv = histQueryOpts->SetMaxResults(MAX_SEARCH_RESULTS_NUM);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsINavHistoryResult> histResult;
rv = mHistoryService->ExecuteQuery(histQuery, histQueryOpts,
getter_AddRefs(histResult));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsINavHistoryContainerResultNode> resultContainer;
rv = histResult->GetRoot(getter_AddRefs(resultContainer));
NS_ENSURE_SUCCESS(rv, rv);
rv = resultContainer->SetContainerOpen(true);
NS_ENSURE_SUCCESS(rv, rv);
// Simulate async searching by delayed reply. This search API will
// likely become async in the future and we want to be sure to not rely on
// its current synchronous behavior.
MOZ_ASSERT(MessageLoop::current());
MessageLoop::current()->PostTask(
NewRunnableFunction("Gnome shell search results", &DispatchSearchResults,
aSearchResult, resultContainer));
return NS_OK;
}
static void DBusGetIDKeyForURI(int aIndex, nsAutoCString& aUri,
nsAutoCString& aIDKey) {
// Compose ID as NN:URL where NN is index to our current history
// result container.
aIDKey = nsPrintfCString("%.2d:%s", aIndex, aUri.get());
}
void nsGNOMEShellHistorySearchResult::SendDBusSearchResultReply() {
MOZ_ASSERT(mReply);
uint32_t childCount = 0;
nsresult rv = mHistResultContainer->GetChildCount(&childCount);
DBusMessageIter iter;
dbus_message_iter_init_append(mReply, &iter);
DBusMessageIter iterArray;
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &iterArray);
if (NS_SUCCEEDED(rv) && childCount > 0) {
if (childCount > MAX_SEARCH_RESULTS_NUM) {
childCount = MAX_SEARCH_RESULTS_NUM;
}
for (uint32_t i = 0; i < childCount; i++) {
nsCOMPtr<nsINavHistoryResultNode> child;
mHistResultContainer->GetChild(i, getter_AddRefs(child));
if (NS_WARN_IF(NS_FAILED(rv))) {
continue;
}
if (!IsHistoryResultNodeURI(child)) {
continue;
}
nsAutoCString uri;
child->GetUri(uri);
nsAutoCString idKey;
DBusGetIDKeyForURI(i, uri, idKey);
const char* id = idKey.get();
dbus_message_iter_append_basic(&iterArray, DBUS_TYPE_STRING, &id);
}
}
nsPrintfCString searchString("%s:%s", KEYWORD_SEARCH_STRING,
mSearchTerm.get());
const char* search = searchString.get();
dbus_message_iter_append_basic(&iterArray, DBUS_TYPE_STRING, &search);
dbus_message_iter_close_container(&iter, &iterArray);
dbus_connection_send(mConnection, mReply, nullptr);
dbus_message_unref(mReply);
mReply = nullptr;
}
void nsGNOMEShellHistorySearchResult::SetSearchResultContainer(
nsCOMPtr<nsINavHistoryContainerResultNode> aHistResultContainer) {
if (mSearchProvider->SetSearchResult(this)) {
mHistResultContainer = aHistResultContainer;
SendDBusSearchResultReply();
}
}
nsGNOMEShellHistoryService* GetGNOMEShellHistoryService() {
static nsGNOMEShellHistoryService gGNOMEShellHistoryService;
return &gGNOMEShellHistoryService;
}

View File

@@ -0,0 +1,101 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:expandtab:shiftwidth=2:tabstop=2:
*/
/* 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 __nsGNOMEShellSearchProvider_h__
#define __nsGNOMEShellSearchProvider_h__
#include "mozilla/DBusHelpers.h"
#include "nsINavHistoryService.h"
#include "nsUnixRemoteServer.h"
#include "nsCOMPtr.h"
class nsGNOMEShellSearchProvider;
// nsGNOMEShellHistorySearchResult is a container with contains search results
// which are files asynchronously by nsGNOMEShellHistoryService.
// The search results can be opened by Firefox then.
class nsGNOMEShellHistorySearchResult : public nsUnixRemoteServer {
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(nsGNOMEShellHistorySearchResult)
nsGNOMEShellHistorySearchResult(nsGNOMEShellSearchProvider* aSearchProvider,
DBusConnection* aConnection, int aTimeStamp)
: mSearchProvider(aSearchProvider),
mReply(nullptr),
mConnection(aConnection),
mTimeStamp(aTimeStamp){};
void SetReply(DBusMessage* aReply) { mReply = aReply; }
void SetSearchTerm(const char* aSearchTerm) {
mSearchTerm = nsAutoCString(aSearchTerm);
}
DBusConnection* GetDBusConnection() { return mConnection; }
int GetTimeStamp() { return mTimeStamp; }
void SetTimeStamp(int aTimeStamp) { mTimeStamp = aTimeStamp; }
nsAutoCString& GetSearchTerm() { return mSearchTerm; }
void SetSearchResultContainer(
nsCOMPtr<nsINavHistoryContainerResultNode> aHistResultContainer);
nsCOMPtr<nsINavHistoryContainerResultNode> GetSearchResultContainer() {
return mHistResultContainer;
}
void HandleCommandLine(const char* aBuffer, uint32_t aTimestamp) {
nsUnixRemoteServer::HandleCommandLine(aBuffer, aTimestamp);
}
private:
void SendDBusSearchResultReply();
~nsGNOMEShellHistorySearchResult() = default;
private:
nsGNOMEShellSearchProvider* mSearchProvider;
nsCOMPtr<nsINavHistoryContainerResultNode> mHistResultContainer;
nsAutoCString mSearchTerm;
DBusMessage* mReply;
DBusConnection* mConnection;
int mTimeStamp;
};
class nsGNOMEShellHistoryService {
public:
nsresult QueryHistory(RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult);
private:
nsCOMPtr<nsINavHistoryService> mHistoryService;
};
class nsGNOMEShellSearchProvider {
public:
nsGNOMEShellSearchProvider()
: mConnection(nullptr), mSearchResultTimeStamp(0) {}
~nsGNOMEShellSearchProvider() { Shutdown(); }
nsresult Startup();
void Shutdown();
DBusHandlerResult HandleDBusMessage(DBusConnection* aConnection,
DBusMessage* msg);
void UnregisterDBusInterface(DBusConnection* aConnection);
bool SetSearchResult(RefPtr<nsGNOMEShellHistorySearchResult> aSearchResult);
private:
DBusHandlerResult HandleSearchResultSet(DBusMessage* msg,
bool aInitialSearch);
DBusHandlerResult HandleResultMetas(DBusMessage* msg);
DBusHandlerResult ActivateResult(DBusMessage* msg);
DBusHandlerResult LaunchSearch(DBusMessage* msg);
// The connection is owned by DBus library
RefPtr<DBusConnection> mConnection;
RefPtr<nsGNOMEShellHistorySearchResult> mSearchResult;
int mSearchResultTimeStamp;
};
nsGNOMEShellHistoryService* GetGNOMEShellHistoryService();
#endif // __nsGNOMEShellSearchProvider_h__

View File

@@ -101,6 +101,14 @@ nsresult nsGNOMEShellService::Init() {
if (!giovfs && !gsettings) return NS_ERROR_NOT_AVAILABLE;
#ifdef MOZ_ENABLE_DBUS
const char* currentDesktop = getenv("XDG_CURRENT_DESKTOP");
if (currentDesktop && strstr(currentDesktop, "GNOME") != nullptr &&
Preferences::GetBool("browser.gnome-search-provider.enabled", false)) {
mSearchProvider.Startup();
}
#endif
// Check G_BROKEN_FILENAMES. If it's set, then filenames in glib use
// the locale encoding. If it's not set, they use UTF-8.
mUseLocaleFilenames = PR_GetEnv("G_BROKEN_FILENAMES") != nullptr;

View File

@@ -10,6 +10,9 @@
#include "nsToolkitShellService.h"
#include "nsString.h"
#include "mozilla/Attributes.h"
#ifdef MOZ_ENABLE_DBUS
# include "nsGNOMEShellSearchProvider.h"
#endif
class nsGNOMEShellService final : public nsIGNOMEShellService,
public nsToolkitShellService {
@@ -28,6 +31,9 @@ class nsGNOMEShellService final : public nsIGNOMEShellService,
bool KeyMatchesAppName(const char* aKeyValue) const;
bool CheckHandlerMatchesAppName(const nsACString& handler) const;
#ifdef MOZ_ENABLE_DBUS
nsGNOMEShellSearchProvider mSearchProvider;
#endif
bool GetAppPathFromLauncher();
bool mUseLocaleFilenames;
nsCString mAppPath;

View File

@@ -1045,3 +1045,7 @@ confirmationHint.breakageReport.label = Report sent. Thank you!
# Used by the export of user's live bookmarks to an OPML file as a title for the file.
# %S will be replaced with brandShortName
livebookmarkMigration.title = %S Live Bookmarks
# LOCALIZATION NOTE (gnomeSearchProviderSearch):
# Used for search by Gnome Shell activity screen, %S is a searched string.
gnomeSearchProviderSearch=Search the web for %S

View File

@@ -25,6 +25,10 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gtk':
'nsDBusRemoteServer.cpp',
]
CXXFLAGS += CONFIG['MOZ_DBUS_GLIB_CFLAGS']
EXPORTS += [
'nsUnixRemoteServer.h',
'RemoteUtils.h',
]
CXXFLAGS += CONFIG['TK_CFLAGS']
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':

View File

@@ -23,7 +23,7 @@
#include <dlfcn.h>
const char* introspect_template =
static const char* introspect_template =
"<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection "
"1.0//EN\"\n"
"\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\";>\n"

View File

@@ -71,6 +71,8 @@ LOCAL_INCLUDES += [
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gtk':
CXXFLAGS += CONFIG['TK_CFLAGS']
if CONFIG['MOZ_ENABLE_DBUS']:
CXXFLAGS += CONFIG['MOZ_DBUS_GLIB_CFLAGS']
if CONFIG['MOZ_LAYOUT_DEBUGGER']:
DEFINES['MOZ_LAYOUT_DEBUGGER'] = True