re_ui 0.27.3

Rerun GUI theme and helpers, built around egui
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use re_entity_db::InstancePath;
use re_log_types::{
    ComponentPath, EntityPath, EntityPathPart, Instance,
    external::re_types_core::{
        ArchetypeName, ComponentDescriptor, ComponentIdentifier, ComponentType,
    },
};

use crate::HasDesignTokens as _;
use egui::{Color32, Style, TextFormat, TextStyle, text::LayoutJob};

// ----------------------------------------------------------------------------
pub trait SyntaxHighlighting {
    fn syntax_highlighted(&self, style: &Style) -> LayoutJob {
        let mut builder = SyntaxHighlightedBuilder::new();
        self.syntax_highlight_into(&mut builder);
        builder.into_job(style)
    }

    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder);
}

// ----------------------------------------------------------------------------

/// Easily build syntax-highlighted text.
#[derive(Debug, Default)]
pub struct SyntaxHighlightedBuilder {
    text: String,
    parts: smallvec::SmallVec<[SyntaxHighlightedPart; 1]>,
}

/// Easily build syntax-highlighted [`LayoutJob`]s.
///
/// Try to use one of the `append_*` or `with_*` methods that semantically matches
/// what you are trying to highlight. Check the docs of the `append_*` methods for examples
/// of what they should be used with.
///
/// The `with_*` methods are builder-style, taking `self` and returning `Self`.
/// The `append_*` methods take `&mut self` and return `&mut Self`.
///
/// Use the `with_*` methods when building something inline.
impl SyntaxHighlightedBuilder {
    pub const QUOTE_CHAR: char = '"';

    pub fn new() -> Self {
        Self::default()
    }

    /// Construct [`Self`] from an existing [`LayoutJob`].
    ///
    /// Some information (the `leading_space`) will be lost.
    pub fn from(job: impl Into<LayoutJob>) -> Self {
        let job = job.into();
        Self {
            text: job.text,
            parts: job
                .sections
                .into_iter()
                .map(|s| SyntaxHighlightedPart {
                    style: SyntaxHighlightedStyle::Custom(Box::new(s.format)),
                    byte_range: s.byte_range,
                })
                .collect(),
        }
    }

    /// Append anything that implements [`SyntaxHighlighting`].
    #[inline]
    pub fn with(mut self, portion: &dyn SyntaxHighlighting) -> Self {
        portion.syntax_highlight_into(&mut self);
        self
    }

    /// Append anything that implements [`SyntaxHighlighting`].
    #[inline]
    pub fn append(&mut self, portion: &dyn SyntaxHighlighting) -> &mut Self {
        portion.syntax_highlight_into(self);
        self
    }

    fn append_kind(&mut self, style: SyntaxHighlightedStyle, portion: &str) -> &mut Self {
        let start = self.text.len();
        self.text.push_str(portion);
        let end = self.text.len();
        self.parts.push(SyntaxHighlightedPart {
            byte_range: start..end,
            style,
        });
        self
    }
}

macro_rules! impl_style_fns {
    ($docs:literal, $pure:ident, $with:ident, $append:ident, $style:ident) => {
        impl_style_fns!($docs, $pure, $with, $append, (self, portion) {
            self.append_kind(SyntaxHighlightedStyle::$style, portion);
        });
    };
    ($docs:literal, $pure:ident, $with:ident, $append:ident, ($self:ident, $portion:ident) $content:expr) => {
        #[doc = $docs]
        #[inline]
        pub fn $with(mut self, portion: &str) -> Self {
            self.$append(portion);
            self
        }

        #[doc = $docs]
        #[inline]
        pub fn $append(&mut $self, $portion: &str) -> &mut Self {
            $content
            $self
        }

        #[doc = $docs]
        #[inline]
        pub fn $pure(portion: &str) -> Self {
            Self::new().$with(portion)
        }
    };
}

impl SyntaxHighlightedBuilder {
    impl_style_fns!(
        "Some primitive value, e.g. a number or bool.",
        primitive,
        with_primitive,
        append_primitive,
        Primitive
    );

    impl_style_fns!(
        "A string identifier.\n\nE.g. a variable name, field name, etc. Won't be quoted.",
        identifier,
        with_identifier,
        append_identifier,
        Identifier
    );

    impl_style_fns!(
        "Some string data. Will be quoted.",
        string_value,
        with_string_value,
        append_string_value,
        (self, portion) {
            let quote = Self::QUOTE_CHAR.to_string();
            self.append_kind(SyntaxHighlightedStyle::StringValue, &quote);
            self.append_kind(SyntaxHighlightedStyle::StringValue, portion);
            self.append_kind(SyntaxHighlightedStyle::StringValue, &quote);
        }
    );

