vm-curator 0.3.2

A TUI application to manage QEMU VM library
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
//! QEMU configuration profiles for different operating systems
//!
//! This module provides OS-specific QEMU defaults that are used
//! when creating new VMs through the creation wizard.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Embedded QEMU profiles from assets/metadata/qemu_profiles.toml
const EMBEDDED_PROFILES: &str = include_str!("../../assets/metadata/qemu_profiles.toml");

/// A QEMU configuration profile for a specific operating system
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QemuProfile {
    /// Human-readable display name
    pub display_name: String,

    /// Category (windows, linux, bsd, unix, classic-mac, alternative, retro, macos)
    pub category: String,

    /// QEMU emulator command (e.g., qemu-system-x86_64)
    pub emulator: String,

    /// Default RAM in megabytes
    pub memory_mb: u32,

    /// Default CPU cores
    pub cpu_cores: u32,

    /// CPU model (host, qemu64, pentium, etc.)
    #[serde(default)]
    pub cpu_model: Option<String>,

    /// Machine type (q35, pc, etc.)
    #[serde(default)]
    pub machine: Option<String>,

    /// Graphics adapter (qxl, virtio, std, cirrus, vmware, none)
    pub vga: String,

    /// Audio devices (e.g., ["intel-hda", "hda-duplex"])
    #[serde(default)]
    pub audio: Vec<String>,

    /// Network adapter model (virtio, e1000, rtl8139, ne2k_pci, pcnet, none)
    pub network_model: String,

    /// Disk interface (virtio, ide, sata, scsi, sd)
    pub disk_interface: String,

    /// Default disk size in gigabytes
    pub disk_size_gb: u32,

    /// Enable KVM acceleration
    #[serde(default)]
    pub enable_kvm: bool,

    /// Boot in UEFI mode
    #[serde(default)]
    pub uefi: bool,

    /// Enable TPM emulation
    #[serde(default)]
    pub tpm: bool,

    /// Set RTC to local time (for Windows)
    #[serde(default)]
    pub rtc_localtime: bool,

    /// Use USB tablet for mouse
    #[serde(default)]
    pub usb_tablet: bool,

    /// Display output (gtk, sdl, spice, vnc)
    #[serde(default = "default_display")]
    pub display: String,

    /// Additional QEMU arguments
    #[serde(default)]
    pub extra_args: Vec<String>,

    /// Download URL for free/open-source OSes
    #[serde(default)]
    pub iso_url: Option<String>,

    /// Tips/notes for this OS
    #[serde(default)]
    pub notes: Option<String>,
}

fn default_display() -> String {
    "gtk".to_string()
}

impl Default for QemuProfile {
    fn default() -> Self {
        Self {
            display_name: "Unknown OS".to_string(),
            category: "alternative".to_string(),
            emulator: "qemu-system-x86_64".to_string(),
            memory_mb: 2048,
            cpu_cores: 2,
            cpu_model: Some("host".to_string()),
            machine: Some("q35".to_string()),
            vga: "std".to_string(),
            audio: vec!["intel-hda".to_string(), "hda-duplex".to_string()],
            network_model: "e1000".to_string(),
            disk_interface: "ide".to_string(),
            disk_size_gb: 32,
            enable_kvm: true,
            uefi: false,
            tpm: false,
            rtc_localtime: false,
            usb_tablet: true,
            display: "gtk".to_string(),
            extra_args: vec![],
            iso_url: None,
            notes: None,
        }
    }
}

impl QemuProfile {
    /// Check if this profile supports free ISO download
    #[allow(dead_code)]
    pub fn has_free_iso(&self) -> bool {
        self.iso_url.is_some()
    }

    /// Check if this profile uses x86 architecture
    #[allow(dead_code)]
    pub fn is_x86(&self) -> bool {
        self.emulator.contains("x86_64") || self.emulator.contains("i386")
    }

    /// Check if this profile uses 64-bit x86
    #[allow(dead_code)]
    pub fn is_x86_64(&self) -> bool {
        self.emulator.contains("x86_64")
    }

