windjammer-ui 0.3.6

Cross-platform UI framework for Windjammer (Web, Desktop, Mobile)
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
// Undo/Redo System Module
// Provides command pattern-based undo/redo functionality for editor operations
//
// IMPORTANT: This system is designed to be usable both from the editor UI
// and programmatically from code. Developers can create and execute commands
// directly without needing the editor.

use std::collections::VecDeque;

// ============================================================================
// COMMAND TRAIT (Core abstraction - can be implemented for any operation)
// ============================================================================

/// Command trait that all undoable operations must implement.
///
/// This allows developers to create custom commands programmatically:
///
/// ```rust,ignore
/// use windjammer_ui::undo_redo::Command;
///
/// struct MyCustomCommand { /* ... */ }
///
/// impl Command for MyCustomCommand {
///     fn execute(&mut self) -> Result<(), String> {
///         // Perform the operation
///         Ok(())
///     }
///     
///     fn undo(&mut self) -> Result<(), String> {
///         // Reverse the operation
///         Ok(())
///     }
///     
///     fn description(&self) -> String {
///         "My Custom Operation".to_string()
///     }
/// }
/// ```
pub trait Command: std::any::Any + Send + Sync {
    /// Execute the command (do the operation)
    fn execute(&mut self) -> Result<(), String>;

    /// Undo the command (reverse the operation)
    fn undo(&mut self) -> Result<(), String>;

    /// Get a human-readable description of the command
    fn description(&self) -> String;

    /// Optional: Merge with another command of the same type
    /// Useful for combining multiple similar operations (e.g., continuous dragging)
    fn try_merge(&mut self, _other: &dyn Command) -> bool {
        false
    }
}

// ============================================================================
// BUILT-IN COMMANDS (Common operations - developers can use these directly)
// ============================================================================

/// Transform modification command (position, rotation, scale)
///
/// Can be used programmatically:
/// ```rust,ignore
/// use windjammer_ui::undo_redo::TransformCommand;
///
/// # fn example() -> Result<(), String> {
/// let object_id = "Player".to_string();
/// let old_transform = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
/// let new_transform = [1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
///
/// let mut cmd = TransformCommand::new(
///     object_id,
///     old_transform,
///     new_transform,
/// );
/// cmd.execute()?;
/// // Later...
/// cmd.undo()?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct TransformCommand {
    pub object_id: String,
    pub old_transform: [f32; 9], // [pos_x, pos_y, pos_z, rot_x, rot_y, rot_z, scale_x, scale_y, scale_z]
    pub new_transform: [f32; 9],
}

impl TransformCommand {
    pub fn new(object_id: String, old_transform: [f32; 9], new_transform: [f32; 9]) -> Self {
        Self {
            object_id,
            old_transform,
            new_transform,
        }
    }
}

impl Command for TransformCommand {
    fn execute(&mut self) -> Result<(), String> {
        // In a real implementation, this would update the scene
        // For now, we just track the state change
        Ok(())
    }

    fn undo(&mut self) -> Result<(), String> {
        // Restore the old transform
        Ok(())
    }

    fn description(&self) -> String {
        format!("Transform {}", self.object_id)
    }

    fn try_merge(&mut self, other: &dyn Command) -> bool {
        // Try to merge consecutive transform operations on the same object
        if let Some(other_transform) =
            (other as &dyn std::any::Any).downcast_ref::<TransformCommand>()
        {
            if self.object_id == other_transform.object_id {
                // Keep the old_transform from self, but update new_transform from other
                self.new_transform = other_transform.new_transform;
                return true;
            }
        }
        false
    }
}

/// File content modification command
///
/// Programmatic usage:
/// ```rust,ignore
/// use windjammer_ui::undo_redo::FileEditCommand;
///
/// # fn example() -> Result<(), String> {
/// let old_content = "fn main() {}".to_string();
/// let new_content = "fn main() { println!(\"Hello\"); }".to_string();
///
/// let mut cmd = FileEditCommand::new(
///     "main.wj".to_string(),
///     old_content,
///     new_content,
/// );
/// cmd.execute()?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct FileEditCommand {
    pub file_path: String,
    pub old_content: String,
    pub new_content: String,
}

impl FileEditCommand {
    pub fn new(file_path: String, old_content: String, new_content: String) -> Self {
        Self {
            file_path,
            old_content,
            new_content,
        }
    }
}

impl Command for FileEditCommand {
    fn execute(&mut self) -> Result<(), String> {
        // In a real implementation, this would update the file
        Ok(())
    }

    fn undo(&mut self) -> Result<(), String> {
        // Restore the old content
        Ok(())
    }

    fn description(&self) -> String {
        format!("Edit {}", self.file_path)
    }
}