    impl_style_fns!(
        "A keyword, e.g. a filter operator, like `and` or `all`",
        keyword,
        with_keyword,
        append_keyword,
        Keyword
    );

    impl_style_fns!(
        "An index number, e.g. an array index.",
        index,
        with_index,
        append_index,
        Index
    );

    impl_style_fns!(
        "Some syntax, e.g. brackets, commas, colons, etc.",
        syntax,
        with_syntax,
        append_syntax,
        Syntax
    );

    impl_style_fns!(
        "Body text, subdued (default label color).",
        body,
        with_body,
        append_body,
        Body
    );

    impl_style_fns!(
        "Body text with default color (color of inactive buttons).",
        body_default,
        with_body_default,
        append_body_default,
        BodyDefault
    );

    impl_style_fns!(
        "Body text in italics, e.g. for emphasis.",
        body_italics,
        with_body_italics,
        append_body_italics,
        BodyItalics
    );

    /// Append text with a custom format.
    #[inline]
    pub fn append_with_format(&mut self, text: &str, format: TextFormat) -> &mut Self {
        self.append_kind(SyntaxHighlightedStyle::Custom(Box::new(format)), text);
        self
    }

    /// Append text with a custom format closure.
    #[inline]
    pub fn append_with_format_closure<F>(&mut self, text: &str, f: F) -> &mut Self
    where
        F: 'static + Fn(&Style) -> TextFormat,
    {
        self.append_kind(SyntaxHighlightedStyle::CustomClosure(Box::new(f)), text);
        self
    }

    /// With a custom format.
    #[inline]
    pub fn with_format(mut self, text: &str, format: TextFormat) -> Self {
        self.append_with_format(text, format);
        self
    }

    /// With a custom format closure.
    #[inline]
    pub fn with_format_closure<F>(mut self, text: &str, f: F) -> Self
    where
        F: 'static + Fn(&Style) -> TextFormat,
    {
        self.append_with_format_closure(text, f);
        self
    }
}

// ----------------------------------------------------------------------------

impl SyntaxHighlightedBuilder {
    #[inline]
    pub fn into_job(self, style: &Style) -> LayoutJob {
        let mut job = LayoutJob {
            text: self.text,
            sections: Vec::with_capacity(self.parts.len()),
            ..Default::default()
        };

        for part in self.parts {
            let format = part.style.into_format(style);
            job.sections.push(egui::text::LayoutSection {
                byte_range: part.byte_range,
                format,
                leading_space: 0.0,
            });
        }

        job
    }

    #[inline]
    pub fn into_widget_text(self, style: &Style) -> egui::WidgetText {
        self.into_job(style).into()
    }

    pub fn text(&self) -> &str {
        &self.text
    }
}

// ----------------------------------------------------------------------------

enum SyntaxHighlightedStyle {
    StringValue,
    Identifier,
    Keyword,
    Index,
    Primitive,
    Syntax,
    Body,
    BodyDefault,
    BodyItalics,
    Custom(Box<TextFormat>),
    CustomClosure(Box<dyn Fn(&Style) -> TextFormat>),
}

impl std::fmt::Debug for SyntaxHighlightedStyle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::StringValue => write!(f, "StringValue"),
            Self::Identifier => write!(f, "Identifier"),
            Self::Keyword => write!(f, "Keyword"),
            Self::Index => write!(f, "Index"),
            Self::Primitive => write!(f, "Primitive"),
            Self::Syntax => write!(f, "Syntax"),
            Self::Body => write!(f, "Body"),
            Self::BodyDefault => write!(f, "BodyDefault"),
            Self::BodyItalics => write!(f, "BodyItalics"),
            Self::Custom(_) => write!(f, "Custom(…)"),
            Self::CustomClosure(_) => write!(f, "CustomClosure(…)"),
        }
    }
}

#[derive(Debug)]
struct SyntaxHighlightedPart {
    byte_range: std::ops::Range<usize>,
    style: SyntaxHighlightedStyle,
}

impl SyntaxHighlightedStyle {
    /// Monospace text format with a specific color (that may be overridden by the style).
    pub fn monospace_with_color(style: &Style, color: Color32) -> TextFormat {
        TextFormat {
            font_id: TextStyle::Monospace.resolve(style),
            color: style.visuals.override_text_color.unwrap_or(color),
            ..Default::default()
        }
    }

