Skip to content

Commit

Permalink
Get rid of RefreshDb since it doesn't really work and we really just …
Browse files Browse the repository at this point in the history
…need broadcasting

Signed-off-by: Alex Saveau <[email protected]>
  • Loading branch information
SUPERCILEX committed Jul 28, 2024
1 parent 0a0087d commit 4e44d11
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 57 deletions.
1 change: 0 additions & 1 deletion client-sdk/api.golden
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,6 @@ pub clipboard_history_client_sdk::ui_actor::Command::GetDetails::id: u64
pub clipboard_history_client_sdk::ui_actor::Command::GetDetails::with_text: bool
pub clipboard_history_client_sdk::ui_actor::Command::LoadFirstPage
pub clipboard_history_client_sdk::ui_actor::Command::LoadImage(u64)
pub clipboard_history_client_sdk::ui_actor::Command::RefreshDb
pub clipboard_history_client_sdk::ui_actor::Command::Search
pub clipboard_history_client_sdk::ui_actor::Command::Search::query: alloc::boxed::Box<str>
pub clipboard_history_client_sdk::ui_actor::Command::Search::regex: bool
Expand Down
95 changes: 43 additions & 52 deletions client-sdk/src/ui_actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,24 @@ use std::{
io::BufReader,
iter::once,
mem,
os::fd::{AsFd, BorrowedFd, OwnedFd},
os::fd::{AsFd, OwnedFd},
str,
sync::Arc,
};

use image::{DynamicImage, ImageError, ImageReader};
use regex::bytes::Regex;
use rustc_hash::FxHasher;
use rustix::{
fs::{openat, statx, AtFlags, Mode, OFlags, StatxFlags, CWD},
net::SocketAddrUnix,
};
use rustix::net::SocketAddrUnix;
use thiserror::Error;