/// Object creation command
///
/// Programmatic usage:
/// ```rust,ignore
/// use windjammer_ui::undo_redo::CreateObjectCommand;
///
/// # fn example() -> Result<(), String> {
/// let object_data = r#"{"type": "Player", "health": 100}"#.to_string();
///
/// let mut cmd = CreateObjectCommand::new(
///     "Player".to_string(),
///     object_data,
/// );
/// cmd.execute()?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct CreateObjectCommand {
    pub object_id: String,
    pub object_data: String, // Serialized object data
}

impl CreateObjectCommand {
    pub fn new(object_id: String, object_data: String) -> Self {
        Self {
            object_id,
            object_data,
        }
    }
}

impl Command for CreateObjectCommand {
    fn execute(&mut self) -> Result<(), String> {
        // Create the object in the scene
        Ok(())
    }

    fn undo(&mut self) -> Result<(), String> {
        // Remove the object from the scene
        Ok(())
    }

    fn description(&self) -> String {
        format!("Create {}", self.object_id)
    }
}

/// Object deletion command
///
/// Programmatic usage:
/// ```rust,ignore
/// use windjammer_ui::undo_redo::DeleteObjectCommand;
///
/// # fn example() -> Result<(), String> {
/// let object_data = r#"{"type": "Enemy", "health": 50}"#.to_string();
///
/// let mut cmd = DeleteObjectCommand::new(
///     "Enemy".to_string(),
///     object_data, // Save for undo
/// );
/// cmd.execute()?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct DeleteObjectCommand {
    pub object_id: String,
    pub object_data: String, // Saved for undo
}

impl DeleteObjectCommand {
    pub fn new(object_id: String, object_data: String) -> Self {
        Self {
            object_id,
            object_data,
        }
    }
}

impl Command for DeleteObjectCommand {
    fn execute(&mut self) -> Result<(), String> {
        // Remove the object from the scene
        Ok(())
    }

    fn undo(&mut self) -> Result<(), String> {
        // Restore the object to the scene
        Ok(())
    }

    fn description(&self) -> String {
        format!("Delete {}", self.object_id)
    }
}

/// Property modification command
///
/// Programmatic usage:
/// ```rust,ignore
/// use windjammer_ui::undo_redo::PropertyChangeCommand;
///
/// # fn example() -> Result<(), String> {
/// let mut cmd = PropertyChangeCommand::new(
///     "Player".to_string(),
///     "health".to_string(),
///     "100".to_string(),
///     "150".to_string(),
/// );
/// cmd.execute()?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct PropertyChangeCommand {
    pub object_id: String,
    pub property_name: String,
    pub old_value: String,
    pub new_value: String,
}

impl PropertyChangeCommand {
    pub fn new(
        object_id: String,
        property_name: String,
        old_value: String,
        new_value: String,
    ) -> Self {
        Self {
            object_id,
            property_name,
            old_value,
            new_value,
        }
    }
}

impl Command for PropertyChangeCommand {
    fn execute(&mut self) -> Result<(), String> {
        // Set the property to new_value
        Ok(())
    }

    fn undo(&mut self) -> Result<(), String> {
        // Restore the property to old_value
        Ok(())
    }

    fn description(&self) -> String {
        format!("Change {}.{}", self.object_id, self.property_name)
    }
}

// ============================================================================
// UNDO/REDO MANAGER (Can be used standalone or with editor)
// ============================================================================

/// Undo/Redo manager that maintains command history.
///
/// Can be used programmatically without the editor:
///
/// ```rust,ignore
/// use windjammer_ui::undo_redo::{UndoRedoManager, TransformCommand};
///
/// # fn example() -> Result<(), String> {
/// let mut manager = UndoRedoManager::new();
///
/// // Execute commands
/// let cmd = TransformCommand::new(
///     "Player".to_string(),
///     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
///     [1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
/// );
/// manager.execute(Box::new(cmd))?;
///
/// // Undo/Redo
/// manager.undo()?;
/// manager.redo()?;
///
/// // Query state
/// if manager.can_undo() {
///     println!("Can undo: {}", manager.get_undo_description());
/// }
/// # Ok(())
/// # }
/// ```
pub struct UndoRedoManager {
    undo_stack: VecDeque<Box<dyn Command>>,
    redo_stack: VecDeque<Box<dyn Command>>,
    max_history: usize,
    merge_time_window_ms: u128, // Time window for merging commands
    last_command_time: Option<std::time::Instant>,
}

impl UndoRedoManager {
    /// Create a new undo/redo manager
    pub fn new() -> Self {
        Self {
            undo_stack: VecDeque::new(),
            redo_stack: VecDeque::new(),
            max_history: 100,
            merge_time_window_ms: 500, // 500ms window for merging
            last_command_time: None,
        }
    }

