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