v2rmp 0.3.6

A powerful Terminal User Interface (TUI) for route optimization using the Chinese Postman Problem algorithm
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
use std::time::Instant;

use crate::core::optimize::TurnPenalties;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum View {
    Home,
    Extract,
    Compile,
    Optimize,
    BrowseMaps,
    BrowseRoutes,
    Help,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DataSource {
    Osm,
    Overture,
}

impl std::fmt::Display for DataSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DataSource::Osm => write!(f, "OpenStreetMap (OSM)"),
            DataSource::Overture => write!(f, "Overture Maps"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct BoundingBox {
    pub min_lon: f64,
    pub min_lat: f64,
    pub max_lon: f64,
    pub max_lat: f64,
}

impl std::fmt::Display for BoundingBox {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:.2},{:.2},{:.2},{:.2}",
            self.min_lat, self.min_lon, self.max_lat, self.max_lon
        )
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Status {
    Ready,
    Running { progress: u8, message: String },
    Done(String),
    Error(String),
}

impl std::fmt::Display for Status {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Status::Ready => write!(f, "Ready"),
            Status::Running { progress, message } => {
                write!(f, "{}% - {}", progress, message)
            }
            Status::Done(msg) => write!(f, "{}", msg),
            Status::Error(msg) => write!(f, "Error: {}", msg),
        }
    }
}

#[derive(Debug, Clone)]
pub struct LogEntry {
    pub timestamp: String,
    pub level: LogLevel,
    pub message: String,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LogLevel {
    Info,
    Success,
    Warn,
    Error,
}

impl std::fmt::Display for LogLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LogLevel::Info => write!(f, "INFO"),
            LogLevel::Success => write!(f, "SUCCESS"),
            LogLevel::Warn => write!(f, "WARN"),
            LogLevel::Error => write!(f, "ERROR"),
        }
    }
}

pub struct InputMode {
    pub active: bool,
    pub field: InputField,
    pub buffer: String,
}

#[derive(Debug, Clone, PartialEq)]
pub enum InputField {
    BoundingBox,
    InputFile,
    OutputFile,
    CacheFile,
    RouteFile,
    LeftTurnPenalty,
    RightTurnPenalty,
    UTurnPenalty,
    DepotCoordinates,
}

pub struct App {
    pub running: bool,
    pub current_view: View,
    pub workflow_selection: usize,
    pub log_entries: Vec<LogEntry>,
    pub log_scroll: usize,

    // Extract state
    pub data_source: DataSource,
    pub bounding_box: Option<BoundingBox>,
    pub extract_status: Status,

    // Compile state
    pub input_file: Option<String>,
    pub output_file: Option<String>,
    pub compile_status: Status,

    // Optimize state
    pub cache_file: Option<String>,
    pub route_file: Option<String>,
    pub turn_penalties: TurnPenalties,
    pub depot_coords: Option<(f64, f64)>,
    pub optimize_status: Status,

    // Browse state
    pub cached_maps: Vec<String>,
    pub saved_routes: Vec<String>,
    pub browse_selection: usize,

    // Input mode
    pub input_mode: InputMode,

    // Timing
    pub start_time: Instant,
}

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

impl App {
    /// Scan current directory for .rmp cache files
    fn scan_cached_maps() -> Vec<String> {
        use std::fs;
        let mut maps = Vec::new();

        if let Ok(entries) = fs::read_dir(".") {
            for entry in entries.flatten() {
                if let Ok(file_name) = entry.file_name().into_string() {
                    if file_name.ends_with(".rmp") {
                        maps.push(file_name);
                    }
                }
            }
        }

        maps.sort();
        maps
    }

    pub fn new() -> Self {
        Self {
            running: true,
            current_view: View::Home,
            workflow_selection: 0,
            log_entries: Vec::new(),
            log_scroll: 0,

            data_source: DataSource::Osm,
            bounding_box: None,
            extract_status: Status::Ready,

            input_file: None,
            output_file: None,
            compile_status: Status::Ready,

            cache_file: None,
            route_file: None,
            turn_penalties: TurnPenalties::default(),
            depot_coords: None,
            optimize_status: Status::Ready,

            cached_maps: Self::scan_cached_maps(),
            saved_routes: Vec::new(),
            browse_selection: 0,

            input_mode: InputMode {
                active: false,
                field: InputField::BoundingBox,
                buffer: String::new(),
            },

            start_time: Instant::now(),
        }
    }