    /// Create a manager with custom history size
    pub fn with_max_history(max_history: usize) -> Self {
        Self {
            max_history,
            ..Self::new()
        }
    }

    /// Execute a command and add it to the undo stack
    ///
    /// This is the main entry point for all operations.
    /// Returns an error if the command execution fails.
    pub fn execute(&mut self, mut command: Box<dyn Command>) -> Result<(), String> {
        // Execute the command
        command.execute()?;

        // Try to merge with the last command if within time window
        let now = std::time::Instant::now();
        let should_merge = if let Some(last_time) = self.last_command_time {
            now.duration_since(last_time).as_millis() < self.merge_time_window_ms
        } else {
            false
        };

        if should_merge {
            if let Some(last_cmd) = self.undo_stack.back_mut() {
                if last_cmd.try_merge(&*command) {
                    // Successfully merged, don't add new command
                    self.last_command_time = Some(now);
                    return Ok(());
                }
            }
        }

        // Add to undo stack
        self.undo_stack.push_back(command);
        self.last_command_time = Some(now);

        // Clear redo stack (new action invalidates redo history)
        self.redo_stack.clear();

        // Limit history size
        while self.undo_stack.len() > self.max_history {
            self.undo_stack.pop_front();
        }

        Ok(())
    }

    /// Undo the last command
    pub fn undo(&mut self) -> Result<(), String> {
        if let Some(mut command) = self.undo_stack.pop_back() {
            command.undo()?;
            self.redo_stack.push_back(command);
            self.last_command_time = None; // Reset merge window
            Ok(())
        } else {
            Err("Nothing to undo".to_string())
        }
    }

    /// Redo the last undone command
    pub fn redo(&mut self) -> Result<(), String> {
        if let Some(mut command) = self.redo_stack.pop_back() {
            command.execute()?;
            self.undo_stack.push_back(command);
            self.last_command_time = None; // Reset merge window
            Ok(())
        } else {
            Err("Nothing to redo".to_string())
        }
    }

    /// Check if undo is available
    pub fn can_undo(&self) -> bool {
        !self.undo_stack.is_empty()
    }

    /// Check if redo is available
    pub fn can_redo(&self) -> bool {
        !self.redo_stack.is_empty()
    }

    /// Get description of the command that would be undone
    pub fn get_undo_description(&self) -> Option<String> {
        self.undo_stack.back().map(|cmd| cmd.description())
    }

    /// Get description of the command that would be redone
    pub fn get_redo_description(&self) -> Option<String> {
        self.redo_stack.back().map(|cmd| cmd.description())
    }

    /// Get the number of commands in the undo stack
    pub fn undo_count(&self) -> usize {
        self.undo_stack.len()
    }

    /// Get the number of commands in the redo stack
    pub fn redo_count(&self) -> usize {
        self.redo_stack.len()
    }

    /// Clear all history
    pub fn clear(&mut self) {
        self.undo_stack.clear();
        self.redo_stack.clear();
        self.last_command_time = None;
    }

    /// Get a list of all undo descriptions (for UI display)
    pub fn get_undo_history(&self) -> Vec<String> {
        self.undo_stack
            .iter()
            .map(|cmd| cmd.description())
            .collect()
    }

    /// Get a list of all redo descriptions (for UI display)
    pub fn get_redo_history(&self) -> Vec<String> {
        self.redo_stack
            .iter()
            .map(|cmd| cmd.description())
            .collect()
    }

    /// Set the maximum history size
    pub fn set_max_history(&mut self, max: usize) {
        self.max_history = max;
        while self.undo_stack.len() > self.max_history {
            self.undo_stack.pop_front();
        }
    }

    /// Set the merge time window (in milliseconds)
    pub fn set_merge_time_window(&mut self, ms: u128) {
        self.merge_time_window_ms = ms;
    }
}

impl Default for UndoRedoManager {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// COMMAND BUILDER (Convenience for creating commands programmatically)
// ============================================================================

/// Builder for creating commands programmatically
///
/// Example usage:
/// ```rust,ignore
/// use windjammer_ui::undo_redo::{CommandBuilder, UndoRedoManager};
///
/// # fn example() -> Result<(), String> {
/// # let mut manager = UndoRedoManager::new();
/// let cmd = CommandBuilder::transform("Player")
///     .old_position(0.0, 0.0, 0.0)
///     .new_position(1.0, 2.0, 3.0)
///     .build();
///
/// manager.execute(cmd)?;
/// # Ok(())
/// # }
/// ```
pub struct CommandBuilder;

impl CommandBuilder {
    /// Start building a transform command
    pub fn transform(object_id: &str) -> TransformCommandBuilder {
        TransformCommandBuilder {
            object_id: object_id.to_string(),
            old_transform: [0.0; 9],
            new_transform: [0.0; 9],
        }
    }

