Initial impl
This commit is contained in:
commit
4b729c5d32
133 files changed
+20475
No files matched your search
@@ -0,0 +1,58 @@
|
||||
[package]
|
||||
name = "reqlite-app"
|
||||
description = "reqlite desktop app (egui)."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
build = "build.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "reqlite-gui"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# Use the OpenGL renderer instead of wgpu (old GPUs, VMs, remote desktops).
|
||||
glow = ["eframe/glow"]
|
||||
|
||||
[dependencies]
|
||||
reqlite-core.workspace = true
|
||||
reqlite-http-curl.workspace = true
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
directories.workspace = true
|
||||
eframe.workspace = true
|
||||
egui.workspace = true
|
||||
egui_extras.workspace = true
|
||||
image.workspace = true
|
||||
notify.workspace = true
|
||||
rfd.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-appender.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
egui_kittest.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.build-dependencies]
|
||||
winresource.workspace = true
|
||||
|
||||
# `cargo bundle --release -p reqlite-app` builds a macOS .app (and .deb).
|
||||
[package.metadata.bundle]
|
||||
name = "reqlite"
|
||||
identifier = "se.torbjornmolin.reqlite"
|
||||
icon = ["assets/icon.png"]
|
||||
category = "public.app-category.developer-tools"
|
||||
short_description = "A small API client for .http files"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.5 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.9 KiB |
@@ -0,0 +1,9 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=reqlite
|
||||
Comment=A small API client for .http files
|
||||
Exec=reqlite-gui %f
|
||||
Icon=reqlite
|
||||
Terminal=false
|
||||
Categories=Development;Network;
|
||||
StartupWMClass=reqlite
|
||||
@@ -0,0 +1,13 @@
|
||||
//! Embeds the icon and version info in the Windows executable.
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=assets/icon.ico");
|
||||
#[cfg(windows)]
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("assets/icon.ico");
|
||||
res.set("ProductName", "reqlite");
|
||||
res.set("FileDescription", "reqlite API client");
|
||||
res.compile().expect("embedding Windows resources");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,761 @@
|
||||
//! `update()` tests: app behaviour without a window.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use reqlite_core::collection::{Collection, Node};
|
||||
use reqlite_core::env::EnvFile;
|
||||
use reqlite_core::http::{BodyStore, Timings};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn state() -> AppState {
|
||||
AppState::default()
|
||||
}
|
||||
|
||||
fn active(s: &AppState) -> TabId {
|
||||
s.active.expect("an active tab")
|
||||
}
|
||||
|
||||
fn response(status: u16, body: &str, headers: &[(&str, &str)]) -> Response {
|
||||
Response {
|
||||
status,
|
||||
reason: "OK".into(),
|
||||
http_version: "HTTP/1.1".into(),
|
||||
headers: headers.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
|
||||
body: BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())),
|
||||
timings: Timings {
|
||||
total: Duration::from_millis(12),
|
||||
..Default::default()
|
||||
},
|
||||
size: body.len() as u64,
|
||||
effective_url: "http://x/".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded collection at `/c` with the given files.
|
||||
fn with_collection(s: &mut AppState, files: &[(&str, &str)]) -> PathBuf {
|
||||
let root = PathBuf::from("/c");
|
||||
let c = Collection {
|
||||
root: root.clone(),
|
||||
tree: Node::Folder {
|
||||
name: "c".into(),
|
||||
path: root.clone(),
|
||||
children: files
|
||||
.iter()
|
||||
.map(|(n, _)| Node::File {
|
||||
name: n.to_string(),
|
||||
path: root.join(n),
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
files: files
|
||||
.iter()
|
||||
.map(|(n, t)| (root.join(n), HttpFile::parse(t.to_string())))
|
||||
.collect(),
|
||||
};
|
||||
let fx = update(s, Action::CollectionLoaded(Ok(c)));
|
||||
assert!(fx.iter().any(|e| matches!(e, Effect::Watch(Some(_)))));
|
||||
assert!(fx.iter().any(|e| matches!(e, Effect::LoadEnvironments(_))));
|
||||
root
|
||||
}
|
||||
|
||||
fn writes(fx: &[Effect]) -> Vec<(PathBuf, String)> {
|
||||
fx.iter()
|
||||
.filter_map(|e| match e {
|
||||
Effect::FileOps { ops, .. } => Some(ops),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.filter_map(|op| match op {
|
||||
FileOp::Write(p, t) => Some((p.clone(), t.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- URL & params
|
||||
|
||||
#[test]
|
||||
fn url_and_params_stay_in_sync() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "{{base}}/users?limit=20&q=a".into()));
|
||||
let t = s.tab(id).unwrap();
|
||||
assert_eq!(t.params, vec![Param::new("limit", "20"), Param::new("q", "a")]);
|
||||
|
||||
let mut p = t.params.clone();
|
||||
p[0].value = Some("50".into());
|
||||
p.remove(1);
|
||||
p.push(Param::new("sort", "{{order}}"));
|
||||
update(&mut s, Action::ParamsEdited(id, p));
|
||||
assert_eq!(s.tab(id).unwrap().request.url, "{{base}}/users?limit=50&sort={{order}}");
|
||||
|
||||
update(&mut s, Action::ParamsEdited(id, vec![]));
|
||||
assert_eq!(s.tab(id).unwrap().request.url, "{{base}}/users");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasting_curl_into_the_url_bar_imports_it() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(
|
||||
&mut s,
|
||||
Action::UrlEdited(
|
||||
id,
|
||||
"curl -X POST 'https://api.x/y?z=1' -H 'A: b' --data-raw '{\"k\":1}'".into(),
|
||||
),
|
||||
);
|
||||
let t = s.tab(id).unwrap();
|
||||
assert_eq!(t.request.method, Method::Post);
|
||||
assert_eq!(t.request.url, "https://api.x/y?z=1");
|
||||
assert_eq!(t.request.header("A"), Some("b"));
|
||||
assert_eq!(t.request.body, Body::Text("{\"k\":1}".into()));
|
||||
assert_eq!(t.params, vec![Param::new("z", "1")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_edits_update_the_source_and_source_edits_update_the_form() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "http://x/a".into()));
|
||||
assert_eq!(s.tab(id).unwrap().source, "GET http://x/a\n");
|
||||
|
||||
update(&mut s, Action::SourceEdited(id, "POST http://x/b\nA: 1\n\nbody".into()));
|
||||
let t = s.tab(id).unwrap();
|
||||
assert_eq!(t.request.method, Method::Post);
|
||||
assert_eq!(t.request.url, "http://x/b");
|
||||
assert_eq!(t.request.body, Body::Text("body".into()));
|
||||
assert!(t.source_error.is_none());
|
||||
|
||||
update(&mut s, Action::SourceEdited(id, "GET /a\n\n###\nGET /b\n".into()));
|
||||
assert!(s.tab(id).unwrap().source_error.is_some());
|
||||
// Sending is refused while the source is broken.
|
||||
assert!(update(&mut s, Action::Send(id)).is_empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- send & receive
|
||||
|
||||
#[test]
|
||||
fn send_then_receive() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "http://localhost/x".into()));
|
||||
let fx = update(&mut s, Action::Send(id));
|
||||
let (seq, cancel) = match &fx[..] {
|
||||
[Effect::SendRequest {
|
||||
tab,
|
||||
seq,
|
||||
request,
|
||||
cancel,
|
||||
}] => {
|
||||
assert_eq!(*tab, id);
|
||||
assert_eq!(request.url, "http://localhost/x");
|
||||
(*seq, cancel.clone())
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert!(s.tab(id).unwrap().in_flight.is_some());
|
||||
// A second send while in flight is ignored.
|
||||
assert!(update(&mut s, Action::Send(id)).is_empty());
|
||||
|
||||
let fx = update(
|
||||
&mut s,
|
||||
Action::ResponseReceived {
|
||||
tab: id,
|
||||
seq,
|
||||
result: Ok(response(200, "{\"a\":1}", &[("content-type", "application/json")])),
|
||||
},
|
||||
);
|
||||
assert!(!cancel.is_cancelled());
|
||||
let t = s.tab(id).unwrap();
|
||||
assert!(t.in_flight.is_none());
|
||||
assert_eq!(t.response.as_ref().unwrap().response.status, 200);
|
||||
assert!(fx.iter().any(|e| matches!(e, Effect::PrepareBody { .. })));
|
||||
assert!(fx
|
||||
.iter()
|
||||
.any(|e| matches!(e, Effect::AppendHistory(h) if h.status == Some(200))));
|
||||
assert_eq!(s.history.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_stops_the_request_and_ignores_a_late_response() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "http://localhost/slow".into()));
|
||||
let fx = update(&mut s, Action::Send(id));
|
||||
let Effect::SendRequest { seq, cancel, .. } = &fx[0] else {
|
||||
panic!()
|
||||
};
|
||||
let (seq, cancel) = (*seq, cancel.clone());
|
||||
|
||||
update(&mut s, Action::Cancel(id));
|
||||
assert!(cancel.is_cancelled());
|
||||
let t = s.tab(id).unwrap();
|
||||
assert!(t.in_flight.is_none());
|
||||
assert_eq!(t.error.as_deref(), Some("Cancelled"));
|
||||
|
||||
let fx = update(
|
||||
&mut s,
|
||||
Action::ResponseReceived {
|
||||
tab: id,
|
||||
seq,
|
||||
result: Ok(response(200, "late", &[])),
|
||||
},
|
||||
);
|
||||
assert!(fx.is_empty());
|
||||
assert!(s.tab(id).unwrap().response.is_none());
|
||||
assert!(s.history.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_variables_are_reported_not_sent() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "{{base}}/x".into()));
|
||||
assert!(update(&mut s, Action::Send(id)).is_empty());
|
||||
assert_eq!(s.tab(id).unwrap().error.as_deref(), Some("unknown variable `base`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environments_resolve_and_switch() {
|
||||
let mut s = state();
|
||||
let root = with_collection(
|
||||
&mut s,
|
||||
&[("a.http", "### A\nGET {{base}}/x\nAuthorization: Bearer {{token}}\n")],
|
||||
);
|
||||
let envs = Environments {
|
||||
public: EnvFile::parse(
|
||||
r#"{"dev": {"base": "http://dev"}, "prod": {"base": "https://prod"}}"#,
|
||||
&root,
|
||||
)
|
||||
.unwrap(),
|
||||
private: EnvFile::parse(r#"{"dev": {"token": "t-dev"}, "prod": {"token": "t-prod"}}"#, &root).unwrap(),
|
||||
};
|
||||
update(&mut s, Action::EnvironmentsLoaded(Ok((envs, false))));
|
||||
update(
|
||||
&mut s,
|
||||
Action::OpenRequest {
|
||||
file: root.join("a.http"),
|
||||
index: 0,
|
||||
},
|
||||
);
|
||||
let id = active(&s);
|
||||
|
||||
for (env, url, auth) in [
|
||||
("dev", "http://dev/x", "Bearer t-dev"),
|
||||
("prod", "https://prod/x", "Bearer t-prod"),
|
||||
] {
|
||||
update(&mut s, Action::SelectEnv(Some(env.into())));
|
||||
let fx = update(&mut s, Action::Send(id));
|
||||
let Effect::SendRequest { request, seq, .. } = &fx[0] else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(request.url, url);
|
||||
assert_eq!(request.headers[0].1, auth);
|
||||
assert!(s.is_private_var("token"));
|
||||
let seq = *seq;
|
||||
update(
|
||||
&mut s,
|
||||
Action::ResponseReceived {
|
||||
tab: id,
|
||||
seq,
|
||||
result: Err(HttpError::Timeout),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookies_are_stored_and_sent_unless_disabled() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "http://h/login".into()));
|
||||
let fx = update(&mut s, Action::Send(id));
|
||||
let Effect::SendRequest { seq, .. } = &fx[0] else {
|
||||
panic!()
|
||||
};
|
||||
let seq = *seq;
|
||||
update(
|
||||
&mut s,
|
||||
Action::ResponseReceived {
|
||||
tab: id,
|
||||
seq,
|
||||
result: Ok(response(200, "", &[("set-cookie", "sid=1; Path=/")])),
|
||||
},
|
||||
);
|
||||
let fx = update(&mut s, Action::Send(id));
|
||||
let Effect::SendRequest { request, seq, .. } = &fx[0] else {
|
||||
panic!()
|
||||
};
|
||||
assert!(request.headers.contains(&("Cookie".into(), "sid=1".into())));
|
||||
let seq = *seq;
|
||||
update(
|
||||
&mut s,
|
||||
Action::ResponseReceived {
|
||||
tab: id,
|
||||
seq,
|
||||
result: Err(HttpError::Timeout),
|
||||
},
|
||||
);
|
||||
|
||||
update(
|
||||
&mut s,
|
||||
Action::SourceEdited(id, "# @no-cookie-jar\nGET http://h/login\n".into()),
|
||||
);
|
||||
let fx = update(&mut s, Action::Send(id));
|
||||
let Effect::SendRequest { request, .. } = &fx[0] else {
|
||||
panic!()
|
||||
};
|
||||
assert!(request.headers.iter().all(|(n, _)| n != "Cookie"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_log_keeps_requests_out_of_history() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(
|
||||
&mut s,
|
||||
Action::SourceEdited(id, "# @no-log\nGET http://h/secret\n".into()),
|
||||
);
|
||||
let fx = update(&mut s, Action::Send(id));
|
||||
let Effect::SendRequest { seq, .. } = &fx[0] else {
|
||||
panic!()
|
||||
};
|
||||
let seq = *seq;
|
||||
let fx = update(
|
||||
&mut s,
|
||||
Action::ResponseReceived {
|
||||
tab: id,
|
||||
seq,
|
||||
result: Ok(response(200, "", &[])),
|
||||
},
|
||||
);
|
||||
assert!(s.history.is_empty());
|
||||
assert!(!fx.iter().any(|e| matches!(e, Effect::AppendHistory(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_finds_matches_in_the_prepared_body() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "http://h/".into()));
|
||||
let fx = update(&mut s, Action::Send(id));
|
||||
let Effect::SendRequest { seq, .. } = &fx[0] else {
|
||||
panic!()
|
||||
};
|
||||
let seq = *seq;
|
||||
let body = "{\"name\":\"Ada\",\"friend\":{\"name\":\"Grace\"}}";
|
||||
update(
|
||||
&mut s,
|
||||
Action::ResponseReceived {
|
||||
tab: id,
|
||||
seq,
|
||||
result: Ok(response(200, body, &[("content-type", "application/json")])),
|
||||
},
|
||||
);
|
||||
let prepared = prepare_body(
|
||||
&BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())),
|
||||
"application/json",
|
||||
1 << 20,
|
||||
);
|
||||
assert_eq!(prepared.kind, BodyKind::Json);
|
||||
update(
|
||||
&mut s,
|
||||
Action::BodyPrepared {
|
||||
tab: id,
|
||||
seq,
|
||||
body: prepared,
|
||||
},
|
||||
);
|
||||
update(&mut s, Action::SearchQuery(id, "NAME".into()));
|
||||
let t = s.tab(id).unwrap();
|
||||
assert_eq!(t.search.matches.len(), 2);
|
||||
assert_eq!(t.search.scroll_to, Some(t.search.matches[0].0));
|
||||
update(&mut s, Action::SearchStep(id, 1));
|
||||
update(&mut s, Action::SearchStep(id, 1));
|
||||
assert_eq!(s.tab(id).unwrap().search.current, 0, "wraps around");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------- collections
|
||||
|
||||
const USERS: &str = "### List users\nGET {{base}}/users\n\n### Create user\n# @name create-user\nPOST {{base}}/users\nContent-Type: application/json\n\n{\"name\": \"Ada\"}\n\n> {% client.global.set(\"id\", response.body.id) %}\n";
|
||||
|
||||
#[test]
|
||||
fn saving_an_unchanged_request_writes_nothing() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS)]);
|
||||
update(
|
||||
&mut s,
|
||||
Action::OpenRequest {
|
||||
file: root.join("users.http"),
|
||||
index: 1,
|
||||
},
|
||||
);
|
||||
let id = active(&s);
|
||||
assert!(!s.tab(id).unwrap().is_dirty());
|
||||
let fx = update(&mut s, Action::Save(id));
|
||||
assert!(writes(&fx).is_empty(), "{fx:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_an_edit_rewrites_only_that_request() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS)]);
|
||||
let file = root.join("users.http");
|
||||
update(
|
||||
&mut s,
|
||||
Action::OpenRequest {
|
||||
file: file.clone(),
|
||||
index: 1,
|
||||
},
|
||||
);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "{{base}}/v2/users".into()));
|
||||
assert!(s.tab(id).unwrap().is_dirty());
|
||||
let fx = update(&mut s, Action::Save(id));
|
||||
let w = writes(&fx);
|
||||
assert_eq!(w.len(), 1);
|
||||
assert_eq!(w[0].0, file);
|
||||
assert_eq!(w[0].1, USERS.replace("POST {{base}}/users", "POST {{base}}/v2/users"));
|
||||
assert!(!s.tab(id).unwrap().is_dirty());
|
||||
// A second save is a no-op.
|
||||
assert!(writes(&update(&mut s, Action::Save(id))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_from_the_source_tab_keeps_comments() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS)]);
|
||||
let file = root.join("users.http");
|
||||
update(
|
||||
&mut s,
|
||||
Action::OpenRequest {
|
||||
file: file.clone(),
|
||||
index: 0,
|
||||
},
|
||||
);
|
||||
let id = active(&s);
|
||||
let src = s.tab(id).unwrap().source.clone();
|
||||
assert_eq!(src, "### List users\nGET {{base}}/users\n");
|
||||
update(&mut s, Action::SourceEdited(id, format!("{src}# a new comment\n")));
|
||||
assert!(s.tab(id).unwrap().is_dirty(), "a comment-only edit is still a change");
|
||||
let w = writes(&update(&mut s, Action::Save(id)));
|
||||
assert_eq!(
|
||||
w[0].1,
|
||||
USERS.replace("GET {{base}}/users\n", "GET {{base}}/users\n# a new comment\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untitled_tabs_save_as_into_a_file() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS)]);
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "http://new".into()));
|
||||
assert!(matches!(update(&mut s, Action::Save(id))[..], [Effect::PickSaveTarget(t)] if t == id));
|
||||
let file = root.join("users.http");
|
||||
let fx = update(
|
||||
&mut s,
|
||||
Action::SaveAs {
|
||||
tab: id,
|
||||
path: file.clone(),
|
||||
existing: None,
|
||||
},
|
||||
);
|
||||
let w = writes(&fx);
|
||||
assert_eq!(w[0].1, format!("{USERS}\n###\nGET http://new\n"));
|
||||
let t = s.tab(id).unwrap();
|
||||
assert_eq!(t.origin.as_ref().unwrap().file, file);
|
||||
assert_eq!(t.origin.as_ref().unwrap().key.index, 2);
|
||||
assert!(!t.is_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_change_reloads_clean_tabs_and_prompts_for_dirty_ones() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS)]);
|
||||
let file = root.join("users.http");
|
||||
update(
|
||||
&mut s,
|
||||
Action::OpenRequest {
|
||||
file: file.clone(),
|
||||
index: 0,
|
||||
},
|
||||
);
|
||||
let clean = active(&s);
|
||||
update(
|
||||
&mut s,
|
||||
Action::OpenRequest {
|
||||
file: file.clone(),
|
||||
index: 1,
|
||||
},
|
||||
);
|
||||
let dirty = active(&s);
|
||||
update(&mut s, Action::UrlEdited(dirty, "{{base}}/mine".into()));
|
||||
|
||||
// Our own write echoing back changes nothing.
|
||||
update(
|
||||
&mut s,
|
||||
Action::FileChangedOnDisk {
|
||||
path: file.clone(),
|
||||
text: Some(USERS.into()),
|
||||
},
|
||||
);
|
||||
assert!(s.dialog.is_none());
|
||||
|
||||
let changed = USERS.replace("GET {{base}}/users", "GET {{base}}/people");
|
||||
update(
|
||||
&mut s,
|
||||
Action::FileChangedOnDisk {
|
||||
path: file.clone(),
|
||||
text: Some(changed),
|
||||
},
|
||||
);
|
||||
assert_eq!(s.tab(clean).unwrap().request.url, "{{base}}/people");
|
||||
assert_eq!(
|
||||
s.dialog,
|
||||
Some(Dialog::Conflict {
|
||||
tab: dirty,
|
||||
path: file.clone()
|
||||
})
|
||||
);
|
||||
|
||||
update(
|
||||
&mut s,
|
||||
Action::ResolveConflict {
|
||||
tab: dirty,
|
||||
keep_mine: false,
|
||||
},
|
||||
);
|
||||
assert_eq!(s.tab(dirty).unwrap().request.url, "{{base}}/users");
|
||||
assert!(!s.tab(dirty).unwrap().is_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_rename_duplicate_move_delete() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS), ("other.http", "### X\nGET /x\n")]);
|
||||
let users = root.join("users.http");
|
||||
let other = root.join("other.http");
|
||||
|
||||
// New request in a file.
|
||||
let w = writes(&update(&mut s, Action::NewRequestIn { file: other.clone() }));
|
||||
assert_eq!(w[0].1, "### X\nGET /x\n\n### New request\nGET \n");
|
||||
|
||||
// Rename (the @name follows the title).
|
||||
let w = writes(&update(
|
||||
&mut s,
|
||||
Action::RenameRequest {
|
||||
file: users.clone(),
|
||||
index: 1,
|
||||
title: "Add user".into(),
|
||||
},
|
||||
));
|
||||
assert!(w[0].1.contains("### Add user\n# @name add-user\nPOST"));
|
||||
|
||||
// Duplicate.
|
||||
let w = writes(&update(
|
||||
&mut s,
|
||||
Action::DuplicateRequest {
|
||||
file: users.clone(),
|
||||
index: 0,
|
||||
},
|
||||
));
|
||||
let f = HttpFile::parse(w[0].1.clone());
|
||||
let names: Vec<_> = f.requests().map(|r| r.display_name().unwrap().to_string()).collect();
|
||||
assert_eq!(names, ["List users", "List users copy", "add-user"]);
|
||||
// The open tab is now the copy.
|
||||
let copy_tab = active(&s);
|
||||
assert_eq!(s.tab(copy_tab).unwrap().origin.as_ref().unwrap().key.index, 1);
|
||||
|
||||
// Move the copy to the other file; its tab follows.
|
||||
let fx = update(
|
||||
&mut s,
|
||||
Action::MoveRequest {
|
||||
from: users.clone(),
|
||||
index: 1,
|
||||
to: other.clone(),
|
||||
},
|
||||
);
|
||||
let w = writes(&fx);
|
||||
let o = w.iter().find(|(p, _)| p == &other).unwrap();
|
||||
assert!(o.1.ends_with("### List users copy\nGET {{base}}/users\n"));
|
||||
let u = w.iter().find(|(p, _)| p == &users).unwrap();
|
||||
assert_eq!(HttpFile::parse(u.1.clone()).request_count(), 2);
|
||||
let origin = s.tab(copy_tab).unwrap().origin.clone().unwrap();
|
||||
assert_eq!(origin.file, other);
|
||||
assert_eq!(origin.key.index, 2);
|
||||
|
||||
// Delete orphans the tab.
|
||||
update(
|
||||
&mut s,
|
||||
Action::DeleteRequest {
|
||||
file: other.clone(),
|
||||
index: 2,
|
||||
},
|
||||
);
|
||||
assert!(s.tab(copy_tab).unwrap().orphaned);
|
||||
assert_eq!(s.collection.as_ref().unwrap().files[&other].request_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_file_and_rename_file() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS)]);
|
||||
let fx = update(
|
||||
&mut s,
|
||||
Action::NewFile {
|
||||
dir: root.clone(),
|
||||
name: "orders".into(),
|
||||
},
|
||||
);
|
||||
let w = writes(&fx);
|
||||
assert_eq!(w[0], (root.join("orders.http"), "### New request\nGET \n".to_string()));
|
||||
assert!(matches!(&fx[0], Effect::FileOps { rescan: Some(_), .. }));
|
||||
let id = active(&s);
|
||||
|
||||
let fx = update(
|
||||
&mut s,
|
||||
Action::RenameFile {
|
||||
path: root.join("orders.http"),
|
||||
new_name: "shop".into(),
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
matches!(&fx[0], Effect::FileOps { ops, .. } if ops == &[FileOp::Rename(root.join("orders.http"), root.join("shop.http"))])
|
||||
);
|
||||
assert_eq!(s.tab(id).unwrap().origin.as_ref().unwrap().file, root.join("shop.http"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_dirty_tab_asks_first() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::CloseTab(id));
|
||||
assert!(s.tabs.is_empty(), "a clean tab closes right away");
|
||||
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "http://x".into()));
|
||||
update(&mut s, Action::CloseTab(id));
|
||||
assert_eq!(s.dialog, Some(Dialog::ConfirmCloseTab(id)));
|
||||
update(&mut s, Action::DiscardAndCloseTab(id));
|
||||
assert!(s.tabs.is_empty());
|
||||
assert!(s.dialog.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quitting_with_unsaved_changes_asks_first() {
|
||||
let mut s = state();
|
||||
update(&mut s, Action::NewTab);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::UrlEdited(id, "http://x".into()));
|
||||
assert!(update(&mut s, Action::CloseRequested).is_empty());
|
||||
assert_eq!(s.dialog, Some(Dialog::ConfirmQuit));
|
||||
assert!(matches!(update(&mut s, Action::ConfirmQuit)[..], [Effect::Quit]));
|
||||
assert!(s.quit_confirmed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_history_opens_a_new_tab() {
|
||||
let mut s = state();
|
||||
update(
|
||||
&mut s,
|
||||
Action::HistoryLoaded(vec![HistoryEntry {
|
||||
at: 0,
|
||||
method: "POST".into(),
|
||||
url: "http://x/y".into(),
|
||||
status: Some(201),
|
||||
duration_ms: 3,
|
||||
env: None,
|
||||
http: "### Make\nPOST http://x/y\n\nhello\n".into(),
|
||||
error: None,
|
||||
}]),
|
||||
);
|
||||
update(&mut s, Action::RestoreHistory(0));
|
||||
let t = s.active_tab().unwrap();
|
||||
assert_eq!(t.request.method, Method::Post);
|
||||
assert_eq!(t.request.body, Body::Text("hello".into()));
|
||||
assert!(t.origin.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_editor_writes_both_files() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[]);
|
||||
update(&mut s, Action::OpenEnvEditor);
|
||||
let mut ed = s.env_editor.clone().unwrap();
|
||||
ed.envs.public.env_mut("dev").set("base", "http://localhost");
|
||||
ed.envs.private.env_mut("dev").set("token", "secret");
|
||||
update(&mut s, Action::EnvEditorChanged(ed));
|
||||
let fx = update(&mut s, Action::EnvEditorSave);
|
||||
let w = writes(&fx);
|
||||
assert_eq!(w.len(), 2);
|
||||
assert!(w
|
||||
.iter()
|
||||
.any(|(p, t)| p == &root.join(env::PUBLIC_FILE) && t.contains("\"base\": \"http://localhost\"")));
|
||||
assert!(w
|
||||
.iter()
|
||||
.any(|(p, t)| p == &root.join(env::PRIVATE_FILE) && t.contains("\"token\": \"secret\"")));
|
||||
assert_eq!(s.collection.as_ref().unwrap().envs.names(), vec!["dev"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_file_paths_are_stored_relative_to_the_http_file() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS)]);
|
||||
update(
|
||||
&mut s,
|
||||
Action::OpenRequest {
|
||||
file: root.join("users.http"),
|
||||
index: 1,
|
||||
},
|
||||
);
|
||||
let id = active(&s);
|
||||
update(&mut s, Action::BodyFilePicked(id, root.join("payloads/a.json")));
|
||||
assert_eq!(
|
||||
s.tab(id).unwrap().request.body,
|
||||
Body::FileRef {
|
||||
path: "./payloads/a.json".into(),
|
||||
substitute: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_file_copies_it_under_a_free_name() {
|
||||
let mut s = state();
|
||||
let root = with_collection(&mut s, &[("users.http", USERS), ("users copy.http", "GET /x\n")]);
|
||||
let fx = update(&mut s, Action::DuplicateFile(root.join("users.http")));
|
||||
assert_eq!(writes(&fx), vec![(root.join("users copy 2.http"), USERS.to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrency_setting_reaches_the_runner() {
|
||||
let mut s = state();
|
||||
let fx = update(
|
||||
&mut s,
|
||||
Action::SettingsLoaded(Settings {
|
||||
max_concurrent_requests: 3,
|
||||
..Settings::default()
|
||||
}),
|
||||
);
|
||||
assert!(matches!(fx[..], [Effect::SetConcurrency(3)]));
|
||||
let mut changed = s.settings.clone();
|
||||
changed.max_concurrent_requests = 5;
|
||||
let fx = update(&mut s, Action::SettingsChanged(changed));
|
||||
assert!(fx.iter().any(|e| matches!(e, Effect::SetConcurrency(5))));
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! The eframe app: owns the state, the effects runner and the action inbox.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reqlite_core::http::DynHttpClient;
|
||||
use tokio::runtime::Handle;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::action::{update, Action};
|
||||
use crate::effects::{Paths, Runner};
|
||||
use crate::settings::ThemeChoice;
|
||||
use crate::state::AppState;
|
||||
|
||||
pub struct ReqliteApp {
|
||||
pub state: AppState,
|
||||
runner: Runner,
|
||||
inbox: mpsc::UnboundedReceiver<Action>,
|
||||
applied: Option<(f32, ThemeChoice)>,
|
||||
}
|
||||
|
||||
impl ReqliteApp {
|
||||
/// `paths` is `None` in tests: nothing is read from or written to the
|
||||
/// user's config and data directories.
|
||||
pub fn new(
|
||||
ctx: Option<egui::Context>,
|
||||
handle: Handle,
|
||||
client: Arc<dyn DynHttpClient>,
|
||||
paths: Option<Paths>,
|
||||
) -> Self {
|
||||
let (runner, inbox) = Runner::new(handle, ctx, client, paths, 8);
|
||||
runner.load_startup();
|
||||
Self {
|
||||
state: AppState::default(),
|
||||
runner,
|
||||
inbox,
|
||||
applied: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dispatch(&mut self, action: Action) {
|
||||
tracing::trace!(?action, "action");
|
||||
for effect in update(&mut self.state, action) {
|
||||
self.runner.run(effect);
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies actions that effects have sent back.
|
||||
pub fn pump(&mut self) {
|
||||
while let Ok(a) = self.inbox.try_recv() {
|
||||
self.dispatch(a);
|
||||
}
|
||||
}
|
||||
|
||||
/// One UI frame: drain the inbox, draw, apply what the user did.
|
||||
pub fn frame(&mut self, ui: &mut egui::Ui) {
|
||||
self.pump();
|
||||
let ctx = ui.ctx().clone();
|
||||
let wanted = (self.state.settings.zoom, self.state.settings.theme);
|
||||
if self.applied != Some(wanted) {
|
||||
ctx.set_zoom_factor(wanted.0.clamp(0.5, 3.0));
|
||||
ctx.set_theme(match wanted.1 {
|
||||
ThemeChoice::System => egui::ThemePreference::System,
|
||||
ThemeChoice::Light => egui::ThemePreference::Light,
|
||||
ThemeChoice::Dark => egui::ThemePreference::Dark,
|
||||
});
|
||||
self.applied = Some(wanted);
|
||||
}
|
||||
if ctx.input(|i| i.viewport().close_requested()) && self.state.any_dirty() && !self.state.quit_confirmed {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
self.dispatch(Action::CloseRequested);
|
||||
}
|
||||
|
||||
let mut actions = Vec::new();
|
||||
crate::ui::draw(ui, &self.state, &mut actions);
|
||||
for a in actions {
|
||||
self.dispatch(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for ReqliteApp {
|
||||
fn logic(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.pump();
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.frame(ui);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,567 @@
|
||||
//! Effects: work that happens outside `update` (HTTP, disk, dialogs, file
|
||||
//! watching). Each effect runs as a Tokio task and reports back by sending an
|
||||
//! [`Action`] over a channel and waking the UI.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use notify::{RecursiveMode, Watcher};
|
||||
use reqlite_core::collection;
|
||||
use reqlite_core::env::{self, Environments};
|
||||
use reqlite_core::http::{BodyStore, DynHttpClient, ResolvedRequest};
|
||||
use reqlite_core::CancelToken;
|
||||
use tokio::runtime::Handle;
|
||||
use tokio::sync::{mpsc, Semaphore};
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::history::{self, HistoryEntry};
|
||||
use crate::settings::Settings;
|
||||
use crate::state::{prepare_body, TabId};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FileOp {
|
||||
Write(PathBuf, String),
|
||||
Delete(PathBuf),
|
||||
Rename(PathBuf, PathBuf),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Effect {
|
||||
SendRequest {
|
||||
tab: TabId,
|
||||
seq: u64,
|
||||
request: ResolvedRequest,
|
||||
cancel: CancelToken,
|
||||
},
|
||||
PrepareBody {
|
||||
tab: TabId,
|
||||
seq: u64,
|
||||
body: BodyStore,
|
||||
content_type: String,
|
||||
},
|
||||
LoadCollection(PathBuf),
|
||||
LoadEnvironments(PathBuf),
|
||||
/// Watch a collection folder (or stop watching).
|
||||
Watch(Option<PathBuf>),
|
||||
/// Run file operations in order, then rescan the collection if given.
|
||||
FileOps {
|
||||
ops: Vec<FileOp>,
|
||||
rescan: Option<PathBuf>,
|
||||
},
|
||||
AppendGitignore(PathBuf),
|
||||
PickCollectionFolder,
|
||||
PickSaveTarget(TabId),
|
||||
PickBodyFile(TabId),
|
||||
PickCaFile,
|
||||
PickPostmanImport,
|
||||
SaveResponseBody {
|
||||
body: BodyStore,
|
||||
suggested_name: String,
|
||||
},
|
||||
CopyToClipboard(String),
|
||||
AppendHistory(HistoryEntry),
|
||||
RewriteHistory(Vec<HistoryEntry>),
|
||||
SaveSettings(Settings),
|
||||
/// Change how many requests may run at once (in-flight ones keep going).
|
||||
SetConcurrency(usize),
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Where settings, history and logs live.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Paths {
|
||||
pub config_dir: PathBuf,
|
||||
pub data_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Paths {
|
||||
pub fn from_system() -> Option<Self> {
|
||||
let d = directories::ProjectDirs::from("", "", "reqlite")?;
|
||||
Some(Self {
|
||||
config_dir: d.config_dir().to_path_buf(),
|
||||
data_dir: d.data_dir().to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn settings_file(&self) -> PathBuf {
|
||||
self.config_dir.join("settings.toml")
|
||||
}
|
||||
|
||||
pub fn history_file(&self) -> PathBuf {
|
||||
self.data_dir.join("history.jsonl")
|
||||
}
|
||||
|
||||
pub fn log_dir(&self) -> PathBuf {
|
||||
self.data_dir.join("logs")
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends actions back to the UI and wakes it up.
|
||||
#[derive(Clone)]
|
||||
pub struct Outbox {
|
||||
tx: mpsc::UnboundedSender<Action>,
|
||||
ctx: Option<egui::Context>,
|
||||
}
|
||||
|
||||
impl Outbox {
|
||||
pub fn send(&self, a: Action) {
|
||||
let _ = self.tx.send(a);
|
||||
if let Some(ctx) = &self.ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Runner {
|
||||
handle: Handle,
|
||||
outbox: Outbox,
|
||||
client: Arc<dyn DynHttpClient>,
|
||||
semaphore: Mutex<Arc<Semaphore>>,
|
||||
watcher: Arc<Mutex<Option<notify::RecommendedWatcher>>>,
|
||||
paths: Option<Paths>,
|
||||
/// Serializes history writes.
|
||||
history_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
}
|
||||
|
||||
/// Bodies bigger than this are only partly shown (the rest can be saved).
|
||||
const MAX_DISPLAY: u64 = 64 * 1024 * 1024;
|
||||
|
||||
impl Runner {
|
||||
pub fn new(
|
||||
handle: Handle,
|
||||
ctx: Option<egui::Context>,
|
||||
client: Arc<dyn DynHttpClient>,
|
||||
paths: Option<Paths>,
|
||||
max_concurrent: usize,
|
||||
) -> (Self, mpsc::UnboundedReceiver<Action>) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
(
|
||||
Self {
|
||||
handle,
|
||||
outbox: Outbox { tx, ctx },
|
||||
client,
|
||||
semaphore: Mutex::new(Arc::new(Semaphore::new(max_concurrent.max(1)))),
|
||||
watcher: Arc::new(Mutex::new(None)),
|
||||
paths,
|
||||
history_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
},
|
||||
rx,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn outbox(&self) -> Outbox {
|
||||
self.outbox.clone()
|
||||
}
|
||||
|
||||
/// Loads settings and history at startup.
|
||||
pub fn load_startup(&self) {
|
||||
let Some(paths) = self.paths.clone() else { return };
|
||||
let out = self.outbox();
|
||||
self.handle.spawn(async move {
|
||||
let settings = match tokio::fs::read_to_string(paths.settings_file()).await {
|
||||
Ok(text) => Settings::from_toml(&text).unwrap_or_else(|e| {
|
||||
out.send(Action::Error(format!("settings.toml: {e}")));
|
||||
Settings::default()
|
||||
}),
|
||||
Err(_) => Settings::default(),
|
||||
};
|
||||
let limit = settings.history_limit;
|
||||
if let Some(last) = settings.recent_collections.first().cloned() {
|
||||
if last.is_dir() {
|
||||
out.send(Action::OpenCollection(last));
|
||||
}
|
||||
}
|
||||
out.send(Action::SettingsLoaded(settings));
|
||||
if let Ok(text) = tokio::fs::read_to_string(paths.history_file()).await {
|
||||
let entries = history::parse(&text, limit);
|
||||
// Compact the file once it holds twice the limit.
|
||||
if text.lines().count() > limit * 2 {
|
||||
let _ = tokio::fs::write(paths.history_file(), history::to_text(&entries)).await;
|
||||
}
|
||||
out.send(Action::HistoryLoaded(entries));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn run(&self, effect: Effect) {
|
||||
let out = self.outbox();
|
||||
match effect {
|
||||
Effect::SendRequest {
|
||||
tab,
|
||||
seq,
|
||||
request,
|
||||
cancel,
|
||||
} => {
|
||||
let client = self.client.clone();
|
||||
let sem = self.semaphore.lock().unwrap().clone();
|
||||
self.handle.spawn(async move {
|
||||
let result = tokio::select! {
|
||||
permit = sem.acquire_owned() => {
|
||||
let _permit = permit;
|
||||
client.send_dyn(request, cancel).await
|
||||
}
|
||||
_ = cancel.cancelled() => Err(reqlite_core::http::HttpError::Cancelled),
|
||||
};
|
||||
out.send(Action::ResponseReceived { tab, seq, result });
|
||||
});
|
||||
}
|
||||
Effect::PrepareBody {
|
||||
tab,
|
||||
seq,
|
||||
body,
|
||||
content_type,
|
||||
} => {
|
||||
self.handle.spawn(async move {
|
||||
let prepared =
|
||||
tokio::task::spawn_blocking(move || prepare_body(&body, &content_type, MAX_DISPLAY)).await;
|
||||
if let Ok(body) = prepared {
|
||||
out.send(Action::BodyPrepared { tab, seq, body });
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::LoadCollection(root) => {
|
||||
self.handle.spawn(async move {
|
||||
let r = tokio::task::spawn_blocking(move || collection::scan(&root).map_err(|e| e.to_string()))
|
||||
.await
|
||||
.unwrap_or_else(|e| Err(e.to_string()));
|
||||
out.send(Action::CollectionLoaded(r));
|
||||
});
|
||||
}
|
||||
Effect::LoadEnvironments(root) => {
|
||||
self.handle.spawn(async move {
|
||||
let r = tokio::task::spawn_blocking(move || {
|
||||
let envs = Environments::load(&root).map_err(|e| e.to_string())?;
|
||||
let not_ignored = root.join(env::PRIVATE_FILE).exists() && !env::private_file_ignored(&root);
|
||||
Ok((envs, not_ignored))
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|e| Err(e.to_string()));
|
||||
out.send(Action::EnvironmentsLoaded(r));
|
||||
});
|
||||
}
|
||||
Effect::Watch(root) => self.watch(root),
|
||||
Effect::FileOps { ops, rescan } => {
|
||||
self.handle.spawn(async move {
|
||||
for op in ops {
|
||||
if let Err(e) = run_file_op(&op).await {
|
||||
out.send(Action::Error(e));
|
||||
}
|
||||
}
|
||||
if let Some(root) = rescan {
|
||||
let r = tokio::task::spawn_blocking(move || collection::scan(&root).map_err(|e| e.to_string()))
|
||||
.await
|
||||
.unwrap_or_else(|e| Err(e.to_string()));
|
||||
out.send(Action::CollectionLoaded(r));
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::AppendGitignore(root) => {
|
||||
self.handle.spawn(async move {
|
||||
let path = root.join(".gitignore");
|
||||
let existing = tokio::fs::read_to_string(&path).await.unwrap_or_default();
|
||||
let text = format!("{existing}{}", env::gitignore_addition(&existing));
|
||||
match tokio::fs::write(&path, text).await {
|
||||
Ok(()) => out.send(Action::Info(format!("Added {} to .gitignore", env::PRIVATE_FILE))),
|
||||
Err(e) => out.send(Action::Error(format!("{}: {e}", path.display()))),
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::PickCollectionFolder => {
|
||||
self.handle.spawn(async move {
|
||||
if let Some(dir) = rfd::AsyncFileDialog::new()
|
||||
.set_title("Open collection folder")
|
||||
.pick_folder()
|
||||
.await
|
||||
{
|
||||
out.send(Action::OpenCollection(dir.path().to_path_buf()));
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::PickSaveTarget(tab) => {
|
||||
self.handle.spawn(async move {
|
||||
if let Some(f) = rfd::AsyncFileDialog::new()
|
||||
.set_title("Save request to .http file")
|
||||
.add_filter("HTTP request files", &["http", "rest"])
|
||||
.set_file_name("requests.http")
|
||||
.save_file()
|
||||
.await
|
||||
{
|
||||
let path = f.path().to_path_buf();
|
||||
let existing = tokio::fs::read_to_string(&path).await.ok();
|
||||
out.send(Action::SaveAs { tab, path, existing });
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::PickBodyFile(tab) => {
|
||||
self.handle.spawn(async move {
|
||||
if let Some(f) = rfd::AsyncFileDialog::new()
|
||||
.set_title("Request body file")
|
||||
.pick_file()
|
||||
.await
|
||||
{
|
||||
out.send(Action::BodyFilePicked(tab, f.path().to_path_buf()));
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::PickCaFile => {
|
||||
self.handle.spawn(async move {
|
||||
if let Some(f) = rfd::AsyncFileDialog::new()
|
||||
.set_title("CA certificate bundle (PEM)")
|
||||
.add_filter("PEM", &["pem", "crt", "cer"])
|
||||
.pick_file()
|
||||
.await
|
||||
{
|
||||
out.send(Action::CaFilePicked(f.path().to_path_buf()));
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::PickPostmanImport => {
|
||||
self.handle.spawn(async move {
|
||||
let Some(coll) = rfd::AsyncFileDialog::new()
|
||||
.set_title("Postman collection (v2.1) to import")
|
||||
.add_filter("Postman collection", &["json"])
|
||||
.pick_file()
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(out_dir) = rfd::AsyncFileDialog::new()
|
||||
.set_title("Folder to write the .http files to")
|
||||
.pick_folder()
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let coll = coll.path().to_path_buf();
|
||||
let out_dir = out_dir.path().to_path_buf();
|
||||
match import_postman(&coll, &out_dir).await {
|
||||
Ok((files, warnings)) => out.send(Action::PostmanImported {
|
||||
root: out_dir,
|
||||
files,
|
||||
warnings,
|
||||
}),
|
||||
Err(e) => out.send(Action::Error(format!("Postman import failed: {e}"))),
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::SaveResponseBody { body, suggested_name } => {
|
||||
self.handle.spawn(async move {
|
||||
let Some(f) = rfd::AsyncFileDialog::new()
|
||||
.set_title("Save response body")
|
||||
.set_file_name(&suggested_name)
|
||||
.save_file()
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let path = f.path().to_path_buf();
|
||||
let r = match &body {
|
||||
BodyStore::InMemory(b) => tokio::fs::write(&path, b.as_ref()).await,
|
||||
BodyStore::TempFile(p) => tokio::fs::copy(&**p, &path).await.map(|_| ()),
|
||||
};
|
||||
match r {
|
||||
Ok(()) => out.send(Action::Info(format!("Saved {}", path.display()))),
|
||||
Err(e) => out.send(Action::Error(format!("{}: {e}", path.display()))),
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::CopyToClipboard(text) => {
|
||||
if let Some(ctx) = &self.outbox.ctx {
|
||||
ctx.copy_text(text);
|
||||
}
|
||||
}
|
||||
Effect::AppendHistory(entry) => {
|
||||
let Some(paths) = self.paths.clone() else { return };
|
||||
let lock = self.history_lock.clone();
|
||||
self.handle.spawn(async move {
|
||||
let _g = lock.lock().await;
|
||||
if let Err(e) = append(&paths.history_file(), &history::to_line(&entry)).await {
|
||||
tracing::warn!("history: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::RewriteHistory(entries) => {
|
||||
let Some(paths) = self.paths.clone() else { return };
|
||||
let lock = self.history_lock.clone();
|
||||
self.handle.spawn(async move {
|
||||
let _g = lock.lock().await;
|
||||
let _ = tokio::fs::create_dir_all(&paths.data_dir).await;
|
||||
let _ = tokio::fs::write(paths.history_file(), history::to_text(&entries)).await;
|
||||
});
|
||||
}
|
||||
Effect::SetConcurrency(n) => {
|
||||
*self.semaphore.lock().unwrap() = Arc::new(Semaphore::new(n.max(1)));
|
||||
}
|
||||
Effect::SaveSettings(s) => {
|
||||
let Some(paths) = self.paths.clone() else { return };
|
||||
self.handle.spawn(async move {
|
||||
let _ = tokio::fs::create_dir_all(&paths.config_dir).await;
|
||||
if let Err(e) = tokio::fs::write(paths.settings_file(), s.to_toml()).await {
|
||||
out.send(Action::Error(format!("Could not save settings: {e}")));
|
||||
}
|
||||
});
|
||||
}
|
||||
Effect::Quit => {
|
||||
if let Some(ctx) = &self.outbox.ctx {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Watches a collection with `notify`; changes are debounced and turned
|
||||
/// into `FileChangedOnDisk` actions (and a rescan when files come or go).
|
||||
fn watch(&self, root: Option<PathBuf>) {
|
||||
let mut slot = self.watcher.lock().unwrap();
|
||||
*slot = None; // drops (stops) the old watcher
|
||||
let Some(root) = root else { return };
|
||||
let (tx, mut rx) = mpsc::unbounded_channel::<notify::Event>();
|
||||
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
if let Ok(ev) = res {
|
||||
let _ = tx.send(ev);
|
||||
}
|
||||
});
|
||||
let mut watcher = match watcher {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
self.outbox
|
||||
.send(Action::Error(format!("Cannot watch {}: {e}", root.display())));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = watcher.watch(&root, RecursiveMode::Recursive) {
|
||||
self.outbox
|
||||
.send(Action::Error(format!("Cannot watch {}: {e}", root.display())));
|
||||
return;
|
||||
}
|
||||
*slot = Some(watcher);
|
||||
let out = self.outbox();
|
||||
self.handle.spawn(async move {
|
||||
while let Some(first) = rx.recv().await {
|
||||
// Debounce: collect everything that arrives within 150 ms.
|
||||
let mut events = vec![first];
|
||||
let deadline = tokio::time::sleep(Duration::from_millis(150));
|
||||
tokio::pin!(deadline);
|
||||
loop {
|
||||
tokio::select! {
|
||||
ev = rx.recv() => match ev {
|
||||
Some(ev) => events.push(ev),
|
||||
None => break,
|
||||
},
|
||||
_ = &mut deadline => break,
|
||||
}
|
||||
}
|
||||
// Folders appearing or disappearing (e.g. after `git pull`)
|
||||
// can hide file events from us, so rescan the whole tree.
|
||||
let rescan = events.iter().any(|e| {
|
||||
use notify::event::{CreateKind, EventKind, RemoveKind};
|
||||
matches!(
|
||||
e.kind,
|
||||
EventKind::Create(CreateKind::Folder) | EventKind::Remove(RemoveKind::Folder)
|
||||
) || ((e.kind.is_create() || e.kind.is_remove()) && e.paths.iter().any(|p| p.is_dir()))
|
||||
});
|
||||
let mut paths: Vec<PathBuf> = events
|
||||
.into_iter()
|
||||
.filter(|e| !e.kind.is_access())
|
||||
.flat_map(|e| e.paths)
|
||||
.filter(|p| is_relevant(p))
|
||||
.collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for p in paths {
|
||||
let text = tokio::fs::read_to_string(&p).await.ok();
|
||||
out.send(Action::FileChangedOnDisk { path: p, text });
|
||||
}
|
||||
if rescan {
|
||||
out.send(Action::Rescan);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn is_relevant(p: &Path) -> bool {
|
||||
if p.components().any(|c| {
|
||||
let s = c.as_os_str().to_string_lossy();
|
||||
s == ".git" || s == "node_modules" || s == "target"
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
collection::is_http_file(p)
|
||||
|| p.file_name()
|
||||
.is_some_and(|n| n == env::PUBLIC_FILE || n == env::PRIVATE_FILE)
|
||||
}
|
||||
|
||||
async fn append(path: &Path, line: &str) -> std::io::Result<()> {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
if let Some(dir) = path.parent() {
|
||||
tokio::fs::create_dir_all(dir).await?;
|
||||
}
|
||||
let mut f = tokio::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)
|
||||
.await?;
|
||||
f.write_all(line.as_bytes()).await
|
||||
}
|
||||
|
||||
async fn run_file_op(op: &FileOp) -> Result<(), String> {
|
||||
let r = match op {
|
||||
FileOp::Write(p, text) => {
|
||||
if let Some(dir) = p.parent() {
|
||||
let _ = tokio::fs::create_dir_all(dir).await;
|
||||
}
|
||||
// Write to a temp file and rename, so a crash never leaves half a file.
|
||||
let tmp = p.with_extension("http.reqlite-tmp");
|
||||
match tokio::fs::write(&tmp, text).await {
|
||||
Ok(()) => tokio::fs::rename(&tmp, p).await,
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
.map_err(|e| format!("{}: {e}", p.display()))
|
||||
}
|
||||
FileOp::Delete(p) => tokio::fs::remove_file(p)
|
||||
.await
|
||||
.map_err(|e| format!("{}: {e}", p.display())),
|
||||
FileOp::Rename(a, b) => {
|
||||
if tokio::fs::try_exists(b).await.unwrap_or(false) {
|
||||
return Err(format!("{} already exists", b.display()));
|
||||
}
|
||||
tokio::fs::rename(a, b)
|
||||
.await
|
||||
.map_err(|e| format!("{}: {e}", a.display()))
|
||||
}
|
||||
};
|
||||
tracing::debug!(?op, ok = r.is_ok(), "file op");
|
||||
r
|
||||
}
|
||||
|
||||
async fn import_postman(coll: &Path, out_dir: &Path) -> Result<(usize, Vec<String>), String> {
|
||||
let json = tokio::fs::read_to_string(coll).await.map_err(|e| e.to_string())?;
|
||||
let imp = reqlite_core::import::postman::import(&json, &[]).map_err(|e| e.to_string())?;
|
||||
for (rel, _) in &imp.files {
|
||||
let p = out_dir.join(rel);
|
||||
if tokio::fs::try_exists(&p).await.unwrap_or(false) {
|
||||
return Err(format!("{} already exists; pick an empty folder", p.display()));
|
||||
}
|
||||
}
|
||||
for (rel, text) in &imp.files {
|
||||
run_file_op(&FileOp::Write(out_dir.join(rel), text.clone())).await?;
|
||||
}
|
||||
let mut warnings = imp.warnings.clone();
|
||||
if let Some(e) = &imp.public_env {
|
||||
let p = out_dir.join(env::PUBLIC_FILE);
|
||||
if tokio::fs::try_exists(&p).await.unwrap_or(false) {
|
||||
warnings.push(format!(
|
||||
"{} exists; collection variables were not written",
|
||||
env::PUBLIC_FILE
|
||||
));
|
||||
} else {
|
||||
run_file_op(&FileOp::Write(p, e.clone())).await?;
|
||||
}
|
||||
}
|
||||
if let Some(e) = &imp.private_env {
|
||||
run_file_op(&FileOp::Write(out_dir.join(env::PRIVATE_FILE), e.clone())).await?;
|
||||
}
|
||||
Ok((imp.files.len(), warnings))
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Request history: an append-only JSON Lines file, capped.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct HistoryEntry {
|
||||
/// Unix seconds.
|
||||
pub at: u64,
|
||||
pub method: String,
|
||||
/// The resolved URL that was sent.
|
||||
pub url: String,
|
||||
pub status: Option<u16>,
|
||||
pub duration_ms: u64,
|
||||
pub env: Option<String>,
|
||||
/// The request as `.http` text (unresolved), for restoring.
|
||||
pub http: String,
|
||||
#[serde(default)]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub fn to_line(e: &HistoryEntry) -> String {
|
||||
let mut s = serde_json::to_string(e).unwrap_or_default();
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
|
||||
/// Parses a history file, skipping corrupt lines, keeping the newest `limit`.
|
||||
pub fn parse(text: &str, limit: usize) -> Vec<HistoryEntry> {
|
||||
let mut v: Vec<HistoryEntry> = text.lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
|
||||
if v.len() > limit {
|
||||
v.drain(..v.len() - limit);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub fn to_text(entries: &[HistoryEntry]) -> String {
|
||||
entries.iter().map(to_line).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_skips_bad_lines_and_caps() {
|
||||
let e = |n: u64| HistoryEntry {
|
||||
at: n,
|
||||
method: "GET".into(),
|
||||
url: format!("http://x/{n}"),
|
||||
status: Some(200),
|
||||
duration_ms: 1,
|
||||
env: None,
|
||||
http: "GET http://x\n".into(),
|
||||
error: None,
|
||||
};
|
||||
let text = format!("{}not json\n{}{}", to_line(&e(1)), to_line(&e(2)), to_line(&e(3)));
|
||||
let parsed = parse(&text, 2);
|
||||
assert_eq!(parsed, vec![e(2), e(3)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! The reqlite desktop app.
|
||||
//!
|
||||
//! Data flow (implementation plan §2.2): UI panels read [`state::AppState`]
|
||||
//! and emit [`action::Action`]s; [`action::update`] applies them and returns
|
||||
//! [`effects::Effect`]s; the [`effects::Runner`] runs those as Tokio tasks,
|
||||
//! which send their results back as actions.
|
||||
|
||||
pub mod action;
|
||||
pub mod app;
|
||||
pub mod effects;
|
||||
pub mod history;
|
||||
pub mod settings;
|
||||
pub mod state;
|
||||
pub mod ui;
|
||||
|
||||
pub use app::ReqliteApp;
|
||||
@@ -0,0 +1,77 @@
|
||||
//! `reqlite-gui [collection-folder]`
|
||||
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reqlite_app::effects::Paths;
|
||||
use reqlite_app::{action::Action, ReqliteApp};
|
||||
use reqlite_core::http::DynHttpClient;
|
||||
use reqlite_http_curl::CurlClient;
|
||||
|
||||
fn init_logging(paths: Option<&Paths>) -> Option<tracing_appender::non_blocking::WorkerGuard> {
|
||||
use tracing_subscriber::EnvFilter;
|
||||
let filter = EnvFilter::try_from_env("REQLITE_LOG")
|
||||
.unwrap_or_else(|_| EnvFilter::new("info,wgpu=warn,wgpu_core=warn,wgpu_hal=warn,naga=warn,eframe=warn"));
|
||||
let dir = paths?.log_dir();
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let appender = tracing_appender::rolling::Builder::new()
|
||||
.rotation(tracing_appender::rolling::Rotation::DAILY)
|
||||
.filename_prefix("reqlite")
|
||||
.filename_suffix("log")
|
||||
.max_log_files(7)
|
||||
.build(&dir)
|
||||
.ok()?;
|
||||
let (writer, guard) = tracing_appender::non_blocking(appender);
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(filter)
|
||||
.with_writer(writer)
|
||||
.with_ansi(false)
|
||||
.init();
|
||||
Some(guard)
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let paths = Paths::from_system();
|
||||
let _log_guard = init_logging(paths.as_ref());
|
||||
tracing::info!(version = env!("CARGO_PKG_VERSION"), curl = %CurlClient::version(), "starting");
|
||||
|
||||
// Tokio runs on its own threads; eframe keeps the main thread (winit
|
||||
// needs it on macOS), so no #[tokio::main] here.
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.thread_name("reqlite-io")
|
||||
.build()
|
||||
.expect("failed to start the async runtime");
|
||||
let handle = runtime.handle().clone();
|
||||
let client: Arc<dyn DynHttpClient> = Arc::new(CurlClient::new());
|
||||
let open_dir = std::env::args_os().nth(1).map(std::path::PathBuf::from);
|
||||
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("reqlite")
|
||||
.with_app_id("reqlite")
|
||||
.with_inner_size([1280.0, 820.0])
|
||||
.with_min_inner_size([640.0, 420.0])
|
||||
.with_icon(
|
||||
eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon.png"))
|
||||
.expect("the bundled icon is a PNG"),
|
||||
),
|
||||
persist_window: true,
|
||||
..Default::default()
|
||||
};
|
||||
let result = eframe::run_native(
|
||||
"reqlite",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
egui_extras::install_image_loaders(&cc.egui_ctx);
|
||||
let mut app = ReqliteApp::new(Some(cc.egui_ctx.clone()), handle, client, paths);
|
||||
if let Some(dir) = open_dir.and_then(|d| std::fs::canonicalize(d).ok()) {
|
||||
app.dispatch(Action::OpenCollection(dir));
|
||||
}
|
||||
Ok(Box::new(app))
|
||||
}),
|
||||
);
|
||||
runtime.shutdown_timeout(std::time::Duration::from_secs(1));
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! User settings, stored as TOML in the config directory.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use reqlite_core::http::{Proxy, RequestOptions};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ThemeChoice {
|
||||
#[default]
|
||||
System,
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProxyMode {
|
||||
#[default]
|
||||
System,
|
||||
None,
|
||||
Manual,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Settings {
|
||||
/// Seconds; 0 means no timeout.
|
||||
pub default_timeout_secs: u64,
|
||||
pub proxy_mode: ProxyMode,
|
||||
pub proxy_url: String,
|
||||
pub verify_tls: bool,
|
||||
/// Extra CA bundle (PEM), used in addition to the system store.
|
||||
pub ca_file: Option<PathBuf>,
|
||||
pub zoom: f32,
|
||||
pub theme: ThemeChoice,
|
||||
pub max_concurrent_requests: usize,
|
||||
pub history_limit: usize,
|
||||
pub recent_collections: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
default_timeout_secs: 0,
|
||||
proxy_mode: ProxyMode::System,
|
||||
proxy_url: String::new(),
|
||||
verify_tls: true,
|
||||
ca_file: None,
|
||||
zoom: 1.0,
|
||||
theme: ThemeChoice::System,
|
||||
max_concurrent_requests: 8,
|
||||
history_limit: 500,
|
||||
recent_collections: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn request_options(&self) -> RequestOptions {
|
||||
RequestOptions {
|
||||
timeout: (self.default_timeout_secs > 0).then(|| Duration::from_secs(self.default_timeout_secs)),
|
||||
verify_tls: self.verify_tls,
|
||||
ca_file: self.ca_file.clone(),
|
||||
proxy: match self.proxy_mode {
|
||||
ProxyMode::System => Proxy::System,
|
||||
ProxyMode::None => Proxy::None,
|
||||
ProxyMode::Manual if self.proxy_url.trim().is_empty() => Proxy::System,
|
||||
ProxyMode::Manual => Proxy::Manual(self.proxy_url.trim().to_string()),
|
||||
},
|
||||
..RequestOptions::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_recent(&mut self, p: PathBuf) {
|
||||
self.recent_collections.retain(|r| r != &p);
|
||||
self.recent_collections.insert(0, p);
|
||||
self.recent_collections.truncate(10);
|
||||
}
|
||||
|
||||
pub fn from_toml(s: &str) -> Result<Self, toml::de::Error> {
|
||||
toml::from_str(s)
|
||||
}
|
||||
|
||||
pub fn to_toml(&self) -> String {
|
||||
toml::to_string_pretty(self).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_and_tolerates_missing_fields() {
|
||||
let mut s = Settings {
|
||||
proxy_mode: ProxyMode::Manual,
|
||||
proxy_url: "http://proxy:3128".into(),
|
||||
..Default::default()
|
||||
};
|
||||
s.add_recent("/a".into());
|
||||
assert_eq!(Settings::from_toml(&s.to_toml()).unwrap(), s);
|
||||
let partial = Settings::from_toml("zoom = 1.5\n").unwrap();
|
||||
assert_eq!(partial.zoom, 1.5);
|
||||
assert_eq!(partial.max_concurrent_requests, 8);
|
||||
assert_eq!(s.request_options().proxy, Proxy::Manual("http://proxy:3128".into()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
//! `AppState`: everything the UI shows, as plain data. Only
|
||||
//! [`crate::action::update`] changes it.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Instant, SystemTime};
|
||||
|
||||
use reqlite_core::collection::Node;
|
||||
use reqlite_core::cookies::CookieJar;
|
||||
use reqlite_core::env::Environments;
|
||||
use reqlite_core::http::{BodyStore, Response};
|
||||
use reqlite_core::httpfile::{HttpFile, RequestKey};
|
||||
use reqlite_core::params::Param;
|
||||
use reqlite_core::template::Resolver;
|
||||
use reqlite_core::{CancelToken, Request};
|
||||
|
||||
use crate::history::HistoryEntry;
|
||||
use crate::settings::Settings;
|
||||
|
||||
pub type TabId = u64;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct AppState {
|
||||
pub tabs: Vec<Tab>,
|
||||
pub active: Option<TabId>,
|
||||
pub next_tab_id: TabId,
|
||||
pub collection: Option<CollectionState>,
|
||||
pub selected_env: Option<String>,
|
||||
pub settings: Settings,
|
||||
/// Oldest first.
|
||||
pub history: Vec<HistoryEntry>,
|
||||
/// Keyed by collection root; `None` for requests outside a collection.
|
||||
pub cookie_jars: HashMap<Option<PathBuf>, CookieJar>,
|
||||
pub status: Option<Status>,
|
||||
pub dialog: Option<Dialog>,
|
||||
pub windows: Windows,
|
||||
pub quick_open: Option<QuickOpen>,
|
||||
pub env_editor: Option<EnvEditor>,
|
||||
/// Asks the UI to focus the URL field on the next frame.
|
||||
pub focus_url: bool,
|
||||
/// Set when the user confirmed quitting with unsaved changes.
|
||||
pub quit_confirmed: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Status {
|
||||
pub text: String,
|
||||
pub is_error: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Windows {
|
||||
pub history: bool,
|
||||
pub cookies: bool,
|
||||
pub settings: bool,
|
||||
pub about: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Dialog {
|
||||
/// Closing a tab with unsaved changes.
|
||||
ConfirmCloseTab(TabId),
|
||||
/// Quitting with unsaved changes.
|
||||
ConfirmQuit,
|
||||
/// The file of a tab with unsaved changes changed on disk.
|
||||
Conflict { tab: TabId, path: PathBuf },
|
||||
/// A text prompt (new file, rename …).
|
||||
Prompt(Prompt),
|
||||
/// Confirm a destructive collection operation.
|
||||
ConfirmDelete(DeleteTarget),
|
||||
/// Result of a Postman import.
|
||||
ImportSummary {
|
||||
root: PathBuf,
|
||||
files: usize,
|
||||
warnings: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DeleteTarget {
|
||||
Request { file: PathBuf, index: usize, label: String },
|
||||
File(PathBuf),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Prompt {
|
||||
pub kind: PromptKind,
|
||||
pub title: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PromptKind {
|
||||
NewFile { dir: PathBuf },
|
||||
RenameFile { path: PathBuf },
|
||||
RenameRequest { file: PathBuf, index: usize },
|
||||
NewEnvironment,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct QuickOpen {
|
||||
pub query: String,
|
||||
pub selected: usize,
|
||||
}
|
||||
|
||||
/// The environment editor works on a copy that is written on Save.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EnvEditor {
|
||||
pub envs: Environments,
|
||||
pub selected: String,
|
||||
/// Private values whose text is shown instead of `••••`.
|
||||
pub revealed: Vec<(String, String)>,
|
||||
pub dirty: bool,
|
||||
}
|
||||
|
||||
pub struct CollectionState {
|
||||
pub root: PathBuf,
|
||||
pub tree: Node,
|
||||
pub files: BTreeMap<PathBuf, HttpFile>,
|
||||
pub envs: Environments,
|
||||
pub env_error: Option<String>,
|
||||
/// The private env file exists but is not git-ignored.
|
||||
pub private_not_ignored: bool,
|
||||
pub gitignore_offer_dismissed: bool,
|
||||
}
|
||||
|
||||
impl CollectionState {
|
||||
/// Every request in the collection as `(file, index, request)`.
|
||||
pub fn all_requests(&self) -> impl Iterator<Item = (&PathBuf, usize, &Request)> {
|
||||
self.files
|
||||
.iter()
|
||||
.flat_map(|(p, f)| f.requests().enumerate().map(move |(i, r)| (p, i, r)))
|
||||
}
|
||||
|
||||
pub fn relative<'a>(&self, p: &'a Path) -> &'a Path {
|
||||
p.strip_prefix(&self.root).unwrap_or(p)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum RequestTab {
|
||||
#[default]
|
||||
Params,
|
||||
Headers,
|
||||
Body,
|
||||
Auth,
|
||||
Source,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum ResponseTab {
|
||||
#[default]
|
||||
Body,
|
||||
Headers,
|
||||
Timings,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum BodyView {
|
||||
#[default]
|
||||
Pretty,
|
||||
Raw,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Origin {
|
||||
pub file: PathBuf,
|
||||
pub key: RequestKey,
|
||||
}
|
||||
|
||||
pub struct InFlight {
|
||||
pub cancel: CancelToken,
|
||||
pub started: Instant,
|
||||
pub seq: u64,
|
||||
/// What goes into history once the response arrives.
|
||||
pub history: HistoryEntry,
|
||||
pub cookie_jar: Option<Option<PathBuf>>,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
pub struct Tab {
|
||||
pub id: TabId,
|
||||
pub origin: Option<Origin>,
|
||||
/// The request being edited.
|
||||
pub request: Request,
|
||||
/// The last loaded or saved version (for the dirty marker).
|
||||
pub saved: Request,
|
||||
/// The Source tab text.
|
||||
pub source: String,
|
||||
pub saved_source: String,
|
||||
/// The last edit was made in the Source tab, so its text (with comments
|
||||
/// and anything else the form doesn't model) is what gets saved.
|
||||
pub source_authoritative: bool,
|
||||
pub source_error: Option<String>,
|
||||
/// Derived from the URL; edits go back to the URL.
|
||||
pub params: Vec<Param>,
|
||||
pub request_tab: RequestTab,
|
||||
pub response_tab: ResponseTab,
|
||||
pub body_view: BodyView,
|
||||
pub in_flight: Option<InFlight>,
|
||||
pub seq: u64,
|
||||
pub response: Option<ResponseView>,
|
||||
pub error: Option<String>,
|
||||
pub search: Search,
|
||||
/// The request was deleted from (or never belonged to) its file.
|
||||
pub orphaned: bool,
|
||||
}
|
||||
|
||||
impl Tab {
|
||||
pub fn new(id: TabId, request: Request, origin: Option<Origin>, source: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
origin,
|
||||
params: reqlite_core::params::parse_params(&request.url),
|
||||
saved: request.clone(),
|
||||
request,
|
||||
saved_source: source.clone(),
|
||||
source,
|
||||
source_authoritative: false,
|
||||
source_error: None,
|
||||
request_tab: RequestTab::default(),
|
||||
response_tab: ResponseTab::default(),
|
||||
body_view: BodyView::default(),
|
||||
in_flight: None,
|
||||
seq: 0,
|
||||
response: None,
|
||||
error: None,
|
||||
search: Search::default(),
|
||||
orphaned: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
!self.request.same_content(&self.saved) || (self.source_authoritative && self.source != self.saved_source)
|
||||
}
|
||||
|
||||
pub fn title(&self) -> String {
|
||||
if let Some(n) = self.request.display_name() {
|
||||
return n.to_string();
|
||||
}
|
||||
let url = self.request.url.trim();
|
||||
if url.is_empty() {
|
||||
"New request".into()
|
||||
} else {
|
||||
let short: String = url.chars().take(40).collect();
|
||||
if url.chars().count() > 40 {
|
||||
format!("{short}…")
|
||||
} else {
|
||||
short
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Search {
|
||||
pub open: bool,
|
||||
pub query: String,
|
||||
/// `(line, byte range in line)`.
|
||||
pub matches: Vec<(usize, std::ops::Range<usize>)>,
|
||||
pub current: usize,
|
||||
/// Asks the UI to scroll to this line.
|
||||
pub scroll_to: Option<usize>,
|
||||
}
|
||||
|
||||
pub struct ResponseView {
|
||||
pub response: Response,
|
||||
pub received_at: SystemTime,
|
||||
pub prepared: Option<PreparedBody>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BodyKind {
|
||||
Json,
|
||||
Text,
|
||||
Image,
|
||||
Binary,
|
||||
Empty,
|
||||
}
|
||||
|
||||
/// A response body made ready for display (off the UI thread).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PreparedBody {
|
||||
pub kind: BodyKind,
|
||||
pub raw: TextLines,
|
||||
pub pretty: Option<TextLines>,
|
||||
pub image: Option<Arc<[u8]>>,
|
||||
/// Only the first part of the body is shown.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
impl PreparedBody {
|
||||
pub fn text(&self, view: BodyView) -> &TextLines {
|
||||
match (view, &self.pretty) {
|
||||
(BodyView::Pretty, Some(p)) => p,
|
||||
_ => &self.raw,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Text plus the byte offset where each line starts.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TextLines {
|
||||
pub text: Arc<String>,
|
||||
pub starts: Arc<Vec<usize>>,
|
||||
}
|
||||
|
||||
impl TextLines {
|
||||
pub fn new(text: String) -> Self {
|
||||
let mut starts = vec![0];
|
||||
starts.extend(text.match_indices('\n').map(|(i, _)| i + 1));
|
||||
if starts.len() > 1 && *starts.last().unwrap() == text.len() {
|
||||
starts.pop();
|
||||
}
|
||||
Self {
|
||||
text: Arc::new(text),
|
||||
starts: Arc::new(starts),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn line_count(&self) -> usize {
|
||||
if self.text.is_empty() {
|
||||
0
|
||||
} else {
|
||||
self.starts.len()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn line(&self, i: usize) -> &str {
|
||||
let start = self.starts[i];
|
||||
let end = self.starts.get(i + 1).copied().unwrap_or(self.text.len());
|
||||
self.text[start..end].trim_end_matches(['\n', '\r'])
|
||||
}
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn tab(&self, id: TabId) -> Option<&Tab> {
|
||||
self.tabs.iter().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
pub fn tab_mut(&mut self, id: TabId) -> Option<&mut Tab> {
|
||||
self.tabs.iter_mut().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
pub fn active_tab(&self) -> Option<&Tab> {
|
||||
self.active.and_then(|id| self.tab(id))
|
||||
}
|
||||
|
||||
pub fn alloc_tab_id(&mut self) -> TabId {
|
||||
self.next_tab_id += 1;
|
||||
self.next_tab_id
|
||||
}
|
||||
|
||||
pub fn any_dirty(&self) -> bool {
|
||||
self.tabs.iter().any(Tab::is_dirty)
|
||||
}
|
||||
|
||||
/// File variables of the tab's file plus the selected environment.
|
||||
pub fn resolver_for(&self, tab: &Tab) -> Resolver {
|
||||
let file_vars = tab
|
||||
.origin
|
||||
.as_ref()
|
||||
.and_then(|o| self.collection.as_ref()?.files.get(&o.file))
|
||||
.map(|f| f.variables())
|
||||
.unwrap_or_default();
|
||||
match &self.collection {
|
||||
Some(c) => c.envs.resolver(self.selected_env.as_deref(), &file_vars),
|
||||
None => Environments::default().resolver(None, &file_vars),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` comes from the private env file (shown masked).
|
||||
pub fn is_private_var(&self, name: &str) -> bool {
|
||||
match (&self.collection, &self.selected_env) {
|
||||
(Some(c), Some(env)) => c.envs.is_private(env, name),
|
||||
(Some(c), None) => c.envs.is_private(reqlite_core::env::SHARED_ENV, name),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Directory that relative file references in the tab resolve against.
|
||||
pub fn base_dir_for(&self, tab: &Tab) -> PathBuf {
|
||||
if let Some(o) = &tab.origin {
|
||||
if let Some(p) = o.file.parent() {
|
||||
return p.to_path_buf();
|
||||
}
|
||||
}
|
||||
if let Some(c) = &self.collection {
|
||||
return c.root.clone();
|
||||
}
|
||||
std::env::current_dir().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn set_error(&mut self, text: impl Into<String>) {
|
||||
self.status = Some(Status {
|
||||
text: text.into(),
|
||||
is_error: true,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_info(&mut self, text: impl Into<String>) {
|
||||
self.status = Some(Status {
|
||||
text: text.into(),
|
||||
is_error: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a `PreparedBody` (runs on a blocking thread for big bodies).
|
||||
pub fn prepare_body(body: &BodyStore, content_type: &str, max_display: u64) -> PreparedBody {
|
||||
let ct = content_type.to_ascii_lowercase();
|
||||
let mut bytes = match body {
|
||||
BodyStore::InMemory(b) => b.as_ref().clone(),
|
||||
BodyStore::TempFile(p) => {
|
||||
use std::io::Read;
|
||||
let mut buf = Vec::new();
|
||||
if let Ok(f) = std::fs::File::open(&**p) {
|
||||
let _ = f.take(max_display).read_to_end(&mut buf);
|
||||
}
|
||||
buf
|
||||
}
|
||||
};
|
||||
let total = match body {
|
||||
BodyStore::InMemory(b) => b.len() as u64,
|
||||
BodyStore::TempFile(p) => std::fs::metadata(&**p).map(|m| m.len()).unwrap_or(0),
|
||||
};
|
||||
let truncated = total > max_display;
|
||||
bytes.truncate(max_display as usize);
|
||||
|
||||
if bytes.is_empty() {
|
||||
return PreparedBody {
|
||||
kind: BodyKind::Empty,
|
||||
raw: TextLines::default(),
|
||||
pretty: None,
|
||||
image: None,
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
if ct.starts_with("image/") && !ct.contains("svg") && !truncated {
|
||||
return PreparedBody {
|
||||
kind: BodyKind::Image,
|
||||
raw: TextLines::default(),
|
||||
pretty: None,
|
||||
image: Some(Arc::from(bytes.into_boxed_slice())),
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
let looks_binary = std::str::from_utf8(&bytes[..bytes.len().min(4096)]).is_err()
|
||||
&& !ct.starts_with("text/")
|
||||
&& !ct.contains("json")
|
||||
&& !ct.contains("xml");
|
||||
if looks_binary {
|
||||
return PreparedBody {
|
||||
kind: BodyKind::Binary,
|
||||
raw: TextLines::new(hex_dump(&bytes[..bytes.len().min(64 * 1024)])),
|
||||
pretty: None,
|
||||
image: None,
|
||||
truncated: truncated || bytes.len() > 64 * 1024,
|
||||
};
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes).into_owned();
|
||||
let is_json = ct.contains("json") || {
|
||||
let t = text.trim_start();
|
||||
(t.starts_with('{') || t.starts_with('[')) && !ct.contains("html")
|
||||
};
|
||||
if is_json && !truncated {
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
|
||||
let pretty = serde_json::to_string_pretty(&v).unwrap_or_default();
|
||||
return PreparedBody {
|
||||
kind: BodyKind::Json,
|
||||
raw: TextLines::new(text),
|
||||
pretty: Some(TextLines::new(pretty)),
|
||||
image: None,
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
}
|
||||
PreparedBody {
|
||||
kind: BodyKind::Text,
|
||||
raw: TextLines::new(text),
|
||||
pretty: None,
|
||||
image: None,
|
||||
truncated,
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_dump(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 4);
|
||||
for (i, chunk) in bytes.chunks(16).enumerate() {
|
||||
out.push_str(&format!("{:08x} ", i * 16));
|
||||
for j in 0..16 {
|
||||
match chunk.get(j) {
|
||||
Some(b) => out.push_str(&format!("{b:02x} ")),
|
||||
None => out.push_str(" "),
|
||||
}
|
||||
}
|
||||
out.push(' ');
|
||||
for &b in chunk {
|
||||
out.push(if b.is_ascii_graphic() || b == b' ' {
|
||||
b as char
|
||||
} else {
|
||||
'.'
|
||||
});
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
//! UI panels. They only read [`AppState`] and push [`Action`]s.
|
||||
|
||||
pub mod request;
|
||||
pub mod response;
|
||||
pub mod sidebar;
|
||||
pub mod widgets;
|
||||
pub mod windows;
|
||||
|
||||
use egui::{Context, Key, KeyboardShortcut, Modifiers, RichText, Ui};
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::state::{AppState, QuickOpen};
|
||||
use widgets::VarCtx;
|
||||
|
||||
pub fn draw(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
|
||||
shortcuts(ui.ctx(), state, acts);
|
||||
|
||||
egui::Panel::top("menu").show(ui, |ui| menu_bar(ui, state, acts));
|
||||
egui::Panel::bottom("status").show(ui, |ui| status_bar(ui, state, acts));
|
||||
egui::Panel::left("sidebar")
|
||||
.resizable(true)
|
||||
.default_size(250.0)
|
||||
.show(ui, |ui| sidebar::show(ui, state, acts));
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
tab_bar(ui, state, acts);
|
||||
match state.active_tab() {
|
||||
Some(tab) => {
|
||||
let resolver = state.resolver_for(tab);
|
||||
let is_private = |n: &str| state.is_private_var(n);
|
||||
let vars = VarCtx {
|
||||
resolver: &resolver,
|
||||
is_private: &is_private,
|
||||
};
|
||||
if tab.orphaned {
|
||||
ui.label(
|
||||
RichText::new("This request is no longer in its file. Save writes it to a file you pick.")
|
||||
.color(ui.visuals().warn_fg_color),
|
||||
);
|
||||
}
|
||||
request::url_bar(ui, state, tab, &vars, acts);
|
||||
ui.add_space(4.0);
|
||||
egui::Panel::top(("request-editor", tab.id))
|
||||
.resizable(true)
|
||||
.default_size(250.0)
|
||||
.size_range(80.0..=f32::INFINITY)
|
||||
.show(ui, |ui| request::editor(ui, state, tab, &vars, acts));
|
||||
egui::CentralPanel::no_frame().show(ui, |ui| {
|
||||
ui.add_space(4.0);
|
||||
response::show(ui, tab, acts);
|
||||
});
|
||||
}
|
||||
None => welcome(ui, acts),
|
||||
}
|
||||
});
|
||||
|
||||
windows::show(ui.ctx(), state, acts);
|
||||
}
|
||||
|
||||
fn shortcuts(ctx: &Context, state: &AppState, acts: &mut Vec<Action>) {
|
||||
if state.dialog.is_some() {
|
||||
return;
|
||||
}
|
||||
let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);
|
||||
let active = state.active;
|
||||
ctx.input_mut(|i| {
|
||||
if i.consume_shortcut(&cmd(Key::Enter)) {
|
||||
if let Some(id) = active {
|
||||
acts.push(Action::Send(id));
|
||||
}
|
||||
}
|
||||
if i.consume_shortcut(&cmd(Key::S)) {
|
||||
if let Some(id) = active {
|
||||
acts.push(Action::Save(id));
|
||||
}
|
||||
}
|
||||
if i.consume_shortcut(&cmd(Key::T)) {
|
||||
acts.push(Action::NewTab);
|
||||
}
|
||||
if i.consume_shortcut(&cmd(Key::W)) {
|
||||
if let Some(id) = active {
|
||||
acts.push(Action::CloseTab(id));
|
||||
}
|
||||
}
|
||||
if i.consume_shortcut(&cmd(Key::L)) {
|
||||
acts.push(Action::FocusUrl);
|
||||
}
|
||||
if i.consume_shortcut(&cmd(Key::P)) {
|
||||
acts.push(Action::QuickOpen(Some(QuickOpen::default())));
|
||||
}
|
||||
if i.consume_shortcut(&cmd(Key::F)) {
|
||||
if let Some(id) = active {
|
||||
acts.push(Action::SearchOpen(id, true));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
ui.menu_button("File", |ui| {
|
||||
if ui.button("New tab Ctrl+T").clicked() {
|
||||
acts.push(Action::NewTab);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Open collection folder…").clicked() {
|
||||
acts.push(Action::PickCollection);
|
||||
ui.close();
|
||||
}
|
||||
ui.menu_button("Recent collections", |ui| {
|
||||
for p in &state.settings.recent_collections {
|
||||
if ui.button(p.display().to_string()).clicked() {
|
||||
acts.push(Action::OpenCollection(p.clone()));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if state.settings.recent_collections.is_empty() {
|
||||
ui.label(RichText::new("None yet").weak());
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
let has_tab = state.active.is_some();
|
||||
if ui
|
||||
.add_enabled(has_tab, egui::Button::new("Save Ctrl+S"))
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::Save(state.active.unwrap()));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Import Postman collection…").clicked() {
|
||||
acts.push(Action::ImportPostman);
|
||||
ui.close();
|
||||
}
|
||||
ui.label(
|
||||
RichText::new("Tip: paste a curl command into the URL bar to import it.")
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
ui.separator();
|
||||
if ui.button("Settings…").clicked() {
|
||||
acts.push(Action::SetWindows(crate::state::Windows {
|
||||
settings: true,
|
||||
..state.windows
|
||||
}));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Quit").clicked() {
|
||||
acts.push(Action::CloseRequested);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
ui.menu_button("View", |ui| {
|
||||
let mut w = state.windows;
|
||||
ui.checkbox(&mut w.history, "History");
|
||||
ui.checkbox(&mut w.cookies, "Cookies");
|
||||
if w != state.windows {
|
||||
acts.push(Action::SetWindows(w));
|
||||
}
|
||||
if ui.button("Quick open… Ctrl+P").clicked() {
|
||||
acts.push(Action::QuickOpen(Some(QuickOpen::default())));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
ui.menu_button("Help", |ui| {
|
||||
if ui.button("About and shortcuts").clicked() {
|
||||
acts.push(Action::SetWindows(crate::state::Windows {
|
||||
about: true,
|
||||
..state.windows
|
||||
}));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Environment picker on the right.
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if let Some(c) = &state.collection {
|
||||
if ui.button("Edit…").on_hover_text("Edit environments").clicked() {
|
||||
acts.push(Action::OpenEnvEditor);
|
||||
}
|
||||
let names = c.envs.names();
|
||||
let label = state.selected_env.clone().unwrap_or_else(|| "No environment".into());
|
||||
egui::ComboBox::from_id_salt("env-picker")
|
||||
.selected_text(label)
|
||||
.width(150.0)
|
||||
.show_ui(ui, |ui| {
|
||||
if ui
|
||||
.selectable_label(state.selected_env.is_none(), "No environment")
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::SelectEnv(None));
|
||||
}
|
||||
for n in names {
|
||||
if ui
|
||||
.selectable_label(state.selected_env.as_ref() == Some(&n), &n)
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::SelectEnv(Some(n.clone())));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label("Environment:");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
|
||||
egui::ScrollArea::horizontal().id_salt("tabs").show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for t in &state.tabs {
|
||||
let selected = state.active == Some(t.id);
|
||||
let mut title = t.title();
|
||||
if t.is_dirty() {
|
||||
title.push_str(" •");
|
||||
}
|
||||
if t.in_flight.is_some() {
|
||||
title.push_str(" ⏳");
|
||||
}
|
||||
let resp = ui.selectable_label(selected, title);
|
||||
let resp = match &t.origin {
|
||||
Some(o) => resp.on_hover_text(o.file.display().to_string()),
|
||||
None => resp,
|
||||
};
|
||||
if resp.clicked() {
|
||||
acts.push(Action::SelectTab(t.id));
|
||||
}
|
||||
if resp.middle_clicked() {
|
||||
acts.push(Action::CloseTab(t.id));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button("Close").clicked() {
|
||||
acts.push(Action::CloseTab(t.id));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
if ui.small_button("×").on_hover_text("Close (Ctrl+W)").clicked() {
|
||||
acts.push(Action::CloseTab(t.id));
|
||||
}
|
||||
ui.separator();
|
||||
}
|
||||
if ui.button("+").on_hover_text("New tab (Ctrl+T)").clicked() {
|
||||
acts.push(Action::NewTab);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
|
||||
fn status_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
|
||||
ui.horizontal(|ui| {
|
||||
match &state.status {
|
||||
Some(s) => {
|
||||
let color = if s.is_error {
|
||||
ui.visuals().error_fg_color
|
||||
} else {
|
||||
ui.visuals().text_color()
|
||||
};
|
||||
ui.colored_label(color, &s.text);
|
||||
if ui.small_button("×").clicked() {
|
||||
acts.push(Action::DismissStatus);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.label(RichText::new("Ready").weak());
|
||||
}
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let n = state.tabs.iter().filter(|t| t.in_flight.is_some()).count();
|
||||
if n > 0 {
|
||||
ui.spinner();
|
||||
ui.label(format!("{n} in flight"));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn welcome(ui: &mut Ui, acts: &mut Vec<Action>) {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(60.0);
|
||||
ui.heading("reqlite");
|
||||
ui.label("Send HTTP requests and keep them as .http files.");
|
||||
ui.add_space(12.0);
|
||||
if ui.button("New request (Ctrl+T)").clicked() {
|
||||
acts.push(Action::NewTab);
|
||||
}
|
||||
if ui.button("Open a collection folder…").clicked() {
|
||||
acts.push(Action::PickCollection);
|
||||
}
|
||||
ui.add_space(12.0);
|
||||
ui.label(RichText::new("Tip: paste a curl command into the URL bar to import it.").weak());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,647 @@
|
||||
//! The URL bar and the request editor tabs.
|
||||
|
||||
use base64::Engine;
|
||||
use egui::{Key, RichText, Ui};
|
||||
use reqlite_core::params::Param;
|
||||
use reqlite_core::{Body, Header, Method, Part, PartBody};
|
||||
|
||||
use super::widgets::{code_edit, method_color, var_text_edit, VarCtx};
|
||||
use crate::action::Action;
|
||||
use crate::state::{AppState, RequestTab, Tab};
|
||||
|
||||
pub const MULTIPART_BOUNDARY: &str = "WebAppBoundary";
|
||||
|
||||
pub fn url_bar(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
ui.horizontal(|ui| {
|
||||
// Method.
|
||||
let dark = ui.visuals().dark_mode;
|
||||
let current = tab.request.method.clone();
|
||||
egui::ComboBox::from_id_salt(("method", id))
|
||||
.width(90.0)
|
||||
.selected_text(
|
||||
RichText::new(current.as_str())
|
||||
.strong()
|
||||
.color(method_color(current.as_str(), dark)),
|
||||
)
|
||||
.show_ui(ui, |ui| {
|
||||
for m in Method::COMMON {
|
||||
let label = RichText::new(m.as_str()).color(method_color(m.as_str(), dark));
|
||||
if ui.selectable_label(m == current, label).clicked() && m != current {
|
||||
acts.push(Action::SetMethod(id, m.clone()));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Buttons on the right, URL takes the rest.
|
||||
let buttons_w = 190.0;
|
||||
let mut url = tab.request.url.clone();
|
||||
let w = (ui.available_width() - buttons_w).max(120.0);
|
||||
let resp = var_text_edit(
|
||||
ui,
|
||||
&mut url,
|
||||
Some(vars),
|
||||
"Enter a URL, or paste a curl command",
|
||||
w,
|
||||
("url", id),
|
||||
);
|
||||
if state.focus_url {
|
||||
resp.request_focus();
|
||||
acts.push(Action::UrlFocused);
|
||||
}
|
||||
if resp.changed() {
|
||||
acts.push(Action::UrlEdited(id, url));
|
||||
}
|
||||
if resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {
|
||||
acts.push(Action::Send(id));
|
||||
}
|
||||
|
||||
if tab.in_flight.is_some() {
|
||||
if ui.button("Cancel").on_hover_text("Stop the request").clicked() {
|
||||
acts.push(Action::Cancel(id));
|
||||
}
|
||||
} else if ui
|
||||
.add(egui::Button::new(RichText::new("Send").strong()))
|
||||
.on_hover_text("Send (Ctrl+Enter)")
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::Send(id));
|
||||
}
|
||||
let save_label = if tab.is_dirty() { "Save •" } else { "Save" };
|
||||
if ui
|
||||
.button(save_label)
|
||||
.on_hover_text("Save to the .http file (Ctrl+S)")
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::Save(id));
|
||||
}
|
||||
ui.menu_button("…", |ui| {
|
||||
if ui.button("Copy as curl").clicked() {
|
||||
acts.push(Action::CopyAsCurl(id));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Copy as .http").clicked() {
|
||||
acts.push(Action::CopyAsHttp(id));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let mut follow = !tab.request.directives.no_redirect;
|
||||
if ui.checkbox(&mut follow, "Follow redirects").changed() {
|
||||
acts.push(Action::SetNoRedirect(id, !follow));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn editor(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
ui.horizontal(|ui| {
|
||||
let enabled_headers = tab.request.headers.iter().filter(|h| !h.disabled).count();
|
||||
let tabs = [
|
||||
(RequestTab::Params, format!("Params ({})", tab.params.len())),
|
||||
(RequestTab::Headers, format!("Headers ({enabled_headers})")),
|
||||
(
|
||||
RequestTab::Body,
|
||||
if tab.request.body.is_none() {
|
||||
"Body".into()
|
||||
} else {
|
||||
"Body •".into()
|
||||
},
|
||||
),
|
||||
(RequestTab::Auth, "Auth".into()),
|
||||
(
|
||||
RequestTab::Source,
|
||||
if tab.source_error.is_some() {
|
||||
"Source ⚠".into()
|
||||
} else {
|
||||
"Source".into()
|
||||
},
|
||||
),
|
||||
];
|
||||
for (t, label) in tabs {
|
||||
if ui.selectable_label(tab.request_tab == t, label).clicked() {
|
||||
acts.push(Action::SetRequestTab(id, t));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt(("req-scroll", id))
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| match tab.request_tab {
|
||||
RequestTab::Params => params(ui, tab, vars, acts),
|
||||
RequestTab::Headers => headers(ui, tab, vars, acts),
|
||||
RequestTab::Body => body(ui, state, tab, vars, acts),
|
||||
RequestTab::Auth => auth(ui, tab, vars, acts),
|
||||
RequestTab::Source => source(ui, tab, vars, acts),
|
||||
});
|
||||
}
|
||||
|
||||
fn params(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
let mut rows: Vec<Param> = tab.params.clone();
|
||||
let mut changed = false;
|
||||
let mut remove = None;
|
||||
let n = rows.len();
|
||||
rows.push(Param::default()); // the "add" row
|
||||
// Measure before the grid: inside it, the width is a single cell's.
|
||||
let w = ((ui.available_width() - 60.0) / 2.0).max(100.0);
|
||||
egui::Grid::new(("params", id))
|
||||
.num_columns(3)
|
||||
.striped(true)
|
||||
.show(ui, |ui| {
|
||||
ui.label(RichText::new("Key").weak());
|
||||
ui.label(RichText::new("Value").weak());
|
||||
ui.label("");
|
||||
ui.end_row();
|
||||
for (i, p) in rows.iter_mut().enumerate() {
|
||||
changed |= var_text_edit(
|
||||
ui,
|
||||
&mut p.key,
|
||||
Some(vars),
|
||||
if i == n { "Add parameter" } else { "" },
|
||||
w,
|
||||
("pk", id, i),
|
||||
)
|
||||
.changed();
|
||||
let mut v = p.value.clone().unwrap_or_default();
|
||||
if var_text_edit(ui, &mut v, Some(vars), "", w, ("pv", id, i)).changed() {
|
||||
p.value = Some(v);
|
||||
changed = true;
|
||||
}
|
||||
if i < n && ui.small_button("×").on_hover_text("Remove").clicked() {
|
||||
remove = Some(i);
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
if let Some(i) = remove {
|
||||
rows.remove(i);
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
if rows
|
||||
.last()
|
||||
.is_some_and(|p| p.key.is_empty() && p.value.as_deref().unwrap_or("").is_empty())
|
||||
{
|
||||
rows.pop();
|
||||
}
|
||||
acts.push(Action::ParamsEdited(id, rows));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.label(
|
||||
RichText::new("Parameters are kept in the URL, exactly as typed.")
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
|
||||
fn headers(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
let mut rows = tab.request.headers.clone();
|
||||
let n = rows.len();
|
||||
rows.push(Header::new("", ""));
|
||||
let mut changed = false;
|
||||
let mut remove = None;
|
||||
let w = (ui.available_width() - 90.0).max(240.0);
|
||||
egui::Grid::new(("headers", id))
|
||||
.num_columns(4)
|
||||
.striped(true)
|
||||
.show(ui, |ui| {
|
||||
ui.label("");
|
||||
ui.label(RichText::new("Name").weak());
|
||||
ui.label(RichText::new("Value").weak());
|
||||
ui.label("");
|
||||
ui.end_row();
|
||||
for (i, h) in rows.iter_mut().enumerate() {
|
||||
if i < n {
|
||||
let mut on = !h.disabled;
|
||||
if ui
|
||||
.checkbox(&mut on, "")
|
||||
.on_hover_text("Disabled headers are kept as `# Name: value` comments")
|
||||
.changed()
|
||||
{
|
||||
h.disabled = !on;
|
||||
changed = true;
|
||||
}
|
||||
} else {
|
||||
ui.label("");
|
||||
}
|
||||
changed |= var_text_edit(
|
||||
ui,
|
||||
&mut h.name,
|
||||
Some(vars),
|
||||
if i == n { "Add header" } else { "" },
|
||||
(w * 0.35).max(100.0),
|
||||
("hn", id, i),
|
||||
)
|
||||
.changed();
|
||||
changed |=
|
||||
var_text_edit(ui, &mut h.value, Some(vars), "", (w * 0.65).max(120.0), ("hv", id, i)).changed();
|
||||
if i < n && ui.small_button("×").on_hover_text("Remove").clicked() {
|
||||
remove = Some(i);
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
if let Some(i) = remove {
|
||||
rows.remove(i);
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
if rows.last().is_some_and(|h| h.name.is_empty() && h.value.is_empty()) {
|
||||
rows.pop();
|
||||
}
|
||||
acts.push(Action::HeadersEdited(id, rows));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Copy)]
|
||||
enum BodyKind {
|
||||
None,
|
||||
Text,
|
||||
File,
|
||||
Form,
|
||||
}
|
||||
|
||||
const MAX_EDITABLE_BODY: usize = 1024 * 1024;
|
||||
|
||||
fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
let req = &tab.request;
|
||||
let kind = match &req.body {
|
||||
Body::None => BodyKind::None,
|
||||
Body::Text(_) => BodyKind::Text,
|
||||
Body::FileRef { .. } => BodyKind::File,
|
||||
Body::Multipart { .. } => BodyKind::Form,
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
for (k, label) in [
|
||||
(BodyKind::None, "None"),
|
||||
(BodyKind::Text, "Text"),
|
||||
(BodyKind::File, "File"),
|
||||
(BodyKind::Form, "Multipart form"),
|
||||
] {
|
||||
if ui.radio(kind == k, label).clicked() && kind != k {
|
||||
match k {
|
||||
BodyKind::None => acts.push(Action::BodyEdited(id, Body::None)),
|
||||
BodyKind::Text => acts.push(Action::BodyEdited(id, Body::Text(String::new()))),
|
||||
BodyKind::File => acts.push(Action::BodyEdited(
|
||||
id,
|
||||
Body::FileRef {
|
||||
path: "./body.json".into(),
|
||||
substitute: false,
|
||||
},
|
||||
)),
|
||||
BodyKind::Form => {
|
||||
let mut headers = req.headers.clone();
|
||||
headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type"));
|
||||
headers.push(Header::new(
|
||||
"Content-Type",
|
||||
format!("multipart/form-data; boundary={MULTIPART_BOUNDARY}"),
|
||||
));
|
||||
acts.push(Action::HeadersEdited(id, headers));
|
||||
acts.push(Action::BodyEdited(
|
||||
id,
|
||||
Body::Multipart {
|
||||
boundary: MULTIPART_BOUNDARY.into(),
|
||||
parts: vec![Part {
|
||||
name: "field".into(),
|
||||
filename: None,
|
||||
headers: Vec::new(),
|
||||
body: PartBody::Text(String::new()),
|
||||
}],
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
match &req.body {
|
||||
Body::None => {
|
||||
ui.label(RichText::new("This request has no body.").weak());
|
||||
}
|
||||
Body::Text(text) => {
|
||||
let ct = req.header("content-type").unwrap_or("").to_ascii_lowercase();
|
||||
let is_json = ct.contains("json");
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Content-Type:");
|
||||
for (label, value) in [
|
||||
("JSON", "application/json"),
|
||||
("XML", "application/xml"),
|
||||
("Text", "text/plain"),
|
||||
("Form", "application/x-www-form-urlencoded"),
|
||||
] {
|
||||
if ui.selectable_label(ct.starts_with(value), label).clicked() {
|
||||
let mut headers = req.headers.clone();
|
||||
headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type"));
|
||||
headers.push(Header::new("Content-Type", value));
|
||||
acts.push(Action::HeadersEdited(id, headers));
|
||||
}
|
||||
}
|
||||
if is_json && ui.button("Format").on_hover_text("Pretty-print the JSON").clicked() {
|
||||
match serde_json::from_str::<serde_json::Value>(text) {
|
||||
Ok(v) => acts.push(Action::BodyEdited(
|
||||
id,
|
||||
Body::Text(serde_json::to_string_pretty(&v).unwrap_or_else(|_| text.clone())),
|
||||
)),
|
||||
Err(e) => acts.push(Action::Error(format!("Not valid JSON: {e}"))),
|
||||
}
|
||||
}
|
||||
});
|
||||
if text.len() > MAX_EDITABLE_BODY {
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"The body is {} KB, too large to edit here. Edit it in the .http file, or move it to a file (`< ./body.json`).",
|
||||
text.len() / 1024
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
} else {
|
||||
let mut t = text.clone();
|
||||
if code_edit(ui, &mut t, is_json, Some(vars.resolver), 12, ("body", id)).changed() {
|
||||
acts.push(Action::BodyEdited(id, Body::Text(t)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Body::FileRef { path, substitute } => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("File:");
|
||||
let mut p = path.display().to_string();
|
||||
if ui
|
||||
.add(egui::TextEdit::singleline(&mut p).desired_width(320.0))
|
||||
.changed()
|
||||
{
|
||||
acts.push(Action::BodyEdited(
|
||||
id,
|
||||
Body::FileRef {
|
||||
path: p.into(),
|
||||
substitute: *substitute,
|
||||
},
|
||||
));
|
||||
}
|
||||
if ui.button("Browse…").clicked() {
|
||||
acts.push(Action::PickBodyFile(id));
|
||||
}
|
||||
});
|
||||
let mut sub = *substitute;
|
||||
if ui
|
||||
.checkbox(&mut sub, "Replace {{variables}} in the file (`<@`)")
|
||||
.changed()
|
||||
{
|
||||
acts.push(Action::BodyEdited(
|
||||
id,
|
||||
Body::FileRef {
|
||||
path: path.clone(),
|
||||
substitute: sub,
|
||||
},
|
||||
));
|
||||
}
|
||||
ui.label(
|
||||
RichText::new("Relative paths are relative to the .http file.")
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
Body::Multipart { boundary, parts } => {
|
||||
let mut parts = parts.clone();
|
||||
let mut changed = false;
|
||||
let mut remove = None;
|
||||
egui::Grid::new(("parts", id))
|
||||
.num_columns(5)
|
||||
.striped(true)
|
||||
.show(ui, |ui| {
|
||||
for h in ["Name", "Kind", "Value / file", "Content-Type", ""] {
|
||||
ui.label(RichText::new(h).weak());
|
||||
}
|
||||
ui.end_row();
|
||||
for (i, p) in parts.iter_mut().enumerate() {
|
||||
changed |= ui
|
||||
.add_sized(
|
||||
[110.0, ui.spacing().interact_size.y],
|
||||
egui::TextEdit::singleline(&mut p.name),
|
||||
)
|
||||
.changed();
|
||||
let is_file = matches!(p.body, PartBody::File(_));
|
||||
egui::ComboBox::from_id_salt(("pk", id, i))
|
||||
.width(60.0)
|
||||
.selected_text(if is_file { "File" } else { "Text" })
|
||||
.show_ui(ui, |ui| {
|
||||
if ui.selectable_label(!is_file, "Text").clicked() && is_file {
|
||||
p.body = PartBody::Text(String::new());
|
||||
p.filename = None;
|
||||
changed = true;
|
||||
}
|
||||
if ui.selectable_label(is_file, "File").clicked() && !is_file {
|
||||
p.body = PartBody::File("./file.bin".into());
|
||||
p.filename = Some("file.bin".into());
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
match &mut p.body {
|
||||
PartBody::Text(t) => {
|
||||
changed |= var_text_edit(ui, t, Some(vars), "", 220.0, ("pv", id, i)).changed();
|
||||
}
|
||||
PartBody::File(f) => {
|
||||
let mut s = f.display().to_string();
|
||||
if ui
|
||||
.add_sized(
|
||||
[220.0, ui.spacing().interact_size.y],
|
||||
egui::TextEdit::singleline(&mut s),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
p.filename = std::path::Path::new(&s)
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned());
|
||||
*f = s.into();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut ct = p.content_type().unwrap_or("").to_string();
|
||||
if ui
|
||||
.add_sized(
|
||||
[120.0, ui.spacing().interact_size.y],
|
||||
egui::TextEdit::singleline(&mut ct),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
p.headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type"));
|
||||
if !ct.is_empty() {
|
||||
p.headers.push(Header::new("Content-Type", ct));
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if ui.small_button("×").clicked() {
|
||||
remove = Some(i);
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
if let Some(i) = remove {
|
||||
parts.remove(i);
|
||||
changed = true;
|
||||
}
|
||||
if ui.button("Add field").clicked() {
|
||||
parts.push(Part {
|
||||
name: format!("field{}", parts.len() + 1),
|
||||
filename: None,
|
||||
headers: Vec::new(),
|
||||
body: PartBody::Text(String::new()),
|
||||
});
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
acts.push(Action::BodyEdited(
|
||||
id,
|
||||
Body::Multipart {
|
||||
boundary: boundary.clone(),
|
||||
parts,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Copy)]
|
||||
enum AuthKind {
|
||||
None,
|
||||
Basic,
|
||||
Bearer,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// Splits an Authorization header into what the Auth tab shows.
|
||||
fn auth_parts(value: Option<&str>) -> (AuthKind, String, String) {
|
||||
let Some(v) = value else {
|
||||
return (AuthKind::None, String::new(), String::new());
|
||||
};
|
||||
if let Some(rest) = v.strip_prefix("Bearer ") {
|
||||
return (AuthKind::Bearer, rest.trim().to_string(), String::new());
|
||||
}
|
||||
if let Some(rest) = v.strip_prefix("Basic ") {
|
||||
let rest = rest.trim();
|
||||
if let Some((u, p)) = rest.split_once(' ') {
|
||||
return (AuthKind::Basic, u.to_string(), p.trim().to_string());
|
||||
}
|
||||
// Already encoded: show the decoded user and password.
|
||||
if let Some((u, p)) = base64::engine::general_purpose::STANDARD
|
||||
.decode(rest)
|
||||
.ok()
|
||||
.and_then(|b| String::from_utf8(b).ok())
|
||||
.and_then(|s| s.split_once(':').map(|(a, b)| (a.to_string(), b.to_string())))
|
||||
{
|
||||
return (AuthKind::Basic, u, p);
|
||||
}
|
||||
return (AuthKind::Basic, rest.to_string(), String::new());
|
||||
}
|
||||
(AuthKind::Other, v.to_string(), String::new())
|
||||
}
|
||||
|
||||
fn auth(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
let header = tab.request.header("authorization");
|
||||
let (kind, a, b) = auth_parts(header);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Type:");
|
||||
for (k, label) in [
|
||||
(AuthKind::None, "None"),
|
||||
(AuthKind::Basic, "Basic"),
|
||||
(AuthKind::Bearer, "Bearer token"),
|
||||
] {
|
||||
if ui.radio(kind == k, label).clicked() && kind != k {
|
||||
acts.push(Action::AuthEdited(
|
||||
id,
|
||||
match k {
|
||||
AuthKind::None => None,
|
||||
AuthKind::Basic => Some("Basic {{username}} {{password}}".into()),
|
||||
AuthKind::Bearer => Some("Bearer {{token}}".into()),
|
||||
AuthKind::Other => unreachable!(),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
match kind {
|
||||
AuthKind::None => {
|
||||
ui.label(RichText::new("No Authorization header.").weak());
|
||||
}
|
||||
AuthKind::Basic => {
|
||||
let (mut u, mut p) = (a, b);
|
||||
let mut changed = false;
|
||||
egui::Grid::new(("basic", id)).num_columns(2).show(ui, |ui| {
|
||||
ui.label("Username");
|
||||
changed |= var_text_edit(ui, &mut u, Some(vars), "", 260.0, ("bu", id)).changed();
|
||||
ui.end_row();
|
||||
ui.label("Password");
|
||||
changed |= var_text_edit(ui, &mut p, Some(vars), "", 260.0, ("bp", id)).changed();
|
||||
ui.end_row();
|
||||
});
|
||||
if changed {
|
||||
acts.push(Action::AuthEdited(id, Some(format!("Basic {u} {p}"))));
|
||||
}
|
||||
ui.label(
|
||||
RichText::new("Written as `Authorization: Basic user password`; it is base64-encoded when sent, like JetBrains does.")
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
AuthKind::Bearer => {
|
||||
let mut t = a;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Token");
|
||||
if var_text_edit(ui, &mut t, Some(vars), "{{token}}", 420.0, ("bt", id)).changed() {
|
||||
acts.push(Action::AuthEdited(id, Some(format!("Bearer {t}"))));
|
||||
}
|
||||
});
|
||||
}
|
||||
AuthKind::Other => {
|
||||
ui.label(format!("Custom Authorization header: {a}"));
|
||||
ui.label(RichText::new("Edit it in the Headers tab.").weak());
|
||||
}
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
ui.label(
|
||||
RichText::new("Auth is just the Authorization header; put secrets in the private env file.")
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
|
||||
fn source(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
if let Some(e) = &tab.source_error {
|
||||
ui.colored_label(ui.visuals().error_fg_color, e);
|
||||
}
|
||||
let mut text = tab.source.clone();
|
||||
if code_edit(ui, &mut text, false, Some(vars.resolver), 14, ("source", id)).changed() {
|
||||
acts.push(Action::SourceEdited(id, text));
|
||||
}
|
||||
ui.label(
|
||||
RichText::new("The request as it is stored in the .http file. Comments and response handlers are kept; scripts are never run.")
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn auth_parts_reads_the_header_forms() {
|
||||
assert!(auth_parts(None).0 == AuthKind::None);
|
||||
let (k, u, p) = auth_parts(Some("Basic {{user}} {{pass}}"));
|
||||
assert!(k == AuthKind::Basic && u == "{{user}}" && p == "{{pass}}");
|
||||
let (k, u, p) = auth_parts(Some("Basic YWRhOnMzY3JldA=="));
|
||||
assert!(k == AuthKind::Basic && u == "ada" && p == "s3cret");
|
||||
let (k, t, _) = auth_parts(Some("Bearer abc"));
|
||||
assert!(k == AuthKind::Bearer && t == "abc");
|
||||
assert!(auth_parts(Some("Digest x")).0 == AuthKind::Other);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! The response panel: status line, body viewer, headers and timings.
|
||||
|
||||
use egui::{Align, FontId, Layout, RichText, Ui};
|
||||
|
||||
use super::widgets::{build_job, human_size, json_spans, status_color, Palette};
|
||||
use crate::action::Action;
|
||||
use crate::state::{BodyKind, BodyView, ResponseTab, Tab, TextLines};
|
||||
|
||||
/// Lines longer than this are cut in the viewer (the full body can be saved
|
||||
/// or copied).
|
||||
const MAX_LINE: usize = 5_000;
|
||||
|
||||
pub fn show(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
if let Some(f) = &tab.in_flight {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spinner();
|
||||
ui.label(format!("Sending… {:.1} s", f.started.elapsed().as_secs_f32()));
|
||||
if ui.button("Cancel").clicked() {
|
||||
acts.push(Action::Cancel(id));
|
||||
}
|
||||
});
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
|
||||
return;
|
||||
}
|
||||
if let Some(e) = &tab.error {
|
||||
ui.colored_label(ui.visuals().error_fg_color, e);
|
||||
return;
|
||||
}
|
||||
let Some(view) = &tab.response else {
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.label(RichText::new("Send the request to see the response here.").weak());
|
||||
});
|
||||
return;
|
||||
};
|
||||
let r = &view.response;
|
||||
let dark = ui.visuals().dark_mode;
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(
|
||||
RichText::new(format!("{} {}", r.status, r.reason))
|
||||
.strong()
|
||||
.color(status_color(r.status, dark)),
|
||||
);
|
||||
ui.separator();
|
||||
ui.label(format!("{} ms", r.timings.total.as_millis()));
|
||||
ui.separator();
|
||||
ui.label(human_size(r.size));
|
||||
ui.separator();
|
||||
ui.label(RichText::new(&r.http_version).weak());
|
||||
if r.body.is_spilled() {
|
||||
ui.label(RichText::new("(stored in a temp file)").weak());
|
||||
}
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if ui.button("Save to file…").clicked() {
|
||||
acts.push(Action::SaveResponseBody(id));
|
||||
}
|
||||
if let Some(p) = &view.prepared {
|
||||
if p.kind != BodyKind::Image && ui.button("Copy body").clicked() {
|
||||
ui.ctx().copy_text(p.text(tab.body_view).text.to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
for (t, label) in [
|
||||
(ResponseTab::Body, "Body".to_string()),
|
||||
(ResponseTab::Headers, format!("Headers ({})", r.headers.len())),
|
||||
(ResponseTab::Timings, "Timings".to_string()),
|
||||
] {
|
||||
if ui.selectable_label(tab.response_tab == t, label).clicked() {
|
||||
acts.push(Action::SetResponseTab(id, t));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
|
||||
match tab.response_tab {
|
||||
ResponseTab::Body => body(ui, tab, acts),
|
||||
ResponseTab::Headers => {
|
||||
egui::ScrollArea::both()
|
||||
.id_salt(("resp-headers", id))
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| {
|
||||
egui::Grid::new(("resp-h", id))
|
||||
.num_columns(2)
|
||||
.striped(true)
|
||||
.show(ui, |ui| {
|
||||
for (n, v) in &r.headers {
|
||||
ui.add(egui::Label::new(RichText::new(n).strong().monospace()).selectable(true));
|
||||
ui.add(egui::Label::new(RichText::new(v).monospace()).selectable(true));
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
if r.effective_url != tab.request.url {
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(format!("Final URL: {}", r.effective_url)).weak());
|
||||
}
|
||||
});
|
||||
}
|
||||
ResponseTab::Timings => timings(ui, tab),
|
||||
}
|
||||
}
|
||||
|
||||
fn body(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
let view = tab.response.as_ref().unwrap();
|
||||
let Some(p) = &view.prepared else {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spinner();
|
||||
ui.label("Preparing the body…");
|
||||
});
|
||||
return;
|
||||
};
|
||||
match p.kind {
|
||||
BodyKind::Empty => {
|
||||
ui.label(RichText::new("No body.").weak());
|
||||
return;
|
||||
}
|
||||
BodyKind::Image => {
|
||||
if let Some(bytes) = &p.image {
|
||||
egui::ScrollArea::both()
|
||||
.id_salt(("img", id))
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| {
|
||||
ui.add(
|
||||
egui::Image::from_bytes(format!("bytes://response-{id}-{}", tab.seq), bytes.clone())
|
||||
.max_size(ui.available_size())
|
||||
.fit_to_original_size(1.0),
|
||||
);
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
if p.pretty.is_some() {
|
||||
if ui
|
||||
.selectable_label(tab.body_view == BodyView::Pretty, "Pretty")
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::SetBodyView(id, BodyView::Pretty));
|
||||
}
|
||||
if ui.selectable_label(tab.body_view == BodyView::Raw, "Raw").clicked() {
|
||||
acts.push(Action::SetBodyView(id, BodyView::Raw));
|
||||
}
|
||||
ui.separator();
|
||||
}
|
||||
if p.kind == BodyKind::Binary {
|
||||
ui.label(RichText::new("Binary body, shown as hex. Use “Save to file” to keep it.").weak());
|
||||
}
|
||||
if p.truncated {
|
||||
ui.label(RichText::new("Only the start of this large body is shown.").weak());
|
||||
}
|
||||
if tab.search.open {
|
||||
search_bar(ui, tab, acts);
|
||||
} else if ui
|
||||
.small_button("🔍 Find")
|
||||
.on_hover_text("Search the body (Ctrl+F)")
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::SearchOpen(id, true));
|
||||
}
|
||||
});
|
||||
|
||||
let lines = p.text(tab.body_view);
|
||||
let json = p.kind == BodyKind::Json && (tab.body_view == BodyView::Pretty || lines.line_count() < 5_000);
|
||||
text_view(ui, tab, lines, json, acts);
|
||||
}
|
||||
|
||||
fn search_bar(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
let mut q = tab.search.query.clone();
|
||||
let resp = ui.add(
|
||||
egui::TextEdit::singleline(&mut q)
|
||||
.hint_text("Find")
|
||||
.desired_width(180.0)
|
||||
.id_salt(("find", id)),
|
||||
);
|
||||
if !resp.has_focus() && tab.search.query.is_empty() && !resp.lost_focus() {
|
||||
resp.request_focus();
|
||||
}
|
||||
if resp.changed() {
|
||||
acts.push(Action::SearchQuery(id, q));
|
||||
}
|
||||
let n = tab.search.matches.len();
|
||||
if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
|
||||
let back = ui.input(|i| i.modifiers.shift);
|
||||
acts.push(Action::SearchStep(id, if back { -1 } else { 1 }));
|
||||
resp.request_focus();
|
||||
}
|
||||
if n > 0 {
|
||||
ui.label(format!("{}/{}", tab.search.current + 1, n));
|
||||
} else if !tab.search.query.is_empty() {
|
||||
ui.label(RichText::new("no matches").weak());
|
||||
}
|
||||
if ui.small_button("Prev").clicked() {
|
||||
acts.push(Action::SearchStep(id, -1));
|
||||
}
|
||||
if ui.small_button("Next").clicked() {
|
||||
acts.push(Action::SearchStep(id, 1));
|
||||
}
|
||||
if ui.small_button("×").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
acts.push(Action::SearchOpen(id, false));
|
||||
}
|
||||
}
|
||||
|
||||
/// Virtualized, line-based text viewer: only visible lines are laid out.
|
||||
fn text_view(ui: &mut Ui, tab: &Tab, lines: &TextLines, json: bool, acts: &mut Vec<Action>) {
|
||||
let id = tab.id;
|
||||
let pal = Palette::for_ui(ui);
|
||||
let font: FontId = egui::TextStyle::Monospace.resolve(ui.style());
|
||||
let row_h = ui.fonts_mut(|f| f.row_height(&font));
|
||||
let spacing = ui.spacing().item_spacing.y;
|
||||
let total = lines.line_count();
|
||||
let gutter = total.max(1).to_string().len();
|
||||
let default = ui.visuals().text_color();
|
||||
|
||||
let mut area = egui::ScrollArea::both()
|
||||
.id_salt(("body-view", id, tab.body_view as u8))
|
||||
.auto_shrink(false);
|
||||
if let Some(line) = tab.search.scroll_to {
|
||||
let y = (line as f32 * (row_h + spacing) - ui.available_height() / 3.0).max(0.0);
|
||||
area = area.vertical_scroll_offset(y);
|
||||
acts.push(Action::ScrolledTo(id));
|
||||
}
|
||||
let matches = &tab.search.matches;
|
||||
let current = matches.get(tab.search.current).cloned();
|
||||
area.show_rows(ui, row_h, total, |ui, range| {
|
||||
let first = matches.partition_point(|m| m.0 < range.start);
|
||||
let mut mi = first;
|
||||
for i in range {
|
||||
let full = lines.line(i);
|
||||
let mut cut = full.len().min(MAX_LINE);
|
||||
while !full.is_char_boundary(cut) {
|
||||
cut -= 1;
|
||||
}
|
||||
let line = &full[..cut];
|
||||
let prefix = format!("{:>gutter$} ", i + 1);
|
||||
let off = prefix.len();
|
||||
let mut text = prefix;
|
||||
text.push_str(line);
|
||||
if cut < full.len() {
|
||||
text.push_str(" …");
|
||||
}
|
||||
let mut colors = vec![vec![(0..off, pal.muted)]];
|
||||
if json {
|
||||
colors.push(
|
||||
json_spans(line, &pal)
|
||||
.into_iter()
|
||||
.map(|(r, c)| (r.start + off..r.end + off, c))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
let mut bgs = Vec::new();
|
||||
while mi < matches.len() && matches[mi].0 == i {
|
||||
let r = &matches[mi].1;
|
||||
let bg = if current.as_ref() == Some(&matches[mi]) {
|
||||
pal.current_bg
|
||||
} else {
|
||||
pal.match_bg
|
||||
};
|
||||
if r.end <= cut {
|
||||
bgs.push((r.start + off..r.end + off, bg));
|
||||
}
|
||||
mi += 1;
|
||||
}
|
||||
let job = build_job(&text, font.clone(), default, &colors, &bgs, f32::INFINITY);
|
||||
ui.add(egui::Label::new(job).selectable(true).extend());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn timings(ui: &mut Ui, tab: &Tab) {
|
||||
let Some(view) = &tab.response else { return };
|
||||
let t = view.response.timings;
|
||||
let total = t.total.as_secs_f32().max(0.000_1);
|
||||
let bar_w = (ui.available_width() - 260.0).max(100.0);
|
||||
let color = ui.visuals().selection.bg_fill;
|
||||
egui::Grid::new(("timings", tab.id)).num_columns(3).show(ui, |ui| {
|
||||
let mut start = 0.0f32;
|
||||
for (label, d) in t.phases() {
|
||||
let secs = d.as_secs_f32();
|
||||
ui.label(label);
|
||||
ui.label(RichText::new(format!("{:.1} ms", secs * 1000.0)).monospace());
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(bar_w, 12.0), egui::Sense::hover());
|
||||
let x0 = rect.left() + bar_w * (start / total);
|
||||
let x1 = (x0 + (bar_w * secs / total).max(1.0)).min(rect.right());
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_min_max(egui::pos2(x0, rect.top()), egui::pos2(x1, rect.bottom())),
|
||||
2.0,
|
||||
color,
|
||||
);
|
||||
start += secs;
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label(RichText::new("Total").strong());
|
||||
ui.label(RichText::new(format!("{:.1} ms", total * 1000.0)).monospace().strong());
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! The collection tree: folders → files → requests.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
use reqlite_core::collection::Node;
|
||||
|
||||
use super::widgets::method_color;
|
||||
use crate::action::Action;
|
||||
use crate::state::{AppState, CollectionState, DeleteTarget, Dialog, Prompt, PromptKind};
|
||||
|
||||
pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
|
||||
let Some(c) = &state.collection else {
|
||||
ui.add_space(8.0);
|
||||
ui.label("No collection open.");
|
||||
ui.label(RichText::new("A collection is a folder of .http files.").weak());
|
||||
ui.add_space(4.0);
|
||||
if ui.button("Open folder…").clicked() {
|
||||
acts.push(Action::PickCollection);
|
||||
}
|
||||
if !state.settings.recent_collections.is_empty() {
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new("Recent").strong());
|
||||
for p in &state.settings.recent_collections {
|
||||
let name = p
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
if ui.link(name).on_hover_text(p.display().to_string()).clicked() {
|
||||
acts.push(Action::OpenCollection(p.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(c.tree.name()).strong())
|
||||
.on_hover_text(c.root.display().to_string());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button("⟳").on_hover_text("Reload from disk").clicked() {
|
||||
acts.push(Action::Rescan);
|
||||
}
|
||||
if ui.small_button("+").on_hover_text("New .http file").clicked() {
|
||||
acts.push(new_file_prompt(&c.root));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if c.private_not_ignored && !c.gitignore_offer_dismissed {
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.label(
|
||||
RichText::new("http-client.private.env.json is not in .gitignore, so secrets could be committed.")
|
||||
.color(ui.visuals().warn_fg_color),
|
||||
);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Add to .gitignore").clicked() {
|
||||
acts.push(Action::AddPrivateFileToGitignore);
|
||||
}
|
||||
if ui.button("Dismiss").clicked() {
|
||||
acts.push(Action::DismissGitignoreOffer);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some(e) = &c.env_error {
|
||||
ui.colored_label(ui.visuals().error_fg_color, format!("Environments: {e}"));
|
||||
}
|
||||
ui.separator();
|
||||
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("tree")
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| {
|
||||
if let Node::Folder { children, .. } = &c.tree {
|
||||
if children.is_empty() {
|
||||
ui.label(RichText::new("No .http files yet.").weak());
|
||||
if ui.button("Create one").clicked() {
|
||||
acts.push(new_file_prompt(&c.root));
|
||||
}
|
||||
}
|
||||
for child in children {
|
||||
node(ui, state, c, child, acts);
|
||||
}
|
||||
}
|
||||
// Right-clicking the empty space below the tree.
|
||||
let size = egui::vec2(ui.available_width(), ui.available_height().max(40.0));
|
||||
ui.allocate_response(size, egui::Sense::click()).context_menu(|ui| {
|
||||
if ui.button("New .http file…").clicked() {
|
||||
acts.push(new_file_prompt(&c.root));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn new_file_prompt(dir: &Path) -> Action {
|
||||
Action::ShowDialog(Some(Dialog::Prompt(Prompt {
|
||||
kind: PromptKind::NewFile { dir: dir.to_path_buf() },
|
||||
title: "New .http file".into(),
|
||||
value: "requests.http".into(),
|
||||
})))
|
||||
}
|
||||
|
||||
fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut Vec<Action>) {
|
||||
match n {
|
||||
Node::Folder { name, path, children } => {
|
||||
let resp = egui::CollapsingHeader::new(format!("📁 {name}"))
|
||||
.id_salt(path)
|
||||
.default_open(true)
|
||||
.show(ui, |ui| {
|
||||
for ch in children {
|
||||
node(ui, state, c, ch, acts);
|
||||
}
|
||||
});
|
||||
resp.header_response.context_menu(|ui| {
|
||||
if ui.button("New .http file…").clicked() {
|
||||
acts.push(new_file_prompt(path));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
Node::File { name, path } => {
|
||||
let Some(file) = c.files.get(path) else { return };
|
||||
let resp = egui::CollapsingHeader::new(format!("📄 {name}"))
|
||||
.id_salt(path)
|
||||
.default_open(true)
|
||||
.show(ui, |ui| {
|
||||
let active = state.active_tab().and_then(|t| t.origin.as_ref());
|
||||
for (i, r) in file.requests().enumerate() {
|
||||
let dark = ui.visuals().dark_mode;
|
||||
let selected = active.is_some_and(|o| &o.file == path && o.key.index == i);
|
||||
let label = r
|
||||
.display_name()
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| short_url(&r.url));
|
||||
let mut job = egui::text::LayoutJob::default();
|
||||
job.append(
|
||||
&format!("{:<6} ", short_method(r.method.as_str())),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::monospace(11.0),
|
||||
color: method_color(r.method.as_str(), dark),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
job.append(
|
||||
&label,
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::TextStyle::Body.resolve(ui.style()),
|
||||
color: ui.visuals().text_color(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let item = ui
|
||||
.selectable_label(selected, job)
|
||||
.on_hover_text(format!("{} {}", r.method, r.url));
|
||||
if item.clicked() {
|
||||
acts.push(Action::OpenRequest {
|
||||
file: path.clone(),
|
||||
index: i,
|
||||
});
|
||||
}
|
||||
item.context_menu(|ui| {
|
||||
if ui.button("Open").clicked() {
|
||||
acts.push(Action::OpenRequest {
|
||||
file: path.clone(),
|
||||
index: i,
|
||||
});
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Rename…").clicked() {
|
||||
acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt {
|
||||
kind: PromptKind::RenameRequest {
|
||||
file: path.clone(),
|
||||
index: i,
|
||||
},
|
||||
title: "Rename request".into(),
|
||||
value: r.display_name().unwrap_or("").to_string(),
|
||||
}))));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Duplicate").clicked() {
|
||||
acts.push(Action::DuplicateRequest {
|
||||
file: path.clone(),
|
||||
index: i,
|
||||
});
|
||||
ui.close();
|
||||
}
|
||||
ui.menu_button("Move to", |ui| {
|
||||
for other in c.files.keys().filter(|p| *p != path) {
|
||||
if ui.button(c.relative(other).display().to_string()).clicked() {
|
||||
acts.push(Action::MoveRequest {
|
||||
from: path.clone(),
|
||||
index: i,
|
||||
to: other.clone(),
|
||||
});
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
if ui.button("Delete…").clicked() {
|
||||
acts.push(Action::ShowDialog(Some(Dialog::ConfirmDelete(DeleteTarget::Request {
|
||||
file: path.clone(),
|
||||
index: i,
|
||||
label: label.clone(),
|
||||
}))));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
if file.request_count() == 0 {
|
||||
ui.label(RichText::new("(no requests)").weak());
|
||||
}
|
||||
});
|
||||
resp.header_response.context_menu(|ui| {
|
||||
if ui.button("New request").clicked() {
|
||||
acts.push(Action::NewRequestIn { file: path.clone() });
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Rename file…").clicked() {
|
||||
acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt {
|
||||
kind: PromptKind::RenameFile { path: path.clone() },
|
||||
title: "Rename file".into(),
|
||||
value: name.clone(),
|
||||
}))));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Duplicate file").clicked() {
|
||||
acts.push(Action::DuplicateFile(path.clone()));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Delete file…").clicked() {
|
||||
acts.push(Action::ShowDialog(Some(Dialog::ConfirmDelete(DeleteTarget::File(
|
||||
path.clone(),
|
||||
)))));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn short_method(m: &str) -> &str {
|
||||
match m {
|
||||
"DELETE" => "DEL",
|
||||
"OPTIONS" => "OPT",
|
||||
"PATCH" => "PATCH",
|
||||
m if m.len() > 6 => &m[..6],
|
||||
m => m,
|
||||
}
|
||||
}
|
||||
|
||||
fn short_url(url: &str) -> String {
|
||||
let u = url.split("://").nth(1).unwrap_or(url);
|
||||
let s: String = u.chars().take(40).collect();
|
||||
if s.is_empty() {
|
||||
"(no URL)".into()
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
//! Shared widgets: syntax-coloured text and `{{var}}`-aware text fields.
|
||||
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::text::{LayoutJob, TextFormat};
|
||||
use egui::{Color32, FontId, TextBuffer, Ui};
|
||||
use reqlite_core::template::{find_vars, Resolver, VarSource};
|
||||
|
||||
pub struct Palette {
|
||||
pub text: Color32,
|
||||
pub key: Color32,
|
||||
pub string: Color32,
|
||||
pub number: Color32,
|
||||
pub keyword: Color32,
|
||||
pub punct: Color32,
|
||||
pub var_ok: Color32,
|
||||
pub var_bad: Color32,
|
||||
pub match_bg: Color32,
|
||||
pub current_bg: Color32,
|
||||
pub muted: Color32,
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
pub fn for_ui(ui: &Ui) -> Self {
|
||||
let text = ui.visuals().text_color();
|
||||
if ui.visuals().dark_mode {
|
||||
Self {
|
||||
text,
|
||||
key: Color32::from_rgb(0x9c, 0xdc, 0xfe),
|
||||
string: Color32::from_rgb(0xce, 0x91, 0x78),
|
||||
number: Color32::from_rgb(0xb5, 0xce, 0xa8),
|
||||
keyword: Color32::from_rgb(0x56, 0x9c, 0xd6),
|
||||
punct: Color32::from_gray(0xa0),
|
||||
var_ok: Color32::from_rgb(0x4e, 0xc9, 0xb0),
|
||||
var_bad: Color32::from_rgb(0xf4, 0x47, 0x47),
|
||||
match_bg: Color32::from_rgba_unmultiplied(0xff, 0xd7, 0x00, 0x50),
|
||||
current_bg: Color32::from_rgba_unmultiplied(0xff, 0x8c, 0x00, 0xa0),
|
||||
muted: Color32::from_gray(0x80),
|
||||
}
|
||||
} else {
|
||||
Self {
|
||||
text,
|
||||
key: Color32::from_rgb(0x00, 0x45, 0x8a),
|
||||
string: Color32::from_rgb(0xa3, 0x15, 0x15),
|
||||
number: Color32::from_rgb(0x09, 0x86, 0x58),
|
||||
keyword: Color32::from_rgb(0x00, 0x00, 0xff),
|
||||
punct: Color32::from_gray(0x60),
|
||||
var_ok: Color32::from_rgb(0x00, 0x80, 0x70),
|
||||
var_bad: Color32::from_rgb(0xd0, 0x00, 0x00),
|
||||
match_bg: Color32::from_rgba_unmultiplied(0xff, 0xd7, 0x00, 0x80),
|
||||
current_bg: Color32::from_rgba_unmultiplied(0xff, 0x8c, 0x00, 0xc0),
|
||||
muted: Color32::from_gray(0x70),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Colour spans for JSON (works line by line, so huge bodies stay cheap).
|
||||
pub fn json_spans(text: &str, p: &Palette) -> Vec<(Range<usize>, Color32)> {
|
||||
let b = text.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
let c = b[i];
|
||||
let start = i;
|
||||
match c {
|
||||
b'"' => {
|
||||
i += 1;
|
||||
while i < b.len() && b[i] != b'"' && b[i] != b'\n' {
|
||||
if b[i] == b'\\' {
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
i = (i + 1).min(b.len());
|
||||
let mut j = i;
|
||||
while j < b.len() && (b[j] == b' ' || b[j] == b'\t') {
|
||||
j += 1;
|
||||
}
|
||||
let color = if j < b.len() && b[j] == b':' { p.key } else { p.string };
|
||||
out.push((start..i, color));
|
||||
}
|
||||
b'-' | b'0'..=b'9' => {
|
||||
i += 1;
|
||||
while i < b.len() && (b[i].is_ascii_digit() || b".eE+-".contains(&b[i])) {
|
||||
i += 1;
|
||||
}
|
||||
out.push((start..i, p.number));
|
||||
}
|
||||
b't' | b'f' | b'n' => {
|
||||
let rest = &text[i..];
|
||||
let kw = ["true", "false", "null"].into_iter().find(|k| rest.starts_with(k));
|
||||
match kw {
|
||||
Some(k) => {
|
||||
i += k.len();
|
||||
out.push((start..i, p.keyword));
|
||||
}
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
b'{' | b'}' | b'[' | b']' | b',' | b':' => {
|
||||
i += 1;
|
||||
out.push((start..i, p.punct));
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Colour spans for `{{var}}` placeholders.
|
||||
pub fn var_spans(text: &str, resolver: Option<&Resolver>, p: &Palette) -> Vec<(Range<usize>, Color32)> {
|
||||
find_vars(text)
|
||||
.into_iter()
|
||||
.map(|(r, name)| {
|
||||
let ok = resolver.is_none_or(|res| res.is_defined(&name));
|
||||
(r, if ok { p.var_ok } else { p.var_bad })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Builds a layout job from base colour spans plus background highlights.
|
||||
/// Later colour spans win over earlier ones.
|
||||
pub fn build_job(
|
||||
text: &str,
|
||||
font: FontId,
|
||||
default: Color32,
|
||||
colors: &[Vec<(Range<usize>, Color32)>],
|
||||
backgrounds: &[(Range<usize>, Color32)],
|
||||
wrap_width: f32,
|
||||
) -> LayoutJob {
|
||||
let mut cuts: Vec<usize> = vec![0, text.len()];
|
||||
for layer in colors {
|
||||
for (r, _) in layer {
|
||||
cuts.push(r.start.min(text.len()));
|
||||
cuts.push(r.end.min(text.len()));
|
||||
}
|
||||
}
|
||||
for (r, _) in backgrounds {
|
||||
cuts.push(r.start.min(text.len()));
|
||||
cuts.push(r.end.min(text.len()));
|
||||
}
|
||||
cuts.retain(|&c| text.is_char_boundary(c));
|
||||
cuts.sort_unstable();
|
||||
cuts.dedup();
|
||||
|
||||
let mut job = LayoutJob::default();
|
||||
job.wrap.max_width = wrap_width;
|
||||
for w in cuts.windows(2) {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
if a == b {
|
||||
continue;
|
||||
}
|
||||
let mut color = default;
|
||||
for layer in colors {
|
||||
if let Some((_, c)) = layer.iter().find(|(r, _)| r.start <= a && b <= r.end) {
|
||||
color = *c;
|
||||
}
|
||||
}
|
||||
let background = backgrounds
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(r, _)| r.start <= a && b <= r.end)
|
||||
.map(|(_, c)| *c)
|
||||
.unwrap_or(Color32::TRANSPARENT);
|
||||
job.append(
|
||||
&text[a..b],
|
||||
0.0,
|
||||
TextFormat {
|
||||
font_id: font.clone(),
|
||||
color,
|
||||
background,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
if text.is_empty() {
|
||||
job.append(
|
||||
"",
|
||||
0.0,
|
||||
TextFormat {
|
||||
font_id: font,
|
||||
color: default,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
job
|
||||
}
|
||||
|
||||
/// What the variable fields need to colour and explain `{{vars}}`.
|
||||
pub struct VarCtx<'a> {
|
||||
pub resolver: &'a Resolver,
|
||||
pub is_private: &'a dyn Fn(&str) -> bool,
|
||||
}
|
||||
|
||||
impl VarCtx<'_> {
|
||||
/// Text for the hover tooltip of a variable.
|
||||
pub fn describe(&self, name: &str) -> String {
|
||||
match self.resolver.lookup(name) {
|
||||
None => format!("{{{{{name}}}}} is not defined in the selected environment"),
|
||||
Some((_, VarSource::Builtin)) => format!("{{{{{name}}}}}: built-in dynamic value"),
|
||||
Some((v, src)) => {
|
||||
let from = match src {
|
||||
VarSource::PrivateEnv => "private env",
|
||||
VarSource::PublicEnv => "env",
|
||||
VarSource::File => "file variable",
|
||||
VarSource::Builtin => "built-in",
|
||||
};
|
||||
let shown = if (self.is_private)(name) {
|
||||
"••••".to_string()
|
||||
} else {
|
||||
match self.resolver.resolve(&v) {
|
||||
Ok(r) if r != v => format!("{v} -> {r}"),
|
||||
_ => v,
|
||||
}
|
||||
};
|
||||
format!("{name} = {shown} ({from})")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A text field that colours `{{vars}}` (green when defined, red when not)
|
||||
/// and shows a variable's value when hovering it.
|
||||
pub fn var_text_edit(
|
||||
ui: &mut Ui,
|
||||
text: &mut String,
|
||||
vars: Option<&VarCtx>,
|
||||
hint: &str,
|
||||
width: f32,
|
||||
id_salt: impl egui::AsIdSalt,
|
||||
) -> egui::Response {
|
||||
let pal = Palette::for_ui(ui);
|
||||
let font = egui::TextStyle::Monospace.resolve(ui.style());
|
||||
let default = ui.visuals().text_color();
|
||||
let resolver = vars.map(|v| v.resolver);
|
||||
// Single-line text never wraps; it scrolls inside the field.
|
||||
let mut layouter = |ui: &Ui, buf: &dyn TextBuffer, _wrap: f32| -> Arc<egui::Galley> {
|
||||
let s = buf.as_str();
|
||||
let job = build_job(
|
||||
s,
|
||||
font.clone(),
|
||||
default,
|
||||
&[var_spans(s, resolver, &pal)],
|
||||
&[],
|
||||
f32::INFINITY,
|
||||
);
|
||||
ui.ctx().fonts_mut(|f| f.layout_job(job))
|
||||
};
|
||||
// TextEdit never grows past the available width, and inside a Grid that
|
||||
// is last frame's column width, so give it an explicitly sized area.
|
||||
let height = ui.spacing().interact_size.y;
|
||||
let out = ui
|
||||
.allocate_ui(egui::vec2(width, height), |ui| {
|
||||
ui.set_min_width(width);
|
||||
egui::TextEdit::singleline(text)
|
||||
.id_salt(id_salt)
|
||||
.hint_text(hint)
|
||||
.desired_width(width)
|
||||
.font(egui::TextStyle::Monospace)
|
||||
.layouter(&mut layouter)
|
||||
.show(ui)
|
||||
})
|
||||
.inner;
|
||||
let response = out.response.response.clone();
|
||||
if let (Some(vars), Some(pos)) = (vars, response.hover_pos()) {
|
||||
let cursor = out.galley.cursor_from_pos(pos - out.galley_pos);
|
||||
let char_idx = cursor.index.0;
|
||||
let byte_idx = text.char_indices().nth(char_idx).map(|(b, _)| b).unwrap_or(text.len());
|
||||
if let Some((_, name)) = find_vars(text)
|
||||
.into_iter()
|
||||
.find(|(r, _)| r.start <= byte_idx && byte_idx < r.end)
|
||||
{
|
||||
let tip = vars.describe(&name);
|
||||
return response.on_hover_text(tip);
|
||||
}
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// A multi-line code editor with JSON and `{{var}}` colouring.
|
||||
pub fn code_edit(
|
||||
ui: &mut Ui,
|
||||
text: &mut String,
|
||||
json: bool,
|
||||
resolver: Option<&Resolver>,
|
||||
rows: usize,
|
||||
id_salt: impl egui::AsIdSalt,
|
||||
) -> egui::Response {
|
||||
let pal = Palette::for_ui(ui);
|
||||
let font = egui::TextStyle::Monospace.resolve(ui.style());
|
||||
let default = ui.visuals().text_color();
|
||||
let mut layouter = |ui: &Ui, buf: &dyn TextBuffer, wrap: f32| -> Arc<egui::Galley> {
|
||||
let s = buf.as_str();
|
||||
let mut layers = Vec::new();
|
||||
if json {
|
||||
layers.push(json_spans(s, &pal));
|
||||
}
|
||||
layers.push(var_spans(s, resolver, &pal));
|
||||
let job = build_job(s, font.clone(), default, &layers, &[], wrap);
|
||||
ui.ctx().fonts_mut(|f| f.layout_job(job))
|
||||
};
|
||||
egui::TextEdit::multiline(text)
|
||||
.id_salt(id_salt)
|
||||
.code_editor()
|
||||
.desired_rows(rows)
|
||||
.desired_width(f32::INFINITY)
|
||||
.layouter(&mut layouter)
|
||||
.show(ui)
|
||||
.response
|
||||
.response
|
||||
}
|
||||
|
||||
pub fn method_color(method: &str, dark: bool) -> Color32 {
|
||||
let (r, g, b): (u8, u8, u8) = match method {
|
||||
"GET" => (0x2e, 0xa0, 0x43),
|
||||
"POST" => (0xd9, 0x8e, 0x04),
|
||||
"PUT" => (0x1f, 0x6f, 0xeb),
|
||||
"PATCH" => (0x8b, 0x5c, 0xf6),
|
||||
"DELETE" => (0xdc, 0x26, 0x26),
|
||||
_ => (0x6b, 0x72, 0x80),
|
||||
};
|
||||
if dark {
|
||||
Color32::from_rgb(r.saturating_add(0x20), g.saturating_add(0x20), b.saturating_add(0x20))
|
||||
} else {
|
||||
Color32::from_rgb(r, g, b)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status_color(status: u16, dark: bool) -> Color32 {
|
||||
match (status / 100, dark) {
|
||||
(2, true) => Color32::from_rgb(0x4a, 0xde, 0x80),
|
||||
(2, false) => Color32::from_rgb(0x15, 0x80, 0x3d),
|
||||
(3, true) => Color32::from_rgb(0x60, 0xa5, 0xfa),
|
||||
(3, false) => Color32::from_rgb(0x1d, 0x4e, 0xd8),
|
||||
(4, true) => Color32::from_rgb(0xfb, 0xbf, 0x24),
|
||||
(4, false) => Color32::from_rgb(0xb4, 0x53, 0x09),
|
||||
(_, true) => Color32::from_rgb(0xf8, 0x71, 0x71),
|
||||
(_, false) => Color32::from_rgb(0xb9, 0x1c, 0x1c),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn human_size(n: u64) -> String {
|
||||
match n {
|
||||
n if n < 1024 => format!("{n} B"),
|
||||
n if n < 1024 * 1024 => format!("{:.1} KB", n as f64 / 1024.0),
|
||||
n => format!("{:.1} MB", n as f64 / (1024.0 * 1024.0)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn json_spans_classify_tokens() {
|
||||
let p = Palette {
|
||||
text: Color32::WHITE,
|
||||
key: Color32::from_rgb(1, 0, 0),
|
||||
string: Color32::from_rgb(2, 0, 0),
|
||||
number: Color32::from_rgb(3, 0, 0),
|
||||
keyword: Color32::from_rgb(4, 0, 0),
|
||||
punct: Color32::from_rgb(5, 0, 0),
|
||||
var_ok: Color32::WHITE,
|
||||
var_bad: Color32::WHITE,
|
||||
match_bg: Color32::WHITE,
|
||||
current_bg: Color32::WHITE,
|
||||
muted: Color32::WHITE,
|
||||
};
|
||||
let s = r#"{"a": "b\"c", "n": -1.5e3, "t": true, "z": null}"#;
|
||||
let kinds: Vec<(&str, u8)> = json_spans(s, &p).into_iter().map(|(r, c)| (&s[r], c.r())).collect();
|
||||
assert!(kinds.contains(&("\"a\"", 1)));
|
||||
assert!(kinds.contains(&("\"b\\\"c\"", 2)));
|
||||
assert!(kinds.contains(&("-1.5e3", 3)));
|
||||
assert!(kinds.contains(&("true", 4)));
|
||||
assert!(kinds.contains(&("null", 4)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_job_covers_the_whole_text() {
|
||||
let text = "héllo {{x}} wörld";
|
||||
let job = build_job(
|
||||
text,
|
||||
FontId::monospace(12.0),
|
||||
Color32::WHITE,
|
||||
&[vec![(6..11, Color32::RED)]],
|
||||
&[(0..2, Color32::YELLOW)],
|
||||
100.0,
|
||||
);
|
||||
assert_eq!(job.text, text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,753 @@
|
||||
//! Modal dialogs and floating windows.
|
||||
|
||||
use egui::{Context, Id, Key, RichText};
|
||||
use reqlite_core::env::{EnvFile, EnvVar, SHARED_ENV};
|
||||
|
||||
use super::widgets::{method_color, status_color};
|
||||
use crate::action::Action;
|
||||
use crate::settings::{ProxyMode, Settings, ThemeChoice};
|
||||
use crate::state::{AppState, DeleteTarget, Dialog, EnvEditor, Prompt, PromptKind, QuickOpen};
|
||||
|
||||
pub fn show(ctx: &Context, state: &AppState, acts: &mut Vec<Action>) {
|
||||
if let Some(d) = &state.dialog {
|
||||
dialog(ctx, state, d, acts);
|
||||
}
|
||||
let mut w = state.windows;
|
||||
let before = w;
|
||||
if w.settings {
|
||||
settings(ctx, &state.settings, &mut w.settings, acts);
|
||||
}
|
||||
if w.history {
|
||||
history(ctx, state, &mut w.history, acts);
|
||||
}
|
||||
if w.cookies {
|
||||
cookies(ctx, state, &mut w.cookies, acts);
|
||||
}
|
||||
if w.about {
|
||||
about(ctx, &mut w.about);
|
||||
}
|
||||
if w != before {
|
||||
acts.push(Action::SetWindows(w));
|
||||
}
|
||||
if let Some(ed) = &state.env_editor {
|
||||
env_editor(ctx, ed, acts);
|
||||
}
|
||||
if let Some(q) = &state.quick_open {
|
||||
quick_open(ctx, state, q, acts);
|
||||
}
|
||||
}
|
||||
|
||||
fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec<Action>) {
|
||||
let close = || Action::ShowDialog(None);
|
||||
let modal = egui::Modal::new(Id::unique("reqlite-dialog")).show(ctx, |ui| {
|
||||
ui.set_max_width(460.0);
|
||||
match d {
|
||||
Dialog::ConfirmCloseTab(id) => {
|
||||
let title = state.tab(*id).map(|t| t.title()).unwrap_or_default();
|
||||
let has_file = state.tab(*id).is_some_and(|t| t.origin.is_some());
|
||||
ui.heading("Unsaved changes");
|
||||
ui.label(format!("“{title}” has changes that are not saved."));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if has_file && ui.button("Save and close").clicked() {
|
||||
acts.push(close());
|
||||
acts.push(Action::Save(*id));
|
||||
acts.push(Action::CloseTab(*id));
|
||||
}
|
||||
if ui.button("Discard").clicked() {
|
||||
acts.push(Action::DiscardAndCloseTab(*id));
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
acts.push(close());
|
||||
}
|
||||
});
|
||||
}
|
||||
Dialog::ConfirmQuit => {
|
||||
let n = state.tabs.iter().filter(|t| t.is_dirty()).count();
|
||||
ui.heading("Quit reqlite?");
|
||||
ui.label(format!("{n} tab(s) have unsaved changes; they will be lost."));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Quit without saving").clicked() {
|
||||
acts.push(Action::ConfirmQuit);
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
acts.push(close());
|
||||
}
|
||||
});
|
||||
}
|
||||
Dialog::Conflict { tab, path } => {
|
||||
ui.heading("File changed on disk");
|
||||
ui.label(format!(
|
||||
"{} was changed outside reqlite, and this tab has unsaved edits.",
|
||||
path.display()
|
||||
));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui
|
||||
.button("Reload from disk")
|
||||
.on_hover_text("Discard my edits")
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::ResolveConflict {
|
||||
tab: *tab,
|
||||
keep_mine: false,
|
||||
});
|
||||
}
|
||||
if ui
|
||||
.button("Keep my version")
|
||||
.on_hover_text("Saving will overwrite this request in the new file")
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::ResolveConflict {
|
||||
tab: *tab,
|
||||
keep_mine: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
Dialog::Prompt(p) => prompt(ui, state, p, acts),
|
||||
Dialog::ConfirmDelete(target) => {
|
||||
let what = match target {
|
||||
DeleteTarget::Request { label, .. } => format!("the request “{label}”"),
|
||||
DeleteTarget::File(p) => format!("the file {}", p.display()),
|
||||
};
|
||||
ui.heading("Delete?");
|
||||
ui.label(format!("This deletes {what} from disk."));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui
|
||||
.button(RichText::new("Delete").color(ui.visuals().error_fg_color))
|
||||
.clicked()
|
||||
{
|
||||
acts.push(match target {
|
||||
DeleteTarget::Request { file, index, .. } => Action::DeleteRequest {
|
||||
file: file.clone(),
|
||||
index: *index,
|
||||
},
|
||||
DeleteTarget::File(p) => Action::DeleteFile(p.clone()),
|
||||
});
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
acts.push(close());
|
||||
}
|
||||
});
|
||||
}
|
||||
Dialog::ImportSummary { root, files, warnings } => {
|
||||
ui.heading("Import finished");
|
||||
ui.label(format!("Wrote {files} .http file(s) to {}.", root.display()));
|
||||
if !warnings.is_empty() {
|
||||
ui.add_space(6.0);
|
||||
ui.label(RichText::new(format!("{} warning(s):", warnings.len())).strong());
|
||||
egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| {
|
||||
for w in warnings {
|
||||
ui.label(format!("• {w}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
if ui.button("OK").clicked() {
|
||||
acts.push(close());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if modal.should_close() && !matches!(d, Dialog::Conflict { .. }) {
|
||||
acts.push(close());
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt(ui: &mut egui::Ui, state: &AppState, p: &Prompt, acts: &mut Vec<Action>) {
|
||||
ui.heading(&p.title);
|
||||
let mut value = p.value.clone();
|
||||
let resp = ui.add(
|
||||
egui::TextEdit::singleline(&mut value)
|
||||
.desired_width(380.0)
|
||||
.id_salt("prompt"),
|
||||
);
|
||||
if !resp.has_focus() && !resp.lost_focus() {
|
||||
resp.request_focus();
|
||||
}
|
||||
if resp.changed() {
|
||||
acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt {
|
||||
value: value.clone(),
|
||||
..p.clone()
|
||||
}))));
|
||||
}
|
||||
let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("OK").clicked() || enter {
|
||||
let action = match &p.kind {
|
||||
PromptKind::NewFile { dir } => Action::NewFile {
|
||||
dir: dir.clone(),
|
||||
name: value.clone(),
|
||||
},
|
||||
PromptKind::RenameFile { path } => Action::RenameFile {
|
||||
path: path.clone(),
|
||||
new_name: value.clone(),
|
||||
},
|
||||
PromptKind::RenameRequest { file, index } => Action::RenameRequest {
|
||||
file: file.clone(),
|
||||
index: *index,
|
||||
title: value.clone(),
|
||||
},
|
||||
PromptKind::NewEnvironment => {
|
||||
if let Some(ed) = &state.env_editor {
|
||||
let mut ed = ed.clone();
|
||||
let name = value.trim().to_string();
|
||||
if !name.is_empty() {
|
||||
ed.envs.public.env_mut(&name);
|
||||
ed.selected = name;
|
||||
ed.dirty = true;
|
||||
}
|
||||
acts.push(Action::EnvEditorChanged(ed));
|
||||
}
|
||||
Action::ShowDialog(None)
|
||||
}
|
||||
};
|
||||
acts.push(action);
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
acts.push(Action::ShowDialog(None));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn settings(ctx: &Context, s: &Settings, open: &mut bool, acts: &mut Vec<Action>) {
|
||||
let mut n = s.clone();
|
||||
egui::Window::new("Settings")
|
||||
.open(open)
|
||||
.resizable(false)
|
||||
.show(ctx, |ui| {
|
||||
egui::Grid::new("settings")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 8.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label("Default timeout");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut n.default_timeout_secs)
|
||||
.range(0..=3600)
|
||||
.suffix(" s"),
|
||||
);
|
||||
ui.label(RichText::new("0 = none; `# @timeout` wins").weak());
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
ui.label("Proxy");
|
||||
ui.vertical(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut n.proxy_mode, ProxyMode::System, "System");
|
||||
ui.radio_value(&mut n.proxy_mode, ProxyMode::None, "None");
|
||||
ui.radio_value(&mut n.proxy_mode, ProxyMode::Manual, "Manual");
|
||||
});
|
||||
if n.proxy_mode == ProxyMode::Manual {
|
||||
ui.add_sized(
|
||||
[260.0, ui.spacing().interact_size.y],
|
||||
egui::TextEdit::singleline(&mut n.proxy_url).hint_text("http://user:pass@proxy:3128"),
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
ui.label("TLS");
|
||||
ui.vertical(|ui| {
|
||||
ui.checkbox(&mut n.verify_tls, "Verify certificates");
|
||||
ui.horizontal(|ui| {
|
||||
let ca = n
|
||||
.ca_file
|
||||
.as_ref()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_else(|| "System store only".into());
|
||||
ui.label(RichText::new(ca).weak());
|
||||
if ui.button("Add CA file…").clicked() {
|
||||
acts.push(Action::PickCaFile);
|
||||
}
|
||||
if n.ca_file.is_some() && ui.button("Clear").clicked() {
|
||||
n.ca_file = None;
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
ui.label("Theme");
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut n.theme, ThemeChoice::System, "System");
|
||||
ui.radio_value(&mut n.theme, ThemeChoice::Light, "Light");
|
||||
ui.radio_value(&mut n.theme, ThemeChoice::Dark, "Dark");
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
ui.label("Font size");
|
||||
ui.add(
|
||||
egui::Slider::new(&mut n.zoom, 0.75..=2.0)
|
||||
.step_by(0.05)
|
||||
.custom_formatter(|v, _| format!("{:.0}%", v * 100.0)),
|
||||
);
|
||||
ui.end_row();
|
||||
|
||||
ui.label("Parallel requests");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut n.max_concurrent_requests).range(1..=64));
|
||||
ui.label(RichText::new("at once").weak());
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
ui.label("History size");
|
||||
ui.add(egui::DragValue::new(&mut n.history_limit).range(10..=10_000));
|
||||
ui.end_row();
|
||||
});
|
||||
});
|
||||
if n != *s {
|
||||
acts.push(Action::SettingsChanged(n));
|
||||
}
|
||||
}
|
||||
|
||||
fn history(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Action>) {
|
||||
egui::Window::new("History")
|
||||
.open(open)
|
||||
.default_size([620.0, 420.0])
|
||||
.show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{} request(s)", state.history.len()));
|
||||
if ui.button("Clear").clicked() {
|
||||
acts.push(Action::ClearHistory);
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
let dark = ui.visuals().dark_mode;
|
||||
egui::ScrollArea::vertical().auto_shrink(false).show(ui, |ui| {
|
||||
egui::Grid::new("history").num_columns(5).striped(true).show(ui, |ui| {
|
||||
for (i, e) in state.history.iter().enumerate().rev() {
|
||||
ui.label(RichText::new(format_time(e.at)).weak().monospace());
|
||||
match (e.status, &e.error) {
|
||||
(Some(s), _) => ui.label(RichText::new(s.to_string()).color(status_color(s, dark))),
|
||||
(None, Some(err)) => ui
|
||||
.label(RichText::new("ERR").color(ui.visuals().error_fg_color))
|
||||
.on_hover_text(err),
|
||||
_ => ui.label("—"),
|
||||
};
|
||||
ui.label(
|
||||
RichText::new(&e.method)
|
||||
.color(method_color(&e.method, dark))
|
||||
.monospace(),
|
||||
);
|
||||
let url: String = e.url.chars().take(70).collect();
|
||||
ui.label(url).on_hover_text(format!(
|
||||
"{}\n{} ms{}",
|
||||
e.url,
|
||||
e.duration_ms,
|
||||
e.env.as_ref().map(|v| format!(", env {v}")).unwrap_or_default()
|
||||
));
|
||||
if ui
|
||||
.small_button("Open")
|
||||
.on_hover_text("Restore into a new tab")
|
||||
.clicked()
|
||||
{
|
||||
acts.push(Action::RestoreHistory(i));
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// `YYYY-MM-DD HH:MM` (UTC) from unix seconds.
|
||||
fn format_time(secs: u64) -> String {
|
||||
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
|
||||
let iso = reqlite_core::template::iso8601(t);
|
||||
format!("{} {}", &iso[..10], &iso[11..16])
|
||||
}
|
||||
|
||||
fn cookies(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Action>) {
|
||||
let key = state.collection.as_ref().map(|c| c.root.clone());
|
||||
let jar = state.cookie_jars.get(&key);
|
||||
egui::Window::new("Cookies")
|
||||
.open(open)
|
||||
.default_size([560.0, 300.0])
|
||||
.show(ctx, |ui| {
|
||||
ui.label(RichText::new("Cookies are kept in memory per collection; `# @no-cookie-jar` skips them.").weak());
|
||||
let cookies = jar.map(|j| j.cookies()).unwrap_or(&[]);
|
||||
if cookies.is_empty() {
|
||||
ui.label("No cookies yet.");
|
||||
return;
|
||||
}
|
||||
if ui.button("Clear all").clicked() {
|
||||
acts.push(Action::ClearCookies);
|
||||
}
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
egui::Grid::new("cookies").num_columns(5).striped(true).show(ui, |ui| {
|
||||
for h in ["Domain", "Path", "Name", "Value", ""] {
|
||||
ui.label(RichText::new(h).weak());
|
||||
}
|
||||
ui.end_row();
|
||||
for (i, c) in cookies.iter().enumerate() {
|
||||
ui.label(&c.domain);
|
||||
ui.label(&c.path);
|
||||
ui.label(RichText::new(&c.name).strong());
|
||||
let v: String = c.value.chars().take(40).collect();
|
||||
ui.label(v).on_hover_text(&c.value);
|
||||
if ui.small_button("×").clicked() {
|
||||
acts.push(Action::DeleteCookie(i));
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn about(ctx: &Context, open: &mut bool) {
|
||||
egui::Window::new("About reqlite")
|
||||
.open(open)
|
||||
.resizable(false)
|
||||
.show(ctx, |ui| {
|
||||
ui.heading(format!("reqlite {}", env!("CARGO_PKG_VERSION")));
|
||||
ui.label("A small API client for .http files.");
|
||||
ui.label(reqlite_http_curl::CurlClient::version());
|
||||
ui.add_space(6.0);
|
||||
ui.label(RichText::new("Shortcuts").strong());
|
||||
egui::Grid::new("keys").show(ui, |ui| {
|
||||
for (k, v) in [
|
||||
("Ctrl+Enter", "Send"),
|
||||
("Ctrl+S", "Save"),
|
||||
("Ctrl+T", "New tab"),
|
||||
("Ctrl+W", "Close tab"),
|
||||
("Ctrl+L", "Focus the URL bar"),
|
||||
("Ctrl+P", "Quick-open a request"),
|
||||
("Ctrl+F", "Find in the response"),
|
||||
] {
|
||||
ui.label(RichText::new(k).monospace());
|
||||
ui.label(v);
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
|
||||
let mut e = ed.clone();
|
||||
let mut open = true;
|
||||
let mut save = false;
|
||||
egui::Window::new(if ed.dirty { "Environments •" } else { "Environments" })
|
||||
.open(&mut open)
|
||||
.default_size([640.0, 380.0])
|
||||
.show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Environment:");
|
||||
let mut names = e.envs.names();
|
||||
names.insert(0, SHARED_ENV.to_string());
|
||||
egui::ComboBox::from_id_salt("env-edit-sel")
|
||||
.selected_text(&e.selected)
|
||||
.show_ui(ui, |ui| {
|
||||
for n in names {
|
||||
let label = if n == SHARED_ENV {
|
||||
"$shared (all environments)".to_string()
|
||||
} else {
|
||||
n.clone()
|
||||
};
|
||||
ui.selectable_value(&mut e.selected, n, label);
|
||||
}
|
||||
});
|
||||
if ui.button("New…").clicked() {
|
||||
acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt {
|
||||
kind: PromptKind::NewEnvironment,
|
||||
title: "New environment".into(),
|
||||
value: String::new(),
|
||||
}))));
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
|
||||
// Rows: (name, value, private).
|
||||
let env = e.selected.clone();
|
||||
let mut rows: Vec<(String, String, bool, bool)> = Vec::new(); // name, value, private, structured
|
||||
for (file, private) in [(&e.envs.public, false), (&e.envs.private, true)] {
|
||||
if let Some(en) = file.env(&env) {
|
||||
for v in &en.vars {
|
||||
rows.push((v.name.clone(), v.value.clone(), private, v.is_structured()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut new_rows = rows.clone();
|
||||
let mut changed = false;
|
||||
let mut remove = None;
|
||||
egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| {
|
||||
egui::Grid::new("env-vars").num_columns(5).striped(true).show(ui, |ui| {
|
||||
for h in ["Name", "Value", "Private", "", ""] {
|
||||
ui.label(RichText::new(h).weak());
|
||||
}
|
||||
ui.end_row();
|
||||
for (i, (name, value, private, structured)) in new_rows.iter_mut().enumerate() {
|
||||
if *structured {
|
||||
ui.label(name.as_str());
|
||||
ui.label(RichText::new("(object; edit the JSON file)").weak());
|
||||
ui.label("");
|
||||
ui.label("");
|
||||
ui.label("");
|
||||
ui.end_row();
|
||||
continue;
|
||||
}
|
||||
changed |= ui
|
||||
.add_sized([160.0, ui.spacing().interact_size.y], egui::TextEdit::singleline(name))
|
||||
.changed();
|
||||
let revealed = e.revealed.contains(&(env.clone(), name.clone()));
|
||||
if *private && !revealed {
|
||||
ui.label(RichText::new("••••••••").monospace());
|
||||
} else {
|
||||
changed |= ui
|
||||
.add_sized(
|
||||
[260.0, ui.spacing().interact_size.y],
|
||||
egui::TextEdit::singleline(value).font(egui::TextStyle::Monospace),
|
||||
)
|
||||
.changed();
|
||||
}
|
||||
changed |= ui
|
||||
.checkbox(private, "")
|
||||
.on_hover_text("Stored in http-client.private.env.json (keep it out of git)")
|
||||
.changed();
|
||||
if *private {
|
||||
if ui
|
||||
.small_button(if revealed { "🙈" } else { "👁" })
|
||||
.on_hover_text("Show / hide")
|
||||
.clicked()
|
||||
{
|
||||
let k = (env.clone(), name.clone());
|
||||
if revealed {
|
||||
e.revealed.retain(|r| r != &k);
|
||||
} else {
|
||||
e.revealed.push(k);
|
||||
}
|
||||
acts.push(Action::EnvEditorChanged(e.clone()));
|
||||
}
|
||||
} else {
|
||||
ui.label("");
|
||||
}
|
||||
if ui.small_button("×").clicked() {
|
||||
remove = Some(i);
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
});
|
||||
if ui.button("Add variable").clicked() {
|
||||
let n = (1..)
|
||||
.map(|i| format!("var{i}"))
|
||||
.find(|n| !new_rows.iter().any(|r| &r.0 == n))
|
||||
.unwrap();
|
||||
new_rows.push((n, String::new(), false, false));
|
||||
changed = true;
|
||||
}
|
||||
if let Some(i) = remove {
|
||||
new_rows.remove(i);
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
apply_rows(&mut e.envs.public, &env, &new_rows, false);
|
||||
apply_rows(&mut e.envs.private, &env, &new_rows, true);
|
||||
e.dirty = true;
|
||||
acts.push(Action::EnvEditorChanged(e.clone()));
|
||||
}
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add_enabled(e.dirty, egui::Button::new("Save")).clicked() {
|
||||
save = true;
|
||||
}
|
||||
ui.label(RichText::new("Writes http-client.env.json and http-client.private.env.json.").weak());
|
||||
});
|
||||
});
|
||||
if e.selected != ed.selected {
|
||||
acts.push(Action::EnvEditorChanged(e.clone()));
|
||||
}
|
||||
if save {
|
||||
acts.push(Action::EnvEditorSave);
|
||||
}
|
||||
if !open {
|
||||
acts.push(Action::EnvEditorClose);
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the editor rows for `env` back into one env file.
|
||||
fn apply_rows(file: &mut EnvFile, env: &str, rows: &[(String, String, bool, bool)], private: bool) {
|
||||
let has_rows = rows.iter().any(|r| r.2 == private);
|
||||
if file.env(env).is_none() && !has_rows {
|
||||
return;
|
||||
}
|
||||
let en = file.env_mut(env);
|
||||
let old = std::mem::take(&mut en.vars);
|
||||
for (name, value, p, structured) in rows {
|
||||
if *p != private || name.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
if *structured {
|
||||
if let Some(v) = old.iter().find(|v| &v.name == name) {
|
||||
en.vars.push(v.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Keep the original JSON value (and type) when only the name matches.
|
||||
let mut v = old
|
||||
.iter()
|
||||
.find(|v| &v.name == name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| EnvVar::new(name.clone(), value.clone()));
|
||||
v.value = value.clone();
|
||||
en.vars.push(v);
|
||||
}
|
||||
}
|
||||
|
||||
fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec<Action>) {
|
||||
let Some(c) = &state.collection else {
|
||||
acts.push(Action::QuickOpen(None));
|
||||
acts.push(Action::Error("Open a collection to quick-open its requests".into()));
|
||||
return;
|
||||
};
|
||||
let query = q.query.to_lowercase();
|
||||
let mut items: Vec<(i32, std::path::PathBuf, usize, String, String)> = c
|
||||
.all_requests()
|
||||
.filter_map(|(path, i, r)| {
|
||||
let name = r.display_name().unwrap_or(&r.url).to_string();
|
||||
let hay = format!("{} {} {} {}", c.relative(path).display(), name, r.method, r.url);
|
||||
let score = fuzzy_score(&hay.to_lowercase(), &query)?;
|
||||
Some((
|
||||
score,
|
||||
path.clone(),
|
||||
i,
|
||||
name,
|
||||
format!("{} {}", r.method, c.relative(path).display()),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
items.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.3.cmp(&b.3)));
|
||||
items.truncate(50);
|
||||
let selected = q.selected.min(items.len().saturating_sub(1));
|
||||
|
||||
let mut next = q.clone();
|
||||
let (up, down, enter, esc) = ctx.input_mut(|i| {
|
||||
(
|
||||
i.consume_key(egui::Modifiers::NONE, Key::ArrowUp),
|
||||
i.consume_key(egui::Modifiers::NONE, Key::ArrowDown),
|
||||
i.consume_key(egui::Modifiers::NONE, Key::Enter),
|
||||
i.consume_key(egui::Modifiers::NONE, Key::Escape),
|
||||
)
|
||||
});
|
||||
if esc {
|
||||
acts.push(Action::QuickOpen(None));
|
||||
return;
|
||||
}
|
||||
if enter {
|
||||
if let Some(it) = items.get(selected) {
|
||||
acts.push(Action::OpenRequest {
|
||||
file: it.1.clone(),
|
||||
index: it.2,
|
||||
});
|
||||
}
|
||||
acts.push(Action::QuickOpen(None));
|
||||
return;
|
||||
}
|
||||
if up {
|
||||
next.selected = selected.saturating_sub(1);
|
||||
}
|
||||
if down {
|
||||
next.selected = (selected + 1).min(items.len().saturating_sub(1));
|
||||
}
|
||||
|
||||
egui::Window::new("Open request")
|
||||
.title_bar(false)
|
||||
.anchor(egui::Align2::CENTER_TOP, [0.0, 60.0])
|
||||
.fixed_size([520.0, 360.0])
|
||||
.show(ctx, |ui| {
|
||||
let mut text = q.query.clone();
|
||||
let r = ui.add(
|
||||
egui::TextEdit::singleline(&mut text)
|
||||
.hint_text("Type to find a request…")
|
||||
.desired_width(f32::INFINITY)
|
||||
.id_salt("quick-open"),
|
||||
);
|
||||
r.request_focus();
|
||||
if r.changed() {
|
||||
next.query = text;
|
||||
next.selected = 0;
|
||||
}
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
for (i, it) in items.iter().enumerate() {
|
||||
let resp = ui.selectable_label(i == selected, format!("{} {}", it.3, it.4));
|
||||
if i == selected && (up || down) {
|
||||
resp.scroll_to_me(None);
|
||||
}
|
||||
if resp.clicked() {
|
||||
acts.push(Action::OpenRequest {
|
||||
file: it.1.clone(),
|
||||
index: it.2,
|
||||
});
|
||||
acts.push(Action::QuickOpen(None));
|
||||
}
|
||||
}
|
||||
if items.is_empty() {
|
||||
ui.label(RichText::new("No matching requests").weak());
|
||||
}
|
||||
});
|
||||
});
|
||||
if next != *q {
|
||||
acts.push(Action::QuickOpen(Some(next)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Subsequence match; higher is better (consecutive and early matches score
|
||||
/// more). `None` when not all query characters appear in order.
|
||||
pub fn fuzzy_score(hay: &str, query: &str) -> Option<i32> {
|
||||
if query.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
let mut score = 0;
|
||||
let mut last: Option<usize> = None;
|
||||
let mut hi = hay.char_indices();
|
||||
for qc in query.chars().filter(|c| !c.is_whitespace()) {
|
||||
loop {
|
||||
let (i, hc) = hi.next()?;
|
||||
if hc == qc {
|
||||
score += match last {
|
||||
Some(l) if l + hc.len_utf8() == i || l + 1 == i => 5,
|
||||
_ => 1,
|
||||
};
|
||||
if i < 20 {
|
||||
score += 1;
|
||||
}
|
||||
last = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(score)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fuzzy() {
|
||||
assert!(fuzzy_score("users.http create user post", "cru").is_some());
|
||||
assert!(fuzzy_score("users.http", "xyz").is_none());
|
||||
assert!(fuzzy_score("create user", "create").unwrap() > fuzzy_score("c-r-e-a-t-e", "create").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_rows_move_between_files() {
|
||||
let mut public = EnvFile::parse(r#"{"dev": {"a": "1", "port": 80}}"#, std::path::Path::new("p")).unwrap();
|
||||
let mut private = EnvFile::default();
|
||||
let rows = vec![
|
||||
("a".to_string(), "1".to_string(), true, false),
|
||||
("port".to_string(), "80".to_string(), false, false),
|
||||
];
|
||||
apply_rows(&mut public, "dev", &rows, false);
|
||||
apply_rows(&mut private, "dev", &rows, true);
|
||||
assert_eq!(public.env("dev").unwrap().get("a"), None);
|
||||
assert_eq!(private.env("dev").unwrap().get("a"), Some("1"));
|
||||
// The number keeps its JSON type.
|
||||
assert!(public.to_json().contains("\"port\": 80"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Every non-ASCII character in the UI code must be drawable with the
|
||||
//! bundled fonts (a missing glyph panics in debug builds).
|
||||
|
||||
#[test]
|
||||
fn ui_symbols_exist_in_the_bundled_fonts() {
|
||||
let mut harness = egui_kittest::Harness::new_ui(|_ui| {});
|
||||
harness.step();
|
||||
let ctx = harness.ctx.clone();
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ui");
|
||||
let mut missing = Vec::new();
|
||||
for entry in std::fs::read_dir(dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let src = std::fs::read_to_string(&path).unwrap();
|
||||
for (n, line) in src.lines().enumerate() {
|
||||
// Only string literals in code matter, not comments.
|
||||
if line.trim_start().starts_with("//") {
|
||||
continue;
|
||||
}
|
||||
for c in line.chars().filter(|c| !c.is_ascii()) {
|
||||
for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] {
|
||||
let ok = ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::new(14.0, family.clone()), c));
|
||||
if !ok {
|
||||
missing.push(format!(
|
||||
"{c:?} (U+{:04X}) {family:?} at {}:{}",
|
||||
c as u32,
|
||||
path.display(),
|
||||
n + 1
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
missing.dedup();
|
||||
assert!(missing.is_empty(), "missing glyphs:\n{}", missing.join("\n"));
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Renders the real UI to PNG files for a visual check. Needs a GPU (or a
|
||||
//! software Vulkan driver), so it is ignored by default:
|
||||
//!
|
||||
//! REQLITE_RENDER_DIR=/tmp/shots cargo test -p reqlite-app --test render -- --ignored
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use reqlite_app::action::Action;
|
||||
use reqlite_app::state::{RequestTab, ResponseTab};
|
||||
use reqlite_app::ReqliteApp;
|
||||
use reqlite_core::http::{BodyStore, HttpClient, HttpError, ResolvedRequest, Response, Timings};
|
||||
use reqlite_core::CancelToken;
|
||||
|
||||
struct Canned;
|
||||
|
||||
impl HttpClient for Canned {
|
||||
async fn send(&self, req: ResolvedRequest, _c: CancelToken) -> Result<Response, HttpError> {
|
||||
let body = r#"{"id":42,"name":"Ada Lovelace","email":"ada@example.com","roles":["admin","author"],"active":true,"manager":null,"stats":{"posts":128,"score":9.75}}"#;
|
||||
Ok(Response {
|
||||
status: 200,
|
||||
reason: "OK".into(),
|
||||
http_version: "HTTP/2".into(),
|
||||
headers: vec![
|
||||
("content-type".into(), "application/json; charset=utf-8".into()),
|
||||
("cache-control".into(), "no-store".into()),
|
||||
("x-request-id".into(), "7f3a9c2e".into()),
|
||||
],
|
||||
size: body.len() as u64,
|
||||
body: BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())),
|
||||
timings: Timings {
|
||||
dns: Duration::from_millis(4),
|
||||
connect: Duration::from_millis(19),
|
||||
tls: Duration::from_millis(48),
|
||||
ttfb: Duration::from_millis(112),
|
||||
total: Duration::from_millis(118),
|
||||
},
|
||||
effective_url: req.url,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn shoot(h: &mut Harness<'_, ReqliteApp>, name: &str) {
|
||||
let Ok(dir) = std::env::var("REQLITE_RENDER_DIR") else {
|
||||
return;
|
||||
};
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for _ in 0..3 {
|
||||
h.step();
|
||||
}
|
||||
let img = h.render().expect("render");
|
||||
img.save(format!("{dir}/{name}.png")).unwrap();
|
||||
}
|
||||
|
||||
fn wait(h: &mut Harness<'_, ReqliteApp>, done: impl Fn(&ReqliteApp) -> bool) {
|
||||
let start = Instant::now();
|
||||
while !done(h.state()) {
|
||||
assert!(start.elapsed() < Duration::from_secs(5));
|
||||
h.step();
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs a GPU; run with --ignored"]
|
||||
fn screenshots() {
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::create_dir(root.join("orders")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("users.http"),
|
||||
"### List users\nGET {{base_url}}/users?limit=20&sort=name\nAccept: application/json\n\n### Create user\n# @name create-user\nPOST {{base_url}}/users\nContent-Type: application/json\nAuthorization: Bearer {{token}}\n\n{\n \"name\": \"Ada\",\n \"team\": \"{{team}}\"\n}\n\n### Delete user\nDELETE {{base_url}}/users/{{id}}\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("orders/orders.http"),
|
||||
"### Get order\nGET {{base_url}}/orders/1\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("http-client.env.json"),
|
||||
r#"{"dev": {"base_url": "http://localhost:8080", "team": "core"}, "prod": {"base_url": "https://api.example.com"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("http-client.private.env.json"),
|
||||
r#"{"dev": {"token": "dev-secret"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let app = ReqliteApp::new(None, rt.handle().clone(), Arc::new(Canned), None);
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(1280.0, 800.0))
|
||||
.wgpu()
|
||||
.build_ui_state(
|
||||
|ui, app: &mut ReqliteApp| {
|
||||
egui_extras::install_image_loaders(ui.ctx());
|
||||
app.frame(ui)
|
||||
},
|
||||
app,
|
||||
);
|
||||
shoot(&mut h, "01-welcome");
|
||||
|
||||
h.state_mut().dispatch(Action::OpenCollection(root.clone()));
|
||||
wait(&mut h, |a| {
|
||||
a.state.collection.as_ref().is_some_and(|c| !c.envs.names().is_empty())
|
||||
});
|
||||
h.state_mut().dispatch(Action::SelectEnv(Some("dev".into())));
|
||||
h.state_mut().dispatch(Action::OpenRequest {
|
||||
file: root.join("users.http"),
|
||||
index: 1,
|
||||
});
|
||||
let id = h.state().state.active.unwrap();
|
||||
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Body));
|
||||
shoot(&mut h, "02-collection-body-tab");
|
||||
|
||||
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Headers));
|
||||
h.state_mut().dispatch(Action::Send(id));
|
||||
wait(&mut h, |a| {
|
||||
a.state
|
||||
.active_tab()
|
||||
.and_then(|t| t.response.as_ref())
|
||||
.is_some_and(|r| r.prepared.is_some())
|
||||
});
|
||||
shoot(&mut h, "03-json-response");
|
||||
|
||||
h.state_mut().dispatch(Action::SearchOpen(id, true));
|
||||
h.state_mut().dispatch(Action::SearchQuery(id, "a".into()));
|
||||
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Source));
|
||||
shoot(&mut h, "04-source-and-search");
|
||||
|
||||
h.state_mut().dispatch(Action::SetResponseTab(id, ResponseTab::Timings));
|
||||
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Auth));
|
||||
shoot(&mut h, "05-auth-and-timings");
|
||||
|
||||
h.state_mut().dispatch(Action::OpenEnvEditor);
|
||||
shoot(&mut h, "06-env-editor");
|
||||
h.state_mut().dispatch(Action::EnvEditorClose);
|
||||
|
||||
let mut s = h.state().state.settings.clone();
|
||||
s.theme = reqlite_app::settings::ThemeChoice::Light;
|
||||
h.state_mut().dispatch(Action::SettingsChanged(s));
|
||||
h.state_mut().dispatch(Action::SetResponseTab(id, ResponseTab::Body));
|
||||
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Params));
|
||||
shoot(&mut h, "07-light-theme");
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! UI smoke tests with egui_kittest and a fake async HttpClient.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use egui_kittest::Harness;
|
||||
use reqlite_app::action::Action;
|
||||
use reqlite_app::ReqliteApp;
|
||||
use reqlite_core::http::{BodyStore, HttpClient, HttpError, ResolvedRequest, Response, Timings};
|
||||
use reqlite_core::CancelToken;
|
||||
|
||||
/// Answers every request with a small JSON body after a short delay.
|
||||
#[derive(Default)]
|
||||
struct FakeClient {
|
||||
seen: Mutex<Vec<ResolvedRequest>>,
|
||||
}
|
||||
|
||||
impl HttpClient for FakeClient {
|
||||
fn send(
|
||||
&self,
|
||||
req: ResolvedRequest,
|
||||
cancel: CancelToken,
|
||||
) -> impl std::future::Future<Output = Result<Response, HttpError>> + Send {
|
||||
self.seen.lock().unwrap().push(req.clone());
|
||||
async move {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_millis(30)) => {}
|
||||
_ = cancel.cancelled() => return Err(HttpError::Cancelled),
|
||||
}
|
||||
let body = format!("{{\"echo\": \"{}\", \"items\": [1, 2, 3]}}", req.url);
|
||||
Ok(Response {
|
||||
status: 200,
|
||||
reason: "OK".into(),
|
||||
http_version: "HTTP/1.1".into(),
|
||||
headers: vec![("content-type".into(), "application/json".into())],
|
||||
size: body.len() as u64,
|
||||
body: BodyStore::InMemory(Arc::new(body.into_bytes())),
|
||||
timings: Timings {
|
||||
total: Duration::from_millis(30),
|
||||
..Default::default()
|
||||
},
|
||||
effective_url: req.url,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn harness(rt: &tokio::runtime::Runtime, client: Arc<FakeClient>) -> Harness<'static, ReqliteApp> {
|
||||
let app = ReqliteApp::new(None, rt.handle().clone(), client, None);
|
||||
Harness::builder()
|
||||
.with_size(egui::vec2(1100.0, 760.0))
|
||||
.build_ui_state(|ui, app: &mut ReqliteApp| app.frame(ui), app)
|
||||
}
|
||||
|
||||
/// Steps the UI until `done` holds (effects finish on other threads).
|
||||
fn step_until(h: &mut Harness<'_, ReqliteApp>, what: &str, done: impl Fn(&Harness<'_, ReqliteApp>) -> bool) {
|
||||
let start = Instant::now();
|
||||
while !done(h) {
|
||||
assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for {what}");
|
||||
h.step();
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_a_request_and_see_the_response() {
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let client = Arc::new(FakeClient::default());
|
||||
let mut h = harness(&rt, client.clone());
|
||||
h.step();
|
||||
// The welcome screen offers a new request.
|
||||
h.get_by_label("New request (Ctrl+T)").click();
|
||||
h.step();
|
||||
let id = h.state().state.active.expect("a tab");
|
||||
h.state_mut()
|
||||
.dispatch(Action::UrlEdited(id, "http://example.test/items?limit=3".into()));
|
||||
h.step();
|
||||
|
||||
// The URL query shows up in the Params tab.
|
||||
assert!(h.query_by_label("Params (1)").is_some());
|
||||
|
||||
h.get_by_label("Send").click();
|
||||
step_until(&mut h, "the response", |h| {
|
||||
h.query_by_label_contains("200 OK").is_some()
|
||||
});
|
||||
step_until(&mut h, "the prepared body", |h| {
|
||||
h.state()
|
||||
.state
|
||||
.active_tab()
|
||||
.unwrap()
|
||||
.response
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.prepared
|
||||
.is_some()
|
||||
});
|
||||
h.step();
|
||||
assert!(h.query_by_label_contains("\"items\"").is_some(), "pretty JSON is shown");
|
||||
assert_eq!(client.seen.lock().unwrap()[0].url, "http://example.test/items?limit=3");
|
||||
|
||||
// Headers and Timings tabs render.
|
||||
h.get_by_label("Headers (1)").click();
|
||||
h.step();
|
||||
h.step();
|
||||
assert!(h.query_by_label("content-type").is_some());
|
||||
h.get_by_label("Timings").click();
|
||||
h.step();
|
||||
h.step();
|
||||
assert!(h.query_by_label("Total").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_shortcuts_open_and_close_tabs() {
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let mut h = harness(&rt, Arc::new(FakeClient::default()));
|
||||
h.step();
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::T);
|
||||
h.step();
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::T);
|
||||
h.step();
|
||||
assert_eq!(h.state().state.tabs.len(), 2);
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::W);
|
||||
h.step();
|
||||
assert_eq!(h.state().state.tabs.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_a_collection_and_shows_its_requests() {
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("users.http"),
|
||||
"### List users\nGET {{base}}/users\n\n### Create user\nPOST {{base}}/users\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("http-client.env.json"),
|
||||
r#"{"dev": {"base": "http://dev"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let client = Arc::new(FakeClient::default());
|
||||
let mut h = harness(&rt, client.clone());
|
||||
h.state_mut().dispatch(Action::OpenCollection(dir.path().to_path_buf()));
|
||||
step_until(&mut h, "the collection", |h| {
|
||||
h.state()
|
||||
.state
|
||||
.collection
|
||||
.as_ref()
|
||||
.is_some_and(|c| !c.envs.names().is_empty())
|
||||
});
|
||||
h.step();
|
||||
h.get_by_label_contains("Create user").click();
|
||||
h.step();
|
||||
assert_eq!(h.state().state.active_tab().unwrap().title(), "Create user");
|
||||
|
||||
h.state_mut().dispatch(Action::SelectEnv(Some("dev".into())));
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Enter);
|
||||
step_until(&mut h, "the response", |h| {
|
||||
h.query_by_label_contains("200 OK").is_some()
|
||||
});
|
||||
assert_eq!(client.seen.lock().unwrap()[0].url, "http://dev/users");
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! The file watcher reports external edits to .http files.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use reqlite_app::action::Action;
|
||||
use reqlite_app::effects::{Effect, Runner};
|
||||
use reqlite_core::http::{HttpClient, HttpError, ResolvedRequest, Response};
|
||||
use reqlite_core::CancelToken;
|
||||
|
||||
struct NoClient;
|
||||
|
||||
impl HttpClient for NoClient {
|
||||
async fn send(&self, _r: ResolvedRequest, _c: CancelToken) -> Result<Response, HttpError> {
|
||||
Err(HttpError::Other("unused".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_changes_to_http_and_env_files() {
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(root.join("a.http"), "GET /a\n").unwrap();
|
||||
let (runner, mut rx) = Runner::new(rt.handle().clone(), None, Arc::new(NoClient), None, 4);
|
||||
runner.run(Effect::Watch(Some(root.clone())));
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
|
||||
std::fs::write(root.join("a.http"), "GET /changed\n").unwrap();
|
||||
std::fs::write(root.join("ignored.txt"), "x").unwrap();
|
||||
std::fs::create_dir(root.join("sub")).unwrap();
|
||||
std::fs::write(root.join("sub/new.http"), "GET /new\n").unwrap();
|
||||
std::fs::write(root.join("http-client.env.json"), "{}").unwrap();
|
||||
|
||||
let mut seen = std::collections::HashMap::new();
|
||||
let mut rescan = false;
|
||||
rt.block_on(async {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
while seen.len() < 2 || !rescan {
|
||||
match tokio::time::timeout_at(deadline, rx.recv()).await {
|
||||
Ok(Some(Action::FileChangedOnDisk { path, text })) => {
|
||||
seen.insert(path, text);
|
||||
}
|
||||
Ok(Some(Action::Rescan)) => rescan = true,
|
||||
Ok(Some(_)) => {}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(
|
||||
seen.get(&root.join("a.http")),
|
||||
Some(&Some("GET /changed\n".to_string()))
|
||||
);
|
||||
// A new folder triggers a rescan (its files may race the new watch).
|
||||
assert!(rescan);
|
||||
assert!(seen.contains_key(&root.join("http-client.env.json")));
|
||||
assert!(!seen.contains_key(&root.join("ignored.txt")));
|
||||
|
||||
std::fs::remove_file(root.join("a.http")).unwrap();
|
||||
let deleted = rt.block_on(async {
|
||||
loop {
|
||||
match tokio::time::timeout(Duration::from_secs(5), rx.recv()).await {
|
||||
Ok(Some(Action::FileChangedOnDisk { path, text })) if path == root.join("a.http") => break text,
|
||||
Ok(Some(_)) => {}
|
||||
_ => panic!("no delete event"),
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(deleted, None);
|
||||
|
||||
// Stopping the watch stops the events.
|
||||
runner.run(Effect::Watch(None));
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
while rx.try_recv().is_ok() {}
|
||||
std::fs::write(root.join("b.http"), "GET /b\n").unwrap();
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
Reference in new issue
Block a user