    pub fn log(&mut self, level: LogLevel, message: impl Into<String>) {
        let timestamp = chrono::Local::now().format("%H:%M:%S").to_string();
        self.log_entries.push(LogEntry {
            timestamp,
            level,
            message: message.into(),
        });
        if self.log_entries.len() > 500 {
            self.log_entries.remove(0);
        }
        self.log_scroll = self.log_entries.len().saturating_sub(1);
    }

    pub fn start_input(&mut self, field: InputField) {
        self.input_mode.active = true;
        self.input_mode.field = field;
        self.input_mode.buffer.clear();
    }

    pub fn confirm_input(&mut self) {
        let value = self.input_mode.buffer.trim().to_string();
        if value.is_empty() {
            self.input_mode.active = false;
            return;
        }

        match self.input_mode.field {
            InputField::BoundingBox => {
                let parts: Vec<&str> = value.split(',').collect();
                if parts.len() == 4 {
                    if let (Ok(min_lon), Ok(min_lat), Ok(max_lon), Ok(max_lat)) = (
                        parts[0].parse::<f64>(),
                        parts[1].parse::<f64>(),
                        parts[2].parse::<f64>(),
                        parts[3].parse::<f64>(),
                    ) {
                        if min_lon >= max_lon || min_lat >= max_lat {
                            self.log(
                                LogLevel::Error,
                                "Invalid bounding box: min must be less than max".to_string(),
                            );
                            self.input_mode.active = false;
                            return;
                        }
                        let bbox = BoundingBox {
                            min_lon,
                            min_lat,
                            max_lon,
                            max_lat,
                        };
                        self.log(LogLevel::Success, format!("Bounding box set: {bbox}"));
                        self.bounding_box = Some(bbox);
                    } else {
                        self.log(LogLevel::Error, "Invalid coordinates".to_string());
                    }
                } else {
                    self.log(
                        LogLevel::Error,
                        "Expected format: min_lon,min_lat,max_lon,max_lat",
                    );
                }
            }
            InputField::InputFile => {
                self.input_file = Some(value.clone());
                if self.output_file.is_none() {
                    let out = value.replace(".geojson", ".rmp").replace(".json", ".rmp");
                    self.output_file = Some(out);
                }
                self.log(LogLevel::Success, format!("Input set: {}", value));
            }
            InputField::OutputFile => {
                self.output_file = Some(value.clone());
                self.log(LogLevel::Success, format!("Output set: {}", value));
            }
            InputField::CacheFile => {
                self.cache_file = Some(value.clone());
                self.log(LogLevel::Success, format!("Cache file set: {}", value));
            }
            InputField::RouteFile => {
                self.route_file = Some(value.clone());
                self.log(LogLevel::Success, format!("Route file set: {}", value));
            }
            InputField::LeftTurnPenalty => {
                if let Ok(v) = value.parse::<f64>() {
                    self.turn_penalties.left = v;
                    self.log(LogLevel::Success, format!("Left turn penalty set: {}", v));
                }
            }
            InputField::RightTurnPenalty => {
                if let Ok(v) = value.parse::<f64>() {
                    self.turn_penalties.right = v;
                    self.log(LogLevel::Success, format!("Right turn penalty set: {}", v));
                }
            }
            InputField::UTurnPenalty => {
                if let Ok(v) = value.parse::<f64>() {
                    self.turn_penalties.u_turn = v;
                    self.log(LogLevel::Success, format!("U-turn penalty set: {}", v));
                }
            }
            InputField::DepotCoordinates => {
                let parts: Vec<&str> = value.split(',').collect();
                if parts.len() == 2 {
                    if let (Ok(lat), Ok(lon)) = (parts[0].parse::<f64>(), parts[1].parse::<f64>()) {
                        self.depot_coords = Some((lat, lon));
                        self.log(
                            LogLevel::Success,
                            format!("Depot set: {:.4},{:.4}", lat, lon),
                        );
                    }
                }
            }
        }
        self.input_mode.active = false;
    }

