enya-plugin 0.1.0

Plugin system for Enya editor
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
# enya-plugin

A host-agnostic plugin system for extending application functionality, inspired by neovim's plugin architecture.

## Overview

This crate provides the core infrastructure for a plugin system that can be embedded in any Rust application. It's designed to be completely decoupled from any specific host implementation through the `PluginHost` trait.

### Key Features

- **Host-agnostic**: Works with any application that implements `PluginHost`
- **Lua scripting**: Write plugins in Lua with conditional logic, validation, and HTTP requests
- **Native plugins**: Implement the `Plugin` trait in Rust for maximum performance
- **Capability-based**: Plugins declare what features they provide
- **Hook system**: Intercept and extend host behavior
- **Custom themes**: Plugins can define complete color schemes
- **Lifecycle management**: Full control over plugin initialization, activation, and cleanup

## Architecture

```
┌──────────────────────────────────────────────────────┐
│                 Host Application                      │
│            (implements PluginHost trait)             │
└──────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────┐
│                   PluginContext                       │
│           (provides host services to plugins)        │
└──────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────┐
│                   PluginRegistry                      │
│             (manages plugin lifecycle)               │
└──────────────────────────────────────────────────────┘
               ┌─────────┴─────────┐
               ▼                   ▼
         ┌──────────┐        ┌──────────┐
         │   Lua    │        │  Native  │
         │ (.lua)   │        │  (Rust)  │
         └──────────┘        └──────────┘
```

## Quick Start

### 1. Implement `PluginHost` for your application

```rust
use enya_plugin::{
    PluginHost, PluginContext, PluginRegistry,
    NotificationLevel, LogLevel, Theme, BoxFuture,
    HttpResponse, HttpError,
};
use rustc_hash::FxHashMap;
use std::sync::Arc;

struct MyApp {
    // ... your application state
}

impl PluginHost for MyApp {
    fn notify(&self, level: NotificationLevel, message: &str) {
        println!("[{:?}] {}", level, message);
    }

    fn request_repaint(&self) {
        // Trigger UI refresh
    }

    fn log(&self, level: LogLevel, message: &str) {
        println!("[{:?}] {}", level, message);
    }

    fn version(&self) -> &'static str {
        "1.0.0"
    }

    fn is_wasm(&self) -> bool {
        false
    }

    fn theme(&self) -> Theme {
        Theme::Dark
    }

    fn theme_name(&self) -> &'static str {
        "dark"
    }

    fn clipboard_write(&self, text: &str) -> bool {
        // Write to system clipboard
        true
    }

    fn clipboard_read(&self) -> Option<String> {
        // Read from system clipboard
        None
    }

    fn spawn(&self, future: BoxFuture<()>) {
        // Spawn async task
        tokio::spawn(future);
    }

    fn http_get(
        &self,
        url: &str,
        headers: &FxHashMap<String, String>,
    ) -> Result<HttpResponse, HttpError> {
        // Perform HTTP GET
        Err(HttpError { message: "Not implemented".to_string() })
    }

    fn http_post(
        &self,
        url: &str,
        body: &str,
        headers: &FxHashMap<String, String>,
    ) -> Result<HttpResponse, HttpError> {
        // Perform HTTP POST
        Err(HttpError { message: "Not implemented".to_string() })
    }
}
```

### 2. Set up the plugin registry

```rust
use enya_plugin::{PluginContext, PluginRegistry};

fn setup_plugins(app: Arc<MyApp>) {
    // Create context from host
    let ctx = PluginContext::new(app);

    // Create and initialize registry
    let mut registry = PluginRegistry::new();
    registry.init(ctx);

    // Load Lua plugins from filesystem (native only)
    #[cfg(not(target_arch = "wasm32"))]
    {
        use enya_plugin::PluginLoader;

        let loader = PluginLoader::new();

        for result in loader.load_all_lua() {
            match result {
                Ok(plugin) => {
                    let id = registry.register(plugin, true).unwrap();
                    registry.init_plugin(id).unwrap();
                    registry.activate_plugin(id).unwrap();
                }
                Err(e) => eprintln!("Failed to load Lua plugin: {}", e),
            }
        }
    }
}
```

### 3. Execute plugin commands

```rust
// Execute a command provided by any active plugin
if registry.execute_command("my-command", "arg1 arg2") {
    println!("Command handled by plugin");
}

// Get all commands from active plugins
for (plugin_info, command) in registry.all_commands() {
    println!("{}: {} - {}", plugin_info.name, command.name, command.description);
}
```

## Lua Plugins

Lua plugins provide a dynamic scripting environment with full access to conditional logic, input validation, and HTTP requests.

### Basic Example

