Files
reqlite/crates/app/src/state.rs
T
Torbjörn Molin 1e7f8678eb
windows / build (push) Successful in 5m0s
Added custom auth support
2026-11-09 12:56:54 +01:00

668 lines
20 KiB
Rust

//! `AppState`: everything the UI shows, as plain data. Only
//! [`crate::action::update`] changes it.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Instant, SystemTime};
use reqlite_core::collection::Node;
use reqlite_core::cookies::CookieJar;
use reqlite_core::env::Environments;
use reqlite_core::folder::{self, AuthHeader, FolderAuth, FolderSettings, InheritedAuth};
use reqlite_core::http::{BodyStore, Response};
use reqlite_core::httpfile::{HttpFile, RequestKey};
use reqlite_core::params::Param;
use reqlite_core::template::Resolver;
use reqlite_core::{CancelToken, Request};
use crate::history::HistoryEntry;
use crate::settings::Settings;
use crate::strings as txt;
pub type TabId = u64;
#[derive(Default)]
pub struct AppState {
pub tabs: Vec<Tab>,
pub active: Option<TabId>,
pub next_tab_id: TabId,
/// Open collections, in the order they were opened.
pub collections: Vec<CollectionState>,
/// The collection last chosen in the sidebar or through a tab. Untitled
/// tabs, the environment picker and the cookie viewer use it.
pub active_collection: Option<PathBuf>,
pub settings: Settings,
/// Oldest first.
pub history: Vec<HistoryEntry>,
/// Keyed by collection root; `None` for requests outside a collection.
pub cookie_jars: HashMap<Option<PathBuf>, CookieJar>,
pub status: Option<Status>,
pub dialog: Option<Dialog>,
pub windows: Windows,
pub quick_open: Option<QuickOpen>,
pub env_editor: Option<EnvEditor>,
/// Asks the UI to focus the URL field on the next frame.
pub focus_url: bool,
/// Set when the user confirmed quitting with unsaved changes.
pub quit_confirmed: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
pub text: String,
pub is_error: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Windows {
pub history: bool,
pub cookies: bool,
pub settings: bool,
pub about: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dialog {
/// Closing a tab with unsaved changes.
ConfirmCloseTab(TabId),
/// Closing several tabs, these of which have unsaved changes.
ConfirmCloseTabs(Vec<TabId>),
/// Quitting with unsaved changes.
ConfirmQuit,
/// The file of a tab with unsaved changes changed on disk.
Conflict { tab: TabId, path: PathBuf },
/// A text prompt (new file, rename …).
Prompt(Prompt),
/// Confirm a destructive collection operation.
ConfirmDelete(DeleteTarget),
/// Editing a folder's (or the collection's) default auth.
FolderAuth(FolderAuthEdit),
/// Making requests in a folder inherit its auth.
ConsolidateAuth(ConsolidateAuth),
/// Result of a Postman import.
ImportSummary {
root: PathBuf,
files: usize,
warnings: Vec<String>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FolderAuthEdit {
pub dir: PathBuf,
pub auth: FolderAuth,
}
/// A request in a collection, for lists in dialogs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestRef {
pub file: PathBuf,
pub index: usize,
pub label: String,
}
/// The plan shown by the "Consolidate auth" dialog. Built by
/// `action::plan_consolidation`; the UI only changes the choices in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConsolidateAuth {
pub dir: PathBuf,
/// The auth requests in `dir` should inherit.
pub target: Option<AuthHeader>,
/// `dir` doesn't have `target` as its own setting yet; applying writes it.
pub set_folder: bool,
/// Values to pick `target` from (with how many requests use each), when
/// `dir` has no auth of its own.
pub choices: Vec<(AuthHeader, usize)>,
/// Requests with their own auth header.
pub own: Vec<OwnAuth>,
/// Requests that inherit today and would send something else once
/// `target` is set on the folder.
pub affected: Vec<(RequestRef, Option<AuthHeader>)>,
/// Give the affected requests their current auth explicitly (a header,
/// or `# @no-auth`) so they keep sending what they send today.
pub keep_affected: bool,
/// Requests skipped because their tab has unsaved edits.
pub skipped_dirty: Vec<RequestRef>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnAuth {
pub request: RequestRef,
pub value: AuthHeader,
/// What the request would inherit without its header.
pub inherits: Option<AuthHeader>,
/// Remove the header.
pub selected: bool,
}
impl OwnAuth {
/// Removing the header keeps the request sending the same thing.
pub fn same(&self) -> bool {
self.inherits
.as_ref()
.is_some_and(|i| folder::same_auth(i, &self.value))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeleteTarget {
Request { file: PathBuf, index: usize, label: String },
File(PathBuf),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prompt {
pub kind: PromptKind,
pub title: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PromptKind {
NewFile { dir: PathBuf },
RenameFile { path: PathBuf },
RenameRequest { file: PathBuf, index: usize },
RenameTab { tab: TabId },
NewEnvironment,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct QuickOpen {
pub query: String,
pub selected: usize,
}
/// The environment editor works on a copy that is written on Save.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvEditor {
/// The collection whose env files are being edited.
pub root: PathBuf,
pub envs: Environments,
pub selected: String,
/// Private values whose text is shown instead of `••••`.
pub revealed: Vec<(String, String)>,
pub dirty: bool,
}
pub struct CollectionState {
pub root: PathBuf,
pub tree: Node,
pub files: BTreeMap<PathBuf, HttpFile>,
/// Folder settings (default auth) by folder.
pub folders: BTreeMap<PathBuf, FolderSettings>,
pub folder_errors: Vec<String>,
pub envs: Environments,
pub selected_env: Option<String>,
pub env_error: Option<String>,
/// The private env file exists but is not git-ignored.
pub private_not_ignored: bool,
pub gitignore_offer_dismissed: bool,
}
impl CollectionState {
/// Every request in the collection as `(file, index, request)`.
pub fn all_requests(&self) -> impl Iterator<Item = (&PathBuf, usize, &Request)> {
self.files
.iter()
.flat_map(|(p, f)| f.requests().enumerate().map(move |(i, r)| (p, i, r)))
}
pub fn relative<'a>(&self, p: &'a Path) -> &'a Path {
p.strip_prefix(&self.root).unwrap_or(p)
}
pub fn name(&self) -> &str {
self.tree.name()
}
pub fn contains(&self, p: &Path) -> bool {
p.starts_with(&self.root)
}
/// The auth requests in `dir` inherit from their folders.
pub fn inherited_auth(&self, dir: &Path) -> Option<InheritedAuth> {
folder::inherited_auth(&self.root, dir, |d| self.folders.get(d))
}
/// The folder's own auth setting.
pub fn folder_auth(&self, dir: &Path) -> FolderAuth {
self.folders.get(dir).map(|s| s.auth.clone()).unwrap_or_default()
}
/// `dir` relative to the root, for messages ("the collection" for the root).
pub fn folder_label(&self, dir: &Path) -> String {
if dir == self.root {
txt::names::collection(self.name())
} else {
txt::names::folder(self.relative(dir).display())
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RequestTab {
#[default]
Params,
Headers,
Body,
Auth,
Source,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ResponseTab {
#[default]
Body,
Headers,
Timings,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BodyView {
#[default]
Pretty,
Raw,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Origin {
pub file: PathBuf,
pub key: RequestKey,
}
pub struct InFlight {
pub cancel: CancelToken,
pub started: Instant,
pub seq: u64,
/// What goes into history once the response arrives.
pub history: HistoryEntry,
pub cookie_jar: Option<Option<PathBuf>>,
pub url: String,
}
pub struct Tab {
pub id: TabId,
pub origin: Option<Origin>,
/// The request being edited.
pub request: Request,
/// The last loaded or saved version (for the dirty marker).
pub saved: Request,
/// The Source tab text.
pub source: String,
pub saved_source: String,
/// The last edit was made in the Source tab, so its text (with comments
/// and anything else the form doesn't model) is what gets saved.
pub source_authoritative: bool,
pub source_error: Option<String>,
/// Derived from the URL; edits go back to the URL.
pub params: Vec<Param>,
pub request_tab: RequestTab,
pub response_tab: ResponseTab,
pub body_view: BodyView,
pub in_flight: Option<InFlight>,
pub seq: u64,
pub response: Option<ResponseView>,
pub error: Option<String>,
pub search: Search,
/// The request was deleted from (or never belonged to) its file.
pub orphaned: bool,
}
impl Tab {
pub fn new(id: TabId, request: Request, origin: Option<Origin>, source: String) -> Self {
Self {
id,
origin,
params: reqlite_core::params::parse_params(&request.url),
saved: request.clone(),
request,
saved_source: source.clone(),
source,
source_authoritative: false,
source_error: None,
request_tab: RequestTab::default(),
response_tab: ResponseTab::default(),
body_view: BodyView::default(),
in_flight: None,
seq: 0,
response: None,
error: None,
search: Search::default(),
orphaned: false,
}
}
pub fn is_dirty(&self) -> bool {
!self.request.same_content(&self.saved) || (self.source_authoritative && self.source != self.saved_source)
}
pub fn title(&self) -> String {
if let Some(n) = self.request.display_name() {
return n.to_string();
}
let url = self.request.url.trim();
if url.is_empty() {
txt::common::NEW_REQUEST.into()
} else {
let short: String = url.chars().take(40).collect();
if url.chars().count() > 40 {
format!("{short}…")
} else {
short
}
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Search {
pub open: bool,
pub query: String,
/// `(line, byte range in line)`.
pub matches: Vec<(usize, std::ops::Range<usize>)>,
pub current: usize,
/// Asks the UI to scroll to this line.
pub scroll_to: Option<usize>,
}
pub struct ResponseView {
pub response: Response,
pub received_at: SystemTime,
pub prepared: Option<PreparedBody>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BodyKind {
Json,
Text,
Image,
Binary,
Empty,
}
/// A response body made ready for display (off the UI thread).
#[derive(Debug, Clone)]
pub struct PreparedBody {
pub kind: BodyKind,
pub raw: TextLines,
pub pretty: Option<TextLines>,
pub image: Option<Arc<[u8]>>,
/// Only the first part of the body is shown.
pub truncated: bool,
}
impl PreparedBody {
pub fn text(&self, view: BodyView) -> &TextLines {
match (view, &self.pretty) {
(BodyView::Pretty, Some(p)) => p,
_ => &self.raw,
}
}
}
/// Text plus the byte offset where each line starts.
#[derive(Debug, Clone, Default)]
pub struct TextLines {
pub text: Arc<String>,
pub starts: Arc<Vec<usize>>,
}
impl TextLines {
pub fn new(text: String) -> Self {
let mut starts = vec![0];
starts.extend(text.match_indices('\n').map(|(i, _)| i + 1));
if starts.len() > 1 && *starts.last().unwrap() == text.len() {
starts.pop();
}
Self {
text: Arc::new(text),
starts: Arc::new(starts),
}
}
pub fn line_count(&self) -> usize {
if self.text.is_empty() {
0
} else {
self.starts.len()
}
}
pub fn line(&self, i: usize) -> &str {
let start = self.starts[i];
let end = self.starts.get(i + 1).copied().unwrap_or(self.text.len());
self.text[start..end].trim_end_matches(['\n', '\r'])
}
}
impl AppState {
pub fn tab(&self, id: TabId) -> Option<&Tab> {
self.tabs.iter().find(|t| t.id == id)
}
pub fn tab_mut(&mut self, id: TabId) -> Option<&mut Tab> {
self.tabs.iter_mut().find(|t| t.id == id)
}
pub fn active_tab(&self) -> Option<&Tab> {
self.active.and_then(|id| self.tab(id))
}
pub fn alloc_tab_id(&mut self) -> TabId {
self.next_tab_id += 1;
self.next_tab_id
}
pub fn any_dirty(&self) -> bool {
self.tabs.iter().any(Tab::is_dirty)
}
/// The collection a path belongs to.
pub fn collection_of(&self, p: &Path) -> Option<&CollectionState> {
self.collections.iter().find(|c| c.contains(p))
}
pub fn collection_of_mut(&mut self, p: &Path) -> Option<&mut CollectionState> {
self.collections.iter_mut().find(|c| c.contains(p))
}
pub fn collection(&self, root: &Path) -> Option<&CollectionState> {
self.collections.iter().find(|c| c.root == root)
}
pub fn collection_mut(&mut self, root: &Path) -> Option<&mut CollectionState> {
self.collections.iter_mut().find(|c| c.root == root)
}
/// The collection the environment picker and untitled tabs use: the
/// active tab's, else the one last chosen, else the first.
pub fn current_collection(&self) -> Option<&CollectionState> {
if let Some(c) = self
.active_tab()
.and_then(|t| t.origin.as_ref())
.and_then(|o| self.collection_of(&o.file))
{
return Some(c);
}
self.active_collection
.as_deref()
.and_then(|r| self.collection(r))
.or_else(|| self.collections.first())
}
/// The collection a tab belongs to (its file's, or the current one for
/// untitled tabs).
pub fn collection_for_tab(&self, tab: &Tab) -> Option<&CollectionState> {
match &tab.origin {
Some(o) => self.collection_of(&o.file),
None => self.current_collection(),
}
}
/// File variables of the tab's file plus its collection's environment.
pub fn resolver_for(&self, tab: &Tab) -> Resolver {
let file_vars = tab
.origin
.as_ref()
.and_then(|o| self.collection_of(&o.file)?.files.get(&o.file))
.map(|f| f.variables())
.unwrap_or_default();
match self.collection_for_tab(tab) {
Some(c) => c.envs.resolver(c.selected_env.as_deref(), &file_vars),
None => Environments::default().resolver(None, &file_vars),
}
}
/// The folder whose auth a tab's request inherits: its file's folder, or
/// for untitled tabs the root of the current collection.
pub fn auth_dir_for(&self, tab: &Tab) -> Option<PathBuf> {
match &tab.origin {
Some(o) => self.collection_of(&o.file).and(o.file.parent()).map(Path::to_path_buf),
None => self.current_collection().map(|c| c.root.clone()),
}
}
/// The auth a tab's request inherits from its folders.
pub fn inherited_auth_for(&self, tab: &Tab) -> Option<InheritedAuth> {
let dir = self.auth_dir_for(tab)?;
self.collection_for_tab(tab)?.inherited_auth(&dir)
}
/// Whether `name` comes from the private env file (shown masked).
pub fn is_private_var(&self, tab: &Tab, name: &str) -> bool {
self.collection_for_tab(tab).is_some_and(|c| {
let env = c.selected_env.as_deref().unwrap_or(reqlite_core::env::SHARED_ENV);
c.envs.is_private(env, name)
})
}
/// Directory that relative file references in the tab resolve against.
pub fn base_dir_for(&self, tab: &Tab) -> PathBuf {
if let Some(o) = &tab.origin {
if let Some(p) = o.file.parent() {
return p.to_path_buf();
}
}
if let Some(c) = self.current_collection() {
return c.root.clone();
}
std::env::current_dir().unwrap_or_default()
}
pub fn set_error(&mut self, text: impl Into<String>) {
self.status = Some(Status {
text: text.into(),
is_error: true,
});
}
pub fn set_info(&mut self, text: impl Into<String>) {
self.status = Some(Status {
text: text.into(),
is_error: false,
});
}
}
/// Builds a `PreparedBody` (runs on a blocking thread for big bodies).
pub fn prepare_body(body: &BodyStore, content_type: &str, max_display: u64) -> PreparedBody {
let ct = content_type.to_ascii_lowercase();
let mut bytes = match body {
BodyStore::InMemory(b) => b.as_ref().clone(),
BodyStore::TempFile(p) => {
use std::io::Read;
let mut buf = Vec::new();
if let Ok(f) = std::fs::File::open(&**p) {
let _ = f.take(max_display).read_to_end(&mut buf);
}
buf
}
};
let total = match body {
BodyStore::InMemory(b) => b.len() as u64,
BodyStore::TempFile(p) => std::fs::metadata(&**p).map(|m| m.len()).unwrap_or(0),
};
let truncated = total > max_display;
bytes.truncate(max_display as usize);
if bytes.is_empty() {
return PreparedBody {
kind: BodyKind::Empty,
raw: TextLines::default(),
pretty: None,
image: None,
truncated: false,
};
}
if ct.starts_with("image/") && !ct.contains("svg") && !truncated {
return PreparedBody {
kind: BodyKind::Image,
raw: TextLines::default(),
pretty: None,
image: Some(Arc::from(bytes.into_boxed_slice())),
truncated,
};
}
let looks_binary = std::str::from_utf8(&bytes[..bytes.len().min(4096)]).is_err()
&& !ct.starts_with("text/")
&& !ct.contains("json")
&& !ct.contains("xml");
if looks_binary {
return PreparedBody {
kind: BodyKind::Binary,
raw: TextLines::new(hex_dump(&bytes[..bytes.len().min(64 * 1024)])),
pretty: None,
image: None,
truncated: truncated || bytes.len() > 64 * 1024,
};
}
let text = String::from_utf8_lossy(&bytes).into_owned();
let is_json = ct.contains("json") || {
let t = text.trim_start();
(t.starts_with('{') || t.starts_with('[')) && !ct.contains("html")
};
if is_json && !truncated {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
let pretty = serde_json::to_string_pretty(&v).unwrap_or_default();
return PreparedBody {
kind: BodyKind::Json,
raw: TextLines::new(text),
pretty: Some(TextLines::new(pretty)),
image: None,
truncated,
};
}
}
PreparedBody {
kind: BodyKind::Text,
raw: TextLines::new(text),
pretty: None,
image: None,
truncated,
}
}
fn hex_dump(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 4);
for (i, chunk) in bytes.chunks(16).enumerate() {
out.push_str(&format!("{:08x} ", i * 16));
for j in 0..16 {
match chunk.get(j) {
Some(b) => out.push_str(&format!("{b:02x} ")),
None => out.push_str(" "),
}
}
out.push(' ');
for &b in chunk {
out.push(if b.is_ascii_graphic() || b == b' ' {
b as char
} else {
'.'
});
}
out.push('\n');
}
out
}