    pub fn cancel_input(&mut self) {
        self.input_mode.active = false;
        self.input_mode.buffer.clear();
        self.log(LogLevel::Info, "Input cancelled");
    }

    pub fn navigate_up(&mut self) {
        match self.current_view {
            View::Home => {
                self.workflow_selection = (self.workflow_selection + 4) % 5;
            }
            View::BrowseMaps => {
                let max = self.cached_maps.len().max(1);
                if max > 0 {
                    self.browse_selection = (self.browse_selection + max - 1) % max;
                }
            }
            View::BrowseRoutes => {
                let max = self.saved_routes.len().max(1);
                if max > 0 {
                    self.browse_selection = (self.browse_selection + max - 1) % max;
                }
            }
            _ => {}
        }
    }

    pub fn navigate_down(&mut self) {
        match self.current_view {
            View::Home => {
                self.workflow_selection = (self.workflow_selection + 1) % 5;
            }
            View::BrowseMaps => {
                let max = self.cached_maps.len().max(1);
                if max > 0 {
                    self.browse_selection = (self.browse_selection + 1) % max;
                }
            }
            View::BrowseRoutes => {
                let max = self.saved_routes.len().max(1);
                if max > 0 {
                    self.browse_selection = (self.browse_selection + 1) % max;
                }
            }
            _ => {}
        }
    }
}

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

    #[test]
    fn test_app_initialization() {
        let app = App::new();

        // Basic state
        assert!(app.running);
        assert_eq!(app.current_view, View::Home);
        assert_eq!(app.workflow_selection, 0);
        assert!(app.log_entries.is_empty());
        assert_eq!(app.log_scroll, 0);

        // Extract state
        assert_eq!(app.data_source, DataSource::Osm);
        assert!(app.bounding_box.is_none());
        assert_eq!(app.extract_status, Status::Ready);

        // Compile state
        assert!(app.input_file.is_none());
        assert!(app.output_file.is_none());
        assert_eq!(app.compile_status, Status::Ready);

        // Optimize state
        assert!(app.cache_file.is_none());
        assert!(app.route_file.is_none());
        assert_eq!(app.turn_penalties.left, 1.0);
        assert_eq!(app.turn_penalties.right, 0.0);
        assert_eq!(app.turn_penalties.u_turn, 5.0);
        assert!(app.depot_coords.is_none());
        assert_eq!(app.optimize_status, Status::Ready);

        // Browse state
        // app.cached_maps depends on filesystem, but should be a Vec
        assert!(app.saved_routes.is_empty());
        assert_eq!(app.browse_selection, 0);

        // Input mode
        assert!(!app.input_mode.active);
        assert_eq!(app.input_mode.field, InputField::BoundingBox);
        assert!(app.input_mode.buffer.is_empty());
    }

    #[test]
    fn test_log_truncation() {
        let mut app = App::new();

        // Add 501 entries
        for i in 0..501 {
            app.log(LogLevel::Info, format!("Message {}", i));
        }

        // Verify length is capped at 500
        assert_eq!(app.log_entries.len(), 500);

        // Verify oldest was removed (first entry should be "Message 1")
        assert_eq!(app.log_entries[0].message, "Message 1");

        // Verify latest is correct
        assert_eq!(app.log_entries[499].message, "Message 500");

        // Verify scroll position
        assert_eq!(app.log_scroll, 499);
    }

    #[test]
    fn test_invalid_bbox_input() {
        let mut app = App::new();
        app.input_mode.field = InputField::BoundingBox;

        // Invalid: min > max
        app.input_mode.buffer = "10.0,20.0,5.0,25.0".to_string();
        app.confirm_input();
        assert!(app.bounding_box.is_none());
        assert_eq!(app.log_entries.last().unwrap().level, LogLevel::Error);
        assert!(app
            .log_entries
            .last()
            .unwrap()
            .message
            .contains("Invalid bounding box"));

        // Valid
        app.input_mode.active = true;
        app.input_mode.buffer = "5.0,15.0,10.0,25.0".to_string();
        app.confirm_input();
        assert!(app.bounding_box.is_some());
        assert_eq!(app.log_entries.last().unwrap().level, LogLevel::Success);
    }

    #[test]
    fn test_confirm_input_empty() {
        let mut app = App::new();
        app.input_mode.active = true;
        app.input_mode.buffer = "  ".to_string();
        app.confirm_input();
        assert!(!app.input_mode.active);
    }

    #[test]
    fn test_confirm_input_bounding_box() {
        let mut app = App::new();
        app.start_input(InputField::BoundingBox);

        // Valid
        app.input_mode.buffer = "1.0,2.0,3.0,4.0".to_string();
        app.confirm_input();
        assert!(app.bounding_box.is_some());
        let bbox = app.bounding_box.as_ref().unwrap();
        assert_eq!(bbox.min_lon, 1.0);
        assert_eq!(bbox.min_lat, 2.0);
        assert_eq!(bbox.max_lon, 3.0);
        assert_eq!(bbox.max_lat, 4.0);
        assert!(!app.input_mode.active);

        // Invalid numeric
        app.start_input(InputField::BoundingBox);
        app.input_mode.buffer = "1.0,abc,3.0,4.0".to_string();
        app.bounding_box = None;
        app.confirm_input();
        assert!(app.bounding_box.is_none());

        // Invalid format
        app.start_input(InputField::BoundingBox);
        app.input_mode.buffer = "1.0,2.0,3.0".to_string();
        app.confirm_input();
        assert!(app.bounding_box.is_none());
    }

    #[test]
    fn test_confirm_input_files() {
        let mut app = App::new();

        // InputFile + OutputFile derivation
        app.start_input(InputField::InputFile);
        app.input_mode.buffer = "map.geojson".to_string();
        app.confirm_input();
        assert_eq!(app.input_file, Some("map.geojson".to_string()));
        assert_eq!(app.output_file, Some("map.rmp".to_string()));

        // OutputFile manual override
        app.start_input(InputField::OutputFile);
        app.input_mode.buffer = "custom.rmp".to_string();
        app.confirm_input();
        assert_eq!(app.output_file, Some("custom.rmp".to_string()));

        // CacheFile
        app.start_input(InputField::CacheFile);
        app.input_mode.buffer = "cache.rmp".to_string();
        app.confirm_input();
        assert_eq!(app.cache_file, Some("cache.rmp".to_string()));

        // RouteFile
        app.start_input(InputField::RouteFile);
        app.input_mode.buffer = "route.json".to_string();
        app.confirm_input();
        assert_eq!(app.route_file, Some("route.json".to_string()));
    }

    #[test]
    fn test_confirm_input_penalties() {
        let mut app = App::new();

        // Left
        app.start_input(InputField::LeftTurnPenalty);
        app.input_mode.buffer = "2.5".to_string();
        app.confirm_input();
        assert_eq!(app.turn_penalties.left, 2.5);

        // Right
        app.start_input(InputField::RightTurnPenalty);
        app.input_mode.buffer = "0.5".to_string();
        app.confirm_input();
        assert_eq!(app.turn_penalties.right, 0.5);

        // U-turn
        app.start_input(InputField::UTurnPenalty);
        app.input_mode.buffer = "10.0".to_string();
        app.confirm_input();
        assert_eq!(app.turn_penalties.u_turn, 10.0);

        // Invalid numeric
        app.start_input(InputField::LeftTurnPenalty);
        app.input_mode.buffer = "invalid".to_string();
        app.confirm_input();
        assert_eq!(app.turn_penalties.left, 2.5); // Should remain unchanged
    }

    #[test]
    fn test_confirm_input_depot() {
        let mut app = App::new();

        // Valid
        app.start_input(InputField::DepotCoordinates);
        app.input_mode.buffer = "45.0,-122.0".to_string();
        app.confirm_input();
        assert_eq!(app.depot_coords, Some((45.0, -122.0)));

        // Invalid format
        app.start_input(InputField::DepotCoordinates);
        app.input_mode.buffer = "45.0".to_string();
        app.depot_coords = None;
        app.confirm_input();
        assert!(app.depot_coords.is_none());
    }
}