```lua
plugin = {
    name = "my-plugin",
    version = "0.1.0",
    description = "A Lua plugin example"
}

enya.register_command("greet", {
    description = "Greet with validation",
    accepts_args = true
}, function(args)
    if args == "" then
        enya.notify("info", "Hello, World!")
    elseif tonumber(args) then
        enya.notify("warn", "That's a number: " .. args)
    else
        enya.notify("info", "Hello, " .. args .. "!")
    end
    return true
end)

enya.keymap("Space+g", "greet", "Greet user")

-- Lifecycle hooks
function on_activate()
    enya.log("info", "Plugin activated!")
end

function on_deactivate()
    enya.log("info", "Plugin deactivated!")
end
```

### Lua API

**Registration (during load)**:
- `enya.register_command(name, config, callback)` - Register a command
- `enya.keymap(keys, command, description, [modes])` - Register a keybinding

**Runtime (in callbacks)**:
- `enya.notify(level, message)` - Show notification ("info", "warn", "error")
- `enya.log(level, message)` - Log a message
- `enya.request_repaint()` - Request UI refresh
- `enya.editor_version()` - Get host version
- `enya.is_wasm()` - Check if running in WASM
- `enya.theme_name()` - Get current theme name
- `enya.clipboard_write(text)` - Write to clipboard
- `enya.clipboard_read()` - Read from clipboard
- `enya.execute(command, [args])` - Execute another command
- `enya.http_get(url, [headers])` - HTTP GET request
- `enya.http_post(url, body, [headers])` - HTTP POST request

**Pane Management**:
- `enya.add_query_pane(query, [title])` - Add a query pane with PromQL query
- `enya.add_logs_pane()` - Add a logs pane with current time range
- `enya.add_tracing_pane([trace_id])` - Add a tracing pane
- `enya.add_terminal_pane()` - Add a terminal pane (native only)
- `enya.add_sql_pane()` - Add a SQL pane
- `enya.close_pane()` - Close the focused pane
- `enya.focus_pane(direction)` - Focus pane in direction ("left", "right", "up", "down")

**Time Range**:
- `enya.set_time_range(preset)` - Set time range preset ("5m", "1h", "24h", etc.)
- `enya.set_time_range_absolute(start, end)` - Set absolute time range (seconds)
- `enya.get_time_range()` - Get current time range as `{start, end}` (seconds)

### Custom Themes in Lua

```lua
plugin = { name = "tokyo-night-theme" }

theme = {
    name = "tokyo-night",
    display_name = "Tokyo Night",
    base = "dark",  -- inherit missing colors from dark theme
    colors = {
        bg_base = "#1a1b26",
        bg_surface = "#24283b",
        bg_elevated = "#414868",
        text_primary = "#c0caf5",
        text_secondary = "#a9b1d6",
        accent_primary = "#7aa2f7",
        accent_hover = "#89b4fa",
        success = "#9ece6a",
        warning = "#e0af68",
        error = "#f7768e",
        info = "#7dcfff",
        chart = {
            "#7aa2f7", "#9ece6a", "#e0af68", "#f7768e",
            "#bb9af7", "#7dcfff", "#73daca", "#ff9e64"
        }
    }
}
```

## Native Plugins (Rust)

For maximum performance or deep integration, implement the `Plugin` trait:

```rust
use enya_plugin::{
    Plugin, PluginCapabilities, PluginContext, PluginResult,
    CommandConfig, KeybindingConfig,
};
use std::any::Any;

pub struct MyPlugin {
    active: bool,
}

impl Plugin for MyPlugin {
    fn name(&self) -> &'static str { "my-native-plugin" }
    fn version(&self) -> &'static str { "1.0.0" }
    fn description(&self) -> &'static str { "A native Rust plugin" }

    fn capabilities(&self) -> PluginCapabilities {
        PluginCapabilities::COMMANDS | PluginCapabilities::KEYBOARD
    }

    fn init(&mut self, _ctx: &PluginContext) -> PluginResult<()> {
        Ok(())
    }

    fn activate(&mut self, _ctx: &PluginContext) -> PluginResult<()> {
        self.active = true;
        Ok(())
    }

    fn deactivate(&mut self, _ctx: &PluginContext) -> PluginResult<()> {
        self.active = false;
        Ok(())
    }

    fn commands(&self) -> Vec<CommandConfig> {
        vec![CommandConfig {
            name: "my-cmd".to_string(),
            aliases: vec!["mc".to_string()],
            description: "Do something".to_string(),
            accepts_args: false,
        }]
    }

    fn keybindings(&self) -> Vec<KeybindingConfig> {
        vec![KeybindingConfig {
            keys: "Space+m+c".to_string(),
            command: "my-cmd".to_string(),
            description: "Run my command".to_string(),
            modes: vec![],
        }]
    }

    fn execute_command(&mut self, command: &str, args: &str, ctx: &PluginContext) -> bool {
        if command == "my-cmd" || command == "mc" {
            ctx.notify("info", "Command executed!");
            return true;
        }
        false
    }

    fn as_any(&self) -> &dyn Any { self }
    fn as_any_mut(&mut self) -> &mut dyn Any { self }
}
```

### Custom Themes in Rust

