Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai e1f466e988 feat(mobile): pair a phone with the desktop and work on its projects
A Tauri iOS app (mobile/) pairs with the desktop over iroh (crates/ide-pair) by
scanning a QR code from Pair Mobile Device, then runs every command on the desktop
through the remote-development JSON-RPC. The phone gets a touch shell: a bottom
bar the user arranges, a nav bar for sub-pages, a phone layout for Agents, read
mode with a pencil to edit in the editor, sheets for dialogs, and popups that stay
above the keyboard.
2026-11-23 12:38:19 +08:00
172 змінених файлів з 16990 додано та 271 видалено

No files matched your search

+1
Переглянути файл
@@ -44,3 +44,4 @@ CLAUDE.local.md
# Local reference screenshots
pycharm-screenshots/
dist-phone
+1
Переглянути файл
@@ -7,6 +7,7 @@
"sortPackageJson": false,
"ignorePatterns": [
"dist",
"mobile/gen",
"target",
"src/bindings.ts",
"docs/snippets/plugin-catalog.jsx",
Створено
+1179 -75
File diff suppressed because it is too large. Load diff
+2 -1
Переглянути файл
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["crates/*", "src-tauri"]
members = ["crates/*", "src-tauri", "mobile"]
# Plugins and the guest SDK build for wasm32-wasip2 in their own workspaces.
exclude = ["sdk", "plugins"]
@@ -21,6 +21,7 @@ ide-index = { path = "crates/ide-index" }
ide-syntax = { path = "crates/ide-syntax" }
ide-search = { path = "crates/ide-search" }
ide-jsonrpc = { path = "crates/ide-jsonrpc" }
ide-pair = { path = "crates/ide-pair" }
ide-lsp = { path = "crates/ide-lsp" }
ide-dap = { path = "crates/ide-dap" }
ide-vcs = { path = "crates/ide-vcs" }
+2
Переглянути файл
@@ -38,6 +38,8 @@ pub enum IdeEvent {
WindowGroupsChanged,
/// A project was loaded or unloaded for the MCP server without a window of its own.
McpBackgroundProjectsChanged,
/// A phone paired with this desktop, connected, disconnected or was removed.
MobileDevicesChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection to its host ended on its own (network loss, the host or
+1
Переглянути файл
@@ -78,6 +78,7 @@ zip.workspace = true
quick-xml = "0.42"
[dev-dependencies]
ide-pair = { workspace = true, features = ["testing"] }
ide-ssh = { workspace = true, features = ["testing"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] }
criterion = { version = "0.5", default-features = false }
+5
Переглянути файл
@@ -255,6 +255,11 @@ impl Host {
}
/// The project of `window` (or of the window owning it).
/// The windows that have a project open.
pub fn windows(&self) -> Vec<String> {
self.projects.read().keys().cloned().collect()
}
pub fn project(&self, window: &str) -> IdeResult<Arc<Project>> {
self.projects
.read()
+49 -3
Переглянути файл
@@ -129,6 +129,23 @@ impl Dispatcher {
self
}
/// Also runs `then` (with the host and the call's window) after each successful call of
/// `name`, when it is registered.
pub fn after(&mut self, name: &str, then: impl Fn(&Arc<Host>, &str) + Send + Sync + 'static) -> &mut Self {
let Some((_, slot)) = self.handlers.get_mut(name) else { return self };
let (inner, then) = (slot.clone(), Arc::new(then));
*slot = Arc::new(move |call: Call| {
let (host, window) = (call.host.clone(), call.window.clone());
let (fut, then) = (inner(call), then.clone());
Box::pin(async move {
let value = fut.await?;
then(&host, &window);
Ok(value)
})
});
self
}
pub fn commands(&self) -> Vec<&'static str> {
let mut out: Vec<_> = self.handlers.keys().copied().collect();
out.sort_unstable();
@@ -155,13 +172,32 @@ where
R: tokio::io::AsyncRead + Unpin + Send + 'static,
W: tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let handler = Arc::new(ServerHandler { host: host.clone(), dispatcher, peer: peer.clone() });
serve_scoped(host, dispatcher, peer, reader, writer, None).await;
}
/// Like [`serve`], for a client that shares `host` with others (a phone paired with the
/// desktop): it may only name windows starting with `scope`, and on disconnect only
/// those windows' reports are forgotten. Without a scope the client owns the host.
pub async fn serve_scoped<R, W>(
host: Arc<Host>,
dispatcher: Dispatcher,
peer: Arc<OnceLock<Peer>>,
reader: R,
writer: W,
scope: Option<String>,
) where
R: tokio::io::AsyncRead + Unpin + Send + 'static,
W: tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let handler = Arc::new(ServerHandler { host: host.clone(), dispatcher, peer: peer.clone(), scope: scope.clone() });
let p = Peer::connect(reader, writer, handler);
let _ = peer.set(p.clone());
p.closed().await;
// Reports belong to the disconnected desktop, even while the host shuts down.
// Reports belong to the disconnected client, even while the host shuts down.
for window in host.projects.read().keys() {
host.mcp_reports.forget_window(window);
if scope.as_deref().is_none_or(|s| window.starts_with(s)) {
host.mcp_reports.forget_window(window);
}
}
}
@@ -178,6 +214,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
match event {
IdeEvent::WindowGroupsChanged
| IdeEvent::McpBackgroundProjectsChanged
| IdeEvent::MobileDevicesChanged
| IdeEvent::WindowFullscreenChanged
| IdeEvent::RemoteConnectionLost { .. }
| IdeEvent::UpdateStatusChanged { .. }
@@ -233,6 +270,8 @@ struct ServerHandler {
host: Arc<Host>,
dispatcher: Dispatcher,
peer: Arc<OnceLock<Peer>>,
/// The prefix of the windows this client may name (see [`serve_scoped`]).
scope: Option<String>,
}
pub fn server_info() -> ServerInfo {
@@ -256,6 +295,12 @@ impl Handler for ServerHandler {
"invoke" => {
let call: Invoke =
serde_json::from_value(params).map_err(|e| (codes::INVALID_PARAMS, e.to_string()))?;
if self.scope.as_deref().is_some_and(|s| !call.window.starts_with(s)) {
return Err(error_reply(IdeError::new(
ide_core::error::ErrorKind::PermissionDenied,
format!("window {} belongs to another client", call.window),
)));
}
let Some((trust, handler)) = self.dispatcher.handlers.get(call.cmd.as_str()).cloned() else {
return Err((codes::METHOD_NOT_FOUND, format!("command {} is not available remotely", call.cmd)));
};
@@ -326,6 +371,7 @@ mod tests {
IdeEvent::WindowGroupsChanged,
IdeEvent::WindowFullscreenChanged,
IdeEvent::McpBackgroundProjectsChanged,
IdeEvent::MobileDevicesChanged,
] {
assert!(!client_accepts(&event, true), "{event:?}");
}
+119
Переглянути файл
@@ -0,0 +1,119 @@
//! A phone paired over iroh drives the desktop's backend: it pairs with a ticket's code,
//! opens a project in a window of its own and gets that window's events back, the way
//! `src-tauri/src/mobile.rs` wires `ide_pair` to `rpc::serve_scoped`.
use ide_host::rpc::{self, Dispatcher, EventMessage, Invoke};
use ide_host::{Host, HostConfig};
use ide_jsonrpc::{Handler, Peer};
use ide_pair::{DeviceStore, Listener, SessionHandler};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
#[derive(Default)]
struct Phone {
events: Mutex<Vec<EventMessage>>,
}
impl Handler for Phone {
fn on_notification(&self, method: &str, params: Value) {
if method == "event" {
self.events.lock().push(serde_json::from_value(params).unwrap());
}
}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
type Peers = Arc<Mutex<HashMap<String, Arc<OnceLock<Peer>>>>>;
fn scope_for(id: &str) -> String {
format!("mobile-{}-", &id[..12])
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_paired_phone_opens_a_project_on_the_desktop_and_gets_its_events() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("demo");
std::fs::create_dir_all(&project).unwrap();
let base = tmp.path().join("desktop");
// The desktop: one host, its phones' windows routed to their connections.
let peers: Peers = Peers::default();
let sink_peers = peers.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |w| {
let scope = w.splitn(3, '-').take(2).collect::<Vec<_>>().join("-") + "-";
let peer = sink_peers.lock().entry(scope).or_default().clone();
rpc::event_sink(peer, Some(w.to_owned()))
}),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let serving_host = host.clone();
let serving_peers = peers.clone();
let handler: SessionHandler = Arc::new(move |session| {
let host = serving_host.clone();
let peers = serving_peers.clone();
Box::pin(async move {
let scope = scope_for(&session.device.id);
let peer = Arc::new(OnceLock::new());
peers.lock().insert(scope.clone(), peer.clone());
rpc::serve_scoped(host, Dispatcher::standard(), peer, session.recv, session.send, Some(scope)).await;
})
});
let listener = Listener::start(
ide_pair::bind_local(true).await,
DeviceStore::load(base.join("config").join("mobile-devices.json")),
"Workstation".into(),
handler,
Arc::new(|| {}),
);
let ticket = listener.ticket(Duration::from_secs(60)).await.0;
// The phone scans the ticket.
let scanned = ide_pair::Ticket::decode(&ticket.encode()).unwrap();
let phone = ide_pair::bind_local(false).await;
let (_conn, welcome, send, recv) =
ide_pair::connect(&phone, scanned.addr, "Pixel", Some(&scanned.code)).await.unwrap();
assert_eq!(welcome.desktop, "Workstation");
let client = Arc::new(Phone::default());
let peer = Peer::connect(recv, send, client.clone());
let window = format!("{}1", scope_for(&phone.id().to_string()));
let invoke = |cmd: &str, args: Value| Invoke { window: window.clone(), cmd: cmd.into(), args };
let opened: Value = peer.request("invoke", invoke("open_project", json!({ "path": project })), None).await.unwrap();
assert_eq!(opened["name"], "demo");
let file = project.join("notes.txt");
std::fs::write(&file, "old").unwrap();
let edit = json!({ "files": [{ "kind": "edit", "path": file, "edits": [{
"range": { "start": { "line": 0, "col": 0 }, "end": { "line": 0, "col": 3 } },
"new_text": "new"
}] }] });
let prepared: Value =
peer.request("invoke", invoke("prepare_workspace_edit", json!({ "edit": edit })), None).await.unwrap();
let _: Value =
peer.request("invoke", invoke("apply_workspace_edit", json!({ "edit": prepared })), None).await.unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "new");
for _ in 0..500 {
let got = client.events.lock().iter().any(|e| {
e.window.as_deref() == Some(window.as_str())
&& matches!(e.event, ide_core::IdeEvent::WorkspaceEditApplied { .. })
});
if got {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("the phone got no event for its window");
}
+39
Переглянути файл
@@ -687,3 +687,42 @@ async fn serves_builtin_mcp_over_remote_dispatch_and_routes_ui_requests() {
invoke(&peer, "close_project", json!({})).await.unwrap();
peer.kill();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_scoped_client_only_reaches_its_own_windows() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("demo");
std::fs::create_dir_all(&project).unwrap();
let base = tmp.path().join("host");
let peer_slot = Arc::new(OnceLock::new());
let sink_peer = peer_slot.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
// A window of the desktop itself.
host.open_project("main", &project).unwrap();
let (client_io, server_io) = tokio::io::duplex(1 << 16);
let (sr, sw) = tokio::io::split(server_io);
let scope = Some("mobile-abc-".to_owned());
tokio::spawn(rpc::serve_scoped(host.clone(), Dispatcher::standard(), peer_slot, sr, sw, scope));
let (cr, cw) = tokio::io::split(client_io);
let peer = Peer::connect(cr, cw, Arc::new(Client::default()));
let call = |window: &str, cmd: &str, args: Value| Invoke { window: window.into(), cmd: cmd.into(), args };
let denied = peer.request::<_, Value>("invoke", call("main", "index_status", json!({})), None).await;
let denied = rpc::error_from_reply(denied.unwrap_err());
assert_eq!(denied.kind, ide_core::error::ErrorKind::PermissionDenied, "{denied:?}");
let own = call("mobile-abc-1", "open_project", json!({ "path": project }));
let opened: Value = peer.request("invoke", own, None).await.unwrap();
assert_eq!(opened["name"], "demo");
assert!(host.project("main").is_ok(), "the desktop's window is untouched");
}
+25
Переглянути файл
@@ -0,0 +1,25 @@
[package]
name = "ide-pair"
description = "Pairing phones with the desktop over iroh: the endpoint, pairing tickets, paired devices and the connection handshake"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
iroh = "1.3"
base64.workspace = true
getrandom = "0.3"
parking_lot.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tokio.workspace = true
tracing.workspace = true
[features]
# `bind_local`: endpoints on the loopback interface without relays, for tests.
testing = []
[dev-dependencies]
tempfile.workspace = true
tokio = { workspace = true, features = ["signal"] }
+38
Переглянути файл
@@ -0,0 +1,38 @@
//! A stand-in phone for trying pairing without the mobile app:
//! `cargo run -p ide-pair --example phone -- '<pairing code>'` pairs with the desktop that
//! showed the code and stays connected; run it again without the code to reconnect.
//! The phone's key is kept in the system temporary directory.
use std::time::Duration;
#[tokio::main]
async fn main() {
let key_file = std::env::temp_dir().join("openidea-example-phone.key");
let addr_file = std::env::temp_dir().join("openidea-example-phone.desktop");
let key = ide_pair::load_or_create_key(&key_file).expect("phone key");
let (addr, code) = match std::env::args().nth(1) {
Some(text) => {
let ticket = ide_pair::Ticket::decode(&text).expect("an openidea-pair: code");
std::fs::write(&addr_file, serde_json::to_vec(&ticket.addr).unwrap()).unwrap();
(ticket.addr, Some(ticket.code))
}
None => {
let saved = std::fs::read(&addr_file).expect("pair first: pass the pairing code");
(serde_json::from_slice(&saved).unwrap(), None)
}
};
let endpoint = iroh::Endpoint::builder(iroh::endpoint::presets::N0).secret_key(key).bind().await.expect("endpoint");
println!("phone {}", endpoint.id());
match ide_pair::connect(&endpoint, addr, "Example Phone", code.as_deref()).await {
Ok((connection, welcome, _send, _recv)) => {
println!("connected to {} — press Ctrl+C to disconnect", welcome.desktop);
tokio::select! {
_ = connection.closed() => println!("the desktop closed the connection"),
_ = tokio::signal::ctrl_c() => {}
}
}
Err(e) => eprintln!("{e}"),
}
endpoint.close().await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
+467
Переглянути файл
@@ -0,0 +1,467 @@
//! Pairing phones with the desktop over iroh.
//!
//! The desktop runs an iroh [`Endpoint`] under a persistent key, so its endpoint id
//! stays the same across restarts. Pairing shows a [`Ticket`] (a QR code): the
//! endpoint's address plus a one-time code that expires. A phone that connects
//! with a valid code is remembered by its own endpoint id ([`DeviceStore`]) and
//! reconnects later without one. iroh authenticates both ends by their keys and
//! encrypts the connection, through a relay when no direct path exists.
//!
//! A connection opens one bidirectional stream. The phone sends a [`Hello`] line
//! (JSON, newline-terminated), the desktop answers a [`Welcome`] line, and then
//! the stream carries the remote development protocol (`ide_host::rpc`) like an
//! SSH channel to `openidea-server` does. [`Listener`] hands accepted streams to
//! the desktop as [`Session`]s; [`connect`] is the phone's side.
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use iroh::endpoint::{Connection, RecvStream, SendStream};
use iroh::{Endpoint, EndpointAddr, SecretKey};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
/// The protocol both ends announce in the QUIC handshake.
pub const ALPN: &[u8] = b"openidea/mobile/1";
/// What a pairing QR code holds before the encoded ticket.
pub const TICKET_PREFIX: &str = "openidea-pair:";
const PROTOCOL: u32 = 1;
/// Longest handshake line either side accepts.
const LINE_MAX: usize = 4096;
/// How long a phone has to send its hello after connecting.
const HELLO_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a ticket waits for the relay before giving direct addresses only.
const ONLINE_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, thiserror::Error)]
pub enum PairError {
#[error("not an OpenIDEA pairing code")]
Ticket,
#[error("cannot reach the desktop: {0}")]
Connect(String),
#[error("the desktop refused the connection: {0}")]
Refused(String),
#[error("{0}")]
Io(#[from] std::io::Error),
}
/// What a pairing QR code carries: where the desktop is and a one-time code.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Ticket {
pub v: u32,
/// The desktop's name, shown on the phone while it connects.
pub desktop: String,
pub addr: EndpointAddr,
pub code: String,
}
impl Ticket {
pub fn encode(&self) -> String {
let json = serde_json::to_vec(self).expect("a ticket serializes");
format!("{TICKET_PREFIX}{}", URL_SAFE_NO_PAD.encode(json))
}
pub fn decode(text: &str) -> Result<Self, PairError> {
let body = text.trim().strip_prefix(TICKET_PREFIX).ok_or(PairError::Ticket)?;
let json = URL_SAFE_NO_PAD.decode(body).map_err(|_| PairError::Ticket)?;
let ticket: Self = serde_json::from_slice(&json).map_err(|_| PairError::Ticket)?;
if ticket.v != PROTOCOL {
return Err(PairError::Ticket);
}
Ok(ticket)
}
}
/// A paired phone, known by its endpoint id.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Device {
pub id: String,
pub name: String,
/// Seconds since the Unix epoch.
pub paired_at: u64,
}
/// The paired phones, kept in a JSON file.
pub struct DeviceStore {
file: PathBuf,
devices: Mutex<Vec<Device>>,
}
impl DeviceStore {
/// Reads `file`; a missing or unreadable one is an empty list.
pub fn load(file: impl Into<PathBuf>) -> Self {
let file = file.into();
let devices = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
Self { file, devices: Mutex::new(devices) }
}
pub fn list(&self) -> Vec<Device> {
self.devices.lock().clone()
}
pub fn get(&self, id: &str) -> Option<Device> {
self.devices.lock().iter().find(|d| d.id == id).cloned()
}
pub fn is_empty(&self) -> bool {
self.devices.lock().is_empty()
}
/// Adds `device`, replacing one with the same id.
pub fn add(&self, device: Device) -> std::io::Result<()> {
let mut devices = self.devices.lock();
devices.retain(|d| d.id != device.id);
devices.push(device);
self.save(&devices)
}
pub fn remove(&self, id: &str) -> std::io::Result<bool> {
let mut devices = self.devices.lock();
let before = devices.len();
devices.retain(|d| d.id != id);
if devices.len() == before {
return Ok(false);
}
self.save(&devices)?;
Ok(true)
}
fn save(&self, devices: &[Device]) -> std::io::Result<()> {
if let Some(dir) = self.file.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = self.file.with_extension("json.tmp");
std::fs::write(&tmp, serde_json::to_vec_pretty(devices).map_err(std::io::Error::other)?)?;
std::fs::rename(&tmp, &self.file)
}
}
/// The endpoint key in `file`, created there (readable by the user only) the first time.
pub fn load_or_create_key(file: &Path) -> std::io::Result<SecretKey> {
if let Ok(bytes) = std::fs::read(file)
&& let Ok(bytes) = <[u8; 32]>::try_from(bytes.as_slice())
{
return Ok(SecretKey::from_bytes(&bytes));
}
let key = SecretKey::generate();
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir)?;
}
write_private(file, &key.to_bytes())?;
Ok(key)
}
/// The desktop's endpoint: its key from `key_file`, n0's relays and address lookup, accepting phones.
pub async fn bind_desktop(key_file: &Path) -> Result<Endpoint, PairError> {
let key = load_or_create_key(key_file)?;
Endpoint::builder(iroh::endpoint::presets::N0)
.secret_key(key)
.alpns(vec![ALPN.to_vec()])
.bind()
.await
.map_err(|e| PairError::Connect(e.to_string()))
}
/// An endpoint on the loopback interface without relays or address lookup; `accept` makes it
/// accept phones. For tests on one machine.
#[cfg(any(test, feature = "testing"))]
pub async fn bind_local(accept: bool) -> Endpoint {
Endpoint::builder(iroh::endpoint::presets::Minimal)
.relay_mode(iroh::RelayMode::Disabled)
.alpns(if accept { vec![ALPN.to_vec()] } else { vec![] })
.bind_addr("127.0.0.1:0")
.expect("a loopback address")
.bind()
.await
.expect("a loopback endpoint")
}
#[cfg(unix)]
fn write_private(file: &Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt as _;
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(file)?;
f.write_all(bytes)
}
#[cfg(not(unix))]
fn write_private(file: &Path, bytes: &[u8]) -> std::io::Result<()> {
std::fs::write(file, bytes)
}
/// The phone's first line.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Hello {
pub v: u32,
/// The phone's name, shown in the desktop's device list.
pub name: String,
/// The ticket's code, when pairing.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
}
/// The desktop's answer to a [`Hello`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Welcome {
pub ok: bool,
pub desktop: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
async fn read_line(recv: &mut RecvStream) -> std::io::Result<Vec<u8>> {
let mut line = Vec::new();
loop {
let byte = recv.read_u8().await?;
if byte == b'\n' {
return Ok(line);
}
if line.len() == LINE_MAX {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "handshake line too long"));
}
line.push(byte);
}
}
async fn write_line<T: Serialize>(send: &mut SendStream, value: &T) -> std::io::Result<()> {
let mut line = serde_json::to_vec(value).map_err(std::io::Error::other)?;
line.push(b'\n');
send.write_all(&line).await?;
send.flush().await
}
/// A phone's accepted connection, its stream ready for the remote development protocol.
pub struct Session {
pub device: Device,
pub connection: Connection,
pub send: SendStream,
pub recv: RecvStream,
}
pub type SessionHandler = Arc<dyn Fn(Session) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
struct Pending {
code: [u8; 16],
expires: Instant,
}
struct Shared {
store: DeviceStore,
desktop: String,
pending: Mutex<Option<Pending>>,
/// Connected phones by device id.
online: Mutex<HashMap<String, Connection>>,
handler: SessionHandler,
on_change: Arc<dyn Fn() + Send + Sync>,
}
impl Shared {
/// Uses up the pairing code when `code` matches it in time.
fn redeem(&self, code: &str) -> bool {
let Ok(given) = URL_SAFE_NO_PAD.decode(code) else { return false };
let mut pending = self.pending.lock();
let valid = pending.as_ref().is_some_and(|p| p.expires > Instant::now() && constant_time_eq(&p.code, &given));
if valid {
*pending = None;
}
valid
}
}
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
fn now_secs() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
}
/// Accepts phones on `endpoint`: paired ones, and new ones holding the current ticket's code.
pub struct Listener {
endpoint: Endpoint,
shared: Arc<Shared>,
}
impl Listener {
/// Starts accepting on the current tokio runtime. `endpoint` must accept [`ALPN`].
/// `handler` serves each session; `on_change` runs when a device pairs, connects,
/// disconnects or is removed.
pub fn start(
endpoint: Endpoint,
store: DeviceStore,
desktop: String,
handler: SessionHandler,
on_change: Arc<dyn Fn() + Send + Sync>,
) -> Self {
let shared = Arc::new(Shared {
store,
desktop,
pending: Mutex::new(None),
online: Mutex::new(HashMap::new()),
handler,
on_change,
});
let accepting = endpoint.clone();
let accept_shared = shared.clone();
tokio::spawn(async move {
while let Some(incoming) = accepting.accept().await {
let shared = accept_shared.clone();
tokio::spawn(async move {
match incoming.await {
Ok(connection) => accept(shared, connection).await,
Err(e) => tracing::debug!("mobile connection failed: {e}"),
}
});
}
});
Self { endpoint, shared }
}
/// A new ticket valid for `ttl`; any earlier one stops working.
pub async fn ticket(&self, ttl: Duration) -> (Ticket, Duration) {
// Without the relay (offline, or a firewall) the address still has the direct ones.
let _ = tokio::time::timeout(ONLINE_TIMEOUT, self.endpoint.online()).await;
let (code, expires) = {
let mut pending = self.shared.pending.lock();
match pending.as_ref() {
// Asked again while the shown code still works (a second dialog, a re-render): the same code.
Some(p) if p.expires > Instant::now() => (p.code, p.expires),
_ => {
let mut code = [0u8; 16];
getrandom::fill(&mut code).expect("system randomness");
let expires = Instant::now() + ttl;
*pending = Some(Pending { code, expires });
(code, expires)
}
}
};
let ticket = Ticket {
v: PROTOCOL,
desktop: self.shared.desktop.clone(),
addr: self.endpoint.addr(),
code: URL_SAFE_NO_PAD.encode(code),
};
(ticket, expires.saturating_duration_since(Instant::now()))
}
/// Stops the current ticket from pairing anything.
pub fn cancel_pairing(&self) {
*self.shared.pending.lock() = None;
}
/// The paired devices, each with whether it is connected now.
pub fn devices(&self) -> Vec<(Device, bool)> {
let online = self.shared.online.lock();
self.shared
.store
.list()
.into_iter()
.map(|d| {
let connected = online.contains_key(&d.id);
(d, connected)
})
.collect()
}
/// Forgets a device and drops its connection.
pub fn remove(&self, id: &str) -> std::io::Result<bool> {
let removed = self.shared.store.remove(id)?;
if let Some(connection) = self.shared.online.lock().remove(id) {
connection.close(0u32.into(), b"unpaired");
}
if removed {
(self.shared.on_change)();
}
Ok(removed)
}
pub fn has_devices(&self) -> bool {
!self.shared.store.is_empty()
}
pub fn endpoint(&self) -> &Endpoint {
&self.endpoint
}
pub async fn close(&self) {
self.endpoint.close().await;
}
}
async fn accept(shared: Arc<Shared>, connection: Connection) {
let id = connection.remote_id().to_string();
let Ok((mut send, mut recv)) = connection.accept_bi().await else { return };
let hello = match tokio::time::timeout(HELLO_TIMEOUT, read_line(&mut recv)).await {
Ok(Ok(line)) => serde_json::from_slice::<Hello>(&line).ok(),
_ => None,
};
let refuse = |error: &str| Welcome { ok: false, desktop: shared.desktop.clone(), error: Some(error.into()) };
let Some(hello) = hello.filter(|h| h.v == PROTOCOL) else {
let _ = write_line(&mut send, &refuse("unsupported client")).await;
let _ = send.finish();
return;
};
let device = if let Some(known) = shared.store.get(&id) {
known
} else if hello.code.as_deref().is_some_and(|code| shared.redeem(code)) {
let device = Device { id: id.clone(), name: hello.name.clone(), paired_at: now_secs() };
if let Err(e) = shared.store.add(device.clone()) {
tracing::warn!("cannot save the paired device: {e}");
}
device
} else {
let reason =
if hello.code.is_some() { "the pairing code is invalid or expired" } else { "this device is not paired" };
let _ = write_line(&mut send, &refuse(reason)).await;
let _ = send.finish();
connection.closed().await;
return;
};
let welcome = Welcome { ok: true, desktop: shared.desktop.clone(), error: None };
if write_line(&mut send, &welcome).await.is_err() {
return;
}
// One connection per device: a reconnect replaces the one it left behind.
if let Some(old) = shared.online.lock().insert(id.clone(), connection.clone()) {
old.close(0u32.into(), b"replaced");
}
(shared.on_change)();
(shared.handler)(Session { device, connection: connection.clone(), send, recv }).await;
{
let mut online = shared.online.lock();
if online.get(&id).is_some_and(|c| c.stable_id() == connection.stable_id()) {
online.remove(&id);
}
}
(shared.on_change)();
}
/// The phone's side: connects to `addr`, pairing with `code` or as a paired device.
pub async fn connect(
endpoint: &Endpoint,
addr: EndpointAddr,
name: &str,
code: Option<&str>,
) -> Result<(Connection, Welcome, SendStream, RecvStream), PairError> {
let connection = endpoint.connect(addr, ALPN).await.map_err(|e| PairError::Connect(e.to_string()))?;
let (mut send, mut recv) = connection.open_bi().await.map_err(|e| PairError::Connect(e.to_string()))?;
let hello = Hello { v: PROTOCOL, name: name.into(), code: code.map(str::to_owned) };
write_line(&mut send, &hello).await?;
let line = read_line(&mut recv).await?;
let welcome: Welcome =
serde_json::from_slice(&line).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
if !welcome.ok {
return Err(PairError::Refused(welcome.error.unwrap_or_default()));
}
Ok((connection, welcome, send, recv))
}
#[cfg(test)]
mod tests;
+138
Переглянути файл
@@ -0,0 +1,138 @@
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
async fn endpoint(alpns: Vec<Vec<u8>>) -> Endpoint {
bind_local(!alpns.is_empty()).await
}
struct Desktop {
listener: Listener,
changes: Arc<AtomicUsize>,
_dir: tempfile::TempDir,
}
/// A desktop whose sessions echo what the phone sends.
async fn desktop() -> Desktop {
let dir = tempfile::tempdir().unwrap();
let changes = Arc::new(AtomicUsize::new(0));
let counted = changes.clone();
let handler: SessionHandler = Arc::new(|mut s: Session| {
Box::pin(async move {
let _ = tokio::io::copy(&mut s.recv, &mut s.send).await;
let _ = s.send.finish();
s.connection.closed().await;
})
});
let listener = Listener::start(
endpoint(vec![ALPN.to_vec()]).await,
DeviceStore::load(dir.path().join("devices.json")),
"Workstation".into(),
handler,
Arc::new(move || {
counted.fetch_add(1, Ordering::SeqCst);
}),
);
Desktop { listener, changes, _dir: dir }
}
async fn echo(send: &mut SendStream, recv: &mut RecvStream) -> Vec<u8> {
send.write_all(b"ping").await.unwrap();
let mut buf = [0u8; 4];
recv.read_exact(&mut buf).await.unwrap();
buf.to_vec()
}
#[test]
fn a_ticket_round_trips_through_its_text() {
let key = SecretKey::generate();
let ticket =
Ticket { v: 1, desktop: "Workstation".into(), addr: EndpointAddr::new(key.public()), code: "abc".into() };
let text = ticket.encode();
assert!(text.starts_with(TICKET_PREFIX));
assert_eq!(Ticket::decode(&text).unwrap(), ticket);
assert!(matches!(Ticket::decode("https://example.com"), Err(PairError::Ticket)));
assert!(matches!(Ticket::decode("openidea-pair:!!"), Err(PairError::Ticket)));
}
#[test]
fn the_endpoint_key_survives_a_restart() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("mobile").join("endpoint.key");
let first = load_or_create_key(&file).unwrap();
assert_eq!(load_or_create_key(&file).unwrap().public(), first.public());
}
#[tokio::test]
async fn a_phone_pairs_with_the_code_once_and_then_reconnects_without_it() {
let desktop = desktop().await;
let ticket = desktop.listener.ticket(Duration::from_secs(60)).await.0;
let phone = endpoint(vec![]).await;
let (conn, welcome, mut send, mut recv) =
connect(&phone, ticket.addr.clone(), "Pixel", Some(&ticket.code)).await.unwrap();
assert_eq!(welcome.desktop, "Workstation");
assert_eq!(echo(&mut send, &mut recv).await, b"ping");
let devices = desktop.listener.devices();
assert_eq!(devices.len(), 1);
assert_eq!(devices[0].0.name, "Pixel");
assert_eq!(devices[0].0.id, phone.id().to_string());
assert!(devices[0].1, "shown as connected");
conn.close(0u32.into(), b"bye");
// The code is used up: another phone can't pair with it.
let stranger = endpoint(vec![]).await;
let refused = connect(&stranger, ticket.addr.clone(), "Stranger", Some(&ticket.code)).await;
assert!(matches!(refused, Err(PairError::Refused(_))), "{refused:?}");
// The paired phone needs no code.
let (_conn, _, mut send, mut recv) = connect(&phone, ticket.addr.clone(), "Pixel", None).await.unwrap();
assert_eq!(echo(&mut send, &mut recv).await, b"ping");
assert!(desktop.changes.load(Ordering::SeqCst) >= 2);
}
#[tokio::test]
async fn an_unpaired_phone_without_a_code_is_refused() {
let desktop = desktop().await;
let ticket = desktop.listener.ticket(Duration::from_secs(60)).await.0;
let phone = endpoint(vec![]).await;
let refused = connect(&phone, ticket.addr, "Pixel", None).await;
assert!(matches!(&refused, Err(PairError::Refused(e)) if e.contains("not paired")), "{refused:?}");
assert!(desktop.listener.devices().is_empty());
}
#[tokio::test]
async fn an_expired_or_cancelled_code_does_not_pair() {
let desktop = desktop().await;
let expired = desktop.listener.ticket(Duration::ZERO).await.0;
let phone = endpoint(vec![]).await;
assert!(connect(&phone, expired.addr.clone(), "Pixel", Some(&expired.code)).await.is_err());
let cancelled = desktop.listener.ticket(Duration::from_secs(60)).await.0;
desktop.listener.cancel_pairing();
assert!(connect(&phone, cancelled.addr, "Pixel", Some(&cancelled.code)).await.is_err());
assert!(desktop.listener.devices().is_empty());
}
#[tokio::test]
async fn removing_a_device_drops_its_connection_and_its_pairing() {
let desktop = desktop().await;
let ticket = desktop.listener.ticket(Duration::from_secs(60)).await.0;
let phone = endpoint(vec![]).await;
let (conn, ..) = connect(&phone, ticket.addr.clone(), "Pixel", Some(&ticket.code)).await.unwrap();
assert!(desktop.listener.remove(&phone.id().to_string()).unwrap());
tokio::time::timeout(Duration::from_secs(5), conn.closed()).await.expect("connection closed");
assert!(desktop.listener.devices().is_empty());
assert!(connect(&phone, ticket.addr, "Pixel", None).await.is_err());
}
#[tokio::test]
async fn asking_again_while_the_code_works_gives_the_same_code() {
let desktop = desktop().await;
let (first, _) = desktop.listener.ticket(Duration::from_secs(60)).await;
let (second, left) = desktop.listener.ticket(Duration::from_secs(60)).await;
assert_eq!(first.code, second.code);
assert!(left <= Duration::from_secs(60));
desktop.listener.cancel_pairing();
assert_ne!(desktop.listener.ticket(Duration::from_secs(60)).await.0.code, first.code);
}
+50
Переглянути файл
@@ -0,0 +1,50 @@
import { expect, test } from "./fixtures";
test.use({ hasTouch: true, isMobile: true, viewport: { width: 1180, height: 820 } });
test("a touch screen gets finger-sized rows and a long press opens the context menu", async ({ workbench: page }) => {
await expect(page.locator("html")).toHaveAttribute("data-form-factor", "tablet");
await expect(page.locator("html")).toHaveAttribute("data-touch", "");
const row = page.getByRole("treeitem", { name: /acme-api/ });
expect((await row.boundingBox())?.height).toBe(36);
const box = (await row.boundingBox())!;
const point = { x: Math.round(box.x + 40), y: Math.round(box.y + box.height / 2) };
const cdp = await page.context().newCDPSession(page);
await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [point] });
await page.waitForTimeout(700);
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
// One menu, still open after the finger lifts.
await expect(page.getByRole("menu")).toHaveCount(1);
await expect(page.getByRole("menuitem", { name: "Copy Path/Reference…" })).toBeVisible();
await page.screenshot({ path: test.info().outputPath("touch-long-press.png"), animations: "disabled" });
});
test.describe("phone", () => {
test.use({ viewport: { width: 390, height: 844 } });
test("shows one page at a time above a bottom bar of tool windows", async ({ page }) => {
await page.goto("/");
const bar = page.getByRole("navigation", { name: "Tool Windows" });
await expect(bar.getByRole("button")).toHaveText(["Agents", "Editor", "Git", "Database", "More"]);
await expect(page.getByRole("tree", { name: "Project" })).toHaveCount(0);
await bar.getByRole("button", { name: "Git" }).tap();
await expect(page.getByRole("region", { name: "Commit", exact: true })).toBeVisible();
await page.getByRole("tab", { name: "Log" }).tap();
await expect(page.getByRole("region", { name: "Git", exact: true })).toBeVisible();
await bar.getByRole("button", { name: "More" }).tap();
await page.getByRole("button", { name: "Project", exact: true }).tap();
const project = page.getByRole("region", { name: "Project", exact: true });
await expect(project.getByRole("tree", { name: "Project" })).toBeVisible();
await expect(project.getByRole("button", { name: "Hide" })).toHaveCount(0);
await expect(bar.getByRole("button", { name: "More" })).toHaveAttribute("aria-current", "page");
await page.screenshot({ path: test.info().outputPath("phone-project.png"), animations: "disabled" });
await page.getByRole("button", { name: "Back" }).tap();
await expect(page.getByRole("heading", { name: "Tool Windows" })).toBeVisible();
});
});
+26
Переглянути файл
@@ -0,0 +1,26 @@
[package]
name = "openidea-mobile"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
description = "OpenIDEA for phones: a client of a paired desktop's backend."
[lib]
name = "openidea_mobile_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
ide-jsonrpc.workspace = true
ide-pair.workspace = true
iroh = "1.3"
parking_lot.workspace = true
rustls.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread", "sync", "time"] }
tracing.workspace = true
+3
Переглянути файл
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
+7
Переглянути файл
@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/mobile-schema.json",
"identifier": "default",
"description": "The phone app's window",
"windows": ["main"],
"permissions": ["core:default"]
}
+3
Переглянути файл
@@ -0,0 +1,3 @@
xcuserdata/
build/
Externals/
Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 1.0 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 2.2 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 2.2 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 3.4 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 1.5 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 3.3 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 3.3 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 5.1 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 2.2 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 4.7 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 4.7 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 7.1 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 118 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 7.1 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 11 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 4.4 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 9.0 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 10 KiB

