Repository: Vencord/Vesktop Branch: main Commit: 1f17c18362b1 Files: 147 Total size: 298.0 KB Directory structure: gitextract_wv_4r5eg/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── config.yml │ │ └── dev-issue.yml │ └── workflows/ │ ├── meta.yml │ ├── release.yml │ ├── test.yml │ ├── update-vencord-dev.yml │ └── winget-submission.yml ├── .gitignore ├── .npmrc ├── .prettierrc.yaml ├── .vscode/ │ └── settings.json ├── LICENSE ├── README.md ├── build/ │ ├── Assets.car │ ├── background.tiff │ ├── entitlements.mac.plist │ ├── icon.icns │ └── installer.nsh ├── eslint.config.mjs ├── package.json ├── packages/ │ └── libvesktop/ │ ├── .gitignore │ ├── Dockerfile │ ├── binding.gyp │ ├── build.sh │ ├── index.d.ts │ ├── package.json │ ├── prebuilds/ │ │ ├── vesktop-arm64.node │ │ └── vesktop-x64.node │ ├── src/ │ │ └── libvesktop.cc │ └── test.js ├── patches/ │ ├── arrpc@3.5.0.patch │ └── electron-updater.patch ├── scripts/ │ ├── build/ │ │ ├── addAssetsCar.mjs │ │ ├── afterPack.mjs │ │ ├── beforePack.mjs │ │ ├── build.mts │ │ ├── includeDirPlugin.mts │ │ ├── injectReact.mjs │ │ ├── sandboxFix.mjs │ │ └── vencordDep.mts │ ├── header.txt │ ├── start.ts │ ├── startWatch.mts │ └── utils/ │ ├── dotenv.ts │ ├── generateMeta.mts │ └── spawn.mts ├── src/ │ ├── globals.d.ts │ ├── main/ │ │ ├── about.ts │ │ ├── appBadge.ts │ │ ├── arrpc/ │ │ │ ├── index.ts │ │ │ ├── types.ts │ │ │ └── worker.ts │ │ ├── autoStart.ts │ │ ├── cli.ts │ │ ├── constants.ts │ │ ├── dbus.ts │ │ ├── events.ts │ │ ├── firstLaunch.ts │ │ ├── index.ts │ │ ├── ipc.ts │ │ ├── ipcCommands.ts │ │ ├── mainWindow.ts │ │ ├── mediaPermissions.ts │ │ ├── screenShare.ts │ │ ├── settings.ts │ │ ├── splash.ts │ │ ├── tray.ts │ │ ├── updater.ts │ │ ├── userAssets.ts │ │ ├── utils/ │ │ │ ├── clearData.ts │ │ │ ├── desktopFileEscape.ts │ │ │ ├── fileExists.ts │ │ │ ├── http.ts │ │ │ ├── ipcWrappers.ts │ │ │ ├── isPathInDirectory.ts │ │ │ ├── makeLinksOpenExternally.ts │ │ │ ├── popout.ts │ │ │ ├── setAsDefaultProtocolClient.ts │ │ │ ├── steamOS.ts │ │ │ └── vencordLoader.ts │ │ ├── vencordFilesDir.ts │ │ ├── venmic.ts │ │ ├── vesktopProtocol.ts │ │ └── vesktopStatic.ts │ ├── module.d.ts │ ├── preload/ │ │ ├── VesktopNative.ts │ │ ├── index.ts │ │ ├── splash.ts │ │ ├── typedIpc.ts │ │ └── updater.ts │ ├── renderer/ │ │ ├── appBadge.ts │ │ ├── arrpc.ts │ │ ├── components/ │ │ │ ├── ScreenSharePicker.tsx │ │ │ ├── SimpleErrorBoundary.tsx │ │ │ ├── index.ts │ │ │ ├── screenSharePicker.css │ │ │ └── settings/ │ │ │ ├── AutoStartToggle.tsx │ │ │ ├── DeveloperOptions.tsx │ │ │ ├── DiscordBranchPicker.tsx │ │ │ ├── NotificationBadgeToggle.tsx │ │ │ ├── OutdatedVesktopWarning.tsx │ │ │ ├── Settings.tsx │ │ │ ├── UserAssets.css │ │ │ ├── UserAssets.tsx │ │ │ ├── VesktopSettingsSwitch.tsx │ │ │ ├── WindowsTransparencyControls.tsx │ │ │ └── settings.css │ │ ├── fixes.ts │ │ ├── index.ts │ │ ├── ipcCommands.ts │ │ ├── logger.ts │ │ ├── patches/ │ │ │ ├── devtoolsFixes.ts │ │ │ ├── enableNotificationsByDefault.ts │ │ │ ├── fixStreamConstraints.ts │ │ │ ├── hideDownloadAppsButton.ts │ │ │ ├── hideSwitchDevice.tsx │ │ │ ├── hideVenmicInput.tsx │ │ │ ├── platformClass.tsx │ │ │ ├── screenShareFixes.ts │ │ │ ├── shared.ts │ │ │ ├── spellCheck.tsx │ │ │ ├── streamerMode.ts │ │ │ ├── taskBarFlash.ts │ │ │ ├── windowMethods.tsx │ │ │ └── windowsTitleBar.tsx │ │ ├── settings.ts │ │ ├── themedSplash.ts │ │ └── utils.ts │ └── shared/ │ ├── IpcEvents.ts │ ├── browserWinProperties.ts │ ├── paths.ts │ ├── settings.d.ts │ └── utils/ │ ├── SettingsStore.ts │ ├── debounce.ts │ ├── guards.ts │ ├── millis.ts │ ├── once.ts │ ├── sleep.ts │ └── text.ts ├── static/ │ └── views/ │ ├── about.html │ ├── common.css │ ├── first-launch.html │ ├── splash.html │ └── updater/ │ ├── index.html │ ├── script.js │ └── style.css └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: Vencord Support Server url: https://discord.gg/D9uwnFnqmd about: "Need Help? Join our support server and ask in the #vesktop-support channel!" ================================================ FILE: .github/ISSUE_TEMPLATE/dev-issue.yml ================================================ name: Vesktop Developer Issue description: Reserved for Vesktop Developers. Join our support server for support. body: - type: markdown attributes: value: | # This form is reserved for Vesktop Developers. Do not open an issue. Instead, use the [#vesktop-support channel](https://discord.com/channels/1015060230222131221/1345457031426871417) on our [Discord server](https://vencord.dev/discord) for help and reporting issues. Your issue will be closed immediately with no comment and you will be blocked if you ignore this. This is because 99% of issues are not actually bugs, but rather user or system issues and it adds a lot of noise to our development process. - type: textarea id: content attributes: label: Content validations: required: true ================================================ FILE: .github/workflows/meta.yml ================================================ name: Update metainfo on release on: release: types: - published workflow_dispatch: permissions: contents: write jobs: update: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 # Install pnpm using packageManager key in package.json - name: Use Node.js 20 uses: actions/setup-node@v4 with: node-version: 20 - name: Install dependencies run: pnpm i - name: Update metainfo run: pnpm generateMeta - name: Commit and merge in changes run: | git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" gh release upload "${{ github.event.release.tag_name }}" dist/dev.vencord.Vesktop.metainfo.xml env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .github/workflows/release.yml ================================================ name: Release on: push: tags: - v* workflow_dispatch: jobs: release: runs-on: ${{ matrix.os }} strategy: matrix: os: [macos-latest, ubuntu-latest, windows-latest] include: - os: macos-latest platform: mac - os: ubuntu-latest platform: linux - os: windows-latest platform: windows steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 # Install pnpm using packageManager key in package.json - name: Use Node.js 20 uses: actions/setup-node@v4 with: node-version: 20 cache: "pnpm" - name: Install dependencies run: pnpm install --frozen-lockfile - name: Build run: pnpm build - name: Run Electron Builder if: ${{ matrix.platform != 'mac' }} run: | pnpm electron-builder --${{ matrix.platform }} --publish always env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Run Electron Builder if: ${{ matrix.platform == 'mac' }} run: | echo "$API_KEY" > apple.p8 pnpm electron-builder --${{ matrix.platform }} --publish always env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} CSC_LINK: ${{ secrets.APPLE_SIGNING_CERT }} CSC_KEY_PASSWORD: ${{ secrets.APPLE_SIGNING_CERT_PASSWORD }} API_KEY: ${{ secrets.APPLE_API_KEY }} APPLE_API_KEY: apple.p8 APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} ================================================ FILE: .github/workflows/test.yml ================================================ name: test on: push: branches: - main pull_request: branches: - main jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 # Install pnpm using packageManager key in package.json - name: Use Node.js 20 uses: actions/setup-node@v4 with: node-version: 20 cache: "pnpm" - name: Install dependencies run: pnpm install --frozen-lockfile - name: Run tests run: pnpm test - name: Test if it compiles run: | pnpm build pnpm build --dev ================================================ FILE: .github/workflows/update-vencord-dev.yml ================================================ name: Update vencord.dev Vesktop version on: release: types: - published jobs: update: runs-on: ubuntu-latest steps: - name: Update scripts/_latestVesktopVersion.txt file in vencord.dev repo run: | git config --global user.name "$USERNAME" git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" git clone https://$USERNAME:$API_TOKEN@github.com/$GH_REPO.git repo cd repo version="${{ github.event.release.tag_name }}" echo "${version#v}" > scripts/_latestVesktopVersion.txt git add scripts/_latestVesktopVersion.txt git commit -m "Update Vesktop version to ${{ github.event.release.tag_name }}" git push https://$USERNAME:$API_TOKEN@github.com/$GH_REPO.git env: API_TOKEN: ${{ secrets.VENCORD_DEV_GITHUB_TOKEN }} GH_REPO: Vencord/vencord.dev USERNAME: GitHub-Actions ================================================ FILE: .github/workflows/winget-submission.yml ================================================ name: Submit to Winget Community Repo on: release: types: [published] workflow_dispatch: inputs: tag: type: string description: The release tag to submit required: true jobs: winget: name: Publish winget package runs-on: windows-latest steps: - name: Submit package to Winget Community Repo uses: vedantmgoyal2009/winget-releaser@0db4f0a478166abd0fa438c631849f0b8dcfb99f with: identifier: Vencord.Vesktop token: ${{ secrets.WINGET_PAT }} installers-regex: '\.exe$' release-tag: ${{ inputs.tag || github.event.release.tag_name }} fork-user: shiggybot ================================================ FILE: .gitignore ================================================ dist node_modules .env .DS_Store .idea/ .pnpm-store/ ================================================ FILE: .npmrc ================================================ node-linker=hoisted package-manager-strict=false ================================================ FILE: .prettierrc.yaml ================================================ tabWidth: 4 semi: true printWidth: 120 trailingComma: none bracketSpacing: true arrowParens: avoid useTabs: false endOfLine: lf ================================================ FILE: .vscode/settings.json ================================================ { "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }, "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[javascriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[jsonc]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "cSpell.words": ["Vesktop"] } ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Vesktop Vesktop is a custom Discord desktop app **Main features**: - Vencord preinstalled - 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 **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) ![](https://github.com/Vencord/Vesktop/assets/45497981/8701e5de-52c4-4346-a990-719cb971642e) ## Installing Visit https://vesktop.dev/install ## Building from Source You need to have the following dependencies installed: - [Git](https://git-scm.com/downloads) - [Node.js](https://nodejs.org/en/download) - pnpm: `npm install --global pnpm` Packaging will create builds in the dist/ folder ```sh git clone https://github.com/Vencord/Vesktop cd Vesktop # Install Dependencies pnpm i # Either run it without packaging pnpm start # Or package (will build packages for your OS) pnpm package # Or only build the Linux Pacman package pnpm package --linux pacman # Or package to a directory only pnpm package:dir ``` ## Building LibVesktop from Source This is a small C++ helper library Vesktop uses on Linux to emit D-Bus events. By default, prebuilt binaries for x64 and arm64 are used. If you want to build it from source: 1. Install build dependencies: - Debian/Ubuntu: `apt install build-essential python3 curl pkg-config libglib2.0-dev` - Fedora: `dnf install @c-development @development-tools python3 curl pkgconf-pkg-config glib2-devel` 2. Run `pnpm buildLibVesktop` 3. From now on, building Vesktop will use your own build ================================================ FILE: build/entitlements.mac.plist ================================================ com.apple.security.cs.allow-unsigned-executable-memory com.apple.security.cs.allow-jit com.apple.security.network.client com.apple.security.device.audio-input com.apple.security.device.camera com.apple.security.device.bluetooth com.apple.security.cs.allow-dyld-environment-variables com.apple.security.cs.disable-library-validation ================================================ FILE: build/installer.nsh ================================================ !macro preInit SetRegView 64 WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "$LocalAppData\vesktop" WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "$LocalAppData\vesktop" SetRegView 32 WriteRegExpandStr HKLM "${INSTALL_REGISTRY_KEY}" InstallLocation "$LocalAppData\vesktop" WriteRegExpandStr HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation "$LocalAppData\vesktop" !macroend ================================================ FILE: eslint.config.mjs ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ //@ts-check import { defineConfig } from "eslint/config"; import stylistic from "@stylistic/eslint-plugin"; import pathAlias from "eslint-plugin-path-alias"; import react from "eslint-plugin-react"; import simpleHeader from "eslint-plugin-simple-header"; import importSort from "eslint-plugin-simple-import-sort"; import unusedImports from "eslint-plugin-unused-imports"; import tseslint from "typescript-eslint"; import prettier from "eslint-plugin-prettier"; export default defineConfig( { ignores: ["dist"] }, { files: ["src/**/*.{tsx,ts,mts,mjs,js,jsx}"], settings: { react: { version: "19" } }, ...react.configs.flat.recommended, rules: { ...react.configs.flat.recommended.rules, "react/react-in-jsx-scope": "off", "react/prop-types": "off", "react/display-name": "off", "react/no-unescaped-entities": "off" } }, { files: ["src/**/*.{tsx,ts,mts,mjs,js,jsx}"], plugins: { simpleHeader, stylistic, importSort, unusedImports, // @ts-expect-error Missing types pathAlias, prettier, "@typescript-eslint": tseslint.plugin }, settings: { "import/resolver": { alias: { map: [] } } }, languageOptions: { parser: tseslint.parser, parserOptions: { project: true, tsconfigRootDir: import.meta.dirname } }, rules: { "simpleHeader/header": [ "error", { files: ["scripts/header.txt"], templates: { author: [".*", "Vendicated and Vesktop contributors"] } } ], // ESLint Rules yoda: "error", eqeqeq: ["error", "always", { null: "ignore" }], "prefer-destructuring": [ "error", { VariableDeclarator: { array: false, object: true }, AssignmentExpression: { array: false, object: false } } ], "operator-assignment": ["error", "always"], "no-useless-computed-key": "error", "no-unneeded-ternary": ["error", { defaultAssignment: false }], "no-invalid-regexp": "error", "no-constant-condition": ["error", { checkLoops: false }], "no-duplicate-imports": "error", "@typescript-eslint/dot-notation": [ "error", { allowPrivateClassPropertyAccess: true, allowProtectedClassPropertyAccess: true } ], "no-useless-escape": [ "error", { allowRegexCharacters: ["i"] } ], "no-fallthrough": "error", "for-direction": "error", "no-async-promise-executor": "error", "no-cond-assign": "error", "no-dupe-else-if": "error", "no-duplicate-case": "error", "no-irregular-whitespace": "error", "no-loss-of-precision": "error", "no-misleading-character-class": "error", "no-prototype-builtins": "error", "no-regex-spaces": "error", "no-shadow-restricted-names": "error", "no-unexpected-multiline": "error", "no-unsafe-optional-chaining": "error", "no-useless-backreference": "error", "use-isnan": "error", "prefer-const": ["error", { destructuring: "all" }], "prefer-spread": "error", // Styling Rules "stylistic/spaced-comment": ["error", "always", { markers: ["!"] }], "stylistic/no-extra-semi": "error", // Plugin Rules "importSort/imports": "error", "importSort/exports": "error", "unusedImports/no-unused-imports": "error", "pathAlias/no-relative": "error", "prettier/prettier": "error" } } ); ================================================ FILE: package.json ================================================ { "name": "vesktop", "version": "1.6.5", "private": true, "description": "Vesktop is a custom Discord desktop app", "keywords": [], "homepage": "https://vencord.dev/", "license": "GPL-3.0-or-later", "author": "Vendicated ", "main": "dist/js/main.js", "scripts": { "build": "tsx scripts/build/build.mts", "build:dev": "pnpm build --dev", "buildLibVesktop": "pnpm -C packages/libvesktop install && pnpm -C packages/libvesktop run build", "package": "pnpm build && electron-builder", "package:dir": "pnpm build && electron-builder --dir", "lint": "eslint", "lint:fix": "pnpm lint --fix", "start": "pnpm build && electron .", "start:dev": "pnpm build:dev && electron .", "start:watch": "pnpm build:dev && tsx scripts/startWatch.mts", "test": "pnpm lint && pnpm testTypes", "testTypes": "tsc --noEmit", "watch": "pnpm build --watch", "generateMeta": "tsx scripts/utils/generateMeta.mts", "updateArrpcDB": "node ./node_modules/arrpc/update_db.js", "postinstall": "pnpm updateArrpcDB" }, "dependencies": { "arrpc": "github:OpenAsar/arrpc#2234e9c9111f4c42ebcc3aa6a2215bfd979eef77", "electron-updater": "^6.6.2" }, "optionalDependencies": { "@vencord/venmic": "^6.1.0" }, "devDependencies": { "@fal-works/esbuild-plugin-global-externals": "^2.1.2", "@stylistic/eslint-plugin": "^5.8.0", "@types/node": "^25.2.3", "@types/react": "19.2.9", "@vencord/types": "^1.14.1", "dotenv": "^17.2.4", "electron": "^40.4.0", "electron-builder": "^26.7.0", "esbuild": "^0.27.3", "eslint": "^10.0.0", "eslint-import-resolver-alias": "^1.1.2", "eslint-plugin-path-alias": "^2.1.0", "eslint-plugin-prettier": "^5.5.5", "eslint-plugin-react": "^7.37.5", "eslint-plugin-simple-header": "^1.2.2", "eslint-plugin-simple-import-sort": "^12.1.1", "eslint-plugin-unused-imports": "^4.4.1", "libvesktop": "link:packages/libvesktop", "prettier": "^3.8.1", "source-map-support": "^0.5.21", "tsx": "^4.21.0", "type-fest": "^5.4.4", "typescript": "^5.9.3", "typescript-eslint": "^8.55.0", "xml-formatter": "^3.6.7" }, "packageManager": "pnpm@10.7.1", "engines": { "node": ">=18", "pnpm": ">=8" }, "build": { "appId": "dev.vencord.vesktop", "productName": "Vesktop", "executableName": "vesktop", "files": [ "!*", "!node_modules", "dist/js", "static", "package.json", "LICENSE" ], "protocols": { "name": "Discord", "schemes": [ "discord" ] }, "beforePack": "scripts/build/beforePack.mjs", "afterPack": "scripts/build/afterPack.mjs", "linux": { "icon": "build/icon.svg", "category": "Network", "maintainer": "vendicated+vesktop@riseup.net", "target": [ { "target": "deb", "arch": [ "x64", "arm64" ] }, { "target": "tar.gz", "arch": [ "x64", "arm64" ] }, { "target": "rpm", "arch": [ "x64", "arm64" ] }, { "target": "AppImage", "arch": [ "x64", "arm64" ] } ], "desktop": { "entry": { "Name": "Vesktop", "GenericName": "Internet Messenger", "Type": "Application", "Categories": "Network;InstantMessaging;Chat;", "Keywords": "discord;vencord;electron;chat;", "MimeType": "x-scheme-handler/discord", "StartupWMClass": "vesktop" } } }, "mac": { "target": [ { "target": "default", "arch": [ "universal" ] } ], "category": "public.app-category.social-networking", "darkModeSupport": true, "extendInfo": { "NSMicrophoneUsageDescription": "This app needs access to the microphone", "NSCameraUsageDescription": "This app needs access to the camera", "com.apple.security.device.audio-input": true, "com.apple.security.device.camera": true, "CFBundleIconName": "Icon" }, "notarize": true }, "dmg": { "background": "build/background.tiff", "icon": "build/icon.icns", "iconSize": 105, "window": { "width": 512, "height": 340 }, "contents": [ { "x": 140, "y": 160 }, { "x": 372, "y": 160, "type": "link", "path": "/Applications" } ] }, "nsis": { "include": "build/installer.nsh", "oneClick": false }, "win": { "icon": "build/icon.ico", "target": [ { "target": "nsis", "arch": [ "x64", "arm64" ] }, { "target": "zip", "arch": [ "x64", "arm64" ] } ] }, "publish": { "provider": "github" }, "rpm": { "fpm": [ "--rpm-rpmbuild-define=_build_id_links none" ] }, "electronFuses": { "runAsNode": false, "enableCookieEncryption": false, "enableNodeOptionsEnvironmentVariable": false, "enableNodeCliInspectArguments": false, "enableEmbeddedAsarIntegrityValidation": false, "onlyLoadAppFromAsar": true, "loadBrowserProcessSpecificV8Snapshot": false, "grantFileProtocolExtraPrivileges": false } }, "pnpm": { "patchedDependencies": { "arrpc@3.5.0": "patches/arrpc@3.5.0.patch", "electron-updater": "patches/electron-updater.patch" }, "onlyBuiltDependencies": [ "@vencord/venmic", "electron", "esbuild" ] } } ================================================ FILE: packages/libvesktop/.gitignore ================================================ build ================================================ FILE: packages/libvesktop/Dockerfile ================================================ # Dockerfile for building both x64 and arm64 on an old distro for maximum compatibility. # ubuntu20 is dead but debian11 is still supported for now FROM debian:11 ENV DEBIAN_FRONTEND=noninteractive RUN dpkg --add-architecture arm64 RUN apt-get update && apt-get install -y \ build-essential python3 curl pkg-config \ g++-aarch64-linux-gnu libglib2.0-dev:amd64 libglib2.0-dev:arm64 \ ca-certificates \ && rm -rf /var/lib/apt/lists/* RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \ && apt-get update && apt-get install -y nodejs \ && rm -rf /var/lib/apt/lists/* WORKDIR /src ================================================ FILE: packages/libvesktop/binding.gyp ================================================ { "targets": [ { "target_name": "libvesktop", "sources": [ "src/libvesktop.cc" ], "include_dirs": [ " #include #include #include #include #include #include #include template struct GObjectDeleter { void operator()(T *obj) const { if (obj) g_object_unref(obj); } }; template using GObjectPtr = std::unique_ptr>; struct GVariantDeleter { void operator()(GVariant *variant) const { if (variant) g_variant_unref(variant); } }; using GVariantPtr = std::unique_ptr; struct GErrorDeleter { void operator()(GError *error) const { if (error) g_error_free(error); } }; using GErrorPtr = std::unique_ptr; bool update_launcher_count(int count) { GError *error = nullptr; const char *chromeDesktop = std::getenv("CHROME_DESKTOP"); std::string desktop_id = std::string("application://") + (chromeDesktop ? chromeDesktop : "vesktop.desktop"); GObjectPtr bus(g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &error)); if (!bus) { GErrorPtr error_ptr(error); std::cerr << "[libvesktop::update_launcher_count] Failed to connect to session bus: " << (error_ptr ? error_ptr->message : "unknown error") << std::endl; return false; } GVariantBuilder builder; g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}")); g_variant_builder_add(&builder, "{sv}", "count", g_variant_new_int64(count)); g_variant_builder_add(&builder, "{sv}", "count-visible", g_variant_new_boolean(count != 0)); gboolean result = g_dbus_connection_emit_signal( bus.get(), nullptr, "/", "com.canonical.Unity.LauncherEntry", "Update", g_variant_new("(sa{sv})", desktop_id.c_str(), &builder), &error); if (!result || error) { GErrorPtr error_ptr(error); std::cerr << "[libvesktop::update_launcher_count] Failed to emit Update signal: " << (error_ptr ? error_ptr->message : "unknown error") << std::endl; return false; } return true; } std::optional get_accent_color() { GError *error = nullptr; GObjectPtr bus(g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &error)); if (!bus) { GErrorPtr error_ptr(error); std::cerr << "[libvesktop::get_accent_color] Failed to connect to session bus: " << (error_ptr ? error_ptr->message : "unknown error") << std::endl; return std::nullopt; } GVariantPtr reply(g_dbus_connection_call_sync( bus.get(), "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Settings", "Read", g_variant_new("(ss)", "org.freedesktop.appearance", "accent-color"), nullptr, G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, &error)); if (!reply) { GErrorPtr error_ptr(error); std::cerr << "[libvesktop::get_accent_color] Failed to call Read: " << (error_ptr ? error_ptr->message : "unknown error") << std::endl; return std::nullopt; } GVariant *inner_raw = nullptr; g_variant_get(reply.get(), "(v)", &inner_raw); if (!inner_raw) { std::cerr << "[libvesktop::get_accent_color] Inner variant is null" << std::endl; return std::nullopt; } GVariantPtr inner(inner_raw); // Unwrap nested variants while (g_variant_is_of_type(inner.get(), G_VARIANT_TYPE_VARIANT)) { GVariant *next = g_variant_get_variant(inner.get()); inner.reset(next); } if (!g_variant_is_of_type(inner.get(), G_VARIANT_TYPE_TUPLE) || g_variant_n_children(inner.get()) < 3) { std::cerr << "[libvesktop::get_accent_color] Inner variant is not a tuple of 3 doubles" << std::endl; return std::nullopt; } double r = 0.0, g = 0.0, b = 0.0; g_variant_get(inner.get(), "(ddd)", &r, &g, &b); bool discard = false; auto toInt = [&discard](double v) -> int { if (!std::isfinite(v) || v < 0.0 || v > 1.0) { discard = true; return 0; } return static_cast(std::round(v * 255.0)); }; int32_t rgb = (toInt(r) << 16) | (toInt(g) << 8) | toInt(b); if (discard) return std::nullopt; return rgb; } bool request_background(bool autostart, const std::vector &commandline) { GError *error = nullptr; GObjectPtr bus(g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &error)); if (!bus) { GErrorPtr error_ptr(error); std::cerr << "[libvesktop::request_background] Failed to connect to session bus: " << (error_ptr ? error_ptr->message : "unknown error") << std::endl; return false; } GVariantBuilder builder; g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}")); g_variant_builder_add(&builder, "{sv}", "autostart", g_variant_new_boolean(autostart)); if (!commandline.empty()) { GVariantBuilder cmd_builder; g_variant_builder_init(&cmd_builder, G_VARIANT_TYPE("as")); for (const auto &s : commandline) g_variant_builder_add(&cmd_builder, "s", s.c_str()); g_variant_builder_add(&builder, "{sv}", "commandline", g_variant_builder_end(&cmd_builder)); } GVariantPtr reply(g_dbus_connection_call_sync( bus.get(), "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Background", "RequestBackground", g_variant_new("(sa{sv})", "", &builder), nullptr, G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, &error)); if (!reply) { GErrorPtr error_ptr(error); std::cerr << "[libvesktop::request_background] Failed to call RequestBackground: " << (error_ptr ? error_ptr->message : "unknown error") << std::endl; return false; } return true; } Napi::Value updateUnityLauncherCount(Napi::CallbackInfo const &info) { if (info.Length() < 1 || !info[0].IsNumber()) { Napi::TypeError::New(info.Env(), "Expected (number)").ThrowAsJavaScriptException(); return info.Env().Undefined(); } int count = info[0].As().Int32Value(); bool success = update_launcher_count(count); return Napi::Boolean::New(info.Env(), success); } Napi::Value getAccentColor(const Napi::CallbackInfo &info) { auto color = get_accent_color(); if (color) return Napi::Number::New(info.Env(), *color); return info.Env().Null(); } Napi::Value RequestBackground(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); if (info.Length() < 2 || !info[0].IsBoolean() || !info[1].IsArray()) { Napi::TypeError::New(env, "Expected (boolean, string[])").ThrowAsJavaScriptException(); return env.Null(); } bool autostart = info[0].As(); Napi::Array arr = info[1].As(); std::vector commandline; for (uint32_t i = 0; i < arr.Length(); i++) { Napi::Value v = arr.Get(i); if (v.IsString()) commandline.push_back(v.As().Utf8Value()); } bool ok = request_background(autostart, commandline); return Napi::Boolean::New(env, ok); } Napi::Object Init(Napi::Env env, Napi::Object exports) { exports.Set("updateUnityLauncherCount", Napi::Function::New(env, updateUnityLauncherCount)); exports.Set("getAccentColor", Napi::Function::New(env, getAccentColor)); exports.Set("requestBackground", Napi::Function::New(env, RequestBackground)); return exports; } NODE_API_MODULE(libvesktop, Init) ================================================ FILE: packages/libvesktop/test.js ================================================ /** * @type {typeof import(".")} */ const libVesktop = require("."); const test = require("node:test"); const assert = require("node:assert/strict"); test("getAccentColor should return a number", () => { const color = libVesktop.getAccentColor(); assert.strictEqual(typeof color, "number"); }); test("updateUnityLauncherCount should return true (success)", () => { assert.strictEqual(libVesktop.updateUnityLauncherCount(5), true); assert.strictEqual(libVesktop.updateUnityLauncherCount(0), true); assert.strictEqual(libVesktop.updateUnityLauncherCount(10), true); }); test("requestBackground should return true (success)", () => { assert.strictEqual(libVesktop.requestBackground(true, ["bash"]), true); assert.strictEqual(libVesktop.requestBackground(false, []), true); }); ================================================ FILE: patches/arrpc@3.5.0.patch ================================================ diff --git a/src/process/index.js b/src/process/index.js index 389b0845256a34b4536d6da99edb00d17f13a6b4..f17a0ac687e9110ebfd33cb91fd2f6250d318643 100644 --- a/src/process/index.js +++ b/src/process/index.js @@ -5,8 +5,20 @@ import fs from 'node:fs'; import { dirname, join } from 'path'; import { fileURLToPath } from 'url'; -const __dirname = dirname(fileURLToPath(import.meta.url)); -const DetectableDB = JSON.parse(fs.readFileSync(join(__dirname, 'detectable.json'), 'utf8')); +const DetectableDB = require('./detectable.json'); +DetectableDB.push( + { + aliases: ["Obs"], + executables: [ + { is_launcher: false, name: "obs", os: "linux" }, + { is_launcher: false, name: "obs.exe", os: "win32" }, + { is_launcher: false, name: "obs.app", os: "darwin" } + ], + hook: true, + id: "STREAMERMODE", + name: "OBS" + } +); import * as Natives from './native/index.js'; const Native = Natives[process.platform]; ================================================ FILE: patches/electron-updater.patch ================================================ diff --git a/out/RpmUpdater.js b/out/RpmUpdater.js index 563187bb18cb0bd154dff6620cb62b8c8f534cd6..d91594026c2bac9cc78ef3b1183df3241d7d9624 100644 --- a/out/RpmUpdater.js +++ b/out/RpmUpdater.js @@ -32,7 +32,10 @@ class RpmUpdater extends BaseUpdater_1.BaseUpdater { const sudo = this.wrapSudo(); // pkexec doesn't want the command to be wrapped in " quotes const wrapper = /pkexec/i.test(sudo) ? "" : `"`; - const packageManager = this.spawnSyncLog("which zypper"); + let packageManager; + try { + packageManager = this.spawnSyncLog("which zypper"); + } catch {} const installerPath = this.installerPath; if (installerPath == null) { this.dispatchError(new Error("No valid update available, can't quit and install")); ================================================ FILE: scripts/build/addAssetsCar.mjs ================================================ import { copyFile, readdir } from "fs/promises"; /** * @param {{ * readonly appOutDir: string; * readonly arch: Arch; * readonly electronPlatformName: string; * readonly outDir: string; * readonly packager: PlatformPackager; * readonly targets: Target[]; * }} context */ export async function addAssetsCar({ appOutDir }) { if (process.platform !== "darwin") return; const appName = (await readdir(appOutDir)).find(item => item.endsWith(".app")); if (!appName) { console.warn(`Could not find .app directory in ${appOutDir}. Skipping adding assets.car`); return; } await copyFile("build/Assets.car", `${appOutDir}/${appName}/Contents/Resources/Assets.car`); } ================================================ FILE: scripts/build/afterPack.mjs ================================================ import { addAssetsCar } from "./addAssetsCar.mjs"; export default async function afterPack(context) { await addAssetsCar(context); } ================================================ FILE: scripts/build/beforePack.mjs ================================================ import { applyAppImageSandboxFix } from "./sandboxFix.mjs"; export default async function beforePack() { await applyAppImageSandboxFix(); } ================================================ FILE: scripts/build/build.mts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { BuildContext, BuildOptions, context } from "esbuild"; import { copyFile } from "fs/promises"; import vencordDep from "./vencordDep.mjs"; import { includeDirPlugin } from "./includeDirPlugin.mts"; const isDev = process.argv.includes("--dev"); const CommonOpts: BuildOptions = { minify: !isDev, bundle: true, sourcemap: "linked", logLevel: "info" }; const NodeCommonOpts: BuildOptions = { ...CommonOpts, format: "cjs", platform: "node", external: ["electron"], target: ["esnext"], loader: { ".node": "file" }, define: { IS_DEV: JSON.stringify(isDev) } }; const contexts = [] as BuildContext[]; async function createContext(options: BuildOptions) { contexts.push(await context(options)); } async function copyVenmic() { if (process.platform !== "linux") return; return Promise.all([ copyFile( "./node_modules/@vencord/venmic/prebuilds/venmic-addon-linux-x64/node-napi-v7.node", "./static/dist/venmic-x64.node" ), copyFile( "./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 copyLibVesktop() { if (process.platform !== "linux") return; try { await copyFile( "./packages/libvesktop/build/Release/vesktop.node", `./static/dist/libvesktop-${process.arch}.node` ); console.log("Using local libvesktop build"); } catch { console.log( "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") ]).catch(() => console.warn("Failed to copy libvesktop. Building without libvesktop support")); } } await Promise.all([ copyVenmic(), copyLibVesktop(), createContext({ ...NodeCommonOpts, entryPoints: ["src/main/index.ts"], outfile: "dist/js/main.js", footer: { js: "//# sourceURL=VesktopMain" } }), createContext({ ...NodeCommonOpts, entryPoints: ["src/main/arrpc/worker.ts"], outfile: "dist/js/arRpcWorker.js", footer: { js: "//# sourceURL=VesktopArRpcWorker" } }), createContext({ ...NodeCommonOpts, entryPoints: ["src/preload/index.ts"], outfile: "dist/js/preload.js", footer: { js: "//# sourceURL=VesktopPreload" } }), createContext({ ...NodeCommonOpts, entryPoints: ["src/preload/splash.ts"], outfile: "dist/js/splashPreload.js", footer: { js: "//# sourceURL=VesktopSplashPreload" } }), createContext({ ...NodeCommonOpts, entryPoints: ["src/preload/updater.ts"], outfile: "dist/js/updaterPreload.js", footer: { js: "//# sourceURL=VesktopUpdaterPreload" } }), createContext({ ...CommonOpts, globalName: "Vesktop", entryPoints: ["src/renderer/index.ts"], outfile: "dist/js/renderer.js", format: "iife", inject: ["./scripts/build/injectReact.mjs"], jsxFactory: "VencordCreateElement", jsxFragment: "VencordFragment", external: ["@vencord/types/*"], plugins: [vencordDep, includeDirPlugin("patches", "src/renderer/patches")], footer: { js: "//# sourceURL=VesktopRenderer" } }) ]); const watch = process.argv.includes("--watch"); if (watch) { await Promise.all(contexts.map(ctx => ctx.watch())); } else { await Promise.all( contexts.map(async ctx => { await ctx.rebuild(); await ctx.dispose(); }) ); } ================================================ FILE: scripts/build/includeDirPlugin.mts ================================================ import { Plugin } from "esbuild"; import { readdir } from "fs/promises"; const makeImportAllCode = (files: string[]) => files.map(f => `require("./${f.replace(/\.[cm]?[tj]sx?$/, "")}")`).join("\n"); const makeImportDirRecursiveCode = (dir: string) => readdir(dir).then(files => makeImportAllCode(files)); export function includeDirPlugin(namespace: string, path: string): Plugin { return { name: `include-dir-plugin:${namespace}`, setup(build) { const filter = new RegExp(`^__${namespace}__$`); build.onResolve({ filter }, args => ({ path: args.path, namespace })); build.onLoad({ filter, namespace }, async args => { return { contents: await makeImportDirRecursiveCode(path), resolveDir: path }; }); } }; } ================================================ FILE: scripts/build/injectReact.mjs ================================================ export const VencordFragment = /* #__PURE__*/ Symbol.for("react.fragment"); export let VencordCreateElement = (...args) => (VencordCreateElement = Vencord.Webpack.Common.React.createElement)(...args); ================================================ FILE: scripts/build/sandboxFix.mjs ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ // Based on https://github.com/gergof/electron-builder-sandbox-fix/blob/master/lib/index.js import fs from "fs/promises"; import path from "path"; import AppImageTarget from "app-builder-lib/out/targets/AppImageTarget.js"; let isApplied = false; export async function applyAppImageSandboxFix() { if (process.platform !== "linux") { // this fix is only required on linux return; } if (isApplied) return; isApplied = true; const oldBuildMethod = AppImageTarget.default.prototype.build; AppImageTarget.default.prototype.build = async function (...args) { console.log("Running AppImage builder hook", args); const oldPath = args[0]; const newPath = oldPath + "-appimage-sandbox-fix"; // just in case try { await fs.rm(newPath, { recursive: true }); } catch {} console.log("Copying to apply appimage fix", oldPath, newPath); await fs.cp(oldPath, newPath, { recursive: true }); args[0] = newPath; const executable = path.join(newPath, this.packager.executableName); const loaderScript = ` #!/usr/bin/env bash SCRIPT_DIR="$( cd "$( dirname "\${BASH_SOURCE[0]}" )" && pwd )" IS_STEAMOS=0 if [[ "$SteamOS" == "1" && "$SteamGamepadUI" == "1" ]]; then echo "Running Vesktop on SteamOS, disabling sandbox" IS_STEAMOS=1 fi exec "$SCRIPT_DIR/${this.packager.executableName}.bin" "$([ "$IS_STEAMOS" == 1 ] && echo '--no-sandbox')" "$@" `.trim(); try { await fs.rename(executable, executable + ".bin"); await fs.writeFile(executable, loaderScript); await fs.chmod(executable, 0o755); } catch (e) { console.error("failed to create loder for sandbox fix: " + e.message); throw new Error("Failed to create loader for sandbox fix"); } const ret = await oldBuildMethod.apply(this, args); await fs.rm(newPath, { recursive: true }); return ret; }; } ================================================ FILE: scripts/build/vencordDep.mts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { globalExternalsWithRegExp } from "@fal-works/esbuild-plugin-global-externals"; const names = { webpack: "Vencord.Webpack", "webpack/common": "Vencord.Webpack.Common", utils: "Vencord.Util", api: "Vencord.Api", "api/settings": "Vencord", components: "Vencord.Components" }; export default globalExternalsWithRegExp({ getModuleInfo(modulePath) { const path = modulePath.replace("@vencord/types/", ""); let varName = names[path]; if (!varName) { const altMapping = names[path.split("/")[0]]; if (!altMapping) throw new Error("Unknown module path: " + modulePath); varName = altMapping + "." + // @ts-ignore path.split("/")[1].replaceAll("/", "."); } return { varName, type: "cjs" }; }, modulePathFilter: /^@vencord\/types.+$/ }); ================================================ FILE: scripts/header.txt ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) {year} {author} * SPDX-License-Identifier: GPL-3.0-or-later */ ================================================ FILE: scripts/start.ts ================================================ /* * SPDX-License-Identifier: GPL-3.0 * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors */ import "./utils/dotenv"; import { spawnNodeModuleBin } from "./utils/spawn.mjs"; spawnNodeModuleBin("electron", [process.cwd(), ...(process.env.ELECTRON_LAUNCH_FLAGS?.split(" ") ?? [])]); ================================================ FILE: scripts/startWatch.mts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import "./start"; import { spawnNodeModuleBin } from "./utils/spawn.mjs"; spawnNodeModuleBin("tsx", ["scripts/build/build.mts", "--", "--watch", "--dev"]); ================================================ FILE: scripts/utils/dotenv.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { config } from "dotenv"; config(); ================================================ FILE: scripts/utils/generateMeta.mts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { promises as fs } from "node:fs"; import { mkdir } from "node:fs/promises"; import { DOMParser, XMLSerializer } from "@xmldom/xmldom"; import xmlFormat from "xml-formatter"; function generateDescription(description: string, descriptionNode: Element) { const lines = description.replace(/\r/g, "").split("\n"); let currentList: Element | null = null; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (line.includes("New Contributors")) { // we're done, don't parse any more since the new contributors section is the last one break; } if (line.startsWith("## ")) { const pNode = descriptionNode.ownerDocument.createElement("p"); pNode.textContent = line.slice(3); descriptionNode.appendChild(pNode); } else if (line.startsWith("* ")) { const liNode = descriptionNode.ownerDocument.createElement("li"); liNode.textContent = line.slice(2).split("in https://github.com")[0].trim(); // don't include links to github if (!currentList) { currentList = descriptionNode.ownerDocument.createElement("ul"); } currentList.appendChild(liNode); } if (currentList && !lines[i + 1].startsWith("* ")) { descriptionNode.appendChild(currentList); currentList = null; } } } const releases = await fetch("https://api.github.com/repos/Vencord/Vesktop/releases", { headers: { Accept: "application/vnd.github+json", "X-Github-Api-Version": "2022-11-28" } }).then(res => res.json()); const latestReleaseInformation = releases[0]; const metaInfo = await (async () => { for (const release of releases) { const metaAsset = release.assets.find((a: any) => a.name === "dev.vencord.Vesktop.metainfo.xml"); if (metaAsset) return fetch(metaAsset.browser_download_url).then(res => res.text()); } })(); if (!metaInfo) { throw new Error("Could not find existing meta information from any release"); } const parser = new DOMParser().parseFromString(metaInfo, "text/xml"); const releaseList = parser.getElementsByTagName("releases")[0]; for (let i = 0; i < releaseList.childNodes.length; i++) { const release = releaseList.childNodes[i] as Element; if (release.nodeType === 1 && release.getAttribute("version") === latestReleaseInformation.name) { console.log("Latest release already added, nothing to be done"); process.exit(0); } } const release = parser.createElement("release"); release.setAttribute("version", latestReleaseInformation.name); release.setAttribute("date", latestReleaseInformation.published_at.split("T")[0]); release.setAttribute("type", "stable"); const releaseUrl = parser.createElement("url"); releaseUrl.textContent = latestReleaseInformation.html_url; release.appendChild(releaseUrl); const description = parser.createElement("description"); // we're not using a full markdown parser here since we don't have a lot of formatting options to begin with generateDescription(latestReleaseInformation.body, description); release.appendChild(description); releaseList.insertBefore(release, releaseList.childNodes[0]); const output = xmlFormat(new XMLSerializer().serializeToString(parser), { lineSeparator: "\n", collapseContent: true, indentation: " " }); await mkdir("./dist", { recursive: true }); await fs.writeFile("./dist/dev.vencord.Vesktop.metainfo.xml", output, "utf-8"); console.log("Updated meta information written to ./dist/dev.vencord.Vesktop.metainfo.xml"); ================================================ FILE: scripts/utils/spawn.mts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { spawn as spaaawn, SpawnOptions } from "child_process"; import { join } from "path"; const EXT = process.platform === "win32" ? ".cmd" : ""; const OPTS: SpawnOptions = { stdio: "inherit" }; export function spawnNodeModuleBin(bin: string, args: string[]) { spaaawn(join("node_modules", ".bin", bin + EXT), args, OPTS); } ================================================ FILE: src/globals.d.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ declare global { export var VesktopNative: typeof import("preload/VesktopNative").VesktopNative; export var Vesktop: typeof import("renderer/index"); export var VesktopPatchGlobals: any; export var IS_DEV: boolean; } export {}; ================================================ FILE: src/main/about.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app, BrowserWindow } from "electron"; import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally"; import { loadView } from "./vesktopStatic"; export async function createAboutWindow() { const height = 750; const width = height * (4 / 3); const about = new BrowserWindow({ center: true, autoHideMenuBar: true, height, width }); makeLinksOpenExternally(about); const data = new URLSearchParams({ APP_VERSION: app.getVersion() }); loadView(about, "about.html", data); return about; } ================================================ FILE: src/main/appBadge.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app, NativeImage, nativeImage } from "electron"; import { join } from "path"; import { BADGE_DIR } from "shared/paths"; import { updateUnityLauncherCount } from "./dbus"; import { AppEvents } from "./events"; import { mainWin } from "./mainWindow"; const imgCache = new Map(); function loadBadge(index: number) { const cached = imgCache.get(index); if (cached) return cached; const img = nativeImage.createFromPath(join(BADGE_DIR, `${index}.ico`)); imgCache.set(index, img); return img; } let lastIndex: null | number = -1; /** * -1 = show unread indicator * 0 = clear */ export function setBadgeCount(count: number) { AppEvents.emit("setTrayVariant", count !== 0 ? "trayUnread" : "tray"); switch (process.platform) { case "linux": if (count === -1) count = 0; updateUnityLauncherCount(count); break; case "darwin": if (count === 0) { app.dock!.setBadge(""); break; } app.dock!.setBadge(count === -1 ? "•" : count.toString()); break; case "win32": const [index, description] = getBadgeIndexAndDescription(count); if (lastIndex === index) break; lastIndex = index; mainWin.setOverlayIcon(index === null ? null : loadBadge(index), description); break; } } function getBadgeIndexAndDescription(count: number): [number | null, string] { if (count === -1) return [11, "Unread Messages"]; if (count === 0) return [null, "No Notifications"]; const index = Math.max(1, Math.min(count, 10)); return [index, `${index} Notification`]; } ================================================ FILE: src/main/arrpc/index.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { resolve } from "path"; import { IpcCommands } from "shared/IpcEvents"; import { MessageChannel, Worker } from "worker_threads"; import { sendRendererCommand } from "../ipcCommands"; import { Settings } from "../settings"; import { ArRpcEvent, ArRpcHostEvent } from "./types"; let worker: Worker; const inviteCodeRegex = /^(\w|-)+$/; export async function initArRPC() { if (worker || !Settings.store.arRPC) return; try { const { port1: hostPort, port2: workerPort } = new MessageChannel(); worker = new Worker(resolve(__dirname, "./arRpcWorker.js"), { workerData: { workerPort }, transferList: [workerPort] }); hostPort.on("message", async ({ type, nonce, data }: ArRpcEvent) => { switch (type) { case "activity": { sendRendererCommand(IpcCommands.RPC_ACTIVITY, data); break; } case "invite": { const invite = String(data); const response: ArRpcHostEvent = { type: "ack-invite", nonce, data: false }; if (!inviteCodeRegex.test(invite)) { return hostPort.postMessage(response); } response.data = await sendRendererCommand(IpcCommands.RPC_INVITE, invite).catch(() => false); hostPort.postMessage(response); break; } case "link": { const response: ArRpcHostEvent = { type: "ack-link", nonce: nonce, data: false }; response.data = await sendRendererCommand(IpcCommands.RPC_DEEP_LINK, data).catch(() => false); hostPort.postMessage(response); break; } } }); } catch (e) { console.error("Failed to start arRPC server", e); } } Settings.addChangeListener("arRPC", initArRPC); ================================================ FILE: src/main/arrpc/types.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ export type ArRpcEvent = ArRpcActivityEvent | ArRpcInviteEvent | ArRpcLinkEvent; export type ArRpcHostEvent = ArRpcHostAckInviteEvent | ArRpcHostAckLinkEvent; export interface ArRpcActivityEvent { type: "activity"; nonce: string; data: string; } export interface ArRpcInviteEvent { type: "invite"; nonce: string; data: string; } export interface ArRpcLinkEvent { type: "link"; nonce: string; data: any; } export interface ArRpcHostAckInviteEvent { type: "ack-invite"; nonce: string; data: boolean; } export interface ArRpcHostAckLinkEvent { type: "ack-link"; nonce: string; data: boolean; } ================================================ FILE: src/main/arrpc/worker.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import Server from "arrpc"; import { randomUUID } from "crypto"; import { MessagePort, workerData } from "worker_threads"; import { ArRpcEvent, ArRpcHostEvent } from "./types"; let server: any; type InviteCallback = (valid: boolean) => void; type LinkCallback = InviteCallback; const inviteCallbacks = new Map(); const linkCallbacks = new Map(); (async function () { const { workerPort } = workerData as { workerPort: MessagePort }; server = await new Server(); server.on("activity", (data: any) => { const event: ArRpcEvent = { type: "activity", data: JSON.stringify(data), nonce: randomUUID() }; workerPort.postMessage(event); }); server.on("invite", (invite: string, callback: InviteCallback) => { const nonce = randomUUID(); inviteCallbacks.set(nonce, callback); const event: ArRpcEvent = { type: "invite", data: invite, nonce }; workerPort.postMessage(event); }); server.on("link", async (data: any, callback: LinkCallback) => { const nonce = randomUUID(); linkCallbacks.set(nonce, callback); const event: ArRpcEvent = { type: "link", data, nonce }; workerPort.postMessage(event); }); workerPort.on("message", (e: ArRpcHostEvent) => { switch (e.type) { case "ack-invite": { inviteCallbacks.get(e.nonce)?.(e.data); inviteCallbacks.delete(e.nonce); break; } case "ack-link": { linkCallbacks.get(e.nonce)?.(e.data); linkCallbacks.delete(e.nonce); break; } } }); })(); ================================================ FILE: src/main/autoStart.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app } from "electron"; import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs"; import { join } from "path"; import { stripIndent } from "shared/utils/text"; import { IS_FLATPAK } from "./constants"; import { requestBackground } from "./dbus"; import { Settings, State } from "./settings"; import { escapeDesktopFileArgument } from "./utils/desktopFileEscape"; interface AutoStart { isEnabled(): boolean; enable(): void; disable(): void; } function getEscapedCommandLine() { const args = process.argv.map(escapeDesktopFileArgument); if (Settings.store.autoStartMinimized) args.push("--start-minimized"); return args; } function makeAutoStartLinuxDesktop(): AutoStart { const configDir = process.env.XDG_CONFIG_HOME || join(process.env.HOME!, ".config"); const dir = join(configDir, "autostart"); const file = join(dir, "vesktop.desktop"); return { isEnabled: () => existsSync(file), enable() { const desktopFile = stripIndent` [Desktop Entry] Type=Application Name=Vesktop Comment=Vesktop autostart script Exec=${getEscapedCommandLine().join(" ")} StartupNotify=false Terminal=false Icon=vesktop `; mkdirSync(dir, { recursive: true }); writeFileSync(file, desktopFile); }, disable: () => rmSync(file, { force: true }) }; } function makeAutoStartLinuxPortal() { return { isEnabled: () => State.store.linuxAutoStartEnabled === true, enable() { const success = requestBackground(true, getEscapedCommandLine()); if (success) { State.store.linuxAutoStartEnabled = true; } return success; }, disable() { const success = requestBackground(false, []); if (success) { State.store.linuxAutoStartEnabled = false; } return success; } }; } const autoStartWindowsMac: AutoStart = { isEnabled: () => app.getLoginItemSettings().openAtLogin, enable: () => app.setLoginItemSettings({ openAtLogin: true, args: Settings.store.autoStartMinimized ? ["--start-minimized"] : [] }), disable: () => app.setLoginItemSettings({ openAtLogin: false }) }; // The portal call uses the app id by default, which is org.chromium.Chromium, even in packaged Vesktop. // This leads to an autostart entry named "Chromium" instead of "Vesktop". // Thus, only use the portal inside Flatpak, where the app is actually correct. // Maybe there is a way to fix it outside of flatpak, but I couldn't figure it out. export const autoStart = process.platform !== "linux" ? autoStartWindowsMac : IS_FLATPAK ? makeAutoStartLinuxPortal() : makeAutoStartLinuxDesktop(); Settings.addChangeListener("autoStartMinimized", () => { if (!autoStart.isEnabled()) return; autoStart.enable(); }); ================================================ FILE: src/main/cli.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app } from "electron"; import { basename } from "path"; import { stripIndent } from "shared/utils/text"; import { parseArgs, ParseArgsOptionDescriptor } from "util"; type Option = ParseArgsOptionDescriptor & { description: string; hidden?: boolean; options?: string[]; argumentName?: string; }; const options = { "start-minimized": { default: false, type: "boolean", short: "m", description: "Start the application minimized to the system tray" }, version: { type: "boolean", short: "v", description: "Print the application version and exit" }, help: { type: "boolean", short: "h", description: "Print help information and exit" }, "user-agent": { type: "string", argumentName: "ua", description: "Set a custom User-Agent. May trigger anti-spam or break voice chat" }, "user-agent-os": { type: "string", description: "Set User-Agent to a specific operating system. May trigger anti-spam or break voice chat", options: ["windows", "linux", "darwin"] } } satisfies Record; // only for help display const extraOptions = { "enable-features": { type: "string", description: "Enable specific Chromium features", argumentName: "feature1,feature2,…" }, "disable-features": { type: "string", description: "Disable specific Chromium features", argumentName: "feature1,feature2,…" }, "ozone-platform": { hidden: process.platform !== "linux", type: "string", description: "Whether to run Vesktop in Wayland or X11 (XWayland)", options: ["x11", "wayland"] } } satisfies Record; const args = basename(process.argv[0]).toLowerCase().startsWith("electron") ? process.argv.slice(2) : process.argv.slice(1); export const CommandLine = parseArgs({ args, options, strict: false as true, // we manually check later, so cast to true to get better types allowPositionals: true }); export function checkCommandLineForHelpOrVersion() { const { help, version } = CommandLine.values; if (version) { console.log(`Vesktop v${app.getVersion()}`); app.exit(0); } if (help) { const base = stripIndent` Vesktop v${app.getVersion()} Usage: ${basename(process.execPath)} [options] [url] Electron Options: See Chromium Options: See - only some of them work Vesktop Options: `; const optionLines = Object.entries(options) .sort(([a], [b]) => a.localeCompare(b)) .concat(Object.entries(extraOptions)) .filter(([, opt]) => !("hidden" in opt && opt.hidden)) .map(([name, opt]) => { const flags = [ "short" in opt && `-${opt.short}`, `--${name}`, opt.type !== "boolean" && ("options" in opt ? `<${opt.options.join(" | ")}>` : `<${opt.argumentName ?? opt.type}>`) ] .filter(Boolean) .join(" "); return [flags, opt.description]; }); const padding = optionLines.reduce((max, [flags]) => Math.max(max, flags.length), 0) + 4; const optionsHelp = optionLines .map(([flags, description]) => ` ${flags.padEnd(padding, " ")}${description}`) .join("\n"); console.log(base + "\n" + optionsHelp); app.exit(0); } for (const [name, def] of Object.entries(options)) { const value = CommandLine.values[name]; if (value == null) continue; if (typeof value !== def.type) { console.error(`Invalid options. Expected ${def.type === "boolean" ? "no" : "an"} argument for --${name}`); app.exit(1); } if ("options" in def && !def.options?.includes(value as string)) { console.error(`Invalid value for --${name}: ${value}\nExpected one of: ${def.options.join(", ")}`); app.exit(1); } } } checkCommandLineForHelpOrVersion(); ================================================ FILE: src/main/constants.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app } from "electron"; import { existsSync, mkdirSync } from "fs"; import { dirname, join } from "path"; import { CommandLine } from "./cli"; const vesktopDir = dirname(process.execPath); export const PORTABLE = process.platform === "win32" && !process.execPath.toLowerCase().endsWith("electron.exe") && !existsSync(join(vesktopDir, "Uninstall Vesktop.exe")); export const DATA_DIR = process.env.VENCORD_USER_DATA_DIR || (PORTABLE ? join(vesktopDir, "Data") : join(app.getPath("userData"))); mkdirSync(DATA_DIR, { recursive: true }); export const SESSION_DATA_DIR = join(DATA_DIR, "sessionData"); app.setPath("sessionData", SESSION_DATA_DIR); export const VENCORD_SETTINGS_DIR = join(DATA_DIR, "settings"); mkdirSync(VENCORD_SETTINGS_DIR, { recursive: true }); export const VENCORD_QUICKCSS_FILE = join(VENCORD_SETTINGS_DIR, "quickCss.css"); export const VENCORD_SETTINGS_FILE = join(VENCORD_SETTINGS_DIR, "settings.json"); export const VENCORD_THEMES_DIR = join(DATA_DIR, "themes"); export const USER_AGENT = `Vesktop/${app.getVersion()} (https://github.com/Vencord/Vesktop)`; // dimensions shamelessly stolen from Discord Desktop :3 export const MIN_WIDTH = 940; export const MIN_HEIGHT = 500; export const DEFAULT_WIDTH = 1280; export const DEFAULT_HEIGHT = 720; export const DISCORD_HOSTNAMES = ["discord.com", "canary.discord.com", "ptb.discord.com"]; const VersionString = `AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${process.versions.chrome.split(".")[0]}.0.0.0 Safari/537.36`; const BrowserUserAgents = { darwin: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ${VersionString}`, linux: `Mozilla/5.0 (X11; Linux x86_64) ${VersionString}`, windows: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) ${VersionString}` }; export const BrowserUserAgent = CommandLine.values["user-agent"] || BrowserUserAgents[CommandLine.values["user-agent-os"] || process.platform] || BrowserUserAgents.windows; export const enum MessageBoxChoice { Default, Cancel } export const IS_FLATPAK = process.env.FLATPAK_ID !== undefined; ================================================ FILE: src/main/dbus.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app } from "electron"; import { join } from "path"; import { STATIC_DIR } from "shared/paths"; let libVesktop: typeof import("libvesktop") | null = null; function loadLibVesktop() { try { if (!libVesktop) { libVesktop = require(join(STATIC_DIR, `dist/libvesktop-${process.arch}.node`)); } } catch (e) { console.error("Failed to load libvesktop:", e); } return libVesktop; } export function getAccentColor() { return loadLibVesktop()?.getAccentColor() ?? null; } export function updateUnityLauncherCount(count: number) { const libVesktop = loadLibVesktop(); if (!libVesktop) { return app.setBadgeCount(count); } return libVesktop.updateUnityLauncherCount(count); } export function requestBackground(autoStart: boolean, commandLine: string[]) { return loadLibVesktop()?.requestBackground(autoStart, commandLine) ?? false; } ================================================ FILE: src/main/events.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { EventEmitter } from "events"; import { UserAssetType } from "./userAssets"; export const AppEvents = new EventEmitter<{ appLoaded: []; userAssetChanged: [UserAssetType]; setTrayVariant: ["tray" | "trayUnread"]; }>(); ================================================ FILE: src/main/firstLaunch.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app } from "electron"; import { BrowserWindow } from "electron/main"; import { copyFileSync, mkdirSync, readdirSync } from "fs"; import { join } from "path"; import { SplashProps } from "shared/browserWinProperties"; import { autoStart } from "./autoStart"; import { DATA_DIR } from "./constants"; import { createWindows } from "./mainWindow"; import { Settings, State } from "./settings"; import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally"; import { loadView } from "./vesktopStatic"; interface Data { discordBranch: "stable" | "canary" | "ptb"; minimizeToTray?: "on"; autoStart?: "on"; importSettings?: "on"; richPresence?: "on"; } export function createFirstLaunchTour() { const win = new BrowserWindow({ ...SplashProps, transparent: false, frame: true, autoHideMenuBar: true, height: 550, width: 600 }); makeLinksOpenExternally(win); loadView(win, "first-launch.html"); win.webContents.addListener("console-message", (_e, _l, msg) => { if (msg === "cancel") return app.exit(); if (!msg.startsWith("form:")) return; const data = JSON.parse(msg.slice(5)) as Data; State.store.firstLaunch = false; Settings.store.discordBranch = data.discordBranch; Settings.store.minimizeToTray = !!data.minimizeToTray; Settings.store.arRPC = !!data.richPresence; if (data.autoStart) autoStart.enable(); if (data.importSettings) { const from = join(app.getPath("userData"), "..", "Vencord", "settings"); const to = join(DATA_DIR, "settings"); try { const files = readdirSync(from); mkdirSync(to, { recursive: true }); for (const file of files) { copyFileSync(join(from, file), join(to, file)); } } catch (e) { if (e instanceof Error && "code" in e && e.code === "ENOENT") { console.log("No Vencord settings found to import."); } else { console.error("Failed to import Vencord settings:", e); } } } win.close(); createWindows(); }); } ================================================ FILE: src/main/index.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import "./cli"; import "./updater"; import "./ipc"; import "./userAssets"; import "./vesktopProtocol"; import { app, BrowserWindow, nativeTheme } from "electron"; import { DATA_DIR } from "./constants"; import { createFirstLaunchTour } from "./firstLaunch"; import { createWindows, mainWin } from "./mainWindow"; import { registerMediaPermissionsHandler } from "./mediaPermissions"; import { registerScreenShareHandler } from "./screenShare"; import { Settings, State } from "./settings"; import { setAsDefaultProtocolClient } from "./utils/setAsDefaultProtocolClient"; import { isDeckGameMode } from "./utils/steamOS"; console.log("Vesktop v" + app.getVersion()); // Make the Vencord files use our DATA_DIR process.env.VENCORD_USER_DATA_DIR = DATA_DIR; const isLinux = process.platform === "linux"; export let enableHardwareAcceleration = true; function init() { setAsDefaultProtocolClient("discord"); const { disableSmoothScroll, hardwareAcceleration, hardwareVideoAcceleration } = Settings.store; const enabledFeatures = new Set(app.commandLine.getSwitchValue("enable-features").split(",")); const disabledFeatures = new Set(app.commandLine.getSwitchValue("disable-features").split(",")); app.commandLine.removeSwitch("enable-features"); app.commandLine.removeSwitch("disable-features"); if (hardwareAcceleration === false || process.argv.includes("--disable-gpu")) { enableHardwareAcceleration = false; app.disableHardwareAcceleration(); } else { if (hardwareVideoAcceleration) { enabledFeatures.add("AcceleratedVideoEncoder"); enabledFeatures.add("AcceleratedVideoDecoder"); if (isLinux) { enabledFeatures.add("AcceleratedVideoDecodeLinuxGL"); enabledFeatures.add("AcceleratedVideoDecodeLinuxZeroCopyGL"); } } } if (disableSmoothScroll) { app.commandLine.appendSwitch("disable-smooth-scrolling"); } // disable renderer backgrounding to prevent the app from unloading when in the background // https://github.com/electron/electron/issues/2822 // https://github.com/GoogleChrome/chrome-launcher/blob/5a27dd574d47a75fec0fb50f7b774ebf8a9791ba/docs/chrome-flags-for-tools.md#task-throttling app.commandLine.appendSwitch("disable-renderer-backgrounding"); app.commandLine.appendSwitch("disable-background-timer-throttling"); app.commandLine.appendSwitch("disable-backgrounding-occluded-windows"); if (process.platform === "win32") { disabledFeatures.add("CalculateNativeWinOcclusion"); } // work around chrome 66 disabling autoplay by default app.commandLine.appendSwitch("autoplay-policy", "no-user-gesture-required"); // WinRetrieveSuggestionsOnlyOnDemand: Work around electron 13 bug w/ async spellchecking on Windows. // HardwareMediaKeyHandling, MediaSessionService: Prevent Discord from registering as a media service. disabledFeatures.add("WinRetrieveSuggestionsOnlyOnDemand"); disabledFeatures.add("HardwareMediaKeyHandling"); disabledFeatures.add("MediaSessionService"); if (isLinux) { // Support TTS on Linux using https://wiki.archlinux.org/title/Speech_dispatcher app.commandLine.appendSwitch("enable-speech-dispatcher"); } disabledFeatures.forEach(feat => enabledFeatures.delete(feat)); const enabledFeaturesArray = enabledFeatures.values().filter(Boolean).toArray(); const disabledFeaturesArray = disabledFeatures.values().filter(Boolean).toArray(); if (enabledFeaturesArray.length) { app.commandLine.appendSwitch("enable-features", enabledFeaturesArray.join(",")); console.log("Enabled Chromium features:", enabledFeaturesArray.join(", ")); } if (disabledFeaturesArray.length) { app.commandLine.appendSwitch("disable-features", disabledFeaturesArray.join(",")); console.log("Disabled Chromium features:", disabledFeaturesArray.join(", ")); } // In the Flatpak on SteamOS the theme is detected as light, but SteamOS only has a dark mode, so we just override it if (isDeckGameMode) nativeTheme.themeSource = "dark"; app.on("second-instance", (_event, _cmdLine, _cwd, data: any) => { if (data.IS_DEV) app.quit(); else if (mainWin) { if (mainWin.isMinimized()) mainWin.restore(); if (!mainWin.isVisible()) mainWin.show(); mainWin.focus(); } }); app.whenReady().then(async () => { if (process.platform === "win32") app.setAppUserModelId("dev.vencord.vesktop"); registerScreenShareHandler(); registerMediaPermissionsHandler(); bootstrap(); app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) createWindows(); }); }); } if (!app.requestSingleInstanceLock({ IS_DEV })) { if (IS_DEV) { console.log("Vesktop is already running. Quitting previous instance..."); init(); } else { console.log("Vesktop is already running. Quitting..."); app.quit(); } } else { init(); } async function bootstrap() { if (!Object.hasOwn(State.store, "firstLaunch")) { createFirstLaunchTour(); } else { createWindows(); } } // MacOS only event export let darwinURL: string | undefined; app.on("open-url", (_, url) => { darwinURL = url; }); app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); }); ================================================ FILE: src/main/ipc.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ if (process.platform === "linux") import("./venmic"); import { execFile } from "child_process"; import { app, BrowserWindow, clipboard, dialog, IpcMainInvokeEvent, nativeImage, RelaunchOptions, session, shell } from "electron"; import { readFileSync, watch } from "fs"; import { readFile, stat } from "fs/promises"; import { enableHardwareAcceleration } from "main"; import { release } from "os"; import { join } from "path"; import { IpcEvents } from "../shared/IpcEvents"; import { setBadgeCount } from "./appBadge"; import { autoStart } from "./autoStart"; import { mainWin } from "./mainWindow"; import { Settings, State } from "./settings"; import { handle, handleSync } from "./utils/ipcWrappers"; import { PopoutWindows } from "./utils/popout"; import { isDeckGameMode, showGamePage } from "./utils/steamOS"; import { isValidVencordInstall } from "./utils/vencordLoader"; import { VENCORD_FILES_DIR } from "./vencordFilesDir"; handleSync(IpcEvents.DEPRECATED_GET_VENCORD_PRELOAD_SCRIPT_PATH, () => join(VENCORD_FILES_DIR, "vencordDesktopPreload.js") ); handleSync(IpcEvents.GET_VENCORD_PRELOAD_SCRIPT, () => readFileSync(join(VENCORD_FILES_DIR, "vencordDesktopPreload.js"), "utf-8") ); handleSync(IpcEvents.GET_VENCORD_RENDERER_SCRIPT, () => readFileSync(join(VENCORD_FILES_DIR, "vencordDesktopRenderer.js"), "utf-8") ); const VESKTOP_RENDERER_JS_PATH = join(__dirname, "renderer.js"); const VESKTOP_RENDERER_CSS_PATH = join(__dirname, "renderer.css"); handleSync(IpcEvents.GET_VESKTOP_RENDERER_SCRIPT, () => readFileSync(VESKTOP_RENDERER_JS_PATH, "utf-8")); handle(IpcEvents.GET_VESKTOP_RENDERER_CSS, () => readFile(VESKTOP_RENDERER_CSS_PATH, "utf-8")); if (IS_DEV) { watch(VESKTOP_RENDERER_CSS_PATH, { persistent: false }, async () => { mainWin?.webContents.postMessage( IpcEvents.VESKTOP_RENDERER_CSS_UPDATE, await readFile(VESKTOP_RENDERER_CSS_PATH, "utf-8") ); }); } handleSync(IpcEvents.GET_SETTINGS, () => Settings.plain); handleSync(IpcEvents.GET_VERSION, () => app.getVersion()); handleSync(IpcEvents.GET_ENABLE_HARDWARE_ACCELERATION, () => enableHardwareAcceleration); handleSync( IpcEvents.SUPPORTS_WINDOWS_TRANSPARENCY, () => process.platform === "win32" && Number(release().split(".").pop()) >= 22621 ); handleSync(IpcEvents.AUTOSTART_ENABLED, () => autoStart.isEnabled()); handle(IpcEvents.ENABLE_AUTOSTART, autoStart.enable); handle(IpcEvents.DISABLE_AUTOSTART, autoStart.disable); handle(IpcEvents.SET_SETTINGS, (_, settings: typeof Settings.store, path?: string) => { Settings.setData(settings, path); }); handle(IpcEvents.RELAUNCH, async () => { const options: RelaunchOptions = { args: process.argv.slice(1).concat(["--relaunch"]) }; if (isDeckGameMode) { // We can't properly relaunch when running under gamescope, but we can at least navigate to our page in Steam. await showGamePage(); } else if (app.isPackaged && process.env.APPIMAGE) { execFile(process.env.APPIMAGE, options.args); } else { app.relaunch(options); } app.exit(); }); handleSync(IpcEvents.IS_USING_CUSTOM_VENCORD_DIR, () => !!State.store.vencordDir); handle(IpcEvents.SHOW_CUSTOM_VENCORD_DIR, async () => { const { vencordDir } = State.store; if (!vencordDir) return; const stats = await stat(vencordDir); if (!stats.isDirectory()) return; shell.openPath(vencordDir); }); function getWindow(e: IpcMainInvokeEvent, key?: string) { return key ? PopoutWindows.get(key)! : (BrowserWindow.fromWebContents(e.sender) ?? mainWin); } handle(IpcEvents.FOCUS, () => { mainWin.show(); mainWin.setSkipTaskbar(false); }); handle(IpcEvents.CLOSE, (e, key?: string) => { getWindow(e, key).close(); }); handle(IpcEvents.MINIMIZE, (e, key?: string) => { getWindow(e, key).minimize(); }); handle(IpcEvents.MAXIMIZE, (e, key?: string) => { const win = getWindow(e, key); if (win.isMaximized()) { win.unmaximize(); } else { win.maximize(); } }); handleSync(IpcEvents.SPELLCHECK_GET_AVAILABLE_LANGUAGES, e => { e.returnValue = session.defaultSession.availableSpellCheckerLanguages; }); handle(IpcEvents.SPELLCHECK_REPLACE_MISSPELLING, (e, word: string) => { e.sender.replaceMisspelling(word); }); handle(IpcEvents.SPELLCHECK_ADD_TO_DICTIONARY, (e, word: string) => { e.sender.session.addWordToSpellCheckerDictionary(word); }); handle(IpcEvents.SELECT_VENCORD_DIR, async (_e, value?: null) => { if (value === null) { delete State.store.vencordDir; return "ok"; } const res = await dialog.showOpenDialog(mainWin!, { properties: ["openDirectory"] }); if (!res.filePaths.length) return "cancelled"; const dir = res.filePaths[0]; if (!isValidVencordInstall(dir)) return "invalid"; State.store.vencordDir = dir; return "ok"; }); handle(IpcEvents.SET_BADGE_COUNT, (_, count: number) => setBadgeCount(count)); handle(IpcEvents.FLASH_FRAME, (_, flag: boolean) => { if (!mainWin || mainWin.isDestroyed() || (flag && mainWin.isFocused())) return; mainWin.flashFrame(flag); }); handle(IpcEvents.CLIPBOARD_COPY_IMAGE, async (_, buf: ArrayBuffer, src: string) => { clipboard.write({ html: ``, image: nativeImage.createFromBuffer(Buffer.from(buf)) }); }); function openDebugPage(page: string) { const win = new BrowserWindow({ autoHideMenuBar: true }); win.loadURL(page); } handle(IpcEvents.DEBUG_LAUNCH_GPU, () => openDebugPage("chrome://gpu")); handle(IpcEvents.DEBUG_LAUNCH_WEBRTC_INTERNALS, () => openDebugPage("chrome://webrtc-internals")); ================================================ FILE: src/main/ipcCommands.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { randomUUID } from "crypto"; import { ipcMain } from "electron"; import { IpcEvents } from "shared/IpcEvents"; import { mainWin } from "./mainWindow"; const resolvers = new Map void>>(); export interface IpcMessage { nonce: string; message: string; data?: any; } export interface IpcResponse { nonce: string; ok: boolean; data?: any; } /** * Sends a message to the renderer process and waits for a response. * `data` must be serializable as it will be sent over IPC. * * You must add a handler for the message in the renderer process. */ export function sendRendererCommand(message: string, data?: any) { if (mainWin.isDestroyed()) { console.warn("Main window is destroyed, cannot send IPC command:", message); return Promise.reject(new Error("Main window is destroyed")); } const nonce = randomUUID(); const promise = new Promise((resolve, reject) => { resolvers.set(nonce, { resolve, reject }); }); mainWin.webContents.send(IpcEvents.IPC_COMMAND, { nonce, message, data }); return promise; } ipcMain.on(IpcEvents.IPC_COMMAND, (_event, { nonce, ok, data }: IpcResponse) => { const resolver = resolvers.get(nonce); if (!resolver) throw new Error(`Unknown message: ${nonce}`); if (ok) { resolver.resolve(data); } else { resolver.reject(data); } resolvers.delete(nonce); }); ================================================ FILE: src/main/mainWindow.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app, BrowserWindow, BrowserWindowConstructorOptions, Menu, MenuItemConstructorOptions, nativeTheme, Rectangle, screen, session } from "electron"; import { join } from "path"; import { IpcCommands, IpcEvents } from "shared/IpcEvents"; import { isTruthy } from "shared/utils/guards"; import { once } from "shared/utils/once"; import type { SettingsStore } from "shared/utils/SettingsStore"; import { createAboutWindow } from "./about"; import { initArRPC } from "./arrpc"; import { CommandLine } from "./cli"; import { BrowserUserAgent, DEFAULT_HEIGHT, DEFAULT_WIDTH, MIN_HEIGHT, MIN_WIDTH } from "./constants"; import { AppEvents } from "./events"; import { darwinURL } from "./index"; import { sendRendererCommand } from "./ipcCommands"; import { Settings, State, VencordSettings } from "./settings"; import { createSplashWindow, updateSplashMessage } from "./splash"; import { destroyTray, initTray } from "./tray"; import { clearData } from "./utils/clearData"; import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally"; import { applyDeckKeyboardFix, askToApplySteamLayout, isDeckGameMode } from "./utils/steamOS"; import { downloadVencordFiles, ensureVencordFiles, vencordSupportsSandboxing } from "./utils/vencordLoader"; import { VENCORD_FILES_DIR } from "./vencordFilesDir"; let isQuitting = false; applyDeckKeyboardFix(); app.on("before-quit", () => { isQuitting = true; }); export let mainWin: BrowserWindow; function makeSettingsListenerHelpers(o: SettingsStore) { const listeners = new Map<(data: any) => void, PropertyKey>(); const addListener: typeof o.addChangeListener = (path, cb) => { listeners.set(cb, path); o.addChangeListener(path, cb); }; const removeAllListeners = () => { for (const [listener, path] of listeners) { o.removeChangeListener(path as any, listener); } listeners.clear(); }; return [addListener, removeAllListeners] as const; } const [addSettingsListener, removeSettingsListeners] = makeSettingsListenerHelpers(Settings); const [addVencordSettingsListener, removeVencordSettingsListeners] = makeSettingsListenerHelpers(VencordSettings); type MenuItemList = Array; function initMenuBar(win: BrowserWindow) { const isWindows = process.platform === "win32"; const isDarwin = process.platform === "darwin"; const wantCtrlQ = !isWindows || VencordSettings.store.winCtrlQ; const subMenu = [ { label: "About Vesktop", click: createAboutWindow }, { label: "Force Update Vencord", async click() { await downloadVencordFiles(); app.relaunch(); app.quit(); }, toolTip: "Vesktop will automatically restart after this operation" }, { label: "Reset Vesktop", async click() { await clearData(win); }, toolTip: "Vesktop will automatically restart after this operation" }, { label: "Relaunch", accelerator: "CmdOrCtrl+Shift+R", click() { app.relaunch(); app.quit(); } }, ...(!isDarwin ? [] : ([ { type: "separator" }, { label: "Settings", accelerator: "CmdOrCtrl+,", async click() { sendRendererCommand(IpcCommands.NAVIGATE_SETTINGS); } }, { type: "separator" }, { role: "hide" }, { role: "hideOthers" }, { role: "unhide" }, { type: "separator" } ] satisfies MenuItemList)), { label: "Quit", accelerator: wantCtrlQ ? "CmdOrCtrl+Q" : void 0, visible: !isWindows, role: "quit", click() { app.quit(); } }, isWindows && { label: "Quit", accelerator: "Alt+F4", role: "quit", click() { app.quit(); } }, // See https://github.com/electron/electron/issues/14742 and https://github.com/electron/electron/issues/5256 { label: "Zoom in (hidden, hack for Qwertz and others)", accelerator: "CmdOrCtrl+=", role: "zoomIn", visible: false } ] satisfies MenuItemList; const menuItems = [ { label: "Vesktop", role: "appMenu", submenu: subMenu.filter(isTruthy) }, { role: "fileMenu" }, { role: "editMenu" }, { role: "viewMenu" }, isDarwin && { role: "windowMenu" } ] satisfies MenuItemList; const menu = Menu.buildFromTemplate(menuItems.filter(isTruthy)); Menu.setApplicationMenu(menu); } function initWindowBoundsListeners(win: BrowserWindow) { const saveState = () => { State.store.maximized = win.isMaximized(); State.store.minimized = win.isMinimized(); }; win.on("maximize", saveState); win.on("minimize", saveState); win.on("unmaximize", saveState); const saveBounds = () => { State.store.windowBounds = win.getBounds(); }; win.on("resize", saveBounds); win.on("move", saveBounds); } function initSettingsListeners(win: BrowserWindow) { addSettingsListener("tray", enable => { if (enable) initTray(win, q => (isQuitting = q)); else destroyTray(); }); addSettingsListener("disableMinSize", disable => { if (disable) { // 0 no work win.setMinimumSize(1, 1); } else { win.setMinimumSize(MIN_WIDTH, MIN_HEIGHT); const { width, height } = win.getBounds(); win.setBounds({ width: Math.max(width, MIN_WIDTH), height: Math.max(height, MIN_HEIGHT) }); } }); addVencordSettingsListener("macosTranslucency", enabled => { if (enabled) { win.setVibrancy("sidebar"); win.setBackgroundColor("#ffffff00"); } else { win.setVibrancy(null); win.setBackgroundColor("#ffffff"); } }); addSettingsListener("enableMenu", enabled => { win.setAutoHideMenuBar(enabled ?? false); }); addSettingsListener("spellCheckLanguages", languages => initSpellCheckLanguages(win, languages)); } async function initSpellCheckLanguages(win: BrowserWindow, languages?: string[]) { languages ??= await sendRendererCommand(IpcCommands.GET_LANGUAGES); if (!languages) return; const ses = session.defaultSession; const available = ses.availableSpellCheckerLanguages; const applicable = languages.filter(l => available.includes(l)).slice(0, 5); if (applicable.length) ses.setSpellCheckerLanguages(applicable); } function initSpellCheck(win: BrowserWindow) { win.webContents.on("context-menu", (_, data) => { win.webContents.send(IpcEvents.SPELLCHECK_RESULT, data.misspelledWord, data.dictionarySuggestions); }); initSpellCheckLanguages(win, Settings.store.spellCheckLanguages); } function initDevtoolsListeners(win: BrowserWindow) { win.webContents.on("devtools-opened", () => { win.webContents.send(IpcEvents.DEVTOOLS_OPENED); }); win.webContents.on("devtools-closed", () => { win.webContents.send(IpcEvents.DEVTOOLS_CLOSED); }); } function initStaticTitle(win: BrowserWindow) { const listener = (e: { preventDefault: Function }) => e.preventDefault(); if (Settings.store.staticTitle) win.on("page-title-updated", listener); addSettingsListener("staticTitle", enabled => { if (enabled) { win.setTitle("Vesktop"); win.on("page-title-updated", listener); } else { win.off("page-title-updated", listener); } }); } function getWindowBoundsOptions(): BrowserWindowConstructorOptions { // We want the default window behaviour to apply in game mode since it expects everything to be fullscreen and maximized. if (isDeckGameMode) return {}; const { x, y, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT } = State.store.windowBounds ?? {}; const options = { width, height } as BrowserWindowConstructorOptions; if (x != null && y != null) { function isInBounds(rect: Rectangle, display: Rectangle) { return !( rect.x + rect.width < display.x || rect.x > display.x + display.width || rect.y + rect.height < display.y || rect.y > display.y + display.height ); } const inBounds = screen.getAllDisplays().some(d => isInBounds({ x, y, width, height }, d.bounds)); if (inBounds) { options.x = x; options.y = y; } } if (!Settings.store.disableMinSize) { options.minWidth = MIN_WIDTH; options.minHeight = MIN_HEIGHT; } return options; } function buildBrowserWindowOptions(): BrowserWindowConstructorOptions { const { staticTitle, transparencyOption, enableMenu, customTitleBar, splashTheming, splashBackground } = Settings.store; const { frameless, transparent, macosVibrancyStyle } = VencordSettings.store; const noFrame = frameless === true || customTitleBar === true; const backgroundColor = splashTheming !== false ? splashBackground : nativeTheme.shouldUseDarkColors ? "#313338" : "#ffffff"; const options: BrowserWindowConstructorOptions = { show: Settings.store.enableSplashScreen === false && !CommandLine.values["start-minimized"], backgroundColor, webPreferences: { nodeIntegration: false, sandbox: vencordSupportsSandboxing(), contextIsolation: true, devTools: true, preload: join(__dirname, "preload.js"), spellcheck: true, // disable renderer backgrounding to prevent the app from unloading when in the background backgroundThrottling: false }, frame: !noFrame, autoHideMenuBar: enableMenu, ...getWindowBoundsOptions() }; if (transparent) { options.transparent = true; options.backgroundColor = "#00000000"; } if (transparencyOption && transparencyOption !== "none") { options.backgroundColor = "#00000000"; options.backgroundMaterial = transparencyOption; if (customTitleBar) { options.transparent = true; } } if (staticTitle) { options.title = "Vesktop"; } if (process.platform === "darwin") { options.titleBarStyle = "hidden"; options.trafficLightPosition = { x: 10, y: 10 }; if (macosVibrancyStyle) { options.vibrancy = macosVibrancyStyle; options.backgroundColor = "#00000000"; } } return options; } function createMainWindow() { // Clear up previous settings listeners removeSettingsListeners(); removeVencordSettingsListeners(); const win = (mainWin = new BrowserWindow(buildBrowserWindowOptions())); win.setMenuBarVisibility(false); if (process.platform === "darwin" && Settings.store.customTitleBar) win.setWindowButtonVisibility(false); win.on("close", e => { const useTray = !isDeckGameMode && Settings.store.minimizeToTray !== false && Settings.store.tray !== false; if (isQuitting || (process.platform !== "darwin" && !useTray)) return; e.preventDefault(); if (process.platform === "darwin") app.hide(); else win.hide(); return false; }); win.on("focus", () => { win.flashFrame(false); }); initWindowBoundsListeners(win); if (!isDeckGameMode && (Settings.store.tray ?? true) && process.platform !== "darwin") initTray(win, q => (isQuitting = q)); initMenuBar(win); makeLinksOpenExternally(win); initSettingsListeners(win); initSpellCheck(win); initDevtoolsListeners(win); initStaticTitle(win); win.webContents.setUserAgent(BrowserUserAgent); // if the open-url event is fired (in index.ts) while starting up, darwinURL will be set. If not fall back to checking the process args (which Windows and Linux use for URI calling.) // win.webContents.session.clearCache().then(() => { loadUrl(darwinURL || process.argv.find(arg => arg.startsWith("discord://"))); // }); return win; } const runVencordMain = once(() => require(join(VENCORD_FILES_DIR, "vencordDesktopMain.js"))); export function loadUrl(uri: string | undefined) { const branch = Settings.store.discordBranch; const subdomain = branch === "canary" || branch === "ptb" ? `${branch}.` : ""; // we do not rely on 'did-finish-load' because it fires even if loadURL fails which triggers early detruction of the splash mainWin .loadURL(`https://${subdomain}discord.com/${uri ? new URL(uri).pathname.slice(1) || "app" : "app"}`) .then(() => AppEvents.emit("appLoaded")) .catch(error => retryUrl(error.url, error.code)); } const retryDelay = 1000; function retryUrl(url: string, description: string) { console.log(`retrying in ${retryDelay}ms`); updateSplashMessage(`Failed to load Discord: ${description}`); setTimeout(() => loadUrl(url), retryDelay); } export async function createWindows() { const startMinimized = CommandLine.values["start-minimized"]; let splash: BrowserWindow | undefined; if (Settings.store.enableSplashScreen !== false) { splash = createSplashWindow(startMinimized); // SteamOS letterboxes and scales it terribly, so just full screen it if (isDeckGameMode) splash.setFullScreen(true); } await ensureVencordFiles(); runVencordMain(); mainWin = createMainWindow(); AppEvents.on("appLoaded", () => { splash?.destroy(); if (!startMinimized) { if (splash) mainWin!.show(); if (State.store.maximized && !isDeckGameMode) mainWin!.maximize(); } if (isDeckGameMode) { // always use entire display mainWin!.setFullScreen(true); askToApplySteamLayout(mainWin); } mainWin.once("show", () => { if (State.store.maximized && !mainWin!.isMaximized() && !isDeckGameMode) { mainWin!.maximize(); } }); }); mainWin.webContents.on("did-navigate", (_, url: string, responseCode: number) => { updateSplashMessage(""); // clear the splash message // check url to ensure app doesn't loop if (responseCode >= 300 && new URL(url).pathname !== `/app`) { loadUrl(undefined); console.warn(`'did-navigate': Caught bad page response: ${responseCode}, redirecting to main app`); } }); initArRPC(); } ================================================ FILE: src/main/mediaPermissions.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { session, systemPreferences } from "electron"; export function registerMediaPermissionsHandler() { if (process.platform !== "darwin") return; session.defaultSession.setPermissionRequestHandler(async (_webContents, permission, callback, details) => { let granted = true; if ("mediaTypes" in details) { if (details.mediaTypes?.includes("audio")) { granted &&= await systemPreferences.askForMediaAccess("microphone"); } if (details.mediaTypes?.includes("video")) { granted &&= await systemPreferences.askForMediaAccess("camera"); } } callback(granted); }); } ================================================ FILE: src/main/screenShare.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { desktopCapturer, session, Streams } from "electron"; import type { StreamPick } from "renderer/components/ScreenSharePicker"; import { IpcCommands, IpcEvents } from "shared/IpcEvents"; import { sendRendererCommand } from "./ipcCommands"; import { handle } from "./utils/ipcWrappers"; const isWayland = process.platform === "linux" && (process.env.XDG_SESSION_TYPE === "wayland" || !!process.env.WAYLAND_DISPLAY); export function registerScreenShareHandler() { handle(IpcEvents.CAPTURER_GET_LARGE_THUMBNAIL, async (_, id: string) => { const sources = await desktopCapturer.getSources({ types: ["window", "screen"], thumbnailSize: { width: 1920, height: 1080 } }); return sources.find(s => s.id === id)?.thumbnail.toDataURL(); }); session.defaultSession.setDisplayMediaRequestHandler(async (request, callback) => { // request full resolution on wayland right away because we always only end up with one result anyway const width = isWayland ? 1920 : 176; const sources = await desktopCapturer .getSources({ types: ["window", "screen"], thumbnailSize: { width, height: width * (9 / 16) } }) .catch(err => console.error("Error during screenshare picker", err)); if (!sources) return callback({}); const data = sources.map(({ id, name, thumbnail }) => ({ id, name, url: thumbnail.toDataURL() })); if (isWayland) { const video = data[0]; if (video) { const stream = await sendRendererCommand(IpcCommands.SCREEN_SHARE_PICKER, { screens: [video], skipPicker: true }).catch(() => null); if (stream === null) return callback({}); } callback(video ? { video: sources[0] } : {}); return; } const choice = await sendRendererCommand(IpcCommands.SCREEN_SHARE_PICKER, { screens: data, skipPicker: false }).catch(e => { console.error("Error during screenshare picker", e); return null; }); if (!choice) return callback({}); const source = sources.find(s => s.id === choice.id); if (!source) return callback({}); const streams: Streams = { video: source }; if (choice.audio && process.platform === "win32") streams.audio = "loopback"; callback(streams); }); } ================================================ FILE: src/main/settings.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { type Settings as TVencordSettings } from "@vencord/types/Vencord"; import { mkdirSync, readFileSync, writeFileSync } from "fs"; import { dirname, join } from "path"; import type { Settings as TSettings, State as TState } from "shared/settings"; import { SettingsStore } from "shared/utils/SettingsStore"; import { DATA_DIR, VENCORD_SETTINGS_FILE } from "./constants"; const SETTINGS_FILE = join(DATA_DIR, "settings.json"); const STATE_FILE = join(DATA_DIR, "state.json"); function loadSettings(file: string, name: string) { let settings = {} as T; try { const content = readFileSync(file, "utf8"); try { settings = JSON.parse(content); } catch (err) { console.error(`Failed to parse ${name}.json:`, err); } } catch {} const store = new SettingsStore(settings); store.addGlobalChangeListener(o => { try { mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, JSON.stringify(o, null, 4)); } catch (err) { console.error(`Failed to save settings to ${name}.json:`, err); } }); return store; } export const Settings = loadSettings(SETTINGS_FILE, "Vesktop settings"); export const VencordSettings = loadSettings(VENCORD_SETTINGS_FILE, "Vencord settings"); export const State = loadSettings(STATE_FILE, "Vesktop state"); ================================================ FILE: src/main/splash.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { BrowserWindow } from "electron"; import { join } from "path"; import { SplashProps } from "shared/browserWinProperties"; import { Settings } from "./settings"; import { loadView } from "./vesktopStatic"; let splash: BrowserWindow | undefined; export function createSplashWindow(startMinimized = false) { splash = new BrowserWindow({ ...SplashProps, show: !startMinimized, webPreferences: { preload: join(__dirname, "splashPreload.js") } }); loadView(splash, "splash.html"); const { splashBackground, splashColor, splashTheming, splashPixelated } = Settings.store; if (splashTheming !== false) { if (splashColor) { const semiTransparentSplashColor = splashColor.replace("rgb(", "rgba(").replace(")", ", 0.2)"); splash.webContents.insertCSS(`body { --fg: ${splashColor} !important }`); splash.webContents.insertCSS(`body { --fg-semi-trans: ${semiTransparentSplashColor} !important }`); } if (splashBackground) { splash.webContents.insertCSS(`body { --bg: ${splashBackground} !important }`); } } if (splashPixelated) { splash.webContents.insertCSS(`img { image-rendering: pixelated; }`); } return splash; } export function updateSplashMessage(message: string) { if (splash && !splash.isDestroyed()) splash.webContents.send("update-splash-message", message); } ================================================ FILE: src/main/tray.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app, BrowserWindow, Menu, Tray } from "electron"; import { createAboutWindow } from "./about"; import { AppEvents } from "./events"; import { Settings } from "./settings"; import { resolveAssetPath } from "./userAssets"; import { clearData } from "./utils/clearData"; import { downloadVencordFiles } from "./utils/vencordLoader"; let tray: Tray; let trayVariant: "tray" | "trayUnread" = "tray"; AppEvents.on("userAssetChanged", async asset => { if (tray && (asset === "tray" || asset === "trayUnread")) { tray.setImage(await resolveAssetPath(trayVariant)); } }); AppEvents.on("setTrayVariant", async variant => { if (trayVariant === variant) return; trayVariant = variant; if (!tray) return; tray.setImage(await resolveAssetPath(trayVariant)); }); export function destroyTray() { tray?.destroy(); } export async function initTray(win: BrowserWindow, setIsQuitting: (val: boolean) => void) { const onTrayClick = () => { if (Settings.store.clickTrayToShowHide && win.isVisible()) win.hide(); else win.show(); }; const trayMenu = Menu.buildFromTemplate([ { label: "Open", click() { win.show(); } }, { label: "About", click: createAboutWindow }, { label: "Repair Vencord", async click() { await downloadVencordFiles(); app.relaunch(); app.quit(); } }, { label: "Reset Vesktop", async click() { await clearData(win); } }, { type: "separator" }, { label: "Restart", click() { app.relaunch(); app.quit(); } }, { label: "Quit", click() { setIsQuitting(true); app.quit(); } } ]); tray = new Tray(await resolveAssetPath(trayVariant)); tray.setToolTip("Vesktop"); tray.setContextMenu(trayMenu); tray.on("click", onTrayClick); } ================================================ FILE: src/main/updater.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app, BrowserWindow, ipcMain } from "electron"; import { autoUpdater, UpdateInfo } from "electron-updater"; import { join } from "path"; import { IpcEvents, UpdaterIpcEvents } from "shared/IpcEvents"; import { Millis } from "shared/utils/millis"; import { State } from "./settings"; import { handle } from "./utils/ipcWrappers"; import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally"; import { loadView } from "./vesktopStatic"; let updaterWindow: BrowserWindow | null = null; autoUpdater.on("update-available", update => { if (State.store.updater?.ignoredVersion === update.version) return; if ((State.store.updater?.snoozeUntil ?? 0) > Date.now()) return; openUpdater(update); }); autoUpdater.on("update-downloaded", () => setTimeout(() => autoUpdater.quitAndInstall(), 100)); autoUpdater.on("download-progress", p => updaterWindow?.webContents.send(UpdaterIpcEvents.DOWNLOAD_PROGRESS, p.percent) ); autoUpdater.on("error", err => updaterWindow?.webContents.send(UpdaterIpcEvents.ERROR, err.message)); autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; autoUpdater.fullChangelog = true; const isOutdated = autoUpdater.checkForUpdates().then(res => Boolean(res?.isUpdateAvailable)); handle(IpcEvents.UPDATER_IS_OUTDATED, () => isOutdated); handle(IpcEvents.UPDATER_OPEN, async () => { const res = await autoUpdater.checkForUpdates(); if (res?.isUpdateAvailable && res.updateInfo) openUpdater(res.updateInfo); }); function openUpdater(update: UpdateInfo) { updaterWindow = new BrowserWindow({ title: "Vesktop Updater", autoHideMenuBar: true, webPreferences: { preload: join(__dirname, "updaterPreload.js") }, minHeight: 400, minWidth: 750 }); makeLinksOpenExternally(updaterWindow); handle(UpdaterIpcEvents.GET_DATA, () => ({ update, version: app.getVersion() })); handle(UpdaterIpcEvents.INSTALL, async () => { await autoUpdater.downloadUpdate(); }); handle(UpdaterIpcEvents.SNOOZE_UPDATE, () => { State.store.updater ??= {}; State.store.updater.snoozeUntil = Date.now() + 1 * Millis.DAY; updaterWindow?.close(); }); handle(UpdaterIpcEvents.IGNORE_UPDATE, () => { State.store.updater ??= {}; State.store.updater.ignoredVersion = update.version; updaterWindow?.close(); }); updaterWindow.on("closed", () => { ipcMain.removeHandler(UpdaterIpcEvents.GET_DATA); ipcMain.removeHandler(UpdaterIpcEvents.INSTALL); ipcMain.removeHandler(UpdaterIpcEvents.SNOOZE_UPDATE); ipcMain.removeHandler(UpdaterIpcEvents.IGNORE_UPDATE); updaterWindow = null; }); loadView(updaterWindow, "updater/index.html"); } ================================================ FILE: src/main/userAssets.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app, dialog, net } from "electron"; import { copyFile, mkdir, rm } from "fs/promises"; import { join } from "path"; import { IpcEvents } from "shared/IpcEvents"; import { STATIC_DIR } from "shared/paths"; import { pathToFileURL } from "url"; import { DATA_DIR } from "./constants"; import { AppEvents } from "./events"; import { mainWin } from "./mainWindow"; import { fileExistsAsync } from "./utils/fileExists"; import { handle } from "./utils/ipcWrappers"; const CUSTOMIZABLE_ASSETS = ["splash", "tray", "trayUnread"] as const; export type UserAssetType = (typeof CUSTOMIZABLE_ASSETS)[number]; const DEFAULT_ASSETS: Record = { splash: "splash.webp", tray: `tray/${process.platform === "darwin" ? "trayTemplate" : "tray"}.png`, trayUnread: "tray/trayUnread.png" }; const UserAssetFolder = join(DATA_DIR, "userAssets"); export async function resolveAssetPath(asset: UserAssetType) { if (!CUSTOMIZABLE_ASSETS.includes(asset)) { throw new Error(`Invalid asset: ${asset}`); } const assetPath = join(UserAssetFolder, asset); if (await fileExistsAsync(assetPath)) { return assetPath; } return join(STATIC_DIR, DEFAULT_ASSETS[asset]); } export async function handleVesktopAssetsProtocol(path: string, req: Request) { const asset = path.slice(1); // @ts-expect-error dumb types if (!CUSTOMIZABLE_ASSETS.includes(asset)) { return new Response(null, { status: 404 }); } try { const res = await net.fetch(pathToFileURL(join(UserAssetFolder, asset)).href); if (res.ok) return res; } catch {} return net.fetch(pathToFileURL(join(STATIC_DIR, DEFAULT_ASSETS[asset])).href); } handle(IpcEvents.CHOOSE_USER_ASSET, async (_event, asset: UserAssetType, value?: null) => { if (!CUSTOMIZABLE_ASSETS.includes(asset)) { throw `Invalid asset: ${asset}`; } const assetPath = join(UserAssetFolder, asset); if (value === null) { try { await rm(assetPath, { force: true }); AppEvents.emit("userAssetChanged", asset); return "ok"; } catch (e) { console.error(`Failed to remove user asset ${asset}:`, e); return "failed"; } } const res = await dialog.showOpenDialog(mainWin, { properties: ["openFile"], title: `Select an image to use as ${asset}`, defaultPath: app.getPath("pictures"), filters: [ { name: "Images", extensions: ["png", "jpg", "jpeg", "webp", "gif", "avif", "svg"] } ] }); if (res.canceled || !res.filePaths.length) return "cancelled"; try { await mkdir(UserAssetFolder, { recursive: true }); await copyFile(res.filePaths[0], assetPath); AppEvents.emit("userAssetChanged", asset); return "ok"; } catch (e) { console.error(`Failed to copy user asset ${asset}:`, e); return "failed"; } }); ================================================ FILE: src/main/utils/clearData.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app, BrowserWindow, dialog } from "electron"; import { rm } from "fs/promises"; import { DATA_DIR, MessageBoxChoice } from "main/constants"; export async function clearData(win: BrowserWindow) { const { response } = await dialog.showMessageBox(win, { message: "Are you sure you want to reset Vesktop?", detail: "This will log you out, clear caches and reset all your settings!\n\nVesktop will automatically restart after this operation.", buttons: ["Yes", "No"], cancelId: MessageBoxChoice.Cancel, defaultId: MessageBoxChoice.Default, type: "warning" }); if (response === MessageBoxChoice.Cancel) return; win.close(); await win.webContents.session.clearStorageData(); await win.webContents.session.clearCache(); await win.webContents.session.clearCodeCaches({}); await rm(DATA_DIR, { force: true, recursive: true }); app.relaunch(); app.quit(); } ================================================ FILE: src/main/utils/desktopFileEscape.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ // https://specifications.freedesktop.org/desktop-entry-spec/latest/exec-variables.html // "If an argument contains a reserved character the argument must be quoted." const desktopFileReservedChars = new Set([ " ", "\t", "\n", '"', "'", "\\", ">", "<", "~", "|", "&", ";", "$", "*", "?", "#", "(", ")", "`" ]); export function escapeDesktopFileArgument(arg: string) { let needsQuoting = false; let out = ""; for (const c of arg) { if (desktopFileReservedChars.has(c)) { // "Quoting must be done by enclosing the argument between double quotes" needsQuoting = true; // "and escaping the double quote character, backtick character ("`"), dollar sign ("$") // and backslash character ("\") by preceding it with an additional backslash character" if (c === '"' || c === "`" || c === "$" || c === "\\") { out += "\\"; } } // "Literal percentage characters must be escaped as %%" if (c === "%") { out += "%%"; } else { out += c; } } return needsQuoting ? `"${out}"` : out; } ================================================ FILE: src/main/utils/fileExists.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { access, constants } from "fs/promises"; export async function fileExistsAsync(path: string) { return await access(path, constants.F_OK) .then(() => true) .catch(() => false); } ================================================ FILE: src/main/utils/http.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { createWriteStream } from "fs"; import { Readable } from "stream"; import { pipeline } from "stream/promises"; import { setTimeout } from "timers/promises"; interface FetchieOptions { retryOnNetworkError?: boolean; } export async function downloadFile(url: string, file: string, options: RequestInit = {}, fetchieOpts?: FetchieOptions) { const res = await fetchie(url, options, fetchieOpts); await pipeline( // @ts-expect-error odd type error Readable.fromWeb(res.body!), createWriteStream(file, { autoClose: true }) ); } const ONE_MINUTE_MS = 1000 * 60; export async function fetchie(url: string, options?: RequestInit, { retryOnNetworkError }: FetchieOptions = {}) { let res: Response | undefined; try { res = await fetch(url, options); } catch (err) { if (retryOnNetworkError) { console.error("Failed to fetch", url + ".", "Gonna retry with backoff."); for (let tries = 0, delayMs = 500; tries < 20; tries++, delayMs = Math.min(2 * delayMs, ONE_MINUTE_MS)) { await setTimeout(delayMs); try { res = await fetch(url, options); break; } catch {} } } if (!res) throw new Error(`Failed to fetch ${url}\n${err}`); } if (res.ok) return res; let msg = `Got non-OK response for ${url}: ${res.status} ${res.statusText}`; const reason = await res.text().catch(() => ""); if (reason) msg += `\n${reason}`; throw new Error(msg); } ================================================ FILE: src/main/utils/ipcWrappers.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { ipcMain, IpcMainEvent, IpcMainInvokeEvent, WebFrameMain } from "electron"; import { DISCORD_HOSTNAMES } from "main/constants"; import { IpcEvents, UpdaterIpcEvents } from "shared/IpcEvents"; export function validateSender(frame: WebFrameMain | null, event: string) { if (!frame) throw new Error(`ipc[${event}]: No sender frame`); if (!frame.url) return; try { var { hostname, protocol } = new URL(frame.url); } catch (e) { throw new Error(`ipc[${event}]: Invalid URL ${frame.url}`); } if (protocol === "file:" || protocol === "vesktop:") return; if (!DISCORD_HOSTNAMES.includes(hostname)) { throw new Error(`ipc[${event}]: Disallowed hostname ${hostname}`); } } export function handleSync(event: IpcEvents | UpdaterIpcEvents, cb: (e: IpcMainEvent, ...args: any[]) => any) { ipcMain.on(event, (e, ...args) => { validateSender(e.senderFrame, event); e.returnValue = cb(e, ...args); }); } export function handle(event: IpcEvents | UpdaterIpcEvents, cb: (e: IpcMainInvokeEvent, ...args: any[]) => any) { ipcMain.handle(event, (e, ...args) => { validateSender(e.senderFrame, event); return cb(e, ...args); }); } ================================================ FILE: src/main/utils/isPathInDirectory.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { resolve, sep } from "path"; export function isPathInDirectory(filePath: string, directory: string) { const resolvedPath = resolve(filePath); const resolvedDirectory = resolve(directory); const normalizedDirectory = resolvedDirectory.endsWith(sep) ? resolvedDirectory : resolvedDirectory + sep; return resolvedPath.startsWith(normalizedDirectory) || resolvedPath === resolvedDirectory; } ================================================ FILE: src/main/utils/makeLinksOpenExternally.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { BrowserWindow, shell } from "electron"; import { DISCORD_HOSTNAMES } from "main/constants"; import { Settings } from "../settings"; import { createOrFocusPopup, setupPopout } from "./popout"; import { execSteamURL, isDeckGameMode, steamOpenURL } from "./steamOS"; export function handleExternalUrl(url: string, protocol?: string): { action: "deny" | "allow" } { if (protocol == null) { try { protocol = new URL(url).protocol; } catch { return { action: "deny" }; } } switch (protocol) { case "http:": case "https:": if (Settings.store.openLinksWithElectron) { return { action: "allow" }; } // eslint-disable-next-line no-fallthrough case "mailto:": case "spotify:": if (isDeckGameMode) { steamOpenURL(url); } else { shell.openExternal(url); } break; case "steam:": if (isDeckGameMode) { execSteamURL(url); } else { shell.openExternal(url); } break; } return { action: "deny" }; } export function makeLinksOpenExternally(win: BrowserWindow) { win.webContents.setWindowOpenHandler(({ url, frameName, features }) => { try { var { protocol, hostname, pathname, searchParams } = new URL(url); } catch { return { action: "deny" }; } if (frameName.startsWith("DISCORD_") && pathname === "/popout" && DISCORD_HOSTNAMES.includes(hostname)) { return createOrFocusPopup(frameName, features); } if (url === "about:blank") return { action: "allow" }; // Drop the static temp page Discord web loads for the connections popout if (frameName === "authorize" && searchParams.get("loading") === "true") return { action: "deny" }; return handleExternalUrl(url, protocol); }); win.webContents.on("did-create-window", (win, { frameName }) => { if (frameName.startsWith("DISCORD_")) setupPopout(win, frameName); }); } ================================================ FILE: src/main/utils/popout.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { BrowserWindow, BrowserWindowConstructorOptions } from "electron"; import { Settings } from "main/settings"; import { handleExternalUrl } from "./makeLinksOpenExternally"; const ALLOWED_FEATURES = new Set([ "width", "height", "left", "top", "resizable", "movable", "alwaysOnTop", "frame", "transparent", "hasShadow", "closable", "skipTaskbar", "backgroundColor", "menubar", "toolbar", "location", "directories", "titleBarStyle" ]); const MIN_POPOUT_WIDTH = 320; const MIN_POPOUT_HEIGHT = 180; const DEFAULT_POPOUT_OPTIONS: BrowserWindowConstructorOptions = { title: "Discord Popout", backgroundColor: "#2f3136", minWidth: MIN_POPOUT_WIDTH, minHeight: MIN_POPOUT_HEIGHT, frame: Settings.store.customTitleBar !== true, titleBarStyle: process.platform === "darwin" ? "hidden" : undefined, trafficLightPosition: process.platform === "darwin" ? { x: 10, y: 3 } : undefined, webPreferences: { nodeIntegration: false, contextIsolation: true }, autoHideMenuBar: Settings.store.enableMenu }; export const PopoutWindows = new Map(); function focusWindow(window: BrowserWindow) { window.setAlwaysOnTop(true); window.focus(); window.setAlwaysOnTop(false); } function parseFeatureValue(feature: string) { if (feature === "yes") return true; if (feature === "no") return false; const n = Number(feature); if (!isNaN(n)) return n; return feature; } function parseWindowFeatures(features: string) { const keyValuesParsed = features.split(","); return keyValuesParsed.reduce((features, feature) => { const [key, value] = feature.split("="); if (ALLOWED_FEATURES.has(key)) features[key] = parseFeatureValue(value); return features; }, {}); } export function createOrFocusPopup(key: string, features: string) { const existingWindow = PopoutWindows.get(key); if (existingWindow) { focusWindow(existingWindow); return { action: "deny" }; } return { action: "allow", overrideBrowserWindowOptions: { ...DEFAULT_POPOUT_OPTIONS, ...parseWindowFeatures(features) } }; } export function setupPopout(win: BrowserWindow, key: string) { win.setMenuBarVisibility(false); PopoutWindows.set(key, win); /* win.webContents.on("will-navigate", (evt, url) => { // maybe prevent if not origin match })*/ win.webContents.setWindowOpenHandler(({ url }) => handleExternalUrl(url)); win.once("closed", () => { win.removeAllListeners(); PopoutWindows.delete(key); }); } ================================================ FILE: src/main/utils/setAsDefaultProtocolClient.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { execFile } from "child_process"; import { app } from "electron"; export async function setAsDefaultProtocolClient(protocol: string) { if (process.platform !== "linux") { return app.setAsDefaultProtocolClient(protocol); } // electron setAsDefaultProtocolClient uses xdg-settings instead of xdg-mime. // xdg-settings had a bug where it would also register the app as a handler for text/html, // aka become your browser. This bug was fixed years ago (xdg-utils 1.2.0) but Ubuntu ships // 7 (YES, SEVEN) years out of date xdg-utils which STILL has the bug. // FIXME: remove this workaround when Ubuntu updates their xdg-utils or electron switches to xdg-mime. const { CHROME_DESKTOP } = process.env; if (!CHROME_DESKTOP) return false; return new Promise(resolve => { execFile("xdg-mime", ["default", CHROME_DESKTOP, `x-scheme-handler/${protocol}`], err => { resolve(err == null); }); }); } ================================================ FILE: src/main/utils/steamOS.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { BrowserWindow, dialog } from "electron"; import { writeFile } from "fs/promises"; import { join } from "path"; import { MessageBoxChoice } from "../constants"; import { State } from "../settings"; // Bump this to re-show the prompt const layoutVersion = 2; // Get this from "show details" on the profile after exporting as a shared personal layout or using share with community const layoutId = "3080264545"; // Vesktop Layout v2 const numberRegex = /^[0-9]*$/; let steamPipeQueue = Promise.resolve(); export const isDeckGameMode = process.env.SteamOS === "1" && process.env.SteamGamepadUI === "1"; export function applyDeckKeyboardFix() { if (!isDeckGameMode) return; // Prevent constant virtual keyboard spam that eventually crashes Steam. process.env.GTK_IM_MODULE = "None"; } // For some reason SteamAppId is always 0 for non-steam apps so we do this insanity instead. function getAppId(): string | null { // /home/deck/.local/share/Steam/steamapps/shadercache/APPID/fozmediav1 const path = process.env.STEAM_COMPAT_MEDIA_PATH; if (!path) return null; const pathElems = path?.split("/"); const appId = pathElems[pathElems.length - 2]; if (appId.match(numberRegex)) { console.log(`Got Steam App ID ${appId}`); return appId; } return null; } export function execSteamURL(url: string) { // This doesn't allow arbitrary execution despite the weird syntax. steamPipeQueue = steamPipeQueue.then(() => writeFile( join(process.env.HOME || "/home/deck", ".steam", "steam.pipe"), // replace ' to prevent argument injection `'${process.env.HOME}/.local/share/Steam/ubuntu12_32/steam' '-ifrunning' '${url.replaceAll("'", "%27")}'\n`, "utf-8" ) ); } export function steamOpenURL(url: string) { execSteamURL(`steam://openurl/${url}`); } export async function showGamePage() { const appId = getAppId(); if (!appId) return; await execSteamURL(`steam://nav/games/details/${appId}`); } async function showLayout(appId: string) { execSteamURL(`steam://controllerconfig/${appId}/${layoutId}`); } export async function askToApplySteamLayout(win: BrowserWindow) { const appId = getAppId(); if (!appId) return; if (State.store.steamOSLayoutVersion === layoutVersion) return; const update = Boolean(State.store.steamOSLayoutVersion); // Touch screen breaks in some menus when native touch mode is enabled on latest SteamOS beta, remove most of the update specific text once that's fixed. const { response } = await dialog.showMessageBox(win, { message: `${update ? "Update" : "Apply"} Vesktop Steam Input Layout?`, detail: `Would you like to ${update ? "Update" : "Apply"} Vesktop's recommended Steam Deck controller settings? ${update ? "Click yes using the touchpad" : "Tap yes"}, then press the X button or tap Apply Layout to confirm.${ update ? " Doing so will undo any customizations you have made." : "" } ${update ? "Click" : "Tap"} no to keep your current layout.`, buttons: ["Yes", "No"], cancelId: MessageBoxChoice.Cancel, defaultId: MessageBoxChoice.Default, type: "question" }); if (State.store.steamOSLayoutVersion !== layoutVersion) { State.store.steamOSLayoutVersion = layoutVersion; } if (response === MessageBoxChoice.Cancel) return; await showLayout(appId); } ================================================ FILE: src/main/utils/vencordLoader.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { mkdirSync, readFileSync } from "fs"; import { access, constants as FsConstants, writeFile } from "fs/promises"; import { VENCORD_FILES_DIR } from "main/vencordFilesDir"; import { join } from "path"; import { USER_AGENT } from "../constants"; import { downloadFile, fetchie } from "./http"; const API_BASE = "https://api.github.com"; export const FILES_TO_DOWNLOAD = [ "vencordDesktopMain.js", "vencordDesktopPreload.js", "vencordDesktopRenderer.js", "vencordDesktopRenderer.css" ]; export interface ReleaseData { name: string; tag_name: string; html_url: string; assets: Array<{ name: string; browser_download_url: string; }>; } export async function githubGet(endpoint: string) { const opts: RequestInit = { headers: { Accept: "application/vnd.github+json", "User-Agent": USER_AGENT } }; if (process.env.GITHUB_TOKEN) (opts.headers! as any).Authorization = `Bearer ${process.env.GITHUB_TOKEN}`; return fetchie(API_BASE + endpoint, opts, { retryOnNetworkError: true }); } export async function downloadVencordFiles() { const release = await githubGet("/repos/Vendicated/Vencord/releases/latest"); const { assets }: ReleaseData = await release.json(); await Promise.all( assets .filter(({ name }) => FILES_TO_DOWNLOAD.some(f => name.startsWith(f))) .map(({ name, browser_download_url }) => downloadFile(browser_download_url, join(VENCORD_FILES_DIR, name), {}, { retryOnNetworkError: true }) ) ); } const existsAsync = (path: string) => access(path, FsConstants.F_OK) .then(() => true) .catch(() => false); export async function isValidVencordInstall(dir: string) { const results = await Promise.all(["package.json", ...FILES_TO_DOWNLOAD].map(f => existsAsync(join(dir, f)))); return !results.includes(false); } export async function ensureVencordFiles() { if (await isValidVencordInstall(VENCORD_FILES_DIR)) return; mkdirSync(VENCORD_FILES_DIR, { recursive: true }); await Promise.all([downloadVencordFiles(), writeFile(join(VENCORD_FILES_DIR, "package.json"), "{}")]); } // TODO: remove this once enough time has passed export function vencordSupportsSandboxing() { const supports = readFileSync(join(VENCORD_FILES_DIR, "vencordDesktopMain.js"), "utf-8").includes( "VencordGetRendererCss" ); if (!supports) { console.warn( "⚠️ [VencordLoader] Vencord version is outdated and does not support sandboxing. Please update Vencord to the latest version." ); } return supports; } ================================================ FILE: src/main/vencordFilesDir.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { join } from "path"; import { SESSION_DATA_DIR } from "./constants"; import { State } from "./settings"; // this is in a separate file to avoid circular dependencies export const VENCORD_FILES_DIR = State.store.vencordDir || join(SESSION_DATA_DIR, "vencordFiles"); ================================================ FILE: src/main/venmic.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import type { LinkData, Node, PatchBay as PatchBayType } from "@vencord/venmic"; import { app, ipcMain } from "electron"; import { join } from "path"; import { IpcEvents } from "shared/IpcEvents"; import { STATIC_DIR } from "shared/paths"; import { Settings } from "./settings"; let PatchBay: typeof PatchBayType | undefined; let patchBayInstance: PatchBayType | undefined; let imported = false; let initialized = false; let hasPipewirePulse = false; let isGlibCxxOutdated = false; function importVenmic() { if (imported) { return; } imported = true; try { PatchBay = (require(join(STATIC_DIR, `dist/venmic-${process.arch}.node`)) as typeof import("@vencord/venmic")) .PatchBay; hasPipewirePulse = PatchBay.hasPipeWire(); } catch (e: any) { console.error("Failed to import venmic", e); isGlibCxxOutdated = (e?.stack || e?.message || "").toLowerCase().includes("glibc"); } } function obtainVenmic() { if (!imported) { importVenmic(); } if (PatchBay && !initialized) { initialized = true; try { patchBayInstance = new PatchBay(); } catch (e: any) { console.error("Failed to instantiate venmic", e); } } return patchBayInstance; } function getRendererAudioServicePid() { return ( app .getAppMetrics() .find(proc => proc.name === "Audio Service") ?.pid?.toString() ?? "owo" ); } ipcMain.handle(IpcEvents.VIRT_MIC_LIST, () => { const audioPid = getRendererAudioServicePid(); const { granularSelect } = Settings.store.audio ?? {}; const targets = obtainVenmic() ?.list(granularSelect ? ["node.name"] : undefined) .filter(s => s["application.process.id"] !== audioPid); return targets ? { ok: true, targets, hasPipewirePulse } : { ok: false, isGlibCxxOutdated }; }); ipcMain.handle(IpcEvents.VIRT_MIC_START, (_, include: Node[]) => { const pid = getRendererAudioServicePid(); const { ignoreDevices, ignoreInputMedia, ignoreVirtual, workaround } = Settings.store.audio ?? {}; const data: LinkData = { include, exclude: [{ "application.process.id": pid }], ignore_devices: ignoreDevices }; if (ignoreInputMedia ?? true) { data.exclude.push({ "media.class": "Stream/Input/Audio" }); } if (ignoreVirtual) { data.exclude.push({ "node.virtual": "true" }); } if (workaround) { data.workaround = [{ "application.process.id": pid, "media.name": "RecordStream" }]; } return obtainVenmic()?.link(data); }); ipcMain.handle(IpcEvents.VIRT_MIC_START_SYSTEM, (_, exclude: Node[]) => { const pid = getRendererAudioServicePid(); const { workaround, ignoreDevices, ignoreInputMedia, ignoreVirtual, onlySpeakers, onlyDefaultSpeakers } = Settings.store.audio ?? {}; const data: LinkData = { include: [], exclude: [{ "application.process.id": pid }, ...exclude], only_speakers: onlySpeakers, ignore_devices: ignoreDevices, only_default_speakers: onlyDefaultSpeakers }; if (ignoreInputMedia ?? true) { data.exclude.push({ "media.class": "Stream/Input/Audio" }); } if (ignoreVirtual) { data.exclude.push({ "node.virtual": "true" }); } if (workaround) { data.workaround = [{ "application.process.id": pid, "media.name": "RecordStream" }]; } return obtainVenmic()?.link(data); }); ipcMain.handle(IpcEvents.VIRT_MIC_STOP, () => obtainVenmic()?.unlink()); ================================================ FILE: src/main/vesktopProtocol.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { app, protocol } from "electron"; import { handleVesktopAssetsProtocol } from "./userAssets"; import { handleVesktopStaticProtocol } from "./vesktopStatic"; app.whenReady().then(() => { protocol.handle("vesktop", async req => { const url = new URL(req.url); switch (url.hostname) { case "assets": return handleVesktopAssetsProtocol(url.pathname, req); case "static": return handleVesktopStaticProtocol(url.pathname, req); default: return new Response(null, { status: 404 }); } }); }); ================================================ FILE: src/main/vesktopStatic.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { BrowserWindow, net } from "electron"; import { join } from "path"; import { pathToFileURL } from "url"; import { isPathInDirectory } from "./utils/isPathInDirectory"; const STATIC_DIR = join(__dirname, "..", "..", "static"); export async function handleVesktopStaticProtocol(path: string, req: Request) { const fullPath = join(STATIC_DIR, path); if (!isPathInDirectory(fullPath, STATIC_DIR)) { return new Response(null, { status: 404 }); } return net.fetch(pathToFileURL(fullPath).href); } export function loadView(browserWindow: BrowserWindow, view: string, params?: URLSearchParams) { const url = new URL(`vesktop://static/views/${view}`); if (params) { url.search = params.toString(); } return browserWindow.loadURL(url.toString()); } ================================================ FILE: src/module.d.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ declare module "__patches__" { const never: never; export default never; } ================================================ FILE: src/preload/VesktopNative.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ 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 { IpcEvents } from "../shared/IpcEvents"; import { invoke, sendSync } from "./typedIpc"; type SpellCheckerResultCallback = (word: string, suggestions: string[]) => void; const spellCheckCallbacks = new Set(); ipcRenderer.on(IpcEvents.SPELLCHECK_RESULT, (_, w: string, s: string[]) => { spellCheckCallbacks.forEach(cb => cb(w, s)); }); let onDevtoolsOpen = () => {}; let onDevtoolsClose = () => {}; ipcRenderer.on(IpcEvents.DEVTOOLS_OPENED, () => onDevtoolsOpen()); ipcRenderer.on(IpcEvents.DEVTOOLS_CLOSED, () => onDevtoolsClose()); export const VesktopNative = { app: { relaunch: () => invoke(IpcEvents.RELAUNCH), getVersion: () => sendSync(IpcEvents.GET_VERSION), setBadgeCount: (count: number) => invoke(IpcEvents.SET_BADGE_COUNT, count), supportsWindowsTransparency: () => sendSync(IpcEvents.SUPPORTS_WINDOWS_TRANSPARENCY), getEnableHardwareAcceleration: () => sendSync(IpcEvents.GET_ENABLE_HARDWARE_ACCELERATION), isOutdated: () => invoke(IpcEvents.UPDATER_IS_OUTDATED), openUpdater: () => invoke(IpcEvents.UPDATER_OPEN), // used by vencord getRendererCss: () => invoke(IpcEvents.GET_VESKTOP_RENDERER_CSS), onRendererCssUpdate: (cb: (newCss: string) => void) => { if (!IS_DEV) return; ipcRenderer.on(IpcEvents.VESKTOP_RENDERER_CSS_UPDATE, (_e, newCss: string) => cb(newCss)); } }, autostart: { isEnabled: () => sendSync(IpcEvents.AUTOSTART_ENABLED), enable: () => invoke(IpcEvents.ENABLE_AUTOSTART), disable: () => invoke(IpcEvents.DISABLE_AUTOSTART) }, fileManager: { isUsingCustomVencordDir: () => sendSync(IpcEvents.IS_USING_CUSTOM_VENCORD_DIR), showCustomVencordDir: () => invoke(IpcEvents.SHOW_CUSTOM_VENCORD_DIR), selectVencordDir: (value?: null) => invoke<"cancelled" | "invalid" | "ok">(IpcEvents.SELECT_VENCORD_DIR, value), chooseUserAsset: (asset: string, value?: null) => invoke<"cancelled" | "invalid" | "ok" | "failed">(IpcEvents.CHOOSE_USER_ASSET, asset, value) }, settings: { get: () => sendSync(IpcEvents.GET_SETTINGS), set: (settings: Settings, path?: string) => invoke(IpcEvents.SET_SETTINGS, settings, path) }, spellcheck: { getAvailableLanguages: () => sendSync(IpcEvents.SPELLCHECK_GET_AVAILABLE_LANGUAGES), onSpellcheckResult(cb: SpellCheckerResultCallback) { spellCheckCallbacks.add(cb); }, offSpellcheckResult(cb: SpellCheckerResultCallback) { spellCheckCallbacks.delete(cb); }, replaceMisspelling: (word: string) => invoke(IpcEvents.SPELLCHECK_REPLACE_MISSPELLING, word), addToDictionary: (word: string) => invoke(IpcEvents.SPELLCHECK_ADD_TO_DICTIONARY, word) }, win: { focus: () => invoke(IpcEvents.FOCUS), close: (key?: string) => invoke(IpcEvents.CLOSE, key), minimize: (key?: string) => invoke(IpcEvents.MINIMIZE, key), maximize: (key?: string) => invoke(IpcEvents.MAXIMIZE, key), flashFrame: (flag: boolean) => invoke(IpcEvents.FLASH_FRAME, flag), setDevtoolsCallbacks: (onOpen: () => void, onClose: () => void) => { onDevtoolsOpen = onOpen; onDevtoolsClose = onClose; } }, capturer: { getLargeThumbnail: (id: string) => invoke(IpcEvents.CAPTURER_GET_LARGE_THUMBNAIL, id) }, /** only available on Linux. */ virtmic: { list: () => invoke< { ok: false; isGlibCxxOutdated: boolean } | { ok: true; targets: Node[]; hasPipewirePulse: boolean } >(IpcEvents.VIRT_MIC_LIST), start: (include: Node[]) => invoke(IpcEvents.VIRT_MIC_START, include), startSystem: (exclude: Node[]) => invoke(IpcEvents.VIRT_MIC_START_SYSTEM, exclude), stop: () => invoke(IpcEvents.VIRT_MIC_STOP) }, clipboard: { copyImage: (imageBuffer: Uint8Array, imageSrc: string) => invoke(IpcEvents.CLIPBOARD_COPY_IMAGE, imageBuffer, imageSrc) }, debug: { launchGpu: () => invoke(IpcEvents.DEBUG_LAUNCH_GPU), launchWebrtcInternals: () => invoke(IpcEvents.DEBUG_LAUNCH_WEBRTC_INTERNALS) }, commands: { onCommand(cb: (message: IpcMessage) => void) { ipcRenderer.on(IpcEvents.IPC_COMMAND, (_, message) => cb(message)); }, respond: (response: IpcResponse) => ipcRenderer.send(IpcEvents.IPC_COMMAND, response) } }; ================================================ FILE: src/preload/index.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { contextBridge, ipcRenderer, webFrame } from "electron/renderer"; import { IpcEvents } from "../shared/IpcEvents"; import { VesktopNative } from "./VesktopNative"; contextBridge.exposeInMainWorld("VesktopNative", VesktopNative); // TODO: remove this legacy workaround once some time has passed const isSandboxed = typeof __dirname === "undefined"; if (isSandboxed) { // While sandboxed, Electron "polyfills" these APIs as local variables. // We have to pass them as arguments as they are not global Function( "require", "Buffer", "process", "clearImmediate", "setImmediate", ipcRenderer.sendSync(IpcEvents.GET_VENCORD_PRELOAD_SCRIPT) )(require, Buffer, process, clearImmediate, setImmediate); } else { require(ipcRenderer.sendSync(IpcEvents.DEPRECATED_GET_VENCORD_PRELOAD_SCRIPT_PATH)); } webFrame.executeJavaScript(ipcRenderer.sendSync(IpcEvents.GET_VENCORD_RENDERER_SCRIPT)); webFrame.executeJavaScript(ipcRenderer.sendSync(IpcEvents.GET_VESKTOP_RENDERER_SCRIPT)); ================================================ FILE: src/preload/splash.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { contextBridge, ipcRenderer } from "electron/renderer"; contextBridge.exposeInMainWorld("VesktopSplashNative", { onUpdateMessage(callback: (message: string) => void) { ipcRenderer.on("update-splash-message", (_, message: string) => callback(message)); } }); ================================================ FILE: src/preload/typedIpc.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { ipcRenderer } from "electron/renderer"; import type { IpcEvents, UpdaterIpcEvents } from "shared/IpcEvents"; export function invoke(event: IpcEvents | UpdaterIpcEvents, ...args: any[]) { return ipcRenderer.invoke(event, ...args) as Promise; } export function sendSync(event: IpcEvents | UpdaterIpcEvents, ...args: any[]) { return ipcRenderer.sendSync(event, ...args) as T; } ================================================ FILE: src/preload/updater.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { contextBridge, ipcRenderer } from "electron/renderer"; import type { UpdateInfo } from "electron-updater"; import { UpdaterIpcEvents } from "shared/IpcEvents"; import { invoke } from "./typedIpc"; contextBridge.exposeInMainWorld("VesktopUpdaterNative", { getData: () => invoke(UpdaterIpcEvents.GET_DATA), installUpdate: () => invoke(UpdaterIpcEvents.INSTALL), onProgress: (cb: (percent: number) => void) => { ipcRenderer.on(UpdaterIpcEvents.DOWNLOAD_PROGRESS, (_, percent: number) => cb(percent)); }, onError: (cb: (message: string) => void) => { ipcRenderer.on(UpdaterIpcEvents.ERROR, (_, message: string) => cb(message)); }, snoozeUpdate: () => invoke(UpdaterIpcEvents.SNOOZE_UPDATE), ignoreUpdate: () => invoke(UpdaterIpcEvents.IGNORE_UPDATE) }); ================================================ FILE: src/renderer/appBadge.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { filters, waitFor } from "@vencord/types/webpack"; import { RelationshipStore } from "@vencord/types/webpack/common"; import { VesktopLogger } from "./logger"; import { Settings } from "./settings"; let GuildReadStateStore: any; let NotificationSettingsStore: any; export function setBadge() { if (Settings.store.appBadge === false) return; try { const mentionCount = GuildReadStateStore.getTotalMentionCount(); const pendingRequests = RelationshipStore.getPendingCount(); const hasUnread = GuildReadStateStore.hasAnyUnread(); const disableUnreadBadge = NotificationSettingsStore.getDisableUnreadBadge(); let totalCount = mentionCount + pendingRequests; if (!totalCount && hasUnread && !disableUnreadBadge) totalCount = -1; VesktopNative.app.setBadgeCount(totalCount); } catch (e) { VesktopLogger.error("Failed to update badge count", e); } } let toFind = 3; function waitForAndSubscribeToStore(name: string, cb?: (m: any) => void) { waitFor(filters.byStoreName(name), store => { cb?.(store); store.addChangeListener(setBadge); toFind--; if (toFind === 0) setBadge(); }); } waitForAndSubscribeToStore("GuildReadStateStore", store => (GuildReadStateStore = store)); waitForAndSubscribeToStore("NotificationSettingsStore", store => (NotificationSettingsStore = store)); waitForAndSubscribeToStore("RelationshipStore"); ================================================ FILE: src/renderer/arrpc.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import type arRpcPlugin from "@vencord/types/plugins/arRPC.web"; import { Logger } from "@vencord/types/utils"; import { findLazy, onceReady } from "@vencord/types/webpack"; import { FluxDispatcher, InviteActions, StreamerModeStore } from "@vencord/types/webpack/common"; import { IpcCommands } from "shared/IpcEvents"; import { onIpcCommand } from "./ipcCommands"; import { Settings } from "./settings"; const logger = new Logger("VesktopRPC", "#5865f2"); const arRPC = Vencord.Plugins.plugins["WebRichPresence (arRPC)"] as typeof arRpcPlugin; onIpcCommand(IpcCommands.RPC_ACTIVITY, async jsonData => { if (!Settings.store.arRPC) return; await onceReady; const data = JSON.parse(jsonData); if (data.socketId === "STREAMERMODE" && StreamerModeStore.autoToggle) { FluxDispatcher.dispatch({ type: "STREAMER_MODE_UPDATE", key: "enabled", value: data.activity?.application_id === "STREAMERMODE" }); return; } arRPC.handleEvent(new MessageEvent("message", { data: jsonData })); }); onIpcCommand(IpcCommands.RPC_INVITE, async code => { const { invite } = await InviteActions.resolveInvite(code, "Desktop Modal"); if (!invite) return false; VesktopNative.win.focus(); FluxDispatcher.dispatch({ type: "INVITE_MODAL_OPEN", invite, code, context: "APP" }); return true; }); const { DEEP_LINK } = findLazy(m => m.DEEP_LINK?.handler); onIpcCommand(IpcCommands.RPC_DEEP_LINK, async data => { logger.debug("Opening deep link:", data); try { DEEP_LINK.handler({ args: data }); return true; } catch (err) { logger.error("Failed to open deep link:", err); return false; } }); ================================================ FILE: src/renderer/components/ScreenSharePicker.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import "./screenSharePicker.css"; import { classNameFactory } from "@vencord/types/api/Styles"; import { BaseText, Button, Card, CogWheel, FormSwitch, Heading, HeadingTertiary, Margins, Paragraph, RestartIcon, Span } from "@vencord/types/components"; import { closeModal, Logger, ModalCloseButton, Modals, ModalSize, openModal, useAwaiter, useForceUpdater } from "@vencord/types/utils"; import { onceReady } from "@vencord/types/webpack"; import { FluxDispatcher, MediaEngineStore, Select, UserStore, useState } from "@vencord/types/webpack/common"; import { Node } from "@vencord/venmic"; import type { Dispatch, SetStateAction } from "react"; import { addPatch } from "renderer/patches/shared"; import { State, useSettings, useVesktopState } from "renderer/settings"; import { isLinux, isWindows } from "renderer/utils"; import { SimpleErrorBoundary } from "./SimpleErrorBoundary"; const StreamResolutions = ["480", "720", "1080", "1440", "2160"] as const; const StreamFps = ["15", "30", "60"] as const; const cl = classNameFactory("vcd-screen-picker-"); export type StreamResolution = (typeof StreamResolutions)[number]; export type StreamFps = (typeof StreamFps)[number]; type SpecialSource = "None" | "Entire System"; type AudioSource = SpecialSource | Node; type AudioSources = SpecialSource | Node[]; interface AudioItem { name: string; value: AudioSource; } interface StreamSettings { audio: boolean; contentHint?: string; includeSources?: AudioSources; excludeSources?: AudioSources; } export interface StreamPick extends StreamSettings { id: string; } interface Source { id: string; name: string; url: string; } export let currentSettings: StreamSettings | null = null; const logger = new Logger("VesktopScreenShare"); addPatch({ patches: [ { find: "this.getDefaultGoliveQuality()", replacement: { match: /this\.getDefaultGoliveQuality\(\)/, replace: "$self.patchStreamQuality($&)" } } ], patchStreamQuality(opts: any) { const { screenshareQuality } = State.store; if (!screenshareQuality) return opts; const framerate = Number(screenshareQuality.frameRate); const height = Number(screenshareQuality.resolution); const width = Math.round(height * (16 / 9)); Object.assign(opts, { bitrateMin: 500000, bitrateMax: 8000000, bitrateTarget: 600000 }); if (opts?.encode) { Object.assign(opts.encode, { framerate, width, height, pixelCount: height * width }); } Object.assign(opts.capture, { framerate, width, height, pixelCount: height * width }); return opts; } }); if (isLinux) { onceReady.then(() => { FluxDispatcher.subscribe("STREAM_CLOSE", ({ streamKey }: { streamKey: string }) => { const owner = streamKey.split(":").at(-1); if (owner !== UserStore.getCurrentUser().id) { return; } VesktopNative.virtmic.stop(); }); }); } export function openScreenSharePicker(screens: Source[], skipPicker: boolean) { let didSubmit = false; return new Promise((resolve, reject) => { const key = openModal( props => ( { didSubmit = true; if (v.includeSources && v.includeSources !== "None") { if (v.includeSources === "Entire System") { await VesktopNative.virtmic.startSystem( !v.excludeSources || isSpecialSource(v.excludeSources) ? [] : v.excludeSources ); } else { await VesktopNative.virtmic.start(v.includeSources); } } resolve(v); }} close={() => { props.onClose(); if (!didSubmit) reject("Aborted"); }} skipPicker={skipPicker} /> ), { onCloseRequest() { closeModal(key); reject("Aborted"); }, onCloseCallback() { if (!didSubmit) reject("Aborted"); } } ); }); } function ScreenPicker({ screens, chooseScreen }: { screens: Source[]; chooseScreen: (id: string) => void }) { return (
{screens.map(({ id, name, url }) => ( ))}
); } function AudioSettingsModal({ modalProps, close, setAudioSources }: { modalProps: any; close: () => void; setAudioSources: (s: AudioSources) => void; }) { const Settings = useSettings(); return ( Audio Settings (Settings.audio = { ...Settings.audio, workaround: v })} value={Settings.audio?.workaround ?? false} /> (Settings.audio = { ...Settings.audio, onlySpeakers: v })} value={Settings.audio?.onlySpeakers ?? true} /> When sharing entire desktop audio, only share apps that play to the default speakers. You may want to disable this when using "mix bussing". } hideBorder onChange={v => (Settings.audio = { ...Settings.audio, onlyDefaultSpeakers: v })} value={Settings.audio?.onlyDefaultSpeakers ?? true} /> (Settings.audio = { ...Settings.audio, ignoreInputMedia: v })} value={Settings.audio?.ignoreInputMedia ?? true} /> (Settings.audio = { ...Settings.audio, ignoreVirtual: v })} value={Settings.audio?.ignoreVirtual ?? false} /> (Settings.audio = { ...Settings.audio, ignoreDevices: v, deviceSelect: v ? false : Settings.audio?.deviceSelect }) } value={Settings.audio?.ignoreDevices ?? true} /> { Settings.audio = { ...Settings.audio, granularSelect: value }; setAudioSources("None"); }} value={Settings.audio?.granularSelect ?? false} /> Allow to select devices such as microphones. Requires Ignore Devices to be turned off. } hideBorder onChange={value => { Settings.audio = { ...Settings.audio, deviceSelect: value }; setAudioSources("None"); }} value={Settings.audio?.deviceSelect ?? false} disabled={Settings.audio?.ignoreDevices} /> ); } function OptionRadio(props: { options: Array | ReadonlyArray; labels?: Array; settings: Settings; settingsKey: Key; onChange: (option: string) => void; }) { const { options, settings, settingsKey, labels, onChange } = props; return (
{(options as string[]).map((option, idx) => ( ))}
); } function StreamSettingsUi({ source, settings, setSettings, skipPicker }: { source: Source; settings: StreamSettings; setSettings: Dispatch>; skipPicker: boolean; }) { const Settings = useSettings(); const qualitySettings = State.store.screenshareQuality!; const [thumb] = useAwaiter( () => (skipPicker ? Promise.resolve(source.url) : VesktopNative.capturer.getLargeThumbnail(source.id)), { fallbackValue: source.url, deps: [source.id] } ); const openSettings = () => { openModal(props => ( props.onClose()} setAudioSources={sources => setSettings(s => ({ ...s, includeSources: sources, excludeSources: sources })) } /> )); }; return (
What you're streaming {source.name} Stream Settings
Resolution (qualitySettings.resolution = value)} />
Frame Rate (qualitySettings.frameRate = value)} />
Content Type
setSettings(s => ({ ...s, contentHint: option }))} /> Choosing "Prefer Clarity" will result in a significantly lower framerate in exchange for a much sharper and clearer image.
{isWindows && ( setSettings(s => ({ ...s, audio: checked }))} className={cl("audio")} /> )}
{isLinux && ( setSettings(s => ({ ...s, includeSources: sources }))} setExcludeSources={sources => setSettings(s => ({ ...s, excludeSources: sources }))} /> )}
); } function isSpecialSource(value?: AudioSource | AudioSources): value is SpecialSource { return typeof value === "string"; } function hasMatchingProps(value: Node, other: Node) { return Object.keys(value).every(key => value[key] === other[key]); } function mapToAudioItem(node: AudioSource, granularSelect?: boolean, deviceSelect?: boolean): AudioItem[] { if (isSpecialSource(node)) { return [{ name: node, value: node }]; } const rtn: AudioItem[] = []; const mediaClass = node["media.class"]; if (mediaClass?.includes("Video") || mediaClass?.includes("Midi")) { return rtn; } if (!deviceSelect && node["device.id"]) { return rtn; } const name = node["application.name"]; if (name) { rtn.push({ name: name, value: { "application.name": name } }); } if (!granularSelect) { return rtn; } const rawName = node["node.name"]; if (!name) { rtn.push({ name: rawName, value: { "node.name": rawName } }); } const binary = node["application.process.binary"]; if (!name && binary) { rtn.push({ name: binary, value: { "application.process.binary": binary } }); } const pid = node["application.process.id"]; const first = rtn[0]; const firstValues = first.value as Node; if (pid) { rtn.push({ name: `${first.name} (${pid})`, value: { ...firstValues, "application.process.id": pid } }); } const mediaName = node["media.name"]; if (mediaName) { rtn.push({ name: `${first.name} [${mediaName}]`, value: { ...firstValues, "media.name": mediaName } }); } if (mediaClass) { rtn.push({ name: `${first.name} [${mediaClass}]`, value: { ...firstValues, "media.class": mediaClass } }); } return rtn; } function isItemSelected(sources?: AudioSources) { return (value: AudioSource) => { if (!sources) { return false; } if (isSpecialSource(sources) || isSpecialSource(value)) { return sources === value; } return sources.some(source => hasMatchingProps(source, value)); }; } function updateItems(setSources: (s: AudioSources) => void, sources?: AudioSources) { return (value: AudioSource) => { if (isSpecialSource(value)) { setSources(value); return; } if (isSpecialSource(sources)) { setSources([value]); return; } if (isItemSelected(sources)(value)) { setSources(sources?.filter(x => !hasMatchingProps(x, value)) ?? "None"); return; } setSources([...(sources || []), value]); }; } function AudioSourcePickerLinux({ includeSources, excludeSources, deviceSelect, granularSelect, openSettings, setIncludeSources, setExcludeSources }: { includeSources?: AudioSources; excludeSources?: AudioSources; deviceSelect?: boolean; granularSelect?: boolean; openSettings: () => void; setIncludeSources: (s: AudioSources) => void; setExcludeSources: (s: AudioSources) => void; }) { const [audioSourcesSignal, refreshAudioSources] = useForceUpdater(true); const [sources, _, loading] = useAwaiter(() => VesktopNative.virtmic.list(), { fallbackValue: { ok: true, targets: [], hasPipewirePulse: true }, deps: [audioSourcesSignal] }); const hasPipewirePulse = sources.ok ? sources.hasPipewirePulse : true; const [ignorePulseWarning, setIgnorePulseWarning] = useState(false); if (!sources.ok && sources.isGlibCxxOutdated) { return ( Failed to retrieve Audio Sources because your C++ library is too old to run venmic . See{" "} this guide {" "} for possible solutions. ); } if (!hasPipewirePulse && !ignorePulseWarning) { return ( Could not find pipewire-pulse. See{" "} this guide {" "} on how to switch to pipewire.
You can still continue, however, please{" "} beware that you can only share audio of apps that are running under pipewire.{" "} setIgnorePulseWarning(true)}>I know what I'm doing!
); } const specialSources: SpecialSource[] = ["None", "Entire System"] as const; const uniqueName = (value: AudioItem, index: number, list: AudioItem[]) => list.findIndex(x => x.name === value.name) === index; const allSources = sources.ok ? [...specialSources, ...sources.targets] .map(target => mapToAudioItem(target, granularSelect, deviceSelect)) .flat() .filter(uniqueName) : []; return ( <>
{loading ? "Loading Sources..." : "Audio Sources"} x.name !== "Entire System") .map(({ name, value }) => ({ label: name, value: value, default: name === "None" }))} isSelected={isItemSelected(excludeSources)} select={updateItems(setExcludeSources, excludeSources)} serialize={String} popoutPosition="top" closeOnSelect={false} />
)}
); } function ModalComponent({ screens, modalProps, submit, close, skipPicker }: { screens: Source[]; modalProps: any; submit: (data: StreamPick) => void; close: () => void; skipPicker: boolean; }) { const [selected, setSelected] = useState(skipPicker ? screens[0].id : void 0); const [settings, setSettings] = useState({ contentHint: "motion", audio: true, includeSources: "None" }); const qualitySettings = (useVesktopState().screenshareQuality ??= { resolution: "720", frameRate: "30" }); return ( Screen Share Picker {!selected ? ( ) : ( s.id === selected)!} settings={settings} setSettings={setSettings} skipPicker={skipPicker} /> )} {selected && !skipPicker ? ( ) : ( )} ); } ================================================ FILE: src/renderer/components/SimpleErrorBoundary.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Card, ErrorBoundary, HeadingTertiary, Paragraph, TextButton } from "@vencord/types/components"; import { FluxDispatcher, InviteActions } from "@vencord/types/webpack/common"; import type { PropsWithChildren } from "react"; async function openSupportChannel() { const code = "YVbdG2ZRG4"; try { const { invite } = await InviteActions.resolveInvite(code, "Desktop Modal"); if (!invite) throw 0; await FluxDispatcher.dispatch({ type: "INVITE_MODAL_OPEN", invite, code, context: "APP" }); } catch { window.open(`https://discord.gg/${code}`, "_blank"); } } function Fallback() { return ( Something went wrong. Please make sure Vencord and Vesktop are fully up to date. You can get help in our{" "} Support Channel ); } export function SimpleErrorBoundary({ children }: PropsWithChildren<{}>) { return {children}; } ================================================ FILE: src/renderer/components/index.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ export * as ScreenShare from "./ScreenSharePicker"; ================================================ FILE: src/renderer/components/screenSharePicker.css ================================================ .vcd-screen-picker-modal { padding: 1em; } .vcd-screen-picker-header-close-button { margin-left: auto; } .vcd-screen-picker-venmic-settings { display: grid; gap: 8px; } .vcd-screen-picker-footer { display: flex; gap: 1em; } .vcd-screen-picker-card { flex-grow: 1; } /* Screen Grid */ .vcd-screen-picker-screen-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 2em 1em; } .vcd-screen-picker-screen-radio { appearance: none; cursor: pointer; } .vcd-screen-picker-screen-label { overflow: hidden; padding: 8px; cursor: pointer; display: grid; justify-items: center; } .vcd-screen-picker-screen-label:hover { outline: 2px solid var(--brand-500); } .vcd-screen-picker-screen-name { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; text-align: center; font-weight: 600; margin-inline: 0.5em; } .vcd-screen-picker-card { padding: 0.5em; box-sizing: border-box; } .vcd-screen-picker-preview-img-linux { width: 60%; margin-bottom: 0.5em; } .vcd-screen-picker-preview-img { width: 90%; margin-bottom: 0.5em; } .vcd-screen-picker-preview { display: flex; flex-direction: column; justify-content: center; align-items: center; margin-bottom: 1em; } /* Option Radios */ .vcd-screen-picker-option-radios { display: grid; grid-template-columns: repeat(auto-fit, minmax(0, 1fr)); width: 100%; border-radius: 3px; } .vcd-screen-picker-option-radio { text-align: center; background-color: var(--background-secondary); border: 1px solid var(--primary-800); padding: 0.3em; cursor: pointer; } .vcd-screen-picker-option-radio:first-child { border-radius: 3px 0 0 3px; } .vcd-screen-picker-option-radio:last-child { border-radius: 0 3px 3px 0; } .vcd-screen-picker-option-input { display: none; } .vcd-screen-picker-option-radio[data-checked="true"] { background-color: var(--brand-500); border-color: var(--brand-500); } .vcd-screen-picker-quality { display: flex; gap: 1em; margin-bottom: 0.5em; } .vcd-screen-picker-quality-section { flex: 1 1 auto; } .vcd-screen-picker-settings-buttons { display: flex; justify-content: end; gap: 0.5em; margin-top: 0.75em; } .vcd-screen-picker-settings-button { display: flex; gap: 0.25em; padding-inline: 0.5em 1em; } .vcd-screen-picker-settings-button-icon { height: 1em; } .vcd-screen-picker-audio { margin-bottom: 0; } .vcd-screen-picker-audio-sources { display: flex; gap: 1em; >section { flex: 1; } } ================================================ FILE: src/renderer/components/settings/AutoStartToggle.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { useState } from "@vencord/types/webpack/common"; import { SettingsComponent } from "./Settings"; import { VesktopSettingsSwitch } from "./VesktopSettingsSwitch"; export const AutoStartToggle: SettingsComponent = ({ settings }) => { const [autoStartEnabled, setAutoStartEnabled] = useState(VesktopNative.autostart.isEnabled()); return ( <> { await VesktopNative.autostart[v ? "enable" : "disable"](); setAutoStartEnabled(v); }} /> (settings.autoStartMinimized = v)} disabled={!autoStartEnabled} /> ); }; ================================================ FILE: src/renderer/components/settings/DeveloperOptions.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { BaseText, Button, Heading, Paragraph, TextButton } from "@vencord/types/components"; import { Margins, ModalCloseButton, ModalContent, ModalHeader, ModalRoot, ModalSize, openModal, useForceUpdater } from "@vencord/types/utils"; import { Toasts } from "@vencord/types/webpack/common"; import { Settings } from "shared/settings"; import { cl, SettingsComponent } from "./Settings"; export const DeveloperOptionsButton: SettingsComponent = ({ settings }) => { return ; }; function openDeveloperOptionsModal(settings: Settings) { openModal(props => ( Vesktop Developer Options
Vencord Location Debugging
)); } const VencordLocationPicker: SettingsComponent = ({ settings }) => { const forceUpdate = useForceUpdater(); const usingCustomVencordDir = VesktopNative.fileManager.isUsingCustomVencordDir(); return ( <> Vencord files are loaded from{" "} {usingCustomVencordDir ? ( { e.preventDefault(); VesktopNative.fileManager.showCustomVencordDir(); }} > a custom location ) : ( "the default location" )}
); }; ================================================ FILE: src/renderer/components/settings/DiscordBranchPicker.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Select } from "@vencord/types/webpack/common"; import { SimpleErrorBoundary } from "../SimpleErrorBoundary"; import { SettingsComponent } from "./Settings"; export const DiscordBranchPicker: SettingsComponent = ({ settings }) => { return ( (settings.transparencyOption = v)} isSelected={v => v === settings.transparencyOption} serialize={s => s} /> ); }; ================================================ FILE: src/renderer/components/settings/settings.css ================================================ .vcd-settings-button-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5em; margin-top: 0.5em; } .vcd-settings-title { margin-bottom: 32px; } .vcd-settings-category { display: flex; flex-direction: column; } .vcd-settings-category-title { margin-bottom: 16px; } .vcd-settings-category-content { display: flex; flex-direction: column; gap: 24px; } .vcd-settings-category-divider { margin-top: 32px; margin-bottom: 32px; } .vcd-settings-switch { margin-bottom: 0; } .vcd-settings-updater-card { padding: 1em; margin-bottom: 1em; display: grid; gap: 0.5em; } ================================================ FILE: src/renderer/fixes.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { localStorage } from "./utils"; // Make clicking Notifications focus the window const originalSetOnClick = Object.getOwnPropertyDescriptor(Notification.prototype, "onclick")!.set!; Object.defineProperty(Notification.prototype, "onclick", { set(onClick) { originalSetOnClick.call(this, function (this: unknown) { onClick.apply(this, arguments); VesktopNative.win.focus(); }); }, configurable: true }); // Hide "Download Discord Desktop now!!!!" banner localStorage.setItem("hideNag", "true"); ================================================ FILE: src/renderer/index.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import "./themedSplash"; import "./ipcCommands"; import "./appBadge"; import "./fixes"; import "./arrpc"; import "__patches__"; // auto generated by the build script export * as Components from "./components"; import SettingsUi from "./components/settings/Settings"; import { VesktopLogger } from "./logger"; import { Settings } from "./settings"; export { Settings }; import type SettingsPlugin from "@vencord/types/plugins/_core/settings"; VesktopLogger.log("read if cute :3"); VesktopLogger.log("Vesktop v" + VesktopNative.app.getVersion()); // TODO const customSettingsSections = (Vencord.Plugins.plugins.Settings as typeof SettingsPlugin).customSections; customSettingsSections.push(() => ({ section: "Vesktop", label: "Vesktop Settings", element: SettingsUi, className: "vc-vesktop-settings" })); // TODO: remove this legacy workaround once some time has passed if (!Vencord.Api.Styles.vencordRootNode) { const style = document.createElement("style"); style.id = "vesktop-css-core"; VesktopNative.app.getRendererCss().then(css => (style.textContent = css)); document.addEventListener("DOMContentLoaded", () => document.documentElement.append(style), { once: true }); } ================================================ FILE: src/renderer/ipcCommands.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { SettingsRouter } from "@vencord/types/webpack/common"; import { IpcCommands } from "shared/IpcEvents"; import { openScreenSharePicker } from "./components/ScreenSharePicker"; type IpcCommandHandler = (data: any) => any; const handlers = new Map(); function respond(nonce: string, ok: boolean, data: any) { VesktopNative.commands.respond({ nonce, ok, data }); } VesktopNative.commands.onCommand(async ({ message, nonce, data }) => { const handler = handlers.get(message); if (!handler) { return respond(nonce, false, `No handler for message: ${message}`); } try { const result = await handler(data); respond(nonce, true, result); } catch (err) { respond(nonce, false, String(err)); } }); export function onIpcCommand(channel: string, handler: IpcCommandHandler) { if (handlers.has(channel)) { throw new Error(`Handler for message ${channel} already exists`); } handlers.set(channel, handler); } export function offIpcCommand(channel: string) { handlers.delete(channel); } /* Generic Handlers */ onIpcCommand(IpcCommands.NAVIGATE_SETTINGS, () => { SettingsRouter.open("My Account"); }); onIpcCommand(IpcCommands.GET_LANGUAGES, () => navigator.languages); onIpcCommand(IpcCommands.SCREEN_SHARE_PICKER, data => openScreenSharePicker(data.screens, data.skipPicker)); ================================================ FILE: src/renderer/logger.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Logger } from "@vencord/types/utils"; export const VesktopLogger = new Logger("Vesktop", "#d3869b"); ================================================ FILE: src/renderer/patches/devtoolsFixes.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { addPatch } from "./shared"; addPatch({ patches: [ // Discord Web blocks the devtools keybin on mac specifically, disable that { find: '"mod+alt+i"', replacement: { match: /"discord\.com"===location\.host/, replace: "false" } }, // Discord Web uses an incredibly broken devtools detector with false positives. // They "hide" (aka remove from storage) your token if it "detects" open devtools. // Due to the false positives, this leads to random logouts. // Patch their devtools detection to use proper Electron APIs instead to fix the false positives { find: ".setDevtoolsCallbacks(", group: true, replacement: [ { match: /if\(null!=(\i)\)(?=.{0,50}\1\.window\.setDevtoolsCallbacks)/, replace: "if(true)" }, { match: /\b\i\.window\.setDevtoolsCallbacks/g, replace: "VesktopNative.win.setDevtoolsCallbacks" } ] } ] }); ================================================ FILE: src/renderer/patches/enableNotificationsByDefault.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { addPatch } from "./shared"; addPatch({ patches: [ { find: '"NotificationSettingsStore', replacement: { match: /\.isPlatformEmbedded(?=\?\i\.\i\.ALL)/g, replace: "$&||true" } } ] }); ================================================ FILE: src/renderer/patches/fixStreamConstraints.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Logger } from "@vencord/types/utils"; import { MediaEngineStore } from "@vencord/types/webpack/common"; const logger = new Logger("VesktopStreamFixes"); function fixAudioTrackConstraints(constraint: MediaTrackConstraints) { const target = constraint.advanced?.find(opt => Object.hasOwn(opt, "autoGainControl")) ?? constraint; target.autoGainControl = MediaEngineStore.getAutomaticGainControl(); } function fixVideoTrackConstraints(constraint: MediaTrackConstraints) { if (typeof constraint.deviceId === "string" && constraint.deviceId !== "default") { constraint.deviceId = { exact: constraint.deviceId }; } } function fixStreamConstraints(constraints: MediaStreamConstraints | undefined) { if (!constraints) return; if (constraints.audio) { if (typeof constraints.audio !== "object") { constraints.audio = {}; } fixAudioTrackConstraints(constraints.audio); } if (constraints.video) { if (typeof constraints.video !== "object") { constraints.video = {}; } fixVideoTrackConstraints(constraints.video); } } const originalGetUserMedia = navigator.mediaDevices.getUserMedia; navigator.mediaDevices.getUserMedia = function (constraints) { try { fixStreamConstraints(constraints); } catch (e) { logger.error("Failed to fix getUserMedia constraints", e); } return originalGetUserMedia.call(this, constraints); }; const originalApplyConstraints = MediaStreamTrack.prototype.applyConstraints; MediaStreamTrack.prototype.applyConstraints = function (constraints) { if (constraints) { try { if (this.kind === "audio") { fixAudioTrackConstraints(constraints); } else if (this.kind === "video") { fixVideoTrackConstraints(constraints); } } catch (e) { logger.error("Failed to fix constraints", e); } } return originalApplyConstraints.call(this, constraints); }; ================================================ FILE: src/renderer/patches/hideDownloadAppsButton.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { addPatch } from "./shared"; addPatch({ patches: [ { find: '"app-download-button"', replacement: { match: /return(?=.{0,50}id:"app-download-button")/, replace: "return null;return" } } ] }); ================================================ FILE: src/renderer/patches/hideSwitchDevice.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { addPatch } from "./shared"; addPatch({ patches: [ { find: "lastOutputSystemDevice.justChanged", replacement: { match: /(\i)\.\i\.getState\(\).neverShowModal/, replace: "$& || $self.shouldIgnoreDevice($1)" } } ], shouldIgnoreDevice(state: any) { return Object.keys(state?.default?.lastDeviceConnected ?? {})?.[0] === "vencord-screen-share"; } }); ================================================ FILE: src/renderer/patches/hideVenmicInput.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { addPatch } from "./shared"; addPatch({ patches: [ { find: 'setSinkId"in', replacement: { match: /return (\i)\?navigator\.mediaDevices\.enumerateDevices/, replace: "return $1 ? $self.filteredDevices" } } ], async filteredDevices() { const original = await navigator.mediaDevices.enumerateDevices(); return original.filter(x => x.label !== "vencord-screen-share"); } }); ================================================ FILE: src/renderer/patches/platformClass.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Settings } from "renderer/settings"; import { isMac } from "renderer/utils"; import { addPatch } from "./shared"; addPatch({ patches: [ { find: "platform-web", replacement: { match: '"platform-web"', replace: "$self.getPlatformClass()" } } ], getPlatformClass() { if (Settings.store.customTitleBar) return "platform-win"; if (isMac) return "platform-osx"; return "platform-web"; } }); ================================================ FILE: src/renderer/patches/screenShareFixes.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Logger } from "@vencord/types/utils"; import { currentSettings } from "renderer/components/ScreenSharePicker"; import { State } from "renderer/settings"; import { isLinux } from "renderer/utils"; const logger = new Logger("VesktopStreamFixes"); if (isLinux) { const original = navigator.mediaDevices.getDisplayMedia; async function getVirtmic() { try { const devices = await navigator.mediaDevices.enumerateDevices(); const audioDevice = devices.find(({ label }) => label === "vencord-screen-share"); return audioDevice?.deviceId; } catch (error) { return null; } } navigator.mediaDevices.getDisplayMedia = async function (opts) { const stream = await original.call(this, opts); const id = await getVirtmic(); const frameRate = Number(State.store.screenshareQuality?.frameRate ?? 30); const height = Number(State.store.screenshareQuality?.resolution ?? 720); const width = Math.round(height * (16 / 9)); const track = stream.getVideoTracks()[0]; track.contentHint = String(currentSettings?.contentHint); const constraints = { ...track.getConstraints(), frameRate: { min: frameRate, ideal: frameRate }, width: { min: 640, ideal: width, max: width }, height: { min: 480, ideal: height, max: height }, advanced: [{ width: width, height: height }], resizeMode: "none" }; track .applyConstraints(constraints) .then(() => { logger.info("Applied constraints successfully. New constraints: ", track.getConstraints()); }) .catch(e => logger.error("Failed to apply constraints.", e)); if (id) { const audio = await navigator.mediaDevices.getUserMedia({ audio: { deviceId: { exact: id }, autoGainControl: false, echoCancellation: false, noiseSuppression: false, channelCount: 2, sampleRate: 48000, sampleSize: 16 } }); stream.getAudioTracks().forEach(t => stream.removeTrack(t)); stream.addTrack(audio.getAudioTracks()[0]); } return stream; }; } ================================================ FILE: src/renderer/patches/shared.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Patch } from "@vencord/types/utils/types"; window.VesktopPatchGlobals = {}; interface PatchData { patches: Omit[]; [key: string]: any; } export function addPatch

