gpuikit-editor 0.1.0

A standalone editor component for GPUI
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Example demonstrating a complete text editor with syntax highlighting
//!
//! Run with: cargo run --example editor_demo

use gpui::*;
use gpui_editor::*;
use gpuikit_keymap::KeymapCollection;
use std::path::Path;

actions!(
    editor,
    [
        MoveUp,
        MoveDown,
        MoveLeft,
        MoveRight,
        MoveUpWithShift,
        MoveDownWithShift,
        MoveLeftWithShift,
        MoveRightWithShift,
        Backspace,
        Delete,
        InsertNewline,
        NextTheme,
        PreviousTheme,
        NextLanguage,
        PreviousLanguage,
        SelectAll,
        Escape,
        Copy,
        Cut,
        Paste
    ]
);

/// A complete editor view with keyboard handling and state management
struct EditorView {
    focus_handle: FocusHandle,
    editor: Editor,
    current_theme_index: usize,
    available_themes: Vec<String>,
    current_language_index: usize,
    available_languages: Vec<(String, String, String)>, // (name, extension, sample_code)
}

impl EditorView {
    fn new(cx: &mut Context<Self>) -> Self {
        let focus_handle = cx.focus_handle();

        let initial_code = vec![
            "// Rust sample code".to_string(),
            "use std::collections::HashMap;".to_string(),
            "".to_string(),
            "fn main() {".to_string(),
            "    let mut count = 0;".to_string(),
            "    ".to_string(),
            "    // Count from 1 to 10".to_string(),
            "    for i in 1..=10 {".to_string(),
            "        count += i;".to_string(),
            "    }".to_string(),
            "    ".to_string(),
            "    // HashMap example".to_string(),
            "    let mut scores = HashMap::new();".to_string(),
            "    scores.insert(\"Blue\", 10);".to_string(),
            "    scores.insert(\"Yellow\", 50);".to_string(),
            "    ".to_string(),
            "    println!(\"Final count: {}\", count);".to_string(),
            "}".to_string(),
        ];

        let mut editor = Editor::new("editor", initial_code);

        let highlighter = SyntaxHighlighter::new();
        let available_themes = highlighter.available_themes();

        let default_theme_index = available_themes
            .iter()
            .position(|t| t == "base16-ocean.dark")
            .unwrap_or(0);

        editor.set_theme(&available_themes[default_theme_index]);

        let available_languages = vec![
            ("Rust".to_string(), "rs".to_string(), get_rust_sample()),
            (
                "Plain Text".to_string(),
                "txt".to_string(),
                get_plain_text_sample(),
            ),
        ];

        editor.set_language("Rust".to_string());

        Self {
            focus_handle,
            editor,
            current_theme_index: default_theme_index,
            available_themes,
            current_language_index: 0,
            available_languages,
        }
    }

    fn get_selected_text(&self) -> String {
        self.editor.get_selected_text()
    }

    // Action handlers
    fn move_up(&mut self, _: &MoveUp, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.move_up(false);
        cx.notify();
    }

    fn move_down(&mut self, _: &MoveDown, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.move_down(false);
        cx.notify();
    }

    fn move_left(&mut self, _: &MoveLeft, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.move_left(false);
        cx.notify();
    }

    fn move_right(&mut self, _: &MoveRight, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.move_right(false);
        cx.notify();
    }

    fn move_up_with_shift(
        &mut self,
        _: &MoveUpWithShift,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.editor.move_up(true);
        cx.notify();
    }

    fn move_down_with_shift(
        &mut self,
        _: &MoveDownWithShift,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.editor.move_down(true);
        cx.notify();
    }

    fn move_left_with_shift(
        &mut self,
        _: &MoveLeftWithShift,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.editor.move_left(true);
        cx.notify();
    }

    fn move_right_with_shift(
        &mut self,
        _: &MoveRightWithShift,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.editor.move_right(true);
        cx.notify();
    }

    fn backspace(&mut self, _: &Backspace, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.backspace();
        cx.notify();
    }

    fn delete(&mut self, _: &Delete, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.delete();
        cx.notify();
    }

    fn insert_newline(&mut self, _: &InsertNewline, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.insert_newline();
        cx.notify();
    }

    fn select_all(&mut self, _: &SelectAll, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.select_all();
        cx.notify();
    }

    fn escape(&mut self, _: &Escape, _window: &mut Window, cx: &mut Context<Self>) {
        self.editor.clear_selection();
        cx.notify();
    }

    fn copy(&mut self, _: &Copy, _window: &mut Window, cx: &mut Context<Self>) {
        let selected_text = self.get_selected_text();
        if !selected_text.is_empty() {
            cx.write_to_clipboard(ClipboardItem::new_string(selected_text));
        }
    }

    fn cut(&mut self, _: &Cut, _window: &mut Window, cx: &mut Context<Self>) {
        let selected_text = self.get_selected_text();
        if !selected_text.is_empty() {
            cx.write_to_clipboard(ClipboardItem::new_string(selected_text));
            self.editor.delete_selection();
            cx.notify();
        }
    }