+116
Переглянути файл
@@ -0,0 +1,116 @@
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "[email protected]",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "[email protected]",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "[email protected]",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "[email protected]",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "[email protected]",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
+6
Переглянути файл
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
+8
Переглянути файл
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>method</key>
<string>debugging</string>
</dict>
</plist>
+30
Переглянути файл
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17150" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="Y6W-OH-hqX">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17122"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="s0d-6b-0kx">
<objects>
<viewController id="Y6W-OH-hqX" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="5EZ-qb-Rvc">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<viewLayoutGuide key="safeArea" id="vDu-zF-Fre"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="Ief-a0-LHa" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
<resources>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
+21
Переглянути файл
@@ -0,0 +1,21 @@
# Uncomment the next line to define a global platform for your project
target 'openidea-mobile_iOS' do
platform :ios, '15.0'
# Pods for openidea-mobile_iOS
end
target 'openidea-mobile_macOS' do
platform :osx, '11.0'
# Pods for openidea-mobile_macOS
end
# Delete the deployment target for iOS and macOS, causing it to be inherited from the Podfile
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
config.build_settings.delete 'MACOSX_DEPLOYMENT_TARGET'
end
end
end
+8
Переглянути файл
@@ -0,0 +1,8 @@
#pragma once
namespace ffi {
extern "C" {
void start_app();
}
}
+6
Переглянути файл
@@ -0,0 +1,6 @@
#include "bindings/bindings.h"
int main(int argc, char * argv[]) {
ffi::start_app();
return 0;
}
+482
Переглянути файл
@@ -0,0 +1,482 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 77;
objects = {
/* Begin PBXBuildFile section */
2744EE2804F53E6D881BBF63 /* main.mm in Sources */ = {isa = PBXBuildFile; fileRef = CB2F9850B5B2E58F8850F60C /* main.mm */; };
439CE87E75F5AD3D7C2BB846 /* Metal.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7C4C118DEB9045B80D2E2F33 /* Metal.framework */; };
50A2CEA4BFAE82C5417AF211 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F0335D6DAA4A236FA00ABDDE /* UIKit.framework */; };
558FF4DEC743B4C4A4E1394A /* MetalKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F6A2CA6A9929991FAE262E92 /* MetalKit.framework */; };
67FF332B4F390BA7238EC4AD /* libapp.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 51CF154506119E3532192BDB /* libapp.a */; };
7427A0592E7B97C8138D6D77 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B0916BE90883D96E76F981E4 /* SystemConfiguration.framework */; };
761D09B9E2A025076C7B5BB7 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 61DCE72B6C0408FC68D678A9 /* Assets.xcassets */; };
8A3D17B05D91E14C58E16E7C /* libresolv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = EBA16B20F8C1BD770CE41317 /* libresolv.tbd */; };
9B750D464D1F6CC949D0A296 /* assets in Resources */ = {isa = PBXBuildFile; fileRef = 757B8928C4FFC96B8E547556 /* assets */; };
A0D84801569B5C8D81344B35 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A9C4E9850A60BC849577163F /* CoreGraphics.framework */; };
A64C2C85D1B23CCAD0ECEF4A /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2E4ABD78F29F9B6F20AD5F99 /* Security.framework */; };
B3A80B9591727EFEA3A4FF5A /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 023842344E3E19138412F2BB /* WebKit.framework */; };
EB560C0C028CA3980BAAAB14 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FEBCCAD47D16E3FE348AA8D9 /* LaunchScreen.storyboard */; };
F10CE1D0D0B023C65E70039C /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BB417B443C7D99CBCA63EC83 /* QuartzCore.framework */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
023842344E3E19138412F2BB /* WebKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; };
031ADDAE46B9939F945B3608 /* main.rs */ = {isa = PBXFileReference; path = main.rs; sourceTree = "<group>"; };
17D55C8B634D7F3CA145C29D /* openidea-mobile_iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "openidea-mobile_iOS.entitlements"; sourceTree = "<group>"; };
2E4ABD78F29F9B6F20AD5F99 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
51CF154506119E3532192BDB /* libapp.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libapp.a; sourceTree = "<group>"; };
61DCE72B6C0408FC68D678A9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
70A325B1D770533BD52889F7 /* lib.rs */ = {isa = PBXFileReference; path = lib.rs; sourceTree = "<group>"; };
735E9C39344322F0BAB0586A /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
757B8928C4FFC96B8E547556 /* assets */ = {isa = PBXFileReference; lastKnownFileType = folder; path = assets; sourceTree = SOURCE_ROOT; };
7C4C118DEB9045B80D2E2F33 /* Metal.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Metal.framework; path = System/Library/Frameworks/Metal.framework; sourceTree = SDKROOT; };
847192858CD7077DE5B78EAC /* openidea-mobile_iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = "openidea-mobile_iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
896863188D37FC615176FB77 /* bindings.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = bindings.h; sourceTree = "<group>"; };
A9C4E9850A60BC849577163F /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
B0916BE90883D96E76F981E4 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; };
BB417B443C7D99CBCA63EC83 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; };
CB2F9850B5B2E58F8850F60C /* main.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = main.mm; sourceTree = "<group>"; };
EBA16B20F8C1BD770CE41317 /* libresolv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libresolv.tbd; path = usr/lib/libresolv.tbd; sourceTree = SDKROOT; };
F0335D6DAA4A236FA00ABDDE /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
F6A2CA6A9929991FAE262E92 /* MetalKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MetalKit.framework; path = System/Library/Frameworks/MetalKit.framework; sourceTree = SDKROOT; };
FEBCCAD47D16E3FE348AA8D9 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
4C0BD3FEE4255BFF3BA6569E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
67FF332B4F390BA7238EC4AD /* libapp.a in Frameworks */,
A0D84801569B5C8D81344B35 /* CoreGraphics.framework in Frameworks */,
439CE87E75F5AD3D7C2BB846 /* Metal.framework in Frameworks */,
558FF4DEC743B4C4A4E1394A /* MetalKit.framework in Frameworks */,
F10CE1D0D0B023C65E70039C /* QuartzCore.framework in Frameworks */,
A64C2C85D1B23CCAD0ECEF4A /* Security.framework in Frameworks */,
7427A0592E7B97C8138D6D77 /* SystemConfiguration.framework in Frameworks */,
8A3D17B05D91E14C58E16E7C /* libresolv.tbd in Frameworks */,
50A2CEA4BFAE82C5417AF211 /* UIKit.framework in Frameworks */,
B3A80B9591727EFEA3A4FF5A /* WebKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
172B4D6F3AD687EF6BC4AC13 = {
isa = PBXGroup;
children = (
757B8928C4FFC96B8E547556 /* assets */,
61DCE72B6C0408FC68D678A9 /* Assets.xcassets */,
FEBCCAD47D16E3FE348AA8D9 /* LaunchScreen.storyboard */,
B26E6A55FCF5686AD3906FFF /* Externals */,
F551C95FA1868AE5DA51D100 /* openidea-mobile_iOS */,
55CB6D093DCFABB98F780B17 /* Sources */,
CA107C281B8B1F5BB49E41D7 /* src */,
638EE276B309A4ED7C13784B /* Frameworks */,
D8049152DD2DE1ECECBD14CF /* Products */,
);
sourceTree = "<group>";
};
55CB6D093DCFABB98F780B17 /* Sources */ = {
isa = PBXGroup;
children = (
DCC0C46EC2E539EF574DFA67 /* openidea-mobile */,
);
path = Sources;
sourceTree = "<group>";
};
638EE276B309A4ED7C13784B /* Frameworks */ = {
isa = PBXGroup;
children = (
A9C4E9850A60BC849577163F /* CoreGraphics.framework */,
51CF154506119E3532192BDB /* libapp.a */,
EBA16B20F8C1BD770CE41317 /* libresolv.tbd */,
7C4C118DEB9045B80D2E2F33 /* Metal.framework */,
F6A2CA6A9929991FAE262E92 /* MetalKit.framework */,
BB417B443C7D99CBCA63EC83 /* QuartzCore.framework */,
2E4ABD78F29F9B6F20AD5F99 /* Security.framework */,
B0916BE90883D96E76F981E4 /* SystemConfiguration.framework */,
F0335D6DAA4A236FA00ABDDE /* UIKit.framework */,
023842344E3E19138412F2BB /* WebKit.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
B26E6A55FCF5686AD3906FFF /* Externals */ = {
isa = PBXGroup;
children = (
);
path = Externals;
sourceTree = "<group>";
};
C621872E9E0D2C765CE79B42 /* bindings */ = {
isa = PBXGroup;
children = (
896863188D37FC615176FB77 /* bindings.h */,
);
path = bindings;
sourceTree = "<group>";
};
CA107C281B8B1F5BB49E41D7 /* src */ = {
isa = PBXGroup;
children = (
70A325B1D770533BD52889F7 /* lib.rs */,
031ADDAE46B9939F945B3608 /* main.rs */,
);
name = src;
path = ../../src;
sourceTree = "<group>";
};
D8049152DD2DE1ECECBD14CF /* Products */ = {
isa = PBXGroup;
children = (
847192858CD7077DE5B78EAC /* openidea-mobile_iOS.app */,
);
name = Products;
sourceTree = "<group>";
};
DCC0C46EC2E539EF574DFA67 /* openidea-mobile */ = {
isa = PBXGroup;
children = (
CB2F9850B5B2E58F8850F60C /* main.mm */,
C621872E9E0D2C765CE79B42 /* bindings */,
);
path = "openidea-mobile";
sourceTree = "<group>";
};
F551C95FA1868AE5DA51D100 /* openidea-mobile_iOS */ = {
isa = PBXGroup;
children = (
735E9C39344322F0BAB0586A /* Info.plist */,
17D55C8B634D7F3CA145C29D /* openidea-mobile_iOS.entitlements */,
);
path = "openidea-mobile_iOS";
sourceTree = "<group>";
};
"TEMP_6FE66B9E-FD05-477E-9B43-E0D023270A34" /* arm64 */ = {
isa = PBXGroup;
children = (
);
path = arm64;
sourceTree = "<group>";
};
"TEMP_D69FF00B-4A56-4E76-B751-168968D4AF6A" /* x86_64 */ = {
isa = PBXGroup;
children = (
);
path = x86_64;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
8CFF48BAA56B4120D8BA712B /* openidea-mobile_iOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1F9E7E2EDE92674BB8D0C67A /* Build configuration list for PBXNativeTarget "openidea-mobile_iOS" */;
buildPhases = (
3DEE39C0B2E9A26D8DFE0116 /* Build Rust Code */,
BA18F72BCCD0E4F1DF3F6687 /* Sources */,
4B64842C21CCD4FD9313BC6B /* Resources */,
4C0BD3FEE4255BFF3BA6569E /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = "openidea-mobile_iOS";
packageProductDependencies = (
);
productName = "openidea-mobile_iOS";
productReference = 847192858CD7077DE5B78EAC /* openidea-mobile_iOS.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
E186C563A0B9A8C675E62D27 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastUpgradeCheck = 1430;
TargetAttributes = {
};
};
buildConfigurationList = 3A54F638E765215F8035A58F /* Build configuration list for PBXProject "openidea-mobile" */;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
Base,
en,
);
mainGroup = 172B4D6F3AD687EF6BC4AC13;
minimizedProjectReferenceProxies = 1;
preferredProjectObjectVersion = 77;
productRefGroup = D8049152DD2DE1ECECBD14CF /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
8CFF48BAA56B4120D8BA712B /* openidea-mobile_iOS */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
4B64842C21CCD4FD9313BC6B /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
761D09B9E2A025076C7B5BB7 /* Assets.xcassets in Resources */,
EB560C0C028CA3980BAAAB14 /* LaunchScreen.storyboard in Resources */,
9B750D464D1F6CC949D0A296 /* assets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
3DEE39C0B2E9A26D8DFE0116 /* Build Rust Code */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = "Build Rust Code";
outputFileListPaths = (
);
outputPaths = (
"$(SRCROOT)/Externals/x86_64/${CONFIGURATION}/libapp.a",
"$(SRCROOT)/Externals/arm64/${CONFIGURATION}/libapp.a",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "pnpm tauri ios xcode-script -v --platform \"${PLATFORM_DISPLAY_NAME:?}\" --sdk-root \"${SDKROOT:?}\" --framework-search-paths \"${FRAMEWORK_SEARCH_PATHS:?}\" --header-search-paths \"${HEADER_SEARCH_PATHS:?}\" --gcc-preprocessor-definitions \"${GCC_PREPROCESSOR_DEFINITIONS:-}\" --configuration \"${CONFIGURATION:?}\" ${FORCE_COLOR} ${ARCHS:?}\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
BA18F72BCCD0E4F1DF3F6687 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2744EE2804F53E6D881BBF63 /* main.mm in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
38DDA77512FF41759C083562 /* debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ARCHS = (
arm64,
);
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = "openidea-mobile_iOS/openidea-mobile_iOS.entitlements";
CODE_SIGN_IDENTITY = "iPhone Developer";
ENABLE_BITCODE = NO;
"EXCLUDED_ARCHS[sdk=iphoneos*]" = x86_64;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"\".\"",
);
INFOPLIST_FILE = "openidea-mobile_iOS/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
"LIBRARY_SEARCH_PATHS[arch=arm64]" = "$(inherited) $(PROJECT_DIR)/Externals/arm64/$(CONFIGURATION) $(SDKROOT)/usr/lib/swift $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME) $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0/$(PLATFORM_NAME)";
"LIBRARY_SEARCH_PATHS[arch=x86_64]" = "$(inherited) $(PROJECT_DIR)/Externals/x86_64/$(CONFIGURATION) $(SDKROOT)/usr/lib/swift $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME) $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0/$(PLATFORM_NAME)";
PRODUCT_BUNDLE_IDENTIFIER = ai.l0ng.openidea.mobile;
PRODUCT_NAME = "OpenIDEA Mobile";
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALID_ARCHS = arm64;
};
name = debug;
};
900382D9B8AEDB1E9722F8D6 /* release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_VERSION = 5.0;
};
name = release;
};
E2545040F8CCC1D43776F5BA /* release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ARCHS = (
arm64,
);
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = "openidea-mobile_iOS/openidea-mobile_iOS.entitlements";
CODE_SIGN_IDENTITY = "iPhone Developer";
ENABLE_BITCODE = NO;
"EXCLUDED_ARCHS[sdk=iphoneos*]" = x86_64;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"\".\"",
);
INFOPLIST_FILE = "openidea-mobile_iOS/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
"LIBRARY_SEARCH_PATHS[arch=arm64]" = "$(inherited) $(PROJECT_DIR)/Externals/arm64/$(CONFIGURATION) $(SDKROOT)/usr/lib/swift $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME) $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0/$(PLATFORM_NAME)";
"LIBRARY_SEARCH_PATHS[arch=x86_64]" = "$(inherited) $(PROJECT_DIR)/Externals/x86_64/$(CONFIGURATION) $(SDKROOT)/usr/lib/swift $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME) $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0/$(PLATFORM_NAME)";
PRODUCT_BUNDLE_IDENTIFIER = ai.l0ng.openidea.mobile;
PRODUCT_NAME = "OpenIDEA Mobile";
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALID_ARCHS = arm64;
};
name = release;
};
ED212AB5CA50F2EC04BBD81B /* debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"$(inherited)",
"DEBUG=1",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = debug;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1F9E7E2EDE92674BB8D0C67A /* Build configuration list for PBXNativeTarget "openidea-mobile_iOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
38DDA77512FF41759C083562 /* debug */,
E2545040F8CCC1D43776F5BA /* release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = debug;
};
3A54F638E765215F8035A58F /* Build configuration list for PBXProject "openidea-mobile" */ = {
isa = XCConfigurationList;
buildConfigurations = (
ED212AB5CA50F2EC04BBD81B /* debug */,
900382D9B8AEDB1E9722F8D6 /* release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = debug;
};
/* End XCConfigurationList section */
};
rootObject = E186C563A0B9A8C675E62D27 /* Project object */;
}
+7
Переглянути файл
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildSystemType</key>
<string>Original</string>
<key>DisableBuildSystemDeprecationDiagnostic</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,131 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1430"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
runPostActionsOnFailure = "NO">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8CFF48BAA56B4120D8BA712B"
BuildableName = "openidea-mobile_iOS.app"
BlueprintName = "openidea-mobile_iOS"
ReferencedContainer = "container:openidea-mobile.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "NO"
onlyGenerateCoverageForSpecifiedTargets = "NO">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8CFF48BAA56B4120D8BA712B"
BuildableName = "openidea-mobile_iOS.app"
BlueprintName = "openidea-mobile_iOS"
ReferencedContainer = "container:openidea-mobile.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
</Testables>
<CommandLineArguments>
</CommandLineArguments>
<EnvironmentVariables>
<EnvironmentVariable
key = "RUST_BACKTRACE"
value = "full"
isEnabled = "YES">
</EnvironmentVariable>
<EnvironmentVariable
key = "RUST_LOG"
value = "info"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
</TestAction>
<LaunchAction
buildConfiguration = "debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8CFF48BAA56B4120D8BA712B"
BuildableName = "openidea-mobile_iOS.app"
BlueprintName = "openidea-mobile_iOS"
ReferencedContainer = "container:openidea-mobile.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
</CommandLineArguments>
<EnvironmentVariables>
<EnvironmentVariable
key = "RUST_BACKTRACE"
value = "full"
isEnabled = "YES">
</EnvironmentVariable>
<EnvironmentVariable
key = "RUST_LOG"
value = "info"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "release"
shouldUseLaunchSchemeArgsEnv = "NO"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "8CFF48BAA56B4120D8BA712B"
BuildableName = "openidea-mobile_iOS.app"
BlueprintName = "openidea-mobile_iOS"
ReferencedContainer = "container:openidea-mobile.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
</CommandLineArguments>
<EnvironmentVariables>
<EnvironmentVariable
key = "RUST_BACKTRACE"
value = "full"
isEnabled = "YES">
</EnvironmentVariable>
<EnvironmentVariable
key = "RUST_LOG"
value = "info"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+44
Переглянути файл
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleVersion</key>
<string>1.0.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
<string>metal</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
+5
Переглянути файл
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict/>
</plist>
+97
Переглянути файл
@@ -0,0 +1,97 @@
name: openidea-mobile
options:
bundleIdPrefix: ai.l0ng.openidea.mobile
deploymentTarget:
iOS: 15.0
fileGroups: [../../src]
configs:
debug: debug
release: release
settingGroups:
app:
base:
PRODUCT_NAME: OpenIDEA Mobile
PRODUCT_BUNDLE_IDENTIFIER: ai.l0ng.openidea.mobile
targetTemplates:
app:
type: application
sources:
- path: Sources
scheme:
environmentVariables:
RUST_BACKTRACE: full
RUST_LOG: info
settings:
groups: [app]
targets:
openidea-mobile_iOS:
type: application
platform: iOS
sources:
- path: Sources
- path: Assets.xcassets
# Exclude built static libs: regenerating with xcodegen after a build
# otherwise turns the per-configuration libapp.a copies into colliding
# resources ("Multiple commands produce …/libapp.a"). They are linked
# via LIBRARY_SEARCH_PATHS, never bundled as resources.
- path: Externals
excludes: ["**/*.a"]
- path: openidea-mobile_iOS
- path: assets
buildPhase: resources
type: folder
- path: LaunchScreen.storyboard
info:
path: openidea-mobile_iOS/Info.plist
properties:
LSRequiresIPhoneOS: true
UILaunchStoryboardName: LaunchScreen
UIRequiredDeviceCapabilities: [arm64, metal]
UISupportedInterfaceOrientations:
- UIInterfaceOrientationPortrait
- UIInterfaceOrientationLandscapeLeft
- UIInterfaceOrientationLandscapeRight
UISupportedInterfaceOrientations~ipad:
- UIInterfaceOrientationPortrait
- UIInterfaceOrientationPortraitUpsideDown
- UIInterfaceOrientationLandscapeLeft
- UIInterfaceOrientationLandscapeRight
CFBundleShortVersionString: 1.0.0
CFBundleVersion: "1.0.0"
entitlements:
path: openidea-mobile_iOS/openidea-mobile_iOS.entitlements
scheme:
environmentVariables:
RUST_BACKTRACE: full
RUST_LOG: info
settings:
base:
ENABLE_BITCODE: false
ARCHS: [arm64]
VALID_ARCHS: arm64
LIBRARY_SEARCH_PATHS[arch=x86_64]: $(inherited) $(PROJECT_DIR)/Externals/x86_64/$(CONFIGURATION) $(SDKROOT)/usr/lib/swift $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME) $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0/$(PLATFORM_NAME)
LIBRARY_SEARCH_PATHS[arch=arm64]: $(inherited) $(PROJECT_DIR)/Externals/arm64/$(CONFIGURATION) $(SDKROOT)/usr/lib/swift $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(PLATFORM_NAME) $(DEVELOPER_DIR)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0/$(PLATFORM_NAME)
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES: true
EXCLUDED_ARCHS[sdk=iphoneos*]: x86_64
groups: [app]
dependencies:
- framework: libapp.a
embed: false
- sdk: CoreGraphics.framework
- sdk: Metal.framework
- sdk: MetalKit.framework
- sdk: QuartzCore.framework
- sdk: Security.framework
# iroh: network interfaces and DNS servers.
- sdk: SystemConfiguration.framework
- sdk: libresolv.tbd
- sdk: UIKit.framework
- sdk: WebKit.framework
preBuildScripts:
- script: |
pnpm tauri ios xcode-script -v --platform "${PLATFORM_DISPLAY_NAME:?}" --sdk-root "${SDKROOT:?}" --framework-search-paths "${FRAMEWORK_SEARCH_PATHS:?}" --header-search-paths "${HEADER_SEARCH_PATHS:?}" --gcc-preprocessor-definitions "${GCC_PREPROCESSOR_DEFINITIONS:-}" --configuration "${CONFIGURATION:?}" ${FORCE_COLOR} ${ARCHS:?}
name: Build Rust Code
basedOnDependencyAnalysis: false
outputFiles:
- $(SRCROOT)/Externals/x86_64/${CONFIGURATION}/libapp.a
- $(SRCROOT)/Externals/arm64/${CONFIGURATION}/libapp.a
+1
Переглянути файл
@@ -0,0 +1 @@
{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"DenLine truncated
+1
Переглянути файл
@@ -0,0 +1 @@
{"default":{"identifier":"default","description":"The phone app's window","local":true,"windows":["main"],"permissions":["core:default"]}}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 2.6 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 4.9 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 718 B

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 2.6 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 3.5 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 3.6 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 6.7 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 876 B

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 7.2 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 1.2 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 1.8 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 2.2 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 1.3 KiB

Бінарний файл не відображається.
Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 13 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 9.9 KiB

+14
Переглянути файл
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 100 100" role="img" aria-label="OpenIDEA Dogfood">
<rect x="2" y="2" width="96" height="96" rx="22" fill="#E6E7E9"/>
<g transform="translate(50 50) scale(1.5) translate(-50 -52)">
<rect x="22" y="26" width="56" height="52" rx="12" fill="#787B82"/>
<rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1C1E"/>
<g transform="translate(50 46) scale(1.35) translate(-50 -46)">
<circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#E6E7E9" stroke-width="2.7"/>
<rect x="54.3" y="42" width="2.8" height="10.5" fill="#E6E7E9"/>
<rect x="51.2" y="42" width="5.9" height="2.5" fill="#E6E7E9"/>
<rect x="51.2" y="50" width="9.4" height="2.5" fill="#E6E7E9"/>
<circle cx="55.7" cy="38.4" r="1.8" fill="#E6E7E9"/>
</g>
</g>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 858 B

+1
Переглянути файл
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 100 100" role="img" aria-label="OpenIDEA Dogfood"><rect x="10" y="10" width="80" height="80" rx="18" fill="#E6E7E9"/><g transform="translate(50 50) scale(1.25) translate(-50 -52)"><rect x="22" y="26" width="56" height="52" rx="12" fill="#787B82"/><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1C1E"/><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#E6E7E9" stroke-width="2.7"/><rect x="54.3" y="42" width="2.8" height="10.5" fill="#E6E7E9"/><rect x="51.2" y="42" width="5.9" height="2.5" fill="#E6E7E9"/><rect x="51.2" y="50" width="9.4" height="2.5" fill="#E6E7E9"/><circle cx="55.7" cy="38.4" r="1.8" fill="#E6E7E9"/></g></svg>

Після

Ширина:  |  Висота:  |  Розмір: 729 B

+1
Переглянути файл
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="22 24 56 56"><title>OpenIDEA</title><rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C"/><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A"/><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7"/><rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0"/><rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0"/><rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0"/><circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0"/></svg>

Після

Ширина:  |  Висота:  |  Розмір: 573 B

+1
Переглянути файл
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 100 100" role="img" aria-label="OpenIDEA"><rect x="10" y="10" width="80" height="80" rx="18" fill="#EAE7E0"/><g transform="translate(50 50) scale(1.25) translate(-50 -52)"><rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C"/><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A"/><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7"/><rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0"/><rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0"/><rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0"/><circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0"/></g></svg>

Після

Ширина:  |  Висота:  |  Розмір: 721 B

+14
Переглянути файл
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 100 100" role="img" aria-label="OpenIDEA">
<rect x="2" y="2" width="96" height="96" rx="22" fill="#EAE7E0"/>
<g transform="translate(50 50) scale(1.5) translate(-50 -52)">
<rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C"/>
<rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A"/>
<g transform="translate(50 46) scale(1.35) translate(-50 -46)">
<circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7"/>
<rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0"/>
<rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0"/>
<rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0"/>
<circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0"/>
</g>
</g>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 850 B

+1
Переглянути файл
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="435" height="128" viewBox="0 0 435 128" role="img" aria-label="OpenIDEA"><title>OpenIDEA</title><g transform="translate(14 14)"><rect x="10" y="10" width="80" height="80" rx="18" fill="#EAE7E0"/><g transform="translate(50 50) scale(1.25) translate(-50 -52)"><rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C"/><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A"/><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7"/><rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0"/><rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0"/><rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0"/><circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0"/></g></g><g transform="translate(0 88.01)"><path fill="#FFFFFF" d="M150.72 0.64Q144.35 0.64 139.25 -2.26Q134.15 -5.16 131.19 -10.66Q128.23 -16.17 128.23 -23.98Q128.23 -31.83 131.19 -37.36Q134.15 -42.88 139.25 -45.77Q144.35 -48.66 150.72 -48.66Q157.11 -48.66 162.19 -45.77Q167.27 -42.88 170.23 -37.36Q173.19 -31.83 173.19 -23.98Q173.19 -16.15 170.23 -10.64Q167.27 -5.14 162.19 -2.25Q157.11 0.64 150.72 0.64ZM150.72 -8.33Q154.42 -8.33 157.15 -10.13Q159.89 -11.93 161.4 -15.42Q162.91 -18.92 162.91 -23.98Q162.91 -29.07 161.4 -32.58Q159.89 -36.09 157.15 -37.89Q154.42 -39.69 150.72 -39.69Q147.05 -39.69 144.31 -37.89Q141.57 -36.09 140.04 -32.58Q138.52 -29.07 138.52 -23.98Q138.52 -18.92 140.04 -15.42Q141.57 -11.93 144.31 -10.13Q147.05 -8.33 150.72 -8.33ZM176.05 13.47V-36.03H185.86V-29.94H186.31Q186.98 -31.42 188.23 -32.94Q189.48 -34.45 191.52 -35.47Q193.55 -36.48 196.56 -36.48Q200.52 -36.48 203.83 -34.43Q207.13 -32.38 209.13 -28.27Q211.13 -24.15 211.13 -17.96Q211.13 -11.94 209.19 -7.81Q207.26 -3.67 203.95 -1.54Q200.63 0.58 196.51 0.58Q193.62 0.58 191.59 -0.39Q189.57 -1.37 188.28 -2.83Q187 -4.29 186.31 -5.77H186.02V13.47ZM193.36 -7.36Q195.83 -7.36 197.5 -8.71Q199.17 -10.06 200.04 -12.46Q200.9 -14.86 200.9 -17.98Q200.9 -21.11 200.04 -23.48Q199.18 -25.86 197.52 -27.2Q195.85 -28.54 193.36 -28.54Q190.95 -28.54 189.26 -27.24Q187.57 -25.95 186.68 -23.58Q185.8 -21.21 185.8 -17.98Q185.8 -14.79 186.69 -12.41Q187.58 -10.02 189.28 -8.69Q190.97 -7.36 193.36 -7.36ZM229.58 0.7Q224.05 0.7 220.03 -1.56Q216.01 -3.81 213.86 -7.97Q211.72 -12.14 211.72 -17.84Q211.72 -23.4 213.86 -27.6Q216 -31.79 219.91 -34.13Q223.82 -36.48 229.11 -36.48Q232.68 -36.48 235.77 -35.34Q238.87 -34.21 241.19 -31.93Q243.51 -29.65 244.8 -26.22Q246.1 -22.79 246.1 -18.19V-15.46H215.69V-21.62H241.26L236.61 -20.01Q236.61 -22.76 235.77 -24.79Q234.93 -26.81 233.28 -27.92Q231.63 -29.04 229.18 -29.04Q226.74 -29.04 225.03 -27.92Q223.33 -26.79 222.44 -24.85Q221.55 -22.91 221.55 -20.39V-16.04Q221.55 -13.12 222.57 -11.04Q223.6 -8.96 225.45 -7.85Q227.3 -6.74 229.74 -6.74Q231.4 -6.74 232.75 -7.22Q234.11 -7.69 235.09 -8.62Q236.07 -9.56 236.57 -10.91L245.79 -10.29Q245.08 -6.96 242.95 -4.49Q240.81 -2.02 237.42 -0.66Q234.04 0.7 229.58 0.7ZM258 -20.81V0H248.03V-36.03H257.84V-29.62H258.2Q259.42 -32.8 262.09 -34.64Q264.75 -36.48 268.79 -36.48Q272.55 -36.48 275.33 -34.84Q278.12 -33.21 279.66 -30.16Q281.2 -27.12 281.2 -22.92V0H271.24V-21.14Q271.24 -24.43 269.54 -26.31Q267.83 -28.19 264.83 -28.19Q262.83 -28.19 261.28 -27.31Q259.74 -26.43 258.87 -24.79Q258 -23.15 258 -20.81Z"/><path fill="#A3A7B0" d="M291.88 -48.02V0H286.08V-48.02ZM312.9 0H301.36V-5.16H312.51Q318.48 -5.16 322.39 -7.44Q326.31 -9.73 328.24 -13.99Q330.17 -18.24 330.17 -24.11Q330.17 -29.91 328.27 -34.11Q326.37 -38.32 322.59 -40.59Q318.8 -42.86 313.16 -42.86H301.11V-48.02H313.55Q320.54 -48.02 325.52 -45.15Q330.5 -42.28 333.14 -36.92Q335.78 -31.55 335.78 -24.11Q335.78 -16.6 333.11 -11.2Q330.43 -5.8 325.32 -2.9Q320.22 0 312.9 0ZM303.88 -48.02V0H298.08V-48.02ZM340.11 0V-48.02H369.11V-42.86H345.91V-26.81H367.57V-21.66H345.91V-5.16H369.44V0ZM376.15 0H370.03L387.69 -48.02H393.68L411.28 0H405.22L390.85 -40.41H390.46ZM378.41 -18.76H402.96V-13.6H378.41Z"/></g></svg>

Після

Ширина:  |  Висота:  |  Розмір: 3.9 KiB

+1
Переглянути файл
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="435" height="128" viewBox="0 0 435 128" role="img" aria-label="OpenIDEA"><title>OpenIDEA</title><g transform="translate(14 14)"><rect x="10" y="10" width="80" height="80" rx="18" fill="#EAE7E0"/><g transform="translate(50 50) scale(1.25) translate(-50 -52)"><rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C"/><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A"/><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7"/><rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0"/><rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0"/><rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0"/><circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0"/></g></g><g transform="translate(0 88.01)"><path fill="#0E0E10" d="M150.72 0.64Q144.35 0.64 139.25 -2.26Q134.15 -5.16 131.19 -10.66Q128.23 -16.17 128.23 -23.98Q128.23 -31.83 131.19 -37.36Q134.15 -42.88 139.25 -45.77Q144.35 -48.66 150.72 -48.66Q157.11 -48.66 162.19 -45.77Q167.27 -42.88 170.23 -37.36Q173.19 -31.83 173.19 -23.98Q173.19 -16.15 170.23 -10.64Q167.27 -5.14 162.19 -2.25Q157.11 0.64 150.72 0.64ZM150.72 -8.33Q154.42 -8.33 157.15 -10.13Q159.89 -11.93 161.4 -15.42Q162.91 -18.92 162.91 -23.98Q162.91 -29.07 161.4 -32.58Q159.89 -36.09 157.15 -37.89Q154.42 -39.69 150.72 -39.69Q147.05 -39.69 144.31 -37.89Q141.57 -36.09 140.04 -32.58Q138.52 -29.07 138.52 -23.98Q138.52 -18.92 140.04 -15.42Q141.57 -11.93 144.31 -10.13Q147.05 -8.33 150.72 -8.33ZM176.05 13.47V-36.03H185.86V-29.94H186.31Q186.98 -31.42 188.23 -32.94Q189.48 -34.45 191.52 -35.47Q193.55 -36.48 196.56 -36.48Q200.52 -36.48 203.83 -34.43Q207.13 -32.38 209.13 -28.27Q211.13 -24.15 211.13 -17.96Q211.13 -11.94 209.19 -7.81Q207.26 -3.67 203.95 -1.54Q200.63 0.58 196.51 0.58Q193.62 0.58 191.59 -0.39Q189.57 -1.37 188.28 -2.83Q187 -4.29 186.31 -5.77H186.02V13.47ZM193.36 -7.36Q195.83 -7.36 197.5 -8.71Q199.17 -10.06 200.04 -12.46Q200.9 -14.86 200.9 -17.98Q200.9 -21.11 200.04 -23.48Q199.18 -25.86 197.52 -27.2Q195.85 -28.54 193.36 -28.54Q190.95 -28.54 189.26 -27.24Q187.57 -25.95 186.68 -23.58Q185.8 -21.21 185.8 -17.98Q185.8 -14.79 186.69 -12.41Q187.58 -10.02 189.28 -8.69Q190.97 -7.36 193.36 -7.36ZM229.58 0.7Q224.05 0.7 220.03 -1.56Q216.01 -3.81 213.86 -7.97Q211.72 -12.14 211.72 -17.84Q211.72 -23.4 213.86 -27.6Q216 -31.79 219.91 -34.13Q223.82 -36.48 229.11 -36.48Q232.68 -36.48 235.77 -35.34Q238.87 -34.21 241.19 -31.93Q243.51 -29.65 244.8 -26.22Q246.1 -22.79 246.1 -18.19V-15.46H215.69V-21.62H241.26L236.61 -20.01Q236.61 -22.76 235.77 -24.79Q234.93 -26.81 233.28 -27.92Q231.63 -29.04 229.18 -29.04Q226.74 -29.04 225.03 -27.92Q223.33 -26.79 222.44 -24.85Q221.55 -22.91 221.55 -20.39V-16.04Q221.55 -13.12 222.57 -11.04Q223.6 -8.96 225.45 -7.85Q227.3 -6.74 229.74 -6.74Q231.4 -6.74 232.75 -7.22Q234.11 -7.69 235.09 -8.62Q236.07 -9.56 236.57 -10.91L245.79 -10.29Q245.08 -6.96 242.95 -4.49Q240.81 -2.02 237.42 -0.66Q234.04 0.7 229.58 0.7ZM258 -20.81V0H248.03V-36.03H257.84V-29.62H258.2Q259.42 -32.8 262.09 -34.64Q264.75 -36.48 268.79 -36.48Q272.55 -36.48 275.33 -34.84Q278.12 -33.21 279.66 -30.16Q281.2 -27.12 281.2 -22.92V0H271.24V-21.14Q271.24 -24.43 269.54 -26.31Q267.83 -28.19 264.83 -28.19Q262.83 -28.19 261.28 -27.31Q259.74 -26.43 258.87 -24.79Q258 -23.15 258 -20.81Z"/><path fill="#5F6470" d="M291.88 -48.02V0H286.08V-48.02ZM312.9 0H301.36V-5.16H312.51Q318.48 -5.16 322.39 -7.44Q326.31 -9.73 328.24 -13.99Q330.17 -18.24 330.17 -24.11Q330.17 -29.91 328.27 -34.11Q326.37 -38.32 322.59 -40.59Q318.8 -42.86 313.16 -42.86H301.11V-48.02H313.55Q320.54 -48.02 325.52 -45.15Q330.5 -42.28 333.14 -36.92Q335.78 -31.55 335.78 -24.11Q335.78 -16.6 333.11 -11.2Q330.43 -5.8 325.32 -2.9Q320.22 0 312.9 0ZM303.88 -48.02V0H298.08V-48.02ZM340.11 0V-48.02H369.11V-42.86H345.91V-26.81H367.57V-21.66H345.91V-5.16H369.44V0ZM376.15 0H370.03L387.69 -48.02H393.68L411.28 0H405.22L390.85 -40.41H390.46ZM378.41 -18.76H402.96V-13.6H378.41Z"/></g></svg>

Після

Ширина:  |  Висота:  |  Розмір: 3.9 KiB

+1
Переглянути файл
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 100 100" role="img" aria-label="OpenIDEA"><rect x="10" y="10" width="80" height="80" rx="18" fill="#EAE7E0"/><g transform="translate(50 50) scale(1.25) translate(-50 -52)"><rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C"/><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A"/><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7"/><rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0"/><rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0"/><rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0"/><circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0"/></g></svg>

Після

Ширина:  |  Висота:  |  Розмір: 721 B

+340
Переглянути файл
@@ -0,0 +1,340 @@
//! OpenIDEA on a phone: the workbench UI as a client of a paired desktop's backend.
//!
//! The phone runs no language servers, terminals or agents itself. It pairs with a desktop
//! over iroh (`ide_pair`) and sends each command of its window to that desktop as an
//! `invoke` (the remote development protocol of `ide_host::rpc`), in the desktop window
//! `mobile-<device>-<label>`. Events and streamed values for that window come back as
//! notifications and go to the webview the way the desktop's own reach its windows.
use ide_jsonrpc::{Handler, Peer};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use tauri::ipc::Channel;
use tauri::{AppHandle, Emitter, Manager, State, WebviewWindow};
/// What the frontend listens to for backend events (`src/platform/ipc.ts`).
const IDE_EVENT: &str = "ide://event";
/// Sent to the webview when the connection to the desktop drops.
const DISCONNECTED_EVENT: &str = "phone://disconnected";
/// A command's failure, shaped like the desktop's `IdeError`.
#[derive(Debug, Serialize)]
struct Failure {
kind: &'static str,
message: String,
}
type Reply<T> = Result<T, Failure>;
fn failure(kind: &'static str, message: impl ToString) -> Failure {
Failure { kind, message: message.to_string() }
}
/// The desktop this phone pairs with: how to reach it and its name.
#[derive(Clone, Serialize, Deserialize)]
struct PairedDesktop {
name: String,
addr: iroh::EndpointAddr,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct PhoneStatus {
/// The paired desktop's name, `None` before pairing.
desktop: Option<String>,
connected: bool,
/// How the connection reaches the desktop: each path's address and round trip, `*` = in use.
paths: Vec<String>,
}
/// A connection to the desktop, as the frontend sees it.
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct PhoneSession {
desktop: String,
/// The commands the desktop answers for the phone.
commands: Vec<String>,
os: String,
home: String,
}
#[derive(Clone, Serialize)]
struct ChannelFrame {
id: u64,
data: String,
}
type Channels = Arc<Mutex<HashMap<u64, (Channel<ChannelFrame>, u64)>>>;
struct Connection {
link: iroh::endpoint::Connection,
peer: Peer,
/// The prefix of this phone's windows on the desktop.
scope: String,
session: PhoneSession,
channels: Channels,
next_channel: AtomicU64,
}
struct Phone {
key_file: PathBuf,
desktop_file: PathBuf,
endpoint: tokio::sync::OnceCell<iroh::Endpoint>,
connection: Mutex<Option<Arc<Connection>>>,
/// One connection attempt at a time.
connecting: tokio::sync::Mutex<()>,
}
impl Phone {
async fn endpoint(&self) -> Reply<&iroh::Endpoint> {
self.endpoint
.get_or_try_init(|| async {
let key = ide_pair::load_or_create_key(&self.key_file).map_err(|e| failure("io", e))?;
iroh::Endpoint::builder(iroh::endpoint::presets::N0)
.secret_key(key)
.bind()
.await
.map_err(|e| failure("unavailable", e))
})
.await
}
fn paired(&self) -> Option<PairedDesktop> {
serde_json::from_slice(&std::fs::read(&self.desktop_file).ok()?).ok()
}
fn current(&self) -> Option<Arc<Connection>> {
self.connection.lock().clone()
}
}
fn device_name() -> String {
if cfg!(target_os = "ios") {
"iPhone".into()
} else if cfg!(target_os = "android") {
"Android phone".into()
} else {
"Phone".into()
}
}
/// Window events and streamed values from the desktop.
struct FromDesktop {
app: AppHandle,
scope: String,
channels: Channels,
}
#[derive(Deserialize)]
struct EventMessage {
window: Option<String>,
event: Value,
}
#[derive(Deserialize)]
struct ChannelMessage {
id: u64,
data: Value,
}
impl Handler for FromDesktop {
fn on_notification(&self, method: &str, params: Value) {
match method {
"event" => {
let Ok(m) = serde_json::from_value::<EventMessage>(params) else { return };
let label = m.window.as_deref().and_then(|w| w.strip_prefix(&self.scope));
let _ = match label {
Some(label) => self.app.emit_to(label, IDE_EVENT, m.event),
None => self.app.emit(IDE_EVENT, m.event),
};
}
"channel" => {
let Ok(m) = serde_json::from_value::<ChannelMessage>(params) else { return };
if let Some((channel, id)) = self.channels.lock().get(&m.id).cloned() {
let _ = channel.send(ChannelFrame { id, data: m.data.to_string() });
}
}
_ => {}
}
}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, format!("the phone does not handle {method}")))
}
}
/// Connects to `desktop`, pairing with `code` the first time, and makes it the current connection.
async fn connect(app: &AppHandle, phone: &Phone, desktop: &PairedDesktop, code: Option<&str>) -> Reply<PhoneSession> {
let _one = phone.connecting.lock().await;
let endpoint = phone.endpoint().await?;
let (connection, welcome, send, recv) =
ide_pair::connect(endpoint, desktop.addr.clone(), &device_name(), code).await.map_err(|e| match e {
ide_pair::PairError::Refused(m) => failure("permissionDenied", m),
e => failure("unavailable", e),
})?;
let id = endpoint.id().to_string();
let scope = format!("mobile-{}-", &id[..12]);
let channels = Channels::default();
let handler = Arc::new(FromDesktop { app: app.clone(), scope: scope.clone(), channels: channels.clone() });
let peer = Peer::connect(recv, send, handler);
#[derive(Deserialize)]
struct ServerInfo {
os: String,
home: String,
}
let info: ServerInfo = peer.request("initialize", json!({}), None).await.map_err(|e| failure("unavailable", e))?;
let commands: Vec<String> =
peer.request("commands", json!({}), None).await.map_err(|e| failure("unavailable", e))?;
let session = PhoneSession { desktop: welcome.desktop.clone(), commands, os: info.os, home: info.home };
let current = Arc::new(Connection {
link: connection,
peer: peer.clone(),
scope,
session: session.clone(),
channels,
next_channel: AtomicU64::new(1),
});
if let Some(old) = phone.connection.lock().replace(current.clone()) {
old.link.close(0u32.into(), b"replaced");
}
let watching = app.clone();
tauri::async_runtime::spawn(async move {
peer.closed().await;
let phone = watching.state::<Phone>();
let mut slot = phone.connection.lock();
if slot.as_ref().is_some_and(|c| Arc::ptr_eq(c, &current)) {
*slot = None;
drop(slot);
let _ = watching.emit(DISCONNECTED_EVENT, ());
}
});
Ok(session)
}
#[tauri::command]
fn phone_status(phone: State<'_, Phone>) -> PhoneStatus {
let current = phone.current();
let paths = current
.as_ref()
.map(|c| {
c.link
.paths()
.iter()
.map(|p| {
let mark = if p.is_selected() { "*" } else { " " };
format!("{mark} {:?} {}ms", p.remote_addr(), p.rtt().as_millis())
})
.collect()
})
.unwrap_or_default();
PhoneStatus { desktop: phone.paired().map(|d| d.name), connected: current.is_some(), paths }
}
/// Pairs with the desktop whose pairing code (`openidea-pair:…`) the user scanned or pasted.
#[tauri::command]
async fn phone_pair(app: AppHandle, phone: State<'_, Phone>, code: String) -> Reply<PhoneSession> {
let ticket = ide_pair::Ticket::decode(code.trim())
.map_err(|_| failure("invalidInput", "this is not an OpenIDEA pairing code"))?;
let desktop = PairedDesktop { name: ticket.desktop.clone(), addr: ticket.addr.clone() };
let session = connect(&app, &phone, &desktop, Some(&ticket.code)).await?;
if let Some(dir) = phone.desktop_file.parent() {
std::fs::create_dir_all(dir).map_err(|e| failure("io", e))?;
}
let saved = PairedDesktop { name: session.desktop.clone(), addr: desktop.addr };
std::fs::write(&phone.desktop_file, serde_json::to_vec(&saved).unwrap_or_default())
.map_err(|e| failure("io", e))?;
Ok(session)
}
/// Connects to the paired desktop (again).
#[tauri::command]
async fn phone_connect(app: AppHandle, phone: State<'_, Phone>) -> Reply<PhoneSession> {
if let Some(c) = phone.current() {
return Ok(c.session.clone());
}
let desktop = phone.paired().ok_or_else(|| failure("notFound", "this phone is not paired with a desktop"))?;
connect(&app, &phone, &desktop, None).await
}
/// Disconnects and forgets the paired desktop.
#[tauri::command]
fn phone_forget(phone: State<'_, Phone>) -> Reply<()> {
if let Some(c) = phone.connection.lock().take() {
c.link.close(0u32.into(), b"forgotten");
}
match std::fs::remove_file(&phone.desktop_file) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(failure("io", e)),
_ => Ok(()),
}
}
/// Runs `cmd` of this window on the desktop. `args` is the arguments' JSON text; streaming
/// arguments are `{ "$channel": id }`, their values arrive on `on_channel` tagged with the id.
#[tauri::command]
async fn remote_invoke(
window: WebviewWindow,
phone: State<'_, Phone>,
cmd: String,
args: String,
on_channel: Channel<ChannelFrame>,
) -> Result<String, Value> {
let c =
phone.current().ok_or_else(|| json!({ "kind": "unavailable", "message": "not connected to the desktop" }))?;
let mut args: Value =
serde_json::from_str(&args).map_err(|e| json!({ "kind": "invalidInput", "message": e.to_string() }))?;
if let Value::Object(map) = &mut args {
for v in map.values_mut() {
if let Some(id) = v.get("$channel").and_then(Value::as_u64) {
let own = c.next_channel.fetch_add(1, Ordering::Relaxed);
c.channels.lock().insert(own, (on_channel.clone(), id));
*v = json!({ "$channel": own });
}
}
}
let call = json!({ "window": format!("{}{}", c.scope, window.label()), "cmd": cmd, "args": args });
match c.peer.request::<_, Value>("invoke", call, None).await {
Ok(value) => Ok(value.to_string()),
// The desktop's `IdeError` is the JSON-RPC error's message.
Err(ide_jsonrpc::RpcError::Server { message, .. }) => {
Err(serde_json::from_str(&message).unwrap_or_else(|_| json!({ "kind": "protocol", "message": message })))
}
Err(e) => Err(json!({ "kind": "unavailable", "message": e.to_string() })),
}
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
// iOS keeps no stderr: a panic's message goes to a file in the app's temporary directory.
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
use std::io::Write;
if let Ok(mut f) =
std::fs::OpenOptions::new().create(true).append(true).open(std::env::temp_dir().join("panic.txt"))
{
let _ = writeln!(f, "{info}");
}
default_hook(info);
}));
// HTTPS clients (iroh's relays) need a process-wide crypto provider.
let _ = rustls::crypto::ring::default_provider().install_default();
tauri::Builder::default()
.setup(|app| {
let data = app.path().app_data_dir()?;
app.manage(Phone {
key_file: data.join("phone.key"),
desktop_file: data.join("desktop.json"),
endpoint: tokio::sync::OnceCell::new(),
connection: Mutex::default(),
connecting: tokio::sync::Mutex::new(()),
});
Ok(())
})
.invoke_handler(tauri::generate_handler![phone_status, phone_pair, phone_connect, phone_forget, remote_invoke])
.run(tauri::generate_context!())
.expect("error while running the OpenIDEA phone app");
}
+6
Переглянути файл
@@ -0,0 +1,6 @@
// Desktop builds of the phone app, for trying it without a simulator.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
openidea_mobile_lib::run()
}
+21
Переглянути файл
@@ -0,0 +1,21 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA Mobile",
"identifier": "ai.l0ng.openidea.mobile",
"build": {
"beforeDevCommand": "pnpm dev:phone",
"devUrl": "http://localhost:1430",
"beforeBuildCommand": "pnpm build:phone",
"frontendDist": "../dist-phone"
},
"app": {
"windows": [{ "label": "main", "title": "OpenIDEA" }],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"icon": ["icons/32x32.png", "icons/128x128.png", "icons/[email protected]", "icons/icon.icns", "icons/icon.ico"]
}
}
+2
Переглянути файл
@@ -7,7 +7,9 @@
"type": "module",
"scripts": {
"dev": "vite",
"dev:phone": "VITE_OPENIDEA_PHONE=1 vite --config vite.phone.config.ts --port 1430 --strictPort",
"build": "node --max-old-space-size=4096 node_modules/typescript/bin/tsc --noEmit && vite build && node scripts/check-webkit.ts",
"build:phone": "VITE_OPENIDEA_PHONE=1 vite build --config vite.phone.config.ts --outDir dist-phone",
"preview": "vite preview",
"tauri": "node scripts/tauri.ts",
"test": "vitest run",
+39
Переглянути файл
@@ -0,0 +1,39 @@
/**
* `pnpm dev:phone` only: runs JavaScript in the phone app's webview for debugging the
* simulator / emulator build. `curl -s localhost:1430/__phone_eval --data-binary 'expr'`
* evaluates `expr` there (through Vite's HMR socket) and answers with its JSON result.
*/
import type { Plugin } from "vite";
export function phoneEval(): Plugin {
let next = 1;
const waiting = new Map<number, (result: string) => void>();
return {
name: "openidea-phone-eval",
apply: "serve",
configureServer(server) {
server.ws.on("phone:eval-result", (data: { id: number; result: string }) => {
waiting.get(data.id)?.(data.result);
waiting.delete(data.id);
});
server.middlewares.use("/__phone_eval", (req, res) => {
let code = "";
req.on("data", (c: Buffer) => (code += c.toString()));
req.on("end", () => {
const id = next++;
const timer = setTimeout(() => {
waiting.delete(id);
res.statusCode = 504;
res.end("no answer from the phone");
}, 10_000);
waiting.set(id, (result) => {
clearTimeout(timer);
res.setHeader("content-type", "application/json");
res.end(result);
});
server.ws.send("phone:eval", { id, code });
});
});
},
};
}
+3
Переглянути файл
@@ -72,6 +72,9 @@ ide-command.workspace = true
ide-mcp.workspace = true
ide-notebook.workspace = true
ide-jsonrpc.workspace = true
ide-pair.workspace = true
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
whoami = { version = "2", default-features = false, features = ["std"] }
ide-tools = { path = "../crates/ide-tools" }
ide-scaffold.workspace = true
ide-plugin = { path = "../crates/ide-plugin" }
+2
Переглянути файл
@@ -37,6 +37,7 @@ pub mod window_group;
pub mod workspace;
pub mod wsl;
use crate::mobile;
use crate::remote_dev;
use ide_host::catalogue::{Command, Placement, TrustClass};
use std::sync::LazyLock;
@@ -206,6 +207,7 @@ fn catalogue() -> (tauri_specta::Commands<tauri::Wry>, Vec<Command>) {
desktop hotkeys;
desktop http;
desktop lsp;
desktop mobile;
desktop nav;
desktop notification;
desktop perf;
+3 -1
Переглянути файл
@@ -4,7 +4,7 @@
//! Tauri adapters of project-host commands are derived from their `ide-host` declarations. No
//! domain logic lives here.
// `commands::catalogue!` recurses a few times per command domain.
#![recursion_limit = "256"]
#![recursion_limit = "512"]
mod application_focus;
mod cli;
@@ -21,6 +21,7 @@ mod logging;
#[cfg(target_os = "macos")]
mod macos;
mod menu;
mod mobile;
#[cfg(target_os = "macos")]
mod page_swipe;
mod plugin_web;
@@ -244,6 +245,7 @@ pub fn run() {
let menu_state = menu::MenuState::default();
menu::install(app.handle(), &menu_state, &state.recent.list());
app.manage(state);
mobile::start_if_paired(app.handle());
{
let state = app.state::<AppState>();
state.host.mcp.apply(&state.host);
+255
Переглянути файл
@@ -0,0 +1,255 @@
//! Phones paired with this desktop over iroh (`ide_pair`).
//!
//! A connected phone is a remote development client of this desktop's backend: its
//! windows (`mobile-<device>-…`) open projects on the shared [`ide_host::Host`], their
//! events go back over the phone's connection, and it can name no other window
//! (`rpc::serve_scoped`). Agent tasks, database connections and repositories are the
//! desktop's own, so the phone sees what the desktop has. When the phone disconnects its
//! projects close.
//!
//! The listener starts when the user pairs a phone, and at start-up once one is paired.
use crate::state::AppState;
use ide_command::desktop_command;
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink};
use ide_host::catalogue::TrustClass;
use ide_host::rpc::{self, Dispatcher};
use ide_jsonrpc::Peer;
use ide_pair::{DeviceStore, Listener, Session, SessionHandler};
use parking_lot::Mutex;
use serde::Serialize;
use specta::Type;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tauri::{AppHandle, Manager, State};
/// Every phone window's label starts with this, then the device's scope.
const WINDOW_PREFIX: &str = "mobile-";
/// How long a pairing code stays valid.
const TICKET_TTL: Duration = Duration::from_secs(300);
/// The desktop's recent projects, which the phone lists as its own.
const PROJECTS_COMMAND: &str = "recent_projects";
/// Commands after which a phone's project is recorded in the recent projects.
const RECORDED_COMMANDS: [&str; 1] = ["open_project"];
/// The prefix of a device's windows: `mobile-<first 12 characters of its id>-`.
pub fn scope_for(device_id: &str) -> String {
let short: String = device_id.chars().take(12).collect();
format!("{WINDOW_PREFIX}{short}-")
}
/// The device scope of a phone's window, `None` for the desktop's own windows.
pub fn scope_of(window: &str) -> Option<&str> {
let rest = window.strip_prefix(WINDOW_PREFIX)?;
let end = rest.find('-')?;
Some(&window[..WINDOW_PREFIX.len() + end + 1])
}
pub struct Mobile {
key_file: PathBuf,
devices_file: PathBuf,
/// The connection of each connected device, by scope.
peers: Mutex<HashMap<String, Arc<OnceLock<Peer>>>>,
listener: tokio::sync::OnceCell<Listener>,
}
impl Mobile {
pub fn new(config_dir: &std::path::Path, data_dir: &std::path::Path) -> Self {
Self {
key_file: data_dir.join("mobile").join("endpoint.key"),
devices_file: config_dir.join("mobile-devices.json"),
peers: Mutex::default(),
listener: tokio::sync::OnceCell::new(),
}
}
/// The event sink of a phone's window (its device's connection); `None` for a desktop window.
pub fn sink(&self, window: &str) -> Option<SharedSink> {
let scope = scope_of(window)?;
let peer = self.peers.lock().entry(scope.to_owned()).or_default().clone();
Some(rpc::event_sink(peer, Some(window.to_owned())))
}
/// Whether a phone has been paired, so the listener should run from start-up.
pub fn has_devices(&self) -> bool {
!DeviceStore::load(&self.devices_file).is_empty()
}
async fn listener(&self, app: &AppHandle) -> IdeResult<&Listener> {
self.listener
.get_or_try_init(|| async {
let endpoint =
ide_pair::bind_desktop(&self.key_file).await.map_err(|e| IdeError::internal(e.to_string()))?;
let store = DeviceStore::load(&self.devices_file);
let serving = app.clone();
let handler: SessionHandler = Arc::new(move |session| Box::pin(serve(serving.clone(), session)));
let notifying = app.clone();
let on_change = Arc::new(move || {
notifying.state::<AppState>().sink.emit(IdeEvent::MobileDevicesChanged);
});
tracing::info!(id = %endpoint.id(), "accepting paired phones");
Ok(Listener::start(endpoint, store, desktop_name(), handler, on_change))
})
.await
}
}
/// Starts accepting paired phones in the background, when there are any.
pub fn start_if_paired(app: &AppHandle) {
if !app.state::<AppState>().mobile.has_devices() {
return;
}
let app = app.clone();
tauri::async_runtime::spawn(async move {
if let Err(e) = app.state::<AppState>().mobile.listener(&app).await {
tracing::warn!("cannot accept paired phones: {}", e.message);
}
});
}
fn desktop_name() -> String {
whoami::devicename().ok().filter(|n| !n.trim().is_empty()).unwrap_or_else(|| "OpenIDEA".into())
}
/// Serves one connected phone until it disconnects, then closes its projects.
async fn serve(app: AppHandle, session: Session) {
let state = app.state::<AppState>();
let scope = scope_for(&session.device.id);
let peer = Arc::new(OnceLock::new());
state.mobile.peers.lock().insert(scope.clone(), peer.clone());
let mut dispatcher = Dispatcher::standard();
let listing = app.clone();
dispatcher.add(PROJECTS_COMMAND, TrustClass::Always, move |_| {
let app = listing.clone();
async move {
let projects = tokio::task::spawn_blocking(move || app.state::<AppState>().recent.list_live())
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(projects)
}
});
// Projects a phone opens are recent projects of this desktop too, as the desktop's own windows record them.
for command in RECORDED_COMMANDS {
let recording = app.clone();
dispatcher.after(command, move |host, window| {
if let Ok(project) = host.project(window)
&& !project.light
&& let Err(e) = recording.state::<AppState>().record_project(&project)
{
tracing::warn!("cannot record {}: {}", project.root.display(), e.message);
}
});
}
tracing::info!(device = %session.device.name, "phone connected");
rpc::serve_scoped(state.host.clone(), dispatcher, peer.clone(), session.recv, session.send, Some(scope.clone()))
.await;
tracing::info!(device = %session.device.name, "phone disconnected");
{
let mut peers = state.mobile.peers.lock();
if peers.get(&scope).is_some_and(|p| Arc::ptr_eq(p, &peer)) {
peers.remove(&scope);
}
}
for window in state.host.windows() {
if window.starts_with(&scope) {
state.host.close_project_detached(&window);
}
}
}
/// A pairing code to show as a QR code.
#[derive(Clone, Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MobilePairing {
/// What the QR code holds (`openidea-pair:…`).
pub ticket: String,
/// The QR code as an SVG document.
pub qr_svg: String,
pub expires_in_secs: u32,
/// This desktop's name, as the phone shows it.
pub desktop: String,
}
#[derive(Clone, Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MobileDevice {
pub id: String,
pub name: String,
/// Milliseconds since the Unix epoch.
pub paired_at_ms: f64,
pub online: bool,
}
/// Starts accepting phones and gives the pairing code: the current one while it works, else a new one.
#[desktop_command(trust = outside_restricted)]
#[tauri::command]
#[specta::specta]
pub async fn mobile_pair(app: AppHandle, state: State<'_, AppState>) -> IdeResult<MobilePairing> {
let listener = state.mobile.listener(&app).await?;
let (ticket, left) = listener.ticket(TICKET_TTL).await;
let text = ticket.encode();
let qr = qrcode::QrCode::with_error_correction_level(text.as_bytes(), qrcode::EcLevel::L)
.map_err(|e| IdeError::internal(e.to_string()))?;
let qr_svg = qr.render::<qrcode::render::svg::Color>().quiet_zone(true).min_dimensions(240, 240).build();
Ok(MobilePairing { ticket: text, qr_svg, expires_in_secs: left.as_secs() as u32, desktop: ticket.desktop })
}
/// Stops the current pairing code from pairing anything.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn mobile_cancel_pairing(state: State<'_, AppState>) -> IdeResult<()> {
if let Some(listener) = state.mobile.listener.get() {
listener.cancel_pairing();
}
Ok(())
}
/// The paired phones, each with whether it is connected now.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn mobile_devices(state: State<'_, AppState>) -> IdeResult<Vec<MobileDevice>> {
let devices = match state.mobile.listener.get() {
Some(listener) => listener.devices(),
None => DeviceStore::load(&state.mobile.devices_file).list().into_iter().map(|d| (d, false)).collect(),
};
Ok(devices
.into_iter()
.map(|(d, online)| MobileDevice { id: d.id, name: d.name, paired_at_ms: d.paired_at as f64 * 1000.0, online })
.collect())
}
/// Forgets a paired phone and drops its connection; it has to pair again.
#[desktop_command(trust = outside_restricted)]
#[tauri::command]
#[specta::specta]
pub async fn mobile_device_remove(app: AppHandle, state: State<'_, AppState>, id: String) -> IdeResult<()> {
let removed = match state.mobile.listener.get() {
Some(listener) => listener.remove(&id)?,
None => DeviceStore::load(&state.mobile.devices_file).remove(&id)?,
};
if removed && state.mobile.listener.get().is_none() {
app.state::<AppState>().sink.emit(IdeEvent::MobileDevicesChanged);
}
Ok(())
}
ide_command::desktop_domain!(mobile_cancel_pairing, mobile_device_remove, mobile_devices, mobile_pair);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_phone_window_belongs_to_its_device_scope() {
let scope = scope_for("4f6c2a9b81d3e5f7a0b2c4d6e8f0");
assert_eq!(scope, "mobile-4f6c2a9b81d3-");
assert_eq!(scope_of(&format!("{scope}1")), Some(scope.as_str()));
assert_eq!(scope_of("main"), None);
assert_eq!(scope_of("settings-main"), None);
assert_eq!(scope_of("mobile-"), None);
}
}
+9
Переглянути файл
@@ -23,6 +23,8 @@ pub struct AppState {
pub askpass: Option<ide_ssh::askpass::AskpassServer>,
/// Remote development connections, by window label.
pub remote_dev: crate::remote_dev::Connections,
/// Phones paired with this desktop, and their connections.
pub mobile: Arc<crate::mobile::Mobile>,
/// Broadcasts to every window.
pub sink: SharedSink,
}
@@ -91,6 +93,8 @@ impl AppState {
let languages = Arc::new(LanguageRegistry::load(Some(&config_dir.join("languages")))?);
let sink_app = app.clone();
let sink_runtime = runtime.clone();
let mobile = Arc::new(crate::mobile::Mobile::new(&config_dir, &data_dir));
let sink_mobile = mobile.clone();
let host = Arc::new(Host::new(ide_host::HostConfig {
config_dir: config_dir.clone(),
data_dir: data_dir.clone(),
@@ -98,6 +102,10 @@ impl AppState {
languages: languages.clone(),
syntax,
sink_for: Box::new(move |window| {
// A paired phone's window: its events go to the phone.
if let Some(sink) = sink_mobile.sink(window) {
return sink;
}
coalescing_sink(
Arc::new(TauriSink { app: sink_app.clone(), window: Some(window.to_owned()) }),
sink_runtime.clone(),
@@ -117,6 +125,7 @@ impl AppState {
sink: global_sink,
plugins: crate::commands::plugin::create_host(&app, &data_dir, &host)?,
remote_dev: crate::remote_dev::Connections::default(),
mobile,
host,
startup: Startup {
process_to_main,
+4
Переглянути файл
@@ -410,6 +410,10 @@ menu_configure always desktop bin
menu_model always desktop bindings sync
menu_refresh always desktop bindings sync
menu_set_disabled always desktop bindings sync
mobile_cancel_pairing always desktop bindings async
mobile_device_remove outside_restricted desktop bindings async
mobile_devices always desktop bindings async
mobile_pair outside_restricted desktop bindings async
nav_index_definitions always project_host bindings async
nav_inheritance always project_host bindings async
nav_resolve_module always project_host bindings async
+29
Переглянути файл
@@ -1076,6 +1076,14 @@ export const commands = {
* disabled in place (no rebuild).
*/
menuSetDisabled: (ids: string[]) => __TAURI_INVOKE<void>("menu_set_disabled", { ids }),
/** Stops the current pairing code from pairing anything. */
mobileCancelPairing: () => typedError<null, IdeError>(__TAURI_INVOKE("mobile_cancel_pairing")),
/** Forgets a paired phone and drops its connection; it has to pair again. */
mobileDeviceRemove: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("mobile_device_remove", { id })),
/** The paired phones, each with whether it is connected now. */
mobileDevices: () => typedError<MobileDevice[], IdeError>(__TAURI_INVOKE("mobile_devices")),
/** Starts accepting phones and gives the pairing code: the current one while it works, else a new one. */
mobilePair: () => typedError<MobilePairing, IdeError>(__TAURI_INVOKE("mobile_pair")),
/**
* Index definitions named `name` within the roots `from` may navigate into (its own root
* plus its configured dependencies).
@@ -7872,6 +7880,8 @@ export type IdeEvent =
{ type: "windowGroupsChanged" } |
/** A project was loaded or unloaded for the MCP server without a window of its own. */
{ type: "mcpBackgroundProjectsChanged" } |
/** A phone paired with this desktop, connected, disconnected or was removed. */
{ type: "mobileDevicesChanged" } |
/** A window entered or left full screen, itself or as a member of a full-screen window group. */
{ type: "windowFullscreenChanged" } |
/**
@@ -9796,6 +9806,25 @@ export type MethodStat = {
total: number | null,
};
export type MobileDevice = {
id: string,
name: string,
/** Milliseconds since the Unix epoch. */
pairedAtMs: number | null,
online: boolean,
};
/** A pairing code to show as a QR code. */
export type MobilePairing = {
/** What the QR code holds (`openidea-pair:…`). */
ticket: string,
/** The QR code as an SVG document. */
qrSvg: string,
expiresInSecs: number,
/** This desktop's name, as the phone shows it. */
desktop: string,
};
/** Dependency entry of a module (Project Structure › Modules › Dependencies). */
export type ModuleDependency = {
/** `"library"` (references a `ProjectLibrary` by name or path) or `"module"` (references another module). */
+2
Переглянути файл
@@ -3,6 +3,7 @@
* parts that change at runtime (language, settings, contributions).
*/
import { Compartment, EditorState, Facet, Prec, type Extension, type Range } from "@codemirror/state";
import { touchReadMode } from "./touchReadMode";
import {
Decoration,
EditorView,
@@ -419,6 +420,7 @@ export function baseExtensions(o: SetupOptions): Extension {
compartments.comments.of(commentTokens(o.info, o.ctx.language)),
compartments.indent.of(indentExtension(o.indent ?? effectiveIndent(o.settings, o.info), o.formatIndent)),
compartments.readOnly.of(readOnlyExtension(o.ctx.readOnly)),
touchReadMode,
compartments.wrap.of(wrapExtension(o.settings, o.ctx.path, o.wrapOverride)),
compartments.sticky.of(stickyExtension(o.settings)),
compartments.heavy.of(heavyExtension(o.docLength, o.settings)),
+76
Переглянути файл
@@ -0,0 +1,76 @@
/**
* On a touch screen the editor opens for reading: a tap moves the caret or picks a symbol and
* a long press opens the context menu, without the on-screen keyboard (which would cover half
* the screen) and without typing by accident. Edit (the editor tab row's pencil) turns every
* editor to editing until Done.
*
* Reading makes the state read-only, so the commands and menu entries that check it (Paste,
* Cut, editing actions) step aside as they do for a read-only file; a file that is read-only
* itself stays so while editing.
*/
import { EditorState, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { ViewPlugin, type EditorView } from "@codemirror/view";
import { create } from "zustand";
import { useFormFactor } from "@/platform/formFactor";
import { LONG_PRESS_MS } from "@/platform/longPress";
export const useTouchEditing = create<{ editing: boolean }>(() => ({ editing: false }));
export function setTouchEditing(editing: boolean) {
useTouchEditing.setState({ editing });
}
const readingNow = () => useFormFactor.getState().touch && !useTouchEditing.getState().editing;
const setReading = StateEffect.define<boolean>();
const reading = StateField.define<boolean>({
create: readingNow,
update: (value, tr) => {
for (const e of tr.effects) if (e.is(setReading)) value = e.value;
return value;
},
});
const follow = ViewPlugin.fromClass(
class {
private readonly off: Array<() => void>;
constructor(private readonly view: EditorView) {
this.apply();
const apply = () => this.apply();
// A long press would select a word and raise the system's Cut / Copy / Paste bar over
// the editor's own menu: while reading, a press held that long selects nothing. A tap
// still places the caret.
let downAt = 0;
const down = () => (downAt = Date.now());
const noNativeSelection = (e: Event) => {
if (this.view.state.field(reading) && Date.now() - downAt > LONG_PRESS_MS * 0.6) e.preventDefault();
};
view.contentDOM.addEventListener("pointerdown", down);
view.contentDOM.addEventListener("selectstart", noNativeSelection);
this.off = [
useTouchEditing.subscribe(apply),
useFormFactor.subscribe(apply),
() => view.contentDOM.removeEventListener("pointerdown", down),
() => view.contentDOM.removeEventListener("selectstart", noNativeSelection),
];
}
apply() {
const now = readingNow();
// `none` keeps the keyboard down while the content still takes the caret and selection.
if (now) this.view.contentDOM.setAttribute("inputmode", "none");
else this.view.contentDOM.removeAttribute("inputmode");
if (this.view.state.field(reading) !== now) this.view.dispatch({ effects: setReading.of(now) });
}
destroy() {
this.off.forEach((f) => f());
}
},
);
/** Lowest precedence: a read-only file's own `readOnly` comes first and wins. */
export const touchReadMode: Extension = Prec.lowest([
reading,
EditorState.readOnly.compute([reading], (s) => s.field(reading)),
follow,
]);
+44 -1
Переглянути файл
@@ -3,6 +3,7 @@
* status, navigation history, autosave. The React views and actions talk to
* this singleton; other features use the EditorService and editor/api.
*/
import { useFormFactor } from "@/platform/formFactor";
import { writeClipboardText } from "@/platform/clipboard";
import { pasteEditorClipboard } from "./cm/clipboard";
import { saveOnBlur } from "./saveOnBlur";
@@ -1030,7 +1031,8 @@ export class EditorController implements SlotHost {
},
] as MenuItem[])),
];
showContextMenu(e, items);
const phone = useFormFactor.getState().formFactor === "phone";
showContextMenu(e, phone ? phoneEditorMenu(slot, view, hoverItems, caretLine) : items);
}
// --- status / context ------------------------------------------------------------
@@ -2510,3 +2512,44 @@ let controller: EditorController | null = null;
export function editorController(): EditorController {
return (controller ??= new EditorController());
}
/**
* The editor's long-press menu on a phone: reading and finding your way (navigation, usages,
* documentation, context actions, running, Git), plus Cut / Paste while editing. What needs a
* keyboard, a mouse or a wide window (column selection, folding, splits, refactorings beyond
* Rename, comparing, opening elsewhere) is left to the desktop.
*/
function phoneEditorMenu(
slot: EditorSlot,
view: NonNullable<EditorSlot["view"]>,
hoverItems: MenuItem[],
caretLine: number,
): MenuItem[] {
const hasSel = !view.state.selection.main.empty;
const editing = !view.state.readOnly;
return [
{ kind: "action", action: "code.showIntentions", label: "Show Context Actions", icon: "bulb" },
{ kind: "action", action: "code.quickDocumentation" },
...(hoverItems.length ? ([{ kind: "separator" }, ...hoverItems] as MenuItem[]) : []),
{ kind: "separator" },
{ kind: "action", action: "navigate.declaration", label: "Go to Declaration or Usages" },
{ kind: "action", action: "navigate.implementation", label: "Go to Implementation(s)" },
{ kind: "action", action: "navigate.typeDeclaration", label: "Go to Type Declaration" },
{ kind: "action", action: "find.usages", label: "Find Usages" },
{ kind: "separator" },
...((hasSel
? [
...(editing ? [{ label: "Cut", icon: "cut", run: () => (view.focus(), document.execCommand("cut")) }] : []),
{ label: "Copy", icon: "copy", run: () => (view.focus(), document.execCommand("copy")) },
]
: []) as MenuItem[]),
...(editing ? ([{ label: "Paste", icon: "paste", run: () => void pasteEditorClipboard(view) }] as MenuItem[]) : []),
slot.model.virtual
? { label: "Copy Reference", run: () => void writeClipboardText(slot.model.path) }
: { kind: "action", action: "editor.copyReference" },
{ kind: "separator" },
{ kind: "action", action: "refactor.rename", label: "Rename…" },
...menuGroupItems("editor", { paths: [slot.model.path], text: view.state.doc.toString(), line: caretLine }),
...(slot.model.virtual ? [] : ([{ kind: "separator" }, gitMenu(slot.model.path)] as MenuItem[])),
];
}
+30 -9
Переглянути файл
@@ -1,4 +1,6 @@
import { ContributedToolbar } from "@/workbench/ContributedToolbar";
import { useFormFactor } from "@/platform/formFactor";
import { setTouchEditing, useTouchEditing } from "../cm/touchReadMode";
import { useFilePresentations } from "@/ui/filePresentation";
/**
* The editor area: split layout of panes, each with IDEA-style tabs (preview
@@ -574,19 +576,38 @@ function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
: undefined;
const [open, setOpen] = useState(false);
const moreRef = useRef<HTMLButtonElement>(null);
const phone = useFormFactor((s) => s.formFactor === "phone");
const editing = useTouchEditing((s) => s.editing);
return (
<div className={styles.tabActions}>
<ContributedToolbar slot="editor.title" />
{LayoutActions && <LayoutActions path={tab.input.path!} tabId={tab.id} />}
<IconButton
icon="split"
title="Split Right"
size="small"
onClick={() => {
ctrl.activate(paneId, tab.id, false);
ctrl.split(paneId, "row");
}}
/>
{phone ? (
// A phone has no room for splits; its editors open for reading (`touchReadMode`).
<IconButton
icon={editing ? "check" : "edit"}
title={editing ? "Done" : "Edit"}
size="small"
pressed={editing}
onClick={() => {
setTouchEditing(!editing);
const content = document.querySelector<HTMLElement>(`[data-pane-id="${CSS.escape(paneId)}"] .cm-content`);
// Focused in the tap itself, or iOS keeps the keyboard down.
if (!editing) content?.focus();
else content?.blur();
}}
/>
) : (
<IconButton
icon="split"
title="Split Right"
size="small"
onClick={() => {
ctrl.activate(paneId, tab.id, false);
ctrl.split(paneId, "row");
}}
/>
)}
<IconButton
ref={moreRef}
icon="more"
+130
Переглянути файл
@@ -0,0 +1,130 @@
.page {
flex: 1;
min-height: 0;
height: 100%;
display: flex;
flex-direction: column;
}
.center {
margin: auto;
padding: var(--space-4);
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-3);
color: var(--fg-muted);
}
/* Task list */
.listBar {
flex: none;
display: flex;
align-items: center;
gap: var(--space-1);
min-height: 40px;
padding: 0 var(--space-2) 0 var(--space-1);
border-bottom: 1px solid var(--border);
}
.search {
flex: 1;
min-width: 0;
}
.list {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow-y: auto;
padding-bottom: var(--space-4);
}
.empty {
margin: 0;
padding: var(--space-4);
color: var(--fg-muted);
text-align: center;
}
.list > .section:first-child {
margin-top: var(--space-1);
}
.section + .section {
margin-top: var(--space-2);
}
.sectionHead {
width: 100%;
display: flex;
align-items: center;
gap: var(--space-2);
min-height: 32px;
padding: 0 var(--space-4);
border: 0;
background: none;
color: var(--fg-muted);
font: inherit;
font-size: var(--fs-small);
font-weight: 600;
text-align: left;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.count {
flex: 1;
font-weight: 400;
}
.rows {
margin: 0;
padding: 0;
list-style: none;
}
.row {
width: 100%;
display: flex;
align-items: center;
gap: var(--space-3);
min-height: 60px;
padding: var(--space-2) var(--space-3) var(--space-2) var(--space-4);
border: 0;
background: none;
color: var(--fg-strong);
font: inherit;
text-align: left;
}
.row:active {
background: var(--bg-hover);
}
.rows > li + li .row {
box-shadow: inset 0 1px 0 var(--border);
}
.rowText {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: var(--space-0-5);
}
.rowTitle,
.rowDetail {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rowTitle.unread {
font-weight: 600;
}
.rowDetail {
display: flex;
align-items: center;
gap: var(--space-1);
color: var(--fg-muted);
font-size: var(--fs-small);
}
.unreadDot {
flex: none;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
}
.chevron {
flex: none;
color: var(--fg-muted);
}
+252
Переглянути файл
@@ -0,0 +1,252 @@
/**
* The Agents page on a phone: the task list, and a task's conversation or New Task as a
* page of its own with a way back, as a phone's chat apps are laid out. The conversation,
* composer and changes are the desktop's (`SessionEditor` / `HomeEditor` docked); what
* belongs to a mouse and a large window (dragging tasks between groups, chat placement, the
* history popup, organising groups, importing sessions) is left out. Long press opens a task's menu.
*/
import { useMemo, useRef, useState } from "react";
import clsx from "clsx";
import type { AgentTask } from "@/bindings";
import { Button, EmptyState, HighlightedText, Icon, IconButton, Menu, SearchField, Spinner, T } from "@/ui";
import { showContextMenu } from "@/ui";
import { tx, useTx } from "@/platform/i18n";
import { basename, useProject } from "@/platform/project";
import { useOwnToolWindowHeader, useToolWindowPageNav } from "@/workbench/toolwindows/ToolWindows";
import { SESSION_KIND, age, branchLabel, groupTasks, providerIcon, sessionKey, statusLabel } from "./model";
import { groupMembers, pinnedMembers, ungroupedMembers } from "./organize";
import { closeInline, openHome, openTask, useAgents } from "./store";
import { taskMenu } from "./taskActions";
import { matchTask } from "./taskSearch";
import { SessionEditor } from "./SessionEditor";
import { HomeEditor } from "./HomeEditor";
import { TaskStatusMark } from "./TaskStatusMark";
import styles from "./AgentsPhone.module.css";
export function AgentsPhone() {
useOwnToolWindowHeader(true);
const docked = useAgents((s) => s.docked);
const homeOpen = useAgents((s) => s.homeOpen);
const title = useAgents((s) => (docked ? (s.tasks.get(docked)?.title ?? docked) : null));
const hasTask = useAgents((s) => !!docked && s.tasks.has(docked));
// The shell's top bar leads back to the list from a task or New Task.
const nav = useMemo(
() =>
homeOpen
? { title: tx("New Task"), back: closeInline }
: docked
? {
title,
detail: hasTask ? <TaskDetail id={docked} /> : undefined,
back: closeInline,
actions: hasTask ? <TaskMenuButton id={docked} /> : undefined,
}
: null,
[homeOpen, docked, title, hasTask],
);
useToolWindowPageNav(nav);
if (homeOpen) return <HomeEditor docked />;
if (docked) {
return (
<SessionEditor
docked
input={{ kind: SESSION_KIND, key: sessionKey(docked), data: { task: docked, title: title ?? undefined } }}
/>
);
}
return <TaskList />;
}
function TaskMenuButton({ id }: { id: string }) {
const task = useAgents((s) => s.tasks.get(id));
const ref = useRef<HTMLButtonElement>(null);
const [open, setOpen] = useState(false);
if (!task) return null;
return (
<>
<IconButton
ref={ref}
icon="more"
title="Task Actions"
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
/>
<Menu
open={open}
onClose={() => setOpen(false)}
anchor={ref}
items={open ? taskMenu([task]) : []}
placement="bottom-end"
/>
</>
);
}
function TaskDetail({ id }: { id: string }) {
const task = useAgents((s) => s.tasks.get(id));
if (!task) return null;
return (
<>
<TaskStatusMark task={task.id} />
<T>{statusLabel(task.status)}</T>
{task.isolation === "worktree" && <span>· {branchLabel(task.branch)}</span>}
</>
);
}
interface Section {
key: string;
label: string;
tasks: AgentTask[];
}
function TaskList() {
const t = useTx();
const loaded = useAgents((s) => s.loaded);
const error = useAgents((s) => s.error);
const tasks = useAgents((s) => s.tasks);
const unread = useAgents((s) => s.unread);
const organize = useAgents((s) => s.organize);
const providers = useAgents((s) => s.providers);
const project = useProject((s) => s.project);
const [query, setQuery] = useState("");
const [open, setOpen] = useState<Set<string>>(() => new Set());
const matches = useMemo(() => {
if (!query.trim()) return null;
const found = new Map<string, number[]>();
for (const task of tasks.values()) {
const hit = matchTask(task, query);
if (hit) found.set(task.id, hit);
}
return found;
}, [tasks, query]);
const sections = useMemo<Section[]>(() => {
const all = [...tasks.values()].filter((task) => !matches || matches.has(task.id));
const pinned = pinnedMembers(all, organize);
return [
...(pinned.length ? [{ key: "pinned", label: "Pinned", tasks: pinned }] : []),
...organize.groups.map((g) => ({ key: `c:${g.id}`, label: g.name, tasks: groupMembers(all, organize, g.id) })),
...groupTasks(ungroupedMembers(all, organize)).map((g) => ({
key: `g:${g.status}`,
label: g.label,
tasks: g.tasks,
})),
].filter((s) => s.tasks.length > 0);
}, [tasks, organize, matches]);
if (!loaded)
return (
<div className={styles.center}>
<Spinner />
</div>
);
if (error) return <EmptyState title="Cannot load agent tasks">{error}</EmptyState>;
const providerName = (id: string) => providers.find((p) => p.id === id)?.name ?? id;
return (
<div className={styles.page}>
<div className={styles.listBar}>
{tasks.size > 0 ? (
<SearchField
className={styles.search}
variant="bare"
value={query}
onChange={setQuery}
clearable
placeholder={t("Search tasks")}
aria-label={t("Search tasks")}
/>
) : (
<span className={styles.search} />
)}
<IconButton icon="plus" size="small" title="New Task" onClick={() => openHome()} />
</div>
<div className={styles.list}>
{sections.length === 0 &&
(matches ? (
<p className={styles.empty}>
<T>No matching tasks</T>
</p>
) : (
<div className={styles.center}>
<Icon name="toolwindow-agents" size={32} />
<p className={styles.empty}>
<T>No agent tasks yet</T>
</p>
<Button variant="primary" onClick={() => openHome()}>
<T>New Task</T>
</Button>
</div>
))}
{sections.map((section) => {
// Archived tasks stay folded until asked for (or found by a search).
const folded = section.key === "g:archived" && !matches && !open.has(section.key);
return (
<section key={section.key} className={styles.section}>
<button
type="button"
className={styles.sectionHead}
aria-expanded={!folded}
onClick={() =>
setOpen((o) => {
const next = new Set(o);
if (folded) next.add(section.key);
else next.delete(section.key);
return next;
})
}
>
<span>{tx(section.label)}</span>
<span className={styles.count}>{section.tasks.length}</span>
{section.key === "g:archived" && <Icon name={folded ? "chevron-right" : "chevron-down"} size={14} />}
</button>
{!folded && (
<ul className={styles.rows}>
{section.tasks.map((task) => (
<li key={task.id}>
<button
type="button"
className={styles.row}
onClick={() => openTask(task.id)}
onContextMenu={(e) => showContextMenu(e, taskMenu([task]))}
>
<Icon name={providerIcon(task.provider)} size={20} label={providerName(task.provider)} />
<span className={styles.rowText}>
<span className={clsx(styles.rowTitle, unread.has(task.id) && styles.unread)}>
{matches?.get(task.id)?.length ? (
<HighlightedText text={task.title} indices={matches.get(task.id)!} />
) : (
task.title
)}
</span>
<span className={styles.rowDetail}>
{task.status !== "ready" && task.status !== "archived" && (
<>
<TaskStatusMark task={task.id} />
<T>{statusLabel(task.status)}</T>
<span aria-hidden="true">·</span>
</>
)}
{project?.workspace && <span>{basename(task.projectRoot ?? project.root)} ·</span>}
{task.isolation === "worktree" && <span>{branchLabel(task.branch)} ·</span>}
<span>{age(task.updatedMs ?? 0)}</span>
</span>
</span>
{unread.has(task.id) && (
<span className={styles.unreadDot} role="img" aria-label={t("Unread")} />
)}
<Icon name="chevron-right" size={16} className={styles.chevron} />
</button>
</li>
))}
</ul>
)}
</section>
);
})}
</div>
</div>
);
}
+8
Переглянути файл
@@ -45,6 +45,8 @@ import { groupMenu, taskMenu } from "./taskActions";
import { matchTask } from "./taskSearch";
import { SessionEditor } from "./SessionEditor";
import { HomeEditor } from "./HomeEditor";
import { AgentsPhone } from "./AgentsPhone";
import { useFormFactor } from "@/platform/formFactor";
import styles from "./Agents.module.css";
import { basename, useProject } from "@/platform/project";
import { useTx } from "@/platform/i18n";
@@ -161,7 +163,13 @@ function TaskStatusIcon({ status }: { status: Status }) {
}
}
/** The tool window's content: on a phone a page layout of its own (`AgentsPhone`). */
export function AgentsView() {
const phone = useFormFactor((s) => s.formFactor === "phone");
return phone ? <AgentsPhone /> : <AgentsDesktopView />;
}
function AgentsDesktopView() {
const project = useProject((s) => s.project);
const tx = useTx();
const loaded = useAgents((s) => s.loaded);
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more