    /// Start building a file edit command
    pub fn file_edit(file_path: &str) -> FileEditCommandBuilder {
        FileEditCommandBuilder {
            file_path: file_path.to_string(),
            old_content: String::new(),
            new_content: String::new(),
        }
    }

    /// Create an object creation command
    pub fn create_object(object_id: &str, object_data: String) -> Box<dyn Command> {
        Box::new(CreateObjectCommand::new(object_id.to_string(), object_data))
    }

    /// Create an object deletion command
    pub fn delete_object(object_id: &str, object_data: String) -> Box<dyn Command> {
        Box::new(DeleteObjectCommand::new(object_id.to_string(), object_data))
    }

    /// Create a property change command
    pub fn property_change(
        object_id: &str,
        property_name: &str,
        old_value: String,
        new_value: String,
    ) -> Box<dyn Command> {
        Box::new(PropertyChangeCommand::new(
            object_id.to_string(),
            property_name.to_string(),
            old_value,
            new_value,
        ))
    }
}

pub struct TransformCommandBuilder {
    object_id: String,
    old_transform: [f32; 9],
    new_transform: [f32; 9],
}

impl TransformCommandBuilder {
    pub fn old_position(mut self, x: f32, y: f32, z: f32) -> Self {
        self.old_transform[0] = x;
        self.old_transform[1] = y;
        self.old_transform[2] = z;
        self
    }

    pub fn new_position(mut self, x: f32, y: f32, z: f32) -> Self {
        self.new_transform[0] = x;
        self.new_transform[1] = y;
        self.new_transform[2] = z;
        self
    }

    pub fn old_rotation(mut self, x: f32, y: f32, z: f32) -> Self {
        self.old_transform[3] = x;
        self.old_transform[4] = y;
        self.old_transform[5] = z;
        self
    }

    pub fn new_rotation(mut self, x: f32, y: f32, z: f32) -> Self {
        self.new_transform[3] = x;
        self.new_transform[4] = y;
        self.new_transform[5] = z;
        self
    }

    pub fn old_scale(mut self, x: f32, y: f32, z: f32) -> Self {
        self.old_transform[6] = x;
        self.old_transform[7] = y;
        self.old_transform[8] = z;
        self
    }

    pub fn new_scale(mut self, x: f32, y: f32, z: f32) -> Self {
        self.new_transform[6] = x;
        self.new_transform[7] = y;
        self.new_transform[8] = z;
        self
    }

    pub fn build(self) -> Box<dyn Command> {
        Box::new(TransformCommand::new(
            self.object_id,
            self.old_transform,
            self.new_transform,
        ))
    }
}

pub struct FileEditCommandBuilder {
    file_path: String,
    old_content: String,
    new_content: String,
}

impl FileEditCommandBuilder {
    pub fn old_content(mut self, content: String) -> Self {
        self.old_content = content;
        self
    }

    pub fn new_content(mut self, content: String) -> Self {
        self.new_content = content;
        self
    }

    pub fn build(self) -> Box<dyn Command> {
        Box::new(FileEditCommand::new(
            self.file_path,
            self.old_content,
            self.new_content,
        ))
    }
}

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

    #[test]
    fn test_undo_redo_basic() {
        let mut manager = UndoRedoManager::new();

        let cmd = Box::new(TransformCommand::new(
            "test".to_string(),
            [0.0; 9],
            [1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
        ));

        manager.execute(cmd).unwrap();
        assert!(manager.can_undo());
        assert!(!manager.can_redo());

        manager.undo().unwrap();
        assert!(!manager.can_undo());
        assert!(manager.can_redo());

        manager.redo().unwrap();
        assert!(manager.can_undo());
        assert!(!manager.can_redo());
    }

    #[test]
    fn test_command_builder() {
        let cmd = CommandBuilder::transform("Player")
            .old_position(0.0, 0.0, 0.0)
            .new_position(1.0, 2.0, 3.0)
            .build();

        assert_eq!(cmd.description(), "Transform Player");
    }

    #[test]
    fn test_history_limit() {
        let mut manager = UndoRedoManager::with_max_history(3);

        for i in 0..5 {
            let cmd = Box::new(TransformCommand::new(
                format!("obj{}", i),
                [0.0; 9],
                [1.0; 9],
            ));
            manager.execute(cmd).unwrap();
        }

        assert_eq!(manager.undo_count(), 3);
    }
}