Add global shortcuts/keybinds (#1238)

Co-authored-by: Kylie C <[email protected]>
Assisted-by: Claude Opus 5.5
This commit is contained in:
VandKylie C authored and GitHub committed 2026-11-16 22:34:01 +01:00
1 parent 857db4313f
commit e45a1027ef
29 files changed
+2025 -25

No files matched your search

+26 -1
View File
@@ -8,10 +8,10 @@ Vesktop is a custom Discord desktop app
- Much more lightweight and faster than the official Discord app
- Linux Screenshare with sound & wayland
- Much better privacy, since Discord has no access to your system
- Global keybinds, including push to talk (see [Global Keybinds](#global-keybinds))
**Not yet supported**:
- Global Keybinds
- see the [Roadmap](https://github.com/Vencord/Vesktop/issues/324)
![](https://github.com/Vencord/Vesktop/assets/45497981/8608a899-96a9-4027-9725-2cb02ba189fd)
@@ -21,6 +21,31 @@ Vesktop is a custom Discord desktop app
Visit https://vesktop.dev/install
## Global Keybinds
Configure them in the Vesktop settings, or from Discord's Keybinds and Voice & Video settings.
- **Windows, Linux (X11)**: Bind any keys or mouse buttons in the Vesktop keybind settings
- **macOS**: Same as above, but Vesktop needs the Accessibility permission
- **Linux (Wayland)**: Wayland doesn't let apps listen to global input. Enable global shortcuts in the Vesktop keybind settings and assign them in your system settings. This requires a desktop that supports the GlobalShortcuts portal, like GNOME or KDE
You can also trigger actions from other programs, for example your compositor's keybinds:
```sh
vesktop --run-shortcut toggleMute
# Append :down or :up to only press or release, e.g. for push to talk
vesktop --run-shortcut pushToTalk:down
vesktop --run-shortcut pushToTalk:up
```
For lower latency, send the same commands as lines to the socket at `$XDG_RUNTIME_DIR/vesktop.sock`:
```sh
echo "run-shortcut pushToTalk:down" | socat - UNIX-CONNECT:$XDG_RUNTIME_DIR/vesktop.sock
```
Run `vesktop --help` to see all actions.
## Building from Source
You need to have the following dependencies installed:
+2 -1
View File
@@ -27,7 +27,8 @@
"generateMeta": "tsx scripts/utils/generateMeta.mts"
},
"dependencies": {
"electron-updater": "6.6.2"
"electron-updater": "6.6.2",
"uiohook-napi": "^1.5.5"
},
"optionalDependencies": {
"@vencord/venmic": "^7.2.5"
+27
View File
@@ -1,2 +1,29 @@
export function requestBackground(autoStart: boolean, commandLine: string[]): boolean;
export function isStatusNotifierHostRegistered(): boolean;
export function registerHostApp(appId: string): boolean;
export function openGnomeAppSettings(appId: string): boolean;
export interface XDPShortcut {
id: string;
description: string;
}
export interface XDPBoundShortcut extends XDPShortcut {
trigger: string;
}
export type XDPGlobalShortcutsEvent =
| [event: "version", version: number]
| [event: "ready"]
| [event: "fatal", message: string]
| [event: "error", message: string]
| [event: "shortcuts", shortcuts: XDPBoundShortcut[]]
| [event: "shortcut", id: string, pressed: boolean];
export class XDPGlobalShortcuts {
constructor(onEvent: (...args: XDPGlobalShortcutsEvent) => void);
bindShortcuts(shortcuts: XDPShortcut[]): void;
configureShortcuts(): void;
destroy(): void;
}
+516
View File
@@ -1,8 +1,13 @@
#include <gio/gio.h>
#include <algorithm>
#include <cstdint>
#include <functional>
#include <iostream>
#include <map>
#include <napi.h>
#include <memory>
#include <string>
#include <vector>
template <typename T>
struct GObjectDeleter
@@ -39,6 +44,29 @@ struct GErrorDeleter
using GErrorPtr = std::unique_ptr<GError, GErrorDeleter>;
struct SignalSubscription {
SignalSubscription() = default;
SignalSubscription(GDBusConnection *conn, guint id) : conn_(conn), id_(id) {}
~SignalSubscription() { reset(); }
SignalSubscription(const SignalSubscription &) = delete;
SignalSubscription &operator=(const SignalSubscription &) = delete;
SignalSubscription(SignalSubscription &&o) noexcept : conn_(o.conn_), id_(o.id_) { o.id_ = 0; }
SignalSubscription &operator=(SignalSubscription &&o) noexcept {
if (this != &o) { reset(); conn_ = o.conn_; id_ = o.id_; o.id_ = 0; }
return *this;
}
void reset() {
if (id_) { g_dbus_connection_signal_unsubscribe(conn_, id_); id_ = 0; }}
explicit operator bool() const { return id_ != 0; }
private:
GDBusConnection *conn_ = nullptr;
guint id_ = 0;
};
bool request_background(bool autostart, const std::vector<std::string> &commandline)
{
GError *error = nullptr;
@@ -158,10 +186,498 @@ Napi::Value IsStatusNotifierHostRegistered(const Napi::CallbackInfo &info)
return Napi::Boolean::New(info.Env(), is_status_notifier_host_registered());
}
constexpr const char *PORTAL_BUS_NAME = "org.freedesktop.portal.Desktop";
constexpr const char *PORTAL_PATH = "/org/freedesktop/portal/desktop";
constexpr const char *SHORTCUTS_INTERFACE = "org.freedesktop.portal.GlobalShortcuts";
// Tells the portal our app id. Unsandboxed apps otherwise have an empty app id, which portals use to persist things like shortcut triggers.
// Must happen before any other portal call on this connection.
bool register_host_app(const std::string &app_id)
{
GError *error = nullptr;
GObjectPtr<GDBusConnection> bus(g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &error));
if (!bus)
{
GErrorPtr error_ptr(error);
return false;
}
GVariantBuilder options;
g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
GVariantPtr reply(g_dbus_connection_call_sync(
bus.get(),
PORTAL_BUS_NAME,
PORTAL_PATH,
"org.freedesktop.host.portal.Registry",
"Register",
g_variant_new("(sa{sv})", app_id.c_str(), &options),
nullptr,
G_DBUS_CALL_FLAGS_NONE,
1000,
nullptr,
&error));
if (!reply)
{
GErrorPtr error_ptr(error);
std::cerr << "[libvesktop::register_host_app] Failed to register app id: "
<< (error_ptr ? error_ptr->message : "unknown error") << std::endl;
return false;
}
// The registration belongs to this connection's unique name. The shared bus connection is only weakly cached by GLib,
// so keep it alive forever to not lose the registration once all other references are dropped
bus.release();
return true;
}
Napi::Value RegisterHostApp(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString())
{
Napi::TypeError::New(env, "Expected (string)").ThrowAsJavaScriptException();
return env.Null();
}
return Napi::Boolean::New(env, register_host_app(info[0].As<Napi::String>().Utf8Value()));
}
// Opens GNOME Settings on the page of the given app, which is where GNOME lets you change its global shortcuts
bool open_gnome_app_settings(const std::string &app_id)
{
GError *error = nullptr;
GObjectPtr<GDBusConnection> bus(g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &error));
if (!bus)
{
GErrorPtr error_ptr(error);
return false;
}
GVariantBuilder panel_args;
g_variant_builder_init(&panel_args, G_VARIANT_TYPE("av"));
g_variant_builder_add(&panel_args, "v", g_variant_new_string(app_id.c_str()));
GVariantBuilder action_params;
g_variant_builder_init(&action_params, G_VARIANT_TYPE("av"));
g_variant_builder_add(&action_params, "v", g_variant_new("(sav)", "applications", &panel_args));
GVariantBuilder platform_data;
g_variant_builder_init(&platform_data, G_VARIANT_TYPE_VARDICT);
GVariantPtr reply(g_dbus_connection_call_sync(
bus.get(),
"org.gnome.Settings",
"/org/gnome/Settings",
"org.freedesktop.Application",
"ActivateAction",
g_variant_new("(sava{sv})", "launch-panel", &action_params, &platform_data),
nullptr,
G_DBUS_CALL_FLAGS_NONE,
5000,
nullptr,
&error));
if (!reply)
{
GErrorPtr error_ptr(error);
std::cerr << "[libvesktop::open_gnome_app_settings] Failed to open GNOME Settings: "
<< (error_ptr ? error_ptr->message : "unknown error") << std::endl;
return false;
}
return true;
}
Napi::Value OpenGnomeAppSettings(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString())
{
Napi::TypeError::New(env, "Expected (string)").ThrowAsJavaScriptException();
return env.Null();
}
return Napi::Boolean::New(env, open_gnome_app_settings(info[0].As<Napi::String>().Utf8Value()));
}
// org.freedesktop.portal.GlobalShortcuts session. Reports everything through the callback passed to the constructor:
// ("version", number), ("ready"), ("fatal", message), ("error", message),
// ("shortcuts", { id, description, trigger }[]), ("shortcut", id, pressed)
class XDPGlobalShortcuts : public Napi::ObjectWrap<XDPGlobalShortcuts>
{
public:
static void Init(Napi::Env env, Napi::Object exports)
{
exports.Set("XDPGlobalShortcuts", DefineClass(env, "XDPGlobalShortcuts", {
InstanceMethod("bindShortcuts", &XDPGlobalShortcuts::BindShortcuts),
InstanceMethod("configureShortcuts", &XDPGlobalShortcuts::ConfigureShortcuts),
InstanceMethod("destroy", &XDPGlobalShortcuts::Destroy),
}));
}
XDPGlobalShortcuts(const Napi::CallbackInfo &info) : ObjectWrap(info)
{
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsFunction())
{
Napi::TypeError::New(env, "Expected (function)").ThrowAsJavaScriptException();
return;
}
GError *error = nullptr;
connection_.reset(g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &error));
if (!connection_)
{
GErrorPtr error_ptr(error);
Napi::Error::New(env, error_ptr ? error_ptr->message : "Failed to connect to session bus")
.ThrowAsJavaScriptException();
return;
}
// Request objects live at /org/freedesktop/portal/desktop/request/SENDER/TOKEN, where SENDER is our unique name (":1.23" -> "1_23")
std::string sender = g_dbus_connection_get_unique_name(connection_.get()) + 1;
std::replace(sender.begin(), sender.end(), '.', '_');
requestPathPrefix_ = std::string(PORTAL_PATH) + "/request/" + sender + "/";
cancellable_.reset(g_cancellable_new());
tsfn_ = Napi::ThreadSafeFunction::New(env, info[0].As<Napi::Function>(), "libvesktop-global-shortcuts", 0, 1);
active_ = true;
FetchVersion();
SubscribeSignals();
CreateSession();
}
~XDPGlobalShortcuts() override { Cleanup(); }
private:
using ArgFactory = std::function<Napi::Value(Napi::Env)>;
using ReplyCallback = std::function<void(GVariant *reply, GError *error)>;
using ResponseCallback = std::function<void(guint32 response, GVariant *results)>;
using SignalCallback = std::function<void(GVariant *parameters)>;
GObjectPtr<GDBusConnection> connection_;
GObjectPtr<GCancellable> cancellable_;
Napi::ThreadSafeFunction tsfn_;
bool active_ = false;
std::string requestPathPrefix_;
std::string session_;
// Tokens must be unique per connection, so shared between all instances
static inline guint32 nextToken_ = 0;
std::map<std::string, SignalSubscription> requests_;
std::vector<SignalSubscription> signals_;
Napi::Value BindShortcuts(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsArray())
{
Napi::TypeError::New(env, "Expected ({ id: string, description: string }[])").ThrowAsJavaScriptException();
return env.Undefined();
}
if (session_.empty())
{
Napi::Error::New(env, "Session is not ready").ThrowAsJavaScriptException();
return env.Undefined();
}
GVariantBuilder shortcuts;
g_variant_builder_init(&shortcuts, G_VARIANT_TYPE("a(sa{sv})"));
Napi::Array arr = info[0].As<Napi::Array>();
for (uint32_t i = 0; i < arr.Length(); i++)
{
Napi::Object item = arr.Get(i).As<Napi::Object>();
std::string id = item.Get("id").ToString().Utf8Value();
std::string description = item.Get("description").ToString().Utf8Value();
GVariantBuilder props;
g_variant_builder_init(&props, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&props, "{sv}", "description", g_variant_new_string(description.c_str()));
g_variant_builder_add(&shortcuts, "(sa{sv})", id.c_str(), &props);
}
std::string token = NewToken();
GVariantBuilder options;
g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&options, "{sv}", "handle_token", g_variant_new_string(token.c_str()));
Request("BindShortcuts", token,
g_variant_new("(oa(sa{sv})sa{sv})", session_.c_str(), &shortcuts, "", &options),
"error",
[this](guint32 response, GVariant *results) {
if (response != 0)
{
Emit("error", {Str(response == 1 ? "Binding shortcuts was cancelled" : "Failed to bind shortcuts")});
return;
}
GVariantPtr bound(g_variant_lookup_value(results, "shortcuts", G_VARIANT_TYPE("a(sa{sv})")));
Emit("shortcuts", {ParseShortcuts(bound.get())});
});
return env.Undefined();
}
Napi::Value ConfigureShortcuts(const Napi::CallbackInfo &info)
{
if (session_.empty())
{
Napi::Error::New(info.Env(), "Session is not ready").ThrowAsJavaScriptException();
return info.Env().Undefined();
}
GVariantBuilder options;
g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
Call(PORTAL_PATH, SHORTCUTS_INTERFACE, "ConfigureShortcuts",
g_variant_new("(osa{sv})", session_.c_str(), "", &options),
nullptr,
[this](GVariant *, GError *error) {
if (error)
Emit("error", {Str(std::string("ConfigureShortcuts: ") + error->message)});
});
return info.Env().Undefined();
}
Napi::Value Destroy(const Napi::CallbackInfo &info)
{
Cleanup();
return info.Env().Undefined();
}
void Cleanup()
{
if (!active_)
return;
active_ = false;
g_cancellable_cancel(cancellable_.get());
requests_.clear();
signals_.clear();
if (!session_.empty())
{
g_dbus_connection_call(connection_.get(), PORTAL_BUS_NAME, session_.c_str(), "org.freedesktop.portal.Session",
"Close", nullptr, nullptr, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, nullptr, nullptr);
session_.clear();
}
tsfn_.Release();
}
void FetchVersion()
{
Call(PORTAL_PATH, "org.freedesktop.DBus.Properties", "Get",
g_variant_new("(ss)", SHORTCUTS_INTERFACE, "version"),
G_VARIANT_TYPE("(v)"),
[this](GVariant *reply, GError *) {
guint32 version = 0;
if (reply)
{
GVariant *raw = nullptr;
g_variant_get(reply, "(v)", &raw);
GVariantPtr value(raw);
if (g_variant_is_of_type(value.get(), G_VARIANT_TYPE_UINT32))
version = g_variant_get_uint32(value.get());
}
Emit("version", {[version](Napi::Env env) -> Napi::Value { return Napi::Number::New(env, version); }});
});
}
void CreateSession()
{
std::string token = NewToken();
GVariantBuilder options;
g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add(&options, "{sv}", "handle_token", g_variant_new_string(token.c_str()));
g_variant_builder_add(&options, "{sv}", "session_handle_token", g_variant_new_string(token.c_str()));
Request("CreateSession", token, g_variant_new("(a{sv})", &options), "fatal",
[this](guint32 response, GVariant *results) {
// Older portal versions send the handle as a string, newer as an object path
GVariantPtr handle(g_variant_lookup_value(results, "session_handle", nullptr));
if (response != 0 || !handle ||
!(g_variant_is_of_type(handle.get(), G_VARIANT_TYPE_STRING) ||
g_variant_is_of_type(handle.get(), G_VARIANT_TYPE_OBJECT_PATH)))
{
Emit("fatal", {Str("Failed to create session (response " + std::to_string(response) + ")")});
return;
}
session_ = g_variant_get_string(handle.get(), nullptr);
Emit("ready");
});
}
void SubscribeSignals()
{
auto onKey = [this](bool pressed) {
return [this, pressed](GVariant *parameters) {
const char *session = nullptr;
const char *id = nullptr;
guint64 timestamp = 0;
g_variant_get(parameters, "(&o&sta{sv})", &session, &id, &timestamp, nullptr);
if (session_ != session)
return;
Emit("shortcut", {Str(id), [pressed](Napi::Env env) -> Napi::Value { return Napi::Boolean::New(env, pressed); }});
};
};
signals_.push_back(Subscribe(SHORTCUTS_INTERFACE, "Activated", PORTAL_PATH, onKey(true)));
signals_.push_back(Subscribe(SHORTCUTS_INTERFACE, "Deactivated", PORTAL_PATH, onKey(false)));
signals_.push_back(Subscribe(SHORTCUTS_INTERFACE, "ShortcutsChanged", PORTAL_PATH, [this](GVariant *parameters) {
const char *session = nullptr;
GVariant *raw = nullptr;
g_variant_get(parameters, "(&o@a(sa{sv}))", &session, &raw);
GVariantPtr shortcuts(raw);
if (session_ == session)
Emit("shortcuts", {ParseShortcuts(shortcuts.get())});
}));
}
std::string NewToken() { return "vesktop" + std::to_string(++nextToken_); }
void Call(const char *path, const char *interface, const char *method, GVariant *params,
const GVariantType *replyType, ReplyCallback callback)
{
g_dbus_connection_call(
connection_.get(), PORTAL_BUS_NAME, path, interface, method, params, replyType,
G_DBUS_CALL_FLAGS_NONE, -1, cancellable_.get(),
[](GObject *source, GAsyncResult *res, gpointer user_data) {
std::unique_ptr<ReplyCallback> callback(static_cast<ReplyCallback *>(user_data));
GError *raw_error = nullptr;
GVariantPtr reply(g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res, &raw_error));
GErrorPtr error(raw_error);
// Cancelled means we were destroyed, so the callback must not run
if (!g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED))
(*callback)(reply.get(), error.get());
},
new ReplyCallback(std::move(callback)));
}
// Calls a portal method that answers asynchronously with a Request::Response signal
void Request(const char *method, const std::string &token, GVariant *params, const char *errorEvent,
ResponseCallback onResponse)
{
requests_[token] = Subscribe("org.freedesktop.portal.Request", "Response", (requestPathPrefix_ + token).c_str(),
[this, token, onResponse](GVariant *parameters) {
guint32 response = 2;
GVariant *raw = nullptr;
g_variant_get(parameters, "(u@a{sv})", &response, &raw);
GVariantPtr results(raw);
// Erasing unsubscribes this handler, so copy what we need first
ResponseCallback callback = onResponse;
std::string key = token;
requests_.erase(key);
callback(response, results.get());
});
Call(PORTAL_PATH, SHORTCUTS_INTERFACE, method, params, G_VARIANT_TYPE("(o)"),
[this, token, method = std::string(method), errorEvent = std::string(errorEvent)](GVariant *, GError *error) {
if (!error)
return;
requests_.erase(token);
Emit(errorEvent, {Str(method + ": " + error->message)});
});
}
SignalSubscription Subscribe(const char *interface, const char *signal, const char *path, SignalCallback callback)
{
guint id = g_dbus_connection_signal_subscribe(
connection_.get(), PORTAL_BUS_NAME, interface, signal, path, nullptr, G_DBUS_SIGNAL_FLAGS_NONE,
[](GDBusConnection *, const char *, const char *, const char *, const char *, GVariant *parameters,
gpointer user_data) { (*static_cast<SignalCallback *>(user_data))(parameters); },
new SignalCallback(std::move(callback)),
[](gpointer user_data) { delete static_cast<SignalCallback *>(user_data); });
return {connection_.get(), id};
}
void Emit(std::string name, std::vector<ArgFactory> args = {})
{
if (!active_)
return;
using Event = std::pair<std::string, std::vector<ArgFactory>>;
tsfn_.NonBlockingCall(new Event(std::move(name), std::move(args)),
[](Napi::Env env, Napi::Function callback, Event *event) {
std::unique_ptr<Event> owned(event);
if (env == nullptr)
return;
std::vector<napi_value> values{Napi::String::New(env, owned->first)};
for (auto &make : owned->second)
values.push_back(make(env));
callback.Call(values);
});
}
static ArgFactory Str(std::string value)
{
return [value = std::move(value)](Napi::Env env) -> Napi::Value { return Napi::String::New(env, value); };
}
static ArgFactory ParseShortcuts(GVariant *shortcuts)
{
struct Shortcut
{
std::string id, description, trigger;
};
std::vector<Shortcut> parsed;
if (shortcuts)
{
GVariantIter iter;
g_variant_iter_init(&iter, shortcuts);
const char *id = nullptr;
GVariant *raw = nullptr;
while (g_variant_iter_next(&iter, "(&s@a{sv})", &id, &raw))
{
GVariantPtr props(raw);
const char *description = "";
const char *trigger = "";
g_variant_lookup(props.get(), "description", "&s", &description);
g_variant_lookup(props.get(), "trigger_description", "&s", &trigger);
parsed.push_back({id, description, trigger});
}
}
return [parsed = std::move(parsed)](Napi::Env env) -> Napi::Value {
Napi::Array arr = Napi::Array::New(env, parsed.size());
for (size_t i = 0; i < parsed.size(); i++)
{
Napi::Object obj = Napi::Object::New(env);
obj.Set("id", parsed[i].id);
obj.Set("description", parsed[i].description);
obj.Set("trigger", parsed[i].trigger);
arr.Set(i, obj);
}
return arr;
};
}
};
Napi::Object Init(Napi::Env env, Napi::Object exports)
{
exports.Set("requestBackground", Napi::Function::New(env, RequestBackground));
exports.Set("isStatusNotifierHostRegistered", Napi::Function::New(env, IsStatusNotifierHostRegistered));
exports.Set("registerHostApp", Napi::Function::New(env, RegisterHostApp));
exports.Set("openGnomeAppSettings", Napi::Function::New(env, OpenGnomeAppSettings));
XDPGlobalShortcuts::Init(env, exports);
return exports;
}
+17
View File
@@ -172,6 +172,9 @@ importers:
electron-updater:
specifier: 6.6.2
version: 6.6.2(patch_hash=080505564abb2ebbda932bbf8fe91540c74dd905de994888d52ffce6f882f887)([email protected])
uiohook-napi:
specifier: ^1.5.5
version: 1.5.5
devDependencies:
'@fal-works/esbuild-plugin-global-externals':
specifier: ^2.1.2
@@ -1808,6 +1811,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}
[email protected]:
resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-ra7Kvlhxn5V9Slyus0ygMa2h+UqExPqUIkfk7Pc8QTLT956JLSy51uWFwHtIYy0vI8cB4BDhc/S03+880My/LQ==}
engines: {node: ^18.17.0 || >=20.5.0}
@@ -2241,6 +2248,10 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-oSlTdnECw2GBfsJPTbBQBeE4v/EXP0EZmX6BJq5nzH/JgFaBE8JpFwEA/kLhiEP7HxQw28FViWiYgdIZzWuuJQ==}
engines: {node: '>= 16'}
[email protected]:
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
@@ -3989,6 +4000,8 @@ snapshots:
dependencies:
semver: 7.8.5
[email protected]: {}
[email protected]([email protected]):
dependencies:
env-paths: 2.2.1
@@ -4455,6 +4468,10 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
node-gyp-build: 4.8.4
[email protected]: {}
[email protected]: {}
+1
View File
@@ -6,6 +6,7 @@ allowBuilds:
electron: true
electron-winstaller: false
esbuild: true
uiohook-napi: true
pmOnFail: warn
verifyDepsBeforeRun: warn
recursiveInstall: false
+53 -12
View File
@@ -6,7 +6,7 @@
import { copyFile, rm } from "fs/promises";
import { BuildContext, BuildOptions, context } from "esbuild";
import { BuildContext, BuildOptions, context, Plugin } from "esbuild";
import { includeDirPlugin } from "./includeDirPlugin.mts";
import vencordDep from "./vencordDep.mjs";
@@ -34,6 +34,29 @@ const NodeCommonOpts: BuildOptions = {
}
};
// uiohook-napi finds its binary with node-gyp-build, so point that at the copy in static/dist (see copyUiohook)
const uiohookBinaryPlugin: Plugin = {
name: "uiohook-binary",
setup(build) {
build.onResolve({ filter: /^node-gyp-build$/ }, args => {
if (args.importer.includes("uiohook-napi")) return { path: "uiohook-binary", namespace: "uiohook-binary" };
});
build.onLoad({ filter: /.*/, namespace: "uiohook-binary" }, () => ({
contents: `
const { join } = require("path");
module.exports = () => require(join(__dirname, "../../static/dist/uiohook-napi-" + process.arch + ".node"));
`,
loader: "js"
}));
}
};
// Overwriting in place crashes a running instance, as the addon is mapped into memory, so replace the file instead
async function copyNativeModule(src: string, dest: string) {
await rm(dest, { force: true });
await copyFile(src, dest);
}
const contexts = [] as BuildContext[];
async function createContext(options: BuildOptions) {
contexts.push(await context(options));
@@ -43,27 +66,40 @@ async function copyVenmic() {
if (process.platform !== "linux") return;
return Promise.all([
copyFile(
copyNativeModule(
"./node_modules/@vencord/venmic/prebuilds/venmic-addon-linux-x64/node-napi-v7.node",
"./static/dist/venmic-x64.node"
),
copyFile(
copyNativeModule(
"./node_modules/@vencord/venmic/prebuilds/venmic-addon-linux-arm64/node-napi-v7.node",
"./static/dist/venmic-arm64.node"
)
]).catch(() => console.warn("Failed to copy venmic. Building without venmic support"));
}
async function copyUiohook() {
const prebuilds = "./node_modules/uiohook-napi/prebuilds";
return Promise.all(
["x64", "arm64"].map(arch =>
copyNativeModule(
`${prebuilds}/${process.platform}-${arch}/uiohook-napi.node`,
`./static/dist/uiohook-napi-${arch}.node`
)
)
).catch(() => console.warn("Failed to copy uiohook. Building without global keybind support"));
}
async function copyGameDetection() {
const prebuilds = "./node_modules/@vencord/game-detection/prebuilds";
return Promise.all(
["x64", "arm64"].map(async arch => {
const dest = `./static/dist/game-detection-${arch}.node`;
// Overwriting in place crashes a running instance, as the addon is mapped into memory
await rm(dest, { force: true });
await copyFile(`${prebuilds}/${process.platform}-${arch}/rpc_native.node`, dest);
})
["x64", "arm64"].map(arch =>
copyNativeModule(
`${prebuilds}/${process.platform}-${arch}/rpc_native.node`,
`./static/dist/game-detection-${arch}.node`
)
)
).catch(() => console.warn("Failed to copy game detection. Building without game detection support"));
}
@@ -71,7 +107,7 @@ async function copyLibVesktop() {
if (process.platform !== "linux") return;
try {
await copyFile(
await copyNativeModule(
"./packages/libvesktop/build/Release/vesktop.node",
`./static/dist/libvesktop-${process.arch}.node`
);
@@ -81,8 +117,11 @@ async function copyLibVesktop() {
"Using prebuilt libvesktop binaries. Run `pnpm buildLibVesktop` and build again to build from source - see README.md for more details"
);
return Promise.all([
copyFile("./packages/libvesktop/prebuilds/vesktop-x64.node", "./static/dist/libvesktop-x64.node"),
copyFile("./packages/libvesktop/prebuilds/vesktop-arm64.node", "./static/dist/libvesktop-arm64.node")
copyNativeModule("./packages/libvesktop/prebuilds/vesktop-x64.node", "./static/dist/libvesktop-x64.node"),
copyNativeModule(
"./packages/libvesktop/prebuilds/vesktop-arm64.node",
"./static/dist/libvesktop-arm64.node"
)
]).catch(() => console.warn("Failed to copy libvesktop. Building without libvesktop support"));
}
}
@@ -91,9 +130,11 @@ await Promise.all([
copyVenmic(),
copyLibVesktop(),
copyGameDetection(),
copyUiohook(),
createContext({
...NodeCommonOpts,
entryPoints: ["src/main/index.ts"],
plugins: [uiohookBinaryPlugin],
outfile: "dist/js/main.js",
footer: { js: "//# sourceURL=VesktopMain" }
}),
+15
View File
@@ -8,6 +8,7 @@ import { basename } from "path";
import { parseArgs, ParseArgsOptionDescriptor } from "util";
import { app } from "electron";
import { parseShortcutCommand, SHORTCUT_ACTIONS } from "shared/utils/keybind";
import { stripIndent } from "shared/utils/text";
type Option = ParseArgsOptionDescriptor & {
@@ -44,6 +45,11 @@ const options = {
description: "Set User-Agent to a specific operating system. May trigger anti-spam or break voice chat",
options: ["windows", "linux", "darwin"]
},
"run-shortcut": {
type: "string",
description: `Trigger a keybind action in the running instance. Append :down or :up to only press or release it (e.g. for push to talk). Actions: ${SHORTCUT_ACTIONS.join(", ")}`,
argumentName: "action[:down|:up]"
},
repair: {
type: "boolean",
description: "Repair the application by re-downloading the latest Vencord files"
@@ -145,6 +151,15 @@ export function checkCommandLineForHelpOrVersion() {
app.exit(1);
}
}
const runShortcut = CommandLine.values["run-shortcut"];
if (runShortcut && !parseShortcutCommand(runShortcut)) {
console.error(
`Invalid value for --run-shortcut: ${runShortcut}\nExpected one of: ${SHORTCUT_ACTIONS.join(", ")}`
);
console.error("Optionally followed by :down or :up");
app.exit(1);
}
}
checkCommandLineForHelpOrVersion();
+18
View File
@@ -5,6 +5,7 @@
*/
import { existsSync, mkdirSync, rmSync } from "fs";
import { tmpdir, userInfo } from "os";
import { dirname, join } from "path";
import { app } from "electron";
@@ -73,3 +74,20 @@ export const enum MessageBoxChoice {
}
export const IS_FLATPAK = process.env.FLATPAK_ID !== undefined;
export const IS_WAYLAND =
process.platform === "linux" && (process.env.XDG_SESSION_TYPE === "wayland" || !!process.env.WAYLAND_DISPLAY);
function getSocketPath() {
if (process.platform === "win32") return `\\\\.\\pipe\\vesktop-${userInfo().username}`;
const { XDG_RUNTIME_DIR, FLATPAK_ID } = process.env;
if (!XDG_RUNTIME_DIR) return join(tmpdir(), `vesktop-${userInfo().uid}.sock`);
// Only $XDG_RUNTIME_DIR/app/$FLATPAK_ID is shared with the host
return FLATPAK_ID
? join(XDG_RUNTIME_DIR, "app", FLATPAK_ID, "vesktop.sock")
: join(XDG_RUNTIME_DIR, "vesktop.sock");
}
export const SOCKET_PATH = getSocketPath();
+21 -1
View File
@@ -6,14 +6,23 @@
import { join } from "path";
import type { XDPGlobalShortcutsEvent } from "libvesktop";
import { STATIC_DIR } from "shared/paths";
import { IS_FLATPAK } from "./constants";
// Name of our .desktop file, which portals and GNOME identify us by
const APP_ID = process.env.FLATPAK_ID ?? "vesktop";
let libVesktop: typeof import("libvesktop") | null = null;
function loadLibVesktop() {
try {
if (!libVesktop) {
libVesktop = require(join(STATIC_DIR, `dist/libvesktop-${process.arch}.node`));
libVesktop = require(
join(STATIC_DIR, `dist/libvesktop-${process.arch}.node`)
) as typeof import("libvesktop");
if (!IS_FLATPAK) libVesktop.registerHostApp(APP_ID);
}
} catch (e) {
console.error("Failed to load libvesktop:", e);
@@ -29,3 +38,14 @@ export function requestBackground(autoStart: boolean, commandLine: string[]) {
export function isStatusNotifierHostRegistered() {
return loadLibVesktop()?.isStatusNotifierHostRegistered() ?? true;
}
export function createXDPGlobalShortcuts(onEvent: (...args: XDPGlobalShortcutsEvent) => void) {
const lib = loadLibVesktop();
if (!lib) return null;
return new lib.XDPGlobalShortcuts(onEvent);
}
export function openGnomeAppSettings() {
return loadLibVesktop()?.openGnomeAppSettings(APP_ID) ?? false;
}
+61
View File
@@ -0,0 +1,61 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { rmSync } from "fs";
import { createServer, Server } from "net";
import { createInterface } from "readline";
import { app } from "electron";
import { parseShortcutCommand } from "shared/utils/keybind";
import { SOCKET_PATH } from "./constants";
import { runShortcutCommand } from "./keybinds";
let server: Server | undefined;
function runCommand(line: string) {
const [command, arg = ""] = line.trim().split(/\s+/, 2);
switch (command) {
case "run-shortcut": {
const shortcut = parseShortcutCommand(arg);
if (!shortcut) return "error: invalid shortcut";
runShortcutCommand(shortcut);
return "ok";
}
default:
return "error: unknown command";
}
}
/**
* Line based socket for triggering actions from other programs, for example compositor keybinds.
* Connections stay open, so a client can send multiple commands, like `run-shortcut pushToTalk:down` and `:up`.
* Every line gets a reply line, either "ok" or "error: <reason>"
*/
export function initSocket() {
// We hold the single instance lock, so any existing socket is stale
if (process.platform !== "win32") rmSync(SOCKET_PATH, { force: true });
server = createServer(socket => {
socket.on("error", () => {});
createInterface({ input: socket }).on("line", line => {
if (line.trim()) socket.write(runCommand(line) + "\n");
});
});
server.on("error", err => console.error("Failed to start IPC socket:", err));
server.listen(SOCKET_PATH);
}
app.on("will-quit", () => {
if (!server) return;
server.close();
if (process.platform !== "win32") rmSync(SOCKET_PATH, { force: true });
});
+43
View File
@@ -0,0 +1,43 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { IpcCommands } from "shared/IpcEvents";
import { KeybindStatus, ShortcutAction } from "shared/utils/keybind";
import { IS_WAYLAND } from "../constants";
import { AppEvents } from "../events";
import { sendRendererCommand } from "../ipcCommands";
let appLoaded = false;
AppEvents.on("appLoaded", () => (appLoaded = true));
export let status: KeybindStatus = { backend: IS_WAYLAND ? "portal" : "hook" };
export function setStatus(newStatus: Omit<KeybindStatus, "backend">) {
status = { backend: status.backend, ...newStatus };
if (appLoaded)
sendRendererCommand(IpcCommands.KEYBINDS_STATUS, status).catch(err =>
console.error("Failed to send keybind status:", err)
);
}
// Events before Discord is loaded are dropped rather than queued, as they would all fire at once later
export function triggerAction(action: ShortcutAction, pressed: boolean) {
if (!appLoaded) return;
sendRendererCommand(IpcCommands.KEYBINDS_TRIGGER, { action, pressed }).catch(err =>
console.error("Failed to trigger keybind action:", action, err)
);
}
/** Runs a command parsed by parseShortcutCommand. If pressed is undefined, the action is pressed and released */
export function runShortcutCommand({ action, pressed }: { action: ShortcutAction; pressed?: boolean }) {
if (pressed !== undefined) return triggerAction(action, pressed);
triggerAction(action, true);
triggerAction(action, false);
}
+181
View File
@@ -0,0 +1,181 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { systemPreferences } from "electron";
import { KeyBind, KeybindStatus, ShortcutAction } from "shared/utils/keybind";
import type { UiohookKeyboardEvent, UiohookMouseEvent } from "uiohook-napi";
import { triggerAction } from "./actions";
type Uiohook = typeof import("uiohook-napi");
type InputEvent = UiohookKeyboardEvent | UiohookMouseEvent;
type ActiveBind = KeyBind & { action: ShortcutAction };
// uiohook key names that differ from our key names (KeyboardEvent.code with merged modifiers)
const KEY_RENAMES: Record<string, string> = {
Ctrl: "Control",
CtrlRight: "Control",
AltRight: "Alt",
ShiftRight: "Shift",
MetaRight: "Meta",
// Numpad keys with NumLock off
NumpadInsert: "Numpad0",
NumpadEnd: "Numpad1",
NumpadArrowDown: "Numpad2",
NumpadPageDown: "Numpad3",
NumpadArrowLeft: "Numpad4",
NumpadArrowRight: "Numpad6",
NumpadHome: "Numpad7",
NumpadArrowUp: "Numpad8",
NumpadPageUp: "Numpad9",
NumpadDelete: "NumpadDecimal"
};
const MODIFIER_FLAGS = {
Control: "ctrlKey",
Shift: "shiftKey",
Alt: "altKey",
Meta: "metaKey"
} as const;
let uiohook: Uiohook | null = null;
let keyNames = new Map<number, string>();
let running = false;
let binds: ActiveBind[] = [];
const heldKeys = new Set<string>();
const activeBinds = new Set<ActiveBind>();
function toKeyName(uiohookName: string) {
if (/^[A-Z]$/.test(uiohookName)) return "Key" + uiohookName;
if (/^\d$/.test(uiohookName)) return "Digit" + uiohookName;
return KEY_RENAMES[uiohookName] ?? uiohookName;
}
function loadUiohook() {
if (!uiohook) {
uiohook = require("uiohook-napi") as Uiohook;
keyNames = new Map(Object.entries(uiohook.UiohookKey).map(([name, code]) => [code, toKeyName(name)]));
}
return uiohook;
}
function press(key: string) {
// Held keys repeat their keydown event
if (heldKeys.has(key)) return;
heldKeys.add(key);
// Other keys may be held too, so push to talk keeps working while moving in a game
for (const bind of binds) {
if (!activeBinds.has(bind) && bind.keys.includes(key) && bind.keys.every(k => heldKeys.has(k))) {
activeBinds.add(bind);
triggerAction(bind.action, true);
}
}
}
function release(key: string) {
heldKeys.delete(key);
for (const bind of activeBinds) {
if (bind.keys.includes(key)) {
activeBinds.delete(bind);
triggerAction(bind.action, false);
}
}
}
function releaseAll() {
for (const key of heldKeys) release(key);
}
// A modifier release can be missed, for example when the lock screen grabs input. The flags of later events tell us
function syncModifiers(event: InputEvent, key?: string) {
for (const [modifier, flag] of Object.entries(MODIFIER_FLAGS)) {
if (modifier !== key && heldKeys.has(modifier) && !event[flag]) release(modifier);
}
}
function onKeyDown(event: UiohookKeyboardEvent) {
const key = keyNames.get(event.keycode);
syncModifiers(event, key);
if (key) press(key);
}
function onKeyUp(event: UiohookKeyboardEvent) {
const key = keyNames.get(event.keycode);
syncModifiers(event, key);
if (key) release(key);
}
// 1 and 2 are left and right click, which we don't allow binding
const mouseKey = (event: UiohookMouseEvent) => {
const button = event.button as number;
return button >= 3 && button <= 5 ? `Mouse${button}` : null;
};
function onMouseDown(event: UiohookMouseEvent) {
syncModifiers(event);
const key = mouseKey(event);
if (key) press(key);
}
function onMouseUp(event: UiohookMouseEvent) {
syncModifiers(event);
const key = mouseKey(event);
if (key) release(key);
}
function start() {
const { uIOhook } = loadUiohook();
if (running) return;
uIOhook.on("keydown", onKeyDown);
uIOhook.on("keyup", onKeyUp);
uIOhook.on("mousedown", onMouseDown);
uIOhook.on("mouseup", onMouseUp);
try {
uIOhook.start();
} catch (err) {
uIOhook.removeAllListeners();
throw err;
}
running = true;
}
export function stopHook() {
releaseAll();
if (!running) return;
uiohook!.uIOhook.stop();
uiohook!.uIOhook.removeAllListeners();
running = false;
}
/** Listens for the given binds, only running the input hook while there are any */
export function setHookBinds(newBinds: KeyBind[]): Omit<KeybindStatus, "backend"> {
releaseAll();
binds = newBinds.filter((b): b is ActiveBind => b.enabled && b.action !== "unassigned" && b.keys.length > 0);
if (!binds.length) {
stopHook();
return {};
}
if (process.platform === "darwin" && !systemPreferences.isTrustedAccessibilityClient(false)) {
stopHook();
return { needsPermission: true };
}
try {
start();
return {};
} catch (err) {
console.error("Failed to start input hook:", err);
return { error: `Failed to listen to input: ${err instanceof Error ? err.message : err}` };
}
}
+49
View File
@@ -0,0 +1,49 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { app, systemPreferences } from "electron";
import { IpcEvents } from "shared/IpcEvents";
import { IS_WAYLAND, SOCKET_PATH } from "../constants";
import { Settings } from "../settings";
import { handle, handleSync } from "../utils/ipcWrappers";
import { setStatus, status } from "./actions";
import { setHookBinds, stopHook } from "./hook";
import { configurePortalShortcuts, setPortalEnabled, stopPortal } from "./portal";
export { runShortcutCommand } from "./actions";
// Wayland doesn't let apps see global input, not even XWayland ones, so we have to go through the portal there
function update() {
if (IS_WAYLAND) setPortalEnabled(!!Settings.store.globalShortcutsPortal);
else setStatus(setHookBinds(Settings.store.keyBinds ?? []));
}
export function initKeybinds() {
update();
if (IS_WAYLAND) Settings.addChangeListener("globalShortcutsPortal", update);
else Settings.addChangeListener("keyBinds", update);
// macOS doesn't tell us when the permission is granted, so check again when the user comes back from System Settings
if (process.platform === "darwin")
app.on("browser-window-focus", () => {
if (status.needsPermission && systemPreferences.isTrustedAccessibilityClient(false)) update();
});
}
handle(IpcEvents.KEYBINDS_GET_STATUS, () => status);
handleSync(IpcEvents.KEYBINDS_GET_SOCKET_PATH, () => SOCKET_PATH);
handle(IpcEvents.KEYBINDS_RETRY, update);
handle(IpcEvents.KEYBINDS_REQUEST_PERMISSION, () => {
if (process.platform === "darwin") systemPreferences.isTrustedAccessibilityClient(true);
});
handle(IpcEvents.KEYBINDS_CONFIGURE_PORTAL, configurePortalShortcuts);
app.on("will-quit", () => {
stopHook();
stopPortal();
});
+85
View File
@@ -0,0 +1,85 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import type { XDPGlobalShortcuts, XDPGlobalShortcutsEvent } from "libvesktop";
import { ACTION_DESCRIPTIONS, isShortcutAction, SHORTCUT_ACTIONS } from "shared/utils/keybind";
import { createXDPGlobalShortcuts, openGnomeAppSettings } from "../dbus";
import { setStatus, status, triggerAction } from "./actions";
let session: XDPGlobalShortcuts | null = null;
function onEvent(...event: XDPGlobalShortcutsEvent) {
switch (event[0]) {
case "version":
setStatus({ ...status, portalVersion: event[1], portalConfigurable: canConfigure(event[1]) });
break;
case "ready":
// The portal decides the triggers, so we register every action and let the user assign the ones they want
session?.bindShortcuts(SHORTCUT_ACTIONS.map(id => ({ id, description: ACTION_DESCRIPTIONS[id] })));
setStatus({ ...status, portalState: "ready" });
break;
case "shortcuts": {
// Portals only return shortcuts that have a trigger assigned
const triggers = new Map(event[1].map(s => [s.id, s.trigger]));
const portalShortcuts = SHORTCUT_ACTIONS.map(id => ({
id,
description: ACTION_DESCRIPTIONS[id],
trigger: triggers.get(id) ?? ""
}));
setStatus({ ...status, portalShortcuts, error: undefined });
break;
}
case "shortcut":
if (isShortcutAction(event[1])) triggerAction(event[1], event[2]);
break;
case "error":
console.error("GlobalShortcuts portal error:", event[1]);
setStatus({ ...status, error: event[1] });
break;
case "fatal":
console.error("GlobalShortcuts portal is unavailable:", event[1]);
stopPortal();
setStatus({ ...status, portalState: "unavailable", error: event[1] });
break;
}
}
export function stopPortal() {
session?.destroy();
session = null;
}
export function setPortalEnabled(enabled: boolean) {
if (!enabled) {
stopPortal();
setStatus({ portalState: "disabled" });
return;
}
if (session) return;
setStatus({ portalState: "connecting" });
try {
session = createXDPGlobalShortcuts(onEvent);
if (!session) setStatus({ portalState: "unavailable", error: "Failed to load libvesktop" });
} catch (err) {
console.error("Failed to create GlobalShortcuts portal session:", err);
setStatus({ portalState: "unavailable", error: String(err) });
}
}
const IS_GNOME = process.env.XDG_CURRENT_DESKTOP?.split(":").includes("GNOME") ?? false;
// Portals before version 2 can't open their shortcut settings, but GNOME Settings has them on the app's page
const canConfigure = (version = 0) => version >= 2 || IS_GNOME;
export function configurePortalShortcuts() {
if ((status.portalVersion ?? 0) >= 2) return session?.configureShortcuts();
if (IS_GNOME && !openGnomeAppSettings())
setStatus({ ...status, error: "Failed to open GNOME Settings. Find Vesktop under Apps instead" });
}
+20 -2
View File
@@ -11,9 +11,14 @@ import "./rpc";
import "./userAssets";
import "./vesktopProtocol";
import { app, BrowserWindow, nativeTheme } from "electron";
import { parseShortcutCommand } from "shared/utils/keybind";
// eslint-disable-next-line no-duplicate-imports
import { CommandLine } from "./cli";
import { DATA_DIR } from "./constants";
import { createFirstLaunchTour } from "./firstLaunch";
import { initSocket } from "./ipcSocket";
import { initKeybinds, runShortcutCommand } from "./keybinds";
import { createWindows, mainWin, openDeepLink } from "./mainWindow";
import { registerMediaPermissionsHandler } from "./mediaPermissions";
import { registerScreenShareHandler } from "./screenShare";
@@ -97,6 +102,12 @@ function init() {
if (isDeckGameMode) nativeTheme.themeSource = "dark";
app.on("second-instance", (_event, cmdLine, _cwd, data: any) => {
if (data?.runShortcut) {
const command = parseShortcutCommand(data.runShortcut);
if (command) runShortcutCommand(command);
return;
}
if (data?.IS_DEV) return app.quit();
if (!mainWin) return;
@@ -111,6 +122,8 @@ function init() {
registerScreenShareHandler();
registerMediaPermissionsHandler();
initKeybinds();
initSocket();
bootstrap();
@@ -120,14 +133,19 @@ function init() {
});
}
if (!app.requestSingleInstanceLock({ IS_DEV })) {
if (IS_DEV) {
const runShortcut = CommandLine.values["run-shortcut"];
if (!app.requestSingleInstanceLock({ IS_DEV, runShortcut })) {
if (IS_DEV && !runShortcut) {
console.log("Vesktop is already running. Quitting previous instance...");
init();
} else {
console.log("Vesktop is already running. Quitting...");
app.quit();
}
} else if (runShortcut) {
console.error("Vesktop is not running, so --run-shortcut has no effect");
app.exit(1);
} else {
init();
}
+3 -5
View File
@@ -10,13 +10,11 @@ import { desktopCapturer, session, Streams } from "electron";
import type { StreamPick } from "renderer/components/ScreenSharePicker";
import { IpcCommands, IpcEvents } from "shared/IpcEvents";
import { IS_WAYLAND } from "./constants";
import { sendRendererCommand } from "./ipcCommands";
import { handle } from "./utils/ipcWrappers";
import { isDiscordUrl } from "./utils/isDiscordUrl";
const isWayland =
process.platform === "linux" && (process.env.XDG_SESSION_TYPE === "wayland" || !!process.env.WAYLAND_DISPLAY);
const supportsLoopbackWithoutChrome = process.platform === "win32" && Number(release().split(".").pop()) >= 19045;
// Sources shown in the currently open picker. Only serve thumbnails for these,
@@ -42,7 +40,7 @@ export function registerScreenShareHandler() {
if (!isDiscordUrl(request.frame?.top?.url)) return callback(null);
// request full resolution on wayland right away because we always only end up with one result anyway
const width = isWayland ? 1920 : 176;
const width = IS_WAYLAND ? 1920 : 176;
const sources = await desktopCapturer
.getSources({
types: ["window", "screen"],
@@ -61,7 +59,7 @@ export function registerScreenShareHandler() {
url: thumbnail.toDataURL()
}));
if (isWayland) {
if (IS_WAYLAND) {
const video = data[0];
if (video) {
const stream = await sendRendererCommand<StreamPick>(IpcCommands.SCREEN_SHARE_PICKER, {
+8
View File
@@ -8,6 +8,7 @@ import type { Node } from "@vencord/venmic";
import { ipcRenderer } from "electron/renderer";
import type { IpcMessage, IpcResponse } from "main/ipcCommands";
import type { Settings } from "shared/settings";
import type { KeybindStatus } from "shared/utils/keybind";
import { IpcEvents } from "../shared/IpcEvents";
import { invoke, sendSync } from "./typedIpc";
@@ -95,6 +96,13 @@ export const VesktopNative = {
unmute: () => invoke<void>(IpcEvents.VIRT_MIC_UNMUTE),
stop: () => invoke<void>(IpcEvents.VIRT_MIC_STOP)
},
keybinds: {
getStatus: () => invoke<KeybindStatus>(IpcEvents.KEYBINDS_GET_STATUS),
getSocketPath: () => sendSync<string>(IpcEvents.KEYBINDS_GET_SOCKET_PATH),
retry: () => invoke<void>(IpcEvents.KEYBINDS_RETRY),
requestPermission: () => invoke<void>(IpcEvents.KEYBINDS_REQUEST_PERMISSION),
configurePortal: () => invoke<void>(IpcEvents.KEYBINDS_CONFIGURE_PORTAL)
},
clipboard: {
copyImage: (imageBuffer: Uint8Array, imageSrc: string) =>
invoke<void>(IpcEvents.CLIPBOARD_COPY_IMAGE, imageBuffer, imageSrc)
@@ -9,6 +9,7 @@ import { classNameFactory } from "@vencord/types/api/Styles";
import { Divider, ErrorBoundary, Text } from "@vencord/types/components";
import { ComponentType } from "react";
import { WebRTCIPHandlingPolicyPicker } from "renderer/components/settings/WebRTCIPHandlingPolicyPicker";
import { KeybindsButton } from "renderer/globalShortcuts/ShortcutSettings";
import { getValueAndOnChange, Settings, useSettings } from "renderer/settings";
import { isMac } from "renderer/utils";
@@ -128,7 +129,8 @@ const SettingsOptions: Record<string, Array<BooleanSetting | SettingsComponent>>
key: "disableSmoothScroll",
title: "Disable smooth scrolling",
description: "Disables smooth scrolling"
}
},
KeybindsButton
],
Notifications: [
NotificationBadgeToggle,
@@ -0,0 +1,92 @@
.vcd-shortcuts-container {
display: flex;
flex-direction: column;
gap: 1em;
padding-block: 1em;
}
.vcd-shortcuts-card,
.vcd-shortcuts-buttons {
display: flex;
gap: 0.5em;
}
.vcd-shortcuts-card {
flex-direction: column;
align-items: start;
}
.vcd-shortcuts-row {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto auto;
gap: 0.5em;
align-items: center;
}
.vcd-shortcuts-recorder {
display: flex;
align-items: center;
gap: 0.5em;
background-color: var(--input-background-default);
border: 1px solid var(--input-border-default);
border-radius: var(--radius-sm);
min-height: calc(var(--select-option-height) - 2px);
padding: 3px 4px 3px 12px;
box-sizing: border-box;
}
.vcd-shortcuts-recorder-keys {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.vcd-shortcuts-muted {
color: var(--text-muted);
}
.vcd-shortcuts-table {
width: 100%;
border-collapse: collapse;
border: 1px solid var(--border-subtle);
border-radius: var(--radius-sm);
& th,
& td {
text-align: start;
padding: 0.6em 1em;
border-bottom: 1px solid var(--border-subtle);
}
& th {
text-transform: uppercase;
background-color: var(--background-base-lower);
}
& tr:last-child td {
border-bottom: none;
}
}
.vcd-shortcuts-external {
display: flex;
flex-direction: column;
gap: 1.25em;
& :is(h3, h4) {
margin: 0;
}
}
.vcd-shortcuts-external-section {
display: flex;
flex-direction: column;
gap: 0.5em;
& pre {
max-width: none;
margin: 0;
}
}
@@ -0,0 +1,340 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import "./ShortcutSettings.css";
import {
Button,
Card,
CodeBlock,
DeleteIcon,
Divider,
FormSwitch,
HeadingSecondary,
HeadingTertiary,
InlineCode,
Paragraph,
Switch,
Text
} from "@vencord/types/components";
import { classNameFactory, identity } from "@vencord/types/utils";
import { Modal, openModal, React, Select, useEffect, useState } from "@vencord/types/webpack/common";
import { SettingsComponent } from "renderer/components/settings/Settings";
import { onIpcCommand } from "renderer/ipcCommands";
import { reactiveValue } from "renderer/reactiveState";
import { useSettings } from "renderer/settings";
import { isLinux } from "renderer/utils";
import { IpcCommands } from "shared/IpcEvents";
import { ACTION_DESCRIPTIONS, KeyBind, KeybindStatus } from "shared/utils/keybind";
import { keysToDisplay, loadKeyboardLayout, recordKeybind } from "./recordKeybind";
const cl = classNameFactory("vcd-shortcuts-");
const keybindStatus = reactiveValue<KeybindStatus | null>(null);
onIpcCommand(IpcCommands.KEYBINDS_STATUS, (status: KeybindStatus) => (keybindStatus.value = status));
const ACTION_OPTIONS = [
{ label: "Unassigned", value: "unassigned" },
...Object.entries(ACTION_DESCRIPTIONS).map(([value, label]) => ({ label, value }))
];
function ErrorCard({ children, onRetry }: { children: React.ReactNode; onRetry?(): void }) {
return (
<Card variant="danger" className={cl("card")}>
<Text size="md">{children}</Text>
{onRetry && (
<Button size="small" variant="secondary" onClick={onRetry}>
Retry
</Button>
)}
</Card>
);
}
function KeybindRecorder({
keybind: { keys, labels },
onChange
}: {
keybind: KeyBind;
onChange(recorded: Pick<KeyBind, "keys" | "labels">): void;
}) {
const [controller, setController] = useState<AbortController | null>(null);
// Stop listening for input if the modal is closed while recording
useEffect(() => () => controller?.abort(), [controller]);
async function toggleRecording() {
if (controller) return controller.abort();
const newController = new AbortController();
setController(newController);
try {
onChange(await recordKeybind(newController.signal));
} catch {
// aborted
} finally {
setController(null);
}
}
const display = keys.length ? keysToDisplay(keys, labels) : "No Keybind Set";
return (
<div className={cl("recorder")}>
<Text size="md" weight={keys.length ? "semibold" : "normal"} className={cl("recorder-keys")}>
{controller ? "Press keys or mouse buttons..." : display}
</Text>
<Button size="small" variant="secondary" onClick={toggleRecording}>
{controller ? "Cancel" : "Record"}
</Button>
</div>
);
}
function KeybindRow({
keybind,
onChange,
onDelete
}: {
keybind: KeyBind;
onChange(keybind: KeyBind): void;
onDelete(): void;
}) {
return (
<div className={cl("row")}>
<Select
options={ACTION_OPTIONS}
isSelected={v => v === keybind.action}
select={action => onChange({ ...keybind, action })}
serialize={identity}
/>
<KeybindRecorder keybind={keybind} onChange={recorded => onChange({ ...keybind, ...recorded })} />
<Button size="iconOnly" variant="secondary" aria-label="Delete Keybind" onClick={onDelete}>
<DeleteIcon />
</Button>
<Switch checked={keybind.enabled} onChange={enabled => onChange({ ...keybind, enabled })} />
</div>
);
}
function HookKeybinds({ status }: { status: KeybindStatus }) {
const settings = useSettings();
const keybinds = settings.keyBinds ?? [];
const setKeybinds = (newKeybinds: KeyBind[]) => (settings.keyBinds = newKeybinds);
return (
<>
{status.needsPermission && (
<Card variant="warning" className={cl("card")}>
<Text size="md">
Vesktop needs the Accessibility permission to detect your keybinds while it is not focused.
</Text>
<Button size="small" onClick={() => VesktopNative.keybinds.requestPermission()}>
Grant Permission
</Button>
</Card>
)}
{status.error && <ErrorCard onRetry={() => VesktopNative.keybinds.retry()}>{status.error}</ErrorCard>}
{keybinds.map((keybind, i) => (
<KeybindRow
key={keybind.id}
keybind={keybind}
onChange={newKeybind => setKeybinds(keybinds.with(i, newKeybind))}
onDelete={() => setKeybinds(keybinds.toSpliced(i, 1))}
/>
))}
<Button
onClick={() =>
setKeybinds([
...keybinds,
{ id: crypto.randomUUID(), action: "unassigned", keys: [], enabled: true }
])
}
>
Add Keybind
</Button>
</>
);
}
// Portals describe triggers in their own format, e.g. GNOME uses "Press <Control><Shift>p"
function formatPortalTrigger(trigger: string) {
const match = /^(?:Press )?((?:<\w+>)+)(.+)$/.exec(trigger);
if (!match) return trigger;
const modifiers = match[1].slice(1, -1).split("><");
const key = match[2].length === 1 ? match[2].toUpperCase() : match[2];
return [...modifiers.map(m => (m === "Control" ? "Ctrl" : m)), key].join(" + ");
}
function PortalKeybinds({ status }: { status: KeybindStatus }) {
const settings = useSettings();
const { portalState, portalShortcuts = [], portalConfigurable } = status;
return (
<>
<FormSwitch
title="Enable global shortcuts"
description="Registers Vesktop's actions with your desktop environment, which lets you assign shortcuts to them. Your system may ask you to set them up."
value={!!settings.globalShortcutsPortal}
onChange={v => (settings.globalShortcutsPortal = v)}
hideBorder
/>
{portalState === "connecting" && <Text size="md">Connecting to your desktop environment...</Text>}
{portalState === "unavailable" && (
<ErrorCard onRetry={() => VesktopNative.keybinds.retry()}>
Your desktop environment does not support global shortcuts. You can still bind actions with your
compositor's keybinds instead, see below.
{status.error && ` (${status.error})`}
</ErrorCard>
)}
{portalState === "ready" && (
<>
{status.error && <ErrorCard>{status.error}</ErrorCard>}
<Table columns={["Action", "Shortcut"]}>
{portalShortcuts.map(({ id, description, trigger }) => (
<tr key={id}>
<Cell>{description}</Cell>
<Cell>
{trigger ? (
<InlineCode>{formatPortalTrigger(trigger)}</InlineCode>
) : (
<span className={cl("muted")}>Not assigned</span>
)}
</Cell>
</tr>
))}
</Table>
{portalConfigurable ? (
<Button onClick={() => VesktopNative.keybinds.configurePortal()}>Change Shortcuts</Button>
) : (
<Paragraph size="md">You can change these shortcuts in your system settings.</Paragraph>
)}
</>
)}
</>
);
}
function Table({ columns, children }: { columns: string[]; children: React.ReactNode }) {
return (
<table className={cl("table")}>
<thead>
<tr>
{columns.map(c => (
<th key={c}>
<Text size="xs" weight="semibold" className={cl("muted")}>
{c}
</Text>
</th>
))}
</tr>
</thead>
<tbody>{children}</tbody>
</table>
);
}
function Cell({ children }: { children: React.ReactNode }) {
return (
<td>
<Text size="md">{children}</Text>
</td>
);
}
function ExternalTriggers() {
const socketPath = VesktopNative.keybinds.getSocketPath();
return (
<section className={cl("external")}>
<HeadingSecondary>Triggering actions from other programs</HeadingSecondary>
<Paragraph size="md">
Useful for scripts or your compositor's keybinds. Add <InlineCode>:down</InlineCode> or{" "}
<InlineCode>:up</InlineCode> to only press or release an action, for example to bind push to talk to a
key press and its release.
</Paragraph>
<div className={cl("external-section")}>
<HeadingTertiary>Command Line</HeadingTertiary>
<CodeBlock
lang="sh"
content={[
"vesktop --run-shortcut toggleMute",
"vesktop --run-shortcut pushToTalk:down",
"vesktop --run-shortcut pushToTalk:up"
].join("\n")}
/>
</div>
<div className={cl("external-section")}>
<HeadingTertiary>Socket</HeadingTertiary>
<Paragraph size="md">
Faster than the command line. Send one command per line to <InlineCode>{socketPath}</InlineCode>
</Paragraph>
<CodeBlock lang="sh" content={`echo "run-shortcut toggleMute" | socat - UNIX-CONNECT:${socketPath}`} />
</div>
<div className={cl("external-section")}>
<HeadingTertiary>Actions</HeadingTertiary>
<Table columns={["Name", "Action"]}>
{Object.entries(ACTION_DESCRIPTIONS).map(([name, description]) => (
<tr key={name}>
<Cell>
<InlineCode>{name}</InlineCode>
</Cell>
<Cell>{description}</Cell>
</tr>
))}
</Table>
</div>
</section>
);
}
function KeybindSettings() {
const status = keybindStatus.use();
useEffect(() => {
VesktopNative.keybinds.getStatus().then(s => (keybindStatus.value = s));
}, []);
if (!status) return null;
return (
<div className={cl("container")}>
{status.backend === "portal" ? <PortalKeybinds status={status} /> : <HookKeybinds status={status} />}
{isLinux && (
<>
<Divider />
<ExternalTriggers />
</>
)}
</div>
);
}
export async function openKeybindsModal() {
await loadKeyboardLayout().catch(e => console.error("Failed to get keyboard layout", e));
openModal(props => (
<Modal {...props} size="xl" title="Global Keybinds">
<KeybindSettings />
</Modal>
));
}
export const KeybindsButton: SettingsComponent = () => (
<Button onClick={() => openKeybindsModal()}>Configure Global Keybinds</Button>
);
@@ -0,0 +1,43 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { Logger } from "@vencord/types/utils";
import { waitFor } from "@vencord/types/webpack";
import { ACTION_MAP, ShortcutAction } from "shared/utils/keybind";
const logger = new Logger("VesktopKeybinds");
interface KeybindAction {
// keybind is the keybind from Discord's KeybindStore that triggered the action
onTrigger(pressed: boolean, keybind: { action: string; shortcut: unknown[]; params: object }): void;
keyEvents: { keydown: boolean; keyup: boolean };
}
let keybindActions: Record<string, KeybindAction> | undefined;
waitFor(["dispatch", "subscribe"], FluxDispatcher => {
FluxDispatcher.subscribe("KEYBINDS_REGISTER_GLOBAL_KEYBIND_ACTIONS", (event: any) => {
keybindActions = event.keybinds;
});
});
export function handleKeybind(action: ShortcutAction, pressed: boolean) {
if (!keybindActions) {
logger.warn("Ignoring keybind, Discord has not registered its keybind actions yet");
return;
}
const discordAction = ACTION_MAP[action];
const keybind = keybindActions[discordAction];
if (!keybind) {
logger.warn(`Discord keybind action ${discordAction} not found`);
return;
}
// Discord decides which key events an action uses. Push to talk uses both, toggles only key up
if (pressed ? keybind.keyEvents.keydown : keybind.keyEvents.keyup)
keybind.onTrigger(pressed, { action: discordAction, shortcut: [], params: {} });
}
@@ -0,0 +1,180 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { isMac, isWindows } from "renderer/utils";
import { KeyBind, sortKeys } from "shared/utils/keybind";
const MODIFIER_CODES: Record<string, string> = {
ControlLeft: "Control",
ControlRight: "Control",
ShiftLeft: "Shift",
ShiftRight: "Shift",
AltLeft: "Alt",
AltRight: "Alt",
MetaLeft: "Meta",
MetaRight: "Meta"
};
// MouseEvent.button: 1 is middle, 3 is back and 4 is forward. Same numbering as the input hook
const MOUSE_BUTTONS: Record<number, string> = {
1: "Mouse3",
3: "Mouse4",
4: "Mouse5"
};
// Keys the input hook can detect, besides modifiers and mouse buttons
const SUPPORTED_KEY = new RegExp(
"^(" +
[
"Key[A-Z]",
"Digit\\d",
"F([1-9]|1\\d|2[0-4])",
"Numpad(\\d|Add|Subtract|Multiply|Divide|Decimal|Enter)",
"Arrow(Up|Down|Left|Right)",
"Backspace|Tab|Enter|CapsLock|Escape|Space|PageUp|PageDown|End|Home|Insert|Delete",
"Semicolon|Equal|Comma|Minus|Period|Slash|Backquote|BracketLeft|Backslash|BracketRight|Quote",
"NumLock|ScrollLock|PrintScreen"
].join("|") +
")$"
);
const DISPLAY_NAMES: Record<string, string> = {
Control: "Ctrl",
Alt: isMac ? "Option" : "Alt",
Meta: isWindows ? "Win" : isMac ? "Cmd" : "Super",
Escape: "Esc",
Backquote: "`",
Minus: "-",
Equal: "=",
BracketLeft: "[",
BracketRight: "]",
Backslash: "\\",
Semicolon: ";",
Quote: "'",
Comma: ",",
Period: ".",
Slash: "/",
NumpadAdd: "Num +",
NumpadSubtract: "Num -",
NumpadMultiply: "Num *",
NumpadDivide: "Num /",
NumpadDecimal: "Num .",
NumpadEnter: "Num Enter"
};
// Maps physical keys (KeyboardEvent.code) to what they type on the user's keyboard layout
let layoutMap: Map<string, string> | undefined;
export async function loadKeyboardLayout() {
layoutMap = await (navigator as any).keyboard.getLayoutMap();
}
// Layout dependent Windows virtual key codes, named like the input hook reports them
const WINDOWS_OEM_KEYS: Record<number, string> = {
0xba: "Semicolon",
0xbb: "Equal",
0xbc: "Comma",
0xbd: "Minus",
0xbe: "Period",
0xbf: "Slash",
0xc0: "Backquote",
0xdb: "BracketLeft",
0xdc: "Backslash",
0xdd: "BracketRight",
0xde: "Quote"
};
// The input hook matches physical keys, except on Windows where it gets the virtual key the layout assigns.
// So store the virtual key there, which keyCode is on Windows
function toBindKey(e: KeyboardEvent) {
if (!isWindows) return e.code;
const vk = e.keyCode;
if (vk >= 0x30 && vk <= 0x39) return "Digit" + String.fromCharCode(vk);
if (vk >= 0x41 && vk <= 0x5a) return "Key" + String.fromCharCode(vk);
return WINDOWS_OEM_KEYS[vk] ?? e.code;
}
function keyToDisplay(key: string, label?: string) {
// Windows binds store virtual keys, which we can't map to what they type, so they come with a label instead
const typed = label ?? (isWindows ? undefined : layoutMap?.get(key));
if (typed?.trim()) return typed.toUpperCase();
if (DISPLAY_NAMES[key]) return DISPLAY_NAMES[key];
const match = /^(Key|Digit|Arrow|Numpad|Mouse)(.+)$/.exec(key);
if (!match) return key;
const [, prefix, rest] = match;
if (prefix === "Numpad") return `Num ${rest}`;
if (prefix === "Mouse") return `Mouse ${rest}`;
return rest;
}
export function keysToDisplay(keys: string[], labels?: Record<string, string>) {
return keys.map(key => keyToDisplay(key, labels?.[key])).join(" + ");
}
/**
* Records a keybind: every key and mouse button held down until the first one is released.
* Modifiers on their own are allowed, since they are popular for push to talk
*/
export function recordKeybind(signal: AbortSignal) {
return new Promise<Pick<KeyBind, "keys" | "labels">>((resolve, reject) => {
const keys = new Set<string>();
const labels: Record<string, string> = {};
// Aborted once recording finishes, to remove all listeners
const done = new AbortController();
const finish = () => {
if (!keys.size) return;
done.abort();
resolve({ keys: sortKeys([...keys]), labels: Object.keys(labels).length ? labels : undefined });
};
const onKeyDown = (e: KeyboardEvent) => {
e.preventDefault();
e.stopImmediatePropagation();
const key = MODIFIER_CODES[e.code] ?? toBindKey(e);
if (!MODIFIER_CODES[e.code] && !SUPPORTED_KEY.test(key)) return;
keys.add(key);
if (isWindows && Object.values(WINDOWS_OEM_KEYS).includes(key))
labels[key] = layoutMap?.get(e.code) ?? e.key;
};
const onKeyUp = (e: KeyboardEvent) => {
e.preventDefault();
e.stopImmediatePropagation();
finish();
};
const onMouseDown = (e: MouseEvent) => {
const key = MOUSE_BUTTONS[e.button];
if (!key) return;
e.preventDefault();
e.stopImmediatePropagation();
keys.add(key);
};
const onMouseUp = (e: MouseEvent) => {
if (!MOUSE_BUTTONS[e.button]) return;
e.preventDefault();
e.stopImmediatePropagation();
finish();
};
const options = { capture: true, signal: AbortSignal.any([signal, done.signal]) };
document.addEventListener("keydown", onKeyDown, options);
document.addEventListener("keyup", onKeyUp, options);
document.addEventListener("mousedown", onMouseDown, options);
document.addEventListener("mouseup", onMouseUp, options);
signal.addEventListener("abort", () => reject(signal.reason), { signal: done.signal });
});
}
+3
View File
@@ -8,6 +8,7 @@ import { NavigationRouter, SettingsRouter } from "@vencord/types/webpack/common"
import { IpcCommands } from "shared/IpcEvents";
import { openScreenSharePicker } from "./components/ScreenSharePicker";
import { handleKeybind } from "./globalShortcuts/keybindHandler";
type IpcCommandHandler = (data: any) => any;
@@ -54,3 +55,5 @@ onIpcCommand(IpcCommands.NAVIGATE_SETTINGS, () => {
onIpcCommand(IpcCommands.GET_LANGUAGES, () => navigator.languages);
onIpcCommand(IpcCommands.SCREEN_SHARE_PICKER, data => openScreenSharePicker(data.screens, data.skipPicker));
onIpcCommand(IpcCommands.KEYBINDS_TRIGGER, ({ action, pressed }) => handleKeybind(action, pressed));
+53
View File
@@ -0,0 +1,53 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { Button, ErrorBoundary } from "@vencord/types/components";
import { openKeybindsModal } from "renderer/globalShortcuts/ShortcutSettings";
import { addPatch } from "./shared";
addPatch({
patches: [
{
find: "#{intl::KEYBIND_IN_BROSWER_NOTICE}",
replacement: {
match: /:(.{0,10}jsx.{0,50}message:.{0,100}#{intl::KEYBIND_IN_BROSWER_NOTICE})/,
replace: ":true?$self.renderKeybindsButton():$1"
}
},
// Push to talk in Voice & Video settings
{
find: '"PTT Limited Modal"',
replacement: [
// Don't warn that push to talk only works while focused
{
match: /(===\i\.\i\.PUSH_TO_TALK&&)\i(?=&&.{0,400}"PTT Limited Modal")/,
replace: "$1false"
},
// Use the normal title instead of "Push-to-talk (Limited)"
{
match: /(VOICE_PUSH_TO_TALK_SETTING,\{useTitle:function\(\)\{return )\i\.\i(?=\?)/,
replace: "$1true"
},
// Remove the subtitle telling you to download the desktop app
{
match: /(?<=useSubtitle:function\(\)\{.{0,120}if\()!\i\.\i&&/,
replace: "false&&"
},
// Replace Discord's in-app recorder with our keybind settings
{
match: /(VOICE_PUSH_TO_TALK_KEYBIND_SETTING,.+?layout:"horizontal-responsive",children:)\(0,\i\.jsxs\)\("div",\{className:\i\.\i,children:\[.+?\(0,\i\.jsx\)\(\i,\{shortcut:\i\}\)\]\}\)/,
replace: "$1$self.renderKeybindsButton()"
}
]
}
],
renderKeybindsButton: ErrorBoundary.wrap(
() => <Button onClick={() => openKeybindsModal()}>Configure Global Keybinds</Button>,
{ noop: true }
)
});
+40
View File
@@ -0,0 +1,40 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { useForceUpdater } from "@vencord/types/utils";
import { useEffect } from "@vencord/types/webpack/common";
interface ReactiveValue<T> {
value: T;
use(): T;
}
export function reactiveValue<T>(initialValue: T): ReactiveValue<T>;
export function reactiveValue<T>(initialValue?: T): ReactiveValue<T | undefined>;
export function reactiveValue<T>(initialValue?: T) {
const changeListeners = new Set<() => void>();
let value = initialValue;
return {
get value() {
return value;
},
set value(newValue) {
value = newValue;
changeListeners.forEach(cb => cb());
},
use() {
const update = useForceUpdater();
useEffect(() => {
changeListeners.add(update);
return () => void changeListeners.delete(update);
}, [update]);
return value;
}
};
}
+11 -2
View File
@@ -66,7 +66,13 @@ export const enum IpcEvents {
DEVTOOLS_OPENED = "VCD_DEVTOOLS_OPENED",
DEVTOOLS_CLOSED = "VCD_DEVTOOLS_CLOSED",
CHOOSE_USER_ASSET = "VCD_CHOOSE_USER_ASSET"
CHOOSE_USER_ASSET = "VCD_CHOOSE_USER_ASSET",
KEYBINDS_GET_STATUS = "VCD_KEYBINDS_GET_STATUS",
KEYBINDS_GET_SOCKET_PATH = "VCD_KEYBINDS_GET_SOCKET_PATH",
KEYBINDS_RETRY = "VCD_KEYBINDS_RETRY",
KEYBINDS_REQUEST_PERMISSION = "VCD_KEYBINDS_REQUEST_PERMISSION",
KEYBINDS_CONFIGURE_PORTAL = "VCD_KEYBINDS_CONFIGURE_PORTAL"
}
export const enum UpdaterIpcEvents {
@@ -90,5 +96,8 @@ export const enum IpcCommands {
GET_LANGUAGES = "navigator.languages",
SCREEN_SHARE_PICKER = "screenshare:picker"
SCREEN_SHARE_PICKER = "screenshare:picker",
KEYBINDS_TRIGGER = "keybinds:trigger",
KEYBINDS_STATUS = "keybinds:status"
}
+6
View File
@@ -6,6 +6,8 @@
import type { Rectangle } from "electron";
import type { KeyBind } from "./utils/keybind";
export interface Settings {
discordBranch: "stable" | "canary" | "ptb";
transparencyOption: "none" | "mica" | "tabbed" | "acrylic";
@@ -55,6 +57,10 @@ export interface Settings {
onlySpeakers?: boolean;
onlyDefaultSpeakers?: boolean;
};
keyBinds?: KeyBind[];
/** Wayland only. Whether to register our actions with the GlobalShortcuts portal */
globalShortcutsPortal?: boolean;
}
export interface State {
+108
View File
@@ -0,0 +1,108 @@
/*
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
* Copyright (c) 2026 Vendicated and Vesktop contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
/**
* A global keybind. Keys are KeyboardEvent.code names, except that left and right modifiers
* are merged into "Control", "Shift", "Alt" and "Meta", and mouse buttons are "Mouse3" to "Mouse5"
*/
export interface KeyBind {
id: string;
action: ShortcutAction | "unassigned";
keys: string[];
// What layout dependent keys typed when recorded on Windows, where we can't look that up later
labels?: Record<string, string>;
enabled: boolean;
}
// Discord's global keybind action for each of our actions
export const ACTION_MAP = {
pushToTalk: "PUSH_TO_TALK",
pushToTalkPriority: "PUSH_TO_TALK_PRIORITY",
pushToMute: "PUSH_TO_MUTE",
vadPriority: "VAD_PRIORITY",
toggleMute: "TOGGLE_MUTE",
toggleDeafen: "TOGGLE_DEAFEN",
toggleVAD: "TOGGLE_VOICE_MODE",
toggleStreamerMode: "TOGGLE_STREAMER_MODE",
toggleCamera: "TOGGLE_CAMERA",
navigateBack: "NAVIGATE_BACK",
navigateForward: "NAVIGATE_FORWARD",
disconnectFromVoiceChannel: "DISCONNECT_FROM_VOICE_CHANNEL"
} as const;
export type ShortcutAction = keyof typeof ACTION_MAP;
export const ACTION_DESCRIPTIONS: Record<ShortcutAction, string> = {
pushToTalk: "Push to Talk (Normal)",
pushToTalkPriority: "Push to Talk (Priority)",
pushToMute: "Push to Mute",
vadPriority: "Voice Activity Priority",
toggleMute: "Toggle Mute",
toggleDeafen: "Toggle Deafen",
toggleVAD: "Toggle Push to Talk / Voice Activity",
toggleStreamerMode: "Toggle Streamer Mode",
toggleCamera: "Toggle Camera",
navigateBack: "Navigate Back",
navigateForward: "Navigate Forward",
disconnectFromVoiceChannel: "Disconnect from Voice Channel"
};
export const SHORTCUT_ACTIONS = Object.keys(ACTION_MAP) as ShortcutAction[];
export function isShortcutAction(action: string): action is ShortcutAction {
return Object.hasOwn(ACTION_MAP, action);
}
/**
* Parses "action", "action:down" or "action:up", as used by --run-shortcut and the IPC socket.
* pressed is undefined if the action should be pressed and released
*/
export function parseShortcutCommand(command: string): { action: ShortcutAction; pressed?: boolean } | null {
const [action, state, ...rest] = command.trim().split(":");
if (rest.length || !isShortcutAction(action)) return null;
switch (state) {
case undefined:
return { action };
case "down":
return { action, pressed: true };
case "up":
return { action, pressed: false };
default:
return null;
}
}
export const MODIFIER_KEYS = ["Control", "Shift", "Alt", "Meta"];
// Modifiers first, in a fixed order, then everything else alphabetically
export function sortKeys(keys: string[]) {
const rank = (key: string) => {
const i = MODIFIER_KEYS.indexOf(key);
return i === -1 ? MODIFIER_KEYS.length : i;
};
return keys.toSorted((a, b) => rank(a) - rank(b) || a.localeCompare(b));
}
export interface PortalShortcut {
id: string;
description: string;
trigger: string;
}
export interface KeybindStatus {
/** "hook" listens to all input (Windows, macOS, X11). "portal" uses the GlobalShortcuts portal (Wayland) */
backend: "hook" | "portal";
error?: string;
/** macOS only. Accessibility permission is required to listen to input */
needsPermission?: boolean;
portalState?: "disabled" | "connecting" | "ready" | "unavailable";
portalVersion?: number;
/** Whether we can open the portal's shortcut settings, see configurePortal */
portalConfigurable?: boolean;
portalShortcuts?: PortalShortcut[];
}