1
0
mirror of https://github.com/emilk/egui.git synced 2026-09-02 06:40:06 -04:00

Change text color of selected text (#7691)

Selected text now gets the color of `visuals.selection.stroke.color`.
This means you can have inverted colors for selected text, like in the
new test:
<img width="154" height="46" alt="image"
src="https://github.com/user-attachments/assets/2666361d-d7e2-4d50-8e4d-2fcc128f1a81"
/>


It also means the color of selected text in labels matches that of the
text color of selected buttons.
This commit is contained in:
Emil Ernerfeldt
2025-11-07 15:34:36 +01:00
committed by GitHub
parent d8dcb31673
commit fa4cfec777
13 changed files with 70 additions and 8 deletions

View File

@@ -1129,7 +1129,10 @@ impl Visuals {
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Selection {
/// Background color behind selected text and other selectable buttons.
pub bg_fill: Color32,
/// Color of selected text.
pub stroke: Stroke,
}

View File

@@ -25,7 +25,9 @@ pub fn paint_text_selection(
// and so we need to clone it if it is shared:
let galley: &mut Galley = Arc::make_mut(galley);
let color = visuals.selection.bg_fill;
let background_color = visuals.selection.bg_fill;
let text_color = visuals.selection.stroke.color;
let [min, max] = cursor_range.sorted_cursors();
let min = galley.layout_from_cursor(min);
let max = galley.layout_from_cursor(max);
@@ -53,6 +55,31 @@ pub fn paint_text_selection(
let rect = Rect::from_min_max(pos2(left, 0.0), pos2(right, row.size.y));
let mesh = &mut row.visuals.mesh;
if !row.glyphs.is_empty() {
// Change color of the selected text:
let first_glyph_index = if ri == min.row { min.column } else { 0 };
let last_glyph_index = if ri == max.row {
max.column
} else {
row.glyphs.len() - 1
};
let first_vertex_index = row
.glyphs
.get(first_glyph_index)
.map_or(row.visuals.glyph_vertex_range.start, |g| {
g.first_vertex as _
});
let last_vertex_index = row
.glyphs
.get(last_glyph_index)
.map_or(row.visuals.glyph_vertex_range.end, |g| g.first_vertex as _);
for vi in first_vertex_index..last_vertex_index {
mesh.vertices[vi].color = text_color;
}
}
// Time to insert the selection rectangle into the row mesh.
// It should be on top (after) of any background in the galley,
// but behind (before) any glyphs. The row visuals has this information:
@@ -60,7 +87,7 @@ pub fn paint_text_selection(
// Start by appending the selection rectangle to end of the mesh, as two triangles (= 6 indices):
let num_indices_before = mesh.indices.len();
mesh.add_colored_rect(rect, color);
mesh.add_colored_rect(rect, background_color);
assert_eq!(
num_indices_before + 6,
mesh.indices.len(),