Compare commits

..
5 Commits
Author SHA1 Message Date
Torbjörn Molin 135e9777fa Publish windows release for v* tags
windows / build (push) Failing after 4m24s
2026-11-09 13:20:48 +01:00
Torbjörn Molin 1e7f8678eb Added custom auth support
windows / build (push) Successful in 5m0s
2026-11-09 12:56:54 +01:00
Torbjörn Molin ae055be9cc Added gitea pipeline
windows / build (push) Successful in 5m44s
2026-11-09 12:45:41 +01:00
Torbjörn Molin 1eec55181d Bumped version to 0.2.0 2026-11-09 12:39:13 +01:00
Torbjörn Molin 425c73da4f Moved UI strings in to separate file 2026-11-09 12:38:34 +01:00
20 changed files with 1598 additions and 592 deletions

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
# Cross-compiles reqlite for Windows (x86_64-pc-windows-gnu, MinGW-w64) on the
# standard Ubuntu runner and uploads a portable zip with both binaries.
name: windows
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
TARGET: x86_64-pc-windows-gnu
# Link the MinGW C runtime pieces statically so the .exe files need no DLLs.
CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUSTFLAGS: -C target-feature=+crt-static
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install MinGW-w64 and zip
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64 zip
- name: Install Rust (version from rust-toolchain.toml)
run: |
if ! command -v rustup >/dev/null; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
export PATH="$HOME/.cargo/bin:$PATH"
fi
rustup show active-toolchain || rustup toolchain install
rustup target add "$TARGET"
- uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: windows-gnu-${{ hashFiles('rust-toolchain.toml', 'Cargo.lock') }}
restore-keys: windows-gnu-
- name: Build
run: cargo build --release --locked --target "$TARGET" -p reqlite-app -p reqlite-cli
- name: Package
id: package
run: |
version=$(cargo pkgid -p reqlite-app | sed 's/.*[#@]//')
name="reqlite-${version}-windows-x86_64"
dir="target/dist/${name}"
rm -rf "$dir" && mkdir -p "$dir"
cp "target/$TARGET/release/reqlite-gui.exe" "target/$TARGET/release/reqlite.exe" README.md "$dir/"
(cd target/dist && rm -f "${name}.zip" && zip -r9 "${name}.zip" "$name")
echo "name=${name}" >> "$GITHUB_OUTPUT"
echo "version=${version}" >> "$GITHUB_OUTPUT"
- uses: actions/upload-artifact@v3
with:
name: ${{ steps.package.outputs.name }}
path: target/dist/${{ steps.package.outputs.name }}.zip
- name: Check tag matches crate version
if: startsWith(github.ref, 'refs/tags/v')
run: |
if [ "${GITHUB_REF_NAME}" != "v${{ steps.package.outputs.version }}" ]; then
echo "Tag ${GITHUB_REF_NAME} does not match crate version v${{ steps.package.outputs.version }}" >&2
exit 1
fi
- name: Publish release
if: startsWith(github.ref, 'refs/tags/v')
uses: https://gitea.com/actions/gitea-release-action@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
name: ${{ github.ref_name }}
files: target/dist/${{ steps.package.outputs.name }}.zip
sha256sum: true
Generated
+4 -4
View File
@@ -3340,7 +3340,7 @@ checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
[[package]] [[package]]
name = "reqlite-app" name = "reqlite-app"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.23.1", "base64 0.23.1",
@@ -3368,7 +3368,7 @@ dependencies = [
[[package]] [[package]]
name = "reqlite-cli" name = "reqlite-cli"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
@@ -3382,7 +3382,7 @@ dependencies = [
[[package]] [[package]]
name = "reqlite-core" name = "reqlite-core"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"base64 0.23.1", "base64 0.23.1",
@@ -3397,7 +3397,7 @@ dependencies = [
[[package]] [[package]]
name = "reqlite-http-curl" name = "reqlite-http-curl"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"curl", "curl",
"rcgen", "rcgen",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/core", "crates/http-curl", "crates/app", "crates/cli"] members = ["crates/core", "crates/http-curl", "crates/app", "crates/cli"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.2.0"
edition = "2021" edition = "2021"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
rust-version = "1.98" rust-version = "1.98"
+9 -4
View File
@@ -75,14 +75,19 @@ Other things worth knowing:
form stay in sync. form stay in sync.
- The **Auth** tab is a helper that writes the `Authorization` header. Basic - The **Auth** tab is a helper that writes the `Authorization` header. Basic
auth is written as `Basic user password` and encoded when sent, like JetBrains. auth is written as `Basic user password` and encoded when sent, like JetBrains.
*Custom header* sends auth in a header of your choice (e.g. `X-API-Key`); the
request is marked with `# @auth-header X-API-Key` so reqlite knows that header
is its auth.
- **Folder auth:** right-click a folder → *Folder auth…* (or a collection → - **Folder auth:** right-click a folder → *Folder auth…* (or a collection →
*Default auth…*) to set auth that every request below it uses when it has no *Default auth…*) to set auth that every request below it uses when it has no
`Authorization` header of its own. The nearest folder wins; a folder can also `Authorization` header of its own. The nearest folder wins; a folder can also
say *None* to stop inheritance. In a request's Auth tab, *Inherit* (no say *None* to stop inheritance. In a request's Auth tab, *Inherit* (no
header) uses it and *None* opts out with `# @no-auth`. It is stored in header) uses it and *None* opts out with `# @no-auth`. It is stored in
`<folder>/.reqlite/folder.json` as `{ "auth": "Bearer {{token}}" }` `<folder>/.reqlite/folder.json` as `{ "auth": "Bearer {{token}}" }`, or
(`null` = none); other `.http` tools ignore it. The CLI applies it too. `{ "auth": { "header": "X-API-Key", "value": "{{api_key}}" } }` for a custom
- **Consolidate auth…** (same menus) removes `Authorization` headers that match header (`null` = none); other `.http` tools ignore it. A request that already
sets the folder's custom header itself keeps its own value. The CLI applies it too.
- **Consolidate auth…** (same menus) removes auth headers that match
what the request would inherit. If the folder has no auth yet, it offers the what the request would inherit. If the folder has no auth yet, it offers the
most used header as the folder's auth, and can pin requests that would most used header as the folder's auth, and can pin requests that would
otherwise change (they get their current header, or `# @no-auth`). otherwise change (they get their current header, or `# @no-auth`).
@@ -129,7 +134,7 @@ on:
- Directives: `# @name`, `# @no-redirect`, `# @no-cookie-jar`, `# @no-log`, - Directives: `# @name`, `# @no-redirect`, `# @no-cookie-jar`, `# @no-log`,
`# @timeout 30` / `500 ms`, `# @connection-timeout`. `# @insecure` is a `# @timeout 30` / `500 ms`, `# @connection-timeout`. `# @insecure` is a
reqlite extension written by curl import for `-k`; `# @no-auth` is one that reqlite extension written by curl import for `-k`; `# @no-auth` is one that
skips folder auth. skips folder auth, and `# @auth-header <name>` marks a custom auth header.
- `#` and `//` comments. - `#` and `//` comments.
Anything else (unknown directives, response handlers `> {% … %}` and Anything else (unknown directives, response handlers `> {% … %}` and
+3 -1
View File
@@ -46,7 +46,9 @@ uuid.workspace = true
egui_kittest.workspace = true egui_kittest.workspace = true
tempfile.workspace = true tempfile.workspace = true
[target.'cfg(windows)'.build-dependencies] # Unconditional so the icon is also embedded when cross-compiling from Linux
# (build.rs checks the *target* OS; only used for Windows targets).
[build-dependencies]
winresource.workspace = true winresource.workspace = true
# `cargo bundle --release -p reqlite-app` builds a macOS .app (and .deb). # `cargo bundle --release -p reqlite-app` builds a macOS .app (and .deb).
-1
View File
@@ -2,7 +2,6 @@
fn main() { fn main() {
println!("cargo:rerun-if-changed=assets/icon.ico"); println!("cargo:rerun-if-changed=assets/icon.ico");
#[cfg(windows)]
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
let mut res = winresource::WindowsResource::new(); let mut res = winresource::WindowsResource::new();
res.set_icon("assets/icon.ico"); res.set_icon("assets/icon.ico");
+48 -51
View File
@@ -8,7 +8,9 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH};
use reqlite_core::collection::{self, Collection}; use reqlite_core::collection::{self, Collection};
use reqlite_core::env::{self, Environments}; use reqlite_core::env::{self, Environments};
use reqlite_core::export::curl::to_curl; use reqlite_core::export::curl::to_curl;
use reqlite_core::folder::{self, auth_mode, same_auth, with_inherited_auth, AuthMode, FolderAuth, FolderSettings}; use reqlite_core::folder::{
self, auth_mode, same_auth, with_inherited_auth, AuthHeader, AuthMode, FolderAuth, FolderSettings,
};
use reqlite_core::http::{HttpError, Response}; use reqlite_core::http::{HttpError, Response};
use reqlite_core::httpfile::{render_request, HttpFile}; use reqlite_core::httpfile::{render_request, HttpFile};
use reqlite_core::import::curl::{from_curl, looks_like_curl}; use reqlite_core::import::curl::{from_curl, looks_like_curl};
@@ -20,6 +22,7 @@ use crate::effects::{Effect, FileOp};
use crate::history::HistoryEntry; use crate::history::HistoryEntry;
use crate::settings::Settings; use crate::settings::Settings;
use crate::state::*; use crate::state::*;
use crate::strings as txt;
#[derive(Debug)] #[derive(Debug)]
pub enum Action { pub enum Action {
@@ -153,7 +156,7 @@ pub enum Action {
/// `target` picks the auth to inherit when the folder has none. /// `target` picks the auth to inherit when the folder has none.
ConsolidateAuth { ConsolidateAuth {
dir: PathBuf, dir: PathBuf,
target: Option<String>, target: Option<AuthHeader>,
}, },
ApplyConsolidateAuth(ConsolidateAuth), ApplyConsolidateAuth(ConsolidateAuth),
@@ -281,7 +284,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
let src = f.request_source(0).unwrap_or("").to_string(); let src = f.request_source(0).unwrap_or("").to_string();
new_tab(state, r, None, src); new_tab(state, r, None, src);
} }
None => state.set_error("No request in that text"), None => state.set_error(txt::msg::NO_REQUEST_IN_TEXT),
} }
} }
@@ -296,10 +299,10 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
req.name = t.request.name.clone(); req.name = t.request.name.clone();
} }
edit(state, id, |r| *r = req); edit(state, id, |r| *r = req);
state.set_info("Imported the curl command"); state.set_info(txt::msg::CURL_IMPORTED);
} }
Err(e) => { Err(e) => {
state.set_error(format!("Could not import curl command: {e}")); state.set_error(txt::msg::curl_import_failed(e));
edit(state, id, |r| r.url = url); edit(state, id, |r| r.url = url);
} }
} }
@@ -319,13 +322,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
} }
Action::HeadersEdited(id, headers) => edit(state, id, |r| r.headers = headers), Action::HeadersEdited(id, headers) => edit(state, id, |r| r.headers = headers),
Action::BodyEdited(id, body) => edit(state, id, |r| r.body = body), Action::BodyEdited(id, body) => edit(state, id, |r| r.body = body),
Action::AuthEdited(id, mode) => edit(state, id, |r| { Action::AuthEdited(id, mode) => edit(state, id, |r| folder::set_auth_mode(r, &mode)),
match &mode {
AuthMode::Own(v) => r.set_header("Authorization", v.as_str()),
AuthMode::NoAuth | AuthMode::Inherit => r.remove_header("Authorization"),
}
folder::set_no_auth(r, mode == AuthMode::NoAuth);
}),
Action::SetNoRedirect(id, on) => edit(state, id, |r| r.directives.no_redirect = on), Action::SetNoRedirect(id, on) => edit(state, id, |r| r.directives.no_redirect = on),
Action::PickBodyFile(id) => fx.push(Effect::PickBodyFile(id)), Action::PickBodyFile(id) => fx.push(Effect::PickBodyFile(id)),
Action::BodyFilePicked(id, path) => { Action::BodyFilePicked(id, path) => {
@@ -352,8 +349,8 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
t.request = r; t.request = r;
t.source_error = None; t.source_error = None;
} }
0 => t.source_error = Some("No request line found".into()), 0 => t.source_error = Some(txt::msg::NO_REQUEST_LINE.into()),
n => t.source_error = Some(format!("The source must contain exactly one request (found {n})")), n => t.source_error = Some(txt::msg::not_one_request(n)),
} }
} }
} }
@@ -380,7 +377,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
if let Some(t) = state.tab_mut(id) { if let Some(t) = state.tab_mut(id) {
if let Some(f) = t.in_flight.take() { if let Some(f) = t.in_flight.take() {
f.cancel.cancel(); f.cancel.cancel();
t.error = Some("Cancelled".into()); t.error = Some(txt::msg::CANCELLED.into());
} }
} }
} }
@@ -448,11 +445,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
.iter() .iter()
.find(|c| root.starts_with(&c.root) || c.root.starts_with(&root)) .find(|c| root.starts_with(&c.root) || c.root.starts_with(&root))
{ {
state.set_error(format!( state.set_error(txt::msg::overlaps(root.display(), other.root.display()));
"{} overlaps the open collection {}; close that one first",
root.display(),
other.root.display()
));
return fx; return fx;
} }
state.settings.add_recent(root.clone()); state.settings.add_recent(root.clone());
@@ -500,7 +493,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
state.active_collection = Some(root); state.active_collection = Some(root);
} }
} }
Action::CollectionLoaded(Err(e)) => state.set_error(format!("Could not open the collection: {e}")), Action::CollectionLoaded(Err(e)) => state.set_error(txt::msg::collection_failed(e)),
Action::CollectionLoaded(Ok(c)) => collection_loaded(state, c, &mut fx), Action::CollectionLoaded(Ok(c)) => collection_loaded(state, c, &mut fx),
Action::EnvironmentsLoaded { root, result } => { Action::EnvironmentsLoaded { root, result } => {
if let Some(c) = state.collection_mut(&root) { if let Some(c) = state.collection_mut(&root) {
@@ -548,11 +541,11 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
}; };
let path = dir.join(name); let path = dir.join(name);
if state.collection_of(&path).is_some_and(|c| c.files.contains_key(&path)) { if state.collection_of(&path).is_some_and(|c| c.files.contains_key(&path)) {
state.set_error(format!("{} already exists", path.display())); state.set_error(txt::msg::already_exists(path.display()));
return fx; return fx;
} }
let req = Request { let req = Request {
title: Some("New request".into()), title: Some(txt::common::NEW_REQUEST.into()),
..Request::default() ..Request::default()
}; };
let text = render_request(&req, "\n"); let text = render_request(&req, "\n");
@@ -564,7 +557,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
let Some(f) = file_of(state, &file) else { return fx }; let Some(f) = file_of(state, &file) else { return fx };
let n = f.request_count(); let n = f.request_count();
let req = Request { let req = Request {
title: Some(unique_title(f, "New request")), title: Some(unique_title(f, txt::common::NEW_REQUEST)),
..Request::default() ..Request::default()
}; };
let text = f.insert_request(None, &req); let text = f.insert_request(None, &req);
@@ -613,10 +606,10 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
let Some(src) = f.request_source(index) else { return fx }; let Some(src) = f.request_source(index) else { return fx };
let orig = f.request(index).cloned().unwrap_or_default(); let orig = f.request(index).cloned().unwrap_or_default();
// Re-title the copy so its key is unique. // Re-title the copy so its key is unique.
let base = orig.display_name().unwrap_or("Request").to_string(); let base = orig.display_name().unwrap_or(txt::names::REQUEST).to_string();
let mut copy = HttpFile::parse(src.to_string()); let mut copy = HttpFile::parse(src.to_string());
let mut r = copy.request(0).cloned().unwrap_or_default(); let mut r = copy.request(0).cloned().unwrap_or_default();
r.title = Some(unique_title(f, &format!("{base} copy"))); r.title = Some(unique_title(f, &txt::names::copy_of(&base)));
r.name = r.name.as_ref().map(|_| slug_name(r.title.as_deref().unwrap())); r.name = r.name.as_ref().map(|_| slug_name(r.title.as_deref().unwrap()));
if let Some(t) = copy.replace_request(0, &r) { if let Some(t) = copy.replace_request(0, &r) {
copy = HttpFile::parse(t); copy = HttpFile::parse(t);
@@ -724,8 +717,8 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
.unwrap_or("http".into()); .unwrap_or("http".into());
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default(); let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
let taken = |p: &PathBuf| state.collection_of(p).is_some_and(|c| c.files.contains_key(p)); let taken = |p: &PathBuf| state.collection_of(p).is_some_and(|c| c.files.contains_key(p));
let copy = std::iter::once(dir.join(format!("{stem} copy.{ext}"))) let copy = std::iter::once(dir.join(txt::names::file_copy(&stem, &ext)))
.chain((2..).map(|n| dir.join(format!("{stem} copy {n}.{ext}")))) .chain((2..).map(|n| dir.join(txt::names::file_copy_n(&stem, n, &ext))))
.find(|p| !taken(p)) .find(|p| !taken(p))
.unwrap(); .unwrap();
fx.push(file_ops(state, vec![FileOp::Write(copy.clone(), text.clone())], true)); fx.push(file_ops(state, vec![FileOp::Write(copy.clone(), text.clone())], true));
@@ -801,7 +794,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
dirty: false, dirty: false,
}); });
} else { } else {
state.set_error("Open a collection folder first; environments live next to the .http files"); state.set_error(txt::msg::NEED_COLLECTION_FOR_ENVS);
} }
} }
Action::EnvEditorChanged(e) => state.env_editor = Some(e), Action::EnvEditorChanged(e) => state.env_editor = Some(e),
@@ -850,9 +843,9 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
) { ) {
Ok(r) => { Ok(r) => {
fx.push(Effect::CopyToClipboard(to_curl(&r))); fx.push(Effect::CopyToClipboard(to_curl(&r)));
state.set_info("Copied as curl"); state.set_info(txt::msg::COPIED_CURL);
} }
Err(e) => state.set_error(format!("Cannot build the curl command: {e}")), Err(e) => state.set_error(txt::msg::curl_failed(e)),
} }
} }
Action::CopyAsHttp(id) => { Action::CopyAsHttp(id) => {
@@ -863,7 +856,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
t.source.clone() t.source.clone()
}; };
fx.push(Effect::CopyToClipboard(text)); fx.push(Effect::CopyToClipboard(text));
state.set_info("Copied as .http"); state.set_info(txt::msg::COPIED_HTTP);
} }
Action::ImportPostman => fx.push(Effect::PickPostmanImport), Action::ImportPostman => fx.push(Effect::PickPostmanImport),
Action::PostmanImported { root, files, warnings } => { Action::PostmanImported { root, files, warnings } => {
@@ -1065,7 +1058,7 @@ fn send(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
if let Some(e) = &t.source_error { if let Some(e) = &t.source_error {
let e = e.clone(); let e = e.clone();
if let Some(t) = state.tab_mut(id) { if let Some(t) = state.tab_mut(id) {
t.error = Some(format!("Fix the source first: {e}")); t.error = Some(txt::msg::fix_source(e));
} }
return; return;
} }
@@ -1426,7 +1419,10 @@ fn unique_title(f: &HttpFile, base: &str) -> String {
if !taken(base) { if !taken(base) {
return base.to_string(); return base.to_string();
} }
(2..).map(|n| format!("{base} {n}")).find(|t| !taken(t)).unwrap() (2..)
.map(|n| txt::names::numbered(base, n))
.find(|t| !taken(t))
.unwrap()
} }
fn slug_name(title: &str) -> String { fn slug_name(title: &str) -> String {
@@ -1434,14 +1430,14 @@ fn slug_name(title: &str) -> String {
} }
/// Works out what "Consolidate auth" on `dir` would do: which requests can /// Works out what "Consolidate auth" on `dir` would do: which requests can
/// drop their own Authorization header and inherit `dir`'s auth instead. /// drop their own auth header and inherit `dir`'s auth instead.
/// When `dir` has no auth of its own, `pick` (or what it already inherits, /// When `dir` has no auth of its own, `pick` (or what it already inherits,
/// or the most used header) becomes its auth. /// or the most used header) becomes its auth.
pub fn plan_consolidation(state: &AppState, dir: &Path, pick: Option<String>) -> Option<ConsolidateAuth> { pub fn plan_consolidation(state: &AppState, dir: &Path, pick: Option<AuthHeader>) -> Option<ConsolidateAuth> {
let c = state.collection_of(dir)?; let c = state.collection_of(dir)?;
let requests: Vec<_> = c.all_requests().filter(|(p, _, _)| p.starts_with(dir)).collect(); let requests: Vec<_> = c.all_requests().filter(|(p, _, _)| p.starts_with(dir)).collect();
let mut choices: Vec<(String, usize)> = Vec::new(); let mut choices: Vec<(AuthHeader, usize)> = Vec::new();
for (_, _, r) in &requests { for (_, _, r) in &requests {
if let AuthMode::Own(v) = auth_mode(r) { if let AuthMode::Own(v) = auth_mode(r) {
match choices.iter_mut().find(|(c, _)| same_auth(c, &v)) { match choices.iter_mut().find(|(c, _)| same_auth(c, &v)) {
@@ -1549,7 +1545,7 @@ enum AuthFix {
/// Drop its own header so it inherits. /// Drop its own header so it inherits.
Inherit, Inherit,
/// Pin the auth it sends today (a header, or `# @no-auth` for `None`). /// Pin the auth it sends today (a header, or `# @no-auth` for `None`).
Keep(Option<String>), Keep(Option<AuthHeader>),
} }
fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec<Effect>) { fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec<Effect>) {
@@ -1583,14 +1579,15 @@ fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec
// The file may have changed since the plan was made. // The file may have changed since the plan was made.
match (&edit, auth_mode(&r)) { match (&edit, auth_mode(&r)) {
(AuthFix::Inherit, AuthMode::Own(_)) => { (AuthFix::Inherit, AuthMode::Own(_)) => {
r.remove_header("Authorization"); folder::set_auth_mode(&mut r, &AuthMode::Inherit);
dropped += 1; dropped += 1;
} }
(AuthFix::Keep(before), AuthMode::Inherit) => { (AuthFix::Keep(before), AuthMode::Inherit) => {
match before { let mode = match before {
Some(v) => r.set_header("Authorization", v.as_str()), Some(h) => AuthMode::Own(h.clone()),
None => folder::set_no_auth(&mut r, true), None => AuthMode::NoAuth,
} };
folder::set_auth_mode(&mut r, &mode);
pinned += 1; pinned += 1;
} }
_ => continue, _ => continue,
@@ -1621,23 +1618,23 @@ fn apply_consolidation(state: &mut AppState, plan: ConsolidateAuth, fx: &mut Vec
settings.auth = FolderAuth::Header(target.clone()); settings.auth = FolderAuth::Header(target.clone());
ops.push(FileOp::Write(folder::settings_path(&plan.dir), settings.to_json())); ops.push(FileOp::Write(folder::settings_path(&plan.dir), settings.to_json()));
c.folders.insert(plan.dir.clone(), settings); c.folders.insert(plan.dir.clone(), settings);
msg.push(format!("set the folder auth to `{target}`")); msg.push(txt::consolidate::set_folder(&target.to_string()));
} }
} }
if dropped > 0 { if dropped > 0 {
msg.push(format!("{dropped} request(s) now inherit it")); msg.push(txt::consolidate::dropped(dropped));
} }
if pinned > 0 { if pinned > 0 {
msg.push(format!("{pinned} request(s) keep their auth explicitly")); msg.push(txt::consolidate::pinned(pinned));
} }
if !plan.skipped_dirty.is_empty() { if !plan.skipped_dirty.is_empty() {
msg.push(format!("{} with unsaved edits skipped", plan.skipped_dirty.len())); msg.push(txt::consolidate::skipped(plan.skipped_dirty.len()));
} }
if !ops.is_empty() { if !ops.is_empty() {
fx.push(Effect::FileOps { ops, rescan: None }); fx.push(Effect::FileOps { ops, rescan: None });
} }
if msg.is_empty() { if msg.is_empty() {
state.set_info("Auth: nothing to change"); state.set_info(txt::consolidate::NOTHING_TO_CHANGE);
} else { } else {
let mut text = msg.join(", "); let mut text = msg.join(", ");
text[..1].make_ascii_uppercase(); text[..1].make_ascii_uppercase();
@@ -1649,7 +1646,7 @@ fn save(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
let Some(t) = state.tab(id) else { return }; let Some(t) = state.tab(id) else { return };
if let Some(e) = &t.source_error { if let Some(e) = &t.source_error {
let e = e.clone(); let e = e.clone();
state.set_error(format!("Cannot save: {e}")); state.set_error(txt::msg::cannot_save(e));
return; return;
} }
let Some(origin) = t.origin.clone() else { let Some(origin) = t.origin.clone() else {
@@ -1657,11 +1654,11 @@ fn save(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
return; return;
}; };
let Some(f) = file_of(state, &origin.file) else { let Some(f) = file_of(state, &origin.file) else {
state.set_error(format!("{} is not loaded", origin.file.display())); state.set_error(txt::msg::not_loaded(origin.file.display()));
return; return;
}; };
let Some(index) = f.find(&origin.key) else { let Some(index) = f.find(&origin.key) else {
state.set_error("The request is no longer in its file; use Save As"); state.set_error(txt::msg::NO_LONGER_IN_FILE);
return; return;
}; };
let new_text = if t.source_authoritative { let new_text = if t.source_authoritative {
+67 -8
View File
@@ -8,7 +8,7 @@ use reqlite_core::collection::{Collection, Node};
use reqlite_core::env::EnvFile; use reqlite_core::env::EnvFile;
use reqlite_core::http::{BodyStore, Timings}; use reqlite_core::http::{BodyStore, Timings};
use reqlite_core::folder::{AuthMode, FolderAuth}; use reqlite_core::folder::{AuthHeader, AuthMode, FolderAuth};
use super::*; use super::*;
@@ -1180,6 +1180,69 @@ fn requests_inherit_folder_auth_unless_they_opt_out() {
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer root")); assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer root"));
} }
fn sent_header(s: &mut AppState, id: TabId, name: &str) -> Option<String> {
let fx = update(s, Action::Send(id));
let Some(Effect::SendRequest { request, .. }) = fx.first() else {
panic!("not sent: {:?}", s.tab(id).unwrap().error)
};
let v = request
.headers
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.clone());
update(s, Action::Cancel(id));
v
}
#[test]
fn folder_and_request_auth_can_use_a_custom_header() {
let mut s = state();
let root = with_collection(
&mut s,
&[("a.http", "### Plain\nGET http://x/a\n\n### Own\nGET http://x/b\n")],
);
let open = |s: &mut AppState, index| {
update(
s,
Action::OpenRequest {
file: root.join("a.http"),
index,
},
);
active(s)
};
let plain = open(&mut s, 0);
let own = open(&mut s, 1);
let key = |v: &str| AuthHeader::custom("X-API-Key", v);
let fx = set_folder_auth(&mut s, root.clone(), FolderAuth::Header(key("k-root")));
assert_eq!(
writes(&fx),
vec![(
root.join(".reqlite/folder.json"),
"{\n \"auth\": {\n \"header\": \"X-API-Key\",\n \"value\": \"k-root\"\n }\n}\n".into()
)]
);
assert_eq!(sent_header(&mut s, plain, "x-api-key").as_deref(), Some("k-root"));
assert_eq!(sent_auth(&mut s, plain), None);
// A request's own custom header replaces the folder's.
update(&mut s, Action::AuthEdited(own, AuthMode::Own(key("k-own"))));
assert!(s
.tab(own)
.unwrap()
.source
.contains("# @auth-header X-API-Key\nGET http://x/b\nX-API-Key: k-own\n"));
assert_eq!(sent_header(&mut s, own, "x-api-key").as_deref(), Some("k-own"));
// Switching to Bearer drops the custom header and the directive.
update(&mut s, Action::AuthEdited(own, AuthMode::Own("Bearer t".into())));
let src = &s.tab(own).unwrap().source;
assert!(!src.contains("X-API-Key") && !src.contains("@auth-header"), "{src}");
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer t"));
assert_eq!(sent_header(&mut s, own, "x-api-key"), None);
}
#[test] #[test]
fn folder_settings_files_are_reloaded_when_they_change() { fn folder_settings_files_are_reloaded_when_they_change() {
let mut s = state(); let mut s = state();
@@ -1213,7 +1276,7 @@ fn consolidate(s: &mut AppState, dir: PathBuf, target: Option<&str>) -> Consolid
s, s,
Action::ConsolidateAuth { Action::ConsolidateAuth {
dir, dir,
target: target.map(str::to_string), target: target.map(Into::into),
}, },
); );
match &s.dialog { match &s.dialog {
@@ -1229,7 +1292,7 @@ fn consolidating_adopts_the_most_common_auth_as_the_collection_default() {
let mut s = state(); let mut s = state();
let root = with_collection(&mut s, &[("a.http", MIXED)]); let root = with_collection(&mut s, &[("a.http", MIXED)]);
let plan = consolidate(&mut s, root.clone(), None); let plan = consolidate(&mut s, root.clone(), None);
assert_eq!(plan.target.as_deref(), Some("Bearer {{token}}")); assert_eq!(plan.target, Some("Bearer {{token}}".into()));
assert!(plan.set_folder); assert!(plan.set_folder);
assert_eq!( assert_eq!(
plan.choices, plan.choices,
@@ -1295,11 +1358,7 @@ fn consolidating_keeps_subfolder_overrides_and_skips_unsaved_tabs() {
update(&mut s, Action::UrlEdited(id, "http://x/edited".into())); update(&mut s, Action::UrlEdited(id, "http://x/edited".into()));
let plan = consolidate(&mut s, root.clone(), Some("Basic ignored")); let plan = consolidate(&mut s, root.clone(), Some("Basic ignored"));
assert_eq!( assert_eq!(plan.target, Some("Bearer root".into()), "the folder's own auth wins");
plan.target.as_deref(),
Some("Bearer root"),
"the folder's own auth wins"
);
assert!(!plan.set_folder && plan.choices.is_empty()); assert!(!plan.set_folder && plan.choices.is_empty());
let own: Vec<(&str, bool)> = plan let own: Vec<(&str, bool)> = plan
.own .own
+25 -24
View File
@@ -20,6 +20,7 @@ use crate::action::Action;
use crate::history::{self, HistoryEntry}; use crate::history::{self, HistoryEntry};
use crate::settings::Settings; use crate::settings::Settings;
use crate::state::{prepare_body, TabId}; use crate::state::{prepare_body, TabId};
use crate::strings as txt;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileOp { pub enum FileOp {
@@ -166,7 +167,7 @@ impl Runner {
self.handle.spawn(async move { self.handle.spawn(async move {
let settings = match tokio::fs::read_to_string(paths.settings_file()).await { let settings = match tokio::fs::read_to_string(paths.settings_file()).await {
Ok(text) => Settings::from_toml(&text).unwrap_or_else(|e| { Ok(text) => Settings::from_toml(&text).unwrap_or_else(|e| {
out.send(Action::Error(format!("settings.toml: {e}"))); out.send(Action::Error(txt::msg::settings_file(e)));
Settings::default() Settings::default()
}), }),
Err(_) => Settings::default(), Err(_) => Settings::default(),
@@ -278,15 +279,15 @@ impl Runner {
let existing = tokio::fs::read_to_string(&path).await.unwrap_or_default(); let existing = tokio::fs::read_to_string(&path).await.unwrap_or_default();
let text = format!("{existing}{}", env::gitignore_addition(&existing)); let text = format!("{existing}{}", env::gitignore_addition(&existing));
match tokio::fs::write(&path, text).await { match tokio::fs::write(&path, text).await {
Ok(()) => out.send(Action::Info(format!("Added {} to .gitignore", env::PRIVATE_FILE))), Ok(()) => out.send(Action::Info(txt::msg::added_to_gitignore(env::PRIVATE_FILE))),
Err(e) => out.send(Action::Error(format!("{}: {e}", path.display()))), Err(e) => out.send(Action::Error(txt::msg::file_error(path.display(), e))),
} }
}); });
} }
Effect::PickCollectionFolder => { Effect::PickCollectionFolder => {
self.handle.spawn(async move { self.handle.spawn(async move {
if let Some(dir) = rfd::AsyncFileDialog::new() if let Some(dir) = rfd::AsyncFileDialog::new()
.set_title("Open collection folder") .set_title(txt::pick::OPEN_COLLECTION)
.pick_folder() .pick_folder()
.await .await
{ {
@@ -297,8 +298,8 @@ impl Runner {
Effect::PickSaveTarget(tab) => { Effect::PickSaveTarget(tab) => {
self.handle.spawn(async move { self.handle.spawn(async move {
if let Some(f) = rfd::AsyncFileDialog::new() if let Some(f) = rfd::AsyncFileDialog::new()
.set_title("Save request to .http file") .set_title(txt::pick::SAVE_REQUEST)
.add_filter("HTTP request files", &["http", "rest"]) .add_filter(txt::pick::HTTP_FILTER, &["http", "rest"])
.set_file_name("requests.http") .set_file_name("requests.http")
.save_file() .save_file()
.await .await
@@ -312,7 +313,7 @@ impl Runner {
Effect::PickBodyFile(tab) => { Effect::PickBodyFile(tab) => {
self.handle.spawn(async move { self.handle.spawn(async move {
if let Some(f) = rfd::AsyncFileDialog::new() if let Some(f) = rfd::AsyncFileDialog::new()
.set_title("Request body file") .set_title(txt::pick::BODY_FILE)
.pick_file() .pick_file()
.await .await
{ {
@@ -323,8 +324,8 @@ impl Runner {
Effect::PickCaFile => { Effect::PickCaFile => {
self.handle.spawn(async move { self.handle.spawn(async move {
if let Some(f) = rfd::AsyncFileDialog::new() if let Some(f) = rfd::AsyncFileDialog::new()
.set_title("CA certificate bundle (PEM)") .set_title(txt::pick::CA_FILE)
.add_filter("PEM", &["pem", "crt", "cer"]) .add_filter(txt::pick::PEM_FILTER, &["pem", "crt", "cer"])
.pick_file() .pick_file()
.await .await
{ {
@@ -335,15 +336,15 @@ impl Runner {
Effect::PickPostmanImport => { Effect::PickPostmanImport => {
self.handle.spawn(async move { self.handle.spawn(async move {
let Some(coll) = rfd::AsyncFileDialog::new() let Some(coll) = rfd::AsyncFileDialog::new()
.set_title("Postman collection (v2.1) to import") .set_title(txt::pick::POSTMAN_FILE)
.add_filter("Postman collection", &["json"]) .add_filter(txt::pick::POSTMAN_FILTER, &["json"])
.pick_file() .pick_file()
.await .await
else { else {
return; return;
}; };
let Some(out_dir) = rfd::AsyncFileDialog::new() let Some(out_dir) = rfd::AsyncFileDialog::new()
.set_title("Folder to write the .http files to") .set_title(txt::pick::IMPORT_TARGET)
.pick_folder() .pick_folder()
.await .await
else { else {
@@ -357,14 +358,14 @@ impl Runner {
files, files,
warnings, warnings,
}), }),
Err(e) => out.send(Action::Error(format!("Postman import failed: {e}"))), Err(e) => out.send(Action::Error(txt::msg::postman_failed(e))),
} }
}); });
} }
Effect::SaveResponseBody { body, suggested_name } => { Effect::SaveResponseBody { body, suggested_name } => {
self.handle.spawn(async move { self.handle.spawn(async move {
let Some(f) = rfd::AsyncFileDialog::new() let Some(f) = rfd::AsyncFileDialog::new()
.set_title("Save response body") .set_title(txt::pick::SAVE_RESPONSE)
.set_file_name(&suggested_name) .set_file_name(&suggested_name)
.save_file() .save_file()
.await .await
@@ -377,8 +378,8 @@ impl Runner {
BodyStore::TempFile(p) => tokio::fs::copy(&**p, &path).await.map(|_| ()), BodyStore::TempFile(p) => tokio::fs::copy(&**p, &path).await.map(|_| ()),
}; };
match r { match r {
Ok(()) => out.send(Action::Info(format!("Saved {}", path.display()))), Ok(()) => out.send(Action::Info(txt::msg::saved(path.display()))),
Err(e) => out.send(Action::Error(format!("{}: {e}", path.display()))), Err(e) => out.send(Action::Error(txt::msg::file_error(path.display(), e))),
} }
}); });
} }
@@ -414,7 +415,7 @@ impl Runner {
self.handle.spawn(async move { self.handle.spawn(async move {
let _ = tokio::fs::create_dir_all(&paths.config_dir).await; let _ = tokio::fs::create_dir_all(&paths.config_dir).await;
if let Err(e) = tokio::fs::write(paths.settings_file(), s.to_toml()).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}"))); out.send(Action::Error(txt::msg::settings_save_failed(e)));
} }
}); });
} }
@@ -443,13 +444,13 @@ impl Runner {
Ok(w) => w, Ok(w) => w,
Err(e) => { Err(e) => {
self.outbox self.outbox
.send(Action::Error(format!("Cannot watch {}: {e}", root.display()))); .send(Action::Error(txt::msg::cannot_watch(root.display(), e)));
return; return;
} }
}; };
if let Err(e) = watcher.watch(&root, RecursiveMode::Recursive) { if let Err(e) = watcher.watch(&root, RecursiveMode::Recursive) {
self.outbox self.outbox
.send(Action::Error(format!("Cannot watch {}: {e}", root.display()))); .send(Action::Error(txt::msg::cannot_watch(root.display(), e)));
return; return;
} }
watchers.insert(root.clone(), watcher); watchers.insert(root.clone(), watcher);
@@ -536,18 +537,18 @@ async fn run_file_op(op: &FileOp) -> Result<(), String> {
Ok(()) => tokio::fs::rename(&tmp, p).await, Ok(()) => tokio::fs::rename(&tmp, p).await,
Err(e) => Err(e), Err(e) => Err(e),
} }
.map_err(|e| format!("{}: {e}", p.display())) .map_err(|e| txt::msg::file_error(p.display(), e))
} }
FileOp::Delete(p) => tokio::fs::remove_file(p) FileOp::Delete(p) => tokio::fs::remove_file(p)
.await .await
.map_err(|e| format!("{}: {e}", p.display())), .map_err(|e| txt::msg::file_error(p.display(), e)),
FileOp::Rename(a, b) => { FileOp::Rename(a, b) => {
if tokio::fs::try_exists(b).await.unwrap_or(false) { if tokio::fs::try_exists(b).await.unwrap_or(false) {
return Err(format!("{} already exists", b.display())); return Err(txt::msg::already_exists(b.display()));
} }
tokio::fs::rename(a, b) tokio::fs::rename(a, b)
.await .await
.map_err(|e| format!("{}: {e}", a.display())) .map_err(|e| txt::msg::file_error(a.display(), e))
} }
}; };
tracing::debug!(?op, ok = r.is_ok(), "file op"); tracing::debug!(?op, ok = r.is_ok(), "file op");
@@ -560,7 +561,7 @@ async fn import_postman(coll: &Path, out_dir: &Path) -> Result<(usize, Vec<Strin
for (rel, _) in &imp.files { for (rel, _) in &imp.files {
let p = out_dir.join(rel); let p = out_dir.join(rel);
if tokio::fs::try_exists(&p).await.unwrap_or(false) { if tokio::fs::try_exists(&p).await.unwrap_or(false) {
return Err(format!("{} already exists; pick an empty folder", p.display())); return Err(txt::msg::pick_empty_folder(p.display()));
} }
} }
for (rel, text) in &imp.files { for (rel, text) in &imp.files {
+1
View File
@@ -11,6 +11,7 @@ pub mod effects;
pub mod history; pub mod history;
pub mod settings; pub mod settings;
pub mod state; pub mod state;
pub mod strings;
pub mod ui; pub mod ui;
pub use app::ReqliteApp; pub use app::ReqliteApp;
+12 -11
View File
@@ -9,7 +9,7 @@ use std::time::{Instant, SystemTime};
use reqlite_core::collection::Node; use reqlite_core::collection::Node;
use reqlite_core::cookies::CookieJar; use reqlite_core::cookies::CookieJar;
use reqlite_core::env::Environments; use reqlite_core::env::Environments;
use reqlite_core::folder::{self, FolderAuth, FolderSettings, InheritedAuth}; use reqlite_core::folder::{self, AuthHeader, FolderAuth, FolderSettings, InheritedAuth};
use reqlite_core::http::{BodyStore, Response}; use reqlite_core::http::{BodyStore, Response};
use reqlite_core::httpfile::{HttpFile, RequestKey}; use reqlite_core::httpfile::{HttpFile, RequestKey};
use reqlite_core::params::Param; use reqlite_core::params::Param;
@@ -18,6 +18,7 @@ use reqlite_core::{CancelToken, Request};
use crate::history::HistoryEntry; use crate::history::HistoryEntry;
use crate::settings::Settings; use crate::settings::Settings;
use crate::strings as txt;
pub type TabId = u64; pub type TabId = u64;
@@ -107,17 +108,17 @@ pub struct RequestRef {
pub struct ConsolidateAuth { pub struct ConsolidateAuth {
pub dir: PathBuf, pub dir: PathBuf,
/// The auth requests in `dir` should inherit. /// The auth requests in `dir` should inherit.
pub target: Option<String>, pub target: Option<AuthHeader>,
/// `dir` doesn't have `target` as its own setting yet; applying writes it. /// `dir` doesn't have `target` as its own setting yet; applying writes it.
pub set_folder: bool, pub set_folder: bool,
/// Values to pick `target` from (with how many requests use each), when /// Values to pick `target` from (with how many requests use each), when
/// `dir` has no auth of its own. /// `dir` has no auth of its own.
pub choices: Vec<(String, usize)>, pub choices: Vec<(AuthHeader, usize)>,
/// Requests with their own Authorization header. /// Requests with their own auth header.
pub own: Vec<OwnAuth>, pub own: Vec<OwnAuth>,
/// Requests that inherit today and would send something else once /// Requests that inherit today and would send something else once
/// `target` is set on the folder. /// `target` is set on the folder.
pub affected: Vec<(RequestRef, Option<String>)>, pub affected: Vec<(RequestRef, Option<AuthHeader>)>,
/// Give the affected requests their current auth explicitly (a header, /// Give the affected requests their current auth explicitly (a header,
/// or `# @no-auth`) so they keep sending what they send today. /// or `# @no-auth`) so they keep sending what they send today.
pub keep_affected: bool, pub keep_affected: bool,
@@ -128,9 +129,9 @@ pub struct ConsolidateAuth {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnAuth { pub struct OwnAuth {
pub request: RequestRef, pub request: RequestRef,
pub value: String, pub value: AuthHeader,
/// What the request would inherit without its header. /// What the request would inherit without its header.
pub inherits: Option<String>, pub inherits: Option<AuthHeader>,
/// Remove the header. /// Remove the header.
pub selected: bool, pub selected: bool,
} }
@@ -139,7 +140,7 @@ impl OwnAuth {
/// Removing the header keeps the request sending the same thing. /// Removing the header keeps the request sending the same thing.
pub fn same(&self) -> bool { pub fn same(&self) -> bool {
self.inherits self.inherits
.as_deref() .as_ref()
.is_some_and(|i| folder::same_auth(i, &self.value)) .is_some_and(|i| folder::same_auth(i, &self.value))
} }
} }
@@ -232,9 +233,9 @@ impl CollectionState {
/// `dir` relative to the root, for messages ("the collection" for the root). /// `dir` relative to the root, for messages ("the collection" for the root).
pub fn folder_label(&self, dir: &Path) -> String { pub fn folder_label(&self, dir: &Path) -> String {
if dir == self.root { if dir == self.root {
format!("the collection “{}”", self.name()) txt::names::collection(self.name())
} else { } else {
format!("the folder {}", self.relative(dir).display()) txt::names::folder(self.relative(dir).display())
} }
} }
} }
@@ -342,7 +343,7 @@ impl Tab {
} }
let url = self.request.url.trim(); let url = self.request.url.trim();
if url.is_empty() { if url.is_empty() {
"New request".into() txt::common::NEW_REQUEST.into()
} else { } else {
let short: String = url.chars().take(40).collect(); let short: String = url.chars().take(40).collect();
if url.chars().count() > 40 { if url.chars().count() > 40 {
+651
View File
@@ -0,0 +1,651 @@
//! Every user-visible string in the app, in one place.
//!
//! Fixed text is a `const`; text with values in it is a function returning a
//! `String`. Grouped by where it shows up. Protocol values (header names,
//! content types) and file formats are not UI strings and stay in the code.
/// Glyphs used as button labels and markers.
pub mod icon {
pub const CLOSE: &str = "×";
pub const ADD: &str = "+";
pub const RELOAD: &str = "⟳";
pub const MORE: &str = "…";
pub const DIRTY: &str = " •";
pub const IN_FLIGHT: &str = " ⏳";
pub const WARNING: &str = " ⚠";
pub const FOLDER: &str = "📁";
pub const FILE: &str = "📄";
pub const SHOW: &str = "👁";
pub const HIDE: &str = "🙈";
pub const MASKED: &str = "••••••••";
pub const MASKED_SHORT: &str = "••••";
pub const BULLET: &str = "•";
pub const NONE: &str = "—";
}
/// Words used in many places.
pub mod common {
pub const APP_NAME: &str = "reqlite";
pub const OK: &str = "OK";
pub const CANCEL: &str = "Cancel";
pub const SAVE: &str = "Save";
pub const CLOSE: &str = "Close";
pub const CLEAR: &str = "Clear";
pub const DELETE: &str = "Delete";
pub const OPEN: &str = "Open";
pub const RENAME: &str = "Rename…";
pub const REMOVE: &str = "Remove";
pub const APPLY: &str = "Apply";
pub const DISMISS: &str = "Dismiss";
pub const NONE: &str = "None";
pub const ALL: &str = "All";
pub const TEXT: &str = "Text";
pub const FILE: &str = "File";
pub const NAME: &str = "Name";
pub const VALUE: &str = "Value";
pub const SYSTEM: &str = "System";
pub const RELOAD_FROM_DISK: &str = "Reload from disk";
pub const NEW_REQUEST: &str = "New request";
pub const RENAME_REQUEST: &str = "Rename request";
pub const NEW_HTTP_FILE: &str = "New .http file";
pub const OPEN_COLLECTION_FOLDER: &str = "Open collection folder…";
pub const ENVIRONMENT_LABEL: &str = "Environment:";
pub const NO_AUTH: &str = "no auth";
/// A bulleted list item.
pub fn bullet(item: impl std::fmt::Display) -> String {
format!("{} {item}", super::icon::BULLET)
}
/// `n request` / `n requests`.
pub fn requests(n: usize) -> String {
format!("{n} request{}", if n == 1 { "" } else { "s" })
}
}
/// The menu bar, status bar and welcome screen.
pub mod main {
pub const FILE: &str = "File";
pub const NEW_TAB: &str = "New tab Ctrl+T";
pub const RECENT_COLLECTIONS: &str = "Recent collections";
pub const NONE_YET: &str = "None yet";
pub const SAVE: &str = "Save Ctrl+S";
pub const CLOSE_ALL_TABS: &str = "Close all tabs Ctrl+Shift+W";
pub const IMPORT_POSTMAN: &str = "Import Postman collection…";
pub const SETTINGS: &str = "Settings…";
pub const QUIT: &str = "Quit";
pub const VIEW: &str = "View";
pub const HISTORY: &str = "History";
pub const COOKIES: &str = "Cookies";
pub const QUICK_OPEN: &str = "Quick open… Ctrl+P";
pub const HELP: &str = "Help";
pub const ABOUT: &str = "About and shortcuts";
pub const EDIT_ENVS: &str = "Edit…";
pub const EDIT_ENVS_HOVER: &str = "Edit environments";
pub const NO_ENVIRONMENT: &str = "No environment";
pub const ENV_OWNER_HOVER: &str = "The collection of the active tab, or the one last clicked in the sidebar";
pub fn collection_environment(collection: &str) -> String {
format!("{collection} environment:")
}
pub const ORPHANED: &str = "This request is no longer in its file. Save writes it to a file you pick.";
pub const READY: &str = "Ready";
pub fn in_flight(n: usize) -> String {
format!("{n} in flight")
}
pub const WELCOME: &str = "Send HTTP requests and keep them as .http files.";
pub const WELCOME_NEW_REQUEST: &str = "New request (Ctrl+T)";
pub const WELCOME_OPEN_FOLDER: &str = "Open a collection folder…";
pub const WELCOME_TIP: &str = "Tip: paste a curl command into the URL bar to import it.";
}
/// The tab bar.
pub mod tabs {
pub const CLOSE_OTHERS: &str = "Close others";
pub const CLOSE_ALL: &str = "Close all";
pub const CLOSE_HOVER: &str = "Close (Ctrl+W)";
pub const NEW_TAB_HOVER: &str = "New tab (Ctrl+T)";
}
/// The URL bar and request editor.
pub mod request {
pub const URL_HINT: &str = "Enter a URL, or paste a curl command";
pub const CANCEL_HOVER: &str = "Stop the request";
pub const SEND: &str = "Send";
pub const SEND_HOVER: &str = "Send (Ctrl+Enter)";
pub const SAVE_DIRTY: &str = "Save •";
pub const SAVE_HOVER: &str = "Save to the .http file (Ctrl+S)";
pub const COPY_AS_CURL: &str = "Copy as curl";
pub const COPY_AS_HTTP: &str = "Copy as .http";
pub const FOLLOW_REDIRECTS: &str = "Follow redirects";
pub fn params_tab(n: usize) -> String {
format!("Params ({n})")
}
pub fn headers_tab(n: usize) -> String {
format!("Headers ({n})")
}
pub const BODY_TAB: &str = "Body";
pub const BODY_TAB_SET: &str = "Body •";
pub const AUTH_TAB: &str = "Auth";
pub const SOURCE_TAB: &str = "Source";
pub const SOURCE_TAB_ERROR: &str = "Source ⚠";
pub const KEY: &str = "Key";
pub const ADD_PARAMETER: &str = "Add parameter";
pub const PARAMS_NOTE: &str = "Parameters are kept in the URL, exactly as typed.";
pub const ADD_HEADER: &str = "Add header";
pub const DISABLED_HEADER_HOVER: &str = "Disabled headers are kept as `# Name: value` comments";
pub const SOURCE_NOTE: &str =
"The request as it is stored in the .http file. Comments and response handlers are kept; scripts are never run.";
}
/// The request body editor.
pub mod body {
pub const MULTIPART_FORM: &str = "Multipart form";
pub const NO_BODY: &str = "This request has no body.";
pub const CONTENT_TYPE_LABEL: &str = "Content-Type:";
pub const JSON: &str = "JSON";
pub const XML: &str = "XML";
pub const FORM: &str = "Form";
pub const FORMAT: &str = "Format";
pub const FORMAT_HOVER: &str = "Pretty-print the JSON";
pub fn too_large(kb: usize) -> String {
format!(
"The body is {kb} KB, too large to edit here. Edit it in the .http file, or move it to a file (`< ./body.json`)."
)
}
pub const FILE_LABEL: &str = "File:";
pub const BROWSE: &str = "Browse…";
pub const SUBSTITUTE: &str = "Replace {{variables}} in the file (`<@`)";
pub const RELATIVE_PATHS: &str = "Relative paths are relative to the .http file.";
pub const PART_KIND: &str = "Kind";
pub const PART_VALUE: &str = "Value / file";
pub const PART_CONTENT_TYPE: &str = "Content-Type";
pub const ADD_FIELD: &str = "Add field";
}
/// The Auth tab and the folder auth dialog.
pub mod auth {
pub const TYPE_LABEL: &str = "Type:";
pub const INHERIT: &str = "Inherit";
pub const NOT_SET: &str = "Not set";
pub const BASIC: &str = "Basic";
pub const BEARER: &str = "Bearer token";
pub const CUSTOM_HEADER: &str = "Custom header";
pub const HEADER_NAME: &str = "Header";
pub const VALUE: &str = "Value";
pub const CUSTOM_NOTE: &str =
"Sent as `Header: value` instead of Authorization; a request marks it with `# @auth-header Header`.";
pub const USERNAME: &str = "Username";
pub const PASSWORD: &str = "Password";
pub const BASIC_NOTE: &str =
"Written as `Authorization: Basic user password`; it is base64-encoded when sent, like JetBrains does.";
pub const TOKEN: &str = "Token";
pub const HEADER_VALUE: &str = "Header value";
pub const NO_AUTH_SET: &str = "No Authorization header, not even the folder's (`# @no-auth`).";
pub const CUSTOM: &str = "Custom Authorization header:";
pub const SECRETS_NOTE: &str = "Auth is just a header; put secrets in the private env file.";
pub const NOT_IN_COLLECTION: &str = "Not in a collection, so there is nothing to inherit.";
pub const USES: &str = "Uses";
pub fn from_folder(folder: &str) -> String {
format!("from {folder}.")
}
pub fn folder_sends_none(folder: &str) -> String {
format!("No auth: {folder} is set to send none.")
}
pub const NO_FOLDER_AUTH: &str = "No auth: no folder above this request has auth set.";
pub const FOLDER_AUTH_BUTTON: &str = "Folder auth…";
pub const COLLECTION_DEFAULT_BUTTON: &str = "Collection default…";
pub const COLLECTION_DEFAULT_HOVER: &str = "Auth for every request in the collection that doesn't set its own";
pub const UNTITLED_NOTE: &str = "Untitled requests use the collection default.";
pub const COLLECTION_DEFAULT_TITLE: &str = "Collection default auth";
pub const FOLDER_AUTH_TITLE: &str = "Folder auth";
pub const ROOT_NOT_SET: &str = "Requests that don't set auth send none.";
pub fn parent_uses(value: &str, folder: &str) -> String {
format!("Uses `{value}` from {folder}.")
}
pub fn parent_none(folder: &str) -> String {
format!("No auth, as set on {folder}.")
}
pub const NO_PARENT_AUTH: &str = "No auth: no parent folder has auth set.";
pub const FOLDER_NONE: &str = "Requests here send no auth unless they set their own.";
pub const FOLDER_NOTE: &str =
"Used by requests in this folder and its subfolders that have no Authorization header of their own. \
Saved in .reqlite/folder.json (other .http tools ignore it).";
}
/// The "Consolidate auth" dialog and its result.
pub mod consolidate {
pub const TITLE: &str = "Consolidate auth";
pub fn intro(folder: &str) -> String {
format!(
"Let requests in {folder} inherit one shared auth instead of each carrying its own Authorization header."
)
}
pub const NOTHING: &str = "None of these requests has an Authorization header, and there is no auth to inherit.";
pub const SHARED_AUTH: &str = "Shared auth:";
pub fn choice(value: &str, n: usize) -> String {
format!("{value} ({})", super::common::requests(n))
}
pub fn will_save(folder: &str) -> String {
format!("It will be saved as the auth of {folder}.")
}
pub fn already_uses(folder: &str) -> String {
format!("{folder} already uses it.")
}
pub const NO_OWN: &str = "No request here has its own Authorization header.";
pub const REMOVE_FROM: &str = "Remove the Authorization header from:";
pub const MATCHING: &str = "Matching";
pub const MATCHING_HOVER: &str = "Only those that send the same thing";
pub fn would_send(has: &str, would: &str) -> String {
format!("has `{has}`; would send `{would}` instead")
}
pub fn affected(n: usize, target: &str) -> String {
format!("{n} request(s) without a header of their own would start sending `{target}`:")
}
pub fn affected_item(label: &str, now: &str) -> String {
format!("{} {label} (now: {now})", super::icon::BULLET)
}
pub const KEEP_AFFECTED: &str = "Keep what they send today";
pub const KEEP_AFFECTED_HOVER: &str = "Gives them their current header, or `# @no-auth`";
pub fn skipped_dirty(labels: &str) -> String {
format!("Skipped, because their tabs have unsaved edits: {labels}")
}
// The status message after applying; parts are joined with ", ".
pub fn set_folder(target: &str) -> String {
format!("set the folder auth to `{target}`")
}
pub fn dropped(n: usize) -> String {
format!("{n} request(s) now inherit it")
}
pub fn pinned(n: usize) -> String {
format!("{n} request(s) keep their auth explicitly")
}
pub fn skipped(n: usize) -> String {
format!("{n} with unsaved edits skipped")
}
pub const NOTHING_TO_CHANGE: &str = "Auth: nothing to change";
}
/// The response panel.
pub mod response {
pub fn sending(secs: f32) -> String {
format!("Sending… {secs:.1} s")
}
pub const EMPTY: &str = "Send the request to see the response here.";
pub fn millis(ms: u128) -> String {
format!("{ms} ms")
}
pub fn millis_f(ms: f32) -> String {
format!("{ms:.1} ms")
}
pub const SPILLED: &str = "(stored in a temp file)";
pub const SAVE_TO_FILE: &str = "Save to file…";
pub const COPY_BODY: &str = "Copy body";
pub const BODY_TAB: &str = "Body";
pub fn headers_tab(n: usize) -> String {
format!("Headers ({n})")
}
pub const TIMINGS_TAB: &str = "Timings";
pub fn final_url(url: &str) -> String {
format!("Final URL: {url}")
}
pub const PREPARING: &str = "Preparing the body…";
pub const NO_BODY: &str = "No body.";
pub const PRETTY: &str = "Pretty";
pub const RAW: &str = "Raw";
pub const BINARY: &str = "Binary body, shown as hex. Use “Save to file” to keep it.";
pub const TRUNCATED: &str = "Only the start of this large body is shown.";
pub const FIND_BUTTON: &str = "🔍 Find";
pub const FIND_HOVER: &str = "Search the body (Ctrl+F)";
pub const FIND_HINT: &str = "Find";
pub const NO_MATCHES: &str = "no matches";
pub const PREV: &str = "Prev";
pub const NEXT: &str = "Next";
pub const TOTAL: &str = "Total";
}
/// The collection tree.
pub mod sidebar {
pub const COLLECTIONS: &str = "Collections";
pub const OPEN: &str = "Open…";
pub const OPEN_HOVER: &str = "Open another collection folder";
pub const NO_COLLECTION: &str = "No collection open.";
pub const WHAT_IS_A_COLLECTION: &str = "A collection is a folder of .http files.";
pub const OPEN_FOLDER: &str = "Open folder…";
pub const RECENT: &str = "Recent";
pub fn collection_hover(root: impl std::fmt::Display) -> String {
format!("{root}\nClick to use its environments for new tabs")
}
pub const NEW_HTTP_FILE: &str = "New .http file…";
pub const DEFAULT_AUTH: &str = "Default auth…";
pub const CLOSE_COLLECTION: &str = "Close collection";
pub const CLOSE_COLLECTION_HOVER: &str = "Close this collection";
pub const PRIVATE_NOT_IGNORED: &str =
"http-client.private.env.json is not in .gitignore, so secrets could be committed.";
pub const ADD_TO_GITIGNORE: &str = "Add to .gitignore";
pub fn env_error(e: &str) -> String {
format!("Environments: {e}")
}
pub fn folder_error(e: &str) -> String {
format!("Folder settings: {e}")
}
pub const NO_FILES: &str = "No .http files yet.";
pub const CREATE_ONE: &str = "Create one";
pub const AUTH_HOVER: &str = "Auth for the requests in here that don't set their own";
pub const CONSOLIDATE: &str = "Consolidate auth…";
pub const CONSOLIDATE_HOVER: &str = "Make requests in here inherit one shared auth";
pub fn folder(name: &str) -> String {
format!("{} {name}", super::icon::FOLDER)
}
pub fn file(name: &str) -> String {
format!("{} {name}", super::icon::FILE)
}
pub fn folder_auth_hover(value: &str) -> String {
format!("Auth: {value}")
}
pub const DUPLICATE: &str = "Duplicate";
pub const MOVE_TO: &str = "Move to";
pub const DELETE: &str = "Delete…";
pub const NO_REQUESTS: &str = "(no requests)";
pub const RENAME_FILE: &str = "Rename file…";
pub const RENAME_FILE_TITLE: &str = "Rename file";
pub const DUPLICATE_FILE: &str = "Duplicate file";
pub const DELETE_FILE: &str = "Delete file…";
pub const NO_URL: &str = "(no URL)";
}
/// Modal dialogs.
pub mod dialog {
pub const UNSAVED: &str = "Unsaved changes";
pub fn tab_unsaved(title: &str) -> String {
format!("“{title}” has changes that are not saved.")
}
pub const SAVE_AND_CLOSE: &str = "Save and close";
pub const DISCARD: &str = "Discard";
pub fn tabs_unsaved(n: usize) -> String {
format!("{n} tab(s) have changes that are not saved:")
}
pub const DISCARD_AND_CLOSE: &str = "Discard and close";
pub const KEEP_OPEN: &str = "Keep them open";
pub const QUIT_TITLE: &str = "Quit reqlite?";
pub fn quit_unsaved(n: usize) -> String {
format!("{n} tab(s) have unsaved changes; they will be lost.")
}
pub const QUIT_WITHOUT_SAVING: &str = "Quit without saving";
pub const CONFLICT_TITLE: &str = "File changed on disk";
pub fn conflict(path: impl std::fmt::Display) -> String {
format!("{path} was changed outside reqlite, and this tab has unsaved edits.")
}
pub const RELOAD_HOVER: &str = "Discard my edits";
pub const KEEP_MINE: &str = "Keep my version";
pub const KEEP_MINE_HOVER: &str = "Saving will overwrite this request in the new file";
pub const DELETE_TITLE: &str = "Delete?";
pub fn delete_request(label: &str) -> String {
format!("the request “{label}”")
}
pub fn delete_file(path: impl std::fmt::Display) -> String {
format!("the file {path}")
}
pub fn delete_body(what: &str) -> String {
format!("This deletes {what} from disk.")
}
pub const IMPORT_TITLE: &str = "Import finished";
pub fn import_wrote(files: usize, root: impl std::fmt::Display) -> String {
format!("Wrote {files} .http file(s) to {root}.")
}
pub fn warnings(n: usize) -> String {
format!("{n} warning(s):")
}
pub const NEW_ENVIRONMENT: &str = "New environment";
}
/// The Settings window.
pub mod settings {
pub const TITLE: &str = "Settings";
pub const TIMEOUT: &str = "Default timeout";
pub const SECONDS_SUFFIX: &str = " s";
pub const TIMEOUT_NOTE: &str = "0 = none; `# @timeout` wins";
pub const PROXY: &str = "Proxy";
pub const MANUAL: &str = "Manual";
pub const PROXY_HINT: &str = "http://user:pass@proxy:3128";
pub const TLS: &str = "TLS";
pub const VERIFY_TLS: &str = "Verify certificates";
pub const SYSTEM_STORE: &str = "System store only";
pub const ADD_CA: &str = "Add CA file…";
pub const THEME: &str = "Theme";
pub const LIGHT: &str = "Light";
pub const DARK: &str = "Dark";
pub const FONT_SIZE: &str = "Font size";
pub fn percent(v: f64) -> String {
format!("{:.0}%", v * 100.0)
}
pub const PARALLEL: &str = "Parallel requests";
pub const AT_ONCE: &str = "at once";
pub const HISTORY_SIZE: &str = "History size";
}
/// The History window.
pub mod history {
pub const TITLE: &str = "History";
pub fn count(n: usize) -> String {
format!("{n} request(s)")
}
pub const ERR: &str = "ERR";
pub fn hover(url: &str, ms: u64, env: Option<&str>) -> String {
format!(
"{url}\n{ms} ms{}",
env.map(|v| format!(", env {v}")).unwrap_or_default()
)
}
pub const RESTORE_HOVER: &str = "Restore into a new tab";
}
/// The Cookies window.
pub mod cookies {
pub const TITLE: &str = "Cookies";
pub const NOTE: &str = "Cookies are kept in memory per collection; `# @no-cookie-jar` skips them.";
pub const EMPTY: &str = "No cookies yet.";
pub const CLEAR_ALL: &str = "Clear all";
pub const DOMAIN: &str = "Domain";
pub const PATH: &str = "Path";
}
/// The About window.
pub mod about {
pub const TITLE: &str = "About reqlite";
pub fn heading(version: &str) -> String {
format!("reqlite {version}")
}
pub const TAGLINE: &str = "A small API client for .http files.";
pub const SHORTCUTS: &str = "Shortcuts";
pub const KEYS: [(&str, &str); 8] = [
("Ctrl+Enter", "Send"),
("Ctrl+S", "Save"),
("Ctrl+T", "New tab"),
("Ctrl+W", "Close tab"),
("Ctrl+Shift+W", "Close all tabs"),
("Ctrl+L", "Focus the URL bar"),
("Ctrl+P", "Quick-open a request"),
("Ctrl+F", "Find in the response"),
];
}
/// The environment editor window.
pub mod env {
pub fn title(collection: &str, dirty: bool) -> String {
format!(
"Environments: {collection}{}",
if dirty { super::icon::DIRTY } else { "" }
)
}
pub const SHARED: &str = "$shared (all environments)";
pub const NEW: &str = "New…";
pub const PRIVATE: &str = "Private";
pub const STRUCTURED: &str = "(object; edit the JSON file)";
pub const PRIVATE_HOVER: &str = "Stored in http-client.private.env.json (keep it out of git)";
pub const SHOW_HIDE_HOVER: &str = "Show / hide";
pub const ADD_VARIABLE: &str = "Add variable";
pub const SAVE_NOTE: &str = "Writes http-client.env.json and http-client.private.env.json.";
}
/// The quick-open popup.
pub mod quick_open {
pub const TITLE: &str = "Open request";
pub const HINT: &str = "Type to find a request…";
pub const NO_MATCHES: &str = "No matching requests";
}
/// Variable hover text in editors.
pub mod vars {
pub fn undefined(name: &str) -> String {
format!("{{{{{name}}}}} is not defined in the selected environment")
}
pub fn builtin(name: &str) -> String {
format!("{{{{{name}}}}}: built-in dynamic value")
}
pub const FROM_PRIVATE_ENV: &str = "private env";
pub const FROM_ENV: &str = "env";
pub const FROM_FILE: &str = "file variable";
pub const FROM_BUILTIN: &str = "built-in";
pub fn resolved(value: &str, result: &str) -> String {
format!("{value} -> {result}")
}
pub fn hover(name: &str, shown: &str, from: &str) -> String {
format!("{name} = {shown} ({from})")
}
}
/// Sizes.
pub mod units {
pub fn bytes(n: u64) -> String {
format!("{n} B")
}
pub fn kilobytes(kb: f64) -> String {
format!("{kb:.1} KB")
}
pub fn megabytes(mb: f64) -> String {
format!("{mb:.1} MB")
}
}
/// Native file dialogs.
pub mod pick {
pub const OPEN_COLLECTION: &str = "Open collection folder";
pub const SAVE_REQUEST: &str = "Save request to .http file";
pub const HTTP_FILTER: &str = "HTTP request files";
pub const BODY_FILE: &str = "Request body file";
pub const CA_FILE: &str = "CA certificate bundle (PEM)";
pub const PEM_FILTER: &str = "PEM";
pub const POSTMAN_FILE: &str = "Postman collection (v2.1) to import";
pub const POSTMAN_FILTER: &str = "Postman collection";
pub const IMPORT_TARGET: &str = "Folder to write the .http files to";
pub const SAVE_RESPONSE: &str = "Save response body";
}
/// Status bar messages and errors shown in a tab.
pub mod msg {
use std::fmt::Display;
pub const NO_REQUEST_IN_TEXT: &str = "No request in that text";
pub const CURL_IMPORTED: &str = "Imported the curl command";
pub fn curl_import_failed(e: impl Display) -> String {
format!("Could not import curl command: {e}")
}
pub const NO_REQUEST_LINE: &str = "No request line found";
pub fn not_one_request(n: usize) -> String {
format!("The source must contain exactly one request (found {n})")
}
pub const CANCELLED: &str = "Cancelled";
pub fn overlaps(root: impl Display, other: impl Display) -> String {
format!("{root} overlaps the open collection {other}; close that one first")
}
pub fn collection_failed(e: impl Display) -> String {
format!("Could not open the collection: {e}")
}
pub fn already_exists(path: impl Display) -> String {
format!("{path} already exists")
}
pub fn pick_empty_folder(path: impl Display) -> String {
format!("{path} already exists; pick an empty folder")
}
pub const NEED_COLLECTION_FOR_ENVS: &str =
"Open a collection folder first; environments live next to the .http files";
pub const NEED_COLLECTION_FOR_QUICK_OPEN: &str = "Open a collection to quick-open its requests";
pub const COPIED_CURL: &str = "Copied as curl";
pub fn curl_failed(e: impl Display) -> String {
format!("Cannot build the curl command: {e}")
}
pub const COPIED_HTTP: &str = "Copied as .http";
pub fn fix_source(e: impl Display) -> String {
format!("Fix the source first: {e}")
}
pub fn cannot_save(e: impl Display) -> String {
format!("Cannot save: {e}")
}
pub fn not_loaded(path: impl Display) -> String {
format!("{path} is not loaded")
}
pub const NO_LONGER_IN_FILE: &str = "The request is no longer in its file; use Save As";
pub fn invalid_json(e: impl Display) -> String {
format!("Not valid JSON: {e}")
}
pub fn settings_file(e: impl Display) -> String {
format!("settings.toml: {e}")
}
pub fn added_to_gitignore(file: &str) -> String {
format!("Added {file} to .gitignore")
}
/// An error about a particular file.
pub fn file_error(path: impl Display, e: impl Display) -> String {
format!("{path}: {e}")
}
pub fn postman_failed(e: impl Display) -> String {
format!("Postman import failed: {e}")
}
pub fn saved(path: impl Display) -> String {
format!("Saved {path}")
}
pub fn settings_save_failed(e: impl Display) -> String {
format!("Could not save settings: {e}")
}
pub fn cannot_watch(path: impl Display, e: impl Display) -> String {
format!("Cannot watch {path}: {e}")
}
}
/// Names the app gives new things (written to files, so users see them).
pub mod names {
pub const REQUEST: &str = "Request";
pub fn copy_of(base: &str) -> String {
format!("{base} copy")
}
pub fn file_copy(stem: &str, ext: &str) -> String {
format!("{stem} copy.{ext}")
}
pub fn file_copy_n(stem: &str, n: usize, ext: &str) -> String {
format!("{stem} copy {n}.{ext}")
}
pub fn numbered(base: &str, n: usize) -> String {
format!("{base} {n}")
}
pub fn collection(name: &str) -> String {
format!("the collection “{name}”")
}
pub fn folder(path: impl std::fmt::Display) -> String {
format!("the folder {path}")
}
}
+57 -51
View File
@@ -10,6 +10,7 @@ use egui::{Context, Key, KeyboardShortcut, Modifiers, RichText, Ui};
use crate::action::Action; use crate::action::Action;
use crate::state::{AppState, QuickOpen}; use crate::state::{AppState, QuickOpen};
use crate::strings as txt;
use widgets::VarCtx; use widgets::VarCtx;
pub fn draw(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) { pub fn draw(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
@@ -32,10 +33,7 @@ pub fn draw(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
is_private: &is_private, is_private: &is_private,
}; };
if tab.orphaned { if tab.orphaned {
ui.label( ui.label(RichText::new(txt::main::ORPHANED).color(ui.visuals().warn_fg_color));
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); request::url_bar(ui, state, tab, &vars, acts);
ui.add_space(4.0); ui.add_space(4.0);
@@ -101,16 +99,16 @@ fn shortcuts(ctx: &Context, state: &AppState, acts: &mut Vec<Action>) {
fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) { fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
egui::MenuBar::new().ui(ui, |ui| { egui::MenuBar::new().ui(ui, |ui| {
ui.menu_button("File", |ui| { ui.menu_button(txt::main::FILE, |ui| {
if ui.button("New tab Ctrl+T").clicked() { if ui.button(txt::main::NEW_TAB).clicked() {
acts.push(Action::NewTab); acts.push(Action::NewTab);
ui.close(); ui.close();
} }
if ui.button("Open collection folder…").clicked() { if ui.button(txt::common::OPEN_COLLECTION_FOLDER).clicked() {
acts.push(Action::PickCollection); acts.push(Action::PickCollection);
ui.close(); ui.close();
} }
ui.menu_button("Recent collections", |ui| { ui.menu_button(txt::main::RECENT_COLLECTIONS, |ui| {
for p in &state.settings.recent_collections { for p in &state.settings.recent_collections {
if ui.button(p.display().to_string()).clicked() { if ui.button(p.display().to_string()).clicked() {
acts.push(Action::OpenCollection(p.clone())); acts.push(Action::OpenCollection(p.clone()));
@@ -118,62 +116,55 @@ fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
} }
} }
if state.settings.recent_collections.is_empty() { if state.settings.recent_collections.is_empty() {
ui.label(RichText::new("None yet").weak()); ui.label(RichText::new(txt::main::NONE_YET).weak());
} }
}); });
ui.separator(); ui.separator();
let has_tab = state.active.is_some(); let has_tab = state.active.is_some();
if ui if ui.add_enabled(has_tab, egui::Button::new(txt::main::SAVE)).clicked() {
.add_enabled(has_tab, egui::Button::new("Save Ctrl+S"))
.clicked()
{
acts.push(Action::Save(state.active.unwrap())); acts.push(Action::Save(state.active.unwrap()));
ui.close(); ui.close();
} }
if ui if ui
.add_enabled(has_tab, egui::Button::new("Close all tabs Ctrl+Shift+W")) .add_enabled(has_tab, egui::Button::new(txt::main::CLOSE_ALL_TABS))
.clicked() .clicked()
{ {
acts.push(Action::CloseTabs(state.tabs.iter().map(|t| t.id).collect())); acts.push(Action::CloseTabs(state.tabs.iter().map(|t| t.id).collect()));
ui.close(); ui.close();
} }
ui.separator(); ui.separator();
if ui.button("Import Postman collection…").clicked() { if ui.button(txt::main::IMPORT_POSTMAN).clicked() {
acts.push(Action::ImportPostman); acts.push(Action::ImportPostman);
ui.close(); ui.close();
} }
ui.label( ui.label(RichText::new(txt::main::WELCOME_TIP).small().weak());
RichText::new("Tip: paste a curl command into the URL bar to import it.")
.small()
.weak(),
);
ui.separator(); ui.separator();
if ui.button("Settings…").clicked() { if ui.button(txt::main::SETTINGS).clicked() {
acts.push(Action::SetWindows(crate::state::Windows { acts.push(Action::SetWindows(crate::state::Windows {
settings: true, settings: true,
..state.windows ..state.windows
})); }));
ui.close(); ui.close();
} }
if ui.button("Quit").clicked() { if ui.button(txt::main::QUIT).clicked() {
acts.push(Action::CloseRequested); acts.push(Action::CloseRequested);
ui.close(); ui.close();
} }
}); });
ui.menu_button("View", |ui| { ui.menu_button(txt::main::VIEW, |ui| {
let mut w = state.windows; let mut w = state.windows;
ui.checkbox(&mut w.history, "History"); ui.checkbox(&mut w.history, txt::main::HISTORY);
ui.checkbox(&mut w.cookies, "Cookies"); ui.checkbox(&mut w.cookies, txt::main::COOKIES);
if w != state.windows { if w != state.windows {
acts.push(Action::SetWindows(w)); acts.push(Action::SetWindows(w));
} }
if ui.button("Quick open… Ctrl+P").clicked() { if ui.button(txt::main::QUICK_OPEN).clicked() {
acts.push(Action::QuickOpen(Some(QuickOpen::default()))); acts.push(Action::QuickOpen(Some(QuickOpen::default())));
ui.close(); ui.close();
} }
}); });
ui.menu_button("Help", |ui| { ui.menu_button(txt::main::HELP, |ui| {
if ui.button("About and shortcuts").clicked() { if ui.button(txt::main::ABOUT).clicked() {
acts.push(Action::SetWindows(crate::state::Windows { acts.push(Action::SetWindows(crate::state::Windows {
about: true, about: true,
..state.windows ..state.windows
@@ -185,17 +176,24 @@ fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
// Environment picker on the right. // Environment picker on the right.
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if let Some(c) = state.current_collection() { if let Some(c) = state.current_collection() {
if ui.button("Edit…").on_hover_text("Edit environments").clicked() { if ui
.button(txt::main::EDIT_ENVS)
.on_hover_text(txt::main::EDIT_ENVS_HOVER)
.clicked()
{
acts.push(Action::OpenEnvEditor); acts.push(Action::OpenEnvEditor);
} }
let names = c.envs.names(); let names = c.envs.names();
let label = c.selected_env.clone().unwrap_or_else(|| "No environment".into()); let label = c
.selected_env
.clone()
.unwrap_or_else(|| txt::main::NO_ENVIRONMENT.into());
egui::ComboBox::from_id_salt("env-picker") egui::ComboBox::from_id_salt("env-picker")
.selected_text(label) .selected_text(label)
.width(150.0) .width(150.0)
.show_ui(ui, |ui| { .show_ui(ui, |ui| {
if ui if ui
.selectable_label(c.selected_env.is_none(), "No environment") .selectable_label(c.selected_env.is_none(), txt::main::NO_ENVIRONMENT)
.clicked() .clicked()
{ {
acts.push(Action::SelectEnv(None)); acts.push(Action::SelectEnv(None));
@@ -208,10 +206,10 @@ fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
}); });
// With several collections, say whose environments these are. // With several collections, say whose environments these are.
if state.collections.len() > 1 { if state.collections.len() > 1 {
ui.label(format!("{} environment:", c.name())) ui.label(txt::main::collection_environment(c.name()))
.on_hover_text("The collection of the active tab, or the one last clicked in the sidebar"); .on_hover_text(txt::main::ENV_OWNER_HOVER);
} else { } else {
ui.label("Environment:"); ui.label(txt::common::ENVIRONMENT_LABEL);
} }
} }
}); });
@@ -229,10 +227,10 @@ fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
let selected = state.active == Some(t.id); let selected = state.active == Some(t.id);
let mut title = t.title(); let mut title = t.title();
if t.is_dirty() { if t.is_dirty() {
title.push_str(" •"); title.push_str(txt::icon::DIRTY);
} }
if t.in_flight.is_some() { if t.in_flight.is_some() {
title.push_str(" ⏳"); title.push_str(txt::icon::IN_FLIGHT);
} }
let resp = ui.selectable_label(selected, title); let resp = ui.selectable_label(selected, title);
let resp = match &t.origin { let resp = match &t.origin {
@@ -249,31 +247,39 @@ fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
acts.push(rename_tab_prompt(t)); acts.push(rename_tab_prompt(t));
} }
resp.context_menu(|ui| { resp.context_menu(|ui| {
if ui.button("Rename…").clicked() { if ui.button(txt::common::RENAME).clicked() {
acts.push(rename_tab_prompt(t)); acts.push(rename_tab_prompt(t));
ui.close(); ui.close();
} }
ui.separator(); ui.separator();
if ui.button("Close").clicked() { if ui.button(txt::common::CLOSE).clicked() {
acts.push(Action::CloseTab(t.id)); acts.push(Action::CloseTab(t.id));
ui.close(); ui.close();
} }
if ui.button("Close others").clicked() { if ui.button(txt::tabs::CLOSE_OTHERS).clicked() {
let others = state.tabs.iter().map(|o| o.id).filter(|&o| o != t.id).collect(); let others = state.tabs.iter().map(|o| o.id).filter(|&o| o != t.id).collect();
acts.push(Action::CloseTabs(others)); acts.push(Action::CloseTabs(others));
ui.close(); ui.close();
} }
if ui.button("Close all").clicked() { if ui.button(txt::tabs::CLOSE_ALL).clicked() {
acts.push(Action::CloseTabs(state.tabs.iter().map(|o| o.id).collect())); acts.push(Action::CloseTabs(state.tabs.iter().map(|o| o.id).collect()));
ui.close(); ui.close();
} }
}); });
if ui.small_button("×").on_hover_text("Close (Ctrl+W)").clicked() { if ui
.small_button(txt::icon::CLOSE)
.on_hover_text(txt::tabs::CLOSE_HOVER)
.clicked()
{
acts.push(Action::CloseTab(t.id)); acts.push(Action::CloseTab(t.id));
} }
ui.separator(); ui.separator();
} }
if ui.button("+").on_hover_text("New tab (Ctrl+T)").clicked() { if ui
.button(txt::icon::ADD)
.on_hover_text(txt::tabs::NEW_TAB_HOVER)
.clicked()
{
acts.push(Action::NewTab); acts.push(Action::NewTab);
} }
}); });
@@ -292,19 +298,19 @@ fn status_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
ui.visuals().text_color() ui.visuals().text_color()
}; };
ui.colored_label(color, &s.text); ui.colored_label(color, &s.text);
if ui.small_button("×").clicked() { if ui.small_button(txt::icon::CLOSE).clicked() {
acts.push(Action::DismissStatus); acts.push(Action::DismissStatus);
} }
} }
None => { None => {
ui.label(RichText::new("Ready").weak()); ui.label(RichText::new(txt::main::READY).weak());
} }
} }
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { 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(); let n = state.tabs.iter().filter(|t| t.in_flight.is_some()).count();
if n > 0 { if n > 0 {
ui.spinner(); ui.spinner();
ui.label(format!("{n} in flight")); ui.label(txt::main::in_flight(n));
} }
}); });
}); });
@@ -313,17 +319,17 @@ fn status_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
fn welcome(ui: &mut Ui, acts: &mut Vec<Action>) { fn welcome(ui: &mut Ui, acts: &mut Vec<Action>) {
ui.vertical_centered(|ui| { ui.vertical_centered(|ui| {
ui.add_space(60.0); ui.add_space(60.0);
ui.heading("reqlite"); ui.heading(txt::common::APP_NAME);
ui.label("Send HTTP requests and keep them as .http files."); ui.label(txt::main::WELCOME);
ui.add_space(12.0); ui.add_space(12.0);
if ui.button("New request (Ctrl+T)").clicked() { if ui.button(txt::main::WELCOME_NEW_REQUEST).clicked() {
acts.push(Action::NewTab); acts.push(Action::NewTab);
} }
if ui.button("Open a collection folder…").clicked() { if ui.button(txt::main::WELCOME_OPEN_FOLDER).clicked() {
acts.push(Action::PickCollection); acts.push(Action::PickCollection);
} }
ui.add_space(12.0); ui.add_space(12.0);
ui.label(RichText::new("Tip: paste a curl command into the URL bar to import it.").weak()); ui.label(RichText::new(txt::main::WELCOME_TIP).weak());
}); });
} }
@@ -331,7 +337,7 @@ fn welcome(ui: &mut Ui, acts: &mut Vec<Action>) {
pub fn rename_tab_prompt(t: &crate::state::Tab) -> Action { pub fn rename_tab_prompt(t: &crate::state::Tab) -> Action {
Action::ShowDialog(Some(crate::state::Dialog::Prompt(crate::state::Prompt { Action::ShowDialog(Some(crate::state::Dialog::Prompt(crate::state::Prompt {
kind: crate::state::PromptKind::RenameTab { tab: t.id }, kind: crate::state::PromptKind::RenameTab { tab: t.id },
title: "Rename request".into(), title: txt::common::RENAME_REQUEST.into(),
value: t.request.display_name().unwrap_or("").to_string(), value: t.request.display_name().unwrap_or("").to_string(),
}))) })))
} }
+156 -133
View File
@@ -2,13 +2,14 @@
use base64::Engine; use base64::Engine;
use egui::{Key, RichText, Ui}; use egui::{Key, RichText, Ui};
use reqlite_core::folder::{auth_mode, AuthMode, InheritedAuth}; use reqlite_core::folder::{auth_mode, AuthHeader, AuthMode, InheritedAuth};
use reqlite_core::params::Param; use reqlite_core::params::Param;
use reqlite_core::{Body, Header, Method, Part, PartBody}; use reqlite_core::{Body, Header, Method, Part, PartBody};
use super::widgets::{code_edit, method_color, var_text_edit, VarCtx}; use super::widgets::{code_edit, method_color, var_text_edit, VarCtx};
use crate::action::Action; use crate::action::Action;
use crate::state::{AppState, RequestTab, Tab}; use crate::state::{AppState, RequestTab, Tab};
use crate::strings as txt;
pub const MULTIPART_BOUNDARY: &str = "WebAppBoundary"; pub const MULTIPART_BOUNDARY: &str = "WebAppBoundary";
@@ -38,14 +39,7 @@ pub fn url_bar(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &m
let buttons_w = 190.0; let buttons_w = 190.0;
let mut url = tab.request.url.clone(); let mut url = tab.request.url.clone();
let w = (ui.available_width() - buttons_w).max(120.0); let w = (ui.available_width() - buttons_w).max(120.0);
let resp = var_text_edit( let resp = var_text_edit(ui, &mut url, Some(vars), txt::request::URL_HINT, w, ("url", id));
ui,
&mut url,
Some(vars),
"Enter a URL, or paste a curl command",
w,
("url", id),
);
if state.focus_url { if state.focus_url {
resp.request_focus(); resp.request_focus();
acts.push(Action::UrlFocused); acts.push(Action::UrlFocused);
@@ -58,40 +52,44 @@ pub fn url_bar(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &m
} }
if tab.in_flight.is_some() { if tab.in_flight.is_some() {
if ui.button("Cancel").on_hover_text("Stop the request").clicked() { if ui
.button(txt::common::CANCEL)
.on_hover_text(txt::request::CANCEL_HOVER)
.clicked()
{
acts.push(Action::Cancel(id)); acts.push(Action::Cancel(id));
} }
} else if ui } else if ui
.add(egui::Button::new(RichText::new("Send").strong())) .add(egui::Button::new(RichText::new(txt::request::SEND).strong()))
.on_hover_text("Send (Ctrl+Enter)") .on_hover_text(txt::request::SEND_HOVER)
.clicked() .clicked()
{ {
acts.push(Action::Send(id)); acts.push(Action::Send(id));
} }
let save_label = if tab.is_dirty() { "Save •" } else { "Save" }; let save_label = if tab.is_dirty() {
if ui txt::request::SAVE_DIRTY
.button(save_label) } else {
.on_hover_text("Save to the .http file (Ctrl+S)") txt::common::SAVE
.clicked() };
{ if ui.button(save_label).on_hover_text(txt::request::SAVE_HOVER).clicked() {
acts.push(Action::Save(id)); acts.push(Action::Save(id));
} }
ui.menu_button("…", |ui| { ui.menu_button(txt::icon::MORE, |ui| {
if ui.button("Copy as curl").clicked() { if ui.button(txt::request::COPY_AS_CURL).clicked() {
acts.push(Action::CopyAsCurl(id)); acts.push(Action::CopyAsCurl(id));
ui.close(); ui.close();
} }
if ui.button("Copy as .http").clicked() { if ui.button(txt::request::COPY_AS_HTTP).clicked() {
acts.push(Action::CopyAsHttp(id)); acts.push(Action::CopyAsHttp(id));
ui.close(); ui.close();
} }
if ui.button("Rename…").clicked() { if ui.button(txt::common::RENAME).clicked() {
acts.push(super::rename_tab_prompt(tab)); acts.push(super::rename_tab_prompt(tab));
ui.close(); ui.close();
} }
ui.separator(); ui.separator();
let mut follow = !tab.request.directives.no_redirect; let mut follow = !tab.request.directives.no_redirect;
if ui.checkbox(&mut follow, "Follow redirects").changed() { if ui.checkbox(&mut follow, txt::request::FOLLOW_REDIRECTS).changed() {
acts.push(Action::SetNoRedirect(id, !follow)); acts.push(Action::SetNoRedirect(id, !follow));
} }
}); });
@@ -103,23 +101,23 @@ pub fn editor(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mu
ui.horizontal(|ui| { ui.horizontal(|ui| {
let enabled_headers = tab.request.headers.iter().filter(|h| !h.disabled).count(); let enabled_headers = tab.request.headers.iter().filter(|h| !h.disabled).count();
let tabs = [ let tabs = [
(RequestTab::Params, format!("Params ({})", tab.params.len())), (RequestTab::Params, txt::request::params_tab(tab.params.len())),
(RequestTab::Headers, format!("Headers ({enabled_headers})")), (RequestTab::Headers, txt::request::headers_tab(enabled_headers)),
( (
RequestTab::Body, RequestTab::Body,
if tab.request.body.is_none() { if tab.request.body.is_none() {
"Body".into() txt::request::BODY_TAB.into()
} else { } else {
"Body •".into() txt::request::BODY_TAB_SET.into()
}, },
), ),
(RequestTab::Auth, "Auth".into()), (RequestTab::Auth, txt::request::AUTH_TAB.into()),
( (
RequestTab::Source, RequestTab::Source,
if tab.source_error.is_some() { if tab.source_error.is_some() {
"Source ⚠".into() txt::request::SOURCE_TAB_ERROR.into()
} else { } else {
"Source".into() txt::request::SOURCE_TAB.into()
}, },
), ),
]; ];
@@ -155,8 +153,8 @@ fn params(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
.num_columns(3) .num_columns(3)
.striped(true) .striped(true)
.show(ui, |ui| { .show(ui, |ui| {
ui.label(RichText::new("Key").weak()); ui.label(RichText::new(txt::request::KEY).weak());
ui.label(RichText::new("Value").weak()); ui.label(RichText::new(txt::common::VALUE).weak());
ui.label(""); ui.label("");
ui.end_row(); ui.end_row();
for (i, p) in rows.iter_mut().enumerate() { for (i, p) in rows.iter_mut().enumerate() {
@@ -164,7 +162,7 @@ fn params(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
ui, ui,
&mut p.key, &mut p.key,
Some(vars), Some(vars),
if i == n { "Add parameter" } else { "" }, if i == n { txt::request::ADD_PARAMETER } else { "" },
w, w,
("pk", id, i), ("pk", id, i),
) )
@@ -174,7 +172,12 @@ fn params(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
p.value = Some(v); p.value = Some(v);
changed = true; changed = true;
} }
if i < n && ui.small_button("×").on_hover_text("Remove").clicked() { if i < n
&& ui
.small_button(txt::icon::CLOSE)
.on_hover_text(txt::common::REMOVE)
.clicked()
{
remove = Some(i); remove = Some(i);
} }
ui.end_row(); ui.end_row();
@@ -194,11 +197,7 @@ fn params(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
acts.push(Action::ParamsEdited(id, rows)); acts.push(Action::ParamsEdited(id, rows));
} }
ui.add_space(4.0); ui.add_space(4.0);
ui.label( ui.label(RichText::new(txt::request::PARAMS_NOTE).small().weak());
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>) { fn headers(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
@@ -214,8 +213,8 @@ fn headers(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
.striped(true) .striped(true)
.show(ui, |ui| { .show(ui, |ui| {
ui.label(""); ui.label("");
ui.label(RichText::new("Name").weak()); ui.label(RichText::new(txt::common::NAME).weak());
ui.label(RichText::new("Value").weak()); ui.label(RichText::new(txt::common::VALUE).weak());
ui.label(""); ui.label("");
ui.end_row(); ui.end_row();
for (i, h) in rows.iter_mut().enumerate() { for (i, h) in rows.iter_mut().enumerate() {
@@ -223,7 +222,7 @@ fn headers(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
let mut on = !h.disabled; let mut on = !h.disabled;
if ui if ui
.checkbox(&mut on, "") .checkbox(&mut on, "")
.on_hover_text("Disabled headers are kept as `# Name: value` comments") .on_hover_text(txt::request::DISABLED_HEADER_HOVER)
.changed() .changed()
{ {
h.disabled = !on; h.disabled = !on;
@@ -236,14 +235,19 @@ fn headers(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
ui, ui,
&mut h.name, &mut h.name,
Some(vars), Some(vars),
if i == n { "Add header" } else { "" }, if i == n { txt::request::ADD_HEADER } else { "" },
(w * 0.35).max(100.0), (w * 0.35).max(100.0),
("hn", id, i), ("hn", id, i),
) )
.changed(); .changed();
changed |= changed |=
var_text_edit(ui, &mut h.value, Some(vars), "", (w * 0.65).max(120.0), ("hv", id, i)).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() { if i < n
&& ui
.small_button(txt::icon::CLOSE)
.on_hover_text(txt::common::REMOVE)
.clicked()
{
remove = Some(i); remove = Some(i);
} }
ui.end_row(); ui.end_row();
@@ -282,10 +286,10 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
}; };
ui.horizontal(|ui| { ui.horizontal(|ui| {
for (k, label) in [ for (k, label) in [
(BodyKind::None, "None"), (BodyKind::None, txt::common::NONE),
(BodyKind::Text, "Text"), (BodyKind::Text, txt::common::TEXT),
(BodyKind::File, "File"), (BodyKind::File, txt::common::FILE),
(BodyKind::Form, "Multipart form"), (BodyKind::Form, txt::body::MULTIPART_FORM),
] { ] {
if ui.radio(kind == k, label).clicked() && kind != k { if ui.radio(kind == k, label).clicked() && kind != k {
match k { match k {
@@ -326,18 +330,18 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
ui.add_space(4.0); ui.add_space(4.0);
match &req.body { match &req.body {
Body::None => { Body::None => {
ui.label(RichText::new("This request has no body.").weak()); ui.label(RichText::new(txt::body::NO_BODY).weak());
} }
Body::Text(text) => { Body::Text(text) => {
let ct = req.header("content-type").unwrap_or("").to_ascii_lowercase(); let ct = req.header("content-type").unwrap_or("").to_ascii_lowercase();
let is_json = ct.contains("json"); let is_json = ct.contains("json");
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("Content-Type:"); ui.label(txt::body::CONTENT_TYPE_LABEL);
for (label, value) in [ for (label, value) in [
("JSON", "application/json"), (txt::body::JSON, "application/json"),
("XML", "application/xml"), (txt::body::XML, "application/xml"),
("Text", "text/plain"), (txt::common::TEXT, "text/plain"),
("Form", "application/x-www-form-urlencoded"), (txt::body::FORM, "application/x-www-form-urlencoded"),
] { ] {
if ui.selectable_label(ct.starts_with(value), label).clicked() { if ui.selectable_label(ct.starts_with(value), label).clicked() {
let mut headers = req.headers.clone(); let mut headers = req.headers.clone();
@@ -346,24 +350,23 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
acts.push(Action::HeadersEdited(id, headers)); acts.push(Action::HeadersEdited(id, headers));
} }
} }
if is_json && ui.button("Format").on_hover_text("Pretty-print the JSON").clicked() { if is_json
&& ui
.button(txt::body::FORMAT)
.on_hover_text(txt::body::FORMAT_HOVER)
.clicked()
{
match serde_json::from_str::<serde_json::Value>(text) { match serde_json::from_str::<serde_json::Value>(text) {
Ok(v) => acts.push(Action::BodyEdited( Ok(v) => acts.push(Action::BodyEdited(
id, id,
Body::Text(serde_json::to_string_pretty(&v).unwrap_or_else(|_| text.clone())), Body::Text(serde_json::to_string_pretty(&v).unwrap_or_else(|_| text.clone())),
)), )),
Err(e) => acts.push(Action::Error(format!("Not valid JSON: {e}"))), Err(e) => acts.push(Action::Error(txt::msg::invalid_json(e))),
} }
} }
}); });
if text.len() > MAX_EDITABLE_BODY { if text.len() > MAX_EDITABLE_BODY {
ui.label( ui.label(RichText::new(txt::body::too_large(text.len() / 1024)).weak());
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 { } else {
let mut t = text.clone(); let mut t = text.clone();
if code_edit(ui, &mut t, is_json, Some(vars.resolver), 12, ("body", id)).changed() { if code_edit(ui, &mut t, is_json, Some(vars.resolver), 12, ("body", id)).changed() {
@@ -373,7 +376,7 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
} }
Body::FileRef { path, substitute } => { Body::FileRef { path, substitute } => {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("File:"); ui.label(txt::body::FILE_LABEL);
let mut p = path.display().to_string(); let mut p = path.display().to_string();
if ui if ui
.add(egui::TextEdit::singleline(&mut p).desired_width(320.0)) .add(egui::TextEdit::singleline(&mut p).desired_width(320.0))
@@ -387,15 +390,12 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
}, },
)); ));
} }
if ui.button("Browse…").clicked() { if ui.button(txt::body::BROWSE).clicked() {
acts.push(Action::PickBodyFile(id)); acts.push(Action::PickBodyFile(id));
} }
}); });
let mut sub = *substitute; let mut sub = *substitute;
if ui if ui.checkbox(&mut sub, txt::body::SUBSTITUTE).changed() {
.checkbox(&mut sub, "Replace {{variables}} in the file (`<@`)")
.changed()
{
acts.push(Action::BodyEdited( acts.push(Action::BodyEdited(
id, id,
Body::FileRef { Body::FileRef {
@@ -404,11 +404,7 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
}, },
)); ));
} }
ui.label( ui.label(RichText::new(txt::body::RELATIVE_PATHS).small().weak());
RichText::new("Relative paths are relative to the .http file.")
.small()
.weak(),
);
} }
Body::Multipart { boundary, parts } => { Body::Multipart { boundary, parts } => {
let mut parts = parts.clone(); let mut parts = parts.clone();
@@ -418,7 +414,13 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
.num_columns(5) .num_columns(5)
.striped(true) .striped(true)
.show(ui, |ui| { .show(ui, |ui| {
for h in ["Name", "Kind", "Value / file", "Content-Type", ""] { for h in [
txt::common::NAME,
txt::body::PART_KIND,
txt::body::PART_VALUE,
txt::body::PART_CONTENT_TYPE,
"",
] {
ui.label(RichText::new(h).weak()); ui.label(RichText::new(h).weak());
} }
ui.end_row(); ui.end_row();
@@ -432,14 +434,14 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
let is_file = matches!(p.body, PartBody::File(_)); let is_file = matches!(p.body, PartBody::File(_));
egui::ComboBox::from_id_salt(("pk", id, i)) egui::ComboBox::from_id_salt(("pk", id, i))
.width(60.0) .width(60.0)
.selected_text(if is_file { "File" } else { "Text" }) .selected_text(if is_file { txt::common::FILE } else { txt::common::TEXT })
.show_ui(ui, |ui| { .show_ui(ui, |ui| {
if ui.selectable_label(!is_file, "Text").clicked() && is_file { if ui.selectable_label(!is_file, txt::common::TEXT).clicked() && is_file {
p.body = PartBody::Text(String::new()); p.body = PartBody::Text(String::new());
p.filename = None; p.filename = None;
changed = true; changed = true;
} }
if ui.selectable_label(is_file, "File").clicked() && !is_file { if ui.selectable_label(is_file, txt::common::FILE).clicked() && !is_file {
p.body = PartBody::File("./file.bin".into()); p.body = PartBody::File("./file.bin".into());
p.filename = Some("file.bin".into()); p.filename = Some("file.bin".into());
changed = true; changed = true;
@@ -480,7 +482,7 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
} }
changed = true; changed = true;
} }
if ui.small_button("×").clicked() { if ui.small_button(txt::icon::CLOSE).clicked() {
remove = Some(i); remove = Some(i);
} }
ui.end_row(); ui.end_row();
@@ -490,7 +492,7 @@ fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec
parts.remove(i); parts.remove(i);
changed = true; changed = true;
} }
if ui.button("Add field").clicked() { if ui.button(txt::body::ADD_FIELD).clicked() {
parts.push(Part { parts.push(Part {
name: format!("field{}", parts.len() + 1), name: format!("field{}", parts.len() + 1),
filename: None, filename: None,
@@ -518,16 +520,20 @@ pub enum AuthKind {
None, None,
Basic, Basic,
Bearer, Bearer,
/// A header other than Authorization, e.g. `X-API-Key`.
Custom,
/// An Authorization value that isn't Basic or Bearer.
Other, Other,
} }
impl AuthKind { impl AuthKind {
/// The header value a newly picked kind starts with. /// The header a newly picked kind starts with.
pub fn template(self) -> Option<String> { pub fn template(self) -> AuthHeader {
match self { match self {
AuthKind::Basic => Some("Basic {{username}} {{password}}".into()), AuthKind::Basic => AuthHeader::authorization("Basic {{username}} {{password}}"),
AuthKind::Bearer => Some("Bearer {{token}}".into()), AuthKind::Bearer => AuthHeader::authorization("Bearer {{token}}"),
_ => None, AuthKind::Custom => AuthHeader::custom("X-API-Key", "{{api_key}}"),
_ => AuthHeader::authorization(""),
} }
} }
} }
@@ -559,15 +565,19 @@ fn auth_parts(value: Option<&str>) -> (AuthKind, String, String) {
(AuthKind::Other, v.to_string(), String::new()) (AuthKind::Other, v.to_string(), String::new())
} }
pub fn header_kind(value: &str) -> AuthKind { pub fn header_kind(h: &AuthHeader) -> AuthKind {
auth_parts(Some(value)).0 if h.is_authorization() {
auth_parts(Some(&h.value)).0
} else {
AuthKind::Custom
}
} }
/// A row of radio buttons; returns the kind picked when it changed. /// A row of radio buttons; returns the kind picked when it changed.
pub fn auth_kind_row(ui: &mut Ui, current: AuthKind, kinds: &[(AuthKind, &str)]) -> Option<AuthKind> { pub fn auth_kind_row(ui: &mut Ui, current: AuthKind, kinds: &[(AuthKind, &str)]) -> Option<AuthKind> {
let mut picked = None; let mut picked = None;
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("Type:"); ui.label(txt::auth::TYPE_LABEL);
for &(k, label) in kinds { for &(k, label) in kinds {
if ui.radio(current == k, label).clicked() && current != k { if ui.radio(current == k, label).clicked() && current != k {
picked = Some(k); picked = Some(k);
@@ -577,9 +587,32 @@ pub fn auth_kind_row(ui: &mut Ui, current: AuthKind, kinds: &[(AuthKind, &str)])
picked picked
} }
/// The fields for an Authorization header value (Basic, Bearer or custom); /// The fields for an auth header (Basic, Bearer, a custom header or a
/// returns the new value when it was edited. /// custom Authorization value); returns the new header when it was edited.
pub fn auth_value_fields(ui: &mut Ui, value: &str, vars: &VarCtx, salt: &str) -> Option<String> { pub fn auth_value_fields(ui: &mut Ui, header: &AuthHeader, vars: &VarCtx, salt: &str) -> Option<AuthHeader> {
if !header.is_authorization() {
let (mut name, mut value) = (header.name.clone(), header.value.clone());
let mut changed = false;
egui::Grid::new(("custom", salt)).num_columns(2).show(ui, |ui| {
ui.label(txt::auth::HEADER_NAME);
changed |= ui
.add(
egui::TextEdit::singleline(&mut name)
.desired_width(260.0)
.id_salt(("cn", salt)),
)
.changed();
ui.end_row();
ui.label(txt::auth::VALUE);
changed |= var_text_edit(ui, &mut value, Some(vars), "", 420.0, ("cv", salt)).changed();
ui.end_row();
});
ui.label(RichText::new(txt::auth::CUSTOM_NOTE).small().weak());
// A header needs a name; keep the old one while the field is empty.
let name = name.trim();
return (changed && !name.is_empty() && !name.contains(':')).then(|| AuthHeader::custom(name, value));
}
let value = header.value.as_str();
let (kind, a, b) = auth_parts(Some(value)); let (kind, a, b) = auth_parts(Some(value));
let mut out = None; let mut out = None;
match kind { match kind {
@@ -587,26 +620,22 @@ pub fn auth_value_fields(ui: &mut Ui, value: &str, vars: &VarCtx, salt: &str) ->
let (mut u, mut p) = (a, b); let (mut u, mut p) = (a, b);
let mut changed = false; let mut changed = false;
egui::Grid::new(("basic", salt)).num_columns(2).show(ui, |ui| { egui::Grid::new(("basic", salt)).num_columns(2).show(ui, |ui| {
ui.label("Username"); ui.label(txt::auth::USERNAME);
changed |= var_text_edit(ui, &mut u, Some(vars), "", 260.0, ("bu", salt)).changed(); changed |= var_text_edit(ui, &mut u, Some(vars), "", 260.0, ("bu", salt)).changed();
ui.end_row(); ui.end_row();
ui.label("Password"); ui.label(txt::auth::PASSWORD);
changed |= var_text_edit(ui, &mut p, Some(vars), "", 260.0, ("bp", salt)).changed(); changed |= var_text_edit(ui, &mut p, Some(vars), "", 260.0, ("bp", salt)).changed();
ui.end_row(); ui.end_row();
}); });
if changed { if changed {
out = Some(format!("Basic {u} {p}")); out = Some(format!("Basic {u} {p}"));
} }
ui.label( ui.label(RichText::new(txt::auth::BASIC_NOTE).small().weak());
RichText::new("Written as `Authorization: Basic user password`; it is base64-encoded when sent, like JetBrains does.")
.small()
.weak(),
);
} }
AuthKind::Bearer => { AuthKind::Bearer => {
let mut t = a; let mut t = a;
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("Token"); ui.label(txt::auth::TOKEN);
if var_text_edit(ui, &mut t, Some(vars), "{{token}}", 420.0, ("bt", salt)).changed() { if var_text_edit(ui, &mut t, Some(vars), "{{token}}", 420.0, ("bt", salt)).changed() {
out = Some(format!("Bearer {t}")); out = Some(format!("Bearer {t}"));
} }
@@ -615,14 +644,14 @@ pub fn auth_value_fields(ui: &mut Ui, value: &str, vars: &VarCtx, salt: &str) ->
_ => { _ => {
let mut v = value.to_string(); let mut v = value.to_string();
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("Header value"); ui.label(txt::auth::HEADER_VALUE);
if var_text_edit(ui, &mut v, Some(vars), "", 420.0, ("bo", salt)).changed() { if var_text_edit(ui, &mut v, Some(vars), "", 420.0, ("bo", salt)).changed() {
out = Some(v.clone()); out = Some(v.clone());
} }
}); });
} }
} }
out out.map(AuthHeader::authorization)
} }
fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) { fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
@@ -634,10 +663,11 @@ fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<
AuthMode::Inherit => AuthKind::Inherit, AuthMode::Inherit => AuthKind::Inherit,
}; };
let kinds = [ let kinds = [
(AuthKind::Inherit, "Inherit"), (AuthKind::Inherit, txt::auth::INHERIT),
(AuthKind::None, "None"), (AuthKind::None, txt::common::NONE),
(AuthKind::Basic, "Basic"), (AuthKind::Basic, txt::auth::BASIC),
(AuthKind::Bearer, "Bearer token"), (AuthKind::Bearer, txt::auth::BEARER),
(AuthKind::Custom, txt::auth::CUSTOM_HEADER),
]; ];
if let Some(k) = auth_kind_row(ui, kind, &kinds) { if let Some(k) = auth_kind_row(ui, kind, &kinds) {
acts.push(Action::AuthEdited( acts.push(Action::AuthEdited(
@@ -645,7 +675,7 @@ fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<
match k { match k {
AuthKind::Inherit => AuthMode::Inherit, AuthKind::Inherit => AuthMode::Inherit,
AuthKind::None => AuthMode::NoAuth, AuthKind::None => AuthMode::NoAuth,
k => AuthMode::Own(k.template().unwrap_or_default()), k => AuthMode::Own(k.template()),
}, },
)); ));
} }
@@ -653,11 +683,11 @@ fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<
match &mode { match &mode {
AuthMode::Inherit => inherited(ui, state, tab, acts), AuthMode::Inherit => inherited(ui, state, tab, acts),
AuthMode::NoAuth => { AuthMode::NoAuth => {
ui.label(RichText::new("No Authorization header, not even the folder's (`# @no-auth`).").weak()); ui.label(RichText::new(txt::auth::NO_AUTH_SET).weak());
} }
AuthMode::Own(v) => { AuthMode::Own(v) => {
if kind == AuthKind::Other { if kind == AuthKind::Other {
ui.label("Custom Authorization header:"); ui.label(txt::auth::CUSTOM);
} }
if let Some(v) = auth_value_fields(ui, v, vars, &format!("tab{id}")) { if let Some(v) = auth_value_fields(ui, v, vars, &format!("tab{id}")) {
acts.push(Action::AuthEdited(id, AuthMode::Own(v))); acts.push(Action::AuthEdited(id, AuthMode::Own(v)));
@@ -665,55 +695,51 @@ fn auth(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec<
} }
} }
ui.add_space(6.0); ui.add_space(6.0);
ui.label( ui.label(RichText::new(txt::auth::SECRETS_NOTE).small().weak());
RichText::new("Auth is just the Authorization header; put secrets in the private env file.")
.small()
.weak(),
);
} }
/// What an inheriting request sends, and buttons to change it. /// What an inheriting request sends, and buttons to change it.
fn inherited(ui: &mut Ui, state: &AppState, tab: &Tab, acts: &mut Vec<Action>) { fn inherited(ui: &mut Ui, state: &AppState, tab: &Tab, acts: &mut Vec<Action>) {
let Some(c) = state.collection_for_tab(tab) else { let Some(c) = state.collection_for_tab(tab) else {
ui.label(RichText::new("Not in a collection, so there is nothing to inherit.").weak()); ui.label(RichText::new(txt::auth::NOT_IN_COLLECTION).weak());
return; return;
}; };
match state.inherited_auth_for(tab) { match state.inherited_auth_for(tab) {
Some(InheritedAuth { from, value: Some(v) }) => { Some(InheritedAuth { from, value: Some(v) }) => {
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
ui.label("Uses"); ui.label(txt::auth::USES);
ui.label(RichText::new(&v).monospace()); ui.label(RichText::new(v.to_string()).monospace());
ui.label(format!("from {}.", c.folder_label(&from))); ui.label(txt::auth::from_folder(&c.folder_label(&from)));
}); });
} }
Some(InheritedAuth { from, value: None }) => { Some(InheritedAuth { from, value: None }) => {
ui.label(format!("No auth: {} is set to send none.", c.folder_label(&from))); ui.label(txt::auth::folder_sends_none(&c.folder_label(&from)));
} }
None => { None => {
ui.label(RichText::new("No auth: no folder above this request has auth set.").weak()); ui.label(RichText::new(txt::auth::NO_FOLDER_AUTH).weak());
} }
} }
let dir = state.auth_dir_for(tab); let dir = state.auth_dir_for(tab);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if let Some(dir) = dir.as_ref().filter(|d| **d != c.root) { if let Some(dir) = dir.as_ref().filter(|d| **d != c.root) {
if ui.button("Folder auth…").on_hover_text(c.folder_label(dir)).clicked() { if ui
.button(txt::auth::FOLDER_AUTH_BUTTON)
.on_hover_text(c.folder_label(dir))
.clicked()
{
acts.push(Action::EditFolderAuth(dir.clone())); acts.push(Action::EditFolderAuth(dir.clone()));
} }
} }
if ui if ui
.button("Collection default…") .button(txt::auth::COLLECTION_DEFAULT_BUTTON)
.on_hover_text("Auth for every request in the collection that doesn't set its own") .on_hover_text(txt::auth::COLLECTION_DEFAULT_HOVER)
.clicked() .clicked()
{ {
acts.push(Action::EditFolderAuth(c.root.clone())); acts.push(Action::EditFolderAuth(c.root.clone()));
} }
}); });
if tab.origin.is_none() { if tab.origin.is_none() {
ui.label( ui.label(RichText::new(txt::auth::UNTITLED_NOTE).small().weak());
RichText::new("Untitled requests use the collection default.")
.small()
.weak(),
);
} }
} }
@@ -726,11 +752,7 @@ fn source(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec<Action>) {
if code_edit(ui, &mut text, false, Some(vars.resolver), 14, ("source", id)).changed() { if code_edit(ui, &mut text, false, Some(vars.resolver), 14, ("source", id)).changed() {
acts.push(Action::SourceEdited(id, text)); acts.push(Action::SourceEdited(id, text));
} }
ui.label( ui.label(RichText::new(txt::request::SOURCE_NOTE).small().weak());
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)] #[cfg(test)]
@@ -747,6 +769,7 @@ mod tests {
let (k, t, _) = auth_parts(Some("Bearer abc")); let (k, t, _) = auth_parts(Some("Bearer abc"));
assert!(k == AuthKind::Bearer && t == "abc"); assert!(k == AuthKind::Bearer && t == "abc");
assert!(auth_parts(Some("Digest x")).0 == AuthKind::Other); assert!(auth_parts(Some("Digest x")).0 == AuthKind::Other);
assert!(header_kind("Bearer {{t}}") == AuthKind::Bearer); assert!(header_kind(&AuthHeader::authorization("Bearer {{t}}")) == AuthKind::Bearer);
assert!(header_kind(&AuthHeader::custom("X-API-Key", "Bearer x")) == AuthKind::Custom);
} }
} }
+35 -27
View File
@@ -5,6 +5,7 @@ use egui::{Align, FontId, Layout, RichText, Ui};
use super::widgets::{build_job, human_size, json_spans, status_color, Palette}; use super::widgets::{build_job, human_size, json_spans, status_color, Palette};
use crate::action::Action; use crate::action::Action;
use crate::state::{BodyKind, BodyView, ResponseTab, Tab, TextLines}; use crate::state::{BodyKind, BodyView, ResponseTab, Tab, TextLines};
use crate::strings as txt;
/// Lines longer than this are cut in the viewer (the full body can be saved /// Lines longer than this are cut in the viewer (the full body can be saved
/// or copied). /// or copied).
@@ -15,8 +16,8 @@ pub fn show(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
if let Some(f) = &tab.in_flight { if let Some(f) = &tab.in_flight {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.spinner(); ui.spinner();
ui.label(format!("Sending… {:.1} s", f.started.elapsed().as_secs_f32())); ui.label(txt::response::sending(f.started.elapsed().as_secs_f32()));
if ui.button("Cancel").clicked() { if ui.button(txt::common::CANCEL).clicked() {
acts.push(Action::Cancel(id)); acts.push(Action::Cancel(id));
} }
}); });
@@ -29,7 +30,7 @@ pub fn show(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
} }
let Some(view) = &tab.response else { let Some(view) = &tab.response else {
ui.centered_and_justified(|ui| { ui.centered_and_justified(|ui| {
ui.label(RichText::new("Send the request to see the response here.").weak()); ui.label(RichText::new(txt::response::EMPTY).weak());
}); });
return; return;
}; };
@@ -43,20 +44,20 @@ pub fn show(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
.color(status_color(r.status, dark)), .color(status_color(r.status, dark)),
); );
ui.separator(); ui.separator();
ui.label(format!("{} ms", r.timings.total.as_millis())); ui.label(txt::response::millis(r.timings.total.as_millis()));
ui.separator(); ui.separator();
ui.label(human_size(r.size)); ui.label(human_size(r.size));
ui.separator(); ui.separator();
ui.label(RichText::new(&r.http_version).weak()); ui.label(RichText::new(&r.http_version).weak());
if r.body.is_spilled() { if r.body.is_spilled() {
ui.label(RichText::new("(stored in a temp file)").weak()); ui.label(RichText::new(txt::response::SPILLED).weak());
} }
ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.button("Save to file…").clicked() { if ui.button(txt::response::SAVE_TO_FILE).clicked() {
acts.push(Action::SaveResponseBody(id)); acts.push(Action::SaveResponseBody(id));
} }
if let Some(p) = &view.prepared { if let Some(p) = &view.prepared {
if p.kind != BodyKind::Image && ui.button("Copy body").clicked() { if p.kind != BodyKind::Image && ui.button(txt::response::COPY_BODY).clicked() {
ui.ctx().copy_text(p.text(tab.body_view).text.to_string()); ui.ctx().copy_text(p.text(tab.body_view).text.to_string());
} }
} }
@@ -65,9 +66,9 @@ pub fn show(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
ui.horizontal(|ui| { ui.horizontal(|ui| {
for (t, label) in [ for (t, label) in [
(ResponseTab::Body, "Body".to_string()), (ResponseTab::Body, txt::response::BODY_TAB.to_string()),
(ResponseTab::Headers, format!("Headers ({})", r.headers.len())), (ResponseTab::Headers, txt::response::headers_tab(r.headers.len())),
(ResponseTab::Timings, "Timings".to_string()), (ResponseTab::Timings, txt::response::TIMINGS_TAB.to_string()),
] { ] {
if ui.selectable_label(tab.response_tab == t, label).clicked() { if ui.selectable_label(tab.response_tab == t, label).clicked() {
acts.push(Action::SetResponseTab(id, t)); acts.push(Action::SetResponseTab(id, t));
@@ -95,7 +96,7 @@ pub fn show(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
}); });
if r.effective_url != tab.request.url { if r.effective_url != tab.request.url {
ui.add_space(8.0); ui.add_space(8.0);
ui.label(RichText::new(format!("Final URL: {}", r.effective_url)).weak()); ui.label(RichText::new(txt::response::final_url(&r.effective_url)).weak());
} }
}); });
} }
@@ -109,13 +110,13 @@ fn body(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
let Some(p) = &view.prepared else { let Some(p) = &view.prepared else {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.spinner(); ui.spinner();
ui.label("Preparing the body…"); ui.label(txt::response::PREPARING);
}); });
return; return;
}; };
match p.kind { match p.kind {
BodyKind::Empty => { BodyKind::Empty => {
ui.label(RichText::new("No body.").weak()); ui.label(RichText::new(txt::response::NO_BODY).weak());
return; return;
} }
BodyKind::Image => { BodyKind::Image => {
@@ -139,27 +140,30 @@ fn body(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
ui.horizontal(|ui| { ui.horizontal(|ui| {
if p.pretty.is_some() { if p.pretty.is_some() {
if ui if ui
.selectable_label(tab.body_view == BodyView::Pretty, "Pretty") .selectable_label(tab.body_view == BodyView::Pretty, txt::response::PRETTY)
.clicked() .clicked()
{ {
acts.push(Action::SetBodyView(id, BodyView::Pretty)); acts.push(Action::SetBodyView(id, BodyView::Pretty));
} }
if ui.selectable_label(tab.body_view == BodyView::Raw, "Raw").clicked() { if ui
.selectable_label(tab.body_view == BodyView::Raw, txt::response::RAW)
.clicked()
{
acts.push(Action::SetBodyView(id, BodyView::Raw)); acts.push(Action::SetBodyView(id, BodyView::Raw));
} }
ui.separator(); ui.separator();
} }
if p.kind == BodyKind::Binary { if p.kind == BodyKind::Binary {
ui.label(RichText::new("Binary body, shown as hex. Use “Save to file” to keep it.").weak()); ui.label(RichText::new(txt::response::BINARY).weak());
} }
if p.truncated { if p.truncated {
ui.label(RichText::new("Only the start of this large body is shown.").weak()); ui.label(RichText::new(txt::response::TRUNCATED).weak());
} }
if tab.search.open { if tab.search.open {
search_bar(ui, tab, acts); search_bar(ui, tab, acts);
} else if ui } else if ui
.small_button("🔍 Find") .small_button(txt::response::FIND_BUTTON)
.on_hover_text("Search the body (Ctrl+F)") .on_hover_text(txt::response::FIND_HOVER)
.clicked() .clicked()
{ {
acts.push(Action::SearchOpen(id, true)); acts.push(Action::SearchOpen(id, true));
@@ -176,7 +180,7 @@ fn search_bar(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
let mut q = tab.search.query.clone(); let mut q = tab.search.query.clone();
let resp = ui.add( let resp = ui.add(
egui::TextEdit::singleline(&mut q) egui::TextEdit::singleline(&mut q)
.hint_text("Find") .hint_text(txt::response::FIND_HINT)
.desired_width(180.0) .desired_width(180.0)
.id_salt(("find", id)), .id_salt(("find", id)),
); );
@@ -195,15 +199,15 @@ fn search_bar(ui: &mut Ui, tab: &Tab, acts: &mut Vec<Action>) {
if n > 0 { if n > 0 {
ui.label(format!("{}/{}", tab.search.current + 1, n)); ui.label(format!("{}/{}", tab.search.current + 1, n));
} else if !tab.search.query.is_empty() { } else if !tab.search.query.is_empty() {
ui.label(RichText::new("no matches").weak()); ui.label(RichText::new(txt::response::NO_MATCHES).weak());
} }
if ui.small_button("Prev").clicked() { if ui.small_button(txt::response::PREV).clicked() {
acts.push(Action::SearchStep(id, -1)); acts.push(Action::SearchStep(id, -1));
} }
if ui.small_button("Next").clicked() { if ui.small_button(txt::response::NEXT).clicked() {
acts.push(Action::SearchStep(id, 1)); acts.push(Action::SearchStep(id, 1));
} }
if ui.small_button("×").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { if ui.small_button(txt::icon::CLOSE).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
acts.push(Action::SearchOpen(id, false)); acts.push(Action::SearchOpen(id, false));
} }
} }
@@ -285,7 +289,7 @@ fn timings(ui: &mut Ui, tab: &Tab) {
for (label, d) in t.phases() { for (label, d) in t.phases() {
let secs = d.as_secs_f32(); let secs = d.as_secs_f32();
ui.label(label); ui.label(label);
ui.label(RichText::new(format!("{:.1} ms", secs * 1000.0)).monospace()); ui.label(RichText::new(txt::response::millis_f(secs * 1000.0)).monospace());
let (rect, _) = ui.allocate_exact_size(egui::vec2(bar_w, 12.0), egui::Sense::hover()); let (rect, _) = ui.allocate_exact_size(egui::vec2(bar_w, 12.0), egui::Sense::hover());
let x0 = rect.left() + bar_w * (start / total); let x0 = rect.left() + bar_w * (start / total);
let x1 = (x0 + (bar_w * secs / total).max(1.0)).min(rect.right()); let x1 = (x0 + (bar_w * secs / total).max(1.0)).min(rect.right());
@@ -297,8 +301,12 @@ fn timings(ui: &mut Ui, tab: &Tab) {
start += secs; start += secs;
ui.end_row(); ui.end_row();
} }
ui.label(RichText::new("Total").strong()); ui.label(RichText::new(txt::response::TOTAL).strong());
ui.label(RichText::new(format!("{:.1} ms", total * 1000.0)).monospace().strong()); ui.label(
RichText::new(txt::response::millis_f(total * 1000.0))
.monospace()
.strong(),
);
ui.end_row(); ui.end_row();
}); });
} }
+58 -57
View File
@@ -8,14 +8,15 @@ use reqlite_core::collection::Node;
use super::widgets::method_color; use super::widgets::method_color;
use crate::action::Action; use crate::action::Action;
use crate::state::{AppState, CollectionState, DeleteTarget, Dialog, Prompt, PromptKind}; use crate::state::{AppState, CollectionState, DeleteTarget, Dialog, Prompt, PromptKind};
use crate::strings as txt;
pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) { pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(RichText::new("Collections").strong()); ui.label(RichText::new(txt::sidebar::COLLECTIONS).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui if ui
.small_button("Open…") .small_button(txt::sidebar::OPEN)
.on_hover_text("Open another collection folder") .on_hover_text(txt::sidebar::OPEN_HOVER)
.clicked() .clicked()
{ {
acts.push(Action::PickCollection); acts.push(Action::PickCollection);
@@ -25,15 +26,15 @@ pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
if state.collections.is_empty() { if state.collections.is_empty() {
ui.add_space(8.0); ui.add_space(8.0);
ui.label("No collection open."); ui.label(txt::sidebar::NO_COLLECTION);
ui.label(RichText::new("A collection is a folder of .http files.").weak()); ui.label(RichText::new(txt::sidebar::WHAT_IS_A_COLLECTION).weak());
ui.add_space(4.0); ui.add_space(4.0);
if ui.button("Open folder…").clicked() { if ui.button(txt::sidebar::OPEN_FOLDER).clicked() {
acts.push(Action::PickCollection); acts.push(Action::PickCollection);
} }
if !state.settings.recent_collections.is_empty() { if !state.settings.recent_collections.is_empty() {
ui.add_space(8.0); ui.add_space(8.0);
ui.label(RichText::new("Recent").strong()); ui.label(RichText::new(txt::sidebar::RECENT).strong());
for p in &state.settings.recent_collections { for p in &state.settings.recent_collections {
let name = p let name = p
.file_name() .file_name()
@@ -59,7 +60,7 @@ pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
// Right-clicking the empty space below the tree. // Right-clicking the empty space below the tree.
let size = egui::vec2(ui.available_width(), ui.available_height().max(40.0)); let size = egui::vec2(ui.available_width(), ui.available_height().max(40.0));
ui.allocate_response(size, egui::Sense::click()).context_menu(|ui| { ui.allocate_response(size, egui::Sense::click()).context_menu(|ui| {
if ui.button("Open collection folder…").clicked() { if ui.button(txt::common::OPEN_COLLECTION_FOLDER).clicked() {
acts.push(Action::PickCollection); acts.push(Action::PickCollection);
ui.close(); ui.close();
} }
@@ -78,38 +79,47 @@ fn collection(ui: &mut Ui, state: &AppState, c: &CollectionState, current: bool,
} }
let resp = ui let resp = ui
.add(egui::Label::new(name).sense(egui::Sense::click())) .add(egui::Label::new(name).sense(egui::Sense::click()))
.on_hover_text(format!( .on_hover_text(txt::sidebar::collection_hover(c.root.display()));
"{}\nClick to use its environments for new tabs",
c.root.display()
));
if resp.clicked() { if resp.clicked() {
acts.push(Action::SetActiveCollection(c.root.clone())); acts.push(Action::SetActiveCollection(c.root.clone()));
} }
resp.context_menu(|ui| { resp.context_menu(|ui| {
if ui.button("New .http file…").clicked() { if ui.button(txt::sidebar::NEW_HTTP_FILE).clicked() {
acts.push(new_file_prompt(&c.root)); acts.push(new_file_prompt(&c.root));
ui.close(); ui.close();
} }
if ui.button("Reload from disk").clicked() { if ui.button(txt::common::RELOAD_FROM_DISK).clicked() {
acts.push(Action::Rescan(c.root.clone())); acts.push(Action::Rescan(c.root.clone()));
ui.close(); ui.close();
} }
ui.separator(); ui.separator();
auth_menu_items(ui, &c.root, "Default auth…", acts); auth_menu_items(ui, &c.root, txt::sidebar::DEFAULT_AUTH, acts);
ui.separator(); ui.separator();
if ui.button("Close collection").clicked() { if ui.button(txt::sidebar::CLOSE_COLLECTION).clicked() {
acts.push(Action::CloseCollection(c.root.clone())); acts.push(Action::CloseCollection(c.root.clone()));
ui.close(); ui.close();
} }
}); });
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button("×").on_hover_text("Close this collection").clicked() { if ui
.small_button(txt::icon::CLOSE)
.on_hover_text(txt::sidebar::CLOSE_COLLECTION_HOVER)
.clicked()
{
acts.push(Action::CloseCollection(c.root.clone())); acts.push(Action::CloseCollection(c.root.clone()));
} }
if ui.small_button("⟳").on_hover_text("Reload from disk").clicked() { if ui
.small_button(txt::icon::RELOAD)
.on_hover_text(txt::common::RELOAD_FROM_DISK)
.clicked()
{
acts.push(Action::Rescan(c.root.clone())); acts.push(Action::Rescan(c.root.clone()));
} }
if ui.small_button("+").on_hover_text("New .http file").clicked() { if ui
.small_button(txt::icon::ADD)
.on_hover_text(txt::common::NEW_HTTP_FILE)
.clicked()
{
acts.push(new_file_prompt(&c.root)); acts.push(new_file_prompt(&c.root));
} }
}); });
@@ -117,32 +127,27 @@ fn collection(ui: &mut Ui, state: &AppState, c: &CollectionState, current: bool,
.body(|ui| { .body(|ui| {
if c.private_not_ignored && !c.gitignore_offer_dismissed { if c.private_not_ignored && !c.gitignore_offer_dismissed {
egui::Frame::group(ui.style()).show(ui, |ui| { egui::Frame::group(ui.style()).show(ui, |ui| {
ui.label( ui.label(RichText::new(txt::sidebar::PRIVATE_NOT_IGNORED).color(ui.visuals().warn_fg_color));
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| { ui.horizontal(|ui| {
if ui.button("Add to .gitignore").clicked() { if ui.button(txt::sidebar::ADD_TO_GITIGNORE).clicked() {
acts.push(Action::AddPrivateFileToGitignore(c.root.clone())); acts.push(Action::AddPrivateFileToGitignore(c.root.clone()));
} }
if ui.button("Dismiss").clicked() { if ui.button(txt::common::DISMISS).clicked() {
acts.push(Action::DismissGitignoreOffer(c.root.clone())); acts.push(Action::DismissGitignoreOffer(c.root.clone()));
} }
}); });
}); });
} }
if let Some(e) = &c.env_error { if let Some(e) = &c.env_error {
ui.colored_label(ui.visuals().error_fg_color, format!("Environments: {e}")); ui.colored_label(ui.visuals().error_fg_color, txt::sidebar::env_error(e));
} }
for e in &c.folder_errors { for e in &c.folder_errors {
ui.colored_label(ui.visuals().error_fg_color, format!("Folder settings: {e}")); ui.colored_label(ui.visuals().error_fg_color, txt::sidebar::folder_error(e));
} }
if let Node::Folder { children, .. } = &c.tree { if let Node::Folder { children, .. } = &c.tree {
if children.is_empty() { if children.is_empty() {
ui.label(RichText::new("No .http files yet.").weak()); ui.label(RichText::new(txt::sidebar::NO_FILES).weak());
if ui.button("Create one").clicked() { if ui.button(txt::sidebar::CREATE_ONE).clicked() {
acts.push(new_file_prompt(&c.root)); acts.push(new_file_prompt(&c.root));
} }
} }
@@ -154,17 +159,13 @@ fn collection(ui: &mut Ui, state: &AppState, c: &CollectionState, current: bool,
} }
fn auth_menu_items(ui: &mut Ui, dir: &Path, edit_label: &str, acts: &mut Vec<Action>) { fn auth_menu_items(ui: &mut Ui, dir: &Path, edit_label: &str, acts: &mut Vec<Action>) {
if ui if ui.button(edit_label).on_hover_text(txt::sidebar::AUTH_HOVER).clicked() {
.button(edit_label)
.on_hover_text("Auth for the requests in here that don't set their own")
.clicked()
{
acts.push(Action::EditFolderAuth(dir.to_path_buf())); acts.push(Action::EditFolderAuth(dir.to_path_buf()));
ui.close(); ui.close();
} }
if ui if ui
.button("Consolidate auth…") .button(txt::sidebar::CONSOLIDATE)
.on_hover_text("Make requests in here inherit one shared auth") .on_hover_text(txt::sidebar::CONSOLIDATE_HOVER)
.clicked() .clicked()
{ {
acts.push(Action::ConsolidateAuth { acts.push(Action::ConsolidateAuth {
@@ -178,7 +179,7 @@ fn auth_menu_items(ui: &mut Ui, dir: &Path, edit_label: &str, acts: &mut Vec<Act
fn new_file_prompt(dir: &Path) -> Action { fn new_file_prompt(dir: &Path) -> Action {
Action::ShowDialog(Some(Dialog::Prompt(Prompt { Action::ShowDialog(Some(Dialog::Prompt(Prompt {
kind: PromptKind::NewFile { dir: dir.to_path_buf() }, kind: PromptKind::NewFile { dir: dir.to_path_buf() },
title: "New .http file".into(), title: txt::common::NEW_HTTP_FILE.into(),
value: "requests.http".into(), value: "requests.http".into(),
}))) })))
} }
@@ -186,7 +187,7 @@ fn new_file_prompt(dir: &Path) -> Action {
fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut Vec<Action>) { fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut Vec<Action>) {
match n { match n {
Node::Folder { name, path, children } => { Node::Folder { name, path, children } => {
let resp = egui::CollapsingHeader::new(format!("📁 {name}")) let resp = egui::CollapsingHeader::new(txt::sidebar::folder(name))
.id_salt(path) .id_salt(path)
.default_open(true) .default_open(true)
.show(ui, |ui| { .show(ui, |ui| {
@@ -196,20 +197,20 @@ fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut
}); });
let mut header = resp.header_response; let mut header = resp.header_response;
if let reqlite_core::folder::FolderAuth::Header(v) = c.folder_auth(path) { if let reqlite_core::folder::FolderAuth::Header(v) = c.folder_auth(path) {
header = header.on_hover_text(format!("Auth: {v}")); header = header.on_hover_text(txt::sidebar::folder_auth_hover(&v.to_string()));
} }
header.context_menu(|ui| { header.context_menu(|ui| {
if ui.button("New .http file…").clicked() { if ui.button(txt::sidebar::NEW_HTTP_FILE).clicked() {
acts.push(new_file_prompt(path)); acts.push(new_file_prompt(path));
ui.close(); ui.close();
} }
ui.separator(); ui.separator();
auth_menu_items(ui, path, "Folder auth…", acts); auth_menu_items(ui, path, txt::auth::FOLDER_AUTH_BUTTON, acts);
}); });
} }
Node::File { name, path } => { Node::File { name, path } => {
let Some(file) = c.files.get(path) else { return }; let Some(file) = c.files.get(path) else { return };
let resp = egui::CollapsingHeader::new(format!("📄 {name}")) let resp = egui::CollapsingHeader::new(txt::sidebar::file(name))
.id_salt(path) .id_salt(path)
.default_open(true) .default_open(true)
.show(ui, |ui| { .show(ui, |ui| {
@@ -250,32 +251,32 @@ fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut
}); });
} }
item.context_menu(|ui| { item.context_menu(|ui| {
if ui.button("Open").clicked() { if ui.button(txt::common::OPEN).clicked() {
acts.push(Action::OpenRequest { acts.push(Action::OpenRequest {
file: path.clone(), file: path.clone(),
index: i, index: i,
}); });
ui.close(); ui.close();
} }
if ui.button("Rename…").clicked() { if ui.button(txt::common::RENAME).clicked() {
acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt { acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt {
kind: PromptKind::RenameRequest { kind: PromptKind::RenameRequest {
file: path.clone(), file: path.clone(),
index: i, index: i,
}, },
title: "Rename request".into(), title: txt::common::RENAME_REQUEST.into(),
value: r.display_name().unwrap_or("").to_string(), value: r.display_name().unwrap_or("").to_string(),
})))); }))));
ui.close(); ui.close();
} }
if ui.button("Duplicate").clicked() { if ui.button(txt::sidebar::DUPLICATE).clicked() {
acts.push(Action::DuplicateRequest { acts.push(Action::DuplicateRequest {
file: path.clone(), file: path.clone(),
index: i, index: i,
}); });
ui.close(); ui.close();
} }
ui.menu_button("Move to", |ui| { ui.menu_button(txt::sidebar::MOVE_TO, |ui| {
let many = state.collections.len() > 1; let many = state.collections.len() > 1;
let targets = state let targets = state
.collections .collections
@@ -299,7 +300,7 @@ fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut
} }
}); });
ui.separator(); ui.separator();
if ui.button("Delete…").clicked() { if ui.button(txt::sidebar::DELETE).clicked() {
acts.push(Action::ShowDialog(Some(Dialog::ConfirmDelete(DeleteTarget::Request { acts.push(Action::ShowDialog(Some(Dialog::ConfirmDelete(DeleteTarget::Request {
file: path.clone(), file: path.clone(),
index: i, index: i,
@@ -310,28 +311,28 @@ fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut
}); });
} }
if file.request_count() == 0 { if file.request_count() == 0 {
ui.label(RichText::new("(no requests)").weak()); ui.label(RichText::new(txt::sidebar::NO_REQUESTS).weak());
} }
}); });
resp.header_response.context_menu(|ui| { resp.header_response.context_menu(|ui| {
if ui.button("New request").clicked() { if ui.button(txt::common::NEW_REQUEST).clicked() {
acts.push(Action::NewRequestIn { file: path.clone() }); acts.push(Action::NewRequestIn { file: path.clone() });
ui.close(); ui.close();
} }
if ui.button("Rename file…").clicked() { if ui.button(txt::sidebar::RENAME_FILE).clicked() {
acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt { acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt {
kind: PromptKind::RenameFile { path: path.clone() }, kind: PromptKind::RenameFile { path: path.clone() },
title: "Rename file".into(), title: txt::sidebar::RENAME_FILE_TITLE.into(),
value: name.clone(), value: name.clone(),
})))); }))));
ui.close(); ui.close();
} }
if ui.button("Duplicate file").clicked() { if ui.button(txt::sidebar::DUPLICATE_FILE).clicked() {
acts.push(Action::DuplicateFile(path.clone())); acts.push(Action::DuplicateFile(path.clone()));
ui.close(); ui.close();
} }
ui.separator(); ui.separator();
if ui.button("Delete file…").clicked() { if ui.button(txt::sidebar::DELETE_FILE).clicked() {
acts.push(Action::ShowDialog(Some(Dialog::ConfirmDelete(DeleteTarget::File( acts.push(Action::ShowDialog(Some(Dialog::ConfirmDelete(DeleteTarget::File(
path.clone(), path.clone(),
))))); )))));
@@ -356,7 +357,7 @@ fn short_url(url: &str) -> String {
let u = url.split("://").nth(1).unwrap_or(url); let u = url.split("://").nth(1).unwrap_or(url);
let s: String = u.chars().take(40).collect(); let s: String = u.chars().take(40).collect();
if s.is_empty() { if s.is_empty() {
"(no URL)".into() txt::sidebar::NO_URL.into()
} else { } else {
s s
} }
+14 -12
View File
@@ -7,6 +7,8 @@ use egui::text::{LayoutJob, TextFormat};
use egui::{Color32, FontId, TextBuffer, Ui}; use egui::{Color32, FontId, TextBuffer, Ui};
use reqlite_core::template::{find_vars, Resolver, VarSource}; use reqlite_core::template::{find_vars, Resolver, VarSource};
use crate::strings as txt;
pub struct Palette { pub struct Palette {
pub text: Color32, pub text: Color32,
pub key: Color32, pub key: Color32,
@@ -199,24 +201,24 @@ impl VarCtx<'_> {
/// Text for the hover tooltip of a variable. /// Text for the hover tooltip of a variable.
pub fn describe(&self, name: &str) -> String { pub fn describe(&self, name: &str) -> String {
match self.resolver.lookup(name) { match self.resolver.lookup(name) {
None => format!("{{{{{name}}}}} is not defined in the selected environment"), None => txt::vars::undefined(name),
Some((_, VarSource::Builtin)) => format!("{{{{{name}}}}}: built-in dynamic value"), Some((_, VarSource::Builtin)) => txt::vars::builtin(name),
Some((v, src)) => { Some((v, src)) => {
let from = match src { let from = match src {
VarSource::PrivateEnv => "private env", VarSource::PrivateEnv => txt::vars::FROM_PRIVATE_ENV,
VarSource::PublicEnv => "env", VarSource::PublicEnv => txt::vars::FROM_ENV,
VarSource::File => "file variable", VarSource::File => txt::vars::FROM_FILE,
VarSource::Builtin => "built-in", VarSource::Builtin => txt::vars::FROM_BUILTIN,
}; };
let shown = if (self.is_private)(name) { let shown = if (self.is_private)(name) {
"••••".to_string() txt::icon::MASKED_SHORT.to_string()
} else { } else {
match self.resolver.resolve(&v) { match self.resolver.resolve(&v) {
Ok(r) if r != v => format!("{v} -> {r}"), Ok(r) if r != v => txt::vars::resolved(&v, &r),
_ => v, _ => v,
} }
}; };
format!("{name} = {shown} ({from})") txt::vars::hover(name, &shown, from)
} }
} }
} }
@@ -344,9 +346,9 @@ pub fn status_color(status: u16, dark: bool) -> Color32 {
pub fn human_size(n: u64) -> String { pub fn human_size(n: u64) -> String {
match n { match n {
n if n < 1024 => format!("{n} B"), n if n < 1024 => txt::units::bytes(n),
n if n < 1024 * 1024 => format!("{:.1} KB", n as f64 / 1024.0), n if n < 1024 * 1024 => txt::units::kilobytes(n as f64 / 1024.0),
n => format!("{:.1} MB", n as f64 / (1024.0 * 1024.0)), n => txt::units::megabytes(n as f64 / (1024.0 * 1024.0)),
} }
} }
+165 -176
View File
@@ -11,6 +11,7 @@ use crate::settings::{ProxyMode, Settings, ThemeChoice};
use crate::state::{ use crate::state::{
AppState, ConsolidateAuth, DeleteTarget, Dialog, EnvEditor, FolderAuthEdit, Prompt, PromptKind, QuickOpen, AppState, ConsolidateAuth, DeleteTarget, Dialog, EnvEditor, FolderAuthEdit, Prompt, PromptKind, QuickOpen,
}; };
use crate::strings as txt;
pub fn show(ctx: &Context, state: &AppState, acts: &mut Vec<Action>) { pub fn show(ctx: &Context, state: &AppState, acts: &mut Vec<Action>) {
if let Some(d) = &state.dialog { if let Some(d) = &state.dialog {
@@ -49,66 +50,63 @@ fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec<Action>) {
Dialog::ConfirmCloseTab(id) => { Dialog::ConfirmCloseTab(id) => {
let title = state.tab(*id).map(|t| t.title()).unwrap_or_default(); 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()); let has_file = state.tab(*id).is_some_and(|t| t.origin.is_some());
ui.heading("Unsaved changes"); ui.heading(txt::dialog::UNSAVED);
ui.label(format!("“{title}” has changes that are not saved.")); ui.label(txt::dialog::tab_unsaved(&title));
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if has_file && ui.button("Save and close").clicked() { if has_file && ui.button(txt::dialog::SAVE_AND_CLOSE).clicked() {
acts.push(close()); acts.push(close());
acts.push(Action::Save(*id)); acts.push(Action::Save(*id));
acts.push(Action::CloseTab(*id)); acts.push(Action::CloseTab(*id));
} }
if ui.button("Discard").clicked() { if ui.button(txt::dialog::DISCARD).clicked() {
acts.push(Action::DiscardAndCloseTab(*id)); acts.push(Action::DiscardAndCloseTab(*id));
} }
if ui.button("Cancel").clicked() { if ui.button(txt::common::CANCEL).clicked() {
acts.push(close()); acts.push(close());
} }
}); });
} }
Dialog::ConfirmCloseTabs(ids) => { Dialog::ConfirmCloseTabs(ids) => {
ui.heading("Unsaved changes"); ui.heading(txt::dialog::UNSAVED);
ui.label(format!("{} tab(s) have changes that are not saved:", ids.len())); ui.label(txt::dialog::tabs_unsaved(ids.len()));
for id in ids { for id in ids {
if let Some(t) = state.tab(*id) { if let Some(t) = state.tab(*id) {
ui.label(format!("• {}", t.title())); ui.label(txt::common::bullet(t.title()));
} }
} }
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.button("Discard and close").clicked() { if ui.button(txt::dialog::DISCARD_AND_CLOSE).clicked() {
acts.push(Action::DiscardAndCloseTabs(ids.clone())); acts.push(Action::DiscardAndCloseTabs(ids.clone()));
} }
if ui.button("Keep them open").clicked() { if ui.button(txt::dialog::KEEP_OPEN).clicked() {
acts.push(close()); acts.push(close());
} }
}); });
} }
Dialog::ConfirmQuit => { Dialog::ConfirmQuit => {
let n = state.tabs.iter().filter(|t| t.is_dirty()).count(); let n = state.tabs.iter().filter(|t| t.is_dirty()).count();
ui.heading("Quit reqlite?"); ui.heading(txt::dialog::QUIT_TITLE);
ui.label(format!("{n} tab(s) have unsaved changes; they will be lost.")); ui.label(txt::dialog::quit_unsaved(n));
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.button("Quit without saving").clicked() { if ui.button(txt::dialog::QUIT_WITHOUT_SAVING).clicked() {
acts.push(Action::ConfirmQuit); acts.push(Action::ConfirmQuit);
} }
if ui.button("Cancel").clicked() { if ui.button(txt::common::CANCEL).clicked() {
acts.push(close()); acts.push(close());
} }
}); });
} }
Dialog::Conflict { tab, path } => { Dialog::Conflict { tab, path } => {
ui.heading("File changed on disk"); ui.heading(txt::dialog::CONFLICT_TITLE);
ui.label(format!( ui.label(txt::dialog::conflict(path.display()));
"{} was changed outside reqlite, and this tab has unsaved edits.",
path.display()
));
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui if ui
.button("Reload from disk") .button(txt::common::RELOAD_FROM_DISK)
.on_hover_text("Discard my edits") .on_hover_text(txt::dialog::RELOAD_HOVER)
.clicked() .clicked()
{ {
acts.push(Action::ResolveConflict { acts.push(Action::ResolveConflict {
@@ -117,8 +115,8 @@ fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec<Action>) {
}); });
} }
if ui if ui
.button("Keep my version") .button(txt::dialog::KEEP_MINE)
.on_hover_text("Saving will overwrite this request in the new file") .on_hover_text(txt::dialog::KEEP_MINE_HOVER)
.clicked() .clicked()
{ {
acts.push(Action::ResolveConflict { acts.push(Action::ResolveConflict {
@@ -133,15 +131,15 @@ fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec<Action>) {
Dialog::ConsolidateAuth(plan) => consolidate_auth(ui, state, plan, acts), Dialog::ConsolidateAuth(plan) => consolidate_auth(ui, state, plan, acts),
Dialog::ConfirmDelete(target) => { Dialog::ConfirmDelete(target) => {
let what = match target { let what = match target {
DeleteTarget::Request { label, .. } => format!("the request “{label}”"), DeleteTarget::Request { label, .. } => txt::dialog::delete_request(label),
DeleteTarget::File(p) => format!("the file {}", p.display()), DeleteTarget::File(p) => txt::dialog::delete_file(p.display()),
}; };
ui.heading("Delete?"); ui.heading(txt::dialog::DELETE_TITLE);
ui.label(format!("This deletes {what} from disk.")); ui.label(txt::dialog::delete_body(&what));
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui if ui
.button(RichText::new("Delete").color(ui.visuals().error_fg_color)) .button(RichText::new(txt::common::DELETE).color(ui.visuals().error_fg_color))
.clicked() .clicked()
{ {
acts.push(match target { acts.push(match target {
@@ -152,25 +150,25 @@ fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec<Action>) {
DeleteTarget::File(p) => Action::DeleteFile(p.clone()), DeleteTarget::File(p) => Action::DeleteFile(p.clone()),
}); });
} }
if ui.button("Cancel").clicked() { if ui.button(txt::common::CANCEL).clicked() {
acts.push(close()); acts.push(close());
} }
}); });
} }
Dialog::ImportSummary { root, files, warnings } => { Dialog::ImportSummary { root, files, warnings } => {
ui.heading("Import finished"); ui.heading(txt::dialog::IMPORT_TITLE);
ui.label(format!("Wrote {files} .http file(s) to {}.", root.display())); ui.label(txt::dialog::import_wrote(*files, root.display()));
if !warnings.is_empty() { if !warnings.is_empty() {
ui.add_space(6.0); ui.add_space(6.0);
ui.label(RichText::new(format!("{} warning(s):", warnings.len())).strong()); ui.label(RichText::new(txt::dialog::warnings(warnings.len())).strong());
egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| {
for w in warnings { for w in warnings {
ui.label(format!("• {w}")); ui.label(txt::common::bullet(w));
} }
}); });
} }
ui.add_space(8.0); ui.add_space(8.0);
if ui.button("OK").clicked() { if ui.button(txt::common::OK).clicked() {
acts.push(close()); acts.push(close());
} }
} }
@@ -188,9 +186,9 @@ fn folder_auth(ui: &mut egui::Ui, state: &AppState, ed: &FolderAuthEdit, acts: &
}; };
let is_root = ed.dir == c.root; let is_root = ed.dir == c.root;
ui.heading(if is_root { ui.heading(if is_root {
"Collection default auth" txt::auth::COLLECTION_DEFAULT_TITLE
} else { } else {
"Folder auth" txt::auth::FOLDER_AUTH_TITLE
}); });
ui.label(RichText::new(c.relative(&ed.dir).display().to_string()).weak()); ui.label(RichText::new(c.relative(&ed.dir).display().to_string()).weak());
ui.add_space(4.0); ui.add_space(4.0);
@@ -206,34 +204,44 @@ fn folder_auth(ui: &mut egui::Ui, state: &AppState, ed: &FolderAuthEdit, acts: &
FolderAuth::Header(v) => header_kind(v), FolderAuth::Header(v) => header_kind(v),
}; };
let kinds = [ let kinds = [
(AuthKind::Inherit, if is_root { "Not set" } else { "Inherit" }), (
(AuthKind::None, "None"), AuthKind::Inherit,
(AuthKind::Basic, "Basic"), if is_root {
(AuthKind::Bearer, "Bearer token"), txt::auth::NOT_SET
} else {
txt::auth::INHERIT
},
),
(AuthKind::None, txt::common::NONE),
(AuthKind::Basic, txt::auth::BASIC),
(AuthKind::Bearer, txt::auth::BEARER),
(AuthKind::Custom, txt::auth::CUSTOM_HEADER),
]; ];
if let Some(k) = auth_kind_row(ui, kind, &kinds) { if let Some(k) = auth_kind_row(ui, kind, &kinds) {
acts.push(set(match k { acts.push(set(match k {
AuthKind::Inherit => FolderAuth::Inherit, AuthKind::Inherit => FolderAuth::Inherit,
AuthKind::None => FolderAuth::None, AuthKind::None => FolderAuth::None,
k => FolderAuth::Header(k.template().unwrap_or_default()), k => FolderAuth::Header(k.template()),
})); }));
} }
ui.add_space(6.0); ui.add_space(6.0);
match &ed.auth { match &ed.auth {
FolderAuth::Inherit if is_root => { FolderAuth::Inherit if is_root => {
ui.label(RichText::new("Requests that don't set auth send none.").weak()); ui.label(RichText::new(txt::auth::ROOT_NOT_SET).weak());
} }
FolderAuth::Inherit => { FolderAuth::Inherit => {
let parent = ed.dir.parent().and_then(|p| c.inherited_auth(p)); let parent = ed.dir.parent().and_then(|p| c.inherited_auth(p));
let text = match parent { let text = match parent {
Some(InheritedAuth { from, value: Some(v) }) => format!("Uses `{v}` from {}.", c.folder_label(&from)), Some(InheritedAuth { from, value: Some(v) }) => {
Some(InheritedAuth { from, value: None }) => format!("No auth, as set on {}.", c.folder_label(&from)), txt::auth::parent_uses(&v.to_string(), &c.folder_label(&from))
None => "No auth: no parent folder has auth set.".into(), }
Some(InheritedAuth { from, value: None }) => txt::auth::parent_none(&c.folder_label(&from)),
None => txt::auth::NO_PARENT_AUTH.into(),
}; };
ui.label(RichText::new(text).weak()); ui.label(RichText::new(text).weak());
} }
FolderAuth::None => { FolderAuth::None => {
ui.label(RichText::new("Requests here send no auth unless they set their own.").weak()); ui.label(RichText::new(txt::auth::FOLDER_NONE).weak());
} }
FolderAuth::Header(v) => { FolderAuth::Header(v) => {
let resolver = c.envs.resolver(c.selected_env.as_deref(), &[]); let resolver = c.envs.resolver(c.selected_env.as_deref(), &[]);
@@ -249,23 +257,16 @@ fn folder_auth(ui: &mut egui::Ui, state: &AppState, ed: &FolderAuthEdit, acts: &
} }
} }
ui.add_space(6.0); ui.add_space(6.0);
ui.label( ui.label(RichText::new(txt::auth::FOLDER_NOTE).small().weak());
RichText::new(
"Used by requests in this folder and its subfolders that have no Authorization header of their own. \
Saved in .reqlite/folder.json (other .http tools ignore it).",
)
.small()
.weak(),
);
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.button("Save").clicked() { if ui.button(txt::common::SAVE).clicked() {
acts.push(Action::SetFolderAuth { acts.push(Action::SetFolderAuth {
dir: ed.dir.clone(), dir: ed.dir.clone(),
auth: ed.auth.clone(), auth: ed.auth.clone(),
}); });
} }
if ui.button("Cancel").clicked() { if ui.button(txt::common::CANCEL).clicked() {
acts.push(Action::ShowDialog(None)); acts.push(Action::ShowDialog(None));
} }
}); });
@@ -277,31 +278,28 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
return; return;
}; };
let set = |plan: ConsolidateAuth| Action::ShowDialog(Some(Dialog::ConsolidateAuth(plan))); let set = |plan: ConsolidateAuth| Action::ShowDialog(Some(Dialog::ConsolidateAuth(plan)));
ui.heading("Consolidate auth"); ui.heading(txt::consolidate::TITLE);
ui.label(format!( ui.label(txt::consolidate::intro(&c.folder_label(&plan.dir)));
"Let requests in {} inherit one shared auth instead of each carrying its own Authorization header.",
c.folder_label(&plan.dir)
));
ui.add_space(6.0); ui.add_space(6.0);
let Some(target) = &plan.target else { let Some(target) = &plan.target else {
ui.label("None of these requests has an Authorization header, and there is no auth to inherit."); ui.label(txt::consolidate::NOTHING);
ui.add_space(8.0); ui.add_space(8.0);
if ui.button("OK").clicked() { if ui.button(txt::common::OK).clicked() {
acts.push(Action::ShowDialog(None)); acts.push(Action::ShowDialog(None));
} }
return; return;
}; };
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("Shared auth:"); ui.label(txt::consolidate::SHARED_AUTH);
if plan.choices.is_empty() { if plan.choices.is_empty() {
ui.label(RichText::new(target).monospace()); ui.label(RichText::new(target.to_string()).monospace());
} else { } else {
egui::ComboBox::from_id_salt("consolidate-target") egui::ComboBox::from_id_salt("consolidate-target")
.selected_text(RichText::new(target).monospace()) .selected_text(RichText::new(target.to_string()).monospace())
.show_ui(ui, |ui| { .show_ui(ui, |ui| {
for (v, n) in &plan.choices { for (v, n) in &plan.choices {
let label = format!("{v} ({n} request{})", if *n == 1 { "" } else { "s" }); let label = txt::consolidate::choice(&v.to_string(), *n);
if ui.selectable_label(v == target, label).clicked() && v != target { if ui.selectable_label(v == target, label).clicked() && v != target {
acts.push(Action::ConsolidateAuth { acts.push(Action::ConsolidateAuth {
dir: plan.dir.clone(), dir: plan.dir.clone(),
@@ -313,38 +311,32 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
} }
}); });
if plan.set_folder { if plan.set_folder {
ui.label( ui.label(RichText::new(txt::consolidate::will_save(&c.folder_label(&plan.dir))).weak());
RichText::new(format!(
"It will be saved as the auth of {}.",
c.folder_label(&plan.dir)
))
.weak(),
);
} else { } else {
ui.label(RichText::new(format!("{} already uses it.", c.folder_label(&plan.dir))).weak()); ui.label(RichText::new(txt::consolidate::already_uses(&c.folder_label(&plan.dir))).weak());
} }
ui.add_space(8.0); ui.add_space(8.0);
if plan.own.is_empty() { if plan.own.is_empty() {
ui.label("No request here has its own Authorization header."); ui.label(txt::consolidate::NO_OWN);
} else { } else {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(RichText::new("Remove the Authorization header from:").strong()); ui.label(RichText::new(txt::consolidate::REMOVE_FROM).strong());
if ui if ui
.small_button("Matching") .small_button(txt::consolidate::MATCHING)
.on_hover_text("Only those that send the same thing") .on_hover_text(txt::consolidate::MATCHING_HOVER)
.clicked() .clicked()
{ {
let mut p = plan.clone(); let mut p = plan.clone();
p.own.iter_mut().for_each(|o| o.selected = o.same()); p.own.iter_mut().for_each(|o| o.selected = o.same());
acts.push(set(p)); acts.push(set(p));
} }
if ui.small_button("All").clicked() { if ui.small_button(txt::common::ALL).clicked() {
let mut p = plan.clone(); let mut p = plan.clone();
p.own.iter_mut().for_each(|o| o.selected = true); p.own.iter_mut().for_each(|o| o.selected = true);
acts.push(set(p)); acts.push(set(p));
} }
if ui.small_button("None").clicked() { if ui.small_button(txt::common::NONE).clicked() {
let mut p = plan.clone(); let mut p = plan.clone();
p.own.iter_mut().for_each(|o| o.selected = false); p.own.iter_mut().for_each(|o| o.selected = false);
acts.push(set(p)); acts.push(set(p));
@@ -356,17 +348,22 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
.show(ui, |ui| { .show(ui, |ui| {
for (i, o) in plan.own.iter().enumerate() { for (i, o) in plan.own.iter().enumerate() {
let mut on = o.selected; let mut on = o.selected;
let resp = ui.checkbox(&mut on, &o.request.label).on_hover_text(&o.value); let resp = ui
.checkbox(&mut on, &o.request.label)
.on_hover_text(o.value.to_string());
if resp.changed() { if resp.changed() {
let mut p = plan.clone(); let mut p = plan.clone();
p.own[i].selected = on; p.own[i].selected = on;
acts.push(set(p)); acts.push(set(p));
} }
if !o.same() { if !o.same() {
let would = o.inherits.as_deref().unwrap_or("no auth"); let would = o
.inherits
.as_ref()
.map_or(txt::common::NO_AUTH.into(), |h| h.to_string());
ui.indent(("diff", i), |ui| { ui.indent(("diff", i), |ui| {
ui.label( ui.label(
RichText::new(format!("has `{}`; would send `{would}` instead", o.value)) RichText::new(txt::consolidate::would_send(&o.value.to_string(), &would))
.small() .small()
.color(ui.visuals().warn_fg_color), .color(ui.visuals().warn_fg_color),
); );
@@ -378,23 +375,20 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
if plan.set_folder && !plan.affected.is_empty() { if plan.set_folder && !plan.affected.is_empty() {
ui.add_space(8.0); ui.add_space(8.0);
ui.label(format!( ui.label(txt::consolidate::affected(plan.affected.len(), &target.to_string()));
"{} request(s) without a header of their own would start sending `{target}`:",
plan.affected.len()
));
egui::ScrollArea::vertical() egui::ScrollArea::vertical()
.id_salt("consolidate-affected") .id_salt("consolidate-affected")
.max_height(120.0) .max_height(120.0)
.show(ui, |ui| { .show(ui, |ui| {
for (r, before) in &plan.affected { for (r, before) in &plan.affected {
let now = before.as_deref().unwrap_or("no auth"); let now = before.as_ref().map_or(txt::common::NO_AUTH.into(), |h| h.to_string());
ui.label(format!("• {} (now: {now})", r.label)); ui.label(txt::consolidate::affected_item(&r.label, &now));
} }
}); });
let mut keep = plan.keep_affected; let mut keep = plan.keep_affected;
if ui if ui
.checkbox(&mut keep, "Keep what they send today") .checkbox(&mut keep, txt::consolidate::KEEP_AFFECTED)
.on_hover_text("Gives them their current header, or `# @no-auth`") .on_hover_text(txt::consolidate::KEEP_AFFECTED_HOVER)
.changed() .changed()
{ {
let mut p = plan.clone(); let mut p = plan.clone();
@@ -406,13 +400,13 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
if !plan.skipped_dirty.is_empty() { if !plan.skipped_dirty.is_empty() {
ui.add_space(6.0); ui.add_space(6.0);
ui.label( ui.label(
RichText::new(format!( RichText::new(txt::consolidate::skipped_dirty(
"Skipped, because their tabs have unsaved edits: {}", &plan
plan.skipped_dirty .skipped_dirty
.iter() .iter()
.map(|r| r.label.as_str()) .map(|r| r.label.as_str())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", "),
)) ))
.weak(), .weak(),
); );
@@ -423,10 +417,13 @@ fn consolidate_auth(ui: &mut egui::Ui, state: &AppState, plan: &ConsolidateAuth,
|| plan.own.iter().any(|o| o.selected) || plan.own.iter().any(|o| o.selected)
|| (plan.keep_affected && plan.set_folder && !plan.affected.is_empty()); || (plan.keep_affected && plan.set_folder && !plan.affected.is_empty());
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.add_enabled(anything, egui::Button::new("Apply")).clicked() { if ui
.add_enabled(anything, egui::Button::new(txt::common::APPLY))
.clicked()
{
acts.push(Action::ApplyConsolidateAuth(plan.clone())); acts.push(Action::ApplyConsolidateAuth(plan.clone()));
} }
if ui.button("Cancel").clicked() { if ui.button(txt::common::CANCEL).clicked() {
acts.push(Action::ShowDialog(None)); acts.push(Action::ShowDialog(None));
} }
}); });
@@ -452,7 +449,7 @@ fn prompt(ui: &mut egui::Ui, state: &AppState, p: &Prompt, acts: &mut Vec<Action
let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)); let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.button("OK").clicked() || enter { if ui.button(txt::common::OK).clicked() || enter {
let action = match &p.kind { let action = match &p.kind {
PromptKind::NewFile { dir } => Action::NewFile { PromptKind::NewFile { dir } => Action::NewFile {
dir: dir.clone(), dir: dir.clone(),
@@ -487,7 +484,7 @@ fn prompt(ui: &mut egui::Ui, state: &AppState, p: &Prompt, acts: &mut Vec<Action
}; };
acts.push(action); acts.push(action);
} }
if ui.button("Cancel").clicked() { if ui.button(txt::common::CANCEL).clicked() {
acts.push(Action::ShowDialog(None)); acts.push(Action::ShowDialog(None));
} }
}); });
@@ -495,7 +492,7 @@ fn prompt(ui: &mut egui::Ui, state: &AppState, p: &Prompt, acts: &mut Vec<Action
fn settings(ctx: &Context, s: &Settings, open: &mut bool, acts: &mut Vec<Action>) { fn settings(ctx: &Context, s: &Settings, open: &mut bool, acts: &mut Vec<Action>) {
let mut n = s.clone(); let mut n = s.clone();
egui::Window::new("Settings") egui::Window::new(txt::settings::TITLE)
.open(open) .open(open)
.resizable(false) .resizable(false)
.show(ctx, |ui| { .show(ctx, |ui| {
@@ -503,77 +500,77 @@ fn settings(ctx: &Context, s: &Settings, open: &mut bool, acts: &mut Vec<Action>
.num_columns(2) .num_columns(2)
.spacing([12.0, 8.0]) .spacing([12.0, 8.0])
.show(ui, |ui| { .show(ui, |ui| {
ui.label("Default timeout"); ui.label(txt::settings::TIMEOUT);
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.add( ui.add(
egui::DragValue::new(&mut n.default_timeout_secs) egui::DragValue::new(&mut n.default_timeout_secs)
.range(0..=3600) .range(0..=3600)
.suffix(" s"), .suffix(txt::settings::SECONDS_SUFFIX),
); );
ui.label(RichText::new("0 = none; `# @timeout` wins").weak()); ui.label(RichText::new(txt::settings::TIMEOUT_NOTE).weak());
}); });
ui.end_row(); ui.end_row();
ui.label("Proxy"); ui.label(txt::settings::PROXY);
ui.vertical(|ui| { ui.vertical(|ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.radio_value(&mut n.proxy_mode, ProxyMode::System, "System"); ui.radio_value(&mut n.proxy_mode, ProxyMode::System, txt::common::SYSTEM);
ui.radio_value(&mut n.proxy_mode, ProxyMode::None, "None"); ui.radio_value(&mut n.proxy_mode, ProxyMode::None, txt::common::NONE);
ui.radio_value(&mut n.proxy_mode, ProxyMode::Manual, "Manual"); ui.radio_value(&mut n.proxy_mode, ProxyMode::Manual, txt::settings::MANUAL);
}); });
if n.proxy_mode == ProxyMode::Manual { if n.proxy_mode == ProxyMode::Manual {
ui.add_sized( ui.add_sized(
[260.0, ui.spacing().interact_size.y], [260.0, ui.spacing().interact_size.y],
egui::TextEdit::singleline(&mut n.proxy_url).hint_text("http://user:pass@proxy:3128"), egui::TextEdit::singleline(&mut n.proxy_url).hint_text(txt::settings::PROXY_HINT),
); );
} }
}); });
ui.end_row(); ui.end_row();
ui.label("TLS"); ui.label(txt::settings::TLS);
ui.vertical(|ui| { ui.vertical(|ui| {
ui.checkbox(&mut n.verify_tls, "Verify certificates"); ui.checkbox(&mut n.verify_tls, txt::settings::VERIFY_TLS);
ui.horizontal(|ui| { ui.horizontal(|ui| {
let ca = n let ca = n
.ca_file .ca_file
.as_ref() .as_ref()
.map(|p| p.display().to_string()) .map(|p| p.display().to_string())
.unwrap_or_else(|| "System store only".into()); .unwrap_or_else(|| txt::settings::SYSTEM_STORE.into());
ui.label(RichText::new(ca).weak()); ui.label(RichText::new(ca).weak());
if ui.button("Add CA file…").clicked() { if ui.button(txt::settings::ADD_CA).clicked() {
acts.push(Action::PickCaFile); acts.push(Action::PickCaFile);
} }
if n.ca_file.is_some() && ui.button("Clear").clicked() { if n.ca_file.is_some() && ui.button(txt::common::CLEAR).clicked() {
n.ca_file = None; n.ca_file = None;
} }
}); });
}); });
ui.end_row(); ui.end_row();
ui.label("Theme"); ui.label(txt::settings::THEME);
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.radio_value(&mut n.theme, ThemeChoice::System, "System"); ui.radio_value(&mut n.theme, ThemeChoice::System, txt::common::SYSTEM);
ui.radio_value(&mut n.theme, ThemeChoice::Light, "Light"); ui.radio_value(&mut n.theme, ThemeChoice::Light, txt::settings::LIGHT);
ui.radio_value(&mut n.theme, ThemeChoice::Dark, "Dark"); ui.radio_value(&mut n.theme, ThemeChoice::Dark, txt::settings::DARK);
}); });
ui.end_row(); ui.end_row();
ui.label("Font size"); ui.label(txt::settings::FONT_SIZE);
ui.add( ui.add(
egui::Slider::new(&mut n.zoom, 0.75..=2.0) egui::Slider::new(&mut n.zoom, 0.75..=2.0)
.step_by(0.05) .step_by(0.05)
.custom_formatter(|v, _| format!("{:.0}%", v * 100.0)), .custom_formatter(|v, _| txt::settings::percent(v)),
); );
ui.end_row(); ui.end_row();
ui.label("Parallel requests"); ui.label(txt::settings::PARALLEL);
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut n.max_concurrent_requests).range(1..=64)); ui.add(egui::DragValue::new(&mut n.max_concurrent_requests).range(1..=64));
ui.label(RichText::new("at once").weak()); ui.label(RichText::new(txt::settings::AT_ONCE).weak());
}); });
ui.end_row(); ui.end_row();
ui.label("History size"); ui.label(txt::settings::HISTORY_SIZE);
ui.add(egui::DragValue::new(&mut n.history_limit).range(10..=10_000)); ui.add(egui::DragValue::new(&mut n.history_limit).range(10..=10_000));
ui.end_row(); ui.end_row();
}); });
@@ -584,13 +581,13 @@ fn settings(ctx: &Context, s: &Settings, open: &mut bool, acts: &mut Vec<Action>
} }
fn history(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Action>) { fn history(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Action>) {
egui::Window::new("History") egui::Window::new(txt::history::TITLE)
.open(open) .open(open)
.default_size([620.0, 420.0]) .default_size([620.0, 420.0])
.show(ctx, |ui| { .show(ctx, |ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(format!("{} request(s)", state.history.len())); ui.label(txt::history::count(state.history.len()));
if ui.button("Clear").clicked() { if ui.button(txt::common::CLEAR).clicked() {
acts.push(Action::ClearHistory); acts.push(Action::ClearHistory);
} }
}); });
@@ -603,9 +600,9 @@ fn history(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Acti
match (e.status, &e.error) { match (e.status, &e.error) {
(Some(s), _) => ui.label(RichText::new(s.to_string()).color(status_color(s, dark))), (Some(s), _) => ui.label(RichText::new(s.to_string()).color(status_color(s, dark))),
(None, Some(err)) => ui (None, Some(err)) => ui
.label(RichText::new("ERR").color(ui.visuals().error_fg_color)) .label(RichText::new(txt::history::ERR).color(ui.visuals().error_fg_color))
.on_hover_text(err), .on_hover_text(err),
_ => ui.label("—"), _ => ui.label(txt::icon::NONE),
}; };
ui.label( ui.label(
RichText::new(&e.method) RichText::new(&e.method)
@@ -613,15 +610,11 @@ fn history(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Acti
.monospace(), .monospace(),
); );
let url: String = e.url.chars().take(70).collect(); let url: String = e.url.chars().take(70).collect();
ui.label(url).on_hover_text(format!( ui.label(url)
"{}\n{} ms{}", .on_hover_text(txt::history::hover(&e.url, e.duration_ms, e.env.as_deref()));
e.url,
e.duration_ms,
e.env.as_ref().map(|v| format!(", env {v}")).unwrap_or_default()
));
if ui if ui
.small_button("Open") .small_button(txt::common::OPEN)
.on_hover_text("Restore into a new tab") .on_hover_text(txt::history::RESTORE_HOVER)
.clicked() .clicked()
{ {
acts.push(Action::RestoreHistory(i)); acts.push(Action::RestoreHistory(i));
@@ -643,22 +636,28 @@ fn format_time(secs: u64) -> String {
fn cookies(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Action>) { fn cookies(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Action>) {
let key = state.current_collection().map(|c| c.root.clone()); let key = state.current_collection().map(|c| c.root.clone());
let jar = state.cookie_jars.get(&key); let jar = state.cookie_jars.get(&key);
egui::Window::new("Cookies") egui::Window::new(txt::cookies::TITLE)
.open(open) .open(open)
.default_size([560.0, 300.0]) .default_size([560.0, 300.0])
.show(ctx, |ui| { .show(ctx, |ui| {
ui.label(RichText::new("Cookies are kept in memory per collection; `# @no-cookie-jar` skips them.").weak()); ui.label(RichText::new(txt::cookies::NOTE).weak());
let cookies = jar.map(|j| j.cookies()).unwrap_or(&[]); let cookies = jar.map(|j| j.cookies()).unwrap_or(&[]);
if cookies.is_empty() { if cookies.is_empty() {
ui.label("No cookies yet."); ui.label(txt::cookies::EMPTY);
return; return;
} }
if ui.button("Clear all").clicked() { if ui.button(txt::cookies::CLEAR_ALL).clicked() {
acts.push(Action::ClearCookies); acts.push(Action::ClearCookies);
} }
egui::ScrollArea::vertical().show(ui, |ui| { egui::ScrollArea::vertical().show(ui, |ui| {
egui::Grid::new("cookies").num_columns(5).striped(true).show(ui, |ui| { egui::Grid::new("cookies").num_columns(5).striped(true).show(ui, |ui| {
for h in ["Domain", "Path", "Name", "Value", ""] { for h in [
txt::cookies::DOMAIN,
txt::cookies::PATH,
txt::common::NAME,
txt::common::VALUE,
"",
] {
ui.label(RichText::new(h).weak()); ui.label(RichText::new(h).weak());
} }
ui.end_row(); ui.end_row();
@@ -668,7 +667,7 @@ fn cookies(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Acti
ui.label(RichText::new(&c.name).strong()); ui.label(RichText::new(&c.name).strong());
let v: String = c.value.chars().take(40).collect(); let v: String = c.value.chars().take(40).collect();
ui.label(v).on_hover_text(&c.value); ui.label(v).on_hover_text(&c.value);
if ui.small_button("×").clicked() { if ui.small_button(txt::icon::CLOSE).clicked() {
acts.push(Action::DeleteCookie(i)); acts.push(Action::DeleteCookie(i));
} }
ui.end_row(); ui.end_row();
@@ -679,26 +678,17 @@ fn cookies(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Acti
} }
fn about(ctx: &Context, open: &mut bool) { fn about(ctx: &Context, open: &mut bool) {
egui::Window::new("About reqlite") egui::Window::new(txt::about::TITLE)
.open(open) .open(open)
.resizable(false) .resizable(false)
.show(ctx, |ui| { .show(ctx, |ui| {
ui.heading(format!("reqlite {}", env!("CARGO_PKG_VERSION"))); ui.heading(txt::about::heading(env!("CARGO_PKG_VERSION")));
ui.label("A small API client for .http files."); ui.label(txt::about::TAGLINE);
ui.label(reqlite_http_curl::CurlClient::version()); ui.label(reqlite_http_curl::CurlClient::version());
ui.add_space(6.0); ui.add_space(6.0);
ui.label(RichText::new("Shortcuts").strong()); ui.label(RichText::new(txt::about::SHORTCUTS).strong());
egui::Grid::new("keys").show(ui, |ui| { egui::Grid::new("keys").show(ui, |ui| {
for (k, v) in [ for (k, v) in txt::about::KEYS {
("Ctrl+Enter", "Send"),
("Ctrl+S", "Save"),
("Ctrl+T", "New tab"),
("Ctrl+W", "Close tab"),
("Ctrl+Shift+W", "Close all tabs"),
("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(RichText::new(k).monospace());
ui.label(v); ui.label(v);
ui.end_row(); ui.end_row();
@@ -716,14 +706,13 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
.file_name() .file_name()
.map(|n| n.to_string_lossy().into_owned()) .map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(); .unwrap_or_default();
let dirty = if ed.dirty { " •" } else { "" }; egui::Window::new(txt::env::title(&name, ed.dirty))
egui::Window::new(format!("Environments: {name}{dirty}"))
.id(egui::Id::unique("env-editor")) .id(egui::Id::unique("env-editor"))
.open(&mut open) .open(&mut open)
.default_size([640.0, 380.0]) .default_size([640.0, 380.0])
.show(ctx, |ui| { .show(ctx, |ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("Environment:"); ui.label(txt::common::ENVIRONMENT_LABEL);
let mut names = e.envs.names(); let mut names = e.envs.names();
names.insert(0, SHARED_ENV.to_string()); names.insert(0, SHARED_ENV.to_string());
egui::ComboBox::from_id_salt("env-edit-sel") egui::ComboBox::from_id_salt("env-edit-sel")
@@ -731,17 +720,17 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
.show_ui(ui, |ui| { .show_ui(ui, |ui| {
for n in names { for n in names {
let label = if n == SHARED_ENV { let label = if n == SHARED_ENV {
"$shared (all environments)".to_string() txt::env::SHARED.to_string()
} else { } else {
n.clone() n.clone()
}; };
ui.selectable_value(&mut e.selected, n, label); ui.selectable_value(&mut e.selected, n, label);
} }
}); });
if ui.button("New…").clicked() { if ui.button(txt::env::NEW).clicked() {
acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt { acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt {
kind: PromptKind::NewEnvironment, kind: PromptKind::NewEnvironment,
title: "New environment".into(), title: txt::dialog::NEW_ENVIRONMENT.into(),
value: String::new(), value: String::new(),
})))); }))));
} }
@@ -763,14 +752,14 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
let mut remove = None; let mut remove = None;
egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| {
egui::Grid::new("env-vars").num_columns(5).striped(true).show(ui, |ui| { egui::Grid::new("env-vars").num_columns(5).striped(true).show(ui, |ui| {
for h in ["Name", "Value", "Private", "", ""] { for h in [txt::common::NAME, txt::common::VALUE, txt::env::PRIVATE, "", ""] {
ui.label(RichText::new(h).weak()); ui.label(RichText::new(h).weak());
} }
ui.end_row(); ui.end_row();
for (i, (name, value, private, structured)) in new_rows.iter_mut().enumerate() { for (i, (name, value, private, structured)) in new_rows.iter_mut().enumerate() {
if *structured { if *structured {
ui.label(name.as_str()); ui.label(name.as_str());
ui.label(RichText::new("(object; edit the JSON file)").weak()); ui.label(RichText::new(txt::env::STRUCTURED).weak());
ui.label(""); ui.label("");
ui.label(""); ui.label("");
ui.label(""); ui.label("");
@@ -782,7 +771,7 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
.changed(); .changed();
let revealed = e.revealed.contains(&(env.clone(), name.clone())); let revealed = e.revealed.contains(&(env.clone(), name.clone()));
if *private && !revealed { if *private && !revealed {
ui.label(RichText::new("••••••••").monospace()); ui.label(RichText::new(txt::icon::MASKED).monospace());
} else { } else {
changed |= ui changed |= ui
.add_sized( .add_sized(
@@ -793,12 +782,12 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
} }
changed |= ui changed |= ui
.checkbox(private, "") .checkbox(private, "")
.on_hover_text("Stored in http-client.private.env.json (keep it out of git)") .on_hover_text(txt::env::PRIVATE_HOVER)
.changed(); .changed();
if *private { if *private {
if ui if ui
.small_button(if revealed { "🙈" } else { "👁" }) .small_button(if revealed { txt::icon::HIDE } else { txt::icon::SHOW })
.on_hover_text("Show / hide") .on_hover_text(txt::env::SHOW_HIDE_HOVER)
.clicked() .clicked()
{ {
let k = (env.clone(), name.clone()); let k = (env.clone(), name.clone());
@@ -812,14 +801,14 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
} else { } else {
ui.label(""); ui.label("");
} }
if ui.small_button("×").clicked() { if ui.small_button(txt::icon::CLOSE).clicked() {
remove = Some(i); remove = Some(i);
} }
ui.end_row(); ui.end_row();
} }
}); });
}); });
if ui.button("Add variable").clicked() { if ui.button(txt::env::ADD_VARIABLE).clicked() {
let n = (1..) let n = (1..)
.map(|i| format!("var{i}")) .map(|i| format!("var{i}"))
.find(|n| !new_rows.iter().any(|r| &r.0 == n)) .find(|n| !new_rows.iter().any(|r| &r.0 == n))
@@ -839,10 +828,10 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
} }
ui.separator(); ui.separator();
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.add_enabled(e.dirty, egui::Button::new("Save")).clicked() { if ui.add_enabled(e.dirty, egui::Button::new(txt::common::SAVE)).clicked() {
save = true; save = true;
} }
ui.label(RichText::new("Writes http-client.env.json and http-client.private.env.json.").weak()); ui.label(RichText::new(txt::env::SAVE_NOTE).weak());
}); });
}); });
if e.selected != ed.selected { if e.selected != ed.selected {
@@ -888,7 +877,7 @@ fn apply_rows(file: &mut EnvFile, env: &str, rows: &[(String, String, bool, bool
fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec<Action>) { fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec<Action>) {
if state.collections.is_empty() { if state.collections.is_empty() {
acts.push(Action::QuickOpen(None)); acts.push(Action::QuickOpen(None));
acts.push(Action::Error("Open a collection to quick-open its requests".into())); acts.push(Action::Error(txt::msg::NEED_COLLECTION_FOR_QUICK_OPEN.into()));
return; return;
} }
let query = q.query.to_lowercase(); let query = q.query.to_lowercase();
@@ -943,7 +932,7 @@ fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec<Act
next.selected = (selected + 1).min(items.len().saturating_sub(1)); next.selected = (selected + 1).min(items.len().saturating_sub(1));
} }
egui::Window::new("Open request") egui::Window::new(txt::quick_open::TITLE)
.title_bar(false) .title_bar(false)
.anchor(egui::Align2::CENTER_TOP, [0.0, 60.0]) .anchor(egui::Align2::CENTER_TOP, [0.0, 60.0])
.fixed_size([520.0, 360.0]) .fixed_size([520.0, 360.0])
@@ -951,7 +940,7 @@ fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec<Act
let mut text = q.query.clone(); let mut text = q.query.clone();
let r = ui.add( let r = ui.add(
egui::TextEdit::singleline(&mut text) egui::TextEdit::singleline(&mut text)
.hint_text("Type to find a request…") .hint_text(txt::quick_open::HINT)
.desired_width(f32::INFINITY) .desired_width(f32::INFINITY)
.id_salt("quick-open"), .id_salt("quick-open"),
); );
@@ -976,7 +965,7 @@ fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec<Act
} }
} }
if items.is_empty() { if items.is_empty() {
ui.label(RichText::new("No matching requests").weak()); ui.label(RichText::new(txt::quick_open::NO_MATCHES).weak());
} }
}); });
}); });
+5 -1
View File
@@ -11,7 +11,11 @@ fn ui_symbols_exist_in_the_bundled_fonts() {
let files = std::fs::read_dir(src_dir.join("ui")) let files = std::fs::read_dir(src_dir.join("ui"))
.unwrap() .unwrap()
.map(|e| e.unwrap().path()) .map(|e| e.unwrap().path())
.chain([src_dir.join("action.rs"), src_dir.join("state.rs")]); .chain([
src_dir.join("action.rs"),
src_dir.join("state.rs"),
src_dir.join("strings.rs"),
]);
let mut missing = Vec::new(); let mut missing = Vec::new();
for path in files { for path in files {
let src = std::fs::read_to_string(&path).unwrap(); let src = std::fs::read_to_string(&path).unwrap();
+203 -30
View File
@@ -1,11 +1,13 @@
//! Per-folder settings, a reqlite extension: `<folder>/.reqlite/folder.json`. //! Per-folder settings, a reqlite extension: `<folder>/.reqlite/folder.json`.
//! //!
//! For now it only holds the folder's default auth, an `Authorization` //! For now it only holds the folder's default auth, a header that requests
//! header value that requests in the folder (and its subfolders) use when //! in the folder (and its subfolders) use when they don't set auth
//! they don't set one themselves: //! themselves. A string is an `Authorization` header value; an object names
//! some other header:
//! //!
//! ```json //! ```json
//! { "auth": "Bearer {{token}}" } //! { "auth": "Bearer {{token}}" }
//! { "auth": { "header": "X-API-Key", "value": "{{api_key}}" } }
//! ``` //! ```
//! //!
//! `"auth": null` means "no auth" (it stops inheritance from parent //! `"auth": null` means "no auth" (it stops inheritance from parent
@@ -24,6 +26,57 @@ pub const DIR: &str = ".reqlite";
pub const FILE: &str = "folder.json"; pub const FILE: &str = "folder.json";
/// `# @no-auth`: the request sends no auth even if its folder has one. /// `# @no-auth`: the request sends no auth even if its folder has one.
pub const NO_AUTH_DIRECTIVE: &str = "no-auth"; pub const NO_AUTH_DIRECTIVE: &str = "no-auth";
/// `# @auth-header X-API-Key`: the request's own auth is that header rather
/// than `Authorization`.
pub const AUTH_HEADER_DIRECTIVE: &str = "auth-header";
pub const AUTHORIZATION: &str = "Authorization";
/// The header auth is sent in: usually `Authorization`, but APIs that take a
/// key in a header of their own (`X-API-Key: …`) are common too.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthHeader {
pub name: String,
pub value: String,
}
impl AuthHeader {
/// An `Authorization` header with this value.
pub fn authorization(value: impl Into<String>) -> Self {
Self {
name: AUTHORIZATION.into(),
value: value.into(),
}
}
pub fn custom(name: impl Into<String>, value: impl Into<String>) -> Self {
Self {
name: name.into(),
value: value.into(),
}
}
pub fn is_authorization(&self) -> bool {
self.name.eq_ignore_ascii_case(AUTHORIZATION)
}
}
/// An `Authorization` header value, like the string form in folder.json.
impl From<&str> for AuthHeader {
fn from(value: &str) -> Self {
Self::authorization(value)
}
}
/// The value for `Authorization`, `Name: value` for other headers.
impl std::fmt::Display for AuthHeader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_authorization() {
f.write_str(&self.value)
} else {
write!(f, "{}: {}", self.name, self.value)
}
}
}
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum FolderError { pub enum FolderError {
@@ -40,8 +93,8 @@ pub enum FolderAuth {
Inherit, Inherit,
/// No auth for this folder, whatever the parents say. /// No auth for this folder, whatever the parents say.
None, None,
/// An `Authorization` header value, e.g. `Bearer {{token}}`. /// A header, e.g. `Authorization: Bearer {{token}}`.
Header(String), Header(AuthHeader),
} }
#[derive(Debug, Clone, PartialEq, Eq, Default)] #[derive(Debug, Clone, PartialEq, Eq, Default)]
@@ -69,7 +122,20 @@ impl FolderSettings {
None => FolderAuth::Inherit, None => FolderAuth::Inherit,
Some(Value::Null) => FolderAuth::None, Some(Value::Null) => FolderAuth::None,
Some(Value::String(s)) if s.trim().is_empty() => FolderAuth::None, Some(Value::String(s)) if s.trim().is_empty() => FolderAuth::None,
Some(Value::String(s)) => FolderAuth::Header(s), Some(Value::String(s)) => FolderAuth::Header(AuthHeader::authorization(s)),
Some(Value::Object(o)) => {
let field = |k: &str| o.get(k).and_then(Value::as_str).map(str::to_string);
match (field("header"), field("value")) {
(Some(name), Some(value)) if !name.trim().is_empty() => {
FolderAuth::Header(AuthHeader::custom(name.trim(), value))
}
_ => {
return Err(FolderError::Shape {
path: path.to_path_buf(),
})
}
}
}
Some(_) => { Some(_) => {
return Err(FolderError::Shape { return Err(FolderError::Shape {
path: path.to_path_buf(), path: path.to_path_buf(),
@@ -86,8 +152,11 @@ impl FolderSettings {
FolderAuth::None => { FolderAuth::None => {
map.insert("auth".into(), Value::Null); map.insert("auth".into(), Value::Null);
} }
FolderAuth::Header(h) if h.is_authorization() => {
map.insert("auth".into(), Value::String(h.value.clone()));
}
FolderAuth::Header(h) => { FolderAuth::Header(h) => {
map.insert("auth".into(), Value::String(h.clone())); map.insert("auth".into(), serde_json::json!({ "header": h.name, "value": h.value }));
} }
} }
map.extend(self.other.clone()); map.extend(self.other.clone());
@@ -127,8 +196,8 @@ pub fn settings_dir(path: &Path) -> Option<&Path> {
pub struct InheritedAuth { pub struct InheritedAuth {
/// The folder whose setting applies. /// The folder whose setting applies.
pub from: PathBuf, pub from: PathBuf,
/// The header value; `None` when that folder says "no auth". /// The header; `None` when that folder says "no auth".
pub value: Option<String>, pub value: Option<AuthHeader>,
} }
/// Walks from `dir` up to `root` (inclusive) and returns the first folder /// Walks from `dir` up to `root` (inclusive) and returns the first folder
@@ -193,11 +262,21 @@ pub fn set_no_auth(req: &mut Request, on: bool) {
} }
} }
/// The header named by `# @auth-header`, if any.
fn auth_header_directive(req: &Request) -> Option<&str> {
req.directives
.other
.iter()
.find(|(n, v)| n == AUTH_HEADER_DIRECTIVE && !v.trim().is_empty())
.map(|(_, v)| v.trim())
}
/// How a request gets its auth. /// How a request gets its auth.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthMode { pub enum AuthMode {
/// It has its own `Authorization` header. /// It has its own auth header: `Authorization`, or the one named by
Own(String), /// `# @auth-header`.
Own(AuthHeader),
/// `# @no-auth`. /// `# @no-auth`.
NoAuth, NoAuth,
/// From its folder. /// From its folder.
@@ -205,29 +284,58 @@ pub enum AuthMode {
} }
pub fn auth_mode(req: &Request) -> AuthMode { pub fn auth_mode(req: &Request) -> AuthMode {
match req.header("authorization") { let custom = auth_header_directive(req).and_then(|n| Some(AuthHeader::custom(n, req.header(n)?)));
Some(v) => AuthMode::Own(v.to_string()), if let Some(h) = custom {
return AuthMode::Own(h);
}
match req.header(AUTHORIZATION) {
Some(v) => AuthMode::Own(AuthHeader::authorization(v)),
None if has_no_auth(req) => AuthMode::NoAuth, None if has_no_auth(req) => AuthMode::NoAuth,
None => AuthMode::Inherit, None => AuthMode::Inherit,
} }
} }
/// The request as it is sent: with the inherited `Authorization` header /// Changes how the request gets its auth: drops its current auth header
/// added when it inherits one. /// (and `# @auth-header` / `# @no-auth`), then writes the new one.
pub fn set_auth_mode(req: &mut Request, mode: &AuthMode) {
if let Some(n) = auth_header_directive(req).map(str::to_string) {
req.remove_header(&n);
}
req.remove_header(AUTHORIZATION);
req.directives
.other
.retain(|(n, _)| n != AUTH_HEADER_DIRECTIVE && n != NO_AUTH_DIRECTIVE);
match mode {
AuthMode::Own(h) => {
if !h.is_authorization() {
req.directives
.other
.push((AUTH_HEADER_DIRECTIVE.into(), h.name.clone()));
}
req.set_header(&h.name, h.value.as_str());
}
AuthMode::NoAuth => set_no_auth(req, true),
AuthMode::Inherit => {}
}
}
/// The request as it is sent: with the inherited auth header added when it
/// inherits one (a header the request already sets wins).
pub fn with_inherited_auth<'a>(req: &'a Request, inherited: Option<&InheritedAuth>) -> Cow<'a, Request> { pub fn with_inherited_auth<'a>(req: &'a Request, inherited: Option<&InheritedAuth>) -> Cow<'a, Request> {
match (auth_mode(req), inherited.and_then(|i| i.value.as_deref())) { match (auth_mode(req), inherited.and_then(|i| i.value.as_ref())) {
(AuthMode::Inherit, Some(v)) => { (AuthMode::Inherit, Some(h)) if h.is_authorization() || req.header(&h.name).is_none() => {
let mut r = req.clone(); let mut r = req.clone();
r.set_header("Authorization", v); r.set_header(&h.name, h.value.as_str());
Cow::Owned(r) Cow::Owned(r)
} }
_ => Cow::Borrowed(req), _ => Cow::Borrowed(req),
} }
} }
/// Whether two header values are the same auth (ignoring spacing). /// Whether two headers are the same auth (ignoring the name's case and the
pub fn same_auth(a: &str, b: &str) -> bool { /// value's spacing).
a.split_whitespace().eq(b.split_whitespace()) pub fn same_auth(a: &AuthHeader, b: &AuthHeader) -> bool {
a.name.eq_ignore_ascii_case(&b.name) && a.value.split_whitespace().eq(b.value.split_whitespace())
} }
#[cfg(test)] #[cfg(test)]
@@ -240,7 +348,7 @@ mod tests {
fn parses_and_writes_back() { fn parses_and_writes_back() {
let p = Path::new("f.json"); let p = Path::new("f.json");
let s = FolderSettings::parse(r#"{ "auth": "Bearer {{t}}", "x": 1 }"#, p).unwrap(); let s = FolderSettings::parse(r#"{ "auth": "Bearer {{t}}", "x": 1 }"#, p).unwrap();
assert_eq!(s.auth, FolderAuth::Header("Bearer {{t}}".into())); assert_eq!(s.auth, FolderAuth::Header(AuthHeader::authorization("Bearer {{t}}")));
assert_eq!(FolderSettings::parse(&s.to_json(), p).unwrap(), s); assert_eq!(FolderSettings::parse(&s.to_json(), p).unwrap(), s);
assert!(s.to_json().contains("\"x\": 1")); assert!(s.to_json().contains("\"x\": 1"));
assert_eq!( assert_eq!(
@@ -251,6 +359,12 @@ mod tests {
assert!(FolderSettings::parse("{}", p).unwrap().is_empty()); assert!(FolderSettings::parse("{}", p).unwrap().is_empty());
assert!(FolderSettings::parse(r#"{"auth": 3}"#, p).is_err()); assert!(FolderSettings::parse(r#"{"auth": 3}"#, p).is_err());
assert!(FolderSettings::parse("[]", p).is_err()); assert!(FolderSettings::parse("[]", p).is_err());
let s = FolderSettings::parse(r#"{"auth": {"header": "X-API-Key", "value": "{{k}}"}}"#, p).unwrap();
assert_eq!(s.auth, FolderAuth::Header(AuthHeader::custom("X-API-Key", "{{k}}")));
assert_eq!(FolderSettings::parse(&s.to_json(), p).unwrap(), s);
assert!(FolderSettings::parse(r#"{"auth": {"header": "", "value": "x"}}"#, p).is_err());
assert!(FolderSettings::parse(r#"{"auth": {"value": "x"}}"#, p).is_err());
} }
#[test] #[test]
@@ -266,7 +380,7 @@ mod tests {
fn inherits_from_the_nearest_folder_within_the_root() { fn inherits_from_the_nearest_folder_within_the_root() {
let mut m = BTreeMap::new(); let mut m = BTreeMap::new();
let hdr = |s: &str| FolderSettings { let hdr = |s: &str| FolderSettings {
auth: FolderAuth::Header(s.into()), auth: FolderAuth::Header(AuthHeader::authorization(s)),
..Default::default() ..Default::default()
}; };
m.insert(PathBuf::from("/"), hdr("outside")); m.insert(PathBuf::from("/"), hdr("outside"));
@@ -282,7 +396,10 @@ mod tests {
let get = |p: &Path| m.get(p); let get = |p: &Path| m.get(p);
let root = Path::new("/c"); let root = Path::new("/c");
let a = inherited_auth(root, Path::new("/c/api/v2"), get).unwrap(); let a = inherited_auth(root, Path::new("/c/api/v2"), get).unwrap();
assert_eq!((a.from.as_path(), a.value.as_deref()), (root, Some("Bearer root"))); assert_eq!(
(a.from.as_path(), a.value.map(|h| h.value).as_deref()),
(root, Some("Bearer root"))
);
let a = inherited_auth(root, Path::new("/c/public/x"), get).unwrap(); let a = inherited_auth(root, Path::new("/c/public/x"), get).unwrap();
assert_eq!(a.value, None); assert_eq!(a.value, None);
assert_eq!(inherited_auth(Path::new("/d"), Path::new("/d/x"), get), None); assert_eq!(inherited_auth(Path::new("/d"), Path::new("/d/x"), get), None);
@@ -294,11 +411,15 @@ mod tests {
let modes: Vec<_> = f.requests().map(auth_mode).collect(); let modes: Vec<_> = f.requests().map(auth_mode).collect();
assert_eq!( assert_eq!(
modes, modes,
vec![AuthMode::Own("Bearer own".into()), AuthMode::NoAuth, AuthMode::Inherit] vec![
AuthMode::Own(AuthHeader::authorization("Bearer own")),
AuthMode::NoAuth,
AuthMode::Inherit
]
); );
let inh = InheritedAuth { let inh = InheritedAuth {
from: "/c".into(), from: "/c".into(),
value: Some("Bearer folder".into()), value: Some(AuthHeader::authorization("Bearer folder")),
}; };
let sent: Vec<_> = f let sent: Vec<_> = f
.requests() .requests()
@@ -316,7 +437,59 @@ mod tests {
let mut r = f.request(2).unwrap().clone(); let mut r = f.request(2).unwrap().clone();
set_no_auth(&mut r, true); set_no_auth(&mut r, true);
assert!(f.replace_request(2, &r).unwrap().ends_with("###\n# @no-auth\nGET /c\n")); assert!(f.replace_request(2, &r).unwrap().ends_with("###\n# @no-auth\nGET /c\n"));
assert!(same_auth("Basic a b", "Basic a b")); assert!(same_auth(
&AuthHeader::authorization("Basic a b"),
&AuthHeader::authorization("Basic a b")
));
assert!(!same_auth(
&AuthHeader::authorization("k"),
&AuthHeader::custom("X-API-Key", "k")
));
}
#[test]
fn custom_header_auth() {
let f = HttpFile::parse(
"# @auth-header X-API-Key\nGET /a\nX-API-Key: own\n\n###\nGET /b\nX-API-Key: plain\n\n###\nGET /c\n",
);
let key = |s: &str| AuthHeader::custom("X-API-Key", s);
assert_eq!(f.request(0).map(auth_mode), Some(AuthMode::Own(key("own"))));
// Without the directive the header is just a header.
assert_eq!(f.request(1).map(auth_mode), Some(AuthMode::Inherit));
let inh = InheritedAuth {
from: "/c".into(),
value: Some(key("folder")),
};
let sent: Vec<_> = f
.requests()
.map(|r| {
with_inherited_auth(r, Some(&inh))
.header("x-api-key")
.map(str::to_string)
})
.collect();
assert_eq!(
sent,
vec![Some("own".into()), Some("plain".into()), Some("folder".into())]
);
// Switching kinds removes the old header and directive.
let mut r = f.request(0).unwrap().clone();
set_auth_mode(&mut r, &AuthMode::Own(AuthHeader::authorization("Bearer t")));
assert_eq!(r.header("x-api-key"), None);
assert_eq!(auth_mode(&r), AuthMode::Own(AuthHeader::authorization("Bearer t")));
set_auth_mode(&mut r, &AuthMode::Own(key("k2")));
assert_eq!(r.header("authorization"), None);
assert_eq!(auth_mode(&r), AuthMode::Own(key("k2")));
assert!(f
.replace_request(0, &r)
.unwrap()
.starts_with("# @auth-header X-API-Key\nGET /a\nX-API-Key: k2\n"));
set_auth_mode(&mut r, &AuthMode::NoAuth);
assert_eq!((r.header("x-api-key"), auth_mode(&r)), (None, AuthMode::NoAuth));
set_auth_mode(&mut r, &AuthMode::Inherit);
assert_eq!(auth_mode(&r), AuthMode::Inherit);
} }
#[test] #[test]
@@ -328,13 +501,13 @@ mod tests {
std::fs::create_dir_all(dir.path().join(DIR)).unwrap(); std::fs::create_dir_all(dir.path().join(DIR)).unwrap();
std::fs::write(settings_path(dir.path()), r#"{"auth": "Bearer outside"}"#).unwrap(); std::fs::write(settings_path(dir.path()), r#"{"auth": "Bearer outside"}"#).unwrap();
assert_eq!( assert_eq!(
inherited_auth_on_disk(&api).unwrap().unwrap().value.as_deref(), inherited_auth_on_disk(&api).unwrap().unwrap().value,
Some("Bearer outside") Some(AuthHeader::authorization("Bearer outside"))
); );
std::fs::write(root.join(crate::env::PUBLIC_FILE), "{}").unwrap(); std::fs::write(root.join(crate::env::PUBLIC_FILE), "{}").unwrap();
assert_eq!(inherited_auth_on_disk(&api).unwrap(), None); assert_eq!(inherited_auth_on_disk(&api).unwrap(), None);
std::fs::write(settings_path(&api), r#"{"auth": "Bearer api"}"#).unwrap(); std::fs::write(settings_path(&api), r#"{"auth": "Bearer api"}"#).unwrap();
let a = inherited_auth_on_disk(&api).unwrap().unwrap(); let a = inherited_auth_on_disk(&api).unwrap().unwrap();
assert_eq!((a.from, a.value.as_deref()), (api, Some("Bearer api"))); assert_eq!((a.from, a.value), (api, Some(AuthHeader::authorization("Bearer api"))));
} }
} }