Repository: nab138/CrossCode
Branch: main
Commit: 796ee09608bf
Files: 115
Total size: 376.2 KB
Directory structure:
gitextract_qiaq0x4s/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ └── bug_report.md
│ └── workflows/
│ └── build.yml
├── .gitignore
├── .vscode/
│ └── extensions.json
├── LICENSE
├── README.md
├── index.html
├── licenses/
│ ├── GPL-3.0.txt
│ └── cpio.NOTICE
├── package.json
├── splash.html
├── src/
│ ├── App.css
│ ├── App.tsx
│ ├── components/
│ │ ├── CommandButton.tsx
│ │ ├── Menu/
│ │ │ ├── MenuBar.tsx
│ │ │ ├── MenuBarButton.tsx
│ │ │ ├── MenuBarDefinition.tsx
│ │ │ └── MenuGroup.tsx
│ │ ├── OperationView.css
│ │ ├── OperationView.tsx
│ │ ├── SDKMenu.tsx
│ │ ├── SwiftMenu.tsx
│ │ ├── TabLike.tsx
│ │ └── Tiles/
│ │ ├── BottomBar.css
│ │ ├── BottomBar.tsx
│ │ ├── CommandConsole.tsx
│ │ ├── Console.css
│ │ ├── Console.tsx
│ │ ├── Editor.css
│ │ ├── Editor.tsx
│ │ ├── FileExplorer.css
│ │ ├── FileExplorer.tsx
│ │ ├── FilteredConsole.tsx
│ │ ├── Tile.css
│ │ └── Tile.tsx
│ ├── main.tsx
│ ├── pages/
│ │ ├── About.tsx
│ │ ├── IDE.css
│ │ ├── IDE.tsx
│ │ ├── New.css
│ │ ├── New.tsx
│ │ ├── NewTemplate.tsx
│ │ ├── Onboarding.css
│ │ └── Onboarding.tsx
│ ├── preferences/
│ │ ├── PreferenceItemRenderer.tsx
│ │ ├── Preferences.tsx
│ │ ├── Prefs.css
│ │ ├── helpers.ts
│ │ ├── pages/
│ │ │ ├── appIds.tsx
│ │ │ ├── appearance.tsx
│ │ │ ├── appleId.ts
│ │ │ ├── certificates.tsx
│ │ │ ├── developer.ts
│ │ │ ├── general.ts
│ │ │ ├── index.ts
│ │ │ ├── sourcekit.tsx
│ │ │ └── swift.tsx
│ │ ├── registry.ts
│ │ └── types.ts
│ ├── styles.css
│ ├── utilities/
│ │ ├── Command.tsx
│ │ ├── IDEContext.tsx
│ │ ├── Shortcut.tsx
│ │ ├── StoreContext.tsx
│ │ ├── TauriFileSystemProvider.ts
│ │ ├── UpdateContext.tsx
│ │ ├── constants.ts
│ │ ├── lsp-client.ts
│ │ ├── operations.ts
│ │ └── templates.ts
│ └── vite-env.d.ts
├── src-tauri/
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── build.rs
│ ├── capabilities/
│ │ ├── desktop.json
│ │ └── migrated.json
│ ├── cpio
│ ├── icons/
│ │ └── icon.icns
│ ├── sdkmoverbin
│ ├── src/
│ │ ├── builder/
│ │ │ ├── config.rs
│ │ │ ├── crossplatform.rs
│ │ │ ├── icon.rs
│ │ │ ├── mod.rs
│ │ │ ├── packer.rs
│ │ │ ├── sdk.rs
│ │ │ └── swift.rs
│ │ ├── lsp_utils.rs
│ │ ├── main.rs
│ │ ├── operation.rs
│ │ ├── sideloader/
│ │ │ ├── apple.rs
│ │ │ ├── apple_commands.rs
│ │ │ ├── device.rs
│ │ │ ├── mod.rs
│ │ │ ├── screenshot.rs
│ │ │ ├── sideload.rs
│ │ │ ├── stdout.rs
│ │ │ └── syslog.rs
│ │ ├── sourcekit_lsp.rs
│ │ ├── templates.rs
│ │ └── windows.rs
│ ├── tauri.conf.json
│ ├── tauri.windows.conf.json
│ └── templates/
│ ├── swiftui/
│ │ ├── Info.plist
│ │ ├── Package.swift
│ │ ├── Sources/
│ │ │ ├── ContentView.swift
│ │ │ └── {{projectName}}.swift
│ │ └── crosscode.toml
│ └── uikit/
│ ├── Info.plist
│ ├── Package.swift
│ ├── Sources/
│ │ ├── AppDelegate.swift
│ │ └── RootViewController.swift
│ └── crosscode.toml
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ""
labels: ""
assignees: ""
---
**Describe the bug**
A clear and concise description of what the bug is.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS (including distro): [e.g. Windows, Arch Linux]
- CrossCode version: [e.g. 0.0.4]
- Package Format: [e.g. exe, deb]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone 6]
- OS: [e.g. iOS 26.0]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/workflows/build.yml
================================================
name: "Build CrossCode"
on:
push:
branches:
- "*"
pull_request:
branches:
- "*"
workflow_dispatch:
release:
types: [published]
jobs:
build:
permissions:
contents: write
strategy:
fail-fast: false
matrix:
include:
- platform: "ubuntu-22.04"
args: "--bundles deb"
- platform: "ubuntu-22.04"
args: "--bundles rpm"
- platform: "ubuntu-22.04"
args: "--bundles appimage"
- platform: "windows-latest"
args: ""
- platform: "macos-latest"
args: "--target aarch64-apple-darwin"
- platform: "macos-15-intel"
args: "--target x86_64-apple-darwin"
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v4
- name: Cache Rust and bun dependencies
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
src-tauri/target
node_modules
key: ${{ matrix.platform }}-crosscode-${{ hashFiles('**/Cargo.lock', 'package-lock.json') }}
restore-keys: |
${{ runner.os }}-crosscode-
- name: Install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ (matrix.platform == 'macos-latest' || matrix.platform == 'macos-15-intel') && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
- name: Install Linux dependencies
if: matrix.platform == 'ubuntu-22.04'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf perl make
- name: Add MSVC to PATH
if: matrix.platform == 'windows-latest'
uses: ilammy/msvc-dev-cmd@v1
- name: Install Perl and Make for Windows
if: matrix.platform == 'windows-latest'
run: |
choco install strawberryperl make --no-progress
- uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Install frontend dependencies
run: bun i --frozen-lockfile
- name: Clean old bundles
if: matrix.platform != 'macos-latest' && matrix.platform != 'macos-15-intel'
run: bunx rimraf src-tauri/target/release/bundle
- name: Clean old bundles
if: matrix.platform == 'macos-latest'
run: bunx rimraf src-tauri/target/aarch64-apple-darwin/release/bundle
- name: Clean old bundles
if: matrix.platform == 'macos-15-intel'
run: bunx rimraf src-tauri/target/x86_64-apple-darwin/release/bundle
- name: Build
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
with:
args: ${{ matrix.args }}
includeUpdaterJson: ${{ github.event_name == 'release' }}
releaseId: ${{ github.event_name == 'release' && github.event.release.id || '' }}
- name: Upload macOS DMG
uses: actions/upload-artifact@v4
if: matrix.platform == 'macos-latest' || matrix.platform == 'macos-15-intel'
with:
name: macos-dmg-${{ matrix.args == '--target aarch64-apple-darwin' && 'arm64' || 'x64' }}
path: ${{ github.workspace }}/src-tauri/target/**/release/bundle/**/*.dmg
- name: Upload Linux DEB
uses: actions/upload-artifact@v4
if: matrix.platform == 'ubuntu-22.04' && matrix.args == '--bundles deb'
with:
name: linux-deb
path: ${{ github.workspace }}/src-tauri/target/release/bundle/**/*.deb
- name: Upload Linux RPM
uses: actions/upload-artifact@v4
if: matrix.platform == 'ubuntu-22.04' && matrix.args == '--bundles rpm'
with:
name: linux-rpm
path: ${{ github.workspace }}/src-tauri/target/release/bundle/**/*.rpm
- name: Upload Linux AppImage
uses: actions/upload-artifact@v4
if: matrix.platform == 'ubuntu-22.04' && matrix.args == '--bundles appimage'
with:
name: linux-appimage
path: ${{ github.workspace }}/src-tauri/target/release/bundle/**/*.AppImage
- name: Upload Windows EXE
uses: actions/upload-artifact@v4
if: matrix.platform == 'windows-latest'
with:
name: windows-exe
path: |
${{ github.workspace }}/src-tauri/target/release/bundle/**/*.exe
================================================
FILE: .gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.zsign_cache
*.key*
sdkmover
================================================
FILE: .vscode/extensions.json
================================================
{
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2025 nab138
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
---
[](https://github.com/nab138/CrossCode/actions/workflows/build.yml)
iOS Swift development IDE for Windows/Linux. Create, build, and test apps without owning a Mac.
Supports Swift 6.2 and the Swift Package Manager.
### Demo
https://github.com/user-attachments/assets/9cbe2b71-d765-46c6-aa25-ef16b539deec
## Installation
CrossCode is currently in alpha. Expect bugs!
Download the latest build for your platform from [releases](https://github.com/nab138/CrossCode/releases/latest).
Check 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)
## Features
- Generate a Darwin SDK for linux from a user provided copy of Xcode 26 to build the apps
- Build apps using swift package manager
- Log in with your Apple ID to sign apps
- Install apps on device
- Create projects from templates
- Code editing including error reporting, autocomplete, go to definition, and other language features
- Light/dark mode and other customizations
- View and manage certificates, app IDs, and more
- View the syslog or the stdout (console) of your device/app
- Much more (and more to come!)
## Future plans
The 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)
Please note that I am one person, so development may be slow. If you want to help, PRs welcome!
## How it works
- 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)
- Swift uses the darwin SDK to build an executable which is packaged into an .app bundle.
- 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.
## Credits
- [idevice](https://github.com/jkcoxson/idevice) is used to communicate with iOS devices.
- [xtool](https://xtool.sh) has been used as a reference for the implementation of the darwin SDK generation.
- [Sideloader](https://github.com/Dadoum/Sideloader) has been heavily used as a reference for the implementation of the Apple Developer APIs and sideloading process.
- [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.
### AI Usage
- Helped port small sections of code from [Sideloader](https://github.com/Dadoum/Sideloader) because I'm not familiar with dlang syntax
================================================
FILE: index.html
================================================
CrossCode
================================================
FILE: licenses/GPL-3.0.txt
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: licenses/cpio.NOTICE
================================================
GNU cpio 2.14
Copyright (C) 1989-2023 Free Software Foundation, Inc.
Licensed under the GNU General Public License, version 3.
================================================
FILE: package.json
================================================
{
"name": "crosscode",
"private": true,
"version": "0.0.5",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri",
"bump-patch": "bunx tauri-version --no-git --no-lock patch",
"bump-minor": "bunx tauri-version --no-git --no-lock minor",
"bump-major": "bunx tauri-version --no-git --no-lock major"
},
"dependencies": {
"@codingame/esbuild-import-meta-url-plugin": "^1.0.3",
"@codingame/monaco-vscode-api": "~20.2.1",
"@codingame/monaco-vscode-languages-service-override": "~20.2.1",
"@codingame/monaco-vscode-model-service-override": "~20.2.1",
"@codingame/monaco-vscode-swift-default-extension": "~20.2.1",
"@codingame/monaco-vscode-textmate-service-override": "~20.2.1",
"@codingame/monaco-vscode-theme-defaults-default-extension": "~20.2.1",
"@codingame/monaco-vscode-theme-service-override": "~20.2.1",
"@codingame/monaco-vscode-views-service-override": "~20.2.1",
"@devbookhq/splitter": "^1.4.2",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@fontsource/inter": "^5.2.5",
"@mui/icons-material": "^7.0.2",
"@mui/joy": "^5.0.0-beta.52",
"@mui/material": "^7.0.2",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-cli": "^2.4.0",
"@tauri-apps/plugin-dialog": "^2",
"@tauri-apps/plugin-fs": "^2",
"@tauri-apps/plugin-opener": "^2",
"@tauri-apps/plugin-os": "^2.3.0",
"@tauri-apps/plugin-process": "^2.3.0",
"@tauri-apps/plugin-shell": "^2",
"@tauri-apps/plugin-store": "^2",
"@tauri-apps/plugin-updater": "^2",
"ansi-to-html": "^0.7.2",
"async-mutex": "^0.5.0",
"monaco-editor": "npm:@codingame/monaco-vscode-editor-api@~20.2.1",
"monaco-languageclient": "^9.8.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.5.1",
"react-router-dom": "^7.5.1",
"react-toast-plus": "^0.1.2",
"react-virtuoso": "^4.12.6",
"vscode": "npm:@codingame/monaco-vscode-extension-api@~20.2.1",
"vscode-ws-jsonrpc": "^3.4.0"
},
"devDependencies": {
"@tauri-apps/cli": "^2",
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@types/vscode": "^1.102.0",
"@vitejs/plugin-react": "^4.2.1",
"typescript": "^5.0.2",
"vite": "^7.1.6"
}
}
================================================
FILE: splash.html
================================================
CrossCode (Loading)
================================================
FILE: src/App.css
================================================
================================================
FILE: src/App.tsx
================================================
import { CssVarsProvider, extendTheme } from "@mui/joy/styles";
import { Sheet } from "@mui/joy";
import "@fontsource/inter";
import "@fontsource/inter/600.css";
import Onboarding from "./pages/Onboarding";
import IDE from "./pages/IDE";
import Preferences from "./preferences/Preferences";
import { BrowserRouter, Route, Routes, Navigate, Outlet } from "react-router";
import { StoreProvider, useStore } from "./utilities/StoreContext";
import { IDEProvider } from "./utilities/IDEContext";
import { CommandProvider } from "./utilities/Command";
import { ToastProvider } from "react-toast-plus";
import New from "./pages/New";
import NewTemplate from "./pages/NewTemplate";
import "vscode/localExtensionHost";
import { UpdateProvider } from "./utilities/UpdateContext";
import About from "./pages/About";
declare module "@mui/joy/IconButton" {
interface IconButtonPropsSizeOverrides {
xs: true;
}
}
const theme = extendTheme({
components: {
JoyIconButton: {
styleOverrides: {
root: ({ ownerState, theme }) => ({
...(ownerState.size === "xs" && {
"--Icon-fontSize": "1rem",
"--Button-gap": "0.25rem",
minHeight: "var(--Button-minHeight, 1.5rem)",
fontSize: theme.vars.fontSize.xs,
paddingBlock: "2px",
paddingInline: "0.25rem",
}),
}),
},
},
},
});
// Layout with IDE-related providers
const IDELayout = () => {
const [appTheme] = useStore("appearance/theme", "dark");
return (
);
};
const App = () => {
return (
{
e.preventDefault();
}}
sx={{
width: "100%",
height: "100%",
overflow: "auto",
}}
>
}>
} />
} />
} />
} />
} />
} />
} />
);
};
export default App;
================================================
FILE: src/components/CommandButton.tsx
================================================
import { Button, MenuItem } from "@mui/joy";
import { useCommandRunner } from "../utilities/Command";
import { useIDE } from "../utilities/IDEContext";
import { useToast } from "react-toast-plus";
export interface CommandButtonProps {
command: string;
parameters?: Record;
label?: string;
tooltip?: string;
icon?: React.ReactNode;
variant?: "plain" | "outlined" | "soft" | "solid";
sx?: React.CSSProperties;
clearConsole?: boolean;
validate?: () => boolean;
validateAsync?: () => Promise;
after?: (data: any) => void;
disabled?: boolean;
useMenuItem?: boolean;
shortcut?: React.ReactNode;
id?: string;
size?: "sm" | "md" | "lg";
}
export default function CommandButton({
command,
parameters,
label,
icon,
variant,
tooltip,
sx = {},
clearConsole = true,
validate = () => true,
validateAsync = () => Promise.resolve(true),
after = (_: any) => {},
disabled = false,
useMenuItem = false,
size = "md",
shortcut,
id,
}: CommandButtonProps) {
const { isRunningCommand, currentCommand, runCommand, cancelCommand } =
useCommandRunner();
const { setConsoleLines } = useIDE();
const Component: React.ElementType = useMenuItem ? MenuItem : Button;
const { addToast } = useToast();
return (
{
if (!validate() || !(await validateAsync())) {
return;
}
if (clearConsole) {
setConsoleLines([]);
}
if (isRunningCommand) {
if (currentCommand === command) {
cancelCommand();
}
return;
}
runCommand(command, parameters)
.then(after)
.catch((e) => {
addToast.error(e);
console.error(e);
});
}}
id={id}
>
{icon !== undefined && icon}
{label != "" && label != undefined && label}
{shortcut !== undefined && " "}
{shortcut}
);
}
================================================
FILE: src/components/Menu/MenuBar.tsx
================================================
import Menu from "@mui/joy/Menu";
import List from "@mui/joy/List";
import ListItem from "@mui/joy/ListItem";
import { useCallback, useEffect, useRef, useState } from "react";
import MenuBarButton from "./MenuBarButton";
import MenuGroup from "./MenuGroup";
import {
Shortcut,
acceleratorPresssed,
acceleratorPresssedMonaco,
} from "../../utilities/Shortcut";
import CommandButton from "../CommandButton";
import {
Construction,
PhonelinkSetup,
Refresh,
CleaningServices,
CameraAlt,
} from "@mui/icons-material";
import { useParams } from "react-router-dom";
import { Divider, Option, Select } from "@mui/joy";
import { useIDE } from "../../utilities/IDEContext";
import { useStore } from "../../utilities/StoreContext";
import { useToast } from "react-toast-plus";
import bar from "./MenuBarDefinition";
import { IStandaloneCodeEditor } from "@codingame/monaco-vscode-api/vscode/vs/editor/standalone/browser/standaloneCodeEditor";
export interface MenuBarProps {
callbacks: Record void>;
editor: IStandaloneCodeEditor | null;
}
export default function MenuBar({ callbacks, editor }: MenuBarProps) {
const menus = useRef>([]);
const [menuIndex, setMenuIndex] = useState(null);
const resetMenuIndex = useCallback(() => setMenuIndex(null), []);
const { path } = useParams<"path">();
const {
devices,
selectedToolchain,
selectedDevice,
setSelectedDevice,
setScreenshot,
mountDdi,
} = useIDE();
const [anisetteServer] = useStore(
"apple-id/anisette-server",
"ani.sidestore.io"
);
const { addToast } = useToast();
const updateScreenshot = useCallback(
(data: number[]) => {
const blob = new Blob([new Uint8Array(data)], {
type: "image/png",
});
const url = URL.createObjectURL(blob);
setScreenshot(url);
},
[setScreenshot]
);
useEffect(() => {
const items: {
shortcut: Shortcut;
callback: () => void;
ignoreShortcutInMonaco: boolean;
}[] = [];
for (const menu of bar) {
for (const group of menu.items) {
for (const item of group.items) {
if (item.shortcut) {
const shortcut = Shortcut.fromString(item.shortcut);
let callback;
if (
"callbackName" in item &&
typeof item.callbackName === "string"
) {
callback = callbacks[item.callbackName];
} else if (
"callback" in item &&
typeof item.callback === "function"
) {
callback = item.callback;
} else if (
"component" in item &&
"componentId" in item &&
typeof item.componentId === "string"
) {
// This whole thing needs to be reworked because this is disgusting, too bad I'm lazy!
callback = () => {
const element = document.getElementById(
item.componentId as string
);
if (element) {
(element as HTMLButtonElement).click();
}
};
} else {
callback = () => {};
}
items.push({
shortcut,
callback,
ignoreShortcutInMonaco: item.ignoreShortcutInMonaco ?? false,
});
}
}
}
}
const handleGlobalKeyDown = (event: KeyboardEvent) => {
if (!acceleratorPresssed(event)) return;
for (const item of items) {
if (item.shortcut.pressed(event)) {
event.preventDefault();
item.callback();
}
}
};
document.addEventListener("keydown", handleGlobalKeyDown);
const monacoItems = items.filter((item) => !item.ignoreShortcutInMonaco);
let dispose = editor?.onKeyDown((event) => {
if (!acceleratorPresssedMonaco(event)) return;
for (const item of monacoItems) {
if (item.shortcut.pressedMonaco(event)) {
event.preventDefault();
item.callback();
}
}
});
return () => {
document.removeEventListener("keydown", handleGlobalKeyDown);
dispose?.dispose();
};
}, [bar, callbacks, editor]);
const openNextMenu = () => {
if (typeof menuIndex === "number") {
if (menuIndex === menus.current.length - 1) {
setMenuIndex(0);
} else {
setMenuIndex(menuIndex + 1);
}
}
};
const openPreviousMenu = () => {
if (typeof menuIndex === "number") {
if (menuIndex === 0) {
setMenuIndex(menus.current.length - 1);
} else {
setMenuIndex(menuIndex - 1);
}
}
};
const handleKeyDown = (event: React.KeyboardEvent) => {
if (event.key === "ArrowRight") {
openNextMenu();
}
if (event.key === "ArrowLeft") {
openPreviousMenu();
}
};
const createHandleButtonKeyDown =
(index: number) => (event: React.KeyboardEvent) => {
if (event.key === "ArrowRight") {
if (index === menus.current.length - 1) {
menus.current[0]?.focus();
} else {
menus.current[index + 1]?.focus();
}
}
if (event.key === "ArrowLeft") {
if (index === 0) {
menus.current[menus.current.length]?.focus();
} else {
menus.current[index - 1]?.focus();
}
}
};
useEffect(() => {
if (devices.length > 0) {
setSelectedDevice(devices[0]);
} else {
setSelectedDevice(null);
}
}, [devices]);
return (
{bar &&
bar.map((menu, index) => (
{
setMenuIndex((prevMenuIndex) =>
prevMenuIndex === null ? index : null
);
}}
onKeyDown={createHandleButtonKeyDown(1)}
onMouseEnter={() => {
if (typeof menuIndex === "number") {
setMenuIndex(index);
}
}}
ref={(instance) => {
menus.current[index] = instance!;
}}
menu={
{
menus.current[index]?.focus();
}}
>
}
>
{menu.label}
))}
}
parameters={{
folder: path,
toolchainPath: selectedToolchain?.path ?? "",
}}
tooltip="Clean"
sx={{ marginRight: 0, marginLeft: "auto" }}
/>
}
parameters={{
folder: path,
toolchainPath: selectedToolchain?.path ?? "",
debug: true,
}}
tooltip="Build .ipa"
sx={{ marginRight: 0 }}
/>
}
tooltip="Refresh Devices"
parameters={{}}
sx={{ marginLeft: 0, marginRight: 0 }}
clearConsole={false}
/>
{
setSelectedDevice(
devices.find((d) => d.id.toString() === value) || null
);
}}
placeholder="Select Device..."
>
{devices.length < 1 && (
No devices connected
)}
{devices.map((device, index) => (
{device.name}
))}
}
parameters={{
folder: path,
anisetteServer,
device: selectedDevice,
toolchainPath: selectedToolchain?.path ?? "",
debug: true,
}}
validate={() => {
if (!selectedDevice) {
addToast.error("Please select a device to deploy to.");
return false;
}
return true;
}}
sx={{ marginRight: 0 }}
/>
}
parameters={{
device: selectedDevice,
}}
after={updateScreenshot}
validateAsync={async () => {
if (!selectedDevice) {
addToast.error("Please select a device to take a screenshot of.");
return false;
}
return await mountDdi(true);
}}
sx={{ marginRight: 0, marginLeft: 0 }}
/>
);
}
================================================
FILE: src/components/Menu/MenuBarButton.tsx
================================================
import {
Dropdown,
DropdownProps,
ListItemButton,
MenuButton,
Theme,
menuItemClasses,
typographyClasses,
} from "@mui/joy";
import { cloneElement, forwardRef } from "react";
type MenuBarButtonProps = Pick & {
onOpen: DropdownProps["onOpenChange"];
onKeyDown: React.KeyboardEventHandler;
menu: JSX.Element;
onMouseEnter: React.MouseEventHandler;
};
export default forwardRef(
(
{ children, menu, open, onOpen, onKeyDown, ...props }: MenuBarButtonProps,
ref: React.ForwardedRef
) => {
return (
{children}
{cloneElement(menu, {
slotProps: {
listbox: {
id: `toolbar-example-menu-${children}`,
"aria-label": children,
},
},
placement: "bottom-start",
disablePortal: false,
variant: "soft",
sx: (theme: Theme) => ({
overflowX: "hidden",
width: 288,
boxShadow: "0 2px 8px 0px rgba(0 0 0 / 0.38)",
"--List-padding": "var(--ListDivider-gap)",
"--ListItem-minHeight": "32px",
[`&& .${menuItemClasses.root}`]: {
transition: "none",
"&:hover": {
...theme.variants.solid.primary,
[`& .${typographyClasses.root}`]: {
color: "inherit",
},
},
},
}),
})}
);
}
);
================================================
FILE: src/components/Menu/MenuBarDefinition.tsx
================================================
import { openUrl } from "@tauri-apps/plugin-opener";
import { MenuBarData } from "./MenuGroup";
import { WebviewWindow } from "@tauri-apps/api/webviewWindow";
import { useParams } from "react-router-dom";
import { useIDE } from "../../utilities/IDEContext";
import CommandButton from "../CommandButton";
import { useStore } from "../../utilities/StoreContext";
import { useToast } from "react-toast-plus";
import { MenuItem } from "@mui/joy";
import { invoke } from "@tauri-apps/api/core";
import { restartServer } from "../../utilities/lsp-client";
import { open } from "@tauri-apps/plugin-dialog";
import { useContext } from "react";
import { UpdateContext } from "../../utilities/UpdateContext";
export default [
{
label: "File",
items: [
{
label: "New",
items: [
// {
// name: "New File...",
// shortcut: "Ctrl+N",
// callback: () => {
// alert("Not implemented yet :(");
// },
// },
{
name: "New Project...",
callbackName: "newProject",
},
],
},
{
label: "Open",
items: [
{
name: "Open File...",
shortcut: "Ctrl+O",
callbackName: "openFile",
},
{
name: "Open Folder...",
callbackName: "openFolderDialog",
},
],
},
{
label: "Save",
items: [
{
name: "Save",
shortcut: "Ctrl+S",
callbackName: "save",
},
{
name: "Save As...",
shortcut: "Ctrl+Shift+S",
callback: () => {
alert("Not implemented yet :(");
},
},
],
},
],
},
{
label: "Edit",
items: [
{
label: "Timeline",
items: [
{
name: "Undo",
shortcut: "Ctrl+Z",
ignoreShortcutInMonaco: true,
callbackName: "undo",
},
{
name: "Redo",
shortcut: "Ctrl+Shift+Z",
ignoreShortcutInMonaco: true,
callbackName: "redo",
},
],
},
{
label: "Icon",
items: [
{
name: "Import Icon",
component: () => {
const { path } = useParams<"path">();
const { addToast } = useToast();
return (
{
if (!path) return;
const iconPath = await open({
title: "Select Icon",
multiple: false,
directory: false,
filters: [
{
name: "Images",
extensions: ["png", "jpg", "jpeg", "gif"],
},
],
});
addToast.promise(
invoke("import_icon", {
projectPath: path,
iconPath: iconPath,
}),
{
pending: "Importing icon...",
success: "Successfully imported icon!",
error: "Failed to import icon",
}
);
}}
id="startLSPMenuBtn"
>
Import Icon
);
},
},
],
},
{
label: "Settings",
items: [
{
name: "Preferences...",
callback: async () => {
let prefsWindow = await WebviewWindow.getByLabel("prefs");
if (prefsWindow) {
await prefsWindow.show();
await prefsWindow.center();
await prefsWindow.setFocus();
return;
}
const appWindow = new WebviewWindow("prefs", {
title: "Preferences",
resizable: false,
width: 800,
height: 600,
url: "/preferences/general",
});
appWindow.once("tauri://created", function () {
appWindow.center();
});
appWindow.once("tauri://error", function (e) {
console.error("Error creating window:", e);
});
},
},
],
},
],
},
{
label: "View",
items: [
{
label: "Navigation",
items: [
{
name: "Show Welcome Page",
callbackName: "welcomePage",
},
],
},
{
label: "Debug",
items: [
{
name: "Reload Window",
callback: async () => {
window.location.reload();
},
shortcut: "Ctrl+R",
},
],
},
],
},
{
label: "Build",
items: [
{
label: "Build",
items: [
{
name: "Build .ipa (Debug)",
shortcut: "Ctrl+B",
component: ({ shortcut }) => {
const { path } = useParams<"path">();
const { selectedToolchain } = useIDE();
return (
);
},
componentId: "buildDebugMenuBtn",
},
{
name: "Build .ipa (Release)",
shortcut: "Ctrl+Shift+B",
component: ({ shortcut }) => {
const { path } = useParams<"path">();
const { selectedToolchain } = useIDE();
return (
);
},
componentId: "buildReleaseMenuBtn",
},
{
name: "Build & Install",
shortcut: "Ctrl+I",
component: ({ selectedDevice, shortcut }) => {
const { path } = useParams<"path">();
const { selectedToolchain } = useIDE();
const [anisetteServer] = useStore(
"apple-id/anisette-server",
"ani.sidestore.io"
);
const { addToast } = useToast();
return (
{
if (!selectedDevice) {
addToast.error("Please select a device to deploy to.");
return false;
}
return true;
}}
useMenuItem
id="deployMenuBtn"
/>
);
},
componentId: "deployMenuBtn",
},
],
},
{
label: "Clean",
items: [
{
name: "Clean",
shortcut: "Ctrl+Shift+C",
component: ({ shortcut }) => {
const { path } = useParams<"path">();
const { selectedToolchain } = useIDE();
return (
);
},
componentId: "cleanMenuBtn",
},
],
},
{
label: "Start LSP",
items: [
{
name: "Restart LSP",
component: () => {
const { path } = useParams<"path">();
const { selectedToolchain } = useIDE();
return (
{
if (!selectedToolchain || !path) return;
restartServer(path, selectedToolchain).catch((e) => {
console.error("Failed to restart SourceKit-LSP:", e);
});
}}
id="startLSPMenuBtn"
>
Restart LSP
);
},
componentId: "startLSPMenuBtn",
},
{
name: "Stop LSP",
component: () => {
return (
{
await invoke("stop_sourcekit_server");
}}
id="stopLSPMenuBtn"
>
Stop LSP
);
},
componentId: "stopLSPMenuBtn",
},
],
},
],
},
{
label: "Help",
items: [
{
label: "About",
items: [
{
name: "About CrossCode",
callback: async () => {
let aboutWindow = await WebviewWindow.getByLabel("about");
if (aboutWindow) {
await aboutWindow.show();
await aboutWindow.center();
await aboutWindow.setFocus();
return;
}
const appWindow = new WebviewWindow("about", {
title: "About CrossCode",
resizable: false,
width: 400,
height: 260,
url: "/about",
backgroundColor: "#171a1c",
});
appWindow.once("tauri://created", async function () {
await appWindow.center();
});
appWindow.once("tauri://error", function (e) {
console.error("Error creating window:", e);
});
},
},
{
name: "View Github",
callback: () => {
openUrl("https://github.com/nab138/CrossCode");
},
},
],
},
{
label: "Get Help",
items: [
{
name: "Report Issue",
callback: () => {
openUrl("https://github.com/nab138/CrossCode/issues");
},
},
{
name: "Troubleshooting",
callback: () => {
openUrl(
"https://github.com/nab138/CrossCode/wiki/Troubleshooting"
);
},
},
],
},
{
label: "Debug",
items: [
{
name: "Open Devtools",
shortcut: "Ctrl+Shift+I",
ignoreShortcutInMonaco: true,
callback: () => {
invoke("open_devtools");
},
},
],
},
{
label: "Updates",
items: [
{
name: "Check for Updates",
component: () => {
const { checkForUpdates } = useContext(UpdateContext);
return (
{
await checkForUpdates();
}}
id="checkForUpdatesMenuBtn"
>
Check for Updates
);
},
},
],
},
],
},
] as MenuBarData;
================================================
FILE: src/components/Menu/MenuGroup.tsx
================================================
import { List, ListDivider, ListItem, MenuItem, Typography } from "@mui/joy";
import { Fragment } from "react/jsx-runtime";
import { DeviceInfo } from "../../utilities/IDEContext";
type BaseMenuItem = {
name: string;
shortcut?: string;
ignoreShortcutInMonaco?: boolean;
};
export type MenuItem = BaseMenuItem &
(
| { callback: () => void }
| { callbackName: string }
| {
component: React.FC<{
shortcut?: React.ReactNode;
selectedDevice?: DeviceInfo | null;
}>;
componentId: string;
}
);
type MenuGroup = {
label: string;
items: MenuItem[];
};
export type MenuBarData = {
label: string;
items: MenuGroup[];
}[];
export interface MenuGroupProps {
groups: MenuGroup[];
handleKeyDown: (event: React.KeyboardEvent) => void;
resetMenuIndex: () => void;
callbacks: Record void>;
selectedDevice: DeviceInfo | null;
}
const renderShortcut = (text: string) => (
{text}
);
const MenuGroup: React.FC = ({
groups,
handleKeyDown,
callbacks,
resetMenuIndex,
selectedDevice,
}) => {
return (
<>
{groups.map((group, groupIndex) => (
{group.items.map((item, itemIndex) => {
if ("component" in item) {
return (
{item.component({
selectedDevice,
shortcut: item.shortcut
? renderShortcut(item.shortcut)
: undefined,
})}
);
}
return (
{
resetMenuIndex();
let callback;
if (
"callbackName" in item &&
typeof item.callbackName === "string"
) {
callback = callbacks[item.callbackName];
} else if (
"callback" in item &&
typeof item.callback === "function"
) {
callback = item.callback;
} else {
callback = () => {};
}
callback();
}}
onKeyDown={handleKeyDown}
>
{item.name} {item.shortcut && renderShortcut(item.shortcut)}
);
})}
{groupIndex < groups.length - 1 && }
))}
>
);
};
export default MenuGroup;
================================================
FILE: src/components/OperationView.css
================================================
.operation-content {
display: flex;
flex-direction: column;
gap: var(--padding-xl);
}
.operation-step-icon {
width: 1.5rem;
height: 1.5rem;
min-width: 1.5rem;
min-height: 1.5rem;
font-size: 1.5rem;
}
.operation-step {
display: flex;
gap: var(--padding-md);
align-items: center;
}
.operation-extra-details {
background-color: black;
overflow-x: auto;
padding: var(--padding-md);
border-radius: 1px;
margin: 0;
}
.operation-step-internal {
flex-shrink: 1;
}
================================================
FILE: src/components/OperationView.tsx
================================================
import {
Accordion,
AccordionDetails,
AccordionSummary,
Divider,
Modal,
ModalClose,
ModalDialog,
Typography,
} from "@mui/joy";
import { OperationState } from "../utilities/operations";
import "./OperationView.css";
import { SuccessIcon, ErrorIcon, StyledLoadingIcon } from "react-toast-plus";
import { PanoramaFishEye, DoNotDisturbOn } from "@mui/icons-material";
export default ({
operationState,
closeMenu,
}: {
operationState: OperationState;
closeMenu: () => void;
}) => {
const operation = operationState.current;
const opFailed = operationState.failed.length > 0;
const done =
(opFailed &&
operationState.started.length ==
operationState.completed.length + operationState.failed.length) ||
operationState.completed.length == operation.steps.length;
return (
{
if (done) closeMenu();
}}
>
{done && }
{operation?.title}
{done
? opFailed
? "Operation failed. Please see steps for details."
: "Operation completed!"
: "Please wait (this may take a while)..."}
{operation.steps.map((step) => {
let failed = operationState.failed.find((f) => f.stepId == step.id);
let completed = operationState.completed.includes(step.id);
let started = operationState.started.includes(step.id);
let notStarted = !failed && !completed && !started;
return (
{failed &&
}
{!failed && completed &&
}
{!failed && !completed && started &&
}
{notStarted && !opFailed && (
)}
{notStarted && opFailed && (
)}
{step.title}
{failed && (
Details
{failed.extraDetails}
)}
);
})}
);
};
================================================
FILE: src/components/SDKMenu.tsx
================================================
import { Button, Typography } from "@mui/joy";
import { useIDE } from "../utilities/IDEContext";
import { open } from "@tauri-apps/plugin-dialog";
import { useToast } from "react-toast-plus";
import { useCallback, useEffect } from "react";
import { openUrl } from "@tauri-apps/plugin-opener";
import { installSdkOperation } from "../utilities/operations";
import ErrorIcon from "@mui/icons-material/Error";
import WarningIcon from "@mui/icons-material/Warning";
import { DARWIN_SDK_VERSION } from "../utilities/constants";
export default () => {
const {
selectedToolchain,
hasDarwinSDK,
darwinSDKVersion,
checkSDK,
startOperation,
isWindows,
hasWSL,
} = useIDE();
const { addToast } = useToast();
const isWindowsReady = !isWindows || hasWSL;
const install = useCallback(async () => {
let xipPath = await open({
directory: false,
multiple: false,
filters: [
{
name: "XCode",
extensions: ["xip"],
},
],
});
if (!xipPath) {
addToast.error("No Xcode.xip selected");
return;
}
const params = {
xcodePath: xipPath,
toolchainPath: selectedToolchain?.path || "",
isDir: false,
};
await startOperation(installSdkOperation, params);
checkSDK();
}, [selectedToolchain, addToast]);
const installFromFolder = useCallback(async () => {
let xcodePath = await open({
directory: true,
multiple: false,
filters: [
{
name: "XCode.app",
extensions: ["app"],
},
],
});
if (!xcodePath) {
addToast.error("No Xcode selected");
return;
}
const params = {
xcodePath,
toolchainPath: selectedToolchain?.path || "",
isDir: true,
};
await startOperation(installSdkOperation, params);
checkSDK();
}, [selectedToolchain, addToast]);
useEffect(() => {
checkSDK();
}, [checkSDK]);
if (hasDarwinSDK === null) {
return Checking for SDK...
;
}
return (
{isWindowsReady ? (
hasDarwinSDK ? (
"Darwin SDK is installed!"
) : (
<>
{selectedToolchain ? : }
{selectedToolchain
? "Darwin SDK is not installed"
: "Select a swift toolchain first"}
>
)
) : (
"Install WSL and Swift first."
)}
{hasDarwinSDK && (
{darwinSDKVersion === DARWIN_SDK_VERSION
? `Version: ${darwinSDKVersion}`
: `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.`}
)}
{
e.preventDefault();
openUrl(
"https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_26/Xcode_26_Universal.xip"
);
}}
>
Download XCode 26
{
if (e.shiftKey) {
installFromFolder();
} else {
install();
}
}}
disabled={!selectedToolchain}
>
{hasDarwinSDK ? "Reinstall SDK" : "Install SDK"}
Check Again
);
};
================================================
FILE: src/components/SwiftMenu.tsx
================================================
import {
Button,
FormControl,
Link,
Radio,
RadioGroup,
Typography,
} from "@mui/joy";
import { Toolchain, useIDE } from "../utilities/IDEContext";
import { useEffect, useState } from "react";
import { openUrl } from "@tauri-apps/plugin-opener";
import ErrorIcon from "@mui/icons-material/Error";
import { invoke } from "@tauri-apps/api/core";
import { SWIFT_VERSION_PREFIX } from "../utilities/constants";
export default () => {
const {
selectedToolchain,
setSelectedToolchain,
toolchains,
scanToolchains,
locateToolchain,
isWindows,
hasWSL,
} = useIDE();
const isWindowsReady = !isWindows || hasWSL;
const [allToolchains, setAllToolchains] = useState([]);
useEffect(() => {
let loadAllToolchains = async () => {
let all: Toolchain[] = [];
if (toolchains !== null && toolchains.toolchains) {
all = [...toolchains.toolchains];
}
if (
selectedToolchain &&
!all.some(
(t) => stringifyToolchain(t) === stringifyToolchain(selectedToolchain)
) &&
(await invoke("validate_toolchain", {
toolchainPath: selectedToolchain.path,
}))
) {
all.push(selectedToolchain);
}
setAllToolchains(all);
};
loadAllToolchains();
}, [selectedToolchain, toolchains]);
return (
{!selectedToolchain && (
No toolchain selected
)}
{toolchains === null
? "Checking for Swift..."
: toolchains.swiftlyInstalled
? `Swiftly Detected: ${toolchains.swiftlyVersion}`
: "CrossCode was unable to detect Swiftly."}
{!isWindowsReady && toolchains !== null && allToolchains.length === 0 && (
Install WSL before swift, as you need to install swift inside of WSL.
)}
{isWindowsReady && toolchains !== null && allToolchains.length === 0 && (
No Swift toolchains found. You can get one by installing swiftly
{isWindows && " in WSL"} and running "
swiftly install {SWIFT_VERSION_PREFIX}
" or manually. If you have already done so, but it is not showing up,
your toolchain installation may be broken. For help, refer to the{" "}
{
e.preventDefault();
openUrl(
"https://github.com/nab138/CrossCode/wiki/Troubleshooting#swift-toolchain-not-detected"
);
}}
>
troubleshooting guide
.
)}
{selectedToolchain !== null && !isCompatable(selectedToolchain) && (
Your selected toolchain is not compatible. Please select a swift{" "}
{SWIFT_VERSION_PREFIX}
toolchain.
)}
{toolchains !== null && allToolchains.length > 0 && (
Select a toolchain:
{allToolchains.map((toolchain) => (
setSelectedToolchain(toolchain)}
/>
{toolchain.path}
{toolchain.isSwiftly ? "(Swiftly)" : "(Manually Installed)"}
))}
)}
{toolchains?.swiftlyInstalled === false &&
selectedToolchain === null && (
{
openUrl("https://www.swift.org/install/linux");
}}
>
Download Swift
)}
{
{
scanToolchains();
}}
>
Scan Again
}
{
Locate Existing Toolchain
}
);
};
export function isCompatable(toolchain: Toolchain | null): boolean {
if (!toolchain) return false;
return toolchain.version.startsWith(SWIFT_VERSION_PREFIX);
}
function stringifyToolchain(toolchain: Toolchain | null): string | null {
if (!toolchain) return null;
return `${toolchain.path}:${toolchain.version}:${toolchain.isSwiftly}`;
}
================================================
FILE: src/components/TabLike.tsx
================================================
import { styled } from "@mui/joy/styles";
import { forwardRef, ButtonHTMLAttributes } from "react";
interface TabLikeProps extends ButtonHTMLAttributes {
selected?: boolean;
dragging?: boolean;
}
const TabLikeRoot = styled("button")(
({ theme, selected, disabled, dragging }) => ({
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
gap: "0.25rem",
position: "relative",
boxSizing: "border-box",
cursor: disabled ? "not-allowed" : "pointer",
fontSize: "14px",
minHeight: "24px !important",
border: 0,
outline: 0,
background: "none",
textDecoration: "none",
...theme.typography["title-sm"],
fontWeight: selected ? theme.vars.fontWeight.md : theme.vars.fontWeight.sm,
padding: "4px 8px",
...theme.variants.plain.neutral,
"&:hover": !disabled ? theme.variants.plainHover.neutral : undefined,
"&:active": !disabled ? theme.variants.plainActive.neutral : undefined,
...(selected && theme.variants.plainActive.neutral),
...(disabled && theme.variants.plainDisabled?.neutral),
"&:focus-visible": {
outline: `2px solid ${theme.vars.palette.focusVisible}`,
outlineOffset: 2,
},
...(dragging && {
opacity: 0.6,
}),
transition: "background-color 120ms, color 120ms",
})
);
export const TabLike = forwardRef(
({ selected, dragging, ...rest }, ref) => {
return (
);
}
);
================================================
FILE: src/components/Tiles/BottomBar.css
================================================
.bottom-container {
height: 100%;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #888 #000;
box-sizing: border-box;
}
================================================
FILE: src/components/Tiles/BottomBar.tsx
================================================
import { useEffect, useRef, useState } from "react";
import "./BottomBar.css";
import { Button, Input, Tab, TabList, TabPanel, Tabs } from "@mui/joy";
import CommandButton from "../CommandButton";
import { Terminal, StopCircle } from "@mui/icons-material";
import { useIDE } from "../../utilities/IDEContext";
import { useToast } from "react-toast-plus";
import { invoke } from "@tauri-apps/api/core";
import CommandConsole from "./CommandConsole";
import Console from "./Console";
import FilteredConsole, { FilteredConsoleHandle } from "./FilteredConsole";
import { useParams } from "react-router";
import { useStore } from "../../utilities/StoreContext";
const staticTabs = [
{
name: "Build Output",
component: ,
},
{
name: "SourceKit-LSP",
component: (
),
},
];
export default function BottomBar() {
const [focused, setFocused] = useState();
const [refreshSyslog, setRefreshSyslog] = useState(0);
const [runningSyslog, setRunningSyslog] = useState(false);
const [runningStdout, setRunningStdout] = useState(false);
const [refreshStdout, setRefreshStdout] = useState(0);
const [syslogFilter, setSyslogFilter] = useState("");
const [stdoutFilter, setStdoutFilter] = useState("");
const syslogRef = useRef(null);
const stdoutRef = useRef(null);
useEffect(() => {
const checkSyslog = async () => {
const isStreaming = await invoke("is_streaming_syslog");
setRunningSyslog(isStreaming);
};
checkSyslog();
}, [focused, refreshSyslog]);
useEffect(() => {
const checkStdout = async () => {
const isStreaming = await invoke("is_streaming_stdout");
setRunningStdout(isStreaming);
};
checkStdout();
}, [focused, refreshStdout]);
useEffect(() => {
if (focused === undefined && staticTabs.length > 0) {
setFocused(0);
}
}, [focused]);
return (
{
if (newValue === null) return;
setFocused(newValue as number);
}}
>
{staticTabs.map((tab, index) => (
{tab.name}
))}
Syslog
App Console
{focused === staticTabs.length && (
{
syslogRef.current?.clear();
}}
/>
)}
{focused === staticTabs.length + 1 && (
{
stdoutRef.current?.clear();
}}
/>
)}
{staticTabs.map((tab, index) => (
{tab.component}
))}
{
setRefreshSyslog((prev) => prev + 1);
}}
/>
,
{
setRefreshStdout((prev) => prev + 1);
}}
ref={stdoutRef}
/>
,
);
}
function BottomBarFilter({
filter,
setFilter,
setRefresh,
clear,
displayName,
errorMessage,
startCommand,
stopCommand,
running,
customTooltip,
requiresDDI = false,
}: {
filter: string;
setFilter: React.Dispatch>;
setRefresh: React.Dispatch>;
clear: () => void;
displayName: string;
errorMessage: string;
startCommand: string;
stopCommand: string;
running: boolean;
customTooltip: string;
requiresDDI?: boolean;
}) {
const { selectedDevice, mountDdi } = useIDE();
const { addToast } = useToast();
const { path } = useParams<"path">();
const [anisetteServer] = useStore(
"apple-id/anisette-server",
"ani.sidestore.io"
);
return (
<>
Clear
{!running && (
}
parameters={{
device: selectedDevice,
folder: path ?? "",
anisetteServer: anisetteServer,
}}
validate={() => {
if (!selectedDevice) {
addToast.error(errorMessage);
return false;
}
return true;
}}
validateAsync={requiresDDI ? () => mountDdi(true) : undefined}
after={() => {
setRefresh((prev) => prev + 1);
}}
label={`Start ${displayName}`}
sx={{
marginRight: "var(--padding-xs)",
fontSize: "12px",
flexShrink: 0,
}}
size="sm"
/>
)}
{running && (
{
setFilter(e.target.value);
}}
sx={{
width: "200px",
minWidth: "150px",
marginRight: "var(--padding-xs)",
fontSize: "12px",
}}
size="sm"
/>
)}
{running && (
}
sx={{
marginRight: "var(--padding-xs)",
fontSize: "12px",
flexShrink: 0,
}}
after={() => {
setRefresh((prev) => prev + 1);
}}
label={`Stop ${displayName}`}
size="sm"
/>
)}
>
);
}
================================================
FILE: src/components/Tiles/CommandConsole.tsx
================================================
import { useEffect, useRef } from "react";
import "./Console.css";
import { listen } from "@tauri-apps/api/event";
import Convert from "ansi-to-html";
import { Virtuoso } from "react-virtuoso";
import { useIDE } from "../../utilities/IDEContext";
import { escapeHtml } from "./Console";
import { useParams } from "react-router";
const convert = new Convert();
export default function CommandConsole() {
const { consoleLines, setConsoleLines } = useIDE();
const listenerAdded = useRef(false);
const unlisten = useRef<() => void>(() => {});
const { path } = useParams<"path">();
useEffect(() => {
setConsoleLines([]);
}, [path]);
useEffect(() => {
if (!listenerAdded.current) {
(async () => {
const unlistenFn = await listen("build-output", (event) => {
let line = event.payload as string;
if (line.includes("command.done")) {
if (line.split(".")[2] === "999") {
setConsoleLines((lines) => [...lines, "Command failed"]);
} else {
setConsoleLines((lines) => [
...lines,
"Command finished with exit code: " + line.split(".")[2],
]);
}
} else {
setConsoleLines((lines) => [...lines, line]);
}
});
unlisten.current = unlistenFn;
})();
listenerAdded.current = true;
}
return () => {
unlisten.current();
};
}, []);
return (
);
}
================================================
FILE: src/components/Tiles/Console.css
================================================
.console-tile {
background-color: var(--joy-background-popup);
font-size: smaller;
height: 100%;
min-width: 100%;
}
.console-container {
height: 100%;
padding: 0 var(--padding-md);
background-color: var(--joy-background-popup);
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #888 #000;
box-sizing: border-box;
}
================================================
FILE: src/components/Tiles/Console.tsx
================================================
import { useEffect, useRef, useState } from "react";
import "./Console.css";
import { listen } from "@tauri-apps/api/event";
import Convert from "ansi-to-html";
import { Virtuoso } from "react-virtuoso";
import { useParams } from "react-router";
const convert = new Convert();
export function escapeHtml(unsafe: string) {
return unsafe
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
export default function Console({
channel,
jsonPrettyPrint,
}: {
channel: string;
jsonPrettyPrint?: boolean;
}) {
const [consoleLines, setConsoleLines] = useState([]);
const listenerAdded = useRef(false);
const unlisten = useRef<() => void>(() => {});
const { path } = useParams<"path">();
useEffect(() => {
setConsoleLines([]);
}, [path]);
useEffect(() => {
if (!listenerAdded.current) {
(async () => {
const unlistenFn = await listen(channel, (event) => {
let line = event.payload as string;
if (jsonPrettyPrint) {
try {
let parsed = JSON.parse(line);
line = JSON.stringify(parsed, null, 2);
} catch (error) {
console.error(
"Failed to parse JSON where prettyPrint was enabled:",
error
);
}
}
setConsoleLines((lines) => [...lines, line]);
});
unlisten.current = unlistenFn;
})();
listenerAdded.current = true;
}
return () => {
unlisten.current();
};
}, []);
return (
);
}
================================================
FILE: src/components/Tiles/Editor.css
================================================
.editor {
height: 100%;
position: relative;
overflow: hidden;
}
.code-editor {
width: 100%;
height: 100%;
max-height: 100%;
overflow: hidden;
position: relative;
/* transform: translate(0, -100%); */
}
.tabsContainer {
display: flex;
padding-bottom: 1px;
position: relative;
width: 100%;
overflow-x: hidden;
}
.tab-wrapper {
display: flex;
align-items: center;
position: relative;
flex-shrink: 0;
}
.tabsContainer .Mui-selected::after {
content: "";
display: block;
height: 2px;
background: currentColor;
position: absolute;
bottom: -1px;
z-index: 999;
left: 0;
right: 0;
}
.drop-indicator {
width: 2px;
height: 100%;
background: var(--joy-palette-neutral-300);
position: absolute;
z-index: 1000;
left: 0;
}
.drop-indicator-end {
position: relative;
left: auto;
margin-left: 0;
height: 32px;
align-self: stretch;
}
================================================
FILE: src/components/Tiles/Editor.tsx
================================================
import { path } from "@tauri-apps/api";
import "./Editor.css";
import { IconButton, useColorScheme } from "@mui/joy";
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
import CloseIcon from "@mui/icons-material/Close";
import CircleIcon from "@mui/icons-material/Circle";
import * as monaco from "monaco-editor";
import { initialize, ITextEditorOptions } from "@codingame/monaco-vscode-api";
import getLanguagesServiceOverride from "@codingame/monaco-vscode-languages-service-override";
import getThemeServiceOverride from "@codingame/monaco-vscode-theme-service-override";
import getTextMateServiceOverride from "@codingame/monaco-vscode-textmate-service-override";
import getEditorServiceOverride from "@codingame/monaco-vscode-editor-service-override";
import getModelServiceOverride from "@codingame/monaco-vscode-model-service-override";
import "@codingame/monaco-vscode-swift-default-extension";
import "@codingame/monaco-vscode-theme-defaults-default-extension";
import { platform } from "@tauri-apps/plugin-os";
import { TabLike } from "../TabLike";
import { useStore } from "../../utilities/StoreContext";
import { useParams } from "react-router";
import { readTextFile, writeTextFile } from "@tauri-apps/plugin-fs";
export type WorkerLoader = () => Worker;
const workerLoaders: Partial> = {
TextEditorWorker: () =>
new Worker(
new URL("monaco-editor/esm/vs/editor/editor.worker.js", import.meta.url),
{ type: "module" }
),
TextMateWorker: () =>
new Worker(
new URL(
"@codingame/monaco-vscode-textmate-service-override/worker",
import.meta.url
),
{ type: "module" }
),
};
window.MonacoEnvironment = {
getWorker: function (_workerId, label) {
const workerFactory = workerLoaders[label];
if (workerFactory != null) {
return workerFactory();
}
throw new Error(`Worker ${label} not found`);
},
};
export interface EditorProps {
openFiles: string[];
setOpenFiles: Dispatch>;
focusedFile: string | null;
setSaveFile: Dispatch Promise) | null>>;
setUndo: Dispatch void) | null>>;
setRedo: Dispatch void) | null>>;
openNewFile: (file: string) => void;
setEditorUpper: Dispatch<
SetStateAction
>;
}
let globalInitialized = false;
let globalEditorServiceCallbacks = {
currentTabsRef: { current: [] as { name: string; file: string }[] },
setFocusedRef: { current: (() => {}) as any },
openNewFileRef: { current: (() => {}) as any },
editorRef: { current: null as monaco.editor.IStandaloneCodeEditor | null },
selectionOverrideRef: { current: null as ITextEditorOptions | null },
};
export default ({
openFiles,
focusedFile,
setSaveFile,
setUndo,
setRedo,
setOpenFiles,
openNewFile,
setEditorUpper,
}: EditorProps) => {
const [tabs, setTabs] = useState<
{
name: string;
file: string;
}[]
>([]);
const [unsavedFiles, setUnsavedFiles] = useState([]);
const [draggedIndex, setDraggedIndex] = useState(null);
const [dropIndicatorIndex, setDropIndicatorIndex] = useState(
null
);
const [focused, setFocused] = useState();
const [editor, setEditor] =
useState(null);
const { mode } = useColorScheme();
const monacoEl = useRef(null);
const [initialized, setInitialized] = useState(false);
const currentTabsRef = useRef(tabs);
const setFocusedRef = useRef(setFocused);
const editorRef = useRef(null);
const openNewFileRef = useRef(openNewFile);
const selectionOverrideRef = useRef(null);
const hasInitializedRef = useRef(false);
const scrollStates = useRef<{
[key: string]: [number, number];
}>({});
const [hoveredOnBtn, setHoveredOnBtn] = useState(null);
const [formatOnSave] = useStore("sourcekit/format", true);
const { path: filePath } = useParams<"path">();
const hasAttemptedToReadOpenFiles = useRef(null);
useEffect(() => {
(async () => {
if (!filePath || hasAttemptedToReadOpenFiles.current === filePath) return;
const savePath = await path.join(
filePath,
".crosscode",
"openFiles.json"
);
try {
let text = await readTextFile(savePath);
if (!text) return;
let data = JSON.parse(text) as { files: string[]; focused: number };
if (
!data ||
typeof data !== "object" ||
!Array.isArray(data.files) ||
typeof data.focused !== "number"
)
return;
data.files = data.files.filter((file) => typeof file === "string");
if (data.files.length === 0) return;
if (data.focused < 0 || data.focused >= data.files.length) {
data.focused = 0;
}
setOpenFiles(data.files);
setTimeout(() => {
setFocused(data.focused);
}, 100);
} catch (e) {
void e;
} finally {
hasAttemptedToReadOpenFiles.current = filePath;
}
})();
}, [filePath, setOpenFiles, setFocused]);
useEffect(() => {
(async () => {
if (!filePath || hasAttemptedToReadOpenFiles.current !== filePath) return;
const savePath = await path.join(
filePath,
".crosscode",
"openFiles.json"
);
let data = {
files: openFiles,
focused: focused ?? 0,
};
writeTextFile(savePath, JSON.stringify(data)).catch((err) => {
console.error("Error writing openFiles.json:", err);
});
})();
}, [openFiles, filePath, focused]);
useEffect(() => {
globalEditorServiceCallbacks.currentTabsRef = currentTabsRef;
globalEditorServiceCallbacks.setFocusedRef = setFocusedRef;
globalEditorServiceCallbacks.editorRef = editorRef;
globalEditorServiceCallbacks.openNewFileRef = openNewFileRef;
globalEditorServiceCallbacks.selectionOverrideRef = selectionOverrideRef;
});
useEffect(() => {
editorRef.current = editor;
setEditorUpper(editor);
}, [editor]);
useEffect(() => {
currentTabsRef.current = tabs;
}, [tabs]);
useEffect(() => {
setFocusedRef.current = setFocused;
}, [setFocused]);
useEffect(() => {
openNewFileRef.current = openNewFile;
}, [openNewFile]);
useEffect(() => {
const initializeEditor = async () => {
if (globalInitialized && !hasInitializedRef.current) {
setInitialized(true);
hasInitializedRef.current = true;
return;
}
globalInitialized = true;
await initialize({
...getTextMateServiceOverride(),
...getThemeServiceOverride(),
...getLanguagesServiceOverride(),
...getEditorServiceOverride((modelRef, options) => {
return new Promise((resolve) => {
if (!globalEditorServiceCallbacks.editorRef.current)
return resolve(undefined);
let path =
platform() === "windows"
? modelRef.object.textEditorModel.uri.path
: modelRef.object.textEditorModel.uri.fsPath;
if (!path) return resolve(undefined);
let tabIndex =
globalEditorServiceCallbacks.currentTabsRef.current.findIndex(
(tab) => tab.file === path
);
if (options !== undefined) {
const opts = options as ITextEditorOptions | undefined;
if (opts?.selection) {
globalEditorServiceCallbacks.selectionOverrideRef.current =
opts;
}
}
if (tabIndex === -1) {
globalEditorServiceCallbacks.openNewFileRef.current(path);
} else {
globalEditorServiceCallbacks.setFocusedRef.current(tabIndex);
}
resolve(undefined);
});
}),
...getModelServiceOverride(),
});
setInitialized(true);
hasInitializedRef.current = true;
};
initializeEditor();
}, []);
useEffect(() => {
if (focusedFile !== null) {
let i = openFiles.indexOf(focusedFile);
if (i === -1 || focused === i) return;
setFocused(i);
}
}, [focusedFile, openFiles]);
useEffect(() => {
const fetchTabNames = async () => {
setTabs(
await Promise.all(
openFiles.map(async (file) => ({
name: await path.basename(file),
file,
}))
)
);
};
fetchTabNames();
}, [openFiles]);
useEffect(() => {
if (!monacoEl.current || editor || !initialized) return;
const newEditor = monaco.editor.create(monacoEl.current, {
value: "",
language: "plaintext",
theme: mode === "dark" ? "vs-dark" : "vs",
});
setUndo(() => () => {
newEditor.trigger("keyboard", "undo", null);
});
setRedo(() => () => {
newEditor.trigger("keyboard", "redo", null);
});
setEditor(newEditor);
return () => {
newEditor.dispose();
};
}, [initialized]);
useEffect(() => {
if (editor === null) return;
let listener = editor.onDidScrollChange((e) => {
if (focused !== undefined) {
scrollStates.current[tabs[focused].file] = [e.scrollTop, e.scrollLeft];
}
});
return () => {
listener.dispose();
};
}, [editor, focused, tabs]);
useEffect(() => {
if (!editor || !initialized) return;
monaco.editor.setTheme(mode === "dark" ? "vs-dark" : "vs");
}, [mode, editor, initialized, openFiles]);
useEffect(() => {
if (!monacoEl.current || !editor) return;
const resizeObserver = new ResizeObserver(() => {
editor.layout();
});
resizeObserver.observe(monacoEl.current);
return () => {
resizeObserver.disconnect();
};
}, [editor]);
const handleDragStart = (e: React.DragEvent, index: number) => {
setDraggedIndex(index);
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", index.toString());
};
const handleDragOver = (e: React.DragEvent, index: number) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
if (draggedIndex === null) return;
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
const midpoint = rect.left + rect.width / 2;
const mouseX = e.clientX;
let insertIndex;
if (mouseX < midpoint) {
insertIndex = index;
} else {
insertIndex = index + 1;
}
if (insertIndex === draggedIndex || insertIndex === draggedIndex + 1) {
setDropIndicatorIndex(null);
} else {
setDropIndicatorIndex(insertIndex);
}
};
const handleContainerDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
if (draggedIndex === null) return;
const container = e.currentTarget as HTMLElement;
const mouseX = e.clientX;
const lastTab = container.querySelector(".tab-wrapper:last-child");
if (lastTab) {
const lastTabRect = lastTab.getBoundingClientRect();
if (mouseX > lastTabRect.right) {
setDropIndicatorIndex(tabs.length);
return;
}
}
const firstTab = container.querySelector(".tab-wrapper:first-child");
if (firstTab) {
const firstTabRect = firstTab.getBoundingClientRect();
if (mouseX < firstTabRect.left) {
setDropIndicatorIndex(0);
return;
}
}
};
const handleDragLeave = (e: React.DragEvent) => {
const container = e.currentTarget as HTMLElement;
const relatedTarget = e.relatedTarget as Node;
if (!container.contains(relatedTarget)) {
setDropIndicatorIndex(null);
}
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
if (draggedIndex === null || dropIndicatorIndex === null) {
setDraggedIndex(null);
setDropIndicatorIndex(null);
return;
}
const newTabs = [...tabs];
const newOpenFiles = [...openFiles];
let actualDropIndex = dropIndicatorIndex;
if (draggedIndex < dropIndicatorIndex) {
actualDropIndex = dropIndicatorIndex - 1;
}
const draggedTab = newTabs.splice(draggedIndex, 1)[0];
const draggedFile = newOpenFiles.splice(draggedIndex, 1)[0];
newTabs.splice(actualDropIndex, 0, draggedTab);
newOpenFiles.splice(actualDropIndex, 0, draggedFile);
let newFocused = focused;
if (focused === draggedIndex) {
newFocused = actualDropIndex;
} else if (focused !== undefined) {
if (draggedIndex < focused && actualDropIndex >= focused) {
newFocused = focused - 1;
} else if (draggedIndex > focused && actualDropIndex <= focused) {
newFocused = focused + 1;
}
}
setTabs(newTabs);
setOpenFiles(newOpenFiles);
setFocused(newFocused);
setDraggedIndex(null);
setDropIndicatorIndex(null);
};
const handleDragEnd = () => {
setDraggedIndex(null);
setDropIndicatorIndex(null);
};
useEffect(() => {
let switchFile = async () => {
if (!editor || focused === undefined || !tabs[focused]) return;
let filePath = tabs[focused]?.file;
let file = monaco.Uri.file(filePath);
let modelRef = await monaco.editor.createModelReference(file);
modelRef.object.onDidChangeDirty(() => {
setUnsavedFiles((files) => {
if (modelRef.object.isDirty()) {
return [...files, tabs[focused]?.file];
} else {
return files.filter((f) => f !== tabs[focused]?.file);
}
});
});
setSaveFile(() => async () => {
if (formatOnSave) {
await editor.getAction("editor.action.formatDocument")?.run();
}
await modelRef.object.save();
});
editor.setModel(modelRef.object.textEditorModel);
if (scrollStates.current && scrollStates.current[filePath]) {
const [scrollTop, scrollLeft] = scrollStates.current[filePath];
editor.setScrollTop(scrollTop);
editor.setScrollLeft(scrollLeft);
}
// I don't love doing it like this but it seems to improve consistency over just running it directly
requestAnimationFrame(() => {
if (
selectionOverrideRef.current &&
selectionOverrideRef.current.selection
) {
editor.setSelection(
{
startLineNumber:
selectionOverrideRef.current.selection.startLineNumber,
startColumn: selectionOverrideRef.current.selection.startColumn,
endLineNumber:
selectionOverrideRef.current.selection.endLineNumber ??
selectionOverrideRef.current.selection.startLineNumber,
endColumn:
selectionOverrideRef.current.selection.endColumn ??
selectionOverrideRef.current.selection.startColumn,
},
selectionOverrideRef.current.selectionSource
);
editor.revealLineNearTop(
selectionOverrideRef.current.selection.startLineNumber,
0
);
selectionOverrideRef.current = null;
}
});
};
switchFile();
}, [focused, editor, tabs, formatOnSave]);
return (
{
if (e.deltaY !== 0) {
e.currentTarget.scrollLeft += e.deltaY;
e.preventDefault();
}
}}
>
{tabs.map((tab, index) => {
let unsaved = unsavedFiles.includes(tab.file);
return (
{dropIndicatorIndex === index && (
)}
{
setFocused(index);
}}
onDragStart={(e) => handleDragStart(e, index)}
onDragOver={(e) => handleDragOver(e, index)}
onDragEnd={handleDragEnd}
>
{tab.name}
setHoveredOnBtn(index)}
onMouseLeave={() => setHoveredOnBtn(null)}
size="xs"
sx={{ margin: "0px", marginLeft: "2px" }}
onClick={(event) => {
event.stopPropagation();
setTabs((tabs) => tabs.filter((_, i) => i !== index));
setFocused((focused) => {
if (focused === index) return 0;
return focused;
});
setOpenFiles((openFiles) =>
openFiles.filter((file) => file !== tab.file)
);
}}
>
{!unsaved || hoveredOnBtn === index ? (
) : (
)}
);
})}
{dropIndicatorIndex === tabs.length && (
)}
= 1 ? {} : { display: "none" }}
/>
);
};
================================================
FILE: src/components/Tiles/FileExplorer.css
================================================
.file-explorer {
overflow-y: auto;
height: 100%;
}
================================================
FILE: src/components/Tiles/FileExplorer.tsx
================================================
import {
Accordion,
AccordionDetails,
AccordionGroup,
AccordionSummary,
Button,
Divider,
Menu,
MenuItem,
Modal,
ModalDialog,
Input,
Typography,
Box,
} from "@mui/joy";
import "./FileExplorer.css";
import { useCallback, useEffect, useState } from "react";
import { path } from "@tauri-apps/api";
import * as fs from "@tauri-apps/plugin-fs";
import { ClickAwayListener } from "@mui/material";
import { revealItemInDir } from "@tauri-apps/plugin-opener";
import { invoke } from "@tauri-apps/api/core";
import { platform } from "@tauri-apps/plugin-os";
import { useToast } from "react-toast-plus";
interface FileItemProps {
filePath: string;
isDirectory: boolean;
setOpenFile: (file: string) => void;
openDefault?: boolean;
refresh?: number;
}
const FileItem: React.FC
= ({
filePath,
isDirectory,
setOpenFile,
openDefault = false,
refresh = 0,
}) => {
const handleOpenFile = useCallback(async () => {
if (platform() === "windows") {
setOpenFile(await invoke("linux_path", { path: filePath }));
} else {
setOpenFile(filePath);
}
}, [filePath]);
const [children, setChildren] = useState<
{
path: string;
isDirectory: boolean;
}[]
>([]);
const [name, setName] = useState("");
const [expanded, setExpanded] = useState(openDefault);
useEffect(() => {
(async () => {
setName(await path.basename(filePath));
if (!isDirectory || !expanded) return;
try {
const files = await fs.readDir(filePath);
const parsedFilePromises = files.map(async (file) => {
let pathS = await path.resolve(filePath, file.name);
return {
path: pathS,
isDirectory: file.isDirectory,
};
});
setChildren(
(await Promise.all(parsedFilePromises)).sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1;
if (!a.isDirectory && b.isDirectory) return 1;
return a.path.localeCompare(b.path);
})
);
} catch (error) {
console.error("Failed to read file:", filePath, error);
}
})();
}, [filePath, expanded, refresh]);
const handleAccordionChange = (
_: React.SyntheticEvent,
isExpanded: boolean
) => {
setExpanded(isExpanded);
};
if (isDirectory) {
return (
{name}
{children.map((child) => (
))}
);
} else {
return (
{name}
);
}
};
export interface FileExplorerProps {
openFolder: string;
setOpenFile: (file: string) => void;
}
export default ({ openFolder, setOpenFile }: FileExplorerProps) => {
const [contextMenu, setContextMenu] = useState<{
mouseX: number;
mouseY: number;
filePath: string;
isFolder: boolean;
} | null>(null);
const { addToast } = useToast();
const [refresh, setRefresh] = useState(0);
const [renameOpen, setRenameOpen] = useState(false);
const [renameValue, setRenameValue] = useState("");
const [renameTarget, setRenameTarget] = useState(null);
const [newOpen, setNewOpen] = useState(false);
const [newValue, setNewValue] = useState("");
const [newTarget, setNewTarget] = useState(null);
const [newFolderOpen, setNewFolderOpen] = useState(false);
const [newFolderValue, setNewFolderValue] = useState("");
const [newFolderTarget, setNewFolderTarget] = useState(null);
const [deleteOpen, setDeleteOpen] = useState(false);
const [deleteTarget, setDeleteTarget] = useState(null);
const [deleteBasename, setDeleteBasename] = useState("");
const handleContextMenu = (event: React.MouseEvent) => {
if (event.target instanceof HTMLButtonElement) {
const path = event.target.getAttribute("data-path");
if (path) {
event.preventDefault();
setContextMenu(
contextMenu === null
? {
mouseX: event.clientX + 2,
mouseY: event.clientY - 6,
filePath: path,
isFolder:
event.target.getAttribute("data-is-folder") === "true",
}
: null
);
}
}
};
const handleClose = () => {
setContextMenu(null);
};
const handleRename = async () => {
if (!renameTarget) return;
const parent = await path.dirname(renameTarget);
const newPath = await path.resolve(parent, renameValue);
await fs.rename(renameTarget, newPath);
setRenameOpen(false);
setRenameTarget(null);
setRenameValue("");
setRefresh((r) => r + 1);
};
const handleDelete = async () => {
if (!deleteTarget) return;
await fs.remove(deleteTarget, { recursive: true });
setDeleteOpen(false);
setDeleteTarget(null);
setRefresh((r) => r + 1);
};
const handleNewFile = async () => {
if (!newTarget) return;
const newPath = await path.resolve(newTarget, newValue);
if (await fs.exists(newPath)) {
addToast.error("File already exists!");
return;
}
await fs.writeTextFile(newPath, "");
setNewOpen(false);
setNewTarget(null);
setNewValue("");
setRefresh((r) => r + 1);
};
const handleNewFolder = async () => {
if (!newFolderTarget) return;
const newPath = await path.resolve(newFolderTarget, newFolderValue);
if (await fs.exists(newPath)) {
addToast.error("Folder already exists!");
return;
}
await fs.mkdir(newPath);
setNewFolderOpen(false);
setNewFolderTarget(null);
setNewFolderValue("");
setRefresh((r) => r + 1);
};
return (
);
};
================================================
FILE: src/components/Tiles/FilteredConsole.tsx
================================================
import { useEffect, useImperativeHandle, useRef, useState } from "react";
import "./Console.css";
import { listen } from "@tauri-apps/api/event";
import Convert from "ansi-to-html";
import { Virtuoso } from "react-virtuoso";
import { escapeHtml } from "./Console";
import React from "react";
import { useParams } from "react-router";
const convert = new Convert();
export type FilteredConsoleHandle = {
clear: () => void;
};
type FilteredConsoleProps = {
filter: string;
channel: string;
doneSignal?: string;
alertDone?: () => void;
};
export default React.forwardRef(
({ filter, channel, doneSignal = "", alertDone }, ref) => {
const [consoleLines, setConsoleLines] = useState([]);
const listenerAdded = useRef(false);
const unlisten = useRef<() => void>(() => {});
useImperativeHandle(ref, () => ({
clear: () => {
setConsoleLines([]);
},
}));
const { path } = useParams<"path">();
useEffect(() => {
setConsoleLines([]);
}, [path]);
useEffect(() => {
if (!listenerAdded.current) {
(async () => {
const unlistenFn = await listen(channel, (event) => {
let line = event.payload as string;
if (doneSignal !== "" && line === doneSignal) return alertDone?.();
setConsoleLines((lines) => [...lines, line]);
});
unlisten.current = unlistenFn;
})();
listenerAdded.current = true;
}
return () => {
unlisten.current();
};
}, []);
return (
{
if (!filter || filter === "") return true;
return line.toLowerCase().includes(filter.toLowerCase());
})}
itemContent={(_, line) => (
)}
/>
);
}
);
================================================
FILE: src/components/Tiles/Tile.css
================================================
.tile {
width: 100%;
height: 100%;
padding: var(--padding-xs);
}
.tile-content {
height: 100%;
}
.tile-title {
color: gray;
}
================================================
FILE: src/components/Tiles/Tile.tsx
================================================
import { Typography } from "@mui/joy";
import "./Tile.css";
export interface TileProps {
title?: string;
children: React.ReactNode;
className?: string;
}
export default ({ title, children, className }: TileProps) => {
return (
{title != null && (
{title}
)}
{children}
);
};
================================================
FILE: src/main.tsx
================================================
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./styles.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
);
================================================
FILE: src/pages/About.tsx
================================================
import logo from "../assets/logo.png";
import { Link, List, ListItem, Typography } from "@mui/joy";
import "./Onboarding.css";
import { useEffect, useState } from "react";
import { getVersion } from "@tauri-apps/api/app";
import { openUrl } from "@tauri-apps/plugin-opener";
export default () => {
const [version, setVersion] = useState("");
useEffect(() => {
const fetchVersion = async () => {
const version = await getVersion();
setVersion(version);
};
fetchVersion();
}, []);
return (
{version && (
<>
CrossCode
Version {version}{" "}
(Early Access)
MIT License
GNU cpio 2.14 is included under GPLv3, with its copyright
holders.{" "}
{
e.preventDefault();
openUrl("https://ftp.gnu.org/gnu/cpio/cpio-2.14.tar.gz");
}}
>
Source
>
)}
);
};
================================================
FILE: src/pages/IDE.css
================================================
.ide-container {
height: 100%;
display: flex;
flex-direction: column;
}
.file-explorer-tile {
padding-right: 0.5rem;
}
.screenshot-tile {
padding: 0;
margin: var(--padding-md);
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
align-items: center;
box-sizing: border-box;
width: calc(100% - var(--padding-md) * 2 - var(--padding-xs));
}
.screenshot-tile > div {
flex-shrink: 0;
display: flex;
justify-content: center;
align-items: center;
gap: var(--padding-lg);
}
.screenshot-img-container {
flex: 1 1 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 0;
min-width: 0;
}
.screenshot-img-container > img {
transform: translateY(calc(-1 * var(--padding-xs)));
max-width: 100%;
max-height: calc(100% - var(--padding-md) * 4);
object-fit: contain;
display: block;
}
================================================
FILE: src/pages/IDE.tsx
================================================
import Splitter, { GutterTheme, SplitDirection } from "@devbookhq/splitter";
import Tile from "../components/Tiles/Tile";
import FileExplorer from "../components/Tiles/FileExplorer";
import { useCallback, useContext, useEffect, useState } from "react";
import Editor from "../components/Tiles/Editor";
import MenuBar from "../components/Menu/MenuBar";
import "./IDE.css";
import { StoreContext, useStore } from "../utilities/StoreContext";
import { useNavigate, useParams } from "react-router";
import { useIDE } from "../utilities/IDEContext";
import { registerFileSystemOverlay } from "@codingame/monaco-vscode-files-service-override";
import TauriFileSystemProvider from "../utilities/TauriFileSystemProvider";
import { invoke } from "@tauri-apps/api/core";
import {
Button,
Divider,
Modal,
ModalClose,
ModalDialog,
Typography,
} from "@mui/joy";
import { ErrorIcon, useToast, WarningIcon } from "react-toast-plus";
import SwiftMenu from "../components/SwiftMenu";
import { restartServer } from "../utilities/lsp-client";
import BottomBar from "../components/Tiles/BottomBar";
import { open as openFileDialog, save } from "@tauri-apps/plugin-dialog";
import { IStandaloneCodeEditor } from "@codingame/monaco-vscode-api/vscode/vs/editor/standalone/browser/standaloneCodeEditor";
import { DARWIN_SDK_VERSION } from "../utilities/constants";
import { writeFile } from "@tauri-apps/plugin-fs";
export interface IDEProps {}
type ProjectValidation =
| "Valid"
| "Invalid"
| "UnsupportedFormatVersion"
| "InvalidPackage"
| "InvalidToolchain";
let autoStartedLsp = "";
export default () => {
const { storeInitialized, store } = useContext(StoreContext);
const [openFile, setOpenFile] = useState(null);
const [openFiles, setOpenFiles] = useState([]);
const [saveFile, setSaveFile] = useState<(() => Promise) | null>(null);
const [undo, setUndo] = useState<(() => void) | null>(null);
const [redo, setRedo] = useState<(() => void) | null>(null);
const [theme] = useStore<"light" | "dark">("appearance/theme", "dark");
const { path } = useParams<"path">();
const {
openFolderDialog,
selectedToolchain,
hasLimitedRam,
initialized,
ready,
darwinSDKVersion,
screenshot,
setScreenshot,
} = useIDE();
const [sourcekitStartup, setSourcekitStartup] = useStore(
"sourcekit/startup",
null
);
const [hasIgnoredRam, setHasIgnoredRam] = useStore(
"has-ignored-ram",
false
);
const [hasIgnoredDarwinSDK, setHasIgnoredDarwinSDK] = useStore(
"has-ignored-darwin-sdk",
false
);
if (!path) {
throw new Error("Path parameter is required in IDE component");
}
const [callbacks, setCallbacks] = useState<
Record void) | (() => Promise)>
>({});
const navigate = useNavigate();
const [projectValidation, setProjectValidation] =
useState(null);
const [editor, setEditor] = useState(null);
const { addToast } = useToast();
useEffect(() => {
if (ready === false && initialized) {
console.log(
"IDE not ready, returning to welcome page",
ready,
initialized
);
navigate("/");
}
}, [ready, initialized, navigate]);
useEffect(() => {
(async () => {
if (!store || !storeInitialized || !path) return;
await store.set("last-opened-project", encodeURIComponent(path!));
})();
}, [path, store, storeInitialized]);
useEffect(() => {
if (
path === undefined ||
path === null ||
selectedToolchain === null ||
!initialized
)
return;
setProjectValidation(null);
(async () => {
if (path) {
const toolchainPath = selectedToolchain?.path ?? "";
const validation = await invoke("validate_project", {
projectPath: path,
toolchainPath: toolchainPath,
});
if (validation) {
setProjectValidation(validation);
}
}
})();
}, [path, selectedToolchain, initialized]);
useEffect(() => {
if (openFiles.length === 0) {
setOpenFile(null);
}
if (!openFiles.includes(openFile!)) {
setOpenFile(openFiles[0]);
}
}, [openFiles]);
useEffect(() => {
let dispose = () => {};
if (path) {
const provider = new TauriFileSystemProvider(false);
const overlayDisposable = registerFileSystemOverlay(1, provider);
dispose = () => {
overlayDisposable.dispose();
provider.dispose();
};
}
return () => {
dispose();
};
}, [path]);
useEffect(() => {
let autoEnable = async () => {
if (initialized && sourcekitStartup === null && hasLimitedRam === false) {
setSourcekitStartup(true);
}
};
autoEnable();
}, [hasLimitedRam, initialized, sourcekitStartup]);
useEffect(() => {
if (!sourcekitStartup || selectedToolchain == null) return;
requestAnimationFrame(async () => {
try {
if (autoStartedLsp === path) return;
autoStartedLsp = path;
await restartServer(path, selectedToolchain);
} catch (e) {
console.error("Failed to start SourceKit-LSP:", e);
addToast.error(
"Failed to start SourceKit-LSP (see devtools for details). Some language features may not be available."
);
}
});
}, [sourcekitStartup, path, selectedToolchain]);
const openNewFile = useCallback((file: string) => {
setOpenFile(file);
setOpenFiles((oF) => {
if (!oF.includes(file)) return [file, ...oF];
return oF;
});
}, []);
const selectFile = useCallback(async () => {
const file = await openFileDialog({ multiple: false, directory: false });
if (file) {
openNewFile(file);
}
}, [openNewFile]);
useEffect(() => {
setCallbacks({
save: saveFile ?? (async () => {}),
openFolderDialog,
newProject: () => navigate("/new"),
welcomePage: () => navigate("/"),
openFile: selectFile,
undo: undo ?? (() => {}),
redo: redo ?? (() => {}),
});
}, [saveFile, openFolderDialog, navigate, selectFile, undo, redo]);
return (
{screenshot && (
Screenshot
{
const blob = await (await fetch(screenshot)).blob();
const arrayBuffer = await blob.arrayBuffer();
const uint8Array = new Uint8Array(arrayBuffer);
const savePath = await save({
title: "Save Screenshot",
defaultPath: "screenshot.png",
filters: [
{ name: "PNG Image", extensions: ["png"] },
{ name: "All Files", extensions: ["*"] },
],
});
if (!savePath) return;
await writeFile(savePath, uint8Array);
addToast.success("Saved screenshot to " + savePath);
}}
>
Save
setScreenshot(null)}>
Close
)}
{initialized &&
selectedToolchain !== null &&
projectValidation !== null &&
projectValidation !== "Valid" && (
{
setProjectValidation(null);
}}
>
{getValidationMsg(projectValidation)} Some features may not
work as expected.
{projectValidation === "InvalidToolchain" && }
{projectValidation !== "InvalidToolchain" && (
<>
{
navigate("/new");
}}
>
Create New
Open Other Project
{
setProjectValidation(null);
}}
variant="outlined"
>
Ignore
>
)}
)}
{initialized &&
selectedToolchain !== null &&
sourcekitStartup === null &&
hasIgnoredRam === false &&
hasLimitedRam && (
{
setHasIgnoredRam(true);
}}
>
SourceKit-LSP is used to provide autocomplete, error
reporting, and other language features. However, it uses a
large amount of memory. Your device does not meet our
recommended memory requirements. You can choose to enable it
anyways, but it may cause crashes or instability.
You can change this at any time in Edit {">"} Preferences{" "}
{">"} SourceKit LSP {">"} Auto-Launch SourceKit.
You can also enable SourceKit temporarily with Build {">"}{" "}
Restart LSP.
{
setSourcekitStartup(false);
setHasIgnoredRam(true);
}}
>
Keep disabled
{
setSourcekitStartup(true);
setHasIgnoredRam(true);
}}
color="danger"
variant="outlined"
>
Enable Anyway
)}
{initialized &&
selectedToolchain !== null &&
hasIgnoredDarwinSDK === false &&
darwinSDKVersion !== DARWIN_SDK_VERSION && (
{
setHasIgnoredDarwinSDK(true);
}}
>
This version of CrossCode is designed to work with Darwin SDK{" "}
{DARWIN_SDK_VERSION}, but you have version {darwinSDKVersion}{" "}
installed. Things may still work, but you will miss out on
newer features (like liquid glass) and may run into issues.
{
navigate("/#install-sdk");
}}
>
Install Correct SDK
{
setHasIgnoredDarwinSDK(true);
}}
variant="outlined"
>
Ignore
)}
);
};
function getValidationMsg(validation: ProjectValidation): string {
switch (validation) {
case "Invalid":
return "This does not appear to be a valid CrossCode project.";
case "InvalidPackage":
return "SwiftPM was unable to parse your package. Please check your Package.swift file.";
case "UnsupportedFormatVersion":
return "This project uses an unsupported config format version. You may need to update CrossCode.";
case "InvalidToolchain":
return "Your Swift toolchain appears to be invalid.";
default:
return "";
}
}
================================================
FILE: src/pages/New.css
================================================
.new-templates-container {
display: flex;
gap: var(--padding-lg);
flex-wrap: wrap;
}
.new-template-card {
max-width: 500px;
flex-grow: 1;
flex-basis: 400px;
cursor: pointer;
}
.new-template-card:hover {
filter: brightness(0.8);
}
.new-template-form {
display: flex;
flex-direction: column;
gap: var(--padding-sm);
width: 100%;
}
.new-template-field {
display: flex;
align-items: center;
gap: var(--padding-lg);
width: 100%;
}
.new-template-field-input {
flex-grow: 1;
}
================================================
FILE: src/pages/New.tsx
================================================
import logo from "../assets/logo.png";
import {
AspectRatio,
Button,
Card,
CardContent,
CardOverflow,
Link,
Typography,
} from "@mui/joy";
import "./Onboarding.css";
import "./New.css";
import { templates } from "../utilities/templates";
import { useNavigate } from "react-router-dom";
export default () => {
const navigate = useNavigate();
return (
Create New Project
Select a template to get started
{templates.map((template) => (
{template.image && (
)}
{
e.preventDefault();
navigate(`/new/${template.id}`);
}}
>
{template.name}
{template.description}
))}
navigate("/")}
variant="outlined"
>
Back to Home
);
};
================================================
FILE: src/pages/NewTemplate.tsx
================================================
import logo from "../assets/logo.png";
import { Input, Typography } from "@mui/joy";
import "./Onboarding.css";
import "./New.css";
import { templates } from "../utilities/templates";
import { Navigate, useNavigate, useParams } from "react-router-dom";
import { useState } from "react";
import { Button } from "@mui/joy";
import { invoke } from "@tauri-apps/api/core";
import { useToast } from "react-toast-plus";
export default () => {
const navigate = useNavigate();
const params = useParams<"template">();
const templateId = params.template;
if (!templateId) {
return ;
}
const template = templates.find((t) => t.id === templateId);
const { addToast } = useToast();
if (!template) return ;
const [form, setForm] = useState(
Object.fromEntries(
Object.entries(template.fields).map(([key]) => [key, ""])
)
);
const handleChange = (key: string, value: string) => {
setForm((prev) => ({ ...prev, [key]: value }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
let path = await invoke("create_template", {
template: templateId,
name: form.projectName || template.name,
parameters: form,
});
if (path) {
navigate(`/ide/${encodeURIComponent(path)}`);
}
} catch (error) {
addToast.error("Failed to create project: " + error);
}
};
return (
{template.name}
{template.description}
);
};
================================================
FILE: src/pages/Onboarding.css
================================================
.onboarding {
padding: var(--padding-lg);
display: flex;
flex-direction: column;
gap: var(--padding-lg);
}
.onboarding h1,
.onboarding p {
margin: 0;
}
.onboarding-header {
display: flex;
align-items: center;
gap: var(--padding-lg);
}
.onboarding-buttons {
display: flex;
gap: var(--padding-lg);
}
.onboarding-logo {
width: 6rem;
height: 6rem;
}
.onboarding-cards {
display: flex;
flex-direction: column;
gap: var(--padding-lg);
}
.disabled-button {
cursor: not-allowed;
}
.onboarding-version {
display: flex;
align-items: center;
justify-content: center;
}
================================================
FILE: src/pages/Onboarding.tsx
================================================
import { useEffect, useRef, useState } from "react";
import { open } from "@tauri-apps/plugin-shell";
import "./Onboarding.css";
import { Button, Card, CardContent, Divider, Link, Typography } from "@mui/joy";
import { useIDE } from "../utilities/IDEContext";
import logo from "../assets/logo.png";
import { useLocation, useNavigate } from "react-router";
import { openUrl } from "@tauri-apps/plugin-opener";
import SwiftMenu from "../components/SwiftMenu";
import SDKMenu from "../components/SDKMenu";
import ErrorIcon from "@mui/icons-material/Error";
import WarningIcon from "@mui/icons-material/Warning";
import { getVersion } from "@tauri-apps/api/app";
import { invoke } from "@tauri-apps/api/core";
import { useToast } from "react-toast-plus";
import { relaunch } from "@tauri-apps/plugin-process";
import { SWIFT_VERSION_PREFIX } from "../utilities/constants";
export interface OnboardingProps {}
export default ({}: OnboardingProps) => {
const { ready, hasWSL, isWindows, openFolderDialog } = useIDE();
const [version, setVersion] = useState("");
const navigate = useNavigate();
const { addToast } = useToast();
useEffect(() => {
const fetchVersion = async () => {
const version = await getVersion();
setVersion(version);
};
fetchVersion();
}, []);
const location = useLocation();
const darwinSdkRef = useRef(null);
useEffect(() => {
console.log(location.hash);
if (location.hash === "#install-sdk" && darwinSdkRef.current) {
darwinSdkRef.current.scrollIntoView({
block: "start",
});
}
}, [location.hash]);
return (
Welcome to CrossCode!
{version && v{version} }
IDE for iOS Development on Windows and Linux
Early Access Version{" "}
This is an early access version of CrossCode. Expect bugs. Please
report any issues you find on{" "}
{
e.preventDefault();
open("https://github.com/nab138/CrossCode/issues");
}}
>
github
. Check the{" "}
{
e.preventDefault();
open("https://github.com/nab138/CrossCode/wiki/Troubleshooting");
}}
>
troubleshooting guide
{" "}
for known issues and workarounds.
{
if (ready) {
navigate("/new");
}
}}
>
Create New
Open Project
{ready ? (
"Use the cards below to manage your CrossCode setup"
) : (
<>
One or more issues need to be resolved before you can use CrossCode
>
)}
{isWindows && (
Windows Subsystem for Linux
Windows Subsystem for Linux (WSL) is required to use CrossCode on
Windows. Learn more about WSL on{" "}
{
e.preventDefault();
open("https://learn.microsoft.com/en-us/windows/wsl/");
}}
>
microsoft.com
. We recommended WSL 2 and Ubuntu 24.04. Other distributions may
work, but are not officially supported. CrossCode will use your
default WSL distribution.
{hasWSL === null ? (
"Checking for wsl..."
) : hasWSL ? (
"WSL is already installed on your system!"
) : (
<>
{" "}
WSL is not installed on your system. CrossCode can attempt
to automatically install WSL. If it fails, follow the
guide on{" "}
{
e.preventDefault();
openUrl(
"https://learn.microsoft.com/en-us/windows/wsl/install"
);
}}
>
microsoft.com
.
>
)}
{!hasWSL && (
{
try {
await invoke("install_wsl");
addToast.success(
"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."
);
} catch (error) {
addToast.error(
"Failed to launch WSL installation. Please try installing it manually."
);
}
}}
>
Install WSL
{
try {
await relaunch();
} catch (error) {
addToast.error(
"Failed to relaunch CrossCode. Please try manually."
);
}
}}
>
Relaunch CrossCode (post-installation)
)}
)}
Swift
You will need a Swift {SWIFT_VERSION_PREFIX} toolchain to use
CrossCode. It is recommended to install it using swiftly, but you
can also install it manually.
Darwin SDK
CrossCode requires a special swift SDK to build apps for iOS. It can
be generated from a copy of Xcode 26 or later. To install it,
download Xcode.xip using the link below, click the "Install SDK"
button, then select the downloaded file. Note that installing the
SDK will temporarily require a lot of disk space (~11GB) and may
take a while.
);
};
================================================
FILE: src/preferences/PreferenceItemRenderer.tsx
================================================
import {
Button,
Input,
Option,
Select,
Typography,
FormControl,
Checkbox,
} from "@mui/joy";
import { PreferenceItem } from "./types";
import { useStore } from "../utilities/StoreContext";
import { useEffect, useState } from "react";
export interface PreferenceItemRendererProps {
item: PreferenceItem;
storeExists: boolean;
pageName: string;
}
export default function PreferenceItemRenderer({
item,
storeExists,
pageName,
}: PreferenceItemRendererProps) {
const storeKey = `${pageName}/${item.id}`.toLowerCase();
const [value, setValue] = useStore(storeKey, item.defaultValue || "");
const [showOtherTextField, setShowOtherTextField] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
if (item.type === "select" && item.options) {
if (
item.options.some((o) => o.value === "other") &&
!item.options.some((o) => o.value === value)
) {
setShowOtherTextField(true);
} else {
setShowOtherTextField(false);
}
}
}, [value]);
if (item.type === "info" && typeof item.defaultValue === "function") {
const [info, setInfo] = useState("");
useEffect(() => {
const fetchInfo = async () => {
const result = await item.defaultValue();
setInfo(result);
};
fetchInfo();
}, [item.defaultValue]);
return (
{item.name}:
{info}
{item.description && (
{item.description}
)}
);
}
if (item.type === "custom" && item.customComponent) {
const CustomComponent = item.customComponent;
return ;
}
const handleChange = async (newValue: any) => {
if (
item.type === "select" &&
item.options?.some((o) => o.default !== undefined)
) {
if (
item.options?.find((o) => o.value === newValue)?.default !== undefined
) {
setNewValue(item.options.find((o) => o.value === newValue)?.default);
return;
}
}
setNewValue(newValue);
};
const setNewValue = async (newValue: any) => {
if (item.validation) {
const validationError = item.validation(newValue);
setError(validationError);
if (validationError) return;
}
setValue(newValue);
if (item.onChange) {
try {
await item.onChange(newValue);
} catch (err) {
console.error(`Error in onChange for ${item.name}:`, err);
setError(err instanceof Error ? err.message : "An error occurred");
}
}
};
return (
{item.type === "select" && showOtherTextField && (
<>
setNewValue(e.target.value)}
/>
>
)}
{error && (
{error}
)}
{item.description && !error && (
{item.description}
)}
);
}
================================================
FILE: src/preferences/Preferences.tsx
================================================
import { useParams } from "react-router";
import "./Prefs.css";
import { Divider, Typography, Link } from "@mui/joy";
import { Link as RouterLink } from "react-router-dom";
import { Fragment, useContext, useEffect } from "react";
import { StoreContext } from "../utilities/StoreContext";
import { preferenceRegistry } from "./pages";
import PreferenceItemRenderer from "./PreferenceItemRenderer";
export default function Preferences() {
const { page } = useParams<"page">();
const { store } = useContext(StoreContext);
const storeExists = store !== null && store !== undefined;
const categories = preferenceRegistry.getAllCategories();
const currentPage = page ? preferenceRegistry.getPage(page) : null;
// Call onLoad when page changes
useEffect(() => {
if (currentPage?.onLoad) {
currentPage.onLoad();
}
}, [currentPage]);
return (
{categories.map((category, categoryIndex) => (
{category.name}
{category.pages.map((p) => (
{p.name}
))}
{categoryIndex !== categories.length - 1 && (
)}
))}
{currentPage ? (
<>
{currentPage.name}
{currentPage.description && (
{currentPage.description}
)}
{currentPage.customComponent ? (
) : (
currentPage.items?.map((item) => (
))
)}
>
) : page ? (
Page Not Found
) : (
Preferences
Select a category from the sidebar to configure your preferences.
)}
);
}
================================================
FILE: src/preferences/Prefs.css
================================================
.prefs-container {
padding: var(--padding-xs);
box-sizing: border-box;
width: 100%;
height: 100%;
overflow: hidden;
}
.prefs-sidebar-container {
width: 150px;
float: left;
height: 100%;
box-sizing: border-box;
display: flex;
}
.prefs-sidebar {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
.prefs-sidebar-item:hover {
background-color: #00000030;
cursor: pointer;
}
.prefs-setting {
display: flex;
flex-direction: column;
gap: var(--padding-xs);
margin-bottom: var(--padding-md);
align-items: flex-start;
}
.prefs-setting-row {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: center;
gap: var(--padding-md);
width: 100%;
}
.prefs-setting-row .prefs-label {
flex-shrink: 0;
margin: 0;
}
.prefs-setting-row .prefs-input {
flex: 1;
max-width: 300px;
}
.prefs-page-header {
margin-bottom: var(--padding-md);
margin-top: var(--padding-md);
padding-bottom: var(--padding-md);
border-bottom: 1px solid var(--joy-palette-divider);
padding-left: var(--padding-md);
}
.prefs-content {
max-height: 100%;
display: flex;
flex-direction: column;
}
.prefs-page-content {
display: flex;
flex-direction: column;
gap: var(--padding-sm);
padding-left: var(--padding-md);
overflow: auto;
flex-grow: 1;
}
.prefs-welcome {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 50%;
text-align: center;
}
.prefs-input {
display: flex;
align-items: center;
}
================================================
FILE: src/preferences/helpers.ts
================================================
import { PreferencePage, PreferenceItem } from "./types";
import { preferenceRegistry } from "./registry";
export function createPreferencePage(
id: string,
name: string,
items: PreferenceItem[],
options?: {
description?: string;
category?: string;
onLoad?: () => void | Promise;
onSave?: () => void | Promise;
}
): PreferencePage {
const page: PreferencePage = {
id,
name,
items,
description: options?.description,
category: options?.category,
onLoad: options?.onLoad,
onSave: options?.onSave,
};
preferenceRegistry.registerPage(page);
return page;
}
export function createCustomPreferencePage(
id: string,
name: string,
component: React.ComponentType,
options?: {
description?: string;
category?: string;
onLoad?: () => void | Promise;
onSave?: () => void | Promise;
}
): PreferencePage {
const page: PreferencePage = {
id,
name,
customComponent: component,
description: options?.description,
category: options?.category,
onLoad: options?.onLoad,
onSave: options?.onSave,
};
preferenceRegistry.registerPage(page);
return page;
}
export const createItems = {
text: (
id: string,
name: string,
description?: string,
defaultValue?: string,
onChange?: (value: string) => void | Promise
): PreferenceItem => ({
id,
name,
description,
type: "text",
defaultValue,
onChange,
}),
select: (
id: string,
name: string,
options: Array<{ label: string; value: string, default?: string }>,
description?: string,
defaultValue?: string,
onChange?: (value: string) => void | Promise
): PreferenceItem => ({
id,
name,
description,
type: "select",
options,
defaultValue,
onChange,
}),
checkbox: (
id: string,
name: string,
description?: string,
defaultValue?: boolean,
onChange?: (value: boolean) => void | Promise
): PreferenceItem => ({
id,
name,
description,
type: "checkbox",
defaultValue,
onChange,
}),
button: (
id: string,
name: string,
description: string,
color: "primary" | "danger" | "neutral" | "success" | "warning" = "primary",
variant: "solid" | "outlined" | "soft" | "plain" = "soft",
onClick: () => void | Promise
): PreferenceItem => ({
id,
name,
description,
type: "button",
onChange: onClick,
color,
variant,
}),
number: (
id: string,
name: string,
description?: string,
defaultValue?: number,
onChange?: (value: number) => void | Promise
): PreferenceItem => ({
id,
name,
description,
type: "number",
defaultValue,
onChange,
}),
custom: (
id: string,
name: string,
customComponent: React.ComponentType
): PreferenceItem => ({
name,
id,
type: "custom",
customComponent,
}),
};
================================================
FILE: src/preferences/pages/appIds.tsx
================================================
import { createCustomPreferencePage } from "../helpers";
import { invoke } from "@tauri-apps/api/core";
import { useEffect, useRef, useState } from "react";
import { useStore } from "../../utilities/StoreContext";
import {
Accordion,
AccordionDetails,
AccordionGroup,
AccordionSummary,
Button,
Typography,
} from "@mui/joy";
type AppId = {
app_id_id: string;
identifier: string;
name: string;
features: Record;
expiration_date: Date | null;
};
type AppIdsResponse = {
app_ids: AppId[];
max_quantity: number;
available_quantity: number;
};
const AppIdsComponent = () => {
const [ids, setIds] = useState([]);
const [maxQuantity, setMaxQuantity] = useState(null);
const [availableQuantity, setAvailableQuantity] = useState(
null
);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [anisetteServer] = useStore(
"apple-id/anisette-server",
"ani.sidestore.io"
);
const [canDelete] = useStore("developer/delete-app-ids", false);
const loadingRef = useRef(false);
useEffect(() => {
let fetch = async () => {
if (loadingRef.current) return;
loadingRef.current = true;
let ids = await invoke("list_app_ids", {
anisetteServer,
});
setIds(ids.app_ids);
setMaxQuantity(ids.max_quantity);
setAvailableQuantity(ids.available_quantity);
setLoading(false);
loadingRef.current = false;
};
fetch().catch((e) => {
console.error("Failed to fetch certificates:", e);
setError(
"Failed to load certificates: " + e + "\nPlease try again later."
);
setLoading(false);
loadingRef.current = false;
});
}, []);
if (loading) {
return Loading App IDs...
;
}
if (error) {
return {error}
;
}
return (
{availableQuantity != null && maxQuantity != null && (
You have {availableQuantity}/{maxQuantity} App IDs available.
)}
{ids.map((id) => (
{canDelete && (
{
try {
await invoke("delete_app_id", {
anisetteServer,
appIdId: id.app_id_id,
});
setIds((prev) =>
prev.filter((c) => c.app_id_id !== id.app_id_id)
);
} catch (e) {
console.error("Failed to delete app ID:", e);
alert(
"Failed to revoke app ID: " +
e +
"\nPlease try again later."
);
}
}}
>
Delete
)}
{id.name}: {id.app_id_id}
{id.identifier}
{id.expiration_date && (
Expires {new Date(id.expiration_date).toLocaleDateString()}
)}
Features:
{Object.entries(id.features).map(([feature, value]) => (
{feature}: {JSON.stringify(value)}
))}
))}
{ids.length === 0 && No App IDs found. }
);
};
export const appIdsPage = createCustomPreferencePage(
"appids",
"App IDs",
AppIdsComponent,
{
description:
"Free developer accounts have a limit of 10 App IDs. You cannot delete App IDs, but they will expire after a week.",
category: "apple",
}
);
================================================
FILE: src/preferences/pages/appearance.tsx
================================================
import { useContext, useState } from "react";
import { createPreferencePage, createItems } from "../helpers";
import { setTheme } from "@tauri-apps/api/app";
import { StoreContext, useStore } from "../../utilities/StoreContext";
import {
FormControl,
Select,
useColorScheme,
Option,
Typography,
} from "@mui/joy";
const ThemeSelector = () => {
const { store } = useContext(StoreContext);
const storeExists = store !== null && store !== undefined;
const storeKey = `appearance/theme`.toLowerCase();
const [value, setValue] = useStore(storeKey, "dark");
const [error, setError] = useState(null);
const { setMode } = useColorScheme();
const handleChange = async (newValue: any) => {
setValue(newValue);
try {
await setTheme(newValue as "light" | "dark");
setMode(newValue as "light" | "dark");
} catch (err) {
console.error(`Error in onChange for theme:`, err);
setError(err instanceof Error ? err.message : "An error occurred");
}
};
return (
Theme:
handleChange(newValue)}
>
Dark
Light
{error && (
{error}
)}
);
};
export const appearancePage = createPreferencePage(
"appearance",
"Appearance",
[createItems.custom("theme", "Theme", ThemeSelector)],
{
description: "Customize the look and feel of the application",
category: "general",
}
);
================================================
FILE: src/preferences/pages/appleId.ts
================================================
import { createPreferencePage, createItems } from "../helpers";
import { invoke } from "@tauri-apps/api/core";
export const appleIdPage = createPreferencePage(
"apple-id",
"Apple ID",
[
createItems.select(
"anisette-server",
"Anisette Server",
[
{ label: "Sidestore (.io)", value: "ani.sidestore.io" },
{ label: "Sidestore (.app)", value: "ani.sidestore.app" },
{ label: "Sidestore (.zip)", value: "ani.sidestore.zip" },
{ label: "Sidestore (.xyz)", value: "ani.846969.xyz" },
{ label: "nythepegasus", value: "ani.npeg.us" },
{ label: "Custom", value: "other", default: "ani.yourserver.com" }
],
"The remote anisette server used. Change this if you are having issues logging in.",
"ani.sidestore.io"
),
{
id: "apple-id-email",
name: "Apple ID",
description: "The apple ID email you are currently logged in with.",
type: "info",
defaultValue: async () => {
const appleId = await invoke("get_apple_email");
return appleId || "Not logged in";
},
},
createItems.button(
"reset-anisette",
"Reset Anisette",
"Remove all anisette data (will require 2fa again)",
"danger",
"soft",
async () => {
await invoke("reset_anisette");
}
),
createItems.button(
"reset-credentials",
"Reset Saved Credentials",
"Remove saved Apple ID credentials and anisette data",
"danger",
"soft",
async () => {
await invoke("delete_stored_credentials");
await invoke("reset_anisette");
}
),
],
{
description: "Manage your Apple ID authentication",
category: "apple",
}
);
================================================
FILE: src/preferences/pages/certificates.tsx
================================================
import { createCustomPreferencePage } from "../helpers";
import { invoke } from "@tauri-apps/api/core";
import { useCallback, useEffect, useRef, useState } from "react";
import { useStore } from "../../utilities/StoreContext";
import { Button, Typography } from "@mui/joy";
type Certificate = {
name: string;
certificate_id: string;
serial_number: string;
machine_name: string;
};
const CertificatesComponent = () => {
let [certificates, setCertificates] = useState([]);
let [loading, setLoading] = useState(true);
let [error, setError] = useState(null);
const [anisetteServer] = useStore(
"apple-id/anisette-server",
"ani.sidestore.io"
);
const loadingRef = useRef(false);
let fetch = useCallback(async () => {
if (loadingRef.current) return;
loadingRef.current = true;
let certs = await invoke("get_certificates", {
anisetteServer,
});
setCertificates(certs);
setLoading(false);
loadingRef.current = false;
}, [anisetteServer]);
useEffect(() => {
fetch().catch((e) => {
console.error("Failed to fetch certificates:", e);
setError(
"Failed to load certificates: " + e + "\nPlease try again later."
);
setLoading(false);
loadingRef.current = false;
});
}, [fetch]);
if (loading) {
return Loading certificates...
;
}
if (error) {
return {error}
;
}
return (
{certificates.map((cert) => (
{
try {
await invoke("revoke_certificate", {
anisetteServer,
serialNumber: cert.serial_number,
});
setCertificates((prev) =>
prev.filter((c) => c.certificate_id !== cert.certificate_id)
);
} catch (e) {
console.error("Failed to revoke certificate:", e);
alert(
"Failed to revoke certificate: " +
e +
"\nPlease try again later."
);
}
}}
>
Revoke
{cert.name}: {cert.machine_name}
{cert.serial_number} ({cert.certificate_id})
))}
{certificates.length === 0 && No certificates found. }
);
};
export const certificatesPage = createCustomPreferencePage(
"certificates",
"Certificates",
CertificatesComponent,
{
description: "Manage your Apple ID certificates",
category: "apple",
}
);
================================================
FILE: src/preferences/pages/developer.ts
================================================
import { invoke } from "@tauri-apps/api/core";
import { createItems, createPreferencePage } from "../helpers";
import { load } from "@tauri-apps/plugin-store";
import { relaunch } from "@tauri-apps/plugin-process";
import { confirm } from "@tauri-apps/plugin-dialog";
export const developerPage = createPreferencePage(
"developer",
"Developer",
[
createItems.checkbox(
"delete-app-ids",
"Allow deleting app IDs",
"Reveal the delete button in the app ID page (note: they will still count towards your limit!)"
),
createItems.button(
"reset-all",
"Reset All Stored Data",
"Resets preferences, credentials, etc. This action is irreversible! The app will restart after.",
"danger",
"solid",
async () => {
if(!await confirm("Are you sure you want to reset all stored data? This action is irreversible!")) return;
await invoke("delete_stored_credentials");
await invoke("reset_anisette");
let storeInstance = await load("preferences.json");
await storeInstance.clear();
await relaunch();
}
),
],
{
description: "Internal developer settings",
category: "advanced",
}
);
================================================
FILE: src/preferences/pages/general.ts
================================================
import { createItems, createPreferencePage } from "../helpers";
import { getVersion } from "@tauri-apps/api/app";
export const generalPage = createPreferencePage(
"general",
"General",
[
{
id: "app-version",
name: "App Version",
description: "The current version of CrossCode.",
type: "info",
defaultValue: async () => {
return await getVersion();
},
},
createItems.select(
"startup",
"Startup Behavior",
[
{
label: "Open last project",
value: "open-last",
},
{
label: "Show welcome page",
value: "welcome",
},
],
"",
"open-last"
),
createItems.select(
"check-updates",
"Check for Updates",
[
{
label: "On Startup",
value: "auto",
},
{
label: "Manually",
value: "manual",
},
],
"",
"auto"
),
],
{
description: "General application settings",
category: "general",
}
);
================================================
FILE: src/preferences/pages/index.ts
================================================
import { preferenceRegistry } from "../registry";
import { PreferenceCategory } from "../types";
import { generalPage } from "./general";
import { appearancePage } from "./appearance";
import { appleIdPage } from "./appleId";
import { certificatesPage } from "./certificates";
import { appIdsPage } from "./appIds";
import { developerPage } from "./developer";
import { swiftPage } from "./swift";
import { sourceKitPage } from "./sourcekit";
const generalCategory: PreferenceCategory = {
id: "general",
name: "General",
pages: [generalPage, appearancePage],
};
const appleCategory: PreferenceCategory = {
id: "apple",
name: "Apple",
pages: [appleIdPage, certificatesPage, appIdsPage],
};
const swiftCategory: PreferenceCategory = {
id: "swift",
name: "Swift",
pages: [swiftPage, sourceKitPage],
};
const advancedCategory: PreferenceCategory = {
id: "advanced",
name: "Advanced",
pages: [developerPage],
};
preferenceRegistry.registerCategory(generalCategory);
preferenceRegistry.registerCategory(appleCategory);
preferenceRegistry.registerCategory(swiftCategory);
preferenceRegistry.registerCategory(advancedCategory);
// In theory, maps should preserve insertion order.
// However, I couldn't get the advanced category to appear after the swift category for some reason.
// So now its here.
const categoryOrder = ["general", "apple", "swift", "advanced"];
export { preferenceRegistry, categoryOrder };
================================================
FILE: src/preferences/pages/sourcekit.tsx
================================================
import { createPreferencePage, createItems } from "../helpers";
export const sourceKitPage = createPreferencePage(
"sourcekit",
"Language Features",
[
createItems.checkbox(
"startup",
"Auto-Launch SourceKit",
"Automatically start sourcekit-lsp when you open a project",
true
),
createItems.checkbox(
"format",
"Format on save",
"Automatically format your code when you save",
true
),
],
{
description: "Configure SourceKit-LSP and other language features",
category: "swift",
}
);
================================================
FILE: src/preferences/pages/swift.tsx
================================================
import { Divider } from "@mui/joy";
import SDKMenu from "../../components/SDKMenu";
import SwiftMenu from "../../components/SwiftMenu";
import { createCustomPreferencePage } from "../helpers";
export const swiftPage = createCustomPreferencePage(
"swift",
"Swift Setup",
() => (
),
{
description: "Manage your swift toolchains and Darwin SDK",
category: "swift",
}
);
================================================
FILE: src/preferences/registry.ts
================================================
import { categoryOrder } from "./pages";
import { PreferencePage, PreferenceCategory } from "./types";
class PreferenceRegistry {
private pages: Map = new Map();
private categories: Map = new Map();
registerPage(page: PreferencePage) {
this.pages.set(page.id, page);
if (page.category) {
if (!this.categories.has(page.category)) {
this.categories.set(page.category, {
id: page.category,
name: page.category,
pages: [],
});
}
const category = this.categories.get(page.category)!;
if (!category.pages.find((p) => p.id === page.id)) {
category.pages.push(page);
}
}
}
registerCategory(category: PreferenceCategory) {
this.categories.set(category.id, category);
category.pages.forEach((page) => {
page.category = category.id;
this.pages.set(page.id, page);
});
}
getPage(id: string): PreferencePage | undefined {
return this.pages.get(id);
}
getAllPages(): PreferencePage[] {
return Array.from(this.pages.values());
}
getAllCategories(): PreferenceCategory[] {
return Array.from(this.categories.values()).sort(
(a, b) => categoryOrder.indexOf(a.id) - categoryOrder.indexOf(b.id)
);
}
}
export const preferenceRegistry = new PreferenceRegistry();
================================================
FILE: src/preferences/types.ts
================================================
export interface PreferenceItem {
id: string;
name: string;
description?: string;
type:
| "text"
| "select"
| "checkbox"
| "button"
| "info"
| "number"
| "custom";
options?: Array<{ label: string; value: string, default?: string }>;
defaultValue?: any;
onChange?: (value: any) => void | Promise;
validation?: (value: any) => string | null;
customComponent?: React.ComponentType;
color?: "primary" | "danger" | "neutral" | "success" | "warning";
variant?: "solid" | "outlined" | "soft" | "plain";
}
export interface PreferencePage {
id: string;
name: string;
description?: string;
icon?: string;
category?: string;
items?: PreferenceItem[];
customComponent?: React.ComponentType;
onLoad?: () => void | Promise;
onSave?: () => void | Promise;
}
export interface PreferenceCategory {
id: string;
name: string;
pages: PreferencePage[];
}
================================================
FILE: src/styles.css
================================================
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
/* Define padding vars */
--padding-xs: 5px;
--padding-sm: 8px;
--padding-md: 10px;
--padding-lg: 15px;
--padding-xl: 20px;
}
html,
body,
#root,
.App {
height: 100%;
margin: 0;
padding: 0;
}
================================================
FILE: src/utilities/Command.tsx
================================================
import { Mutex } from "async-mutex";
import { invoke } from "@tauri-apps/api/core";
import { useState, createContext, useContext } from "react";
const commandRunnerMutex = new Mutex();
// Create a context for sharing command state
const CommandContext = createContext<{
isRunningCommand: boolean;
currentCommand: string | null;
setIsRunningCommand: React.Dispatch>;
setCurrentCommand: React.Dispatch>;
} | null>(null);
export function CommandProvider({ children }: { children: React.ReactNode }) {
const [isRunningCommand, setIsRunningCommand] = useState(false);
const [currentCommand, setCurrentCommand] = useState(null);
return (
{children}
);
}
// Modified hook that returns command functions with the context baked in
export function useCommandRunner() {
const context = useContext(CommandContext);
if (!context) {
throw new Error("useCommandRunner must be used within a CommandProvider");
}
const {
isRunningCommand,
currentCommand,
setIsRunningCommand,
setCurrentCommand,
} = context;
// Define the run command function inside the hook
const runCommand = (
command: string,
parameters?: Record
) => {
return new Promise(async (resolve) => {
const release = await commandRunnerMutex.acquire();
setIsRunningCommand(true);
setCurrentCommand(command);
try {
let res = await invoke(command, parameters);
resolve(res as any);
} finally {
release();
setIsRunningCommand(false);
setCurrentCommand(null);
}
});
};
// Define the cancel command function inside the hook
const cancelCommand = async () => {
try {
commandRunnerMutex.cancel();
commandRunnerMutex.release();
} finally {
setIsRunningCommand(true);
setCurrentCommand(null);
// try {
// await invoke("cancel_command");
// } finally {
setIsRunningCommand(false);
}
//}
};
return {
isRunningCommand,
currentCommand,
runCommand,
cancelCommand,
};
}
================================================
FILE: src/utilities/IDEContext.tsx
================================================
// create a context to store a few state values about the system that are checked at startup
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { invoke } from "@tauri-apps/api/core";
import { getCurrentWindow, Window } from "@tauri-apps/api/window";
import { emit, listen } from "@tauri-apps/api/event";
import * as dialog from "@tauri-apps/plugin-dialog";
import { useToast } from "react-toast-plus";
import { useNavigate } from "react-router-dom";
import {
Button,
Checkbox,
Input,
Modal,
ModalDialog,
Typography,
} from "@mui/joy";
import { useCommandRunner } from "./Command";
import { StoreContext, useStore } from "./StoreContext";
import { Operation, OperationState, OperationUpdate } from "./operations";
import OperationView from "../components/OperationView";
import { UpdateContext } from "./UpdateContext";
import { isCompatable } from "../components/SwiftMenu";
let isMainWindow = getCurrentWindow().label === "main";
export interface IDEContextType {
initialized: boolean;
ready: boolean | null;
isWindows: boolean;
hasWSL: boolean;
hasDarwinSDK: boolean;
darwinSDKVersion: string;
hasLimitedRam: boolean;
toolchains: ListToolchainResponse | null;
selectedToolchain: Toolchain | null;
devices: DeviceInfo[];
openFolderDialog: () => void;
consoleLines: string[];
setConsoleLines: React.Dispatch>;
scanToolchains: () => Promise;
checkSDK: () => Promise;
locateToolchain: () => Promise;
startOperation: (
operation: Operation,
params: { [key: string]: any }
) => Promise;
setSelectedToolchain: (
value: Toolchain | ((oldValue: Toolchain | null) => Toolchain | null) | null
) => void;
selectedDevice: DeviceInfo | null;
setSelectedDevice: React.Dispatch>;
mountDdi: (ask: boolean) => Promise;
setScreenshot: React.Dispatch>;
screenshot: string | null;
}
export type DeviceInfo = {
name: string;
id: number;
uuid: string;
};
export type Toolchain = {
version: string;
path: string;
isSwiftly: boolean;
};
type ListToolchainResponseWithSwiftly = {
swiftlyInstalled: true;
swiftlyVersion: string;
toolchains: Toolchain[];
};
type ListToolchainResponseWithoutSwiftly = {
swiftlyInstalled: false;
swiftlyVersion: null;
toolchains: Toolchain[];
};
export type ListToolchainResponse =
| ListToolchainResponseWithSwiftly
| ListToolchainResponseWithoutSwiftly;
export const IDEContext = createContext(null);
let hasCheckedForUpdates = false;
export const IDEProvider: React.FC<{
children: React.ReactNode;
}> = ({ children }) => {
const [isWindows, setIsWindows] = useState(false);
const [hasWSL, setHasWSL] = useState(false);
const [toolchains, setToolchains] = useState(
null
);
const [hasDarwinSDK, setHasDarwinSDK] = useState(false);
const [darwinSDKVersion, setDarwinSDKVersion] = useState("none");
const [initialized, setInitialized] = useState(false);
const [ready, setReady] = useState(null);
const [devices, setDevices] = useState([]);
const [consoleLines, setConsoleLines] = useState([]);
const [selectedToolchain, setSelectedToolchain] = useStore(
"swift/selected-toolchain",
null
);
const [hasLimitedRam, setHasLimitedRam] = useState(false);
const [selectedDevice, setSelectedDevice] = useState(null);
const [ddiOpen, setDdiOpen] = useState(false);
const [ddiProgress, setDdiProgress] = useState(0);
const [screenshot, setScreenshot] = useState(null);
const { checkForUpdates } = useContext(UpdateContext);
const { store, storeInitialized } = useContext(StoreContext);
const { addToast } = useToast();
const mountDdi = useCallback(
async (ask: boolean): Promise => {
if (!selectedDevice) {
addToast.error("No device selected");
return false;
}
try {
if (await invoke("is_ddi_mounted", { device: selectedDevice }))
return true;
if (ask) {
const result = await dialog.ask(
`This will download & mount the developer disk image on ${selectedDevice.name}. This is required for debugging apps. Do you want to continue?`,
{
title: "Mount Developer Disk Image",
}
);
if (!result) {
return false;
}
}
setDdiProgress(0);
setDdiOpen(true);
await invoke("mount_ddi", { device: selectedDevice });
setDdiOpen(false);
return true;
} catch (error) {
addToast.error("Failed to mount DDI: " + error);
console.error("Failed to mount DDI:", error);
setDdiOpen(false);
return false;
}
},
[selectedDevice]
);
const checkSDK = useCallback(async () => {
try {
let result = await invoke("has_darwin_sdk", {
toolchainPath: selectedToolchain?.path || "",
});
setHasDarwinSDK(result != "none");
setDarwinSDKVersion(result);
} catch (e) {
console.error("Failed to check for SDK:", e);
setHasDarwinSDK(false);
setDarwinSDKVersion("none");
}
}, [selectedToolchain]);
const scanToolchains = useCallback(() => {
return new Promise(async (resolve) => {
let response = await invoke(
"get_swiftly_toolchains"
);
if (response) {
setToolchains(response);
resolve();
}
});
}, []);
const locateToolchain = useCallback(async () => {
let path = await dialog.open({
directory: true,
multiple: false,
});
if (!path) {
addToast.error("No path selected");
return;
}
if (!(await invoke("validate_toolchain", { toolchainPath: path }))) {
if (isWindows) {
if (path?.startsWith("\\\\wsl.localhost\\")) {
path = path.replace("\\\\wsl.localhost\\", "\\\\wsl$\\");
}
path = await invoke("linux_path", {
path,
});
if (!(await invoke("validate_toolchain", { toolchainPath: path }))) {
addToast.error("Invalid toolchain path");
return;
}
} else {
addToast.error("Invalid toolchain path");
return;
}
}
const info = await invoke("get_toolchain_info", {
toolchainPath: path,
isSwiftly: false,
}).catch((error) => {
console.error("Error getting toolchain info:", error);
addToast.error("Failed to get toolchain info");
return null;
});
if (!info) {
addToast.error("Invalid toolchain path or version not found");
return;
}
if (info) {
setSelectedToolchain(info);
}
}, [isWindows]);
useEffect(() => {
if (!initialized) return setReady(null);
if (toolchains !== null && isWindows !== null && hasWSL !== null) {
setReady(
selectedToolchain !== null &&
isCompatable(selectedToolchain) &&
(isWindows ? hasWSL : true) &&
hasDarwinSDK
);
} else {
setReady(false);
}
}, [
selectedToolchain,
toolchains,
hasWSL,
isWindows,
hasDarwinSDK,
initialized,
]);
let startedInitializing = useRef(false);
useEffect(() => {
if (startedInitializing.current) return;
startedInitializing.current = true;
let initPromises: Promise[] = [];
initPromises.push(scanToolchains());
initPromises.push(
invoke("has_wsl").then((response) => {
setHasWSL(response as boolean);
})
);
initPromises.push(
invoke("is_windows").then((response) => {
setIsWindows(response as boolean);
})
);
initPromises.push(
invoke("has_darwin_sdk", {
toolchainPath: selectedToolchain?.path ?? "",
}).then((response) => {
setHasDarwinSDK(response != "none");
setDarwinSDKVersion(response);
})
);
initPromises.push(
invoke("has_limited_ram").then((response) => {
setHasLimitedRam(response as boolean);
})
);
Promise.all(initPromises)
.then(() => {
setInitialized(true);
})
.catch((error) => {
console.error("Error initializing IDE context: ", error);
alert("An error occurred while initializing the IDE context: " + error);
});
}, []);
useEffect(() => {
if (!initialized) return;
let changeWindows = async () => {
let splash = await Window.getByLabel("splashscreen");
let main = await Window.getByLabel("main");
if (splash && main) {
splash.close();
await main.show();
main.setFocus();
}
};
changeWindows();
}, [initialized]);
useEffect(() => {
if (!store || !storeInitialized || !initialized || !checkForUpdates) return;
let check = async () => {
if (hasCheckedForUpdates) return;
if (
(await store.has("general/check-updates")) &&
(await store.get("general/check-updates")) === "manual"
)
return;
hasCheckedForUpdates = true;
checkForUpdates();
};
check();
}, [initialized, checkForUpdates, store, storeInitialized]);
const listenerAdded = useRef(false);
const listener2Added = useRef(false);
const listener3Added = useRef(false);
const unlisten = useRef<() => void>(() => {});
const unlisten2fa = useRef<() => void>(() => {});
const unlistenAppleid = useRef<() => void>(() => {});
const [tfaOpen, setTfaOpen] = useState(false);
const tfaInput = useRef(null);
const [appleIdOpen, setAppleIdOpen] = useState(false);
const appleIdInput = useRef(null);
const applePassInput = useRef(null);
const saveCredentials = useRef(null);
useEffect(() => {
if (!listenerAdded.current) {
(async () => {
const unlistenFn = await listen("idevices", (event) => {
let devices = event.payload as DeviceInfo[];
setDevices(devices);
if (devices.length === 0) {
addToast.info("No devices found");
}
});
unlisten.current = unlistenFn;
})();
listenerAdded.current = true;
}
return () => {
unlisten.current();
};
}, []);
useEffect(() => {
if (!listener2Added.current) {
(async () => {
const unlistenFn = await listen("2fa-required", async () => {
if (isMainWindow) {
setTfaOpen(true);
} else {
addToast.info("Please complete 2FA in the main window.");
}
});
unlisten2fa.current = unlistenFn;
})();
listener2Added.current = true;
}
return () => {
unlisten2fa.current();
};
}, []);
useEffect(() => {
if (!listener3Added.current) {
(async () => {
const unlistenFn = await listen("apple-id-required", () => {
if (isMainWindow) {
setAppleIdOpen(true);
} else {
addToast.info("Please login to your Apple ID in the main window.");
}
});
unlistenAppleid.current = unlistenFn;
})();
listener3Added.current = true;
}
return () => {
unlistenAppleid.current();
};
}, []);
const ddiListenerAdded = useRef(false);
const ddiUnlisten = useRef<() => void>(() => {});
useEffect(() => {
if (!ddiListenerAdded.current) {
(async () => {
const unlistenFn = await listen("ddi-mount-progress", (event) => {
const progress = event.payload as number;
setDdiProgress(progress);
});
ddiUnlisten.current = unlistenFn;
})();
ddiListenerAdded.current = true;
}
return () => {
ddiUnlisten.current();
};
}, [setDdiProgress]);
const navigate = useNavigate();
const openFolderDialog = useCallback(async () => {
const path = await dialog.open({
directory: true,
multiple: false,
});
if (path) {
navigate("/ide/" + encodeURIComponent(path));
}
}, []);
const { cancelCommand } = useCommandRunner();
const [operationState, setOperationState] = useState(
null
);
const startOperation = useCallback(
async (
operation: Operation,
params: { [key: string]: any }
): Promise => {
setOperationState({
current: operation,
started: [],
failed: [],
completed: [],
});
return new Promise(async (resolve, reject) => {
const unlistenFn = await listen(
"operation_" + operation.id,
(event) => {
setOperationState((old) => {
if (old == null) return null;
if (event.payload.updateType === "started") {
return {
...old,
started: [...old.started, event.payload.stepId],
};
} else if (event.payload.updateType === "finished") {
return {
...old,
completed: [...old.completed, event.payload.stepId],
};
} else if (event.payload.updateType === "failed") {
return {
...old,
failed: [
...old.failed,
{
stepId: event.payload.stepId,
extraDetails: event.payload.extraDetails,
},
],
};
}
return old;
});
}
);
try {
await invoke(operation.id + "_operation", params);
unlistenFn();
resolve();
} catch (e) {
unlistenFn();
reject(e);
}
});
},
[setOperationState]
);
const contextValue = useMemo(
() => ({
isWindows,
hasWSL,
toolchains,
initialized,
devices,
openFolderDialog,
consoleLines,
setConsoleLines,
selectedToolchain,
scanToolchains,
locateToolchain,
setSelectedToolchain,
hasDarwinSDK,
checkSDK,
startOperation,
hasLimitedRam,
selectedDevice,
setSelectedDevice,
mountDdi,
ready,
darwinSDKVersion,
screenshot,
setScreenshot,
}),
[
isWindows,
hasWSL,
toolchains,
initialized,
devices,
openFolderDialog,
consoleLines,
setConsoleLines,
selectedToolchain,
scanToolchains,
locateToolchain,
setSelectedToolchain,
hasDarwinSDK,
checkSDK,
startOperation,
hasLimitedRam,
selectedDevice,
setSelectedDevice,
mountDdi,
ready,
darwinSDKVersion,
screenshot,
setScreenshot,
]
);
return (
{children}
{
if (!tfaInput.current?.value) {
addToast.error("Please enter a 2FA code");
return;
}
emit("2fa-recieved", tfaInput.current?.value || "");
setTfaOpen(false);
}}
>
A two-factor authentication code has been sent, please enter it
below.
{
setAppleIdOpen(false);
appleIdInput.current!.value = "";
applePassInput.current!.value = "";
emit("login-cancelled");
cancelCommand();
}}
>
Login with your apple account to continue
Your credentials will only be sent to apple. In general, never trust
a third-party app with your Apple ID. We recommend using a burner
account with CrossCode and other sideloaders. (CrossCode is not very
secure)
Mounting Developer Disk Image...
This may take a few minutes. Please do not disconnect your device or
close the app.
Progress: {ddiProgress.toFixed(2)}%
{operationState && (
{
setOperationState(null);
}}
/>
)}
);
};
export const useIDE = () => {
const context = React.useContext(IDEContext);
if (!context) {
throw new Error("useIDEContext must be used within an IDEContextProvider");
}
return context;
};
================================================
FILE: src/utilities/Shortcut.tsx
================================================
import { IKeyboardEvent, KeyCode } from "monaco-editor";
export type Accelerator = "ctrl" | "alt" | "shift" | "super";
export class Shortcut {
accelerators: Accelerator[];
key: string;
monacoKey: KeyCode;
ctrl = false;
alt = false;
shift = false;
super = false;
constructor(accelerator: Accelerator[], key: string) {
this.accelerators = accelerator;
for (const acc of accelerator) {
if (acc === "ctrl") this.ctrl = true;
if (acc === "alt") this.alt = true;
if (acc === "shift") this.shift = true;
if (acc === "super") this.super = true;
}
this.key = key;
this.monacoKey =
KeyCode[`Key${key.toUpperCase()}` as keyof typeof KeyCode] ||
KeyCode[key.toUpperCase() as keyof typeof KeyCode];
}
static fromString(shortcut: string): Shortcut {
if (!shortcut) throw new Error("Shortcut string is empty");
if (!shortcut.includes("+")) throw new Error("Shortcut string is invalid");
const [key, ...accelerators] = shortcut.toLowerCase().split("+").reverse();
if (accelerators.length === 0)
throw new Error("Shortcut string is invalid");
return new Shortcut(accelerators as Accelerator[], key.toLowerCase());
}
toString(): string {
return [...this.accelerators, this.key.toUpperCase()].join("+");
}
pressed(event: KeyboardEvent): boolean {
return (
this.ctrl === event.ctrlKey &&
this.alt === event.altKey &&
this.shift === event.shiftKey &&
this.super === event.metaKey &&
event.key.toLowerCase() === this.key
);
}
pressedMonaco(event: IKeyboardEvent): boolean {
return (
this.ctrl === event.ctrlKey &&
this.alt === event.altKey &&
this.shift === event.shiftKey &&
this.super === event.metaKey &&
event.keyCode === this.monacoKey
);
}
}
export function acceleratorPresssed(event: KeyboardEvent): boolean {
return event.ctrlKey || event.altKey || event.shiftKey || event.metaKey;
}
export function acceleratorPresssedMonaco(event: IKeyboardEvent): boolean {
return event.ctrlKey || event.altKey || event.shiftKey || event.metaKey;
}
================================================
FILE: src/utilities/StoreContext.tsx
================================================
import React, {
createContext,
useContext,
useState,
useEffect,
useCallback,
useMemo,
} from "react";
import { load, Store } from "@tauri-apps/plugin-store";
import { emit, listen } from "@tauri-apps/api/event";
import { setTheme } from "@tauri-apps/api/app";
import { useColorScheme } from "@mui/joy";
export const StoreContext = createContext<{
storeValues: { [key: string]: any };
setStoreValue: (key: string, value: any) => void;
store: Store | null;
storeInitialized: boolean;
}>({
storeValues: {},
setStoreValue: () => {},
store: null,
storeInitialized: false,
});
export const StoreProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [storeValues, setStoreValues] = useState<{ [key: string]: any }>({});
const [store, setStore] = useState(null);
const [storeInitialized, setStoreInitialized] = useState(false);
const { setMode } = useColorScheme();
useEffect(() => {
const initializeStore = async () => {
const storeInstance = await load("preferences.json");
setStore(storeInstance);
let theme = await storeInstance.get("appearance/theme");
if (theme === undefined) theme = "dark";
await setTheme(theme as "light" | "dark");
setMode(theme as "light" | "dark");
storeInstance.set("isCrossCodePrefs", true);
const keys = await storeInstance.keys();
const values: { [key: string]: any } = {};
for (const key of keys) {
values[key] = await storeInstance.get(key);
}
setStoreValues(values);
setStoreInitialized(true);
};
initializeStore();
}, []);
useEffect(() => {
// Listen for store changes from other windows
const unlisten = listen<{ key: string; value: any }>(
"store-value-changed",
(event) => {
const { key, value } = event.payload;
// Update local state without triggering another event
setStoreValues((prev) => ({ ...prev, [key]: value }));
}
);
return () => {
unlisten.then((unlistenFn) => unlistenFn());
};
}, []);
const setStoreValue = useCallback(
async (key: string, value: any) => {
if (!store) return;
setStoreValues((prevValues) => {
const newValues = { ...prevValues, [key]: value };
return newValues;
});
await store.set(key, value);
await store.save();
// Emit event to notify other windows
emit("store-value-changed", { key, value });
},
[store]
);
const contextValue = useMemo(
() => ({ storeValues, setStoreValue, store, storeInitialized }),
[storeValues, setStoreValue, store]
);
if (!store || !storeInitialized) {
return null;
}
return (
{children}
);
};
export const useStore = (
key: string,
initialValue: T
): [T, (value: T | ((oldValue: T) => T)) => void, boolean] => {
const { storeValues, setStoreValue, storeInitialized } =
useContext(StoreContext);
const [value, setValue] = useState(storeValues[key] ?? initialValue);
// Prevent infinite update loops
useEffect(() => {
if (storeValues[key] !== undefined && storeValues[key] !== value) {
setValue(storeValues[key]);
}
}, [storeValues, key]);
const setStoredValue = useCallback(
(newValue: T | ((oldValue: T) => T)) => {
const valueToStore =
typeof newValue === "function"
? (newValue as (oldValue: T) => T)(value)
: newValue;
setValue(valueToStore);
setStoreValue(key, valueToStore);
},
[key, setStoreValue, value]
);
return [value, setStoredValue, storeInitialized];
};
================================================
FILE: src/utilities/TauriFileSystemProvider.ts
================================================
import {
Disposable,
IDisposable,
} from "@codingame/monaco-vscode-api/vscode/vs/base/common/lifecycle";
import { URI } from "@codingame/monaco-vscode-api/vscode/vs/base/common/uri";
import {
FileChangeType,
FileSystemProviderCapabilities,
FileType,
IFileChange,
IFileDeleteOptions,
IFileOverwriteOptions,
IFileSystemProviderWithFileReadWriteCapability,
IFileWriteOptions,
IStat,
IWatchOptions,
} from "@codingame/monaco-vscode-files-service-override";
import {
Emitter,
Event,
} from "@codingame/monaco-vscode-api/vscode/vs/base/common/event";
import * as fs from "@tauri-apps/plugin-fs";
import { invoke } from "@tauri-apps/api/core";
import { platform } from "@tauri-apps/plugin-os";
export default class TauriFileSystemProvider
extends Disposable
implements IFileSystemProviderWithFileReadWriteCapability
{
private _onDidChangeFile: Emitter;
capabilities: FileSystemProviderCapabilities;
onDidChangeCapabilities: Event;
onDidChangeFile: Event;
onDidWatchError?: Event | undefined;
constructor(readonly: boolean) {
super();
this.onDidChangeCapabilities = Event.None;
this._onDidChangeFile = new Emitter();
this.onDidChangeFile = this._onDidChangeFile.event;
this.capabilities =
FileSystemProviderCapabilities.FileReadWrite |
FileSystemProviderCapabilities.PathCaseSensitive;
if (readonly) {
this.capabilities |= FileSystemProviderCapabilities.Readonly;
}
}
async readFile(resource: URI): Promise {
return await fs.readFile(await this.path(resource));
}
async writeFile(resource: URI, content: Uint8Array, opts: IFileWriteOptions) {
await fs.writeFile(await this.path(resource), content, {
create: opts.create,
createNew: !opts.overwrite,
});
this._onDidChangeFile.fire([
{
type: opts.create ? FileChangeType.ADDED : FileChangeType.UPDATED,
resource,
},
]);
}
async stat(resource: URI): Promise {
let stat = await fs.stat(await this.path(resource));
let type = stat.isFile ? FileType.File : FileType.Directory;
if (stat.isSymlink) {
type = FileType.SymbolicLink;
}
let ctime = stat.birthtime?.getMilliseconds() || 0;
let mtime = stat.mtime?.getMilliseconds() || 0;
return {
type,
ctime,
mtime,
size: stat.size,
};
}
watch(resource: URI, opts: IWatchOptions): IDisposable {
let disposed = false;
(async () => {
fs.watchImmediate(
await this.path(resource),
() => {
if (!disposed) {
// TODO: Exclude files based on opts.excludes and look into how recursive watch actually works
this._onDidChangeFile.fire([
{
type: FileChangeType.UPDATED,
resource,
},
]);
}
},
{
recursive: opts.recursive,
}
).then((unwatch) => {
if (disposed) {
unwatch();
}
(disposable as any)._unwatch = unwatch;
});
})();
const disposable: IDisposable = {
dispose: () => {
disposed = true;
if ((disposable as any)._unwatch) {
(disposable as any)._unwatch();
}
},
};
return disposable;
}
// TODO: Implement remaining methods
// @ts-ignore
mkdir(resource: URI): Promise {
throw new Error("Mkdir not implemented.");
}
// @ts-ignore
readdir(resource: URI): Promise<[string, FileType][]> {
throw new Error("Readdir not implemented.");
}
// @ts-ignore
delete(resource: URI, opts: IFileDeleteOptions): Promise {
throw new Error("Delete not implemented.");
}
// @ts-ignore
rename(from: URI, to: URI, opts: IFileOverwriteOptions): Promise {
throw new Error("Rename not implemented.");
}
private async path(resource: URI): Promise {
if (platform() === "windows") {
return await invoke("windows_path", { path: resource.path });
}
return resource.fsPath;
}
}
================================================
FILE: src/utilities/UpdateContext.tsx
================================================
import { createContext, useCallback, useContext } from "react";
import { StoreContext } from "./StoreContext";
import { check } from "@tauri-apps/plugin-updater";
import { getVersion } from "@tauri-apps/api/app";
import { relaunch } from "@tauri-apps/plugin-process";
import * as dialog from "@tauri-apps/plugin-dialog";
import { useToast } from "react-toast-plus";
export interface UpdateContextType {
checkForUpdates: () => Promise;
}
export const UpdateContext = createContext({
checkForUpdates: async () => {},
});
export const UpdateProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const { store, storeInitialized } = useContext(StoreContext);
const { addToast } = useToast();
const checkForUpdates = useCallback(async () => {
const update = await check();
if (!update) return;
let shouldUpdate = await dialog.ask(
"A new update (" +
(await getVersion()) +
" -> " +
update.version +
") is available. Would you like to install it?",
{
title: "Update Available",
}
);
if (!shouldUpdate) return;
let downloadPromise = update.download();
addToast.promise(downloadPromise, {
pending: "Downloading update...",
success: "Update downloaded",
error: "Failed to download update",
});
await downloadPromise;
let installPromise = update.install();
addToast.promise(installPromise, {
pending: "Installing update...",
success: "Update installed",
error: "Failed to install update",
});
await installPromise;
const shouldRelaunch = await dialog.ask(
"The update has been installed. Would you like to relaunch the application?",
{
title: "Relaunch Required",
}
);
if (shouldRelaunch) {
await relaunch();
}
}, [store, storeInitialized, addToast]);
return (
{children}
);
};
================================================
FILE: src/utilities/constants.ts
================================================
export const SWIFT_VERSION_PREFIX = "6.2";
export const DARWIN_SDK_VERSION = "26.0";
================================================
FILE: src/utilities/lsp-client.ts
================================================
// https://github.com/CodinGame/monaco-vscode-api/wiki/Getting-started-guide
// lsp-client.ts
import {
WebSocketMessageReader,
WebSocketMessageWriter,
toSocket,
} from "vscode-ws-jsonrpc";
import {
CloseAction,
ErrorAction,
MessageTransports,
} from "vscode-languageclient/browser.js";
import { MonacoLanguageClient } from "monaco-languageclient";
import { Toolchain } from "./IDEContext";
import { invoke } from "@tauri-apps/api/core";
import { Uri } from "monaco-editor";
export const initWebSocketAndStartClient = async (
url: string,
folder: string
): Promise => {
let workspaceFolder = await invoke("linux_path", { path: folder });
const webSocket = new WebSocket(url);
webSocket.onopen = () => {
const socket = toSocket(webSocket);
const reader = new WebSocketMessageReader(socket);
const writer = new WebSocketMessageWriter(socket);
const languageClient = createLanguageClient(
{
reader,
writer,
},
workspaceFolder
);
languageClient.start();
reader.onClose(() => languageClient.stop());
};
return webSocket;
};
const createLanguageClient = (
messageTransports: MessageTransports,
folder: string
): MonacoLanguageClient => {
return new MonacoLanguageClient({
name: "Swift Language Client",
clientOptions: {
documentSelector: ["swift", "c", "cpp", "h", "hpp", "m", "mm"],
workspaceFolder: { uri: Uri.file(folder), name: folder, index: 0 },
errorHandler: {
error: () => ({ action: ErrorAction.Continue }),
closed: () => ({ action: CloseAction.DoNotRestart }),
},
initializationOptions: {
swiftPM: {
swiftSDK: "arm64-apple-ios",
},
},
middleware: {
workspace: {
configuration: () => {
return [
{
swiftPM: {
swiftSDK: "arm64-apple-ios",
},
},
];
},
},
},
},
messageTransports,
});
};
export const restartServer = async (
path: string,
selectedToolchain: Toolchain
) => {
// this has been replaced with the middleware above
// await invoke("ensure_lsp_config", {
// projectPath: path || "",
// });
try {
await invoke("stop_sourcekit_server");
} catch (e) {
void e;
}
let port = await invoke("start_sourcekit_server", {
toolchainPath: selectedToolchain?.path ?? "",
folder: path || "",
});
await initWebSocketAndStartClient(`ws://localhost:${port}`, path || "");
};
================================================
FILE: src/utilities/operations.ts
================================================
export type Operation = {
id: string;
title: string;
steps: OperationStep[];
};
export type OperationStep = {
id: string;
title: string;
};
export type OperationState = {
current: Operation;
completed: string[];
started: string[];
failed: {
stepId: string;
extraDetails: string;
}[];
};
type OperationInfoUpdate = {
updateType: "started" | "finished";
stepId: string;
};
type OperationFailedUpdate = {
updateType: "failed";
stepId: string;
extraDetails: string;
};
export type OperationUpdate = OperationInfoUpdate | OperationFailedUpdate;
export const installSdkOperation: Operation = {
id: "install_sdk",
title: "Installing Darwin SDK",
steps: [
{
id: "create_stage",
title: "Create Stage",
},
{
id: "install_toolset",
title: "Download & Install toolset",
},
{
id: "extract_xip",
title: "Extract Xcode.xip",
},
{
id: "copy_files",
title: "Move Files",
},
{
id: "write_metadata",
title: "Write Metadata",
},
{
id: "install_sdk",
title: "Install SDK",
},
{
id: "cleanup",
title: "Clean Up",
},
],
};
================================================
FILE: src/utilities/templates.ts
================================================
import swiftui from "../assets/swiftui.png";
import uikit from "../assets/uikit.png";
export interface TemplateField {
type: string;
label: string;
default: string;
}
export interface Template {
name: string;
description: string;
id: string;
image?: string;
version: string;
fields: {
[key: string]: TemplateField;
};
}
const defaultFields = {
projectName: {
type: "text",
label: "Project Name",
default: "MyProject",
},
bundleId: {
type: "text",
label: "Bundle Identifier",
default: "com.example.myproject",
},
};
export const templates: Template[] = [
{
name: "Basic SwiftUI Application",
description: "A barebones SwiftUI template to get you started quickly",
image: swiftui,
id: "swiftui",
version: "1.0.0",
fields: {
...defaultFields,
},
},
{
name: "Basic UIKit Application",
description: "A barebones UIKit template to get you started quickly",
image: uikit,
id: "uikit",
version: "1.0.0",
fields: {
...defaultFields,
},
},
];
================================================
FILE: src/vite-env.d.ts
================================================
///
================================================
FILE: src-tauri/.gitignore
================================================
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas
================================================
FILE: src-tauri/Cargo.toml
================================================
[package]
name = "crosscode"
version = "0.0.5"
description = "Cross platform iOS IDE"
authors = ["nab138"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "2.4.0", features = [] }
[dependencies]
tauri = { version = "2.8.3", features = ["devtools"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri-plugin-shell = "2.3.0"
tauri-plugin-fs = { version = "2.4.2", features= ["watch"] }
tauri-plugin-dialog = "2.4.0"
tauri-plugin-store = "2.4.0"
tauri-plugin-opener = "2.5.0"
tauri-plugin-os = "2.3.1"
tauri-plugin-process = "2.3.0"
idevice = { 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}
futures = "0.3.31"
keyring = "2"
once_cell = "1.21.3"
zip = { version = "4.5", default-features = false, features = ["deflate"] }
isideload = { version = "0.1.17", features = ["vendored-openssl"] }
walkdir = "2.5.0"
dircpy = "0.3.19"
tar = "0.4.44"
reqwest = "0.12.23"
flate2 = "1.1.2"
regex = "1"
toml = "0.9.5"
tokio = { version = "1.47.1", features = ["process"] }
futures-util = "0.3.31"
sysinfo = "0.37.0"
tokio-util = "0.7.16"
image = "0.25.6"
unxip-rs = "0.1.1"
tokio-tungstenite = "0.28.0"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }
[target.'cfg(unix)'.dependencies]
sdkmover = { path = "../sdkmover" }
[features]
# This feature is used for production builds or when a dev server is not specified, DO NOT REMOVE!!
custom-protocol = ["tauri/custom-protocol"]
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-cli = "2.4.0"
tauri-plugin-updater = "2.9.0"
================================================
FILE: src-tauri/build.rs
================================================
fn main() {
tauri_build::build()
}
================================================
FILE: src-tauri/capabilities/desktop.json
================================================
{
"identifier": "desktop-capability",
"platforms": [
"macOS",
"windows",
"linux"
],
"windows": [
"main"
],
"permissions": [
"cli:default",
"updater:default"
]
}
================================================
FILE: src-tauri/capabilities/migrated.json
================================================
{
"identifier": "migrated",
"description": "permissions that were migrated from v1",
"local": true,
"windows": ["main", "prefs", "splashscreen", "about"],
"permissions": [
"core:default",
"core:window:allow-show",
"core:window:allow-center",
"core:window:allow-create",
"core:window:allow-set-focus",
"core:window:allow-set-title",
"core:app:allow-set-app-theme",
"core:window:allow-close",
"core:webview:allow-create-webview-window",
"fs:allow-read-file",
"fs:allow-write-file",
"fs:allow-write-text-file",
"fs:allow-read-dir",
"fs:allow-copy-file",
"fs:allow-mkdir",
"fs:allow-remove",
"fs:allow-remove",
"fs:allow-rename",
"fs:allow-exists",
"fs:allow-stat",
"fs:allow-watch",
{
"identifier": "fs:scope",
"allow": ["**", ".*", "**/.*"],
"requireLiteralLeadingDot": false
},
"shell:allow-open",
"dialog:allow-open",
"dialog:allow-save",
"shell:default",
"fs:default",
"dialog:default",
"store:default",
"opener:default",
{
"identifier": "opener:allow-reveal-item-in-dir",
"allow": [
{
"path": "**"
},
{
"path": ".*"
},
{
"path": "**/.*"
}
]
},
"os:default",
"process:allow-restart"
]
}
================================================
FILE: src-tauri/src/builder/config.rs
================================================
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::builder::swift::SwiftBin;
pub const FORMAT_VERSION: u32 = 1;
pub struct BuildSettings {
pub debug: bool,
}
// TODO: Min ios version, etc.
pub struct ProjectConfig {
pub product: String,
pub version_num: String,
pub version_string: String,
pub bundle_id: String,
pub project_path: PathBuf,
}
#[derive(Deserialize, Serialize)]
pub struct TomlConfig {
pub format_version: u32,
pub project: ProjectTomlConfig,
}
#[derive(Deserialize, Serialize)]
pub struct ProjectTomlConfig {
pub version_num: String,
pub version_string: String,
pub bundle_id: String,
}
// TODO: Check platforms
#[derive(Deserialize)]
struct SwiftPackageDump {
name: String,
targets: Vec,
}
// TODO: Resources
#[derive(Deserialize)]
struct SwiftPackageTarget {
name: String,
}
#[derive(Deserialize, Serialize)]
pub enum ProjectValidation {
Valid,
Invalid,
UnsupportedFormatVersion,
InvalidPackage,
InvalidToolchain,
}
impl ProjectConfig {
pub fn load(project_path: PathBuf, toolchain_path: &str) -> Result {
let toml_config = TomlConfig::load_or_default(project_path.clone())?;
let swift = SwiftBin::new(toolchain_path)?;
let raw_package = swift
.command()
.arg("package")
.arg("dump-package")
.current_dir(&project_path)
.output()
.map_err(|e| format!("Failed to execute swift command: {}", e))?;
if !raw_package.status.success() {
return Err(format!(
"Failed to dump package: {}",
String::from_utf8_lossy(&raw_package.stderr)
));
}
let package: SwiftPackageDump = serde_json::from_slice(&raw_package.stdout)
.map_err(|e| format!("Failed to parse package dump: {}", e))?;
Ok(ProjectConfig {
product: package.name,
version_num: toml_config.project.version_num,
version_string: toml_config.project.version_string,
bundle_id: toml_config.project.bundle_id,
project_path,
})
}
pub fn validate(project_path: PathBuf, toolchain_path: &str) -> ProjectValidation {
if !project_path.exists() {
return ProjectValidation::Invalid;
}
if !project_path.join("Package.swift").exists() {
return ProjectValidation::Invalid;
}
if !project_path.join("crosscode.toml").exists() {
return ProjectValidation::Invalid;
}
let config_res = TomlConfig::load(project_path.clone());
// make sure the error isn't unsupported format version
if let Err(e) = config_res {
if e.contains("Unsupported format version") {
return ProjectValidation::UnsupportedFormatVersion;
}
}
let swift = SwiftBin::new(toolchain_path);
if let Err(_) = swift {
return ProjectValidation::InvalidToolchain;
}
let swift = swift.unwrap();
let raw_package = swift
.command()
.arg("package")
.arg("dump-package")
.current_dir(&project_path)
.output();
if let Err(_) = raw_package {
return ProjectValidation::InvalidToolchain;
}
let raw_package = raw_package.unwrap();
if !raw_package.status.success() {
return ProjectValidation::InvalidPackage;
}
let package = serde_json::from_slice::(&raw_package.stdout);
if let Err(_) = package {
return ProjectValidation::InvalidPackage;
}
ProjectValidation::Valid
}
}
impl TomlConfig {
pub fn default(bundle_id: &str) -> Self {
TomlConfig {
format_version: FORMAT_VERSION,
project: ProjectTomlConfig {
version_num: "1".to_string(),
version_string: "1.0.0".to_string(),
bundle_id: bundle_id.to_string(),
},
}
}
pub fn load_or_default(project_path: PathBuf) -> Result {
if project_path.exists() {
Self::load(project_path)
} else {
let config = Self::default("com.example.myapp");
config.save(project_path)?;
Ok(config)
}
}
fn load(project_path: PathBuf) -> Result {
let content = std::fs::read_to_string(project_path.join("crosscode.toml"))
.map_err(|e| e.to_string())?;
let config: TomlConfig = toml::from_str(&content).map_err(|e| e.to_string())?;
if config.format_version != FORMAT_VERSION {
return Err(format!(
"Unsupported format version: {}, expected: {}",
config.format_version, FORMAT_VERSION
));
}
Ok(config)
}
pub fn save(&self, project_path: PathBuf) -> Result<(), String> {
let content = toml::to_string(self).map_err(|e| e.to_string())?;
std::fs::write(project_path.join("crosscode.toml"), content).map_err(|e| e.to_string())?;
Ok(())
}
}
================================================
FILE: src-tauri/src/builder/crossplatform.rs
================================================
#[cfg(target_os = "windows")]
use crate::windows::{has_wsl, windows_to_wsl_path, wsl_to_windows_path};
#[cfg(not(target_os = "windows"))]
use std::fs;
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
#[cfg(not(target_os = "windows"))]
use std::path::Path;
use std::path::PathBuf;
#[cfg(target_os = "windows")]
use std::process::{Command, Stdio};
#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x08000000;
pub fn symlink(target: &str, link: &str) -> std::io::Result<()> {
#[cfg(not(target_os = "windows"))]
{
return std::os::unix::fs::symlink(target, link);
}
#[cfg(target_os = "windows")]
{
if !has_wsl() {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"WSL is not available",
));
}
let path = windows_to_wsl_path(link).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Path conversion error: {}", e),
)
})?;
let output = Command::new("wsl")
.arg("ln")
.arg("-s")
.arg(target)
.arg(path)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.creation_flags(CREATE_NO_WINDOW)
.output()
.expect("failed to execute process");
if !output.status.success() {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"failed to create symlink: {}",
String::from_utf8_lossy(&output.stderr)
),
));
}
return Ok(());
}
}
pub fn linux_env(key: &str) -> Result {
#[cfg(not(target_os = "windows"))]
{
return std::env::var(key).map_err(|e| e.to_string());
}
#[cfg(target_os = "windows")]
{
if !has_wsl() {
return Err("WSL is not available".to_string());
}
let output = Command::new("wsl")
.args(["bash", "-l", "-c"])
.arg(format!("printenv {}", key))
.creation_flags(CREATE_NO_WINDOW)
.output()
.expect("failed to execute process");
if output.status.success() {
let res = String::from_utf8_lossy(&output.stdout).trim().to_string();
if res.is_empty() {
Err("Environment variable not found".to_string())
} else {
Ok(res)
}
} else {
Err(format!(
"Failed to get environment variable '{}': {}",
key,
String::from_utf8_lossy(&output.stderr)
))
}
}
}
#[tauri::command]
pub fn windows_path(path: &str) -> Result {
#[cfg(not(target_os = "windows"))]
{
return Ok(path.to_string());
}
#[cfg(target_os = "windows")]
{
if !has_wsl() {
return Ok(path.to_string());
}
return wsl_to_windows_path(path);
}
}
#[tauri::command]
pub fn linux_path(path: &str) -> Result {
#[cfg(not(target_os = "windows"))]
{
return Ok(path.to_string());
}
#[cfg(target_os = "windows")]
{
if !has_wsl() {
return Ok(path.to_string());
}
return windows_to_wsl_path(path);
}
}
#[cfg(target_os = "windows")]
pub fn is_linux_dir(path: &str) -> Result {
// #[cfg(not(target_os = "windows"))]
// {
// let p = Path::new(path);
// return Ok(p.is_dir());
// }
// #[cfg(target_os = "windows")]
// {
if !has_wsl() {
return Err("WSL is not available".to_string());
}
let output = Command::new("wsl")
.arg("test")
.arg("-d")
.arg(&path)
.creation_flags(CREATE_NO_WINDOW)
.output()
.expect("failed to execute process");
if output.status.success() {
Ok(true)
} else {
Ok(false)
}
//}
}
pub fn linux_temp_dir() -> Result {
#[cfg(target_os = "windows")]
{
if !has_wsl() {
return Err("WSL is not available".to_string());
}
if let Ok(tmpdir) = linux_env("TMPDIR") {
if is_linux_dir(&tmpdir)? {
let win_path = wsl_to_windows_path(&tmpdir)?;
return Ok(PathBuf::from(win_path));
}
}
if is_linux_dir("/var/tmp")? {
let win_path = wsl_to_windows_path("/var/tmp")?;
return Ok(PathBuf::from(win_path));
}
let win_path = wsl_to_windows_path("/tmp")?;
return Ok(PathBuf::from(win_path));
}
#[cfg(not(target_os = "windows"))]
{
if let Ok(tmpdir) = std::env::var("TMPDIR") {
let path = Path::new(&tmpdir);
if path.is_dir() {
return Ok(path.to_path_buf());
}
}
if Path::new("/var/tmp").is_dir() {
return Ok(PathBuf::from("/var/tmp"));
}
Ok(PathBuf::from("/tmp"))
}
}
pub fn remove_dir_all(path: &PathBuf) -> Result<(), String> {
#[cfg(not(target_os = "windows"))]
{
return fs::remove_dir_all(path).map_err(|e| e.to_string());
}
#[cfg(target_os = "windows")]
{
if !has_wsl() {
return Err("WSL is not available".to_string());
}
let path = windows_to_wsl_path(&path.to_string_lossy().to_string())?;
let output = Command::new("wsl")
.arg("rm")
.arg("-rf")
.arg(path)
.creation_flags(CREATE_NO_WINDOW)
.output()
.expect("failed to execute process");
if output.status.success() {
Ok(())
} else {
Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
}
}
}
================================================
FILE: src-tauri/src/builder/icon.rs
================================================
use std::{fs, path::Path};
use image::{ImageFormat, ImageReader};
const ICON_FILES: &[(&str, u32)] = &[
("AppIcon29x29.png", 29),
("AppIcon29x29@2x.png", 58),
("AppIcon29x29@3x.png", 87),
("AppIcon40x40.png", 40),
("AppIcon40x40@2x.png", 80),
("AppIcon40x40@3x.png", 120),
("AppIcon50x50.png", 50),
("AppIcon50x50@2x.png", 100),
("AppIcon57x57.png", 57),
("AppIcon57x57@2x.png", 114),
("AppIcon57x57@3x.png", 171),
("AppIcon60x60.png", 60),
("AppIcon60x60@2x.png", 120),
("AppIcon60x60@3x.png", 180),
("AppIcon72x72.png", 72),
("AppIcon72x72@2x.png", 144),
("AppIcon76x76.png", 76),
("AppIcon76x76@2x.png", 152),
];
#[tauri::command]
pub async fn import_icon(project_path: String, icon_path: String) -> Result<(), String> {
let img = ImageReader::open(icon_path)
.map_err(|e| format!("Failed to open icon image: {}", e))?
.decode()
.map_err(|e| format!("Failed to decode icon image: {}", e))?;
let icon_dir = Path::new(&project_path).join("Resources");
fs::create_dir_all(&icon_dir).map_err(|e| format!("Failed to create icon directory: {}", e))?;
for (file_name, size) in ICON_FILES {
let resized = img.resize(*size, *size, image::imageops::FilterType::CatmullRom);
let output_path = icon_dir.join(file_name);
resized
.save_with_format(&output_path, ImageFormat::Png)
.map_err(|e| format!("Failed to save icon image: {}", e))?;
}
Ok(())
}
================================================
FILE: src-tauri/src/builder/mod.rs
================================================
pub mod config;
pub mod crossplatform;
pub mod icon;
pub mod packer;
pub mod sdk;
pub mod swift;
================================================
FILE: src-tauri/src/builder/packer.rs
================================================
use std::{
fs::{self, File},
io::prelude::*,
path::PathBuf,
};
use dircpy::CopyBuilder;
use zip::write::SimpleFileOptions;
use crate::builder::config::{BuildSettings, ProjectConfig};
pub fn pack(
project_path: PathBuf,
config: &ProjectConfig,
build_settings: &BuildSettings,
) -> Result {
let workdir = project_path.join(".crosscode").join("Payload");
if !workdir.exists() {
std::fs::create_dir_all(&workdir)
.map_err(|e| format!("Failed to create work directory: {}", e))?;
}
let app_path = workdir.join(format!("{}.app", config.product));
if app_path.exists() {
std::fs::remove_dir_all(&app_path)
.map_err(|e| format!("Failed to remove existing app directory: {}", e))?;
}
std::fs::create_dir_all(&app_path)
.map_err(|e| format!("Failed to create app directory: {}", e))?;
let exec = project_path
.join(".build")
.join("arm64-apple-ios")
.join(if build_settings.debug {
"debug"
} else {
"release"
})
.join(&config.product);
if !exec.exists() {
return Err(format!("Executable not found at: {}", exec.display()));
}
fs::copy(exec, app_path.join(&config.product))
.map_err(|e| format!("Failed to copy executable: {}", e))?;
// TODO: Create default Info.plist if it doesn't exist
let info_plist = project_path.join("Info.plist");
if !info_plist.exists() {
return Err(format!("Info.plist not found at: {}", info_plist.display()));
}
let info_content = fs::read_to_string(&info_plist)
.map_err(|e| format!("Failed to read Info.plist: {}", e))?
.replace("[[bundle_id]]", &config.bundle_id)
.replace("[[product]]", &config.product)
.replace("[[version_num]]", &config.version_num)
.replace("[[version_string]]", &config.version_string);
fs::write(&app_path.join("Info.plist"), info_content)
.map_err(|e| format!("Failed to write Info.plist: {}", e))?;
let resources = project_path.join("Resources");
if !resources.exists() {
std::fs::create_dir_all(&resources)
.map_err(|e| format!("Failed to create Resources directory: {}", e))?;
}
CopyBuilder::new(&resources, &app_path)
.run()
.map_err(|e| format!("Failed to copy resources: {}", e))?;
Ok(app_path)
}
pub fn zip_ipa(app: PathBuf, config: &ProjectConfig) -> Result {
let payload = app.parent().unwrap_or(&PathBuf::from(".")).to_path_buf();
if !payload.exists() || !payload.is_dir() {
return Err(format!(
"Payload directory does not exist: {}",
payload.display()
));
}
let ipa_path = payload
.parent()
.unwrap()
.join(format!("{}.ipa", config.product));
let zip_file = File::create(&ipa_path)
.map_err(|e| format!("Failed to create zip file in payload directory: {}", e))?;
let mut zip = zip::ZipWriter::new(zip_file);
let options = SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.unix_permissions(0o755);
let walkdir = walkdir::WalkDir::new(&payload)
.into_iter()
.filter_map(|e| e.ok());
let prefix = payload.as_path().parent().ok_or(format!(
"Failed to get parent directory of payload: {}",
payload.display()
))?;
// https://github.com/zip-rs/zip2/blob/6c78fe381da074610d99e2d59546b0530bcb6e54/examples/write_dir.rs
let mut buffer = Vec::new();
for entry in walkdir {
let path = entry.path();
let name = path
.strip_prefix(prefix)
.map_err(|e| format!("Failed to strip prefix from path: {}", e))?;
let path_as_string = name
.to_str()
.map(str::to_owned)
.ok_or_else(|| format!("Failed to convert path to string: {}", path.display()))?;
// Write file or directory explicitly
// Some unzip tools unzip files with directory paths correctly, some do not!
if path.is_file() {
zip.start_file(path_as_string, options)
.map_err(|e| format!("Failed to start file {}: {}", path.display(), e))?;
let mut f = File::open(path)
.map_err(|e| format!("Failed to open file {}: {}", path.display(), e))?;
f.read_to_end(&mut buffer)
.map_err(|e| format!("Failed to read file {}: {}", path.display(), e))?;
zip.write_all(&buffer)
.map_err(|e| format!("Failed to write file {}: {}", path.display(), e))?;
buffer.clear();
} else if !name.as_os_str().is_empty() {
// Only if not root! Avoids path spec / warning
// and mapname conversion failed error on unzip
zip.add_directory(path_as_string, options)
.map_err(|e| format!("Failed to add directory {}: {}", path.display(), e))?;
}
}
zip.finish()
.map_err(|e| format!("Failed to finish zip file: {}", e))?;
Ok(ipa_path)
}
================================================
FILE: src-tauri/src/builder/sdk.rs
================================================
// Reference: https://github.com/xtool-org/xtool/blob/main/Sources/XToolSupport/SDKBuilder.swift
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::io::{Read, Seek};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use tauri::{AppHandle, Manager, Window};
use crate::builder::crossplatform::{linux_path, linux_temp_dir, remove_dir_all, symlink};
use crate::builder::swift::{validate_toolchain, SwiftBin};
use crate::operation::Operation;
use tauri::path::BaseDirectory;
use unxip_rs::{reader::XipReader, UnxipError};
#[cfg(not(target_os = "windows"))]
use sdkmover::copy_developer;
#[cfg(target_os = "windows")]
use crate::windows::windows_to_wsl_path;
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x08000000;
const DARWIN_TOOLS_VERSION: &str = "1.0.1";
#[tauri::command]
pub async fn install_sdk_operation(
app: AppHandle,
window: Window,
xcode_path: String,
toolchain_path: String,
is_dir: bool,
) -> Result<(), String> {
let op = Operation::new("install_sdk".to_string(), &window);
op.start("create_stage")?;
let work_dir = op
.fail_if_err("create_stage", linux_temp_dir())?
.join("crosscode")
.join("DarwinSDKBuild");
let res = install_sdk_internal(
app,
xcode_path,
toolchain_path,
work_dir.clone(),
is_dir,
&op,
)
.await;
op.start("cleanup")?;
let cleanup_result = if work_dir.exists() {
remove_dir_all(&work_dir)
} else {
Ok(())
};
let cleanup_result_for_match = cleanup_result
.as_ref()
.map(|_| ())
.map_err(|e| format!("{}", e));
let cleanup_result = op.fail_if_err_map("cleanup", cleanup_result, |e| {
format!("Failed to remove temp dir: {}", e)
});
if cleanup_result.is_ok() {
op.complete("cleanup")?;
}
match (res, cleanup_result_for_match) {
(Err(main_err), Err(cleanup_err)) => Err(format!(
"{main_err} (additionally, failed to clean up temp dir: {cleanup_err})"
)),
(Err(main_err), _) => Err(main_err),
(Ok(_), Err(cleanup_err)) => Err(format!(
"Install succeeded, but failed to clean up temp dir: {cleanup_err}"
)),
(Ok(val), Ok(_)) => Ok(val),
}
}
async fn install_sdk_internal(
app: AppHandle,
xcode_path: String,
toolchain_path: String,
work_dir: PathBuf,
is_dir: bool,
op: &Operation<'_>,
) -> Result<(), String> {
if xcode_path.is_empty() || (!xcode_path.ends_with(".xip") && !is_dir) {
return op.fail("create_stage", "Xcode not found".to_string());
}
if toolchain_path.is_empty() {
return op.fail("create_stage", "Toolchain not found".to_string());
}
if !validate_toolchain(&toolchain_path) {
return op.fail("create_stage", "Invalid toolchain path".to_string());
}
let swift_bin = SwiftBin::new(&toolchain_path);
if swift_bin.is_err() {
return op.fail("create_stage", "Invalid toolchain path".to_string());
}
let swift_bin = swift_bin.unwrap();
let output = swift_bin.output(&["sdk", "remove", "darwin"]);
if let Ok(output) = output {
if !output.status.success() && output.status.code() != Some(1) {
return op.fail(
"create_stage",
format!(
"Failed to remove existing darwin SDK: {}",
String::from_utf8_lossy(&output.stderr)
),
);
}
}
let output_dir = work_dir.join("darwin.artifactbundle");
if output_dir.exists() {
op.fail_if_err_map("create_stage", remove_dir_all(&output_dir), |e| {
format!("Failed to remove existing output directory: {}", e)
})?;
}
op.fail_if_err_map("create_stage", fs::create_dir_all(&output_dir), |e| {
format!("Failed to create output directory: {}", e)
})?;
op.move_on("create_stage", "install_toolset")?;
op.fail_if_err("install_toolset", install_toolset(&output_dir).await)?;
op.complete("install_toolset")?;
let dev = install_developer(app, &output_dir, &xcode_path, is_dir, op).await?;
op.start("write_metadata")?;
let iphone_os_sdk = op.fail_if_err("write_metadata", sdk(&dev, "iPhoneOS"))?;
let mac_os_sdk = op.fail_if_err("write_metadata", sdk(&dev, "MacOSX"))?;
let iphone_simulator_sdk = op.fail_if_err("write_metadata", sdk(&dev, "iPhoneSimulator"))?;
let info = "{
\"schemaVersion\": \"1.0\",
\"artifacts\": {
\"darwin\": {
\"type\": \"swiftSDK\",
\"version\": \"0.0.1\",
\"variants\": [
{
\"path\": \".\",
\"supportedTriples\": [\"aarch64-unknown-linux-gnu\", \"x86_64-unknown-linux-gnu\"]
}
]
}
}
}";
op.fail_if_err_map(
"write_metadata",
fs::write(output_dir.join("info.json"), info),
|e| format!("Failed to write info.json: {}", e),
)?;
let toolset = "{
\"schemaVersion\": \"1.0\",
\"rootPath\": \"toolset/bin\",
\"linker\": {
\"path\": \"ld64.lld\"
},
\"swiftCompiler\": {
\"extraCLIOptions\": [
\"-use-ld=lld\"
]
}
}";
op.fail_if_err_map(
"write_metadata",
fs::write(output_dir.join("toolset.json"), toolset),
|e| format!("Failed to write toolset.json: {}", e),
)?;
let sdk_def = SDKDefinition {
schema_version: "4.0".to_string(),
target_triples: HashMap::from([
(
"arm64-apple-ios".to_string(),
Triple::from_sdk("iPhoneOS", &iphone_os_sdk),
),
(
"arm64-apple-ios-simulator".to_string(),
Triple::from_sdk("iPhoneSimulator", &iphone_simulator_sdk),
),
(
"x86_64-apple-ios-simulator".to_string(),
Triple::from_sdk("iPhoneSimulator", &iphone_simulator_sdk),
),
(
"arm64-apple-macos".to_string(),
Triple::from_sdk("MacOSX", &mac_os_sdk),
),
(
"x86_64-apple-macos".to_string(),
Triple::from_sdk("MacOSX", &mac_os_sdk),
),
]),
};
let sdk_def_path = output_dir.join("swift-sdk.json");
op.fail_if_err_map(
"write_metadata",
fs::write(
sdk_def_path,
op.fail_if_err_map(
"write_metadata",
serde_json::to_string_pretty(&sdk_def),
|e| format!("Failed to serialize SDKDefinition: {}", e),
)?,
),
|e| format!("Failed to write swift-sdk.json: {}", e),
)?;
let sdk_version_path = output_dir.join("darwin-sdk-version.txt");
op.fail_if_err_map(
"write_metadata",
fs::write(&sdk_version_path, "develop"),
|e| format!("Failed to write darwin-sdk-version.txt: {}", e),
)?;
op.move_on("write_metadata", "install_sdk")?;
let real_output_dir =
op.fail_if_err("install_sdk", linux_path(&output_dir.to_string_lossy()))?;
let output = op.fail_if_err_map(
"install_sdk",
swift_bin.output(&["sdk", "install", &real_output_dir]),
|e| format!("Failed to execute swift command: {}", e),
)?;
if !output.status.success() {
return op.fail(
"install_sdk",
format!(
"Swift command failed: {}",
String::from_utf8_lossy(&output.stderr)
),
);
}
op.complete("install_sdk")?;
Ok(())
}
fn sdk(dev: &PathBuf, platform: &str) -> Result {
let dir = dev.join(format!("Platforms/{}.platform/Developer/SDKs", platform));
let regex = Regex::new(&format!(r"^{}\d+\.\d+\.sdk$", regex::escape(platform)))
.map_err(|e| format!("Invalid regex: {}", e))?;
let entries =
fs::read_dir(&dir).map_err(|e| format!("Failed to read SDKs directory: {}", e))?;
for entry in entries {
let entry = entry.map_err(|e| format!("Failed to read entry: {}", e))?;
let name = entry.file_name();
let name_str = name.to_string_lossy();
if regex.is_match(&name_str) {
return Ok(name_str.into_owned());
}
}
Err(format!("Could not find SDK for {}/{}", platform, platform))
}
async fn install_toolset(output_path: &PathBuf) -> Result<(), String> {
let toolset_dir = output_path.join("toolset");
fs::create_dir_all(&toolset_dir)
.map_err(|e| format!("Failed to create toolset directory: {}", e))?;
let arch = if cfg!(target_arch = "x86_64") {
"x86_64"
} else if cfg!(target_arch = "aarch64") {
"aarch64"
} else {
return Err("Unsupported architecture".to_string());
};
let toolset_url = format!(
"https://github.com/xtool-org/darwin-tools-linux-llvm/releases/download/v{}/toolset-{}.tar.gz",
DARWIN_TOOLS_VERSION, arch
);
let response = reqwest::get(&toolset_url)
.await
.map_err(|e| format!("Failed to download toolset: {}", e))?;
if !response.status().is_success() {
return Err(format!("Failed to download toolset: {}", response.status()));
}
let tar_gz = response
.bytes()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(&*tar_gz));
archive
.unpack(&toolset_dir)
.map_err(|e| format!("Failed to extract toolset: {}", e))?;
#[cfg(target_os = "windows")]
{
// 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
let wsl_toolset_path =
windows_to_wsl_path(&toolset_dir.join("bin").to_string_lossy().to_string())?;
let output = Command::new("wsl")
.arg("chmod")
.arg("+x")
.arg(format!("{}/*", wsl_toolset_path))
.creation_flags(CREATE_NO_WINDOW)
.output()
.map_err(|e| format!("Failed to run chmod: {}", e))?;
if !output.status.success() {
return Err(format!(
"Failed to set executable permissions: {}",
String::from_utf8_lossy(&output.stderr)
));
}
}
Ok(())
}
async fn install_developer(
app: AppHandle,
output_path: &PathBuf,
xcode_path: &str,
is_dir: bool,
op: &Operation<'_>,
) -> Result {
op.start("extract_xip")?;
let dev_stage = output_path.join("DeveloperStage");
let mut app_path = PathBuf::from(xcode_path);
if !is_dir {
op.fail_if_err_map("extract_xip", fs::create_dir_all(&dev_stage), |e| {
format!("Failed to create DeveloperStage directory: {}", e)
})?;
let mut file = op.fail_if_err_map("extract_xip", fs::File::open(xcode_path), |e| {
format!("Failed to open xip file: {}", e)
})?;
let cpio = op
.fail_if_err_map(
"extract_xip",
app.path().resolve("cpio", BaseDirectory::Resource),
|e| format!("Failed to resolve cpio path: {}", e),
)?
.to_string_lossy()
.to_string();
#[cfg(target_os = "windows")]
let cpio = op.fail_if_err("extract_xip", windows_to_wsl_path(&cpio))?;
op.fail_if_err_map("extract_xip", unxip(&mut file, &dev_stage, cpio), |e| {
format!("Failed to extract xip file: {}", e)
})?;
let app_dirs = op
.fail_if_err_map("extract_xip", fs::read_dir(&dev_stage), |e| {
format!("Failed to read DeveloperStage directory: {}", e)
})?
.filter_map(Result::ok)
.filter(|entry| entry.path().extension().map_or(false, |ext| ext == "app"))
.collect::>();
if app_dirs.len() != 1 {
return op.fail(
"extract_xip",
format!(
"Expected one .app in DeveloperStage, found {}",
app_dirs.len()
),
);
}
app_path = app_dirs[0].path();
}
op.move_on("extract_xip", "copy_files")?;
let dev = output_path.join("Developer");
op.fail_if_err_map("copy_files", fs::create_dir_all(&dev), |e| {
format!("Failed to create Developer directory: {}", e)
})?;
let contents_developer = app_path.join("Contents").join("Developer");
if !contents_developer.exists() {
return op.fail(
"copy_files",
"Contents/Developer not found in .app".to_string(),
);
}
#[cfg(not(target_os = "windows"))]
op.fail_if_err(
"copy_files",
copy_developer(
&contents_developer,
&dev,
Path::new("Contents/Developer"),
false,
),
)?;
#[cfg(target_os = "windows")]
{
let sdkmover_path = op
.fail_if_err_map(
"copy_files",
app.path().resolve("sdkmoverbin", BaseDirectory::Resource),
|e| format!("Failed to resolve sdkmoverbin path: {}", e),
)?
.to_string_lossy()
.to_string();
let linux_sdkmover_path =
op.fail_if_err("copy_files", windows_to_wsl_path(&sdkmover_path))?;
let linux_contents_developer = op.fail_if_err(
"copy_files",
windows_to_wsl_path(&contents_developer.to_string_lossy().to_string()),
)?;
let linux_dev = op.fail_if_err(
"copy_files",
windows_to_wsl_path(&dev.to_string_lossy().to_string()),
)?;
let output = op.fail_if_err_map(
"copy_files",
Command::new("wsl")
.arg(&linux_sdkmover_path)
.arg(&linux_contents_developer)
.arg(&linux_dev)
.creation_flags(CREATE_NO_WINDOW)
.output(),
|e| format!("Failed to run sdkmover: {}", e),
)?;
if !output.status.success() {
return op.fail(
"copy_files",
format!(
"Failed to move files: {}",
String::from_utf8_lossy(&output.stderr)
),
);
}
}
if dev_stage.exists() {
op.fail_if_err_map("copy_files", remove_dir_all(&dev_stage), |e| {
format!("Failed to remove DeveloperStage directory: {}", e)
})?;
}
for platform in ["iPhoneOS", "MacOSX", "iPhoneSimulator"] {
let lib = "../../../../../Library";
let dest = dev.join(format!(
"Platforms/{}.platform/Developer/SDKs/{}.sdk/System/Library/Frameworks",
platform, platform
));
let links = [
(
"Testing.framework",
format!("{}/Frameworks/Testing.framework", lib),
),
(
"XCTest.framework",
format!("{}/Frameworks/XCTest.framework", lib),
),
(
"XCUIAutomation.framework",
format!("{}/Frameworks/XCUIAutomation.framework", lib),
),
(
"XCTestCore.framework",
format!("{}/PrivateFrameworks/XCTestCore.framework", lib),
),
];
for (name, target) in &links {
let link_path = dest.join(name);
op.fail_if_err_map(
"copy_files",
symlink(target, &link_path.to_string_lossy().to_string()),
|e| {
format!(
"Failed to create symlink {:?} -> {:?}: {}",
link_path, target, e
)
},
)?;
}
}
op.complete("copy_files")?;
Ok(dev)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Triple {
sdk_root_path: String,
include_search_paths: Vec,
library_search_paths: Vec,
swift_resources_path: String,
swift_static_resources_path: String,
toolset_paths: Vec,
}
impl Triple {
fn from_sdk(platform: &str, sdk: &str) -> Self {
Triple {
sdk_root_path: format!(
"Developer/Platforms/{}.platform/Developer/SDKs/{}",
platform, sdk
),
include_search_paths: vec![format!(
"Developer/Platforms/{}.platform/Developer/usr/lib",
platform
)],
library_search_paths: vec![format!(
"Developer/Platforms/{}.platform/Developer/usr/lib",
platform
)],
swift_resources_path: format!(
"Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift"
),
swift_static_resources_path: format!(
"Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift_static"
),
toolset_paths: vec![format!("toolset.json")],
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SDKDefinition {
schema_version: String,
target_triples: HashMap,
}
pub fn unxip(
reader: &mut R,
output_path: &Path,
cpio_path: String,
) -> Result<(), UnxipError> {
let mut xip_reader = XipReader::new(reader)?;
std::fs::create_dir_all(output_path).map_err(UnxipError::IoError)?;
#[cfg(not(target_os = "windows"))]
let mut child = Command::new(&cpio_path)
.arg("-idm")
.current_dir(output_path)
.stdin(Stdio::piped())
.spawn()
.map_err(|e| UnxipError::Misc(format!("Failed to spawn cpio: {}", e)))?;
#[cfg(target_os = "windows")]
let mut child = Command::new("wsl")
.arg(format!("{}", cpio_path))
.arg("-idm")
.current_dir(output_path)
.creation_flags(CREATE_NO_WINDOW)
.stdin(Stdio::piped())
.stdout(Stdio::inherit())
.spawn()
.map_err(|e| UnxipError::Misc(format!("Failed to spawn cpio: {}", e)))?;
{
let stdin = child
.stdin
.as_mut()
.ok_or_else(|| UnxipError::Misc("Failed to open cpio stdin".to_string()))?;
std::io::copy(&mut xip_reader, stdin).map_err(UnxipError::IoError)?;
}
let status = child.wait().map_err(UnxipError::IoError)?;
if !status.success() {
return Err(UnxipError::Misc(format!(
"cpio failed with status: {}",
status
)));
}
Ok(())
}
================================================
FILE: src-tauri/src/builder/swift.rs
================================================
#[cfg(target_os = "windows")]
use crate::windows::has_wsl;
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
use crate::{
builder::{
config::{BuildSettings, ProjectConfig},
crossplatform::{linux_env, windows_path},
packer::{pack, zip_ipa},
},
emit_error_and_return,
sideloader::{device::DeviceInfo, sideload::sideload_app},
};
use serde::{Deserialize, Serialize};
use std::{
io::{self, BufRead, BufReader},
path::PathBuf,
process::{Command, Output, Stdio},
thread,
};
use tauri::{Emitter, Window};
use tokio::process::Command as TokioCommand;
#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x08000000;
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ToolchainResult {
pub swiftly_installed: bool,
pub swiftly_version: Option,
pub toolchains: Vec,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Toolchain {
pub version: String,
pub path: String,
pub is_swiftly: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
struct SwiftlyConfig {
pub installed_toolchains: Vec,
pub version: String,
}
#[derive(Debug, Clone)]
pub struct SwiftBin {
pub bin_path: String,
pub sourcekit_path: String,
}
impl SwiftBin {
pub fn new(toolchain_path: &str) -> Result {
#[cfg(target_os = "windows")]
{
if !has_wsl() {
return Err("WSL is not available".to_string());
}
let output = Command::new("wsl")
.args([
"bash",
"-c",
&format!("test -f \"{}/usr/bin/swift\"", toolchain_path),
])
.creation_flags(CREATE_NO_WINDOW)
.output()
.map_err(|e| format!("Failed to execute command: {}", e))?;
if !output.status.success() {
return Err(format!(
"Swift toolchain invalid: {}",
String::from_utf8_lossy(&output.stderr)
));
}
Ok(SwiftBin {
bin_path: format!("{}/usr/bin/swift", toolchain_path),
sourcekit_path: format!("{}/usr/bin/sourcekit-lsp", toolchain_path),
})
}
#[cfg(not(target_os = "windows"))]
{
let path = PathBuf::from(toolchain_path);
if !path.exists() || !path.is_dir() {
return Err("Invalid toolchain path".to_string());
}
let swift_path = path.join("usr").join("bin").join("swift");
if !swift_path.exists() || !swift_path.is_file() {
return Err("Swift binary not found in toolchain".to_string());
}
let sourcekit_path = path.join("usr").join("bin").join("sourcekit-lsp");
if !sourcekit_path.exists() || !sourcekit_path.is_file() {
return Err("SourceKit-LSP binary not found in toolchain".to_string());
}
Ok(SwiftBin {
bin_path: swift_path.to_string_lossy().to_string(),
sourcekit_path: sourcekit_path.to_string_lossy().to_string(),
})
}
}
pub fn output(&self, args: &[&str]) -> io::Result {
#[cfg(target_os = "windows")]
{
if !has_wsl() {
return Err(io::Error::new(io::ErrorKind::Other, "WSL is not available"));
}
let mut cmd = Command::new("wsl");
cmd.args(["bash", "-l", "-c"])
.arg(format!("\"{}\" {}", self.bin_path, args.join(" ")))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.creation_flags(CREATE_NO_WINDOW)
.output()
}
#[cfg(not(target_os = "windows"))]
{
let mut cmd = Command::new(&self.bin_path);
cmd.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
}
}
pub fn command(&self) -> Command {
#[cfg(target_os = "windows")]
{
let mut cmd = Command::new("wsl");
cmd.arg(&self.bin_path);
cmd.creation_flags(CREATE_NO_WINDOW);
cmd
}
#[cfg(not(target_os = "windows"))]
{
Command::new(&self.bin_path)
}
}
pub fn sourcekit_command(&self) -> TokioCommand {
#[cfg(target_os = "windows")]
{
let mut cmd = TokioCommand::new("wsl");
cmd.arg(&self.sourcekit_path);
cmd.creation_flags(CREATE_NO_WINDOW);
cmd
}
#[cfg(not(target_os = "windows"))]
{
TokioCommand::new(&self.sourcekit_path)
}
}
}
#[tauri::command]
pub fn has_darwin_sdk(toolchain_path: &str) -> String {
let swift_bin = SwiftBin::new(toolchain_path);
if swift_bin.is_err() {
return "none".to_string();
}
let swift_bin = swift_bin.unwrap();
let output = swift_bin.output(&["sdk", "list"]);
if output.is_err() {
return "none".to_string();
}
let output = output.unwrap();
if !output.status.success() {
return "none".to_string();
}
let output_str = String::from_utf8_lossy(&output.stdout);
if !output_str.contains("darwin") {
return "none".to_string();
}
let output = swift_bin.output(&[
"sdk",
"configure",
"--show-configuration",
"darwin",
"arm64-apple-ios",
]);
if output.is_err() {
return "none".to_string();
}
let output = output.unwrap();
if !output.status.success() {
return "none".to_string();
}
let output_str = String::from_utf8_lossy(&output.stdout);
let sdk_version = output_str.lines().find_map(|line| {
if line.starts_with("sdkRootPath:") {
let parts: Vec<&str> = line.split('/').collect();
for part in parts {
if part.starts_with("iPhoneOS") && part.ends_with(".sdk") {
let version = part.trim_start_matches("iPhoneOS").trim_end_matches(".sdk");
return Some(version.to_string());
}
}
}
None
});
if let Some(version) = sdk_version {
version
} else {
"none".to_string()
}
}
#[tauri::command]
pub fn validate_toolchain(toolchain_path: &str) -> bool {
let swift_path = SwiftBin::new(toolchain_path);
if swift_path.is_err() {
return false;
}
let swift_path = swift_path.unwrap();
let output = swift_path.output(&["--version"]);
if output.is_err() {
return false;
}
let output = output.unwrap();
if !output.status.success() {
return false;
}
true
}
#[tauri::command]
pub async fn get_toolchain_info(
toolchain_path: String,
is_swiftly: bool,
) -> Result {
if !validate_toolchain(&toolchain_path) {
return Err("Invalid toolchain path".to_string());
}
let swift_path = SwiftBin::new(&toolchain_path)?;
let output = swift_path
.output(&["--version"])
.map_err(|e| format!("Failed to run swift command: {}", e))?;
let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
let version = version
.split_whitespace()
.nth(2)
.ok_or("Failed to parse swift version".to_string())?
.to_string();
Ok(Toolchain {
version,
path: toolchain_path.clone(),
is_swiftly,
})
}
#[tauri::command]
pub async fn get_swiftly_toolchains() -> Result {
let swiftly_home_dir = get_swiftly_path();
if get_swiftly_config().is_err() {
return Ok(ToolchainResult {
swiftly_installed: false,
swiftly_version: None,
toolchains: vec![],
});
}
if let Some(_) = swiftly_home_dir {
let config = get_swiftly_config()?;
let toolchains_unfiltered: Vec = config
.installed_toolchains
.iter()
.map(|version| {
#[cfg(target_os = "windows")]
{
let path = format!(
"{}/toolchains/{}",
swiftly_home_dir.as_ref().unwrap(),
version
);
Toolchain {
version: version.clone(),
path,
is_swiftly: true,
}
}
#[cfg(not(target_os = "windows"))]
{
let path = PathBuf::from(swiftly_home_dir.as_ref().unwrap())
.join("toolchains")
.join(version);
Toolchain {
version: version.clone(),
path: path.to_string_lossy().to_string(),
is_swiftly: true,
}
}
})
.collect();
let mut toolchains = Vec::new();
for toolchain in toolchains_unfiltered {
if validate_toolchain(&toolchain.path) {
toolchains.push(toolchain);
}
}
return Ok(ToolchainResult {
swiftly_installed: true,
swiftly_version: Some(config.version),
toolchains,
});
} else {
return Ok(ToolchainResult {
swiftly_installed: false,
swiftly_version: None,
toolchains: vec![],
});
}
}
fn get_swiftly_config() -> Result {
let swiftly_home_dir = get_swiftly_path().ok_or("Swiftly home directory not found")?;
let swiftly_home_dir = windows_path(&swiftly_home_dir)?;
let config_path = format!("{}/config.json", swiftly_home_dir);
let content = std::fs::read_to_string(&config_path)
.map_err(|_| "Failed to read config file".to_string())?;
// TODO: why?
let content = content.trim_end_matches('%').to_string();
let config: SwiftlyConfig = serde_json::from_str(&content)
.map_err(|e| format!("Failed to parse config file: {}", e))?;
Ok(config)
}
fn get_swiftly_path() -> Option {
let swiftly_home_dir = linux_env("SWIFTLY_HOME_DIR").unwrap_or_default();
if !swiftly_home_dir.is_empty() {
return Some(swiftly_home_dir);
}
let home_dir = linux_env("HOME").unwrap_or_default();
if !home_dir.is_empty() {
let swiftly_path = format!("{}/.local/share/swiftly", home_dir);
if std::path::Path::new(&swiftly_path).exists() {
return Some(swiftly_path);
}
}
None
}
async fn build_swift_internal(
window: &Window,
folder: &str,
toolchain_path: &str,
build_settings: BuildSettings,
emit_exit_code: bool,
) -> Result<(PathBuf, ProjectConfig), String> {
let config = match ProjectConfig::load(PathBuf::from(&folder), &toolchain_path) {
Ok(config) => config,
Err(e) => {
return emit_error_and_return(&window, &format!("Failed to load project config: {}", e))
}
};
let swift_bin = SwiftBin::new(&toolchain_path)?;
let mut cmd = swift_bin.command();
cmd.arg("build")
.arg("-c")
.arg(if build_settings.debug {
"debug"
} else {
"release"
})
.arg("--swift-sdk")
.arg("arm64-apple-ios")
.current_dir(&folder);
pipe_command(&mut cmd, &window, emit_exit_code).await?;
match pack(PathBuf::from(&folder), &config, &build_settings) {
Ok(app) => {
window
.emit("build-output", "Pack Success")
.expect("failed to send output");
Ok((app, config))
}
Err(e) => emit_error_and_return(&window, &format!("Failed to pack app: {}", e)),
}
}
#[tauri::command]
pub async fn build_swift(
window: tauri::Window,
folder: String,
toolchain_path: String,
debug: bool,
) -> Result<(), String> {
let build_settings = BuildSettings { debug };
if !validate_toolchain(&toolchain_path) {
return emit_error_and_return(&window, "Invalid Toolchain");
}
let (app, config) =
build_swift_internal(&window, &folder, &toolchain_path, build_settings, true).await?;
let ipa_path = zip_ipa(app, &config);
if ipa_path.is_err() {
return emit_error_and_return(
&window,
&format!("Failed to zip IPA: {}", ipa_path.err().unwrap()),
);
}
let ipa_path = ipa_path.unwrap();
window
.emit(
"build-output",
format!("Build Success, output file at {}", ipa_path.display()),
)
.expect("failed to send output");
Ok(())
}
#[tauri::command]
pub async fn clean_swift(
window: tauri::Window,
folder: String,
toolchain_path: String,
) -> Result<(), String> {
let swift_bin = SwiftBin::new(&toolchain_path)?;
let mut cmd = swift_bin.command();
cmd.arg("package").arg("clean").current_dir(folder);
window
.emit("build-output", "Cleaning...")
.expect("failed to send output");
pipe_command(&mut cmd, &window, true).await
}
#[tauri::command]
pub async fn deploy_swift(
handle: tauri::AppHandle,
window: tauri::Window,
anisette_server: String,
device: DeviceInfo,
folder: String,
toolchain_path: String,
debug: bool,
) -> Result<(), String> {
let build_settings = BuildSettings { debug };
if !validate_toolchain(&toolchain_path) {
return emit_error_and_return(&window, "Invalid Toolchain");
}
let (app, _) =
build_swift_internal(&window, &folder, &toolchain_path, build_settings, false).await?;
sideload_app(&handle, &window, anisette_server, device, app)
.await
.map_err(|e| format!("Failed to sideload app: {}", e))?;
window
.emit("build-output", "Build & Install Success")
.expect("failed to send output");
Ok(())
}
pub async fn pipe_command(
cmd: &mut Command,
window: &tauri::Window,
emit_exit_code: bool,
) -> Result<(), String> {
let name = "build-output";
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
let mut command = match cmd.spawn() {
Ok(cmd) => cmd,
Err(_) => {
return emit_error_and_return(&window, "Failed to spawn build command");
}
};
let stdout = match command.stdout.take() {
Some(out) => out,
None => {
return emit_error_and_return(&window, "Failed to get stdout");
}
};
let stderr = match command.stderr.take() {
Some(err) => err,
None => {
return emit_error_and_return(&window, "Failed to get stderr");
}
};
let stdout_handle = spawn_output_thread(stdout, window.clone(), name.to_string());
let stderr_handle = spawn_output_thread(stderr, window.clone(), name.to_string());
stdout_handle.join().expect("stdout thread panicked");
stderr_handle.join().expect("stderr thread panicked");
let exit_status = match command.wait() {
Ok(status) => status,
Err(_) => {
return emit_error_and_return(&window, "Failed to wait for command");
}
};
let exit_code = exit_status.code().unwrap_or(1);
if exit_code != 0 || emit_exit_code {
window
.emit(name, format!("command.done.{}", exit_code))
.expect("failed to send output");
}
if exit_code != 0 {
return Err(format!("Command exited with code {}", exit_code));
}
Ok(())
}
fn spawn_output_thread(
reader: R,
window: tauri::Window,
name: String,
) -> std::thread::JoinHandle<()> {
thread::spawn(move || {
let reader = BufReader::new(reader);
for line in reader.lines() {
match line {
Ok(line) => {
window.emit(&name, line).expect("failed to send output");
}
Err(err) => {
window
.emit(&name, "command.done.999".to_string())
.expect("failed to send output");
eprintln!("Error reading output: {}", err);
return;
}
}
}
})
}
================================================
FILE: src-tauri/src/lsp_utils.rs
================================================
use std::path::PathBuf;
use sysinfo::System;
use crate::builder::config::{ProjectConfig, ProjectValidation};
#[tauri::command]
pub fn has_limited_ram() -> bool {
let s = System::new_all();
let mem_gib = s.total_memory() as f64 / (1024.0 * 1024.0 * 1024.0);
// This is intended to be 16gb, however 16gb of physical ram does not always translate to 16gb of usable memory.
mem_gib < 14.0
}
#[tauri::command]
pub fn validate_project(project_path: String, toolchain_path: String) -> ProjectValidation {
ProjectConfig::validate(PathBuf::from(project_path), &toolchain_path)
}
// #[tauri::command]
// pub fn ensure_lsp_config(project_path: String) -> Result<(), String> {
// let project_path = PathBuf::from(project_path);
// if !project_path.exists() {
// return Err(format!("Project path does not exist: {:?}", project_path));
// }
// let sourcekit_lsp_path = project_path.join(".sourcekit-lsp");
// if !sourcekit_lsp_path.exists() {
// fs::create_dir_all(sourcekit_lsp_path).map_err(|e| e.to_string())?;
// }
// let config_path = project_path.join(".sourcekit-lsp").join("config.json");
// if !config_path.exists() {
// fs::write(config_path, "{
// \"$schema\": \"https://raw.githubusercontent.com/swiftlang/sourcekit-lsp/refs/heads/release/6.2/config.schema.json\",
// \"swiftPM\": {
// \"swiftSDK\": \"arm64-apple-ios\"
// }
// }").map_err(|e| e.to_string())?;
// }
// Ok(())
// }
================================================
FILE: src-tauri/src/main.rs
================================================
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#[macro_use]
mod templates;
#[macro_use]
mod windows;
#[macro_use]
mod builder;
mod operation;
#[macro_use]
mod sideloader;
#[macro_use]
mod sourcekit_lsp;
#[macro_use]
mod lsp_utils;
use builder::crossplatform::{linux_path, windows_path};
use builder::icon::import_icon;
use builder::sdk::install_sdk_operation;
use builder::swift::{
build_swift, clean_swift, deploy_swift, get_swiftly_toolchains, get_toolchain_info,
has_darwin_sdk, validate_toolchain,
};
use lsp_utils::{has_limited_ram, validate_project};
use serde_json::Value;
use sideloader::{
apple_commands::{
delete_app_id, delete_stored_credentials, get_apple_email, get_certificates, list_app_ids,
reset_anisette, revoke_certificate,
},
device::{is_ddi_mounted, mount_ddi},
screenshot::take_screenshot,
sideload::refresh_idevice,
stdout::{is_streaming_stdout, start_stream_stdout, stop_stream_stdout, StdoutStream},
syslog::{is_streaming_syslog, start_stream_syslog, stop_stream_syslog, SyslogStream},
};
use sourcekit_lsp::{get_server_status, start_sourcekit_server, stop_sourcekit_server};
use std::sync::Arc;
use tauri::Emitter;
use tauri::Manager;
use tauri_plugin_cli::CliExt;
use tauri_plugin_store::StoreExt;
use templates::create_template;
use tokio::sync::Mutex;
use windows::{has_wsl, install_wsl, is_windows};
fn main() {
let _ = fix_path_env::fix();
#[cfg(target_os = "linux")]
{
use std::env;
if env::var_os("__NV_DISABLE_EXPLICIT_SYNC").is_none() {
env::set_var("__NV_DISABLE_EXPLICIT_SYNC", "1");
}
}
let syslog_stream: SyslogStream = SyslogStream(Arc::new(Mutex::new(None)));
let stdout_stream: StdoutStream = Arc::new(Mutex::new(None));
tauri::Builder::default()
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_cli::init())
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_store::Builder::new().build())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_shell::init())
.manage(sourcekit_lsp::create_server_state())
.manage(syslog_stream)
.manage(stdout_stream)
.setup(|app| {
match app.cli().matches() {
Ok(matches) => {
if let Some(arg) = matches.args.get("showMainWindow") {
if arg.value == Value::Bool(true) {
let window = app.get_webview_window("main").unwrap();
window.show().unwrap();
window.open_devtools();
}
}
}
Err(_) => {}
}
let store = app.store("preferences.json")?;
let open_last = if store.has("general/startup") {
store.get("general/startup").unwrap().as_str().unwrap() == "open-last"
} else {
true
};
if open_last {
if let Some(last_project) = store.get("last-opened-project") {
if last_project.is_string() {
let path = last_project.as_str().unwrap();
let url_str = format!("/ide/{}", path);
app.get_webview_window("main")
.unwrap()
.eval(&format!("window.location.replace('{}')", url_str))?;
}
}
}
Ok(())
})
.on_window_event(|window, event| match event {
tauri::WindowEvent::Destroyed => {
if window.label() == "main" {
window.app_handle().exit(0);
}
}
_ => {}
})
.invoke_handler(tauri::generate_handler![
is_windows,
has_wsl,
build_swift,
deploy_swift,
clean_swift,
refresh_idevice,
delete_stored_credentials,
reset_anisette,
get_apple_email,
revoke_certificate,
get_certificates,
list_app_ids,
delete_app_id,
create_template,
get_swiftly_toolchains,
validate_toolchain,
get_toolchain_info,
install_sdk_operation,
has_darwin_sdk,
start_sourcekit_server,
stop_sourcekit_server,
get_server_status,
has_limited_ram,
validate_project,
linux_path,
windows_path,
start_stream_syslog,
stop_stream_syslog,
import_icon,
is_streaming_syslog,
open_devtools,
start_stream_stdout,
stop_stream_stdout,
is_streaming_stdout,
install_wsl,
is_ddi_mounted,
mount_ddi,
take_screenshot,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
pub fn emit_error_and_return(window: &tauri::Window, msg: &str) -> Result {
window.emit("build-output", msg.to_string()).ok();
window.emit("build-output", "command.done.999").ok();
Err(msg.to_string())
}
#[tauri::command]
fn open_devtools(app: tauri::AppHandle) -> Result<(), String> {
app.get_webview_window("main").unwrap().open_devtools();
Ok(())
}
================================================
FILE: src-tauri/src/operation.rs
================================================
use serde::Serialize;
use tauri::{Emitter, Window};
pub struct Operation<'a> {
id: String,
window: &'a Window,
}
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct OperationUpdate<'a> {
update_type: &'a str,
step_id: &'a str,
extra_details: Option,
}
impl<'a> Operation<'a> {
pub fn new(id: String, window: &'a Window) -> Operation<'a> {
Operation { id, window }
}
pub fn move_on(&self, old_id: &str, new_id: &str) -> Result<(), String> {
self.complete(old_id)?;
self.start(new_id)
}
pub fn start(&self, id: &str) -> Result<(), String> {
self.window
.emit(
&format!("operation_{}", self.id),
OperationUpdate {
update_type: "started",
step_id: id,
extra_details: None,
},
)
.map_err(|_| "Failed to emit status to frontend".to_string())
}
pub fn complete(&self, id: &str) -> Result<(), String> {
self.window
.emit(
&format!("operation_{}", self.id),
OperationUpdate {
update_type: "finished",
step_id: id,
extra_details: None,
},
)
.map_err(|_| "Failed to emit status to frontend".to_string())
}
pub fn fail(&self, id: &str, error: String) -> Result {
self.window
.emit(
&format!("operation_{}", self.id),
OperationUpdate {
update_type: "failed",
step_id: id,
extra_details: Some(error.clone()),
},
)
.map_err(|_| "Failed to emit status to frontend".to_string())?;
return Err(error);
}
pub fn fail_if_err(&self, id: &str, res: Result) -> Result {
match res {
Ok(t) => Ok(t),
Err(e) => self.fail::(id, e),
}
}
pub fn fail_if_err_map String>(
&self,
id: &str,
res: Result,
map_err: O,
) -> Result {
match res {
Ok(t) => Ok(t),
Err(e) => {
let err = map_err(e);
self.fail::(id, err.clone())
}
}
}
}
================================================
FILE: src-tauri/src/sideloader/apple.rs
================================================
use isideload::{developer_session::DeveloperSession, AnisetteConfiguration, AppleAccount};
use once_cell::sync::OnceCell;
use serde_json::Value;
use std::{
sync::{mpsc::RecvTimeoutError, Arc, Mutex},
time::Duration,
};
use tauri::{Emitter, Listener, Manager};
use crate::sideloader::apple_commands::{get_stored_credentials, store_credentials};
pub static APPLE_ACCOUNT: OnceCell>>> = OnceCell::new();
pub async fn get_account(
handle: &tauri::AppHandle,
window: &tauri::Window,
anisette_server: String,
) -> Result, String> {
let cell = APPLE_ACCOUNT.get_or_init(|| Mutex::new(None));
{
let account_guard = cell.lock().unwrap();
if let Some(account) = &*account_guard {
return Ok(account.clone());
}
}
let account = login(handle, window, anisette_server).await?;
let mut account_guard = cell.lock().unwrap();
*account_guard = Some(account.clone());
Ok(account)
}
pub async fn get_developer_session(
handle: &tauri::AppHandle,
window: &tauri::Window,
anisette_server: String,
) -> Result {
let account = get_account(handle, window, anisette_server.clone()).await?;
let mut dev_session = DeveloperSession::new(account);
let teams = match dev_session.list_teams().await {
Ok(t) => t,
Err(e) => {
// This code means we have been logged in for too long and we must relogin again
let is_22411 = match &e {
isideload::Error::Auth(code, _) => *code == -22411,
isideload::Error::DeveloperSession(code, _) => *code == -22411,
_ => false,
};
if is_22411 {
invalidate_account();
let account = get_account(handle, window, anisette_server).await?;
dev_session = DeveloperSession::new(account);
match dev_session.list_teams().await {
Ok(t) => t,
Err(e) => {
return Err(format!("Failed to list teams after re-login: {:?}", e));
}
}
} else {
return Err(format!("Failed to list teams: {:?}", e));
}
}
};
dev_session.set_team(teams[0].clone());
Ok(dev_session)
}
pub async fn login(
handle: &tauri::AppHandle,
window: &tauri::Window,
anisette_server: String,
) -> Result, String> {
let (tx, rx) = std::sync::mpsc::channel::();
let window_clone = window.clone();
let appleid_closure = move || -> Result<(String, String), String> {
if let Some((email, password)) = get_stored_credentials() {
window_clone
.emit(
"build-output",
"Using stored Apple ID credentials".to_string(),
)
.ok();
return Ok((email, password));
}
window_clone
.emit("apple-id-required", ())
.expect("Failed to emit apple-id-required event");
let tx1 = tx.clone();
let handler_id_recieved = window_clone.listen("apple-id-recieved", move |event| {
let json = event.payload();
let _ = tx1.send(format!("apple-id-recieved:{}", json));
});
let tx2 = tx.clone();
let handler_id_cancelled = window_clone.listen("login-cancelled", move |_event| {
let _ = tx2.send("login-cancelled".to_string());
});
let result = rx.recv_timeout(Duration::from_secs(120));
window_clone.unlisten(handler_id_recieved);
window_clone.unlisten(handler_id_cancelled);
match result {
Ok(msg) if msg.starts_with("apple-id-recieved:") => {
let json = &msg["apple-id-recieved:".len()..];
let json: Value = serde_json::from_str(json).expect("Failed to parse json");
let apple_id = json
.get("appleId")
.and_then(Value::as_str)
.expect("Failed to get apple_id from json")
.to_string();
let password = json
.get("applePass")
.and_then(Value::as_str)
.expect("Failed to get password from json")
.to_string();
let save_credentials = json
.get("saveCredentials")
.and_then(Value::as_bool)
.unwrap_or(false);
if save_credentials {
if let Err(e) = store_credentials(&apple_id, &password) {
window_clone
.emit(
"build-output",
format!("Failed to save credentials: {:?}", e),
)
.ok();
}
}
Ok((apple_id, password))
}
Ok(msg) if msg == "login-cancelled" => {
window_clone
.emit("build-output", "Login cancelled by user".to_string())
.ok();
Err("Login cancelled by user".to_string())
}
Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) | _ => {
window_clone
.emit("build-output", "Login cancelled or timed out".to_string())
.ok();
Err("Login cancelled or timed out".to_string())
}
}
};
let (tx, rx) = std::sync::mpsc::channel::();
let window_clone = window.clone();
let tfa_closure = move || -> Result {
window_clone
.emit("2fa-required", ())
.expect("Failed to emit 2fa-required event");
let tx = tx.clone();
let handler_id = window_clone.listen("2fa-recieved", move |event| {
let code = event.payload();
let _ = tx.send(code.to_string());
});
let result = rx.recv_timeout(Duration::from_secs(120));
window_clone.unlisten(handler_id);
match result {
Ok(code) => {
let code = code.trim_matches('"').to_string();
Ok(code)
}
Err(RecvTimeoutError::Timeout) => Err("2FA cancelled or timed out".to_string()),
Err(RecvTimeoutError::Disconnected) => Err("2FA disconnected".to_string()),
}
};
let config = AnisetteConfiguration::default();
let config =
config.set_configuration_path(handle.path().app_config_dir().map_err(|e| e.to_string())?);
let config = config.set_anisette_url(format!("https://{}", anisette_server));
window
.emit("build-output", "Logging in...")
.map_err(|e| e.to_string())?;
let account = AppleAccount::login(appleid_closure, tfa_closure, config).await;
if let Err(e) = account {
window
.emit("build-output", "Login failed or cancelled".to_string())
.ok();
window.emit("build-output", format!("{:?}", e)).ok();
return Err(format!("{:?}", e));
}
let account = Arc::new(account.unwrap());
window
.emit("build-output", "Successfully logged in".to_string())
.map_err(|e| e.to_string())?;
Ok(account)
}
pub fn invalidate_account() {
let cell = APPLE_ACCOUNT.get();
if let Some(account) = cell {
let mut account_guard = account.lock().unwrap();
*account_guard = None;
}
}
================================================
FILE: src-tauri/src/sideloader/apple_commands.rs
================================================
use isideload::developer_session::{DeveloperDeviceType, ListAppIdsResponse};
use keyring::{Entry, Error as KeyringError};
use serde::{Deserialize, Serialize};
use tauri::Manager;
use crate::sideloader::apple::APPLE_ACCOUNT;
pub fn store_credentials(email: &str, password: &str) -> Result<(), KeyringError> {
let email_entry = Entry::new("crosscode", "apple_id_email")?;
email_entry.set_password(email)?;
let pass_entry = Entry::new("crosscode", email)?;
pass_entry.set_password(password)
}
pub fn get_stored_credentials() -> Option<(String, String)> {
let email_entry = Entry::new("crosscode", "apple_id_email").ok()?;
let email = email_entry.get_password().ok()?;
let pass_entry = Entry::new("crosscode", &email).ok()?;
let password = pass_entry.get_password().ok()?;
Some((email, password))
}
#[tauri::command]
pub fn get_apple_email() -> String {
let credentials = get_stored_credentials();
if credentials.is_none() {
return "".to_string();
}
let (email, _) = credentials.unwrap();
email
}
#[tauri::command]
pub fn delete_stored_credentials() -> Result<(), String> {
let email_entry =
Entry::new("crosscode", "apple_id_email").map_err(|e| format!("Keyring error: {:?}", e))?;
let email = match email_entry.get_password() {
Ok(email) => email,
Err(_) => {
return Ok(());
}
};
let pass_entry =
Entry::new("crosscode", &email).map_err(|e| format!("Keyring error: {:?}", e))?;
pass_entry
.delete_password()
.map_err(|e| format!("Keyring error: {:?}", e))?;
email_entry
.delete_password()
.map_err(|e| format!("Keyring error: {:?}", e))?;
if let Some(account) = APPLE_ACCOUNT.get() {
let mut account_guard = account.lock().unwrap();
*account_guard = None;
}
Ok(())
}
#[tauri::command]
pub async fn reset_anisette(handle: tauri::AppHandle) -> Result<(), String> {
let config_dir = handle.path().app_config_dir().map_err(|e| e.to_string())?;
let status_path = config_dir.join("state.plist");
if status_path.exists() {
std::fs::remove_file(&status_path).map_err(|e| e.to_string())?;
}
Ok(())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CertificateInfo {
pub name: String,
pub certificate_id: String,
pub serial_number: String,
pub machine_name: String,
}
#[tauri::command]
pub async fn get_certificates(
handle: tauri::AppHandle,
window: tauri::Window,
anisette_server: String,
) -> Result, String> {
let dev_session =
crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())
.await?;
let team = dev_session
.get_team()
.await
.map_err(|e| format!("Failed to get developer team: {:?}", e))?;
let certificates = dev_session
.list_all_development_certs(DeveloperDeviceType::Ios, &team)
.await
.map_err(|e| format!("Failed to get development certificates: {:?}", e))?;
Ok(certificates
.into_iter()
.map(|cert| CertificateInfo {
name: cert.name,
certificate_id: cert.certificate_id,
serial_number: cert.serial_number,
machine_name: cert.machine_name,
})
.collect())
}
#[tauri::command]
pub async fn revoke_certificate(
handle: tauri::AppHandle,
window: tauri::Window,
anisette_server: String,
serial_number: String,
) -> Result<(), String> {
let dev_session =
crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())
.await?;
let team = dev_session
.get_team()
.await
.map_err(|e| format!("Failed to get developer team: {:?}", e))?;
dev_session
.revoke_development_cert(DeveloperDeviceType::Ios, &team, &serial_number)
.await
.map_err(|e| format!("Failed to revoke development certificates: {:?}", e))?;
Ok(())
}
#[tauri::command]
pub async fn list_app_ids(
handle: tauri::AppHandle,
window: tauri::Window,
anisette_server: String,
) -> Result {
let dev_session =
crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())
.await?;
let team = dev_session
.get_team()
.await
.map_err(|e| format!("Failed to get developer team: {:?}", e))?;
let app_ids = dev_session
.list_app_ids(DeveloperDeviceType::Ios, &team)
.await
.map_err(|e| format!("Failed to list App IDs: {:?}", e))?;
Ok(app_ids)
}
#[tauri::command]
pub async fn delete_app_id(
handle: tauri::AppHandle,
window: tauri::Window,
anisette_server: String,
app_id_id: String,
) -> Result<(), String> {
let dev_session =
crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())
.await?;
let team = dev_session
.get_team()
.await
.map_err(|e| format!("Failed to get developer team: {:?}", e))?;
dev_session
.delete_app_id(DeveloperDeviceType::Ios, &team, app_id_id)
.await
.map_err(|e| format!("Failed to delete App ID: {:?}", e))?;
Ok(())
}
================================================
FILE: src-tauri/src/sideloader/device.rs
================================================
use std::path::PathBuf;
use idevice::{
lockdown::LockdownClient,
mobile_image_mounter::ImageMounter,
provider::UsbmuxdProvider,
usbmuxd::{UsbmuxdAddr, UsbmuxdConnection},
IdeviceService,
};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, Manager, Window};
const BUILD_MANIFEST_URL: &str =
"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/PersonalizedImages/Xcode_iOS_DDI_Personalized/BuildManifest.plist";
const PERSONALIZED_IMAGE_URL: &str =
"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/PersonalizedImages/Xcode_iOS_DDI_Personalized/Image.dmg";
const TRUST_CACHE_URL: &str = "https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/PersonalizedImages/Xcode_iOS_DDI_Personalized/Image.dmg.trustcache";
#[derive(Deserialize, Serialize, Clone)]
pub struct DeviceInfo {
pub name: String,
pub id: u32,
pub uuid: String,
}
pub async fn list_devices() -> Result, String> {
let usbmuxd = UsbmuxdConnection::default().await;
if usbmuxd.is_err() {
eprintln!("Failed to connect to usbmuxd: {:?}", usbmuxd.err());
return Err("Failed to connect to usbmuxd".to_string());
}
let mut usbmuxd = usbmuxd.unwrap();
let devs = usbmuxd.get_devices().await.unwrap();
if devs.is_empty() {
return Ok(vec![]);
}
let device_info_futures: Vec<_> = devs
.iter()
.map(|d| async move {
let provider = d.to_provider(UsbmuxdAddr::from_env_var().unwrap(), "crosscode");
let device_uid = d.device_id;
let mut lockdown_client = match LockdownClient::connect(&provider).await {
Ok(l) => l,
Err(e) => {
eprintln!("Unable to connect to lockdown: {e:?}");
return DeviceInfo {
name: String::from("Unknown Device"),
id: device_uid,
uuid: d.udid.clone(),
};
}
};
let device_name = lockdown_client
.get_value(Some("DeviceName"), None)
.await
.expect("Failed to get device name")
.as_string()
.expect("Failed to convert device name to string")
.to_string();
DeviceInfo {
name: device_name,
id: device_uid,
uuid: d.udid.clone(),
}
})
.collect();
Ok(futures::future::join_all(device_info_futures).await)
}
pub async fn get_provider(device: &DeviceInfo) -> Result {
let mut usbmuxd = UsbmuxdConnection::default()
.await
.map_err(|e| format!("Failed to connect to usbmuxd: {}", e))?;
let device_info = usbmuxd
.get_device(&device.uuid)
.await
.map_err(|e| format!("Failed to get device: {}", e))?;
let provider = device_info.to_provider(UsbmuxdAddr::from_env_var().unwrap(), "crosscode");
Ok(provider)
}
#[tauri::command]
pub async fn is_ddi_mounted(device: DeviceInfo) -> Result {
let provider = get_provider(&device).await?;
let mut mounter_client = ImageMounter::connect(&provider).await.map_err(|e| {
format!(
"Failed to connect to mobile image mounter on device {}: {}",
device.name, e
)
})?;
let devices = mounter_client.copy_devices().await.map_err(|e| {
format!(
"Failed to get mounted images on device {}: {}",
device.name, e
)
})?;
Ok(devices.len() > 0)
}
// https://github.com/jkcoxson/idevice/blob/master/tools/src/mounter.rs
#[tauri::command]
pub async fn mount_ddi(app: AppHandle, window: Window, device: DeviceInfo) -> Result<(), String> {
let provider = get_provider(&device).await?;
let mut mounter_client = ImageMounter::connect(&provider).await.map_err(|e| {
format!(
"Failed to connect to mobile image mounter on device {}: {}",
device.name, e
)
})?;
let mut lockdown_client = LockdownClient::connect(&provider)
.await
.map_err(|e| format!("Failed to connect to lockdown: {}", e))?;
let product_version = lockdown_client
.get_value(Some("ProductVersion"), None)
.await
.map_err(|e| format!("Failed to get product version: {}", e))?;
let product_version = product_version
.as_string()
.ok_or("Unexpected value for ProductVersion")?;
let product_version_num = product_version.split('.').collect::>()[0]
.parse::()
.map_err(|e| format!("Failed to parse product version: {}", e))?;
if product_version_num < 17 {
// make sure product version is x.x, trimming the final .x if it exists
let product_version = if product_version.matches('.').count() > 1 {
let mut parts = product_version.split('.').collect::>();
parts.pop();
parts.join(".")
} else {
product_version.to_string()
};
let (image, signature) = download_ddi(&app, &product_version).await?;
let image = tokio::fs::read(image)
.await
.map_err(|e| format!("Unable to read image: {}", e))?;
let signature = tokio::fs::read(signature)
.await
.map_err(|e| format!("Unable to read signature: {}", e))?;
mounter_client
.mount_developer(&image, signature)
.await
.map_err(|e| format!("Unable to mount: {}", e))?;
} else {
let (manifest, trust_cache, image) = download_personalized_image(&app).await?;
let image = tokio::fs::read(image)
.await
.map_err(|e| format!("Unable to read image: {}", e))?;
let build_manifest = &tokio::fs::read(manifest)
.await
.map_err(|e| format!("Unable to read build manifest: {}", e))?;
let trust_cache = tokio::fs::read(trust_cache)
.await
.map_err(|e| format!("Unable to read trust cache: {}", e))?;
let unique_chip_id = lockdown_client
.get_value(Some("UniqueChipID"), None)
.await
.map_err(|e| format!("Failed to get UniqueChipID: {}", e))?
.as_unsigned_integer()
.ok_or("Unexpected value for UniqueChipID")?;
mounter_client
.mount_personalized_with_callback(
&provider,
image,
trust_cache,
build_manifest,
None,
unique_chip_id,
async |((n, d), _)| {
let percent = (n as f64 / d as f64) * 100.0;
window
.emit("ddi-mount-progress", percent)
.unwrap_or_else(|e| {
eprintln!("Failed to emit ddi-mount-progress: {}", e);
});
},
(),
)
.await
.map_err(|e| format!("Unable to mount image: {}", e))?;
}
Ok(())
}
pub async fn download_ddi(
app: &AppHandle,
product_version: &str,
) -> Result<(PathBuf, PathBuf), String> {
let config_dir = app.path().app_config_dir().map_err(|e| e.to_string())?;
let ddi_path = config_dir.join("DDI");
let image_path = ddi_path.join("DeveloperDiskImage.dmg");
let sig_path = ddi_path.join("DeveloperDiskImage.dmg.signature");
if !ddi_path.exists() {
tokio::fs::create_dir_all(&ddi_path)
.await
.map_err(|e| format!("Failed to create DDI directory: {}", e))?;
}
let mut download_futures = vec![];
if !image_path.exists() {
let url = format!(
"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/DeveloperDiskImages/{}/DeveloperDiskImage.dmg",
product_version
);
download_futures.push(download(url, &image_path));
}
if !sig_path.exists() {
let url = format!(
"https://github.com/doronz88/DeveloperDiskImage/raw/refs/heads/main/DeveloperDiskImages/{}/DeveloperDiskImage.dmg.signature",
product_version
);
download_futures.push(download(url, &sig_path));
}
futures::future::join_all(download_futures).await;
return Ok((image_path, sig_path));
}
pub async fn download_personalized_image(
app: &AppHandle,
) -> Result<(PathBuf, PathBuf, PathBuf), String> {
let config_dir = app.path().app_config_dir().map_err(|e| e.to_string())?;
let ddi_path = config_dir.join("DDI");
let build_manifest_path = ddi_path.join("BuildManifest.plist");
let trust_cache_path = ddi_path.join("Image.dmg.trustcache");
let image_path = ddi_path.join("Image.dmg");
if !ddi_path.exists() {
tokio::fs::create_dir_all(&ddi_path)
.await
.map_err(|e| format!("Failed to create DDI directory: {}", e))?;
}
let mut download_futures = vec![];
if !build_manifest_path.exists() {
download_futures.push(download(BUILD_MANIFEST_URL, &build_manifest_path));
}
if !trust_cache_path.exists() {
download_futures.push(download(TRUST_CACHE_URL, &trust_cache_path));
}
if !image_path.exists() {
download_futures.push(download(PERSONALIZED_IMAGE_URL, &image_path));
}
futures::future::join_all(download_futures).await;
return Ok((build_manifest_path, trust_cache_path, image_path));
}
pub async fn download(url: impl AsRef, dest: &PathBuf) -> Result<(), String> {
let response = reqwest::get(url.as_ref())
.await
.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!(
"Failed to download file: HTTP {}",
response.status()
));
}
let bytes = response.bytes().await.map_err(|e| e.to_string())?;
tokio::fs::write(dest, &bytes)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
================================================
FILE: src-tauri/src/sideloader/mod.rs
================================================
pub mod apple;
pub mod apple_commands;
pub mod device;
pub mod screenshot;
pub mod sideload;
pub mod stdout;
pub mod syslog;
================================================
FILE: src-tauri/src/sideloader/screenshot.rs
================================================
use idevice::{
core_device_proxy::CoreDeviceProxy,
dvt::{remote_server::RemoteServerClient, screenshot::ScreenshotClient},
rsd::RsdHandshake,
IdeviceService,
};
use crate::sideloader::device::{get_provider, DeviceInfo};
#[tauri::command]
pub async fn take_screenshot(device: DeviceInfo) -> Result, String> {
let provider = get_provider(&device).await?;
let proxy = CoreDeviceProxy::connect(&provider)
.await
.map_err(|e| format!("Failed to connect to device proxy: {}", e))?;
let rsd_port = proxy.handshake.server_rsd_port;
let adapter = proxy
.create_software_tunnel()
.map_err(|e| format!("Failed to create software tunnel: {}", e))?;
let mut adapter = adapter.to_async_handle();
let rsd_stream = adapter
.connect(rsd_port)
.await
.map_err(|e| format!("Failed to connect to RSD: {}", e))?;
let handshake = RsdHandshake::new(rsd_stream)
.await
.map_err(|e| format!("Failed to create RSD handshake: {}", e))?;
let instruments_service = handshake
.services
.get("com.apple.instruments.dtservicehub")
.ok_or("Instruments service not found")?;
let ts_client_stream = adapter
.connect(instruments_service.port)
.await
.map_err(|e| format!("Failed to connect to remote server: {}", e))?;
let mut ts_client = RemoteServerClient::new(ts_client_stream);
ts_client
.read_message(0)
.await
.map_err(|e| format!("Failed to read message: {}", e))?;
let mut sc = ScreenshotClient::new(&mut ts_client)
.await
.map_err(|e| format!("Failed to create screenshot client: {}", e))?;
let screenshot_data = sc
.take_screenshot()
.await
.map_err(|e| format!("Failed to take screenshot: {}", e))?;
Ok(screenshot_data)
}
================================================
FILE: src-tauri/src/sideloader/sideload.rs
================================================
use std::{path::PathBuf, sync::Arc};
use crate::sideloader::device::{get_provider, list_devices, DeviceInfo};
use isideload::{sideload, Error, SideloadConfiguration, SideloadLogger};
use tauri::{Emitter, Manager, Window};
pub struct TauriLogger {
window: Arc,
}
impl SideloadLogger for TauriLogger {
fn log(&self, message: &str) {
self.window.emit("build-output", message.to_string()).ok();
}
fn error(&self, error: &Error) {
self.window
.emit("build-output", format!("Error: {}", error))
.ok();
}
}
pub async fn sideload_app(
handle: &tauri::AppHandle,
window: &tauri::Window,
anisette_server: String,
device: DeviceInfo,
app_path: PathBuf,
) -> Result<(), String> {
let dev_session =
crate::sideloader::apple::get_developer_session(&handle, &window, anisette_server.clone())
.await?;
let logger = TauriLogger {
window: Arc::new(window.clone()),
};
let store_dir = handle.path().app_config_dir().map_err(|e| e.to_string())?;
let config = SideloadConfiguration::new()
.set_store_dir(store_dir.clone())
.set_logger(&logger)
.set_machine_name("CrossCode".to_string());
let provider = get_provider(&device).await?;
sideload::sideload_app(&provider, &dev_session, app_path, config)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
#[tauri::command]
pub async fn refresh_idevice(window: tauri::Window) {
match list_devices().await {
Ok(devices) => {
window
.emit("idevices", devices)
.expect("Failed to send devices");
}
Err(e) => {
window
.emit("idevices", Vec::::new())
.expect("Failed to send error");
eprintln!("Failed to list devices: {}", e);
}
};
}
================================================
FILE: src-tauri/src/sideloader/stdout.rs
================================================
use crate::{
builder::config::TomlConfig,
sideloader::{
apple::get_developer_session,
device::{get_provider, DeviceInfo},
},
};
use idevice::{
core_device::{AppServiceClient, OpenStdioSocketClient},
core_device_proxy::CoreDeviceProxy,
rsd::RsdHandshake,
IdeviceService, RsdService,
};
use std::{path::PathBuf, sync::Arc};
use tauri::{AppHandle, Emitter, State, Window};
use tokio::{io::AsyncReadExt, sync::Mutex};
use tokio_util::sync::CancellationToken;
pub type StdoutStream = Arc>>;
#[tauri::command]
pub async fn start_stream_stdout(
handle: AppHandle,
window: Window,
device: DeviceInfo,
stream: State<'_, StdoutStream>,
folder: String,
anisette_server: String,
) -> Result<(), String> {
let bundle_id = get_bundle_id(&handle, &window, anisette_server, folder).await?;
let mut stream_guard = stream.lock().await;
if let Some(token) = stream_guard.take() {
token.cancel();
}
let provider = get_provider(&device).await?;
let proxy = CoreDeviceProxy::connect(&provider)
.await
.map_err(|e| format!("Failed to connect to device proxy: {}", e))?;
let rsd_port = proxy.handshake.server_rsd_port;
let adapter = proxy
.create_software_tunnel()
.map_err(|e| format!("Failed to create software tunnel: {}", e))?;
let mut adapter = adapter.to_async_handle();
let rsd_stream = adapter
.connect(rsd_port)
.await
.map_err(|e| format!("Failed to connect to RSD: {}", e))?;
let mut handshake = RsdHandshake::new(rsd_stream)
.await
.map_err(|e| format!("Failed to create RSD handshake: {}", e))?;
let mut stdio_conn = OpenStdioSocketClient::connect_rsd(&mut adapter, &mut handshake)
.await
.map_err(|e| format!("Failed to connect to stdio: {}", e))?;
let stdio_uuid = stdio_conn
.read_uuid()
.await
.map_err(|e| format!("Failed to read stdio UUID: {}", e))?;
use tokio::sync::oneshot;
let (tx, rx) = oneshot::channel();
let mut adapter_for_launch = adapter;
std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let result = rt.block_on(async {
let mut asc: AppServiceClient> =
AppServiceClient::connect_rsd(&mut adapter_for_launch, &mut handshake)
.await
.map_err(|e| format!("Failed to connect to app service: {}", e))?;
asc.launch_application(bundle_id, &[], true, false, None, None, Some(stdio_uuid))
.await
.map_err(|e| format!("Failed to launch application: {}", e))
});
let _ = tx.send(result);
});
rx.await.map_err(|_| "Launch thread failed".to_string())??;
let cancellation_token = CancellationToken::new();
*stream_guard = Some(cancellation_token.clone());
let stream_clone = stream.inner().clone();
tokio::spawn(async move {
loop {
tokio::select! {
_ = cancellation_token.cancelled() => {
println!("Stdout stream cancelled");
break;
}
result = async {
let mut buffer = [0u8; 1024];
let n = stdio_conn.inner.read(&mut buffer).await?;
Ok::<_, std::io::Error>(buffer[..n].to_vec())
} => {
match result {
Ok(data) => {
if !data.is_empty() {
if let Ok(log_str) = String::from_utf8(data) {
window.emit("stdout-message", log_str).unwrap_or_else(|e| {
eprintln!("Failed to emit stdout message: {}", e);
});
}
}
}
Err(e) => {
eprintln!("Error reading from stdio: {}", e);
window.emit("stdout-message", "stdout.done").unwrap_or_else(|e| {
eprintln!("Failed to emit stdout error: {}", e);
});
break;
}
}
}
}
}
let mut stream_guard = stream_clone.lock().await;
*stream_guard = None;
});
Ok(())
}
async fn get_bundle_id(
handle: &AppHandle,
window: &Window,
anisette_server: String,
folder: String,
) -> Result {
let config = TomlConfig::load_or_default(PathBuf::from(folder))?;
let bundle_id = config.project.bundle_id;
let session = get_developer_session(handle, window, anisette_server).await?;
let team_id = session
.get_team()
.await
.map_err(|e| format!("Failed to get team: {:?}", e))?
.team_id;
Ok(format!("{}.{}", bundle_id, team_id))
}
#[tauri::command]
pub async fn stop_stream_stdout(stream: State<'_, StdoutStream>) -> Result<(), String> {
let mut stream_guard = stream.lock().await;
if let Some(token) = stream_guard.take() {
token.cancel();
Ok(())
} else {
Err("No active stdout stream found".to_string())
}
}
#[tauri::command]
pub async fn is_streaming_stdout(stream: State<'_, StdoutStream>) -> Result {
let stream_guard = stream.lock().await;
Ok(stream_guard.is_some())
}
================================================
FILE: src-tauri/src/sideloader/syslog.rs
================================================
use crate::sideloader::device::{get_provider, DeviceInfo};
use idevice::{syslog_relay::SyslogRelayClient, IdeviceService};
use std::sync::Arc;
use tauri::{Emitter, State, Window};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
pub struct SyslogStream(pub Arc>>);
#[tauri::command]
pub async fn start_stream_syslog(
window: Window,
device: DeviceInfo,
stream: State<'_, SyslogStream>,
) -> Result<(), String> {
let mut stream_guard = stream.0.lock().await;
if let Some(token) = stream_guard.take() {
token.cancel();
}
let provider = get_provider(&device).await?;
let mut relay_client = SyslogRelayClient::connect(&provider)
.await
.map_err(|e| format!("Failed to connect to syslog relay: {}", e))?;
let cancellation_token = CancellationToken::new();
*stream_guard = Some(cancellation_token.clone());
let stream_clone = stream.0.clone();
tokio::spawn(async move {
loop {
tokio::select! {
_ = cancellation_token.cancelled() => {
println!("Syslog stream cancelled");
break;
}
message_result = relay_client.next() => {
match message_result {
Ok(message) => {
if let Err(e) = window.emit("syslog-message", &message) {
eprintln!("Failed to emit syslog message: {}", e);
break;
}
}
Err(e) => {
eprintln!("Error reading syslog message: {}", e);
let _ = window.emit("syslog-message", format!("Error reading syslog: {}", e));
break;
}
}
}
}
}
let mut stream_guard = stream_clone.lock().await;
*stream_guard = None;
});
Ok(())
}
#[tauri::command]
pub async fn stop_stream_syslog(stream: State<'_, SyslogStream>) -> Result<(), String> {
let mut stream_guard = stream.0.lock().await;
if let Some(token) = stream_guard.take() {
token.cancel();
Ok(())
} else {
Err("No active syslog stream found".to_string())
}
}
#[tauri::command]
pub async fn is_streaming_syslog(stream: State<'_, SyslogStream>) -> Result {
let stream_guard = stream.0.lock().await;
Ok(stream_guard.is_some())
}
================================================
FILE: src-tauri/src/sourcekit_lsp.rs
================================================
use futures_util::{SinkExt, StreamExt};
use serde::Serialize;
use std::sync::Arc;
use tauri::{Emitter, State, Window};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::process::Child;
use tokio::sync::{broadcast, mpsc, RwLock};
use tokio_tungstenite::{accept_async, tungstenite::Message, WebSocketStream};
use crate::builder::swift::{validate_toolchain, SwiftBin};
#[derive(Debug, Clone, Serialize)]
pub struct ServerStatus {
pub is_running: bool,
pub port: Option,
pub connected_clients: usize,
}
pub struct SourceKitServer {
pub process: Option,
pub websocket_listener: Option,
pub status: ServerStatus,
pub abort_handles: Vec,
}
impl SourceKitServer {
pub fn new() -> Self {
Self {
process: None,
websocket_listener: None,
status: ServerStatus {
is_running: false,
port: None,
connected_clients: 0,
},
abort_handles: Vec::new(),
}
}
}
pub type ServerState = Arc>;
#[tauri::command]
pub async fn start_sourcekit_server(
window: Window,
state: State<'_, ServerState>,
toolchain_path: String,
folder: String,
) -> Result {
let mut server = state.write().await;
if server.status.is_running {
return Err("Server is already running".to_string());
}
if !validate_toolchain(&toolchain_path) {
return Err(format!("Invalid toolchain path: {}", toolchain_path));
}
let swift_bin = SwiftBin::new(&toolchain_path)?;
let mut child = swift_bin
.sourcekit_command()
.current_dir(folder)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| format!("Failed to start sourcekit-lsp: {}", e))?;
let mut stdin = child.stdin.take().ok_or("Failed to get stdin")?;
let stdout = child.stdout.take().ok_or("Failed to get stdout")?;
let listener = TcpListener::bind("127.0.0.1:0")
.await
.map_err(|e| format!("Failed to bind WebSocket server: {}", e))?;
let actual_port = listener
.local_addr()
.map_err(|e| format!("Failed to get server address: {}", e))?
.port();
let (to_lsp_tx, mut to_lsp_rx) = mpsc::unbounded_channel::();
let (from_lsp_tx, _from_lsp_rx) = broadcast::channel::(100);
let state_clone = state.inner().clone();
let ws_state = state_clone.clone();
let ws_to_lsp = to_lsp_tx.clone();
let ws_from_lsp = from_lsp_tx.subscribe();
let ws_task = tokio::spawn(async move {
handle_websocket_connections(listener, ws_state, ws_to_lsp, ws_from_lsp).await;
});
let stdin_task = tokio::spawn(async move {
while let Some(message) = to_lsp_rx.recv().await {
let packet = if message.starts_with("Content-Length:") {
message
} else {
format!("Content-Length: {}\r\n\r\n{}", message.len(), message)
};
if let Err(e) = stdin.write_all(packet.as_bytes()).await {
eprintln!("Failed to write to sourcekit-lsp stdin: {}", e);
break;
}
if let Err(e) = stdin.flush().await {
eprintln!("Failed to flush sourcekit-lsp stdin: {}", e);
break;
}
}
});
let stdout_task = tokio::spawn(async move {
let mut reader = BufReader::new(stdout);
let mut buffer = String::new();
loop {
buffer.clear();
let mut content_length = 0;
loop {
buffer.clear();
match reader.read_line(&mut buffer).await {
Ok(0) => return,
Ok(_) => {
let line = buffer.trim();
if line.is_empty() {
break;
} else if line.starts_with("Content-Length:") {
if let Some(length_str) = line.strip_prefix("Content-Length:") {
content_length = length_str.trim().parse::().unwrap_or(0);
}
}
}
Err(e) => {
eprintln!("Failed to read LSP headers: {}", e);
return;
}
}
}
if content_length == 0 {
continue;
}
let mut content = vec![0u8; content_length];
match reader.read_exact(&mut content).await {
Ok(_) => {
let message = String::from_utf8_lossy(&content).to_string();
window
.emit("lsp-message", message.clone())
.unwrap_or_default();
if let Err(_) = from_lsp_tx.send(message) {
// No receivers, continue
}
}
Err(e) => {
eprintln!("Failed to read LSP content: {}", e);
break;
}
}
}
});
server.abort_handles.push(ws_task.abort_handle());
server.abort_handles.push(stdin_task.abort_handle());
server.abort_handles.push(stdout_task.abort_handle());
server.process = Some(child);
server.status.is_running = true;
server.status.port = Some(actual_port);
Ok(actual_port)
}
async fn handle_websocket_connections(
listener: TcpListener,
state: ServerState,
to_lsp_tx: mpsc::UnboundedSender