    fn paste(&mut self, _: &Paste, _window: &mut Window, cx: &mut Context<Self>) {
        if let Some(clipboard) = cx.read_from_clipboard() {
            if let Some(text) = clipboard.text() {
                // Delete selection if exists
                self.editor.delete_selection();

                // Insert text character by character (simplified)
                for ch in text.chars() {
                    if ch == '\n' {
                        self.editor.insert_newline();
                    } else if ch != '\r' {
                        self.editor.insert_char(ch);
                    }
                }
                cx.notify();
            }
        }
    }

    fn next_theme(&mut self, _: &NextTheme, _window: &mut Window, cx: &mut Context<Self>) {
        self.current_theme_index = (self.current_theme_index + 1) % self.available_themes.len();
        self.editor
            .set_theme(&self.available_themes[self.current_theme_index]);
        cx.notify();
    }

    fn previous_theme(&mut self, _: &PreviousTheme, _window: &mut Window, cx: &mut Context<Self>) {
        self.current_theme_index = if self.current_theme_index == 0 {
            self.available_themes.len() - 1
        } else {
            self.current_theme_index - 1
        };
        self.editor
            .set_theme(&self.available_themes[self.current_theme_index]);
        cx.notify();
    }

    fn next_language(&mut self, _: &NextLanguage, _window: &mut Window, cx: &mut Context<Self>) {
        self.current_language_index =
            (self.current_language_index + 1) % self.available_languages.len();
        let (language, _, sample_code) = &self.available_languages[self.current_language_index];
        self.editor.set_language(language.clone());
        self.editor
            .update_buffer(sample_code.lines().map(|s| s.to_string()).collect());
        cx.notify();
    }

    fn previous_language(
        &mut self,
        _: &PreviousLanguage,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.current_language_index = if self.current_language_index == 0 {
            self.available_languages.len() - 1
        } else {
            self.current_language_index - 1
        };
        let (language, _, sample_code) = &self.available_languages[self.current_language_index];
        self.editor.set_language(language.clone());
        self.editor
            .update_buffer(sample_code.lines().map(|s| s.to_string()).collect());
        cx.notify();
    }
}

impl Render for EditorView {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let _current_theme = &self.available_themes[self.current_theme_index];
        let (current_language, _, _) = &self.available_languages[self.current_language_index];

        let language = match current_language.as_str() {
            "Rust" => Language::Rust,
            _ => Language::PlainText,
        };

        let cursor_position = self.editor.cursor_position();
        let cursor_point = Point::new(cursor_position.col, cursor_position.row);

        let selection = if self.editor.has_selection() {
            let selected_text = self.get_selected_text();
            Some(Selection {
                lines: selected_text.matches('\n').count(),
                chars: selected_text.len(),
            })
        } else {
            None
        };

        div()
            .key_context("editor")
            .size_full()
            .flex()
            .flex_col()
            .child(
                div()
                    .flex_grow()
                    .track_focus(&self.focus_handle)
                    .on_action(cx.listener(Self::move_up))
                    .on_action(cx.listener(Self::move_down))
                    .on_action(cx.listener(Self::move_left))
                    .on_action(cx.listener(Self::move_right))
                    .on_action(cx.listener(Self::move_up_with_shift))
                    .on_action(cx.listener(Self::move_down_with_shift))
                    .on_action(cx.listener(Self::move_left_with_shift))
                    .on_action(cx.listener(Self::move_right_with_shift))
                    .on_action(cx.listener(Self::backspace))
                    .on_action(cx.listener(Self::delete))
                    .on_action(cx.listener(Self::insert_newline))
                    .on_action(cx.listener(Self::select_all))
                    .on_action(cx.listener(Self::escape))
                    .on_action(cx.listener(Self::copy))
                    .on_action(cx.listener(Self::cut))
                    .on_action(cx.listener(Self::paste))
                    .on_action(cx.listener(Self::next_theme))
                    .on_action(cx.listener(Self::previous_theme))
                    .on_action(cx.listener(Self::next_language))
                    .on_action(cx.listener(Self::previous_language))
                    .on_key_down(cx.listener(
                        |this: &mut Self, event: &KeyDownEvent, _window, cx| {
                            // Handle character input
                            if let Some(text) = &event.keystroke.key_char {
                                if !event.keystroke.modifiers.platform
                                    && !event.keystroke.modifiers.control
                                    && !event.keystroke.modifiers.function
                                {
                                    for ch in text.chars() {
                                        this.editor.insert_char(ch);
                                    }
                                    cx.notify();
                                }
                            }
                        },
                    ))
                    .child(EditorElement::new(self.editor.clone())),
            )
            .child(MetaLine::new(cursor_point, language, selection))
    }
}

