deweygui 1.0.0

An agentic-first GUI framework with pluggable rendering backends and complete ontology for AI agent discoverability
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
//! Rich text widget — renders styled text spans and basic Markdown.
//!
//! Supports inline formatting: **bold**, *italic*, `code`, ~~strikethrough~~,
//! and \[links\](url). Paragraphs are separated by blank lines.

use crate::core::style::{Color, FontWeight, TextStyle};
use crate::core::{Position, Rect};
use crate::ontology::*;
use crate::runtime::Frame;
use crate::widget::Widget;

/// A styled text span.
#[derive(Debug, Clone)]
pub struct TextSpan {
    /// The text content.
    pub text: String,
    /// Whether the text is bold.
    pub bold: bool,
    /// Whether the text is italic.
    pub italic: bool,
    /// Whether the text is monospace/code.
    pub code: bool,
    /// Whether the text has strikethrough.
    pub strikethrough: bool,
    /// Optional link URL.
    pub link: Option<String>,
    /// Optional color override.
    pub color: Option<Color>,
}

impl TextSpan {
    /// Create a plain text span.
    #[must_use]
    pub fn plain(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            bold: false,
            italic: false,
            code: false,
            strikethrough: false,
            link: None,
            color: None,
        }
    }

    /// Create a bold text span.
    #[must_use]
    pub fn bold(text: impl Into<String>) -> Self {
        Self {
            bold: true,
            ..Self::plain(text)
        }
    }

    /// Create an italic text span.
    #[must_use]
    pub fn italic(text: impl Into<String>) -> Self {
        Self {
            italic: true,
            ..Self::plain(text)
        }
    }

    /// Create a code (monospace) text span.
    #[must_use]
    pub fn code(text: impl Into<String>) -> Self {
        Self {
            code: true,
            ..Self::plain(text)
        }
    }

    /// Create a link text span.
    #[must_use]
    pub fn link(text: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            link: Some(url.into()),
            color: Some(Color::rgba(0.4, 0.65, 1.0, 1.0)),
            ..Self::plain(text)
        }
    }

    /// Set a color override on this span.
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }
}

/// A rich text widget that renders styled text spans.
pub struct RichText {
    spans: Vec<TextSpan>,
    agent_id: String,
    font_size: f32,
    base_color: Color,
}

impl RichText {
    /// Create from a list of styled spans.
    #[must_use]
    pub fn new(spans: Vec<TextSpan>) -> Self {
        Self {
            spans,
            agent_id: String::new(),
            font_size: 14.0,
            base_color: Color::WHITE,
        }
    }

    /// Parse basic Markdown into rich text.
    ///
    /// Supported syntax: `**bold**`, `*italic*`, `` `code` ``,
    /// `~~strikethrough~~`, `[text](url)`.
    pub fn from_markdown(md: &str) -> Self {
        Self::new(parse_markdown(md))
    }

    /// Set the agent ID.
    pub fn agent_id(mut self, id: impl Into<String>) -> Self {
        self.agent_id = id.into();
        self
    }

    /// Set the base font size.
    pub fn font_size(mut self, size: f32) -> Self {
        self.font_size = size;
        self
    }

    /// Set the base text color.
    pub fn color(mut self, color: Color) -> Self {
        self.base_color = color;
        self
    }
}

impl Discoverable for RichText {
    fn schema(&self) -> WidgetSchema {
        let mut schema = WidgetSchema::new(
            "RichText",
            "A rich text display with styled spans and Markdown support",
            SemanticRole::Display,
        );
        schema.usage_hint = Some("RichText::from_markdown(\"**bold** and *italic*\")".into());
        schema.tags = vec![
            "text".into(),
            "rich".into(),
            "markdown".into(),
            "formatted".into(),
        ];
        schema
    }

    fn capabilities(&self) -> Vec<AgentCapability> {
        vec![AgentCapability::Focusable, AgentCapability::Copyable]
    }

