implement proxy exceptions tab

This commit is contained in:
yggverse 2025-07-26 05:21:29 +03:00
parent b15e4a5fc1
commit a7c6e79aac
13 changed files with 462 additions and 72 deletions

View File

@ -1,13 +1,15 @@
//! Proxy settings dialog //! Proxy settings dialog
mod rules; mod ignore;
mod rule;
use super::Profile; use super::Profile;
use adw::{ use adw::{
PreferencesGroup, PreferencesPage, PreferencesGroup, PreferencesPage,
prelude::{AdwDialogExt, PreferencesDialogExt, PreferencesGroupExt, PreferencesPageExt}, prelude::{AdwDialogExt, PreferencesDialogExt, PreferencesGroupExt, PreferencesPageExt},
}; };
use rules::Rules; use ignore::Ignore;
use rule::Rule;
use std::rc::Rc; use std::rc::Rc;
pub trait Proxy { pub trait Proxy {
@ -17,7 +19,8 @@ pub trait Proxy {
impl Proxy for adw::PreferencesDialog { impl Proxy for adw::PreferencesDialog {
fn proxy(profile: &Rc<Profile>) -> Self { fn proxy(profile: &Rc<Profile>) -> Self {
// Init components // Init components
let rules = Rules::build(profile); let ignore = Ignore::build(profile);
let rule = Rule::build(profile);
// Init widget // Init widget
let d = adw::PreferencesDialog::builder() let d = adw::PreferencesDialog::builder()
@ -32,23 +35,24 @@ impl Proxy for adw::PreferencesDialog {
.build(); .build();
p.add(&{ p.add(&{
let g = PreferencesGroup::new(); let g = PreferencesGroup::new();
g.add(&rules.widget); g.add(&rule.widget);
g g
}); });
/* @TODO URL entry p.add(&{
let g = PreferencesGroup::builder().title("Test").build();
//g.add(&Box::rules(profile));
g
});*/
p p
}); });
d.add( d.add(&{
&PreferencesPage::builder() let p = PreferencesPage::builder()
.title("Exceptions") .title("Exceptions")
.icon_name("action-unavailable-symbolic") .icon_name("action-unavailable-symbolic")
.build(), .build();
); p.add(&{
let g = PreferencesGroup::new();
g.add(&ignore.widget);
g
});
p
});
d.add( d.add(
&PreferencesPage::builder() &PreferencesPage::builder()
@ -61,18 +65,27 @@ impl Proxy for adw::PreferencesDialog {
let profile = profile.clone(); let profile = profile.clone();
move |_| { move |_| {
profile.proxy.rule.clear(); profile.proxy.rule.clear();
for rule in rules.take() { for r in rule.take() {
if rule.validate() { if r.validate() {
profile.proxy.rule.add( profile.proxy.rule.add(
rule.id, r.id,
rule.is_enabled(), r.is_enabled(),
rule.priority(), r.priority(),
rule.request().to_string(), r.request().to_string(),
rule.url().to_string(), r.url().to_string(),
rule.time, r.time,
) )
} }
} }
profile.proxy.ignore.clear();
for i in ignore.take() {
if i.validate() {
profile
.proxy
.ignore
.add(i.id, i.is_enabled(), i.host().to_string(), i.time)
}
}
} }
}); });
d d

View File

@ -0,0 +1,91 @@
mod row;
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use super::Profile;
use gtk::{
Box,
glib::{GString, uuid_string_random},
prelude::BoxExt,
};
use row::Row;
pub struct Ignore {
pub widget: Box,
rows: Rc<RefCell<HashMap<GString, Row>>>,
}
impl Ignore {
pub fn build(profile: &Rc<Profile>) -> Self {
let config = profile.proxy.ignore.all();
let rows: Rc<RefCell<HashMap<GString, Row>>> =
Rc::new(RefCell::new(HashMap::with_capacity(config.len())));
let form = Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(8)
.build();
{
let mut r = rows.borrow_mut();
for proxy in config {
let key = uuid_string_random();
let row = Row::build(
proxy.id,
Some(&proxy.time),
Some(&proxy.host),
proxy.is_enabled,
{
let form = form.clone();
let key = key.clone();
let rows = rows.clone();
move || form.remove(&rows.borrow_mut().remove(&key).unwrap().widget)
},
);
row.validate();
form.append(&row.widget);
assert!(r.insert(key, row).is_none())
}
}
let add = {
let b = Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(8)
.build();
b.append(&row::new({
let form = form.clone();
let rows = rows.clone();
move || {
let key = uuid_string_random();
let row = Row::build(None, None, None, false, {
let rows = rows.clone();
let key = key.clone();
let form = form.clone();
move || form.remove(&rows.borrow_mut().remove(&key).unwrap().widget)
});
form.append(&row.widget);
assert!(rows.borrow_mut().insert(key, row).is_none())
}
}));
b
};
let widget = Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(8)
.build();
widget.append(&form);
widget.append(&add);
Self { rows, widget }
}
pub fn take(&self) -> Vec<Row> {
self.rows.take().into_values().collect()
}
}

View File

@ -0,0 +1,183 @@
use gtk::{
Align, Box, Button, Entry, Switch,
glib::{DateTime, GString},
prelude::{BoxExt, ButtonExt, EditableExt, WidgetExt},
};
pub struct Row {
pub id: Option<i64>,
host: Entry,
status: Switch,
pub time: DateTime,
pub widget: Box,
}
impl Row {
// Constructors
pub fn build(
id: Option<i64>,
time: Option<&DateTime>,
host: Option<&str>,
is_enabled: bool,
on_delete: impl Fn() + 'static,
) -> Self {
// Init components
let status = Switch::builder()
.active(is_enabled)
.valign(Align::Center)
.build();
let host = Entry::builder()
.hexpand(true)
.placeholder_text("Host")
.text(host.unwrap_or_default())
.build();
let delete = Button::builder()
.css_classes(["error"])
.icon_name("user-trash-symbolic")
.tooltip_text("Delete")
.build();
// Init widget
let widget = Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(8)
.build();
widget.append(&status);
widget.append(&host);
widget.append(&delete);
// Activate
delete.connect_clicked({
let c = std::rc::Rc::new(on_delete);
move |this| {
use adw::{
AlertDialog, ResponseAppearance,
prelude::{AdwDialogExt, AlertDialogExt, AlertDialogExtManual},
};
const RESPONSE_CONFIRM: (&str, &str) = ("confirm", "Confirm");
const RESPONSE_CANCEL: (&str, &str) = ("cancel", "Cancel");
let dialog = AlertDialog::builder()
.heading("Delete this host?")
.close_response(RESPONSE_CANCEL.0)
.default_response(RESPONSE_CONFIRM.0)
.build();
dialog.add_responses(&[RESPONSE_CANCEL, RESPONSE_CONFIRM]);
dialog.set_response_appearance(RESPONSE_CONFIRM.0, ResponseAppearance::Destructive);
dialog.connect_response(None, {
let c = c.clone();
move |dialog, response| {
dialog.set_response_enabled(response, false); // prevent double-click
if response == RESPONSE_CONFIRM.0 {
c()
}
}
});
dialog.present(Some(this))
}
});
host.connect_changed(move |this| {
validate(this);
});
status.connect_state_set({
let host = host.clone();
move |_, state| {
validate(&host);
host.set_sensitive(state);
gtk::glib::Propagation::Proceed
}
});
Self {
id,
status,
time: time.cloned().unwrap_or(DateTime::now_local().unwrap()),
host,
widget,
}
}
// Actions
pub fn validate(&self) -> bool {
validate(&self.host)
}
// Getters
pub fn host(&self) -> GString {
self.host.text()
}
pub fn is_enabled(&self) -> bool {
self.status.is_active()
}
}
pub fn new(on_add: impl Fn() + 'static) -> Box {
let b = Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(8)
.build();
b.append(&{
let add = Button::builder()
.css_classes(["success"])
.hexpand(true)
.icon_name("list-add-symbolic")
.tooltip_text("Add proxy")
.build();
add.connect_clicked(move |_| on_add());
add
});
b
}
fn validate(host: &Entry) -> bool {
fn highlight(entry: &Entry, error: Result<(), String>) {
const E: &str = "error";
match error {
Err(e) => {
entry.set_css_classes(&[E]);
entry.set_tooltip_text(Some(&e))
}
Ok(()) => {
entry.remove_css_class(E);
entry.set_tooltip_text(Some("Value is valid"))
}
}
}
fn validate_host(value: &str) -> Result<(), String> {
match gtk::gio::InetAddress::from_string(value) {
Some(address) => {
if address.to_string() != value {
Err("Host could not be parsed properly".to_string())
} else {
Ok(())
}
}
None => Err("Valid host is required".to_string()),
}
}
let v = validate_host(&host.text());
let is_valid_host = v.is_ok();
highlight(host, v);
is_valid_host
}

View File

@ -1,6 +1,4 @@
mod rule; mod row;
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use super::Profile; use super::Profile;
use gtk::{ use gtk::{
@ -8,18 +6,19 @@ use gtk::{
glib::{GString, uuid_string_random}, glib::{GString, uuid_string_random},
prelude::BoxExt, prelude::BoxExt,
}; };
use rule::Rule; use row::Row;
use std::{cell::RefCell, collections::HashMap, rc::Rc};
pub struct Rules { pub struct Rule {
pub widget: Box, pub widget: Box,
rules: Rc<RefCell<HashMap<GString, Rule>>>, rows: Rc<RefCell<HashMap<GString, Row>>>,
} }
impl Rules { impl Rule {
pub fn build(profile: &Rc<Profile>) -> Self { pub fn build(profile: &Rc<Profile>) -> Self {
let config = profile.proxy.rule.all(); let config = profile.proxy.rule.all();
let rules: Rc<RefCell<HashMap<GString, Rule>>> = let rows: Rc<RefCell<HashMap<GString, Row>>> =
Rc::new(RefCell::new(HashMap::with_capacity(config.len()))); Rc::new(RefCell::new(HashMap::with_capacity(config.len())));
let form = Box::builder() let form = Box::builder()
@ -28,11 +27,11 @@ impl Rules {
.build(); .build();
{ {
let mut r = rules.borrow_mut(); let mut r = rows.borrow_mut();
for proxy in config { for proxy in config {
let key = uuid_string_random(); let key = uuid_string_random();
let rule = Rule::build( let rule = Row::build(
proxy.id, proxy.id,
Some(&proxy.time), Some(&proxy.time),
Some(&proxy.request), Some(&proxy.request),
@ -40,10 +39,10 @@ impl Rules {
Some(proxy.priority), Some(proxy.priority),
proxy.is_enabled, proxy.is_enabled,
{ {
let rules = rules.clone(); let rows = rows.clone();
let key = key.clone(); let key = key.clone();
let form = form.clone(); let form = form.clone();
move || form.remove(&rules.borrow_mut().remove(&key).unwrap().widget) move || form.remove(&rows.borrow_mut().remove(&key).unwrap().widget)
}, },
); );
rule.validate(); rule.validate();
@ -58,19 +57,19 @@ impl Rules {
.spacing(8) .spacing(8)
.build(); .build();
b.append(&rule::new({ b.append(&row::new({
let rules = rules.clone(); let rows = rows.clone();
let form = form.clone(); let form = form.clone();
move || { move || {
let key = uuid_string_random(); let key = uuid_string_random();
let rule = Rule::build(None, None, None, None, None, false, { let row = Row::build(None, None, None, None, None, false, {
let rules = rules.clone(); let rows = rows.clone();
let key = key.clone(); let key = key.clone();
let form = form.clone(); let form = form.clone();
move || form.remove(&rules.borrow_mut().remove(&key).unwrap().widget) move || form.remove(&rows.borrow_mut().remove(&key).unwrap().widget)
}); });
form.append(&rule.widget); form.append(&row.widget);
assert!(rules.borrow_mut().insert(key, rule).is_none()) assert!(rows.borrow_mut().insert(key, row).is_none())
} }
})); }));
b b
@ -84,10 +83,10 @@ impl Rules {
widget.append(&form); widget.append(&form);
widget.append(&add); widget.append(&add);
Self { rules, widget } Self { rows, widget }
} }
pub fn take(&self) -> Vec<Rule> { pub fn take(&self) -> Vec<Row> {
self.rules.take().into_values().collect() self.rows.take().into_values().collect()
} }
} }

View File

@ -4,7 +4,7 @@ use gtk::{
prelude::{BoxExt, ButtonExt, EditableExt, WidgetExt}, prelude::{BoxExt, ButtonExt, EditableExt, WidgetExt},
}; };
pub struct Rule { pub struct Row {
pub id: Option<i64>, pub id: Option<i64>,
priority: Entry, priority: Entry,
request: Entry, request: Entry,
@ -14,7 +14,7 @@ pub struct Rule {
pub widget: Box, pub widget: Box,
} }
impl Rule { impl Row {
// Constructors // Constructors
pub fn build( pub fn build(
@ -220,7 +220,7 @@ fn validate(priority: &Entry, url: &Entry) -> bool {
Ok(uri) => { Ok(uri) => {
if uri.scheme().is_empty() { if uri.scheme().is_empty() {
Err("Scheme is empty".to_string()) Err("Scheme is empty".to_string())
} else if uri.host().is_none() { } else if uri.host().is_none_or(|h| h.is_empty()) {
Err("Host is required".to_string()) Err("Host is required".to_string())
} else if uri.port() == -1 { } else if uri.port() == -1 {
Err("Port is required".to_string()) Err("Port is required".to_string())

View File

@ -27,7 +27,7 @@ impl Proxy {
pub fn save(&self) -> Result<()> { pub fn save(&self) -> Result<()> {
self.rule.save()?; self.rule.save()?;
//self.ignore.save()?; self.ignore.save()?;
Ok(()) Ok(())
} }

View File

@ -3,6 +3,7 @@ mod memory;
use anyhow::Result; use anyhow::Result;
use database::Database; use database::Database;
use gtk::glib::DateTime;
use memory::Memory; use memory::Memory;
use r2d2::Pool; use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
@ -25,10 +26,12 @@ impl Ignore {
{ {
// build in-memory index... // build in-memory index...
let mut m = memory.borrow_mut(); let mut m = memory.borrow_mut();
for i in rows { for row in rows {
m.push(Memory { m.push(Memory {
is_enabled: i.is_enabled, id: Some(row.id),
host: i.host, host: row.host,
is_enabled: row.is_enabled,
time: DateTime::from_unix_local(row.time)?,
}); });
} }
} }
@ -36,7 +39,35 @@ impl Ignore {
Ok(Self { database, memory }) Ok(Self { database, memory })
} }
// Actions // Setters
pub fn add(&self, id: Option<i64>, is_enabled: bool, host: String, time: DateTime) {
self.memory.borrow_mut().push(Memory {
id,
host,
is_enabled,
time,
}) // @TODO validate?
}
pub fn clear(&self) {
self.memory.borrow_mut().clear();
}
pub fn save(&self) -> Result<()> {
let rules = self.memory.take();
let mut keep_id = Vec::with_capacity(rules.len());
for rule in rules {
keep_id.push(self.database.persist(
rule.id,
rule.time.to_unix(),
rule.is_enabled,
rule.host,
)?);
}
self.database.clean(keep_id)?;
Ok(())
}
// Getters // Getters

View File

@ -26,6 +26,36 @@ impl Database {
pub fn rows(&self) -> Result<Vec<Row>> { pub fn rows(&self) -> Result<Vec<Row>> {
rows(&self.pool.get()?.unchecked_transaction()?, self.profile_id) rows(&self.pool.get()?.unchecked_transaction()?, self.profile_id)
} }
// Setters
pub fn clean(&self, keep_id: Vec<i64>) -> Result<()> {
let mut c = self.pool.get()?;
let tx = c.transaction()?;
clean(&tx, keep_id)?;
tx.commit()?;
Ok(())
}
pub fn persist(
&self,
id: Option<i64>,
time: i64,
is_enabled: bool,
host: String,
) -> Result<i64> {
let mut c = self.pool.get()?;
let tx = c.transaction()?;
let id = match id {
Some(id) => {
update(&tx, id, time, is_enabled, host)?;
id
}
None => insert(&tx, self.profile_id, time, is_enabled, host)?,
};
tx.commit()?;
Ok(id)
}
} }
// Low-level DB API // Low-level DB API
@ -46,6 +76,54 @@ pub fn init(tx: &Transaction) -> Result<usize> {
)?) )?)
} }
fn clean(tx: &Transaction, keep_id: Vec<i64>) -> Result<usize> {
if keep_id.is_empty() {
return Ok(0);
}
Ok(tx.execute(
&format!(
"DELETE FROM `profile_proxy_ignore` WHERE `id` NOT IN ({})",
keep_id
.into_iter()
.map(|id| id.to_string())
.collect::<Vec<String>>()
.join(",")
),
[],
)?)
}
fn insert(
tx: &Transaction,
profile_id: i64,
time: i64,
is_enabled: bool,
host: String,
) -> Result<i64> {
tx.execute(
"INSERT INTO `profile_proxy_ignore` (
`profile_id`,
`time`,
`is_enabled`,
`host`
) VALUES (?, ?, ?, ?)",
(profile_id, time, is_enabled, host),
)?;
Ok(tx.last_insert_rowid())
}
fn update(tx: &Transaction, id: i64, time: i64, is_enabled: bool, host: String) -> Result<usize> {
Ok(tx.execute(
"UPDATE `profile_proxy_ignore`
SET `time` = ?,
`is_enabled` = ?,
`host` = ?
WHERE `id` = ?",
(time, is_enabled, host, id),
)?)
}
fn rows(tx: &Transaction, profile_id: i64) -> Result<Vec<Row>> { fn rows(tx: &Transaction, profile_id: i64) -> Result<Vec<Row>> {
let mut stmt = tx.prepare( let mut stmt = tx.prepare(
"SELECT `id`, "SELECT `id`,
@ -60,9 +138,9 @@ fn rows(tx: &Transaction, profile_id: i64) -> Result<Vec<Row>> {
let result = stmt.query_map([profile_id], |row| { let result = stmt.query_map([profile_id], |row| {
Ok(Row { Ok(Row {
//id: row.get(0)?, id: row.get(0)?,
//profile_id: row.get(1)?, //profile_id: row.get(1)?,
//time: DateTime::from_unix_local(row.get(2)?).unwrap(), time: row.get(2)?,
host: row.get(3)?, host: row.get(3)?,
is_enabled: row.get(4)?, is_enabled: row.get(4)?,
}) })

View File

@ -1,4 +1,6 @@
pub struct Row { pub struct Row {
pub host: String, pub host: String,
pub id: i64,
pub is_enabled: bool, pub is_enabled: bool,
pub time: i64,
} }

View File

@ -1,5 +1,7 @@
#[derive(Clone)] #[derive(Clone)]
pub struct Memory { pub struct Memory {
pub host: String, pub host: String,
pub id: Option<i64>,
pub is_enabled: bool, pub is_enabled: bool,
pub time: gtk::glib::DateTime,
} }

View File

@ -29,10 +29,10 @@ impl Rule {
for row in rows { for row in rows {
m.push(Memory { m.push(Memory {
id: Some(row.id), id: Some(row.id),
time: row.time,
is_enabled: row.is_enabled, is_enabled: row.is_enabled,
priority: row.priority, priority: row.priority,
request: row.request, request: row.request,
time: DateTime::from_unix_local(row.time)?,
url: row.url, url: row.url,
}); });
} }
@ -52,8 +52,7 @@ impl Rule {
url: String, url: String,
time: DateTime, time: DateTime,
) { ) {
let mut rules = self.memory.borrow_mut(); self.memory.borrow_mut().push(Memory {
rules.push(Memory {
id, id,
time, time,
is_enabled, is_enabled,
@ -73,7 +72,7 @@ impl Rule {
for rule in rules { for rule in rules {
keep_id.push(self.database.persist( keep_id.push(self.database.persist(
rule.id, rule.id,
rule.time, rule.time.to_unix(),
rule.is_enabled, rule.is_enabled,
rule.priority, rule.priority,
rule.request, rule.request,

View File

@ -1,7 +1,6 @@
mod row; mod row;
use anyhow::Result; use anyhow::Result;
use gtk::glib::DateTime;
use r2d2::Pool; use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
use row::Row; use row::Row;
@ -41,7 +40,7 @@ impl Database {
pub fn persist( pub fn persist(
&self, &self,
id: Option<i64>, id: Option<i64>,
time: DateTime, time: i64,
is_enabled: bool, is_enabled: bool,
priority: i32, priority: i32,
request: String, request: String,
@ -109,7 +108,7 @@ fn clean(tx: &Transaction, keep_id: Vec<i64>) -> Result<usize> {
fn insert( fn insert(
tx: &Transaction, tx: &Transaction,
profile_id: i64, profile_id: i64,
time: DateTime, time: i64,
is_enabled: bool, is_enabled: bool,
priority: i32, priority: i32,
request: String, request: String,
@ -124,14 +123,7 @@ fn insert(
`request`, `request`,
`url` `url`
) VALUES (?, ?, ?, ?, ?, ?)", ) VALUES (?, ?, ?, ?, ?, ?)",
( (profile_id, time, is_enabled, priority, request, url),
profile_id,
time.to_unix(),
is_enabled,
priority,
request,
url,
),
)?; )?;
Ok(tx.last_insert_rowid()) Ok(tx.last_insert_rowid())
} }
@ -139,7 +131,7 @@ fn insert(
fn update( fn update(
tx: &Transaction, tx: &Transaction,
id: i64, id: i64,
time: DateTime, time: i64,
is_enabled: bool, is_enabled: bool,
priority: i32, priority: i32,
request: String, request: String,
@ -154,7 +146,7 @@ fn update(
`url` = ? `url` = ?
WHERE `id` = ?", WHERE `id` = ?",
(time.to_unix(), is_enabled, priority, request, url, id), (time, is_enabled, priority, request, url, id),
)?) )?)
} }
@ -177,7 +169,7 @@ fn rows(tx: &Transaction, profile_id: i64) -> Result<Vec<Row>> {
Ok(Row { Ok(Row {
id: row.get(0)?, id: row.get(0)?,
//profile_id: row.get(1)?, //profile_id: row.get(1)?,
time: DateTime::from_unix_local(row.get(2)?).unwrap(), time: row.get(2)?,
is_enabled: row.get(3)?, is_enabled: row.get(3)?,
priority: row.get(4)?, priority: row.get(4)?,
request: row.get(5)?, request: row.get(5)?,

View File

@ -3,6 +3,6 @@ pub struct Row {
pub is_enabled: bool, pub is_enabled: bool,
pub priority: i32, pub priority: i32,
pub request: String, pub request: String,
pub time: gtk::glib::DateTime, pub time: i64,
pub url: String, pub url: String,
} }