fn load_keymaps(cx: &mut App) {
    // Load keymaps from JSON configuration
    let mut keymap_collection = KeymapCollection::new();

    let keymap_path = Path::new("examples/demo-keymap.json");
    let loaded_from_file = if keymap_path.exists() {
        match keymap_collection.load_file(keymap_path) {
            Ok(_) => {
                println!("Loaded keymaps from file: {}", keymap_path.display());
                true
            }
            Err(e) => {
                eprintln!("Failed to load keymap file: {}", e);
                false
            }
        }
    } else {
        false
    };

    if !loaded_from_file {
        let demo_keymap = include_str!("demo-keymap.json");
        keymap_collection
            .load_json(demo_keymap)
            .expect("Failed to load embedded demo keymaps");
        println!("Loaded embedded demo keymaps");
    }

    let specs = keymap_collection.get_binding_specs();

    let mut bindings = Vec::new();

    for spec in specs {
        if !spec.action_name.starts_with("editor::") {
            continue;
        }

        let action_name = spec
            .action_name
            .strip_prefix("editor::")
            .unwrap_or(&spec.action_name);
        let context = spec.context.as_deref();

        match action_name {
            "MoveUp" => bindings.push(KeyBinding::new(&spec.keystrokes, MoveUp, context)),
            "MoveDown" => bindings.push(KeyBinding::new(&spec.keystrokes, MoveDown, context)),
            "MoveLeft" => bindings.push(KeyBinding::new(&spec.keystrokes, MoveLeft, context)),
            "MoveRight" => bindings.push(KeyBinding::new(&spec.keystrokes, MoveRight, context)),
            "MoveUpWithShift" => {
                bindings.push(KeyBinding::new(&spec.keystrokes, MoveUpWithShift, context))
            }
            "MoveDownWithShift" => bindings.push(KeyBinding::new(
                &spec.keystrokes,
                MoveDownWithShift,
                context,
            )),
            "MoveLeftWithShift" => bindings.push(KeyBinding::new(
                &spec.keystrokes,
                MoveLeftWithShift,
                context,
            )),
            "MoveRightWithShift" => bindings.push(KeyBinding::new(
                &spec.keystrokes,
                MoveRightWithShift,
                context,
            )),
            "Backspace" => bindings.push(KeyBinding::new(&spec.keystrokes, Backspace, context)),
            "Delete" => bindings.push(KeyBinding::new(&spec.keystrokes, Delete, context)),
            "InsertNewline" => {
                bindings.push(KeyBinding::new(&spec.keystrokes, InsertNewline, context))
            }
            "SelectAll" => bindings.push(KeyBinding::new(&spec.keystrokes, SelectAll, context)),
            "Escape" => bindings.push(KeyBinding::new(&spec.keystrokes, Escape, context)),
            "Copy" => bindings.push(KeyBinding::new(&spec.keystrokes, Copy, context)),
            "Cut" => bindings.push(KeyBinding::new(&spec.keystrokes, Cut, context)),
            "Paste" => bindings.push(KeyBinding::new(&spec.keystrokes, Paste, context)),
            "NextTheme" => bindings.push(KeyBinding::new(&spec.keystrokes, NextTheme, context)),
            "PreviousTheme" => {
                bindings.push(KeyBinding::new(&spec.keystrokes, PreviousTheme, context))
            }
            "NextLanguage" => {
                bindings.push(KeyBinding::new(&spec.keystrokes, NextLanguage, context))
            }
            "PreviousLanguage" => {
                bindings.push(KeyBinding::new(&spec.keystrokes, PreviousLanguage, context))
            }
            unknown => {
                eprintln!("Unknown editor action: {}", unknown);
            }
        }
    }

    println!(
        "Registered {} keybindings from configuration",
        bindings.len()
    );
    cx.bind_keys(bindings);
}

fn main() {
    Application::new().run(move |cx: &mut App| {
        load_keymaps(cx);

        cx.open_window(
            WindowOptions {
                window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
                    None,
                    size(px(800.0), px(600.0)),
                    cx,
                ))),
                focus: true,
                ..Default::default()
            },
            |_window, cx| cx.new(EditorView::new),
        )
        .unwrap();

        cx.activate(true)
    });
}

fn get_rust_sample() -> String {
    r#"// Rust sample code
use std::collections::HashMap;

fn main() {
    let mut count = 0;

    // Count from 1 to 10
    for i in 1..=10 {
        count += i;
    }

    // HashMap example
    let mut scores = HashMap::new();
    scores.insert("Blue", 10);
    scores.insert("Yellow", 50);

    println!("Final count: {}", count);
}"#
    .to_string()
}

fn get_plain_text_sample() -> String {
    r#"This is a plain text document.

No syntax highlighting is applied to plain text files.
You can write anything here without worrying about code formatting.

Features of this editor:
- Syntax highlighting for multiple languages
- Theme switching with Cmd+[ and Cmd+]
- Language switching with Cmd+Shift+[ and Cmd+Shift+]
- Text selection with Shift+Arrow keys
- Copy, Cut, and Paste support
- Line numbers
- Active line highlighting

The editor uses the syntect library for syntax highlighting,
which provides TextMate-compatible syntax definitions and themes.

Try switching between different languages and themes to see
how the editor adapts to different file types!"#
        .to_string()
}