cleaned old tab system

This commit is contained in:
WanderingPenwing 2024-02-07 17:32:47 +01:00
parent fd08458951
commit c6bd2f32fd
5 changed files with 418 additions and 504 deletions

View file

@ -8,7 +8,6 @@ use crate::panels;
use crate::save_path; use crate::save_path;
use crate::sub_windows; use crate::sub_windows;
use crate::Calcifer; use crate::Calcifer;
use crate::MAX_TABS;
use crate::TIME_LABELS; use crate::TIME_LABELS;
impl Calcifer { impl Calcifer {
@ -20,12 +19,12 @@ impl Calcifer {
if self.refresh_confirm.proceed { if self.refresh_confirm.proceed {
self.refresh_confirm.close(); self.refresh_confirm.close();
self.tabs[self.selected_tab.to_index()].refresh(); self.tabs[self.selected_tab].refresh();
} }
} }
pub fn save_tab(&self) -> Option<PathBuf> { pub fn save_tab(&self) -> Option<PathBuf> {
if self.tabs[self.selected_tab.to_index()] if self.tabs[self.selected_tab]
.path .path
.file_name() .file_name()
.map_or(true, |name| name.to_string_lossy() == "untitled") .map_or(true, |name| name.to_string_lossy() == "untitled")
@ -33,13 +32,13 @@ impl Calcifer {
self.save_tab_as() self.save_tab_as()
} else { } else {
if let Err(err) = fs::write( if let Err(err) = fs::write(
&self.tabs[self.selected_tab.to_index()].path, &self.tabs[self.selected_tab].path,
&self.tabs[self.selected_tab.to_index()].code, &self.tabs[self.selected_tab].code,
) { ) {
eprintln!("Error writing file: {}", err); eprintln!("Error writing file: {}", err);
return None; return None;
} }
Some(self.tabs[self.selected_tab.to_index()].path.clone()) Some(self.tabs[self.selected_tab].path.clone())
} }
} }
@ -48,7 +47,7 @@ impl Calcifer {
.set_directory(self.home.as_path()) .set_directory(self.home.as_path())
.save_file() .save_file()
{ {
if let Err(err) = fs::write(&path, &self.tabs[self.selected_tab.to_index()].code) { if let Err(err) = fs::write(&path, &self.tabs[self.selected_tab].code) {
eprintln!("Error writing file: {}", err); eprintln!("Error writing file: {}", err);
return None; return None;
} }
@ -60,8 +59,8 @@ impl Calcifer {
pub fn handle_save_file(&mut self, path_option: Option<PathBuf>) { pub fn handle_save_file(&mut self, path_option: Option<PathBuf>) {
if let Some(path) = path_option { if let Some(path) = path_option {
println!("File saved successfully at: {:?}", path); println!("File saved successfully at: {:?}", path);
self.tabs[self.selected_tab.to_index()].path = path; self.tabs[self.selected_tab].path = path;
self.tabs[self.selected_tab.to_index()].saved = true; self.tabs[self.selected_tab].saved = true;
} else { } else {
println!("File save failed."); println!("File save failed.");
} }
@ -112,38 +111,35 @@ impl Calcifer {
pub fn move_through_tabs(&mut self, forward: bool) { pub fn move_through_tabs(&mut self, forward: bool) {
let new_index = if forward { let new_index = if forward {
(self.selected_tab.to_index() + 1) % self.tabs.len() (self.selected_tab + 1) % self.tabs.len()
} else { } else {
self.selected_tab self.selected_tab
.to_index()
.checked_sub(1) .checked_sub(1)
.unwrap_or(self.tabs.len() - 1) .unwrap_or(self.tabs.len() - 1)
}; };
self.selected_tab = panels::TabNumber::from_index(new_index); self.selected_tab = new_index;
} }
pub fn open_file(&mut self, path_option: Option<&Path>) { pub fn open_file(&mut self, path_option: Option<&Path>) {
if let Some(path) = path_option { if let Some(path) = path_option {
for (index, tab) in self.tabs.clone().iter().enumerate() { for (index, tab) in self.tabs.clone().iter().enumerate() {
if tab.path == path { if tab.path == path {
self.selected_tab = panels::TabNumber::from_index(index); self.selected_tab = index;
return; return;
} }
} }
} }
if self.tabs.len() < MAX_TABS {
if let Some(path) = path_option { if let Some(path) = path_option {
self.tabs.push(panels::Tab::new(path.to_path_buf())); self.tabs.push(panels::Tab::new(path.to_path_buf()));
} else { } else {
self.tabs.push(panels::Tab::default()); self.tabs.push(panels::Tab::default());
} }
self.selected_tab = panels::TabNumber::from_index(self.tabs.len() - 1); self.selected_tab = self.tabs.len() - 1;
}
} }
pub fn delete_tab(&mut self, index: usize) { pub fn delete_tab(&mut self, index: usize) {
self.tabs.remove(index); self.tabs.remove(index);
self.selected_tab = panels::TabNumber::from_index(min(index, self.tabs.len() - 1)); self.selected_tab = min(index, self.tabs.len() - 1);
} }
pub fn toggle(&self, ui: &mut egui::Ui, display: bool, title: &str) -> bool { pub fn toggle(&self, ui: &mut egui::Ui, display: bool, title: &str) -> bool {

View file

@ -8,7 +8,6 @@ use crate::editor;
use crate::panels; use crate::panels;
use crate::Calcifer; use crate::Calcifer;
use crate::DISPLAY_PATH_DEPTH; use crate::DISPLAY_PATH_DEPTH;
use crate::MAX_TABS;
use crate::PROJECT_EXTENSION; use crate::PROJECT_EXTENSION;
use crate::RED; use crate::RED;
use crate::TERMINAL_HEIGHT; use crate::TERMINAL_HEIGHT;
@ -43,7 +42,7 @@ impl Calcifer {
ui.separator(); ui.separator();
self.profiler_visible = self.toggle(ui, self.profiler_visible, ""); self.profiler_visible = self.toggle(ui, self.profiler_visible, "");
if self.tabs[self.selected_tab.to_index()].language == PROJECT_EXTENSION { if self.tabs[self.selected_tab].language == PROJECT_EXTENSION {
ui.separator(); ui.separator();
self.project_content.item_window.visible = self.project_content.item_window.visible =
self.toggle(ui, self.project_content.item_window.visible, "🖊"); self.toggle(ui, self.project_content.item_window.visible, "🖊");
@ -181,57 +180,6 @@ impl Calcifer {
} }
pub fn draw_tab_panel(&mut self, ctx: &egui::Context) { pub fn draw_tab_panel(&mut self, ctx: &egui::Context) {
egui::TopBottomPanel::top("tabs")
.resizable(false)
.show(ctx, |ui| {
ui.horizontal(|ui| {
ui.style_mut().visuals.selection.bg_fill =
core::hex_str_to_color(self.theme.functions);
ui.style_mut().visuals.hyperlink_color =
core::hex_str_to_color(self.theme.functions);
for (index, tab) in self.tabs.clone().iter().enumerate() {
let mut title = tab.get_name();
if !tab.saved {
title += " ~";
}
if self.selected_tab == panels::TabNumber::from_index(index) {
ui.style_mut().visuals.override_text_color =
Some(core::hex_str_to_color(self.theme.bg));
}
ui.selectable_value(
&mut self.selected_tab,
panels::TabNumber::from_index(index),
title,
);
ui.style_mut().visuals.override_text_color = None;
if ui.link("X").clicked() && !self.close_tab_confirm.visible {
if self.tabs.len() > 1 {
if tab.saved {
self.delete_tab(index);
} else {
self.close_tab_confirm.ask();
self.tab_to_close = index;
}
} else {
egui::Context::send_viewport_cmd(ctx, egui::ViewportCommand::Close);
}
}
ui.separator();
}
if self.tabs.len() < MAX_TABS {
ui.selectable_value(&mut self.selected_tab, panels::TabNumber::Open, "+");
}
if self.selected_tab == panels::TabNumber::Open {
self.open_file(None);
}
});
});
ctx.set_visuals(egui::Visuals::dark());
}
pub fn draw_alternate_tab_panel(&mut self, ctx: &egui::Context) {
egui::TopBottomPanel::top("tabs") egui::TopBottomPanel::top("tabs")
.resizable(false) .resizable(false)
.show(ctx, |ui| { .show(ctx, |ui| {
@ -247,7 +195,7 @@ impl Calcifer {
for (index, tab) in self.tabs.clone().iter().enumerate() { for (index, tab) in self.tabs.clone().iter().enumerate() {
strip.cell(|ui| { strip.cell(|ui| {
let mut color = core::hex_str_to_color(self.theme.comments); let mut color = core::hex_str_to_color(self.theme.comments);
if self.selected_tab == panels::TabNumber::from_index(index) { if self.selected_tab == index {
ui.painter().rect_filled( ui.painter().rect_filled(
ui.available_rect_before_wrap(), ui.available_rect_before_wrap(),
0.0, 0.0,
@ -256,16 +204,19 @@ impl Calcifer {
color = core::hex_str_to_color(self.theme.bg) color = core::hex_str_to_color(self.theme.bg)
} }
let unsaved_indicator = if tab.saved { "" } else { "~ " }; let unsaved_indicator = if tab.saved { "" } else { "~ " };
ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| { ui.with_layout(
egui::Layout::right_to_left(egui::Align::TOP),
|ui| {
ui.label(""); ui.label("");
if ui.add( if ui
.add(
egui::Label::new( egui::Label::new(
egui::RichText::new(" X ") egui::RichText::new(" X ").color(color),
.color(color),
) )
.sense(egui::Sense::click()), .sense(egui::Sense::click()),
) )
.clicked() && !self.close_tab_confirm.visible .clicked()
&& !self.close_tab_confirm.visible
{ {
if self.tabs.len() > 1 { if self.tabs.len() > 1 {
if tab.saved { if tab.saved {
@ -275,11 +226,17 @@ impl Calcifer {
self.tab_to_close = index; self.tab_to_close = index;
} }
} else { } else {
egui::Context::send_viewport_cmd(ctx, egui::ViewportCommand::Close); egui::Context::send_viewport_cmd(
ctx,
egui::ViewportCommand::Close,
);
} }
} }
ui.with_layout(egui::Layout::left_to_right(egui::Align::TOP), |ui| { ui.with_layout(
if ui.add( egui::Layout::left_to_right(egui::Align::TOP),
|ui| {
if ui
.add(
egui::Label::new( egui::Label::new(
egui::RichText::new(format!( egui::RichText::new(format!(
" {}{}", " {}{}",
@ -293,10 +250,12 @@ impl Calcifer {
) )
.clicked() .clicked()
{ {
self.selected_tab = panels::TabNumber::from_index(index); self.selected_tab = index;
} }
}); },
}); );
},
);
}); });
} }
strip.cell(|ui| { strip.cell(|ui| {
@ -318,14 +277,14 @@ impl Calcifer {
.add(egui::Button::new("open directory in terminal")) .add(egui::Button::new("open directory in terminal"))
.clicked() .clicked()
{ {
let mut path = self.tabs[self.selected_tab.to_index()].path.clone(); let mut path = self.tabs[self.selected_tab].path.clone();
path.pop(); path.pop();
panels::send_command(format!("cd {}", path.display())); panels::send_command(format!("cd {}", path.display()));
} }
ui.label("Picked file:"); ui.label("Picked file:");
ui.monospace( ui.monospace(
self.tabs[self.selected_tab.to_index()] self.tabs[self.selected_tab]
.path .path
.to_string_lossy() .to_string_lossy()
.to_string(), .to_string(),
@ -333,7 +292,7 @@ impl Calcifer {
}); });
ui.separator(); ui.separator();
if self.tabs[self.selected_tab.to_index()].language == PROJECT_EXTENSION { if self.tabs[self.selected_tab].language == PROJECT_EXTENSION {
self.draw_project_file(ui); self.draw_project_file(ui);
} else { } else {
self.draw_code_file(ui); self.draw_code_file(ui);
@ -342,7 +301,7 @@ impl Calcifer {
} }
fn draw_code_file(&mut self, ui: &mut egui::Ui) { fn draw_code_file(&mut self, ui: &mut egui::Ui) {
let current_tab = &mut self.tabs[self.selected_tab.to_index()]; let current_tab = &mut self.tabs[self.selected_tab];
let lines = current_tab.code.chars().filter(|&c| c == '\n').count() + 1; let lines = current_tab.code.chars().filter(|&c| c == '\n').count() + 1;
let mut override_cursor: Option<CCursorRange> = None; let mut override_cursor: Option<CCursorRange> = None;
@ -372,7 +331,7 @@ impl Calcifer {
} }
fn draw_project_file(&mut self, ui: &mut egui::Ui) { fn draw_project_file(&mut self, ui: &mut egui::Ui) {
let current_tab = &mut self.tabs[self.selected_tab.to_index()]; let current_tab = &mut self.tabs[self.selected_tab];
self.project_content self.project_content
.update_from_code(current_tab.code.clone()); .update_from_code(current_tab.code.clone());

View file

@ -27,7 +27,6 @@ const TIME_LABELS: [&str; 7] = [
]; ];
const MAX_FPS: f32 = 30.0; const MAX_FPS: f32 = 30.0;
const DISPLAY_PATH_DEPTH: usize = 3; const DISPLAY_PATH_DEPTH: usize = 3;
const MAX_TABS: usize = 20;
const MAX_PROJECT_COLUMNS: usize = 8; const MAX_PROJECT_COLUMNS: usize = 8;
const RUNNING_COMMAND_REFRESH_DELAY: f32 = 0.1; const RUNNING_COMMAND_REFRESH_DELAY: f32 = 0.1;
@ -59,7 +58,7 @@ fn main() -> Result<(), eframe::Error> {
} }
struct Calcifer { struct Calcifer {
selected_tab: panels::TabNumber, selected_tab: usize,
tabs: Vec<panels::Tab>, tabs: Vec<panels::Tab>,
command: String, command: String,
@ -96,7 +95,7 @@ struct Calcifer {
impl Default for Calcifer { impl Default for Calcifer {
fn default() -> Self { fn default() -> Self {
Self { Self {
selected_tab: panels::TabNumber::from_index(0), selected_tab: 0,
tabs: vec![panels::Tab::default()], tabs: vec![panels::Tab::default()],
command: String::new(), command: String::new(),
@ -170,15 +169,15 @@ impl eframe::App for Calcifer {
if ctx.input(|i| i.key_pressed(egui::Key::R) && i.modifiers.ctrl) if ctx.input(|i| i.key_pressed(egui::Key::R) && i.modifiers.ctrl)
&& !self.refresh_confirm.visible && !self.refresh_confirm.visible
{ {
if self.tabs[self.selected_tab.to_index()].saved { if self.tabs[self.selected_tab].saved {
self.tabs[self.selected_tab.to_index()].refresh(); self.tabs[self.selected_tab].refresh();
} else { } else {
self.refresh_confirm.ask(); self.refresh_confirm.ask();
} }
} }
if ctx.input(|i| i.key_pressed(egui::Key::Enter)) if ctx.input(|i| i.key_pressed(egui::Key::Enter))
&& self.tabs[self.selected_tab.to_index()].language == PROJECT_EXTENSION && self.tabs[self.selected_tab].language == PROJECT_EXTENSION
{ {
self.project_content.item_window.visible = true; self.project_content.item_window.visible = true;
} }
@ -252,8 +251,7 @@ impl eframe::App for Calcifer {
self.time_watch[3] = watch.elapsed().as_micros() as f32 / 1000.0; self.time_watch[3] = watch.elapsed().as_micros() as f32 / 1000.0;
watch = time::Instant::now(); watch = time::Instant::now();
//self.draw_tab_panel(ctx); self.draw_tab_panel(ctx);
self.draw_alternate_tab_panel(ctx);
self.time_watch[4] = watch.elapsed().as_micros() as f32 / 1000.0; self.time_watch[4] = watch.elapsed().as_micros() as f32 / 1000.0;
watch = time::Instant::now(); watch = time::Instant::now();

View file

@ -1,30 +1,6 @@
use eframe::egui::text_edit::CCursorRange; use eframe::egui::text_edit::CCursorRange;
use std::{fs::read_to_string, path::Path, path::PathBuf}; use std::{fs::read_to_string, path::Path, path::PathBuf};
use crate::MAX_TABS;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum TabNumber {
Open,
Number(u8), // Using a range for numeric values
}
impl TabNumber {
pub fn from_index(n: usize) -> TabNumber {
match n {
0..=MAX_TABS => TabNumber::Number(n as u8),
_ => TabNumber::Number(0),
}
}
pub fn to_index(&self) -> usize {
match self {
TabNumber::Number(n) => *n as usize,
_ => 0,
}
}
}
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct Tab { pub struct Tab {
pub path: PathBuf, pub path: PathBuf,

View file

@ -1,7 +1,7 @@
use eframe::egui; use eframe::egui;
use std::cmp::min; use std::cmp::min;
use crate::panels::{Tab, TabNumber}; use crate::panels::Tab;
use crate::RED; use crate::RED;
enum Action { enum Action {
@ -12,23 +12,13 @@ enum Action {
None, None,
} }
#[derive(Clone)] #[derive(Clone, Default)]
pub struct Selection { pub struct Selection {
pub tab: TabNumber, pub tab: usize,
pub start: usize, pub start: usize,
pub end: usize, pub end: usize,
} }
impl Default for Selection {
fn default() -> Self {
Self {
tab: TabNumber::from_index(0),
start: 0,
end: 0,
}
}
}
pub struct SearchWindow { pub struct SearchWindow {
pub visible: bool, pub visible: bool,
@ -72,7 +62,7 @@ impl Default for SearchWindow {
} }
impl SearchWindow { impl SearchWindow {
pub fn show(&mut self, ctx: &egui::Context, tabs: &mut Vec<Tab>, selected_tab: &mut TabNumber) { pub fn show(&mut self, ctx: &egui::Context, tabs: &mut Vec<Tab>, selected_tab: &mut usize) {
let mut visible = self.visible; let mut visible = self.visible;
egui::Window::new("Search") egui::Window::new("Search")
.open(&mut visible) //I want it to be able to change its visibility (if user close manually) .open(&mut visible) //I want it to be able to change its visibility (if user close manually)
@ -82,7 +72,7 @@ impl SearchWindow {
self.visible = self.visible && visible; self.visible = self.visible && visible;
} }
fn ui(&mut self, ui: &mut egui::Ui, tabs: &mut Vec<Tab>, selected_tab: &mut TabNumber) { fn ui(&mut self, ui: &mut egui::Ui, tabs: &mut Vec<Tab>, selected_tab: &mut usize) {
ui.set_min_width(250.0); ui.set_min_width(250.0);
let font_id = egui::TextStyle::Body.resolve(ui.style()); let font_id = egui::TextStyle::Body.resolve(ui.style());
@ -171,7 +161,7 @@ impl SearchWindow {
self.results[self.current_result].end self.results[self.current_result].end
} }
fn search(&mut self, tabs: &mut Vec<Tab>, selected_tab: &mut TabNumber) { fn search(&mut self, tabs: &mut Vec<Tab>, selected_tab: &mut usize) {
if self.search_text.is_empty() { if self.search_text.is_empty() {
return; return;
} }
@ -180,14 +170,10 @@ impl SearchWindow {
if self.across_documents { if self.across_documents {
for (index, tab) in tabs.iter().enumerate() { for (index, tab) in tabs.iter().enumerate() {
search_results search_results.extend(self.match_text(tab.code.clone(), index));
.extend(self.match_text(tab.code.clone(), TabNumber::from_index(index)));
} }
} else { } else {
search_results.extend(self.match_text( search_results.extend(self.match_text(tabs[*selected_tab].code.clone(), *selected_tab));
tabs[selected_tab.to_index()].code.clone(),
selected_tab.clone(),
));
} }
self.searched_text = self.search_text.clone(); self.searched_text = self.search_text.clone();
@ -199,11 +185,11 @@ impl SearchWindow {
} }
} }
fn match_text(&self, tab_text: String, tab_number: TabNumber) -> Vec<Selection> { fn match_text(&self, tab_text: String, tab_number: usize) -> Vec<Selection> {
let matches = tab_text let matches = tab_text
.match_indices(&self.search_text.clone()) .match_indices(&self.search_text.clone())
.map(|(i, _)| Selection { .map(|(i, _)| Selection {
tab: tab_number.clone(), tab: tab_number,
start: i, start: i,
end: i + self.search_text.len(), end: i + self.search_text.len(),
}) })
@ -212,7 +198,7 @@ impl SearchWindow {
matches matches
} }
fn find_result(&mut self, tabs: &mut Vec<Tab>, selected_tab: &mut TabNumber, direction: i32) { fn find_result(&mut self, tabs: &mut Vec<Tab>, selected_tab: &mut usize, direction: i32) {
if self.searched_text != self.search_text { if self.searched_text != self.search_text {
self.search(tabs, &mut *selected_tab); self.search(tabs, &mut *selected_tab);
} else if !self.results.is_empty() { } else if !self.results.is_empty() {
@ -220,33 +206,32 @@ impl SearchWindow {
(self.current_result as i32 + direction + self.results.len() as i32) as usize (self.current_result as i32 + direction + self.results.len() as i32) as usize
% self.results.len(); % self.results.len();
self.result_selected = false; self.result_selected = false;
*selected_tab = self.results[self.current_result].tab.clone(); *selected_tab = self.results[self.current_result].tab;
let target = self.results[self.current_result].start; let target = self.results[self.current_result].start;
let code = tabs[selected_tab.to_index()].code.clone(); let code = tabs[*selected_tab].code.clone();
let (upstream, _downstream) = code.split_at(target); let (upstream, _downstream) = code.split_at(target);
let row = upstream let row = upstream
.match_indices(&"\n".to_string()) .match_indices(&"\n".to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.len(); .len();
tabs[selected_tab.to_index()].scroll_offset = tabs[*selected_tab].scroll_offset = self.row_height * row.saturating_sub(5) as f32;
self.row_height * row.saturating_sub(5) as f32;
} }
} }
fn replace(&mut self, tabs: &mut Vec<Tab>, selected_tab: &mut TabNumber) { fn replace(&mut self, tabs: &mut Vec<Tab>, selected_tab: &mut usize) {
self.search(tabs, &mut *selected_tab); self.search(tabs, &mut *selected_tab);
let mut done: Vec<TabNumber> = vec![]; let mut done: Vec<usize> = vec![];
for element in &self.results { for element in &self.results {
if done.contains(&element.tab) { if done.contains(&element.tab) {
continue; continue;
} }
tabs[element.tab.to_index()].code = tabs[element.tab.to_index()] tabs[element.tab].code = tabs[element.tab]
.code .code
.replace(&self.search_text, &self.replace_text); .replace(&self.search_text, &self.replace_text);
tabs[element.tab.to_index()].saved = false; tabs[element.tab].saved = false;
done.push(element.tab.clone()) done.push(element.tab)
} }
} }
} }