[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"\"\nlabels: \"\"\nassignees: \"\"\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Desktop (please complete the following information):**\n\n- OS (including distro): [e.g. Windows, Arch Linux]\n- CrossCode version: [e.g. 0.0.4]\n- Package Format: [e.g. exe, deb]\n\n**Smartphone (please complete the following information):**\n\n- Device: [e.g. iPhone 6]\n- OS: [e.g. iOS 26.0]\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: \"Build CrossCode\"\n\non:\n  push:\n    branches:\n      - \"*\"\n  pull_request:\n    branches:\n      - \"*\"\n  workflow_dispatch:\n  release:\n    types: [published]\n\njobs:\n  build:\n    permissions:\n      contents: write\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          - platform: \"ubuntu-22.04\"\n            args: \"--bundles deb\"\n          - platform: \"ubuntu-22.04\"\n            args: \"--bundles rpm\"\n          - platform: \"ubuntu-22.04\"\n            args: \"--bundles appimage\"\n          - platform: \"windows-latest\"\n            args: \"\"\n          - platform: \"macos-latest\"\n            args: \"--target aarch64-apple-darwin\"\n          - platform: \"macos-15-intel\"\n            args: \"--target x86_64-apple-darwin\"\n\n    runs-on: ${{ matrix.platform }}\n    steps:\n      - uses: actions/checkout@v4\n\n      - name: Cache Rust and bun dependencies\n        uses: actions/cache@v4\n        with:\n          path: |\n            ~/.cargo/registry\n            ~/.cargo/git\n            src-tauri/target\n            node_modules\n          key: ${{ matrix.platform }}-crosscode-${{ hashFiles('**/Cargo.lock', 'package-lock.json') }}\n          restore-keys: |\n            ${{ runner.os }}-crosscode-\n\n      - name: Install Rust stable\n        uses: dtolnay/rust-toolchain@stable\n        with:\n          targets: ${{ (matrix.platform == 'macos-latest' || matrix.platform == 'macos-15-intel') && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}\n\n      - name: Install Linux dependencies\n        if: matrix.platform == 'ubuntu-22.04'\n        run: |\n          sudo apt-get update\n          sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf perl make\n\n      - name: Add MSVC to PATH\n        if: matrix.platform == 'windows-latest'\n        uses: ilammy/msvc-dev-cmd@v1\n\n      - name: Install Perl and Make for Windows\n        if: matrix.platform == 'windows-latest'\n        run: |\n          choco install strawberryperl make --no-progress\n\n      - uses: oven-sh/setup-bun@v2\n        with:\n          bun-version: latest\n\n      - name: Install frontend dependencies\n        run: bun i --frozen-lockfile\n\n      - name: Clean old bundles\n        if: matrix.platform != 'macos-latest' && matrix.platform != 'macos-15-intel'\n        run: bunx rimraf src-tauri/target/release/bundle\n\n      - name: Clean old bundles\n        if: matrix.platform == 'macos-latest'\n        run: bunx rimraf src-tauri/target/aarch64-apple-darwin/release/bundle\n\n      - name: Clean old bundles\n        if: matrix.platform == 'macos-15-intel'\n        run: bunx rimraf src-tauri/target/x86_64-apple-darwin/release/bundle\n\n      - name: Build\n        uses: tauri-apps/tauri-action@v0\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}\n          TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}\n        with:\n          args: ${{ matrix.args }}\n          includeUpdaterJson: ${{ github.event_name == 'release' }}\n          releaseId: ${{ github.event_name == 'release' && github.event.release.id || '' }}\n\n      - name: Upload macOS DMG\n        uses: actions/upload-artifact@v4\n        if: matrix.platform == 'macos-latest' || matrix.platform == 'macos-15-intel'\n        with:\n          name: macos-dmg-${{ matrix.args == '--target aarch64-apple-darwin' && 'arm64' || 'x64' }}\n          path: ${{ github.workspace }}/src-tauri/target/**/release/bundle/**/*.dmg\n\n      - name: Upload Linux DEB\n        uses: actions/upload-artifact@v4\n        if: matrix.platform == 'ubuntu-22.04' && matrix.args == '--bundles deb'\n        with:\n          name: linux-deb\n          path: ${{ github.workspace }}/src-tauri/target/release/bundle/**/*.deb\n\n      - name: Upload Linux RPM\n        uses: actions/upload-artifact@v4\n        if: matrix.platform == 'ubuntu-22.04' && matrix.args == '--bundles rpm'\n        with:\n          name: linux-rpm\n          path: ${{ github.workspace }}/src-tauri/target/release/bundle/**/*.rpm\n\n      - name: Upload Linux AppImage\n        uses: actions/upload-artifact@v4\n        if: matrix.platform == 'ubuntu-22.04' && matrix.args == '--bundles appimage'\n        with:\n          name: linux-appimage\n          path: ${{ github.workspace }}/src-tauri/target/release/bundle/**/*.AppImage\n\n      - name: Upload Windows EXE\n        uses: actions/upload-artifact@v4\n        if: matrix.platform == 'windows-latest'\n        with:\n          name: windows-exe\n          path: |\n            ${{ github.workspace }}/src-tauri/target/release/bundle/**/*.exe\n"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndist-ssr\n*.local\n\n# Editor directories and files\n.vscode/*\n!.vscode/extensions.json\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n.zsign_cache\n*.key*\nsdkmover"
  },
  {
    "path": ".vscode/extensions.json",
    "content": "{\n  \"recommendations\": [\"tauri-apps.tauri-vscode\", \"rust-lang.rust-analyzer\"]\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2025 nab138\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<img align=\"left\" width=\"120\" height=\"120\" src=\"/logo.png\">\n\n<div id=\"user-content-toc\">\n  <ul style=\"list-style: none;\">\n    <summary>\n      <h1>CrossCode</h1>\n    </summary>\n  </ul>\n</div>\n\n---\n\n[![Build CrossCode](https://github.com/nab138/CrossCode/actions/workflows/build.yml/badge.svg)](https://github.com/nab138/CrossCode/actions/workflows/build.yml)\n\niOS Swift development IDE for Windows/Linux. Create, build, and test apps without owning a Mac.\n\nSupports Swift 6.2 and the Swift Package Manager.\n\n### Demo\n\nhttps://github.com/user-attachments/assets/9cbe2b71-d765-46c6-aa25-ef16b539deec\n\n## Installation\n\nCrossCode is currently in alpha. Expect bugs!\n\nDownload the latest build for your platform from [releases](https://github.com/nab138/CrossCode/releases/latest).\n\nCheck out the [Getting Started](https://github.com/nab138/CrossCode/wiki#getting-started) section of the [wiki](https://github.com/nab138/CrossCode/wiki). Also, see [Troubleshooting](https://github.com/nab138/CrossCode/wiki/Troubleshooting) and [FAQ](https://github.com/nab138/CrossCode/wiki/FAQ)\n\n## Features\n\n- Generate a Darwin SDK for linux from a user provided copy of Xcode 26 to build the apps\n- Build apps using swift package manager\n- Log in with your Apple ID to sign apps\n- Install apps on device\n- Create projects from templates\n- Code editing including error reporting, autocomplete, go to definition, and other language features\n- Light/dark mode and other customizations\n- View and manage certificates, app IDs, and more\n- View the syslog or the stdout (console) of your device/app\n- Much more (and more to come!)\n\n## Future plans\n\nThe app is currently functional but does not have all the features it should. You can see a tentative plan for the future [on trello](https://trello.com/b/QYQFfOvm/ycode)\n\nPlease note that I am one person, so development may be slow. If you want to help, PRs welcome!\n\n## How it works\n\n- A darwin SDK is generated from a user provided copy of Xcode 26 (extracted with [unxip-rs](https://github.com/nab138/unxip-rs)) and darwin tools from [darwin-tools-linux-llvm](https://github.com/xtool-org/darwin-tools-linux-llvm)\n- Swift uses the darwin SDK to build an executable which is packaged into an .app bundle.\n- The code to sign and install apps onto a device has been removed from CrossCode's source and moved to a standalone package, [isideload](https://github.com/nab138/isideload). It was built on a lot of other libraries, so check out its README for more info.\n\n## Credits\n\n- [idevice](https://github.com/jkcoxson/idevice) is used to communicate with iOS devices.\n- [xtool](https://xtool.sh) has been used as a reference for the implementation of the darwin SDK generation.\n- [Sideloader](https://github.com/Dadoum/Sideloader) has been heavily used as a reference for the implementation of the Apple Developer APIs and sideloading process.\n- [GNU cpio](https://www.gnu.org/software/cpio/) 2.14 is included under GPLv3 (see licenses/GPL-3.0.txt), with its copyright holders. See [Source code](https://ftp.gnu.org/gnu/cpio/cpio-2.14.tar.gz). It is used to help with XIP extraction.\n\n### AI Usage\n\n- Helped port small sections of code from [Sideloader](https://github.com/Dadoum/Sideloader) because I'm not familiar with dlang syntax\n"
  },
  {
    "path": "index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>CrossCode</title>\n  </head>\n\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "licenses/GPL-3.0.txt",
    "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>."
  },
  {
    "path": "licenses/cpio.NOTICE",
    "content": "GNU cpio 2.14\nCopyright (C) 1989-2023 Free Software Foundation, Inc.\nLicensed under the GNU General Public License, version 3."
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"crosscode\",\n  \"private\": true,\n  \"version\": \"0.0.5\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview\",\n    \"tauri\": \"tauri\",\n    \"bump-patch\": \"bunx tauri-version --no-git --no-lock patch\",\n    \"bump-minor\": \"bunx tauri-version --no-git --no-lock minor\",\n    \"bump-major\": \"bunx tauri-version --no-git --no-lock major\"\n  },\n  \"dependencies\": {\n    \"@codingame/esbuild-import-meta-url-plugin\": \"^1.0.3\",\n    \"@codingame/monaco-vscode-api\": \"~20.2.1\",\n    \"@codingame/monaco-vscode-languages-service-override\": \"~20.2.1\",\n    \"@codingame/monaco-vscode-model-service-override\": \"~20.2.1\",\n    \"@codingame/monaco-vscode-swift-default-extension\": \"~20.2.1\",\n    \"@codingame/monaco-vscode-textmate-service-override\": \"~20.2.1\",\n    \"@codingame/monaco-vscode-theme-defaults-default-extension\": \"~20.2.1\",\n    \"@codingame/monaco-vscode-theme-service-override\": \"~20.2.1\",\n    \"@codingame/monaco-vscode-views-service-override\": \"~20.2.1\",\n    \"@devbookhq/splitter\": \"^1.4.2\",\n    \"@emotion/react\": \"^11.14.0\",\n    \"@emotion/styled\": \"^11.14.0\",\n    \"@fontsource/inter\": \"^5.2.5\",\n    \"@mui/icons-material\": \"^7.0.2\",\n    \"@mui/joy\": \"^5.0.0-beta.52\",\n    \"@mui/material\": \"^7.0.2\",\n    \"@tauri-apps/api\": \"^2\",\n    \"@tauri-apps/plugin-cli\": \"^2.4.0\",\n    \"@tauri-apps/plugin-dialog\": \"^2\",\n    \"@tauri-apps/plugin-fs\": \"^2\",\n    \"@tauri-apps/plugin-opener\": \"^2\",\n    \"@tauri-apps/plugin-os\": \"^2.3.0\",\n    \"@tauri-apps/plugin-process\": \"^2.3.0\",\n    \"@tauri-apps/plugin-shell\": \"^2\",\n    \"@tauri-apps/plugin-store\": \"^2\",\n    \"@tauri-apps/plugin-updater\": \"^2\",\n    \"ansi-to-html\": \"^0.7.2\",\n    \"async-mutex\": \"^0.5.0\",\n    \"monaco-editor\": \"npm:@codingame/monaco-vscode-editor-api@~20.2.1\",\n    \"monaco-languageclient\": \"^9.8.0\",\n    \"react\": \"^19.1.0\",\n    \"react-dom\": \"^19.1.0\",\n    \"react-router\": \"^7.5.1\",\n    \"react-router-dom\": \"^7.5.1\",\n    \"react-toast-plus\": \"^0.1.2\",\n    \"react-virtuoso\": \"^4.12.6\",\n    \"vscode\": \"npm:@codingame/monaco-vscode-extension-api@~20.2.1\",\n    \"vscode-ws-jsonrpc\": \"^3.4.0\"\n  },\n  \"devDependencies\": {\n    \"@tauri-apps/cli\": \"^2\",\n    \"@types/react\": \"^18.2.15\",\n    \"@types/react-dom\": \"^18.2.7\",\n    \"@types/vscode\": \"^1.102.0\",\n    \"@vitejs/plugin-react\": \"^4.2.1\",\n    \"typescript\": \"^5.0.2\",\n    \"vite\": \"^7.1.6\"\n  }\n}"
  },
  {
    "path": "splash.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>CrossCode (Loading)</title>\n    <style>\n      .splash {\n        width: 100%;\n        height: 100%;\n        display: flex;\n        flex-direction: column;\n        align-items: center;\n        justify-content: center;\n        gap: 20px;\n      }\n      body,\n      html {\n        width: 100%;\n        height: 100%;\n        margin: 0;\n        background: rgb(23, 26, 28);\n        color: rgb(205, 215, 225);\n      }\n      .loading {\n        border: 6px solid rgba(11, 107, 203, 0.2);\n        border-top: 6px solid rgb(11, 107, 203); /* Blue */\n        border-radius: 50%;\n        width: 40px;\n        height: 40px;\n        animation: spin 1s linear infinite;\n        will-change: transform;\n      }\n\n      @keyframes spin {\n        0% {\n          transform: rotate(0deg);\n        }\n        100% {\n          transform: rotate(360deg);\n        }\n      }\n    </style>\n  </head>\n\n  <body>\n    <div class=\"splash\">\n      <div class=\"loading\"></div>\n      Loading CrossCode...\n    </div>\n  </body>\n</html>\n"
  },
  {
    "path": "src/App.css",
    "content": ""
  },
  {
    "path": "src/App.tsx",
    "content": "import { CssVarsProvider, extendTheme } from \"@mui/joy/styles\";\nimport { Sheet } from \"@mui/joy\";\nimport \"@fontsource/inter\";\nimport \"@fontsource/inter/600.css\";\nimport Onboarding from \"./pages/Onboarding\";\nimport IDE from \"./pages/IDE\";\nimport Preferences from \"./preferences/Preferences\";\nimport { BrowserRouter, Route, Routes, Navigate, Outlet } from \"react-router\";\nimport { StoreProvider, useStore } from \"./utilities/StoreContext\";\nimport { IDEProvider } from \"./utilities/IDEContext\";\nimport { CommandProvider } from \"./utilities/Command\";\nimport { ToastProvider } from \"react-toast-plus\";\nimport New from \"./pages/New\";\nimport NewTemplate from \"./pages/NewTemplate\";\nimport \"vscode/localExtensionHost\";\nimport { UpdateProvider } from \"./utilities/UpdateContext\";\nimport About from \"./pages/About\";\n\ndeclare module \"@mui/joy/IconButton\" {\n  interface IconButtonPropsSizeOverrides {\n    xs: true;\n  }\n}\n\nconst theme = extendTheme({\n  components: {\n    JoyIconButton: {\n      styleOverrides: {\n        root: ({ ownerState, theme }) => ({\n          ...(ownerState.size === \"xs\" && {\n            \"--Icon-fontSize\": \"1rem\",\n            \"--Button-gap\": \"0.25rem\",\n            minHeight: \"var(--Button-minHeight, 1.5rem)\",\n            fontSize: theme.vars.fontSize.xs,\n            paddingBlock: \"2px\",\n            paddingInline: \"0.25rem\",\n          }),\n        }),\n      },\n    },\n  },\n});\n\n// Layout with IDE-related providers\nconst IDELayout = () => {\n  const [appTheme] = useStore(\"appearance/theme\", \"dark\");\n  return (\n    <StoreProvider>\n      <ToastProvider\n        toastOptions={{ placement: \"bottom-right\" }}\n        toastStyles={\n          appTheme == \"dark\"\n            ? { toastBgColor: \"#333\", toastTextColor: \"#fff\" }\n            : {}\n        }\n      >\n        <UpdateProvider>\n          <CommandProvider>\n            <IDEProvider>\n              <Outlet />\n            </IDEProvider>\n          </CommandProvider>\n        </UpdateProvider>\n      </ToastProvider>\n    </StoreProvider>\n  );\n};\n\nconst App = () => {\n  return (\n    <BrowserRouter>\n      <CssVarsProvider defaultMode=\"system\" theme={theme}>\n        <Sheet\n          onContextMenu={(e) => {\n            e.preventDefault();\n          }}\n          sx={{\n            width: \"100%\",\n            height: \"100%\",\n            overflow: \"auto\",\n          }}\n        >\n          <Routes>\n            <Route element={<IDELayout />}>\n              <Route index element={<Onboarding />} />\n              <Route path=\"/ide/:path\" element={<IDE />} />\n              <Route path=\"/new\" element={<New />} />\n              <Route path=\"/new/:template\" element={<NewTemplate />} />\n              <Route path=\"*\" element={<Navigate to=\"/\" replace />} />\n\n              <Route path=\"/preferences/:page?\" element={<Preferences />} />\n            </Route>\n            <Route path=\"/about\" element={<About />} />\n          </Routes>\n        </Sheet>\n      </CssVarsProvider>\n    </BrowserRouter>\n  );\n};\n\nexport default App;\n"
  },
  {
    "path": "src/components/CommandButton.tsx",
    "content": "import { Button, MenuItem } from \"@mui/joy\";\nimport { useCommandRunner } from \"../utilities/Command\";\nimport { useIDE } from \"../utilities/IDEContext\";\nimport { useToast } from \"react-toast-plus\";\n\nexport interface CommandButtonProps {\n  command: string;\n  parameters?: Record<string, unknown>;\n  label?: string;\n  tooltip?: string;\n  icon?: React.ReactNode;\n  variant?: \"plain\" | \"outlined\" | \"soft\" | \"solid\";\n  sx?: React.CSSProperties;\n  clearConsole?: boolean;\n  validate?: () => boolean;\n  validateAsync?: () => Promise<boolean>;\n  after?: (data: any) => void;\n  disabled?: boolean;\n  useMenuItem?: boolean;\n  shortcut?: React.ReactNode;\n  id?: string;\n  size?: \"sm\" | \"md\" | \"lg\";\n}\n\nexport default function CommandButton({\n  command,\n  parameters,\n  label,\n  icon,\n  variant,\n  tooltip,\n  sx = {},\n  clearConsole = true,\n  validate = () => true,\n  validateAsync = () => Promise.resolve(true),\n  after = (_: any) => {},\n  disabled = false,\n  useMenuItem = false,\n  size = \"md\",\n  shortcut,\n  id,\n}: CommandButtonProps) {\n  const { isRunningCommand, currentCommand, runCommand, cancelCommand } =\n    useCommandRunner();\n  const { setConsoleLines } = useIDE();\n\n  const Component: React.ElementType = useMenuItem ? MenuItem : Button;\n  const { addToast } = useToast();\n\n  return (\n    <Component\n      disabled={disabled || (isRunningCommand && currentCommand !== command)}\n      loading={\n        useMenuItem ? undefined : isRunningCommand && currentCommand === command\n      }\n      variant={variant}\n      size={size}\n      sx={\n        useMenuItem\n          ? {}\n          : {\n              marginRight: \"var(--padding-md)\",\n              padding: \"0 var(--padding-md)\",\n              ...sx,\n            }\n      }\n      title={tooltip}\n      onClick={async () => {\n        if (!validate() || !(await validateAsync())) {\n          return;\n        }\n        if (clearConsole) {\n          setConsoleLines([]);\n        }\n        if (isRunningCommand) {\n          if (currentCommand === command) {\n            cancelCommand();\n          }\n          return;\n        }\n        runCommand(command, parameters)\n          .then(after)\n          .catch((e) => {\n            addToast.error(e);\n            console.error(e);\n          });\n      }}\n      id={id}\n    >\n      <div\n        style={{\n          display: \"flex\",\n          gap: \"var(--padding-xs)\",\n          alignItems: \"center\",\n        }}\n      >\n        {icon !== undefined && icon}\n        {label != \"\" && label != undefined && label}\n      </div>\n      {shortcut !== undefined && \" \"}\n      {shortcut}\n    </Component>\n  );\n}\n"
  },
  {
    "path": "src/components/Menu/MenuBar.tsx",
    "content": "import Menu from \"@mui/joy/Menu\";\nimport List from \"@mui/joy/List\";\nimport ListItem from \"@mui/joy/ListItem\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport MenuBarButton from \"./MenuBarButton\";\nimport MenuGroup from \"./MenuGroup\";\nimport {\n  Shortcut,\n  acceleratorPresssed,\n  acceleratorPresssedMonaco,\n} from \"../../utilities/Shortcut\";\nimport CommandButton from \"../CommandButton\";\nimport {\n  Construction,\n  PhonelinkSetup,\n  Refresh,\n  CleaningServices,\n  CameraAlt,\n} from \"@mui/icons-material\";\nimport { useParams } from \"react-router-dom\";\nimport { Divider, Option, Select } from \"@mui/joy\";\nimport { useIDE } from \"../../utilities/IDEContext\";\nimport { useStore } from \"../../utilities/StoreContext\";\nimport { useToast } from \"react-toast-plus\";\nimport bar from \"./MenuBarDefinition\";\nimport { IStandaloneCodeEditor } from \"@codingame/monaco-vscode-api/vscode/vs/editor/standalone/browser/standaloneCodeEditor\";\n\nexport interface MenuBarProps {\n  callbacks: Record<string, () => void>;\n  editor: IStandaloneCodeEditor | null;\n}\nexport default function MenuBar({ callbacks, editor }: MenuBarProps) {\n  const menus = useRef<Array<HTMLButtonElement>>([]);\n  const [menuIndex, setMenuIndex] = useState<null | number>(null);\n\n  const resetMenuIndex = useCallback(() => setMenuIndex(null), []);\n  const { path } = useParams<\"path\">();\n  const {\n    devices,\n    selectedToolchain,\n    selectedDevice,\n    setSelectedDevice,\n    setScreenshot,\n    mountDdi,\n  } = useIDE();\n  const [anisetteServer] = useStore<string>(\n    \"apple-id/anisette-server\",\n    \"ani.sidestore.io\"\n  );\n  const { addToast } = useToast();\n\n  const updateScreenshot = useCallback(\n    (data: number[]) => {\n      const blob = new Blob([new Uint8Array(data)], {\n        type: \"image/png\",\n      });\n      const url = URL.createObjectURL(blob);\n      setScreenshot(url);\n    },\n    [setScreenshot]\n  );\n\n  useEffect(() => {\n    const items: {\n      shortcut: Shortcut;\n      callback: () => void;\n      ignoreShortcutInMonaco: boolean;\n    }[] = [];\n\n    for (const menu of bar) {\n      for (const group of menu.items) {\n        for (const item of group.items) {\n          if (item.shortcut) {\n            const shortcut = Shortcut.fromString(item.shortcut);\n            let callback;\n            if (\n              \"callbackName\" in item &&\n              typeof item.callbackName === \"string\"\n            ) {\n              callback = callbacks[item.callbackName];\n            } else if (\n              \"callback\" in item &&\n              typeof item.callback === \"function\"\n            ) {\n              callback = item.callback;\n            } else if (\n              \"component\" in item &&\n              \"componentId\" in item &&\n              typeof item.componentId === \"string\"\n            ) {\n              // This whole thing needs to be reworked because this is disgusting, too bad I'm lazy!\n              callback = () => {\n                const element = document.getElementById(\n                  item.componentId as string\n                );\n                if (element) {\n                  (element as HTMLButtonElement).click();\n                }\n              };\n            } else {\n              callback = () => {};\n            }\n            items.push({\n              shortcut,\n              callback,\n              ignoreShortcutInMonaco: item.ignoreShortcutInMonaco ?? false,\n            });\n          }\n        }\n      }\n    }\n\n    const handleGlobalKeyDown = (event: KeyboardEvent) => {\n      if (!acceleratorPresssed(event)) return;\n\n      for (const item of items) {\n        if (item.shortcut.pressed(event)) {\n          event.preventDefault();\n          item.callback();\n        }\n      }\n    };\n\n    document.addEventListener(\"keydown\", handleGlobalKeyDown);\n\n    const monacoItems = items.filter((item) => !item.ignoreShortcutInMonaco);\n    let dispose = editor?.onKeyDown((event) => {\n      if (!acceleratorPresssedMonaco(event)) return;\n\n      for (const item of monacoItems) {\n        if (item.shortcut.pressedMonaco(event)) {\n          event.preventDefault();\n          item.callback();\n        }\n      }\n    });\n\n    return () => {\n      document.removeEventListener(\"keydown\", handleGlobalKeyDown);\n      dispose?.dispose();\n    };\n  }, [bar, callbacks, editor]);\n\n  const openNextMenu = () => {\n    if (typeof menuIndex === \"number\") {\n      if (menuIndex === menus.current.length - 1) {\n        setMenuIndex(0);\n      } else {\n        setMenuIndex(menuIndex + 1);\n      }\n    }\n  };\n\n  const openPreviousMenu = () => {\n    if (typeof menuIndex === \"number\") {\n      if (menuIndex === 0) {\n        setMenuIndex(menus.current.length - 1);\n      } else {\n        setMenuIndex(menuIndex - 1);\n      }\n    }\n  };\n\n  const handleKeyDown = (event: React.KeyboardEvent) => {\n    if (event.key === \"ArrowRight\") {\n      openNextMenu();\n    }\n    if (event.key === \"ArrowLeft\") {\n      openPreviousMenu();\n    }\n  };\n\n  const createHandleButtonKeyDown =\n    (index: number) => (event: React.KeyboardEvent) => {\n      if (event.key === \"ArrowRight\") {\n        if (index === menus.current.length - 1) {\n          menus.current[0]?.focus();\n        } else {\n          menus.current[index + 1]?.focus();\n        }\n      }\n      if (event.key === \"ArrowLeft\") {\n        if (index === 0) {\n          menus.current[menus.current.length]?.focus();\n        } else {\n          menus.current[index - 1]?.focus();\n        }\n      }\n    };\n\n  useEffect(() => {\n    if (devices.length > 0) {\n      setSelectedDevice(devices[0]);\n    } else {\n      setSelectedDevice(null);\n    }\n  }, [devices]);\n\n  return (\n    <List\n      size=\"sm\"\n      orientation=\"horizontal\"\n      aria-label=\"CrossCode menu bar\"\n      role=\"menubar\"\n      sx={{\n        bgcolor: \"background.body\",\n        width: \"100%\",\n        borderColor: \"divider\",\n        borderBottomWidth: \"1px\",\n        borderBottomStyle: \"solid\",\n        paddingRight: 0,\n      }}\n    >\n      {bar &&\n        bar.map((menu, index) => (\n          <ListItem key={index}>\n            <MenuBarButton\n              open={menuIndex === index}\n              onOpen={() => {\n                setMenuIndex((prevMenuIndex) =>\n                  prevMenuIndex === null ? index : null\n                );\n              }}\n              onKeyDown={createHandleButtonKeyDown(1)}\n              onMouseEnter={() => {\n                if (typeof menuIndex === \"number\") {\n                  setMenuIndex(index);\n                }\n              }}\n              ref={(instance) => {\n                menus.current[index] = instance!;\n              }}\n              menu={\n                <Menu\n                  keepMounted\n                  size=\"sm\"\n                  onClose={() => {\n                    menus.current[index]?.focus();\n                  }}\n                >\n                  <MenuGroup\n                    handleKeyDown={handleKeyDown}\n                    resetMenuIndex={resetMenuIndex}\n                    groups={menu.items}\n                    selectedDevice={selectedDevice}\n                    callbacks={callbacks}\n                  />\n                </Menu>\n              }\n            >\n              {menu.label}\n            </MenuBarButton>\n          </ListItem>\n        ))}\n      <CommandButton\n        variant=\"plain\"\n        command=\"clean_swift\"\n        icon={<CleaningServices />}\n        parameters={{\n          folder: path,\n          toolchainPath: selectedToolchain?.path ?? \"\",\n        }}\n        tooltip=\"Clean\"\n        sx={{ marginRight: 0, marginLeft: \"auto\" }}\n      />\n      <CommandButton\n        variant=\"plain\"\n        command=\"build_swift\"\n        icon={<Construction />}\n        parameters={{\n          folder: path,\n          toolchainPath: selectedToolchain?.path ?? \"\",\n          debug: true,\n        }}\n        tooltip=\"Build .ipa\"\n        sx={{ marginRight: 0 }}\n      />\n      <Divider orientation=\"vertical\" />\n      <div style={{ display: \"flex\", alignItems: \"center\" }}>\n        <CommandButton\n          variant=\"plain\"\n          command=\"refresh_idevice\"\n          icon={<Refresh />}\n          tooltip=\"Refresh Devices\"\n          parameters={{}}\n          sx={{ marginLeft: 0, marginRight: 0 }}\n          clearConsole={false}\n        />\n        <Select\n          size=\"sm\"\n          title=\"Select Device\"\n          value={selectedDevice?.id.toString() ?? \"none\"}\n          onChange={(_, value) => {\n            setSelectedDevice(\n              devices.find((d) => d.id.toString() === value) || null\n            );\n          }}\n          placeholder=\"Select Device...\"\n        >\n          {devices.length < 1 && (\n            <Option disabled value=\"none\">\n              No devices connected\n            </Option>\n          )}\n          {devices.map((device, index) => (\n            <Option key={index} value={device.id.toString()}>\n              {device.name}\n            </Option>\n          ))}\n        </Select>\n        <CommandButton\n          disabled={!selectedDevice}\n          tooltip=\"Build & Install\"\n          variant=\"plain\"\n          command=\"deploy_swift\"\n          icon={<PhonelinkSetup />}\n          parameters={{\n            folder: path,\n            anisetteServer,\n            device: selectedDevice,\n            toolchainPath: selectedToolchain?.path ?? \"\",\n            debug: true,\n          }}\n          validate={() => {\n            if (!selectedDevice) {\n              addToast.error(\"Please select a device to deploy to.\");\n              return false;\n            }\n            return true;\n          }}\n          sx={{ marginRight: 0 }}\n        />\n        <CommandButton\n          disabled={!selectedDevice}\n          tooltip=\"Take Screenshot\"\n          variant=\"plain\"\n          command=\"take_screenshot\"\n          icon={<CameraAlt />}\n          parameters={{\n            device: selectedDevice,\n          }}\n          after={updateScreenshot}\n          validateAsync={async () => {\n            if (!selectedDevice) {\n              addToast.error(\"Please select a device to take a screenshot of.\");\n              return false;\n            }\n            return await mountDdi(true);\n          }}\n          sx={{ marginRight: 0, marginLeft: 0 }}\n        />\n      </div>\n    </List>\n  );\n}\n"
  },
  {
    "path": "src/components/Menu/MenuBarButton.tsx",
    "content": "import {\n  Dropdown,\n  DropdownProps,\n  ListItemButton,\n  MenuButton,\n  Theme,\n  menuItemClasses,\n  typographyClasses,\n} from \"@mui/joy\";\nimport { cloneElement, forwardRef } from \"react\";\n\ntype MenuBarButtonProps = Pick<DropdownProps, \"children\" | \"open\"> & {\n  onOpen: DropdownProps[\"onOpenChange\"];\n  onKeyDown: React.KeyboardEventHandler;\n  menu: JSX.Element;\n  onMouseEnter: React.MouseEventHandler;\n};\n\nexport default forwardRef(\n  (\n    { children, menu, open, onOpen, onKeyDown, ...props }: MenuBarButtonProps,\n    ref: React.ForwardedRef<HTMLButtonElement>\n  ) => {\n    return (\n      <Dropdown open={open} onOpenChange={onOpen}>\n        <MenuButton\n          {...props}\n          slots={{ root: ListItemButton }}\n          ref={ref}\n          role=\"menuitem\"\n          variant={open ? \"soft\" : \"plain\"}\n        >\n          {children}\n        </MenuButton>\n        {cloneElement(menu, {\n          slotProps: {\n            listbox: {\n              id: `toolbar-example-menu-${children}`,\n              \"aria-label\": children,\n            },\n          },\n          placement: \"bottom-start\",\n          disablePortal: false,\n          variant: \"soft\",\n          sx: (theme: Theme) => ({\n            overflowX: \"hidden\",\n            width: 288,\n            boxShadow: \"0 2px 8px 0px rgba(0 0 0 / 0.38)\",\n            \"--List-padding\": \"var(--ListDivider-gap)\",\n            \"--ListItem-minHeight\": \"32px\",\n            [`&& .${menuItemClasses.root}`]: {\n              transition: \"none\",\n              \"&:hover\": {\n                ...theme.variants.solid.primary,\n                [`& .${typographyClasses.root}`]: {\n                  color: \"inherit\",\n                },\n              },\n            },\n          }),\n        })}\n      </Dropdown>\n    );\n  }\n);\n"
  },
  {
    "path": "src/components/Menu/MenuBarDefinition.tsx",
    "content": "import { openUrl } from \"@tauri-apps/plugin-opener\";\nimport { MenuBarData } from \"./MenuGroup\";\nimport { WebviewWindow } from \"@tauri-apps/api/webviewWindow\";\nimport { useParams } from \"react-router-dom\";\nimport { useIDE } from \"../../utilities/IDEContext\";\nimport CommandButton from \"../CommandButton\";\nimport { useStore } from \"../../utilities/StoreContext\";\nimport { useToast } from \"react-toast-plus\";\nimport { MenuItem } from \"@mui/joy\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { restartServer } from \"../../utilities/lsp-client\";\nimport { open } from \"@tauri-apps/plugin-dialog\";\nimport { useContext } from \"react\";\nimport { UpdateContext } from \"../../utilities/UpdateContext\";\n\nexport default [\n  {\n    label: \"File\",\n    items: [\n      {\n        label: \"New\",\n        items: [\n          // {\n          //   name: \"New File...\",\n          //   shortcut: \"Ctrl+N\",\n          //   callback: () => {\n          //     alert(\"Not implemented yet :(\");\n          //   },\n          // },\n          {\n            name: \"New Project...\",\n            callbackName: \"newProject\",\n          },\n        ],\n      },\n      {\n        label: \"Open\",\n        items: [\n          {\n            name: \"Open File...\",\n            shortcut: \"Ctrl+O\",\n            callbackName: \"openFile\",\n          },\n          {\n            name: \"Open Folder...\",\n            callbackName: \"openFolderDialog\",\n          },\n        ],\n      },\n      {\n        label: \"Save\",\n        items: [\n          {\n            name: \"Save\",\n            shortcut: \"Ctrl+S\",\n            callbackName: \"save\",\n          },\n          {\n            name: \"Save As...\",\n            shortcut: \"Ctrl+Shift+S\",\n            callback: () => {\n              alert(\"Not implemented yet :(\");\n            },\n          },\n        ],\n      },\n    ],\n  },\n  {\n    label: \"Edit\",\n    items: [\n      {\n        label: \"Timeline\",\n        items: [\n          {\n            name: \"Undo\",\n            shortcut: \"Ctrl+Z\",\n            ignoreShortcutInMonaco: true,\n            callbackName: \"undo\",\n          },\n          {\n            name: \"Redo\",\n            shortcut: \"Ctrl+Shift+Z\",\n            ignoreShortcutInMonaco: true,\n            callbackName: \"redo\",\n          },\n        ],\n      },\n      {\n        label: \"Icon\",\n        items: [\n          {\n            name: \"Import Icon\",\n            component: () => {\n              const { path } = useParams<\"path\">();\n              const { addToast } = useToast();\n              return (\n                <MenuItem\n                  onClick={async () => {\n                    if (!path) return;\n                    const iconPath = await open({\n                      title: \"Select Icon\",\n                      multiple: false,\n                      directory: false,\n                      filters: [\n                        {\n                          name: \"Images\",\n                          extensions: [\"png\", \"jpg\", \"jpeg\", \"gif\"],\n                        },\n                      ],\n                    });\n                    addToast.promise(\n                      invoke(\"import_icon\", {\n                        projectPath: path,\n                        iconPath: iconPath,\n                      }),\n                      {\n                        pending: \"Importing icon...\",\n                        success: \"Successfully imported icon!\",\n                        error: \"Failed to import icon\",\n                      }\n                    );\n                  }}\n                  id=\"startLSPMenuBtn\"\n                >\n                  Import Icon\n                </MenuItem>\n              );\n            },\n          },\n        ],\n      },\n      {\n        label: \"Settings\",\n        items: [\n          {\n            name: \"Preferences...\",\n            callback: async () => {\n              let prefsWindow = await WebviewWindow.getByLabel(\"prefs\");\n              if (prefsWindow) {\n                await prefsWindow.show();\n                await prefsWindow.center();\n                await prefsWindow.setFocus();\n                return;\n              }\n\n              const appWindow = new WebviewWindow(\"prefs\", {\n                title: \"Preferences\",\n                resizable: false,\n                width: 800,\n                height: 600,\n                url: \"/preferences/general\",\n              });\n              appWindow.once(\"tauri://created\", function () {\n                appWindow.center();\n              });\n              appWindow.once(\"tauri://error\", function (e) {\n                console.error(\"Error creating window:\", e);\n              });\n            },\n          },\n        ],\n      },\n    ],\n  },\n  {\n    label: \"View\",\n    items: [\n      {\n        label: \"Navigation\",\n        items: [\n          {\n            name: \"Show Welcome Page\",\n            callbackName: \"welcomePage\",\n          },\n        ],\n      },\n      {\n        label: \"Debug\",\n        items: [\n          {\n            name: \"Reload Window\",\n            callback: async () => {\n              window.location.reload();\n            },\n            shortcut: \"Ctrl+R\",\n          },\n        ],\n      },\n    ],\n  },\n  {\n    label: \"Build\",\n    items: [\n      {\n        label: \"Build\",\n        items: [\n          {\n            name: \"Build .ipa (Debug)\",\n            shortcut: \"Ctrl+B\",\n            component: ({ shortcut }) => {\n              const { path } = useParams<\"path\">();\n              const { selectedToolchain } = useIDE();\n              return (\n                <CommandButton\n                  shortcut={shortcut}\n                  command=\"build_swift\"\n                  parameters={{\n                    folder: path,\n                    toolchainPath: selectedToolchain?.path ?? \"\",\n                    debug: true,\n                  }}\n                  label=\"Build .ipa (Debug)\"\n                  useMenuItem\n                  id=\"buildDebugMenuBtn\"\n                />\n              );\n            },\n            componentId: \"buildDebugMenuBtn\",\n          },\n          {\n            name: \"Build .ipa (Release)\",\n            shortcut: \"Ctrl+Shift+B\",\n            component: ({ shortcut }) => {\n              const { path } = useParams<\"path\">();\n              const { selectedToolchain } = useIDE();\n              return (\n                <CommandButton\n                  shortcut={shortcut}\n                  command=\"build_swift\"\n                  parameters={{\n                    folder: path,\n                    toolchainPath: selectedToolchain?.path ?? \"\",\n                    debug: false,\n                  }}\n                  label=\"Build .ipa (Release)\"\n                  useMenuItem\n                  id=\"buildReleaseMenuBtn\"\n                />\n              );\n            },\n            componentId: \"buildReleaseMenuBtn\",\n          },\n          {\n            name: \"Build & Install\",\n            shortcut: \"Ctrl+I\",\n            component: ({ selectedDevice, shortcut }) => {\n              const { path } = useParams<\"path\">();\n              const { selectedToolchain } = useIDE();\n              const [anisetteServer] = useStore<string>(\n                \"apple-id/anisette-server\",\n                \"ani.sidestore.io\"\n              );\n              const { addToast } = useToast();\n              return (\n                <CommandButton\n                  shortcut={shortcut}\n                  command=\"deploy_swift\"\n                  parameters={{\n                    folder: path,\n                    anisetteServer,\n                    device: selectedDevice,\n                    toolchainPath: selectedToolchain?.path ?? \"\",\n                    debug: true,\n                  }}\n                  label=\"Build & Install\"\n                  validate={() => {\n                    if (!selectedDevice) {\n                      addToast.error(\"Please select a device to deploy to.\");\n                      return false;\n                    }\n                    return true;\n                  }}\n                  useMenuItem\n                  id=\"deployMenuBtn\"\n                />\n              );\n            },\n            componentId: \"deployMenuBtn\",\n          },\n        ],\n      },\n      {\n        label: \"Clean\",\n        items: [\n          {\n            name: \"Clean\",\n            shortcut: \"Ctrl+Shift+C\",\n            component: ({ shortcut }) => {\n              const { path } = useParams<\"path\">();\n              const { selectedToolchain } = useIDE();\n              return (\n                <CommandButton\n                  shortcut={shortcut}\n                  command=\"clean_swift\"\n                  parameters={{\n                    folder: path,\n                    toolchainPath: selectedToolchain?.path ?? \"\",\n                  }}\n                  label=\"Clean\"\n                  useMenuItem\n                  id=\"cleanMenuBtn\"\n                />\n              );\n            },\n            componentId: \"cleanMenuBtn\",\n          },\n        ],\n      },\n      {\n        label: \"Start LSP\",\n        items: [\n          {\n            name: \"Restart LSP\",\n            component: () => {\n              const { path } = useParams<\"path\">();\n              const { selectedToolchain } = useIDE();\n              return (\n                <MenuItem\n                  onClick={async () => {\n                    if (!selectedToolchain || !path) return;\n                    restartServer(path, selectedToolchain).catch((e) => {\n                      console.error(\"Failed to restart SourceKit-LSP:\", e);\n                    });\n                  }}\n                  id=\"startLSPMenuBtn\"\n                >\n                  Restart LSP\n                </MenuItem>\n              );\n            },\n            componentId: \"startLSPMenuBtn\",\n          },\n          {\n            name: \"Stop LSP\",\n            component: () => {\n              return (\n                <MenuItem\n                  onClick={async () => {\n                    await invoke<number>(\"stop_sourcekit_server\");\n                  }}\n                  id=\"stopLSPMenuBtn\"\n                >\n                  Stop LSP\n                </MenuItem>\n              );\n            },\n            componentId: \"stopLSPMenuBtn\",\n          },\n        ],\n      },\n    ],\n  },\n  {\n    label: \"Help\",\n    items: [\n      {\n        label: \"About\",\n        items: [\n          {\n            name: \"About CrossCode\",\n            callback: async () => {\n              let aboutWindow = await WebviewWindow.getByLabel(\"about\");\n              if (aboutWindow) {\n                await aboutWindow.show();\n                await aboutWindow.center();\n                await aboutWindow.setFocus();\n                return;\n              }\n\n              const appWindow = new WebviewWindow(\"about\", {\n                title: \"About CrossCode\",\n                resizable: false,\n                width: 400,\n                height: 260,\n                url: \"/about\",\n                backgroundColor: \"#171a1c\",\n              });\n\n              appWindow.once(\"tauri://created\", async function () {\n                await appWindow.center();\n              });\n              appWindow.once(\"tauri://error\", function (e) {\n                console.error(\"Error creating window:\", e);\n              });\n            },\n          },\n          {\n            name: \"View Github\",\n            callback: () => {\n              openUrl(\"https://github.com/nab138/CrossCode\");\n            },\n          },\n        ],\n      },\n      {\n        label: \"Get Help\",\n        items: [\n          {\n            name: \"Report Issue\",\n            callback: () => {\n              openUrl(\"https://github.com/nab138/CrossCode/issues\");\n            },\n          },\n          {\n            name: \"Troubleshooting\",\n            callback: () => {\n              openUrl(\n                \"https://github.com/nab138/CrossCode/wiki/Troubleshooting\"\n              );\n            },\n          },\n        ],\n      },\n      {\n        label: \"Debug\",\n        items: [\n          {\n            name: \"Open Devtools\",\n            shortcut: \"Ctrl+Shift+I\",\n            ignoreShortcutInMonaco: true,\n            callback: () => {\n              invoke(\"open_devtools\");\n            },\n          },\n        ],\n      },\n      {\n        label: \"Updates\",\n        items: [\n          {\n            name: \"Check for Updates\",\n            component: () => {\n              const { checkForUpdates } = useContext(UpdateContext);\n              return (\n                <MenuItem\n                  onClick={async () => {\n                    await checkForUpdates();\n                  }}\n                  id=\"checkForUpdatesMenuBtn\"\n                >\n                  Check for Updates\n                </MenuItem>\n              );\n            },\n          },\n        ],\n      },\n    ],\n  },\n] as MenuBarData;\n"
  },
  {
    "path": "src/components/Menu/MenuGroup.tsx",
    "content": "import { List, ListDivider, ListItem, MenuItem, Typography } from \"@mui/joy\";\n\nimport { Fragment } from \"react/jsx-runtime\";\nimport { DeviceInfo } from \"../../utilities/IDEContext\";\n\ntype BaseMenuItem = {\n  name: string;\n  shortcut?: string;\n  ignoreShortcutInMonaco?: boolean;\n};\n\nexport type MenuItem = BaseMenuItem &\n  (\n    | { callback: () => void }\n    | { callbackName: string }\n    | {\n        component: React.FC<{\n          shortcut?: React.ReactNode;\n          selectedDevice?: DeviceInfo | null;\n        }>;\n        componentId: string;\n      }\n  );\n\ntype MenuGroup = {\n  label: string;\n  items: MenuItem[];\n};\n\nexport type MenuBarData = {\n  label: string;\n  items: MenuGroup[];\n}[];\n\nexport interface MenuGroupProps {\n  groups: MenuGroup[];\n  handleKeyDown: (event: React.KeyboardEvent) => void;\n  resetMenuIndex: () => void;\n  callbacks: Record<string, () => void>;\n  selectedDevice: DeviceInfo | null;\n}\n\nconst renderShortcut = (text: string) => (\n  <Typography level=\"body-sm\" textColor=\"text.tertiary\" ml=\"auto\">\n    {text}\n  </Typography>\n);\n\nconst MenuGroup: React.FC<MenuGroupProps> = ({\n  groups,\n  handleKeyDown,\n  callbacks,\n  resetMenuIndex,\n  selectedDevice,\n}) => {\n  return (\n    <>\n      {groups.map((group, groupIndex) => (\n        <Fragment key={groupIndex}>\n          <ListItem nested>\n            <List aria-label={group.label}>\n              {group.items.map((item, itemIndex) => {\n                if (\"component\" in item) {\n                  return (\n                    <span key={itemIndex}>\n                      {item.component({\n                        selectedDevice,\n                        shortcut: item.shortcut\n                          ? renderShortcut(item.shortcut)\n                          : undefined,\n                      })}\n                    </span>\n                  );\n                }\n                return (\n                  <MenuItem\n                    key={itemIndex}\n                    onClick={() => {\n                      resetMenuIndex();\n                      let callback;\n                      if (\n                        \"callbackName\" in item &&\n                        typeof item.callbackName === \"string\"\n                      ) {\n                        callback = callbacks[item.callbackName];\n                      } else if (\n                        \"callback\" in item &&\n                        typeof item.callback === \"function\"\n                      ) {\n                        callback = item.callback;\n                      } else {\n                        callback = () => {};\n                      }\n                      callback();\n                    }}\n                    onKeyDown={handleKeyDown}\n                  >\n                    {item.name} {item.shortcut && renderShortcut(item.shortcut)}\n                  </MenuItem>\n                );\n              })}\n            </List>\n          </ListItem>\n          {groupIndex < groups.length - 1 && <ListDivider />}\n        </Fragment>\n      ))}\n    </>\n  );\n};\n\nexport default MenuGroup;\n"
  },
  {
    "path": "src/components/OperationView.css",
    "content": ".operation-content {\n  display: flex;\n  flex-direction: column;\n  gap: var(--padding-xl);\n}\n\n.operation-step-icon {\n  width: 1.5rem;\n  height: 1.5rem;\n  min-width: 1.5rem;\n  min-height: 1.5rem;\n\n  font-size: 1.5rem;\n}\n\n.operation-step {\n  display: flex;\n  gap: var(--padding-md);\n  align-items: center;\n}\n\n.operation-extra-details {\n  background-color: black;\n  overflow-x: auto;\n  padding: var(--padding-md);\n  border-radius: 1px;\n  margin: 0;\n}\n\n.operation-step-internal {\n  flex-shrink: 1;\n}\n"
  },
  {
    "path": "src/components/OperationView.tsx",
    "content": "import {\n  Accordion,\n  AccordionDetails,\n  AccordionSummary,\n  Divider,\n  Modal,\n  ModalClose,\n  ModalDialog,\n  Typography,\n} from \"@mui/joy\";\nimport { OperationState } from \"../utilities/operations\";\nimport \"./OperationView.css\";\nimport { SuccessIcon, ErrorIcon, StyledLoadingIcon } from \"react-toast-plus\";\nimport { PanoramaFishEye, DoNotDisturbOn } from \"@mui/icons-material\";\n\nexport default ({\n  operationState,\n  closeMenu,\n}: {\n  operationState: OperationState;\n  closeMenu: () => void;\n}) => {\n  const operation = operationState.current;\n  const opFailed = operationState.failed.length > 0;\n  const done =\n    (opFailed &&\n      operationState.started.length ==\n        operationState.completed.length + operationState.failed.length) ||\n    operationState.completed.length == operation.steps.length;\n\n  return (\n    <Modal\n      open={true}\n      onClose={() => {\n        if (done) closeMenu();\n      }}\n    >\n      <ModalDialog sx={{ minWidth: \"40rem\", maxWidth: \"90vw\" }}>\n        {done && <ModalClose />}\n        <div>\n          <Typography level=\"h3\">{operation?.title}</Typography>\n          <Typography level=\"body-lg\">\n            {done\n              ? opFailed\n                ? \"Operation failed. Please see steps for details.\"\n                : \"Operation completed!\"\n              : \"Please wait (this may take a while)...\"}\n          </Typography>\n        </div>\n        <Divider />\n        <div className=\"operation-content\">\n          {operation.steps.map((step) => {\n            let failed = operationState.failed.find((f) => f.stepId == step.id);\n            let completed = operationState.completed.includes(step.id);\n            let started = operationState.started.includes(step.id);\n            let notStarted = !failed && !completed && !started;\n            return (\n              <div className=\"operation-step\" key={step.id}>\n                <div className=\"operation-step-icon\">\n                  {failed && <ErrorIcon />}\n                  {!failed && completed && <SuccessIcon />}\n                  {!failed && !completed && started && <StyledLoadingIcon />}\n                  {notStarted && !opFailed && (\n                    <PanoramaFishEye\n                      sx={{\n                        width: \"100%\",\n                        height: \"100%\",\n                        color: \"neutral.500\",\n\n                        transform: \"scale(1.2)\",\n                      }}\n                    />\n                  )}\n                  {notStarted && opFailed && (\n                    <DoNotDisturbOn\n                      sx={{\n                        width: \"100%\",\n                        height: \"100%\",\n                        color: \"neutral.500\",\n                        transform: \"scale(1.2)\",\n                      }}\n                    />\n                  )}\n                </div>\n\n                <div className=\"operation-step-internal\">\n                  <Typography\n                    textColor={notStarted ? \"neutral.500\" : undefined}\n                  >\n                    {step.title}\n                  </Typography>\n                  {failed && (\n                    <Accordion sx={{ marginTop: 0 }}>\n                      <AccordionSummary>\n                        <Typography level=\"body-sm\">Details</Typography>\n                      </AccordionSummary>\n                      <AccordionDetails>\n                        <pre className=\"operation-extra-details\">\n                          {failed.extraDetails}\n                        </pre>\n                      </AccordionDetails>\n                    </Accordion>\n                  )}\n                </div>\n              </div>\n            );\n          })}\n        </div>\n      </ModalDialog>\n    </Modal>\n  );\n};\n"
  },
  {
    "path": "src/components/SDKMenu.tsx",
    "content": "import { Button, Typography } from \"@mui/joy\";\nimport { useIDE } from \"../utilities/IDEContext\";\nimport { open } from \"@tauri-apps/plugin-dialog\";\nimport { useToast } from \"react-toast-plus\";\nimport { useCallback, useEffect } from \"react\";\nimport { openUrl } from \"@tauri-apps/plugin-opener\";\nimport { installSdkOperation } from \"../utilities/operations\";\nimport ErrorIcon from \"@mui/icons-material/Error\";\nimport WarningIcon from \"@mui/icons-material/Warning\";\nimport { DARWIN_SDK_VERSION } from \"../utilities/constants\";\n\nexport default () => {\n  const {\n    selectedToolchain,\n    hasDarwinSDK,\n    darwinSDKVersion,\n    checkSDK,\n    startOperation,\n    isWindows,\n    hasWSL,\n  } = useIDE();\n  const { addToast } = useToast();\n\n  const isWindowsReady = !isWindows || hasWSL;\n\n  const install = useCallback(async () => {\n    let xipPath = await open({\n      directory: false,\n      multiple: false,\n      filters: [\n        {\n          name: \"XCode\",\n          extensions: [\"xip\"],\n        },\n      ],\n    });\n    if (!xipPath) {\n      addToast.error(\"No Xcode.xip selected\");\n      return;\n    }\n    const params = {\n      xcodePath: xipPath,\n      toolchainPath: selectedToolchain?.path || \"\",\n      isDir: false,\n    };\n    await startOperation(installSdkOperation, params);\n    checkSDK();\n  }, [selectedToolchain, addToast]);\n\n  const installFromFolder = useCallback(async () => {\n    let xcodePath = await open({\n      directory: true,\n      multiple: false,\n      filters: [\n        {\n          name: \"XCode.app\",\n          extensions: [\"app\"],\n        },\n      ],\n    });\n    if (!xcodePath) {\n      addToast.error(\"No Xcode selected\");\n      return;\n    }\n    const params = {\n      xcodePath,\n      toolchainPath: selectedToolchain?.path || \"\",\n      isDir: true,\n    };\n    await startOperation(installSdkOperation, params);\n    checkSDK();\n  }, [selectedToolchain, addToast]);\n\n  useEffect(() => {\n    checkSDK();\n  }, [checkSDK]);\n\n  if (hasDarwinSDK === null) {\n    return <div>Checking for SDK...</div>;\n  }\n\n  return (\n    <div\n      style={{\n        width: \"fit-content\",\n        display: \"flex\",\n        flexDirection: \"column\",\n        gap: \"var(--padding-md)\",\n      }}\n    >\n      <div>\n        <Typography\n          level=\"body-md\"\n          color={\n            hasDarwinSDK ? \"success\" : selectedToolchain ? \"danger\" : \"warning\"\n          }\n          sx={{\n            alignContent: \"center\",\n            display: \"flex\",\n            gap: \"var(--padding-xs)\",\n          }}\n        >\n          {isWindowsReady ? (\n            hasDarwinSDK ? (\n              \"Darwin SDK is installed!\"\n            ) : (\n              <>\n                {selectedToolchain ? <ErrorIcon /> : <WarningIcon />}\n                {selectedToolchain\n                  ? \"Darwin SDK is not installed\"\n                  : \"Select a swift toolchain first\"}\n              </>\n            )\n          ) : (\n            \"Install WSL and Swift first.\"\n          )}\n        </Typography>\n        {hasDarwinSDK && (\n          <Typography\n            level=\"body-sm\"\n            color={\n              darwinSDKVersion === DARWIN_SDK_VERSION ? undefined : \"warning\"\n            }\n          >\n            {darwinSDKVersion === DARWIN_SDK_VERSION\n              ? `Version: ${darwinSDKVersion}`\n              : `Unsupported SDK version (${darwinSDKVersion}). Apps may compile, but you may not be able to use newer features (like liquid glass). Please re-install with Xcode 26.`}\n          </Typography>\n        )}\n      </div>\n      <div\n        style={{\n          display: \"flex\",\n          gap: \"var(--padding-md)\",\n        }}\n      >\n        <Button\n          variant=\"soft\"\n          onClick={(e) => {\n            e.preventDefault();\n            openUrl(\n              \"https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_26/Xcode_26_Universal.xip\"\n            );\n          }}\n        >\n          Download XCode 26\n        </Button>\n        <Button\n          variant=\"soft\"\n          onClick={(e) => {\n            if (e.shiftKey) {\n              installFromFolder();\n            } else {\n              install();\n            }\n          }}\n          disabled={!selectedToolchain}\n        >\n          {hasDarwinSDK ? \"Reinstall SDK\" : \"Install SDK\"}\n        </Button>\n        <Button variant=\"soft\" onClick={checkSDK} disabled={!selectedToolchain}>\n          Check Again\n        </Button>\n      </div>\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/components/SwiftMenu.tsx",
    "content": "import {\n  Button,\n  FormControl,\n  Link,\n  Radio,\n  RadioGroup,\n  Typography,\n} from \"@mui/joy\";\nimport { Toolchain, useIDE } from \"../utilities/IDEContext\";\nimport { useEffect, useState } from \"react\";\nimport { openUrl } from \"@tauri-apps/plugin-opener\";\nimport ErrorIcon from \"@mui/icons-material/Error\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { SWIFT_VERSION_PREFIX } from \"../utilities/constants\";\n\nexport default () => {\n  const {\n    selectedToolchain,\n    setSelectedToolchain,\n    toolchains,\n    scanToolchains,\n    locateToolchain,\n    isWindows,\n    hasWSL,\n  } = useIDE();\n\n  const isWindowsReady = !isWindows || hasWSL;\n\n  const [allToolchains, setAllToolchains] = useState<Toolchain[]>([]);\n  useEffect(() => {\n    let loadAllToolchains = async () => {\n      let all: Toolchain[] = [];\n      if (toolchains !== null && toolchains.toolchains) {\n        all = [...toolchains.toolchains];\n      }\n      if (\n        selectedToolchain &&\n        !all.some(\n          (t) => stringifyToolchain(t) === stringifyToolchain(selectedToolchain)\n        ) &&\n        (await invoke(\"validate_toolchain\", {\n          toolchainPath: selectedToolchain.path,\n        }))\n      ) {\n        all.push(selectedToolchain);\n      }\n      setAllToolchains(all);\n    };\n    loadAllToolchains();\n  }, [selectedToolchain, toolchains]);\n\n  return (\n    <div\n      style={{\n        width: \"fit-content\",\n        display: \"flex\",\n        flexDirection: \"column\",\n        gap: \"var(--padding-md)\",\n      }}\n    >\n      {!selectedToolchain && (\n        <Typography\n          level=\"body-md\"\n          color=\"danger\"\n          sx={{\n            alignContent: \"center\",\n            display: \"flex\",\n            gap: \"var(--padding-xs)\",\n          }}\n        >\n          <ErrorIcon />\n          No toolchain selected\n        </Typography>\n      )}\n      <Typography level=\"body-sm\">\n        {toolchains === null\n          ? \"Checking for Swift...\"\n          : toolchains.swiftlyInstalled\n          ? `Swiftly Detected: ${toolchains.swiftlyVersion}`\n          : \"CrossCode was unable to detect Swiftly.\"}\n      </Typography>\n      {!isWindowsReady && toolchains !== null && allToolchains.length === 0 && (\n        <Typography level=\"body-md\" color=\"danger\">\n          Install WSL before swift, as you need to install swift inside of WSL.\n        </Typography>\n      )}\n      {isWindowsReady && toolchains !== null && allToolchains.length === 0 && (\n        <Typography level=\"body-md\" color=\"warning\">\n          No Swift toolchains found. You can get one by installing swiftly\n          {isWindows && \" in WSL\"} and running \"\n          <span\n            style={{\n              fontFamily: \"monospace\",\n            }}\n          >\n            swiftly install {SWIFT_VERSION_PREFIX}\n          </span>\n          \" or manually. If you have already done so, but it is not showing up,\n          your toolchain installation may be broken. For help, refer to the{\" \"}\n          <Link\n            href=\"#\"\n            onClick={(e) => {\n              e.preventDefault();\n              openUrl(\n                \"https://github.com/nab138/CrossCode/wiki/Troubleshooting#swift-toolchain-not-detected\"\n              );\n            }}\n          >\n            troubleshooting guide\n          </Link>\n          .\n        </Typography>\n      )}\n      {selectedToolchain !== null && !isCompatable(selectedToolchain) && (\n        <Typography level=\"body-md\" color=\"danger\">\n          Your selected toolchain is not compatible. Please select a swift{\" \"}\n          {SWIFT_VERSION_PREFIX}\n          toolchain.\n        </Typography>\n      )}\n      {toolchains !== null && allToolchains.length > 0 && (\n        <div>\n          <Typography level=\"body-md\">Select a toolchain:</Typography>\n          <RadioGroup\n            value={stringifyToolchain(selectedToolchain)}\n            sx={{\n              marginTop: \"var(--padding-xs)\",\n              display: \"flex\",\n              flexDirection: \"column\",\n              gap: \"var(--padding-md)\",\n            }}\n          >\n            {allToolchains.map((toolchain) => (\n              <FormControl key={stringifyToolchain(toolchain)}>\n                <Radio\n                  label={\n                    toolchain.version +\n                    (isCompatable(toolchain) ? \"\" : \" - Not Compatable\")\n                  }\n                  disabled={!isCompatable(toolchain) || !isWindowsReady}\n                  value={stringifyToolchain(toolchain)}\n                  variant=\"outlined\"\n                  overlay\n                  onChange={() => setSelectedToolchain(toolchain)}\n                />\n                <div\n                  style={{\n                    display: \"flex\",\n                    alignItems: \"center\",\n                    gap: \"var(--padding-xs)\",\n                  }}\n                >\n                  <Typography level=\"body-sm\">{toolchain.path}</Typography>\n                  <Typography level=\"body-sm\" color=\"primary\">\n                    {toolchain.isSwiftly ? \"(Swiftly)\" : \"(Manually Installed)\"}\n                  </Typography>\n                </div>\n              </FormControl>\n            ))}\n          </RadioGroup>\n        </div>\n      )}\n      <div\n        style={{\n          display: \"flex\",\n          gap: \"var(--padding-md)\",\n        }}\n      >\n        {toolchains?.swiftlyInstalled === false &&\n          selectedToolchain === null && (\n            <Button\n              disabled={!isWindowsReady}\n              variant=\"soft\"\n              onClick={() => {\n                openUrl(\"https://www.swift.org/install/linux\");\n              }}\n            >\n              Download Swift\n            </Button>\n          )}\n        {\n          <Button\n            disabled={!isWindowsReady}\n            variant=\"soft\"\n            onClick={() => {\n              scanToolchains();\n            }}\n          >\n            Scan Again\n          </Button>\n        }\n        {\n          <Button\n            variant=\"soft\"\n            onClick={locateToolchain}\n            disabled={!isWindowsReady}\n          >\n            Locate Existing Toolchain\n          </Button>\n        }\n      </div>\n    </div>\n  );\n};\n\nexport function isCompatable(toolchain: Toolchain | null): boolean {\n  if (!toolchain) return false;\n  return toolchain.version.startsWith(SWIFT_VERSION_PREFIX);\n}\n\nfunction stringifyToolchain(toolchain: Toolchain | null): string | null {\n  if (!toolchain) return null;\n  return `${toolchain.path}:${toolchain.version}:${toolchain.isSwiftly}`;\n}\n"
  },
  {
    "path": "src/components/TabLike.tsx",
    "content": "import { styled } from \"@mui/joy/styles\";\nimport { forwardRef, ButtonHTMLAttributes } from \"react\";\n\ninterface TabLikeProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n  selected?: boolean;\n  dragging?: boolean;\n}\n\nconst TabLikeRoot = styled(\"button\")<TabLikeProps>(\n  ({ theme, selected, disabled, dragging }) => ({\n    display: \"inline-flex\",\n    alignItems: \"center\",\n    justifyContent: \"center\",\n    gap: \"0.25rem\",\n    position: \"relative\",\n    boxSizing: \"border-box\",\n    cursor: disabled ? \"not-allowed\" : \"pointer\",\n    fontSize: \"14px\",\n    minHeight: \"24px !important\",\n    border: 0,\n    outline: 0,\n    background: \"none\",\n    textDecoration: \"none\",\n    ...theme.typography[\"title-sm\"],\n    fontWeight: selected ? theme.vars.fontWeight.md : theme.vars.fontWeight.sm,\n    padding: \"4px 8px\",\n    ...theme.variants.plain.neutral,\n    \"&:hover\": !disabled ? theme.variants.plainHover.neutral : undefined,\n    \"&:active\": !disabled ? theme.variants.plainActive.neutral : undefined,\n    ...(selected && theme.variants.plainActive.neutral),\n    ...(disabled && theme.variants.plainDisabled?.neutral),\n    \"&:focus-visible\": {\n      outline: `2px solid ${theme.vars.palette.focusVisible}`,\n      outlineOffset: 2,\n    },\n    ...(dragging && {\n      opacity: 0.6,\n    }),\n    transition: \"background-color 120ms, color 120ms\",\n  })\n);\n\nexport const TabLike = forwardRef<HTMLButtonElement, TabLikeProps>(\n  ({ selected, dragging, ...rest }, ref) => {\n    return (\n      <TabLikeRoot\n        ref={ref}\n        selected={selected}\n        dragging={dragging}\n        {...rest}\n      />\n    );\n  }\n);\n"
  },
  {
    "path": "src/components/Tiles/BottomBar.css",
    "content": ".bottom-container {\n  height: 100%;\n  overflow: auto;\n  scrollbar-width: thin;\n  scrollbar-color: #888 #000;\n  box-sizing: border-box;\n}\n"
  },
  {
    "path": "src/components/Tiles/BottomBar.tsx",
    "content": "import { useEffect, useRef, useState } from \"react\";\nimport \"./BottomBar.css\";\nimport { Button, Input, Tab, TabList, TabPanel, Tabs } from \"@mui/joy\";\nimport CommandButton from \"../CommandButton\";\nimport { Terminal, StopCircle } from \"@mui/icons-material\";\nimport { useIDE } from \"../../utilities/IDEContext\";\nimport { useToast } from \"react-toast-plus\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport CommandConsole from \"./CommandConsole\";\nimport Console from \"./Console\";\nimport FilteredConsole, { FilteredConsoleHandle } from \"./FilteredConsole\";\nimport { useParams } from \"react-router\";\nimport { useStore } from \"../../utilities/StoreContext\";\n\nconst staticTabs = [\n  {\n    name: \"Build Output\",\n    component: <CommandConsole />,\n  },\n  {\n    name: \"SourceKit-LSP\",\n    component: (\n      <Console key=\"lsp-message\" channel=\"lsp-message\" jsonPrettyPrint />\n    ),\n  },\n];\n\nexport default function BottomBar() {\n  const [focused, setFocused] = useState<number>();\n  const [refreshSyslog, setRefreshSyslog] = useState<number>(0);\n  const [runningSyslog, setRunningSyslog] = useState<boolean>(false);\n  const [runningStdout, setRunningStdout] = useState<boolean>(false);\n  const [refreshStdout, setRefreshStdout] = useState<number>(0);\n  const [syslogFilter, setSyslogFilter] = useState<string>(\"\");\n  const [stdoutFilter, setStdoutFilter] = useState<string>(\"\");\n\n  const syslogRef = useRef<FilteredConsoleHandle>(null);\n  const stdoutRef = useRef<FilteredConsoleHandle>(null);\n\n  useEffect(() => {\n    const checkSyslog = async () => {\n      const isStreaming = await invoke<boolean>(\"is_streaming_syslog\");\n      setRunningSyslog(isStreaming);\n    };\n    checkSyslog();\n  }, [focused, refreshSyslog]);\n\n  useEffect(() => {\n    const checkStdout = async () => {\n      const isStreaming = await invoke<boolean>(\"is_streaming_stdout\");\n      setRunningStdout(isStreaming);\n    };\n    checkStdout();\n  }, [focused, refreshStdout]);\n\n  useEffect(() => {\n    if (focused === undefined && staticTabs.length > 0) {\n      setFocused(0);\n    }\n  }, [focused]);\n\n  return (\n    <div className=\"bottom-container\">\n      <Tabs\n        sx={{\n          height: \"calc(100% - var(--padding-sm))\",\n          overflow: \"hidden\",\n          paddingBottom: \"var(--padding-sm)\",\n        }}\n        value={focused ?? 0}\n        onChange={(_, newValue) => {\n          if (newValue === null) return;\n          setFocused(newValue as number);\n        }}\n      >\n        <TabList\n          size=\"sm\"\n          sx={{\n            minHeight: 33,\n\n            overflowX: \"auto\",\n            \"& .MuiTab-root\": {\n              fontSize: 12,\n              minHeight: 24,\n              padding: \"2px 8px\",\n              flexShrink: 0,\n            },\n          }}\n        >\n          {staticTabs.map((tab, index) => (\n            <Tab key={tab.name} value={index} indicatorPlacement=\"bottom\">\n              {tab.name}\n            </Tab>\n          ))}\n          <Tab value={staticTabs.length} indicatorPlacement=\"bottom\">\n            Syslog\n          </Tab>\n          <Tab value={staticTabs.length + 1} indicatorPlacement=\"bottom\">\n            App Console\n          </Tab>\n          {focused === staticTabs.length && (\n            <BottomBarFilter\n              filter={syslogFilter}\n              setFilter={setSyslogFilter}\n              setRefresh={setRefreshSyslog}\n              displayName=\"Syslog\"\n              errorMessage=\"Please select a device to stream the syslog from.\"\n              startCommand=\"start_stream_syslog\"\n              stopCommand=\"stop_stream_syslog\"\n              customTooltip=\"will cause performance issues\"\n              running={runningSyslog}\n              clear={() => {\n                syslogRef.current?.clear();\n              }}\n            />\n          )}\n          {focused === staticTabs.length + 1 && (\n            <BottomBarFilter\n              filter={stdoutFilter}\n              setFilter={setStdoutFilter}\n              setRefresh={setRefreshStdout}\n              displayName=\"App Console\"\n              errorMessage=\"Please select a device to stream app console from.\"\n              startCommand=\"start_stream_stdout\"\n              stopCommand=\"stop_stream_stdout\"\n              customTooltip=\"will launch app automatically\"\n              requiresDDI={true}\n              running={runningStdout}\n              clear={() => {\n                stdoutRef.current?.clear();\n              }}\n            />\n          )}\n        </TabList>\n        {staticTabs.map((tab, index) => (\n          <TabPanel\n            value={index}\n            key={tab.name}\n            sx={{ padding: 0 }}\n            keepMounted\n          >\n            {tab.component}\n          </TabPanel>\n        ))}\n\n        <TabPanel value={staticTabs.length} sx={{ padding: 0 }} keepMounted>\n          <FilteredConsole\n            filter={syslogFilter}\n            channel={\"syslog-message\"}\n            ref={syslogRef}\n            doneSignal=\"syslog.done\"\n            alertDone={() => {\n              setRefreshSyslog((prev) => prev + 1);\n            }}\n          />\n          ,\n        </TabPanel>\n        <TabPanel value={staticTabs.length + 1} sx={{ padding: 0 }} keepMounted>\n          <FilteredConsole\n            filter={stdoutFilter}\n            channel={\"stdout-message\"}\n            doneSignal=\"stdout.done\"\n            alertDone={() => {\n              setRefreshStdout((prev) => prev + 1);\n            }}\n            ref={stdoutRef}\n          />\n          ,\n        </TabPanel>\n      </Tabs>\n    </div>\n  );\n}\n\nfunction BottomBarFilter({\n  filter,\n  setFilter,\n  setRefresh,\n  clear,\n  displayName,\n  errorMessage,\n  startCommand,\n  stopCommand,\n  running,\n  customTooltip,\n  requiresDDI = false,\n}: {\n  filter: string;\n  setFilter: React.Dispatch<React.SetStateAction<string>>;\n  setRefresh: React.Dispatch<React.SetStateAction<number>>;\n  clear: () => void;\n  displayName: string;\n  errorMessage: string;\n  startCommand: string;\n  stopCommand: string;\n  running: boolean;\n  customTooltip: string;\n  requiresDDI?: boolean;\n}) {\n  const { selectedDevice, mountDdi } = useIDE();\n  const { addToast } = useToast();\n  const { path } = useParams<\"path\">();\n  const [anisetteServer] = useStore<string>(\n    \"apple-id/anisette-server\",\n    \"ani.sidestore.io\"\n  );\n\n  return (\n    <>\n      <Button\n        variant=\"plain\"\n        sx={{\n          marginLeft: \"auto\",\n          marginRight: \"var(--padding-xs)\",\n          fontSize: \"12px\",\n        }}\n        size=\"sm\"\n        onClick={clear}\n      >\n        Clear\n      </Button>\n      {!running && (\n        <CommandButton\n          disabled={!selectedDevice}\n          tooltip={`Start ${displayName} (${customTooltip})`}\n          variant=\"plain\"\n          command={startCommand}\n          icon={<Terminal />}\n          parameters={{\n            device: selectedDevice,\n            folder: path ?? \"\",\n            anisetteServer: anisetteServer,\n          }}\n          validate={() => {\n            if (!selectedDevice) {\n              addToast.error(errorMessage);\n              return false;\n            }\n            return true;\n          }}\n          validateAsync={requiresDDI ? () => mountDdi(true) : undefined}\n          after={() => {\n            setRefresh((prev) => prev + 1);\n          }}\n          label={`Start ${displayName}`}\n          sx={{\n            marginRight: \"var(--padding-xs)\",\n            fontSize: \"12px\",\n            flexShrink: 0,\n          }}\n          size=\"sm\"\n        />\n      )}\n      {running && (\n        <Input\n          placeholder={`Filter ${displayName}...`}\n          value={filter}\n          onChange={(e) => {\n            setFilter(e.target.value);\n          }}\n          sx={{\n            width: \"200px\",\n            minWidth: \"150px\",\n            marginRight: \"var(--padding-xs)\",\n            fontSize: \"12px\",\n          }}\n          size=\"sm\"\n        />\n      )}\n      {running && (\n        <CommandButton\n          tooltip={`Stop ${displayName}`}\n          variant=\"plain\"\n          command={stopCommand}\n          icon={<StopCircle />}\n          sx={{\n            marginRight: \"var(--padding-xs)\",\n            fontSize: \"12px\",\n            flexShrink: 0,\n          }}\n          after={() => {\n            setRefresh((prev) => prev + 1);\n          }}\n          label={`Stop ${displayName}`}\n          size=\"sm\"\n        />\n      )}\n    </>\n  );\n}\n"
  },
  {
    "path": "src/components/Tiles/CommandConsole.tsx",
    "content": "import { useEffect, useRef } from \"react\";\nimport \"./Console.css\";\nimport { listen } from \"@tauri-apps/api/event\";\nimport Convert from \"ansi-to-html\";\nimport { Virtuoso } from \"react-virtuoso\";\nimport { useIDE } from \"../../utilities/IDEContext\";\nimport { escapeHtml } from \"./Console\";\nimport { useParams } from \"react-router\";\n\nconst convert = new Convert();\n\nexport default function CommandConsole() {\n  const { consoleLines, setConsoleLines } = useIDE();\n  const listenerAdded = useRef(false);\n  const unlisten = useRef<() => void>(() => {});\n\n  const { path } = useParams<\"path\">();\n\n  useEffect(() => {\n    setConsoleLines([]);\n  }, [path]);\n\n  useEffect(() => {\n    if (!listenerAdded.current) {\n      (async () => {\n        const unlistenFn = await listen(\"build-output\", (event) => {\n          let line = event.payload as string;\n          if (line.includes(\"command.done\")) {\n            if (line.split(\".\")[2] === \"999\") {\n              setConsoleLines((lines) => [...lines, \"Command failed\"]);\n            } else {\n              setConsoleLines((lines) => [\n                ...lines,\n                \"Command finished with exit code: \" + line.split(\".\")[2],\n              ]);\n            }\n          } else {\n            setConsoleLines((lines) => [...lines, line]);\n          }\n        });\n        unlisten.current = unlistenFn;\n      })();\n      listenerAdded.current = true;\n    }\n    return () => {\n      unlisten.current();\n    };\n  }, []);\n\n  return (\n    <div className=\"console-container\">\n      <Virtuoso\n        className=\"console-tile\"\n        atBottomThreshold={20}\n        followOutput={\"auto\"}\n        data={consoleLines}\n        itemContent={(_, line) => (\n          <pre\n            style={{ margin: 0, width: \"fit-content\", padding: 0 }}\n            dangerouslySetInnerHTML={{\n              __html: convert.toHtml(escapeHtml(line)),\n            }}\n          />\n        )}\n      />\n    </div>\n  );\n}\n"
  },
  {
    "path": "src/components/Tiles/Console.css",
    "content": ".console-tile {\n  background-color: var(--joy-background-popup);\n  font-size: smaller;\n  height: 100%;\n  min-width: 100%;\n}\n\n.console-container {\n  height: 100%;\n  padding: 0 var(--padding-md);\n  background-color: var(--joy-background-popup);\n  overflow: auto;\n  scrollbar-width: thin;\n  scrollbar-color: #888 #000;\n  box-sizing: border-box;\n}\n"
  },
  {
    "path": "src/components/Tiles/Console.tsx",
    "content": "import { useEffect, useRef, useState } from \"react\";\nimport \"./Console.css\";\nimport { listen } from \"@tauri-apps/api/event\";\nimport Convert from \"ansi-to-html\";\nimport { Virtuoso } from \"react-virtuoso\";\nimport { useParams } from \"react-router\";\n\nconst convert = new Convert();\n\nexport function escapeHtml(unsafe: string) {\n  return unsafe\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&#039;\");\n}\n\nexport default function Console({\n  channel,\n  jsonPrettyPrint,\n}: {\n  channel: string;\n  jsonPrettyPrint?: boolean;\n}) {\n  const [consoleLines, setConsoleLines] = useState<string[]>([]);\n  const listenerAdded = useRef(false);\n  const unlisten = useRef<() => void>(() => {});\n  const { path } = useParams<\"path\">();\n\n  useEffect(() => {\n    setConsoleLines([]);\n  }, [path]);\n\n  useEffect(() => {\n    if (!listenerAdded.current) {\n      (async () => {\n        const unlistenFn = await listen(channel, (event) => {\n          let line = event.payload as string;\n          if (jsonPrettyPrint) {\n            try {\n              let parsed = JSON.parse(line);\n              line = JSON.stringify(parsed, null, 2);\n            } catch (error) {\n              console.error(\n                \"Failed to parse JSON where prettyPrint was enabled:\",\n                error\n              );\n            }\n          }\n          setConsoleLines((lines) => [...lines, line]);\n        });\n        unlisten.current = unlistenFn;\n      })();\n      listenerAdded.current = true;\n    }\n    return () => {\n      unlisten.current();\n    };\n  }, []);\n\n  return (\n    <div className=\"console-container\">\n      <Virtuoso\n        className=\"console-tile\"\n        atBottomThreshold={40}\n        followOutput={\"auto\"}\n        data={consoleLines}\n        itemContent={(_, line) => (\n          <pre\n            style={{ margin: 0, width: \"fit-content\", padding: 0 }}\n            dangerouslySetInnerHTML={{\n              __html: convert.toHtml(escapeHtml(line)),\n            }}\n          />\n        )}\n      />\n    </div>\n  );\n}\n"
  },
  {
    "path": "src/components/Tiles/Editor.css",
    "content": ".editor {\n  height: 100%;\n  position: relative;\n  overflow: hidden;\n}\n.code-editor {\n  width: 100%;\n  height: 100%;\n  max-height: 100%;\n  overflow: hidden;\n  position: relative;\n  /* transform: translate(0, -100%); */\n}\n\n.tabsContainer {\n  display: flex;\n  padding-bottom: 1px;\n  position: relative;\n  width: 100%;\n  overflow-x: hidden;\n}\n\n.tab-wrapper {\n  display: flex;\n  align-items: center;\n  position: relative;\n  flex-shrink: 0;\n}\n\n.tabsContainer .Mui-selected::after {\n  content: \"\";\n  display: block;\n  height: 2px;\n  background: currentColor;\n  position: absolute;\n  bottom: -1px;\n  z-index: 999;\n  left: 0;\n  right: 0;\n}\n\n.drop-indicator {\n  width: 2px;\n  height: 100%;\n  background: var(--joy-palette-neutral-300);\n  position: absolute;\n  z-index: 1000;\n  left: 0;\n}\n\n.drop-indicator-end {\n  position: relative;\n  left: auto;\n  margin-left: 0;\n  height: 32px;\n  align-self: stretch;\n}\n"
  },
  {
    "path": "src/components/Tiles/Editor.tsx",
    "content": "import { path } from \"@tauri-apps/api\";\nimport \"./Editor.css\";\nimport { IconButton, useColorScheme } from \"@mui/joy\";\nimport { Dispatch, SetStateAction, useEffect, useRef, useState } from \"react\";\nimport CloseIcon from \"@mui/icons-material/Close\";\nimport CircleIcon from \"@mui/icons-material/Circle\";\nimport * as monaco from \"monaco-editor\";\nimport { initialize, ITextEditorOptions } from \"@codingame/monaco-vscode-api\";\nimport getLanguagesServiceOverride from \"@codingame/monaco-vscode-languages-service-override\";\nimport getThemeServiceOverride from \"@codingame/monaco-vscode-theme-service-override\";\nimport getTextMateServiceOverride from \"@codingame/monaco-vscode-textmate-service-override\";\nimport getEditorServiceOverride from \"@codingame/monaco-vscode-editor-service-override\";\nimport getModelServiceOverride from \"@codingame/monaco-vscode-model-service-override\";\nimport \"@codingame/monaco-vscode-swift-default-extension\";\nimport \"@codingame/monaco-vscode-theme-defaults-default-extension\";\nimport { platform } from \"@tauri-apps/plugin-os\";\nimport { TabLike } from \"../TabLike\";\nimport { useStore } from \"../../utilities/StoreContext\";\nimport { useParams } from \"react-router\";\nimport { readTextFile, writeTextFile } from \"@tauri-apps/plugin-fs\";\n\nexport type WorkerLoader = () => Worker;\nconst workerLoaders: Partial<Record<string, WorkerLoader>> = {\n  TextEditorWorker: () =>\n    new Worker(\n      new URL(\"monaco-editor/esm/vs/editor/editor.worker.js\", import.meta.url),\n      { type: \"module\" }\n    ),\n  TextMateWorker: () =>\n    new Worker(\n      new URL(\n        \"@codingame/monaco-vscode-textmate-service-override/worker\",\n        import.meta.url\n      ),\n      { type: \"module\" }\n    ),\n};\n\nwindow.MonacoEnvironment = {\n  getWorker: function (_workerId, label) {\n    const workerFactory = workerLoaders[label];\n    if (workerFactory != null) {\n      return workerFactory();\n    }\n    throw new Error(`Worker ${label} not found`);\n  },\n};\n\nexport interface EditorProps {\n  openFiles: string[];\n  setOpenFiles: Dispatch<SetStateAction<string[]>>;\n  focusedFile: string | null;\n  setSaveFile: Dispatch<SetStateAction<(() => Promise<void>) | null>>;\n  setUndo: Dispatch<SetStateAction<(() => void) | null>>;\n  setRedo: Dispatch<SetStateAction<(() => void) | null>>;\n  openNewFile: (file: string) => void;\n  setEditorUpper: Dispatch<\n    SetStateAction<monaco.editor.IStandaloneCodeEditor | null>\n  >;\n}\n\nlet globalInitialized = false;\nlet globalEditorServiceCallbacks = {\n  currentTabsRef: { current: [] as { name: string; file: string }[] },\n  setFocusedRef: { current: (() => {}) as any },\n  openNewFileRef: { current: (() => {}) as any },\n  editorRef: { current: null as monaco.editor.IStandaloneCodeEditor | null },\n  selectionOverrideRef: { current: null as ITextEditorOptions | null },\n};\n\nexport default ({\n  openFiles,\n  focusedFile,\n  setSaveFile,\n  setUndo,\n  setRedo,\n  setOpenFiles,\n  openNewFile,\n  setEditorUpper,\n}: EditorProps) => {\n  const [tabs, setTabs] = useState<\n    {\n      name: string;\n      file: string;\n    }[]\n  >([]);\n  const [unsavedFiles, setUnsavedFiles] = useState<string[]>([]);\n  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);\n  const [dropIndicatorIndex, setDropIndicatorIndex] = useState<number | null>(\n    null\n  );\n\n  const [focused, setFocused] = useState<number>();\n  const [editor, setEditor] =\n    useState<monaco.editor.IStandaloneCodeEditor | null>(null);\n\n  const { mode } = useColorScheme();\n\n  const monacoEl = useRef(null);\n  const [initialized, setInitialized] = useState(false);\n  const currentTabsRef = useRef(tabs);\n  const setFocusedRef = useRef(setFocused);\n  const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);\n  const openNewFileRef = useRef(openNewFile);\n  const selectionOverrideRef = useRef<ITextEditorOptions | null>(null);\n  const hasInitializedRef = useRef(false);\n  const scrollStates = useRef<{\n    [key: string]: [number, number];\n  }>({});\n  const [hoveredOnBtn, setHoveredOnBtn] = useState<number | null>(null);\n  const [formatOnSave] = useStore<boolean>(\"sourcekit/format\", true);\n\n  const { path: filePath } = useParams<\"path\">();\n  const hasAttemptedToReadOpenFiles = useRef<string | null>(null);\n\n  useEffect(() => {\n    (async () => {\n      if (!filePath || hasAttemptedToReadOpenFiles.current === filePath) return;\n      const savePath = await path.join(\n        filePath,\n        \".crosscode\",\n        \"openFiles.json\"\n      );\n      try {\n        let text = await readTextFile(savePath);\n        if (!text) return;\n        let data = JSON.parse(text) as { files: string[]; focused: number };\n        if (\n          !data ||\n          typeof data !== \"object\" ||\n          !Array.isArray(data.files) ||\n          typeof data.focused !== \"number\"\n        )\n          return;\n        data.files = data.files.filter((file) => typeof file === \"string\");\n        if (data.files.length === 0) return;\n        if (data.focused < 0 || data.focused >= data.files.length) {\n          data.focused = 0;\n        }\n        setOpenFiles(data.files);\n        setTimeout(() => {\n          setFocused(data.focused);\n        }, 100);\n      } catch (e) {\n        void e;\n      } finally {\n        hasAttemptedToReadOpenFiles.current = filePath;\n      }\n    })();\n  }, [filePath, setOpenFiles, setFocused]);\n\n  useEffect(() => {\n    (async () => {\n      if (!filePath || hasAttemptedToReadOpenFiles.current !== filePath) return;\n      const savePath = await path.join(\n        filePath,\n        \".crosscode\",\n        \"openFiles.json\"\n      );\n      let data = {\n        files: openFiles,\n        focused: focused ?? 0,\n      };\n      writeTextFile(savePath, JSON.stringify(data)).catch((err) => {\n        console.error(\"Error writing openFiles.json:\", err);\n      });\n    })();\n  }, [openFiles, filePath, focused]);\n\n  useEffect(() => {\n    globalEditorServiceCallbacks.currentTabsRef = currentTabsRef;\n    globalEditorServiceCallbacks.setFocusedRef = setFocusedRef;\n    globalEditorServiceCallbacks.editorRef = editorRef;\n    globalEditorServiceCallbacks.openNewFileRef = openNewFileRef;\n    globalEditorServiceCallbacks.selectionOverrideRef = selectionOverrideRef;\n  });\n\n  useEffect(() => {\n    editorRef.current = editor;\n    setEditorUpper(editor);\n  }, [editor]);\n\n  useEffect(() => {\n    currentTabsRef.current = tabs;\n  }, [tabs]);\n\n  useEffect(() => {\n    setFocusedRef.current = setFocused;\n  }, [setFocused]);\n\n  useEffect(() => {\n    openNewFileRef.current = openNewFile;\n  }, [openNewFile]);\n\n  useEffect(() => {\n    const initializeEditor = async () => {\n      if (globalInitialized && !hasInitializedRef.current) {\n        setInitialized(true);\n        hasInitializedRef.current = true;\n        return;\n      }\n\n      globalInitialized = true;\n      await initialize({\n        ...getTextMateServiceOverride(),\n        ...getThemeServiceOverride(),\n        ...getLanguagesServiceOverride(),\n        ...getEditorServiceOverride((modelRef, options) => {\n          return new Promise((resolve) => {\n            if (!globalEditorServiceCallbacks.editorRef.current)\n              return resolve(undefined);\n\n            let path =\n              platform() === \"windows\"\n                ? modelRef.object.textEditorModel.uri.path\n                : modelRef.object.textEditorModel.uri.fsPath;\n\n            if (!path) return resolve(undefined);\n            let tabIndex =\n              globalEditorServiceCallbacks.currentTabsRef.current.findIndex(\n                (tab) => tab.file === path\n              );\n            if (options !== undefined) {\n              const opts = options as ITextEditorOptions | undefined;\n              if (opts?.selection) {\n                globalEditorServiceCallbacks.selectionOverrideRef.current =\n                  opts;\n              }\n            }\n            if (tabIndex === -1) {\n              globalEditorServiceCallbacks.openNewFileRef.current(path);\n            } else {\n              globalEditorServiceCallbacks.setFocusedRef.current(tabIndex);\n            }\n\n            resolve(undefined);\n          });\n        }),\n        ...getModelServiceOverride(),\n      });\n      setInitialized(true);\n      hasInitializedRef.current = true;\n    };\n\n    initializeEditor();\n  }, []);\n\n  useEffect(() => {\n    if (focusedFile !== null) {\n      let i = openFiles.indexOf(focusedFile);\n      if (i === -1 || focused === i) return;\n      setFocused(i);\n    }\n  }, [focusedFile, openFiles]);\n\n  useEffect(() => {\n    const fetchTabNames = async () => {\n      setTabs(\n        await Promise.all(\n          openFiles.map(async (file) => ({\n            name: await path.basename(file),\n            file,\n          }))\n        )\n      );\n    };\n\n    fetchTabNames();\n  }, [openFiles]);\n\n  useEffect(() => {\n    if (!monacoEl.current || editor || !initialized) return;\n\n    const newEditor = monaco.editor.create(monacoEl.current, {\n      value: \"\",\n      language: \"plaintext\",\n      theme: mode === \"dark\" ? \"vs-dark\" : \"vs\",\n    });\n\n    setUndo(() => () => {\n      newEditor.trigger(\"keyboard\", \"undo\", null);\n    });\n\n    setRedo(() => () => {\n      newEditor.trigger(\"keyboard\", \"redo\", null);\n    });\n\n    setEditor(newEditor);\n\n    return () => {\n      newEditor.dispose();\n    };\n  }, [initialized]);\n\n  useEffect(() => {\n    if (editor === null) return;\n    let listener = editor.onDidScrollChange((e) => {\n      if (focused !== undefined) {\n        scrollStates.current[tabs[focused].file] = [e.scrollTop, e.scrollLeft];\n      }\n    });\n    return () => {\n      listener.dispose();\n    };\n  }, [editor, focused, tabs]);\n\n  useEffect(() => {\n    if (!editor || !initialized) return;\n    monaco.editor.setTheme(mode === \"dark\" ? \"vs-dark\" : \"vs\");\n  }, [mode, editor, initialized, openFiles]);\n\n  useEffect(() => {\n    if (!monacoEl.current || !editor) return;\n\n    const resizeObserver = new ResizeObserver(() => {\n      editor.layout();\n    });\n\n    resizeObserver.observe(monacoEl.current);\n\n    return () => {\n      resizeObserver.disconnect();\n    };\n  }, [editor]);\n\n  const handleDragStart = (e: React.DragEvent, index: number) => {\n    setDraggedIndex(index);\n    e.dataTransfer.effectAllowed = \"move\";\n    e.dataTransfer.setData(\"text/plain\", index.toString());\n  };\n\n  const handleDragOver = (e: React.DragEvent, index: number) => {\n    e.preventDefault();\n    e.dataTransfer.dropEffect = \"move\";\n\n    if (draggedIndex === null) return;\n\n    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();\n    const midpoint = rect.left + rect.width / 2;\n    const mouseX = e.clientX;\n\n    let insertIndex;\n    if (mouseX < midpoint) {\n      insertIndex = index;\n    } else {\n      insertIndex = index + 1;\n    }\n\n    if (insertIndex === draggedIndex || insertIndex === draggedIndex + 1) {\n      setDropIndicatorIndex(null);\n    } else {\n      setDropIndicatorIndex(insertIndex);\n    }\n  };\n\n  const handleContainerDragOver = (e: React.DragEvent) => {\n    e.preventDefault();\n    e.dataTransfer.dropEffect = \"move\";\n\n    if (draggedIndex === null) return;\n\n    const container = e.currentTarget as HTMLElement;\n    const mouseX = e.clientX;\n\n    const lastTab = container.querySelector(\".tab-wrapper:last-child\");\n    if (lastTab) {\n      const lastTabRect = lastTab.getBoundingClientRect();\n      if (mouseX > lastTabRect.right) {\n        setDropIndicatorIndex(tabs.length);\n        return;\n      }\n    }\n\n    const firstTab = container.querySelector(\".tab-wrapper:first-child\");\n    if (firstTab) {\n      const firstTabRect = firstTab.getBoundingClientRect();\n      if (mouseX < firstTabRect.left) {\n        setDropIndicatorIndex(0);\n        return;\n      }\n    }\n  };\n\n  const handleDragLeave = (e: React.DragEvent) => {\n    const container = e.currentTarget as HTMLElement;\n    const relatedTarget = e.relatedTarget as Node;\n\n    if (!container.contains(relatedTarget)) {\n      setDropIndicatorIndex(null);\n    }\n  };\n\n  const handleDrop = (e: React.DragEvent) => {\n    e.preventDefault();\n\n    if (draggedIndex === null || dropIndicatorIndex === null) {\n      setDraggedIndex(null);\n      setDropIndicatorIndex(null);\n      return;\n    }\n\n    const newTabs = [...tabs];\n    const newOpenFiles = [...openFiles];\n\n    let actualDropIndex = dropIndicatorIndex;\n    if (draggedIndex < dropIndicatorIndex) {\n      actualDropIndex = dropIndicatorIndex - 1;\n    }\n\n    const draggedTab = newTabs.splice(draggedIndex, 1)[0];\n    const draggedFile = newOpenFiles.splice(draggedIndex, 1)[0];\n\n    newTabs.splice(actualDropIndex, 0, draggedTab);\n    newOpenFiles.splice(actualDropIndex, 0, draggedFile);\n\n    let newFocused = focused;\n    if (focused === draggedIndex) {\n      newFocused = actualDropIndex;\n    } else if (focused !== undefined) {\n      if (draggedIndex < focused && actualDropIndex >= focused) {\n        newFocused = focused - 1;\n      } else if (draggedIndex > focused && actualDropIndex <= focused) {\n        newFocused = focused + 1;\n      }\n    }\n\n    setTabs(newTabs);\n    setOpenFiles(newOpenFiles);\n    setFocused(newFocused);\n    setDraggedIndex(null);\n    setDropIndicatorIndex(null);\n  };\n\n  const handleDragEnd = () => {\n    setDraggedIndex(null);\n    setDropIndicatorIndex(null);\n  };\n\n  useEffect(() => {\n    let switchFile = async () => {\n      if (!editor || focused === undefined || !tabs[focused]) return;\n      let filePath = tabs[focused]?.file;\n      let file = monaco.Uri.file(filePath);\n      let modelRef = await monaco.editor.createModelReference(file);\n      modelRef.object.onDidChangeDirty(() => {\n        setUnsavedFiles((files) => {\n          if (modelRef.object.isDirty()) {\n            return [...files, tabs[focused]?.file];\n          } else {\n            return files.filter((f) => f !== tabs[focused]?.file);\n          }\n        });\n      });\n\n      setSaveFile(() => async () => {\n        if (formatOnSave) {\n          await editor.getAction(\"editor.action.formatDocument\")?.run();\n        }\n        await modelRef.object.save();\n      });\n\n      editor.setModel(modelRef.object.textEditorModel);\n\n      if (scrollStates.current && scrollStates.current[filePath]) {\n        const [scrollTop, scrollLeft] = scrollStates.current[filePath];\n        editor.setScrollTop(scrollTop);\n        editor.setScrollLeft(scrollLeft);\n      }\n\n      // I don't love doing it like this but it seems to improve consistency over just running it directly\n      requestAnimationFrame(() => {\n        if (\n          selectionOverrideRef.current &&\n          selectionOverrideRef.current.selection\n        ) {\n          editor.setSelection(\n            {\n              startLineNumber:\n                selectionOverrideRef.current.selection.startLineNumber,\n              startColumn: selectionOverrideRef.current.selection.startColumn,\n              endLineNumber:\n                selectionOverrideRef.current.selection.endLineNumber ??\n                selectionOverrideRef.current.selection.startLineNumber,\n              endColumn:\n                selectionOverrideRef.current.selection.endColumn ??\n                selectionOverrideRef.current.selection.startColumn,\n            },\n            selectionOverrideRef.current.selectionSource\n          );\n          editor.revealLineNearTop(\n            selectionOverrideRef.current.selection.startLineNumber,\n            0\n          );\n          selectionOverrideRef.current = null;\n        }\n      });\n    };\n    switchFile();\n  }, [focused, editor, tabs, formatOnSave]);\n\n  return (\n    <div className={\"editor\"}>\n      <div\n        className=\"tabsContainer MuiTabList-sizeSm\"\n        onDragOver={handleContainerDragOver}\n        onDragLeave={handleDragLeave}\n        onDrop={handleDrop}\n        onWheel={(e) => {\n          if (e.deltaY !== 0) {\n            e.currentTarget.scrollLeft += e.deltaY;\n            e.preventDefault();\n          }\n        }}\n      >\n        {tabs.map((tab, index) => {\n          let unsaved = unsavedFiles.includes(tab.file);\n          return (\n            <div key={tab.file} className=\"tab-wrapper\">\n              {dropIndicatorIndex === index && (\n                <div className=\"drop-indicator\" />\n              )}\n              <TabLike\n                className={\n                  (focused === index ? \" Mui-selected\" : \"\") +\n                  (draggedIndex === index ? \" dragging\" : \"\")\n                }\n                role=\"tab\"\n                draggable={true}\n                onClick={() => {\n                  setFocused(index);\n                }}\n                onDragStart={(e) => handleDragStart(e, index)}\n                onDragOver={(e) => handleDragOver(e, index)}\n                onDragEnd={handleDragEnd}\n              >\n                {tab.name}\n                <IconButton\n                  component=\"span\"\n                  onMouseEnter={() => setHoveredOnBtn(index)}\n                  onMouseLeave={() => setHoveredOnBtn(null)}\n                  size=\"xs\"\n                  sx={{ margin: \"0px\", marginLeft: \"2px\" }}\n                  onClick={(event) => {\n                    event.stopPropagation();\n                    setTabs((tabs) => tabs.filter((_, i) => i !== index));\n                    setFocused((focused) => {\n                      if (focused === index) return 0;\n                      return focused;\n                    });\n                    setOpenFiles((openFiles) =>\n                      openFiles.filter((file) => file !== tab.file)\n                    );\n                  }}\n                >\n                  {!unsaved || hoveredOnBtn === index ? (\n                    <CloseIcon />\n                  ) : (\n                    <CircleIcon\n                      sx={{ width: \"10px\", height: \"10px\", padding: \"0 3px\" }}\n                    />\n                  )}\n                </IconButton>\n              </TabLike>\n            </div>\n          );\n        })}\n        {dropIndicatorIndex === tabs.length && (\n          <div className=\"drop-indicator drop-indicator-end\" />\n        )}\n      </div>\n      <div\n        className={\"code-editor\"}\n        ref={monacoEl}\n        style={tabs.length >= 1 ? {} : { display: \"none\" }}\n      />\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/components/Tiles/FileExplorer.css",
    "content": ".file-explorer {\n  overflow-y: auto;\n  height: 100%;\n}\n"
  },
  {
    "path": "src/components/Tiles/FileExplorer.tsx",
    "content": "import {\n  Accordion,\n  AccordionDetails,\n  AccordionGroup,\n  AccordionSummary,\n  Button,\n  Divider,\n  Menu,\n  MenuItem,\n  Modal,\n  ModalDialog,\n  Input,\n  Typography,\n  Box,\n} from \"@mui/joy\";\nimport \"./FileExplorer.css\";\nimport { useCallback, useEffect, useState } from \"react\";\nimport { path } from \"@tauri-apps/api\";\nimport * as fs from \"@tauri-apps/plugin-fs\";\nimport { ClickAwayListener } from \"@mui/material\";\nimport { revealItemInDir } from \"@tauri-apps/plugin-opener\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { platform } from \"@tauri-apps/plugin-os\";\nimport { useToast } from \"react-toast-plus\";\n\ninterface FileItemProps {\n  filePath: string;\n  isDirectory: boolean;\n  setOpenFile: (file: string) => void;\n  openDefault?: boolean;\n  refresh?: number;\n}\n\nconst FileItem: React.FC<FileItemProps> = ({\n  filePath,\n  isDirectory,\n  setOpenFile,\n  openDefault = false,\n  refresh = 0,\n}) => {\n  const handleOpenFile = useCallback(async () => {\n    if (platform() === \"windows\") {\n      setOpenFile(await invoke<string>(\"linux_path\", { path: filePath }));\n    } else {\n      setOpenFile(filePath);\n    }\n  }, [filePath]);\n\n  const [children, setChildren] = useState<\n    {\n      path: string;\n      isDirectory: boolean;\n    }[]\n  >([]);\n  const [name, setName] = useState(\"\");\n  const [expanded, setExpanded] = useState(openDefault);\n\n  useEffect(() => {\n    (async () => {\n      setName(await path.basename(filePath));\n      if (!isDirectory || !expanded) return;\n      try {\n        const files = await fs.readDir(filePath);\n        const parsedFilePromises = files.map(async (file) => {\n          let pathS = await path.resolve(filePath, file.name);\n          return {\n            path: pathS,\n            isDirectory: file.isDirectory,\n          };\n        });\n        setChildren(\n          (await Promise.all(parsedFilePromises)).sort((a, b) => {\n            if (a.isDirectory && !b.isDirectory) return -1;\n            if (!a.isDirectory && b.isDirectory) return 1;\n            return a.path.localeCompare(b.path);\n          })\n        );\n      } catch (error) {\n        console.error(\"Failed to read file:\", filePath, error);\n      }\n    })();\n  }, [filePath, expanded, refresh]);\n\n  const handleAccordionChange = (\n    _: React.SyntheticEvent,\n    isExpanded: boolean\n  ) => {\n    setExpanded(isExpanded);\n  };\n\n  if (isDirectory) {\n    return (\n      <Accordion onChange={handleAccordionChange} defaultExpanded={openDefault}>\n        <AccordionSummary\n          slotProps={{\n            button: {\n              \"data-path\": filePath,\n              \"data-is-folder\": true,\n            },\n          }}\n        >\n          {name}\n        </AccordionSummary>\n        <AccordionDetails>\n          <AccordionGroup\n            size=\"sm\"\n            sx={{\n              borderLeft: \"1px solid var(--joy-palette-neutral-800, #171A1C)\",\n            }}\n            disableDivider={true}\n          >\n            {children.map((child) => (\n              <FileItem\n                key={child.path}\n                filePath={child.path}\n                isDirectory={child.isDirectory}\n                setOpenFile={setOpenFile}\n                refresh={refresh}\n              />\n            ))}\n          </AccordionGroup>\n        </AccordionDetails>\n      </Accordion>\n    );\n  } else {\n    return (\n      <Button\n        data-is-folder={false}\n        size=\"sm\"\n        onClick={handleOpenFile}\n        variant=\"plain\"\n        data-path={filePath}\n        sx={{\n          justifyContent: \"flex-start\",\n          whiteSpace: \"nowrap\",\n          textOverflow: \"ellipsis\",\n          overflow: \"hidden\",\n          width: \"100%\",\n          display: \"block\",\n          textAlign: \"left\",\n          paddingLeft: \"0.5rem\",\n        }}\n      >\n        {name}\n      </Button>\n    );\n  }\n};\n\nexport interface FileExplorerProps {\n  openFolder: string;\n  setOpenFile: (file: string) => void;\n}\nexport default ({ openFolder, setOpenFile }: FileExplorerProps) => {\n  const [contextMenu, setContextMenu] = useState<{\n    mouseX: number;\n    mouseY: number;\n    filePath: string;\n    isFolder: boolean;\n  } | null>(null);\n\n  const { addToast } = useToast();\n\n  const [refresh, setRefresh] = useState(0);\n\n  const [renameOpen, setRenameOpen] = useState(false);\n  const [renameValue, setRenameValue] = useState(\"\");\n  const [renameTarget, setRenameTarget] = useState<string | null>(null);\n  const [newOpen, setNewOpen] = useState(false);\n  const [newValue, setNewValue] = useState(\"\");\n  const [newTarget, setNewTarget] = useState<string | null>(null);\n  const [newFolderOpen, setNewFolderOpen] = useState(false);\n  const [newFolderValue, setNewFolderValue] = useState(\"\");\n  const [newFolderTarget, setNewFolderTarget] = useState<string | null>(null);\n\n  const [deleteOpen, setDeleteOpen] = useState(false);\n  const [deleteTarget, setDeleteTarget] = useState<string | null>(null);\n  const [deleteBasename, setDeleteBasename] = useState(\"\");\n\n  const handleContextMenu = (event: React.MouseEvent) => {\n    if (event.target instanceof HTMLButtonElement) {\n      const path = event.target.getAttribute(\"data-path\");\n      if (path) {\n        event.preventDefault();\n\n        setContextMenu(\n          contextMenu === null\n            ? {\n                mouseX: event.clientX + 2,\n                mouseY: event.clientY - 6,\n                filePath: path,\n                isFolder:\n                  event.target.getAttribute(\"data-is-folder\") === \"true\",\n              }\n            : null\n        );\n      }\n    }\n  };\n\n  const handleClose = () => {\n    setContextMenu(null);\n  };\n\n  const handleRename = async () => {\n    if (!renameTarget) return;\n    const parent = await path.dirname(renameTarget);\n    const newPath = await path.resolve(parent, renameValue);\n    await fs.rename(renameTarget, newPath);\n    setRenameOpen(false);\n    setRenameTarget(null);\n    setRenameValue(\"\");\n    setRefresh((r) => r + 1);\n  };\n\n  const handleDelete = async () => {\n    if (!deleteTarget) return;\n    await fs.remove(deleteTarget, { recursive: true });\n    setDeleteOpen(false);\n    setDeleteTarget(null);\n    setRefresh((r) => r + 1);\n  };\n\n  const handleNewFile = async () => {\n    if (!newTarget) return;\n    const newPath = await path.resolve(newTarget, newValue);\n    if (await fs.exists(newPath)) {\n      addToast.error(\"File already exists!\");\n      return;\n    }\n    await fs.writeTextFile(newPath, \"\");\n    setNewOpen(false);\n    setNewTarget(null);\n    setNewValue(\"\");\n    setRefresh((r) => r + 1);\n  };\n\n  const handleNewFolder = async () => {\n    if (!newFolderTarget) return;\n    const newPath = await path.resolve(newFolderTarget, newFolderValue);\n    if (await fs.exists(newPath)) {\n      addToast.error(\"Folder already exists!\");\n      return;\n    }\n    await fs.mkdir(newPath);\n    setNewFolderOpen(false);\n    setNewFolderTarget(null);\n    setNewFolderValue(\"\");\n    setRefresh((r) => r + 1);\n  };\n\n  return (\n    <div className={\"file-explorer\"} onContextMenu={handleContextMenu}>\n      <FileItem\n        filePath={openFolder}\n        isDirectory={true}\n        setOpenFile={setOpenFile}\n        openDefault={true}\n        refresh={refresh}\n      />\n      <ClickAwayListener onClickAway={handleClose}>\n        <Menu\n          size=\"sm\"\n          open={contextMenu !== null}\n          onClose={handleClose}\n          anchorEl={\n            contextMenu !== null\n              ? ({\n                  getBoundingClientRect: () =>\n                    ({\n                      top: contextMenu.mouseY,\n                      left: contextMenu.mouseX,\n                      right: contextMenu.mouseX,\n                      bottom: contextMenu.mouseY,\n                      width: 0,\n                      height: 0,\n                    } as DOMRect),\n                } as any)\n              : undefined\n          }\n          placement=\"bottom-start\"\n          sx={{\n            pt: 0,\n            pb: 0,\n          }}\n        >\n          {contextMenu?.isFolder && (\n            <MenuItem\n              onClick={async () => {\n                handleClose();\n                setNewTarget(contextMenu!.filePath);\n                setNewValue(\"\");\n                setNewOpen(true);\n              }}\n            >\n              New File...\n            </MenuItem>\n          )}\n          {contextMenu?.isFolder && (\n            <MenuItem\n              onClick={async () => {\n                handleClose();\n                setNewFolderTarget(contextMenu!.filePath);\n                setNewFolderValue(\"\");\n                setNewFolderOpen(true);\n              }}\n            >\n              New Folder...\n            </MenuItem>\n          )}\n          {contextMenu?.isFolder && <Divider />}\n          <MenuItem\n            onClick={async () => {\n              handleClose();\n              await revealItemInDir(contextMenu!.filePath);\n            }}\n          >\n            Open Containing Folder\n          </MenuItem>\n          <Divider />\n          <MenuItem\n            onClick={async () => {\n              handleClose();\n              setRenameTarget(contextMenu!.filePath);\n              setRenameValue(await path.basename(contextMenu!.filePath));\n              setRenameOpen(true);\n            }}\n          >\n            Rename...\n          </MenuItem>\n          <MenuItem\n            onClick={async () => {\n              handleClose();\n              setDeleteTarget(contextMenu!.filePath);\n              setDeleteBasename(await path.basename(contextMenu!.filePath));\n              setDeleteOpen(true);\n            }}\n          >\n            Delete\n          </MenuItem>\n          <Divider />\n          <MenuItem\n            onClick={async () => {\n              handleClose();\n              setRefresh((r) => r + 1);\n            }}\n          >\n            Refresh\n          </MenuItem>\n        </Menu>\n      </ClickAwayListener>\n\n      {/* New File Modal */}\n      <Modal open={newOpen} onClose={() => setNewOpen(false)}>\n        <ModalDialog>\n          <Typography level=\"h4\" component=\"h2\" sx={{ mb: 2 }}>\n            New File\n          </Typography>\n          <Input\n            autoFocus\n            value={newValue}\n            onChange={(e) => setNewValue(e.target.value)}\n            onKeyDown={async (e) => {\n              if (e.key === \"Enter\") {\n                await handleNewFile();\n              }\n            }}\n          />\n          <Box\n            sx={{ display: \"flex\", gap: 1, justifyContent: \"flex-end\", mt: 2 }}\n          >\n            <Button onClick={() => setNewOpen(false)}>Cancel</Button>\n            <Button onClick={handleNewFile} disabled={!newValue.trim()}>\n              Create\n            </Button>\n          </Box>\n        </ModalDialog>\n      </Modal>\n\n      {/* New Folder Modal */}\n      <Modal open={newFolderOpen} onClose={() => setNewFolderOpen(false)}>\n        <ModalDialog>\n          <Typography level=\"h4\" component=\"h2\" sx={{ mb: 2 }}>\n            New Folder\n          </Typography>\n          <Input\n            autoFocus\n            value={newFolderValue}\n            onChange={(e) => setNewFolderValue(e.target.value)}\n            onKeyDown={async (e) => {\n              if (e.key === \"Enter\") {\n                await handleNewFolder();\n              }\n            }}\n          />\n          <Box\n            sx={{ display: \"flex\", gap: 1, justifyContent: \"flex-end\", mt: 2 }}\n          >\n            <Button onClick={() => setNewFolderOpen(false)}>Cancel</Button>\n            <Button onClick={handleNewFolder} disabled={!newFolderValue.trim()}>\n              Create\n            </Button>\n          </Box>\n        </ModalDialog>\n      </Modal>\n\n      {/* Rename Modal */}\n      <Modal open={renameOpen} onClose={() => setRenameOpen(false)}>\n        <ModalDialog>\n          <Typography level=\"h4\" component=\"h2\" sx={{ mb: 2 }}>\n            Rename\n          </Typography>\n          <Input\n            autoFocus\n            value={renameValue}\n            onChange={(e) => setRenameValue(e.target.value)}\n            onKeyDown={async (e) => {\n              if (e.key === \"Enter\") {\n                await handleRename();\n              }\n            }}\n          />\n          <Box\n            sx={{ display: \"flex\", gap: 1, justifyContent: \"flex-end\", mt: 2 }}\n          >\n            <Button onClick={() => setRenameOpen(false)}>Cancel</Button>\n            <Button onClick={handleRename} disabled={!renameValue.trim()}>\n              Rename\n            </Button>\n          </Box>\n        </ModalDialog>\n      </Modal>\n\n      {/* Rename Modal */}\n      <Modal open={renameOpen} onClose={() => setRenameOpen(false)}>\n        <ModalDialog>\n          <Typography level=\"h4\" component=\"h2\" sx={{ mb: 2 }}>\n            Rename\n          </Typography>\n          <Input\n            autoFocus\n            value={renameValue}\n            onChange={(e) => setRenameValue(e.target.value)}\n            onKeyDown={async (e) => {\n              if (e.key === \"Enter\") {\n                await handleRename();\n              }\n            }}\n          />\n          <Box\n            sx={{ display: \"flex\", gap: 1, justifyContent: \"flex-end\", mt: 2 }}\n          >\n            <Button onClick={() => setRenameOpen(false)}>Cancel</Button>\n            <Button onClick={handleRename} disabled={!renameValue.trim()}>\n              Rename\n            </Button>\n          </Box>\n        </ModalDialog>\n      </Modal>\n\n      {/* Delete Confirmation Modal */}\n      <Modal open={deleteOpen} onClose={() => setDeleteOpen(false)}>\n        <ModalDialog>\n          <Typography level=\"h4\" component=\"h2\" sx={{ mb: 2 }}>\n            Confirm Delete\n          </Typography>\n          <Typography sx={{ mb: 2 }}>\n            Are you sure you want to delete <b>{deleteBasename}</b>? This action\n            cannot be undone.\n          </Typography>\n          <Box\n            sx={{ display: \"flex\", gap: 1, justifyContent: \"flex-end\", mt: 2 }}\n          >\n            <Button onClick={() => setDeleteOpen(false)}>Cancel</Button>\n            <Button color=\"danger\" onClick={handleDelete}>\n              Delete\n            </Button>\n          </Box>\n        </ModalDialog>\n      </Modal>\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/components/Tiles/FilteredConsole.tsx",
    "content": "import { useEffect, useImperativeHandle, useRef, useState } from \"react\";\nimport \"./Console.css\";\nimport { listen } from \"@tauri-apps/api/event\";\nimport Convert from \"ansi-to-html\";\nimport { Virtuoso } from \"react-virtuoso\";\nimport { escapeHtml } from \"./Console\";\nimport React from \"react\";\nimport { useParams } from \"react-router\";\n\nconst convert = new Convert();\n\nexport type FilteredConsoleHandle = {\n  clear: () => void;\n};\n\ntype FilteredConsoleProps = {\n  filter: string;\n  channel: string;\n  doneSignal?: string;\n  alertDone?: () => void;\n};\n\nexport default React.forwardRef<FilteredConsoleHandle, FilteredConsoleProps>(\n  ({ filter, channel, doneSignal = \"\", alertDone }, ref) => {\n    const [consoleLines, setConsoleLines] = useState<string[]>([]);\n    const listenerAdded = useRef(false);\n    const unlisten = useRef<() => void>(() => {});\n\n    useImperativeHandle(ref, () => ({\n      clear: () => {\n        setConsoleLines([]);\n      },\n    }));\n\n    const { path } = useParams<\"path\">();\n\n    useEffect(() => {\n      setConsoleLines([]);\n    }, [path]);\n\n    useEffect(() => {\n      if (!listenerAdded.current) {\n        (async () => {\n          const unlistenFn = await listen(channel, (event) => {\n            let line = event.payload as string;\n            if (doneSignal !== \"\" && line === doneSignal) return alertDone?.();\n            setConsoleLines((lines) => [...lines, line]);\n          });\n          unlisten.current = unlistenFn;\n        })();\n        listenerAdded.current = true;\n      }\n      return () => {\n        unlisten.current();\n      };\n    }, []);\n\n    return (\n      <div className=\"console-container\">\n        <Virtuoso\n          className=\"console-tile\"\n          atBottomThreshold={50}\n          followOutput={\"auto\"}\n          data={consoleLines.filter((line) => {\n            if (!filter || filter === \"\") return true;\n            return line.toLowerCase().includes(filter.toLowerCase());\n          })}\n          itemContent={(_, line) => (\n            <pre\n              style={{ margin: 0, width: \"fit-content\", padding: 0 }}\n              dangerouslySetInnerHTML={{\n                __html: convert.toHtml(escapeHtml(line)),\n              }}\n            />\n          )}\n        />\n      </div>\n    );\n  }\n);\n"
  },
  {
    "path": "src/components/Tiles/Tile.css",
    "content": ".tile {\n  width: 100%;\n  height: 100%;\n  padding: var(--padding-xs);\n}\n.tile-content {\n  height: 100%;\n}\n.tile-title {\n  color: gray;\n}\n"
  },
  {
    "path": "src/components/Tiles/Tile.tsx",
    "content": "import { Typography } from \"@mui/joy\";\nimport \"./Tile.css\";\n\nexport interface TileProps {\n  title?: string;\n  children: React.ReactNode;\n  className?: string;\n}\n\nexport default ({ title, children, className }: TileProps) => {\n  return (\n    <div className={\"tile\"}>\n      {title != null && (\n        <Typography level=\"body-xs\" className={\"tile-title\"}>\n          {title}\n        </Typography>\n      )}\n      <div className={\"tile-content\" + (className ? \" \" + className : \"\")}>\n        {children}\n      </div>\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/main.tsx",
    "content": "import React from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport App from \"./App\";\nimport \"./styles.css\";\n\nReactDOM.createRoot(document.getElementById(\"root\") as HTMLElement).render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>\n);\n"
  },
  {
    "path": "src/pages/About.tsx",
    "content": "import logo from \"../assets/logo.png\";\nimport { Link, List, ListItem, Typography } from \"@mui/joy\";\nimport \"./Onboarding.css\";\nimport { useEffect, useState } from \"react\";\nimport { getVersion } from \"@tauri-apps/api/app\";\nimport { openUrl } from \"@tauri-apps/plugin-opener\";\n\nexport default () => {\n  const [version, setVersion] = useState<string>(\"\");\n\n  useEffect(() => {\n    const fetchVersion = async () => {\n      const version = await getVersion();\n      setVersion(version);\n    };\n    fetchVersion();\n  }, []);\n\n  return (\n    <div className=\"onboarding\">\n      {version && (\n        <>\n          <div className=\"onboarding-header\">\n            <img src={logo} alt=\"CrossCode Logo\" className=\"onboarding-logo\" />\n            <div>\n              <Typography level=\"h1\">CrossCode</Typography>\n              <Typography level=\"body-md\">\n                Version {version}{\" \"}\n                <span style={{ opacity: 0.7 }}>(Early Access)</span>\n              </Typography>\n            </div>\n          </div>\n          <List marker=\"disc\">\n            <ListItem>\n              <Typography level=\"body-md\">MIT License</Typography>\n            </ListItem>\n            <ListItem>\n              <Typography level=\"body-md\">\n                GNU cpio 2.14 is included under GPLv3, with its copyright\n                holders.{\" \"}\n                <Link\n                  href=\"#\"\n                  onClick={(e) => {\n                    e.preventDefault();\n                    openUrl(\"https://ftp.gnu.org/gnu/cpio/cpio-2.14.tar.gz\");\n                  }}\n                >\n                  Source\n                </Link>\n              </Typography>\n            </ListItem>\n          </List>\n        </>\n      )}\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/pages/IDE.css",
    "content": ".ide-container {\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n}\n\n.file-explorer-tile {\n  padding-right: 0.5rem;\n}\n\n.screenshot-tile {\n  padding: 0;\n  margin: var(--padding-md);\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n  align-items: center;\n  box-sizing: border-box;\n  width: calc(100% - var(--padding-md) * 2 - var(--padding-xs));\n}\n\n.screenshot-tile > div {\n  flex-shrink: 0;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  gap: var(--padding-lg);\n}\n\n.screenshot-img-container {\n  flex: 1 1 0;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  min-height: 0;\n  min-width: 0;\n}\n\n.screenshot-img-container > img {\n  transform: translateY(calc(-1 * var(--padding-xs)));\n  max-width: 100%;\n  max-height: calc(100% - var(--padding-md) * 4);\n  object-fit: contain;\n  display: block;\n}\n"
  },
  {
    "path": "src/pages/IDE.tsx",
    "content": "import Splitter, { GutterTheme, SplitDirection } from \"@devbookhq/splitter\";\nimport Tile from \"../components/Tiles/Tile\";\nimport FileExplorer from \"../components/Tiles/FileExplorer\";\nimport { useCallback, useContext, useEffect, useState } from \"react\";\nimport Editor from \"../components/Tiles/Editor\";\nimport MenuBar from \"../components/Menu/MenuBar\";\nimport \"./IDE.css\";\nimport { StoreContext, useStore } from \"../utilities/StoreContext\";\nimport { useNavigate, useParams } from \"react-router\";\nimport { useIDE } from \"../utilities/IDEContext\";\nimport { registerFileSystemOverlay } from \"@codingame/monaco-vscode-files-service-override\";\nimport TauriFileSystemProvider from \"../utilities/TauriFileSystemProvider\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport {\n  Button,\n  Divider,\n  Modal,\n  ModalClose,\n  ModalDialog,\n  Typography,\n} from \"@mui/joy\";\nimport { ErrorIcon, useToast, WarningIcon } from \"react-toast-plus\";\nimport SwiftMenu from \"../components/SwiftMenu\";\nimport { restartServer } from \"../utilities/lsp-client\";\nimport BottomBar from \"../components/Tiles/BottomBar\";\nimport { open as openFileDialog, save } from \"@tauri-apps/plugin-dialog\";\nimport { IStandaloneCodeEditor } from \"@codingame/monaco-vscode-api/vscode/vs/editor/standalone/browser/standaloneCodeEditor\";\nimport { DARWIN_SDK_VERSION } from \"../utilities/constants\";\nimport { writeFile } from \"@tauri-apps/plugin-fs\";\n\nexport interface IDEProps {}\n\ntype ProjectValidation =\n  | \"Valid\"\n  | \"Invalid\"\n  | \"UnsupportedFormatVersion\"\n  | \"InvalidPackage\"\n  | \"InvalidToolchain\";\n\nlet autoStartedLsp = \"\";\n\nexport default () => {\n  const { storeInitialized, store } = useContext(StoreContext);\n  const [openFile, setOpenFile] = useState<string | null>(null);\n  const [openFiles, setOpenFiles] = useState<string[]>([]);\n  const [saveFile, setSaveFile] = useState<(() => Promise<void>) | null>(null);\n  const [undo, setUndo] = useState<(() => void) | null>(null);\n  const [redo, setRedo] = useState<(() => void) | null>(null);\n  const [theme] = useStore<\"light\" | \"dark\">(\"appearance/theme\", \"dark\");\n  const { path } = useParams<\"path\">();\n  const {\n    openFolderDialog,\n    selectedToolchain,\n    hasLimitedRam,\n    initialized,\n    ready,\n    darwinSDKVersion,\n    screenshot,\n    setScreenshot,\n  } = useIDE();\n  const [sourcekitStartup, setSourcekitStartup] = useStore<boolean | null>(\n    \"sourcekit/startup\",\n    null\n  );\n  const [hasIgnoredRam, setHasIgnoredRam] = useStore<boolean>(\n    \"has-ignored-ram\",\n    false\n  );\n\n  const [hasIgnoredDarwinSDK, setHasIgnoredDarwinSDK] = useStore<boolean>(\n    \"has-ignored-darwin-sdk\",\n    false\n  );\n\n  if (!path) {\n    throw new Error(\"Path parameter is required in IDE component\");\n  }\n\n  const [callbacks, setCallbacks] = useState<\n    Record<string, (() => void) | (() => Promise<void>)>\n  >({});\n  const navigate = useNavigate();\n  const [projectValidation, setProjectValidation] =\n    useState<ProjectValidation | null>(null);\n  const [editor, setEditor] = useState<IStandaloneCodeEditor | null>(null);\n  const { addToast } = useToast();\n\n  useEffect(() => {\n    if (ready === false && initialized) {\n      console.log(\n        \"IDE not ready, returning to welcome page\",\n        ready,\n        initialized\n      );\n      navigate(\"/\");\n    }\n  }, [ready, initialized, navigate]);\n\n  useEffect(() => {\n    (async () => {\n      if (!store || !storeInitialized || !path) return;\n      await store.set(\"last-opened-project\", encodeURIComponent(path!));\n    })();\n  }, [path, store, storeInitialized]);\n\n  useEffect(() => {\n    if (\n      path === undefined ||\n      path === null ||\n      selectedToolchain === null ||\n      !initialized\n    )\n      return;\n    setProjectValidation(null);\n    (async () => {\n      if (path) {\n        const toolchainPath = selectedToolchain?.path ?? \"\";\n        const validation = await invoke<ProjectValidation>(\"validate_project\", {\n          projectPath: path,\n          toolchainPath: toolchainPath,\n        });\n        if (validation) {\n          setProjectValidation(validation);\n        }\n      }\n    })();\n  }, [path, selectedToolchain, initialized]);\n\n  useEffect(() => {\n    if (openFiles.length === 0) {\n      setOpenFile(null);\n    }\n    if (!openFiles.includes(openFile!)) {\n      setOpenFile(openFiles[0]);\n    }\n  }, [openFiles]);\n\n  useEffect(() => {\n    let dispose = () => {};\n\n    if (path) {\n      const provider = new TauriFileSystemProvider(false);\n      const overlayDisposable = registerFileSystemOverlay(1, provider);\n      dispose = () => {\n        overlayDisposable.dispose();\n        provider.dispose();\n      };\n    }\n    return () => {\n      dispose();\n    };\n  }, [path]);\n\n  useEffect(() => {\n    let autoEnable = async () => {\n      if (initialized && sourcekitStartup === null && hasLimitedRam === false) {\n        setSourcekitStartup(true);\n      }\n    };\n    autoEnable();\n  }, [hasLimitedRam, initialized, sourcekitStartup]);\n\n  useEffect(() => {\n    if (!sourcekitStartup || selectedToolchain == null) return;\n    requestAnimationFrame(async () => {\n      try {\n        if (autoStartedLsp === path) return;\n        autoStartedLsp = path;\n        await restartServer(path, selectedToolchain);\n      } catch (e) {\n        console.error(\"Failed to start SourceKit-LSP:\", e);\n        addToast.error(\n          \"Failed to start SourceKit-LSP (see devtools for details). Some language features may not be available.\"\n        );\n      }\n    });\n  }, [sourcekitStartup, path, selectedToolchain]);\n\n  const openNewFile = useCallback((file: string) => {\n    setOpenFile(file);\n    setOpenFiles((oF) => {\n      if (!oF.includes(file)) return [file, ...oF];\n      return oF;\n    });\n  }, []);\n\n  const selectFile = useCallback(async () => {\n    const file = await openFileDialog({ multiple: false, directory: false });\n    if (file) {\n      openNewFile(file);\n    }\n  }, [openNewFile]);\n\n  useEffect(() => {\n    setCallbacks({\n      save: saveFile ?? (async () => {}),\n      openFolderDialog,\n      newProject: () => navigate(\"/new\"),\n      welcomePage: () => navigate(\"/\"),\n      openFile: selectFile,\n      undo: undo ?? (() => {}),\n      redo: redo ?? (() => {}),\n    });\n  }, [saveFile, openFolderDialog, navigate, selectFile, undo, redo]);\n\n  return (\n    <div className=\"ide-container\">\n      <MenuBar callbacks={callbacks} editor={editor} />\n      <Splitter\n        gutterTheme={theme === \"dark\" ? GutterTheme.Dark : GutterTheme.Light}\n        direction={SplitDirection.Horizontal}\n        initialSizes={screenshot ? [20, 50, 30] : [20, 80]}\n      >\n        <Tile className=\"file-explorer-tile\">\n          <FileExplorer openFolder={path} setOpenFile={openNewFile} />\n        </Tile>\n        <Splitter\n          gutterTheme={theme === \"dark\" ? GutterTheme.Dark : GutterTheme.Light}\n          direction={SplitDirection.Vertical}\n          initialSizes={[70, 30]}\n        >\n          <Editor\n            openFiles={openFiles}\n            focusedFile={openFile}\n            setSaveFile={setSaveFile}\n            setUndo={setUndo}\n            setRedo={setRedo}\n            setOpenFiles={setOpenFiles}\n            openNewFile={openNewFile}\n            setEditorUpper={setEditor}\n          />\n          <BottomBar />\n        </Splitter>\n        {screenshot && (\n          <div className=\"screenshot-tile\">\n            <div>\n              <Typography level=\"h3\">Screenshot</Typography>\n              <Button\n                variant=\"outlined\"\n                onClick={async () => {\n                  const blob = await (await fetch(screenshot)).blob();\n                  const arrayBuffer = await blob.arrayBuffer();\n                  const uint8Array = new Uint8Array(arrayBuffer);\n                  const savePath = await save({\n                    title: \"Save Screenshot\",\n                    defaultPath: \"screenshot.png\",\n                    filters: [\n                      { name: \"PNG Image\", extensions: [\"png\"] },\n                      { name: \"All Files\", extensions: [\"*\"] },\n                    ],\n                  });\n                  if (!savePath) return;\n                  await writeFile(savePath, uint8Array);\n                  addToast.success(\"Saved screenshot to \" + savePath);\n                }}\n              >\n                Save\n              </Button>\n              <Button variant=\"outlined\" onClick={() => setScreenshot(null)}>\n                Close\n              </Button>\n            </div>\n            <div className=\"screenshot-img-container\">\n              <img src={screenshot} alt=\"screenshot\" />\n            </div>\n          </div>\n        )}\n      </Splitter>\n      {initialized &&\n        selectedToolchain !== null &&\n        projectValidation !== null &&\n        projectValidation !== \"Valid\" && (\n          <Modal\n            open={true}\n            onClose={() => {\n              setProjectValidation(null);\n            }}\n          >\n            <ModalDialog sx={{ maxWidth: \"90vw\" }}>\n              <ModalClose />\n              <div>\n                <div style={{ display: \"flex\", gap: \"var(--padding-sm)\" }}>\n                  <div style={{ width: \"1.25rem\" }}>\n                    <ErrorIcon />\n                  </div>\n                  <Typography level=\"h3\">Failed to load project</Typography>\n                </div>\n                <Typography level=\"body-lg\">\n                  {getValidationMsg(projectValidation)} Some features may not\n                  work as expected.\n                </Typography>\n              </div>\n\n              <Divider sx={{ mb: \"var(--padding-xs)\" }} />\n              <div style={{ display: \"flex\", gap: \"var(--padding-lg)\" }}>\n                {projectValidation === \"InvalidToolchain\" && <SwiftMenu />}\n                {projectValidation !== \"InvalidToolchain\" && (\n                  <>\n                    <Button\n                      onClick={() => {\n                        navigate(\"/new\");\n                      }}\n                    >\n                      Create New\n                    </Button>\n                    <Button onClick={openFolderDialog}>\n                      Open Other Project\n                    </Button>\n                    <Button\n                      onClick={() => {\n                        setProjectValidation(null);\n                      }}\n                      variant=\"outlined\"\n                    >\n                      Ignore\n                    </Button>\n                  </>\n                )}\n              </div>\n            </ModalDialog>\n          </Modal>\n        )}\n      {initialized &&\n        selectedToolchain !== null &&\n        sourcekitStartup === null &&\n        hasIgnoredRam === false &&\n        hasLimitedRam && (\n          <Modal\n            open={true}\n            onClose={() => {\n              setHasIgnoredRam(true);\n            }}\n          >\n            <ModalDialog sx={{ maxWidth: \"90vw\" }}>\n              <ModalClose />\n              <div>\n                <div style={{ display: \"flex\", gap: \"var(--padding-md)\" }}>\n                  <div style={{ width: \"1.25rem\" }}>\n                    <WarningIcon />\n                  </div>\n                  <Typography level=\"h3\">Limited Memory</Typography>\n                </div>\n                <Typography level=\"body-lg\">\n                  SourceKit-LSP is used to provide autocomplete, error\n                  reporting, and other language features. However, it uses a\n                  large amount of memory. Your device does not meet our\n                  recommended memory requirements. You can choose to enable it\n                  anyways, but it may cause crashes or instability.\n                </Typography>\n                <Typography\n                  level=\"body-lg\"\n                  style={{ marginTop: \"var(--padding-sm)\" }}\n                >\n                  You can change this at any time in Edit {\">\"} Preferences{\" \"}\n                  {\">\"} SourceKit LSP {\">\"} Auto-Launch SourceKit.\n                </Typography>\n                <Typography\n                  level=\"body-lg\"\n                  style={{ marginTop: \"var(--padding-sm)\" }}\n                >\n                  You can also enable SourceKit temporarily with Build {\">\"}{\" \"}\n                  Restart LSP.\n                </Typography>\n              </div>\n\n              <Divider sx={{ mb: \"var(--padding-xs)\" }} />\n              <div style={{ display: \"flex\", gap: \"var(--padding-lg)\" }}>\n                <Button\n                  onClick={() => {\n                    setSourcekitStartup(false);\n                    setHasIgnoredRam(true);\n                  }}\n                >\n                  Keep disabled\n                </Button>\n                <Button\n                  onClick={() => {\n                    setSourcekitStartup(true);\n                    setHasIgnoredRam(true);\n                  }}\n                  color=\"danger\"\n                  variant=\"outlined\"\n                >\n                  Enable Anyway\n                </Button>\n              </div>\n            </ModalDialog>\n          </Modal>\n        )}\n      {initialized &&\n        selectedToolchain !== null &&\n        hasIgnoredDarwinSDK === false &&\n        darwinSDKVersion !== DARWIN_SDK_VERSION && (\n          <Modal\n            open={true}\n            onClose={() => {\n              setHasIgnoredDarwinSDK(true);\n            }}\n          >\n            <ModalDialog sx={{ maxWidth: \"90vw\" }}>\n              <ModalClose />\n              <div>\n                <div style={{ display: \"flex\", gap: \"var(--padding-md)\" }}>\n                  <div style={{ width: \"1.25rem\" }}>\n                    <WarningIcon />\n                  </div>\n                  <Typography level=\"h3\">Incompatible SDK Version</Typography>\n                </div>\n                <Typography level=\"body-lg\">\n                  This version of CrossCode is designed to work with Darwin SDK{\" \"}\n                  {DARWIN_SDK_VERSION}, but you have version {darwinSDKVersion}{\" \"}\n                  installed. Things may still work, but you will miss out on\n                  newer features (like liquid glass) and may run into issues.\n                </Typography>\n              </div>\n\n              <Divider sx={{ mb: \"var(--padding-xs)\" }} />\n              <div style={{ display: \"flex\", gap: \"var(--padding-lg)\" }}>\n                <Button\n                  onClick={() => {\n                    navigate(\"/#install-sdk\");\n                  }}\n                >\n                  Install Correct SDK\n                </Button>\n                <Button\n                  onClick={() => {\n                    setHasIgnoredDarwinSDK(true);\n                  }}\n                  variant=\"outlined\"\n                >\n                  Ignore\n                </Button>\n              </div>\n            </ModalDialog>\n          </Modal>\n        )}\n    </div>\n  );\n};\n\nfunction getValidationMsg(validation: ProjectValidation): string {\n  switch (validation) {\n    case \"Invalid\":\n      return \"This does not appear to be a valid CrossCode project.\";\n    case \"InvalidPackage\":\n      return \"SwiftPM was unable to parse your package. Please check your Package.swift file.\";\n    case \"UnsupportedFormatVersion\":\n      return \"This project uses an unsupported config format version. You may need to update CrossCode.\";\n    case \"InvalidToolchain\":\n      return \"Your Swift toolchain appears to be invalid.\";\n    default:\n      return \"\";\n  }\n}\n"
  },
  {
    "path": "src/pages/New.css",
    "content": ".new-templates-container {\n  display: flex;\n  gap: var(--padding-lg);\n  flex-wrap: wrap;\n}\n\n.new-template-card {\n  max-width: 500px;\n  flex-grow: 1;\n  flex-basis: 400px;\n  cursor: pointer;\n}\n\n.new-template-card:hover {\n  filter: brightness(0.8);\n}\n\n.new-template-form {\n  display: flex;\n  flex-direction: column;\n  gap: var(--padding-sm);\n  width: 100%;\n}\n.new-template-field {\n  display: flex;\n  align-items: center;\n  gap: var(--padding-lg);\n  width: 100%;\n}\n\n.new-template-field-input {\n  flex-grow: 1;\n}\n"
  },
  {
    "path": "src/pages/New.tsx",
    "content": "import logo from \"../assets/logo.png\";\nimport {\n  AspectRatio,\n  Button,\n  Card,\n  CardContent,\n  CardOverflow,\n  Link,\n  Typography,\n} from \"@mui/joy\";\nimport \"./Onboarding.css\";\nimport \"./New.css\";\nimport { templates } from \"../utilities/templates\";\nimport { useNavigate } from \"react-router-dom\";\n\nexport default () => {\n  const navigate = useNavigate();\n  return (\n    <div className=\"onboarding\">\n      <div className=\"onboarding-header\">\n        <img src={logo} alt=\"CrossCode Logo\" className=\"onboarding-logo\" />\n        <div>\n          <Typography level=\"h1\">Create New Project</Typography>\n          <Typography level=\"body-sm\">\n            Select a template to get started\n          </Typography>\n        </div>\n      </div>\n      <div className=\"new-templates-container\">\n        {templates.map((template) => (\n          <Card key={template.id} className=\"new-template-card\">\n            {template.image && (\n              <CardOverflow>\n                <AspectRatio ratio=\"2\">\n                  <img src={template.image} alt={template.name} />\n                </AspectRatio>\n              </CardOverflow>\n            )}\n            <CardContent>\n              <Typography level=\"h3\" className=\"new-template-title\">\n                <Link\n                  overlay\n                  underline=\"none\"\n                  href={`#`}\n                  sx={{ color: \"text.primary\" }}\n                  onClick={(e) => {\n                    e.preventDefault();\n                    navigate(`/new/${template.id}`);\n                  }}\n                >\n                  {template.name}\n                </Link>\n              </Typography>\n              <Typography level=\"body-sm\" className=\"new-template-description\">\n                {template.description}\n              </Typography>\n            </CardContent>\n          </Card>\n        ))}\n      </div>\n\n      <Button\n        sx={{ width: \"fit-content\" }}\n        onClick={() => navigate(\"/\")}\n        variant=\"outlined\"\n      >\n        Back to Home\n      </Button>\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/pages/NewTemplate.tsx",
    "content": "import logo from \"../assets/logo.png\";\nimport { Input, Typography } from \"@mui/joy\";\nimport \"./Onboarding.css\";\nimport \"./New.css\";\nimport { templates } from \"../utilities/templates\";\nimport { Navigate, useNavigate, useParams } from \"react-router-dom\";\nimport { useState } from \"react\";\nimport { Button } from \"@mui/joy\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { useToast } from \"react-toast-plus\";\n\nexport default () => {\n  const navigate = useNavigate();\n  const params = useParams<\"template\">();\n  const templateId = params.template;\n  if (!templateId) {\n    return <Navigate to=\"/new\" replace />;\n  }\n  const template = templates.find((t) => t.id === templateId);\n  const { addToast } = useToast();\n  if (!template) return <Navigate to=\"/new\" replace />;\n\n  const [form, setForm] = useState(\n    Object.fromEntries(\n      Object.entries(template.fields).map(([key]) => [key, \"\"])\n    )\n  );\n\n  const handleChange = (key: string, value: string) => {\n    setForm((prev) => ({ ...prev, [key]: value }));\n  };\n\n  const handleSubmit = async (e: React.FormEvent) => {\n    e.preventDefault();\n    try {\n      let path = await invoke<string>(\"create_template\", {\n        template: templateId,\n        name: form.projectName || template.name,\n        parameters: form,\n      });\n      if (path) {\n        navigate(`/ide/${encodeURIComponent(path)}`);\n      }\n    } catch (error) {\n      addToast.error(\"Failed to create project: \" + error);\n    }\n  };\n\n  return (\n    <div className=\"onboarding\">\n      <div className=\"onboarding-header\">\n        <img src={logo} alt=\"CrossCode Logo\" className=\"onboarding-logo\" />\n        <div>\n          <Typography level=\"h1\">{template.name}</Typography>\n          <Typography level=\"body-sm\">{template.description}</Typography>\n        </div>\n      </div>\n      <form onSubmit={handleSubmit} className=\"new-template-form\">\n        {Object.keys(template.fields).map((key) => {\n          const field = template.fields[key];\n          return (\n            <div key={key} className=\"new-template-field\">\n              <Typography className=\"new-template-field-label\">\n                {field.label}\n              </Typography>\n              <Input\n                required\n                className=\"new-template-field-input\"\n                placeholder={field.default}\n                value={form[key] ?? \"\"}\n                onChange={(e) => handleChange(key, e.target.value)}\n                name={key}\n              />\n            </div>\n          );\n        })}\n        <Button type=\"submit\" sx={{ mt: 2 }}>\n          Create Project\n        </Button>\n        <Button onClick={() => navigate(\"/new\")} variant=\"outlined\">\n          Back to Templates\n        </Button>\n      </form>\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/pages/Onboarding.css",
    "content": ".onboarding {\n  padding: var(--padding-lg);\n  display: flex;\n  flex-direction: column;\n  gap: var(--padding-lg);\n}\n\n.onboarding h1,\n.onboarding p {\n  margin: 0;\n}\n\n.onboarding-header {\n  display: flex;\n  align-items: center;\n  gap: var(--padding-lg);\n}\n\n.onboarding-buttons {\n  display: flex;\n  gap: var(--padding-lg);\n}\n\n.onboarding-logo {\n  width: 6rem;\n  height: 6rem;\n}\n\n.onboarding-cards {\n  display: flex;\n  flex-direction: column;\n  gap: var(--padding-lg);\n}\n\n.disabled-button {\n  cursor: not-allowed;\n}\n\n.onboarding-version {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n"
  },
  {
    "path": "src/pages/Onboarding.tsx",
    "content": "import { useEffect, useRef, useState } from \"react\";\nimport { open } from \"@tauri-apps/plugin-shell\";\nimport \"./Onboarding.css\";\nimport { Button, Card, CardContent, Divider, Link, Typography } from \"@mui/joy\";\nimport { useIDE } from \"../utilities/IDEContext\";\nimport logo from \"../assets/logo.png\";\nimport { useLocation, useNavigate } from \"react-router\";\nimport { openUrl } from \"@tauri-apps/plugin-opener\";\nimport SwiftMenu from \"../components/SwiftMenu\";\nimport SDKMenu from \"../components/SDKMenu\";\nimport ErrorIcon from \"@mui/icons-material/Error\";\nimport WarningIcon from \"@mui/icons-material/Warning\";\nimport { getVersion } from \"@tauri-apps/api/app\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { useToast } from \"react-toast-plus\";\nimport { relaunch } from \"@tauri-apps/plugin-process\";\nimport { SWIFT_VERSION_PREFIX } from \"../utilities/constants\";\n\nexport interface OnboardingProps {}\n\nexport default ({}: OnboardingProps) => {\n  const { ready, hasWSL, isWindows, openFolderDialog } = useIDE();\n  const [version, setVersion] = useState<string>(\"\");\n  const navigate = useNavigate();\n  const { addToast } = useToast();\n\n  useEffect(() => {\n    const fetchVersion = async () => {\n      const version = await getVersion();\n      setVersion(version);\n    };\n    fetchVersion();\n  }, []);\n\n  const location = useLocation();\n  const darwinSdkRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    console.log(location.hash);\n    if (location.hash === \"#install-sdk\" && darwinSdkRef.current) {\n      darwinSdkRef.current.scrollIntoView({\n        block: \"start\",\n      });\n    }\n  }, [location.hash]);\n\n  return (\n    <div className=\"onboarding\">\n      <div className=\"onboarding-header\">\n        <img src={logo} alt=\"CrossCode Logo\" className=\"onboarding-logo\" />\n        <div>\n          <div\n            style={{\n              display: \"flex\",\n              alignItems: \"baseline\",\n              gap: \"var(--padding-sm)\",\n            }}\n          >\n            <Typography level=\"h1\">Welcome to CrossCode!</Typography>\n            {version && <Typography level=\"body-sm\">v{version}</Typography>}\n          </div>\n          <Typography level=\"body-sm\">\n            IDE for iOS Development on Windows and Linux\n          </Typography>\n        </div>\n      </div>\n      <div>\n        <Typography\n          level=\"h3\"\n          sx={{\n            alignContent: \"center\",\n            display: \"flex\",\n            gap: \"var(--padding-sm)\",\n          }}\n          color=\"warning\"\n        >\n          <WarningIcon sx={{ width: \"1.5rem\" }} /> Early Access Version{\" \"}\n          <WarningIcon sx={{ width: \"1.5rem\" }} />\n        </Typography>\n        <Typography level=\"body-md\">\n          This is an early access version of CrossCode. Expect bugs. Please\n          report any issues you find on{\" \"}\n          <Link\n            href=\"#\"\n            onClick={(e) => {\n              e.preventDefault();\n              open(\"https://github.com/nab138/CrossCode/issues\");\n            }}\n          >\n            github\n          </Link>\n          . Check the{\" \"}\n          <Link\n            href=\"#\"\n            onClick={(e) => {\n              e.preventDefault();\n              open(\"https://github.com/nab138/CrossCode/wiki/Troubleshooting\");\n            }}\n          >\n            troubleshooting guide\n          </Link>{\" \"}\n          for known issues and workarounds.\n        </Typography>\n      </div>\n      <div className=\"onboarding-buttons\">\n        <Button\n          size=\"lg\"\n          disabled={!ready}\n          className={!ready ? \"disabled-button\" : \"\"}\n          onClick={() => {\n            if (ready) {\n              navigate(\"/new\");\n            }\n          }}\n        >\n          Create New\n        </Button>\n        <Button size=\"lg\" disabled={!ready} onClick={openFolderDialog}>\n          Open Project\n        </Button>\n      </div>\n\n      <Typography\n        level={ready ? \"body-sm\" : \"body-md\"}\n        sx={{\n          alignContent: \"center\",\n          display: \"flex\",\n          gap: \"var(--padding-xs)\",\n        }}\n        color={ready ? undefined : \"danger\"}\n      >\n        {ready ? (\n          \"Use the cards below to manage your CrossCode setup\"\n        ) : (\n          <>\n            <ErrorIcon />\n            One or more issues need to be resolved before you can use CrossCode\n          </>\n        )}\n      </Typography>\n      <div className=\"onboarding-cards\">\n        {isWindows && (\n          <Card variant=\"soft\">\n            <Typography level=\"h3\">Windows Subsystem for Linux</Typography>\n            <Typography level=\"body-sm\">\n              Windows Subsystem for Linux (WSL) is required to use CrossCode on\n              Windows. Learn more about WSL on{\" \"}\n              <Link\n                href=\"#\"\n                onClick={(e) => {\n                  e.preventDefault();\n                  open(\"https://learn.microsoft.com/en-us/windows/wsl/\");\n                }}\n              >\n                microsoft.com\n              </Link>\n              . We recommended WSL 2 and Ubuntu 24.04. Other distributions may\n              work, but are not officially supported. CrossCode will use your\n              default WSL distribution.\n            </Typography>\n            <Divider />\n            <CardContent>\n              <Typography\n                level=\"body-md\"\n                sx={{\n                  alignContent: \"center\",\n                  display: \"flex\",\n                  gap: \"var(--padding-xs)\",\n                }}\n                color={hasWSL === false ? \"danger\" : undefined}\n              >\n                {hasWSL === null ? (\n                  \"Checking for wsl...\"\n                ) : hasWSL ? (\n                  \"WSL is already installed on your system!\"\n                ) : (\n                  <>\n                    <ErrorIcon />{\" \"}\n                    <div>\n                      WSL is not installed on your system. CrossCode can attempt\n                      to automatically install WSL. If it fails, follow the\n                      guide on{\" \"}\n                      <Link\n                        href=\"#\"\n                        onClick={(e) => {\n                          e.preventDefault();\n                          openUrl(\n                            \"https://learn.microsoft.com/en-us/windows/wsl/install\"\n                          );\n                        }}\n                      >\n                        microsoft.com\n                      </Link>\n                      .\n                    </div>\n                  </>\n                )}\n              </Typography>\n              {!hasWSL && (\n                <div\n                  style={{\n                    display: \"flex\",\n                    gap: \"var(--padding-md)\",\n                    marginTop: \"var(--padding-xs)\",\n                  }}\n                >\n                  <Button\n                    variant=\"soft\"\n                    onClick={async () => {\n                      try {\n                        await invoke(\"install_wsl\");\n                        addToast.success(\n                          \"Started WSL installation. It may take a while, and may ask you to restart your PC. If you are prompted to enter a username or password, choose whatever you like.\"\n                        );\n                      } catch (error) {\n                        addToast.error(\n                          \"Failed to launch WSL installation. Please try installing it manually.\"\n                        );\n                      }\n                    }}\n                  >\n                    Install WSL\n                  </Button>\n                  <Button\n                    variant=\"soft\"\n                    onClick={async () => {\n                      try {\n                        await relaunch();\n                      } catch (error) {\n                        addToast.error(\n                          \"Failed to relaunch CrossCode. Please try manually.\"\n                        );\n                      }\n                    }}\n                  >\n                    Relaunch CrossCode (post-installation)\n                  </Button>\n                </div>\n              )}\n            </CardContent>\n          </Card>\n        )}\n        <Card variant=\"soft\">\n          <Typography level=\"h3\">Swift</Typography>\n          <Typography level=\"body-sm\">\n            You will need a Swift {SWIFT_VERSION_PREFIX} toolchain to use\n            CrossCode. It is recommended to install it using swiftly, but you\n            can also install it manually.\n          </Typography>\n          <Divider />\n          <CardContent>\n            <SwiftMenu />\n          </CardContent>\n        </Card>\n        <Card variant=\"soft\" id=\"install-sdk\">\n          <Typography level=\"h3\">Darwin SDK</Typography>\n          <Typography level=\"body-sm\">\n            CrossCode requires a special swift SDK to build apps for iOS. It can\n            be generated from a copy of Xcode 26 or later. To install it,\n            download Xcode.xip using the link below, click the \"Install SDK\"\n            button, then select the downloaded file. Note that installing the\n            SDK will temporarily require a lot of disk space (~11GB) and may\n            take a while.\n          </Typography>\n          <Divider />\n          <CardContent>\n            <SDKMenu />\n          </CardContent>\n        </Card>\n      </div>\n      <div style={{ width: 0, height: 0 }} ref={darwinSdkRef}></div>\n    </div>\n  );\n};\n"
  },
  {
    "path": "src/preferences/PreferenceItemRenderer.tsx",
    "content": "import {\n  Button,\n  Input,\n  Option,\n  Select,\n  Typography,\n  FormControl,\n  Checkbox,\n} from \"@mui/joy\";\nimport { PreferenceItem } from \"./types\";\nimport { useStore } from \"../utilities/StoreContext\";\nimport { useEffect, useState } from \"react\";\n\nexport interface PreferenceItemRendererProps {\n  item: PreferenceItem;\n  storeExists: boolean;\n  pageName: string;\n}\n\nexport default function PreferenceItemRenderer({\n  item,\n  storeExists,\n  pageName,\n}: PreferenceItemRendererProps) {\n  const storeKey = `${pageName}/${item.id}`.toLowerCase();\n  const [value, setValue] = useStore(storeKey, item.defaultValue || \"\");\n  const [showOtherTextField, setShowOtherTextField] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n\n  useEffect(() => {\n    if (item.type === \"select\" && item.options) {\n      if (\n        item.options.some((o) => o.value === \"other\") &&\n        !item.options.some((o) => o.value === value)\n      ) {\n        setShowOtherTextField(true);\n      } else {\n        setShowOtherTextField(false);\n      }\n    }\n  }, [value]);\n\n  if (item.type === \"info\" && typeof item.defaultValue === \"function\") {\n    const [info, setInfo] = useState(\"\");\n\n    useEffect(() => {\n      const fetchInfo = async () => {\n        const result = await item.defaultValue();\n        setInfo(result);\n      };\n      fetchInfo();\n    }, [item.defaultValue]);\n\n    return (\n      <FormControl className=\"prefs-setting\">\n        <div className=\"prefs-setting-row\">\n          <Typography level=\"body-md\" className=\"prefs-label\">\n            {item.name}:\n          </Typography>\n          <Typography level=\"body-md\">{info}</Typography>\n        </div>\n        {item.description && (\n          <Typography\n            level=\"body-xs\"\n            sx={{ color: \"var(--joy-palette-neutral-400)\" }}\n          >\n            {item.description}\n          </Typography>\n        )}\n      </FormControl>\n    );\n  }\n\n  if (item.type === \"custom\" && item.customComponent) {\n    const CustomComponent = item.customComponent;\n    return <CustomComponent />;\n  }\n\n  const handleChange = async (newValue: any) => {\n    if (\n      item.type === \"select\" &&\n      item.options?.some((o) => o.default !== undefined)\n    ) {\n      if (\n        item.options?.find((o) => o.value === newValue)?.default !== undefined\n      ) {\n        setNewValue(item.options.find((o) => o.value === newValue)?.default);\n        return;\n      }\n    }\n    setNewValue(newValue);\n  };\n\n  const setNewValue = async (newValue: any) => {\n    if (item.validation) {\n      const validationError = item.validation(newValue);\n      setError(validationError);\n      if (validationError) return;\n    }\n\n    setValue(newValue);\n    if (item.onChange) {\n      try {\n        await item.onChange(newValue);\n      } catch (err) {\n        console.error(`Error in onChange for ${item.name}:`, err);\n        setError(err instanceof Error ? err.message : \"An error occurred\");\n      }\n    }\n  };\n\n  return (\n    <FormControl className=\"prefs-setting\" error={!!error}>\n      <div className=\"prefs-setting-row\">\n        {item.type !== \"button\" && (\n          <Typography level=\"body-md\" className=\"prefs-label\">\n            {item.name}:\n          </Typography>\n        )}\n\n        <div className=\"prefs-input\">\n          {item.type === \"text\" && (\n            <Input\n              type=\"text\"\n              size=\"sm\"\n              disabled={!storeExists}\n              value={value}\n              onChange={(e) => handleChange(e.target.value)}\n            />\n          )}\n\n          {item.type === \"number\" && (\n            <Input\n              type=\"number\"\n              size=\"sm\"\n              disabled={!storeExists}\n              value={value}\n              onChange={(e) => handleChange(Number(e.target.value))}\n            />\n          )}\n\n          {item.type === \"select\" && (\n            <Select\n              value={showOtherTextField ? \"other\" : value}\n              size=\"sm\"\n              disabled={!storeExists}\n              onChange={(_, newValue) => handleChange(newValue)}\n            >\n              {item.options?.map((option) => (\n                <Option key={option.value} value={option.value}>\n                  {option.label}\n                </Option>\n              ))}\n            </Select>\n          )}\n\n          {item.type === \"checkbox\" && (\n            <Checkbox\n              checked={value === true || value === \"true\"}\n              disabled={!storeExists}\n              onChange={(e) => handleChange(e.target.checked)}\n            />\n          )}\n\n          {item.type === \"button\" && (\n            <Button\n              variant={item.variant || \"soft\"}\n              color={item.color || \"primary\"}\n              disabled={!storeExists}\n              onClick={() => handleChange(\"\")}\n            >\n              {item.name}\n            </Button>\n          )}\n\n          {item.type === \"info\" && (\n            <Typography\n              level=\"body-sm\"\n              sx={{ color: \"var(--joy-palette-neutral-500)\" }}\n            >\n              {value}\n            </Typography>\n          )}\n        </div>\n      </div>\n\n      {item.type === \"select\" && showOtherTextField && (\n        <>\n          <Input\n            type=\"text\"\n            size=\"sm\"\n            disabled={!storeExists}\n            value={value}\n            onChange={(e) => setNewValue(e.target.value)}\n          />\n        </>\n      )}\n\n      {error && (\n        <Typography level=\"body-xs\" color=\"danger\">\n          {error}\n        </Typography>\n      )}\n\n      {item.description && !error && (\n        <Typography\n          level=\"body-xs\"\n          sx={{ color: \"var(--joy-palette-neutral-400)\" }}\n        >\n          {item.description}\n        </Typography>\n      )}\n    </FormControl>\n  );\n}\n"
  },
  {
    "path": "src/preferences/Preferences.tsx",
    "content": "import { useParams } from \"react-router\";\nimport \"./Prefs.css\";\n\nimport { Divider, Typography, Link } from \"@mui/joy\";\nimport { Link as RouterLink } from \"react-router-dom\";\nimport { Fragment, useContext, useEffect } from \"react\";\nimport { StoreContext } from \"../utilities/StoreContext\";\nimport { preferenceRegistry } from \"./pages\";\nimport PreferenceItemRenderer from \"./PreferenceItemRenderer\";\n\nexport default function Preferences() {\n  const { page } = useParams<\"page\">();\n  const { store } = useContext(StoreContext);\n  const storeExists = store !== null && store !== undefined;\n\n  const categories = preferenceRegistry.getAllCategories();\n  const currentPage = page ? preferenceRegistry.getPage(page) : null;\n\n  // Call onLoad when page changes\n  useEffect(() => {\n    if (currentPage?.onLoad) {\n      currentPage.onLoad();\n    }\n  }, [currentPage]);\n\n  return (\n    <div className=\"prefs-container\">\n      <div className=\"prefs-sidebar-container\">\n        <div className=\"prefs-sidebar\">\n          {categories.map((category, categoryIndex) => (\n            <Fragment key={category.id}>\n              <Typography\n                level=\"title-sm\"\n                sx={{\n                  padding: \"var(--padding-xs) 0\",\n                  color: \"var(--joy-palette-neutral-600)\",\n                  textTransform: \"uppercase\",\n                  fontSize: \"0.75rem\",\n                  fontWeight: 600,\n                }}\n              >\n                {category.name}\n              </Typography>\n              {category.pages.map((p) => (\n                <Link\n                  level=\"body-sm\"\n                  className=\"prefs-sidebar-item\"\n                  key={p.id}\n                  component={RouterLink}\n                  to={`/preferences/${p.id}`}\n                  sx={{\n                    textDecoration: page === p.id ? \"underline\" : \"none\",\n                    color: \"inherit\",\n                    padding: \"var(--padding-xs)\",\n                    marginTop: \"2px\",\n                    fontWeight: page === p.id ? 600 : 400,\n                  }}\n                >\n                  {p.name}\n                </Link>\n              ))}\n              {categoryIndex !== categories.length - 1 && (\n                <Divider orientation=\"horizontal\" />\n              )}\n            </Fragment>\n          ))}\n        </div>\n        <Divider orientation=\"vertical\" />\n      </div>\n\n      <div className=\"prefs-content\">\n        {currentPage ? (\n          <>\n            <div className=\"prefs-page-header\">\n              <Typography level=\"title-lg\">{currentPage.name}</Typography>\n              {currentPage.description && (\n                <Typography level=\"body-sm\">\n                  {currentPage.description}\n                </Typography>\n              )}\n            </div>\n\n            <div className=\"prefs-page-content\">\n              {currentPage.customComponent ? (\n                <currentPage.customComponent />\n              ) : (\n                currentPage.items?.map((item) => (\n                  <PreferenceItemRenderer\n                    key={item.id}\n                    item={item}\n                    storeExists={storeExists}\n                    pageName={currentPage.id}\n                  />\n                ))\n              )}\n            </div>\n          </>\n        ) : page ? (\n          <Typography level=\"h2\">Page Not Found</Typography>\n        ) : (\n          <div className=\"prefs-welcome\">\n            <Typography level=\"title-lg\">Preferences</Typography>\n            <Typography level=\"body-md\" sx={{ marginTop: \"var(--padding-sm)\" }}>\n              Select a category from the sidebar to configure your preferences.\n            </Typography>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n"
  },
  {
    "path": "src/preferences/Prefs.css",
    "content": ".prefs-container {\n  padding: var(--padding-xs);\n  box-sizing: border-box;\n  width: 100%;\n  height: 100%;\n  overflow: hidden;\n}\n\n.prefs-sidebar-container {\n  width: 150px;\n  float: left;\n  height: 100%;\n  box-sizing: border-box;\n  display: flex;\n}\n\n.prefs-sidebar {\n  display: flex;\n  flex-direction: column;\n  width: 100%;\n  height: 100%;\n}\n\n.prefs-sidebar-item:hover {\n  background-color: #00000030;\n  cursor: pointer;\n}\n\n.prefs-setting {\n  display: flex;\n  flex-direction: column;\n  gap: var(--padding-xs);\n  margin-bottom: var(--padding-md);\n  align-items: flex-start;\n}\n\n.prefs-setting-row {\n  display: flex;\n  flex-direction: row;\n  flex-wrap: nowrap;\n  align-items: center;\n  gap: var(--padding-md);\n  width: 100%;\n}\n\n.prefs-setting-row .prefs-label {\n  flex-shrink: 0;\n  margin: 0;\n}\n\n.prefs-setting-row .prefs-input {\n  flex: 1;\n  max-width: 300px;\n}\n\n.prefs-page-header {\n  margin-bottom: var(--padding-md);\n  margin-top: var(--padding-md);\n  padding-bottom: var(--padding-md);\n  border-bottom: 1px solid var(--joy-palette-divider);\n  padding-left: var(--padding-md);\n}\n\n.prefs-content {\n  max-height: 100%;\n  display: flex;\n  flex-direction: column;\n}\n\n.prefs-page-content {\n  display: flex;\n  flex-direction: column;\n  gap: var(--padding-sm);\n  padding-left: var(--padding-md);\n  overflow: auto;\n\n  flex-grow: 1;\n}\n\n.prefs-welcome {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 50%;\n  text-align: center;\n}\n\n.prefs-input {\n  display: flex;\n  align-items: center;\n}\n"
  },
  {
    "path": "src/preferences/helpers.ts",
    "content": "import { PreferencePage, PreferenceItem } from \"./types\";\nimport { preferenceRegistry } from \"./registry\";\n\nexport function createPreferencePage(\n  id: string,\n  name: string,\n  items: PreferenceItem[],\n  options?: {\n    description?: string;\n    category?: string;\n    onLoad?: () => void | Promise<void>;\n    onSave?: () => void | Promise<void>;\n  }\n): PreferencePage {\n  const page: PreferencePage = {\n    id,\n    name,\n    items,\n    description: options?.description,\n    category: options?.category,\n    onLoad: options?.onLoad,\n    onSave: options?.onSave,\n  };\n\n  preferenceRegistry.registerPage(page);\n  return page;\n}\n\nexport function createCustomPreferencePage(\n  id: string,\n  name: string,\n  component: React.ComponentType,\n  options?: {\n    description?: string;\n    category?: string;\n    onLoad?: () => void | Promise<void>;\n    onSave?: () => void | Promise<void>;\n  }\n): PreferencePage {\n  const page: PreferencePage = {\n    id,\n    name,\n    customComponent: component,\n    description: options?.description,\n    category: options?.category,\n    onLoad: options?.onLoad,\n    onSave: options?.onSave,\n  };\n\n  preferenceRegistry.registerPage(page);\n  return page;\n}\n\nexport const createItems = {\n  text: (\n    id: string,\n    name: string,\n    description?: string,\n    defaultValue?: string,\n    onChange?: (value: string) => void | Promise<void>\n  ): PreferenceItem => ({\n    id,\n    name,\n    description,\n    type: \"text\",\n    defaultValue,\n    onChange,\n  }),\n\n  select: (\n    id: string,\n    name: string,\n    options: Array<{ label: string; value: string, default?: string }>,\n    description?: string,\n    defaultValue?: string,\n    onChange?: (value: string) => void | Promise<void>\n  ): PreferenceItem => ({\n    id,\n    name,\n    description,\n    type: \"select\",\n    options,\n    defaultValue,\n    onChange,\n  }),\n\n  checkbox: (\n    id: string,\n    name: string,\n    description?: string,\n    defaultValue?: boolean,\n    onChange?: (value: boolean) => void | Promise<void>\n  ): PreferenceItem => ({\n    id,\n    name,\n    description,\n    type: \"checkbox\",\n    defaultValue,\n    onChange,\n  }),\n\n  button: (\n    id: string,\n    name: string,\n    description: string,\n    color: \"primary\" | \"danger\" | \"neutral\" | \"success\" | \"warning\" = \"primary\",\n    variant: \"solid\" | \"outlined\" | \"soft\" | \"plain\" = \"soft\",\n    onClick: () => void | Promise<void>\n  ): PreferenceItem => ({\n    id,\n    name,\n    description,\n    type: \"button\",\n    onChange: onClick,\n    color,\n    variant,\n  }),\n\n  number: (\n    id: string,\n    name: string,\n    description?: string,\n    defaultValue?: number,\n    onChange?: (value: number) => void | Promise<void>\n  ): PreferenceItem => ({\n    id,\n    name,\n    description,\n    type: \"number\",\n    defaultValue,\n    onChange,\n  }),\n\n  custom: (\n    id: string,\n    name: string,\n    customComponent: React.ComponentType\n  ): PreferenceItem => ({\n    name,\n    id,\n    type: \"custom\",\n    customComponent,\n  }),\n};\n"
  },
  {
    "path": "src/preferences/pages/appIds.tsx",
    "content": "import { createCustomPreferencePage } from \"../helpers\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useStore } from \"../../utilities/StoreContext\";\nimport {\n  Accordion,\n  AccordionDetails,\n  AccordionGroup,\n  AccordionSummary,\n  Button,\n  Typography,\n} from \"@mui/joy\";\n\ntype AppId = {\n  app_id_id: string;\n  identifier: string;\n  name: string;\n  features: Record<string, any>;\n  expiration_date: Date | null;\n};\n\ntype AppIdsResponse = {\n  app_ids: AppId[];\n  max_quantity: number;\n  available_quantity: number;\n};\n\nconst AppIdsComponent = () => {\n  const [ids, setIds] = useState<AppId[]>([]);\n  const [maxQuantity, setMaxQuantity] = useState<number | null>(null);\n  const [availableQuantity, setAvailableQuantity] = useState<number | null>(\n    null\n  );\n  const [loading, setLoading] = useState<boolean>(true);\n  const [error, setError] = useState<string | null>(null);\n  const [anisetteServer] = useStore<string>(\n    \"apple-id/anisette-server\",\n    \"ani.sidestore.io\"\n  );\n  const [canDelete] = useStore<boolean>(\"developer/delete-app-ids\", false);\n  const loadingRef = useRef<boolean>(false);\n\n  useEffect(() => {\n    let fetch = async () => {\n      if (loadingRef.current) return;\n      loadingRef.current = true;\n      let ids = await invoke<AppIdsResponse>(\"list_app_ids\", {\n        anisetteServer,\n      });\n      setIds(ids.app_ids);\n      setMaxQuantity(ids.max_quantity);\n      setAvailableQuantity(ids.available_quantity);\n      setLoading(false);\n      loadingRef.current = false;\n    };\n    fetch().catch((e) => {\n      console.error(\"Failed to fetch certificates:\", e);\n      setError(\n        \"Failed to load certificates: \" + e + \"\\nPlease try again later.\"\n      );\n      setLoading(false);\n      loadingRef.current = false;\n    });\n  }, []);\n\n  if (loading) {\n    return <div>Loading App IDs...</div>;\n  }\n  if (error) {\n    return <div className=\"error\">{error}</div>;\n  }\n\n  return (\n    <div>\n      {availableQuantity != null && maxQuantity != null && (\n        <div style={{ marginBottom: \"var(--padding-lg)\" }}>\n          You have {availableQuantity}/{maxQuantity} App IDs available.\n        </div>\n      )}\n      <AccordionGroup\n        sx={{ margin: 0, padding: 0, width: \"calc(100% - var(--padding-xl))\" }}\n      >\n        {ids.map((id) => (\n          <Accordion key={id.app_id_id}>\n            <AccordionSummary\n              sx={{\n                display: \"flex\",\n                alignItems: \"center\",\n                gap: \"var(--padding-md)\",\n                padding: 0,\n              }}\n            >\n              {canDelete && (\n                <Button\n                  variant=\"soft\"\n                  color=\"warning\"\n                  onClick={async () => {\n                    try {\n                      await invoke(\"delete_app_id\", {\n                        anisetteServer,\n                        appIdId: id.app_id_id,\n                      });\n                      setIds((prev) =>\n                        prev.filter((c) => c.app_id_id !== id.app_id_id)\n                      );\n                    } catch (e) {\n                      console.error(\"Failed to delete app ID:\", e);\n                      alert(\n                        \"Failed to revoke app ID: \" +\n                          e +\n                          \"\\nPlease try again later.\"\n                      );\n                    }\n                  }}\n                >\n                  Delete\n                </Button>\n              )}\n              <div>\n                <div>\n                  {id.name}: {id.app_id_id}\n                </div>\n                <Typography\n                  level=\"body-xs\"\n                  sx={{ color: \"var(--joy-palette-neutral-500)\" }}\n                >\n                  {id.identifier}\n                </Typography>\n              </div>\n              {id.expiration_date && (\n                <div style={{ flexGrow: 1, textAlign: \"right\" }}>\n                  <Typography level=\"body-sm\">\n                    Expires {new Date(id.expiration_date).toLocaleDateString()}\n                  </Typography>\n                </div>\n              )}\n            </AccordionSummary>\n            <AccordionDetails>\n              <Typography level=\"body-md\">Features:</Typography>\n              <ul style={{ margin: 0, paddingLeft: \"var(--padding-xl)\" }}>\n                {Object.entries(id.features).map(([feature, value]) => (\n                  <li key={feature}>\n                    <strong>{feature}:</strong> {JSON.stringify(value)}\n                  </li>\n                ))}\n              </ul>\n            </AccordionDetails>\n          </Accordion>\n        ))}\n        {ids.length === 0 && <li>No App IDs found.</li>}\n      </AccordionGroup>\n    </div>\n  );\n};\n\nexport const appIdsPage = createCustomPreferencePage(\n  \"appids\",\n  \"App IDs\",\n  AppIdsComponent,\n  {\n    description:\n      \"Free developer accounts have a limit of 10 App IDs. You cannot delete App IDs, but they will expire after a week.\",\n    category: \"apple\",\n  }\n);\n"
  },
  {
    "path": "src/preferences/pages/appearance.tsx",
    "content": "import { useContext, useState } from \"react\";\nimport { createPreferencePage, createItems } from \"../helpers\";\nimport { setTheme } from \"@tauri-apps/api/app\";\nimport { StoreContext, useStore } from \"../../utilities/StoreContext\";\nimport {\n  FormControl,\n  Select,\n  useColorScheme,\n  Option,\n  Typography,\n} from \"@mui/joy\";\n\nconst ThemeSelector = () => {\n  const { store } = useContext(StoreContext);\n  const storeExists = store !== null && store !== undefined;\n  const storeKey = `appearance/theme`.toLowerCase();\n  const [value, setValue] = useStore(storeKey, \"dark\");\n  const [error, setError] = useState<string | null>(null);\n  const { setMode } = useColorScheme();\n\n  const handleChange = async (newValue: any) => {\n    setValue(newValue);\n    try {\n      await setTheme(newValue as \"light\" | \"dark\");\n      setMode(newValue as \"light\" | \"dark\");\n    } catch (err) {\n      console.error(`Error in onChange for theme:`, err);\n      setError(err instanceof Error ? err.message : \"An error occurred\");\n    }\n  };\n\n  return (\n    <FormControl className=\"prefs-setting\" error={!!error}>\n      <div className=\"prefs-setting-row\">\n        <div className=\"prefs-label\">Theme: </div>\n        <div className=\"prefs-input\">\n          <Select\n            value={value}\n            size=\"sm\"\n            disabled={!storeExists}\n            onChange={(_, newValue) => handleChange(newValue)}\n          >\n            <Option value={\"dark\"}>Dark</Option>\n            <Option value={\"light\"}>Light</Option>\n          </Select>\n        </div>\n      </div>\n\n      {error && (\n        <Typography level=\"body-xs\" color=\"danger\">\n          {error}\n        </Typography>\n      )}\n    </FormControl>\n  );\n};\n\nexport const appearancePage = createPreferencePage(\n  \"appearance\",\n  \"Appearance\",\n  [createItems.custom(\"theme\", \"Theme\", ThemeSelector)],\n  {\n    description: \"Customize the look and feel of the application\",\n    category: \"general\",\n  }\n);\n"
  },
  {
    "path": "src/preferences/pages/appleId.ts",
    "content": "import { createPreferencePage, createItems } from \"../helpers\";\nimport { invoke } from \"@tauri-apps/api/core\";\n\nexport const appleIdPage = createPreferencePage(\n  \"apple-id\",\n  \"Apple ID\",\n  [\n    createItems.select(\n      \"anisette-server\",\n      \"Anisette Server\",\n      [\n        { label: \"Sidestore (.io)\", value: \"ani.sidestore.io\" },\n        { label: \"Sidestore (.app)\", value: \"ani.sidestore.app\" },\n        { label: \"Sidestore (.zip)\", value: \"ani.sidestore.zip\" },\n        { label: \"Sidestore (.xyz)\", value: \"ani.846969.xyz\" },\n        { label: \"nythepegasus\", value: \"ani.npeg.us\" },\n        { label: \"Custom\", value: \"other\", default: \"ani.yourserver.com\" }\n      ],\n      \"The remote anisette server used. Change this if you are having issues logging in.\",\n      \"ani.sidestore.io\"\n    ),\n    {\n      id: \"apple-id-email\",\n      name: \"Apple ID\",\n      description: \"The apple ID email you are currently logged in with.\",\n      type: \"info\",\n      defaultValue: async () => {\n        const appleId = await invoke<string>(\"get_apple_email\");\n        return appleId || \"Not logged in\";\n      },\n    },\n    createItems.button(\n      \"reset-anisette\",\n      \"Reset Anisette\",\n      \"Remove all anisette data (will require 2fa again)\",\n      \"danger\",\n      \"soft\",\n      async () => {\n        await invoke(\"reset_anisette\");\n      }\n    ),\n    createItems.button(\n      \"reset-credentials\",\n      \"Reset Saved Credentials\",\n      \"Remove saved Apple ID credentials and anisette data\",\n      \"danger\",\n      \"soft\",\n      async () => {\n        await invoke(\"delete_stored_credentials\");\n        await invoke(\"reset_anisette\");\n      }\n    ),\n  ],\n  {\n    description: \"Manage your Apple ID authentication\",\n    category: \"apple\",\n  }\n);\n"
  },
  {
    "path": "src/preferences/pages/certificates.tsx",
    "content": "import { createCustomPreferencePage } from \"../helpers\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useStore } from \"../../utilities/StoreContext\";\nimport { Button, Typography } from \"@mui/joy\";\n\ntype Certificate = {\n  name: string;\n  certificate_id: string;\n  serial_number: string;\n  machine_name: string;\n};\n\nconst CertificatesComponent = () => {\n  let [certificates, setCertificates] = useState<Certificate[]>([]);\n  let [loading, setLoading] = useState<boolean>(true);\n  let [error, setError] = useState<string | null>(null);\n  const [anisetteServer] = useStore<string>(\n    \"apple-id/anisette-server\",\n    \"ani.sidestore.io\"\n  );\n  const loadingRef = useRef<boolean>(false);\n  let fetch = useCallback(async () => {\n    if (loadingRef.current) return;\n    loadingRef.current = true;\n    let certs = await invoke<Certificate[]>(\"get_certificates\", {\n      anisetteServer,\n    });\n    setCertificates(certs);\n    setLoading(false);\n    loadingRef.current = false;\n  }, [anisetteServer]);\n\n  useEffect(() => {\n    fetch().catch((e) => {\n      console.error(\"Failed to fetch certificates:\", e);\n      setError(\n        \"Failed to load certificates: \" + e + \"\\nPlease try again later.\"\n      );\n      setLoading(false);\n      loadingRef.current = false;\n    });\n  }, [fetch]);\n\n  if (loading) {\n    return <div>Loading certificates...</div>;\n  }\n  if (error) {\n    return <div className=\"error\">{error}</div>;\n  }\n\n  return (\n    <ul style={{ margin: 0, padding: 0, listStyleType: \"none\" }}>\n      {certificates.map((cert) => (\n        <li\n          key={cert.certificate_id}\n          style={{\n            display: \"flex\",\n            alignItems: \"center\",\n            gap: \"var(--padding-md)\",\n          }}\n        >\n          <Button\n            variant=\"soft\"\n            color=\"warning\"\n            onClick={async () => {\n              try {\n                await invoke(\"revoke_certificate\", {\n                  anisetteServer,\n                  serialNumber: cert.serial_number,\n                });\n                setCertificates((prev) =>\n                  prev.filter((c) => c.certificate_id !== cert.certificate_id)\n                );\n              } catch (e) {\n                console.error(\"Failed to revoke certificate:\", e);\n                alert(\n                  \"Failed to revoke certificate: \" +\n                    e +\n                    \"\\nPlease try again later.\"\n                );\n              }\n            }}\n          >\n            Revoke\n          </Button>\n          <div>\n            <div>\n              {cert.name}: {cert.machine_name}\n            </div>\n            <Typography\n              level=\"body-xs\"\n              sx={{ color: \"var(--joy-palette-neutral-500)\" }}\n            >\n              {cert.serial_number} ({cert.certificate_id})\n            </Typography>\n          </div>\n        </li>\n      ))}\n      {certificates.length === 0 && <li>No certificates found.</li>}\n    </ul>\n  );\n};\n\nexport const certificatesPage = createCustomPreferencePage(\n  \"certificates\",\n  \"Certificates\",\n  CertificatesComponent,\n  {\n    description: \"Manage your Apple ID certificates\",\n    category: \"apple\",\n  }\n);\n"
  },
  {
    "path": "src/preferences/pages/developer.ts",
    "content": "import { invoke } from \"@tauri-apps/api/core\";\nimport { createItems, createPreferencePage } from \"../helpers\";\nimport { load } from \"@tauri-apps/plugin-store\";\nimport { relaunch } from \"@tauri-apps/plugin-process\";\nimport { confirm } from \"@tauri-apps/plugin-dialog\";\n\nexport const developerPage = createPreferencePage(\n  \"developer\",\n  \"Developer\",\n  [\n    createItems.checkbox(\n      \"delete-app-ids\",\n      \"Allow deleting app IDs\",\n      \"Reveal the delete button in the app ID page (note: they will still count towards your limit!)\"\n    ),\n    createItems.button(\n      \"reset-all\",\n      \"Reset All Stored Data\",\n      \"Resets preferences, credentials, etc. This action is irreversible! The app will restart after.\",\n      \"danger\",\n      \"solid\",\n      async () => {\n        if(!await confirm(\"Are you sure you want to reset all stored data? This action is irreversible!\")) return;\n        await invoke(\"delete_stored_credentials\");\n        await invoke(\"reset_anisette\");\n\n        let storeInstance = await load(\"preferences.json\");\n        await storeInstance.clear();\n\n        await relaunch();\n      }\n    ),\n  ],\n  {\n    description: \"Internal developer settings\",\n    category: \"advanced\",\n  }\n);\n"
  },
  {
    "path": "src/preferences/pages/general.ts",
    "content": "import { createItems, createPreferencePage } from \"../helpers\";\nimport { getVersion } from \"@tauri-apps/api/app\";\n\nexport const generalPage = createPreferencePage(\n  \"general\",\n  \"General\",\n  [\n    {\n      id: \"app-version\",\n      name: \"App Version\",\n      description: \"The current version of CrossCode.\",\n      type: \"info\",\n      defaultValue: async () => {\n        return await getVersion();\n      },\n    },\n    createItems.select(\n      \"startup\",\n      \"Startup Behavior\",\n      [\n        {\n          label: \"Open last project\",\n          value: \"open-last\",\n        },\n        {\n          label: \"Show welcome page\",\n          value: \"welcome\",\n        },\n      ],\n      \"\",\n      \"open-last\"\n    ),\n    createItems.select(\n      \"check-updates\",\n      \"Check for Updates\",\n      [\n        {\n          label: \"On Startup\",\n          value: \"auto\",\n        },\n        {\n          label: \"Manually\",\n          value: \"manual\",\n        },\n      ],\n      \"\",\n      \"auto\"\n    ),\n  ],\n  {\n    description: \"General application settings\",\n    category: \"general\",\n  }\n);\n"
  },
  {
    "path": "src/preferences/pages/index.ts",
    "content": "import { preferenceRegistry } from \"../registry\";\nimport { PreferenceCategory } from \"../types\";\n\nimport { generalPage } from \"./general\";\nimport { appearancePage } from \"./appearance\";\nimport { appleIdPage } from \"./appleId\";\nimport { certificatesPage } from \"./certificates\";\nimport { appIdsPage } from \"./appIds\";\nimport { developerPage } from \"./developer\";\nimport { swiftPage } from \"./swift\";\nimport { sourceKitPage } from \"./sourcekit\";\n\nconst generalCategory: PreferenceCategory = {\n  id: \"general\",\n  name: \"General\",\n  pages: [generalPage, appearancePage],\n};\n\nconst appleCategory: PreferenceCategory = {\n  id: \"apple\",\n  name: \"Apple\",\n  pages: [appleIdPage, certificatesPage, appIdsPage],\n};\n\nconst swiftCategory: PreferenceCategory = {\n  id: \"swift\",\n  name: \"Swift\",\n  pages: [swiftPage, sourceKitPage],\n};\n\nconst advancedCategory: PreferenceCategory = {\n  id: \"advanced\",\n  name: \"Advanced\",\n  pages: [developerPage],\n};\n\npreferenceRegistry.registerCategory(generalCategory);\npreferenceRegistry.registerCategory(appleCategory);\npreferenceRegistry.registerCategory(swiftCategory);\npreferenceRegistry.registerCategory(advancedCategory);\n\n// In theory, maps should preserve insertion order.\n// However, I couldn't get the advanced category to appear after the swift category for some reason.\n// So now its here.\nconst categoryOrder = [\"general\", \"apple\", \"swift\", \"advanced\"];\n\nexport { preferenceRegistry, categoryOrder };\n"
  },
  {
    "path": "src/preferences/pages/sourcekit.tsx",
    "content": "import { createPreferencePage, createItems } from \"../helpers\";\n\nexport const sourceKitPage = createPreferencePage(\n  \"sourcekit\",\n  \"Language Features\",\n  [\n    createItems.checkbox(\n      \"startup\",\n      \"Auto-Launch SourceKit\",\n      \"Automatically start sourcekit-lsp when you open a project\",\n      true\n    ),\n    createItems.checkbox(\n      \"format\",\n      \"Format on save\",\n      \"Automatically format your code when you save\",\n      true\n    ),\n  ],\n  {\n    description: \"Configure SourceKit-LSP and other language features\",\n    category: \"swift\",\n  }\n);\n"
  },
  {
    "path": "src/preferences/pages/swift.tsx",
    "content": "import { Divider } from \"@mui/joy\";\nimport SDKMenu from \"../../components/SDKMenu\";\nimport SwiftMenu from \"../../components/SwiftMenu\";\nimport { createCustomPreferencePage } from \"../helpers\";\n\nexport const swiftPage = createCustomPreferencePage(\n  \"swift\",\n  \"Swift Setup\",\n  () => (\n    <div\n      style={{\n        display: \"flex\",\n        flexDirection: \"column\",\n        gap: \"var(--padding-md)\",\n      }}\n    >\n      <SwiftMenu />\n      <Divider style={{ marginLeft: \"-20px\" }} />\n      <SDKMenu />\n    </div>\n  ),\n  {\n    description: \"Manage your swift toolchains and Darwin SDK\",\n    category: \"swift\",\n  }\n);\n"
  },
  {
    "path": "src/preferences/registry.ts",
    "content": "import { categoryOrder } from \"./pages\";\nimport { PreferencePage, PreferenceCategory } from \"./types\";\n\nclass PreferenceRegistry {\n  private pages: Map<string, PreferencePage> = new Map();\n  private categories: Map<string, PreferenceCategory> = new Map();\n\n  registerPage(page: PreferencePage) {\n    this.pages.set(page.id, page);\n\n    if (page.category) {\n      if (!this.categories.has(page.category)) {\n        this.categories.set(page.category, {\n          id: page.category,\n          name: page.category,\n          pages: [],\n        });\n      }\n      const category = this.categories.get(page.category)!;\n      if (!category.pages.find((p) => p.id === page.id)) {\n        category.pages.push(page);\n      }\n    }\n  }\n\n  registerCategory(category: PreferenceCategory) {\n    this.categories.set(category.id, category);\n    category.pages.forEach((page) => {\n      page.category = category.id;\n      this.pages.set(page.id, page);\n    });\n  }\n\n  getPage(id: string): PreferencePage | undefined {\n    return this.pages.get(id);\n  }\n\n  getAllPages(): PreferencePage[] {\n    return Array.from(this.pages.values());\n  }\n\n  getAllCategories(): PreferenceCategory[] {\n    return Array.from(this.categories.values()).sort(\n      (a, b) => categoryOrder.indexOf(a.id) - categoryOrder.indexOf(b.id)\n    );\n  }\n}\n\nexport const preferenceRegistry = new PreferenceRegistry();\n"
  },
  {
    "path": "src/preferences/types.ts",
    "content": "export interface PreferenceItem {\n  id: string;\n  name: string;\n  description?: string;\n  type:\n    | \"text\"\n    | \"select\"\n    | \"checkbox\"\n    | \"button\"\n    | \"info\"\n    | \"number\"\n    | \"custom\";\n  options?: Array<{ label: string; value: string, default?: string }>;\n  defaultValue?: any;\n  onChange?: (value: any) => void | Promise<void>;\n  validation?: (value: any) => string | null;\n  customComponent?: React.ComponentType;\n  color?: \"primary\" | \"danger\" | \"neutral\" | \"success\" | \"warning\";\n  variant?: \"solid\" | \"outlined\" | \"soft\" | \"plain\";\n}\n\nexport interface PreferencePage {\n  id: string;\n  name: string;\n  description?: string;\n  icon?: string;\n  category?: string;\n  items?: PreferenceItem[];\n  customComponent?: React.ComponentType;\n  onLoad?: () => void | Promise<void>;\n  onSave?: () => void | Promise<void>;\n}\n\nexport interface PreferenceCategory {\n  id: string;\n  name: string;\n  pages: PreferencePage[];\n}\n"
  },
  {
    "path": "src/styles.css",
    "content": ":root {\n  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;\n  font-size: 16px;\n  line-height: 24px;\n  font-weight: 400;\n\n  color: #0f0f0f;\n  background-color: #f6f6f6;\n\n  font-synthesis: none;\n  text-rendering: optimizeLegibility;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n  -webkit-text-size-adjust: 100%;\n\n  /* Define padding vars */\n  --padding-xs: 5px;\n  --padding-sm: 8px;\n  --padding-md: 10px;\n  --padding-lg: 15px;\n  --padding-xl: 20px;\n}\n\nhtml,\nbody,\n#root,\n.App {\n  height: 100%;\n  margin: 0;\n  padding: 0;\n}\n"
  },
  {
    "path": "src/utilities/Command.tsx",
    "content": "import { Mutex } from \"async-mutex\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { useState, createContext, useContext } from \"react\";\n\nconst commandRunnerMutex = new Mutex();\n\n// Create a context for sharing command state\nconst CommandContext = createContext<{\n  isRunningCommand: boolean;\n  currentCommand: string | null;\n  setIsRunningCommand: React.Dispatch<React.SetStateAction<boolean>>;\n  setCurrentCommand: React.Dispatch<React.SetStateAction<string | null>>;\n} | null>(null);\n\nexport function CommandProvider({ children }: { children: React.ReactNode }) {\n  const [isRunningCommand, setIsRunningCommand] = useState(false);\n  const [currentCommand, setCurrentCommand] = useState<string | null>(null);\n\n  return (\n    <CommandContext.Provider\n      value={{\n        isRunningCommand,\n        currentCommand,\n        setIsRunningCommand,\n        setCurrentCommand,\n      }}\n    >\n      {children}\n    </CommandContext.Provider>\n  );\n}\n\n// Modified hook that returns command functions with the context baked in\nexport function useCommandRunner() {\n  const context = useContext(CommandContext);\n  if (!context) {\n    throw new Error(\"useCommandRunner must be used within a CommandProvider\");\n  }\n\n  const {\n    isRunningCommand,\n    currentCommand,\n    setIsRunningCommand,\n    setCurrentCommand,\n  } = context;\n\n  // Define the run command function inside the hook\n  const runCommand = (\n    command: string,\n    parameters?: Record<string, unknown>\n  ) => {\n    return new Promise<any>(async (resolve) => {\n      const release = await commandRunnerMutex.acquire();\n      setIsRunningCommand(true);\n      setCurrentCommand(command);\n      try {\n        let res = await invoke(command, parameters);\n        resolve(res as any);\n      } finally {\n        release();\n        setIsRunningCommand(false);\n        setCurrentCommand(null);\n      }\n    });\n  };\n\n  // Define the cancel command function inside the hook\n  const cancelCommand = async () => {\n    try {\n      commandRunnerMutex.cancel();\n      commandRunnerMutex.release();\n    } finally {\n      setIsRunningCommand(true);\n      setCurrentCommand(null);\n      // try {\n      //   await invoke(\"cancel_command\");\n      // } finally {\n      setIsRunningCommand(false);\n    }\n    //}\n  };\n\n  return {\n    isRunningCommand,\n    currentCommand,\n    runCommand,\n    cancelCommand,\n  };\n}\n"
  },
  {
    "path": "src/utilities/IDEContext.tsx",
    "content": "// create a context to store a few state values about the system that are checked at startup\nimport React, {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { getCurrentWindow, Window } from \"@tauri-apps/api/window\";\nimport { emit, listen } from \"@tauri-apps/api/event\";\nimport * as dialog from \"@tauri-apps/plugin-dialog\";\nimport { useToast } from \"react-toast-plus\";\nimport { useNavigate } from \"react-router-dom\";\nimport {\n  Button,\n  Checkbox,\n  Input,\n  Modal,\n  ModalDialog,\n  Typography,\n} from \"@mui/joy\";\nimport { useCommandRunner } from \"./Command\";\nimport { StoreContext, useStore } from \"./StoreContext\";\nimport { Operation, OperationState, OperationUpdate } from \"./operations\";\nimport OperationView from \"../components/OperationView\";\nimport { UpdateContext } from \"./UpdateContext\";\nimport { isCompatable } from \"../components/SwiftMenu\";\n\nlet isMainWindow = getCurrentWindow().label === \"main\";\n\nexport interface IDEContextType {\n  initialized: boolean;\n  ready: boolean | null;\n  isWindows: boolean;\n  hasWSL: boolean;\n  hasDarwinSDK: boolean;\n  darwinSDKVersion: string;\n  hasLimitedRam: boolean;\n  toolchains: ListToolchainResponse | null;\n  selectedToolchain: Toolchain | null;\n  devices: DeviceInfo[];\n  openFolderDialog: () => void;\n  consoleLines: string[];\n  setConsoleLines: React.Dispatch<React.SetStateAction<string[]>>;\n  scanToolchains: () => Promise<void>;\n  checkSDK: () => Promise<void>;\n  locateToolchain: () => Promise<void>;\n  startOperation: (\n    operation: Operation,\n    params: { [key: string]: any }\n  ) => Promise<void>;\n  setSelectedToolchain: (\n    value: Toolchain | ((oldValue: Toolchain | null) => Toolchain | null) | null\n  ) => void;\n  selectedDevice: DeviceInfo | null;\n  setSelectedDevice: React.Dispatch<React.SetStateAction<DeviceInfo | null>>;\n  mountDdi: (ask: boolean) => Promise<boolean>;\n  setScreenshot: React.Dispatch<React.SetStateAction<string | null>>;\n  screenshot: string | null;\n}\n\nexport type DeviceInfo = {\n  name: string;\n  id: number;\n  uuid: string;\n};\n\nexport type Toolchain = {\n  version: string;\n  path: string;\n  isSwiftly: boolean;\n};\n\ntype ListToolchainResponseWithSwiftly = {\n  swiftlyInstalled: true;\n  swiftlyVersion: string;\n  toolchains: Toolchain[];\n};\n\ntype ListToolchainResponseWithoutSwiftly = {\n  swiftlyInstalled: false;\n  swiftlyVersion: null;\n  toolchains: Toolchain[];\n};\n\nexport type ListToolchainResponse =\n  | ListToolchainResponseWithSwiftly\n  | ListToolchainResponseWithoutSwiftly;\n\nexport const IDEContext = createContext<IDEContextType | null>(null);\n\nlet hasCheckedForUpdates = false;\n\nexport const IDEProvider: React.FC<{\n  children: React.ReactNode;\n}> = ({ children }) => {\n  const [isWindows, setIsWindows] = useState<boolean>(false);\n  const [hasWSL, setHasWSL] = useState<boolean>(false);\n  const [toolchains, setToolchains] = useState<ListToolchainResponse | null>(\n    null\n  );\n  const [hasDarwinSDK, setHasDarwinSDK] = useState<boolean>(false);\n  const [darwinSDKVersion, setDarwinSDKVersion] = useState<string>(\"none\");\n  const [initialized, setInitialized] = useState(false);\n  const [ready, setReady] = useState<boolean | null>(null);\n  const [devices, setDevices] = useState<DeviceInfo[]>([]);\n  const [consoleLines, setConsoleLines] = useState<string[]>([]);\n  const [selectedToolchain, setSelectedToolchain] = useStore<Toolchain | null>(\n    \"swift/selected-toolchain\",\n    null\n  );\n\n  const [hasLimitedRam, setHasLimitedRam] = useState<boolean>(false);\n\n  const [selectedDevice, setSelectedDevice] = useState<DeviceInfo | null>(null);\n\n  const [ddiOpen, setDdiOpen] = useState(false);\n  const [ddiProgress, setDdiProgress] = useState(0);\n  const [screenshot, setScreenshot] = useState<string | null>(null);\n\n  const { checkForUpdates } = useContext(UpdateContext);\n  const { store, storeInitialized } = useContext(StoreContext);\n\n  const { addToast } = useToast();\n\n  const mountDdi = useCallback(\n    async (ask: boolean): Promise<boolean> => {\n      if (!selectedDevice) {\n        addToast.error(\"No device selected\");\n        return false;\n      }\n      try {\n        if (await invoke<boolean>(\"is_ddi_mounted\", { device: selectedDevice }))\n          return true;\n\n        if (ask) {\n          const result = await dialog.ask(\n            `This will download & mount the developer disk image on ${selectedDevice.name}. This is required for debugging apps. Do you want to continue?`,\n            {\n              title: \"Mount Developer Disk Image\",\n            }\n          );\n          if (!result) {\n            return false;\n          }\n        }\n        setDdiProgress(0);\n        setDdiOpen(true);\n\n        await invoke(\"mount_ddi\", { device: selectedDevice });\n        setDdiOpen(false);\n        return true;\n      } catch (error) {\n        addToast.error(\"Failed to mount DDI: \" + error);\n        console.error(\"Failed to mount DDI:\", error);\n        setDdiOpen(false);\n        return false;\n      }\n    },\n    [selectedDevice]\n  );\n\n  const checkSDK = useCallback(async () => {\n    try {\n      let result = await invoke<string>(\"has_darwin_sdk\", {\n        toolchainPath: selectedToolchain?.path || \"\",\n      });\n      setHasDarwinSDK(result != \"none\");\n      setDarwinSDKVersion(result);\n    } catch (e) {\n      console.error(\"Failed to check for SDK:\", e);\n      setHasDarwinSDK(false);\n      setDarwinSDKVersion(\"none\");\n    }\n  }, [selectedToolchain]);\n\n  const scanToolchains = useCallback(() => {\n    return new Promise<void>(async (resolve) => {\n      let response = await invoke<ListToolchainResponse>(\n        \"get_swiftly_toolchains\"\n      );\n      if (response) {\n        setToolchains(response);\n        resolve();\n      }\n    });\n  }, []);\n\n  const locateToolchain = useCallback(async () => {\n    let path = await dialog.open({\n      directory: true,\n      multiple: false,\n    });\n    if (!path) {\n      addToast.error(\"No path selected\");\n      return;\n    }\n    if (!(await invoke(\"validate_toolchain\", { toolchainPath: path }))) {\n      if (isWindows) {\n        if (path?.startsWith(\"\\\\\\\\wsl.localhost\\\\\")) {\n          path = path.replace(\"\\\\\\\\wsl.localhost\\\\\", \"\\\\\\\\wsl$\\\\\");\n        }\n        path = await invoke<string>(\"linux_path\", {\n          path,\n        });\n        if (!(await invoke(\"validate_toolchain\", { toolchainPath: path }))) {\n          addToast.error(\"Invalid toolchain path\");\n          return;\n        }\n      } else {\n        addToast.error(\"Invalid toolchain path\");\n        return;\n      }\n    }\n    const info = await invoke<Toolchain>(\"get_toolchain_info\", {\n      toolchainPath: path,\n      isSwiftly: false,\n    }).catch((error) => {\n      console.error(\"Error getting toolchain info:\", error);\n      addToast.error(\"Failed to get toolchain info\");\n      return null;\n    });\n    if (!info) {\n      addToast.error(\"Invalid toolchain path or version not found\");\n      return;\n    }\n    if (info) {\n      setSelectedToolchain(info);\n    }\n  }, [isWindows]);\n\n  useEffect(() => {\n    if (!initialized) return setReady(null);\n    if (toolchains !== null && isWindows !== null && hasWSL !== null) {\n      setReady(\n        selectedToolchain !== null &&\n          isCompatable(selectedToolchain) &&\n          (isWindows ? hasWSL : true) &&\n          hasDarwinSDK\n      );\n    } else {\n      setReady(false);\n    }\n  }, [\n    selectedToolchain,\n    toolchains,\n    hasWSL,\n    isWindows,\n    hasDarwinSDK,\n    initialized,\n  ]);\n\n  let startedInitializing = useRef(false);\n\n  useEffect(() => {\n    if (startedInitializing.current) return;\n    startedInitializing.current = true;\n    let initPromises: Promise<void>[] = [];\n    initPromises.push(scanToolchains());\n    initPromises.push(\n      invoke(\"has_wsl\").then((response) => {\n        setHasWSL(response as boolean);\n      })\n    );\n    initPromises.push(\n      invoke(\"is_windows\").then((response) => {\n        setIsWindows(response as boolean);\n      })\n    );\n    initPromises.push(\n      invoke<string>(\"has_darwin_sdk\", {\n        toolchainPath: selectedToolchain?.path ?? \"\",\n      }).then((response) => {\n        setHasDarwinSDK(response != \"none\");\n        setDarwinSDKVersion(response);\n      })\n    );\n    initPromises.push(\n      invoke(\"has_limited_ram\").then((response) => {\n        setHasLimitedRam(response as boolean);\n      })\n    );\n\n    Promise.all(initPromises)\n      .then(() => {\n        setInitialized(true);\n      })\n      .catch((error) => {\n        console.error(\"Error initializing IDE context: \", error);\n        alert(\"An error occurred while initializing the IDE context: \" + error);\n      });\n  }, []);\n\n  useEffect(() => {\n    if (!initialized) return;\n    let changeWindows = async () => {\n      let splash = await Window.getByLabel(\"splashscreen\");\n      let main = await Window.getByLabel(\"main\");\n      if (splash && main) {\n        splash.close();\n        await main.show();\n        main.setFocus();\n      }\n    };\n    changeWindows();\n  }, [initialized]);\n\n  useEffect(() => {\n    if (!store || !storeInitialized || !initialized || !checkForUpdates) return;\n\n    let check = async () => {\n      if (hasCheckedForUpdates) return;\n      if (\n        (await store.has(\"general/check-updates\")) &&\n        (await store.get(\"general/check-updates\")) === \"manual\"\n      )\n        return;\n\n      hasCheckedForUpdates = true;\n      checkForUpdates();\n    };\n\n    check();\n  }, [initialized, checkForUpdates, store, storeInitialized]);\n\n  const listenerAdded = useRef(false);\n  const listener2Added = useRef(false);\n  const listener3Added = useRef(false);\n  const unlisten = useRef<() => void>(() => {});\n  const unlisten2fa = useRef<() => void>(() => {});\n  const unlistenAppleid = useRef<() => void>(() => {});\n\n  const [tfaOpen, setTfaOpen] = useState(false);\n  const tfaInput = useRef<HTMLInputElement | null>(null);\n  const [appleIdOpen, setAppleIdOpen] = useState(false);\n  const appleIdInput = useRef<HTMLInputElement | null>(null);\n  const applePassInput = useRef<HTMLInputElement | null>(null);\n  const saveCredentials = useRef<HTMLInputElement | null>(null);\n\n  useEffect(() => {\n    if (!listenerAdded.current) {\n      (async () => {\n        const unlistenFn = await listen(\"idevices\", (event) => {\n          let devices = event.payload as DeviceInfo[];\n          setDevices(devices);\n          if (devices.length === 0) {\n            addToast.info(\"No devices found\");\n          }\n        });\n        unlisten.current = unlistenFn;\n      })();\n      listenerAdded.current = true;\n    }\n    return () => {\n      unlisten.current();\n    };\n  }, []);\n\n  useEffect(() => {\n    if (!listener2Added.current) {\n      (async () => {\n        const unlistenFn = await listen(\"2fa-required\", async () => {\n          if (isMainWindow) {\n            setTfaOpen(true);\n          } else {\n            addToast.info(\"Please complete 2FA in the main window.\");\n          }\n        });\n        unlisten2fa.current = unlistenFn;\n      })();\n      listener2Added.current = true;\n    }\n    return () => {\n      unlisten2fa.current();\n    };\n  }, []);\n\n  useEffect(() => {\n    if (!listener3Added.current) {\n      (async () => {\n        const unlistenFn = await listen(\"apple-id-required\", () => {\n          if (isMainWindow) {\n            setAppleIdOpen(true);\n          } else {\n            addToast.info(\"Please login to your Apple ID in the main window.\");\n          }\n        });\n        unlistenAppleid.current = unlistenFn;\n      })();\n      listener3Added.current = true;\n    }\n    return () => {\n      unlistenAppleid.current();\n    };\n  }, []);\n\n  const ddiListenerAdded = useRef(false);\n  const ddiUnlisten = useRef<() => void>(() => {});\n\n  useEffect(() => {\n    if (!ddiListenerAdded.current) {\n      (async () => {\n        const unlistenFn = await listen(\"ddi-mount-progress\", (event) => {\n          const progress = event.payload as number;\n          setDdiProgress(progress);\n        });\n        ddiUnlisten.current = unlistenFn;\n      })();\n      ddiListenerAdded.current = true;\n    }\n    return () => {\n      ddiUnlisten.current();\n    };\n  }, [setDdiProgress]);\n\n  const navigate = useNavigate();\n\n  const openFolderDialog = useCallback(async () => {\n    const path = await dialog.open({\n      directory: true,\n      multiple: false,\n    });\n    if (path) {\n      navigate(\"/ide/\" + encodeURIComponent(path));\n    }\n  }, []);\n\n  const { cancelCommand } = useCommandRunner();\n\n  const [operationState, setOperationState] = useState<OperationState | null>(\n    null\n  );\n\n  const startOperation = useCallback(\n    async (\n      operation: Operation,\n      params: { [key: string]: any }\n    ): Promise<void> => {\n      setOperationState({\n        current: operation,\n        started: [],\n        failed: [],\n        completed: [],\n      });\n      return new Promise<void>(async (resolve, reject) => {\n        const unlistenFn = await listen<OperationUpdate>(\n          \"operation_\" + operation.id,\n          (event) => {\n            setOperationState((old) => {\n              if (old == null) return null;\n              if (event.payload.updateType === \"started\") {\n                return {\n                  ...old,\n                  started: [...old.started, event.payload.stepId],\n                };\n              } else if (event.payload.updateType === \"finished\") {\n                return {\n                  ...old,\n                  completed: [...old.completed, event.payload.stepId],\n                };\n              } else if (event.payload.updateType === \"failed\") {\n                return {\n                  ...old,\n                  failed: [\n                    ...old.failed,\n                    {\n                      stepId: event.payload.stepId,\n                      extraDetails: event.payload.extraDetails,\n                    },\n                  ],\n                };\n              }\n              return old;\n            });\n          }\n        );\n        try {\n          await invoke(operation.id + \"_operation\", params);\n          unlistenFn();\n          resolve();\n        } catch (e) {\n          unlistenFn();\n          reject(e);\n        }\n      });\n    },\n    [setOperationState]\n  );\n\n  const contextValue = useMemo(\n    () => ({\n      isWindows,\n      hasWSL,\n      toolchains,\n      initialized,\n      devices,\n      openFolderDialog,\n      consoleLines,\n      setConsoleLines,\n      selectedToolchain,\n      scanToolchains,\n      locateToolchain,\n      setSelectedToolchain,\n      hasDarwinSDK,\n      checkSDK,\n      startOperation,\n      hasLimitedRam,\n      selectedDevice,\n      setSelectedDevice,\n      mountDdi,\n      ready,\n      darwinSDKVersion,\n      screenshot,\n      setScreenshot,\n    }),\n    [\n      isWindows,\n      hasWSL,\n      toolchains,\n      initialized,\n      devices,\n      openFolderDialog,\n      consoleLines,\n      setConsoleLines,\n      selectedToolchain,\n      scanToolchains,\n      locateToolchain,\n      setSelectedToolchain,\n      hasDarwinSDK,\n      checkSDK,\n      startOperation,\n      hasLimitedRam,\n      selectedDevice,\n      setSelectedDevice,\n      mountDdi,\n      ready,\n      darwinSDKVersion,\n      screenshot,\n      setScreenshot,\n    ]\n  );\n\n  return (\n    <IDEContext.Provider value={contextValue}>\n      {children}\n      <Modal\n        open={tfaOpen}\n        onClose={() => {\n          if (!tfaInput.current?.value) {\n            addToast.error(\"Please enter a 2FA code\");\n            return;\n          }\n          emit(\"2fa-recieved\", tfaInput.current?.value || \"\");\n          setTfaOpen(false);\n        }}\n      >\n        <ModalDialog>\n          <Typography level=\"body-md\">\n            A two-factor authentication code has been sent, please enter it\n            below.\n          </Typography>\n          <form\n            onSubmit={() => {\n              if (!tfaInput.current?.value) {\n                addToast.error(\"Please enter a 2FA code\");\n                return;\n              }\n              emit(\"2fa-recieved\", tfaInput.current?.value || \"\");\n              setTfaOpen(false);\n              tfaInput.current!.value = \"\"; // Clear the input after submission\n              return false; // Prevent form submission\n            }}\n          >\n            <Input type=\"number\" slotProps={{ input: { ref: tfaInput } }} />\n            <Button\n              variant=\"soft\"\n              sx={{\n                margin: \"10px 0\",\n                width: \"100%\",\n              }}\n              type=\"submit\"\n            >\n              Submit\n            </Button>\n          </form>\n        </ModalDialog>\n      </Modal>\n      <Modal\n        open={appleIdOpen}\n        onClose={() => {\n          setAppleIdOpen(false);\n          appleIdInput.current!.value = \"\";\n          applePassInput.current!.value = \"\";\n          emit(\"login-cancelled\");\n          cancelCommand();\n        }}\n      >\n        <ModalDialog>\n          <Typography level=\"body-md\">\n            Login with your apple account to continue\n          </Typography>\n          <Typography level=\"body-xs\">\n            Your credentials will only be sent to apple. In general, never trust\n            a third-party app with your Apple ID. We recommend using a burner\n            account with CrossCode and other sideloaders. (CrossCode is not very\n            secure)\n          </Typography>\n          <form\n            onSubmit={() => {\n              if (\n                appleIdInput.current?.value &&\n                applePassInput.current?.value\n              ) {\n                setAppleIdOpen(false);\n                emit(\"apple-id-recieved\", {\n                  appleId: appleIdInput.current.value,\n                  applePass: applePassInput.current.value,\n                  saveCredentials: saveCredentials.current?.checked || false,\n                });\n              } else {\n                addToast.error(\"Please enter your Apple ID and password\");\n              }\n              return false;\n            }}\n          >\n            <Input\n              type=\"text\"\n              slotProps={{ input: { ref: appleIdInput } }}\n              placeholder=\"Apple ID\"\n              sx={{ marginBottom: \"var(--padding-sm)\" }}\n            />\n            <Input\n              type=\"password\"\n              slotProps={{ input: { ref: applePassInput } }}\n              placeholder=\"Password\"\n            />\n            <Checkbox\n              slotProps={{ input: { ref: saveCredentials } }}\n              sx={{ marginTop: \"var(--padding-sm)\", color: \"grey\" }}\n              label=\"Remember credentials\"\n              size=\"sm\"\n            />\n            <Button\n              variant=\"soft\"\n              sx={{\n                margin: \"var(--padding-md) 0\",\n                width: \"100%\",\n                marginBottom: \"0\",\n              }}\n              type=\"submit\"\n            >\n              Submit\n            </Button>\n            <Button\n              variant=\"soft\"\n              sx={{\n                margin: \"var(--padding-md) 0\",\n                width: \"100%\",\n                marginBottom: \"0\",\n              }}\n              onClick={() => {\n                setAppleIdOpen(false);\n                appleIdInput.current!.value = \"\";\n                applePassInput.current!.value = \"\";\n                emit(\"login-cancelled\");\n                cancelCommand();\n              }}\n              color=\"neutral\"\n            >\n              Cancel\n            </Button>\n          </form>\n        </ModalDialog>\n      </Modal>\n      <Modal open={ddiOpen}>\n        <ModalDialog>\n          <Typography level=\"h4\">Mounting Developer Disk Image...</Typography>\n          <Typography level=\"body-md\">\n            This may take a few minutes. Please do not disconnect your device or\n            close the app.\n          </Typography>\n          <Typography level=\"body-sm\">\n            Progress: {ddiProgress.toFixed(2)}%\n          </Typography>\n        </ModalDialog>\n      </Modal>\n      {operationState && (\n        <OperationView\n          operationState={operationState}\n          closeMenu={() => {\n            setOperationState(null);\n          }}\n        />\n      )}\n    </IDEContext.Provider>\n  );\n};\n\nexport const useIDE = () => {\n  const context = React.useContext(IDEContext);\n  if (!context) {\n    throw new Error(\"useIDEContext must be used within an IDEContextProvider\");\n  }\n  return context;\n};\n"
  },
  {
    "path": "src/utilities/Shortcut.tsx",
    "content": "import { IKeyboardEvent, KeyCode } from \"monaco-editor\";\n\nexport type Accelerator = \"ctrl\" | \"alt\" | \"shift\" | \"super\";\n\nexport class Shortcut {\n  accelerators: Accelerator[];\n  key: string;\n  monacoKey: KeyCode;\n\n  ctrl = false;\n  alt = false;\n  shift = false;\n  super = false;\n\n  constructor(accelerator: Accelerator[], key: string) {\n    this.accelerators = accelerator;\n    for (const acc of accelerator) {\n      if (acc === \"ctrl\") this.ctrl = true;\n      if (acc === \"alt\") this.alt = true;\n      if (acc === \"shift\") this.shift = true;\n      if (acc === \"super\") this.super = true;\n    }\n    this.key = key;\n    this.monacoKey =\n      KeyCode[`Key${key.toUpperCase()}` as keyof typeof KeyCode] ||\n      KeyCode[key.toUpperCase() as keyof typeof KeyCode];\n  }\n\n  static fromString(shortcut: string): Shortcut {\n    if (!shortcut) throw new Error(\"Shortcut string is empty\");\n    if (!shortcut.includes(\"+\")) throw new Error(\"Shortcut string is invalid\");\n    const [key, ...accelerators] = shortcut.toLowerCase().split(\"+\").reverse();\n    if (accelerators.length === 0)\n      throw new Error(\"Shortcut string is invalid\");\n    return new Shortcut(accelerators as Accelerator[], key.toLowerCase());\n  }\n\n  toString(): string {\n    return [...this.accelerators, this.key.toUpperCase()].join(\"+\");\n  }\n\n  pressed(event: KeyboardEvent): boolean {\n    return (\n      this.ctrl === event.ctrlKey &&\n      this.alt === event.altKey &&\n      this.shift === event.shiftKey &&\n      this.super === event.metaKey &&\n      event.key.toLowerCase() === this.key\n    );\n  }\n\n  pressedMonaco(event: IKeyboardEvent): boolean {\n    return (\n      this.ctrl === event.ctrlKey &&\n      this.alt === event.altKey &&\n      this.shift === event.shiftKey &&\n      this.super === event.metaKey &&\n      event.keyCode === this.monacoKey\n    );\n  }\n}\n\nexport function acceleratorPresssed(event: KeyboardEvent): boolean {\n  return event.ctrlKey || event.altKey || event.shiftKey || event.metaKey;\n}\n\nexport function acceleratorPresssedMonaco(event: IKeyboardEvent): boolean {\n  return event.ctrlKey || event.altKey || event.shiftKey || event.metaKey;\n}\n"
  },
  {
    "path": "src/utilities/StoreContext.tsx",
    "content": "import React, {\n  createContext,\n  useContext,\n  useState,\n  useEffect,\n  useCallback,\n  useMemo,\n} from \"react\";\nimport { load, Store } from \"@tauri-apps/plugin-store\";\nimport { emit, listen } from \"@tauri-apps/api/event\";\nimport { setTheme } from \"@tauri-apps/api/app\";\nimport { useColorScheme } from \"@mui/joy\";\n\nexport const StoreContext = createContext<{\n  storeValues: { [key: string]: any };\n  setStoreValue: (key: string, value: any) => void;\n  store: Store | null;\n  storeInitialized: boolean;\n}>({\n  storeValues: {},\n  setStoreValue: () => {},\n  store: null,\n  storeInitialized: false,\n});\n\nexport const StoreProvider: React.FC<{ children: React.ReactNode }> = ({\n  children,\n}) => {\n  const [storeValues, setStoreValues] = useState<{ [key: string]: any }>({});\n  const [store, setStore] = useState<Store | null>(null);\n  const [storeInitialized, setStoreInitialized] = useState(false);\n  const { setMode } = useColorScheme();\n\n  useEffect(() => {\n    const initializeStore = async () => {\n      const storeInstance = await load(\"preferences.json\");\n      setStore(storeInstance);\n\n      let theme = await storeInstance.get(\"appearance/theme\");\n      if (theme === undefined) theme = \"dark\";\n      await setTheme(theme as \"light\" | \"dark\");\n      setMode(theme as \"light\" | \"dark\");\n\n      storeInstance.set(\"isCrossCodePrefs\", true);\n\n      const keys = await storeInstance.keys();\n      const values: { [key: string]: any } = {};\n      for (const key of keys) {\n        values[key] = await storeInstance.get(key);\n      }\n      setStoreValues(values);\n      setStoreInitialized(true);\n    };\n\n    initializeStore();\n  }, []);\n\n  useEffect(() => {\n    // Listen for store changes from other windows\n    const unlisten = listen<{ key: string; value: any }>(\n      \"store-value-changed\",\n      (event) => {\n        const { key, value } = event.payload;\n        // Update local state without triggering another event\n        setStoreValues((prev) => ({ ...prev, [key]: value }));\n      }\n    );\n\n    return () => {\n      unlisten.then((unlistenFn) => unlistenFn());\n    };\n  }, []);\n\n  const setStoreValue = useCallback(\n    async (key: string, value: any) => {\n      if (!store) return;\n\n      setStoreValues((prevValues) => {\n        const newValues = { ...prevValues, [key]: value };\n        return newValues;\n      });\n\n      await store.set(key, value);\n      await store.save();\n\n      // Emit event to notify other windows\n      emit(\"store-value-changed\", { key, value });\n    },\n    [store]\n  );\n\n  const contextValue = useMemo(\n    () => ({ storeValues, setStoreValue, store, storeInitialized }),\n    [storeValues, setStoreValue, store]\n  );\n\n  if (!store || !storeInitialized) {\n    return null;\n  }\n\n  return (\n    <StoreContext.Provider value={contextValue}>\n      {children}\n    </StoreContext.Provider>\n  );\n};\n\nexport const useStore = <T,>(\n  key: string,\n  initialValue: T\n): [T, (value: T | ((oldValue: T) => T)) => void, boolean] => {\n  const { storeValues, setStoreValue, storeInitialized } =\n    useContext(StoreContext);\n  const [value, setValue] = useState<T>(storeValues[key] ?? initialValue);\n\n  // Prevent infinite update loops\n  useEffect(() => {\n    if (storeValues[key] !== undefined && storeValues[key] !== value) {\n      setValue(storeValues[key]);\n    }\n  }, [storeValues, key]);\n\n  const setStoredValue = useCallback(\n    (newValue: T | ((oldValue: T) => T)) => {\n      const valueToStore =\n        typeof newValue === \"function\"\n          ? (newValue as (oldValue: T) => T)(value)\n          : newValue;\n      setValue(valueToStore);\n      setStoreValue(key, valueToStore);\n    },\n    [key, setStoreValue, value]\n  );\n\n  return [value, setStoredValue, storeInitialized];\n};\n"
  },
  {
    "path": "src/utilities/TauriFileSystemProvider.ts",
    "content": "import {\n  Disposable,\n  IDisposable,\n} from \"@codingame/monaco-vscode-api/vscode/vs/base/common/lifecycle\";\nimport { URI } from \"@codingame/monaco-vscode-api/vscode/vs/base/common/uri\";\nimport {\n  FileChangeType,\n  FileSystemProviderCapabilities,\n  FileType,\n  IFileChange,\n  IFileDeleteOptions,\n  IFileOverwriteOptions,\n  IFileSystemProviderWithFileReadWriteCapability,\n  IFileWriteOptions,\n  IStat,\n  IWatchOptions,\n} from \"@codingame/monaco-vscode-files-service-override\";\nimport {\n  Emitter,\n  Event,\n} from \"@codingame/monaco-vscode-api/vscode/vs/base/common/event\";\nimport * as fs from \"@tauri-apps/plugin-fs\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { platform } from \"@tauri-apps/plugin-os\";\n\nexport default class TauriFileSystemProvider\n  extends Disposable\n  implements IFileSystemProviderWithFileReadWriteCapability\n{\n  private _onDidChangeFile: Emitter<readonly IFileChange[]>;\n\n  capabilities: FileSystemProviderCapabilities;\n  onDidChangeCapabilities: Event<void>;\n  onDidChangeFile: Event<readonly IFileChange[]>;\n  onDidWatchError?: Event<string> | undefined;\n\n  constructor(readonly: boolean) {\n    super();\n    this.onDidChangeCapabilities = Event.None;\n    this._onDidChangeFile = new Emitter();\n    this.onDidChangeFile = this._onDidChangeFile.event;\n    this.capabilities =\n      FileSystemProviderCapabilities.FileReadWrite |\n      FileSystemProviderCapabilities.PathCaseSensitive;\n    if (readonly) {\n      this.capabilities |= FileSystemProviderCapabilities.Readonly;\n    }\n  }\n  async readFile(resource: URI): Promise<Uint8Array> {\n    return await fs.readFile(await this.path(resource));\n  }\n  async writeFile(resource: URI, content: Uint8Array, opts: IFileWriteOptions) {\n    await fs.writeFile(await this.path(resource), content, {\n      create: opts.create,\n      createNew: !opts.overwrite,\n    });\n    this._onDidChangeFile.fire([\n      {\n        type: opts.create ? FileChangeType.ADDED : FileChangeType.UPDATED,\n        resource,\n      },\n    ]);\n  }\n\n  async stat(resource: URI): Promise<IStat> {\n    let stat = await fs.stat(await this.path(resource));\n    let type = stat.isFile ? FileType.File : FileType.Directory;\n    if (stat.isSymlink) {\n      type = FileType.SymbolicLink;\n    }\n    let ctime = stat.birthtime?.getMilliseconds() || 0;\n    let mtime = stat.mtime?.getMilliseconds() || 0;\n    return {\n      type,\n      ctime,\n      mtime,\n      size: stat.size,\n    };\n  }\n\n  watch(resource: URI, opts: IWatchOptions): IDisposable {\n    let disposed = false;\n    (async () => {\n      fs.watchImmediate(\n        await this.path(resource),\n        () => {\n          if (!disposed) {\n            // TODO: Exclude files based on opts.excludes and look into how recursive watch actually works\n            this._onDidChangeFile.fire([\n              {\n                type: FileChangeType.UPDATED,\n                resource,\n              },\n            ]);\n          }\n        },\n        {\n          recursive: opts.recursive,\n        }\n      ).then((unwatch) => {\n        if (disposed) {\n          unwatch();\n        }\n        (disposable as any)._unwatch = unwatch;\n      });\n    })();\n\n    const disposable: IDisposable = {\n      dispose: () => {\n        disposed = true;\n        if ((disposable as any)._unwatch) {\n          (disposable as any)._unwatch();\n        }\n      },\n    };\n    return disposable;\n  }\n\n  // TODO: Implement remaining methods\n  // @ts-ignore\n  mkdir(resource: URI): Promise<void> {\n    throw new Error(\"Mkdir not implemented.\");\n  }\n\n  // @ts-ignore\n  readdir(resource: URI): Promise<[string, FileType][]> {\n    throw new Error(\"Readdir not implemented.\");\n  }\n\n  // @ts-ignore\n  delete(resource: URI, opts: IFileDeleteOptions): Promise<void> {\n    throw new Error(\"Delete not implemented.\");\n  }\n\n  // @ts-ignore\n  rename(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void> {\n    throw new Error(\"Rename not implemented.\");\n  }\n\n  private async path(resource: URI): Promise<string> {\n    if (platform() === \"windows\") {\n      return await invoke<string>(\"windows_path\", { path: resource.path });\n    }\n    return resource.fsPath;\n  }\n}\n"
  },
  {
    "path": "src/utilities/UpdateContext.tsx",
    "content": "import { createContext, useCallback, useContext } from \"react\";\nimport { StoreContext } from \"./StoreContext\";\nimport { check } from \"@tauri-apps/plugin-updater\";\nimport { getVersion } from \"@tauri-apps/api/app\";\nimport { relaunch } from \"@tauri-apps/plugin-process\";\nimport * as dialog from \"@tauri-apps/plugin-dialog\";\nimport { useToast } from \"react-toast-plus\";\n\nexport interface UpdateContextType {\n  checkForUpdates: () => Promise<void>;\n}\n\nexport const UpdateContext = createContext<UpdateContextType>({\n  checkForUpdates: async () => {},\n});\n\nexport const UpdateProvider: React.FC<{ children: React.ReactNode }> = ({\n  children,\n}) => {\n  const { store, storeInitialized } = useContext(StoreContext);\n  const { addToast } = useToast();\n\n  const checkForUpdates = useCallback(async () => {\n    const update = await check();\n    if (!update) return;\n\n    let shouldUpdate = await dialog.ask(\n      \"A new update (\" +\n        (await getVersion()) +\n        \" -> \" +\n        update.version +\n        \") is available. Would you like to install it?\",\n      {\n        title: \"Update Available\",\n      }\n    );\n\n    if (!shouldUpdate) return;\n\n    let downloadPromise = update.download();\n\n    addToast.promise(downloadPromise, {\n      pending: \"Downloading update...\",\n      success: \"Update downloaded\",\n      error: \"Failed to download update\",\n    });\n\n    await downloadPromise;\n\n    let installPromise = update.install();\n    addToast.promise(installPromise, {\n      pending: \"Installing update...\",\n      success: \"Update installed\",\n      error: \"Failed to install update\",\n    });\n    await installPromise;\n\n    const shouldRelaunch = await dialog.ask(\n      \"The update has been installed. Would you like to relaunch the application?\",\n      {\n        title: \"Relaunch Required\",\n      }\n    );\n\n    if (shouldRelaunch) {\n      await relaunch();\n    }\n  }, [store, storeInitialized, addToast]);\n\n  return (\n    <UpdateContext.Provider value={{ checkForUpdates }}>\n      {children}\n    </UpdateContext.Provider>\n  );\n};\n"
  },
  {
    "path": "src/utilities/constants.ts",
    "content": "export const SWIFT_VERSION_PREFIX = \"6.2\";\nexport const DARWIN_SDK_VERSION = \"26.0\";\n"
  },
  {
    "path": "src/utilities/lsp-client.ts",
    "content": "// https://github.com/CodinGame/monaco-vscode-api/wiki/Getting-started-guide\n\n// lsp-client.ts\nimport {\n  WebSocketMessageReader,\n  WebSocketMessageWriter,\n  toSocket,\n} from \"vscode-ws-jsonrpc\";\nimport {\n  CloseAction,\n  ErrorAction,\n  MessageTransports,\n} from \"vscode-languageclient/browser.js\";\nimport { MonacoLanguageClient } from \"monaco-languageclient\";\nimport { Toolchain } from \"./IDEContext\";\nimport { invoke } from \"@tauri-apps/api/core\";\nimport { Uri } from \"monaco-editor\";\n\nexport const initWebSocketAndStartClient = async (\n  url: string,\n  folder: string\n): Promise<WebSocket> => {\n  let workspaceFolder = await invoke<string>(\"linux_path\", { path: folder });\n  const webSocket = new WebSocket(url);\n  webSocket.onopen = () => {\n    const socket = toSocket(webSocket);\n    const reader = new WebSocketMessageReader(socket);\n    const writer = new WebSocketMessageWriter(socket);\n\n    const languageClient = createLanguageClient(\n      {\n        reader,\n        writer,\n      },\n      workspaceFolder\n    );\n    languageClient.start();\n    reader.onClose(() => languageClient.stop());\n  };\n  return webSocket;\n};\nconst createLanguageClient = (\n  messageTransports: MessageTransports,\n  folder: string\n): MonacoLanguageClient => {\n  return new MonacoLanguageClient({\n    name: \"Swift Language Client\",\n    clientOptions: {\n      documentSelector: [\"swift\", \"c\", \"cpp\", \"h\", \"hpp\", \"m\", \"mm\"],\n      workspaceFolder: { uri: Uri.file(folder), name: folder, index: 0 },\n      errorHandler: {\n        error: () => ({ action: ErrorAction.Continue }),\n        closed: () => ({ action: CloseAction.DoNotRestart }),\n      },\n      initializationOptions: {\n        swiftPM: {\n          swiftSDK: \"arm64-apple-ios\",\n        },\n      },\n      middleware: {\n        workspace: {\n          configuration: () => {\n            return [\n              {\n                swiftPM: {\n                  swiftSDK: \"arm64-apple-ios\",\n                },\n              },\n            ];\n          },\n        },\n      },\n    },\n    messageTransports,\n  });\n};\n\nexport const restartServer = async (\n  path: string,\n  selectedToolchain: Toolchain\n) => {\n  // this has been replaced with the middleware above\n  // await invoke(\"ensure_lsp_config\", {\n  //   projectPath: path || \"\",\n  // });\n  try {\n    await invoke<number>(\"stop_sourcekit_server\");\n  } catch (e) {\n    void e;\n  }\n  let port = await invoke<number>(\"start_sourcekit_server\", {\n    toolchainPath: selectedToolchain?.path ?? \"\",\n    folder: path || \"\",\n  });\n  await initWebSocketAndStartClient(`ws://localhost:${port}`, path || \"\");\n};\n"
  },
  {
    "path": "src/utilities/operations.ts",
    "content": "export type Operation = {\n  id: string;\n  title: string;\n  steps: OperationStep[];\n};\n\nexport type OperationStep = {\n  id: string;\n  title: string;\n};\n\nexport type OperationState = {\n  current: Operation;\n  completed: string[];\n  started: string[];\n  failed: {\n    stepId: string;\n    extraDetails: string;\n  }[];\n};\n\ntype OperationInfoUpdate = {\n  updateType: \"started\" | \"finished\";\n  stepId: string;\n};\n\ntype OperationFailedUpdate = {\n  updateType: \"failed\";\n  stepId: string;\n  extraDetails: string;\n};\n\nexport type OperationUpdate = OperationInfoUpdate | OperationFailedUpdate;\n\nexport const installSdkOperation: Operation = {\n  id: \"install_sdk\",\n  title: \"Installing Darwin SDK\",\n  steps: [\n    {\n      id: \"create_stage\",\n      title: \"Create Stage\",\n    },\n    {\n      id: \"install_toolset\",\n      title: \"Download & Install toolset\",\n    },\n    {\n      id: \"extract_xip\",\n      title: \"Extract Xcode.xip\",\n    },\n    {\n      id: \"copy_files\",\n      title: \"Move Files\",\n    },\n    {\n      id: \"write_metadata\",\n      title: \"Write Metadata\",\n    },\n    {\n      id: \"install_sdk\",\n      title: \"Install SDK\",\n    },\n    {\n      id: \"cleanup\",\n      title: \"Clean Up\",\n    },\n  ],\n};\n"
  },
  {
    "path": "src/utilities/templates.ts",
    "content": "import swiftui from \"../assets/swiftui.png\";\nimport uikit from \"../assets/uikit.png\";\n\nexport interface TemplateField {\n  type: string;\n  label: string;\n  default: string;\n}\n\nexport interface Template {\n  name: string;\n  description: string;\n  id: string;\n  image?: string;\n  version: string;\n  fields: {\n    [key: string]: TemplateField;\n  };\n}\n\nconst defaultFields = {\n  projectName: {\n    type: \"text\",\n    label: \"Project Name\",\n    default: \"MyProject\",\n  },\n  bundleId: {\n    type: \"text\",\n    label: \"Bundle Identifier\",\n    default: \"com.example.myproject\",\n  },\n};\n\nexport const templates: Template[] = [\n  {\n    name: \"Basic SwiftUI Application\",\n    description: \"A barebones SwiftUI template to get you started quickly\",\n    image: swiftui,\n    id: \"swiftui\",\n    version: \"1.0.0\",\n    fields: {\n      ...defaultFields,\n    },\n  },\n  {\n    name: \"Basic UIKit Application\",\n    description: \"A barebones UIKit template to get you started quickly\",\n    image: uikit,\n    id: \"uikit\",\n    version: \"1.0.0\",\n    fields: {\n      ...defaultFields,\n    },\n  },\n];\n"
  },
  {
    "path": "src/vite-env.d.ts",
    "content": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "src-tauri/.gitignore",
    "content": "# Generated by Cargo\n# will have compiled files and executables\n/target/\n\n# Generated by Tauri\n# will have schema files for capabilities auto-completion\n/gen/schemas\n"
  },
  {
    "path": "src-tauri/Cargo.toml",
    "content": "[package]\nname = \"crosscode\"\nversion = \"0.0.5\"\ndescription = \"Cross platform iOS IDE\"\nauthors = [\"nab138\"]\nedition = \"2021\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[build-dependencies]\ntauri-build = { version = \"2.4.0\", features = [] }\n\n[dependencies]\ntauri = { version = \"2.8.3\", features = [\"devtools\"] }\nserde = { version = \"1\", features = [\"derive\"] }\nserde_json = \"1\"\ntauri-plugin-shell = \"2.3.0\"\ntauri-plugin-fs = { version = \"2.4.2\", features= [\"watch\"] }\ntauri-plugin-dialog = \"2.4.0\"\ntauri-plugin-store = \"2.4.0\"\ntauri-plugin-opener = \"2.5.0\"\ntauri-plugin-os = \"2.3.1\"\ntauri-plugin-process = \"2.3.0\"\nidevice = { version = \"0.1.47\", features = [\"usbmuxd\", \"syslog_relay\", \"core_device_proxy\", \"tunnel_tcp_stack\", \"rsd\", \"core_device\", \"dvt\", \"mobile_image_mounter\", \"tss\", \"ring\"], default-features = false}\nfutures = \"0.3.31\"\nkeyring = \"2\"\nonce_cell = \"1.21.3\"\nzip = { version = \"4.5\", default-features = false, features = [\"deflate\"] }\nisideload = { version = \"0.1.17\", features = [\"vendored-openssl\"] }\nwalkdir = \"2.5.0\"\ndircpy = \"0.3.19\"\ntar = \"0.4.44\"\nreqwest = \"0.12.23\"\nflate2 = \"1.1.2\"\nregex = \"1\"\ntoml = \"0.9.5\"\ntokio = { version = \"1.47.1\", features = [\"process\"] }\nfutures-util = \"0.3.31\"\nsysinfo = \"0.37.0\"\ntokio-util = \"0.7.16\"\nimage = \"0.25.6\"\nunxip-rs = \"0.1.1\"\ntokio-tungstenite = \"0.28.0\"\nfix-path-env = { git = \"https://github.com/tauri-apps/fix-path-env-rs\" }\n\n[target.'cfg(unix)'.dependencies]\nsdkmover = { path = \"../sdkmover\" }\n\n[features]\n# This feature is used for production builds or when a dev server is not specified, DO NOT REMOVE!!\ncustom-protocol = [\"tauri/custom-protocol\"]\n\n[target.'cfg(not(any(target_os = \"android\", target_os = \"ios\")))'.dependencies]\ntauri-plugin-cli = \"2.4.0\"\ntauri-plugin-updater = \"2.9.0\"\n"
  },
  {
    "path": "src-tauri/build.rs",
    "content": "fn main() {\n    tauri_build::build()\n}\n"
  },
  {
    "path": "src-tauri/capabilities/desktop.json",
    "content": "{\n  \"identifier\": \"desktop-capability\",\n  \"platforms\": [\n    \"macOS\",\n    \"windows\",\n    \"linux\"\n  ],\n  \"windows\": [\n    \"main\"\n  ],\n  \"permissions\": [\n    \"cli:default\",\n    \"updater:default\"\n  ]\n}"
  },
  {
    "path": "src-tauri/capabilities/migrated.json",
    "content": "{\n  \"identifier\": \"migrated\",\n  \"description\": \"permissions that were migrated from v1\",\n  \"local\": true,\n  \"windows\": [\"main\", \"prefs\", \"splashscreen\", \"about\"],\n  \"permissions\": [\n    \"core:default\",\n    \"core:window:allow-show\",\n    \"core:window:allow-center\",\n    \"core:window:allow-create\",\n    \"core:window:allow-set-focus\",\n    \"core:window:allow-set-title\",\n    \"core:app:allow-set-app-theme\",\n    \"core:window:allow-close\",\n    \"core:webview:allow-create-webview-window\",\n    \"fs:allow-read-file\",\n    \"fs:allow-write-file\",\n    \"fs:allow-write-text-file\",\n    \"fs:allow-read-dir\",\n    \"fs:allow-copy-file\",\n    \"fs:allow-mkdir\",\n    \"fs:allow-remove\",\n    \"fs:allow-remove\",\n    \"fs:allow-rename\",\n    \"fs:allow-exists\",\n    \"fs:allow-stat\",\n    \"fs:allow-watch\",\n    {\n      \"identifier\": \"fs:scope\",\n      \"allow\": [\"**\", \".*\", \"**/.*\"],\n      \"requireLiteralLeadingDot\": false\n    },\n    \"shell:allow-open\",\n    \"dialog:allow-open\",\n    \"dialog:allow-save\",\n    \"shell:default\",\n    \"fs:default\",\n    \"dialog:default\",\n    \"store:default\",\n    \"opener:default\",\n    {\n      \"identifier\": \"opener:allow-reveal-item-in-dir\",\n      \"allow\": [\n        {\n          \"path\": \"**\"\n        },\n        {\n          \"path\": \".*\"\n        },\n        {\n          \"path\": \"**/.*\"\n        }\n      ]\n    },\n    \"os:default\",\n    \"process:allow-restart\"\n  ]\n}\n"
  },
  {
    "path": "src-tauri/src/builder/config.rs",
    "content": "use std::path::PathBuf;\n\nuse serde::{Deserialize, Serialize};\n\nuse crate::builder::swift::SwiftBin;\n\npub const FORMAT_VERSION: u32 = 1;\n\npub struct BuildSettings {\n    pub debug: bool,\n}\n\n// TODO: Min ios version, etc.\npub struct ProjectConfig {\n    pub product: String,\n    pub version_num: String,\n    pub version_string: String,\n    pub bundle_id: String,\n    pub project_path: PathBuf,\n}\n\n#[derive(Deserialize, Serialize)]\npub struct TomlConfig {\n    pub format_version: u32,\n    pub project: ProjectTomlConfig,\n}\n\n#[derive(Deserialize, Serialize)]\npub struct ProjectTomlConfig {\n    pub version_num: String,\n    pub version_string: String,\n    pub bundle_id: String,\n}\n\n// TODO: Check platforms\n#[derive(Deserialize)]\nstruct SwiftPackageDump {\n    name: String,\n    targets: Vec<SwiftPackageTarget>,\n}\n\n// TODO: Resources\n#[derive(Deserialize)]\nstruct SwiftPackageTarget {\n    name: String,\n}\n\n#[derive(Deserialize, Serialize)]\npub enum ProjectValidation {\n    Valid,\n    Invalid,\n    UnsupportedFormatVersion,\n    InvalidPackage,\n    InvalidToolchain,\n}\n\nimpl ProjectConfig {\n    pub fn load(project_path: PathBuf, toolchain_path: &str) -> Result<Self, String> {\n        let toml_config = TomlConfig::load_or_default(project_path.clone())?;\n        let swift = SwiftBin::new(toolchain_path)?;\n        let raw_package = swift\n            .command()\n            .arg(\"package\")\n            .arg(\"dump-package\")\n            .current_dir(&project_path)\n            .output()\n            .map_err(|e| format!(\"Failed to execute swift command: {}\", e))?;\n        if !raw_package.status.success() {\n            return Err(format!(\n                \"Failed to dump package: {}\",\n                String::from_utf8_lossy(&raw_package.stderr)\n            ));\n        }\n\n        let package: SwiftPackageDump = serde_json::from_slice(&raw_package.stdout)\n            .map_err(|e| format!(\"Failed to parse package dump: {}\", e))?;\n\n        Ok(ProjectConfig {\n            product: package.name,\n            version_num: toml_config.project.version_num,\n            version_string: toml_config.project.version_string,\n            bundle_id: toml_config.project.bundle_id,\n            project_path,\n        })\n    }\n\n    pub fn validate(project_path: PathBuf, toolchain_path: &str) -> ProjectValidation {\n        if !project_path.exists() {\n            return ProjectValidation::Invalid;\n        }\n        if !project_path.join(\"Package.swift\").exists() {\n            return ProjectValidation::Invalid;\n        }\n        if !project_path.join(\"crosscode.toml\").exists() {\n            return ProjectValidation::Invalid;\n        }\n        let config_res = TomlConfig::load(project_path.clone());\n        // make sure the error isn't unsupported format version\n        if let Err(e) = config_res {\n            if e.contains(\"Unsupported format version\") {\n                return ProjectValidation::UnsupportedFormatVersion;\n            }\n        }\n\n        let swift = SwiftBin::new(toolchain_path);\n        if let Err(_) = swift {\n            return ProjectValidation::InvalidToolchain;\n        }\n        let swift = swift.unwrap();\n\n        let raw_package = swift\n            .command()\n            .arg(\"package\")\n            .arg(\"dump-package\")\n            .current_dir(&project_path)\n            .output();\n        if let Err(_) = raw_package {\n            return ProjectValidation::InvalidToolchain;\n        }\n        let raw_package = raw_package.unwrap();\n\n        if !raw_package.status.success() {\n            return ProjectValidation::InvalidPackage;\n        }\n\n        let package = serde_json::from_slice::<SwiftPackageDump>(&raw_package.stdout);\n        if let Err(_) = package {\n            return ProjectValidation::InvalidPackage;\n        }\n\n        ProjectValidation::Valid\n    }\n}\n\nimpl TomlConfig {\n    pub fn default(bundle_id: &str) -> Self {\n        TomlConfig {\n            format_version: FORMAT_VERSION,\n            project: ProjectTomlConfig {\n                version_num: \"1\".to_string(),\n                version_string: \"1.0.0\".to_string(),\n                bundle_id: bundle_id.to_string(),\n            },\n        }\n    }\n\n    pub fn load_or_default(project_path: PathBuf) -> Result<Self, String> {\n        if project_path.exists() {\n            Self::load(project_path)\n        } else {\n            let config = Self::default(\"com.example.myapp\");\n            config.save(project_path)?;\n            Ok(config)\n        }\n    }\n\n    fn load(project_path: PathBuf) -> Result<Self, String> {\n        let content = std::fs::read_to_string(project_path.join(\"crosscode.toml\"))\n            .map_err(|e| e.to_string())?;\n        let config: TomlConfig = toml::from_str(&content).map_err(|e| e.to_string())?;\n        if config.format_version != FORMAT_VERSION {\n            return Err(format!(\n                \"Unsupported format version: {}, expected: {}\",\n                config.format_version, FORMAT_VERSION\n            ));\n        }\n        Ok(config)\n    }\n\n    pub fn save(&self, project_path: PathBuf) -> Result<(), String> {\n        let content = toml::to_string(self).map_err(|e| e.to_string())?;\n        std::fs::write(project_path.join(\"crosscode.toml\"), content).map_err(|e| e.to_string())?;\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src-tauri/src/builder/crossplatform.rs",
    "content": "#[cfg(target_os = \"windows\")]\nuse crate::windows::{has_wsl, windows_to_wsl_path, wsl_to_windows_path};\n#[cfg(not(target_os = \"windows\"))]\nuse std::fs;\n#[cfg(target_os = \"windows\")]\nuse std::os::windows::process::CommandExt;\n#[cfg(not(target_os = \"windows\"))]\nuse std::path::Path;\nuse std::path::PathBuf;\n#[cfg(target_os = \"windows\")]\nuse std::process::{Command, Stdio};\n\n#[cfg(target_os = \"windows\")]\nconst CREATE_NO_WINDOW: u32 = 0x08000000;\n\npub fn symlink(target: &str, link: &str) -> std::io::Result<()> {\n    #[cfg(not(target_os = \"windows\"))]\n    {\n        return std::os::unix::fs::symlink(target, link);\n    }\n    #[cfg(target_os = \"windows\")]\n    {\n        if !has_wsl() {\n            return Err(std::io::Error::new(\n                std::io::ErrorKind::Other,\n                \"WSL is not available\",\n            ));\n        }\n        let path = windows_to_wsl_path(link).map_err(|e| {\n            std::io::Error::new(\n                std::io::ErrorKind::Other,\n                format!(\"Path conversion error: {}\", e),\n            )\n        })?;\n        let output = Command::new(\"wsl\")\n            .arg(\"ln\")\n            .arg(\"-s\")\n            .arg(target)\n            .arg(path)\n            .stdout(Stdio::piped())\n            .stderr(Stdio::piped())\n            .creation_flags(CREATE_NO_WINDOW)\n            .output()\n            .expect(\"failed to execute process\");\n        if !output.status.success() {\n            return Err(std::io::Error::new(\n                std::io::ErrorKind::Other,\n                format!(\n                    \"failed to create symlink: {}\",\n                    String::from_utf8_lossy(&output.stderr)\n                ),\n            ));\n        }\n        return Ok(());\n    }\n}\n\npub fn linux_env(key: &str) -> Result<String, String> {\n    #[cfg(not(target_os = \"windows\"))]\n    {\n        return std::env::var(key).map_err(|e| e.to_string());\n    }\n    #[cfg(target_os = \"windows\")]\n    {\n        if !has_wsl() {\n            return Err(\"WSL is not available\".to_string());\n        }\n        let output = Command::new(\"wsl\")\n            .args([\"bash\", \"-l\", \"-c\"])\n            .arg(format!(\"printenv {}\", key))\n            .creation_flags(CREATE_NO_WINDOW)\n            .output()\n            .expect(\"failed to execute process\");\n        if output.status.success() {\n            let res = String::from_utf8_lossy(&output.stdout).trim().to_string();\n            if res.is_empty() {\n                Err(\"Environment variable not found\".to_string())\n            } else {\n                Ok(res)\n            }\n        } else {\n            Err(format!(\n                \"Failed to get environment variable '{}': {}\",\n                key,\n                String::from_utf8_lossy(&output.stderr)\n            ))\n        }\n    }\n}\n\n#[tauri::command]\npub fn windows_path(path: &str) -> Result<String, String> {\n    #[cfg(not(target_os = \"windows\"))]\n    {\n        return Ok(path.to_string());\n    }\n    #[cfg(target_os = \"windows\")]\n    {\n        if !has_wsl() {\n            return Ok(path.to_string());\n        }\n        return wsl_to_windows_path(path);\n    }\n}\n\n#[tauri::command]\npub fn linux_path(path: &str) -> Result<String, String> {\n    #[cfg(not(target_os = \"windows\"))]\n    {\n        return Ok(path.to_string());\n    }\n    #[cfg(target_os = \"windows\")]\n    {\n        if !has_wsl() {\n            return Ok(path.to_string());\n        }\n        return windows_to_wsl_path(path);\n    }\n}\n\n#[cfg(target_os = \"windows\")]\npub fn is_linux_dir(path: &str) -> Result<bool, String> {\n    // #[cfg(not(target_os = \"windows\"))]\n    // {\n    //     let p = Path::new(path);\n    //     return Ok(p.is_dir());\n    // }\n    // #[cfg(target_os = \"windows\")]\n    // {\n    if !has_wsl() {\n        return Err(\"WSL is not available\".to_string());\n    }\n    let output = Command::new(\"wsl\")\n        .arg(\"test\")\n        .arg(\"-d\")\n        .arg(&path)\n        .creation_flags(CREATE_NO_WINDOW)\n        .output()\n        .expect(\"failed to execute process\");\n    if output.status.success() {\n        Ok(true)\n    } else {\n        Ok(false)\n    }\n    //}\n}\n\npub fn linux_temp_dir() -> Result<PathBuf, String> {\n    #[cfg(target_os = \"windows\")]\n    {\n        if !has_wsl() {\n            return Err(\"WSL is not available\".to_string());\n        }\n\n        if let Ok(tmpdir) = linux_env(\"TMPDIR\") {\n            if is_linux_dir(&tmpdir)? {\n                let win_path = wsl_to_windows_path(&tmpdir)?;\n                return Ok(PathBuf::from(win_path));\n            }\n        }\n\n        if is_linux_dir(\"/var/tmp\")? {\n            let win_path = wsl_to_windows_path(\"/var/tmp\")?;\n            return Ok(PathBuf::from(win_path));\n        }\n\n        let win_path = wsl_to_windows_path(\"/tmp\")?;\n        return Ok(PathBuf::from(win_path));\n    }\n\n    #[cfg(not(target_os = \"windows\"))]\n    {\n        if let Ok(tmpdir) = std::env::var(\"TMPDIR\") {\n            let path = Path::new(&tmpdir);\n            if path.is_dir() {\n                return Ok(path.to_path_buf());\n            }\n        }\n\n        if Path::new(\"/var/tmp\").is_dir() {\n            return Ok(PathBuf::from(\"/var/tmp\"));\n        }\n\n        Ok(PathBuf::from(\"/tmp\"))\n    }\n}\n\npub fn remove_dir_all(path: &PathBuf) -> Result<(), String> {\n    #[cfg(not(target_os = \"windows\"))]\n    {\n        return fs::remove_dir_all(path).map_err(|e| e.to_string());\n    }\n    #[cfg(target_os = \"windows\")]\n    {\n        if !has_wsl() {\n            return Err(\"WSL is not available\".to_string());\n        }\n        let path = windows_to_wsl_path(&path.to_string_lossy().to_string())?;\n        let output = Command::new(\"wsl\")\n            .arg(\"rm\")\n            .arg(\"-rf\")\n            .arg(path)\n            .creation_flags(CREATE_NO_WINDOW)\n            .output()\n            .expect(\"failed to execute process\");\n        if output.status.success() {\n            Ok(())\n        } else {\n            Err(String::from_utf8_lossy(&output.stderr).trim().to_string())\n        }\n    }\n}\n"
  },
  {
    "path": "src-tauri/src/builder/icon.rs",
    "content": "use std::{fs, path::Path};\n\nuse image::{ImageFormat, ImageReader};\n\nconst ICON_FILES: &[(&str, u32)] = &[\n    (\"AppIcon29x29.png\", 29),\n    (\"AppIcon29x29@2x.png\", 58),\n    (\"AppIcon29x29@3x.png\", 87),\n    (\"AppIcon40x40.png\", 40),\n    (\"AppIcon40x40@2x.png\", 80),\n    (\"AppIcon40x40@3x.png\", 120),\n    (\"AppIcon50x50.png\", 50),\n    (\"AppIcon50x50@2x.png\", 100),\n    (\"AppIcon57x57.png\", 57),\n    (\"AppIcon57x57@2x.png\", 114),\n    (\"AppIcon57x57@3x.png\", 171),\n    (\"AppIcon60x60.png\", 60),\n    (\"AppIcon60x60@2x.png\", 120),\n    (\"AppIcon60x60@3x.png\", 180),\n    (\"AppIcon72x72.png\", 72),\n    (\"AppIcon72x72@2x.png\", 144),\n    (\"AppIcon76x76.png\", 76),\n    (\"AppIcon76x76@2x.png\", 152),\n];\n\n#[tauri::command]\npub async fn import_icon(project_path: String, icon_path: String) -> Result<(), String> {\n    let img = ImageReader::open(icon_path)\n        .map_err(|e| format!(\"Failed to open icon image: {}\", e))?\n        .decode()\n        .map_err(|e| format!(\"Failed to decode icon image: {}\", e))?;\n\n    let icon_dir = Path::new(&project_path).join(\"Resources\");\n    fs::create_dir_all(&icon_dir).map_err(|e| format!(\"Failed to create icon directory: {}\", e))?;\n\n    for (file_name, size) in ICON_FILES {\n        let resized = img.resize(*size, *size, image::imageops::FilterType::CatmullRom);\n        let output_path = icon_dir.join(file_name);\n        resized\n            .save_with_format(&output_path, ImageFormat::Png)\n            .map_err(|e| format!(\"Failed to save icon image: {}\", e))?;\n    }\n\n    Ok(())\n}\n"
  },
  {
    "path": "src-tauri/src/builder/mod.rs",
    "content": "pub mod config;\npub mod crossplatform;\npub mod icon;\npub mod packer;\npub mod sdk;\npub mod swift;\n"
  },
  {
    "path": "src-tauri/src/builder/packer.rs",
    "content": "use std::{\n    fs::{self, File},\n    io::prelude::*,\n    path::PathBuf,\n};\n\nuse dircpy::CopyBuilder;\nuse zip::write::SimpleFileOptions;\n\nuse crate::builder::config::{BuildSettings, ProjectConfig};\n\npub fn pack(\n    project_path: PathBuf,\n    config: &ProjectConfig,\n    build_settings: &BuildSettings,\n) -> Result<PathBuf, String> {\n    let workdir = project_path.join(\".crosscode\").join(\"Payload\");\n    if !workdir.exists() {\n        std::fs::create_dir_all(&workdir)\n            .map_err(|e| format!(\"Failed to create work directory: {}\", e))?;\n    }\n    let app_path = workdir.join(format!(\"{}.app\", config.product));\n    if app_path.exists() {\n        std::fs::remove_dir_all(&app_path)\n            .map_err(|e| format!(\"Failed to remove existing app directory: {}\", e))?;\n    }\n    std::fs::create_dir_all(&app_path)\n        .map_err(|e| format!(\"Failed to create app directory: {}\", e))?;\n\n    let exec = project_path\n        .join(\".build\")\n        .join(\"arm64-apple-ios\")\n        .join(if build_settings.debug {\n            \"debug\"\n        } else {\n            \"release\"\n        })\n        .join(&config.product);\n\n    if !exec.exists() {\n        return Err(format!(\"Executable not found at: {}\", exec.display()));\n    }\n\n    fs::copy(exec, app_path.join(&config.product))\n        .map_err(|e| format!(\"Failed to copy executable: {}\", e))?;\n\n    // TODO: Create default Info.plist if it doesn't exist\n    let info_plist = project_path.join(\"Info.plist\");\n    if !info_plist.exists() {\n        return Err(format!(\"Info.plist not found at: {}\", info_plist.display()));\n    }\n\n    let info_content = fs::read_to_string(&info_plist)\n        .map_err(|e| format!(\"Failed to read Info.plist: {}\", e))?\n        .replace(\"[[bundle_id]]\", &config.bundle_id)\n        .replace(\"[[product]]\", &config.product)\n        .replace(\"[[version_num]]\", &config.version_num)\n        .replace(\"[[version_string]]\", &config.version_string);\n    fs::write(&app_path.join(\"Info.plist\"), info_content)\n        .map_err(|e| format!(\"Failed to write Info.plist: {}\", e))?;\n\n    let resources = project_path.join(\"Resources\");\n\n    if !resources.exists() {\n        std::fs::create_dir_all(&resources)\n            .map_err(|e| format!(\"Failed to create Resources directory: {}\", e))?;\n    }\n\n    CopyBuilder::new(&resources, &app_path)\n        .run()\n        .map_err(|e| format!(\"Failed to copy resources: {}\", e))?;\n\n    Ok(app_path)\n}\n\npub fn zip_ipa(app: PathBuf, config: &ProjectConfig) -> Result<PathBuf, String> {\n    let payload = app.parent().unwrap_or(&PathBuf::from(\".\")).to_path_buf();\n\n    if !payload.exists() || !payload.is_dir() {\n        return Err(format!(\n            \"Payload directory does not exist: {}\",\n            payload.display()\n        ));\n    }\n\n    let ipa_path = payload\n        .parent()\n        .unwrap()\n        .join(format!(\"{}.ipa\", config.product));\n    let zip_file = File::create(&ipa_path)\n        .map_err(|e| format!(\"Failed to create zip file in payload directory: {}\", e))?;\n    let mut zip = zip::ZipWriter::new(zip_file);\n    let options = SimpleFileOptions::default()\n        .compression_method(zip::CompressionMethod::Deflated)\n        .unix_permissions(0o755);\n    let walkdir = walkdir::WalkDir::new(&payload)\n        .into_iter()\n        .filter_map(|e| e.ok());\n\n    let prefix = payload.as_path().parent().ok_or(format!(\n        \"Failed to get parent directory of payload: {}\",\n        payload.display()\n    ))?;\n\n    // https://github.com/zip-rs/zip2/blob/6c78fe381da074610d99e2d59546b0530bcb6e54/examples/write_dir.rs\n    let mut buffer = Vec::new();\n    for entry in walkdir {\n        let path = entry.path();\n        let name = path\n            .strip_prefix(prefix)\n            .map_err(|e| format!(\"Failed to strip prefix from path: {}\", e))?;\n        let path_as_string = name\n            .to_str()\n            .map(str::to_owned)\n            .ok_or_else(|| format!(\"Failed to convert path to string: {}\", path.display()))?;\n\n        // Write file or directory explicitly\n        // Some unzip tools unzip files with directory paths correctly, some do not!\n        if path.is_file() {\n            zip.start_file(path_as_string, options)\n                .map_err(|e| format!(\"Failed to start file {}: {}\", path.display(), e))?;\n            let mut f = File::open(path)\n                .map_err(|e| format!(\"Failed to open file {}: {}\", path.display(), e))?;\n\n            f.read_to_end(&mut buffer)\n                .map_err(|e| format!(\"Failed to read file {}: {}\", path.display(), e))?;\n            zip.write_all(&buffer)\n                .map_err(|e| format!(\"Failed to write file {}: {}\", path.display(), e))?;\n            buffer.clear();\n        } else if !name.as_os_str().is_empty() {\n            // Only if not root! Avoids path spec / warning\n            // and mapname conversion failed error on unzip\n            zip.add_directory(path_as_string, options)\n                .map_err(|e| format!(\"Failed to add directory {}: {}\", path.display(), e))?;\n        }\n    }\n\n    zip.finish()\n        .map_err(|e| format!(\"Failed to finish zip file: {}\", e))?;\n    Ok(ipa_path)\n}\n"
  },
  {
    "path": "src-tauri/src/builder/sdk.rs",
    "content": "// Reference: https://github.com/xtool-org/xtool/blob/main/Sources/XToolSupport/SDKBuilder.swift\nuse regex::Regex;\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\nuse std::fs;\nuse std::io::{Read, Seek};\nuse std::path::{Path, PathBuf};\nuse std::process::{Command, Stdio};\nuse tauri::{AppHandle, Manager, Window};\n\nuse crate::builder::crossplatform::{linux_path, linux_temp_dir, remove_dir_all, symlink};\nuse crate::builder::swift::{validate_toolchain, SwiftBin};\nuse crate::operation::Operation;\nuse tauri::path::BaseDirectory;\nuse unxip_rs::{reader::XipReader, UnxipError};\n\n#[cfg(not(target_os = \"windows\"))]\nuse sdkmover::copy_developer;\n\n#[cfg(target_os = \"windows\")]\nuse crate::windows::windows_to_wsl_path;\n#[cfg(target_os = \"windows\")]\nuse std::os::windows::process::CommandExt;\n#[cfg(target_os = \"windows\")]\nconst CREATE_NO_WINDOW: u32 = 0x08000000;\n\nconst DARWIN_TOOLS_VERSION: &str = \"1.0.1\";\n\n#[tauri::command]\npub async fn install_sdk_operation(\n    app: AppHandle,\n    window: Window,\n    xcode_path: String,\n    toolchain_path: String,\n    is_dir: bool,\n) -> Result<(), String> {\n    let op = Operation::new(\"install_sdk\".to_string(), &window);\n    op.start(\"create_stage\")?;\n    let work_dir = op\n        .fail_if_err(\"create_stage\", linux_temp_dir())?\n        .join(\"crosscode\")\n        .join(\"DarwinSDKBuild\");\n    let res = install_sdk_internal(\n        app,\n        xcode_path,\n        toolchain_path,\n        work_dir.clone(),\n        is_dir,\n        &op,\n    )\n    .await;\n    op.start(\"cleanup\")?;\n    let cleanup_result = if work_dir.exists() {\n        remove_dir_all(&work_dir)\n    } else {\n        Ok(())\n    };\n\n    let cleanup_result_for_match = cleanup_result\n        .as_ref()\n        .map(|_| ())\n        .map_err(|e| format!(\"{}\", e));\n\n    let cleanup_result = op.fail_if_err_map(\"cleanup\", cleanup_result, |e| {\n        format!(\"Failed to remove temp dir: {}\", e)\n    });\n\n    if cleanup_result.is_ok() {\n        op.complete(\"cleanup\")?;\n    }\n\n    match (res, cleanup_result_for_match) {\n        (Err(main_err), Err(cleanup_err)) => Err(format!(\n            \"{main_err} (additionally, failed to clean up temp dir: {cleanup_err})\"\n        )),\n        (Err(main_err), _) => Err(main_err),\n        (Ok(_), Err(cleanup_err)) => Err(format!(\n            \"Install succeeded, but failed to clean up temp dir: {cleanup_err}\"\n        )),\n        (Ok(val), Ok(_)) => Ok(val),\n    }\n}\nasync fn install_sdk_internal(\n    app: AppHandle,\n    xcode_path: String,\n    toolchain_path: String,\n    work_dir: PathBuf,\n    is_dir: bool,\n    op: &Operation<'_>,\n) -> Result<(), String> {\n    if xcode_path.is_empty() || (!xcode_path.ends_with(\".xip\") && !is_dir) {\n        return op.fail(\"create_stage\", \"Xcode not found\".to_string());\n    }\n    if toolchain_path.is_empty() {\n        return op.fail(\"create_stage\", \"Toolchain not found\".to_string());\n    }\n    if !validate_toolchain(&toolchain_path) {\n        return op.fail(\"create_stage\", \"Invalid toolchain path\".to_string());\n    }\n\n    let swift_bin = SwiftBin::new(&toolchain_path);\n    if swift_bin.is_err() {\n        return op.fail(\"create_stage\", \"Invalid toolchain path\".to_string());\n    }\n    let swift_bin = swift_bin.unwrap();\n    let output = swift_bin.output(&[\"sdk\", \"remove\", \"darwin\"]);\n    if let Ok(output) = output {\n        if !output.status.success() && output.status.code() != Some(1) {\n            return op.fail(\n                \"create_stage\",\n                format!(\n                    \"Failed to remove existing darwin SDK: {}\",\n                    String::from_utf8_lossy(&output.stderr)\n                ),\n            );\n        }\n    }\n\n    let output_dir = work_dir.join(\"darwin.artifactbundle\");\n    if output_dir.exists() {\n        op.fail_if_err_map(\"create_stage\", remove_dir_all(&output_dir), |e| {\n            format!(\"Failed to remove existing output directory: {}\", e)\n        })?;\n    }\n    op.fail_if_err_map(\"create_stage\", fs::create_dir_all(&output_dir), |e| {\n        format!(\"Failed to create output directory: {}\", e)\n    })?;\n\n    op.move_on(\"create_stage\", \"install_toolset\")?;\n    op.fail_if_err(\"install_toolset\", install_toolset(&output_dir).await)?;\n    op.complete(\"install_toolset\")?;\n    let dev = install_developer(app, &output_dir, &xcode_path, is_dir, op).await?;\n    op.start(\"write_metadata\")?;\n\n    let iphone_os_sdk = op.fail_if_err(\"write_metadata\", sdk(&dev, \"iPhoneOS\"))?;\n    let mac_os_sdk = op.fail_if_err(\"write_metadata\", sdk(&dev, \"MacOSX\"))?;\n    let iphone_simulator_sdk = op.fail_if_err(\"write_metadata\", sdk(&dev, \"iPhoneSimulator\"))?;\n\n    let info = \"{\n    \\\"schemaVersion\\\": \\\"1.0\\\",\n    \\\"artifacts\\\": {\n        \\\"darwin\\\": {\n            \\\"type\\\": \\\"swiftSDK\\\",\n            \\\"version\\\": \\\"0.0.1\\\",\n            \\\"variants\\\": [\n                {\n                    \\\"path\\\": \\\".\\\",\n                    \\\"supportedTriples\\\": [\\\"aarch64-unknown-linux-gnu\\\", \\\"x86_64-unknown-linux-gnu\\\"]\n                }\n            ]\n        }\n    }\n}\";\n    op.fail_if_err_map(\n        \"write_metadata\",\n        fs::write(output_dir.join(\"info.json\"), info),\n        |e| format!(\"Failed to write info.json: {}\", e),\n    )?;\n\n    let toolset = \"{\n    \\\"schemaVersion\\\": \\\"1.0\\\",\n    \\\"rootPath\\\": \\\"toolset/bin\\\",\n    \\\"linker\\\": {\n        \\\"path\\\": \\\"ld64.lld\\\"\n    },\n    \\\"swiftCompiler\\\": {\n        \\\"extraCLIOptions\\\": [\n            \\\"-use-ld=lld\\\"\n        ]\n    }\n}\";\n    op.fail_if_err_map(\n        \"write_metadata\",\n        fs::write(output_dir.join(\"toolset.json\"), toolset),\n        |e| format!(\"Failed to write toolset.json: {}\", e),\n    )?;\n\n    let sdk_def = SDKDefinition {\n        schema_version: \"4.0\".to_string(),\n        target_triples: HashMap::from([\n            (\n                \"arm64-apple-ios\".to_string(),\n                Triple::from_sdk(\"iPhoneOS\", &iphone_os_sdk),\n            ),\n            (\n                \"arm64-apple-ios-simulator\".to_string(),\n                Triple::from_sdk(\"iPhoneSimulator\", &iphone_simulator_sdk),\n            ),\n            (\n                \"x86_64-apple-ios-simulator\".to_string(),\n                Triple::from_sdk(\"iPhoneSimulator\", &iphone_simulator_sdk),\n            ),\n            (\n                \"arm64-apple-macos\".to_string(),\n                Triple::from_sdk(\"MacOSX\", &mac_os_sdk),\n            ),\n            (\n                \"x86_64-apple-macos\".to_string(),\n                Triple::from_sdk(\"MacOSX\", &mac_os_sdk),\n            ),\n        ]),\n    };\n\n    let sdk_def_path = output_dir.join(\"swift-sdk.json\");\n    op.fail_if_err_map(\n        \"write_metadata\",\n        fs::write(\n            sdk_def_path,\n            op.fail_if_err_map(\n                \"write_metadata\",\n                serde_json::to_string_pretty(&sdk_def),\n                |e| format!(\"Failed to serialize SDKDefinition: {}\", e),\n            )?,\n        ),\n        |e| format!(\"Failed to write swift-sdk.json: {}\", e),\n    )?;\n\n    let sdk_version_path = output_dir.join(\"darwin-sdk-version.txt\");\n    op.fail_if_err_map(\n        \"write_metadata\",\n        fs::write(&sdk_version_path, \"develop\"),\n        |e| format!(\"Failed to write darwin-sdk-version.txt: {}\", e),\n    )?;\n    op.move_on(\"write_metadata\", \"install_sdk\")?;\n\n    let real_output_dir =\n        op.fail_if_err(\"install_sdk\", linux_path(&output_dir.to_string_lossy()))?;\n    let output = op.fail_if_err_map(\n        \"install_sdk\",\n        swift_bin.output(&[\"sdk\", \"install\", &real_output_dir]),\n        |e| format!(\"Failed to execute swift command: {}\", e),\n    )?;\n\n    if !output.status.success() {\n        return op.fail(\n            \"install_sdk\",\n            format!(\n                \"Swift command failed: {}\",\n                String::from_utf8_lossy(&output.stderr)\n            ),\n        );\n    }\n    op.complete(\"install_sdk\")?;\n\n    Ok(())\n}\n\nfn sdk(dev: &PathBuf, platform: &str) -> Result<String, String> {\n    let dir = dev.join(format!(\"Platforms/{}.platform/Developer/SDKs\", platform));\n    let regex = Regex::new(&format!(r\"^{}\\d+\\.\\d+\\.sdk$\", regex::escape(platform)))\n        .map_err(|e| format!(\"Invalid regex: {}\", e))?;\n\n    let entries =\n        fs::read_dir(&dir).map_err(|e| format!(\"Failed to read SDKs directory: {}\", e))?;\n\n    for entry in entries {\n        let entry = entry.map_err(|e| format!(\"Failed to read entry: {}\", e))?;\n        let name = entry.file_name();\n        let name_str = name.to_string_lossy();\n        if regex.is_match(&name_str) {\n            return Ok(name_str.into_owned());\n        }\n    }\n\n    Err(format!(\"Could not find SDK for {}/{}\", platform, platform))\n}\n\nasync fn install_toolset(output_path: &PathBuf) -> Result<(), String> {\n    let toolset_dir = output_path.join(\"toolset\");\n    fs::create_dir_all(&toolset_dir)\n        .map_err(|e| format!(\"Failed to create toolset directory: {}\", e))?;\n\n    let arch = if cfg!(target_arch = \"x86_64\") {\n        \"x86_64\"\n    } else if cfg!(target_arch = \"aarch64\") {\n        \"aarch64\"\n    } else {\n        return Err(\"Unsupported architecture\".to_string());\n    };\n    let toolset_url = format!(\n        \"https://github.com/xtool-org/darwin-tools-linux-llvm/releases/download/v{}/toolset-{}.tar.gz\",\n        DARWIN_TOOLS_VERSION, arch\n    );\n\n    let response = reqwest::get(&toolset_url)\n        .await\n        .map_err(|e| format!(\"Failed to download toolset: {}\", e))?;\n    if !response.status().is_success() {\n        return Err(format!(\"Failed to download toolset: {}\", response.status()));\n    }\n    let tar_gz = response\n        .bytes()\n        .await\n        .map_err(|e| format!(\"Failed to read response: {}\", e))?;\n    let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(&*tar_gz));\n    archive\n        .unpack(&toolset_dir)\n        .map_err(|e| format!(\"Failed to extract toolset: {}\", e))?;\n    #[cfg(target_os = \"windows\")]\n    {\n        // I'm guessing this has to be done because I'm extracting the tar from windows into the wsl file system and windows doesn't play nice with permissions, but im too lazy to do this properly\n        let wsl_toolset_path =\n            windows_to_wsl_path(&toolset_dir.join(\"bin\").to_string_lossy().to_string())?;\n        let output = Command::new(\"wsl\")\n            .arg(\"chmod\")\n            .arg(\"+x\")\n            .arg(format!(\"{}/*\", wsl_toolset_path))\n            .creation_flags(CREATE_NO_WINDOW)\n            .output()\n            .map_err(|e| format!(\"Failed to run chmod: {}\", e))?;\n        if !output.status.success() {\n            return Err(format!(\n                \"Failed to set executable permissions: {}\",\n                String::from_utf8_lossy(&output.stderr)\n            ));\n        }\n    }\n    Ok(())\n}\n\nasync fn install_developer(\n    app: AppHandle,\n    output_path: &PathBuf,\n    xcode_path: &str,\n    is_dir: bool,\n    op: &Operation<'_>,\n) -> Result<PathBuf, String> {\n    op.start(\"extract_xip\")?;\n\n    let dev_stage = output_path.join(\"DeveloperStage\");\n    let mut app_path = PathBuf::from(xcode_path);\n    if !is_dir {\n        op.fail_if_err_map(\"extract_xip\", fs::create_dir_all(&dev_stage), |e| {\n            format!(\"Failed to create DeveloperStage directory: {}\", e)\n        })?;\n\n        let mut file = op.fail_if_err_map(\"extract_xip\", fs::File::open(xcode_path), |e| {\n            format!(\"Failed to open xip file: {}\", e)\n        })?;\n        let cpio = op\n            .fail_if_err_map(\n                \"extract_xip\",\n                app.path().resolve(\"cpio\", BaseDirectory::Resource),\n                |e| format!(\"Failed to resolve cpio path: {}\", e),\n            )?\n            .to_string_lossy()\n            .to_string();\n\n        #[cfg(target_os = \"windows\")]\n        let cpio = op.fail_if_err(\"extract_xip\", windows_to_wsl_path(&cpio))?;\n\n        op.fail_if_err_map(\"extract_xip\", unxip(&mut file, &dev_stage, cpio), |e| {\n            format!(\"Failed to extract xip file: {}\", e)\n        })?;\n\n        let app_dirs = op\n            .fail_if_err_map(\"extract_xip\", fs::read_dir(&dev_stage), |e| {\n                format!(\"Failed to read DeveloperStage directory: {}\", e)\n            })?\n            .filter_map(Result::ok)\n            .filter(|entry| entry.path().extension().map_or(false, |ext| ext == \"app\"))\n            .collect::<Vec<_>>();\n        if app_dirs.len() != 1 {\n            return op.fail(\n                \"extract_xip\",\n                format!(\n                    \"Expected one .app in DeveloperStage, found {}\",\n                    app_dirs.len()\n                ),\n            );\n        }\n\n        app_path = app_dirs[0].path();\n    }\n\n    op.move_on(\"extract_xip\", \"copy_files\")?;\n    let dev = output_path.join(\"Developer\");\n    op.fail_if_err_map(\"copy_files\", fs::create_dir_all(&dev), |e| {\n        format!(\"Failed to create Developer directory: {}\", e)\n    })?;\n\n    let contents_developer = app_path.join(\"Contents\").join(\"Developer\");\n    if !contents_developer.exists() {\n        return op.fail(\n            \"copy_files\",\n            \"Contents/Developer not found in .app\".to_string(),\n        );\n    }\n\n    #[cfg(not(target_os = \"windows\"))]\n    op.fail_if_err(\n        \"copy_files\",\n        copy_developer(\n            &contents_developer,\n            &dev,\n            Path::new(\"Contents/Developer\"),\n            false,\n        ),\n    )?;\n\n    #[cfg(target_os = \"windows\")]\n    {\n        let sdkmover_path = op\n            .fail_if_err_map(\n                \"copy_files\",\n                app.path().resolve(\"sdkmoverbin\", BaseDirectory::Resource),\n                |e| format!(\"Failed to resolve sdkmoverbin path: {}\", e),\n            )?\n            .to_string_lossy()\n            .to_string();\n        let linux_sdkmover_path =\n            op.fail_if_err(\"copy_files\", windows_to_wsl_path(&sdkmover_path))?;\n        let linux_contents_developer = op.fail_if_err(\n            \"copy_files\",\n            windows_to_wsl_path(&contents_developer.to_string_lossy().to_string()),\n        )?;\n        let linux_dev = op.fail_if_err(\n            \"copy_files\",\n            windows_to_wsl_path(&dev.to_string_lossy().to_string()),\n        )?;\n        let output = op.fail_if_err_map(\n            \"copy_files\",\n            Command::new(\"wsl\")\n                .arg(&linux_sdkmover_path)\n                .arg(&linux_contents_developer)\n                .arg(&linux_dev)\n                .creation_flags(CREATE_NO_WINDOW)\n                .output(),\n            |e| format!(\"Failed to run sdkmover: {}\", e),\n        )?;\n        if !output.status.success() {\n            return op.fail(\n                \"copy_files\",\n                format!(\n                    \"Failed to move files: {}\",\n                    String::from_utf8_lossy(&output.stderr)\n                ),\n            );\n        }\n    }\n\n    if dev_stage.exists() {\n        op.fail_if_err_map(\"copy_files\", remove_dir_all(&dev_stage), |e| {\n            format!(\"Failed to remove DeveloperStage directory: {}\", e)\n        })?;\n    }\n\n    for platform in [\"iPhoneOS\", \"MacOSX\", \"iPhoneSimulator\"] {\n        let lib = \"../../../../../Library\";\n        let dest = dev.join(format!(\n            \"Platforms/{}.platform/Developer/SDKs/{}.sdk/System/Library/Frameworks\",\n            platform, platform\n        ));\n\n        let links = [\n            (\n                \"Testing.framework\",\n                format!(\"{}/Frameworks/Testing.framework\", lib),\n            ),\n            (\n                \"XCTest.framework\",\n                format!(\"{}/Frameworks/XCTest.framework\", lib),\n            ),\n            (\n                \"XCUIAutomation.framework\",\n                format!(\"{}/Frameworks/XCUIAutomation.framework\", lib),\n            ),\n            (\n                \"XCTestCore.framework\",\n                format!(\"{}/PrivateFrameworks/XCTestCore.framework\", lib),\n            ),\n        ];\n\n        for (name, target) in &links {\n            let link_path = dest.join(name);\n            op.fail_if_err_map(\n                \"copy_files\",\n                symlink(target, &link_path.to_string_lossy().to_string()),\n                |e| {\n                    format!(\n                        \"Failed to create symlink {:?} -> {:?}: {}\",\n                        link_path, target, e\n                    )\n                },\n            )?;\n        }\n    }\n\n    op.complete(\"copy_files\")?;\n\n    Ok(dev)\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\nstruct Triple {\n    sdk_root_path: String,\n    include_search_paths: Vec<String>,\n    library_search_paths: Vec<String>,\n    swift_resources_path: String,\n    swift_static_resources_path: String,\n    toolset_paths: Vec<String>,\n}\n\nimpl Triple {\n    fn from_sdk(platform: &str, sdk: &str) -> Self {\n        Triple {\n            sdk_root_path: format!(\n                \"Developer/Platforms/{}.platform/Developer/SDKs/{}\",\n                platform, sdk\n            ),\n            include_search_paths: vec![format!(\n                \"Developer/Platforms/{}.platform/Developer/usr/lib\",\n                platform\n            )],\n            library_search_paths: vec![format!(\n                \"Developer/Platforms/{}.platform/Developer/usr/lib\",\n                platform\n            )],\n            swift_resources_path: format!(\n                \"Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift\"\n            ),\n            swift_static_resources_path: format!(\n                \"Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift_static\"\n            ),\n            toolset_paths: vec![format!(\"toolset.json\")],\n        }\n    }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\nstruct SDKDefinition {\n    schema_version: String,\n    target_triples: HashMap<String, Triple>,\n}\n\npub fn unxip<R: Read + Seek + Sized + std::fmt::Debug>(\n    reader: &mut R,\n    output_path: &Path,\n    cpio_path: String,\n) -> Result<(), UnxipError> {\n    let mut xip_reader = XipReader::new(reader)?;\n\n    std::fs::create_dir_all(output_path).map_err(UnxipError::IoError)?;\n\n    #[cfg(not(target_os = \"windows\"))]\n    let mut child = Command::new(&cpio_path)\n        .arg(\"-idm\")\n        .current_dir(output_path)\n        .stdin(Stdio::piped())\n        .spawn()\n        .map_err(|e| UnxipError::Misc(format!(\"Failed to spawn cpio: {}\", e)))?;\n\n    #[cfg(target_os = \"windows\")]\n    let mut child = Command::new(\"wsl\")\n        .arg(format!(\"{}\", cpio_path))\n        .arg(\"-idm\")\n        .current_dir(output_path)\n        .creation_flags(CREATE_NO_WINDOW)\n        .stdin(Stdio::piped())\n        .stdout(Stdio::inherit())\n        .spawn()\n        .map_err(|e| UnxipError::Misc(format!(\"Failed to spawn cpio: {}\", e)))?;\n    {\n        let stdin = child\n            .stdin\n            .as_mut()\n            .ok_or_else(|| UnxipError::Misc(\"Failed to open cpio stdin\".to_string()))?;\n\n        std::io::copy(&mut xip_reader, stdin).map_err(UnxipError::IoError)?;\n    }\n\n    let status = child.wait().map_err(UnxipError::IoError)?;\n    if !status.success() {\n        return Err(UnxipError::Misc(format!(\n            \"cpio failed with status: {}\",\n            status\n        )));\n    }\n    Ok(())\n}\n"
  },
  {
    "path": "src-tauri/src/builder/swift.rs",
    "content": "#[cfg(target_os = \"windows\")]\nuse crate::windows::has_wsl;\n#[cfg(target_os = \"windows\")]\nuse std::os::windows::process::CommandExt;\n\nuse crate::{\n    builder::{\n        config::{BuildSettings, ProjectConfig},\n        crossplatform::{linux_env, windows_path},\n        packer::{pack, zip_ipa},\n    },\n    emit_error_and_return,\n    sideloader::{device::DeviceInfo, sideload::sideload_app},\n};\nuse serde::{Deserialize, Serialize};\nuse std::{\n    io::{self, BufRead, BufReader},\n    path::PathBuf,\n    process::{Command, Output, Stdio},\n    thread,\n};\nuse tauri::{Emitter, Window};\nuse tokio::process::Command as TokioCommand;\n\n#[cfg(target_os = \"windows\")]\nconst CREATE_NO_WINDOW: u32 = 0x08000000;\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct ToolchainResult {\n    pub swiftly_installed: bool,\n    pub swiftly_version: Option<String>,\n    pub toolchains: Vec<Toolchain>,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct Toolchain {\n    pub version: String,\n    pub path: String,\n    pub is_swiftly: bool,\n}\n\n#[derive(Serialize, Deserialize, Debug, Clone)]\n#[serde(rename_all = \"camelCase\")]\nstruct SwiftlyConfig {\n    pub installed_toolchains: Vec<String>,\n    pub version: String,\n}\n\n#[derive(Debug, Clone)]\npub struct SwiftBin {\n    pub bin_path: String,\n    pub sourcekit_path: String,\n}\n\nimpl SwiftBin {\n    pub fn new(toolchain_path: &str) -> Result<Self, String> {\n        #[cfg(target_os = \"windows\")]\n        {\n            if !has_wsl() {\n                return Err(\"WSL is not available\".to_string());\n            }\n            let output = Command::new(\"wsl\")\n                .args([\n                    \"bash\",\n                    \"-c\",\n                    &format!(\"test -f \\\"{}/usr/bin/swift\\\"\", toolchain_path),\n                ])\n                .creation_flags(CREATE_NO_WINDOW)\n                .output()\n                .map_err(|e| format!(\"Failed to execute command: {}\", e))?;\n            if !output.status.success() {\n                return Err(format!(\n                    \"Swift toolchain invalid: {}\",\n                    String::from_utf8_lossy(&output.stderr)\n                ));\n            }\n            Ok(SwiftBin {\n                bin_path: format!(\"{}/usr/bin/swift\", toolchain_path),\n                sourcekit_path: format!(\"{}/usr/bin/sourcekit-lsp\", toolchain_path),\n            })\n        }\n        #[cfg(not(target_os = \"windows\"))]\n        {\n            let path = PathBuf::from(toolchain_path);\n\n            if !path.exists() || !path.is_dir() {\n                return Err(\"Invalid toolchain path\".to_string());\n            }\n            let swift_path = path.join(\"usr\").join(\"bin\").join(\"swift\");\n\n            if !swift_path.exists() || !swift_path.is_file() {\n                return Err(\"Swift binary not found in toolchain\".to_string());\n            }\n\n            let sourcekit_path = path.join(\"usr\").join(\"bin\").join(\"sourcekit-lsp\");\n            if !sourcekit_path.exists() || !sourcekit_path.is_file() {\n                return Err(\"SourceKit-LSP binary not found in toolchain\".to_string());\n            }\n            Ok(SwiftBin {\n                bin_path: swift_path.to_string_lossy().to_string(),\n                sourcekit_path: sourcekit_path.to_string_lossy().to_string(),\n            })\n        }\n    }\n\n    pub fn output(&self, args: &[&str]) -> io::Result<Output> {\n        #[cfg(target_os = \"windows\")]\n        {\n            if !has_wsl() {\n                return Err(io::Error::new(io::ErrorKind::Other, \"WSL is not available\"));\n            }\n            let mut cmd = Command::new(\"wsl\");\n            cmd.args([\"bash\", \"-l\", \"-c\"])\n                .arg(format!(\"\\\"{}\\\" {}\", self.bin_path, args.join(\" \")))\n                .stdout(Stdio::piped())\n                .stderr(Stdio::piped())\n                .creation_flags(CREATE_NO_WINDOW)\n                .output()\n        }\n        #[cfg(not(target_os = \"windows\"))]\n        {\n            let mut cmd = Command::new(&self.bin_path);\n            cmd.args(args)\n                .stdout(Stdio::piped())\n                .stderr(Stdio::piped())\n                .output()\n        }\n    }\n\n    pub fn command(&self) -> Command {\n        #[cfg(target_os = \"windows\")]\n        {\n            let mut cmd = Command::new(\"wsl\");\n            cmd.arg(&self.bin_path);\n            cmd.creation_flags(CREATE_NO_WINDOW);\n            cmd\n        }\n        #[cfg(not(target_os = \"windows\"))]\n        {\n            Command::new(&self.bin_path)\n        }\n    }\n\n    pub fn sourcekit_command(&self) -> TokioCommand {\n        #[cfg(target_os = \"windows\")]\n        {\n            let mut cmd = TokioCommand::new(\"wsl\");\n            cmd.arg(&self.sourcekit_path);\n            cmd.creation_flags(CREATE_NO_WINDOW);\n            cmd\n        }\n        #[cfg(not(target_os = \"windows\"))]\n        {\n            TokioCommand::new(&self.sourcekit_path)\n        }\n    }\n}\n\n#[tauri::command]\npub fn has_darwin_sdk(toolchain_path: &str) -> String {\n    let swift_bin = SwiftBin::new(toolchain_path);\n    if swift_bin.is_err() {\n        return \"none\".to_string();\n    }\n    let swift_bin = swift_bin.unwrap();\n\n    let output = swift_bin.output(&[\"sdk\", \"list\"]);\n    if output.is_err() {\n        return \"none\".to_string();\n    }\n    let output = output.unwrap();\n    if !output.status.success() {\n        return \"none\".to_string();\n    }\n    let output_str = String::from_utf8_lossy(&output.stdout);\n    if !output_str.contains(\"darwin\") {\n        return \"none\".to_string();\n    }\n\n    let output = swift_bin.output(&[\n        \"sdk\",\n        \"configure\",\n        \"--show-configuration\",\n        \"darwin\",\n        \"arm64-apple-ios\",\n    ]);\n    if output.is_err() {\n        return \"none\".to_string();\n    }\n    let output = output.unwrap();\n    if !output.status.success() {\n        return \"none\".to_string();\n    }\n\n    let output_str = String::from_utf8_lossy(&output.stdout);\n\n    let sdk_version = output_str.lines().find_map(|line| {\n        if line.starts_with(\"sdkRootPath:\") {\n            let parts: Vec<&str> = line.split('/').collect();\n            for part in parts {\n                if part.starts_with(\"iPhoneOS\") && part.ends_with(\".sdk\") {\n                    let version = part.trim_start_matches(\"iPhoneOS\").trim_end_matches(\".sdk\");\n                    return Some(version.to_string());\n                }\n            }\n        }\n        None\n    });\n\n    if let Some(version) = sdk_version {\n        version\n    } else {\n        \"none\".to_string()\n    }\n}\n\n#[tauri::command]\npub fn validate_toolchain(toolchain_path: &str) -> bool {\n    let swift_path = SwiftBin::new(toolchain_path);\n    if swift_path.is_err() {\n        return false;\n    }\n    let swift_path = swift_path.unwrap();\n\n    let output = swift_path.output(&[\"--version\"]);\n    if output.is_err() {\n        return false;\n    }\n    let output = output.unwrap();\n    if !output.status.success() {\n        return false;\n    }\n\n    true\n}\n\n#[tauri::command]\npub async fn get_toolchain_info(\n    toolchain_path: String,\n    is_swiftly: bool,\n) -> Result<Toolchain, String> {\n    if !validate_toolchain(&toolchain_path) {\n        return Err(\"Invalid toolchain path\".to_string());\n    }\n    let swift_path = SwiftBin::new(&toolchain_path)?;\n\n    let output = swift_path\n        .output(&[\"--version\"])\n        .map_err(|e| format!(\"Failed to run swift command: {}\", e))?;\n    let version = String::from_utf8_lossy(&output.stdout).trim().to_string();\n    let version = version\n        .split_whitespace()\n        .nth(2)\n        .ok_or(\"Failed to parse swift version\".to_string())?\n        .to_string();\n    Ok(Toolchain {\n        version,\n        path: toolchain_path.clone(),\n        is_swiftly,\n    })\n}\n\n#[tauri::command]\npub async fn get_swiftly_toolchains() -> Result<ToolchainResult, String> {\n    let swiftly_home_dir = get_swiftly_path();\n    if get_swiftly_config().is_err() {\n        return Ok(ToolchainResult {\n            swiftly_installed: false,\n            swiftly_version: None,\n            toolchains: vec![],\n        });\n    }\n    if let Some(_) = swiftly_home_dir {\n        let config = get_swiftly_config()?;\n        let toolchains_unfiltered: Vec<Toolchain> = config\n            .installed_toolchains\n            .iter()\n            .map(|version| {\n                #[cfg(target_os = \"windows\")]\n                {\n                    let path = format!(\n                        \"{}/toolchains/{}\",\n                        swiftly_home_dir.as_ref().unwrap(),\n                        version\n                    );\n                    Toolchain {\n                        version: version.clone(),\n                        path,\n                        is_swiftly: true,\n                    }\n                }\n                #[cfg(not(target_os = \"windows\"))]\n                {\n                    let path = PathBuf::from(swiftly_home_dir.as_ref().unwrap())\n                        .join(\"toolchains\")\n                        .join(version);\n                    Toolchain {\n                        version: version.clone(),\n                        path: path.to_string_lossy().to_string(),\n                        is_swiftly: true,\n                    }\n                }\n            })\n            .collect();\n\n        let mut toolchains = Vec::new();\n        for toolchain in toolchains_unfiltered {\n            if validate_toolchain(&toolchain.path) {\n                toolchains.push(toolchain);\n            }\n        }\n\n        return Ok(ToolchainResult {\n            swiftly_installed: true,\n            swiftly_version: Some(config.version),\n            toolchains,\n        });\n    } else {\n        return Ok(ToolchainResult {\n            swiftly_installed: false,\n            swiftly_version: None,\n            toolchains: vec![],\n        });\n    }\n}\n\nfn get_swiftly_config() -> Result<SwiftlyConfig, String> {\n    let swiftly_home_dir = get_swiftly_path().ok_or(\"Swiftly home directory not found\")?;\n    let swiftly_home_dir = windows_path(&swiftly_home_dir)?;\n\n    let config_path = format!(\"{}/config.json\", swiftly_home_dir);\n\n    let content = std::fs::read_to_string(&config_path)\n        .map_err(|_| \"Failed to read config file\".to_string())?;\n\n    // TODO: why?\n    let content = content.trim_end_matches('%').to_string();\n    let config: SwiftlyConfig = serde_json::from_str(&content)\n        .map_err(|e| format!(\"Failed to parse config file: {}\", e))?;\n\n    Ok(config)\n}\n\nfn get_swiftly_path() -> Option<String> {\n    let swiftly_home_dir = linux_env(\"SWIFTLY_HOME_DIR\").unwrap_or_default();\n    if !swiftly_home_dir.is_empty() {\n        return Some(swiftly_home_dir);\n    }\n    let home_dir = linux_env(\"HOME\").unwrap_or_default();\n    if !home_dir.is_empty() {\n        let swiftly_path = format!(\"{}/.local/share/swiftly\", home_dir);\n        if std::path::Path::new(&swiftly_path).exists() {\n            return Some(swiftly_path);\n        }\n    }\n\n    None\n}\n\nasync fn build_swift_internal(\n    window: &Window,\n    folder: &str,\n    toolchain_path: &str,\n    build_settings: BuildSettings,\n    emit_exit_code: bool,\n) -> Result<(PathBuf, ProjectConfig), String> {\n    let config = match ProjectConfig::load(PathBuf::from(&folder), &toolchain_path) {\n        Ok(config) => config,\n        Err(e) => {\n            return emit_error_and_return(&window, &format!(\"Failed to load project config: {}\", e))\n        }\n    };\n    let swift_bin = SwiftBin::new(&toolchain_path)?;\n    let mut cmd = swift_bin.command();\n    cmd.arg(\"build\")\n        .arg(\"-c\")\n        .arg(if build_settings.debug {\n            \"debug\"\n        } else {\n            \"release\"\n        })\n        .arg(\"--swift-sdk\")\n        .arg(\"arm64-apple-ios\")\n        .current_dir(&folder);\n\n    pipe_command(&mut cmd, &window, emit_exit_code).await?;\n\n    match pack(PathBuf::from(&folder), &config, &build_settings) {\n        Ok(app) => {\n            window\n                .emit(\"build-output\", \"Pack Success\")\n                .expect(\"failed to send output\");\n            Ok((app, config))\n        }\n        Err(e) => emit_error_and_return(&window, &format!(\"Failed to pack app: {}\", e)),\n    }\n}\n\n#[tauri::command]\npub async fn build_swift(\n    window: tauri::Window,\n    folder: String,\n    toolchain_path: String,\n    debug: bool,\n) -> Result<(), String> {\n    let build_settings = BuildSettings { debug };\n    if !validate_toolchain(&toolchain_path) {\n        return emit_error_and_return(&window, \"Invalid Toolchain\");\n    }\n\n    let (app, config) =\n        build_swift_internal(&window, &folder, &toolchain_path, build_settings, true).await?;\n\n    let ipa_path = zip_ipa(app, &config);\n    if ipa_path.is_err() {\n        return emit_error_and_return(\n            &window,\n            &format!(\"Failed to zip IPA: {}\", ipa_path.err().unwrap()),\n        );\n    }\n    let ipa_path = ipa_path.unwrap();\n\n    window\n        .emit(\n            \"build-output\",\n            format!(\"Build Success, output file at {}\", ipa_path.display()),\n        )\n        .expect(\"failed to send output\");\n\n    Ok(())\n}\n\n#[tauri::command]\npub async fn clean_swift(\n    window: tauri::Window,\n    folder: String,\n    toolchain_path: String,\n) -> Result<(), String> {\n    let swift_bin = SwiftBin::new(&toolchain_path)?;\n    let mut cmd = swift_bin.command();\n    cmd.arg(\"package\").arg(\"clean\").current_dir(folder);\n\n    window\n        .emit(\"build-output\", \"Cleaning...\")\n        .expect(\"failed to send output\");\n\n    pipe_command(&mut cmd, &window, true).await\n}\n\n#[tauri::command]\npub async fn deploy_swift(\n    handle: tauri::AppHandle,\n    window: tauri::Window,\n    anisette_server: String,\n    device: DeviceInfo,\n    folder: String,\n    toolchain_path: String,\n    debug: bool,\n) -> Result<(), String> {\n    let build_settings = BuildSettings { debug };\n    if !validate_toolchain(&toolchain_path) {\n        return emit_error_and_return(&window, \"Invalid Toolchain\");\n    }\n\n    let (app, _) =\n        build_swift_internal(&window, &folder, &toolchain_path, build_settings, false).await?;\n\n    sideload_app(&handle, &window, anisette_server, device, app)\n        .await\n        .map_err(|e| format!(\"Failed to sideload app: {}\", e))?;\n\n    window\n        .emit(\"build-output\", \"Build & Install Success\")\n        .expect(\"failed to send output\");\n\n    Ok(())\n}\n\npub async fn pipe_command(\n    cmd: &mut Command,\n    window: &tauri::Window,\n    emit_exit_code: bool,\n) -> Result<(), String> {\n    let name = \"build-output\";\n    cmd.stdout(Stdio::piped());\n    cmd.stderr(Stdio::piped());\n\n    let mut command = match cmd.spawn() {\n        Ok(cmd) => cmd,\n        Err(_) => {\n            return emit_error_and_return(&window, \"Failed to spawn build command\");\n        }\n    };\n\n    let stdout = match command.stdout.take() {\n        Some(out) => out,\n        None => {\n            return emit_error_and_return(&window, \"Failed to get stdout\");\n        }\n    };\n\n    let stderr = match command.stderr.take() {\n        Some(err) => err,\n        None => {\n            return emit_error_and_return(&window, \"Failed to get stderr\");\n        }\n    };\n\n    let stdout_handle = spawn_output_thread(stdout, window.clone(), name.to_string());\n    let stderr_handle = spawn_output_thread(stderr, window.clone(), name.to_string());\n\n    stdout_handle.join().expect(\"stdout thread panicked\");\n    stderr_handle.join().expect(\"stderr thread panicked\");\n\n    let exit_status = match command.wait() {\n        Ok(status) => status,\n        Err(_) => {\n            return emit_error_and_return(&window, \"Failed to wait for command\");\n        }\n    };\n\n    let exit_code = exit_status.code().unwrap_or(1);\n\n    if exit_code != 0 || emit_exit_code {\n        window\n            .emit(name, format!(\"command.done.{}\", exit_code))\n            .expect(\"failed to send output\");\n    }\n\n    if exit_code != 0 {\n        return Err(format!(\"Command exited with code {}\", exit_code));\n    }\n\n    Ok(())\n}\n\nfn spawn_output_thread<R: std::io::Read + Send + 'static>(\n    reader: R,\n    window: tauri::Window,\n    name: String,\n) -> std::thread::JoinHandle<()> {\n    thread::spawn(move || {\n        let reader = BufReader::new(reader);\n        for line in reader.lines() {\n            match line {\n                Ok(line) => {\n                    window.emit(&name, line).expect(\"failed to send output\");\n                }\n                Err(err) => {\n                    window\n                        .emit(&name, \"command.done.999\".to_string())\n                        .expect(\"failed to send output\");\n                    eprintln!(\"Error reading output: {}\", err);\n                    return;\n                }\n            }\n        }\n    })\n}\n"
  },
  {
    "path": "src-tauri/src/lsp_utils.rs",
    "content": "use std::path::PathBuf;\n\nuse sysinfo::System;\n\nuse crate::builder::config::{ProjectConfig, ProjectValidation};\n\n#[tauri::command]\npub fn has_limited_ram() -> bool {\n    let s = System::new_all();\n    let mem_gib = s.total_memory() as f64 / (1024.0 * 1024.0 * 1024.0);\n    // This is intended to be 16gb, however 16gb of physical ram does not always translate to 16gb of usable memory.\n    mem_gib < 14.0\n}\n\n#[tauri::command]\npub fn validate_project(project_path: String, toolchain_path: String) -> ProjectValidation {\n    ProjectConfig::validate(PathBuf::from(project_path), &toolchain_path)\n}\n\n// #[tauri::command]\n// pub fn ensure_lsp_config(project_path: String) -> Result<(), String> {\n//     let project_path = PathBuf::from(project_path);\n//     if !project_path.exists() {\n//         return Err(format!(\"Project path does not exist: {:?}\", project_path));\n//     }\n\n//     let sourcekit_lsp_path = project_path.join(\".sourcekit-lsp\");\n//     if !sourcekit_lsp_path.exists() {\n//         fs::create_dir_all(sourcekit_lsp_path).map_err(|e| e.to_string())?;\n//     }\n\n//     let config_path = project_path.join(\".sourcekit-lsp\").join(\"config.json\");\n//     if !config_path.exists() {\n//         fs::write(config_path, \"{\n//   \\\"$schema\\\": \\\"https://raw.githubusercontent.com/swiftlang/sourcekit-lsp/refs/heads/release/6.2/config.schema.json\\\",\n//   \\\"swiftPM\\\": {\n//     \\\"swiftSDK\\\": \\\"arm64-apple-ios\\\"\n//   }\n// }\").map_err(|e| e.to_string())?;\n//     }\n//     Ok(())\n// }\n"
  },
  {
    "path": "src-tauri/src/main.rs",
    "content": "// Prevents additional console window on Windows in release, DO NOT REMOVE!!\n#![cfg_attr(not(debug_assertions), windows_subsystem = \"windows\")]\n\n#[macro_use]\nmod templates;\n#[macro_use]\nmod windows;\n#[macro_use]\nmod builder;\nmod operation;\n#[macro_use]\nmod sideloader;\n#[macro_use]\nmod sourcekit_lsp;\n#[macro_use]\nmod lsp_utils;\n\nuse builder::crossplatform::{linux_path, windows_path};\nuse builder::icon::import_icon;\nuse builder::sdk::install_sdk_operation;\nuse builder::swift::{\n    build_swift, clean_swift, deploy_swift, get_swiftly_toolchains, get_toolchain_info,\n    has_darwin_sdk, validate_toolchain,\n};\nuse lsp_utils::{has_limited_ram, validate_project};\nuse serde_json::Value;\nuse sideloader::{\n    apple_commands::{\n        delete_app_id, delete_stored_credentials, get_apple_email, get_certificates, list_app_ids,\n        reset_anisette, revoke_certificate,\n    },\n    device::{is_ddi_mounted, mount_ddi},\n    screenshot::take_screenshot,\n    sideload::refresh_idevice,\n    stdout::{is_streaming_stdout, start_stream_stdout, stop_stream_stdout, StdoutStream},\n    syslog::{is_streaming_syslog, start_stream_syslog, stop_stream_syslog, SyslogStream},\n};\nuse sourcekit_lsp::{get_server_status, start_sourcekit_server, stop_sourcekit_server};\nuse std::sync::Arc;\nuse tauri::Emitter;\nuse tauri::Manager;\nuse tauri_plugin_cli::CliExt;\nuse tauri_plugin_store::StoreExt;\nuse templates::create_template;\nuse tokio::sync::Mutex;\nuse windows::{has_wsl, install_wsl, is_windows};\n\nfn main() {\n    let _ = fix_path_env::fix();\n\n    #[cfg(target_os = \"linux\")]\n    {\n        use std::env;\n        if env::var_os(\"__NV_DISABLE_EXPLICIT_SYNC\").is_none() {\n            env::set_var(\"__NV_DISABLE_EXPLICIT_SYNC\", \"1\");\n        }\n    }\n\n    let syslog_stream: SyslogStream = SyslogStream(Arc::new(Mutex::new(None)));\n    let stdout_stream: StdoutStream = Arc::new(Mutex::new(None));\n\n    tauri::Builder::default()\n        .plugin(tauri_plugin_updater::Builder::new().build())\n        .plugin(tauri_plugin_process::init())\n        .plugin(tauri_plugin_cli::init())\n        .plugin(tauri_plugin_os::init())\n        .plugin(tauri_plugin_opener::init())\n        .plugin(tauri_plugin_store::Builder::new().build())\n        .plugin(tauri_plugin_dialog::init())\n        .plugin(tauri_plugin_fs::init())\n        .plugin(tauri_plugin_shell::init())\n        .manage(sourcekit_lsp::create_server_state())\n        .manage(syslog_stream)\n        .manage(stdout_stream)\n        .setup(|app| {\n            match app.cli().matches() {\n                Ok(matches) => {\n                    if let Some(arg) = matches.args.get(\"showMainWindow\") {\n                        if arg.value == Value::Bool(true) {\n                            let window = app.get_webview_window(\"main\").unwrap();\n                            window.show().unwrap();\n                            window.open_devtools();\n                        }\n                    }\n                }\n                Err(_) => {}\n            }\n\n            let store = app.store(\"preferences.json\")?;\n\n            let open_last = if store.has(\"general/startup\") {\n                store.get(\"general/startup\").unwrap().as_str().unwrap() == \"open-last\"\n            } else {\n                true\n            };\n\n            if open_last {\n                if let Some(last_project) = store.get(\"last-opened-project\") {\n                    if last_project.is_string() {\n                        let path = last_project.as_str().unwrap();\n                        let url_str = format!(\"/ide/{}\", path);\n                        app.get_webview_window(\"main\")\n                            .unwrap()\n                            .eval(&format!(\"window.location.replace('{}')\", url_str))?;\n                    }\n                }\n            }\n\n            Ok(())\n        })\n        .on_window_event(|window, event| match event {\n            tauri::WindowEvent::Destroyed => {\n                if window.label() == \"main\" {\n                    window.app_handle().exit(0);\n                }\n            }\n            _ => {}\n        })\n        .invoke_handler(tauri::generate_handler![\n            is_windows,\n            has_wsl,\n            build_swift,\n            deploy_swift,\n            clean_swift,\n            refresh_idevice,\n            delete_stored_credentials,\n            reset_anisette,\n            get_apple_email,\n            revoke_certificate,\n            get_certificates,\n            list_app_ids,\n            delete_app_id,\n            create_template,\n            get_swiftly_toolchains,\n            validate_toolchain,\n            get_toolchain_info,\n            install_sdk_operation,\n            has_darwin_sdk,\n            start_sourcekit_server,\n            stop_sourcekit_server,\n            get_server_status,\n            has_limited_ram,\n            validate_project,\n            linux_path,\n            windows_path,\n            start_stream_syslog,\n            stop_stream_syslog,\n            import_icon,\n            is_streaming_syslog,\n            open_devtools,\n            start_stream_stdout,\n            stop_stream_stdout,\n            is_streaming_stdout,\n            install_wsl,\n            is_ddi_mounted,\n            mount_ddi,\n            take_screenshot,\n        ])\n        .run(tauri::generate_context!())\n        .expect(\"error while running tauri application\");\n}\n\npub fn emit_error_and_return<T>(window: &tauri::Window, msg: &str) -> Result<T, String> {\n    window.emit(\"build-output\", msg.to_string()).ok();\n    window.emit(\"build-output\", \"command.done.999\").ok();\n    Err(msg.to_string())\n}\n\n#[tauri::command]\nfn open_devtools(app: tauri::AppHandle) -> Result<(), String> {\n    app.get_webview_window(\"main\").unwrap().open_devtools();\n    Ok(())\n}\n"
  },
  {
    "path": "src-tauri/src/operation.rs",
    "content": "use serde::Serialize;\nuse tauri::{Emitter, Window};\n\npub struct Operation<'a> {\n    id: String,\n    window: &'a Window,\n}\n\n#[derive(Clone, Serialize)]\n#[serde(rename_all = \"camelCase\")]\nstruct OperationUpdate<'a> {\n    update_type: &'a str,\n    step_id: &'a str,\n    extra_details: Option<String>,\n}\n\nimpl<'a> Operation<'a> {\n    pub fn new(id: String, window: &'a Window) -> Operation<'a> {\n        Operation { id, window }\n    }\n\n    pub fn move_on(&self, old_id: &str, new_id: &str) -> Result<(), String> {\n        self.complete(old_id)?;\n        self.start(new_id)\n    }\n\n    pub fn start(&self, id: &str) -> Result<(), String> {\n        self.window\n            .emit(\n                &format!(\"operation_{}\", self.id),\n                OperationUpdate {\n                    update_type: \"started\",\n                    step_id: id,\n                    extra_details: None,\n                },\n            )\n            .map_err(|_| \"Failed to emit status to frontend\".to_string())\n    }\n\n    pub fn complete(&self, id: &str) -> Result<(), String> {\n        self.window\n            .emit(\n                &format!(\"operation_{}\", self.id),\n                OperationUpdate {\n                    update_type: \"finished\",\n                    step_id: id,\n                    extra_details: None,\n                },\n            )\n            .map_err(|_| \"Failed to emit status to frontend\".to_string())\n    }\n\n    pub fn fail<T>(&self, id: &str, error: String) -> Result<T, String> {\n        self.window\n            .emit(\n                &format!(\"operation_{}\", self.id),\n                OperationUpdate {\n                    update_type: \"failed\",\n                    step_id: id,\n                    extra_details: Some(error.clone()),\n                },\n            )\n            .map_err(|_| \"Failed to emit status to frontend\".to_string())?;\n        return Err(error);\n    }\n\n    pub fn fail_if_err<T>(&self, id: &str, res: Result<T, String>) -> Result<T, String> {\n        match res {\n            Ok(t) => Ok(t),\n            Err(e) => self.fail::<T>(id, e),\n        }\n    }\n\n    pub fn fail_if_err_map<T, E, O: FnOnce(E) -> String>(\n        &self,\n        id: &str,\n        res: Result<T, E>,\n        map_err: O,\n    ) -> Result<T, String> {\n        match res {\n            Ok(t) => Ok(t),\n            Err(e) => {\n                let err = map_err(e);\n                self.fail::<T>(id, err.clone())\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src-tauri/src/sideloader/apple.rs",
    "content": "use isideload::{developer_session::DeveloperSession, AnisetteConfiguration, AppleAccount};\nuse once_cell::sync::OnceCell;\nuse serde_json::Value;\nuse std::{\n    sync::{mpsc::RecvTimeoutError, Arc, Mutex},\n    time::Duration,\n};\nuse tauri::{Emitter, Listener, Manager};\n\nuse crate::sideloader::apple_commands::{get_stored_credentials, store_credentials};\n\npub static APPLE_ACCOUNT: OnceCell<Mutex<Option<Arc<AppleAccount>>>> = OnceCell::new();\n\npub async fn get_account(\n    handle: &tauri::AppHandle,\n    window: &tauri::Window,\n    anisette_server: String,\n) -> Result<Arc<AppleAccount>, String> {\n    let cell = APPLE_ACCOUNT.get_or_init(|| Mutex::new(None));\n    {\n        let account_guard = cell.lock().unwrap();\n        if let Some(account) = &*account_guard {\n            return Ok(account.clone());\n        }\n    }\n\n    let account = login(handle, window, anisette_server).await?;\n    let mut account_guard = cell.lock().unwrap();\n    *account_guard = Some(account.clone());\n    Ok(account)\n}\n\npub async fn get_developer_session(\n    handle: &tauri::AppHandle,\n    window: &tauri::Window,\n    anisette_server: String,\n) -> Result<DeveloperSession, String> {\n    let account = get_account(handle, window, anisette_server.clone()).await?;\n\n    let mut dev_session = DeveloperSession::new(account);\n\n    let teams = match dev_session.list_teams().await {\n        Ok(t) => t,\n        Err(e) => {\n            // This code means we have been logged in for too long and we must relogin again\n            let is_22411 = match &e {\n                isideload::Error::Auth(code, _) => *code == -22411,\n                isideload::Error::DeveloperSession(code, _) => *code == -22411,\n                _ => false,\n            };\n            if is_22411 {\n                invalidate_account();\n                let account = get_account(handle, window, anisette_server).await?;\n                dev_session = DeveloperSession::new(account);\n                match dev_session.list_teams().await {\n                    Ok(t) => t,\n                    Err(e) => {\n                        return Err(format!(\"Failed to list teams after re-login: {:?}\", e));\n                    }\n                }\n            } else {\n                return Err(format!(\"Failed to list teams: {:?}\", e));\n            }\n        }\n    };\n\n    dev_session.set_team(teams[0].clone());\n\n    Ok(dev_session)\n}\n\npub async fn login(\n    handle: &tauri::AppHandle,\n    window: &tauri::Window,\n    anisette_server: String,\n) -> Result<Arc<AppleAccount>, String> {\n    let (tx, rx) = std::sync::mpsc::channel::<String>();\n    let window_clone = window.clone();\n\n    let appleid_closure = move || -> Result<(String, String), String> {\n        if let Some((email, password)) = get_stored_credentials() {\n            window_clone\n                .emit(\n                    \"build-output\",\n                    \"Using stored Apple ID credentials\".to_string(),\n                )\n                .ok();\n            return Ok((email, password));\n        }\n\n        window_clone\n            .emit(\"apple-id-required\", ())\n            .expect(\"Failed to emit apple-id-required event\");\n\n        let tx1 = tx.clone();\n        let handler_id_recieved = window_clone.listen(\"apple-id-recieved\", move |event| {\n            let json = event.payload();\n            let _ = tx1.send(format!(\"apple-id-recieved:{}\", json));\n        });\n\n        let tx2 = tx.clone();\n        let handler_id_cancelled = window_clone.listen(\"login-cancelled\", move |_event| {\n            let _ = tx2.send(\"login-cancelled\".to_string());\n        });\n\n        let result = rx.recv_timeout(Duration::from_secs(120));\n        window_clone.unlisten(handler_id_recieved);\n        window_clone.unlisten(handler_id_cancelled);\n\n        match result {\n            Ok(msg) if msg.starts_with(\"apple-id-recieved:\") => {\n                let json = &msg[\"apple-id-recieved:\".len()..];\n                let json: Value = serde_json::from_str(json).expect(\"Failed to parse json\");\n                let apple_id = json\n                    .get(\"appleId\")\n                    .and_then(Value::as_str)\n                    .expect(\"Failed to get apple_id from json\")\n                    .to_string();\n                let password = json\n                    .get(\"applePass\")\n                    .and_then(Value::as_str)\n                    .expect(\"Failed to get password from json\")\n                    .to_string();\n                let save_credentials = json\n                    .get(\"saveCredentials\")\n                    .and_then(Value::as_bool)\n                    .unwrap_or(false);\n\n                if save_credentials {\n                    if let Err(e) = store_credentials(&apple_id, &password) {\n                        window_clone\n                            .emit(\n                                \"build-output\",\n                                format!(\"Failed to save credentials: {:?}\", e),\n                            )\n                            .ok();\n                    }\n                }\n\n                Ok((apple_id, password))\n            }\n            Ok(msg) if msg == \"login-cancelled\" => {\n                window_clone\n                    .emit(\"build-output\", \"Login cancelled by user\".to_string())\n                    .ok();\n                Err(\"Login cancelled by user\".to_string())\n            }\n            Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) | _ => {\n                window_clone\n                    .emit(\"build-output\", \"Login cancelled or timed out\".to_string())\n                    .ok();\n                Err(\"Login cancelled or timed out\".to_string())\n            }\n        }\n    };\n\n    let (tx, rx) = std::sync::mpsc::channel::<String>();\n    let window_clone = window.clone();\n    let tfa_closure = move || -> Result<String, String> {\n        window_clone\n            .emit(\"2fa-required\", ())\n            .expect(\"Failed to emit 2fa-required event\");\n\n        let tx = tx.clone();\n        let handler_id = window_clone.listen(\"2fa-recieved\", move |event| {\n            let code = event.payload();\n            let _ = tx.send(code.to_string());\n        });\n\n        let result = rx.recv_timeout(Duration::from_secs(120));\n        window_clone.unlisten(handler_id);\n\n        match result {\n            Ok(code) => {\n                let code = code.trim_matches('\"').to_string();\n                Ok(code)\n            }\n            Err(RecvTimeoutError::Timeout) => Err(\"2FA cancelled or timed out\".to_string()),\n            Err(RecvTimeoutError::Disconnected) => Err(\"2FA disconnected\".to_string()),\n        }\n    };\n\n    let config = AnisetteConfiguration::default();\n    let config =\n        config.set_configuration_path(handle.path().app_config_dir().map_err(|e| e.to_string())?);\n    let config = config.set_anisette_url(format!(\"https://{}\", anisette_server));\n    window\n        .emit(\"build-output\", \"Logging in...\")\n        .map_err(|e| e.to_string())?;\n\n    let account = AppleAccount::login(appleid_closure, tfa_closure, config).await;\n    if let Err(e) = account {\n        window\n            .emit(\"build-output\", \"Login failed or cancelled\".to_string())\n            .ok();\n        window.emit(\"build-output\", format!(\"{:?}\", e)).ok();\n        return Err(format!(\"{:?}\", e));\n    }\n    let account = Arc::new(account.unwrap());\n    window\n        .emit(\"build-output\", \"Successfully logged in\".to_string())\n        .map_err(|e| e.to_string())?;\n\n    Ok(account)\n}\n\npub fn invalidate_account() {\n    let cell = APPLE_ACCOUNT.get();\n    if let Some(account) = cell {\n        let mut account_guard = account.lock().unwrap();\n        *account_guard = None;\n    }\n}\n"
  },
  {
    "path": "src-tauri/src/sideloader/apple_commands.rs",
    "content": "use isideload::developer_session::{DeveloperDeviceType, ListAppIdsResponse};\nuse keyring::{Entry, Error as KeyringError};\nuse serde::{Deserialize, Serialize};\nuse tauri::Manager;\n\nuse crate::sideloader::apple::APPLE_ACCOUNT;\n\npub fn store_credentials(email: &str, password: &str) -> Result<(), KeyringError> {\n    let email_entry = Entry::new(\"crosscode\", \"apple_id_email\")?;\n    email_entry.set_password(email)?;\n    let pass_entry = Entry::new(\"crosscode\", email)?;\n    pass_entry.set_password(password)\n}\n\npub fn get_stored_credentials() -> Option<(String, String)> {\n    let email_entry = Entry::new(\"crosscode\", \"apple_id_email\").ok()?;\n    let email = email_entry.get_password().ok()?;\n    let pass_entry = Entry::new(\"crosscode\", &email).ok()?;\n    let password = pass_entry.get_password().ok()?;\n    Some((email, password))\n}\n\n#[tauri::command]\npub fn get_apple_email() -> String {\n    let credentials = get_stored_credentials();\n    if credentials.is_none() {\n        return \"\".to_string();\n    }\n    let (email, _) = credentials.unwrap();\n    email\n}\n\n#[tauri::command]\npub fn delete_stored_credentials() -> Result<(), String> {\n    let email_entry =\n        Entry::new(\"crosscode\", \"apple_id_email\").map_err(|e| format!(\"Keyring error: {:?}\", e))?;\n    let email = match email_entry.get_password() {\n        Ok(email) => email,\n        Err(_) => {\n            return Ok(());\n        }\n    };\n    let pass_entry =\n        Entry::new(\"crosscode\", &email).map_err(|e| format!(\"Keyring error: {:?}\", e))?;\n\n    pass_entry\n        .delete_password()\n        .map_err(|e| format!(\"Keyring error: {:?}\", e))?;\n    email_entry\n        .delete_password()\n        .map_err(|e| format!(\"Keyring error: {:?}\", e))?;\n\n    if let Some(account) = APPLE_ACCOUNT.get() {\n        let mut account_guard = account.lock().unwrap();\n        *account_guard = None;\n    }\n    Ok(())\n}\n\n#[tauri::command]\npub async fn reset_anisette(handle: tauri::AppHandle) -> Result<(), String> {\n    let config_dir = handle.path().app_config_dir().map_err(|e| e.to_string())?;\n    let status_path = config_dir.join(\"state.plist\");\n    if status_path.exists() {\n        std::fs::remove_file(&status_path).map_err(|e| e.to_string())?;\n    }\n\n    Ok(())\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CertificateInfo {\n    pub name: String,\n    pub certificate_id: String,\n    pub serial_number: String,\n    pub machine_name: String,\n}\n\n#[tauri::command]\npub async fn get_certificates(\n    handle: tauri::AppHandle,\n    window: tauri::Window,\n    anisette_server: String,\n) -> Result<Vec<CertificateInfo>, String> {\n    let dev_session =\n        crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())\n            .await?;\n    let team = dev_session\n        .get_team()\n        .await\n        .map_err(|e| format!(\"Failed to get developer team: {:?}\", e))?;\n    let certificates = dev_session\n        .list_all_development_certs(DeveloperDeviceType::Ios, &team)\n        .await\n        .map_err(|e| format!(\"Failed to get development certificates: {:?}\", e))?;\n    Ok(certificates\n        .into_iter()\n        .map(|cert| CertificateInfo {\n            name: cert.name,\n            certificate_id: cert.certificate_id,\n            serial_number: cert.serial_number,\n            machine_name: cert.machine_name,\n        })\n        .collect())\n}\n\n#[tauri::command]\npub async fn revoke_certificate(\n    handle: tauri::AppHandle,\n    window: tauri::Window,\n    anisette_server: String,\n    serial_number: String,\n) -> Result<(), String> {\n    let dev_session =\n        crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())\n            .await?;\n    let team = dev_session\n        .get_team()\n        .await\n        .map_err(|e| format!(\"Failed to get developer team: {:?}\", e))?;\n    dev_session\n        .revoke_development_cert(DeveloperDeviceType::Ios, &team, &serial_number)\n        .await\n        .map_err(|e| format!(\"Failed to revoke development certificates: {:?}\", e))?;\n    Ok(())\n}\n\n#[tauri::command]\npub async fn list_app_ids(\n    handle: tauri::AppHandle,\n    window: tauri::Window,\n    anisette_server: String,\n) -> Result<ListAppIdsResponse, String> {\n    let dev_session =\n        crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())\n            .await?;\n    let team = dev_session\n        .get_team()\n        .await\n        .map_err(|e| format!(\"Failed to get developer team: {:?}\", e))?;\n    let app_ids = dev_session\n        .list_app_ids(DeveloperDeviceType::Ios, &team)\n        .await\n        .map_err(|e| format!(\"Failed to list App IDs: {:?}\", e))?;\n    Ok(app_ids)\n}\n\n#[tauri::command]\npub async fn delete_app_id(\n    handle: tauri::AppHandle,\n    window: tauri::Window,\n    anisette_server: String,\n    app_id_id: String,\n) -> Result<(), String> {\n    let dev_session =\n        crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())\n            .await?;\n    let team = dev_session\n        .get_team()\n        .await\n        .map_err(|e| format!(\"Failed to get developer team: {:?}\", e))?;\n    dev_session\n        .delete_app_id(DeveloperDeviceType::Ios, &team, app_id_id)\n        .await\n        .map_err(|e| format!(\"Failed to delete App ID: {:?}\", e))?;\n    Ok(())\n}\n"
  },
  {
    "path": "src-tauri/src/sideloader/device.rs",
    "content": "use std::path::PathBuf;\n\nuse idevice::{\n    lockdown::LockdownClient,\n    mobile_image_mounter::ImageMounter,\n    provider::UsbmuxdProvider,\n    usbmuxd::{UsbmuxdAddr, UsbmuxdConnection},\n    IdeviceService,\n};\nuse serde::{Deserialize, Serialize};\nuse tauri::{AppHandle, Emitter, Manager, Window};\n\nconst BUILD_MANIFEST_URL: &str =\n    \"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/PersonalizedImages/Xcode_iOS_DDI_Personalized/BuildManifest.plist\";\nconst PERSONALIZED_IMAGE_URL: &str =\n    \"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/PersonalizedImages/Xcode_iOS_DDI_Personalized/Image.dmg\";\nconst TRUST_CACHE_URL: &str = \"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/PersonalizedImages/Xcode_iOS_DDI_Personalized/Image.dmg.trustcache\";\n\n#[derive(Deserialize, Serialize, Clone)]\npub struct DeviceInfo {\n    pub name: String,\n    pub id: u32,\n    pub uuid: String,\n}\n\npub async fn list_devices() -> Result<Vec<DeviceInfo>, String> {\n    let usbmuxd = UsbmuxdConnection::default().await;\n    if usbmuxd.is_err() {\n        eprintln!(\"Failed to connect to usbmuxd: {:?}\", usbmuxd.err());\n        return Err(\"Failed to connect to usbmuxd\".to_string());\n    }\n    let mut usbmuxd = usbmuxd.unwrap();\n\n    let devs = usbmuxd.get_devices().await.unwrap();\n    if devs.is_empty() {\n        return Ok(vec![]);\n    }\n\n    let device_info_futures: Vec<_> = devs\n        .iter()\n        .map(|d| async move {\n            let provider = d.to_provider(UsbmuxdAddr::from_env_var().unwrap(), \"crosscode\");\n            let device_uid = d.device_id;\n\n            let mut lockdown_client = match LockdownClient::connect(&provider).await {\n                Ok(l) => l,\n                Err(e) => {\n                    eprintln!(\"Unable to connect to lockdown: {e:?}\");\n                    return DeviceInfo {\n                        name: String::from(\"Unknown Device\"),\n                        id: device_uid,\n                        uuid: d.udid.clone(),\n                    };\n                }\n            };\n\n            let device_name = lockdown_client\n                .get_value(Some(\"DeviceName\"), None)\n                .await\n                .expect(\"Failed to get device name\")\n                .as_string()\n                .expect(\"Failed to convert device name to string\")\n                .to_string();\n\n            DeviceInfo {\n                name: device_name,\n                id: device_uid,\n                uuid: d.udid.clone(),\n            }\n        })\n        .collect();\n\n    Ok(futures::future::join_all(device_info_futures).await)\n}\n\npub async fn get_provider(device: &DeviceInfo) -> Result<UsbmuxdProvider, String> {\n    let mut usbmuxd = UsbmuxdConnection::default()\n        .await\n        .map_err(|e| format!(\"Failed to connect to usbmuxd: {}\", e))?;\n    let device_info = usbmuxd\n        .get_device(&device.uuid)\n        .await\n        .map_err(|e| format!(\"Failed to get device: {}\", e))?;\n\n    let provider = device_info.to_provider(UsbmuxdAddr::from_env_var().unwrap(), \"crosscode\");\n    Ok(provider)\n}\n\n#[tauri::command]\npub async fn is_ddi_mounted(device: DeviceInfo) -> Result<bool, String> {\n    let provider = get_provider(&device).await?;\n\n    let mut mounter_client = ImageMounter::connect(&provider).await.map_err(|e| {\n        format!(\n            \"Failed to connect to mobile image mounter on device {}: {}\",\n            device.name, e\n        )\n    })?;\n\n    let devices = mounter_client.copy_devices().await.map_err(|e| {\n        format!(\n            \"Failed to get mounted images on device {}: {}\",\n            device.name, e\n        )\n    })?;\n\n    Ok(devices.len() > 0)\n}\n\n// https://github.com/jkcoxson/idevice/blob/master/tools/src/mounter.rs\n#[tauri::command]\npub async fn mount_ddi(app: AppHandle, window: Window, device: DeviceInfo) -> Result<(), String> {\n    let provider = get_provider(&device).await?;\n\n    let mut mounter_client = ImageMounter::connect(&provider).await.map_err(|e| {\n        format!(\n            \"Failed to connect to mobile image mounter on device {}: {}\",\n            device.name, e\n        )\n    })?;\n\n    let mut lockdown_client = LockdownClient::connect(&provider)\n        .await\n        .map_err(|e| format!(\"Failed to connect to lockdown: {}\", e))?;\n\n    let product_version = lockdown_client\n        .get_value(Some(\"ProductVersion\"), None)\n        .await\n        .map_err(|e| format!(\"Failed to get product version: {}\", e))?;\n\n    let product_version = product_version\n        .as_string()\n        .ok_or(\"Unexpected value for ProductVersion\")?;\n\n    let product_version_num = product_version.split('.').collect::<Vec<&str>>()[0]\n        .parse::<u8>()\n        .map_err(|e| format!(\"Failed to parse product version: {}\", e))?;\n\n    if product_version_num < 17 {\n        // make sure product version is x.x, trimming the final .x if it exists\n        let product_version = if product_version.matches('.').count() > 1 {\n            let mut parts = product_version.split('.').collect::<Vec<&str>>();\n            parts.pop();\n            parts.join(\".\")\n        } else {\n            product_version.to_string()\n        };\n\n        let (image, signature) = download_ddi(&app, &product_version).await?;\n\n        let image = tokio::fs::read(image)\n            .await\n            .map_err(|e| format!(\"Unable to read image: {}\", e))?;\n        let signature = tokio::fs::read(signature)\n            .await\n            .map_err(|e| format!(\"Unable to read signature: {}\", e))?;\n\n        mounter_client\n            .mount_developer(&image, signature)\n            .await\n            .map_err(|e| format!(\"Unable to mount: {}\", e))?;\n    } else {\n        let (manifest, trust_cache, image) = download_personalized_image(&app).await?;\n\n        let image = tokio::fs::read(image)\n            .await\n            .map_err(|e| format!(\"Unable to read image: {}\", e))?;\n\n        let build_manifest = &tokio::fs::read(manifest)\n            .await\n            .map_err(|e| format!(\"Unable to read build manifest: {}\", e))?;\n\n        let trust_cache = tokio::fs::read(trust_cache)\n            .await\n            .map_err(|e| format!(\"Unable to read trust cache: {}\", e))?;\n\n        let unique_chip_id = lockdown_client\n            .get_value(Some(\"UniqueChipID\"), None)\n            .await\n            .map_err(|e| format!(\"Failed to get UniqueChipID: {}\", e))?\n            .as_unsigned_integer()\n            .ok_or(\"Unexpected value for UniqueChipID\")?;\n\n        mounter_client\n            .mount_personalized_with_callback(\n                &provider,\n                image,\n                trust_cache,\n                build_manifest,\n                None,\n                unique_chip_id,\n                async |((n, d), _)| {\n                    let percent = (n as f64 / d as f64) * 100.0;\n                    window\n                        .emit(\"ddi-mount-progress\", percent)\n                        .unwrap_or_else(|e| {\n                            eprintln!(\"Failed to emit ddi-mount-progress: {}\", e);\n                        });\n                },\n                (),\n            )\n            .await\n            .map_err(|e| format!(\"Unable to mount image: {}\", e))?;\n    }\n\n    Ok(())\n}\n\npub async fn download_ddi(\n    app: &AppHandle,\n    product_version: &str,\n) -> Result<(PathBuf, PathBuf), String> {\n    let config_dir = app.path().app_config_dir().map_err(|e| e.to_string())?;\n    let ddi_path = config_dir.join(\"DDI\");\n\n    let image_path = ddi_path.join(\"DeveloperDiskImage.dmg\");\n    let sig_path = ddi_path.join(\"DeveloperDiskImage.dmg.signature\");\n\n    if !ddi_path.exists() {\n        tokio::fs::create_dir_all(&ddi_path)\n            .await\n            .map_err(|e| format!(\"Failed to create DDI directory: {}\", e))?;\n    }\n\n    let mut download_futures = vec![];\n    if !image_path.exists() {\n        let url = format!(\n        \"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/DeveloperDiskImages/{}/DeveloperDiskImage.dmg\",\n        product_version\n    );\n        download_futures.push(download(url, &image_path));\n    }\n    if !sig_path.exists() {\n        let url = format!(\n        \"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/DeveloperDiskImages/{}/DeveloperDiskImage.dmg.signature\",\n        product_version\n    );\n        download_futures.push(download(url, &sig_path));\n    }\n\n    futures::future::join_all(download_futures).await;\n\n    return Ok((image_path, sig_path));\n}\n\npub async fn download_personalized_image(\n    app: &AppHandle,\n) -> Result<(PathBuf, PathBuf, PathBuf), String> {\n    let config_dir = app.path().app_config_dir().map_err(|e| e.to_string())?;\n    let ddi_path = config_dir.join(\"DDI\");\n\n    let build_manifest_path = ddi_path.join(\"BuildManifest.plist\");\n    let trust_cache_path = ddi_path.join(\"Image.dmg.trustcache\");\n    let image_path = ddi_path.join(\"Image.dmg\");\n\n    if !ddi_path.exists() {\n        tokio::fs::create_dir_all(&ddi_path)\n            .await\n            .map_err(|e| format!(\"Failed to create DDI directory: {}\", e))?;\n    }\n\n    let mut download_futures = vec![];\n    if !build_manifest_path.exists() {\n        download_futures.push(download(BUILD_MANIFEST_URL, &build_manifest_path));\n    }\n    if !trust_cache_path.exists() {\n        download_futures.push(download(TRUST_CACHE_URL, &trust_cache_path));\n    }\n    if !image_path.exists() {\n        download_futures.push(download(PERSONALIZED_IMAGE_URL, &image_path));\n    }\n    futures::future::join_all(download_futures).await;\n\n    return Ok((build_manifest_path, trust_cache_path, image_path));\n}\n\npub async fn download(url: impl AsRef<str>, dest: &PathBuf) -> Result<(), String> {\n    let response = reqwest::get(url.as_ref())\n        .await\n        .map_err(|e| e.to_string())?;\n    if !response.status().is_success() {\n        return Err(format!(\n            \"Failed to download file: HTTP {}\",\n            response.status()\n        ));\n    }\n\n    let bytes = response.bytes().await.map_err(|e| e.to_string())?;\n    tokio::fs::write(dest, &bytes)\n        .await\n        .map_err(|e| e.to_string())?;\n\n    Ok(())\n}\n"
  },
  {
    "path": "src-tauri/src/sideloader/mod.rs",
    "content": "pub mod apple;\npub mod apple_commands;\npub mod device;\npub mod screenshot;\npub mod sideload;\npub mod stdout;\npub mod syslog;\n"
  },
  {
    "path": "src-tauri/src/sideloader/screenshot.rs",
    "content": "use idevice::{\n    core_device_proxy::CoreDeviceProxy,\n    dvt::{remote_server::RemoteServerClient, screenshot::ScreenshotClient},\n    rsd::RsdHandshake,\n    IdeviceService,\n};\n\nuse crate::sideloader::device::{get_provider, DeviceInfo};\n\n#[tauri::command]\npub async fn take_screenshot(device: DeviceInfo) -> Result<Vec<u8>, String> {\n    let provider = get_provider(&device).await?;\n\n    let proxy = CoreDeviceProxy::connect(&provider)\n        .await\n        .map_err(|e| format!(\"Failed to connect to device proxy: {}\", e))?;\n    let rsd_port = proxy.handshake.server_rsd_port;\n\n    let adapter = proxy\n        .create_software_tunnel()\n        .map_err(|e| format!(\"Failed to create software tunnel: {}\", e))?;\n    let mut adapter = adapter.to_async_handle();\n\n    let rsd_stream = adapter\n        .connect(rsd_port)\n        .await\n        .map_err(|e| format!(\"Failed to connect to RSD: {}\", e))?;\n\n    let handshake = RsdHandshake::new(rsd_stream)\n        .await\n        .map_err(|e| format!(\"Failed to create RSD handshake: {}\", e))?;\n\n    let instruments_service = handshake\n        .services\n        .get(\"com.apple.instruments.dtservicehub\")\n        .ok_or(\"Instruments service not found\")?;\n\n    let ts_client_stream = adapter\n        .connect(instruments_service.port)\n        .await\n        .map_err(|e| format!(\"Failed to connect to remote server: {}\", e))?;\n    let mut ts_client = RemoteServerClient::new(ts_client_stream);\n    ts_client\n        .read_message(0)\n        .await\n        .map_err(|e| format!(\"Failed to read message: {}\", e))?;\n    let mut sc = ScreenshotClient::new(&mut ts_client)\n        .await\n        .map_err(|e| format!(\"Failed to create screenshot client: {}\", e))?;\n\n    let screenshot_data = sc\n        .take_screenshot()\n        .await\n        .map_err(|e| format!(\"Failed to take screenshot: {}\", e))?;\n\n    Ok(screenshot_data)\n}\n"
  },
  {
    "path": "src-tauri/src/sideloader/sideload.rs",
    "content": "use std::{path::PathBuf, sync::Arc};\n\nuse crate::sideloader::device::{get_provider, list_devices, DeviceInfo};\nuse isideload::{sideload, Error, SideloadConfiguration, SideloadLogger};\nuse tauri::{Emitter, Manager, Window};\n\npub struct TauriLogger {\n    window: Arc<Window>,\n}\n\nimpl SideloadLogger for TauriLogger {\n    fn log(&self, message: &str) {\n        self.window.emit(\"build-output\", message.to_string()).ok();\n    }\n\n    fn error(&self, error: &Error) {\n        self.window\n            .emit(\"build-output\", format!(\"Error: {}\", error))\n            .ok();\n    }\n}\n\npub async fn sideload_app(\n    handle: &tauri::AppHandle,\n    window: &tauri::Window,\n    anisette_server: String,\n    device: DeviceInfo,\n    app_path: PathBuf,\n) -> Result<(), String> {\n    let dev_session =\n        crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())\n            .await?;\n    let logger = TauriLogger {\n        window: Arc::new(window.clone()),\n    };\n    let store_dir = handle.path().app_config_dir().map_err(|e| e.to_string())?;\n\n    let config = SideloadConfiguration::new()\n        .set_store_dir(store_dir.clone())\n        .set_logger(&logger)\n        .set_machine_name(\"CrossCode\".to_string());\n\n    let provider = get_provider(&device).await?;\n    sideload::sideload_app(&provider, &dev_session, app_path, config)\n        .await\n        .map_err(|e| e.to_string())?;\n\n    Ok(())\n}\n\n#[tauri::command]\npub async fn refresh_idevice(window: tauri::Window) {\n    match list_devices().await {\n        Ok(devices) => {\n            window\n                .emit(\"idevices\", devices)\n                .expect(\"Failed to send devices\");\n        }\n        Err(e) => {\n            window\n                .emit(\"idevices\", Vec::<DeviceInfo>::new())\n                .expect(\"Failed to send error\");\n            eprintln!(\"Failed to list devices: {}\", e);\n        }\n    };\n}\n"
  },
  {
    "path": "src-tauri/src/sideloader/stdout.rs",
    "content": "use crate::{\n    builder::config::TomlConfig,\n    sideloader::{\n        apple::get_developer_session,\n        device::{get_provider, DeviceInfo},\n    },\n};\nuse idevice::{\n    core_device::{AppServiceClient, OpenStdioSocketClient},\n    core_device_proxy::CoreDeviceProxy,\n    rsd::RsdHandshake,\n    IdeviceService, RsdService,\n};\nuse std::{path::PathBuf, sync::Arc};\nuse tauri::{AppHandle, Emitter, State, Window};\nuse tokio::{io::AsyncReadExt, sync::Mutex};\nuse tokio_util::sync::CancellationToken;\n\npub type StdoutStream = Arc<Mutex<Option<CancellationToken>>>;\n\n#[tauri::command]\npub async fn start_stream_stdout(\n    handle: AppHandle,\n    window: Window,\n    device: DeviceInfo,\n    stream: State<'_, StdoutStream>,\n    folder: String,\n    anisette_server: String,\n) -> Result<(), String> {\n    let bundle_id = get_bundle_id(&handle, &window, anisette_server, folder).await?;\n\n    let mut stream_guard = stream.lock().await;\n    if let Some(token) = stream_guard.take() {\n        token.cancel();\n    }\n\n    let provider = get_provider(&device).await?;\n\n    let proxy = CoreDeviceProxy::connect(&provider)\n        .await\n        .map_err(|e| format!(\"Failed to connect to device proxy: {}\", e))?;\n    let rsd_port = proxy.handshake.server_rsd_port;\n\n    let adapter = proxy\n        .create_software_tunnel()\n        .map_err(|e| format!(\"Failed to create software tunnel: {}\", e))?;\n    let mut adapter = adapter.to_async_handle();\n\n    let rsd_stream = adapter\n        .connect(rsd_port)\n        .await\n        .map_err(|e| format!(\"Failed to connect to RSD: {}\", e))?;\n\n    let mut handshake = RsdHandshake::new(rsd_stream)\n        .await\n        .map_err(|e| format!(\"Failed to create RSD handshake: {}\", e))?;\n\n    let mut stdio_conn = OpenStdioSocketClient::connect_rsd(&mut adapter, &mut handshake)\n        .await\n        .map_err(|e| format!(\"Failed to connect to stdio: {}\", e))?;\n\n    let stdio_uuid = stdio_conn\n        .read_uuid()\n        .await\n        .map_err(|e| format!(\"Failed to read stdio UUID: {}\", e))?;\n\n    use tokio::sync::oneshot;\n\n    let (tx, rx) = oneshot::channel();\n\n    let mut adapter_for_launch = adapter;\n    std::thread::spawn(move || {\n        let rt = tokio::runtime::Builder::new_current_thread()\n            .enable_all()\n            .build()\n            .unwrap();\n        let result = rt.block_on(async {\n            let mut asc: AppServiceClient<Box<dyn idevice::ReadWrite>> =\n                AppServiceClient::connect_rsd(&mut adapter_for_launch, &mut handshake)\n                    .await\n                    .map_err(|e| format!(\"Failed to connect to app service: {}\", e))?;\n            asc.launch_application(bundle_id, &[], true, false, None, None, Some(stdio_uuid))\n                .await\n                .map_err(|e| format!(\"Failed to launch application: {}\", e))\n        });\n        let _ = tx.send(result);\n    });\n\n    rx.await.map_err(|_| \"Launch thread failed\".to_string())??;\n\n    let cancellation_token = CancellationToken::new();\n\n    *stream_guard = Some(cancellation_token.clone());\n\n    let stream_clone = stream.inner().clone();\n\n    tokio::spawn(async move {\n        loop {\n            tokio::select! {\n                _ = cancellation_token.cancelled() => {\n                    println!(\"Stdout stream cancelled\");\n                    break;\n                }\n                result = async {\n                    let mut buffer = [0u8; 1024];\n                    let n = stdio_conn.inner.read(&mut buffer).await?;\n                    Ok::<_, std::io::Error>(buffer[..n].to_vec())\n                } => {\n                    match result {\n                        Ok(data) => {\n                            if !data.is_empty() {\n                                if let Ok(log_str) = String::from_utf8(data) {\n                                    window.emit(\"stdout-message\", log_str).unwrap_or_else(|e| {\n                                        eprintln!(\"Failed to emit stdout message: {}\", e);\n                                    });\n                                }\n                            }\n                        }\n                        Err(e) => {\n                            eprintln!(\"Error reading from stdio: {}\", e);\n                            window.emit(\"stdout-message\", \"stdout.done\").unwrap_or_else(|e| {\n                                eprintln!(\"Failed to emit stdout error: {}\", e);\n                            });\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        let mut stream_guard = stream_clone.lock().await;\n        *stream_guard = None;\n    });\n\n    Ok(())\n}\n\nasync fn get_bundle_id(\n    handle: &AppHandle,\n    window: &Window,\n    anisette_server: String,\n    folder: String,\n) -> Result<String, String> {\n    let config = TomlConfig::load_or_default(PathBuf::from(folder))?;\n    let bundle_id = config.project.bundle_id;\n\n    let session = get_developer_session(handle, window, anisette_server).await?;\n\n    let team_id = session\n        .get_team()\n        .await\n        .map_err(|e| format!(\"Failed to get team: {:?}\", e))?\n        .team_id;\n\n    Ok(format!(\"{}.{}\", bundle_id, team_id))\n}\n#[tauri::command]\npub async fn stop_stream_stdout(stream: State<'_, StdoutStream>) -> Result<(), String> {\n    let mut stream_guard = stream.lock().await;\n\n    if let Some(token) = stream_guard.take() {\n        token.cancel();\n        Ok(())\n    } else {\n        Err(\"No active stdout stream found\".to_string())\n    }\n}\n\n#[tauri::command]\npub async fn is_streaming_stdout(stream: State<'_, StdoutStream>) -> Result<bool, String> {\n    let stream_guard = stream.lock().await;\n    Ok(stream_guard.is_some())\n}\n"
  },
  {
    "path": "src-tauri/src/sideloader/syslog.rs",
    "content": "use crate::sideloader::device::{get_provider, DeviceInfo};\nuse idevice::{syslog_relay::SyslogRelayClient, IdeviceService};\nuse std::sync::Arc;\nuse tauri::{Emitter, State, Window};\nuse tokio::sync::Mutex;\nuse tokio_util::sync::CancellationToken;\n\npub struct SyslogStream(pub Arc<Mutex<Option<CancellationToken>>>);\n\n#[tauri::command]\npub async fn start_stream_syslog(\n    window: Window,\n    device: DeviceInfo,\n    stream: State<'_, SyslogStream>,\n) -> Result<(), String> {\n    let mut stream_guard = stream.0.lock().await;\n    if let Some(token) = stream_guard.take() {\n        token.cancel();\n    }\n\n    let provider = get_provider(&device).await?;\n\n    let mut relay_client = SyslogRelayClient::connect(&provider)\n        .await\n        .map_err(|e| format!(\"Failed to connect to syslog relay: {}\", e))?;\n\n    let cancellation_token = CancellationToken::new();\n\n    *stream_guard = Some(cancellation_token.clone());\n\n    let stream_clone = stream.0.clone();\n\n    tokio::spawn(async move {\n        loop {\n            tokio::select! {\n                _ = cancellation_token.cancelled() => {\n                    println!(\"Syslog stream cancelled\");\n                    break;\n                }\n                message_result = relay_client.next() => {\n                    match message_result {\n                        Ok(message) => {\n                            if let Err(e) = window.emit(\"syslog-message\", &message) {\n                                eprintln!(\"Failed to emit syslog message: {}\", e);\n                                break;\n                            }\n                        }\n                        Err(e) => {\n                            eprintln!(\"Error reading syslog message: {}\", e);\n                            let _ = window.emit(\"syslog-message\", format!(\"Error reading syslog: {}\", e));\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        let mut stream_guard = stream_clone.lock().await;\n        *stream_guard = None;\n    });\n\n    Ok(())\n}\n\n#[tauri::command]\npub async fn stop_stream_syslog(stream: State<'_, SyslogStream>) -> Result<(), String> {\n    let mut stream_guard = stream.0.lock().await;\n\n    if let Some(token) = stream_guard.take() {\n        token.cancel();\n        Ok(())\n    } else {\n        Err(\"No active syslog stream found\".to_string())\n    }\n}\n\n#[tauri::command]\npub async fn is_streaming_syslog(stream: State<'_, SyslogStream>) -> Result<bool, String> {\n    let stream_guard = stream.0.lock().await;\n    Ok(stream_guard.is_some())\n}\n"
  },
  {
    "path": "src-tauri/src/sourcekit_lsp.rs",
    "content": "use futures_util::{SinkExt, StreamExt};\nuse serde::Serialize;\nuse std::sync::Arc;\nuse tauri::{Emitter, State, Window};\nuse tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};\nuse tokio::net::TcpListener;\nuse tokio::process::Child;\nuse tokio::sync::{broadcast, mpsc, RwLock};\nuse tokio_tungstenite::{accept_async, tungstenite::Message, WebSocketStream};\n\nuse crate::builder::swift::{validate_toolchain, SwiftBin};\n\n#[derive(Debug, Clone, Serialize)]\npub struct ServerStatus {\n    pub is_running: bool,\n    pub port: Option<u16>,\n    pub connected_clients: usize,\n}\n\npub struct SourceKitServer {\n    pub process: Option<Child>,\n    pub websocket_listener: Option<TcpListener>,\n    pub status: ServerStatus,\n    pub abort_handles: Vec<tokio::task::AbortHandle>,\n}\n\nimpl SourceKitServer {\n    pub fn new() -> Self {\n        Self {\n            process: None,\n            websocket_listener: None,\n            status: ServerStatus {\n                is_running: false,\n                port: None,\n                connected_clients: 0,\n            },\n            abort_handles: Vec::new(),\n        }\n    }\n}\n\npub type ServerState = Arc<RwLock<SourceKitServer>>;\n\n#[tauri::command]\npub async fn start_sourcekit_server(\n    window: Window,\n    state: State<'_, ServerState>,\n    toolchain_path: String,\n    folder: String,\n) -> Result<u16, String> {\n    let mut server = state.write().await;\n\n    if server.status.is_running {\n        return Err(\"Server is already running\".to_string());\n    }\n\n    if !validate_toolchain(&toolchain_path) {\n        return Err(format!(\"Invalid toolchain path: {}\", toolchain_path));\n    }\n\n    let swift_bin = SwiftBin::new(&toolchain_path)?;\n    let mut child = swift_bin\n        .sourcekit_command()\n        .current_dir(folder)\n        .stdin(std::process::Stdio::piped())\n        .stdout(std::process::Stdio::piped())\n        .stderr(std::process::Stdio::piped())\n        .spawn()\n        .map_err(|e| format!(\"Failed to start sourcekit-lsp: {}\", e))?;\n\n    let mut stdin = child.stdin.take().ok_or(\"Failed to get stdin\")?;\n    let stdout = child.stdout.take().ok_or(\"Failed to get stdout\")?;\n\n    let listener = TcpListener::bind(\"127.0.0.1:0\")\n        .await\n        .map_err(|e| format!(\"Failed to bind WebSocket server: {}\", e))?;\n\n    let actual_port = listener\n        .local_addr()\n        .map_err(|e| format!(\"Failed to get server address: {}\", e))?\n        .port();\n\n    let (to_lsp_tx, mut to_lsp_rx) = mpsc::unbounded_channel::<String>();\n    let (from_lsp_tx, _from_lsp_rx) = broadcast::channel::<String>(100);\n\n    let state_clone = state.inner().clone();\n\n    let ws_state = state_clone.clone();\n    let ws_to_lsp = to_lsp_tx.clone();\n    let ws_from_lsp = from_lsp_tx.subscribe();\n    let ws_task = tokio::spawn(async move {\n        handle_websocket_connections(listener, ws_state, ws_to_lsp, ws_from_lsp).await;\n    });\n\n    let stdin_task = tokio::spawn(async move {\n        while let Some(message) = to_lsp_rx.recv().await {\n            let packet = if message.starts_with(\"Content-Length:\") {\n                message\n            } else {\n                format!(\"Content-Length: {}\\r\\n\\r\\n{}\", message.len(), message)\n            };\n\n            if let Err(e) = stdin.write_all(packet.as_bytes()).await {\n                eprintln!(\"Failed to write to sourcekit-lsp stdin: {}\", e);\n                break;\n            }\n            if let Err(e) = stdin.flush().await {\n                eprintln!(\"Failed to flush sourcekit-lsp stdin: {}\", e);\n                break;\n            }\n        }\n    });\n\n    let stdout_task = tokio::spawn(async move {\n        let mut reader = BufReader::new(stdout);\n        let mut buffer = String::new();\n\n        loop {\n            buffer.clear();\n\n            let mut content_length = 0;\n            loop {\n                buffer.clear();\n                match reader.read_line(&mut buffer).await {\n                    Ok(0) => return,\n                    Ok(_) => {\n                        let line = buffer.trim();\n                        if line.is_empty() {\n                            break;\n                        } else if line.starts_with(\"Content-Length:\") {\n                            if let Some(length_str) = line.strip_prefix(\"Content-Length:\") {\n                                content_length = length_str.trim().parse::<usize>().unwrap_or(0);\n                            }\n                        }\n                    }\n                    Err(e) => {\n                        eprintln!(\"Failed to read LSP headers: {}\", e);\n                        return;\n                    }\n                }\n            }\n\n            if content_length == 0 {\n                continue;\n            }\n\n            let mut content = vec![0u8; content_length];\n            match reader.read_exact(&mut content).await {\n                Ok(_) => {\n                    let message = String::from_utf8_lossy(&content).to_string();\n                    window\n                        .emit(\"lsp-message\", message.clone())\n                        .unwrap_or_default();\n                    if let Err(_) = from_lsp_tx.send(message) {\n                        // No receivers, continue\n                    }\n                }\n                Err(e) => {\n                    eprintln!(\"Failed to read LSP content: {}\", e);\n                    break;\n                }\n            }\n        }\n    });\n\n    server.abort_handles.push(ws_task.abort_handle());\n    server.abort_handles.push(stdin_task.abort_handle());\n    server.abort_handles.push(stdout_task.abort_handle());\n\n    server.process = Some(child);\n    server.status.is_running = true;\n    server.status.port = Some(actual_port);\n\n    Ok(actual_port)\n}\n\nasync fn handle_websocket_connections(\n    listener: TcpListener,\n    state: ServerState,\n    to_lsp_tx: mpsc::UnboundedSender<String>,\n    mut from_lsp_rx: broadcast::Receiver<String>,\n) {\n    let (client_tx, mut client_rx) = mpsc::unbounded_channel::<\n        futures_util::stream::SplitSink<WebSocketStream<tokio::net::TcpStream>, Message>,\n    >();\n\n    let _broadcast_task = tokio::spawn(async move {\n        let mut clients = Vec::new();\n\n        loop {\n            tokio::select! {\n                Some(ws_stream) = client_rx.recv() => {\n                    clients.push(ws_stream);\n\n                    let mut server = state.write().await;\n                    server.status.connected_clients = clients.len();\n                }\n\n                Ok(message) = from_lsp_rx.recv() => {\n                    let mut i = 0;\n                    while i < clients.len() {\n                        if let Err(_) = clients[i].send(Message::Text(message.clone().into())).await {\n                            let _ = clients.remove(i);\n                        } else {\n                            i += 1;\n                        }\n                    }\n\n                    let mut server = state.write().await;\n                    server.status.connected_clients = clients.len();\n                }\n            }\n        }\n    });\n\n    while let Ok((stream, _)) = listener.accept().await {\n        match accept_async(stream).await {\n            Ok(ws_stream) => {\n                let (ws_sender, mut ws_receiver) = ws_stream.split();\n                let to_lsp_tx_clone = to_lsp_tx.clone();\n\n                let _ = client_tx.send(ws_sender);\n\n                tokio::spawn(async move {\n                    while let Some(msg) = ws_receiver.next().await {\n                        match msg {\n                            Ok(Message::Text(text)) => {\n                                if let Err(_) = to_lsp_tx_clone.send(text.to_string()) {\n                                    break;\n                                }\n                            }\n                            Ok(Message::Close(_)) => break,\n                            Err(_) => break,\n                            _ => {}\n                        }\n                    }\n                });\n            }\n            Err(e) => {\n                eprintln!(\"WebSocket connection error: {}\", e);\n            }\n        }\n    }\n}\n\n#[tauri::command]\npub async fn stop_sourcekit_server(state: tauri::State<'_, ServerState>) -> Result<(), String> {\n    let mut server = state.write().await;\n\n    if !server.status.is_running {\n        return Err(\"Server is not running\".to_string());\n    }\n\n    for handle in server.abort_handles.drain(..) {\n        handle.abort();\n    }\n\n    if let Some(mut process) = server.process.take() {\n        let _ = process.kill().await;\n    }\n\n    server.websocket_listener = None;\n\n    server.status = ServerStatus {\n        is_running: false,\n        port: None,\n        connected_clients: 0,\n    };\n\n    Ok(())\n}\n\n#[tauri::command]\npub async fn get_server_status(\n    state: tauri::State<'_, ServerState>,\n) -> Result<ServerStatus, String> {\n    let server = state.read().await;\n    Ok(server.status.clone())\n}\n\npub fn create_server_state() -> ServerState {\n    Arc::new(RwLock::new(SourceKitServer::new()))\n}\n"
  },
  {
    "path": "src-tauri/src/templates.rs",
    "content": "use std::collections::HashMap;\n\nuse dircpy::CopyBuilder;\nuse tauri::{AppHandle, Manager};\nuse tauri_plugin_dialog::DialogExt;\n\n#[tauri::command]\npub async fn create_template(\n    app: AppHandle,\n    template: String,\n    name: String,\n    parameters: HashMap<String, String>,\n) -> Result<String, String> {\n    let template_dir = app\n        .path()\n        .resolve(\"templates\", tauri::path::BaseDirectory::Resource)\n        .map_err(|e| format!(\"Failed to resolve template directory: {}\", e))?;\n    let template_path = template_dir.join(&template);\n    if !template_path.exists() {\n        return Err(format!(\"Template '{}' does not exist\", template));\n    }\n    let file_path = app\n        .dialog()\n        .file()\n        .set_title(\"Project Location\")\n        .blocking_pick_folder();\n    if file_path.is_none() {\n        return Err(\"No folder selected\".to_string());\n    }\n    let file_path = file_path.unwrap();\n    let target_path = file_path.as_path().unwrap().join(&name);\n    if target_path.exists() {\n        return Err(format!(\n            \"Target path '{}' already exists\",\n            target_path.display()\n        ));\n    }\n    std::fs::create_dir_all(&target_path)\n        .map_err(|e| format!(\"Failed to create target directory: {}\", e))?;\n\n    if !template_path.is_dir() {\n        return Err(format!(\n            \"Template path '{}' is not a directory\",\n            template_path.display()\n        ));\n    }\n\n    CopyBuilder::new(&template_path, &target_path)\n        .run()\n        .map_err(|e| format!(\"Failed to copy template: {}\", e))?;\n\n    let walker = walkdir::WalkDir::new(&target_path)\n        .into_iter()\n        .filter_map(|e| e.ok());\n\n    for entry in walker {\n        let path = entry.path();\n        if path.is_file() {\n            let mut content = std::fs::read(path)\n                .map_err(|e| format!(\"Failed to read file '{}': {}\", path.display(), e))?;\n\n            let mut filename = path\n                .file_name()\n                .map(|s| s.to_string_lossy().to_string())\n                .unwrap_or(\"\".to_string());\n\n            for (key, value) in &parameters {\n                if filename.contains(&format!(\"{{{{{}}}}}\", key)) {\n                    filename = filename.replace(&format!(\"{{{{{}}}}}\", key), value);\n                    let new_path = path.with_file_name(&filename);\n                    std::fs::rename(path, &new_path).map_err(|e| {\n                        format!(\"Failed to rename file '{}': {}\", path.display(), e)\n                    })?;\n                }\n            }\n\n            if let Ok(s) = String::from_utf8(content) {\n                let mut replaced = s;\n                for (key, value) in &parameters {\n                    replaced = replaced.replace(&format!(\"{{{{{}}}}}\", key), value);\n                }\n                content = replaced.into_bytes();\n            } else {\n                continue;\n            }\n\n            let final_path = path.with_file_name(&filename);\n            std::fs::write(&final_path, content)\n                .map_err(|e| format!(\"Failed to write file '{}': {}\", path.display(), e))?;\n        }\n    }\n\n    Ok(target_path.to_string_lossy().to_string())\n}\n"
  },
  {
    "path": "src-tauri/src/windows.rs",
    "content": "#[cfg(target_os = \"windows\")]\nuse std::os::windows::process::CommandExt;\n#[cfg(target_os = \"windows\")]\nuse std::process::{Command, Stdio};\n\n#[cfg(target_os = \"windows\")]\npub fn windows_to_wsl_path(path: &str) -> Result<String, String> {\n    let res = convert(path, Conversion::WindowsToWsl, false, true).map_err(|e| e.to_string());\n    match res {\n        Ok(path) => Ok(path),\n        Err(err) => {\n            let res2 = convert(path, Conversion::WindowsToWsl, false, false);\n            match res2 {\n                Ok(path) => Ok(path),\n                Err(_) => Err(err),\n            }\n        }\n    }\n}\n\n#[cfg(target_os = \"windows\")]\npub fn wsl_to_windows_path(path: &str) -> Result<String, String> {\n    let res = convert(path, Conversion::WslToWindows, false, true).map_err(|e| e.to_string());\n    match res {\n        Ok(path) => Ok(path),\n        Err(err) => {\n            let res2 = convert(path, Conversion::WslToWindows, false, false);\n            match res2 {\n                Ok(path) => Ok(path),\n                Err(_) => Err(err),\n            }\n        }\n    }\n}\n\n#[tauri::command]\npub fn has_wsl() -> bool {\n    #[cfg(not(target_os = \"windows\"))]\n    {\n        return false;\n    }\n    #[cfg(target_os = \"windows\")]\n    {\n        let output = Command::new(\"wsl\")\n            .arg(\"echo\")\n            .arg(\"1\")\n            .stdout(Stdio::piped())\n            .creation_flags(0x08000000) // CREATE_NO_WINDOW\n            .output();\n\n        if let Err(err) = output {\n            println!(\"Failed to execute WSL: {}\", err);\n            return false;\n        }\n\n        let output = output.unwrap();\n\n        let output = String::from_utf8_lossy(&output.stdout);\n        return output.trim() == \"1\";\n    }\n}\n\n#[tauri::command]\npub fn is_windows() -> bool {\n    cfg!(target_os = \"windows\")\n}\n\n#[tauri::command]\npub fn install_wsl() -> Result<(), String> {\n    #[cfg(target_os = \"windows\")]\n    {\n        Command::new(\"powershell\")\n            .arg(\"-Command\")\n            .arg(\"Start-Process powershell -Verb runAs -ArgumentList '-NoExit','-Command','wsl --install Ubuntu-24.04; Write-Host \\\"`nIf this is your first time installing WSL, you must restart your PC to finish. It is safe to ignore the error about missing features. After restarting, open CrossCode and click Install WSL again to finish the installation.\\\"; Read-Host \\\"Press Enter to close\\\"'\")\n            .spawn()\n            .map_err(|e| e.to_string())?;\n    }\n    Ok(())\n}\n\n// Taken from wslpath2 crate and modified\n#[cfg(target_os = \"windows\")]\n#[derive(Debug)]\npub enum Conversion {\n    /// Convert Windows path to WSL path\n    WindowsToWsl,\n    /// Convert WSL path to Windows path\n    WslToWindows,\n}\n\n#[cfg(target_os = \"windows\")]\npub fn convert(\n    path: &str,\n    options: Conversion,\n    force_absolute_path: bool,\n    replace_backslash: bool,\n) -> Result<String, Box<dyn std::error::Error>> {\n    let mut args = Vec::new();\n\n    args.push(\"-e\");\n    args.push(\"wslpath\");\n\n    args.push(match options {\n        Conversion::WindowsToWsl => \"-u\",\n        Conversion::WslToWindows => \"-w\",\n    });\n\n    if force_absolute_path {\n        args.push(\"-a\");\n    }\n\n    let mut cmd = Command::new(\"wsl.exe\");\n    cmd.args(args);\n    let real_path = if replace_backslash {\n        path.replace('\\\\', \"\\\\\\\\\")\n    } else {\n        path.to_string()\n    };\n    cmd.arg(real_path);\n\n    #[cfg(windows)]\n    cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW\n\n    let output = cmd\n        .output()\n        .map_err(|e| format!(\"Error executing wsl.exe: {}\", e))?;\n\n    let code = output.status.code().unwrap_or(-1);\n    if code != 0 {\n        return Err(format!(\"Error getting wslpath: {}\", code).into());\n    }\n\n    Ok(std::str::from_utf8(&output.stdout)\n        .map_err(|e| format!(\"Error converting output to string: {}\", e))?\n        .trim()\n        .to_string())\n}\n"
  },
  {
    "path": "src-tauri/tauri.conf.json",
    "content": "{\n  \"build\": {\n    \"beforeDevCommand\": \"bun run dev\",\n    \"beforeBuildCommand\": \"bun run build\",\n    \"frontendDist\": \"../dist\",\n    \"devUrl\": \"http://localhost:1420\"\n  },\n  \"bundle\": {\n    \"active\": true,\n    \"targets\": \"all\",\n    \"resources\": [\n      \"templates\",\n      \"cpio\"\n    ],\n    \"icon\": [\n      \"icons/32x32.png\",\n      \"icons/128x128.png\",\n      \"icons/128x128@2x.png\",\n      \"icons/icon.icns\",\n      \"icons/icon.ico\"\n    ],\n    \"createUpdaterArtifacts\": true\n  },\n  \"productName\": \"CrossCode\",\n  \"mainBinaryName\": \"CrossCode\",\n  \"version\": \"0.0.5\",\n  \"identifier\": \"me.nabdev.crosscode\",\n  \"plugins\": {\n    \"fs\": {\n      \"requireLiteralLeadingDot\": false\n    },\n    \"cli\": {\n      \"args\": [\n        {\n          \"name\": \"showMainWindow\"\n        }\n      ]\n    },\n    \"updater\": {\n      \"pubkey\": \"dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDZFOEM1NUQyOEUzNDc5MTcKUldRWGVUU08wbFdNYmg1MHM0S3p2c2x1OFZKVnN0NXNVSDMvakExMFZnMnczamxIVGdjNGY4Mm4K\",\n      \"endpoints\": [\n        \"https://github.com/nab138/CrossCode/releases/latest/download/latest.json\"\n      ]\n    }\n  },\n  \"app\": {\n    \"security\": {\n      \"csp\": null\n    },\n    \"windows\": [\n      {\n        \"title\": \"CrossCode\",\n        \"label\": \"main\",\n        \"width\": 1000,\n        \"height\": 700,\n        \"useHttpsScheme\": true,\n        \"visible\": false,\n        \"url\": \"/\"\n      },\n      {\n        \"title\": \"CrossCode (Loading)\",\n        \"label\": \"splashscreen\",\n        \"url\": \"/splash.html\",\n        \"width\": 200,\n        \"height\": 250,\n        \"resizable\": false,\n        \"decorations\": false,\n        \"fullscreen\": false,\n        \"visible\": true,\n        \"center\": true,\n        \"focus\": true,\n        \"backgroundColor\": \"#171a1c\"\n      }\n    ]\n  }\n}"
  },
  {
    "path": "src-tauri/tauri.windows.conf.json",
    "content": "{\n  \"bundle\": {\n    \"resources\": [\"templates\", \"cpio\", \"sdkmoverbin\"]\n  }\n}\n"
  },
  {
    "path": "src-tauri/templates/swiftui/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleName</key>\n\t<string>[[product]]</string>\n\t<key>CFBundleExecutable</key>\n\t<string>[[product]]</string>\n\t<key>CFBundleIcons</key>\n\t<dict>\n\t\t<key>CFBundlePrimaryIcon</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIconFiles</key>\n\t\t\t<array>\n\t\t\t\t<string>AppIcon29x29</string>\n\t\t\t\t<string>AppIcon40x40</string>\n\t\t\t\t<string>AppIcon57x57</string>\n\t\t\t\t<string>AppIcon60x60</string>\n\t\t\t</array>\n\t\t\t<key>UIPrerenderedIcon</key>\n\t\t\t<true/>\n\t\t</dict>\n\t</dict>\n\t<key>CFBundleIcons~ipad</key>\n\t<dict>\n\t\t<key>CFBundlePrimaryIcon</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIconFiles</key>\n\t\t\t<array>\n\t\t\t\t<string>AppIcon29x29</string>\n\t\t\t\t<string>AppIcon40x40</string>\n\t\t\t\t<string>AppIcon57x57</string>\n\t\t\t\t<string>AppIcon60x60</string>\n\t\t\t\t<string>AppIcon50x50</string>\n\t\t\t\t<string>AppIcon72x72</string>\n\t\t\t\t<string>AppIcon76x76</string>\n\t\t\t</array>\n\t\t\t<key>UIPrerenderedIcon</key>\n\t\t\t<true/>\n\t\t</dict>\n\t</dict>\n\t<key>CFBundleIdentifier</key>\n\t<string>[[bundle_id]]</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleSupportedPlatforms</key>\n\t<array>\n\t\t<string>iPhoneOS</string>\n\t</array>\n\t<key>CFBundleVersion</key>\n\t<string>[[version_num]]</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>[[version_string]]</string>\n\t<key>LSRequiresIPhoneOS</key>\n\t<true/>\n\t<key>UIDeviceFamily</key>\n\t<array>\n\t\t<integer>1</integer>\n\t\t<integer>2</integer>\n\t</array>\n\t<key>UIRequiredDeviceCapabilities</key>\n\t<array>\n\t\t<string>arm64</string>\n\t</array>\n\t<key>UILaunchStoryboardName</key>\n\t<string>LaunchScreen</string>\n\t<key>UISupportedInterfaceOrientations</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations~ipad</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationPortraitUpsideDown</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n</dict>\n</plist>\n"
  },
  {
    "path": "src-tauri/templates/swiftui/Package.swift",
    "content": "// swift-tools-version: 6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"{{projectName}}\",\n    platforms: [.iOS(.v15)],\n    targets: [\n        .executableTarget(\n            name: \"{{projectName}}\",\n            path: \"Sources\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "src-tauri/templates/swiftui/Sources/ContentView.swift",
    "content": "import SwiftUI\n\nstruct ContentView: View {\n    @State private var items: [Date] = []\n\n    var body: some View {\n        NavigationView {\n            VStack {\n                List {\n                    ForEach(items, id: \\.self) { item in\n                        Text(item.description)\n                    }\n                    .onDelete(perform: delete)\n                }.toolbar {\n                    ToolbarItem(placement: .navigationBarLeading) {\n                        EditButton()\n                    }\n                }\n                .listStyle(InsetGroupedListStyle())\n            }\n            .navigationTitle(\"{{projectName}}\")\n            .toolbar {\n                ToolbarItem(placement: .navigationBarTrailing) {\n                    Button {\n                        withAnimation(.easeInOut) {\n                            items.insert(Date(), at: 0)\n                        }\n                    } label: {\n                        Image(systemName: \"plus\")\n                    }\n                }\n            }\n        }\n    }\n\n    func delete(at offsets: IndexSet) {\n        items.remove(atOffsets: offsets)\n    }\n}\n"
  },
  {
    "path": "src-tauri/templates/swiftui/Sources/{{projectName}}.swift",
    "content": "import SwiftUI\n\n@main\nstruct {{projectName}}: App {\n\tvar body: some Scene {\n\t\tWindowGroup {\n\t\t\tContentView()\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src-tauri/templates/swiftui/crosscode.toml",
    "content": "format_version = 1\n\n[project]\nversion_num = \"1\"\nversion_string = \"1.0.0\"\nbundle_id = \"{{bundleId}}\""
  },
  {
    "path": "src-tauri/templates/uikit/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleName</key>\n\t<string>[[product]]</string>\n\t<key>CFBundleExecutable</key>\n\t<string>[[product]]</string>\n\t<key>CFBundleIcons</key>\n\t<dict>\n\t\t<key>CFBundlePrimaryIcon</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIconFiles</key>\n\t\t\t<array>\n\t\t\t\t<string>AppIcon29x29</string>\n\t\t\t\t<string>AppIcon40x40</string>\n\t\t\t\t<string>AppIcon57x57</string>\n\t\t\t\t<string>AppIcon60x60</string>\n\t\t\t</array>\n\t\t\t<key>UIPrerenderedIcon</key>\n\t\t\t<true/>\n\t\t</dict>\n\t</dict>\n\t<key>CFBundleIcons~ipad</key>\n\t<dict>\n\t\t<key>CFBundlePrimaryIcon</key>\n\t\t<dict>\n\t\t\t<key>CFBundleIconFiles</key>\n\t\t\t<array>\n\t\t\t\t<string>AppIcon29x29</string>\n\t\t\t\t<string>AppIcon40x40</string>\n\t\t\t\t<string>AppIcon57x57</string>\n\t\t\t\t<string>AppIcon60x60</string>\n\t\t\t\t<string>AppIcon50x50</string>\n\t\t\t\t<string>AppIcon72x72</string>\n\t\t\t\t<string>AppIcon76x76</string>\n\t\t\t</array>\n\t\t\t<key>UIPrerenderedIcon</key>\n\t\t\t<true/>\n\t\t</dict>\n\t</dict>\n\t<key>CFBundleIdentifier</key>\n\t<string>[[bundle_id]]</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleSupportedPlatforms</key>\n\t<array>\n\t\t<string>iPhoneOS</string>\n\t</array>\n\t<key>CFBundleVersion</key>\n\t<string>[[version_num]]</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>[[version_string]]</string>\n\t<key>LSRequiresIPhoneOS</key>\n\t<true/>\n\t<key>UIDeviceFamily</key>\n\t<array>\n\t\t<integer>1</integer>\n\t\t<integer>2</integer>\n\t</array>\n\t<key>UIRequiredDeviceCapabilities</key>\n\t<array>\n\t\t<string>arm64</string>\n\t</array>\n\t<key>UILaunchStoryboardName</key>\n\t<string>LaunchScreen</string>\n\t<key>UISupportedInterfaceOrientations</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations~ipad</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationPortraitUpsideDown</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n</dict>\n</plist>\n"
  },
  {
    "path": "src-tauri/templates/uikit/Package.swift",
    "content": "// swift-tools-version: 6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"{{projectName}}\",\n    platforms: [.iOS(.v15)],\n    targets: [\n        .executableTarget(\n            name: \"{{projectName}}\",\n            path: \"Sources\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "src-tauri/templates/uikit/Sources/AppDelegate.swift",
    "content": "import UIKit\n\n@UIApplicationMain\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n\n\tvar window: UIWindow?\n\n\tfunc application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {\n\t\twindow = UIWindow(frame: UIScreen.main.bounds)\n\t\twindow!.rootViewController = UINavigationController(rootViewController: RootViewController())\n\t\twindow!.makeKeyAndVisible()\n\t\treturn true\n\t}\n\n}\n"
  },
  {
    "path": "src-tauri/templates/uikit/Sources/RootViewController.swift",
    "content": "import UIKit\n\nclass RootViewController: UITableViewController {\n\n\tvar objects: [Date] = []\n\n\toverride func loadView() {\n\t\tsuper.loadView()\n\n\t\ttableView.register(UITableViewCell.self, forCellReuseIdentifier: \"Cell\")\n\n\t\ttitle = \"Root View Controller\"\n\t\tnavigationItem.leftBarButtonItem = editButtonItem\n\t\tnavigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonTapped))\n\t}\n\n\t@objc func addButtonTapped(_ sender: Any) {\n\t\tobjects.insert(Date(), at: 0)\n\t\ttableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)\n\t}\n\n\t// MARK: - Table View Data Source\n\n\toverride func numberOfSections(in tableView: UITableView) -> Int {\n\t\treturn 1\n\t}\n\n\toverride func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n\t\treturn objects.count\n\t}\n\n\toverride func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n\t\tlet cell = tableView.dequeueReusableCell(withIdentifier: \"Cell\", for: indexPath)\n\n\t\tlet date = objects[indexPath.row]\n\t\tcell.textLabel!.text = date.description\n\t\treturn cell\n\t}\n\n\toverride func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {\n\t\tobjects.remove(at: indexPath.row)\n\t\ttableView.deleteRows(at: [indexPath], with: .automatic)\n\t}\n\n\t// MARK: - Table View Delegate\n\n\toverride func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n\t\ttableView.deselectRow(at: indexPath, animated: true)\n\t}\n\n}\n"
  },
  {
    "path": "src-tauri/templates/uikit/crosscode.toml",
    "content": "format_version = 1\n\n[project]\nversion_num = \"1\"\nversion_string = \"1.0.0\"\nbundle_id = \"{{bundleId}}\""
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"ESNext\",\n    \"skipLibCheck\": true,\n\n    /* Bundler mode */\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n\n    /* Linting */\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noFallthroughCasesInSwitch\": true\n  },\n  \"include\": [\"src\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n"
  },
  {
    "path": "tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"skipLibCheck\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "vite.config.ts",
    "content": "import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport importMetaUrlPlugin from \"@codingame/esbuild-import-meta-url-plugin\";\n\n// https://vitejs.dev/config/\nconst plugins = [react()];\n\nexport default defineConfig(async () => ({\n  plugins: plugins,\n  // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`\n  //\n  // 1. prevent vite from obscuring rust errors\n  clearScreen: false,\n  // 2. tauri expects a fixed port, fail if that port is not available\n  server: {\n    port: 1420,\n    strictPort: true,\n    watch: {\n      // 3. tell vite to ignore watching `src-tauri`\n      ignored: [\"**/src-tauri/**\"],\n    },\n  },\n  worker: {\n    format: \"es\" as const,\n  },\n  build: {\n    rollupOptions: {\n      input: {\n        index: \"./index.html\",\n        splash: \"./splash.html\",\n      },\n    },\n  },\n  optimizeDeps: {\n    esbuildOptions: {\n      plugins: [importMetaUrlPlugin],\n    },\n    include: [\"vscode-textmate\", \"vscode-oniguruma\"],\n  },\n}));\n"
  }
]