```rust
use enya_plugin::{ThemeDefinition, ThemeBase};

fn themes(&self) -> Vec<ThemeDefinition> {
    vec![
        ThemeDefinition::new("my-theme", "My Theme", ThemeBase::Dark)
            .with_backgrounds(Some(0x1a1b26), Some(0x24283b), Some(0x414868))
            .with_text(Some(0xc0caf5), Some(0xa9b1d6), Some(0x565f89))
            .with_accents(Some(0x7aa2f7), Some(0x89b4fa), Some(0x3d59a1))
            .with_semantic(Some(0x9ece6a), Some(0xe0af68), Some(0xf7768e), Some(0x7dcfff))
            .with_chart_palette(vec![0x7aa2f7, 0x9ece6a, 0xe0af68, 0xf7768e])
    ]
}
```

## Plugin Capabilities

Plugins declare their capabilities using bitflags:

| Capability | Description |
|------------|-------------|
| `COMMANDS` | Provides command palette commands |
| `PANES` | Provides custom pane types |
| `KEYBOARD` | Provides custom keybindings |
| `THEMING` | Reacts to theme changes |
| `CUSTOM_THEMES` | Defines custom color themes |
| `VISUALIZATIONS` | Provides custom chart types |
| `DATA_SOURCES` | Provides backend integrations |
| `AGENT_COMMANDS` | Provides AI integration commands |
| `STATUS_LINE` | Provides status line segments |
| `FINDER_SOURCES` | Provides unified finder sources |

## Hook System

Plugins can intercept and extend host behavior through hooks:

### Lifecycle Hooks

```rust
impl LifecycleHook for MyHook {
    fn on_workspace_loaded(&mut self) { }
    fn on_workspace_saving(&mut self) { }
    fn on_pane_added(&mut self, pane_id: usize) { }
    fn on_pane_removing(&mut self, pane_id: usize) { }
    fn on_pane_focused(&mut self, pane_id: usize) { }
    fn on_closing(&mut self) { }
    fn on_frame(&mut self) { } // Use sparingly!
}
```

### Command Hooks

```rust
impl CommandHook for MyHook {
    fn before_command(&mut self, command: &str, args: &str) -> CommandHookResult {
        // Return Handled to prevent default handler
        CommandHookResult::Continue
    }

    fn after_command(&mut self, command: &str, args: &str, success: bool) { }
}
```

### Keyboard Hooks

```rust
impl KeyboardHook for MyHook {
    fn on_key_pressed(&mut self, key: &KeyEvent) -> KeyboardHookResult {
        KeyboardHookResult::Continue
    }

    fn on_key_combo(&mut self, combo: &KeyCombo) -> KeyboardHookResult {
        KeyboardHookResult::Continue
    }
}
```

### Theme Hooks

```rust
impl ThemeHook for MyHook {
    fn before_theme_change(&mut self, old: Theme, new: Theme) { }
    fn after_theme_change(&mut self, theme: Theme) { }
    fn customize_theme(&self, theme: Theme) -> Option<ThemeCustomization> { None }
}
```

### Pane Hooks

```rust
impl PaneHook for MyHook {
    fn on_pane_created(&mut self, pane_id: usize, pane_type: &str) { }
    fn on_query_changed(&mut self, pane_id: usize, query: &str) { }
    fn on_data_received(&mut self, pane_id: usize) { }
    fn on_pane_error(&mut self, pane_id: usize, error: &str) { }
}
```

## Plugin Lifecycle

```
Registration ──► Initialization ──► Activation ──► Runtime ──► Deactivation
     │                │                  │            │              │
     │                │                  │            │              │
     ▼                ▼                  ▼            ▼              ▼
 Registered       Inactive           Active       Hooks         Inactive
   state           state             state       dispatch         state
```

1. **Registration**: Plugin added to registry (`PluginState::Registered`)
2. **Initialization**: `init()` called, metadata collected (`PluginState::Inactive`)
3. **Activation**: `activate()` called (`PluginState::Active`)
4. **Runtime**: Commands executed, hooks dispatched
5. **Deactivation**: `deactivate()` called (`PluginState::Inactive`)

## Platform Support

| Feature | Native | WASM |
|---------|--------|------|
| Lua plugins |||
| Native plugins |||
| Custom themes |||
| HTTP requests || Host-dependent |
| Clipboard || Host-dependent |
| Shell commands |||

## Module Structure

```
src/
├── lib.rs          # Crate entry, re-exports
├── types.rs        # Core types (PluginHost, PluginContext, etc.)
├── traits.rs       # Plugin trait, capabilities, configs
├── registry.rs     # PluginRegistry, lifecycle management
├── hooks.rs        # Hook traits (Lifecycle, Command, Keyboard, etc.)
├── theme.rs        # ThemeDefinition, ThemeColors
├── loader.rs       # PluginLoader, filesystem discovery (native only)
└── lua.rs          # LuaPlugin, Lua API (native only)
```

## License

MIT