    fn actions(&self) -> Vec<AgentAction> {
        vec![
            AgentAction::with_params(
                "set_markdown",
                "Replace content with parsed Markdown",
                vec![ActionParam::required(
                    "content",
                    "Markdown string",
                    ActionParamType::String,
                )],
                true,
            ),
            AgentAction::simple("clear", "Remove all spans", true),
        ]
    }

    fn semantic_role(&self) -> SemanticRole {
        SemanticRole::Display
    }

    fn agent_state(&self) -> serde_json::Value {
        let plain: String = self.spans.iter().map(|s| s.text.as_str()).collect();
        let spans: Vec<serde_json::Value> = self
            .spans
            .iter()
            .map(|s| {
                let mut obj = serde_json::json!({ "text": s.text });
                if s.bold {
                    obj["bold"] = serde_json::json!(true);
                }
                if s.italic {
                    obj["italic"] = serde_json::json!(true);
                }
                if s.code {
                    obj["code"] = serde_json::json!(true);
                }
                if s.strikethrough {
                    obj["strikethrough"] = serde_json::json!(true);
                }
                if let Some(ref link) = s.link {
                    obj["link"] = serde_json::json!(link);
                }
                obj
            })
            .collect();
        serde_json::json!({
            "text": plain,
            "span_count": self.spans.len(),
            "spans": spans,
        })
    }

    fn execute_action(
        &mut self,
        action: &str,
        params: &serde_json::Value,
    ) -> Result<serde_json::Value, String> {
        match action {
            "set_markdown" => {
                let content = params["content"].as_str().ok_or("missing content")?;
                self.spans = parse_markdown(content);
                Ok(serde_json::json!({ "span_count": self.spans.len() }))
            }
            "clear" => {
                self.spans.clear();
                Ok(serde_json::json!({ "span_count": 0 }))
            }
            _ => Err(format!("Unknown action: {action}")),
        }
    }

    fn agent_id(&self) -> Option<&str> {
        if self.agent_id.is_empty() {
            None
        } else {
            Some(&self.agent_id)
        }
    }

    fn accessibility_label(&self) -> Option<String> {
        let plain: String = self.spans.iter().map(|s| s.text.as_str()).collect();
        if plain.is_empty() { None } else { Some(plain) }
    }
}

impl Widget for RichText {
    fn render(self, area: Rect, frame: &mut Frame<'_>) {
        if !self.agent_id.is_empty() {
            let plain: String = self.spans.iter().map(|s| s.text.as_str()).collect();
            let node = UiNode::new("RichText", SemanticRole::Display)
                .with_id(&self.agent_id)
                .with_bounds(area.into())
                .with_property("text", serde_json::json!(plain));
            frame.register_widget(node);
        }

        let mut x = area.x;
        let y = area.y;

        for span in &self.spans {
            let color = span.color.unwrap_or(self.base_color);
            let weight = if span.bold {
                FontWeight::Bold
            } else {
                FontWeight::Regular
            };
            let ts = TextStyle {
                font_size: self.font_size,
                color,
                weight,
                italic: span.italic,
                strikethrough: span.strikethrough,
                underline: span.link.is_some(),
                ..Default::default()
            };

            if span.code {
                // Draw code background
                let size = frame.painter().measure_text(&span.text, &ts);
                frame.painter().fill_rect(
                    Rect::new(x, y, size.width + 4.0, size.height),
                    Color::rgba(0.2, 0.2, 0.25, 0.6),
                    2.0,
                );
                frame
                    .painter()
                    .text(Position::new(x + 2.0, y), &span.text, &ts);
                x += size.width + 6.0;
            } else {
                let size = frame.painter().measure_text(&span.text, &ts);
                frame.painter().text(Position::new(x, y), &span.text, &ts);
                x += size.width;
            }
        }
    }
}

