Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions core/crates/ffi/src/run/query_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ impl QueryRun {
.map(|store| Arc::new(ResultSet::new(index, store)))
}

/// The app shows this set no more, so the run lets go of its rows; they go once no `ResultSet` holds them.
pub fn release_set(&self, index: u32) {
self.state.release_set(index);
}

pub fn cancel(&self) {
self.state.cancel.cancel();
}
Expand Down
74 changes: 69 additions & 5 deletions core/crates/ffi/src/run/run_state.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::{Arc, Mutex, PoisonError, Weak};

use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
Expand All @@ -20,7 +20,14 @@ pub(crate) struct RunState {
#[derive(Default)]
struct Queue {
events: Vec<RunEvent>,
sets: Vec<Arc<ResultStore>>,
// A released set keeps its slot, so every later set keeps its index.
sets: Vec<Slot>,
}

enum Slot {
Held(Arc<ResultStore>),
// Weak, so a `ResultSet` the app still holds is finished with the run.
Released(Weak<ResultStore>),
}

impl RunState {
Expand All @@ -36,12 +43,34 @@ impl RunState {

pub(crate) fn add_set(&self, store: Arc<ResultStore>) -> u32 {
let mut queue = self.lock();
queue.sets.push(store);
queue.sets.push(Slot::Held(store));
u32::try_from(queue.sets.len() - 1).unwrap_or(u32::MAX)
}

pub(crate) fn set(&self, index: u32) -> Option<Arc<ResultStore>> {
self.lock().sets.get(usize::try_from(index).ok()?).cloned()
match self.lock().sets.get(usize::try_from(index).ok()?)? {
Slot::Held(store) => Some(store.clone()),
Slot::Released(_) => None,
}
}

pub(crate) fn release_set(&self, index: u32) {
let Ok(index) = usize::try_from(index) else {
return;
};
let released = {
let mut queue = self.lock();
let Some(slot) = queue.sets.get_mut(index) else {
return;
};
let Slot::Held(store) = slot else {
return;
};
let weak = Arc::downgrade(store);
std::mem::replace(slot, Slot::Released(weak))
};
// Outside the lock: freeing a large set's rows takes a while, and the reader posts under it.
drop(released);
}

// Called on a runtime thread.
Expand Down Expand Up @@ -84,7 +113,15 @@ impl RunState {

// Every set holds what it will, and `Finished` is the last event.
pub(crate) fn finish(&self, outcome: RunOutcome, transaction: TransactionStateTag) {
let sets = self.lock().sets.clone();
let sets: Vec<_> = self
.lock()
.sets
.iter()
.filter_map(|slot| match slot {
Slot::Held(store) => Some(store.clone()),
Slot::Released(store) => store.upgrade(),
})
.collect();
sets.iter().for_each(|store| store.finish());
self.enqueue(RunEvent::Finished {
outcome: outcome.clone(),
Expand Down Expand Up @@ -226,6 +263,33 @@ mod tests {
assert_eq!(state.drain(), [rows(0, 3)]);
}

#[test]
fn a_released_set_is_gone_from_the_run_and_the_later_sets_keep_their_index() {
let state = RunState::new(Box::new(CountingListener::default()));
let first = Arc::new(ResultStore::new(Vec::new().into()));
let second = Arc::new(ResultStore::new(Vec::new().into()));
let third = Arc::new(ResultStore::new(Vec::new().into()));
let dropped = Arc::downgrade(&third);
assert_eq!(state.add_set(first.clone()), 0);
assert_eq!(state.add_set(second.clone()), 1);
assert_eq!(state.add_set(third), 2);

state.release_set(0);
state.release_set(0);
state.release_set(2);
state.release_set(7);

assert!(state.set(0).is_none());
assert!(Arc::ptr_eq(&state.set(1).unwrap(), &second));
assert_eq!(Arc::strong_count(&first), 1);
assert!(dropped.upgrade().is_none());
assert_eq!(state.add_set(Arc::new(ResultStore::new(Vec::new().into()))), 3);
state.finish(RunOutcome::Cancelled, TransactionStateTag::Idle);
assert!(second.is_finished());
// The app may still read a set it released, and it ends with the run.
assert!(first.is_finished());
}

#[derive(Clone, Default)]
struct OutcomeAtWake {
outcome: Arc<OnceLock<watch::Receiver<Option<RunOutcome>>>>,
Expand Down
2 changes: 1 addition & 1 deletion windows/docs/decisions/0002-sql-editor-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
- A SwapChainPanel holds a composition swap chain (flip sequential, three buffers, at most two frames waiting). A frame starts only when the swap chain can take it, through its frame latency object, so Present never blocks the UI thread. Direct3D 11 runs on the GPU, or WARP when there is none or software rendering is asked for. Direct2D draws on it, DirectWrite lays out each visible line.
- Every editor on a UI thread draws on one Direct3D and Direct2D device, as the grid's rows do (0003), and the first editor to find it lost replaces it for the rest. Each editor has its own device context and swap chain. TabView unloads a tab's content on every switch, so a hidden editor gives back its swap chain (`SetSwapChain(null)`) and keeps its layouts and brushes; showing it again makes one swap chain.
- Line layouts are cached by text and colors, so lines that shift after an edit keep theirs; only the edited line is laid out again. A line over 4,096 characters is laid out in a slice around the visible columns.
- A frame is drawn on the UI thread when something changed, and many changes before it give one frame. It holds the gutter, current line band, find matches, selections, text, IME marks and carets. The caret blinks at the system rate, with the system caret width, and stops after the system caret timeout (`SPI_GETCARETTIMEOUT`, 5 seconds when the call fails) with no input, shown, as a Win32 edit control's does. In an inactive window (`InputActivationListener`) it is hidden and nothing blinks, as Win32's About Carets asks.
- A frame is drawn on the UI thread when something changed, and many changes before it give one frame. It holds the gutter, current line band, find matches, selections, text and IME marks. The carets are a composition visual of their own over the swap chain, one sprite per visible caret, as WinUI's TextBox keeps its caret in an element of its own (`TextBoxView.cpp`, `EnsureCaretElement`). SwapChainPanel draws its swap chain first (`SwapChainPanel.cpp`, `GetChildrenInRenderOrder`), so the panel's child visual lies above it. A frame places the sprites at the positions it laid out, snapped to pixels; a blink, focus or the window's activation only shows or hides the visual, with no frame. On `windows-2025` (run 43277097648) focus and a 5 second blink of 10 toggles presented 11 frames when the frame held the caret, and 0 with the visual. The caret blinks at the system rate, with the system caret width, and stops after the system caret timeout (`SPI_GETCARETTIMEOUT`, 5 seconds when the call fails) with no input, shown, as a Win32 edit control's does. In an inactive window (`InputActivationListener`) it is hidden and nothing blinks, as Win32's About Carets asks.
- Why a SwapChainPanel and not Composition drawing surfaces: one surface, presented when something changed, and a frame time measured from input to present; the same model as Windows Terminal. Surfaces per line would add their own management for scrolling that this cost does not need.
- Colors: theme resources for the chrome. In high contrast the system colors, selected text in the highlight text color, and no syntax colors.
- DPI: the buffer is in pixels and the panel's composition scale shrinks it back. Ctrl+wheel, Ctrl+= and Ctrl+- zoom.
Expand Down
Loading
Loading