    /// Get a short summary for display in the wizard
    pub fn summary(&self) -> String {
        let mut parts = vec![];

        // Memory
        if self.memory_mb >= 1024 {
            parts.push(format!("{}GB RAM", self.memory_mb / 1024));
        } else {
            parts.push(format!("{}MB RAM", self.memory_mb));
        }

        // Disk
        parts.push(format!("{}GB", self.disk_size_gb));

        // Notable features
        if self.uefi {
            parts.push("UEFI".to_string());
        }
        if self.disk_interface == "virtio" {
            parts.push("virtio".to_string());
        }

        parts.join(", ")
    }
}

/// Store for QEMU profiles with support for user overrides
#[derive(Debug, Default)]
pub struct QemuProfileStore {
    profiles: HashMap<String, QemuProfile>,
}

impl QemuProfileStore {
    /// Create a new empty profile store
    pub fn new() -> Self {
        Self {
            profiles: HashMap::new(),
        }
    }

    /// Load the embedded profiles from compile-time data
    pub fn load_embedded() -> Self {
        let mut store = Self::new();

        match toml::from_str::<HashMap<String, QemuProfile>>(EMBEDDED_PROFILES) {
            Ok(profiles) => {
                store.profiles = profiles;
            }
            Err(e) => {
                eprintln!("Warning: Failed to parse embedded QEMU profiles: {}", e);
            }
        }

        store
    }

    /// Load user override profiles from a file
    pub fn load_user_overrides(&mut self, path: &Path) {
        if !path.exists() {
            return;
        }

        match std::fs::read_to_string(path) {
            Ok(content) => match toml::from_str::<HashMap<String, QemuProfile>>(&content) {
                Ok(user_profiles) => {
                    // Merge user profiles (override existing)
                    for (id, profile) in user_profiles {
                        self.profiles.insert(id, profile);
                    }
                }
                Err(e) => {
                    eprintln!("Warning: Failed to parse user QEMU profiles: {}", e);
                }
            },
            Err(e) => {
                eprintln!("Warning: Failed to read user QEMU profiles: {}", e);
            }
        }
    }

    /// Get a profile by OS ID
    pub fn get(&self, os_id: &str) -> Option<&QemuProfile> {
        self.profiles.get(os_id)
    }

    /// Get a profile by OS ID, or return the default profile
    #[allow(dead_code)]
    pub fn get_or_default(&self, os_id: &str) -> QemuProfile {
        self.profiles
            .get(os_id)
            .cloned()
            .unwrap_or_else(QemuProfile::default)
    }

    /// List all profiles
    #[allow(dead_code)]
    pub fn list_all(&self) -> Vec<(&String, &QemuProfile)> {
        let mut profiles: Vec<_> = self.profiles.iter().collect();
        profiles.sort_by(|a, b| a.1.display_name.cmp(&b.1.display_name));
        profiles
    }

    /// List profiles by category
    pub fn list_by_category(&self, category: &str) -> Vec<(&String, &QemuProfile)> {
        let mut profiles: Vec<_> = self
            .profiles
            .iter()
            .filter(|(_, p)| p.category == category)
            .collect();
        profiles.sort_by(|a, b| a.1.display_name.cmp(&b.1.display_name));
        profiles
    }

    /// Get all unique categories
    #[allow(dead_code)]
    pub fn categories(&self) -> Vec<String> {
        let mut categories: Vec<String> = self
            .profiles
            .values()
            .map(|p| p.category.clone())
            .collect();
        categories.sort();
        categories.dedup();
        categories
    }

