diff --git a/crates/app/src/views/bar.rs b/crates/app/src/views/bar.rs index 033499a..97c2cd8 100644 --- a/crates/app/src/views/bar.rs +++ b/crates/app/src/views/bar.rs @@ -178,11 +178,11 @@ fn filtering(listing: &Listing, f: &Filter) -> Vec> { ages.extend(Age::ALL.map(|a| Item::new(a.label(), Pick::Age(Some(a))).checked(f.age == Some(a)))); let mut hosts = vec![Item::new(tr!("host.any"), Pick::Host(None)).checked(f.host.is_none())]; // Those with the most downloads, by name. - let mut most: Vec<_> = listing.counts.hosts.iter().collect(); + let mut most = listing.hosts(); most.sort_by_key(|(_, n)| std::cmp::Reverse(*n)); most.truncate(HOSTS); most.sort(); - hosts.extend(most.into_iter().map(|(h, _)| Item::new(host_name(h), Pick::Host(Some(h.to_string()))).checked(f.host.as_deref() == Some(h)))); + hosts.extend(most.into_iter().map(|(h, _)| Item::new(host_name(&h), Pick::Host(Some(h.to_string()))).checked(f.host.as_deref() == Some(&*h)))); vec![ Item::sub(tr!("filter.host"), hosts).icon("public"), Item::sub(tr!("filter.age"), ages).icon("calendar_month"), diff --git a/crates/app/src/views/list/mod.rs b/crates/app/src/views/list/mod.rs index 5fc1055..c3f8c75 100644 --- a/crates/app/src/views/list/mod.rs +++ b/crates/app/src/views/list/mod.rs @@ -165,11 +165,14 @@ impl List { } /// Brings the rows up to date. Cheap when nothing changed. - pub fn follow(&mut self, ui: &Ui, shot: &Snapshot, lists: &Arc) { + pub fn follow(&mut self, ui: &Ui, shot: &Arc, lists: &Arc) { let today = model::today(core::now()); if self.listing.fresh(shot, &self.query, lists, today) { return; } + if self.listing.patch(shot, &self.query, lists, today) { + return; + } let old = std::mem::take(&mut self.listing.rows); self.listing.update(shot, &self.query, lists, today); let layout = Layout::new(&self.listing, self.layout.form, self.layout.width()); diff --git a/crates/app/src/views/list/model.rs b/crates/app/src/views/list/model.rs index d6dcce9..80513d8 100644 --- a/crates/app/src/views/list/model.rs +++ b/crates/app/src/views/list/model.rs @@ -228,16 +228,36 @@ pub fn kind_of(name: &str, mime: Option<&str>) -> Kind { /// How many there are, whatever the search. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Counts { - pub status: HashMap, - pub queues: HashMap, - pub tags: HashMap, - pub kinds: HashMap, - /// By name. - pub hosts: Vec<(Arc, usize)>, + /// In the order of `Status::ALL` and `Kind::ALL`. + pub status: [usize; 6], + pub kinds: [usize; 7], + queues: Vec<(QueueId, usize)>, + tags: Vec<(TagId, usize)>, /// Waiting for the network. pub offline: usize, } +fn one_more(list: &mut Vec<(K, usize)>, key: K) { + match list.iter_mut().find(|(k, _)| *k == key) { + Some((_, n)) => *n += 1, + None => list.push((key, 1)), + } +} + +fn number(list: &[(K, usize)], key: K) -> usize { + list.iter().find(|(k, _)| *k == key).map_or(0, |(_, n)| *n) +} + +impl Counts { + pub fn queue(&self, id: QueueId) -> usize { + number(&self.queues, id) + } + + pub fn tag(&self, id: TagId) -> usize { + number(&self.tags, id) + } +} + /// What is asked of a task at every change, worked out once. struct Info { of: Arc, @@ -273,8 +293,17 @@ pub struct Listing { pub rows: Vec>, pub heads: Vec, pub counts: Counts, - infos: HashMap, - seen: Option<(u64, Query, Arc, Time, usize)>, + /// Of every download, by id. + infos: Vec, + seen: Option, +} + +/// What the rows were made from. +struct Seen { + shot: Arc, + query: Query, + lists: Arc, + today: Time, } struct Entry<'a> { @@ -288,13 +317,49 @@ struct Entry<'a> { impl Listing { /// Is this what the list was last made from? - pub fn fresh(&self, shot: &Snapshot, query: &Query, lists: &Arc, today: Time) -> bool { - self.seen.as_ref().is_some_and(|(rev, q, l, t, n)| *rev == shot.rev && *n == shot.len() && q == query && Arc::ptr_eq(l, lists) && *t == today) + pub fn fresh(&self, shot: &Arc, query: &Query, lists: &Arc, today: Time) -> bool { + self.seen.as_ref().is_some_and(|s| Arc::ptr_eq(&s.shot, shot) && s.query == *query && Arc::ptr_eq(&s.lists, lists) && s.today == today) + } + + /// Takes over new numbers when nothing changed that decides what is shown, and where. False when that is not enough. + pub fn patch(&mut self, shot: &Arc, query: &Query, lists: &Arc, today: Time) -> bool { + let Some(seen) = self.seen.as_mut().filter(|s| s.query == *query && Arc::ptr_eq(&s.lists, lists) && s.today == today) else { return false }; + if seen.shot.len() != shot.len() || matches!(query.sort, Sort::Size | Sort::Progress | Sort::Speed | Sort::Left) { + return false; + } + let mut new: Vec<&Arc> = vec![]; + for (a, b) in seen.shot.iter().zip(shot.iter()) { + if Arc::ptr_eq(a, b) { + continue; + } + if a.id() != b.id() || !Arc::ptr_eq(&a.task, &b.task) || !Arc::ptr_eq(&a.server, &b.server) { + return false; + } + new.push(b); + } + if !new.is_empty() { + for row in &mut self.rows { + if let Ok(i) = new.binary_search_by_key(&row.id(), |v| v.id()) { + *row = new[i].clone(); + } + } + } + seen.shot = shot.clone(); + true + } + + /// Servers and how many downloads each has, by name. + pub fn hosts(&self) -> Vec<(Arc, usize)> { + let mut all: HashMap<&Arc, usize> = HashMap::new(); + self.infos.iter().for_each(|i| *all.entry(&i.server).or_default() += 1); + let mut list: Vec<_> = all.into_iter().map(|(h, n)| (h.clone(), n)).collect(); + list.sort_unstable(); + list } /// Kind of a row. pub fn kind(&self, id: TaskId) -> Kind { - self.infos.get(&id).map_or(Kind::Other, |i| i.kind) + self.infos.binary_search_by_key(&id, |i| i.of.id).map_or(Kind::Other, |i| self.infos[i].kind) } /// Which heading a row is under. @@ -302,24 +367,22 @@ impl Listing { self.heads.partition_point(|h| h.first <= row).checked_sub(1) } - pub fn update(&mut self, shot: &Snapshot, query: &Query, lists: &Arc, today: Time) { + pub fn update(&mut self, shot: &Arc, query: &Query, lists: &Arc, today: Time) { self.learn(shot); let words: Vec = query.filter.search.to_lowercase().split_whitespace().map(String::from).collect(); let places: HashMap = lists.queues.iter().map(|q| (q.id, q.position)).collect(); let f = &query.filter; let mut counts = Counts::default(); - let mut hosts: HashMap<&Arc, usize> = HashMap::new(); let mut group_names: HashMap<&str, u32> = HashMap::new(); let mut entries = Vec::with_capacity(shot.len()); - for view in shot.iter() { - let (task, info) = (&view.task, &self.infos[&view.id()]); + for (view, info) in shot.iter().zip(&self.infos) { + let task = &view.task; let status = Status::of(task.state); - *counts.status.entry(Status::All).or_default() += 1; - *counts.status.entry(status).or_default() += 1; - *counts.queues.entry(task.queue).or_default() += 1; - *counts.kinds.entry(info.kind).or_default() += 1; - *hosts.entry(&info.server).or_default() += 1; - task.tags.iter().for_each(|t| *counts.tags.entry(*t).or_default() += 1); + counts.status[Status::All as usize] += 1; + counts.status[status as usize] += 1; + counts.kinds[info.kind as usize] += 1; + one_more(&mut counts.queues, task.queue); + task.tags.iter().for_each(|t| one_more(&mut counts.tags, *t)); counts.offline += usize::from(task.state == State::Waiting && task.error.as_ref().and_then(|e| e.kind).is_some_and(|k| matches!(k, ErrorKind::Offline | ErrorKind::Portal))); let shown = (f.status == Status::All || f.status == status) && f.queue.is_none_or(|q| q == task.queue) @@ -333,7 +396,7 @@ impl Listing { } let group = match query.group { Group::None => 0, - Group::State => Status::ALL.iter().position(|s| *s == status).unwrap_or(0) as u32, + Group::State => status as u32, Group::Queue => lists.queues.iter().position(|q| q.id == task.queue).unwrap_or(usize::MAX) as u32, Group::Kind => info.kind as u32, Group::Added => Age::of(task.added_at, today) as u32, @@ -364,10 +427,11 @@ impl Listing { entries.iter_mut().for_each(|e| e.group = place[e.group as usize]); } let order = |a: &Entry, b: &Entry| a.num.total_cmp(&b.num).then(a.num2.total_cmp(&b.num2)).then_with(|| a.text.cmp(b.text)); - entries.sort_by(|a, b| { - let o = order(a, b); - a.group.cmp(&b.group).then(if query.down { o.reverse() } else { o }) - }); + // Few groups first, then each alone, where the order is often there already: both are quick for this sort. + entries.sort_by_key(|e| e.group); + for group in entries.chunk_by_mut(|a, b| a.group == b.group) { + group.sort_by(|a, b| if query.down { order(b, a) } else { order(a, b) }); + } self.heads.clear(); if query.group != Group::None { let mut last = None; @@ -379,11 +443,9 @@ impl Listing { self.heads.last_mut().expect("just pushed").count += 1; } } - counts.hosts = hosts.into_iter().map(|(h, n)| (h.clone(), n)).collect(); - counts.hosts.sort_unstable(); self.rows = entries.into_iter().map(|e| e.view.clone()).collect(); self.counts = counts; - self.seen = Some((shot.rev, query.clone(), lists.clone(), today, shot.len())); + self.seen = Some(Seen { shot: shot.clone(), query: query.clone(), lists: lists.clone(), today }); } fn head_label(&self, group: Group, v: &TaskView, lists: &Lists, today: Time) -> String { @@ -398,18 +460,24 @@ impl Listing { } fn learn(&mut self, shot: &Snapshot) { - if self.infos.len() > shot.len() { - self.infos.retain(|id, _| shot.get(*id).is_some()); - } - for v in shot.iter() { - match self.infos.get_mut(&v.id()) { - Some(i) if Arc::ptr_eq(&i.of, &v.task) && Arc::ptr_eq(&i.server, &v.server) => {} - Some(i) => *i = Info::new(v), - None => { - self.infos.insert(v.id(), Info::new(v)); + let same = self.infos.len() == shot.len() && self.infos.iter().zip(shot.iter()).all(|(i, v)| i.of.id == v.id()); + if same { + for (i, v) in self.infos.iter_mut().zip(shot.iter()) { + if !Arc::ptr_eq(&i.of, &v.task) || !Arc::ptr_eq(&i.server, &v.server) { + *i = Info::new(v); } } + return; } + // Both are by id. + let mut old = std::mem::take(&mut self.infos).into_iter().peekable(); + self.infos = shot + .iter() + .map(|v| { + while old.next_if(|i| i.of.id < v.id()).is_some() {} + old.next_if(|i| Arc::ptr_eq(&i.of, &v.task) && Arc::ptr_eq(&i.server, &v.server)).unwrap_or_else(|| Info::new(v)) + }) + .collect(); } } diff --git a/crates/app/src/views/rail.rs b/crates/app/src/views/rail.rs index db0b6a9..4d2d29a 100644 --- a/crates/app/src/views/rail.rs +++ b/crates/app/src/views/rail.rs @@ -52,8 +52,7 @@ pub fn show(ui: &mut Ui, t: &Theme, rect: Rect, open: bool, filter: &mut Filter, let mut body = ui.new_child(UiBuilder::new().max_rect(body).id_salt("entries")); ScrollArea::vertical().auto_shrink(false).show(&mut body, |ui| { ui.spacing_mut().item_spacing = vec2(0.0, GAP); - let at = |n: Option<&usize>| n.copied().unwrap_or(0); - let states = Status::ALL.map(|s| Entry { mark: Mark::Icon(s.icon()), name: s.label(), count: at(counts.status.get(&s)), on: filter.status == s }); + let states = Status::ALL.map(|s| Entry { mark: Mark::Icon(s.icon()), name: s.label(), count: counts.status[s as usize], on: filter.status == s }); if let Some(i) = section(ui, t, rect, "", &states, true) { filter.status = Status::ALL[i]; } @@ -61,7 +60,7 @@ pub fn show(ui: &mut Ui, t: &Theme, rect: Rect, open: bool, filter: &mut Filter, let queues: Vec = lists .queues .iter() - .map(|q| Entry { mark: Mark::Letter, name: queue_name(lists, q.id), count: at(counts.queues.get(&q.id)), on: filter.queue == Some(q.id) }) + .map(|q| Entry { mark: Mark::Letter, name: queue_name(lists, q.id), count: counts.queue(q.id), on: filter.queue == Some(q.id) }) .collect(); if let Some(i) = section(ui, t, rect, &tr!("rail.queues"), &queues, false) { filter.queue = Some(lists.queues[i].id).filter(|q| filter.queue != Some(*q)); @@ -72,16 +71,16 @@ pub fn show(ui: &mut Ui, t: &Theme, rect: Rect, open: bool, filter: &mut Filter, let tags: Vec = lists .tags .iter() - .map(|g| Entry { mark: Mark::Dot(colour(&g.color)), name: g.name.clone(), count: at(counts.tags.get(&g.id)), on: filter.tag == Some(g.id) }) + .map(|g| Entry { mark: Mark::Dot(colour(&g.color)), name: g.name.clone(), count: counts.tag(g.id), on: filter.tag == Some(g.id) }) .collect(); if let Some(i) = section(ui, t, rect, &tr!("rail.tags"), &tags, false) { filter.tag = Some(lists.tags[i].id).filter(|g| filter.tag != Some(*g)); } } // Types that are there, and the one that is asked for. - let there: Vec = Kind::ALL.into_iter().filter(|k| counts.kinds.contains_key(k) || filter.kind == Some(*k)).collect(); + let there: Vec = Kind::ALL.into_iter().filter(|k| counts.kinds[*k as usize] > 0 || filter.kind == Some(*k)).collect(); let kinds: Vec = - there.iter().map(|k| Entry { mark: Mark::Kind(*k), name: kind_label(*k), count: at(counts.kinds.get(k)), on: filter.kind == Some(*k) }).collect(); + there.iter().map(|k| Entry { mark: Mark::Kind(*k), name: kind_label(*k), count: counts.kinds[*k as usize], on: filter.kind == Some(*k) }).collect(); if !kinds.is_empty() && let Some(i) = section(ui, t, rect, &tr!("rail.kinds"), &kinds, false) { diff --git a/crates/app/tests/main.rs b/crates/app/tests/main.rs index adaaa40..70f5f7d 100644 --- a/crates/app/tests/main.rs +++ b/crates/app/tests/main.rs @@ -117,7 +117,7 @@ fn name(h: &H, of: &str) -> Pos2 { fn listed(query: &Query, shot: &Snapshot) -> (Vec, Listing) { let mut listing = Listing::default(); - listing.update(shot, query, &Arc::new(lists()), medlar_app::views::list::model::today(medlar_core::model::now())); + listing.update(&Arc::new(shot.clone()), query, &Arc::new(lists()), medlar_app::views::list::model::today(medlar_core::model::now())); (listing.rows.iter().map(|v| v.id()).collect(), listing) } @@ -453,22 +453,29 @@ fn frame_of_ten_thousand_rows_is_quick() { let at = pos2(900.0, 600.0); h.input_mut().events.push(Event::PointerMoved(at)); h.run_steps(30); - let measure = |h: &mut H, scroll: bool, change: bool| { + let mut views: Vec> = many(10_000, 1).iter().cloned().collect(); + h.run_steps(30); + let mut measure = |h: &mut H, change: bool, state: bool| { let mut times = vec![]; for i in 0..120u64 { + // Ten times a second the running ones have new numbers. if change && i % 6 == 0 { - app(h).main.bridge.set_still(many(10_000, i + 2)); + for v in &mut views[..8] { + let v = Arc::make_mut(v); + (v.rev, v.downloaded) = (i + 2, v.downloaded + 100_000); + if state { + Arc::make_mut(&mut v.task).notes = i.to_string(); + } + } + app(h).main.bridge.set_still(views.iter().cloned().collect()); } - if scroll { - let delta = vec2(0.0, -230.0); - h.input_mut().events.push(Event::MouseWheel { + h.input_mut().events.push(Event::MouseWheel { unit: eframe::egui::MouseWheelUnit::Point, - delta, + delta: vec2(0.0, -230.0), phase: eframe::egui::TouchPhase::Move, source: eframe::egui::MouseWheelSource::Trackpad, modifiers: Modifiers::NONE, }); - } let begun = Instant::now(); h.step(); times.push(begun.elapsed().as_secs_f64() * 1000.0); @@ -476,11 +483,12 @@ fn frame_of_ten_thousand_rows_is_quick() { times.sort_by(f64::total_cmp); (times[60], times[113], times[119]) }; - let scrolling = measure(&mut h, true, false); - let both = measure(&mut h, true, true); - println!("{form:?}: scrolling median {:.2}, 95 % {:.2}, worst {:.2} ms; with changes {:.2}, {:.2}, {:.2} ms", scrolling.0, scrolling.1, scrolling.2, both.0, both.1, both.2); + let scrolling = measure(&mut h, false, false); + let both = measure(&mut h, true, false); + let all = measure(&mut h, true, true); + println!("{form:?}: scrolling median {:.2}, 95 % {:.2}, worst {:.2} ms; with changes {:.2}, {:.2}, {:.2} ms; with changes of tasks {:.2}, {:.2}, {:.2} ms", scrolling.0, scrolling.1, scrolling.2, both.0, both.1, both.2, all.0, all.1, all.2); if !cfg!(debug_assertions) { - assert!(scrolling.1 < 8.0 && both.1 < 8.0); + assert!(scrolling.1 < 8.0 && both.1 < 8.0 && all.1 < 8.0); } } } diff --git a/crates/app/tests/main/fixture.rs b/crates/app/tests/main/fixture.rs index d215de5..cfcc6f7 100644 --- a/crates/app/tests/main/fixture.rs +++ b/crates/app/tests/main/fixture.rs @@ -114,7 +114,7 @@ pub fn lists() -> Lists { pub fn shot(views: Vec) -> Snapshot { let totals = totals(&views); - let mut shot: Snapshot = views.into_iter().collect(); + let mut shot: Snapshot = views.into_iter().map(Arc::new).collect(); shot.totals = totals; shot } diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rs index 9f3090d..cd109e3 100644 --- a/crates/core/src/snapshot.rs +++ b/crates/core/src/snapshot.rs @@ -134,8 +134,11 @@ impl Snapshot { } pub(crate) fn put(&mut self, view: TaskView) { + self.place(Arc::new(view)); + } + + fn place(&mut self, view: Arc) { let (id, at) = (view.id(), self.chunk_of(view.id())); - let view = Arc::new(view); let Some(chunk) = self.chunks.get_mut(at) else { self.chunks.push(Arc::new(vec![view])); self.len += 1; @@ -170,12 +173,12 @@ impl Snapshot { } /// For tests and pictures; the manager's own come from the manager. -impl FromIterator for Snapshot { - fn from_iter>(views: I) -> Snapshot { +impl FromIterator> for Snapshot { + fn from_iter>>(views: I) -> Snapshot { let mut shot = Snapshot::default(); for view in views { shot.rev = shot.rev.max(view.rev); - shot.put(view); + shot.place(view); } shot }