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
#![allow(clippy::module_inception)]
use std::time::Duration;

use crossterm::event;
use ratatui::{
    backend::Backend,
    layout::Rect,
    text::{Line, Text},
    widgets::{Block, Borders, Clear},
};

use super::{
    asm::assembly_line::AssemblyLine,
    data::Data,
    files::filesystem::FileSystem,
    help::HelpLine,
    info_mode::InfoMode,
    log::{logger::Logger, NotificationLevel},
    plugins::plugin_manager::PluginManager,
    popup::popup_state::PopupState,
    settings::{color_settings::ColorSettings, Settings},
    widgets::{logo::Logo, scrollbar::Scrollbar},
};

use crate::{args::Args, get_app_context, headers::Header};

pub struct App {
    pub(super) plugin_manager: PluginManager,
    pub(super) filesystem: FileSystem,
    pub(super) header: Header,
    pub(super) logger: Logger,
    pub(super) help_list: Vec<HelpLine>,
    pub(super) data: Data,
    pub(super) assembly_offsets: Vec<usize>,
    pub(super) assembly_instructions: Vec<AssemblyLine>,
    pub(super) text_last_searched_string: String,
    pub(super) info_mode: InfoMode,
    pub(super) scroll: usize,
    pub(super) cursor: (u16, u16),
    pub(super) poll_time: Duration,
    pub(super) needs_to_exit: bool,
    pub(super) screen_size: (u16, u16),

    pub(super) settings: Settings,

    pub(super) popup: Option<PopupState>,

    pub(super) vertical_margin: u16,
    pub(super) block_size: usize,
    pub(super) blocks_per_row: usize,
}

