Merge pull request #394 from ludovic111/fix/text-highlight

Vanilla text selection colours and blinking cursors in the creative search and anvil
This commit is contained in:
Ludovic Marie
2026-10-15 21:07:57 +02:00
committed by GitHub
9 changed files with 258 additions and 51 deletions
+7
View File
@@ -36,6 +36,9 @@ pub struct Creative {
/// The scrollbar is held (scrolling): dragging moves it.
pub scrolling: bool,
pub search: String,
/// When the search box took the focus (`EditBox.setFocused`): its
/// cursor blinks from then.
pub search_focused: std::time::Instant,
/// The search tab's stacks, in its display order.
search_items: Vec<ItemStack>,
search_index: Vec<SearchEntry>,
@@ -212,6 +215,7 @@ impl Creative {
scroll: 0.0,
scrolling: false,
search: String::new(),
search_focused: std::time::Instant::now(),
search_items,
search_index,
}
@@ -226,6 +230,9 @@ impl Creative {
}
self.selected = tab;
self.scroll = 0.0;
if self.tab().search {
self.search_focused = std::time::Instant::now();
}
}
/// The search tab's stacks.
pub fn search_items(&self) -> &[ItemStack] {
+14 -2
View File
@@ -7803,8 +7803,20 @@ impl Game<'_> {
);
}
if tab.search {
let shown = format!("{}_", self.creative_screen.search);
batch.text(atlas, &shown, ox + 82.0, oy + 6.0, u32::MAX, true);
// The search box: an unbordered EditBox of 80 at (82, 6), white.
let search = &self.creative_screen.search;
horizon_client::ui::append_field(
batch,
atlas,
search,
(ox + 82.0, oy + 6.0, 80.0),
u32::MAX,
clipboard::CREATIVE_SEARCH_CHARS,
self.text_selection
.covers(clipboard::CREATIVE_SEARCH, search),
true,
self.creative_screen.search_focused.elapsed().as_millis(),
);
}
let mut hovered: Option<String> = None;
if tab.inventory {
+4 -3
View File
@@ -85,7 +85,7 @@ impl Game<'_> {
if Self::append_shortcut(
&mut self.text_selection,
&mut self.clipboard,
("creative.search", 0),
CREATIVE_SEARCH,
&mut self.creative_screen.search,
shortcut,
CREATIVE_SEARCH_CHARS,
@@ -96,7 +96,7 @@ impl Game<'_> {
/// Typing or a backspace in the creative search box.
pub(super) fn creative_search_edit(&mut self, typed: Option<&str>, backspace: bool) {
let search = &mut self.creative_screen.search;
let cleared = self.text_selection.take(("creative.search", 0), search);
let cleared = self.text_selection.take(CREATIVE_SEARCH, search);
if backspace {
if !cleared {
search.pop();
@@ -109,4 +109,5 @@ impl Game<'_> {
}
/// `CreativeModeInventoryScreen`'s search box: `setMaxLength(50)`.
const CREATIVE_SEARCH_CHARS: usize = 50;
pub(super) const CREATIVE_SEARCH_CHARS: usize = 50;
pub(super) const CREATIVE_SEARCH: horizon_client::clipboard::FieldId = ("creative.search", 0);
@@ -1096,13 +1096,10 @@ impl Game<'_> {
),
Call::Highlight { x0, y0, x1, y1 } => {
let (a, b) = (*x0.min(x1), *x0.max(x1));
batch.fill(
batch.text_highlight(
atlas,
a as f32,
*y0 as f32,
(b - a) as f32,
(y1 - y0) as f32,
rgba(0, 0, 255, 128),
(a as f32, *y0 as f32, (b - a) as f32, (y1 - y0) as f32),
true,
);
}
Call::Text {
@@ -227,6 +227,14 @@ impl Game<'_> {
let x = cx - (lw as i32 / 2) as f32;
let ly = y + i as f32 * line_height - midpoint;
batch.text(atlas, line, x, ly, color, false);
if i == edit.line
&& self
.text_selection
.covers(sign_line_id(edit.front, i), line)
{
// AbstractSignEditScreen: the selection from its start to its end.
batch.text_highlight(atlas, (x, ly, lw, line_height), true);
}
if i == edit.line && blink {
// TextCursorUtils.extractAppendCursor: an underscore after the text.
batch.text(atlas, "_", x + lw, ly, color, false);
+12 -10
View File
@@ -140,6 +140,8 @@ pub(super) struct Station {
input_item: Option<Arc<str>>,
/// Anvil: the input the rename box was last filled from.
anvil_last: Option<ItemStack>,
/// When the screen opened: the rename box has the focus from then.
opened: std::time::Instant,
pub(super) last_sound: u64,
/// Villager trading state.
pub(super) merchant: Option<Box<super::trading::MerchantState>>,
@@ -164,6 +166,7 @@ impl Station {
start: 0,
input_item: None,
anvil_last: None,
opened: std::time::Instant::now(),
last_sound: 0,
merchant: None,
beacon: [None; 2],
@@ -1645,18 +1648,17 @@ impl Game<'_> {
);
}
if s.inputs[0].is_some() {
let blink = if (self.ticks / 6).is_multiple_of(2) {
"_"
} else {
""
};
batch.text(
// AnvilScreen's name box: white, 103 wide, no inverted highlight.
horizon_client::ui::append_field(
batch,
atlas,
&format!("{}{blink}", s.name),
ox + 62.0,
oy + 24.0,
&s.name,
(ox + 62.0, oy + 24.0, 103.0),
u32::MAX,
true,
ANVIL_NAME_CHARS,
self.text_selection.covers(ANVIL_NAME, &s.name),
false,
s.opened.elapsed().as_millis(),
);
}
let cost = s.anvil.cost;
+80 -22
View File
@@ -328,9 +328,18 @@ pub struct HudBatch {
pub height: f32,
/// Glyph pixels to upload into the atlas before drawing.
pub patches: Vec<crate::font::Patch>,
/// Vertex ranges drawn with `RenderPipelines.CROSSHAIR`'s
/// `BlendFunction.INVERT` instead of alpha blending.
pub invert: Vec<std::ops::Range<u32>>,
/// Vertex ranges drawn with another blend than alpha blending, in order.
pub blends: Vec<(std::ops::Range<u32>, Blend)>,
}
/// How a run of HUD vertices blends with what is under it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Blend {
/// `BlendFunction.TRANSLUCENT`.
Alpha,
/// `BlendFunction.INVERT` (`RenderPipelines.CROSSHAIR`, `GUI_INVERT`).
Invert,
/// `BlendFunction.ADDITIVE` (`RenderPipelines.GUI_TEXT_HIGHLIGHT`).
Additive,
}
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r)
@@ -353,34 +362,56 @@ impl HudBatch {
width: (window[0] as f32 / scale as f32).ceil(),
height: (window[1] as f32 / scale as f32).ceil(),
patches: Vec::new(),
invert: Vec::new(),
blends: Vec::new(),
}
}
/// Draw the vertices added since `start` with the inverting blend.
pub fn invert_since(&mut self, start: usize) {
self.blend_since(start, Blend::Invert);
}
/// Draw the vertices added since `start` with `blend`.
pub fn blend_since(&mut self, start: usize, blend: Blend) {
let range = start as u32..self.vertices.len() as u32;
if range.is_empty() {
if range.is_empty() || blend == Blend::Alpha {
return;
}
match self.invert.last_mut() {
Some(last) if last.end == range.start => last.end = range.end,
_ => self.invert.push(range),
match self.blends.last_mut() {
Some((last, b)) if last.end == range.start && *b == blend => last.end = range.end,
_ => self.blends.push((range, blend)),
}
}
/// The vertex ranges in order, each with whether it inverts.
pub fn runs(&self) -> Vec<(std::ops::Range<u32>, bool)> {
/// `GuiGraphicsExtractor.textHighlight`: with `invert_text` the area's
/// colours are inverted first (white text on a dark field turns blue on
/// white), then blue is added.
pub fn text_highlight(
&mut self,
atlas: &HudAtlas,
(x, y, w, h): (f32, f32, f32, f32),
invert_text: bool,
) {
if invert_text {
let start = self.vertices.len();
self.fill(atlas, x, y, w, h, rgba(255, 255, 255, 255));
self.invert_since(start);
}
let start = self.vertices.len();
self.fill(atlas, x, y, w, h, rgba(0, 0, 255, 255));
self.blend_since(start, Blend::Additive);
}
/// The vertex ranges in order, each with its blend.
pub fn runs(&self) -> Vec<(std::ops::Range<u32>, Blend)> {
let mut out = Vec::new();
let mut at = 0;
for r in &self.invert {
for (r, blend) in &self.blends {
if r.start > at {
out.push((at..r.start, false));
out.push((at..r.start, Blend::Alpha));
}
out.push((r.clone(), true));
out.push((r.clone(), *blend));
at = r.end;
}
let end = self.vertices.len() as u32;
if end > at {
out.push((at..end, false));
out.push((at..end, Blend::Alpha));
}
out
}
@@ -675,6 +706,7 @@ pub struct HudRenderer {
pipeline: wgpu::RenderPipeline,
/// `RenderPipelines.CROSSHAIR`.
invert_pipeline: wgpu::RenderPipeline,
additive_pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
buffer: wgpu::Buffer,
@@ -805,6 +837,20 @@ impl HudRenderer {
},
"fs_crosshair",
);
// BlendFunction.ADDITIVE: ONE, ONE.
let add = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
};
let additive_pipeline = create(
"HUD text highlight",
wgpu::BlendState {
color: add,
alpha: add,
},
"fs_main",
);
let capacity = 1 << 16;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HUD vertices"),
@@ -817,6 +863,7 @@ impl HudRenderer {
fire_animations: Vec::new(),
pipeline,
invert_pipeline,
additive_pipeline,
group,
uniform,
buffer,
@@ -932,11 +979,11 @@ impl HudRenderer {
});
pass.set_bind_group(0, &self.group, &[]);
pass.set_vertex_buffer(0, self.buffer.slice(..));
for (range, invert) in batch.runs() {
pass.set_pipeline(if invert {
&self.invert_pipeline
} else {
&self.pipeline
for (range, blend) in batch.runs() {
pass.set_pipeline(match blend {
Blend::Alpha => &self.pipeline,
Blend::Invert => &self.invert_pipeline,
Blend::Additive => &self.additive_pipeline,
});
pass.draw(range, 0..1);
}
@@ -1039,11 +1086,22 @@ mod tests {
quad(&mut batch);
batch.invert_since(start);
batch.invert_since(batch.vertices.len());
let start = batch.vertices.len();
quad(&mut batch);
assert_eq!(batch.invert, vec![6..18]);
batch.blend_since(start, Blend::Additive);
quad(&mut batch);
assert_eq!(
batch.blends,
vec![(6..18, Blend::Invert), (18..24, Blend::Additive)]
);
assert_eq!(
batch.runs(),
vec![(0..6, false), (6..18, true), (18..24, false)]
vec![
(0..6, Blend::Alpha),
(6..18, Blend::Invert),
(18..24, Blend::Additive),
(24..30, Blend::Alpha)
]
);
}
#[test]
@@ -1056,7 +1114,7 @@ mod tests {
width: width as f32,
height: height as f32,
patches: Vec::new(),
invert: Vec::new(),
blends: Vec::new(),
};
for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] {
assert_eq!(
+3 -6
View File
@@ -920,13 +920,10 @@ pub fn paint(batch: &mut HudBatch, atlas: &HudAtlas, draws: &[Draw]) {
),
Draw::Highlight { x0, y0, x1, y1 } => {
let (a, b) = ((*x0).min(*x1), (*x0).max(*x1));
batch.fill(
batch.text_highlight(
atlas,
a as f32,
*y0 as f32,
(b - a) as f32,
(y1 - y0) as f32,
crate::hud::rgba(0, 0, 255, 128),
(a as f32, *y0 as f32, (b - a) as f32, (y1 - y0) as f32),
true,
);
}
Draw::Text {
+127 -2
View File
@@ -598,6 +598,46 @@ pub struct EditBox {
pub suggestion: Option<String>,
pub text_color: u32,
}
/// `EditBox.extractWidgetRenderState` for Horizon's append-only fields,
/// unbordered and with the cursor at the end: the text from (x, y), the
/// highlight when Select All covers the value (`invert_text` as
/// `setInvertHighlightedTextColor`), and the cursor, blinking from when the
/// field took the focus (`TextCursorUtils.isCursorVisible`): an underscore,
/// or a bar once the value is `max_chars` long.
#[allow(clippy::too_many_arguments)]
pub fn append_field(
batch: &mut HudBatch,
atlas: &HudAtlas,
value: &str,
(x, y, width): (f32, f32, f32),
color: u32,
max_chars: usize,
selected: bool,
invert_text: bool,
focused_ms: u128,
) {
let mut cursor_x = x;
if !value.is_empty() {
batch.text(atlas, value, x, y, color, true);
cursor_x += HudBatch::text_width(atlas, value) + 1.0;
}
let insert = char_len(value) >= max_chars;
if insert {
cursor_x -= 1.0;
}
if selected && !value.is_empty() {
let right = x + width;
let (x0, x1) = (cursor_x.min(right), (x - 1.0).min(right));
batch.text_highlight(atlas, (x1, y - 1.0, x0 - x1, 11.0), invert_text);
}
if (focused_ms / 300).is_multiple_of(2) {
if insert {
batch.fill(atlas, cursor_x, y - 1.0, 1.0, 11.0, color);
} else {
batch.text(atlas, "_", cursor_x, y, color, true);
}
}
}
fn byte_index(s: &str, chars: usize) -> usize {
s.char_indices().nth(chars).map_or(s.len(), |(i, _)| i)
}
@@ -904,8 +944,11 @@ impl EditBox {
+ atlas
.font
.width(&displayed.chars().take(rel_highlight).collect::<String>());
let (a, b) = (cursor_x.min(hx - 1.0), cursor_x.max(hx - 1.0));
batch.fill(atlas, a, ty - 1.0, b - a, 11.0, rgba(0, 0, 255, 128));
// textHighlight between the cursor and the anchor, clipped at the right edge.
let right = self.x + self.width;
let (x0, x1) = (cursor_x.min(right), (hx - 1.0).min(right));
let (a, b) = (x0.min(x1), x0.max(x1));
batch.text_highlight(atlas, (a, ty - 1.0, b - a, 11.0), true);
}
if show_cursor {
if insert {
@@ -939,6 +982,88 @@ impl EditBox {
mod tests {
use super::*;
#[test]
fn append_fields_highlight_the_whole_value_and_blink_their_cursor() {
use crate::hud::Blend;
let atlas = HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap();
let end = 10.0 + HudBatch::text_width(&atlas, "abc") + 1.0;
let span = |b: &HudBatch, r: &std::ops::Range<u32>| {
let v = &b.vertices[r.start as usize..r.end as usize];
let xs = v.iter().map(|v| v.pos[0]);
let ys = v.iter().map(|v| v.pos[1]);
(
xs.clone().fold(f32::MAX, f32::min),
xs.fold(f32::MIN, f32::max),
ys.clone().fold(f32::MAX, f32::min),
ys.fold(f32::MIN, f32::max),
)
};
// Select All in the creative search: inverted white, then blue added,
// from one pixel before the text to the cursor, 11 high.
let mut b = HudBatch::new([854, 480]);
append_field(
&mut b,
&atlas,
"abc",
(10.0, 20.0, 80.0),
u32::MAX,
50,
true,
true,
0,
);
let blends: Vec<_> = b.blends.iter().map(|(_, blend)| *blend).collect();
assert_eq!(blends, vec![Blend::Invert, Blend::Additive]);
for (r, _) in &b.blends {
assert_eq!(span(&b, r), (9.0, end, 19.0, 30.0));
}
// The anvil keeps its text colour; 300 ms later the cursor is hidden.
let mut b = HudBatch::new([854, 480]);
append_field(
&mut b,
&atlas,
"abc",
(10.0, 20.0, 103.0),
u32::MAX,
50,
true,
false,
300,
);
let blends: Vec<_> = b.blends.iter().map(|(_, blend)| *blend).collect();
assert_eq!(blends, vec![Blend::Additive]);
let quads = |ms| {
let mut b = HudBatch::new([854, 480]);
append_field(
&mut b,
&atlas,
"abc",
(10.0, 20.0, 103.0),
0,
50,
false,
false,
ms,
);
b.vertices.len()
};
assert!(quads(300) < quads(600));
// A full field shows a bar on its last pixel instead of an underscore.
let mut b = HudBatch::new([854, 480]);
append_field(
&mut b,
&atlas,
"abc",
(10.0, 20.0, 80.0),
u32::MAX,
3,
false,
true,
0,
);
let bar = b.vertices.len() as u32 - 6..b.vertices.len() as u32;
assert_eq!(span(&b, &bar), (end - 1.0, end, 19.0, 30.0));
}
#[test]
fn held_scrollbars_follow_the_pointer_and_stop_at_the_ends() {
// A 100-pixel list holding 400: the thumb is 25 -> 32 high, so a
// pixel of drag scrolls 300 / 68 pixels (AbstractScrollArea.mouseDragged).