/// Parse basic inline Markdown into spans.
fn parse_markdown(input: &str) -> Vec<TextSpan> {
    let mut spans = Vec::new();
    let chars: Vec<char> = input.chars().collect();
    let len = chars.len();
    let mut i = 0;
    let mut buf = String::new();

    while i < len {
        // **bold**
        if i + 1 < len && chars[i] == '*' && chars[i + 1] == '*' {
            if !buf.is_empty() {
                spans.push(TextSpan::plain(std::mem::take(&mut buf)));
            }
            i += 2;
            let mut bold_buf = String::new();
            while i + 1 < len && !(chars[i] == '*' && chars[i + 1] == '*') {
                bold_buf.push(chars[i]);
                i += 1;
            }
            if i + 1 < len {
                i += 2; // skip closing **
            }
            spans.push(TextSpan::bold(bold_buf));
            continue;
        }

        // ~~strikethrough~~
        if i + 1 < len && chars[i] == '~' && chars[i + 1] == '~' {
            if !buf.is_empty() {
                spans.push(TextSpan::plain(std::mem::take(&mut buf)));
            }
            i += 2;
            let mut strike_buf = String::new();
            while i + 1 < len && !(chars[i] == '~' && chars[i + 1] == '~') {
                strike_buf.push(chars[i]);
                i += 1;
            }
            if i + 1 < len {
                i += 2;
            }
            spans.push(TextSpan {
                strikethrough: true,
                ..TextSpan::plain(strike_buf)
            });
            continue;
        }

        // *italic*
        if chars[i] == '*' {
            if !buf.is_empty() {
                spans.push(TextSpan::plain(std::mem::take(&mut buf)));
            }
            i += 1;
            let mut ital_buf = String::new();
            while i < len && chars[i] != '*' {
                ital_buf.push(chars[i]);
                i += 1;
            }
            if i < len {
                i += 1;
            }
            spans.push(TextSpan::italic(ital_buf));
            continue;
        }

        // `code`
        if chars[i] == '`' {
            if !buf.is_empty() {
                spans.push(TextSpan::plain(std::mem::take(&mut buf)));
            }
            i += 1;
            let mut code_buf = String::new();
            while i < len && chars[i] != '`' {
                code_buf.push(chars[i]);
                i += 1;
            }
            if i < len {
                i += 1;
            }
            spans.push(TextSpan::code(code_buf));
            continue;
        }

        // [text](url)
        if chars[i] == '[' {
            if !buf.is_empty() {
                spans.push(TextSpan::plain(std::mem::take(&mut buf)));
            }
            i += 1;
            let mut link_text = String::new();
            while i < len && chars[i] != ']' {
                link_text.push(chars[i]);
                i += 1;
            }
            if i < len {
                i += 1; // skip ]
            }
            if i < len && chars[i] == '(' {
                i += 1;
                let mut url = String::new();
                while i < len && chars[i] != ')' {
                    url.push(chars[i]);
                    i += 1;
                }
                if i < len {
                    i += 1;
                }
                spans.push(TextSpan::link(link_text, url));
            } else {
                // Not a real link, treat as plain text
                buf.push('[');
                buf.push_str(&link_text);
                buf.push(']');
            }
            continue;
        }

        buf.push(chars[i]);
        i += 1;
    }

    if !buf.is_empty() {
        spans.push(TextSpan::plain(buf));
    }

    spans
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_plain() {
        let spans = parse_markdown("hello world");
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].text, "hello world");
        assert!(!spans[0].bold);
    }

    #[test]
    fn parse_bold() {
        let spans = parse_markdown("a **bold** b");
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].text, "bold");
        assert!(spans[1].bold);
    }

    #[test]
    fn parse_italic() {
        let spans = parse_markdown("a *italic* b");
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].text, "italic");
        assert!(spans[1].italic);
    }

    #[test]
    fn parse_code() {
        let spans = parse_markdown("a `code` b");
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].text, "code");
        assert!(spans[1].code);
    }

    #[test]
    fn parse_link() {
        let spans = parse_markdown("click [here](https://example.com) now");
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].text, "here");
        assert_eq!(spans[1].link.as_deref(), Some("https://example.com"));
    }

    #[test]
    fn parse_strikethrough() {
        let spans = parse_markdown("a ~~removed~~ b");
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[1].text, "removed");
        assert!(spans[1].strikethrough);
    }
}