fixed zoom and tree, + working with nix

This commit is contained in:
WanderingPenwing 2024-03-22 18:01:43 +01:00
parent 716a5eb3fa
commit f4a62c9c32
8 changed files with 391 additions and 310 deletions

29
project/calcifer.nix Normal file
View file

@ -0,0 +1,29 @@
{ pkgs ? import <nixpkgs> {} }:
pkgs.stdenv.mkDerivation rec {
pname = "Calcifer";
version = "1.0";
src = pkgs.fetchFromGitHub {
owner = "WanderingPenwing";
repo = "Calcifer";
rev = "v${version}";
sha256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
};
buildInputs = [ pkgs.rustc pkgs.cargo ];
nativeBuildInputs = [ pkgs.pkg-config ];
cargoSha256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
installPhase = ''
cargo install --path . --root $out
'';
meta = with pkgs.stdenv.lib; {
description = "MyApp - A simple desktop application written in Rust";
homepage = "https://github.com/your-github-username/myapp";
license = licenses.mit;
maintainers = [ maintainers.your-name ];s
};
}

38
shell.nix Normal file
View file

@ -0,0 +1,38 @@
{ pkgs ? import <nixpkgs> { overlays = [ (import (builtins.fetchTarball https://github.com/mozilla/nixpkgs-mozilla/archive/master.tar.gz)) ]; },}:
with pkgs;
mkShell {
nativeBuildInputs = with xorg; [
libxcb
libXcursor
libXrandr
libXi
pkg-config
] ++ [
cargo
rustc
atk
gdk-pixbuf
webkitgtk
glib
libGL
libGLU
libxkbcommon
gtk3-x11
gnome.zenity
];
buildInputs = [
latest.rustChannels.stable.rust
xorg.libX11
wayland
libxkbcommon
python3Packages.virtualenv
python3Packages.plyer
python3Packages.pygobject3
python3Packages.pillow
];
shellHook = ''
export LD_LIBRARY_PATH=/run/opengl-driver/lib/:${lib.makeLibraryPath ([libGL libGLU libxkbcommon])}
'';
}

View file

@ -11,215 +11,221 @@ use crate::Calcifer;
use crate::TIME_LABELS; use crate::TIME_LABELS;
impl Calcifer { impl Calcifer {
pub fn handle_confirm(&mut self) { pub fn handle_confirm(&mut self) {
if self.close_tab_confirm.proceed { if self.close_tab_confirm.proceed {
self.close_tab_confirm.close(); self.close_tab_confirm.close();
self.delete_tab(self.tab_to_close); self.delete_tab(self.tab_to_close);
} }
if self.refresh_confirm.proceed { if self.refresh_confirm.proceed {
self.refresh_confirm.close(); self.refresh_confirm.close();
self.tabs[self.selected_tab].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] 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")
{ {
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].path, &self.tabs[self.selected_tab].path,
&self.tabs[self.selected_tab].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].path.clone()) Some(self.tabs[self.selected_tab].path.clone())
} }
} }
pub fn save_tab_as(&self) -> Option<PathBuf> { pub fn save_tab_as(&self) -> Option<PathBuf> {
if let Some(path) = rfd::FileDialog::new() if let Some(path) = rfd::FileDialog::new()
.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].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;
} }
return Some(path); return Some(path);
} }
None None
} }
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].path = path; self.tabs[self.selected_tab].path = path;
self.tabs[self.selected_tab].saved = true; self.tabs[self.selected_tab].saved = true;
} else { } else {
println!("File save failed."); println!("File save failed.");
} }
} }
pub fn from_app_state(app_state: core::AppState) -> Self { pub fn from_app_state(app_state: core::AppState) -> Self {
let mut new = Self { let mut new = Self {
theme: DEFAULT_THEMES[min(app_state.theme, DEFAULT_THEMES.len() - 1)], theme: DEFAULT_THEMES[min(app_state.theme, DEFAULT_THEMES.len() - 1)],
tabs: Vec::new(), tabs: Vec::new(),
settings_menu: sub_windows::SettingsWindow::new(DEFAULT_THEMES[app_state.theme]), settings_menu: sub_windows::SettingsWindow::new(DEFAULT_THEMES[app_state.theme]),
..Default::default() ..Default::default()
}; };
for path in app_state.tabs { println!("zoom : {}", app_state.zoom.clone());
if !path if app_state.zoom != 0.0 {
.file_name() new.zoom = app_state.zoom;
.map_or(true, |name| name.to_string_lossy() == "untitled") }
{
new.open_file(Some(&path));
}
}
if new.tabs == vec![] { for path in app_state.tabs {
new.open_file(None); if !path
} .file_name()
.map_or(true, |name| name.to_string_lossy() == "untitled")
{
new.open_file(Some(&path));
}
}
new if new.tabs == vec![] {
} new.open_file(None);
}
pub fn save_state(&self) { new
let mut state_theme: usize = 0; }
if let Some(theme) = DEFAULT_THEMES.iter().position(|&r| r == self.theme) {
state_theme = theme;
}
let mut state_tabs = vec![]; pub fn save_state(&self) {
let mut state_theme: usize = 0;
if let Some(theme) = DEFAULT_THEMES.iter().position(|&r| r == self.theme) {
state_theme = theme;
}
for tab in &self.tabs { let mut state_tabs = vec![];
state_tabs.push(tab.path.clone());
}
let app_state = core::AppState {
tabs: state_tabs,
theme: state_theme,
};
let _ = core::save_state(&app_state, save_path().as_path()); for tab in &self.tabs {
} state_tabs.push(tab.path.clone());
}
let app_state = core::AppState {
tabs: state_tabs,
theme: state_theme,
zoom: self.zoom,
};
pub fn move_through_tabs(&mut self, forward: bool) { let _ = core::save_state(&app_state, save_path().as_path());
let new_index = if forward { }
(self.selected_tab + 1) % self.tabs.len()
} else {
self.selected_tab
.checked_sub(1)
.unwrap_or(self.tabs.len() - 1)
};
self.selected_tab = new_index;
}
pub fn open_file(&mut self, path_option: Option<&Path>) { pub fn move_through_tabs(&mut self, forward: bool) {
if let Some(path) = path_option { let new_index = if forward {
for (index, tab) in self.tabs.clone().iter().enumerate() { (self.selected_tab + 1) % self.tabs.len()
if tab.path == path { } else {
self.selected_tab = index; self.selected_tab
return; .checked_sub(1)
} .unwrap_or(self.tabs.len() - 1)
} };
} self.selected_tab = new_index;
if let Some(path) = path_option { }
self.tabs.push(panels::Tab::new(path.to_path_buf()));
} else {
self.tabs.push(panels::Tab::default());
}
self.selected_tab = self.tabs.len() - 1;
}
pub fn delete_tab(&mut self, index: usize) { pub fn open_file(&mut self, path_option: Option<&Path>) {
self.tabs.remove(index); if let Some(path) = path_option {
self.selected_tab = min(index, self.tabs.len() - 1); for (index, tab) in self.tabs.clone().iter().enumerate() {
} if tab.path == path {
self.selected_tab = index;
return;
}
}
}
if let Some(path) = path_option {
self.tabs.push(panels::Tab::new(path.to_path_buf()));
} else {
self.tabs.push(panels::Tab::default());
}
self.selected_tab = self.tabs.len() - 1;
}
pub fn toggle(&self, ui: &mut egui::Ui, display: bool, title: &str) -> bool { pub fn delete_tab(&mut self, index: usize) {
let bg_color: Color32; self.tabs.remove(index);
let text_color: Color32; self.selected_tab = min(index, self.tabs.len() - 1);
}
if display { pub fn toggle(&self, ui: &mut egui::Ui, display: bool, title: &str) -> bool {
bg_color = hex_str_to_color(self.theme.functions); let bg_color: Color32;
text_color = hex_str_to_color(self.theme.bg); let text_color: Color32;
} else {
bg_color = hex_str_to_color(self.theme.bg);
text_color = hex_str_to_color(self.theme.literals);
};
ui.style_mut().visuals.override_text_color = Some(text_color); if display {
bg_color = hex_str_to_color(self.theme.functions);
text_color = hex_str_to_color(self.theme.bg);
} else {
bg_color = hex_str_to_color(self.theme.bg);
text_color = hex_str_to_color(self.theme.literals);
};
if ui.add(egui::Button::new(title).fill(bg_color)).clicked() { ui.style_mut().visuals.override_text_color = Some(text_color);
return !display;
}
ui.style_mut().visuals.override_text_color = None;
display if ui.add(egui::Button::new(title).fill(bg_color)).clicked() {
} return !display;
}
ui.style_mut().visuals.override_text_color = None;
pub fn profiler(&self) -> String { display
if !self.profiler_visible { }
return "".to_string();
}
let combined_string: Vec<String> = TIME_LABELS
.into_iter()
.zip(self.time_watch.clone())
.map(|(s, v)| format!("{} : {:.1} ms", s, v))
.collect();
let mut result = combined_string.join(" ; "); pub fn profiler(&self) -> String {
result.push_str(&format!( if !self.profiler_visible {
" total : {:.1} ms", return "".to_string();
self.time_watch.clone().iter().sum::<f32>() }
)); let combined_string: Vec<String> = TIME_LABELS
result .into_iter()
} .zip(self.time_watch.clone())
.map(|(s, v)| format!("{} : {:.1} ms", s, v))
.collect();
pub fn list_files( let mut result = combined_string.join(" ; ");
&mut self, result.push_str(&format!(
ui: &mut egui::Ui, " total : {:.1} ms",
file: &panels::FileEntry, self.time_watch.clone().iter().sum::<f32>()
n_files: &mut usize, ));
) -> bool { result
*n_files += 1; }
if let Some(folder_content) = &file.folder_content { pub fn list_files(
let mut check_for_update: bool = false; &mut self,
let collapsing_response = egui::CollapsingHeader::new(file.name.clone()) ui: &mut egui::Ui,
.default_open(self.tree_dir_opened.contains(&file.name)) file: &panels::FileEntry,
.show(ui, |ui| { n_files: &mut usize,
if !self.tree_dir_opened.contains(&file.name) { ) -> bool {
return; *n_files += 1;
}
for deeper_file in folder_content {
if self.list_files(ui, deeper_file, n_files) {
check_for_update = true;
}
}
});
if collapsing_response.fully_closed() {
self.tree_dir_opened.retain(|s| s != &file.name);
} else if !self.tree_dir_opened.contains(&file.name) {
self.tree_dir_opened.push(file.name.clone());
return !file.content_checked;
}
return check_for_update;
} else if ui.button(&file.name).clicked() {
self.open_file(Some(&file.path));
}
false if let Some(folder_content) = &file.folder_content {
} let mut check_for_update: bool = false;
let collapsing_response = egui::CollapsingHeader::new(file.name.clone())
.default_open(self.tree_dir_opened.contains(&file.name))
.show(ui, |ui| {
if !self.tree_dir_opened.contains(&file.name) {
return;
}
for deeper_file in folder_content {
if self.list_files(ui, deeper_file, n_files) {
check_for_update = true;
}
}
});
if collapsing_response.fully_closed() {
self.tree_dir_opened.retain(|s| s != &file.name);
} else if !self.tree_dir_opened.contains(&file.name) {
self.tree_dir_opened.push(file.name.clone());
return !file.content_checked;
}
return check_for_update;
} else if ui.button(&file.name).clicked() {
self.open_file(Some(&file.path));
}
false
}
} }
#[allow(clippy::unnecessary_lazy_evaluations)] #[allow(clippy::unnecessary_lazy_evaluations)]
pub fn hex_str_to_color(hex_str: &str) -> Color32 { pub fn hex_str_to_color(hex_str: &str) -> Color32 {
Color32::from_hex(hex_str).unwrap_or_else(|_| Color32::BLACK) Color32::from_hex(hex_str).unwrap_or_else(|_| Color32::BLACK)
} }