(p: P) { const { patches, ...globals } = p; for (const patch of patches) { Vencord.Plugins.addPatch(patch, "Vesktop", "VesktopPatchGlobals"); } Object.assign(VesktopPatchGlobals, globals); } ================================================ FILE: src/renderer/patches/spellCheck.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { addContextMenuPatch } from "@vencord/types/api/ContextMenu"; import { FluxDispatcher, Menu, SpellCheckStore, useMemo, useStateFromStores } from "@vencord/types/webpack/common"; import { useSettings } from "renderer/settings"; import { addPatch } from "./shared"; let word: string; let corrections: string[]; // Make spellcheck suggestions work addPatch({ patches: [ { find: ".enableSpellCheck", replacement: { // if (settings?.enableSpellCheck && isDesktop) { DiscordNative.onSpellcheck(openMenu(props)) } else { e.preventDefault(); openMenu(props) } match: /else (\i)\.preventDefault\(\),(\i\(\i\))(?<=(\i)\??\.enableSpellCheck.+?)/, replace: "else $self.onSlateContext($1, $3?.enableSpellCheck, () => $2)" } } ], onSlateContext(e: MouseEvent, hasSpellcheck: boolean | undefined, openMenu: () => void) { if (!hasSpellcheck) { e.preventDefault(); openMenu(); return; } const cb = (w: string, c: string[]) => { VesktopNative.spellcheck.offSpellcheckResult(cb); word = w; corrections = c; openMenu(); }; VesktopNative.spellcheck.onSpellcheckResult(cb); } }); addContextMenuPatch("textarea-context", children => { const spellCheckEnabled = useStateFromStores([SpellCheckStore], () => SpellCheckStore.isEnabled()); const hasCorrections = Boolean(word && corrections?.length); const availableLanguages = useMemo(VesktopNative.spellcheck.getAvailableLanguages, []); const settings = useSettings(); const spellCheckLanguages = (settings.spellCheckLanguages ??= [...new Set(navigator.languages)]); const pasteSectionIndex = children.findIndex(c => c?.props?.children?.some?.(c => c?.props?.id === "paste")); children.splice( pasteSectionIndex === -1 ? children.length : pasteSectionIndex, 0, {hasCorrections && ( <> {corrections.map(c => ( VesktopNative.spellcheck.replaceMisspelling(c)} /> ))} VesktopNative.spellcheck.addToDictionary(word)} /> )} { FluxDispatcher.dispatch({ type: "SPELLCHECK_TOGGLE" }); }} /> {availableLanguages.map(lang => { const isEnabled = spellCheckLanguages.includes(lang); return ( = 5} action={() => { const newSpellCheckLanguages = spellCheckLanguages.filter(l => l !== lang); if (newSpellCheckLanguages.length === spellCheckLanguages.length) { newSpellCheckLanguages.push(lang); } settings.spellCheckLanguages = newSpellCheckLanguages; }} /> ); })} ); }); ================================================ FILE: src/renderer/patches/streamerMode.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { addPatch } from "./shared"; addPatch({ patches: [ { find: ".STREAMING_AUTO_STREAMER_MODE,", replacement: { // remove if (platformEmbedded) check from streamer mode toggle match: /(?<=usePredicate.{0,20}?return )\i\.\i/g, replace: "true" } } ] }); ================================================ FILE: src/renderer/patches/taskBarFlash.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Settings } from "renderer/settings"; import { addPatch } from "./shared"; addPatch({ patches: [ { find: ".flashFrame(!0)", replacement: { match: /(\i)&&\i\.\i\.taskbarFlash&&\i\.\i\.flashFrame\(!0\)/, replace: "$self.flashFrame()" } } ], flashFrame() { if (Settings.store.enableTaskbarFlashing) { VesktopNative.win.flashFrame(true); } } }); ================================================ FILE: src/renderer/patches/windowMethods.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { addPatch } from "./shared"; addPatch({ patches: [ { find: ",setSystemTrayApplications", replacement: [ { match: /\i\.window\.(close|minimize|maximize)/g, replace: `VesktopNative.win.$1` }, { match: /(focus(\(\i\)){).{0,150}?\.focus\(\i,\i\)/, replace: "$1VesktopNative.win.focus$2" }, { match: /,getEnableHardwareAcceleration/, replace: "$&:VesktopNative.app.getEnableHardwareAcceleration,_oldGetEnableHardwareAcceleration" } ] } ] }); ================================================ FILE: src/renderer/patches/windowsTitleBar.tsx ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Settings } from "renderer/settings"; import { addPatch } from "./shared"; if (Settings.store.customTitleBar) addPatch({ patches: [ { find: ".USE_OSX_NATIVE_TRAFFIC_LIGHTS", replacement: [ { match: /case \i\.\i\.WINDOWS:/, replace: 'case "WEB":' } ] }, // Visual Refresh { find: '"refresh-title-bar-small"', replacement: [ { match: /\i===\i\.PlatformTypes\.WINDOWS/g, replace: "true" }, { match: /\i===\i\.PlatformTypes\.WEB/g, replace: "false" } ] } ] }); ================================================ FILE: src/renderer/settings.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { useEffect, useReducer } from "@vencord/types/webpack/common"; import { SettingsStore } from "shared/utils/SettingsStore"; import { VesktopLogger } from "./logger"; import { localStorage } from "./utils"; export const Settings = new SettingsStore(VesktopNative.settings.get()); Settings.addGlobalChangeListener((o, p) => VesktopNative.settings.set(o, p)); export function useSettings() { const [, update] = useReducer(x => x + 1, 0); useEffect(() => { Settings.addGlobalChangeListener(update); return () => Settings.removeGlobalChangeListener(update); }, []); return Settings.store; } export function getValueAndOnChange(key: keyof typeof Settings.store) { return { value: Settings.store[key] as any, onChange: (value: any) => (Settings.store[key] = value) }; } interface TState { screenshareQuality?: { resolution: string; frameRate: string; }; } const stateKey = "VesktopState"; const currentState: TState = (() => { const stored = localStorage.getItem(stateKey); if (!stored) return {}; try { return JSON.parse(stored); } catch (e) { VesktopLogger.error("Failed to parse stored state", e); return {}; } })(); export const State = new SettingsStore(currentState); State.addGlobalChangeListener((o, p) => localStorage.setItem(stateKey, JSON.stringify(o))); export function useVesktopState() { const [, update] = useReducer(x => x + 1, 0); useEffect(() => { State.addGlobalChangeListener(update); return () => State.removeGlobalChangeListener(update); }, []); return State.store; } ================================================ FILE: src/renderer/themedSplash.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { Settings } from "./settings"; function isValidColor(color: CSSStyleValue | undefined): color is CSSUnparsedValue & { [0]: string } { return color instanceof CSSUnparsedValue && typeof color[0] === "string" && CSS.supports("color", color[0]); } // https://gist.github.com/earthbound19/e7fe15fdf8ca3ef814750a61bc75b5ce function clamp(value: number, min: number, max: number) { return Math.max(Math.min(value, max), min); } const linearToGamma = (c: number) => (c >= 0.0031308 ? 1.055 * Math.pow(c, 1 / 2.4) - 0.055 : 12.92 * c); function oklabToSRGB({ L, a, b }: { L: number; a: number; b: number }) { let l = L + a * +0.3963377774 + b * +0.2158037573; let m = L + a * -0.1055613458 + b * -0.0638541728; let s = L + a * -0.0894841775 + b * -1.291485548; l **= 3; m **= 3; s **= 3; let R = l * +4.0767416621 + m * -3.3077115913 + s * +0.2309699292; let G = l * -1.2684380046 + m * +2.6097574011 + s * -0.3413193965; let B = l * -0.0041960863 + m * -0.7034186147 + s * +1.707614701; R = 255 * linearToGamma(R); G = 255 * linearToGamma(G); B = 255 * linearToGamma(B); R = Math.round(clamp(R, 0, 255)); G = Math.round(clamp(G, 0, 255)); B = Math.round(clamp(B, 0, 255)); return `rgb(${R}, ${G}, ${B})`; } function resolveColor(color: string) { const span = document.createElement("span"); span.style.color = color; span.style.display = "none"; document.body.append(span); let rgbColor = getComputedStyle(span).color; span.remove(); if (rgbColor.startsWith("oklab(")) { // scam const [_, L, a, b] = rgbColor.match(/oklab\((.+?)[, ]+(.+?)[, ]+(.+?)\)/) ?? []; if (L && a && b) { rgbColor = oklabToSRGB({ L: parseFloat(L), a: parseFloat(a), b: parseFloat(b) }); } } return rgbColor; } const updateSplashColors = () => { const bodyStyles = document.body.computedStyleMap(); const color = bodyStyles.get("--text-default"); const backgroundColor = bodyStyles.get("--background-base-lowest"); if (isValidColor(color)) { Settings.store.splashColor = resolveColor(color[0]); } if (isValidColor(backgroundColor)) { Settings.store.splashBackground = resolveColor(backgroundColor[0]); } }; if (document.readyState === "complete") { updateSplashColors(); } else { window.addEventListener("load", updateSplashColors); } window.addEventListener("beforeunload", updateSplashColors); ================================================ FILE: src/renderer/utils.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ // Discord deletes this from the window so we need to capture it in a variable export const { localStorage } = window; export const isFirstRun = (() => { const key = "VCD_FIRST_RUN"; if (localStorage.getItem(key) !== null) return false; localStorage.setItem(key, "false"); return true; })(); const { platform } = navigator; export const isWindows = platform.startsWith("Win"); export const isMac = platform.startsWith("Mac"); export const isLinux = platform.startsWith("Linux"); ================================================ FILE: src/shared/IpcEvents.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ export const enum IpcEvents { GET_VENCORD_PRELOAD_SCRIPT = "VCD_GET_VC_PRELOAD_SCRIPT", DEPRECATED_GET_VENCORD_PRELOAD_SCRIPT_PATH = "DEPRECATED_GET_VENCORD_PRELOAD_SCRIPT_PATH", GET_VENCORD_RENDERER_SCRIPT = "VCD_GET_VC_RENDERER_SCRIPT", GET_VESKTOP_RENDERER_SCRIPT = "VCD_GET_RENDERER_SCRIPT", GET_VESKTOP_RENDERER_CSS = "VCD_GET_RENDERER_CSS", VESKTOP_RENDERER_CSS_UPDATE = "VCD_PRELOAD_RENDERER_CSS_UPDATE", GET_VERSION = "VCD_GET_VERSION", SUPPORTS_WINDOWS_TRANSPARENCY = "VCD_SUPPORTS_WINDOWS_TRANSPARENCY", GET_ENABLE_HARDWARE_ACCELERATION = "VCD_GET_ENABLE_HARDWARE_ACCELERATION", RELAUNCH = "VCD_RELAUNCH", CLOSE = "VCD_CLOSE", FOCUS = "VCD_FOCUS", MINIMIZE = "VCD_MINIMIZE", MAXIMIZE = "VCD_MAXIMIZE", GET_SETTINGS = "VCD_GET_SETTINGS", SET_SETTINGS = "VCD_SET_SETTINGS", IS_USING_CUSTOM_VENCORD_DIR = "VCD_IS_USING_CUSTOM_VENCORD_DIR", SHOW_CUSTOM_VENCORD_DIR = "VCD_SHOW_CUSTOM_VENCORD_DIR", SELECT_VENCORD_DIR = "VCD_SELECT_VENCORD_DIR", UPDATER_IS_OUTDATED = "VCD_UPDATER_IS_OUTDATED", UPDATER_OPEN = "VCD_UPDATER_OPEN", SPELLCHECK_GET_AVAILABLE_LANGUAGES = "VCD_SPELLCHECK_GET_AVAILABLE_LANGUAGES", SPELLCHECK_RESULT = "VCD_SPELLCHECK_RESULT", SPELLCHECK_REPLACE_MISSPELLING = "VCD_SPELLCHECK_REPLACE_MISSPELLING", SPELLCHECK_ADD_TO_DICTIONARY = "VCD_SPELLCHECK_ADD_TO_DICTIONARY", SET_BADGE_COUNT = "VCD_SET_BADGE_COUNT", FLASH_FRAME = "FLASH_FRAME", CAPTURER_GET_LARGE_THUMBNAIL = "VCD_CAPTURER_GET_LARGE_THUMBNAIL", AUTOSTART_ENABLED = "VCD_AUTOSTART_ENABLED", ENABLE_AUTOSTART = "VCD_ENABLE_AUTOSTART", DISABLE_AUTOSTART = "VCD_DISABLE_AUTOSTART", VIRT_MIC_LIST = "VCD_VIRT_MIC_LIST", VIRT_MIC_START = "VCD_VIRT_MIC_START", VIRT_MIC_START_SYSTEM = "VCD_VIRT_MIC_START_ALL", VIRT_MIC_STOP = "VCD_VIRT_MIC_STOP", CLIPBOARD_COPY_IMAGE = "VCD_CLIPBOARD_COPY_IMAGE", DEBUG_LAUNCH_GPU = "VCD_DEBUG_LAUNCH_GPU", DEBUG_LAUNCH_WEBRTC_INTERNALS = "VCD_DEBUG_LAUNCH_WEBRTC", IPC_COMMAND = "VCD_IPC_COMMAND", DEVTOOLS_OPENED = "VCD_DEVTOOLS_OPENED", DEVTOOLS_CLOSED = "VCD_DEVTOOLS_CLOSED", CHOOSE_USER_ASSET = "VCD_CHOOSE_USER_ASSET" } export const enum UpdaterIpcEvents { GET_DATA = "VCD_UPDATER_GET_DATA", INSTALL = "VCD_UPDATER_INSTALL", DOWNLOAD_PROGRESS = "VCD_UPDATER_DOWNLOAD_PROGRESS", ERROR = "VCD_UPDATER_ERROR", SNOOZE_UPDATE = "VCD_UPDATER_SNOOZE_UPDATE", IGNORE_UPDATE = "VCD_UPDATER_IGNORE_UPDATE" } export const enum IpcCommands { RPC_ACTIVITY = "rpc:activity", RPC_INVITE = "rpc:invite", RPC_DEEP_LINK = "rpc:link", NAVIGATE_SETTINGS = "navigate:settings", GET_LANGUAGES = "navigator.languages", SCREEN_SHARE_PICKER = "screenshare:picker" } ================================================ FILE: src/shared/browserWinProperties.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import type { BrowserWindowConstructorOptions } from "electron"; export const SplashProps: BrowserWindowConstructorOptions = { transparent: true, frame: false, height: 350, width: 300, center: true, resizable: false, maximizable: false, alwaysOnTop: true }; ================================================ FILE: src/shared/paths.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { join } from "path"; export const STATIC_DIR = /* @__PURE__ */ join(__dirname, "..", "..", "static"); export const BADGE_DIR = /* @__PURE__ */ join(STATIC_DIR, "badges"); ================================================ FILE: src/shared/settings.d.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import type { Rectangle } from "electron"; export interface Settings { discordBranch?: "stable" | "canary" | "ptb"; transparencyOption?: "none" | "mica" | "tabbed" | "acrylic"; tray?: boolean; minimizeToTray?: boolean; autoStartMinimized?: boolean; openLinksWithElectron?: boolean; staticTitle?: boolean; enableMenu?: boolean; disableSmoothScroll?: boolean; hardwareAcceleration?: boolean; hardwareVideoAcceleration?: boolean; arRPC?: boolean; appBadge?: boolean; enableTaskbarFlashing?: boolean; disableMinSize?: boolean; clickTrayToShowHide?: boolean; customTitleBar?: boolean; enableSplashScreen?: boolean; splashTheming?: boolean; splashColor?: string; splashBackground?: string; splashPixelated?: boolean; spellCheckLanguages?: string[]; audio?: { workaround?: boolean; deviceSelect?: boolean; granularSelect?: boolean; ignoreVirtual?: boolean; ignoreDevices?: boolean; ignoreInputMedia?: boolean; onlySpeakers?: boolean; onlyDefaultSpeakers?: boolean; }; } export interface State { maximized?: boolean; minimized?: boolean; windowBounds?: Rectangle; firstLaunch?: boolean; steamOSLayoutVersion?: number; linuxAutoStartEnabled?: boolean; vencordDir?: string; updater?: { ignoredVersion?: string; snoozeUntil?: number; }; } ================================================ FILE: src/shared/utils/SettingsStore.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ import { LiteralUnion } from "type-fest"; // Resolves a possibly nested prop in the form of "some.nested.prop" to type of T.some.nested.prop type ResolvePropDeep = P extends `${infer Pre}.${infer Suf}` ? Pre extends keyof T ? ResolvePropDeep : any : P extends keyof T ? T[P] : any; /** * The SettingsStore allows you to easily create a mutable store that * has support for global and path-based change listeners. */ export class SettingsStore { private pathListeners = new Map void>>(); private globalListeners = new Set<(newData: T, path: string) => void>(); /** * The store object. Making changes to this object will trigger the applicable change listeners */ declare public store: T; /** * The plain data. Changes to this object will not trigger any change listeners */ declare public plain: T; public constructor(plain: T) { this.plain = plain; this.store = this.makeProxy(plain); } private makeProxy(object: any, root: T = object, path: string = "") { const self = this; return new Proxy(object, { get(target, key: string) { const v = target[key]; if (typeof v === "object" && v !== null && !Array.isArray(v)) return self.makeProxy(v, root, `${path}${path && "."}${key}`); return v; }, set(target, key: string, value) { if (target[key] === value) return true; Reflect.set(target, key, value); const setPath = `${path}${path && "."}${key}`; self.globalListeners.forEach(cb => cb(root, setPath)); self.pathListeners.get(setPath)?.forEach(cb => cb(value)); return true; }, deleteProperty(target, key: string) { if (!(key in target)) return true; const res = Reflect.deleteProperty(target, key); if (!res) return false; const setPath = `${path}${path && "."}${key}`; self.globalListeners.forEach(cb => cb(root, setPath)); self.pathListeners.get(setPath)?.forEach(cb => cb(undefined)); return res; } }); } /** * Set the data of the store. * This will update this.store and this.plain (and old references to them will be stale! Avoid storing them in variables) * * Additionally, all global listeners (and those for pathToNotify, if specified) will be called with the new data * @param value New data * @param pathToNotify Optional path to notify instead of globally. Used to transfer path via ipc */ public setData(value: T, pathToNotify?: string) { this.plain = value; this.store = this.makeProxy(value); if (pathToNotify) { let v = value; const path = pathToNotify.split("."); for (const p of path) { if (!v) { console.warn( `Settings#setData: Path ${pathToNotify} does not exist in new data. Not dispatching update` ); return; } v = v[p]; } this.pathListeners.get(pathToNotify)?.forEach(cb => cb(v)); } this.globalListeners.forEach(cb => cb(value, "")); } /** * Add a global change listener, that will fire whenever any setting is changed */ public addGlobalChangeListener(cb: (data: T, path: string) => void) { this.globalListeners.add(cb); } /** * Add a scoped change listener that will fire whenever a setting matching the specified path is changed. * * For example if path is `"foo.bar"`, the listener will fire on * ```js * Setting.store.foo.bar = "hi" * ``` * but not on * ```js * Setting.store.foo.baz = "hi" * ``` * @param path * @param cb */ public addChangeListener

