app.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. use std::{error, collections::HashMap};
  2. use ratatui::widgets::ListState;
  3. use wad::{Wad, load_wad_file};
  4. use crate::lumps::{LumpInfo, get_lumps, LumpType};
  5. /// Application result type.
  6. pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>;
  7. /// Application.
  8. pub struct StatefulList<T> {
  9. pub state: ListState,
  10. pub items: Vec<T>,
  11. }
  12. impl<T> StatefulList<T> {
  13. fn with_items(items: Vec<T>) -> StatefulList<T> {
  14. StatefulList {
  15. state: ListState::default(),
  16. items,
  17. }
  18. }
  19. pub fn next(&mut self) {
  20. let i = match self.state.selected() {
  21. Some(i) => {
  22. if i >= self.items.len() - 1 {
  23. 0
  24. } else {
  25. i + 1
  26. }
  27. }
  28. None => 0,
  29. };
  30. self.state.select(Some(i));
  31. }
  32. pub fn previous(&mut self) {
  33. let i = match self.state.selected() {
  34. Some(i) => {
  35. if i == 0 {
  36. self.items.len() - 1
  37. } else {
  38. i - 1
  39. }
  40. }
  41. None => 0,
  42. };
  43. self.state.select(Some(i));
  44. }
  45. pub fn unselect(&mut self) {
  46. self.state.select(None);
  47. }
  48. }
  49. pub struct App {
  50. pub wad:Wad,
  51. pub lumps:StatefulList<LumpInfo>,
  52. pub sizes: HashMap<Option<LumpType>, usize>,
  53. pub running:bool,
  54. }
  55. impl App {
  56. fn from_wad(wad_path:&str) -> Self {
  57. let wad = load_wad_file(wad_path).unwrap();
  58. let lumps = get_lumps(&wad);
  59. let mut sizes = HashMap::new();
  60. for lump in lumps.iter() {
  61. if let Some(LumpType::Marker(_, _)) = lump.lump_type {
  62. continue;
  63. }
  64. sizes.insert(lump.lump_type.clone(), sizes.get(&lump.lump_type).unwrap_or(&0) + lump.size);
  65. }
  66. Self {
  67. wad: wad,
  68. lumps: StatefulList::with_items(lumps),
  69. sizes: sizes,
  70. running: true
  71. }
  72. }
  73. }
  74. impl App {
  75. /// Constructs a new instance of [`App`].
  76. pub fn new(wad_path:&str) -> Self {
  77. Self::from_wad(wad_path)
  78. }
  79. /// Handles the tick event of the terminal.
  80. pub fn tick(&self) {}
  81. /// Set running to false to quit the application.
  82. pub fn quit(&mut self) {
  83. self.running = false;
  84. }
  85. }