22 Commits

Author SHA1 Message Date
514c55367e typo 2026-03-13 21:32:58 -04:00
22dc9b0165 Fix badge links. 2026-03-13 21:19:07 -04:00
234e6a168e Add mirror badges. 2026-03-13 21:17:50 -04:00
ae5d1c7e22 Align tui and gui menubars. 2026-03-13 17:46:15 -04:00
a92844b8e5 Add syntax highlighter. 2026-02-28 23:00:01 -05:00
7a0b2d197f Fix logger scrolling. 2026-02-28 21:45:42 -05:00
a9564493cb Remove unused fonts. 2026-02-28 20:10:11 -05:00
dd11aeca54 Format. 2026-02-28 19:51:11 -05:00
3473eeb529 Public export for Loggable derive. 2026-02-22 23:04:08 -05:00
fed1d43ac9 Loggable trait and derive macro. 2026-02-22 21:56:32 -05:00
b0ed2e6e1f Move icon helper. 2026-02-22 21:56:32 -05:00
2e67c01377 Add icons to TUI. 2026-02-22 21:56:32 -05:00
5b356781ba Fix comments. 2026-02-22 21:56:32 -05:00
be969ef335 Add macros for logging. 2026-02-22 21:56:32 -05:00
c21ede292c Share colors for GUI and TUI.
The shim is there but it isn't used yet.
2026-02-22 21:56:32 -05:00
11fd130171 Update CI badge. 2026-02-22 21:56:32 -05:00
65242c2ea9 Add workspace dependencies. 2026-02-22 21:56:32 -05:00
73c467e19e Renames. 2026-02-22 21:56:32 -05:00
8fd0bb48de Set up workspace, add formatting CI. 2026-02-22 21:56:32 -05:00
d5671a5590 Fix clide lints. 2026-02-22 21:56:32 -05:00
7490e36a2f Fix libclide lints. 2026-02-22 21:56:32 -05:00
0e8910807e Add CI. 2026-02-22 21:56:19 -05:00
32 changed files with 385 additions and 215 deletions

View File

@@ -26,6 +26,9 @@ jobs:
- name: Build libclide
run: |
cargo b -p libclide --release
- name: Build libclide-macros
run: |
cargo b -p libclide-macros --release
- name: Build clide
run: |
cargo b --release
@@ -44,6 +47,9 @@ jobs:
- name: Test libclide
run: |
cargo test -p libclide
- name: Test libclide-macros
run: |
cargo test -p libclide-macros
- name: Test clide
run: |
cargo test
@@ -62,6 +68,9 @@ jobs:
- name: Lint libclide
run: |
cargo clippy -p libclide -- -D warnings
- name: Lint libclide-macros
run: |
cargo clippy -p libclide-macros -- -D warnings
- name: Lint clide
run: |
cargo clippy -- -D warnings
@@ -80,6 +89,9 @@ jobs:
- name: Format libclide
run: |
cargo fmt -p libclide --verbose -- --check
- name: Format libclide-macros
run: |
cargo fmt -p libclide-macros -- --check
- name: Format clide
run: |
cargo fmt --verbose -- --check

14
Cargo.lock generated
View File

@@ -299,6 +299,7 @@ dependencies = [
"dirs",
"edtui",
"libclide",
"libclide-macros",
"log",
"ratatui",
"strum",
@@ -1169,7 +1170,20 @@ name = "libclide"
version = "0.1.0"
dependencies = [
"anyhow",
"devicons",
"libclide-macros",
"log",
"strum",
"syntect",
]
[[package]]
name = "libclide-macros"
version = "0.1.0"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]

View File

@@ -5,20 +5,18 @@ edition = "2024"
[workspace]
resolver = "3"
members = [
".",
"libclide",
]
members = [".", "libclide", "libclide-macros", ]
[workspace.dependencies]
anyhow = "1.0.100"
strum = "0.27.2"
log = { version = "0.4.27", features = [] }
devicons = "0.6.12"
[dependencies]
cxx = "1.0.95"
cxx-qt = "0.8.0"
cxx-qt-lib = { version = "0.8.0", features = ["qt_full", "qt_gui", "qt_qml"] }
log = { version = "0.4.27", features = [] }
dirs = "6.0.0"
syntect = "5.2.0"
clap = { version = "4.5.54", features = ["derive"] }
@@ -26,11 +24,13 @@ ratatui = "0.30.0"
tui-tree-widget = "0.24.0"
tui-logger = "0.18.1"
edtui = "0.11.1"
devicons = "0.6.12"
libclide = { path = "./libclide" }
libclide-macros = { path = "./libclide-macros" }
anyhow = { workspace = true }
strum = { workspace = true }
log = { workspace = true }
devicons = { workspace = true }
[build-dependencies]
# The link_qt_object_files feature is required for statically linking Qt 6.
cxx-qt-build = { version = "0.8.0", features = ["link_qt_object_files"] }
cxx-qt-build = { version = "0.8.0", features = ["link_qt_object_files"] }

View File