>( path: P, cb: (data: ResolvePropDeep) => void ) { const listeners = this.pathListeners.get(path as string) ?? new Set(); listeners.add(cb); this.pathListeners.set(path as string, listeners); } /** * Remove a global listener * @see {@link addGlobalChangeListener} */ public removeGlobalChangeListener(cb: (data: T, path: string) => void) { this.globalListeners.delete(cb); } /** * Remove a scoped listener * @see {@link addChangeListener} */ public removeChangeListener(path: LiteralUnion, cb: (data: any) => void) { const listeners = this.pathListeners.get(path as string); if (!listeners) return; listeners.delete(cb); if (!listeners.size) this.pathListeners.delete(path as string); } /** * Call all global change listeners */ public markAsChanged() { this.globalListeners.forEach(cb => cb(this.plain, "")); } } ================================================ FILE: src/shared/utils/debounce.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ /** * Returns a new function that will only be called after the given delay. * Subsequent calls will cancel the previous timeout and start a new one from 0 * * Useful for grouping multiple calls into one */ export function debounce(func: T, delay = 300): T { let timeout: NodeJS.Timeout; return function (...args: any[]) { clearTimeout(timeout); timeout = setTimeout(() => { func(...args); }, delay); } as any; } ================================================ FILE: src/shared/utils/guards.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ export function isTruthy(item: T): item is Exclude { return Boolean(item); } export function isNonNullish(item: T): item is Exclude { return item != null; } ================================================ FILE: src/shared/utils/millis.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ export const enum Millis { SECOND = 1000, MINUTE = 60 * SECOND, HOUR = 60 * MINUTE, DAY = 24 * HOUR } ================================================ FILE: src/shared/utils/once.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ /** * Wraps the given function so that it can only be called once * @param fn Function to wrap * @returns New function that can only be called once */ export function once(fn: T): T { let called = false; return function (this: any, ...args: any[]) { if (called) return; called = true; return fn.apply(this, args); } as any; } ================================================ FILE: src/shared/utils/sleep.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2023 Vendicated and Vencord contributors * SPDX-License-Identifier: GPL-3.0-or-later */ export function sleep(ms: number): Promise { return new Promise(r => setTimeout(r, ms)); } ================================================ FILE: src/shared/utils/text.ts ================================================ /* * Vesktop, a desktop app aiming to give you a snappier Discord Experience * Copyright (c) 2025 Vendicated and Vesktop contributors * SPDX-License-Identifier: GPL-3.0-or-later */ export function stripIndent(strings: TemplateStringsArray, ...values: any[]) { const string = String.raw({ raw: strings }, ...values); const match = string.match(/^[ \t]*(?=\S)/gm); if (!match) return string.trim(); const minIndent = match.reduce((r, a) => Math.min(r, a.length), Infinity); return string.replace(new RegExp(`^[ \\t]{${minIndent}}`, "gm"), "").trim(); } ================================================ FILE: static/views/about.html ================================================ About Vesktop