    /// Get category display name
    pub fn category_display_name(category: &str) -> &'static str {
        match category {
            "windows" => "Windows",
            "linux" => "Linux",
            "bsd" => "BSD",
            "unix" => "Unix",
            "classic-mac" => "Classic Mac",
            "macos" => "macOS",
            "alternative" => "Alternative",
            "retro" => "Retro",
            "mobile" => "Mobile / Android",
            "infrastructure" => "Infrastructure",
            "utilities" => "Utilities",
            _ => "Other",
        }
    }

    /// Get profiles that support free ISO download
    #[allow(dead_code)]
    pub fn list_with_free_iso(&self) -> Vec<(&String, &QemuProfile)> {
        let mut profiles: Vec<_> = self
            .profiles
            .iter()
            .filter(|(_, p)| p.iso_url.is_some())
            .collect();
        profiles.sort_by(|a, b| a.1.display_name.cmp(&b.1.display_name));
        profiles
    }

    /// Get profiles that are x86/x86_64 (supported in V1.0)
    #[allow(dead_code)]
    pub fn list_x86_profiles(&self) -> Vec<(&String, &QemuProfile)> {
        let mut profiles: Vec<_> = self.profiles.iter().filter(|(_, p)| p.is_x86()).collect();
        profiles.sort_by(|a, b| a.1.display_name.cmp(&b.1.display_name));
        profiles
    }

    /// Search profiles by name
    #[allow(dead_code)]
    pub fn search(&self, query: &str) -> Vec<(&String, &QemuProfile)> {
        let query_lower = query.to_lowercase();
        let mut profiles: Vec<_> = self
            .profiles
            .iter()
            .filter(|(id, p)| {
                id.to_lowercase().contains(&query_lower)
                    || p.display_name.to_lowercase().contains(&query_lower)
            })
            .collect();
        profiles.sort_by(|a, b| a.1.display_name.cmp(&b.1.display_name));
        profiles
    }

    /// Get the count of profiles
    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.profiles.len()
    }

    /// Check if the store is empty
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.profiles.is_empty()
    }

    /// Get a generic profile based on category
    #[allow(dead_code)]
    pub fn generic_profile_for_category(category: &str) -> &'static str {
        match category {
            "windows" => "generic-windows",
            "linux" => "generic-linux",
            "bsd" => "generic-bsd",
            _ => "generic-other",
        }
    }
}

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

    #[test]
    fn test_load_embedded_profiles() {
        let store = QemuProfileStore::load_embedded();
        assert!(!store.is_empty(), "Should have loaded some profiles");

        // Check that some expected profiles exist
        assert!(store.get("windows-10").is_some(), "Should have Windows 10");
        assert!(store.get("linux-debian").is_some(), "Should have Debian");
        assert!(store.get("freebsd").is_some(), "Should have FreeBSD");
    }

    #[test]
    fn test_profile_summary() {
        let profile = QemuProfile {
            display_name: "Test OS".to_string(),
            memory_mb: 4096,
            disk_size_gb: 64,
            uefi: true,
            disk_interface: "virtio".to_string(),
            ..Default::default()
        };

        let summary = profile.summary();
        assert!(summary.contains("4GB RAM"));
        assert!(summary.contains("64GB"));
        assert!(summary.contains("UEFI"));
        assert!(summary.contains("virtio"));
    }

    #[test]
    fn test_categories() {
        let store = QemuProfileStore::load_embedded();
        let categories = store.categories();

        assert!(categories.contains(&"windows".to_string()));
        assert!(categories.contains(&"linux".to_string()));
        assert!(categories.contains(&"bsd".to_string()));
    }

    #[test]
    fn test_search() {
        let store = QemuProfileStore::load_embedded();

        let results = store.search("windows");
        assert!(!results.is_empty(), "Should find Windows profiles");

        let results = store.search("debian");
        assert!(!results.is_empty(), "Should find Debian profiles");
    }

    #[test]
    fn test_free_iso_profiles() {
        let store = QemuProfileStore::load_embedded();
        let free_profiles = store.list_with_free_iso();

        // Should have at least some free/open-source OSes
        assert!(
            !free_profiles.is_empty(),
            "Should have profiles with free ISOs"
        );

        // Check that a known free OS is in the list
        let has_debian = free_profiles.iter().any(|(id, _)| *id == "linux-debian");
        assert!(has_debian, "Debian should have a free ISO URL");
    }
}