@@ -1,4 +1,7 @@
# CLIDE
[![Github](https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white)](https://github.com/shaunrd0/clide)
[![Gitlab](https://img.shields.io/badge/GitLab-330F63?style=for-the-badge&logo=gitlab&logoColor=white)](https://gitlab.com/shaunrd0/clide)
[![Gitea](https://img.shields.io/badge/Gitea-609926?style=for-the-badge&logo=gitea&logoColor=white)](https://git.shaunreed.com/shaunrd0/clide)
[![Check](https://github.com/shaunrd0/clide/actions/workflows/check.yaml/badge.svg)](https://github.com/shaunrd0/clide/actions/workflows/check.yaml)
@@ -38,7 +41,7 @@ export QMAKE=$HOME/Qt/6.7.3/gcc_64/bin/qmake6
export LD_LIBRARY_PATH=$HOME/Qt/6.7.3/gcc_64/lib
```
Though environment variables set using `export` will take precedence, these can also be set in [.cargo/config.toml](./.cargo/config.toml) for conveinence
Though environment variables set using `export` will take precedence, these can also be set in [.cargo/config.toml](./.cargo/config.toml) for convenience
```toml
[env]

View File

@@ -0,0 +1,12 @@
[package]
name = "libclide-macros"
version = "0.1.0"
edition = "2024"
[lib]
proc-macro = true
[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"
proc-macro2 = "1"

View File

@@ -0,0 +1,24 @@
// SPDX-FileCopyrightText: 2026, Shaun Reed <shaunrd0@gmail.com>
//
// SPDX-License-Identifier: GNU General Public License v3.0 or later
use proc_macro::TokenStream;
use quote::quote;
use syn::{ItemStruct, parse_macro_input};
#[proc_macro_derive(Loggable)]
pub fn loggable(item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as ItemStruct);
let struct_name = &input.ident;
let generics = &input.generics;
let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
let struct_name_str = struct_name.to_string();
let expanded = quote! {
impl #impl_generics libclide::log::Loggable for #struct_name #type_generics #where_clause {
const ID: &'static str = #struct_name_str;
}
};
TokenStream::from(expanded)
}

View File

@@ -6,3 +6,7 @@ edition = "2024"
[dependencies]
anyhow = { workspace = true }
strum = { workspace = true }
log = { workspace = true }
devicons = { workspace = true }
libclide-macros = { path = "../libclide-macros" }
syntect = "5.3.0"

View File

@@ -3,3 +3,22 @@
// SPDX-License-Identifier: GNU General Public License v3.0 or later
pub mod entry_meta;
use anyhow::Context;
pub use entry_meta::icon;
use std::fs;
use std::path::Path;
pub fn read_file<P: AsRef<Path>>(p: P) -> anyhow::Result<String> {
let path = p.as_ref();
let meta =
fs::metadata(path).unwrap_or_else(|_| panic!("Failed to get file metadata {path:?}"));
if !meta.is_file() {
crate::warn!(target:"FileSystem", "Attempted to open file {path:?} that is not a valid file");
Err(anyhow::anyhow!(
"Attempted to open file {path:?} that is not a valid file"
))?;
}
let path_str = path.to_string_lossy().to_string();
fs::read_to_string(path_str.as_str()).context(format!("Failed to read file {path:?}"))
}

View File

@@ -3,6 +3,7 @@
// SPDX-License-Identifier: GNU General Public License v3.0 or later
use anyhow::{Context, Result};
use devicons::FileIcon;
use std::path::{Path, PathBuf};
#[derive(Debug)]
@@ -10,6 +11,7 @@ pub struct EntryMeta {
pub abs_path: String,
pub file_name: String,
pub is_dir: bool,
pub icon: FileIcon,
}
impl EntryMeta {
@@ -41,10 +43,22 @@ impl EntryMeta {
.context(format!("Failed to get file name for path: {abs_path:?}"))?
.to_string_lossy()
.to_string();
let icon = crate::fs::icon(&abs_path);
Ok(EntryMeta {
abs_path,
file_name,
is_dir,
icon,
})
}
}
pub fn icon<P: AsRef<str>>(p: P) -> FileIcon {
let path = p.as_ref();
if Path::new(&path).is_dir() {
// Ensures directories are given a folder icon and not mistakenly resolved to a language.
// For example, a directory named `cpp` would otherwise return a C++ icon.
return FileIcon::from("dir/");
}
FileIcon::from(path)
}

View File

@@ -3,4 +3,5 @@
// SPDX-License-Identifier: GNU General Public License v3.0 or later
pub mod fs;
pub mod log;
pub mod theme;

10
libclide/src/log.rs Normal file
View File

@@ -0,0 +1,10 @@
// SPDX-FileCopyrightText: 2026, Shaun Reed <shaunrd0@gmail.com>
//
// SPDX-License-Identifier: GNU General Public License v3.0 or later
pub mod macros;
pub use libclide_macros::Loggable;
pub trait Loggable {
const ID: &'static str;
}

View File

@@ -0,0 +1,75 @@
// SPDX-FileCopyrightText: 2026, Shaun Reed <shaunrd0@gmail.com>
//
// SPDX-License-Identifier: GNU General Public License v3.0 or later
//! Logging targets allow filtering of log messages by their source. By default, the log crate sets
//! the target to the module path where the log macro was invoked if no target is provided.
//!
//! These macros essentially disable using the default target and instead require the target to be
//! explicitly set. This is to avoid implicit pooling of log messages under the same default target,
//! which can make it difficult to filter log messages by their source.
//!
//! The Loggable trait can be implemented to automatically associate log messages with a struct.
//! ```
//! use libclide::log::Loggable;
//!
//! #[derive(Loggable)]
//! struct MyStruct;
//! impl MyStruct {
//! fn my_method(&self) {
//! libclide::info!("This log message will use target <Self as Loggable>::ID, which is 'MyStruct'");
//! }
//! }
//! ```
//!
//! If the struct does not derive or implement Loggable, the target variant of the log macros must
//! be used instead.
//! ```
//! libclide::info!(target: "CustomTarget", "This log message will have the target 'CustomTarget'");
//! ```
//!
#[macro_export]
macro_rules! info {
(target: $target:expr, $($arg:tt)+) => ({
log::info!(target: $target, $($arg)+)
});
($($arg:tt)+) => (log::info!(target: Self::ID, $($arg)+))
}
#[macro_export]
macro_rules! debug {
(target: $target:expr, $($arg:tt)+) => ({
log::debug!(target: $target, $($arg)+)
});
($($arg:tt)+) => (log::debug!(target: Self::ID, $($arg)+))
}
#[macro_export]
macro_rules! warn {
(target: $target:expr, $($arg:tt)+) => ({
log::warn!(target: $target, $($arg)+)
});
($($arg:tt)+) => (log::warn!(target: Self::ID, $($arg)+))
}
#[macro_export]
macro_rules! error {
(target: $target:expr, $($arg:tt)+) => ({
log::error!(target: $target, $($arg)+)
});
($($arg:tt)+) => (log::error!(target: Self::ID, $($arg)+))
}
#[macro_export]
macro_rules! trace {
(target: $target:expr, $($arg:tt)+) => ({
log::trace!(target: $target, $($arg)+)
});
($($arg:tt)+) => (log::trace!(target: Self::ID, $($arg)+))
}

View File

@@ -3,3 +3,4 @@
// SPDX-License-Identifier: GNU General Public License v3.0 or later
pub mod colors;
pub mod highlighter;

View File

@@ -2,8 +2,8 @@
//
// SPDX-License-Identifier: GNU General Public License v3.0 or later
/// Colors shared between the TUI and GUI for the current theme.
pub struct Colors {}
impl Colors {
pub const HOVERED: &str = "#303234";
pub const UNHOVERED: &str = "#3c3f41";
@@ -14,7 +14,7 @@ impl Colors {
pub const SCROLLBAR_ACTIVE: &str = "#4b4f51";
pub const SCROLLBAR_GUTTER: &str = "#3b3b3b";
pub const LINENUMBER: &str = "#94989b";
pub const ACTIVE: &str = "#a9acb0";
pub const ACTIVE: &str = "#d1d33f";
pub const INACTIVE: &str = "#FFF";
pub const EDITOR_BACKGROUND: &str = "#1E1F22";
pub const EDITOR_TEXT: &str = "#acaea3";
@@ -34,19 +34,21 @@ impl Colors {
pub const ERROR_LOG: &str = "#ff5555";
pub const TRACE_LOG: &str = "#ffaa00";
pub fn css_to_u32(css: &str) -> Result<u32, String> {
/// Converts a CSS hex color string (e.g., "#RRGGBB" or "#RGB") to u32 in 0x00RRGGBB format.
pub fn css_to_u32(css: &str) -> u32 {
let hex = css.trim_start_matches('#');
// Expand shorthand #RGB to #RRGGBB
let hex_full = match hex.len() {
3 => hex.chars()
.map(|c| std::iter::repeat(c).take(2).collect::<String>())
3 => hex
.chars()
.map(|c| std::iter::repeat_n(c, 2).collect::<String>())
.collect::<String>(),
6 => hex.to_string(),
_ => return Err(format!("Invalid hex color length: {}", hex)),
_ => panic!("Invalid hex color length: {hex:?}"),
};
// Parse the hex string as u32, masking to ensure the top byte is 0x00.
// Parse the hex string as u32, masking to ensure the top (alpha) byte is 0x00.
u32::from_str_radix(&hex_full, 16)
.map(|rgb| rgb & 0x00FF_FFFF)
.map_err(|e| format!("Failed to parse hex: {}", e))
.unwrap_or_else(|e| panic!("Failed to parse hex: {e:?}"))
}
}

View File

@@ -0,0 +1,66 @@
use std::fs;
use std::path::Path;
use syntect::easy::HighlightLines;
use syntect::highlighting::ThemeSet;
use syntect::html::{IncludeBackground, append_highlighted_html_for_styled_line};
use syntect::parsing::SyntaxSet;
use syntect::util::LinesWithEndings;
pub struct Highlighter {
path: String,
ss: SyntaxSet,
ts: ThemeSet,
}
impl Highlighter {
pub fn new<P: AsRef<Path>>(p: P) -> anyhow::Result<Highlighter> {
let path = p.as_ref();
let meta =
fs::metadata(path).unwrap_or_else(|_| panic!("Failed to get file metadata {path:?}"));
let ss = SyntaxSet::load_defaults_nonewlines();
let ts = ThemeSet::load_defaults();
if !meta.is_file() {
crate::error!(target:"FileSystem", "Attempted to open file {path:?} that is not a valid file");
Err(anyhow::anyhow!(
"Attempted to open file {path:?} that is not a valid file"
))?;
}
Ok(Highlighter {
path: path.to_string_lossy().to_string(),
ss,
ts,
})
}
pub fn syntax_highlight_text<P: AsRef<str>>(&self, p: P) -> String {
let text = p.as_ref();
let theme = &self.ts.themes["base16-ocean.dark"];
let lang = self
.ss
.find_syntax_by_extension(
Path::new(self.path.as_str())
.extension()
.map(|s| s.to_str())
.unwrap_or_else(|| Some("md"))
.expect("Failed to get file extension"),
)
.unwrap_or_else(|| self.ss.find_syntax_plain_text());
let mut highlighter = HighlightLines::new(lang, theme);
// If you care about the background, see `start_highlighted_html_snippet(theme);`.
let mut output = String::from("<pre>\n");
for line in LinesWithEndings::from(text) {
let regions = highlighter
.highlight_line(line, &self.ss)
.expect("Failed to highlight");
append_highlighted_html_for_styled_line(
&regions[..],
IncludeBackground::No,
&mut output,
)
.expect("Failed to insert highlighted html");
}
output.push_str("</pre>\n");
output
}
}

View File

@@ -14,7 +14,6 @@ Rectangle {
ListModel {
id: model
}
ListView {
id: listView
@@ -38,10 +37,10 @@ Rectangle {
anchors.fill: parent
model: model
verticalLayoutDirection: ListView.BottomToTop
delegate: Text {
color: listView.getLogColor(level)
font.family: "monospace"
text: `[${level}] ${message}`
}

View File

@@ -18,22 +18,6 @@ MenuBar {
ClideMenu {
title: qsTr("&File")
ClideMenuItem {
action: Action {
id: actionNewProject
text: qsTr("&New Project...")
}
}
ClideMenuItem {
action: Action {
id: actionOpen
text: qsTr("&Open...")
}
onTriggered: FileSystem.setDirectory(FileSystem.filePath)
}
ClideMenuItem {
action: Action {
id: actionSave
@@ -41,6 +25,13 @@ MenuBar {
text: qsTr("&Save")
}
}
ClideMenuItem {
action: Action {
id: actionReload
text: qsTr("&Reload")
}
}
MenuSeparator {
background: Rectangle {
border.color: color
@@ -67,37 +58,9 @@ MenuBar {
ClideMenuItem {
action: Action {
id: actionUndo
id: actionCloseTab
text: qsTr("&Undo")
}
}
ClideMenuItem {
action: Action {
id: actionRedo
text: qsTr("&Redo")
}
}
ClideMenuItem {
action: Action {
id: actionCut
text: qsTr("&Cut")
}
}
ClideMenuItem {
action: Action {
id: actionCopy
text: qsTr("&Copy")
}
}
ClideMenuItem {
action: Action {
id: actionPaste
text: qsTr("&Paste")
text: qsTr("&Close Tab")
}
}
}
@@ -132,13 +95,6 @@ MenuBar {
ClideMenu {
title: qsTr("&Help")
ClideMenuItem {
action: Action {
id: actionDocumentation
text: qsTr("&Documentation")
}
}
ClideMenuItem {
action: Action {
id: actionAbout

View File

@@ -3,8 +3,6 @@
<file alias="kilroy.png">resources/images/kilroy-256.png</file>
</qresource>
<qresource prefix="/fonts">
<file alias="saucecodepro.ttf">resources/SauceCodeProNerdFont-Black.ttf</file>
<file alias="saucecodepro-light.ttf">resources/SauceCodeProNerdFont-Light.ttf</file>
<file alias="saucecodepro-xlight.ttf">resources/SauceCodeProNerdFont-ExtraLight.ttf</file>
</qresource>
</RCC>

View File

@@ -5,13 +5,12 @@
use crate::AppContext;
use anyhow::Result;
use cxx_qt_lib::{QMapPair, QMapPair_QString_QVariant, QString, QVariant};
use log::trace;
pub mod colors;
pub mod filesystem;
pub fn run(app_context: AppContext) -> Result<()> {
trace!(target:"gui::run()", "Starting the GUI editor at {:?}", app_context.path);
libclide::trace!(target:"gui::run()", "Starting the GUI editor at {:?}", app_context.path);
use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QUrl};

View File

@@ -3,16 +3,10 @@
// SPDX-License-Identifier: GNU General Public License v3.0 or later
use cxx_qt_lib::{QModelIndex, QString};
use devicons::FileIcon;
use dirs;
use log::warn;
use libclide::error;
use libclide::theme::highlighter::Highlighter;
use std::fs;
use std::path::Path;
use syntect::easy::HighlightLines;
use syntect::highlighting::ThemeSet;
use syntect::html::{IncludeBackground, append_highlighted_html_for_styled_line};
use syntect::parsing::SyntaxSet;
use syntect::util::LinesWithEndings;
#[cxx_qt::bridge]
pub mod qobject {
@@ -72,49 +66,15 @@ impl Default for FileSystemImpl {
impl qobject::FileSystem {
fn read_file(&self, path: &QString) -> QString {
if path.is_empty() {
return QString::default();
}
let meta = fs::metadata(path.to_string())
.unwrap_or_else(|_| panic!("Failed to get file metadata {path:?}"));
if !meta.is_file() {
warn!(target:"FileSystem", "Attempted to open file {path:?} that is not a valid file");
return QString::default();
}
let path_str = path.to_string();
if let Ok(lines) = fs::read_to_string(path_str.as_str()) {
let ss = SyntaxSet::load_defaults_nonewlines();
let ts = ThemeSet::load_defaults();
let theme = &ts.themes["base16-ocean.dark"];
let lang = ss
.find_syntax_by_extension(
Path::new(path_str.as_str())
.extension()
.map(|s| s.to_str())
.unwrap_or_else(|| Some("md"))
.expect("Failed to get file extension"),
)
.unwrap_or_else(|| ss.find_syntax_plain_text());
let mut highlighter = HighlightLines::new(lang, theme);
// If you care about the background, see `start_highlighted_html_snippet(theme);`.
let mut output = String::from("<pre>\n");
for line in LinesWithEndings::from(lines.as_str()) {
let regions = highlighter
.highlight_line(line, &ss)
.expect("Failed to highlight");
append_highlighted_html_for_styled_line(
&regions[..],
IncludeBackground::No,
&mut output,
)
.expect("Failed to insert highlighted html");
}
output.push_str("</pre>\n");
QString::from(output)
let text = libclide::fs::read_file(path.to_string()).unwrap_or_else(|_| {
error!(target: "qobject::FileSystem", "Failed to read file at path {path:?}");
String::default()
});
if let Ok(highlighter) = Highlighter::new(path.to_string()) {
QString::from(highlighter.syntax_highlight_text(text))
} else {
QString::default()
error!(target: "qobject::FileSystem", "Failed to create highlighter");
QString::from(text)
}
}
@@ -143,13 +103,6 @@ impl qobject::FileSystem {
}
fn icon(self: std::pin::Pin<&mut Self>, path: &QString) -> QString {
let str = path.to_string();
if Path::new(&str).is_dir() {
// Ensures directories are given a folder icon and not mistakenly resolved to a language.
// For example, a directory named `cpp` would otherwise return a C++ icon.
return QString::from(FileIcon::from("dir/").to_string());
}
let icon = FileIcon::from(str);
QString::from(icon.to_string())
QString::from(libclide::fs::icon(path.to_string().as_str()).to_string())
}
}

View File

@@ -4,7 +4,6 @@
use anyhow::{Context, Result, anyhow};
use clap::Parser;
use log::{info, trace};
use std::process::{Command, Stdio};
pub mod gui;
@@ -56,7 +55,7 @@ impl AppContext {
// If no path was provided, use the current directory.
None => std::env::current_dir().context("Failed to obtain current directory")?,
};
info!(target:"main()", "Root path detected: {path:?}");
libclide::info!(target:"main()", "Root path detected: {path:?}");
Ok(Self {
path,
@@ -80,7 +79,7 @@ fn main() -> Result<()> {
RunMode::GuiAttached => gui::run(app_context),
RunMode::Tui => tui::run(app_context),
RunMode::Gui => {
trace!(target:"main()", "Starting GUI in a new process");
libclide::trace!(target:"main()", "Starting GUI in a new process");
Command::new(std::env::current_exe()?)
.args(["--gui", app_context.path.to_str().unwrap()])
.stdout(Stdio::null())

View File

@@ -13,7 +13,8 @@ mod menu_bar;
use crate::AppContext;
use anyhow::{Context, Result};
use log::{LevelFilter, debug, info, trace};
use libclide::log::Loggable;
use log::LevelFilter;
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::crossterm::event::{
@@ -28,24 +29,22 @@ use tui_logger::{
TuiLoggerFile, TuiLoggerLevelOutput, init_logger, set_default_level, set_log_file,
};
#[derive(Loggable)]
struct Tui {
terminal: Terminal<CrosstermBackend<Stdout>>,
root_path: std::path::PathBuf,
}
pub fn run(app_context: AppContext) -> Result<()> {
trace!(target:Tui::ID, "Starting TUI");
libclide::trace!(target: "clide::tui::run", "Starting TUI");
Tui::new(app_context)?.start()
}
impl Tui {
pub const ID: &str = "Tui";
fn new(app_context: AppContext) -> Result<Self> {
trace!(target:Self::ID, "Building {}", Self::ID);
init_logger(LevelFilter::Trace)?;
set_default_level(LevelFilter::Trace);
debug!(target:Self::ID, "Logging initialized");
libclide::debug!("Logging initialized");
let mut dir = env::temp_dir();
dir.push("clide.log");
@@ -57,7 +56,7 @@ impl Tui {
.output_file(false)
.output_separator(':');
set_log_file(file_options);
debug!(target:Self::ID, "Logging to file: {dir:?}");
libclide::debug!("Logging to file: {dir:?}");
Ok(Self {
terminal: Terminal::new(CrosstermBackend::new(stdout()))?,
@@ -66,7 +65,7 @@ impl Tui {
}
fn start(self) -> Result<()> {
info!(target:Self::ID, "Starting the TUI editor at {:?}", self.root_path);
libclide::info!("Starting the TUI editor at {:?}", self.root_path);
ratatui::crossterm::execute!(
stdout(),
EnterAlternateScreen,
@@ -83,7 +82,7 @@ impl Tui {
}
fn stop() -> Result<()> {
info!(target:Self::ID, "Stopping the TUI editor");
libclide::info!("Stopping the TUI editor");
disable_raw_mode()?;
ratatui::crossterm::execute!(
stdout(),

View File

@@ -2,19 +2,18 @@
//
// SPDX-License-Identifier: GNU General Public License v3.0 or later
use libclide::log::Loggable;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Padding, Paragraph, Widget, Wrap};
#[derive(Loggable)]
pub struct About {}
impl About {
#[allow(unused)]
pub const ID: &str = "About";
pub fn new() -> Self {
// trace!(target:Self::id(), "Building {}", Self::id());
// libclide::trace!("Building {}", Self::id());
Self {}
}
}

View File

@@ -9,7 +9,7 @@ use crate::tui::explorer::Explorer;
use crate::tui::logger::Logger;
use crate::tui::menu_bar::MenuBar;
use anyhow::{Context, Result};
use log::{error, info, trace};
use libclide::log::Loggable;
use ratatui::DefaultTerminal;
use ratatui::buffer::Buffer;
use ratatui::crossterm::event;
@@ -30,6 +30,7 @@ pub enum AppComponent {
MenuBar,
}
#[derive(Loggable)]
pub struct App<'a> {
editor_tab: EditorTab,
explorer: Explorer<'a>,
@@ -40,10 +41,8 @@ pub struct App<'a> {
}
impl<'a> App<'a> {
pub const ID: &'static str = "App";
pub fn new(root_path: PathBuf) -> Result<Self> {
trace!(target:Self::ID, "Building {}", Self::ID);
libclide::trace!("Building {}", Self::ID);
let app = Self {
editor_tab: EditorTab::new(),
explorer: Explorer::new(&root_path)?,
@@ -57,13 +56,13 @@ impl<'a> App<'a> {
/// Logic that should be executed once on application startup.
pub fn start(&mut self) -> Result<()> {
trace!(target:Self::ID, "Starting App");
libclide::trace!("Starting App");
Ok(())
}
pub fn run(mut self, mut terminal: DefaultTerminal) -> Result<()> {
self.start()?;
trace!(target:Self::ID, "Entering App run loop");
libclide::trace!("Entering App run loop");
loop {
terminal.draw(|f| {
f.render_widget(&mut self, f.area());
@@ -89,7 +88,7 @@ impl<'a> App<'a> {
Some(editor) => editor.component_state.help_text.clone(),
None => {
if !self.editor_tab.is_empty() {
error!(target:Self::ID, "Failed to get Editor while drawing bottom status bar");
libclide::error!("Failed to get Editor while drawing bottom status bar");
}
"Failed to get current Editor while getting widget help text".to_string()
}
@@ -113,26 +112,26 @@ impl<'a> App<'a> {
}
fn clear_focus(&mut self) {
info!(target:Self::ID, "Clearing all widget focus");
libclide::info!("Clearing all widget focus");
self.explorer.component_state.set_focus(Focus::Inactive);
self.explorer.component_state.set_focus(Focus::Inactive);
self.logger.component_state.set_focus(Focus::Inactive);
self.menu_bar.component_state.set_focus(Focus::Inactive);
match self.editor_tab.current_editor_mut() {
None => {
error!(target:Self::ID, "Failed to get current Editor while clearing focus")
libclide::error!("Failed to get current Editor while clearing focus")
}
Some(editor) => editor.component_state.set_focus(Focus::Inactive),
}
}
fn change_focus(&mut self, focus: AppComponent) {
info!(target:Self::ID, "Changing widget focus to {:?}", focus);
libclide::info!("Changing widget focus to {:?}", focus);
self.clear_focus();
match focus {
AppComponent::Editor => match self.editor_tab.current_editor_mut() {
None => {
error!(target:Self::ID, "Failed to get current Editor while changing focus")
libclide::error!("Failed to get current Editor while changing focus")
}
Some(editor) => editor.component_state.set_focus(Focus::Active),
},
@@ -275,13 +274,15 @@ impl<'a> Component for App<'a> {
Action::Quit | Action::Handled => Ok(action),
Action::Save => match self.editor_tab.current_editor_mut() {
None => {
error!(target:Self::ID, "Failed to get current editor while handling App Action::Save");
libclide::error!(
"Failed to get current editor while handling App Action::Save"
);
Ok(Action::Noop)
}
Some(editor) => match editor.save() {
Ok(_) => Ok(Action::Handled),
Err(e) => {
error!(target:Self::ID, "Failed to save editor contents: {e}");
libclide::error!("Failed to save editor contents: {e}");
Ok(Action::Noop)
}
},
@@ -300,14 +301,16 @@ impl<'a> Component for App<'a> {
Err(_) => Ok(Action::Noop),
},
Action::ReloadFile => {
trace!(target:Self::ID, "Reloading file for current editor");
libclide::trace!("Reloading file for current editor");
if let Some(editor) = self.editor_tab.current_editor_mut() {
editor
.reload_contents()
.map(|_| Action::Handled)
.context("Failed to handle Action::ReloadFile")
} else {
error!(target:Self::ID, "Failed to get current editor while handling App Action::ReloadFile");
libclide::error!(
"Failed to get current editor while handling App Action::ReloadFile"
);
Ok(Action::Noop)
}
}

View File

@@ -7,8 +7,8 @@
use crate::tui::component::Focus::Inactive;
use Focus::Active;
use anyhow::Result;
use libclide::log::Loggable;
use libclide::theme::colors::Colors;
use log::trace;
use ratatui::crossterm::event::{Event, KeyEvent, MouseEvent};
use ratatui::style::Color;
@@ -62,7 +62,7 @@ pub trait Component {
}
}
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, Loggable)]
pub struct ComponentState {
pub(crate) focus: Focus,
pub(crate) vis: Visibility,
@@ -75,7 +75,7 @@ impl ComponentState {
}
fn new() -> Self {
trace!(target:Self::id(), "Building {}", Self::id());
libclide::trace!(target:Self::id(), "Building {}", Self::id());
Self {
focus: Active,
vis: Visibility::Visible,
@@ -99,8 +99,8 @@ pub enum Focus {
impl Focus {
pub(crate) fn get_active_color(&self) -> Color {
match self {
Active => Color::from_u32(Colors::css_to_u32(Colors::ACTIVE)?),
Inactive => Color::from_u32(Colors::css_to_u32(Colors::INACTIVE)?),
Active => Color::from_u32(Colors::css_to_u32(Colors::ACTIVE)),
Inactive => Color::from_u32(Colors::css_to_u32(Colors::INACTIVE)),
}
}
}

View File

@@ -7,7 +7,7 @@ use anyhow::{Context, Result, bail};
use edtui::{
EditorEventHandler, EditorState, EditorTheme, EditorView, LineNumbers, Lines, SyntaxHighlighter,
};
use log::{error, trace};
use libclide::log::Loggable;
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Alignment, Rect};
@@ -16,19 +16,18 @@ use ratatui::widgets::{Block, Borders, Padding, Widget};
use std::path::PathBuf;
use syntect::parsing::SyntaxSet;
#[derive(Loggable)]
pub struct Editor {
pub state: EditorState,
pub event_handler: EditorEventHandler,
pub file_path: Option<std::path::PathBuf>,
pub file_path: Option<PathBuf>,
syntax_set: SyntaxSet,
pub(crate) component_state: ComponentState,
}
impl Editor {
pub const ID: &str = "Editor";
pub fn new(path: &std::path::Path) -> Self {
trace!(target:Self::ID, "Building {}", Self::ID);
libclide::trace!("Building {}", <Self as Loggable>::ID);
Editor {
state: EditorState::default(),
event_handler: EditorEventHandler::default(),
@@ -42,10 +41,10 @@ impl Editor {
}
pub fn reload_contents(&mut self) -> Result<()> {
trace!(target:Self::ID, "Reloading editor file contents {:?}", self.file_path);
libclide::trace!("Reloading editor file contents {:?}", self.file_path);
match self.file_path.clone() {
None => {
error!(target:Self::ID, "Failed to reload editor contents with None file_path");
libclide::error!("Failed to reload editor contents with None file_path");
bail!("Failed to reload editor contents with None file_path")
}
Some(path) => self.set_contents(&path),
@@ -53,7 +52,7 @@ impl Editor {
}
pub fn set_contents(&mut self, path: &std::path::Path) -> Result<()> {
trace!(target:Self::ID, "Setting Editor contents from path {:?}", path);
libclide::trace!("Setting Editor contents from path {:?}", path);
if let Ok(contents) = std::fs::read_to_string(path) {
let lines: Vec<_> = contents
.lines()
@@ -69,10 +68,10 @@ impl Editor {
pub fn save(&self) -> Result<()> {
if let Some(path) = &self.file_path {
trace!(target:Self::ID, "Saving Editor contents {:?}", path);
libclide::trace!("Saving Editor contents {:?}", path);
return std::fs::write(path, self.state.lines.to_string()).map_err(|e| e.into());
};
error!(target:Self::ID, "Failed saving Editor contents; file_path was None");
libclide::error!("Failed saving Editor contents; file_path was None");
bail!("File not saved. No file path set.")
}
}

View File

@@ -5,7 +5,7 @@
use crate::tui::component::{Action, Component, Focus, FocusState};
use crate::tui::editor::Editor;
use anyhow::{Context, Result, anyhow};
use log::{error, info, trace, warn};
use libclide::log::Loggable;
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::Rect;
@@ -16,6 +16,7 @@ use std::collections::HashMap;
// Render the tabs with keys as titles
// Tab keys can be file names.
// Render the editor using the key as a reference for lookup
#[derive(Loggable)]
pub struct EditorTab {
pub(crate) editors: HashMap<String, Editor>,
tab_order: Vec<String>,
@@ -23,10 +24,8 @@ pub struct EditorTab {
}
impl EditorTab {
pub const ID: &str = "EditorTab";
pub fn new() -> Self {
trace!(target:Self::ID, "Building {}", Self::ID);
libclide::trace!("Building {}", <Self as Loggable>::ID);
Self {
editors: HashMap::new(),
tab_order: Vec::new(),
@@ -36,7 +35,11 @@ impl EditorTab {
pub fn next_editor(&mut self) {
let next = (self.current_editor + 1) % self.tab_order.len();
trace!(target:Self::ID, "Moving from {} to next editor tab at {}", self.current_editor, next);
libclide::trace!(
"Moving from {} to next editor tab at {}",
self.current_editor,
next
);
self.set_tab_focus(Focus::Active, next);
self.current_editor = next;
}
@@ -46,7 +49,11 @@ impl EditorTab {
.current_editor
.checked_sub(1)
.unwrap_or(self.tab_order.len() - 1);
trace!(target:Self::ID, "Moving from {} to previous editor tab at {}", self.current_editor, prev);
libclide::trace!(
"Moving from {} to previous editor tab at {}",
self.current_editor,
prev
);
self.set_tab_focus(Focus::Active, prev);
self.current_editor = prev;
}
@@ -55,7 +62,7 @@ impl EditorTab {
match self.tab_order.get(index) {
None => {
if !self.tab_order.is_empty() {
error!(target:Self::ID, "Failed to get editor tab key with invalid index {index}");
libclide::error!("Failed to get editor tab key with invalid index {index}");
}
None
}
@@ -73,16 +80,19 @@ impl EditorTab {
}
pub fn set_current_tab_focus(&mut self, focus: Focus) {
trace!(target:Self::ID, "Setting current tab {} focus to {:?}", self.current_editor, focus);
libclide::trace!(
"Setting current tab {} focus to {:?}",
self.current_editor,
focus
);
self.set_tab_focus(focus, self.current_editor)
}
pub fn set_tab_focus(&mut self, focus: Focus, index: usize) {
trace!(target:Self::ID, "Setting tab {} focus to {:?}", index, focus);
libclide::trace!("Setting tab {} focus to {:?}", index, focus);
if focus == Focus::Active && index != self.current_editor {
// If we are setting another tab to active, disable the current one.
trace!(
target:Self::ID,
libclide::trace!(
"New tab {} focus set to Active; Setting current tab {} to Inactive",
index,
self.current_editor
@@ -91,12 +101,11 @@ impl EditorTab {
}
match self.get_editor_key(index) {
None => {
error!(target:Self::ID, "Failed setting tab focus for invalid key {index}");
libclide::error!("Failed setting tab focus for invalid key {index}");
}
Some(key) => match self.editors.get_mut(&key) {
None => {
error!(
target:Self::ID,
libclide::error!(
"Failed to update tab focus at index {} with invalid key: {}",
self.current_editor,
self.tab_order[self.current_editor]
@@ -108,12 +117,12 @@ impl EditorTab {
}
pub fn open_tab(&mut self, path: &std::path::Path) -> Result<()> {
trace!(target:Self::ID, "Opening new EditorTab with path {:?}", path);
libclide::trace!("Opening new EditorTab with path {:?}", path);
if self
.editors
.contains_key(&path.to_string_lossy().to_string())
{
warn!(target:Self::ID, "EditorTab already opened with this file");
libclide::warn!("EditorTab already opened with this file");
return Ok(());
}
@@ -138,12 +147,12 @@ impl EditorTab {
.to_owned();
match self.editors.remove(&key) {
None => {
error!(target:Self::ID, "Failed to remove editor tab {key} with invalid index {index}")
libclide::error!("Failed to remove editor tab {key} with invalid index {index}")
}
Some(_) => {
self.prev_editor();
self.tab_order.remove(index);
info!(target:Self::ID, "Closed editor tab {key} at index {index}")
libclide::info!("Closed editor tab {key} at index {index}")
}
}
Ok(())

View File

@@ -5,7 +5,7 @@
use crate::tui::component::{Action, Component, ComponentState, Focus, FocusState};
use anyhow::{Context, Result, bail};
use libclide::fs::entry_meta::EntryMeta;
use log::trace;
use libclide::log::Loggable;
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, MouseEvent, MouseEventKind};
use ratatui::layout::{Alignment, Position, Rect};
@@ -16,7 +16,7 @@ use std::fs;
use std::path::{Path, PathBuf};
use tui_tree_widget::{Tree, TreeItem, TreeState};
#[derive(Debug)]
#[derive(Debug, Loggable)]
pub struct Explorer<'a> {
root_path: EntryMeta,
tree_items: TreeItem<'a, String>,
@@ -25,10 +25,8 @@ pub struct Explorer<'a> {
}
impl<'a> Explorer<'a> {
pub const ID: &'static str = "Explorer";
pub fn new(path: &PathBuf) -> Result<Self> {
trace!(target:Self::ID, "Building {}", Self::ID);
libclide::trace!("Building {}", <Self as Loggable>::ID);
let explorer = Explorer {
root_path: EntryMeta::new(path)?,
tree_items: Self::build_tree_from_path(path)?,
@@ -64,17 +62,17 @@ impl<'a> Explorer<'a> {
} else {
children.push(TreeItem::new_leaf(
entry_meta.abs_path.clone(),
entry_meta.file_name.clone(),
format!("{} {}", entry_meta.icon.icon, entry_meta.file_name.as_str()),
));
}
}
}
// Note: The first argument is a unique identifier, where no 2 TreeItems may share the same.
// Note: The first argument is a unique identifier, where no. 2 TreeItems may share the same.
// For a file tree this is fine because we shouldn't list the same object twice.
TreeItem::new(
path_meta.abs_path.clone(),
path_meta.file_name.clone(),
format!("{} {}", path_meta.icon.icon, path_meta.file_name.as_str()),
children,
)
.context(format!(

View File

@@ -3,7 +3,8 @@
// SPDX-License-Identifier: GNU General Public License v3.0 or later
use crate::tui::component::{Action, Component, ComponentState, Focus, FocusState};
use log::{LevelFilter, trace};
use libclide::log::Loggable;
use log::LevelFilter;
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{Event, KeyCode, KeyEvent};
use ratatui::layout::Rect;
@@ -13,16 +14,15 @@ use tui_logger::{TuiLoggerLevelOutput, TuiLoggerSmartWidget, TuiWidgetEvent, Tui
/// Any log written as info!(target:self.id(), "message") will work with this logger.
/// The logger is bound to info!, debug!, error!, trace! macros within Tui::new().
#[derive(Loggable)]
pub struct Logger {
state: TuiWidgetState,
pub(crate) component_state: ComponentState,
}
impl Logger {
pub const ID: &str = "Logger";
pub fn new() -> Self {
trace!(target:Self::ID, "Building {}", Self::ID);
libclide::trace!("Building {}", <Self as Loggable>::ID);
let state = TuiWidgetState::new();
state.transition(TuiWidgetEvent::HideKey);
Self {

View File

@@ -7,7 +7,7 @@ use crate::tui::menu_bar::MenuBarItemOption::{
About, CloseTab, Exit, Reload, Save, ShowHideExplorer, ShowHideLogger,
};
use anyhow::Context;
use log::trace;
use libclide::log::Loggable;
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{KeyCode, KeyEvent};
use ratatui::layout::Rect;
@@ -21,6 +21,7 @@ use strum::{EnumIter, FromRepr, IntoEnumIterator};
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr, EnumIter)]
enum MenuBarItem {
File,
Edit,
View,
Help,
}
@@ -68,18 +69,21 @@ impl MenuBarItem {
MenuBarItem::File => "File",
MenuBarItem::View => "View",
MenuBarItem::Help => "Help",
MenuBarItem::Edit => "Edit",
}
}
pub fn options(&self) -> &[MenuBarItemOption] {
match self {
MenuBarItem::File => &[Save, CloseTab, Reload, Exit],
MenuBarItem::File => &[Save, Reload, Exit],
MenuBarItem::Edit => &[CloseTab],
MenuBarItem::View => &[ShowHideExplorer, ShowHideLogger],
MenuBarItem::Help => &[About],
}
}
}
#[derive(Debug, Loggable)]
pub struct MenuBar {
selected: MenuBarItem,
opened: Option<MenuBarItem>,
@@ -88,11 +92,9 @@ pub struct MenuBar {
}
impl MenuBar {
pub const ID: &str = "MenuBar";
const DEFAULT_HELP: &str = "(←/h)/(→/l): Select option | Enter: Choose selection";
pub fn new() -> Self {
trace!(target:Self::ID, "Building {}", Self::ID);
libclide::trace!("Building");
Self {
selected: MenuBarItem::File,
opened: None,
@@ -157,7 +159,7 @@ impl MenuBar {
height,
}
// TODO: X offset for item option? It's fine as-is, but it might look nicer.
// trace!(target:Self::ID, "Building Rect under MenuBar popup {}", rect);
// trace!("Building Rect under MenuBar popup {}", rect);
}
}