Vesktop v{{APP_VERSION}}

Vesktop is a cross platform Discord Desktop client, aiming to give you a better Discord experience

Links

License

Vesktop is licensed under the GNU General Public License v3.0.
This is free software, and you are welcome to redistribute it under certain conditions; see the license for details.

Acknowledgements

These awesome libraries empower Vesktop

  • Electron - Build cross-platform desktop apps with JavaScript, HTML, and CSS
  • Electron Builder - A complete solution to package and build a ready for distribution Electron app with "auto update" support out of the box
  • arrpc - An open implementation of Discord's Rich Presence server
  • rohrkabel - A C++ RAII Pipewire-API Wrapper
  • And many more open source libraries
================================================ FILE: static/views/common.css ================================================ :root { color-scheme: light dark; --bg: light-dark(white, hsl(223 6.7% 20.6%)); --fg: light-dark(black, white); --fg-secondary: light-dark(#313338, #b5bac1); --fg-semi-trans: light-dark(rgb(0 0 0 / 0.2), rgb(255 255 255 / 0.2)); --link: light-dark(#006ce7, #00a8fc); --link-hover: light-dark(#005bb5, #0086c3); } html, body { margin: 0; padding: 0; } body { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; background: var(--bg); color: var(--fg); } a { color: var(--link); transition: color 0.2s linear; } a:hover { color: var(--link-hover); } ================================================ FILE: static/views/first-launch.html ================================================ Vesktop Setup

Welcome to Vesktop

Let's customise your experience!

================================================ FILE: static/views/splash.html ================================================

Loading Vesktop...

================================================ FILE: static/views/updater/index.html ================================================ Vesktop Updater

An update is available!

Current version: New version:

Release Notes

Downloading Update

Please wait while the update is being downloaded. Once the update finished downloading, it will automatically install and Vesktop will restart.

Installing Update

Please wait while the update is being installed. Vesktop will restart shortly.

================================================ FILE: static/views/updater/script.js ================================================ const { update, version: currentVersion } = await VesktopUpdaterNative.getData(); document.getElementById("current-version").textContent = currentVersion; document.getElementById("new-version").textContent = update.version; document.getElementById("release-notes").innerHTML = update.releaseNotes .map( ({ version, note: html }) => `

Version ${version}

${html.replace(/<\/?h([1-3])/g, (m, level) => m.replace(level, Number(level) + 3))}
` ) .join("\n"); document.querySelectorAll("a").forEach(a => { a.target = "_blank"; }); // remove useless headings document.querySelectorAll("h3, h4, h5, h6").forEach(h => { if (h.textContent.trim().toLowerCase() === "what's changed") { h.remove(); } }); /** @type {HTMLDialogElement} */ const updateDialog = document.getElementById("update-dialog"); /** @type {HTMLDialogElement} */ const installingDialog = document.getElementById("installing-dialog"); /** @type {HTMLProgressElement} */ const downloadProgress = document.getElementById("download-progress"); /** @type {HTMLElement} */ const errorText = document.getElementById("error"); document.getElementById("update-button").addEventListener("click", () => { downloadProgress.value = 0; errorText.textContent = ""; if (navigator.platform.startsWith("Linux")) { document.getElementById("linux-note").classList.remove("hidden"); } updateDialog.showModal(); VesktopUpdaterNative.installUpdate().then(() => { downloadProgress.value = 100; updateDialog.closedBy = "any"; installingDialog.showModal(); updateDialog.classList.add("hidden"); }); }); document.getElementById("later-button").addEventListener("click", () => VesktopUpdaterNative.snoozeUpdate()); document.getElementById("ignore-button").addEventListener("click", () => { const confirmed = confirm( "Are you sure you want to ignore this update? You will not be notified about this update again. Updates are important for security and stability." ); if (confirmed) VesktopUpdaterNative.ignoreUpdate(); }); VesktopUpdaterNative.onProgress(percent => (downloadProgress.value = percent)); VesktopUpdaterNative.onError(message => { updateDialog.closedBy = "any"; errorText.textContent = `An error occurred while downloading the update: ${message}`; installingDialog.close(); updateDialog.classList.remove("hidden"); }); ================================================ FILE: static/views/updater/style.css ================================================ html, body { height: 100%; margin: 0; box-sizing: border-box; } body { padding: 2em; display: flex; flex-direction: column; height: 100vh; header, footer { flex: 0 0 auto; } main { flex: 1 1 0%; min-height: 0; overflow: auto; } footer { margin-top: 1em; } } #versions { display: inline-grid; grid-template-columns: auto 1fr; column-gap: 0.5em; .label { white-space: nowrap; } .value { text-align: left; } #current-version { color: #fc8f8a; } #new-version { color: #71c07f; } } #release-notes { display: grid; gap: 1em; } #buttons { display: flex; gap: 0.5em; justify-content: end; } button { cursor: pointer; padding: 0.5rem 1rem; font-size: 1.2em; color: var(--fg); border: none; border-radius: 3px; font-weight: bold; transition: filter 0.2 ease-in-out; } button:hover, button:active { filter: brightness(0.9); } .green { background-color: #248046; } .grey { background-color: rgba(151, 151, 159, 0.12); } .hidden { display: none; } h1, h2, h3, h4, h5, h6 { margin: 0 0 0.5em 0; } h1 { text-align: center; } h2 { margin-bottom: 1em; } dialog { width: 80%; padding: 2em; } progress { width: 100%; height: 1.5em; margin-top: 1em; } #error { color: red; font-weight: bold; } .spinner-wrapper { display: flex; justify-content: center; align-items: center; margin-top: 2em; } .spinner { width: 48px; height: 48px; border: 5px solid var(--fg); border-bottom-color: transparent; border-radius: 50%; display: inline-block; box-sizing: border-box; animation: rotation 1s linear infinite; } @keyframes rotation { to { transform: rotate(360deg); } } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "allowSyntheticDefaultImports": true, "esModuleInterop": true, "lib": ["DOM", "DOM.Iterable", "esnext", "esnext.array", "esnext.asynciterable", "esnext.symbol"], "module": "commonjs", "moduleResolution": "node", "strict": true, "noImplicitAny": false, "target": "ESNEXT", "jsx": "preserve", // @vencord/types has some errors for now "skipLibCheck": true, "baseUrl": "./src/", "typeRoots": ["./node_modules/@types", "./node_modules/@vencord"] }, "include": ["src/**/*"] }