[
  {
    "path": ".editorconfig",
    "content": "# EditorConfig is awesome: https://EditorConfig.org\n\n# top-most EditorConfig file\nroot = true\n\n[*]\nend_of_line = lf\ninsert_final_newline = true\ntrim_trailing_whitespace = true\ncharset = utf-8\nindent_style = tab\n"
  },
  {
    "path": ".eslintrc",
    "content": "{\n  \"extends\": [\n    \"eslint:recommended\",\n    \"plugin:react/recommended\"\n  ],\n  \"parserOptions\": {\n    \"ecmaVersion\": 2020,\n    \"sourceType\": \"module\",\n    \"ecmaFeatures\": {\n      \"jsx\": true\n    }\n  },\n  \"env\": {\n    \"browser\": true\n  },\n  \"globals\": {\n    \"browser\": true,\n    \"chrome\": true\n  },\n  \"rules\": {\n    \"react/prop-types\": \"ignore\"\n  }\n}\n"
  },
  {
    "path": ".github/workflows/update-changelog.yaml",
    "content": "# .github/workflows/update-changelog.yaml\nname: \"Update Changelog\"\n\non:\n  release:\n    types: [released]\n\njobs:\n  update:\n    runs-on: ubuntu-latest\n\n    permissions:\n      # Give the default GITHUB_TOKEN write permission to commit and push the \n      # updated CHANGELOG back to the repository.\n      # https://github.blog/changelog/2023-02-02-github-actions-updating-the-default-github_token-permissions-to-read-only/\n      contents: write\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v3\n        with:\n          ref: ${{ github.event.release.target_commitish }}\n\n      - name: Update Changelog\n        uses: stefanzweifel/changelog-updater-action@v1\n        with:\n          latest-version: ${{ github.event.release.tag_name }}\n          release-notes: ${{ github.event.release.body }}\n\n      - name: Commit updated CHANGELOG\n        uses: stefanzweifel/git-auto-commit-action@v4\n        with:\n          create_branch: true\n          branch: changelog-update-${{ github.event.release.tag_name }}\n          commit_message: Update CHANGELOG\n          file_pattern: CHANGELOG.md\n"
  },
  {
    "path": ".gitignore",
    "content": "# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n*.dll\n\n# Fortran module files\n*.mod\n*.smod\n\n# Compiled Static libraries\n*.lai\n*.la\n*.a\n*.lib\n\n# Executables\n*.exe\n*.out\n*.app\n\n# VSCodium history\n.history/\n\n# Node deps\n/node_modules\n\n/result\n/pipewire-screenaudio.zip\n"
  },
  {
    "path": ".prettierrc.yml",
    "content": "useTabs: true\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## 0.4.2 - 2026-03-24\n\n### What's Changed\n\n* Fix node list not updating by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/123\n* Fix error while removing event listeners during cleanup by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/122\n* Refactor popup component into multiple hooks that each manages their own state by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/124\n* Improve popup size consistency when in errored state by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/125\n* Fix popup showing both scrollbars in chromium by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/126\n* feat(popup): disable all desktop in firefox private windows by @jim3692 in https://github.com/IceDBorn/pipewire-screenaudio/pull/128\n* rework(install): support multiple browsers by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/127\n* fix(override-gdm): do not edit page title on chromium by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/129\n* (update): readme deps & add reference to install.md by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/131\n* fix(flake): use the new manifest introduced in cb2860b6c25c20f92794e2e59c9699e0481bb491 by @Kladki in https://github.com/IceDBorn/pipewire-screenaudio/pull/130\n* fix(override-gdm): chromium detection by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/134\n* readme: add Chrome Web Store url by @jim3692 in https://github.com/IceDBorn/pipewire-screenaudio/pull/135\n\n### New Contributors\n\n* @Kladki made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/130\n\n**Full Changelog**: https://github.com/IceDBorn/pipewire-screenaudio/compare/0.4.1...0.4.2\n\n## 0.4.1 - 2026-03-10\n\n### What's Changed\n\n* Fix detection of misconfigured native connector by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/117\n* Fix version check compatibility by @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/116\n\n**Full Changelog**: https://github.com/IceDBorn/pipewire-screenaudio/compare/0.4.0...0.4.1\n\n## 0.4.0 - 2026-03-10\n\n### What's Changed\n\n* Implement simple CLI wrapper for connector by @jim3692 in https://github.com/IceDBorn/pipewire-screenaudio/pull/97\n* Rust rewrite by @jim3692, @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/99\n* Fixing Teamspeak 6 segfault by supplying node.description in pipewire.rs by @licentiapoetica in https://github.com/IceDBorn/pipewire-screenaudio/pull/112\n* Fix missing AudioCallbackDriver by @jim3692 in https://github.com/IceDBorn/pipewire-screenaudio/pull/87\n* New UI based on MUI by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/71\n* Frontend react rewrite by @jim3692, @IceDBorn, @alansartorio in https://github.com/IceDBorn/pipewire-screenaudio/pull/71\n* Fix injector breaking stream audio/video constraints by @IceDBorn in https://github.com/IceDBorn/pipewire-screenaudio/pull/71\n\n### New Contributors\n\n* @Andreas02-dev made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/95\n* @jvdcf-dev made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/107\n* @DADA30000 made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/110\n* @licentiapoetica made their first contribution in https://github.com/IceDBorn/pipewire-screenaudio/pull/112\n\n**Full Changelog**: https://github.com/IceDBorn/pipewire-screenaudio/compare/0.3.4...0.4.0\n\n## 0.3.4 - 2023-10-26\n\n![Father Gascoigne](https://s6.gifyu.com/images/S8sjU.gif)\n\n### Fixed\n\n- Flake installation\n- Enqueued actions causing the nodes loop to stop (#61) @jim3692\n- micId being \"null\" instead of null, causing errors\n- setSelectedNode(null) always failing (#70)\n- Nodes loop being stopped after sharing (#67)\n- Multiple additions of dropdown listeners (#68)\n- Crash when starting \"All Desktop Audio\" without nodes (#69) @alansartorio\n\n## 0.3.3 - 2023-10-22\n\n### Added\n\n- Logging (#30) @jim3692 @alansartorio\n\n### Fixed\n\n- Extension reporting falsely pipewire-screenaudio is running (#37) @jim3692\n- Discord workaround not working when another session is open (#44) @alansartorio\n- Race condition upon linking ports (#48) @alansartorio\n- Race condition upon setting nodes to share (#49) @jim3692\n- Being able to hide \"All Desktop Audio\" (#46) @jim3692\n\n### Changed\n\n- Code cleanup (#29 #30) @jim3692 @alansartorio\n\n## 0.3.2 - 2023-10-10\n\n### Fixed\n\n- `intToBin` not working on some Linux distros (#27) @jim3692\n\n## 0.3.1 - 2023-08-09\n\n### Fixed\n\n- Discord screen-sharing not working if the user does not select a video source within 5 seconds (#20) @alansartorio\n\n## 0.3.0 - 2023-08-08\n\n### Added\n\n- Information about Matrix\n- Note about bugzilla report\n- Switching nodes while streaming @alansartorio\n\n### Fixed\n\n- All Desktop Audio not working sometimes @alansartorio\n- Duplicated audio occurring on Discord + Wayland @alansartorio 😱\n\n## 0.2.1 - 2023-07-20\n\n### Added\n\n- NixOS flakes support and installation instructions\n\n### Changed\n\n- License to GPL3\n- Extension icon @illuminor 💘\n\n## 0.2.0 - 2023-07-19\n\nWe reworked the whole extension to only use bash and pipewire. This was made possible by the great work of @jim3692 💋\n\n### Added\n\n- Install script for the native part of the extension\n- Version checks\n\n### Changed\n\n- Port the native part to pure bash\n\n### Removed\n\n- C++ and its dependencies\n\n## 0.1.1 - 2023-07-18\n\n### Fixed\n\n- The injector script not applying in iframes\n\n## 0.1.0 - 2023-07-12\n\n### Added\n\n- \"All Desktop Audio\" support @alansartorio\n\n## 0.0.1 - 2023-07-10\n\nInitial release\n"
  },
  {
    "path": "INSTALL.md",
    "content": "# Installation Guide\n\n## Dependencies\n\n### Extension UI\n\n- Node.js\n- Yarn\n\n### Native Connector\n\n- Cargo\n\n## Browser Extension\n\nYou can install the extension from your browser's extension store or build and sideload it locally.\n\n### Published Extensions\n\n- [Firefox Add-ons](https://addons.mozilla.org/en-US/firefox/addon/pipewire-screenaudio/)\n- [Chrome Web Store](https://chromewebstore.google.com/detail/pipewire-screenaudio/cbmjbapailadjabjnjnnbfdimkbdicja)\n\n### Local Installation\n\n- **Firefox-based browsers:**\n  1.  Go to [about:debugging](about:debugging#/runtime/this-firefox) and click \"Load Temporary Add-on\".\n  1.  Select the `manifest.json` file inside the `extension` directory in the project root\n- **Chromium-based browsers:**\n  1.  Go to [chrome://extensions](chrome://extensions) and click \"Load unpacked\".\n  1.  Select the `extension` directory containing the `manifest.json` file in the project root\n\n> **Note:** For Chromium-based browsers, after loading the extension, copy its ID and provide it to the install script when prompted.\n\n## Native Messaging Hosts\n\nThe extension communicates with a native connector for pipewire management. For security reasons, browsers require explicit configuration specifying which extensions can interact with which binaries.\n\nConfiguration paths vary by browser. Some common locations are:\n\n### Firefox-based Browsers\n\n- `~/.mozilla/native-messaging-hosts` or `~/.config/mozilla/firefox/native-messaging-hosts` (Firefox)\n- `~/.librewolf/native-messaging-hosts` (Librewolf)\n\n### Chromium-based Browsers\n\n- `~/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts` (Brave)\n- `~/.config/chromium/NativeMessagingHosts` (Chromium)\n- `~/.config/net.imput.helium/NativeMessagingHosts` (Helium)\n- `~/.config/google-chrome/NativeMessagingHosts` (Google Chrome)\n\n## Native Connector\n\n- The native connector can be built from source or installed via your package manager\n- The typical binary path is: `/usr/lib/pipewire-screenaudio/connector/connector-rs`\n\nIf you build the connector yourself, do not move or delete the project directory, as the binary resides within it. If you move the directory, rerun the install script to update the path.\n\n## Uninstallation\n\n- Remove the browser extension from your browser's extensions page\n- Delete the `com.icedborn.pipewirescreenaudioconnector.json` manifest from your browser's native messaging hosts directory\n- Remove the native connector binary if built from source\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# <img src=\"./extension/assets/icons/icon.svg\" width=\"22\" alt=\"Logo\"> Pipewire Screenaudio\n\nExtension to passthrough Pipewire audio to WebRTC Screenshare\n\nBased on [virtual-mic](https://github.com/Curve/rohrkabel/tree/master/examples/virtual-mic) and [Screenshare-with-audio-on-Discord-with-Linux](https://github.com/edisionnano/Screenshare-with-audio-on-Discord-with-Linux)\n\n## Communication\n\nYou can find us on [Matrix](https://matrix.to/#/#pipewire-screenaudio:matrix.org)\n\n## Installation\n\n### Packages\n\n[![AUR](https://img.shields.io/aur/version/pipewire-screenaudio?style=for-the-badge)](https://aur.archlinux.org/packages/pipewire-screenaudio)\n[![AUR](https://img.shields.io/aur/version/pipewire-screenaudio-git?style=for-the-badge)](https://aur.archlinux.org/packages/pipewire-screenaudio-git)\n\n#### NixOS Flakes\n\n```nix\n# flake.nix\n\n{\n  inputs.pipewire-screenaudio.url = \"github:IceDBorn/pipewire-screenaudio\";\n  # ...\n\n  outputs = {nixpkgs, pipewire-screenaudio, ...} @ inputs: {\n    nixosConfigurations.HOSTNAME = nixpkgs.lib.nixosSystem {\n      specialArgs = { inherit inputs; }; # this is the important part\n      modules = [\n        ./configuration.nix\n      ];\n    };\n  }\n}\n\n# configuration.nix\n\n{inputs, pkgs, ...}: {\n  environment.systemPackages = with pkgs; [\n    (firefox.override { nativeMessagingHosts = [ inputs.pipewire-screenaudio.packages.${pkgs.system}.default ]; })\n    # ...\n  ];\n}\n```\n\n### Installing from Source\n\n#### Requirements\n\n- cargo\n- node.js\n- yarn\n\n```bash\ngit clone https://github.com/IceDBorn/pipewire-screenaudio.git\ncd pipewire-screenaudio\nbash install.sh\n```\n\nFor detailed instructions check [INSTALL.md](https://github.com/IceDBorn/pipewire-screenaudio/blob/main/INSTALL.md)\n\n## Usage\n\n- #### Via the extension\n  - Install the [extension](https://addons.mozilla.org/firefox/addon/pipewire-screenaudio)\n  - Optional: Grant extension with access permissions to all sites\n  - Join a WebRTC call, click the extension icon, select an audio node and share\n  - Stream, your transmission should contain both audio and video\n\n- #### Via the CLI\n  - **Description:** It's used to manually call the commands that are normally called by the extension. It is meant for troubleshooting, but it could be used for integrating the connector with other apps.\n  - **Usage:**\n    ```bash\n    bash native/connector/cli.sh COMMAND ARGUMENTS\n    ```\n  - **Example:**\n    ```bash\n    bash native/connector/cli.sh GetNodes\n    ```\n    ```bash\n    bash native/connector/cli.sh SetSharingNode '{ \"nodes\": [ 10840 ] }'\n    ```\n    ```bash\n    # All desktop audio\n    bash native/connector/cli.sh SetSharingNode '{ \"nodes\": [ -1 ] }'\n    ```\n    ```bash\n    # Multiple nodes\n    bash native/connector/cli.sh SetSharingNode '{ \"nodes\": [ 10840, 10841 ] }'\n    ```\n  - **Environment:**\n    ```bash\n    DEBUG=1 # Set to enable verbose logging\n    ```\n\n### resistFingerprinting\n\n- privacy.resistFingerprinting (enabled by default in LibreWolf, arkenfox user.js, etc.) breaks the extension. Either disable the preference or add any domains you wish to use Pipewire Screenaudio with to `privacy.resistFingerprinting.exemptedDomains` in `about:config`\n"
  },
  {
    "path": "extension/manifest.json",
    "content": "{\n\t\"manifest_version\": 3,\n\t\"name\": \"Pipewire Screenaudio\",\n\t\"version\": \"0.4.2\",\n\n\t\"description\": \"Passthrough pipewire audio to WebRTC screenshare\",\n\n\t\"browser_specific_settings\": {\n\t\t\"gecko\": {\n\t\t\t\"id\": \"pipewire-screenaudio@icenjim\"\n\t\t}\n\t},\n\n\t\"action\": {\n\t\t\"default_popup\": \"react/dist/index.html\"\n\t},\n\n\t\"icons\": {\n\t\t\"128\": \"assets/icons/icon.png\"\n\t},\n\n\t\"content_scripts\": [\n\t\t{\n\t\t\t\"matches\": [\"<all_urls>\"],\n\t\t\t\"run_at\": \"document_start\",\n\t\t\t\"js\": [\"scripts/injector.js\"],\n\t\t\t\"all_frames\": true\n\t\t}\n\t],\n\n\t\"background\": {\n\t\t\"scripts\": [\"scripts/background.js\"],\n\t\t\"service_worker\": \"scripts/background.js\"\n\t},\n\n\t\"permissions\": [\"nativeMessaging\", \"storage\"],\n\n\t\"web_accessible_resources\": [\n\t\t{\n\t\t\t\"matches\": [\"<all_urls>\"],\n\t\t\t\"resources\": [\"scripts/override-gdm.js\"]\n\t\t}\n\t]\n}\n"
  },
  {
    "path": "extension/react/.gitignore",
    "content": "/dist"
  },
  {
    "path": "extension/react/build-watcher.sh",
    "content": "#!/usr/bin/env bash\n\nscriptRoot=\"$( cd -- \"$(dirname \"$0\")\" > /dev/null 2>&1 ; pwd -P )\"\n\ncd $scriptRoot\n\n# Watch for file changes\nnpx nodemon -e js,jsx --ignore ./dist/ --exec \"yarn build && notify-send -i $scriptRoot/../assets/icons/icon.svg 'Pipewire Screenaudio' 'Extension rebuilt'\"\n"
  },
  {
    "path": "extension/react/components/nodes-table.jsx",
    "content": "import React from \"react\";\n\nimport Table from \"@mui/material/Table\";\nimport TableContainer from \"@mui/material/TableContainer\";\nimport TableHead from \"@mui/material/TableHead\";\nimport TableBody from \"@mui/material/TableBody\";\nimport TableRow from \"@mui/material/TableRow\";\nimport TableCell from \"@mui/material/TableCell\";\n\nimport Paper from \"@mui/material/Paper\";\nimport Checkbox from \"@mui/material/Checkbox\";\n\nexport default function NodesTable({\n\thasError,\n\tallDesktopAudio,\n\tnodes,\n\tnodeSelection,\n\ttoggleNodes,\n}) {\n\tconst allChecked = nodes.every((node) => nodeSelection.has(node.serial));\n\n\treturn (\n\t\t<TableContainer\n\t\t\tcomponent={Paper}\n\t\t\tsx={{\n\t\t\t\tminHeight: 100,\n\t\t\t\tmaxHeight: 275,\n\t\t\t\tborderRadius: 0,\n\t\t\t}}\n\t\t>\n\t\t\t<Table\n\t\t\t\tsize=\"small\"\n\t\t\t\tdisabled={hasError}\n\t\t\t>\n\t\t\t\t<TableHead\n\t\t\t\t\tsx={{\n\t\t\t\t\t\tposition: \"sticky\",\n\t\t\t\t\t\ttop: 0,\n\t\t\t\t\t\tzIndex: 10,\n\t\t\t\t\t\tbackground: \"#1e1e1e\",\n\t\t\t\t\t\tborderBottom: \"solid\",\n\t\t\t\t\t\tborderColor: \"#515151\",\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<TableRow>\n\t\t\t\t\t\t<TableCell>\n\t\t\t\t\t\t\t<Checkbox\n\t\t\t\t\t\t\t\tdisabled={allDesktopAudio || hasError}\n\t\t\t\t\t\t\t\tonChange={(event) => toggleNodes(null)}\n\t\t\t\t\t\t\t\tchecked={allChecked}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</TableCell>\n\t\t\t\t\t\t<TableCell>Media</TableCell>\n\t\t\t\t\t\t<TableCell>Application</TableCell>\n\t\t\t\t\t</TableRow>\n\t\t\t\t</TableHead>\n\t\t\t\t<TableBody>\n\t\t\t\t\t{nodes.map((node) => (\n\t\t\t\t\t\t<TableRow\n\t\t\t\t\t\t\tkey={node.mediaName}\n\t\t\t\t\t\t\tsx={{ \"&:last-child td, &:last-child th\": { border: 0 } }}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<TableCell>\n\t\t\t\t\t\t\t\t<Checkbox\n\t\t\t\t\t\t\t\t\tonChange={(event) => toggleNodes([node.serial])}\n\t\t\t\t\t\t\t\t\tdisabled={allDesktopAudio || hasError}\n\t\t\t\t\t\t\t\t\tchecked={nodeSelection.has(node.serial)}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t</TableCell>\n\t\t\t\t\t\t\t<TableCell component=\"th\" scope=\"row\">\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\t\toverflow: \"hidden\",\n\t\t\t\t\t\t\t\t\t\twidth: 200,\n\t\t\t\t\t\t\t\t\t\ttextOverflow: \"ellipsis\",\n\t\t\t\t\t\t\t\t\t\twhiteSpace: \"nowrap\",\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{node.mediaName}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</TableCell>\n\t\t\t\t\t\t\t<TableCell>\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\t\toverflow: \"hidden\",\n\t\t\t\t\t\t\t\t\t\twidth: 140,\n\t\t\t\t\t\t\t\t\t\ttextOverflow: \"ellipsis\",\n\t\t\t\t\t\t\t\t\t\twhiteSpace: \"nowrap\",\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{node.applicationName}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</TableCell>\n\t\t\t\t\t\t</TableRow>\n\t\t\t\t\t))}\n\t\t\t\t</TableBody>\n\t\t\t</Table>\n\t\t</TableContainer>\n\t);\n}\n"
  },
  {
    "path": "extension/react/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<meta charset=\"UTF-8\" />\n\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n\t\t<title>Document</title>\n\t</head>\n\t<body style=\"width: 500px\">\n\t\t<div id=\"root\"></div>\n\t\t<script type=\"module\" src=\"/index.jsx\"></script>\n\t</body>\n</html>\n"
  },
  {
    "path": "extension/react/index.jsx",
    "content": "import { createRoot } from \"react-dom/client\";\nimport {\n\tcreateBrowserRouter,\n\tuseSearchParams,\n\tRouterProvider,\n} from \"react-router-dom\";\n\nimport \"@fontsource/roboto/300.css\";\nimport \"@fontsource/roboto/400.css\";\nimport \"@fontsource/roboto/500.css\";\nimport \"@fontsource/roboto/700.css\";\n\nimport { ThemeProvider, createTheme } from \"@mui/material/styles\";\nimport CssBaseline from \"@mui/material/CssBaseline\";\n\nimport Popup from \"./routes/popup\";\n\nconst darkTheme = createTheme({\n\tpalette: {\n\t\tmode: \"dark\",\n\t},\n});\n\nconst router = createBrowserRouter([\n\t{\n\t\tpath: \"/react/dist/index.html\",\n\t\telement: <PageWrapper />,\n\t},\n]);\n\nfunction PageWrapper() {\n\tconst [search] = useSearchParams();\n\tconsole.log(search);\n\n\tif (!search.has(\"page\")) {\n\t\treturn <Popup />;\n\t}\n}\n\nfunction App() {\n\treturn (\n\t\t<ThemeProvider theme={darkTheme}>\n\t\t\t<CssBaseline />\n\t\t\t<RouterProvider router={router} basename=\"/react/dist/index.html\" />\n\t\t</ThemeProvider>\n\t);\n}\n\nconst rootEl = document.getElementById(\"root\");\nconst root = createRoot(rootEl);\nroot.render(<App />);\n"
  },
  {
    "path": "extension/react/lib/backend.js",
    "content": "import { MIC_ID, readLocalStorage } from \"./local-storage\";\n\nconst MESSAGE_NAME = \"com.icedborn.pipewirescreenaudioconnector\";\nconst EXT_VERSION = chrome.runtime.getManifest().version;\n\nexport const ERROR_VERSION_MISMATCH = \"Version Mismatch\";\n\nexport const EVENT_MIC_ID_UPDATED = \"onMicIdUpdated\";\nexport const EVENT_MIC_ID_REMOVED = \"onMicIdRemoved\";\n\nlet isStopping = false;\n\nfunction enqueueCommandToBackground(command) {\n\tsendMessage(\"enqueue-command\", command);\n}\n\nasync function sendNativeMessage(command, args) {\n\tconsole.log(\"Sent native message\", { command, args });\n\n\tconst response = await chrome.runtime.sendNativeMessage(MESSAGE_NAME, {\n\t\tcmd: command,\n\t\targs: args,\n\t});\n\t// support previous connector versions\n\tif (response.success === undefined) {\n\t\treturn response;\n\t}\n\tif (!response.success) {\n\t\tthrow new Error(\n\t\t\t`unsuccessful message response during call to ${command} with arguments ${JSON.stringify(args)}: ${response.errorMessage}`,\n\t\t);\n\t}\n\treturn response.response;\n}\n\nasync function sendMessage(message, command) {\n\tconsole.log(\"Sent message\", { command, message });\n\n\ttry {\n\t\treturn await chrome.runtime.sendMessage({\n\t\t\tmessageName: MESSAGE_NAME,\n\t\t\tmessage: message,\n\t\t\tcommand: command,\n\t\t});\n\t} catch (err) {\n\t\tconsole.error(\n\t\t\t`Failed message \"${message}\" with command: ${JSON.stringify(command)}`,\n\t\t);\n\t\tthrow err;\n\t}\n}\n\nfunction matchVersion(a, b) {\n\tconst aSplit = a.split(\".\");\n\tconst bSplit = b.split(\".\");\n\treturn aSplit[0] === bSplit[0] && aSplit[1] === bSplit[1];\n}\n\nfunction getNewPromise() {\n\tlet resolvePromise, rejectPromise;\n\tconst promise = new Promise((resolve, reject) => {\n\t\tresolvePromise = resolve;\n\t\trejectPromise = reject;\n\t});\n\n\treturn { promise, resolvePromise, rejectPromise };\n}\n\nfunction handleMessage(message) {\n\tconsole.log({ message });\n\n\tif (message === EVENT_MIC_ID_UPDATED) {\n\t\treadLocalStorage(MIC_ID).then((micId) => {\n\t\t\tconst event = new CustomEvent(EVENT_MIC_ID_UPDATED, {\n\t\t\t\tdetail: { micId },\n\t\t\t});\n\t\t\tdocument.dispatchEvent(event);\n\t\t});\n\t}\n\n\tif (message === EVENT_MIC_ID_REMOVED) {\n\t\tconst event = new CustomEvent(EVENT_MIC_ID_REMOVED);\n\t\tdocument.dispatchEvent(event);\n\t}\n}\n\nchrome.runtime.onMessage.addListener(handleMessage);\n\nexport async function healthCheck() {\n\tconst { version: nativeVersion } = await sendNativeMessage(\"GetVersion\");\n\n\tif (!matchVersion(nativeVersion, EXT_VERSION)) {\n\t\tthrow new Error(ERROR_VERSION_MISMATCH, {\n\t\t\tcause: {\n\t\t\t\tnativeVersion,\n\t\t\t\textensionVersion: EXT_VERSION,\n\t\t\t},\n\t\t});\n\t}\n\n\treturn true;\n}\n\nexport async function getNodes() {\n\treturn await sendNativeMessage(\"GetNodes\");\n}\n\nexport async function isPipewireScreenAudioRunning(micId) {\n\treturn (await sendNativeMessage(\"IsPipewireScreenAudioRunning\", { micId }))\n\t\t.isRunning;\n}\n\nexport function startPipewireScreenAudio() {\n\tisStopping = false;\n\tenqueueCommandToBackground({\n\t\tcmd: \"StartPipewireScreenAudio\",\n\t\tmaps: { outMap: [[MIC_ID, \"micId\"]] }, // Set the `micId` in LocalStorage to the incoming `micId`\n\t\tevent: EVENT_MIC_ID_UPDATED,\n\t});\n}\n\nexport function stopPipewireScreenAudio(micId) {\n\tisStopping = true;\n\tenqueueCommandToBackground({\n\t\tcmd: \"StopPipewireScreenAudio\",\n\t\targs: { micId },\n\t\tmaps: { outMap: [[MIC_ID, null]] }, // Clear the `micId` in LocalStorage\n\t\tevent: EVENT_MIC_ID_REMOVED,\n\t});\n}\n\nexport function setSharingNode(nodeSerials) {\n\tenqueueCommandToBackground({\n\t\tcmd: \"SetSharingNode\",\n\t\targs: { nodes: nodeSerials },\n\t\tmaps: { inMap: [[MIC_ID, \"micId\"]] }, // Read the `micId` from LocalStorage and pass it as the `micId` arg\n\t});\n}\n\nexport const isChromium = () => typeof browser === \"undefined\";\n\nexport const isIncognito = () => {\n\tif (isChromium()) {\n\t\treturn false;\n\t}\n\n\treturn !!browser?.extension.inIncognitoContext;\n}\n"
  },
  {
    "path": "extension/react/lib/hooks.js",
    "content": "import { useEffect, useRef, useState } from \"react\";\nimport { readLocalStorage, updateLocalStorage } from \"./local-storage\";\n\nexport function useDidUpdateEffect(fn, inputs) {\n\tconst didMountRef = useRef(false);\n\n\tuseEffect(() => {\n\t\tif (didMountRef.current) {\n\t\t\treturn fn();\n\t\t}\n\t\tdidMountRef.current = true;\n\t}, inputs);\n}\n\nexport function useLocalStorage(name) {\n\tconst [data, setData] = useState(undefined);\n\tconst [isLoading, setIsLoading] = useState(true);\n\n\tuseEffect(() => {\n\t\treadLocalStorage(name).then((val) => {\n\t\t\tsetData(val);\n\t\t\tsetIsLoading(false);\n\t\t});\n\t}, [name]);\n\n\tconst setStoredData = (val) => {\n\t\tsetData(val);\n\t\tupdateLocalStorage(name, val);\n\t};\n\n\treturn { isLoading, data, setData: setStoredData };\n}\n"
  },
  {
    "path": "extension/react/lib/local-storage.js",
    "content": "export const SELECTED_NODES = \"selectedNodes\";\nexport const MIC_ID = \"micId\";\nexport const ALL_DESKTOP = \"allDesktopAudio\";\n\nexport async function readLocalStorage(name) {\n\ttry {\n\t\tconst stored = await chrome.storage.local.get(name);\n\t\treturn stored[name] ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function updateLocalStorage(name, value) {\n\tawait chrome.storage.local.set({ [name]: value });\n}\n"
  },
  {
    "path": "extension/react/lib/match-node.js",
    "content": "export default function matchNode(a, b) {\n\treturn (\n\t\ta.serial === b.serial &&\n\t\ta.mediaName === b.mediaName &&\n\t\ta.applicationName === b.applicationName\n\t);\n}\n"
  },
  {
    "path": "extension/react/routes/popup.jsx",
    "content": "// TODO: Add nodes sorting\nimport React, { useCallback, useEffect, useState } from \"react\";\n\nimport Alert from \"@mui/material/Alert\";\nimport AppBar from \"@mui/material/AppBar\";\nimport Box from \"@mui/material/Box\";\nimport Button from \"@mui/material/Button\";\nimport FormControlLabel from \"@mui/material/FormControlLabel\";\nimport Grid from \"@mui/material/Grid\";\nimport Paper from \"@mui/material/Paper\";\nimport Switch from \"@mui/material/Switch\";\nimport Toolbar from \"@mui/material/Toolbar\";\nimport Typography from \"@mui/material/Typography\";\n\nimport { useDebouncedCallback } from \"use-debounce\";\n\nimport {\n\tERROR_VERSION_MISMATCH,\n\tEVENT_MIC_ID_UPDATED,\n\tEVENT_MIC_ID_REMOVED,\n\thealthCheck,\n\tgetNodes,\n\tisChromium,\n\tisIncognito,\n\tisPipewireScreenAudioRunning,\n\tstartPipewireScreenAudio,\n\tstopPipewireScreenAudio,\n\tsetSharingNode,\n} from \"../lib/backend\";\n\nimport {\n\tMIC_ID,\n\tALL_DESKTOP,\n\treadLocalStorage,\n\tupdateLocalStorage,\n\tSELECTED_NODES,\n} from \"../lib/local-storage\";\nimport { useDidUpdateEffect, useLocalStorage } from \"../lib/hooks\";\n\nimport NodesTable from \"../components/nodes-table\";\nimport matchNode from \"../lib/match-node\";\n\nfunction mapNode(node) {\n\treturn {\n\t\tmediaName: node.properties[\"media.name\"],\n\t\tapplicationName: node.properties[\"application.name\"],\n\t\tserial: node.properties[\"object.serial\"],\n\t\tchecked: false,\n\t};\n}\n\n/**\n * @param {Object} param0\n * @param {object[]} param0.nodes\n * @param {boolean} param0.areNodesLoading\n */\nfunction useNodeSelectionState({ nodes, areNodesLoading }) {\n\tconst {\n\t\tdata: storedNodeSelection,\n\t\tsetData: setStoredNodeSelection,\n\t\tisLoading,\n\t} = useLocalStorage(SELECTED_NODES);\n\n\tif (isLoading || areNodesLoading) return { isLoading: true };\n\n\tlet nodeSelection;\n\n\tif (!nodes) {\n\t\tnodeSelection = new Set(\n\t\t\t(storedNodeSelection ?? []).map((node) => node.serial),\n\t\t);\n\t} else {\n\t\tnodeSelection = new Set(\n\t\t\t(storedNodeSelection ?? [])\n\t\t\t\t.filter((selectedNode) =>\n\t\t\t\t\tnodes.some((node) => matchNode(node, selectedNode)),\n\t\t\t\t)\n\t\t\t\t.map((node) => node.serial),\n\t\t);\n\t}\n\n\t/**\n\t * @type {function(int[]):void}\n\t */\n\tconst toggleNodes = (serials) => {\n\t\tlet newNodeSelection;\n\t\tif (serials === null) {\n\t\t\tconst turnOn = !nodes.every((node) => nodeSelection.has(node.serial));\n\t\t\tnewNodeSelection = new Set(\n\t\t\t\tturnOn ? nodes.map((node) => node.serial) : [],\n\t\t\t);\n\t\t} else {\n\t\t\tnewNodeSelection = new Set(nodeSelection);\n\t\t\tfor (const serial of serials) {\n\t\t\t\tif (newNodeSelection.has(serial)) {\n\t\t\t\t\tnewNodeSelection.delete(serial);\n\t\t\t\t} else {\n\t\t\t\t\tnewNodeSelection.add(serial);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsetStoredNodeSelection(\n\t\t\tnodes.filter((node) => newNodeSelection.has(node.serial)),\n\t\t);\n\t};\n\n\treturn { isLoading: false, nodeSelection, toggleNodes };\n}\n\nfunction useHealthchecks() {\n\tconst [isLoading, setIsLoading] = useState(true);\n\tconst [versionMatches, setVersionMatches] = useState(null);\n\tconst [connectorConnection, setConnectorConnection] = useState(false);\n\tconst [extensionVersion, setExtensionVersion] = useState(null);\n\tconst [nativeVersion, setNativeVersion] = useState(null);\n\n\tuseEffect(() => {\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tconst health = await healthCheck();\n\t\t\t\tsetVersionMatches(health);\n\t\t\t\tsetConnectorConnection(true);\n\t\t\t} catch (err) {\n\t\t\t\tif (err.message === ERROR_VERSION_MISMATCH) {\n\t\t\t\t\tsetNativeVersion(err.cause.nativeVersion);\n\t\t\t\t\tsetExtensionVersion(err.cause.extensionVersion);\n\t\t\t\t\tsetVersionMatches(false);\n\t\t\t\t\tsetConnectorConnection(true);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsetIsLoading(false);\n\t\t})();\n\t}, []);\n\n\treturn {\n\t\tisLoading,\n\t\tversionMatches,\n\t\tconnectorConnection,\n\t\textensionVersion,\n\t\tnativeVersion,\n\t};\n}\n\n/**\n * @param {Object} param0\n * @param {boolean} param0.enabled\n */\nfunction useNodes({ enabled }) {\n\tconst [nodes, setNodes] = useState(null);\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tconst [isErrored, setIsErrored] = useState(false);\n\n\tuseEffect(() => {\n\t\tif (!enabled) return;\n\n\t\tlet previousNodes = null;\n\t\tconst nodesReceive = async () => {\n\t\t\ttry {\n\t\t\t\tconst n = await getNodes();\n\t\t\t\tconst currentNodesStr = JSON.stringify(n);\n\t\t\t\tif (currentNodesStr !== previousNodes) setNodes(n.map(mapNode));\n\t\t\t\tpreviousNodes = currentNodesStr;\n\t\t\t\tsetIsErrored(false);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(\"error receiving nodes: \", err);\n\t\t\t\tsetNodes(null);\n\t\t\t\tsetIsErrored(true);\n\t\t\t}\n\t\t\tif (!isInitialized) setIsInitialized(true);\n\t\t};\n\t\tnodesReceive();\n\n\t\tlet nodesInterval = setInterval(nodesReceive, 2000);\n\n\t\treturn () => {\n\t\t\tif (nodesInterval !== null) {\n\t\t\t\tclearInterval(nodesInterval);\n\t\t\t}\n\t\t};\n\t}, [enabled]);\n\n\treturn { nodes, isErrored, isInitialized };\n}\n\n/**\n * @param {Object} param0\n * @param {boolean} param0.enabled\n */\nfunction useCurrentMicId({ enabled }) {\n\tconst [isRunning, setIsRunning] = useState(null);\n\tconst {\n\t\tisLoading: isLocalStorageLoading,\n\t\tdata: micId,\n\t\tsetData: setMicId,\n\t} = useLocalStorage(MIC_ID);\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\n\tconst shouldListen = enabled && !isLocalStorageLoading;\n\n\tfunction handleMicIdUpdated(id) {\n\t\tif (!id) return;\n\t\tsetMicId(id.detail.micId);\n\t\tsetIsRunning(true);\n\t}\n\n\tfunction handleMicIdRemoved() {\n\t\tsetMicId(null);\n\t\tsetIsRunning(false);\n\t}\n\n\tuseEffect(() => {\n\t\tif (!shouldListen) return;\n\n\t\tlet func = async () => {\n\t\t\ttry {\n\t\t\t\tconst res = await isPipewireScreenAudioRunning(micId);\n\t\t\t\tconsole.log({ res, micId });\n\t\t\t\tif (!res) setMicId(null);\n\t\t\t\tsetIsRunning(res);\n\n\t\t\t\tdocument.addEventListener(EVENT_MIC_ID_UPDATED, handleMicIdUpdated);\n\t\t\t\tdocument.addEventListener(EVENT_MIC_ID_REMOVED, handleMicIdRemoved);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(\"unhandled error:\", err);\n\t\t\t}\n\t\t\tsetIsInitialized(true);\n\t\t};\n\n\t\tfunc();\n\n\t\treturn () => {\n\t\t\tdocument.removeEventListener(EVENT_MIC_ID_UPDATED, handleMicIdUpdated);\n\t\t\tdocument.removeEventListener(EVENT_MIC_ID_REMOVED, handleMicIdRemoved);\n\t\t};\n\t}, [shouldListen]);\n\n\treturn { isInitialized, micId, isRunning };\n}\n\nfunction useAllDesktopAudio() {\n\tconst { isLoading, data, setData } = useLocalStorage(ALL_DESKTOP);\n\n\treturn {\n\t\tisAllDesktopAudioLoading: isLoading,\n\t\tallDesktopAudio: !!data,\n\t\tsetAllDesktopAudio: setData,\n\t};\n}\n\nexport default function Popup() {\n\tconst {\n\t\tisLoading: isHealthcheckLoading,\n\t\tconnectorConnection,\n\t\tversionMatches,\n\t\tnativeVersion,\n\t\textensionVersion,\n\t} = useHealthchecks();\n\n\tconst {\n\t\tnodes,\n\t\tisErrored: areNodesErrored,\n\t\tisInitialized: areNodesInitialized,\n\t} = useNodes({\n\t\tenabled: !isHealthcheckLoading && connectorConnection,\n\t});\n\tconst nodesSuccessfullyLoaded = areNodesInitialized && !areNodesErrored;\n\n\tconst {\n\t\tisInitialized: isCurrentMicIdInitialized,\n\t\tisRunning,\n\t\tmicId,\n\t} = useCurrentMicId({\n\t\tenabled: !isHealthcheckLoading && connectorConnection,\n\t});\n\n\tconst { isAllDesktopAudioLoading, allDesktopAudio, setAllDesktopAudio } =\n\t\tuseAllDesktopAudio();\n\n\tconst {\n\t\tisLoading: isNodeSelectionLoading,\n\t\tnodeSelection,\n\t\ttoggleNodes,\n\t} = useNodeSelectionState({\n\t\tnodes,\n\t\tareNodesLoading: !nodesSuccessfullyLoaded,\n\t});\n\n\tconst debouncedSetSharingNodes = useDebouncedCallback(() => {\n\t\tsetSharingNode(Array.from(nodeSelection));\n\t}, 1000);\n\n\tconst debouncedShareAllDesktopAudio = useDebouncedCallback(() => {\n\t\tif (allDesktopAudio) {\n\t\t\tsetSharingNode([-1]);\n\t\t} else {\n\t\t\tsetSharingNode([]);\n\t\t}\n\t}, 1000);\n\n\tconst showConnectionError = !connectorConnection || areNodesErrored;\n\tconst isHealthy =\n\t\t!isHealthcheckLoading && versionMatches && !showConnectionError;\n\n\tfunction shareNodes(allDesktopAudio) {\n\t\tif (!isHealthy || !isRunning || allDesktopAudio) return;\n\t\tdebouncedSetSharingNodes();\n\t}\n\n\tasync function handleStartStop() {\n\t\tif (!isRunning) {\n\t\t\tstartPipewireScreenAudio();\n\t\t\tif (allDesktopAudio) {\n\t\t\t\tsetSharingNode([-1]);\n\t\t\t} else {\n\t\t\t\tsetSharingNode(Array.from(nodeSelection));\n\t\t\t}\n\t\t} else {\n\t\t\tstopPipewireScreenAudio(micId);\n\t\t}\n\t}\n\n\treturn (\n\t\t!isHealthcheckLoading && (\n\t\t\t<>\n\t\t\t\t<AppBar position=\"static\">\n\t\t\t\t\t<Toolbar>\n\t\t\t\t\t\t<Typography variant=\"h6\" component=\"div\" sx={{ flexGrow: 1 }}>\n\t\t\t\t\t\t\tPipewire Screenaudio\n\t\t\t\t\t\t</Typography>\n\t\t\t\t\t</Toolbar>\n\t\t\t\t</AppBar>\n\t\t\t\t{(showConnectionError ||\n\t\t\t\t\t!versionMatches ||\n\t\t\t\t\t(isCurrentMicIdInitialized && isRunning)) && (\n\t\t\t\t\t<Alert\n\t\t\t\t\t\tseverity={isRunning ? \"info\" : \"error\"}\n\t\t\t\t\t\tcolor={isRunning ? \"info\" : \"error\"}\n\t\t\t\t\t>\n\t\t\t\t\t\t{showConnectionError\n\t\t\t\t\t\t\t? \"The native connector is missing or misconfigured\"\n\t\t\t\t\t\t\t: !versionMatches\n\t\t\t\t\t\t\t\t? `Version mismatch! Extension: ${extensionVersion}, Native: ${nativeVersion}`\n\t\t\t\t\t\t\t\t: isRunning\n\t\t\t\t\t\t\t\t\t? `Running with ID: ${micId}`\n\t\t\t\t\t\t\t\t\t: console.error(\"unreachable\")}\n\t\t\t\t\t</Alert>\n\t\t\t\t)}\n\t\t\t\t{/* Content */}\n\t\t\t\t{(areNodesInitialized || showConnectionError) &&\n\t\t\t\t\t(showConnectionError || !nodes.length ? (\n\t\t\t\t\t\t<Paper sx={{ minHeight: 80, borderRadius: 0 }}>\n\t\t\t\t\t\t\t<div></div>\n\t\t\t\t\t\t\t<Typography\n\t\t\t\t\t\t\t\tvariant=\"h6\"\n\t\t\t\t\t\t\t\tcomponent=\"div\"\n\t\t\t\t\t\t\t\tsx={{\n\t\t\t\t\t\t\t\t\tflexGrow: 1,\n\t\t\t\t\t\t\t\t\tmarginLeft: 13,\n\t\t\t\t\t\t\t\t\tpaddingTop: 5,\n\t\t\t\t\t\t\t\t\tpaddingBottom: 5,\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{showConnectionError\n\t\t\t\t\t\t\t\t\t? \"Could not retrieve node list\"\n\t\t\t\t\t\t\t\t\t: \"No nodes available for sharing\"}\n\t\t\t\t\t\t\t</Typography>\n\t\t\t\t\t\t</Paper>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<NodesTable\n\t\t\t\t\t\t\tnodes={nodes}\n\t\t\t\t\t\t\tnodeSelection={nodeSelection}\n\t\t\t\t\t\t\ttoggleNodes={(serials) => {\n\t\t\t\t\t\t\t\ttoggleNodes(serials);\n\t\t\t\t\t\t\t\tshareNodes(allDesktopAudio);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\thasError={!isHealthy}\n\t\t\t\t\t\t\tallDesktopAudio={allDesktopAudio}\n\t\t\t\t\t\t/>\n\t\t\t\t\t))}\n\t\t\t\t<Paper sx={{ borderRadius: \"0\", padding: 1 }}>\n\t\t\t\t\t<Grid container justify=\"space-between\">\n\t\t\t\t\t\t<span\n\t\t\t\t\t\t\ttitle={isChromium() ? \"Not supported on Chromium browsers\" : \"\"}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<FormControlLabel\n\t\t\t\t\t\t\t\tcontrol={\n\t\t\t\t\t\t\t\t\t<Switch\n\t\t\t\t\t\t\t\t\t\tonChange={() => {\n\t\t\t\t\t\t\t\t\t\t\tconst currentAllDesktopAudio = !allDesktopAudio;\n\t\t\t\t\t\t\t\t\t\t\tsetAllDesktopAudio(currentAllDesktopAudio);\n\n\t\t\t\t\t\t\t\t\t\t\tif (currentAllDesktopAudio) {\n\t\t\t\t\t\t\t\t\t\t\t\tdebouncedShareAllDesktopAudio();\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tshareNodes(currentAllDesktopAudio);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsx={{ marginLeft: 0 }}\n\t\t\t\t\t\t\t\tlabel=\"All Desktop Audio\"\n\t\t\t\t\t\t\t\tchecked={allDesktopAudio}\n\t\t\t\t\t\t\t\tdisabled={!isHealthy || isAllDesktopAudioLoading || isChromium() || isIncognito()}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tsx={{\n\t\t\t\t\t\t\t\tminWidth: 75,\n\t\t\t\t\t\t\t\tmarginLeft: \"auto\",\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\tvariant=\"contained\"\n\t\t\t\t\t\t\tcolor={isRunning ? \"error\" : \"success\"}\n\t\t\t\t\t\t\tonClick={handleStartStop}\n\t\t\t\t\t\t\tdisabled={!isHealthy || !isCurrentMicIdInitialized}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{isRunning ? \"Stop\" : \"Start\"}\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</Grid>\n\t\t\t\t</Paper>\n\t\t\t</>\n\t\t)\n\t);\n}\n"
  },
  {
    "path": "extension/react/vite.config.js",
    "content": "import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n\tplugins: [react()],\n\tbase: \"/react/dist\",\n\tesbuild: {\n\t\tjsxFactory: \"React.createElement\",\n\t\tjsxFragment: \"React.Fragment\",\n\t},\n\tcss: {\n\t\tmodules: {\n\t\t\tlocalsConvention: \"camelCaseOnly\",\n\t\t},\n\t},\n\tbuild: {\n\t\tsourcemap: \"inline\",\n\t\tchunkSizeWarningLimit: Infinity,\n\t},\n});\n"
  },
  {
    "path": "extension/scripts/background.js",
    "content": "// Any event, that is handled in here, should have a comment with the reason it is handled in here\n\nlet commandsQueue = [];\nlet commandsQueueRunning = false;\n\nasync function sendNativeMessage(messageName, cmd, args) {\n\tconst response = await chrome.runtime.sendNativeMessage(messageName, {\n\t\tcmd,\n\t\targs,\n\t});\n\t// support previous connector versions\n\tif (response.success === undefined) {\n\t\treturn response;\n\t}\n\tif (!response.success) {\n\t\tthrow new Error(\n\t\t\t`unsuccessful message response during call to ${cmd} with arguments ${JSON.stringify(args)}: ${response.errorMessage}`,\n\t\t);\n\t}\n\treturn response.response;\n}\n\nasync function runQueuedCommands() {\n\tcommandsQueueRunning = true;\n\n\twhile (commandsQueue.length) {\n\t\ttry {\n\t\t\tconst command = commandsQueue.shift();\n\t\t\tconst args = { ...command.args };\n\t\t\tconst { inMap, outMap } = command.maps || {};\n\n\t\t\tif (inMap) {\n\t\t\t\tfor (const [storageKey, argKey] of inMap) {\n\t\t\t\t\tconst stored = await chrome.storage.local.get(storageKey);\n\t\t\t\t\targs[argKey] = stored[storageKey] ?? null;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconsole.log(args);\n\t\t\tconst result = await sendNativeMessage(\n\t\t\t\tcommand.messageName,\n\t\t\t\tcommand.cmd,\n\t\t\t\targs,\n\t\t\t\tcommand.maps,\n\t\t\t);\n\t\t\tconsole.log(result);\n\n\t\t\tif (outMap) {\n\t\t\t\tfor (const [storageKey, resultKey] of outMap) {\n\t\t\t\t\tawait chrome.storage.local.set({\n\t\t\t\t\t\t[storageKey]: resultKey ? result[resultKey] : null,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (command.event) {\n\t\t\t\tchrome.runtime.sendMessage(command.event);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t}\n\t}\n\n\tcommandsQueueRunning = false;\n}\n\nfunction handleMessage(request) {\n\t// Run multiple commands sequentially\n\tif (request.message === \"enqueue-command\") {\n\t\tcommandsQueue.push({\n\t\t\t...request.command,\n\t\t\tmessageName: request.messageName,\n\t\t});\n\t\tif (!commandsQueueRunning) {\n\t\t\trunQueuedCommands();\n\t\t}\n\t}\n\n\t// Called from injector.js - It cannot directly call sendNativeMessage\n\tif (request.message === \"get-session-type\") {\n\t\treturn sendNativeMessage(request.messageName, \"GetSessionType\");\n\t}\n\n\tif (request.message === \"instance-identifier\") {\n\t\treturn sendNativeMessage(request.messageName, \"SetInstanceIdentifier\", {\n\t\t\tid: request.instanceIdentifier,\n\t\t});\n\t}\n}\n\nchrome.runtime.onMessage.addListener(handleMessage);\n"
  },
  {
    "path": "extension/scripts/injector.js",
    "content": "const MESSAGE_NAME = \"com.icedborn.pipewirescreenaudioconnector\";\n\nconst nullthrows = (v) => {\n\tif (v == null) throw new Error(\"null\");\n\treturn v;\n};\n\nfunction injectCode(src) {\n\tconst script = document.createElement(\"script\");\n\tscript.src = src;\n\tscript.onload = function () {\n\t\tconsole.log(\"pipewire-screenaudio script injected\");\n\n\t\tchrome.runtime\n\t\t\t.sendMessage({ messageName: MESSAGE_NAME, message: \"get-session-type\" })\n\t\t\t.then((response) => {\n\t\t\t\tif (!response) return;\n\t\t\t\twindow.postMessage({\n\t\t\t\t\tmessage: \"set-session-type\",\n\t\t\t\t\ttype: response.type,\n\t\t\t\t});\n\t\t\t});\n\n\t\tthis.remove();\n\t};\n\n\tnullthrows(document.head || document.documentElement).appendChild(script);\n}\n\nwindow.addEventListener(\"message\", ({ data }) => {\n\tif (data.message === \"instance-identifier\") {\n\t\tchrome.runtime.sendMessage({\n\t\t\tmessageName: MESSAGE_NAME,\n\t\t\tmessage: data.message,\n\t\t\tinstanceIdentifier: data.instanceIdentifier,\n\t\t});\n\t}\n});\n\ninjectCode(chrome.runtime.getURL(\"/scripts/override-gdm.js\"));\n"
  },
  {
    "path": "extension/scripts/override-gdm.js",
    "content": "(() => {\n\tlet sessionType = null;\n\n\tconst instanceIdentifier = `pipewire-screenaudio-${createRandomString(16)}`;\n\n\tconst getTitleWithInstanceIdentifier = (title) =>\n\t\t`${title} | ${instanceIdentifier}`;\n\n\tfunction createRandomString(\n\t\tlength,\n\t\tchars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n\t) {\n\t\tconst array = new Uint8Array(length);\n\t\tcrypto.getRandomValues(array);\n\t\treturn Array.from(array, (byte) => chars[byte % chars.length]).join(\"\");\n\t}\n\n\tfunction overrideGetDisplayMedia() {\n\t\tnavigator.mediaDevices.chromiumGetDisplayMedia =\n\t\t\tnavigator.mediaDevices.getDisplayMedia;\n\n\t\tconst getAudioDevice = async (nameOfAudioDevice) => {\n\t\t\tawait navigator.mediaDevices.getUserMedia({\n\t\t\t\taudio: true,\n\t\t\t});\n\n\t\t\tawait new Promise((resolve, reject) => setTimeout(resolve, 1000));\n\t\t\tconst devices = await navigator.mediaDevices.enumerateDevices();\n\n\t\t\tconst audioDevice = devices.find(\n\t\t\t\t({ label }) => label === nameOfAudioDevice,\n\t\t\t);\n\n\t\t\treturn audioDevice;\n\t\t};\n\n\t\tconst getDisplayMedia = async (constraints = {}) => {\n\t\t\t// Keep the original constraints (video fps/resolution/etc) and only\n\t\t\t// inject `pipewire-screenaudio` audio track when appropriate.\n\t\t\tconst originalGetDisplayMedia =\n\t\t\t\tnavigator.mediaDevices.chromiumGetDisplayMedia.bind(\n\t\t\t\t\tnavigator.mediaDevices,\n\t\t\t\t);\n\n\t\t\t// If caller doesn't request audio, or provided an explicit deviceId,\n\t\t\t// forward constraints unchanged.\n\t\t\tif (\n\t\t\t\t!constraints.audio ||\n\t\t\t\t(typeof constraints.audio === \"object\" &&\n\t\t\t\t\tconstraints.audio !== null &&\n\t\t\t\t\t(constraints.audio.deviceId || constraints.audio.deviceId === 0))\n\t\t\t) {\n\t\t\t\treturn await originalGetDisplayMedia(constraints);\n\t\t\t}\n\n\t\t\tlet micId;\n\t\t\ttry {\n\t\t\t\tmicId = await getAudioDevice(\"pipewire-screenaudio\").then(\n\t\t\t\t\t({ deviceId }) => deviceId,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\treturn await originalGetDisplayMedia(constraints);\n\t\t\t}\n\n\t\t\tconst capturePipewireScreenaudioMic =\n\t\t\t\tawait navigator.mediaDevices.getUserMedia({\n\t\t\t\t\taudio: {\n\t\t\t\t\t\tdeviceId: { exact: micId },\n\t\t\t\t\t\tautoGainControl: false,\n\t\t\t\t\t\techoCancellation: false,\n\t\t\t\t\t\tnoiseSuppression: false,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\tconst [track] = capturePipewireScreenaudioMic.getAudioTracks();\n\n\t\t\tconst displayMedia = await originalGetDisplayMedia(constraints);\n\t\t\tdisplayMedia.addTrack(track);\n\n\t\t\tconst isChromium = typeof window.chrome !== \"undefined\";\n\t\t\tlet stopWatchTitle;\n\n\t\t\tif (!isChromium) {\n\t\t\t\tstopWatchTitle = watchTitle();\n\t\t\t\tdocument.title = document.title;\n\n\t\t\t\t// Send the node name to exclude for All Desktop Audio\n\t\t\t\twindow.postMessage({\n\t\t\t\t\tmessage: \"instance-identifier\",\n\t\t\t\t\tinstanceIdentifier,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Watch track and clear instance when ended\n\t\t\t// Workaround solution for firefox, because it does not support MediaStream's inactive event\n\t\t\tconst trackWatcher = setInterval(() => {\n\t\t\t\tif (track.readyState !== \"ended\") return;\n\n\t\t\t\t// TODO: Add instance clearing native logic when implementing multiple instances\n\t\t\t\tconsole.log(\"track ended\");\n\n\t\t\t\tif (stopWatchTitle) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstopWatchTitle();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconsole.error(\"error while stop watching title.\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tclearInterval(trackWatcher);\n\t\t\t}, 50);\n\n\t\t\treturn displayMedia;\n\t\t};\n\n\t\tnavigator.mediaDevices.getDisplayMedia = getDisplayMedia;\n\t}\n\n\t// Watch the title element for changes and append our identifier if missing\n\tfunction watchTitle() {\n\t\tconst titleEl = document.querySelector(\"title\");\n\t\tif (!titleEl) return;\n\n\t\tconst titleWatcher = new MutationObserver((mutations) => {\n\t\t\tfor (const mut of mutations) {\n\t\t\t\tif ([\"childList\", \"characterData\"].includes(mut.type)) {\n\t\t\t\t\tif (document.title.includes(instanceIdentifier)) break;\n\t\t\t\t\tdocument.title = getTitleWithInstanceIdentifier(document.title);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\ttitleWatcher.observe(titleEl, {\n\t\t\tchildList: true,\n\t\t\tcharacterData: true,\n\t\t\tsubtree: true,\n\t\t});\n\n\t\treturn () => titleWatcher.disconnect();\n\t}\n\n\toverrideGetDisplayMedia();\n\n\tconst onMessageHooks = {};\n\n\t// Store the session type we get (either \"x11\" or \"wayland\") into sessionType\n\t// This message gets sent from the onload listener in injector.js\n\tconst onMessage = (event) => {\n\t\tif (event.target !== window) return;\n\t\tif (event.data.message === \"set-session-type\") {\n\t\t\tsessionType = event.data.type;\n\t\t\twindow.removeEventListener(\"message\", onMessage);\n\t\t}\n\n\t\tObject.values(onMessageHooks).forEach((hook) => hook(event));\n\t};\n\n\twindow.addEventListener(\"message\", onMessage);\n})();\n"
  },
  {
    "path": "flake.nix",
    "content": "{\n  inputs.nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\";\n  description = \"The native part of the Pipewire Screenaudio extension\";\n\n  outputs =\n    { self, nixpkgs }:\n    let\n      forAllSystems = nixpkgs.lib.genAttrs systems;\n      pkgsFor = nixpkgs.legacyPackages;\n      read = builtins.readFile;\n      systems = [\n        \"aarch64-linux\"\n        \"i686-linux\"\n        \"x86_64-linux\"\n      ];\n      write = builtins.toFile;\n\n      mkDate =\n        longDate:\n        with builtins;\n        (concatStringsSep \"-\" [\n          (substring 0 4 longDate)\n          (substring 4 2 longDate)\n          (substring 6 2 longDate)\n        ]);\n\n      manifestJSON = write \"manifest.json\" (read native/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json);\n      connectorPath = \"lib/mozilla/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json\";\n    in\n    {\n      packages = forAllSystems (\n        system:\n        let\n          pkgs = pkgsFor.${system};\n          fs = pkgs.lib.fileset;\n        in\n        rec {\n          default =\n            with pkgs;\n            rustPlatform.buildRustPackage {\n              name = \"pipewire-screenaudio\";\n              version = mkDate (self.lastModifiedDate or \"19700101\") + \"_\" + (self.shortRev or \"dirty\");\n\n              src = ./native/connector-rs;\n              nativeBuildInputs = [\n                pkg-config\n              ];\n              buildInputs = [\n                pipewire\n              ];\n              LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath [\n                libclang\n              ];\n              BINDGEN_EXTRA_CLANG_ARGS = ''\n                -I${glibc.dev}/include\n              '';\n              cargoLock.lockFile = ./native/connector-rs/Cargo.lock;\n\n              postInstall = ''\n                # Firefox manifest\n                install -Dm644 ${manifestJSON} \"$out/${connectorPath}\"\n                substituteInPlace \"$out/${connectorPath}\" \\\n                    --replace \"CONNECTOR_BINARY_PATH\" \"$out/bin/connector-rs\" \\\n                    --replace \"ALLOWED_FIELD\" \"allowed_extensions\" \\\n                    --replace \"ALLOWED_VALUE\" \"pipewire-screenaudio@icenjim\"\n              '';\n            };\n          extension-react = pkgs.stdenvNoCC.mkDerivation (finalAttrs: {\n            pname = \"pipewire-screenaudio-extension-react\";\n            version = \"0.4.2\";\n\n            src = fs.toSource {\n              root = ./.;\n              fileset = fs.unions [\n                ./yarn.lock\n                ./package.json\n                ./extension/react\n              ];\n            };\n\n            yarnOfflineCache = pkgs.fetchYarnDeps {\n              yarnLock = finalAttrs.src + \"/yarn.lock\";\n              hash = \"sha256-Z/4lmw+AiiQycsppLna+Y2uFKd+5RTAUjILQVqN5mOM=\";\n            };\n\n            nativeBuildInputs = with pkgs; [\n              yarnConfigHook\n              yarnBuildHook\n              # Needed for executing package.json scripts\n              nodejs\n            ];\n            installPhase = ''\n              cp -r extension/react/dist $out/\n            '';\n          });\n          extension =\n            pkgs.runCommand \"pipewire-screenaudio-extension\"\n              {\n                src = fs.toSource {\n                  root = ./extension;\n                  fileset = fs.difference ./extension (\n                    fs.fileFilter (file: file.name == \".prettierrc.yml\") ./extension\n                  );\n                };\n                nativeBuildInputs = with pkgs; [\n                  zip\n                ];\n              }\n              ''\n                mkdir -p release\n\n                mkdir -p release/react\n                ln -s ${extension-react} release/react/dist\n\n                cp -r $src/scripts $src/assets $src/manifest.json release/\n\n                cd release\n                zip -r - . > $out\n              '';\n        }\n      );\n      devShells = forAllSystems (\n        system: with pkgsFor.${system}; {\n          default = mkShell {\n            buildInputs = [\n              cargo\n              clippy\n              nodejs\n              pipewire\n              pkg-config\n              rust-analyzer\n              rustc\n              rustfmt\n              yarn\n            ];\n            LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath [\n              libclang\n            ];\n            BINDGEN_EXTRA_CLANG_ARGS = ''\n              -I${glibc.dev}/include\n            '';\n          };\n        }\n      );\n    };\n}\n"
  },
  {
    "path": "install.sh",
    "content": "#!/usr/bin/env bash\nset -e\n\nDEFAULT_CHROMIUM_EXT_ID=\"cbmjbapailadjabjnjnnbfdimkbdicja\"\nREQUIRED_BINS_JS=(\"yarn\")\nREQUIRED_BINS_RUST=(\"cargo\")\n\nprojectRoot=\"$( cd -- \"$(dirname \"$0\")\" > /dev/null 2>&1 ; pwd -P )\"\njsonTemplate=\"$projectRoot/native/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json\"\n\nfunction prompt_yn_question() {\n\tlocal prompt=\"$1\"\n\tlocal default=\"$2\"\n\n\tif [[ \"$default\" == \"Y\" ]]; then\n\t\tpromptPostfix=\"[Y/n]\"\n\t\tdefaultReturn=\"0\"\n\telse\n\t\tpromptPostfix=\"[y/N]\"\n\t\tdefaultReturn=\"1\"\n\tfi\n\n\twhile true; do\n\t\tread -p \"$prompt $promptPostfix: \" yn\n\n\t\t[ -z \"$yn\" ] && return $defaultReturn\n\n\t\tcase $yn in\n\t\t\t[Yy]*) return 0 ;;\n\t\t\t[Nn]*) return 1 ;;\n\t\t\t*) echo \"Please answer yes (y) or no (n).\" ;;\n\t\tesac\n\tdone\n}\n\nfunction prompt_browser_type() {\n\twhile true; do\n\t\tread -p \"Select browser type (1 = Firefox-based, 2 = Chromium-based): \" browser_num\n\n\t\tcase $browser_num in\n\t\t\t1) BROWSER=\"firefox\"; return ;;\n\t\t\t2) BROWSER=\"chromium\"; return ;;\n\t\t\t*) echo -e \"Invalid selection.\\n\" ;;\n\t\tesac\n\tdone\n}\n\nfunction prompt_required_value() {\n\tlocal prompt=\"$1\"\n\tlocal emptyMessage=\"$2\"\n\n\twhile true; do\n\t\tread -p \"$prompt\" returnValue\n\n\t\tif [[ -z \"$returnValue\" ]]; then\n\t\t\t[[ ! -z \"$emptyMessage\" ]] && echo \"$emptyMessage\" >/dev/stderr\n\t\t\tcontinue\n\t\tfi\n\n\t\techo \"$returnValue\"\n\t\tbreak\n\tdone\n}\n\nfunction prompt_native_messaging_hosts_path() {\n\tlocal dir\n\n\twhile true; do\n\t\tdir=$(\n\t\t\tprompt_required_value \\\n\t\t\t\t\"Directory path: \" \\\n\t\t\t\t\"Directory path cannot be empty. Please try again.\"\n\t\t)\n\n\t\tdir=$(eval echo \"$dir\") # Replace ~/ with absolute path\n\t\tif [[ ! -d \"$dir\" ]]; then\n\t\t\techo \"Directory \\\"$dir\\\" does not exist.\"\n\n\t\t\tif prompt_yn_question \"Do you want to create it?\" \"N\"; then\n\t\t\t\tmkdir -p \"$dir\" && echo \"Created directory: $dir\"\n\t\t\telse\n\t\t\t\techo -e \"Please provide a valid directory path or create it.\"\n\t\t\t\tcontinue 2\n\t\t\tfi\n\t\tfi\n\n\t\tDIR=\"$dir\"\n\t\treturn\n\tdone\n}\n\nfunction prompt_chromium_extension_id() {\n\twhile true; do\n\t\tread -p \"Provide the extension ID (default: $DEFAULT_CHROMIUM_EXT_ID). Press enter to use default: \" extid\n\t\tif [[ -z \"$extid\" ]]; then\n\t\t\techo \"$DEFAULT_CHROMIUM_EXT_ID\"\n\t\t\treturn\n\t\telse\n\t\t\techo \"$extid\"\n\t\t\treturn\n\t\tfi\n\tdone\n}\n\nfunction check_required_bins() {\n\tfor bin in \"${@}\"; do\n\t\tif command -v \"$bin\" >/dev/null; then\n\t\t\tcontinue\n\t\tfi\n\n\t\techo \"$bin: command not found\" >/dev/stderr\n\t\texit 1\n\tdone\n}\n\nif [[ \"$DEBUG\" != 1 ]] && ! prompt_yn_question \"Can you confirm that you are following our instructions in INSTALL.md ?\" \"N\"; then\n\techo \"Please read the instructions before proceeding.\" >/dev/stderr\n\techo \"https://github.com/IceDBorn/pipewire-screenaudio/blob/main/INSTALL.md\" >/dev/stderr\n\texit 1\nfi\n\n# Build React\nif prompt_yn_question \"Do you want to build the extension?\" \"N\"; then\n\tcheck_required_bins \"${REQUIRED_BINS_JS[@]}\"\n\t( cd \"$projectRoot/extension/react\" && yarn install && yarn build || exit 1 ) || exit 1\n\techo\nelse\n\techo \"Skipping extension build.\"\nfi\n\n# Build Rust\nwhile true; do\n\tif [[ -f \"/usr/lib/pipewire-screenaudio/connector/connector-rs\" ]] && prompt_yn_question \"Do you want to use the installed native connector binary?\" \"Y\" ; then\n\t\tCONNECTOR_PATH=\"/usr/lib/pipewire-screenaudio/connector/connector-rs\"\n\telif prompt_yn_question \"Do you want to build the native connector?\" \"Y\"; then\n\t\tcheck_required_bins \"${REQUIRED_BINS_RUST[@]}\"\n\t\t( cd \"$projectRoot/native/connector-rs\" && cargo build || exit 1 ) || exit 1\n\t\techo\n\t\tCONNECTOR_PATH=\"$projectRoot/native/connector-rs/target/debug/connector-rs\"\n\telse\n\t\techo -e \"Native connector is required.\\n\" >/dev/stderr\n\t\tcontinue\n\tfi\n\n\tbreak\ndone\n\n# Browser type selection\nprompt_browser_type\n\n# Native messaging hosts path selection\necho -e \"Provide the browser native messaging hosts directory path:\"\nif [[ \"$BROWSER\" == \"firefox\" ]]; then\n\techo \"Example paths: ~/.config/mozilla/firefox/native-messaging-hosts, ~/.mozilla/native-messaging-hosts\"\n\tprompt_native_messaging_hosts_path\n\tALLOWED_FIELD=\"allowed_extensions\"\n\tALLOWED_VALUE=\"pipewire-screenaudio@icenjim\"\nelif [[ \"$BROWSER\" == \"chromium\" ]]; then\n\techo \"Example path: ~/.config/google-chrome/NativeMessagingHosts\"\n\tprompt_native_messaging_hosts_path\n\textid=$(prompt_chromium_extension_id)\n\tALLOWED_FIELD=\"allowed_origins\"\n\tALLOWED_VALUE=\"chrome-extension://$extid/\"\nfi\n\n# Prepare and install json to native messaging hosts path\noutput_json=\"$DIR/com.icedborn.pipewirescreenaudioconnector.json\"\ntmp_json=$(mktemp)\n\n# Replace values in JSON\ncp \"$jsonTemplate\" \"$tmp_json\"\nsed -i \"s|CONNECTOR_BINARY_PATH|$CONNECTOR_PATH|g\" \"$tmp_json\"\nsed -i \"s|ALLOWED_FIELD|$ALLOWED_FIELD|g\" \"$tmp_json\"\nsed -i \"s|ALLOWED_VALUE|$ALLOWED_VALUE|g\" \"$tmp_json\"\n\nif cp \"$tmp_json\" \"$output_json\"; then\n\techo \"Installed native messaging hosts manifest json file to $output_json\"\nelse\n\techo \"Failed to write manifest. Please check permissions and try again.\"\n\texit 1\nfi\n\nrm \"$tmp_json\"\n"
  },
  {
    "path": "native/.gitignore",
    "content": "build\nout\n"
  },
  {
    "path": "native/connector/cli.sh",
    "content": "#!/usr/bin/env bash\n\nexport LC_ALL=C\nexport PROJECT_ROOT=\"$( cd -- \"$(dirname \"$0\")\" > /dev/null 2>&1 ; cd .. ; pwd -P )\"\nsource $PROJECT_ROOT/connector/util.sh\n\ncmd=$1\nargs=$2\n\njson=\"{ \\\"cmd\\\": \\\"$cmd\\\" }\"\nif [[ -n \"$args\" ]]; then\n\tjson=$(echo $json | jq --arg args \"$args\" '. + { args: ($args | fromjson) }')\nfi\n\necho $cmd $args $json >/dev/stderr\n\nUtilTextToMessage \"$json\" \\\n  | (\n    cd $PROJECT_ROOT/connector-rs\n    if [[ \"$DEBUG\" -eq 1 ]]; then\n      export RUST_BACKTRACE=1\n      export RUST_LOG=debug\n    fi\n    cargo run\n  ) \\\n  | ( head -c 4 >/dev/null ; jq )\n"
  },
  {
    "path": "native/connector/util.sh",
    "content": "#!/usr/bin/bash\n\nTEMP_PATH_ROOT=\"$XDG_RUNTIME_DIR/pipewire-screenaudio\"\nFIFO_PATH=\"$TEMP_PATH_ROOT/fifos\"\nLOG_PATH=\"$TEMP_PATH_ROOT/logs\"\n\nmkdir -p $LOG_PATH\nMAIN_LOG_PATH=\"$LOG_PATH/main.log\"\n\nCURRENT_PID=$$\n\nset -e\n\nUtilGetFifoPath () {\n  local virtmicId=\"$1\"\n  mkdir -p $FIFO_PATH\n  printf \"$FIFO_PATH/$virtmicId\"\n}\n\nfunction UtilBinToInt () {\n  head -c 4 |                             # Read 4 bytes\n    hexdump |                             # Read raw bytes as hex\n    head -n 1 |                           # Discard new line\n    awk '{print \"0x\"$3$2}' |              # Format hex number\n    xargs -I {} bash -c 'echo $(( {} ))'  # Return int\n}\n\nfunction UtilIntToBin () {\n  printf '%08x' $1 |                  # Convert integer to 8 digit hex\n    sed 's/\\(..\\)/\\1 /g' |            # Split hex to pairs (bytes)\n    awk '{printf $4 $3 $2 $1}' |      # Reverse order of bytes\n    sed 's/\\(..\\)\\s*/\\\\\\\\x\\1/g' |     # Prefix bytes with \\\\x\n    xargs -I {} bash -c \"printf '{}'\" # Return raw bytes\n}\n\nfunction UtilTextToMessage () {\n  local message=\"$1\"\n  local messageLength=`echo -n \"$message\" | wc -c`\n\n  UtilLog \"[util.sh] [Sending Message] $message Length: $messageLength\"\n\n  UtilIntToBin $messageLength\n  echo -n \"$message\"\n}\n\nfunction UtilGetPayload () {\n  payloadLength=`UtilBinToInt`\n  UtilLog \"[util.sh] [Reading Bytes] $payloadLength\"\n\n  payload=`head -c \"$payloadLength\"`\n  UtilLog \"[util.sh] [Got Payload] $payload\"\n\n  cmd=`echo \"$payload\" | jq -r .cmd`\n  UtilLog \"[util.sh] [Got Cmd] $cmd\"\n\n  args=`echo \"$payload\" | jq .args`\n  UtilLog \"[util.sh] [Got Args] $args\"\n}\n\nfunction UtilGetArg () {\n  local field=\"$1\"\n  UtilLog \"[util.sh] [Reading Arg] $field\"\n  local arg=`echo \"$args\" | jq -rc \".$field\" | head -n 1`\n  UtilLog \"[util.sh] [Arg Value] `[ \"$arg\" = \"\" ] && printf 'null' || printf \"%s\" \"$arg\"`\"\n  printf \"%s\" \"$arg\"\n}\n\nfunction UtilLog () {\n  echo \"$@\" >> $MAIN_LOG_PATH\n  # notify-send \"$@\"\n}\n\nfunction UtilGetLogPathForFile () {\n  mkdir -p \"$LOG_PATH/file\"\n  echo \"$LOG_PATH/file/$1.log\"\n}\n\nfunction UtilGetTempFile () {\n  mkdir -p \"$XDG_RUNTIME_DIR/tmp\"\n  mktemp -p \"$XDG_RUNTIME_DIR/tmp\"\n}\n"
  },
  {
    "path": "native/connector-rs/.gitignore",
    "content": "# Generated by Cargo\n# will have compiled files and executables\ndebug/\ntarget/\n\n# These are backup files generated by rustfmt\n**/*.rs.bk\n\n# MSVC Windows builds of rustc generate these, which store debugging information\n*.pdb\n"
  },
  {
    "path": "native/connector-rs/Cargo.toml",
    "content": "[package]\nname = \"connector-rs\"\nversion = \"0.4.2\"\nedition = \"2021\"\n\n[dependencies]\nserde_json = \"1.0\"\nserde = { version = \"1.0\", features = [\"derive\"] }\npipewire-utils.path = \"pipewire-utils\"\nctrlc.workspace = true\nthiserror.workspace = true\ntracing.workspace = true\ntracing-appender = \"0.2.3\"\ntracing-subscriber.workspace = true\ntracing-panic = { version = \"0.1.2\", features = [\"capture-backtrace\"] }\n\n[workspace]\nmembers = [\"pipewire-utils\"]\nresolver = \"3\"\n\n[workspace.dependencies]\ntracing = \"0.1.41\"\nthiserror = \"2.0.17\"\nctrlc = { version = \"3.5.1\", features = [\"termination\"] }\ntracing-subscriber = { version = \"0.3.20\", features = [\"env-filter\"] }\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/.gitignore",
    "content": "/target\n/Cargo.lock\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/Cargo.toml",
    "content": "[package]\nname = \"pipewire-utils\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\nlibspa = \"0.9.2\"\nlibspa-sys = \"0.9.2\"\npipewire = \"0.9.2\"\npipewire-sys = \"0.9.2\"\ntracing.workspace = true\nthiserror.workspace = true\n\n[dev-dependencies]\nctrlc.workspace = true\ntracing-subscriber.workspace = true\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/examples/all-desktop-audio.rs",
    "content": "use pipewire_utils::{self, cancellation_signal::CancellationSignal, ManagedNode, PipewireClient};\nuse tracing::Level;\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n    tracing_subscriber::fmt()\n        .with_max_level(Level::TRACE)\n        .init();\n\n    let client = PipewireClient::new()?;\n    let node = ManagedNode::create_managed_node(&client, \"test node\")?;\n    tracing::info!(\"created node\");\n\n    let (controller, signal) = CancellationSignal::pair();\n    ctrlc::set_handler(move || {\n        controller.cancel();\n    })\n    .unwrap();\n\n    tracing::info!(\"started monitoring\");\n    client.monitor_and_connect_nodes(node.get_node_with_ports().ports, signal, |_| true)?;\n\n    tracing::info!(\"finishing\");\n\n    Ok(())\n}\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/examples/create-node.rs",
    "content": "use pipewire_utils::PipewireClient;\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n    let client = PipewireClient::new()?;\n\n    let node = client.await_create_node(\"pipewire-screenaudio\")?;\n    dbg!(node);\n\n    Ok(())\n}\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/rustfmt.toml",
    "content": "tab_spaces=4\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/cancellation_signal.rs",
    "content": "use std::{\n    thread::{self, JoinHandle},\n    time::Duration,\n};\n\nuse pipewire::{\n    channel::{channel, AttachedReceiver, Receiver, Sender},\n    loop_::Loop,\n};\n\n#[derive(Debug)]\npub struct TerminateSignal;\n\npub struct CancellationSignal {\n    receiver: Receiver<TerminateSignal>,\n}\n\npub struct AttachedCancellationSignal<'a> {\n    receiver: AttachedReceiver<'a, TerminateSignal>,\n}\n\n#[derive(Clone)]\npub struct CancellationController {\n    sender: Sender<TerminateSignal>,\n}\n\nimpl CancellationSignal {\n    pub fn pair() -> (CancellationController, CancellationSignal) {\n        let (sender, receiver) = channel();\n        (\n            CancellationController { sender },\n            CancellationSignal { receiver },\n        )\n    }\n\n    pub fn attach(\n        self,\n        loop_: &Loop,\n        callback: impl Fn() + 'static,\n    ) -> AttachedCancellationSignal<'_> {\n        AttachedCancellationSignal {\n            receiver: self.receiver.attach(loop_, move |_| callback()),\n        }\n    }\n}\n\nimpl<'a> AttachedCancellationSignal<'a> {\n    pub fn deattach(self) -> CancellationSignal {\n        CancellationSignal {\n            receiver: self.receiver.deattach(),\n        }\n    }\n}\n\npub struct TimeoutHandle {\n    handle: Option<JoinHandle<()>>,\n}\n\nimpl Drop for TimeoutHandle {\n    fn drop(&mut self) {\n        let handle = self\n            .handle\n            .take()\n            .expect(\"handle should always have a value\");\n        handle.thread().unpark();\n        handle.join().unwrap();\n    }\n}\n\nimpl CancellationController {\n    pub fn cancel(&self) {\n        if self.sender.send(TerminateSignal).is_err() {\n            tracing::warn!(\"error while trying to cancel pipewire loop\");\n        }\n    }\n\n    pub fn timeout(&self, duration: Duration) -> TimeoutHandle {\n        let handle = thread::spawn({\n            let cloned_self = self.clone();\n            move || {\n                thread::park_timeout(duration);\n                cloned_self.cancel();\n            }\n        });\n        TimeoutHandle {\n            handle: Some(handle),\n        }\n    }\n}\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/lib.rs",
    "content": "pub mod cancellation_signal;\nmod monitor;\nmod pipewire_client;\nmod pipewire_objects;\nmod proxies;\nmod roundtrip;\nmod utils;\n\npub use pipewire_client::*;\npub use pipewire_objects::{NodeWithPorts, Ports};\npub use utils::ManagedNode;\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/monitor.rs",
    "content": "use std::{\n    cell::{Cell, RefCell},\n    collections::{hash_map::Entry, HashMap, HashSet},\n    rc::Rc,\n};\n\nuse pipewire::{\n    link::Link,\n    proxy::{ProxyListener, ProxyT},\n};\nuse tracing::instrument;\n\nuse crate::pipewire_objects::{OwnedPortInfo, PortInfo};\n\n#[derive(Clone)]\npub struct NodeAndPortsRegistry<AddedCallback, RemovedCallback> {\n    relevant_nodes: Rc<RefCell<HashSet<u32>>>,\n    nodes_to_ports: Rc<RefCell<HashMap<u32, HashSet<u32>>>>,\n    ports: Rc<RefCell<HashMap<u32, OwnedPortInfo>>>,\n    relevant_port_added_callback: Option<AddedCallback>,\n    relevant_port_removed_callback: Option<RemovedCallback>,\n}\n\nimpl<AddedCallback, RemovedCallback> Default\n    for NodeAndPortsRegistry<AddedCallback, RemovedCallback>\n{\n    fn default() -> Self {\n        Self {\n            relevant_nodes: Rc::new(RefCell::new(HashSet::new())),\n            nodes_to_ports: Rc::new(RefCell::new(HashMap::<u32, HashSet<u32>>::new())),\n            ports: Rc::new(RefCell::new(HashMap::<u32, OwnedPortInfo>::new())),\n            relevant_port_added_callback: None,\n            relevant_port_removed_callback: None,\n        }\n    }\n}\n\nimpl<AddedCallback: Fn(&OwnedPortInfo), RemovedCallback: Fn(&OwnedPortInfo)>\n    NodeAndPortsRegistry<AddedCallback, RemovedCallback>\n{\n    pub fn set_relevant_port_added_callback(&mut self, callback: AddedCallback) {\n        self.relevant_port_added_callback = Some(callback);\n    }\n\n    pub fn set_relevant_port_removed_callback(&mut self, callback: RemovedCallback) {\n        self.relevant_port_removed_callback = Some(callback);\n    }\n\n    fn invoke_for_all_ports_in_node<F: Fn(&OwnedPortInfo)>(&self, node_id: u32, callback: F) {\n        if let Some(port_ids) = self.nodes_to_ports.borrow().get(&node_id) {\n            let ports = self.ports.borrow();\n            for port_id in port_ids {\n                let port_info = ports.get(port_id).expect(\"there must be info\");\n\n                callback(port_info);\n            }\n        }\n    }\n\n    pub fn is_node_relevant(&self, node_id: u32) -> bool {\n        self.relevant_nodes.borrow().contains(&node_id)\n    }\n\n    #[instrument(skip(self))]\n    pub fn add_relevant_node(&self, node_id: u32) {\n        self.relevant_nodes.borrow_mut().insert(node_id);\n\n        if let Some(callback) = &self.relevant_port_added_callback {\n            self.invoke_for_all_ports_in_node(node_id, callback);\n        }\n    }\n\n    #[instrument(skip(self))]\n    pub fn try_remove_relevant_node(&self, node_id: u32) -> bool {\n        let removed = self.relevant_nodes.borrow_mut().remove(&node_id);\n\n        if removed {\n            if let Some(callback) = &self.relevant_port_removed_callback {\n                self.invoke_for_all_ports_in_node(node_id, callback);\n            }\n        }\n\n        removed\n    }\n\n    #[instrument(skip(self))]\n    pub fn add_port(&self, port_info: PortInfo<'_>) {\n        match self.nodes_to_ports.borrow_mut().entry(port_info.node_id) {\n            Entry::Vacant(entry) => {\n                entry.insert(HashSet::from_iter([port_info.id]));\n            }\n            Entry::Occupied(mut entry) => {\n                let node_ports = entry.get_mut();\n                node_ports.insert(port_info.id);\n            }\n        }\n\n        let port_info = OwnedPortInfo::from(port_info);\n\n        if self.relevant_nodes.borrow().contains(&port_info.node_id) {\n            tracing::trace!(port_id = port_info.id, \"port is from a relevant node\");\n            if let Some(callback) = &self.relevant_port_added_callback {\n                callback(&port_info);\n            }\n        }\n\n        self.ports.borrow_mut().insert(port_info.id, port_info);\n    }\n\n    #[instrument(skip(self))]\n    pub fn try_remove_port(&self, port_id: u32) -> Option<OwnedPortInfo> {\n        let port_info = self.ports.borrow_mut().remove(&port_id);\n        if let Some(port_info) = port_info.as_ref() {\n            if self.relevant_nodes.borrow().contains(&port_info.node_id) {\n                if let Some(callback) = &self.relevant_port_removed_callback {\n                    callback(port_info);\n                }\n            }\n            self.nodes_to_ports\n                .borrow_mut()\n                .get_mut(&port_info.node_id)\n                .unwrap()\n                .remove(&port_id);\n        }\n        port_info\n    }\n}\n\npub struct LinkTrackerHandle {\n    #[expect(unused)]\n    listener: ProxyListener,\n    id: Rc<Cell<Option<u32>>>,\n}\n\nimpl LinkTrackerHandle {\n    pub fn new(link: Link) -> Self {\n        let id = Rc::new(Cell::new(None));\n        let listener = link\n            .upcast()\n            .add_listener_local()\n            .bound({\n                let id = id.clone();\n                move |link_id| {\n                    id.set(Some(link_id));\n                }\n            })\n            .register();\n        Self { listener, id }\n    }\n\n    pub fn id(&self) -> Option<u32> {\n        self.id.get()\n    }\n}\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/pipewire_client.rs",
    "content": "use std::{\n    cell::{OnceCell, RefCell},\n    collections::{HashMap, HashSet},\n    rc::Rc,\n};\n\nuse libspa::utils::dict::DictRef;\nuse pipewire::{\n    context::ContextRc,\n    core::CoreRc,\n    keys,\n    link::Link,\n    main_loop::MainLoopRc,\n    node::{Node, NodeChangeMask, NodeInfoRef},\n    properties::properties,\n    proxy::ProxyT,\n    registry::{GlobalObject, Listener, RegistryRc},\n    types::ObjectType,\n};\nuse thiserror::Error;\nuse tracing::instrument;\n\nuse crate::{\n    cancellation_signal::CancellationSignal,\n    monitor::{LinkTrackerHandle, NodeAndPortsRegistry},\n    pipewire_objects::*,\n    proxies::ProxyRefs,\n    roundtrip::{Scheduler, StopSettings, StopSettingsBuilder},\n};\n\n#[derive(Error, Debug)]\n#[error(\"internal pipewire error {0:?}\")]\npub struct PipewireError(#[from] pipewire::Error);\n\npub type Result<T, E = PipewireError> = std::result::Result<T, E>;\n\n#[derive(Clone)]\npub struct PipewireClient {\n    mainloop: MainLoopRc,\n    #[allow(unused)]\n    context: ContextRc,\n    core: CoreRc,\n}\n\npub enum IterationAction {\n    Stop,\n    ScheduleRoundtrip,\n}\n\n#[derive(Clone)]\nstruct IterationContext {\n    registry: RegistryRc,\n    scheduler: Scheduler,\n}\n\n#[derive(Debug)]\npub struct NodeProperties {\n    pub application_name: Option<String>,\n    pub media_name: String,\n    pub object_serial: i64,\n\n    pub media_class: String,\n}\n\n#[derive(Debug)]\npub struct OutputNode {\n    pub id: u32,\n    pub properties: NodeProperties,\n}\n\n#[derive(Error, Debug)]\npub enum OutputNodeCreationError {\n    #[error(\"missing property dictionary\")]\n    MissingPropertyDict,\n    #[error(\"missing some properties: {properties:?}\")]\n    MissingProperties { properties: Vec<&'static str> },\n}\n\nimpl TryFrom<&NodeInfoRef> for OutputNode {\n    type Error = OutputNodeCreationError;\n    fn try_from(value: &NodeInfoRef) -> Result<Self, Self::Error> {\n        let Some(props) = value.props() else {\n            return Err(OutputNodeCreationError::MissingPropertyDict);\n        };\n        let application_name = props.get(\"application.name\");\n        let object_serial = props.get(\"object.serial\");\n        let media_class = props.get(\"media.class\");\n        let media_name = props.get(\"media.name\");\n        let (Some(object_serial), Some(media_class), Some(media_name)) =\n            (object_serial, media_class, media_name)\n        else {\n            return Err(OutputNodeCreationError::MissingProperties {\n                properties: [\n                    (object_serial, \"object.serial\"),\n                    (media_class, \"media.class\"),\n                    (media_name, \"media.name\"),\n                ]\n                .into_iter()\n                .flat_map(|(prop, name)| prop.is_none().then_some(name))\n                .collect(),\n            });\n        };\n\n        Ok(OutputNode {\n            id: value.id(),\n            properties: {\n                NodeProperties {\n                    application_name: application_name.map(|s| s.to_owned()),\n                    media_name: media_name.to_owned(),\n                    object_serial: object_serial.parse().unwrap(),\n                    media_class: media_class.to_owned(),\n                }\n            },\n        })\n    }\n}\nimpl IterationContext {\n    #[instrument(skip_all)]\n    fn stop(&self) {\n        tracing::trace!(\"stopping scheduler\");\n        self.scheduler.stop();\n    }\n\n    #[instrument(skip_all)]\n    fn schedule_roundtrip(&self) {\n        tracing::trace!(\"scheduling roundtrip\");\n        self.scheduler.schedule_roundtrip();\n    }\n}\n\nstruct NodeListenerHandle {\n    #[allow(unused)]\n    registry_listener: Listener,\n    #[allow(unused)]\n    proxies: Rc<RefCell<ProxyRefs>>,\n}\n\nimpl PipewireClient {\n    pub fn new() -> Result<Self> {\n        let mainloop = MainLoopRc::new(None)?;\n        let context = ContextRc::new(&mainloop, None)?;\n        let core = context.connect_rc(None)?;\n\n        Ok(Self {\n            mainloop,\n            context,\n            core,\n        })\n    }\n\n    fn create_scheduler(&self) -> Scheduler {\n        //let mainloop = MainLoopRc::new(None).unwrap();\n        //let context = ContextRc::new(&mainloop, None).unwrap();\n        //let core = context.connect_rc(None).unwrap();\n\n        //Scheduler::new(mainloop, core)\n        Scheduler::new(self.mainloop.clone(), self.core.clone())\n    }\n\n    fn do_roundtrip(&self) {\n        self.create_scheduler().run(\n            StopSettingsBuilder::default()\n                .stop_on_last_roundtrip()\n                .build(),\n        );\n    }\n\n    fn iterate_globals(\n        &self,\n        stop_settings: StopSettings,\n        global_callback: impl Fn(&IterationContext, &GlobalObject<&DictRef>) + 'static,\n    ) {\n        let scheduler = self.create_scheduler();\n\n        let registry = self.core.get_registry_rc().unwrap();\n\n        let iteration_context = IterationContext {\n            registry: registry.clone(),\n            scheduler: scheduler.clone(),\n        };\n        let reg_listener = registry\n            .add_listener_local()\n            .global(move |global| global_callback(&iteration_context, global))\n            .register();\n\n        scheduler.run(stop_settings);\n\n        drop(reg_listener);\n    }\n\n    fn add_node_listener<F, DF>(\n        &self,\n        registry: RegistryRc,\n        node_callback: F,\n        node_destroy_callback: DF,\n        scheduler: Option<Scheduler>,\n    ) -> NodeListenerHandle\n    where\n        F: Fn(&NodeInfoRef) + Clone + 'static,\n        DF: Fn(u32) + 'static,\n    {\n        let proxies: Rc<RefCell<ProxyRefs>> = Rc::new(RefCell::new(ProxyRefs::new()));\n\n        let listener = registry\n            .add_listener_local()\n            .global({\n                let proxies = proxies.clone();\n                let registry = registry.clone();\n                move |global| {\n                    if !matches!(global.type_, ObjectType::Node) {\n                        return;\n                    }\n                    let Ok(proxy) = registry.bind::<Node, _>(global) else {\n                        tracing::trace!(\"global {} is not assignable to node\", global.id);\n                        return;\n                    };\n                    let listener = proxy\n                        .add_listener_local()\n                        .info({\n                            let node_callback = node_callback.clone();\n                            move |node| {\n                                node_callback(node);\n                            }\n                        })\n                        .register();\n                    if let Some(scheduler) = scheduler.as_ref() {\n                        scheduler.schedule_roundtrip();\n                    }\n                    proxies\n                        .borrow_mut()\n                        .add_proxy(Box::new(proxy), vec![Box::new(listener)]);\n                }\n            })\n            .global_remove({\n                let proxies = proxies.clone();\n                move |global_id| {\n                    if proxies.borrow_mut().remove_proxy(&global_id) {\n                        node_destroy_callback(global_id);\n                    }\n                }\n            })\n            .register();\n\n        NodeListenerHandle {\n            registry_listener: listener,\n            proxies,\n        }\n    }\n\n    fn iterate_nodes<F>(&self, stop_settings: StopSettings, object_callback: F)\n    where\n        F: Fn(&IterationContext, &NodeInfoRef) + Clone + 'static,\n    {\n        let scheduler = self.create_scheduler();\n\n        let registry = self.core.get_registry_rc().unwrap();\n\n        let iteration_context = IterationContext {\n            registry: registry.clone(),\n            scheduler: scheduler.clone(),\n        };\n        let reg_listener = self.add_node_listener(\n            registry,\n            move |node| object_callback(&iteration_context, node),\n            |_| {},\n            Some(scheduler.clone()),\n        );\n        scheduler.run(stop_settings);\n\n        drop(reg_listener);\n    }\n\n    fn extract_port_info<'a>(global: &'a GlobalObject<&'a DictRef>) -> Option<PortInfo<'a>> {\n        let props = global.props?;\n\n        if global.type_ != ObjectType::Port {\n            return None;\n        }\n\n        let id: u32 = global.id;\n        let node_id = props.get(*keys::NODE_ID)?.parse().unwrap();\n        let direction = props.get(*keys::PORT_DIRECTION)?.parse().unwrap();\n        let channel = AudioChannel::from(props.get(*keys::AUDIO_CHANNEL)?);\n        Some(PortInfo {\n            channel,\n            id,\n            node_id,\n            direction,\n        })\n    }\n\n    fn is_global_a_port_for_node<'a>(\n        global: &'a GlobalObject<&'a DictRef>,\n        direction: PortDirection,\n        node_id: u32,\n    ) -> Option<PortInfo<'a>> {\n        let port_info = Self::extract_port_info(global)?;\n\n        (port_info.node_id == node_id && port_info.direction == direction).then_some(port_info)\n    }\n\n    fn find_fl_fr_ports(\n        &self,\n        node_id: u32,\n        direction: PortDirection,\n        only_existent: bool,\n    ) -> MaybePorts {\n        let fl_port = Rc::new(OnceCell::new());\n        let fr_port = Rc::new(OnceCell::new());\n\n        self.iterate_globals(\n            StopSettingsBuilder::default()\n                .set_stop_on_last_roundtrip(only_existent)\n                .build(),\n            {\n                let fl_port = fl_port.clone();\n                let fr_port = fr_port.clone();\n                move |iteration_context, global| {\n                    let Some(port) = Self::is_global_a_port_for_node(global, direction, node_id)\n                    else {\n                        return;\n                    };\n\n                    tracing::debug!(port_id = port.id, node_id, \"found port for node\");\n                    // Save port id into channel cell\n                    if let Some(channel_cell) = match port.channel {\n                        AudioChannel::FrontLeft => Some(&fl_port),\n                        AudioChannel::FrontRight => Some(&fr_port),\n                        AudioChannel::Other(_) => None,\n                    } {\n                        channel_cell\n                            .set(port.id)\n                            .expect(\"Node has multiple ports for same channel\");\n                    }\n\n                    // Stop searching if we found all ports\n                    let found_all_ports = [&fl_port, &fr_port]\n                        .iter()\n                        .all(|port_id| port_id.get().is_some());\n\n                    tracing::trace!(found_all_ports);\n\n                    if found_all_ports {\n                        iteration_context.stop();\n                    }\n                }\n            },\n        );\n\n        let fl_port = Rc::into_inner(fl_port).unwrap().into_inner();\n        let fr_port = Rc::into_inner(fr_port).unwrap().into_inner();\n\n        MaybePorts { fl_port, fr_port }\n    }\n\n    fn await_find_fl_fr_ports(&self, node_id: u32, direction: PortDirection) -> Ports {\n        self.find_fl_fr_ports(node_id, direction, false)\n            .both()\n            .unwrap()\n    }\n\n    pub fn await_create_node(&self, node_name: impl AsRef<str>) -> Result<NodeWithPorts> {\n        let node = self.core.create_object::<Node>(\n            \"adapter\",\n            &properties! {\n                *keys::FACTORY_NAME => \"support.null-audio-sink\",\n                *keys::NODE_NAME => node_name.as_ref(),\n                *keys::NODE_DESCRIPTION => node_name.as_ref(),\n                *keys::MEDIA_CLASS => \"Audio/Source/Virtual\",\n                \"audio.position\" => \"[FL, FR]\",\n                *keys::OBJECT_LINGER => \"1\",\n            },\n        )?;\n\n        Ok(self.await_node_creation(node))\n    }\n\n    pub fn destroy_global(&self, global_id: u32) -> Result<()> {\n        let registry = self.core.get_registry()?;\n        registry.destroy_global(global_id);\n        self.do_roundtrip();\n        Ok(())\n    }\n\n    fn unlink_ports(&self, ports: HashSet<u32>) {\n        tracing::debug!(?ports, \"removing links to ports\");\n        let is_link_to_port = move |global: &GlobalObject<&DictRef>| {\n            if global.type_ != ObjectType::Link {\n                return false;\n            }\n            let Some(props) = global.props else {\n                return false;\n            };\n            let Some(output_port) = props.get(\"link.input.port\") else {\n                return false;\n            };\n            let Ok(output_port) = output_port.parse::<u32>() else {\n                return false;\n            };\n            ports.contains(&output_port)\n        };\n\n        self.iterate_globals(\n            StopSettingsBuilder::default()\n                .stop_on_last_roundtrip()\n                .build(),\n            {\n                move |iteration_context, global| {\n                    if is_link_to_port(global) {\n                        tracing::trace!(link_id = global.id, \"removing link\");\n                        iteration_context.registry.destroy_global(global.id);\n                        iteration_context.schedule_roundtrip();\n                    }\n                }\n            },\n        );\n        tracing::trace!(\"links removed\");\n    }\n\n    pub fn unlink_node_ports(&self, ports: Ports) {\n        self.unlink_ports(HashSet::from_iter([ports.fl_port, ports.fr_port]));\n    }\n\n    fn await_node_creation(&self, node: Node) -> NodeWithPorts {\n        let node_id = Rc::new(OnceCell::new());\n\n        tracing::trace!(\"awaiting to find node\");\n        let listener = node\n            .upcast()\n            .add_listener_local()\n            .bound({\n                let node_id = node_id.clone();\n                move |id| {\n                    tracing::trace!(\"node {id} was bound\");\n                    node_id.set(id).unwrap()\n                }\n            })\n            .register();\n\n        self.do_roundtrip();\n        drop(listener);\n\n        let node_id = Rc::into_inner(node_id).unwrap().into_inner().unwrap();\n\n        tracing::trace!(\"awaiting to find ports\");\n        let ports = self.await_find_fl_fr_ports(node_id, PortDirection::Input);\n\n        NodeWithPorts { id: node_id, ports }\n    }\n\n    fn link_ports(&self, from: u32, to: u32) -> Result<Link, pipewire::Error> {\n        self.core.create_object::<Link>(\n            \"link-factory\",\n            &properties! {\n                *keys::LINK_INPUT_PORT => to.to_string(),\n                *keys::LINK_OUTPUT_PORT => from.to_string(),\n                *keys::OBJECT_LINGER => \"1\",\n            },\n        )\n    }\n\n    #[instrument(skip(self))]\n    fn try_link_ports(&self, from: u32, to: u32) {\n        match self.link_ports(from, to) {\n            Err(err) => tracing::warn!(\"failed to link ports: {err}\"),\n            Ok(_) => tracing::trace!(\"linked ports\"),\n        };\n    }\n\n    pub fn link_nodes(&self, from_id: u32, to_ports: Ports) {\n        let from_ports = self.find_fl_fr_ports(from_id, PortDirection::Output, true);\n\n        let ports = [from_ports.fl_port, from_ports.fr_port]\n            .into_iter()\n            .zip([to_ports.fl_port, to_ports.fr_port])\n            .zip([AudioChannel::FrontLeft, AudioChannel::FrontRight]);\n\n        for ((from, to), channel) in ports {\n            let Some(from) = from else {\n                tracing::warn!(\"missing output port for channel {channel:?} in node {from_id}\");\n                continue;\n            };\n            self.try_link_ports(from, to);\n        }\n        self.do_roundtrip();\n    }\n\n    pub fn monitor_and_connect_nodes(\n        &self,\n        target_ports: Ports,\n        cancellation_signal: CancellationSignal,\n        media_name_filter: impl Fn(Option<&str>) -> bool + Clone + 'static,\n    ) -> Result<()> {\n        let scheduler = self.create_scheduler();\n        let registry = self.core.get_registry_rc()?;\n\n        let links_by_port = Rc::new(RefCell::new(HashMap::new()));\n\n        let mut node_and_ports_registry = NodeAndPortsRegistry::default();\n        node_and_ports_registry.set_relevant_port_added_callback({\n            let client = self.clone();\n            let links_by_port = links_by_port.clone();\n            move |port_info| {\n                let Some(channel) = port_info.channel else {\n                    tracing::debug!(\n                        port = port_info.id,\n                        channel = ?port_info.channel,\n                        \"unmapped channel\"\n                    );\n                    return;\n                };\n                let target_port = target_ports.get_stereo_channel(&channel);\n                match client.link_ports(port_info.id, target_port) {\n                    Ok(link) => {\n                        if let Some(prev_handle) = links_by_port\n                            .borrow_mut()\n                            .insert(port_info.id, LinkTrackerHandle::new(link))\n                        {\n                            tracing::warn!(\n                                prev_id = prev_handle.id(),\n                                \"linked twice without unlinking\"\n                            );\n                        }\n                        tracing::debug!(source_port = port_info.id, target_port, \"linked ports\");\n                    }\n                    Err(err) => {\n                        tracing::warn!(?err, \"error while trying to link ports\");\n                    }\n                }\n            }\n        });\n        node_and_ports_registry.set_relevant_port_removed_callback({\n            let registry = registry.clone();\n            let links_by_port = links_by_port.clone();\n            move |port_info| {\n                let port_id = port_info.id;\n                tracing::debug!(port_id, \"port is no longer relevant, unlinking\");\n                let Some(link_handle) = links_by_port.borrow_mut().remove(&port_id) else {\n                    tracing::warn!(\n                        port_id,\n                        \"trying to unlink port, but link is not being tracked\"\n                    );\n                    return;\n                };\n                let Some(link_id) = link_handle.id() else {\n                    tracing::warn!(port_id, \"link does not have a defined id\");\n                    return;\n                };\n                registry.destroy_global(link_id);\n            }\n        });\n\n        let node_listener = self.add_node_listener(\n            registry.clone(),\n            {\n                let node_and_ports_registry = node_and_ports_registry.clone();\n                move |node| {\n                    let node_id: u32 = node.id();\n\n                    if !node.change_mask().contains(NodeChangeMask::PROPS) {\n                        return;\n                    }\n\n                    let is_node_relevant = node.props().is_some_and(|props| {\n                        props.get(*keys::MEDIA_CLASS) == Some(\"Stream/Output/Audio\")\n                            && media_name_filter(props.get(*keys::MEDIA_NAME))\n                    });\n\n                    tracing::trace!(node_id, is_node_relevant, \"node props updated\");\n                    let was_node_relevant = node_and_ports_registry.is_node_relevant(node_id);\n                    if was_node_relevant != is_node_relevant {\n                        if is_node_relevant {\n                            node_and_ports_registry.add_relevant_node(node_id);\n                        } else {\n                            node_and_ports_registry.try_remove_relevant_node(node_id);\n                        }\n                    } else {\n                        tracing::trace!(node_id, \"node relevancy has not changed\");\n                    }\n                }\n            },\n            {\n                let node_and_ports_registry = node_and_ports_registry.clone();\n                move |node_id| {\n                    tracing::trace!(node_id, \"node removed\");\n                    node_and_ports_registry.try_remove_relevant_node(node_id);\n                }\n            },\n            None,\n        );\n\n        let port_listener = registry\n            .add_listener_local()\n            .global({\n                let node_and_ports_registry = node_and_ports_registry.clone();\n                move |global_object| {\n                    let Some(port_info) = Self::extract_port_info(global_object) else {\n                        return;\n                    };\n\n                    if port_info.direction != PortDirection::Output {\n                        return;\n                    }\n\n                    tracing::trace!(port_id = port_info.id, \"port created\");\n                    node_and_ports_registry.add_port(port_info);\n                }\n            })\n            .global_remove({\n                let node_and_ports_registry = node_and_ports_registry.clone();\n                move |global_id| {\n                    if node_and_ports_registry.try_remove_port(global_id).is_some() {\n                        tracing::trace!(port_id = global_id, \"port removed\");\n                    }\n                }\n            })\n            .register();\n\n        scheduler.run(cancellation_signal.into());\n\n        drop(node_listener);\n        drop(port_listener);\n\n        Ok(())\n    }\n\n    pub fn find_node_by_name(&self, node_name: impl AsRef<str> + 'static) -> Option<u32> {\n        let result = Rc::new(OnceCell::new());\n        self.iterate_nodes(\n            StopSettingsBuilder::default()\n                .stop_on_last_roundtrip()\n                .build(),\n            {\n                let result = result.clone();\n                let node_name = Rc::new(node_name);\n                move |iteration_context, node| {\n                    if node\n                        .props()\n                        .and_then(|props| props.get(*pipewire::keys::NODE_NAME))\n                        .is_some_and(|name| (*node_name).as_ref() == name)\n                    {\n                        result.set(node.id()).unwrap();\n                        iteration_context.stop();\n                    }\n                }\n            },\n        );\n        Rc::try_unwrap(result).unwrap().into_inner()\n    }\n\n    pub fn list_output_nodes(&self) -> Vec<OutputNode> {\n        let output_nodes = Rc::new(RefCell::new(vec![]));\n        tracing::trace!(\"iterating over nodes\");\n        self.iterate_nodes(\n            StopSettingsBuilder::default()\n                .stop_on_last_roundtrip()\n                .build(),\n            {\n                let output_nodes = output_nodes.clone();\n                move |_iteration_context, node| match OutputNode::try_from(node) {\n                    Ok(node) => {\n                        if node.properties.media_class == \"Stream/Output/Audio\" {\n                            tracing::trace!(?node, \"adding node\");\n                            output_nodes.borrow_mut().push(node);\n                        } else {\n                            tracing::trace!(node_id = node.id, \"node is not an output\");\n                        }\n                    }\n                    Err(err) => {\n                        tracing::trace!(\n                            node_id = node.id(),\n                            ?err,\n                            \"node does not contain all required properties\",\n                        )\n                    }\n                }\n            },\n        );\n        Rc::into_inner(output_nodes).unwrap().into_inner()\n    }\n\n    pub fn get_node_id_from_object_serial(&self, serial: i64) -> Option<u32> {\n        let result = Rc::new(OnceCell::new());\n        self.iterate_nodes(\n            StopSettingsBuilder::default()\n                .stop_on_last_roundtrip()\n                .build(),\n            {\n                let result = result.clone();\n                move |iteration_context, node| {\n                    let Ok(node) = OutputNode::try_from(node) else {\n                        return;\n                    };\n                    if node.properties.object_serial == serial {\n                        result.set(node.id).unwrap();\n                        iteration_context.stop();\n                    }\n                }\n            },\n        );\n        Rc::try_unwrap(result).unwrap().into_inner()\n    }\n}\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/pipewire_objects.rs",
    "content": "use std::str::FromStr;\n\nuse thiserror::Error;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum PortDirection {\n    Input,\n    Output,\n}\n\n#[derive(Debug)]\npub struct InvalidPortError;\nimpl FromStr for PortDirection {\n    type Err = InvalidPortError;\n    fn from_str(s: &str) -> Result<Self, Self::Err> {\n        match s {\n            \"in\" => Ok(PortDirection::Input),\n            \"out\" => Ok(PortDirection::Output),\n            _ => Err(InvalidPortError),\n        }\n    }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum AudioChannel<'a> {\n    FrontLeft,\n    FrontRight,\n    Other(&'a str),\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum StereoAudioChannel {\n    FrontLeft,\n    FrontRight,\n}\n\nimpl<'a> From<&'a str> for AudioChannel<'a> {\n    fn from(value: &'a str) -> Self {\n        match value {\n            \"FL\" => AudioChannel::FrontLeft,\n            \"FR\" => AudioChannel::FrontRight,\n            s => AudioChannel::Other(s),\n        }\n    }\n}\n\n#[derive(Debug, Clone, Copy)]\npub struct Ports {\n    pub fl_port: u32,\n    pub fr_port: u32,\n}\n\nimpl Ports {\n    pub fn get_stereo_channel(&self, channel: &StereoAudioChannel) -> u32 {\n        match channel {\n            StereoAudioChannel::FrontLeft => self.fl_port,\n            StereoAudioChannel::FrontRight => self.fr_port,\n        }\n    }\n    pub fn get_channel<'a>(&self, channel: &AudioChannel<'a>) -> Option<&u32> {\n        match channel {\n            AudioChannel::FrontLeft => Some(&self.fl_port),\n            AudioChannel::FrontRight => Some(&self.fr_port),\n            AudioChannel::Other(_) => None,\n        }\n    }\n}\n\n#[derive(Debug, Clone, Copy)]\npub struct NodeWithPorts {\n    pub id: u32,\n    pub ports: Ports,\n}\n\n#[derive(Debug, Clone, Copy)]\npub struct MaybePorts {\n    pub fl_port: Option<u32>,\n    pub fr_port: Option<u32>,\n}\n\nimpl MaybePorts {\n    pub fn both(self) -> Option<Ports> {\n        let MaybePorts { fl_port, fr_port } = self;\n        let fl_port = fl_port?;\n        let fr_port = fr_port?;\n        Some(Ports { fl_port, fr_port })\n    }\n}\n\n#[derive(Debug, Clone, Copy)]\npub struct PortInfo<'a> {\n    pub(crate) channel: AudioChannel<'a>,\n    pub(crate) node_id: u32,\n    pub(crate) id: u32,\n    pub(crate) direction: PortDirection,\n}\n\n#[derive(Error, Debug)]\n#[error(\"port channel is not stereo\")]\npub struct ChannelIsNotStereoError;\nimpl<'a> TryFrom<AudioChannel<'a>> for StereoAudioChannel {\n    type Error = ChannelIsNotStereoError;\n    fn try_from(value: AudioChannel<'a>) -> Result<Self, Self::Error> {\n        match value {\n            AudioChannel::FrontLeft => Ok(StereoAudioChannel::FrontLeft),\n            AudioChannel::FrontRight => Ok(StereoAudioChannel::FrontRight),\n            AudioChannel::Other(_) => Err(ChannelIsNotStereoError),\n        }\n    }\n}\n\npub struct OwnedPortInfo {\n    pub(crate) channel: Option<StereoAudioChannel>,\n    pub(crate) node_id: u32,\n    pub(crate) id: u32,\n    #[allow(unused)]\n    pub(crate) direction: PortDirection,\n}\n\nimpl<'a> From<PortInfo<'a>> for OwnedPortInfo {\n    fn from(\n        PortInfo {\n            channel,\n            node_id,\n            id,\n            direction,\n        }: PortInfo<'a>,\n    ) -> Self {\n        OwnedPortInfo {\n            id,\n            node_id,\n            channel: channel.try_into().ok(),\n            direction,\n        }\n    }\n}\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/proxies.rs",
    "content": "use std::collections::HashMap;\n\nuse pipewire::proxy::{Listener, ProxyT};\n\npub struct ProxyRef {\n    _proxy: Box<dyn ProxyT>,\n    _listeners: Vec<Box<dyn Listener>>,\n}\n\n#[derive(Default)]\npub struct ProxyRefs {\n    refs: HashMap<u32, ProxyRef>,\n}\n\nimpl ProxyRefs {\n    pub fn new() -> Self {\n        Self::default()\n    }\n\n    pub fn add_proxy(&mut self, proxy: Box<dyn ProxyT>, listeners: Vec<Box<dyn Listener>>) {\n        let proxy_id = {\n            let proxy = proxy.upcast_ref();\n            proxy.id()\n        };\n\n        self.refs.insert(\n            proxy_id,\n            ProxyRef {\n                _proxy: proxy,\n                _listeners: listeners,\n            },\n        );\n    }\n\n    pub fn remove_proxy(&mut self, proxy_id: &u32) -> bool {\n        self.refs.remove(proxy_id).is_some()\n    }\n}\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/roundtrip.rs",
    "content": "use std::{cell::Cell, fmt::Debug, rc::Rc};\n\nuse libspa::utils::result::AsyncSeq;\nuse pipewire::{\n    core::{CoreRc, PW_ID_CORE},\n    main_loop::MainLoopRc,\n};\nuse tracing::instrument;\n\nuse crate::cancellation_signal::CancellationSignal;\n\n#[derive(Clone)]\npub struct Scheduler {\n    sync_seq: Rc<Cell<Option<AsyncSeq>>>,\n    mainloop: MainLoopRc,\n    core: CoreRc,\n    done: Rc<Cell<bool>>,\n}\n\npub struct StopSettings {\n    on_last_roundtrip: bool,\n    signal_receiver: Option<CancellationSignal>,\n}\n\nimpl Debug for StopSettings {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        f.write_fmt(format_args!(\n            \"StopSettings {{ on_last_roundtrip: {}, signal_receiver: {} }}\",\n            self.on_last_roundtrip,\n            self.signal_receiver\n                .as_ref()\n                .map(|_| \"Some(...)\")\n                .unwrap_or(\"None\")\n        ))\n    }\n}\n\nimpl From<CancellationSignal> for StopSettings {\n    fn from(value: CancellationSignal) -> Self {\n        StopSettingsBuilder::default().stop_on_signal(value).build()\n    }\n}\n\npub struct StopSettingsBuilder {\n    on_last_roundtrip: bool,\n    signal_receiver: Option<CancellationSignal>,\n}\n\n#[allow(clippy::derivable_impls)]\nimpl Default for StopSettingsBuilder {\n    fn default() -> Self {\n        Self {\n            on_last_roundtrip: false,\n            signal_receiver: None,\n        }\n    }\n}\nimpl StopSettingsBuilder {\n    pub fn stop_on_last_roundtrip(mut self) -> Self {\n        self.on_last_roundtrip = true;\n        self\n    }\n\n    pub fn set_stop_on_last_roundtrip(mut self, value: bool) -> Self {\n        self.on_last_roundtrip = value;\n        self\n    }\n\n    pub fn stop_on_signal(mut self, receiver: CancellationSignal) -> Self {\n        self.signal_receiver = Some(receiver);\n        self\n    }\n\n    pub fn build(self) -> StopSettings {\n        StopSettings {\n            on_last_roundtrip: self.on_last_roundtrip,\n            signal_receiver: self.signal_receiver,\n        }\n    }\n}\n\nimpl Scheduler {\n    pub fn new(mainloop: MainLoopRc, core: CoreRc) -> Self {\n        Self {\n            mainloop,\n            core,\n            sync_seq: Default::default(),\n            done: Default::default(),\n        }\n    }\n\n    #[instrument(skip(self))]\n    pub fn schedule_roundtrip(&self) {\n        tracing::trace!(\"sending sync\");\n        self.sync_seq.replace(Some(self.core.sync(0).unwrap()));\n    }\n\n    pub fn stop(&self) {\n        self.mainloop.quit();\n        self.done.set(true);\n    }\n\n    #[instrument(skip(self, stop_settings))]\n    pub fn run(self, stop_settings: StopSettings) {\n        let mut listener_core = None;\n        if stop_settings.on_last_roundtrip {\n            self.schedule_roundtrip();\n            listener_core = Some(\n                self.core\n                    .add_listener_local()\n                    .done({\n                        let done = self.done.clone();\n                        let mainloop = self.mainloop.clone();\n                        let sync_seq = self.sync_seq.clone();\n                        move |id, seq| {\n                            tracing::trace!(\"sync\");\n                            if id == PW_ID_CORE && Some(seq) == sync_seq.get() {\n                                tracing::trace!(\"core sync\");\n                                done.set(true);\n                                mainloop.quit();\n                            }\n                        }\n                    })\n                    .register(),\n            );\n        }\n\n        let attached_receiver = stop_settings.signal_receiver.map(|stop_signal_receiver| {\n            stop_signal_receiver.attach(self.mainloop.loop_(), {\n                let done = self.done.clone();\n                let mainloop = self.mainloop.clone();\n                move || {\n                    done.set(true);\n                    mainloop.quit()\n                }\n            })\n        });\n\n        tracing::trace!(\"starting pipewire loop\");\n        while !self.done.get() {\n            self.mainloop.run();\n        }\n        tracing::trace!(\"pipewire loop finished\");\n\n        if let Some(attached_receiver) = attached_receiver {\n            attached_receiver.deattach();\n        }\n\n        drop(listener_core);\n    }\n}\n"
  },
  {
    "path": "native/connector-rs/pipewire-utils/src/utils.rs",
    "content": "use crate::{pipewire_client::PipewireClient, pipewire_objects::NodeWithPorts, PipewireError};\n\npub struct ManagedNode {\n    pipewire_client: PipewireClient,\n    node_with_ports: NodeWithPorts,\n}\n\nimpl ManagedNode {\n    pub fn create_managed_node(\n        pipewire_client: &PipewireClient,\n        node_name: impl AsRef<str>,\n    ) -> Result<Self, PipewireError> {\n        let node = pipewire_client.await_create_node(node_name)?;\n\n        Ok(ManagedNode {\n            pipewire_client: pipewire_client.clone(),\n            node_with_ports: node,\n        })\n    }\n\n    pub fn get_node_with_ports(&self) -> &NodeWithPorts {\n        &self.node_with_ports\n    }\n}\n\nimpl Drop for ManagedNode {\n    fn drop(&mut self) {\n        let id = self.node_with_ports.id;\n        if let Err(err) = self.pipewire_client.destroy_global(id) {\n            tracing::error!(\"error removing managed node {id}, ignoring error: {err}\");\n        }\n    }\n}\n"
  },
  {
    "path": "native/connector-rs/rustfmt.toml",
    "content": "tab_spaces=2\n"
  },
  {
    "path": "native/connector-rs/src/command.rs",
    "content": "#![allow(non_snake_case)]\n\nuse std::env;\nuse std::env::current_exe;\nuse std::process::Command;\nuse std::process::Stdio;\nuse std::str;\n\nuse pipewire_utils::PipewireClient;\nuse serde_json::{json, Value};\n\nuse crate::daemon;\nuse crate::helpers::io;\nuse crate::helpers::parse_numeric_argument;\nuse crate::helpers::pipewire::OutputNode;\nuse crate::ipc;\nuse crate::ipc_request;\n\nconst VERSION: &str = env!(\"CARGO_PKG_VERSION\");\npub const VIRTMIC_NODE_NAME: &str = \"pipewire-screenaudio\";\n\nfn GetVersion(_: io::Payload) -> Result<Value, String> {\n  Ok(json!({\n    \"version\": VERSION\n  }))\n}\n\nfn GetSessionType(_: io::Payload) -> Result<Value, String> {\n  let session_type = match env::var_os(\"WAYLAND_DISPLAY\") {\n    Some(_) => \"wayland\",\n    None => \"x11\",\n  };\n\n  Ok(json!({\n    \"type\": session_type\n  }))\n}\n\nfn GetNodes(_: io::Payload) -> Result<Value, String> {\n  let client = PipewireClient::new().unwrap();\n  let nodes: Vec<_> = client\n    .list_output_nodes()\n    .into_iter()\n    .map(OutputNode::from)\n    .collect();\n  Ok(serde_json::to_value(nodes).unwrap())\n}\n\nfn StartPipewireScreenAudio(_: io::Payload) -> Result<Value, String> {\n  let mut daemon_process = Command::new(current_exe().unwrap())\n    .arg(\"daemon\")\n    .stdout(Stdio::piped())\n    .stderr(Stdio::null())\n    .stdin(Stdio::null())\n    .spawn()\n    .unwrap();\n\n  let daemon_stdout = daemon_process.stdout.take().unwrap();\n\n  let mic_id = ipc_request::read_start_result(daemon_stdout);\n  drop(daemon_process);\n\n  Ok(json!({\n    \"micId\": mic_id?\n  }))\n}\n\nfn SetSharingNode(payload: io::Payload) -> Result<Value, String> {\n  let nodes_arg = payload.arguments.get(\"nodes\");\n\n  let mut isAllDesktop = false;\n\n  let arr = nodes_arg\n    .and_then(|nodes_arg| nodes_arg.as_array())\n    .ok_or_else(|| \"nodes argument must be an array\".to_string())?;\n\n  let nodes = {\n    let mut node_ids = Vec::new();\n    let client = PipewireClient::new().unwrap();\n\n    for node_value in arr {\n      if node_value == -1 {\n        // If any node is -1, treat as AllDesktop (None)\n        node_ids.clear();\n        isAllDesktop = true;\n        break;\n      }\n\n      let node_serial = parse_numeric_argument(node_value.clone());\n      tracing::debug!(\"node serial to connect: {node_serial}\");\n\n      let node_id = client\n        .get_node_id_from_object_serial(node_serial)\n        .ok_or_else(|| format!(\"failed to obtain node id for node with serial {node_serial}\"))?;\n      tracing::info!(\"node id to connect: {node_id}\");\n      node_ids.push(node_id);\n    }\n\n    node_ids\n  };\n\n  let pipe = ipc::connect().map_err(|err| err.to_string())?;\n  let nodes = if isAllDesktop { None } else { Some(nodes) };\n  io::write(daemon::Command::SetSharingNode { nodes }, &pipe).unwrap();\n  let res: daemon::Response = io::read(&pipe).unwrap();\n\n  let daemon::Response::SetSharingNodeResult { success } = res else {\n    tracing::error!(\"invalid response for SetSharingNode, {res:?}\");\n    return Err(format!(\"invalid response for SetSharingNode, {res:?}\"));\n  };\n\n  if !success {\n    return Err(\"unable to set sharing node\".to_string());\n  }\n\n  Ok(json!({}))\n}\n\nfn IsPipewireScreenAudioRunning(_payload: io::Payload) -> Result<Value, String> {\n  let is_running = ipc_request::is_daemon_running().is_ok_and(|running| running);\n  Ok(json!({\n    \"isRunning\": is_running\n  }))\n}\n\nfn StopPipewireScreenAudio(_payload: io::Payload) -> Result<Value, String> {\n  ipc_request::stop_daemon()?;\n\n  Ok(json!({}))\n}\n\nfn SetInstanceIdentifier(payload: io::Payload) -> Result<Value, String> {\n  let instance_identifier = payload.arguments.get(\"id\").unwrap().as_str().unwrap();\n  ipc_request::set_instance_identifier(instance_identifier)?;\n  Ok(json!({}))\n}\n\npub fn run(payload: io::Payload) -> Result<Value, String> {\n  let cmd = payload.command.as_str();\n  match cmd {\n    \"GetVersion\" => GetVersion(payload),\n    \"GetSessionType\" => GetSessionType(payload),\n    \"GetNodes\" => GetNodes(payload),\n    \"StartPipewireScreenAudio\" => StartPipewireScreenAudio(payload),\n    \"SetSharingNode\" => SetSharingNode(payload),\n    \"IsPipewireScreenAudioRunning\" => IsPipewireScreenAudioRunning(payload),\n    \"StopPipewireScreenAudio\" => StopPipewireScreenAudio(payload),\n    \"SetInstanceIdentifier\" => SetInstanceIdentifier(payload),\n    _ => Err(format!(\"Unknown command: {}\", payload.command)),\n  }\n}\n"
  },
  {
    "path": "native/connector-rs/src/daemon.rs",
    "content": "use serde::{Deserialize, Serialize};\nuse std::{\n  io::stdout,\n  num::ParseIntError,\n  os::unix::net::UnixStream,\n  sync::atomic::{AtomicBool, Ordering},\n};\nuse thiserror::Error;\nuse tracing::instrument;\n\nuse crate::{\n  command::VIRTMIC_NODE_NAME,\n  helpers::io::{self},\n  ipc,\n  monitor::MonitorThreadHandle,\n};\nuse pipewire_utils::{ManagedNode, NodeWithPorts, PipewireClient};\n\n#[derive(Error, Debug)]\npub enum ArgParseError {\n  #[error(\"error parsing int\")]\n  ParseIntError(#[from] ParseIntError),\n}\n\n#[derive(Error, Debug)]\npub enum Error {\n  #[error(\"error parsing arguments\")]\n  ArgParseError(#[from] ArgParseError),\n}\n\n#[derive(Debug, Serialize, Deserialize)]\n#[serde(tag = \"cmd\")]\npub enum Command {\n  SetSharingNode { nodes: Option<Vec<u32>> },\n  SetInstanceIdentifier { instance_identifier: String },\n  Ping,\n  Stop,\n}\n\n#[allow(clippy::enum_variant_names)]\n#[derive(Debug, Serialize, Deserialize)]\n#[serde(tag = \"type\")]\npub enum Response {\n  StartResult {\n    #[serde(rename = \"micId\")]\n    mic_id: u32,\n  },\n  SetSharingNodeResult {\n    success: bool,\n  },\n  PingResult,\n  StopResult,\n  SetInstanceIdentifierResult,\n}\n\nstatic KEEP_RUNNING: AtomicBool = AtomicBool::new(true);\n\nenum SharingNodeState {\n  Ids(Vec<u32>),\n  AllDesktop,\n  NotSharing,\n}\n\nstruct DaemonState {\n  running_thread: Option<MonitorThreadHandle>,\n  sharing_node_state: SharingNodeState,\n  instance_identifier: Option<String>,\n}\n\nimpl DaemonState {\n  fn reshare(&mut self, virtual_node: &NodeWithPorts, pipewire_client: &PipewireClient) -> bool {\n    let _ = self.running_thread.take();\n    pipewire_client.unlink_node_ports(virtual_node.ports);\n    let success = match &self.sharing_node_state {\n      SharingNodeState::Ids(node_ids) => {\n        for node_id in node_ids {\n          pipewire_client.link_nodes(*node_id, virtual_node.ports);\n        }\n        true\n      }\n      SharingNodeState::AllDesktop => {\n        match MonitorThreadHandle::launch_monitor_thread(\n          virtual_node.ports,\n          self.instance_identifier.clone(),\n        ) {\n          Ok(handle) => {\n            self.running_thread.replace(handle);\n            true\n          }\n          Err(err) => {\n            tracing::error!(\"error while launching monitor thread: {err}\");\n            false\n          }\n        }\n      }\n      SharingNodeState::NotSharing => true,\n    };\n    success\n  }\n}\n\nfn handle_client(\n  state: &mut DaemonState,\n  pipewire_client: &PipewireClient,\n  virtual_node: &NodeWithPorts,\n  stream: UnixStream,\n) {\n  let command = match io::read::<_, Command>(&stream) {\n    Ok(command) => command,\n    Err(err) => {\n      tracing::error!(\"invalid input from ipc channel: {err:?}\");\n      return;\n    }\n  };\n  tracing::info!(\"input: {:?}\", command);\n\n  match command {\n    Command::SetSharingNode { nodes } => {\n      state.sharing_node_state = match nodes {\n        Some(node_ids) => SharingNodeState::Ids(node_ids),\n        None => SharingNodeState::AllDesktop,\n      };\n      let success = state.reshare(virtual_node, pipewire_client);\n      io::write(Response::SetSharingNodeResult { success }, &stream).unwrap();\n    }\n    Command::SetInstanceIdentifier {\n      instance_identifier,\n    } => {\n      state.instance_identifier = Some(instance_identifier);\n      state.reshare(virtual_node, pipewire_client);\n      io::write(Response::SetInstanceIdentifierResult, &stream).unwrap();\n    }\n    Command::Ping => {\n      io::write(Response::PingResult, &stream).unwrap();\n    }\n    Command::Stop => {\n      io::write(Response::StopResult, &stream).unwrap();\n      stop_daemon();\n    }\n  }\n}\n\nfn stop_daemon() {\n  tracing::info!(\"shutting down\");\n  KEEP_RUNNING.store(false, Ordering::Relaxed);\n  ipc::fake_connect();\n}\n\n#[instrument]\npub fn monitor_and_connect_nodes() -> Result<(), Error> {\n  tracing::info!(\"starting daemon monitor\");\n\n  let pipewire_client = PipewireClient::new().unwrap();\n\n  let pipe = ipc::listen().unwrap();\n\n  let managed_virtual_node =\n    ManagedNode::create_managed_node(&pipewire_client, VIRTMIC_NODE_NAME).unwrap();\n  let virtual_node = *managed_virtual_node.get_node_with_ports();\n\n  ctrlc::set_handler(|| {\n    stop_daemon();\n  })\n  .unwrap();\n\n  let mut state = DaemonState {\n    running_thread: None,\n    instance_identifier: None,\n    sharing_node_state: SharingNodeState::NotSharing,\n  };\n\n  io::write(\n    Response::StartResult {\n      mic_id: virtual_node.id,\n    },\n    stdout(),\n  )\n  .unwrap();\n\n  for stream in pipe.incoming() {\n    if !KEEP_RUNNING.load(Ordering::Relaxed) {\n      tracing::warn!(\"stopping daemon\");\n      break;\n    }\n    let Ok(stream) = stream else {\n      tracing::warn!(\"failed to accept incomming connection\");\n      continue;\n    };\n    handle_client(&mut state, &pipewire_client, &virtual_node, stream);\n  }\n\n  drop(state);\n\n  Ok(())\n}\n"
  },
  {
    "path": "native/connector-rs/src/dirs.rs",
    "content": "use std::{env, path::PathBuf};\n\npub fn get_runtime_path() -> PathBuf {\n  let mut path: PathBuf = env::var(\"XDG_RUNTIME_DIR\")\n    .unwrap_or(\"/tmp\".to_owned())\n    .into();\n\n  path.push(\"pipewire-screenaudio\");\n\n  path\n}\n"
  },
  {
    "path": "native/connector-rs/src/helpers/io.rs",
    "content": "use std::fmt::Debug;\nuse std::io::prelude::{Read, Write};\nuse std::str;\n\nuse serde::{Deserialize, Serialize};\nuse serde_json::{json, Value};\n\nuse thiserror::Error;\n\n#[derive(Debug, Serialize, Deserialize)]\npub struct RawPayload {\n  #[serde(rename = \"cmd\")]\n  pub command: String,\n  #[serde(rename = \"args\")]\n  pub arguments: Option<Value>,\n}\n\nimpl From<RawPayload> for Payload {\n  fn from(value: RawPayload) -> Self {\n    let RawPayload { command, arguments } = value;\n    Self {\n      command,\n      arguments: arguments.unwrap_or_else(|| json!({})),\n    }\n  }\n}\n\nimpl From<Payload> for RawPayload {\n  fn from(value: Payload) -> Self {\n    Self {\n      command: value.command,\n      arguments: Some(value.arguments),\n    }\n  }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(from = \"RawPayload\", into = \"RawPayload\")]\npub struct Payload {\n  pub command: String,\n  pub arguments: Value,\n}\n\n#[derive(Error, Debug)]\npub enum ReadError {\n  #[error(\"error while reading length header\")]\n  ReadingLengthHeader(std::io::Error),\n  #[error(\"error while reading payload\")]\n  ReadingPayload(std::io::Error),\n  #[error(\"error while parsing payload\")]\n  PayloadUTFError(std::str::Utf8Error),\n  #[error(\"error while parsing payload\")]\n  ParsingPayload(serde_json::Error),\n}\n\n#[derive(Error, Debug)]\npub enum WriteError {\n  #[error(\"error while writing length header\")]\n  WritingLengthHeader(std::io::Error),\n  #[error(\"error while writing payload\")]\n  WritingPayload(std::io::Error),\n  #[error(\"error while serializing payload\")]\n  SerializingPayload(serde_json::Error),\n  #[error(\"error while flushing\")]\n  Flushing(std::io::Error),\n}\n\npub fn read<R: Read, P: for<'a> Deserialize<'a> + Debug>(mut reader: R) -> Result<P, ReadError> {\n  let mut length_buffer = [0u8; 4];\n\n  reader\n    .read_exact(&mut length_buffer)\n    .map_err(ReadError::ReadingLengthHeader)?;\n\n  let length = u32::from_le_bytes(length_buffer);\n  tracing::trace!(\"Length: {}\", length);\n\n  let mut payload_buffer = vec![0u8; length as usize];\n  reader\n    .read_exact(&mut payload_buffer)\n    .map_err(ReadError::ReadingPayload)?;\n\n  let payload_string = str::from_utf8(&payload_buffer).map_err(ReadError::PayloadUTFError)?;\n\n  let payload = serde_json::from_str(payload_string).map_err(ReadError::ParsingPayload)?;\n  tracing::debug!(\"read payload: {:?}\", &payload);\n\n  Ok(payload)\n}\n\npub fn write<W: Write, P: Serialize>(payload: P, mut writer: W) -> Result<(), WriteError> {\n  let payload = serde_json::to_string(&payload).map_err(WriteError::SerializingPayload)?;\n  tracing::debug!(\"writing payload: {}\", payload);\n\n  let payload = payload.as_bytes();\n  let length = payload.len();\n  let length_buffer = u32::try_from(length).unwrap().to_le_bytes();\n\n  writer\n    .write_all(&length_buffer)\n    .map_err(WriteError::WritingLengthHeader)?;\n  writer\n    .write_all(payload)\n    .map_err(WriteError::WritingPayload)?;\n  writer.flush().map_err(WriteError::Flushing)?;\n\n  Ok(())\n}\n"
  },
  {
    "path": "native/connector-rs/src/helpers/pipewire.rs",
    "content": "use serde::Serialize;\n\n#[derive(Debug, Serialize)]\npub struct NodeProperties {\n  #[serde(rename = \"application.name\")]\n  application_name: Option<String>,\n  #[serde(rename = \"media.name\")]\n  media_name: String,\n  #[serde(rename = \"object.serial\")]\n  object_serial: i64,\n\n  #[serde(skip_serializing)]\n  #[allow(unused)]\n  media_class: String,\n}\n\n#[derive(Debug, Serialize)]\npub struct OutputNode {\n  id: u32,\n  properties: NodeProperties,\n}\n\nimpl From<pipewire_utils::NodeProperties> for NodeProperties {\n  fn from(\n    pipewire_utils::NodeProperties {\n      application_name,\n      media_name,\n      object_serial,\n      media_class,\n    }: pipewire_utils::NodeProperties,\n  ) -> Self {\n    Self {\n      application_name,\n      media_name,\n      object_serial,\n      media_class,\n    }\n  }\n}\n\nimpl From<pipewire_utils::OutputNode> for OutputNode {\n  fn from(pipewire_utils::OutputNode { id, properties }: pipewire_utils::OutputNode) -> Self {\n    Self {\n      id,\n      properties: properties.into(),\n    }\n  }\n}\n"
  },
  {
    "path": "native/connector-rs/src/helpers.rs",
    "content": "use serde_json::Value;\n\npub mod io;\npub mod pipewire;\n\npub fn parse_numeric_argument(value: Value) -> i64 {\n  if value.is_i64() {\n    value.as_number().unwrap().as_i64().unwrap()\n  } else {\n    value.as_str().unwrap().parse::<i64>().unwrap()\n  }\n}\n"
  },
  {
    "path": "native/connector-rs/src/ipc.rs",
    "content": "use std::{\n  error::Error,\n  fs, io,\n  os::unix::net::{UnixListener, UnixStream},\n  path::{Path, PathBuf},\n  thread,\n  time::Duration,\n};\n\nuse crate::io as ipc_io;\nuse crate::{daemon, dirs::get_runtime_path};\n\nfn get_ipc_socket_path() -> PathBuf {\n  let mut path = get_runtime_path();\n  path.push(\"ipc.sock\");\n  path\n}\n\nfn ensure_stopped(path: &Path) -> Result<(), Box<dyn Error>> {\n  if path.exists() {\n    let stream = connect_inner(1)?;\n    ipc_io::write(daemon::Command::Stop, &stream)?;\n  }\n  Ok(())\n}\n\npub fn listen() -> io::Result<UnixListener> {\n  let path = get_ipc_socket_path();\n  let _ = ensure_stopped(&path);\n  let _ = fs::remove_file(&path);\n  UnixListener::bind(path)\n}\n\npub fn fake_connect() {\n  let _ = UnixStream::connect(get_ipc_socket_path());\n}\n\npub fn connect_inner(tries: usize) -> io::Result<UnixStream> {\n  let mut retries = tries;\n  let path = get_ipc_socket_path();\n  let mut last_error = None;\n  while retries > 0 {\n    tracing::debug!(\"connecting\");\n    match UnixStream::connect(path.clone()) {\n      Ok(socket) => return Ok(socket),\n      Err(err) => last_error = Some(err),\n    }\n    retries -= 1;\n    if retries > 0 {\n      thread::sleep(Duration::from_millis(100));\n    }\n  }\n  Err(last_error.unwrap())\n}\n\npub fn connect() -> io::Result<UnixStream> {\n  connect_inner(1)\n}\n"
  },
  {
    "path": "native/connector-rs/src/ipc_request.rs",
    "content": "use std::process::ChildStdout;\n\nuse crate::{daemon, helpers::io, ipc};\n\npub fn is_daemon_running() -> Result<bool, String> {\n  let pipe = ipc::connect().map_err(|err| err.to_string())?;\n  io::write(daemon::Command::Ping, &pipe).map_err(|err| err.to_string())?;\n  let res: daemon::Response = io::read(&pipe).map_err(|err| err.to_string())?;\n\n  let daemon::Response::PingResult = res else {\n    tracing::error!(\"invalid response for Ping, {res:?}\");\n    return Err(format!(\"invalid response for Ping, {res:?}\"));\n  };\n\n  Ok(true)\n}\n\npub fn stop_daemon() -> Result<(), String> {\n  let pipe = ipc::connect().map_err(|err| err.to_string())?;\n  io::write(daemon::Command::Stop, &pipe).map_err(|err| err.to_string())?;\n  let res: daemon::Response = io::read(&pipe).map_err(|err| err.to_string())?;\n\n  let daemon::Response::StopResult = res else {\n    tracing::error!(\"invalid response for Stop, {res:?}\");\n    return Err(format!(\"invalid response for Stop, {res:?}\"));\n  };\n\n  Ok(())\n}\n\npub fn set_instance_identifier(instance_identifier: &str) -> Result<(), String> {\n  let pipe = ipc::connect().map_err(|err| err.to_string())?;\n  io::write(\n    daemon::Command::SetInstanceIdentifier {\n      instance_identifier: instance_identifier.to_owned(),\n    },\n    &pipe,\n  )\n  .map_err(|err| err.to_string())?;\n  let res: daemon::Response = io::read(&pipe).map_err(|err| err.to_string())?;\n\n  let daemon::Response::SetInstanceIdentifierResult = res else {\n    tracing::error!(\"invalid response for SetExcludedTitle, {res:?}\");\n    return Err(format!(\"invalid response for SetExcludedTitle, {res:?}\"));\n  };\n\n  Ok(())\n}\n\npub fn read_start_result(daemon_stdout: ChildStdout) -> Result<u32, String> {\n  let status: daemon::Response = io::read(daemon_stdout)\n    .map_err(|err| format!(\"error obtaining first response from daemon: {err}\"))?;\n\n  let daemon::Response::StartResult { mic_id } = status else {\n    return Err(format!(\n      \"first response from daemon has unexpected format: {status:?}\"\n    ));\n  };\n  Ok(mic_id)\n}\n"
  },
  {
    "path": "native/connector-rs/src/main.rs",
    "content": "use std::{\n  env,\n  error::Error,\n  io::{stdin, stdout},\n  panic,\n  path::PathBuf,\n  process,\n};\n\nmod command;\nmod daemon;\nmod dirs;\nmod helpers;\nmod ipc;\nmod ipc_request;\nmod monitor;\n\nuse helpers::io;\nuse serde_json::json;\nuse tracing::{level_filters::LevelFilter, Level};\nuse tracing_appender::rolling::RollingFileAppender;\nuse tracing_panic::panic_hook;\nuse tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter, Layer, Registry};\n\nuse crate::{daemon::monitor_and_connect_nodes, dirs::get_runtime_path};\n\nfn get_logs_path() -> PathBuf {\n  let mut path = get_runtime_path();\n  path.push(\"logs\");\n  path\n}\n\nfn main() -> Result<(), Box<dyn Error>> {\n  let mut args = env::args();\n  let _ = args.next().expect(\"binary path should be the first arg\");\n  let subcommand = args.next();\n\n  let file_appender = RollingFileAppender::builder()\n    .filename_prefix(\n      match subcommand.as_deref() {\n        Some(\"daemon\") => \"daemon\",\n        _ => \"connector\",\n      }\n      .to_owned(),\n    )\n    .build(get_logs_path())\n    .unwrap();\n  let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);\n  let subscriber = Registry::default()\n    .with(\n      fmt::Layer::default()\n        .with_writer(non_blocking)\n        .with_ansi(false)\n        .with_filter(LevelFilter::from_level(Level::DEBUG)),\n    )\n    .with(\n      fmt::Layer::default()\n        .with_writer(std::io::stderr)\n        .with_filter(\n          EnvFilter::builder()\n            .with_default_directive(LevelFilter::ERROR.into())\n            .from_env_lossy(),\n        ),\n    );\n\n  tracing::subscriber::set_global_default(subscriber).expect(\"unable to set global subscriber\");\n  let span = tracing::info_span!(\"main\", pid = process::id());\n  let _span_handle = span.enter();\n\n  panic::set_hook(Box::new(panic_hook));\n\n  match subcommand.as_deref() {\n    Some(\"daemon\") => {\n      if let Err(err) = monitor_and_connect_nodes() {\n        tracing::error!(\"error: {}\", err);\n        Err(Box::new(err))?;\n      }\n    }\n    Some(_) | None => {\n      let payload = io::read(stdin()).unwrap();\n      tracing::info!(payload = format!(\"{payload:?}\"), \"running connector\");\n      match command::run(payload) {\n        Ok(result) => {\n          let _ = io::write(\n            json!({\n              \"success\": true,\n              \"response\": result,\n            }),\n            stdout(),\n          );\n        }\n        Err(err) => {\n          tracing::error!(\"command error: {}\", err);\n          let _ = io::write(\n            json!({\n              \"success\": false,\n              \"errorMessage\": err,\n            }),\n            stdout(),\n          );\n        }\n      }\n    }\n  }\n\n  Ok(())\n}\n"
  },
  {
    "path": "native/connector-rs/src/monitor.rs",
    "content": "use std::{\n  io,\n  rc::Rc,\n  thread::{self, JoinHandle},\n};\n\nuse pipewire_utils::{\n  cancellation_signal::{CancellationController, CancellationSignal},\n  PipewireClient, PipewireError, Ports,\n};\nuse thiserror::Error;\n\n#[derive(Error, Debug)]\npub enum Error {\n  #[error(\"pipewire error\")]\n  PipewireError(#[from] PipewireError),\n  #[error(\"thread spawning error\")]\n  ThreadSpawnError(io::Error),\n}\n\npub type Result<T, E = Error> = std::result::Result<T, E>;\n\npub struct MonitorThreadHandle {\n  join_handle: Option<JoinHandle<Result<(), PipewireError>>>,\n  cancellation_controller: CancellationController,\n}\n\nimpl MonitorThreadHandle {\n  pub fn launch_monitor_thread(\n    mic_ports: Ports,\n    instance_identifier: Option<String>,\n  ) -> Result<Self> {\n    tracing::debug!(\"starting monitor thread\");\n    let (controller, signal) = CancellationSignal::pair();\n\n    let join_handle = thread::Builder::new()\n      .name(\"monitor and connector thread\".to_owned())\n      .spawn(move || {\n        let client = PipewireClient::new()?;\n        let instance_identifier = instance_identifier.map(Rc::new);\n        client.monitor_and_connect_nodes(mic_ports, signal, move |node_app_name| {\n          tracing::trace!(\n            node_app_name,\n            instance_identifier = instance_identifier.as_ref().map(|ii| ii.as_str()),\n            \"filtering\"\n          );\n          instance_identifier\n            .as_ref()\n            .is_none_or(move |excluded_node_name| {\n              node_app_name\n                .is_none_or(|node_app_name| !node_app_name.ends_with(excluded_node_name.as_ref()))\n            })\n        })\n      })\n      .map_err(Error::ThreadSpawnError)?;\n\n    Ok(MonitorThreadHandle {\n      join_handle: Some(join_handle),\n      cancellation_controller: controller,\n    })\n  }\n\n  pub fn stop(&mut self) {\n    tracing::debug!(\"stopping monitor thread\");\n    self.cancellation_controller.cancel();\n    if let Some(handle) = self.join_handle.take() {\n      if let Err(err) = handle.join().unwrap() {\n        tracing::error!(\"monitor thread returned error: {err}\");\n      }\n    }\n  }\n}\n\nimpl Drop for MonitorThreadHandle {\n  fn drop(&mut self) {\n    self.stop();\n  }\n}\n"
  },
  {
    "path": "native/native-messaging-hosts/com.icedborn.pipewirescreenaudioconnector.json",
    "content": "{\n\t\"name\": \"com.icedborn.pipewirescreenaudioconnector\",\n\t\"description\": \"Connector to communicate with the browser\",\n\t\"path\": \"CONNECTOR_BINARY_PATH\",\n\t\"type\": \"stdio\",\n\t\"ALLOWED_FIELD\": [\"ALLOWED_VALUE\"]\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n\t\"name\": \"pipewire-screenaudio\",\n\t\"version\": \"0.4.2\",\n\t\"scripts\": {\n\t\t\"build\": \"vite build extension/react\"\n\t},\n\t\"dependencies\": {\n\t\t\"@emotion/react\": \"^11.11.1\",\n\t\t\"@emotion/styled\": \"^11.11.0\",\n\t\t\"@fontsource/roboto\": \"^5.0.8\",\n\t\t\"@mui/material\": \"^5.14.4\",\n\t\t\"react\": \"^18.2.0\",\n\t\t\"react-dom\": \"^18.2.0\",\n\t\t\"react-router\": \"^6.17.0\",\n\t\t\"react-router-dom\": \"^6.17.0\",\n\t\t\"use-debounce\": \"^9.0.4\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@vitejs/plugin-react\": \"^4.0.4\",\n\t\t\"eslint\": \"^8.47.0\",\n\t\t\"eslint-plugin-react\": \"^7.33.2\",\n\t\t\"nodemon\": \"^3.0.1\",\n\t\t\"prettier\": \"^3.0.1\",\n\t\t\"vite\": \"^4.4.9\"\n\t}\n}\n"
  }
]