View file

@ -14,6 +14,7 @@ use serde::Deserialize;
pub struct AppState { pub struct AppState {
pub tabs: Vec<PathBuf>, pub tabs: Vec<PathBuf>,
pub theme: usize, pub theme: usize,
pub zoom: f32,
} }
pub fn save_state(state: &AppState, file_path: &Path) -> Result<(), std::io::Error> { pub fn save_state(state: &AppState, file_path: &Path) -> Result<(), std::io::Error> {

View file

@ -191,7 +191,7 @@ impl Calcifer {
core::hex_str_to_color(self.theme.bg), core::hex_str_to_color(self.theme.bg),
); );
StripBuilder::new(ui) StripBuilder::new(ui)
.sizes(Size::remainder(), max(10, self.tabs.len() + 1)) .sizes(Size::remainder(), max(6, self.tabs.len() + 1))
.sense(egui::Sense::click()) .sense(egui::Sense::click())
.horizontal(|mut strip| { .horizontal(|mut strip| {
for (index, tab) in self.tabs.clone().iter().enumerate() { for (index, tab) in self.tabs.clone().iter().enumerate() {

View file

@ -17,7 +17,7 @@ const TITLE: &str = " debug";
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
const TITLE: &str = ""; const TITLE: &str = "";
const ALLOWED_FILE_EXTENSIONS: [&str; 13] = ["", "rs", "toml", "txt", "project", "sh", "md", "html", "js", "css", "php", "py", "kv"]; //const ALLOWED_FILE_EXTENSIONS: [&str; 14] = ["", "rs", "toml", "txt", "project", "sh", "md", "html", "js", "css", "php", "py", "kv", "nix"];
const PROJECT_EXTENSION: &str = "project"; const PROJECT_EXTENSION: &str = "project";
const TERMINAL_HEIGHT: f32 = 200.0; const TERMINAL_HEIGHT: f32 = 200.0;
const TERMINAL_RANGE: Range<f32> = 100.0..600.0; const TERMINAL_RANGE: Range<f32> = 100.0..600.0;
@ -25,6 +25,7 @@ const RED: egui::Color32 = egui::Color32::from_rgb(235, 108, 99);
const TIME_LABELS: [&str; 7] = [ const TIME_LABELS: [&str; 7] = [
"input", "settings", "tree", "terminal", "tabs", "content", "windows", "input", "settings", "tree", "terminal", "tabs", "content", "windows",
]; ];
const ZOOM_FACTOR: f32 = 1.1;
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_PROJECT_COLUMNS: usize = 8; const MAX_PROJECT_COLUMNS: usize = 8;
@ -67,6 +68,7 @@ struct Calcifer {
theme: editor::ColorTheme, theme: editor::ColorTheme,
font_size: f32, font_size: f32,
zoom: f32,
project_content: panels::Project, project_content: panels::Project,
@ -104,6 +106,7 @@ impl Default for Calcifer {
theme: editor::themes::DEFAULT_THEMES[0], theme: editor::themes::DEFAULT_THEMES[0],
font_size: 14.0, font_size: 14.0,
zoom: 1.0,
project_content: panels::Project::new(), project_content: panels::Project::new(),
@ -166,6 +169,10 @@ impl eframe::App for Calcifer {
.into(); .into();
ctx.set_style(style); ctx.set_style(style);
if ctx.zoom_factor() != self.zoom {
ctx.set_zoom_factor(self.zoom);
}
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
{ {
@ -204,11 +211,11 @@ impl eframe::App for Calcifer {
} }
if ctx.input(|i| i.zoom_delta() > 1.0) { if ctx.input(|i| i.zoom_delta() > 1.0) {
self.font_size = (self.font_size * 1.1).min(30.0); self.zoom = (self.zoom*ZOOM_FACTOR).min(10.0);
} }
if ctx.input(|i| i.zoom_delta() < 1.0) { if ctx.input(|i| i.zoom_delta() < 1.0) {
self.font_size = (self.font_size / 1.1).max(10.0); self.zoom = (self.zoom/ZOOM_FACTOR).max(0.1);
} }
if ctx.input(|i| i.key_pressed(egui::Key::F) && i.modifiers.ctrl) { if ctx.input(|i| i.key_pressed(egui::Key::F) && i.modifiers.ctrl) {

View file

@ -1,154 +1,154 @@
use std::{ use std::{
cmp::Ordering, cmp::Ordering,
ffi::OsStr, ffi::OsStr,
fs, io, fs, io,
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use crate::ALLOWED_FILE_EXTENSIONS; //use crate::ALLOWED_FILE_EXTENSIONS;
#[derive(Clone)] #[derive(Clone)]
pub struct FileEntry { pub struct FileEntry {
pub name: String, pub name: String,
pub path: PathBuf, pub path: PathBuf,
pub folder_content: Option<Vec<FileEntry>>, pub folder_content: Option<Vec<FileEntry>>,
pub content_checked: bool, pub content_checked: bool,
} }
impl FileEntry { impl FileEntry {
pub fn new_entry(name: String, path: PathBuf) -> Self { pub fn new_entry(name: String, path: PathBuf) -> Self {
Self { Self {
name, name,
path, path,
folder_content: None, folder_content: None,
content_checked: true, content_checked: true,
} }
} }
pub fn end_of_branch(name: String, path: PathBuf) -> Self { pub fn end_of_branch(name: String, path: PathBuf) -> Self {
Self { Self {
name, name,
path, path,
folder_content: Some(vec![]), folder_content: Some(vec![]),
content_checked: false, content_checked: false,
} }
} }
} }
pub fn update_file_tree(file: FileEntry, opened_dirs: Vec<String>) -> FileEntry { pub fn update_file_tree(file: FileEntry, opened_dirs: Vec<String>) -> FileEntry {
if opened_dirs.contains(&file.name) { if opened_dirs.contains(&file.name) {
if let Some(folder_content) = &file.folder_content { if let Some(folder_content) = &file.folder_content {
if !file.content_checked { if !file.content_checked {
return generate_folder_entry(&file.path); return generate_folder_entry(&file.path);
} }
let updated_content: Vec<FileEntry> = folder_content let updated_content: Vec<FileEntry> = folder_content
.iter() .iter()
.map(|entry| update_file_tree(entry.clone(), opened_dirs.clone())) .map(|entry| update_file_tree(entry.clone(), opened_dirs.clone()))
.collect(); .collect();
FileEntry { FileEntry {
name: file.name, name: file.name,
path: file.path, path: file.path,
folder_content: Some(updated_content), folder_content: Some(updated_content),
content_checked: true, content_checked: true,
} }
} else { } else {
file file
} }
} else { } else {
file file
} }
} }
pub fn generate_folder_entry(path: &Path) -> FileEntry { pub fn generate_folder_entry(path: &Path) -> FileEntry {
if let Some(file_name) = path.file_name() { if let Some(file_name) = path.file_name() {
let name = file_name.to_string_lossy().into_owned(); let name = file_name.to_string_lossy().into_owned();
match fs::read_dir(path) { match fs::read_dir(path) {
Err(err) => FileEntry::new_entry( Err(err) => FileEntry::new_entry(
format!("Error reading directory: {}", err), format!("Error reading directory: {}", err),
path.to_path_buf(), path.to_path_buf(),
), ),
Ok(entries) => { Ok(entries) => {
let mut paths: Vec<Result<fs::DirEntry, io::Error>> = entries let mut paths: Vec<Result<fs::DirEntry, io::Error>> = entries
.map(|r| r.map_err(|e| io::Error::new(io::ErrorKind::Other, e))) .map(|r| r.map_err(|e| io::Error::new(io::ErrorKind::Other, e)))
.collect(); .collect();
paths.sort_by(|a, b| match (a, b) { paths.sort_by(|a, b| match (a, b) {
(Ok(entry_a), Ok(entry_b)) => sort_directories_first(entry_a, entry_b), (Ok(entry_a), Ok(entry_b)) => sort_directories_first(entry_a, entry_b),
(Err(_), Ok(_)) => std::cmp::Ordering::Greater, (Err(_), Ok(_)) => std::cmp::Ordering::Greater,
(Ok(_), Err(_)) => std::cmp::Ordering::Less, (Ok(_), Err(_)) => std::cmp::Ordering::Less,
(Err(_), Err(_)) => std::cmp::Ordering::Equal, (Err(_), Err(_)) => std::cmp::Ordering::Equal,
}); });
let mut folder_content = Vec::new(); let mut folder_content = Vec::new();
for result in paths { for result in paths {
match result { match result {
Ok(entry) => { Ok(entry) => {
if let Some(file) = generate_entry(&entry.path()) { if let Some(file) = generate_entry(&entry.path()) {
folder_content.push(file); folder_content.push(file);
} }
} }
Err(err) => { Err(err) => {
folder_content.push(FileEntry::new_entry( folder_content.push(FileEntry::new_entry(
format!("Error reading entry: {}", err), format!("Error reading entry: {}", err),
path.to_path_buf(), path.to_path_buf(),
)); ));
} }
} }
} }
FileEntry { FileEntry {
name, name,
path: path.to_path_buf(), path: path.to_path_buf(),
folder_content: Some(folder_content), folder_content: Some(folder_content),
content_checked: true, content_checked: true,
} }
} }
} }
} else { } else {
FileEntry::new_entry( FileEntry::new_entry(
"Error reading directory name".to_string(), "Error reading directory name".to_string(),
path.to_path_buf(), path.to_path_buf(),
) )
} }
} }
fn generate_entry(path: &Path) -> Option<FileEntry> { fn generate_entry(path: &Path) -> Option<FileEntry> {
if let Some(file_name) = path.file_name() { if let Some(file_name) = path.file_name() {
if file_name.to_string_lossy().starts_with('.') { if file_name.to_string_lossy().starts_with('.') {
return None; return None;
} }
let extension = path.extension().and_then(|ext| ext.to_str()); // let extension = path.extension().and_then(|ext| ext.to_str());
if !ALLOWED_FILE_EXTENSIONS.contains(&extension.unwrap_or_default()) { // if !ALLOWED_FILE_EXTENSIONS.contains(&extension.unwrap_or_default()) {
return None; // return None;
} // }
} else { } else {
return None; return None;
} }
let name = path let name = path
.file_name() .file_name()
.unwrap_or_else(|| OsStr::new("")) .unwrap_or_else(|| OsStr::new(""))
.to_string_lossy() .to_string_lossy()
.into_owned(); .into_owned();
if !path.is_dir() { if !path.is_dir() {
return Some(FileEntry::new_entry(name, path.to_path_buf())); return Some(FileEntry::new_entry(name, path.to_path_buf()));
} }
Some(FileEntry::end_of_branch(name, path.to_path_buf())) Some(FileEntry::end_of_branch(name, path.to_path_buf()))
} }
fn sort_directories_first(a: &std::fs::DirEntry, b: &std::fs::DirEntry) -> Ordering { fn sort_directories_first(a: &std::fs::DirEntry, b: &std::fs::DirEntry) -> Ordering {
let a_is_dir = a.path().is_dir(); let a_is_dir = a.path().is_dir();
let b_is_dir = b.path().is_dir(); let b_is_dir = b.path().is_dir();
// Directories come first, then files // Directories come first, then files
if a_is_dir && !b_is_dir { if a_is_dir && !b_is_dir {
Ordering::Less Ordering::Less
} else if !a_is_dir && b_is_dir { } else if !a_is_dir && b_is_dir {
Ordering::Greater Ordering::Greater
} else { } else {
// Both are either directories or files, sort alphabetically // Both are either directories or files, sort alphabetically
a.path().cmp(&b.path()) a.path().cmp(&b.path())
} }
} }