impl App {
    pub(super) fn print_loading_status<B: Backend>(
        color_settings: &ColorSettings,
        status: &str,
        terminal: &mut ratatui::Terminal<B>,
    ) -> Result<(), String> {
        terminal
            .draw(|f| {
                let size = f.size();
                let mut text = Text::default();
                for _ in 0..(size.height.saturating_sub(1)) {
                    text.lines.push(ratatui::text::Line::default());
                }
                text.lines
                    .push(Line::styled(status.to_string(), color_settings.menu_text));
                let paragraph = ratatui::widgets::Paragraph::new(text)
                    .block(Block::default().borders(Borders::NONE));
                let logo = Logo::default();
                let logo_size = logo.get_size();
                f.render_widget(paragraph, size);
                if logo_size.0 < size.width && logo_size.1 < size.height {
                    f.render_widget(
                        logo,
                        Rect::new(
                            size.width / 2 - logo_size.0 / 2,
                            size.height / 2 - logo_size.1 / 2,
                            logo_size.0,
                            logo_size.1,
                        ),
                    );
                }
            })
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    pub(super) fn get_size<B: Backend>(
        terminal: &mut ratatui::Terminal<B>,
    ) -> Result<(u16, u16), String> {
        terminal
            .size()
            .map_err(|e| e.to_string())
            .map(|s| (s.width, s.height))
    }

    pub fn new<B: Backend>(
        args: Args,
        terminal: &mut ratatui::Terminal<B>,
    ) -> Result<Self, String> {
        let mut logger = Logger::default();
        let settings = match Settings::load_or_create(args.config.as_deref()) {
            Ok(settings) => settings,
            Err(e) => {
                logger.log(
                    NotificationLevel::Error,
                    &format!("Error loading settings: {e}"),
                );
                Settings::default()
            }
        };
        logger.change_limit(settings.app.log_limit);
        Self::print_loading_status(
            &settings.color,
            &format!("Opening \"{}\"...", args.path),
            terminal,
        )?;

        let filesystem = if let Some(ssh) = &args.ssh {
            FileSystem::new_remote(&args.path, ssh, args.password.as_deref())
                .map_err(|e| format!("Failed to connect to {}: {e}", ssh))?
        } else {
            FileSystem::new_local(&args.path).map_err(|e| e.to_string())?
        };
        let screen_size = Self::get_size(terminal)?;

        let mut app = App {
            filesystem,
            screen_size,
            help_list: Self::help_list(&settings.key),
            settings,
            logger,
            ..Default::default()
        };

        let mut app_context = get_app_context!(app);
        app.plugin_manager = match PluginManager::load(args.plugins.as_deref(), &mut app_context) {
            Ok(plugins) => plugins,
            Err(e) => {
                app.log(
                    NotificationLevel::Error,
                    &format!("Error loading plugins: {e}"),
                );
                PluginManager::default()
            }
        };

        if app.filesystem.is_file(app.filesystem.pwd()) {
            let path = app.filesystem.pwd().to_string();
            app.open_file(&path, Some(terminal))
                .map_err(|e| e.to_string())?;
        } else {
            let dir = app.filesystem.pwd().to_string();
            Self::open_dir(&mut app.popup, &dir, &mut app.filesystem).map_err(|e| e.to_string())?;
        }

        Ok(app)
    }

    pub fn run<B: Backend>(
        &mut self,
        terminal: &mut ratatui::Terminal<B>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.screen_size = (terminal.size()?.width, terminal.size()?.height);
        self.resize_to_size(self.screen_size.0, self.screen_size.1);

        while !self.needs_to_exit {
            if event::poll(self.poll_time)? {
                while event::poll(Duration::from_millis(0))? {
                    let event = event::read()?;
                    let event_result = self.handle_event(event, terminal);
                    if let Err(e) = event_result {
                        self.log(NotificationLevel::Error, &e.to_string());
                    }
                }
            }

            terminal.draw(|f| {
                let min_width = self.block_size as u16 * 3 + 17 + 3;
                if f.size().width < min_width {
                    return;
                }
                let output_rect = Rect::new(0, f.size().height - 1, f.size().width, 1);
                let address_rect = Rect::new(0, 0, 17, f.size().height - output_rect.height);
                let hex_editor_rect = Rect::new(
                    address_rect.width,
                    0,
                    (self.block_size * 3 * self.blocks_per_row + self.blocks_per_row) as u16,
                    f.size().height - output_rect.height,
                );
                let info_view_rect = Rect::new(
                    address_rect.width + hex_editor_rect.width,
                    0,
                    f.size().width - hex_editor_rect.width - address_rect.width - 2,
                    f.size().height - output_rect.height,
                );
                let scrollbar_rect = Rect::new(f.size().width - 1, 0, 1, f.size().height);

                let output_block = ratatui::widgets::Paragraph::new(self.build_status_bar())
                    .block(Block::default().borders(Borders::NONE));

                let scrolled_amount = self.get_cursor_position().global_byte_index;
                let total_amount = self.data.len();
                let scrollbar =
                    Scrollbar::new(scrolled_amount, total_amount, self.settings.color.scrollbar);

                if !self.data.is_empty() {
                    let line_start_index = self.scroll;
                    let line_end_index = (self.scroll + f.size().height as usize).saturating_sub(2);

                    let address_view = self.get_address_view(line_start_index, line_end_index);
                    let hex_view = self.get_hex_view(line_start_index, line_end_index);

                    let address_block = ratatui::widgets::Paragraph::new(address_view).block(
                        Block::default()
                            .title("Address")
                            .borders(Borders::LEFT | Borders::TOP),
                    );

                    let editor_title =
                        format!("Hex Editor{}", if self.data.dirty() { " *" } else { "" });

                    let hex_editor_block = ratatui::widgets::Paragraph::new(hex_view).block(
                        Block::default()
                            .title(editor_title)
                            .borders(Borders::LEFT | Borders::TOP | Borders::RIGHT),
                    );

                    let info_view_block = match &self.info_mode {
                        InfoMode::Text => {
                            let text_subview_lines =
                                self.get_text_view(line_start_index, line_end_index);
                            let mut text_subview = Text::default();
                            text_subview
                                .lines
                                .extend(text_subview_lines.iter().cloned());
                            ratatui::widgets::Paragraph::new(text_subview).block(
                                Block::default()
                                    .title("Text View")
                                    .borders(Borders::TOP | Borders::RIGHT),
                            )
                        }
                        InfoMode::Assembly => {
                            let assembly_start_index = self.get_assembly_view_scroll();
                            let assembly_end_index =
                                (assembly_start_index + f.size().height as usize - 2)
                                    .min(self.assembly_instructions.len());
                            let assembly_subview_lines = &self.assembly_instructions
                                [assembly_start_index..assembly_end_index];
                            let mut assembly_subview = Text::default();
                            let address_min_width = self
                                .assembly_instructions
                                .last()
                                .map(|x| format!("{:X}", x.file_address()).len() + 1)
                                .unwrap_or(1);
                            assembly_subview
                                .lines
                                .extend(assembly_subview_lines.iter().map(|x| {
                                    x.to_line(
                                        &self.settings.color,
                                        self.get_cursor_position().global_byte_index,
                                        &self.header,
                                        address_min_width,
                                    )
                                }));
                            ratatui::widgets::Paragraph::new(assembly_subview).block(
                                Block::default()
                                    .title("Assembly View")
                                    .borders(Borders::TOP | Borders::RIGHT),
                            )
                        }
                    };

                    f.render_widget(address_block, address_rect);
                    f.render_widget(hex_editor_block, hex_editor_rect);
                    f.render_widget(info_view_block, info_view_rect);
                }
                f.render_widget(output_block, output_rect);
                f.render_widget(scrollbar, scrollbar_rect);

                // Draw popup
                if self.popup.is_some() {
                    let mut popup_text = Text::default();
                    let mut popup_title = "Popup".into();

                    let mut popup_width = 60;
                    let mut popup_height = 5;

                    let popup_result = self.fill_popup(
                        &mut popup_title,
                        &mut popup_text,
                        &mut popup_height,
                        &mut popup_width,
                    );

                    popup_height = popup_height.min(f.size().height.saturating_sub(2) as usize);
                    popup_width = popup_width.min(f.size().width.saturating_sub(1) as usize);
                    let popup_rect = Rect::new(
                        (f.size().width / 2).saturating_sub((popup_width / 2 + 1) as u16),
                        (f.size().height / 2).saturating_sub((popup_height / 2) as u16),
                        popup_width as u16,
                        popup_height as u16,
                    );

                    match popup_result {
                        Ok(()) => {
                            let popup = ratatui::widgets::Paragraph::new(popup_text)
                                .block(Block::default().title(popup_title).borders(Borders::ALL))
                                .alignment(ratatui::layout::Alignment::Center);
                            f.render_widget(Clear, popup_rect);
                            f.render_widget(popup, popup_rect);
                        }
                        Err(e) => {
                            self.logger
                                .log(NotificationLevel::Error, &format!("Filling popup: {e}"));
                        }
                    }
                }
            })?;
        }

        Ok(())
    }
}

impl Default for App {
    fn default() -> Self {
        App {
            plugin_manager: PluginManager::default(),
            filesystem: FileSystem::default(),
            header: Header::None,
            logger: Logger::default(),
            help_list: Self::help_list(&Settings::default().key),
            data: Data::default(),
            assembly_offsets: Vec::new(),
            assembly_instructions: Vec::new(),
            text_last_searched_string: String::new(),
            info_mode: InfoMode::Text,
            scroll: 0,
            cursor: (0, 0),
            poll_time: Duration::from_millis(1000),
            needs_to_exit: false,
            screen_size: (0, 0),

            settings: Settings::default(),

            popup: None,

            vertical_margin: 2,
            block_size: 8,
            blocks_per_row: 1,
        }
    }
}