use crate::{
api::{connect_to_server, MoveToFrontRequest, RemoveRequest},
core::{
dirs::{data_dir, socket_file},
protocol::{composite_id, IdNotFoundError, MoveToFrontResponse, RemoveResponse, RingKind},
ring::{offset_to_entries, Ring, MAX_ENTRIES},
size_to_bucket, BucketAndIndex, Error as CoreError, IoErr, PathView, RingAndIndex,
ring::{Ring, MAX_ENTRIES},
size_to_bucket, BucketAndIndex, Error as CoreError, IoErr, RingAndIndex,
},
search,
search::{CancellationToken, EntryLocation, Query},
Expand All @@ -53,7 +50,6 @@ impl From<IdNotFoundError> for CommandError {

#[derive(Debug)]
pub enum Command {
RefreshDb,
LoadFirstPage,
GetDetails { id: u64, with_text: bool },
Favorite(u64),
Expand Down Expand Up @@ -128,22 +124,14 @@ pub fn controller<E>(
}

let mut server = None;
let ((mut database, reader), rings) = {
let (mut database, reader) = {
let run = || {
let mut dir = data_dir();

let database = DatabaseReader::open(&mut dir)?;
let reader = EntryReader::open(&mut dir)?;

let mut open_ring = |kind: RingKind| {
let path = PathView::new(&mut dir, kind.file_name());
openat(CWD, &*path, OFlags::PATH, Mode::empty()).map_io_err(|| {
format!("Failed to open Ringboard database for reading: {path:?}")
})
};
let rings = (open_ring(RingKind::Main)?, open_ring(RingKind::Favorites)?);

Ok(((database, reader), rings))
Ok((database, reader))
};

match run() {
Expand All @@ -155,8 +143,7 @@ pub fn controller<E>(
}
};
let mut reader = Some(reader);
let mut reverse_index_cache = HashMap::default();
let mut search_result_buf = Vec::new();
let mut cache = Default::default();

for command in once(Command::LoadFirstPage).chain(commands) {
let result = handle_command(
Expand All @@ -165,9 +152,7 @@ pub fn controller<E>(
&mut send,
&mut database,
&mut reader,
&(&rings.0, &rings.1),
&mut reverse_index_cache,
&mut search_result_buf,
&mut cache,
)
.unwrap_or_else(|e| Some(Message::Error(e)));

Expand All @@ -186,30 +171,33 @@ fn handle_command<'a, Server: AsFd, E>(
send: impl FnMut(Message) -> Result<(), E>,
database: &mut DatabaseReader,
reader_: &mut Option<EntryReader>,
rings: &(impl AsFd, impl AsFd),
reverse_index_cache: &mut HashMap<BucketAndIndex, RingAndIndex, BuildHasherDefault<FxHasher>>,
search_result_buf: &mut Vec<RingAndIndex>,
cache: &mut (
Option<(u32, u32)>,
HashMap<BucketAndIndex, RingAndIndex, BuildHasherDefault<FxHasher>>,
Vec<RingAndIndex>,
),
) -> Result<Option<Message>, CommandError> {
let reader = reader_.as_mut().unwrap();
match command {
Command::RefreshDb => {
reverse_index_cache.clear();
let run = |ring: &mut Ring, fd: BorrowedFd| {
let len = statx(fd, c"", AtFlags::EMPTY_PATH, StatxFlags::SIZE)
.map_io_err(|| "Failed to statx Ringboard database file.")?
.stx_size;
let len = offset_to_entries(usize::try_from(len).unwrap());
unsafe {
ring.set_len(len);
Command::LoadFirstPage => {
// This will trigger every time once the ring has reached capacity and doesn't
// work if the ring fully wrapped around while we weren't looking.
let shitty_refresh = |ring: &mut Ring| {
let head = ring.write_head();
#[allow(clippy::comparison_chain)]
if head < ring.len() {
unsafe {
ring.set_len(ring.capacity());
}
} else if head > ring.len() {
unsafe {
ring.set_len(head);
}
}
Ok::<_, CoreError>(())
};
run(database.main_ring_mut(), rings.0.as_fd())?;
run(database.favorites_ring_mut(), rings.1.as_fd())?;
shitty_refresh(database.favorites_ring_mut());
shitty_refresh(database.main_ring_mut());

Ok(None)
}
Command::LoadFirstPage => {
let mut entries = Vec::with_capacity(100);
for entry in database
.favorites()
Expand Down Expand Up @@ -289,15 +277,7 @@ fn handle_command<'a, Server: AsFd, E>(
Query::Plain(query.trim().as_bytes())
};
Ok(Some(Message::SearchResults(
do_search(
query,
reader_,
database,
send,
reverse_index_cache,
search_result_buf,
)
.into(),
do_search(query, reader_, database, send, cache).into(),
)))
}
Command::LoadImage(id) => {
Expand Down Expand Up @@ -374,8 +354,11 @@ fn do_search<E>(
reader_: &mut Option<EntryReader>,
database: &mut DatabaseReader,
mut send: impl FnMut(Message) -> Result<(), E>,
reverse_index_cache: &mut HashMap<BucketAndIndex, RingAndIndex, BuildHasherDefault<FxHasher>>,
search_result_buf: &mut Vec<RingAndIndex>,
(cached_write_heads, reverse_index_cache, search_result_buf): &mut (
Option<(u32, u32)>,
HashMap<BucketAndIndex, RingAndIndex, BuildHasherDefault<FxHasher>>,
Vec<RingAndIndex>,
),
) -> Vec<UiEntry> {
const MAX_SEARCH_ENTRIES: usize = 256;

Expand All @@ -386,6 +369,14 @@ fn do_search<E>(
result_stream.cancellation_token().clone(),
));

if *cached_write_heads
!= Some((
database.favorites().ring().write_head(),
database.main().ring().write_head(),
))
{
reverse_index_cache.clear();
}
if reverse_index_cache.is_empty() {
for entry in database.favorites().chain(database.main()) {
let Kind::Bucket(bucket) = entry.kind() else {
Expand Down
3 changes: 1 addition & 2 deletions egui/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ fn main_ui(
) {
let State { entries, ui: state } = state_;
let refresh = |state: &mut UiState| {
let _ = requests.send(Command::RefreshDb);
let _ = requests.send(Command::LoadFirstPage);
if !state.query.is_empty() {
if let Some(token) = &state.pending_search_token {
token.cancel();
Expand All @@ -378,7 +378,6 @@ fn main_ui(
regex: state.search_with_regex,
});
}
let _ = requests.send(Command::LoadFirstPage);
};

{
Expand Down
3 changes: 1 addition & 2 deletions tui/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ fn handle_event(event: Event, state: &mut State, requests: &Sender<Command>) ->
ui.detailed_entry = None;
};
let refresh = |ui: &mut UiState| {
let _ = requests.send(Command::RefreshDb);
let _ = requests.send(Command::LoadFirstPage);
if let &Some(SearchState { focused: _, regex }) = &ui.search_state {
if let Some(token) = &ui.pending_search_token {
token.cancel();
Expand All @@ -392,7 +392,6 @@ fn handle_event(event: Event, state: &mut State, requests: &Sender<Command>) ->
regex,
});
}
let _ = requests.send(Command::LoadFirstPage);
};

match event {
Expand Down

0 comments on commit 4e44d11

Please sign in to comment.