    pub fn body_with_color(style: &Style, color: Color32) -> TextFormat {
        TextFormat {
            font_id: TextStyle::Body.resolve(style),
            color: style.visuals.override_text_color.unwrap_or(color),
            ..Default::default()
        }
    }

    pub fn body(style: &Style) -> TextFormat {
        Self::body_with_color(style, Color32::PLACEHOLDER)
    }

    pub fn into_format(self, style: &Style) -> TextFormat {
        match self {
            Self::StringValue => {
                Self::monospace_with_color(style, style.tokens().code_string_color)
            }
            Self::Identifier => Self::monospace_with_color(style, style.tokens().text_default),
            // TODO(lucas): Find a better way to deal with body / monospace style
            Self::Keyword => Self::body_with_color(style, style.tokens().code_keyword_color),
            Self::Index => Self::monospace_with_color(style, style.tokens().code_index_color),
            Self::Primitive => {
                Self::monospace_with_color(style, style.tokens().code_primitive_color)
            }
            Self::Syntax => Self::monospace_with_color(style, style.tokens().text_subdued),
            Self::Body => Self::body(style),
            Self::BodyDefault => {
                let mut format = Self::body(style);
                format.color = style
                    .visuals
                    .override_text_color
                    .unwrap_or(style.tokens().text_default);
                format
            }
            Self::BodyItalics => {
                let mut format = Self::body(style);
                format.italics = true;
                format
            }
            Self::Custom(format) => *format,
            Self::CustomClosure(f) => f(style),
        }
    }
}

// ----------------------------------------------------------------------------

impl SyntaxHighlighting for EntityPathPart {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        builder.append_identifier(&self.ui_string());
    }
}

impl SyntaxHighlighting for Instance {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        if self.is_all() {
            builder.append_primitive("all");
        } else {
            builder.append_index(&re_format::format_uint(self.get()));
        }
    }
}

impl SyntaxHighlighting for EntityPath {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        builder.append_syntax("/");

        for (i, part) in self.iter().enumerate() {
            if i != 0 {
                builder.append_syntax("/");
            }
            builder.append(part);
        }
    }
}

impl SyntaxHighlighting for InstancePath {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        builder.append(&self.entity_path);
        if self.instance.is_specific() {
            builder.append(&InstanceInBrackets(self.instance));
        }
    }
}

impl SyntaxHighlighting for ComponentType {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        builder.append_identifier(self.short_name());
    }
}

impl SyntaxHighlighting for ArchetypeName {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        builder.append_identifier(self.short_name());
    }
}

impl SyntaxHighlighting for ComponentIdentifier {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        builder.append_identifier(self.as_ref());
    }
}

impl SyntaxHighlighting for ComponentDescriptor {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        builder.append_identifier(self.display_name());
    }
}

impl SyntaxHighlighting for ComponentPath {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        let Self {
            entity_path,
            component,
        } = self;
        builder
            .append(entity_path)
            .append_syntax(":")
            .append(component);
    }
}

/// Formats an instance number enclosed in square brackets: `[123]`
pub struct InstanceInBrackets(pub Instance);

impl SyntaxHighlighting for InstanceInBrackets {
    fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
        builder
            .append_syntax("[")
            .append(&self.0)
            .append_syntax("]");
    }
}

macro_rules! impl_sh_primitive {
    ($t:ty, $to_string:path) => {
        impl SyntaxHighlighting for $t {
            fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
                builder.append_primitive(&$to_string(*self));
            }
        }
    };
    ($t:ty) => {
        impl SyntaxHighlighting for $t {
            fn syntax_highlight_into(&self, builder: &mut SyntaxHighlightedBuilder) {
                builder.append_primitive(&self.to_string());
            }
        }
    };
}

impl_sh_primitive!(f32, re_format::format_f32);
impl_sh_primitive!(f64, re_format::format_f64);

impl_sh_primitive!(i8, re_format::format_int);
impl_sh_primitive!(i16, re_format::format_int);
impl_sh_primitive!(i32, re_format::format_int);
impl_sh_primitive!(i64, re_format::format_int);
impl_sh_primitive!(isize, re_format::format_int);
impl_sh_primitive!(u8, re_format::format_uint);
impl_sh_primitive!(u16, re_format::format_uint);
impl_sh_primitive!(u32, re_format::format_uint);
impl_sh_primitive!(u64, re_format::format_uint);
impl_sh_primitive!(usize, re_format::format_uint);

impl_sh_primitive!(bool);

impl<T: SyntaxHighlighting> From<T> for SyntaxHighlightedBuilder {
    fn from(portion: T) -> Self {
        let mut builder = Self::new();
        portion.syntax_highlight_into(&mut builder);
        builder
    }
}