56 Commits

Author SHA1 Message Date
Byson94
e1c9cdfcb9 feat: added name in 0.2.0 release changelog 2025-09-29 15:04:21 +05:30
Byson94
2aa5d94cea chore: a small rename :) 2025-09-29 14:29:13 +05:30
Byson94
c49d7f36f5 feat: removed monitor lib in favour of gtk4 2025-09-29 14:23:08 +05:30
Byson94
598c28bb9e feat: fixed falure send & added print flag to engine-override 2025-09-29 12:38:37 +05:30
Byson94
f56c126ef4 feat: better management of rhai crate 2025-09-29 12:11:49 +05:30
Byson94
02686bd919 feat: removed more code/dependencies 2025-09-29 12:04:37 +05:30
Byson94
37d880af2d feat: removed unnecessary dependencies 2025-09-29 11:59:07 +05:30
Byson94
04f6835892 chore: cargo fmt 2025-09-29 11:49:50 +05:30
Byson94
21e72a2e8f feat: added file path indicator in errors! 2025-09-29 11:30:53 +05:30
Byson94
497d9b664d fix: resolver throwing err at import on p/e err 2025-09-28 19:25:39 +05:30
Byson94
09b1c24b61 feat: even better err support with rhai_trace v3 2025-09-28 18:29:36 +05:30
Byson94
85a179bf81 feat: renaming setup_for_rt to setup_dyn_ids 2025-09-28 16:51:59 +05:30
Byson94
0238a9ae07 feat: removed INPUT_VAL var support in input wdgt 2025-09-28 14:45:10 +05:30
Byson94
26946b8e70 feat: improved the module heading generation 2025-09-27 19:49:00 +05:30
Byson94
97920a8bb0 fix: fixed doc error 2025-09-27 19:35:28 +05:30
Byson94
48bb71d615 chore: removed lagacy support on focusable win prop 2025-09-27 19:32:34 +05:30
Byson94
2244a1cbda feat: added force_normal property for windows 2025-09-27 19:10:30 +05:30
Byson94
0094818d73 fix: m/min duration end & ewwii crash 2025-09-27 11:49:59 +05:30
Byson94
df23beb9bb fix: fixed broken m value for min 2025-09-27 11:47:04 +05:30
Byson94
05ac8c89e5 feat: improving the engine-override feature 2025-09-26 19:26:16 +05:30
Byson94
3d5a454fe3 fix(typo): in 0.2.0 CHANGELOG 2025-09-26 19:04:09 +05:30
Byson94
a88797a92b feat: added engine-override command 2025-09-25 22:45:30 +05:30
Byson94
25ed97cc53 feat(stdlib): added std::regex for regex matching 2025-09-23 20:00:21 +05:30
Byson94
2083e0a2d1 chore: removed added support for open-many in v0.2.0 2025-09-23 19:14:04 +05:30
Byson94
b6c38aeddc feat: improved rhai docs generator 2025-09-19 17:39:07 +05:30
Byson94
b2abecdd7d feat(doc auto gen): fixed broken code for docusaurus 2025-09-19 16:50:33 +05:30
Byson94
d03ec33f70 Merge branch 'main' into iidev 2025-09-19 16:33:05 +05:30
Byson94
9ac4e57c7c feat: removing stuff in autogen 2025-09-19 16:32:55 +05:30
Byson94
c2e82d8943 feat: removing stuff in autogen 2025-09-19 16:32:40 +05:30
Byson94
85b4594ad7 Merge branch 'main' into iidev 2025-09-19 16:27:41 +05:30
Byson94
52bd01315c feat(doc gen): fixed mdx issues 2025-09-19 16:27:34 +05:30
Byson94
71f9180c5d feat(doc gen): fixed mdx issues 2025-09-19 16:27:12 +05:30
Byson94
b03f275ead Merge branch 'main' into iidev 2025-09-19 15:23:11 +05:30
Byson94
ebbd1355c6 feat: renaming js => javascript 2025-09-19 15:23:03 +05:30
Byson94
a28c5382b4 Merge branch 'main' into iidev 2025-09-19 14:16:01 +05:30
Byson94
44e7298d86 feat: removed docs/ and moving to docusarus 2025-09-19 14:15:53 +05:30
Byson94
934be31248 feat: removed docs/ and moving to docusarus 2025-09-19 14:14:50 +05:30
Byson94
767eb4e7a7 feat: added m as another duration unit for minute 2025-09-19 12:44:07 +05:30
Byson94
c10a759478 feat: more renaming | eww => ewwii 2025-09-19 12:39:49 +05:30
Byson94
e9cc5f1518 feat: removing a few comment of minee 2025-09-19 12:37:54 +05:30
Byson94
ee37ea5555 feat: fully renamed EwwPaths => EwwiiPaths 2025-09-19 12:34:02 +05:30
Byson94
8800b9b887 feat: made eval_code fn use the compile_code fn to compile 2025-09-19 12:16:39 +05:30
Byson94
b9368d912c chore: renaming a few eww => ewwii 2025-09-19 11:58:46 +05:30
Byson94
a75cfd65f3 feat: added state command and fixed log issues 2025-09-19 11:55:44 +05:30
Byson94
bd7f1f58bf feat: added --preserve in the docs 2025-09-18 20:42:03 +05:30
Byson94
ad7229039f feat: added date in 0.1.4 release 2025-09-18 20:36:04 +05:30
Byson94
9ddfad0fbe feat: added perserve flag to the update command which preserves the new updates 2025-09-18 20:17:44 +05:30
Byson94
10a7f8a1da chore(cargo): building for 0.1.3 2025-09-17 22:15:38 +05:30
Byson94
0a1f981bb1 feat: fixed image_width and height not working issue for image 2025-09-17 22:12:39 +05:30
Byson94
9053cf8700 feat: removed getting started section from docs 2025-09-14 10:54:17 +05:30
Byson94
909b33a897 chore: fixing a comment... 2025-09-14 09:46:49 +05:30
Byson94
b96a34a1f4 feat: reworking the inject-vars arg of update 2025-09-14 09:44:44 +05:30
Byson94
11e21bbdda feat: made update cmd so that it will preserve current wdgt state 2025-09-13 14:40:54 +05:30
Byson94
e18b6da679 feat(docs): added exclusive true in config 2025-09-13 13:28:59 +05:30
Byson94
dc135f22a9 fix(docs): fixed invalid config in configuration.md 2025-09-13 13:27:26 +05:30
Byson94
fc88f6e38d feat: updating ewwii dark theme 2025-09-13 13:20:15 +05:30
78 changed files with 657 additions and 10417 deletions

View File

@@ -1,93 +0,0 @@
name: Build and deploy Github pages
on:
push:
branches:
- main
paths:
- "docs/**"
- ".github/workflows/**"
- "tools/generate-rhai-docs/**"
permissions:
contents: write
jobs:
build:
name: Build mdBook
runs-on: ubuntu-latest
steps:
# Checkout code
- name: Checkout repository
uses: actions/checkout@v4
# Cache apt package lists
- name: Cache apt-get package lists
uses: actions/cache@v3
with:
path: |
/var/cache/apt/archives
/var/lib/apt/lists
key: ${{ runner.os }}-apt-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-apt-
# Install necessary dependencies for glib-sys and gobject-sys
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
pkg-config \
libcairo2-dev \
libglib2.0-dev \
libgirepository1.0-dev \
libpango1.0-dev \
libatk1.0-dev \
libgtk-3-dev
# Cache Rust toolchain
- name: Cache Rust toolchain
uses: actions/cache@v4
with:
path: ~/.cargo
key: ${{ runner.os }}-rust-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-rust-
# Install Rust
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source $HOME/.cargo/env
# Cache Cargo registry and git directory
- name: Cache Cargo registry and git
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
# Generate module docs
- name: Generate module docs
run: cargo run --release -p generate-rhai-docs
# Build mdBook
- name: Build mdBook page
uses: peaceiris/actions-mdbook@v1
with:
mdbook-version: "0.4.52"
- name: Run mdBook build
run: mdbook build docs
# Deploy to GitHub Pages
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs/book/

View File

@@ -5,6 +5,50 @@ All notable changes to `ewwii` are documented here.
This changelog follows the [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) format,
and this project adheres to [Semantic Versioning](https://semver.org/).
## [0.2.0] - 2025-09-29
### Added
- `state` command to print the current poll/listen variable state.
- `m` as another duration unit for minute.
- `std::regex` library for regex matching.
- `engine-override` command which can be used to change engine settings of a configuration.
- `force_normal` property for ewwii windows. It allows user to create normal windows on wayland.
- Better error support by migrating to `rhai_trace` v0.3.0.
- File path indicator in rhai errors.
### Fixed
- The logs going to `eww_{}.log` instead of `ewwii_{}.log`.
- Logs not truncating if it is over 100MB and not deleting if over 7 days old.
- Ewwii crashing on invalid duration property.
- The module resolver throwing error at `import` defenition.
- Fixed commands sending error with success status.
### Removed
- Legacy `true`/`false` support for `focusable` window property.
- `$INPUT_VAL` variable injected in commands ran by input widget.
- Many dependencies and code for faster build and lesser binary size.
- `monitor` library as a step towards GTK4.
## [0.1.4] - 2025-09-18
### Added
- `--preserve` flag to the `update` command which preserves the new updates.
## [0.1.3] - 2025-09-17
### Changed
- `update` command so that it preserves current widget state.
- `--inject-vars` argument of update to just `--inject` (or `-i` in short).
### Fixed
- `image_width` and `image_height` not working for image widget.
## [0.1.2] - 2025-09-13
### Added

129
Cargo.lock generated
View File

@@ -46,21 +46,6 @@ version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
[[package]]
name = "android-tzdata"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "anstream"
version = "0.6.15"
@@ -233,15 +218,6 @@ dependencies = [
"system-deps 6.2.2",
]
[[package]]
name = "cc"
version = "1.1.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9540e661f81799159abee814118cc139a2004b3a3aa3ea37724a1b66530b90e0"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-expr"
version = "0.15.8"
@@ -274,21 +250,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chrono"
version = "0.4.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d"
dependencies = [
"android-tzdata",
"iana-time-zone",
"js-sys",
"num-traits",
"pure-rust-locales",
"wasm-bindgen",
"windows-link",
]
[[package]]
name = "clap"
version = "4.5.18"
@@ -380,12 +341,6 @@ dependencies = [
"tiny-keccak",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpufeatures"
version = "0.2.14"
@@ -566,7 +521,7 @@ dependencies = [
[[package]]
name = "ewwii"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"anyhow",
"bincode",
@@ -1137,29 +1092,6 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "iana-time-zone"
version = "0.1.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "ident_case"
version = "1.0.1"
@@ -1680,12 +1612,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "pure-rust-locales"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1190fd18ae6ce9e137184f207593877e70f39b015040156b1e05081cdfe3733a"
[[package]]
name = "quote"
version = "1.0.37"
@@ -1740,26 +1666,6 @@ dependencies = [
"bitflags 2.6.0",
]
[[package]]
name = "ref-cast"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931"
dependencies = [
"ref-cast-impl",
]
[[package]]
name = "ref-cast-impl"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.87",
]
[[package]]
name = "regex"
version = "1.10.6"
@@ -1843,6 +1749,7 @@ dependencies = [
"log",
"nix",
"once_cell",
"regex",
"rhai",
"rhai_trace",
"serde",
@@ -1852,9 +1759,9 @@ dependencies = [
[[package]]
name = "rhai_trace"
version = "0.2.0"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3b719976dd04e8f881b0637892aa5b459f47048f91b1632c6bc32b632d44367"
checksum = "90093b2d5beff618cbf5698c4952ecca7eca5c5a6d9a892c0d19d9046d8329e4"
dependencies = [
"rhai",
]
@@ -1971,19 +1878,10 @@ name = "shared_utils"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"derive_more",
"ref-cast",
"rhai",
"serde",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signal-hook-registry"
version = "1.4.2"
@@ -2322,9 +2220,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wait-timeout"
version = "0.2.0"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
@@ -2440,21 +2338,6 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-core"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-link"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38"
[[package]]
name = "windows-sys"
version = "0.48.0"

View File

@@ -11,9 +11,6 @@ anyhow = "1.0.86"
ahash = "0.8.12"
bincode = "1.3.3"
bytesize = "2.0.1"
cached = "0.53.1"
chrono = "0.4.38"
chrono-tz = "0.10.0"
clap = { version = "4.5.1", features = ["derive"] }
clap_complete = "4.5.12"
codespan-reporting = "0.11"
@@ -28,13 +25,7 @@ extend = "1.2"
futures = "0.3.30"
grass = "0.13.4"
gtk = "0.18.1"
insta = "1.7"
itertools = "0.13.0"
jaq-core = "1.5.1"
jaq-parse = "1.0.3"
jaq-std = "1.6.0"
jaq-interpret = "1.5.0"
jaq-syn = "1.6.0"
libc = "0.2"
log = "0.4"
nix = "0.29.0"
@@ -42,16 +33,13 @@ notify = "6.1.1"
once_cell = "1.19"
pretty_assertions = "1.4.0"
pretty_env_logger = "0.5.0"
ref-cast = "1.0.22"
regex = "1.10.5"
rhai = { version = "1.22.2", features = ["internals"] }
rhai = "1.22.2"
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
simple-signal = "1.1"
smart-default = "0.7.1"
static_assertions = "1.1.0"
strsim = "0.11"
strum = { version = "0.26", features = ["derive"] }
thiserror = "1.0"
tokio = { version = "1.39.2", features = ["full"] }
unescape = "0.1"

View File

@@ -1,6 +1,6 @@
[package]
name = "ewwii"
version = "0.1.0"
version = "0.2.0"
authors = ["byson94 <byson94wastaken@gmail.com>"]
description = "Widgets for everyone made better!"
license = "GPL-3.0-or-later"

View File

@@ -6,7 +6,7 @@ use crate::{
gtk::prelude::{
ContainerExt, CssProviderExt, GtkWindowExt, MonitorExt, StyleContextExt, WidgetExt,
},
paths::EwwPaths,
paths::EwwiiPaths,
widgets::window::Window,
// dynval::DynVal,
widgets::{
@@ -31,6 +31,7 @@ use itertools::Itertools;
use once_cell::sync::Lazy;
use rhai::Dynamic;
use rhai_impl::ast::WidgetNode;
use serde::{de::Error as SerdeError, Deserialize, Deserializer};
use shared_utils::Span;
use std::{
cell::{Cell, RefCell},
@@ -75,13 +76,23 @@ pub enum DaemonCommand {
KillServer,
CloseAll,
PrintDebug(DaemonResponseSender),
ShowState(DaemonResponseSender),
ListWindows(DaemonResponseSender),
ListActiveWindows(DaemonResponseSender),
TriggerUpdateUI(Option<HashMap<String, String>>),
TriggerUpdateUI {
inject_vars: Option<HashMap<String, String>>,
should_preserve_state: bool,
sender: DaemonResponseSender,
},
CallRhaiFns {
calls: Vec<String>,
sender: DaemonResponseSender,
},
EngineOverride {
config: String,
print: bool,
sender: DaemonResponseSender,
},
}
/// An opened window.
@@ -146,7 +157,9 @@ pub struct App<B: DisplayBackend> {
// The cached store of poll/listen handlers
pub pl_handler_store: Option<rhai_impl::updates::ReactiveVarStore>,
pub paths: EwwPaths,
pub rt_engine_config: EngineConfValues,
pub paths: EwwiiPaths,
pub phantom: PhantomData<B>,
}
@@ -306,22 +319,46 @@ impl<B: DisplayBackend> App<B> {
let output = format!("{:#?}", &self);
sender.send_success(output)?
}
DaemonCommand::TriggerUpdateUI(inject_vars) => {
let _ = self.trigger_ui_update_with(inject_vars)?;
DaemonCommand::ShowState(sender) => {
if let Some(maybe_store) = &self.pl_handler_store {
let output = format!("{:#?}", maybe_store.read().unwrap());
sender.send_success(output)?
} else {
sender.send_failure(
"The poll/listen handler store doesn't exist or is empty".to_string(),
)?
}
}
DaemonCommand::TriggerUpdateUI { inject_vars, should_preserve_state, sender } => {
match self.trigger_ui_update_with(inject_vars, should_preserve_state) {
Ok(_) => sender.send_success(String::new())?,
Err(e) => sender.send_failure(e.to_string())?,
};
}
DaemonCommand::CallRhaiFns { calls, sender } => {
let output = match self.call_rhai_fns(calls) {
Ok(_) => String::new(),
Err(e) => e.to_string(),
match self.call_rhai_fns(calls) {
Ok(_) => sender.send_success(String::new())?,
Err(e) => sender.send_failure(e.to_string())?,
};
}
DaemonCommand::EngineOverride { config, print, sender } => {
match self.set_engine_overrides(config) {
Ok(_) => {
if print {
sender.send_success(format!("{:#?}", self.rt_engine_config))?
} else {
sender.send_success(String::new())?
}
}
Err(e) => sender.send_failure(e.to_string())?,
};
sender.send_success(output)?
}
}
Ok(())
}
/// Fully stop ewwii:
/// close all windows, stop the script_var_handler, quit the gtk appliaction and send the exit instruction to the lifecycle manager
/// close all windows, kill the poll/listen state handler, quit the gtk appliaction and send the exit instruction to the lifecycle manager
fn stop_application(&mut self) {
rhai_impl::updates::kill_state_change_handler();
for (_, window) in self.open_windows.drain() {
@@ -435,6 +472,9 @@ impl<B: DisplayBackend> App<B> {
let config_path = self.paths.get_rhai_path();
let compiled_ast = self.ewwii_config.get_owned_compiled_ast();
let mut stored_parser = rhai_impl::parser::ParseConfig::new();
stored_parser.set_opt_level(get_opt_level_from(
self.rt_engine_config.optimization_level.unwrap_or(1),
));
if self.open_windows.is_empty() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
@@ -446,6 +486,7 @@ impl<B: DisplayBackend> App<B> {
);
self.pl_handler_store = Some(store.clone());
let b_interval = self.rt_engine_config.batching_interval;
glib::MainContext::default().spawn_local(async move {
let mut pending_updates = HashSet::new();
@@ -453,8 +494,13 @@ impl<B: DisplayBackend> App<B> {
while let Some(var_name) = rx.recv().await {
pending_updates.insert(var_name);
// short batching interval (1 frame)
glib::timeout_future(Duration::from_millis(16)).await;
match b_interval {
Some(i) => glib::timeout_future(Duration::from_millis(i)).await,
None => {
// short batching interval (1 frame)
glib::timeout_future(Duration::from_millis(16)).await
}
}
while let Ok(next_var) = rx.try_recv() {
pending_updates.insert(next_var);
@@ -493,7 +539,10 @@ impl<B: DisplayBackend> App<B> {
} else {
// else, just update the window from the current store.
let widget_reg_store = self.widget_reg_store.clone();
let store = self.pl_handler_store.clone().expect("REASON");
let store = self
.pl_handler_store
.clone()
.expect("Failed to clone poll listen handler store");
glib::MainContext::default().spawn_local(async move {
let vars = store.read().unwrap().clone();
@@ -666,42 +715,59 @@ impl<B: DisplayBackend> App<B> {
pub fn trigger_ui_update_with(
&self,
inject_vars: Option<HashMap<String, String>>,
should_preserve_state: bool,
) -> Result<()> {
let compiled_ast = self.ewwii_config.get_owned_compiled_ast();
let config_path = self.paths.get_rhai_path();
let mut reeval_parser = ParseConfig::new();
let rhai_code = reeval_parser.code_from_file(&config_path)?;
let mut scope = ParseConfig::initial_poll_listen_scope(&rhai_code)?;
if let Some(vars) = inject_vars {
for (name, val) in vars {
scope.set_value(name, Dynamic::from(val));
}
}
if !config_path.exists() {
bail!("The configuration file `{}` does not exist", config_path.display());
}
let new_root_widget =
reeval_parser.eval_code_with(&rhai_code, Some(scope), compiled_ast.as_deref())?;
let mut reeval_parser = ParseConfig::new();
let rhai_code = reeval_parser.code_from_file(&config_path)?;
match config::EwwiiConfig::get_windows_root_widget(new_root_widget) {
Ok(new_widget) => {
if let Ok(mut maybe_registry) = self.widget_reg_store.lock() {
if let Some(widget_registry) = maybe_registry.as_mut() {
let _ = widget_registry.update_widget_tree(new_widget);
} else {
log::error!("Widget registry is empty");
let mut scope = ParseConfig::initial_poll_listen_scope(&rhai_code)?;
if let Some(maybe_all_vars) = &self.pl_handler_store {
let all_vars = maybe_all_vars.read().unwrap().clone();
for (name, val) in all_vars {
scope.set_value(name.clone(), Dynamic::from(val.clone()));
}
}
if let Some(vars) = inject_vars {
for (name, val) in vars {
scope.set_value(name.clone(), Dynamic::from(val.clone()));
// Preserving the new state.
// ---
// This is esstentially storing the inject variables
// in the poll/listen variable store (or the `pl_handler_store` in self)
if should_preserve_state {
if let Some(maybe_store) = &self.pl_handler_store {
maybe_store.write().unwrap().insert(name, val);
}
} else {
log::error!("Failed to acquire lock on widget registry");
}
}
Err(e) => {
log::error!("Failed to generate new widgetnode: {:#}", e);
}
let new_root_widget = reeval_parser.eval_code_with(
&rhai_code,
Some(scope),
compiled_ast.as_deref(),
config_path.to_str(),
)?;
if let Ok(mut maybe_registry) = self.widget_reg_store.lock() {
if let Some(widget_registry) = maybe_registry.as_mut() {
let _ = widget_registry.update_widget_tree(new_root_widget);
} else {
log::error!("Widget registry is empty");
}
} else {
log::error!("Failed to acquire lock on widget registry");
}
Ok(())
@@ -726,6 +792,56 @@ impl<B: DisplayBackend> App<B> {
Ok(())
}
pub fn set_engine_overrides(&mut self, config: String) -> Result<()> {
let parsed_config: EngineConfValues = serde_json::from_str(&config)?;
self.rt_engine_config = self.rt_engine_config.merge(parsed_config);
Ok(())
}
}
#[derive(Deserialize, Debug)]
pub struct EngineConfValues {
pub batching_interval: Option<u64>,
#[serde(default, deserialize_with = "validate_optimization_level")]
pub optimization_level: Option<u8>,
}
impl EngineConfValues {
pub fn default() -> Self {
Self {
batching_interval: Some(16), // 16 ms
optimization_level: Some(1), // 1 = simple
}
}
pub fn merge(&self, val: Self) -> Self {
// could be cleaner
Self {
batching_interval: Some(
val.batching_interval.unwrap_or(self.batching_interval.unwrap_or(16)),
),
optimization_level: Some(
val.optimization_level.unwrap_or(self.optimization_level.unwrap_or(1)),
),
}
}
}
fn validate_optimization_level<'de, D>(deserializer: D) -> Result<Option<u8>, D::Error>
where
D: Deserializer<'de>,
{
let opt = Option::<u8>::deserialize(deserializer)?;
if let Some(value) = opt {
match value {
0 | 1 | 2 => Ok(Some(value)),
_ => Err(D::Error::custom("optimization_level must be 0, 1, or 2")),
}
} else {
Ok(None)
}
}
fn initialize_window<B: DisplayBackend>(
@@ -830,11 +946,21 @@ async fn generate_new_widgetnode(
bail!("The configuration file `{}` does not exist", code_path.display());
}
let new_root_widget = reeval_parser.eval_code_with(&rhai_code, Some(scope), compiled_ast)?;
let new_root_widget =
reeval_parser.eval_code_with(&rhai_code, Some(scope), compiled_ast, code_path.to_str())?;
Ok(new_root_widget)
}
fn get_opt_level_from(n: u8) -> rhai::OptimizationLevel {
match n {
0 => rhai::OptimizationLevel::None,
1 => rhai::OptimizationLevel::Simple,
2 => rhai::OptimizationLevel::Full,
_ => rhai::OptimizationLevel::Simple,
}
}
/// Apply the provided window-positioning rules to the window.
#[cfg(feature = "x11")]
fn apply_window_position(

View File

@@ -3,7 +3,7 @@ use std::process::Stdio;
use crate::{
daemon_response::DaemonResponse,
opts::{self, ActionClientOnly},
paths::EwwPaths,
paths::EwwiiPaths,
};
use anyhow::{Context, Result};
use std::{
@@ -11,7 +11,7 @@ use std::{
os::unix::net::UnixStream,
};
pub fn handle_client_only_action(paths: &EwwPaths, action: ActionClientOnly) -> Result<()> {
pub fn handle_client_only_action(paths: &EwwiiPaths, action: ActionClientOnly) -> Result<()> {
match action {
ActionClientOnly::Logs => {
std::process::Command::new("tail")

View File

@@ -1,7 +1,7 @@
use crate::{
// ipc_server,
// error_handling_ctx,
paths::EwwPaths,
paths::EwwiiPaths,
window::backend_window_options::BackendWindowOptionsDef,
};
use anyhow::{bail, Context, Result};
@@ -13,9 +13,9 @@ use rhai_impl::{ast::WidgetNode, parser::ParseConfig};
// use tokio::{net::UnixStream, runtime::Runtime, sync::mpsc};
/// Load an [`EwwiiConfig`] from the config dir of the given [`crate::EwwPaths`],
/// Load an [`EwwiiConfig`] from the config dir of the given [`crate::EwwiiPaths`],
/// resetting and applying the global YuckFiles object in [`crate::error_handling_ctx`].
pub fn read_from_ewwii_paths(eww_paths: &EwwPaths) -> Result<EwwiiConfig> {
pub fn read_from_ewwii_paths(eww_paths: &EwwiiPaths) -> Result<EwwiiConfig> {
EwwiiConfig::read_from_dir(eww_paths)
}
@@ -36,8 +36,8 @@ pub struct WindowDefinition {
}
impl EwwiiConfig {
/// Load an [`EwwiiConfig`] from the config dir of the given [`crate::EwwPaths`], reading the main config file.
pub fn read_from_dir(eww_paths: &EwwPaths) -> Result<Self> {
/// Load an [`EwwiiConfig`] from the config dir of the given [`crate::EwwiiPaths`], reading the main config file.
pub fn read_from_dir(eww_paths: &EwwiiPaths) -> Result<Self> {
let rhai_path = eww_paths.get_rhai_path();
if !rhai_path.exists() {
bail!("The configuration file `{}` does not exist", rhai_path.display());
@@ -49,13 +49,18 @@ impl EwwiiConfig {
// get code from file
let rhai_code = config_parser.code_from_file(&rhai_path)?;
// Get Option<&str> form of rhai_path
let rhai_path_opt_str = rhai_path.to_str();
// get the iirhai widget tree
let compiled_ast = config_parser.compile_code(&rhai_code)?;
let compiled_ast =
config_parser.compile_code(&rhai_code, rhai_path_opt_str.unwrap_or("<rhai>"))?;
let poll_listen_scope = ParseConfig::initial_poll_listen_scope(&rhai_code)?;
let config_tree = config_parser.eval_code_with(
&rhai_code,
Some(poll_listen_scope),
Some(&compiled_ast),
rhai_path_opt_str,
)?;
let mut window_definitions = HashMap::new();
@@ -104,19 +109,6 @@ impl EwwiiConfig {
self.root_node.clone().ok_or_else(|| anyhow::anyhow!("root_node is missing"))
}
pub fn get_windows_root_widget(config_tree: WidgetNode) -> Result<WidgetNode> {
if let WidgetNode::Enter(children) = config_tree {
for node in children {
if let WidgetNode::DefWindow { node: boxed_node, .. } = node {
return Ok(*boxed_node);
}
}
bail!("No `DefWindow` found inside `Enter`");
} else {
bail!("Expected root node to be `Enter`, but got something else.");
}
}
pub fn get_owned_compiled_ast(&self) -> Option<Rc<AST>> {
self.compiled_ast.clone()
}

View File

@@ -1,6 +1,6 @@
//! Types to manage messages that notify the eww client over the result of a command
//! Types to manage messages that notify the ewwii client over the result of a command
//!
//! Communcation between the daemon and eww client happens via IPC.
//! Communcation between the daemon and ewwii client happens via IPC.
//! If the daemon needs to send messages back to the client as a response to a command (mostly for CLI output),
//! this happens via the DaemonResponse types

View File

@@ -63,30 +63,6 @@ mod platform_wayland {
y: i32,
) -> Option<Window> {
let window = Window::new(gtk::WindowType::Toplevel, x, y);
// Initialising a layer shell surface
window.init_layer_shell();
// Sets the monitor where the surface is shown
if let Some(ident) = window_init.monitor.clone() {
let display = gdk::Display::default().expect("could not get default display");
if let Some(monitor) = crate::app::get_monitor_from_display(&display, &ident) {
window.set_monitor(&monitor);
} else {
return None;
}
};
window.set_resizable(window_init.resizable);
// Sets the layer where the layer shell surface will spawn
match window_init.stacking {
WindowStacking::Foreground => window.set_layer(gtk_layer_shell::Layer::Top),
WindowStacking::Background => window.set_layer(gtk_layer_shell::Layer::Background),
WindowStacking::Bottom => window.set_layer(gtk_layer_shell::Layer::Bottom),
WindowStacking::Overlay => window.set_layer(gtk_layer_shell::Layer::Overlay),
}
if let Some(namespace) = &window_init.backend_options.wayland.namespace {
window.set_namespace(namespace);
}
// Sets the keyboard interactivity
match window_init.backend_options.wayland.focusable {
@@ -95,53 +71,84 @@ mod platform_wayland {
WlWindowFocusable::OnDemand => window.set_keyboard_mode(KeyboardMode::OnDemand),
}
if let Some(geometry) = window_init.geometry {
// Positioning surface
let mut top = false;
let mut left = false;
let mut right = false;
let mut bottom = false;
window.set_resizable(window_init.resizable);
match geometry.anchor_point.x {
AnchorAlignment::START => left = true,
AnchorAlignment::CENTER => {}
AnchorAlignment::END => right = true,
}
match geometry.anchor_point.y {
AnchorAlignment::START => top = true,
AnchorAlignment::CENTER => {}
AnchorAlignment::END => bottom = true,
if !window_init.backend_options.wayland.force_normal {
// Initialising a layer shell surface
window.init_layer_shell();
// Sets the monitor where the surface is shown
if let Some(ident) = window_init.monitor.clone() {
let display = gdk::Display::default().expect("could not get default display");
if let Some(monitor) = crate::app::get_monitor_from_display(&display, &ident) {
window.set_monitor(&monitor);
} else {
return None;
}
};
// Sets the layer where the layer shell surface will spawn
match window_init.stacking {
WindowStacking::Foreground => window.set_layer(gtk_layer_shell::Layer::Top),
WindowStacking::Background => {
window.set_layer(gtk_layer_shell::Layer::Background)
}
WindowStacking::Bottom => window.set_layer(gtk_layer_shell::Layer::Bottom),
WindowStacking::Overlay => window.set_layer(gtk_layer_shell::Layer::Overlay),
}
window.set_anchor(gtk_layer_shell::Edge::Left, left);
window.set_anchor(gtk_layer_shell::Edge::Right, right);
window.set_anchor(gtk_layer_shell::Edge::Top, top);
window.set_anchor(gtk_layer_shell::Edge::Bottom, bottom);
let xoffset = geometry.offset.x.pixels_relative_to(monitor.width());
let yoffset = geometry.offset.y.pixels_relative_to(monitor.height());
if left {
window.set_layer_shell_margin(gtk_layer_shell::Edge::Left, xoffset);
} else {
window.set_layer_shell_margin(gtk_layer_shell::Edge::Right, xoffset);
if let Some(namespace) = &window_init.backend_options.wayland.namespace {
window.set_namespace(namespace);
}
if bottom {
window.set_layer_shell_margin(gtk_layer_shell::Edge::Bottom, yoffset);
} else {
window.set_layer_shell_margin(gtk_layer_shell::Edge::Top, yoffset);
if let Some(geometry) = window_init.geometry {
// Positioning surface
let mut top = false;
let mut left = false;
let mut right = false;
let mut bottom = false;
match geometry.anchor_point.x {
AnchorAlignment::START => left = true,
AnchorAlignment::CENTER => {}
AnchorAlignment::END => right = true,
}
match geometry.anchor_point.y {
AnchorAlignment::START => top = true,
AnchorAlignment::CENTER => {}
AnchorAlignment::END => bottom = true,
}
window.set_anchor(gtk_layer_shell::Edge::Left, left);
window.set_anchor(gtk_layer_shell::Edge::Right, right);
window.set_anchor(gtk_layer_shell::Edge::Top, top);
window.set_anchor(gtk_layer_shell::Edge::Bottom, bottom);
let xoffset = geometry.offset.x.pixels_relative_to(monitor.width());
let yoffset = geometry.offset.y.pixels_relative_to(monitor.height());
if left {
window.set_layer_shell_margin(gtk_layer_shell::Edge::Left, xoffset);
} else {
window.set_layer_shell_margin(gtk_layer_shell::Edge::Right, xoffset);
}
if bottom {
window.set_layer_shell_margin(gtk_layer_shell::Edge::Bottom, yoffset);
} else {
window.set_layer_shell_margin(gtk_layer_shell::Edge::Top, yoffset);
}
// https://github.com/elkowar/eww/issues/296
if window_init.backend_options.wayland.exclusive
&& geometry.anchor_point.x != AnchorAlignment::CENTER
&& geometry.anchor_point.y != AnchorAlignment::CENTER
{
log::warn!("When ':exclusive true' the anchor has to include 'center', otherwise exlcusive won't work")
}
}
// https://github.com/elkowar/eww/issues/296
if window_init.backend_options.wayland.exclusive
&& geometry.anchor_point.x != AnchorAlignment::CENTER
&& geometry.anchor_point.y != AnchorAlignment::CENTER
{
log::warn!("When ':exclusive true' the anchor has to include 'center', otherwise exlcusive won't work")
if window_init.backend_options.wayland.exclusive {
window.auto_exclusive_zone_enable();
}
}
if window_init.backend_options.wayland.exclusive {
window.auto_exclusive_zone_enable();
}
Some(window)
}
}

View File

@@ -28,7 +28,7 @@ use clap::CommandFactory as _;
use daemon_response::{DaemonResponse, DaemonResponseReceiver};
use display_backend::DisplayBackend;
use opts::ActionWithServer;
use paths::EwwPaths;
use paths::EwwiiPaths;
use std::{os::unix::net, path::Path, time::Duration};
use crate::server::ForkResult;
@@ -56,9 +56,8 @@ mod window_arguments;
mod window_initiator;
fn main() {
// gets the eww binary
let eww_binary_name = std::env::args().next().unwrap();
let opts: opts::Opt = opts::Opt::from_env(); // opts of clap (from ./opts.rs)
let ewwii_binary_name = std::env::args().next().unwrap();
let opts: opts::Opt = opts::Opt::from_env();
let trace_enabled = std::env::var("EWWII_TRACE").is_ok();
@@ -101,14 +100,14 @@ fn main() {
opts.force_wayland,
detected_wayland
);
run::<display_backend::WaylandBackend>(opts, eww_binary_name)
run::<display_backend::WaylandBackend>(opts, ewwii_binary_name)
} else {
log::debug!(
"Running on X11. force_wayland={}, detected_wayland={}",
opts.force_wayland,
detected_wayland
);
run::<display_backend::X11Backend>(opts, eww_binary_name)
run::<display_backend::X11Backend>(opts, ewwii_binary_name)
};
#[cfg(all(not(feature = "wayland"), feature = "x11"))]
@@ -116,14 +115,14 @@ fn main() {
if use_wayland {
log::warn!("Ewwii compiled without wayland support. Falling back to X11, eventhough wayland was requested.");
}
run::<display_backend::X11Backend>(opts, eww_binary_name)
run::<display_backend::X11Backend>(opts, ewwii_binary_name)
};
#[cfg(all(feature = "wayland", not(feature = "x11")))]
let result = run::<display_backend::WaylandBackend>(opts, eww_binary_name);
let result = run::<display_backend::WaylandBackend>(opts, ewwii_binary_name);
#[cfg(not(any(feature = "wayland", feature = "x11")))]
let result = run::<display_backend::NoBackend>(opts, eww_binary_name);
let result = run::<display_backend::NoBackend>(opts, ewwii_binary_name);
if let Err(err) = result {
error_handling_ctx::print_error(err);
@@ -139,11 +138,11 @@ fn detect_wayland() -> bool {
|| (!wayland_display.is_empty() && !session_type.contains("x11"))
}
fn run<B: DisplayBackend>(opts: opts::Opt, eww_binary_name: String) -> Result<()> {
fn run<B: DisplayBackend>(opts: opts::Opt, ewwii_binary_name: String) -> Result<()> {
let paths = opts
.config_path
.map(EwwPaths::from_config_dir)
.unwrap_or_else(EwwPaths::default)
.map(EwwiiPaths::from_config_dir)
.unwrap_or_else(EwwiiPaths::default)
.context("Failed to initialize ewwii paths")?;
let should_restart = match &opts.action {
@@ -167,12 +166,11 @@ fn run<B: DisplayBackend>(opts: opts::Opt, eww_binary_name: String) -> Result<()
false
}
// make sure that there isn't already a Eww daemon running.
// make sure that there isn't already a Ewwii daemon running.
opts::Action::Daemon if check_server_running(paths.get_ipc_socket_file()) => {
eprintln!("Ewwii server already running.");
true
}
// initializing the eww server i see..
opts::Action::Daemon => {
log::info!("Initializing Ewwii server. ({})", paths.get_ipc_socket_file().display());
let _ = std::fs::remove_file(paths.get_ipc_socket_file());
@@ -180,7 +178,7 @@ fn run<B: DisplayBackend>(opts: opts::Opt, eww_binary_name: String) -> Result<()
if !opts.show_logs {
println!(
"Run `{} logs` to see any errors while editing your configuration.",
eww_binary_name
ewwii_binary_name
);
}
let fork_result =
@@ -217,7 +215,7 @@ fn run<B: DisplayBackend>(opts: opts::Opt, eww_binary_name: String) -> Result<()
if !opts.show_logs {
println!(
"Run `{} logs` to see any errors while editing your configuration.",
eww_binary_name
ewwii_binary_name
);
}
@@ -259,7 +257,7 @@ fn listen_for_daemon_response(mut recv: DaemonResponseReceiver) {
/// attempt to send a command to the daemon and send it the given action repeatedly.
fn handle_server_command(
paths: &EwwPaths,
paths: &EwwiiPaths,
action: &ActionWithServer,
connect_attempts: usize,
) -> Result<Option<DaemonResponse>> {
@@ -295,7 +293,7 @@ fn attempt_connect(socket_path: impl AsRef<Path>, attempts: usize) -> Option<net
None
}
/// Check if a eww server is currently running by trying to send a ping message to it.
/// Check if a ewwii server is currently running by trying to send a ping message to it.
fn check_server_running(socket_path: impl AsRef<Path>) -> bool {
let response = net::UnixStream::connect(socket_path).ok().and_then(|mut stream| {
client::do_server_call(&mut stream, &opts::ActionWithServer::Ping).ok()

View File

@@ -164,13 +164,9 @@ pub enum ActionWithServer {
#[command(name = "close-all", alias = "ca")]
CloseAll,
// /// Prints the variables used in all currently open window
// #[command(name = "state")]
// ShowState {
// /// Shows all variables, including not currently used ones
// #[arg(short, long)]
// all: bool,
// },
/// Prints all the variables in the registery
#[command(name = "state")]
ShowState,
/// List the names of active windows
#[command(name = "list-windows")]
ListWindows,
@@ -193,19 +189,34 @@ pub enum ActionWithServer {
TriggerUpdateUI {
/// Inject variables while updating the UI
///
/// Format: --inject-vars foo="val1" baz="val2"
/// Format: --inject foo="val1" baz="val2"
/// Only variables used by the widget tree will affect the UI.
#[arg(long, value_parser = parse_inject_var_map)]
#[arg(long = "inject", short = 'i', value_parser = parse_inject_var_map)]
inject_vars: Option<HashMap<String, String>>,
/// Preserve the new updates. Only meaningful if used with inject.
#[arg(long = "preserve", short = 'p')]
should_preserve_state: bool,
},
/// Call rhai functions. (NOTE: All poll/listen will default to their initial value)
#[command(name = "call-fns")]
CallRhaiFns {
// Rhai functions to call. Format: --fn-calls "fn_name1(args)" "fn_name2(args)"
/// Rhai functions to call. Format: call-fns "fn_name1(args)" "fn_name2(args)"
#[arg(required = true)]
calls: Vec<String>,
},
/// Override the default runtime engine settings
#[command(name = "engine-override")]
EngineOverride {
/// Configuration in JSON format
config_json: String,
/// Weather to print the current engine settings
#[arg(long = "sprint", short = 'p')]
print: bool,
},
}
impl Opt {
@@ -267,8 +278,12 @@ impl ActionWithServer {
self,
) -> (app::DaemonCommand, Option<daemon_response::DaemonResponseReceiver>) {
let command = match self {
ActionWithServer::TriggerUpdateUI { inject_vars } => {
app::DaemonCommand::TriggerUpdateUI(inject_vars)
ActionWithServer::TriggerUpdateUI { inject_vars, should_preserve_state } => {
return with_response_channel(|sender| app::DaemonCommand::TriggerUpdateUI {
inject_vars,
should_preserve_state,
sender,
})
}
ActionWithServer::CallRhaiFns { calls } => {
return with_response_channel(|sender| app::DaemonCommand::CallRhaiFns {
@@ -276,7 +291,6 @@ impl ActionWithServer {
sender,
})
}
ActionWithServer::OpenInspector => app::DaemonCommand::OpenInspector,
ActionWithServer::KillServer => app::DaemonCommand::KillServer,
@@ -322,6 +336,9 @@ impl ActionWithServer {
ActionWithServer::Reload => {
return with_response_channel(app::DaemonCommand::ReloadConfigAndCss)
}
ActionWithServer::ShowState => {
return with_response_channel(app::DaemonCommand::ShowState)
}
ActionWithServer::ListWindows => {
return with_response_channel(app::DaemonCommand::ListWindows)
}
@@ -331,6 +348,13 @@ impl ActionWithServer {
ActionWithServer::ShowDebug => {
return with_response_channel(app::DaemonCommand::PrintDebug)
}
ActionWithServer::EngineOverride { config_json, print } => {
return with_response_channel(|sender| app::DaemonCommand::EngineOverride {
config: config_json,
print,
sender,
})
}
};
(command, None)
}

View File

@@ -6,17 +6,16 @@ use std::{
use anyhow::{bail, Result};
/// Stores references to all the paths relevant to eww, and abstracts access to these files and directories
/// Stores references to all the paths relevant to ewwii, and abstracts access to these files and directories
#[derive(Debug, Clone)]
pub struct EwwPaths {
pub struct EwwiiPaths {
pub log_file: PathBuf,
pub log_dir: PathBuf,
pub ipc_socket_file: PathBuf,
pub config_dir: PathBuf,
}
// all the eww paths i suppose from the name?
impl EwwPaths {
impl EwwiiPaths {
pub fn from_config_dir<P: AsRef<Path>>(config_dir: P) -> Result<Self> {
let config_dir = config_dir.as_ref();
if config_dir.is_file() {
@@ -55,9 +54,9 @@ impl EwwPaths {
std::fs::create_dir_all(&log_dir)?;
}
Ok(EwwPaths {
Ok(Self {
config_dir,
log_file: log_dir.join(format!("eww_{}.log", daemon_id)),
log_file: log_dir.join(format!("ewwii_{}.log", daemon_id)),
log_dir,
ipc_socket_file,
})
@@ -94,7 +93,7 @@ impl EwwPaths {
}
}
impl std::fmt::Display for EwwPaths {
impl std::fmt::Display for EwwiiPaths {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,

View File

@@ -1,8 +1,8 @@
use crate::{
app::{self, App, DaemonCommand},
app::{self, App, DaemonCommand, EngineConfValues},
config, daemon_response,
display_backend::DisplayBackend,
error_handling_ctx, ipc_server, EwwPaths,
error_handling_ctx, ipc_server, EwwiiPaths,
};
use anyhow::{Context, Result};
@@ -19,7 +19,7 @@ use std::{
use tokio::sync::mpsc::*;
pub fn initialize_server<B: DisplayBackend>(
paths: EwwPaths,
paths: EwwiiPaths,
action: Option<DaemonCommand>,
should_daemonize: bool,
) -> Result<ForkResult> {
@@ -88,6 +88,7 @@ pub fn initialize_server<B: DisplayBackend>(
window_close_timer_abort_senders: HashMap::new(),
widget_reg_store: std::rc::Rc::new(std::sync::Mutex::new(None)),
pl_handler_store: None,
rt_engine_config: EngineConfValues::default(),
paths,
phantom: PhantomData,
};
@@ -165,7 +166,7 @@ fn reload_config_and_css(ui_send: &UnboundedSender<DaemonCommand>) -> Result<()>
}
fn init_async_part(
paths: EwwPaths,
paths: EwwiiPaths,
ui_send: UnboundedSender<app::DaemonCommand>,
) -> tokio::runtime::Handle {
let rt = tokio::runtime::Builder::new_multi_thread()
@@ -316,7 +317,7 @@ fn do_detach(log_file_path: impl AsRef<Path>) -> Result<ForkResult> {
/// Ensure the log directory never grows larger than 100MB by deleting files older than 7 days,
/// and truncating all other logfiles to 100MB.
fn cleanup_log_dir(log_dir: impl AsRef<Path>) -> Result<()> {
// Find all files named "eww_*.log" in the log directory
// Find all files named "ewwii_*.log" in the log directory
let log_files = std::fs::read_dir(&log_dir)?
.filter_map(|entry| {
let entry = entry.ok()?;

View File

@@ -484,7 +484,6 @@ pub(super) fn build_gtk_event_box(
timeout,
&onscroll,
&[if delta < 0f64 { "up" } else { "down" }],
None,
);
}
glib::Propagation::Proceed
@@ -499,7 +498,7 @@ pub(super) fn build_gtk_event_box(
widget,
widget.connect_enter_notify_event(move |_, evt| {
if evt.detail() != NotifyType::Inferior {
run_command(timeout, &onhover, &[evt.position().0, evt.position().1], None);
run_command(timeout, &onhover, &[evt.position().0, evt.position().1]);
}
glib::Propagation::Proceed
})
@@ -513,12 +512,7 @@ pub(super) fn build_gtk_event_box(
widget,
widget.connect_leave_notify_event(move |_, evt| {
if evt.detail() != NotifyType::Inferior {
run_command(
timeout,
&onhoverlost,
&[evt.position().0, evt.position().1],
None,
);
run_command(timeout, &onhoverlost, &[evt.position().0, evt.position().1]);
}
glib::Propagation::Proceed
})
@@ -585,14 +579,12 @@ pub(super) fn build_gtk_event_box(
timeout,
&ondropped,
&[data.to_string(), "file".to_string()],
None,
);
} else if let Some(data) = selection_data.text() {
run_command(
timeout,
&ondropped,
&[data.to_string(), "text".to_string()],
None,
);
}
}
@@ -649,9 +641,9 @@ pub(super) fn build_gtk_event_box(
widget,
widget.connect_button_release_event(move |_, evt| {
match evt.button() {
1 => run_command(timeout, &onclick, &[] as &[&str], None),
2 => run_command(timeout, &onmiddleclick, &[] as &[&str], None),
3 => run_command(timeout, &onrightclick, &[] as &[&str], None),
1 => run_command(timeout, &onclick, &[] as &[&str]),
2 => run_command(timeout, &onmiddleclick, &[] as &[&str]),
3 => run_command(timeout, &onrightclick, &[] as &[&str]),
_ => {}
}
glib::Propagation::Proceed
@@ -1135,9 +1127,9 @@ pub(super) fn build_gtk_button(
widget,
widget.connect_button_release_event(move |_, evt| {
match evt.button() {
1 => run_command(timeout, &onclick, &[] as &[&str], None),
2 => run_command(timeout, &onmiddleclick, &[] as &[&str], None),
3 => run_command(timeout, &onrightclick, &[] as &[&str], None),
1 => run_command(timeout, &onclick, &[] as &[&str]),
2 => run_command(timeout, &onmiddleclick, &[] as &[&str]),
3 => run_command(timeout, &onrightclick, &[] as &[&str]),
_ => {}
}
glib::Propagation::Proceed
@@ -1149,9 +1141,9 @@ pub(super) fn build_gtk_button(
widget.connect_key_release_event(move |_, evt| {
match evt.scancode() {
// return
36 => run_command(timeout, &onclick_, &[] as &[&str], None),
36 => run_command(timeout, &onclick_, &[] as &[&str]),
// space
65 => run_command(timeout, &onclick_, &[] as &[&str], None),
65 => run_command(timeout, &onclick_, &[] as &[&str]),
_ => {}
}
glib::Propagation::Proceed
@@ -1326,13 +1318,7 @@ pub(super) fn build_gtk_input(
connect_signal_handler!(
widget,
widget.connect_changed(move |widget| {
let input_val = widget.text().to_string();
run_command(
timeout,
&onchange,
&[widget.text().to_string()],
Some(vec![("INPUT_VAL".to_string(), input_val)]),
);
run_command(timeout, &onchange, &[widget.text().to_string()]);
})
);
}
@@ -1341,13 +1327,7 @@ pub(super) fn build_gtk_input(
connect_signal_handler!(
widget,
widget.connect_activate(move |widget| {
let input_val = widget.text().to_string();
run_command(
timeout,
&onaccept,
&[widget.text().to_string()],
Some(vec![("INPUT_VAL".to_string(), input_val)]),
);
run_command(timeout, &onaccept, &[widget.text().to_string()]);
})
);
}
@@ -1441,7 +1421,7 @@ pub(super) fn build_gtk_calendar(
connect_signal_handler!(
widget,
widget.connect_day_selected(move |w| {
run_command(timeout, &onclick, &[w.day(), w.month(), w.year()], None)
run_command(timeout, &onclick, &[w.day(), w.month(), w.year()])
})
);
}
@@ -1497,7 +1477,6 @@ pub(super) fn build_gtk_combo_box_text(
timeout,
&onchange,
&[widget.active_text().unwrap_or_else(|| "".into())],
None,
);
})
);
@@ -1667,7 +1646,6 @@ pub(super) fn build_gtk_checkbox(
timeout,
if widget.is_active() { &onchecked } else { &onunchecked },
&[] as &[&str],
None,
);
})
);
@@ -1720,7 +1698,7 @@ pub(super) fn build_gtk_color_button(
connect_signal_handler!(
widget,
widget.connect_color_set(move |widget| {
run_command(timeout, &onchange, &[widget.rgba()], None);
run_command(timeout, &onchange, &[widget.rgba()]);
})
);
}
@@ -1773,7 +1751,7 @@ pub(super) fn build_gtk_color_chooser(
connect_signal_handler!(
widget,
widget.connect_color_activated(move |_a, color| {
run_command(timeout, &onchange, &[*color], None);
run_command(timeout, &onchange, &[*color]);
})
);
}
@@ -2068,7 +2046,7 @@ pub(super) fn resolve_range_attrs(
gtk_widget.connect_value_changed(move |gtk_widget| {
let value = gtk_widget.value();
if last_set_value.borrow_mut().take() != Some(value) {
run_command(timeout, &onchange, &[value], None);
run_command(timeout, &onchange, &[value]);
}
})
);

View File

@@ -5,12 +5,8 @@ use rhai::Map;
use std::process::Command;
// Run a command and get the output
pub(super) fn run_command<T>(
timeout: std::time::Duration,
cmd: &str,
args: &[T],
injected_vars: Option<Vec<(String, String)>>,
) where
pub(super) fn run_command<T>(timeout: std::time::Duration, cmd: &str, args: &[T])
where
T: 'static + std::fmt::Display + Send + Sync + Clone,
{
use wait_timeout::ChildExt;
@@ -26,12 +22,6 @@ pub(super) fn run_command<T>(
let mut command = Command::new("/bin/sh");
command.arg("-c").arg(&cmd);
if let Some(vars) = injected_vars {
for (key, value) in vars {
command.env(key, value);
}
}
let child = command.spawn();
match child {
Ok(mut child) => match child.wait_timeout(timeout) {

View File

@@ -81,6 +81,7 @@ impl BackendWindowOptionsDef {
exclusive: Self::get_optional(map, "exclusive")?,
focusable,
namespace: Self::get_optional(map, "namespace")?,
force_normal: Self::get_optional(map, "force_normal")?,
};
Ok(Self { wayland, x11 })
@@ -167,6 +168,7 @@ pub struct WlBackendWindowOptions {
pub exclusive: bool,
pub focusable: WlWindowFocusable,
pub namespace: Option<String>,
pub force_normal: bool,
}
/// Unevaluated form of [`WlBackendWindowOptions`]
@@ -175,6 +177,7 @@ pub struct WlBackendWindowOptionsDef {
pub exclusive: Option<bool>,
pub focusable: Option<String>,
pub namespace: Option<String>,
pub force_normal: Option<bool>,
}
impl WlBackendWindowOptionsDef {
@@ -189,6 +192,10 @@ impl WlBackendWindowOptionsDef {
None => WlWindowFocusable::default(),
},
namespace: properties.get("namespace").map(|d| d.clone_cast::<String>()),
force_normal: properties
.get("force_normal")
.map(|d| d.clone_cast::<bool>())
.unwrap_or(false),
})
}
}
@@ -219,9 +226,6 @@ impl FromStr for WlWindowFocusable {
"none" => Self::None,
"exclusive" => Self::Exclusive,
"ondemand" => Self::OnDemand,
// legacy support
"true" => Self::Exclusive,
"false" => Self::None,
}
}
}

View File

@@ -22,5 +22,6 @@ ahash.workspace = true
nix = { workspace = true, features = ["process", "fs", "signal"] }
libc.workspace = true
# error handling
rhai_trace = "0.2.0"
codespan-reporting.workspace = true
rhai_trace = "0.3.0"
codespan-reporting.workspace = true
regex.workspace = true

View File

@@ -4,7 +4,7 @@ use rhai::{Dynamic, Map};
impl WidgetNode {
/// A very important implementation of [`WidgetNode`].
/// This function implements dyn_id property to widgets.
pub fn setup_for_rt(&self, parent_path: &str) -> Self {
pub fn setup_dyn_ids(&self, parent_path: &str) -> Self {
// fn to assign dyn_id to a node
fn with_dyn_id(mut props: Map, dyn_id: &str) -> Map {
props.insert("dyn_id".into(), Dynamic::from(dyn_id.to_string()));
@@ -22,7 +22,7 @@ impl WidgetNode {
.enumerate()
.map(|(idx, child)| {
let child_path = format!("{}_{}_{}", parent_path, kind, idx);
child.setup_for_rt(&child_path)
child.setup_dyn_ids(&child_path)
})
.collect()
}
@@ -31,7 +31,7 @@ impl WidgetNode {
WidgetNode::DefWindow { name, props, node } => WidgetNode::DefWindow {
name: name.clone(),
props: props.clone(),
node: Box::new(node.setup_for_rt(name)),
node: Box::new(node.setup_dyn_ids(name)),
},
// == Containers with children ==

View File

@@ -5,7 +5,12 @@ use rhai::{Engine, EvalAltResult, ParseError};
use rhai_trace::{BetterError, Span};
/// Return a formatted Rhai evaluation error.
pub fn format_eval_error(error: &EvalAltResult, code: &str, engine: &Engine) -> String {
pub fn format_eval_error(
error: &EvalAltResult,
code: &str,
engine: &Engine,
file_id: Option<&str>,
) -> String {
let better_error =
BetterError::improve_eval_error(error, code, engine, None).unwrap_or(BetterError {
message: error.to_string(),
@@ -14,11 +19,11 @@ pub fn format_eval_error(error: &EvalAltResult, code: &str, engine: &Engine) ->
note: None,
span: Span::new(0, 0, 0, 0),
});
format_codespan_error(better_error, code)
format_codespan_error(better_error, code, file_id)
}
/// Return a formatted Rhai parse error.
pub fn format_parse_error(error: &ParseError, code: &str) -> String {
pub fn format_parse_error(error: &ParseError, code: &str, file_id: Option<&str>) -> String {
let better_error = BetterError::improve_parse_error(error, code).unwrap_or(BetterError {
message: error.to_string(),
help: None,
@@ -26,13 +31,13 @@ pub fn format_parse_error(error: &ParseError, code: &str) -> String {
note: None,
span: Span::new(0, 0, 0, 0),
});
format_codespan_error(better_error, code)
format_codespan_error(better_error, code, file_id)
}
/// Return a formatted error as a String
pub fn format_codespan_error(be: BetterError, code: &str) -> String {
pub fn format_codespan_error(be: BetterError, code: &str, file_id: Option<&str>) -> String {
let mut files = SimpleFiles::new();
let file_id = files.add("<rhai>", code);
let file_id = files.add(file_id.unwrap_or("<rhai>"), code);
// build the notes
let mut notes = Vec::new();

View File

@@ -15,7 +15,7 @@ pub fn extract_poll_and_listen_vars(code: &str) -> Result<Vec<(String, Option<St
results.push((sig.var, initial));
}
Err(e) => {
return Err(anyhow::anyhow!(format_eval_error(&e, code, &engine)));
return Err(anyhow::anyhow!(format_eval_error(&e, code, &engine, None)));
}
}
}

View File

@@ -45,8 +45,10 @@ impl ModuleResolver for SimpleFileResolver {
})?;
let ast: AST = engine.compile(&script).map_err(|e| {
log::error!("{}", format_parse_error(&e, &script));
e
Box::new(EvalAltResult::ErrorSystem(
"module_parse_failed".into(),
format_parse_error(&e, &script, full_path.to_str()).into(),
))
})?;
let scope = ParseConfig::initial_poll_listen_scope(&script).map_err(|e| {
EvalAltResult::ErrorSystem(
@@ -55,8 +57,10 @@ impl ModuleResolver for SimpleFileResolver {
)
})?;
let mut module = Module::eval_ast_as_new(scope, &ast, engine).map_err(|e| {
log::error!("{}", format_eval_error(&e, &script, engine));
e
Box::new(EvalAltResult::ErrorSystem(
"module_eval_failed".into(),
format_eval_error(&e, &script, engine, full_path.to_str()).into(),
))
})?;
module.build_index();
@@ -80,6 +84,12 @@ impl<R1: ModuleResolver, R2: ModuleResolver> ModuleResolver for ChainedResolver<
match self.first.resolve(engine, source_path, path, pos) {
Ok(m) => Ok(m),
Err(e1) => {
if let EvalAltResult::ErrorSystem(msg, _) = e1.as_ref() {
if msg == "module_eval_failed" || msg == "module_parse_failed" {
return Err(e1);
}
}
log::trace!(
"Error executing resolver 1, falling back to resolver 2. Error details: {}",
e1

View File

@@ -7,7 +7,7 @@ use crate::{
providers::register_all_providers,
};
use anyhow::{anyhow, Result};
use rhai::{Dynamic, Engine, Scope, AST};
use rhai::{Dynamic, Engine, OptimizationLevel, Scope, AST};
use std::cell::RefCell;
use std::fs;
use std::path::Path;
@@ -32,13 +32,10 @@ impl ParseConfig {
Self { engine, all_nodes }
}
pub fn eval_code(&mut self, code: &str) -> Result<WidgetNode> {
let ast = self.engine.compile(code)?;
self.eval_code_with(code, None, Some(&ast))
}
pub fn compile_code(&mut self, code: &str) -> Result<AST> {
self.engine.compile(code).map_err(|e| anyhow!(format_parse_error(&e, code)))
pub fn compile_code(&mut self, code: &str, file_path: &str) -> Result<AST> {
self.engine
.compile(code)
.map_err(|e| anyhow!(format_parse_error(&e, code, Some(file_path))))
}
pub fn eval_code_with(
@@ -46,6 +43,7 @@ impl ParseConfig {
code: &str,
rhai_scope: Option<Scope>,
compiled_ast: Option<&AST>,
file_id: Option<&str>,
) -> Result<WidgetNode> {
let mut scope = match rhai_scope {
Some(s) => s,
@@ -57,12 +55,12 @@ impl ParseConfig {
let _ = self
.engine
.eval_ast_with_scope::<Dynamic>(&mut scope, &ast)
.map_err(|e| anyhow!(format_eval_error(&e, code, &self.engine)))?;
.map_err(|e| anyhow!(format_eval_error(&e, code, &self.engine, file_id)))?;
} else {
let _ = self
.engine
.eval_with_scope::<Dynamic>(&mut scope, code)
.map_err(|e| anyhow!(format_eval_error(&e, code, &self.engine)))?;
.map_err(|e| anyhow!(format_eval_error(&e, code, &self.engine, file_id)))?;
};
// Merge all nodes in all_nodes (`enter([])`) into a single root node
@@ -83,7 +81,7 @@ impl ParseConfig {
WidgetNode::Enter(merged_children)
};
Ok(merged_node.setup_for_rt("root"))
Ok(merged_node.setup_dyn_ids("root"))
}
pub fn code_from_file<P: AsRef<Path>>(&mut self, file_path: P) -> Result<String> {
@@ -144,4 +142,8 @@ impl ParseConfig {
}
}
}
pub fn set_opt_level(&mut self, opt_lvl: OptimizationLevel) {
self.engine.set_optimization_level(opt_lvl);
}
}

View File

@@ -20,7 +20,7 @@ pub mod linux {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::linux" as linux;
///
/// let k_version = linux::get_kernel_version();
@@ -44,7 +44,7 @@ pub mod linux {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::linux" as linux;
///
/// let battery_perc = linux::get_battery_perc();
@@ -88,7 +88,7 @@ pub mod linux {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::linux" as linux;
///
/// let cpu_info = linux::get_cpu_info();
@@ -143,7 +143,7 @@ pub mod linux {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::linux" as linux;
///
/// let ram_info = linux::get_ram_info();
@@ -201,7 +201,7 @@ pub mod linux {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::linux" as linux;
///
/// let gpu_info = linux::get_gpu_info();
@@ -272,7 +272,7 @@ pub mod linux {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::linux" as linux;
///
/// let disk_info = linux::get_disk_info();

View File

@@ -21,7 +21,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// let networks = wifi::scan();
@@ -66,7 +66,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// let networks = wifi::scan();
@@ -111,7 +111,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// let networks = wifi::scan();
@@ -146,7 +146,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// let connection = wifi::current_connection();
@@ -225,7 +225,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// wifi::connect("MySecretNetwork", "password123");
@@ -277,7 +277,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// wifi::connect_without_password("MySecretNetwork", "password123");
@@ -329,7 +329,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// wifi::disconnect();
@@ -402,7 +402,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// wifi::disable_adapter();
@@ -453,7 +453,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// wifi::enable_adapter();
@@ -516,7 +516,7 @@ pub mod wifi {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "api::wifi" as wifi;
///
/// wifi::enable_adapter();

View File

@@ -17,7 +17,7 @@ pub mod command {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::command" as cmd;
///
/// // Run a shell command (e.g., list directory contents)
@@ -46,7 +46,7 @@ pub mod command {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::command" as cmd;
///
/// // Run a shell command and capture its output

View File

@@ -16,7 +16,7 @@ pub mod env {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::env" as env;
///
/// // Get the value of the "HOME" environment variable
@@ -41,7 +41,7 @@ pub mod env {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::env" as env;
///
/// // Set the value of the "MY_VAR" environment variable
@@ -60,7 +60,7 @@ pub mod env {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::env" as env;
///
/// // Get the home directory
@@ -81,7 +81,7 @@ pub mod env {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::env" as env;
///
/// // Get the current working directory
@@ -106,7 +106,7 @@ pub mod env {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::env" as env;
///
/// // Get the username of the current user

View File

@@ -1,23 +1,25 @@
pub mod command;
pub mod env;
pub mod monitor;
pub mod regex;
pub mod text;
use rhai::exported_module;
use rhai::module_resolvers::StaticModuleResolver;
pub fn register_stdlib(resolver: &mut StaticModuleResolver) {
use crate::providers::stdlib::{command::command, env::env, monitor::monitor, text::text};
use crate::providers::stdlib::{
command::command, env::env, regex::regex_lib, text::text,
};
// adding modules
let text_mod = exported_module!(text);
let env_mod = exported_module!(env);
let monitor_mod = exported_module!(monitor);
let command_mod = exported_module!(command);
let regex_mod = exported_module!(regex_lib);
// inserting modules
resolver.insert("std::text", text_mod);
resolver.insert("std::env", env_mod);
resolver.insert("std::monitor", monitor_mod);
resolver.insert("std::command", command_mod);
resolver.insert("std::regex", regex_mod);
}

View File

@@ -1,249 +0,0 @@
use gtk::gdk;
use gtk::prelude::*;
use rhai::plugin::*;
#[export_module]
pub mod monitor {
/// Get the number of connected monitors.
///
/// # Returns
///
/// Returns the total number of connected monitors as an `i64`.
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let count = monitor::count();
/// print(count); // Output: Number of connected monitors
/// ```
pub fn count() -> i64 {
get_monitor_count()
}
/// Get the resolution of the primary monitor.
///
/// # Returns
///
/// Returns an array containing the width and height of the primary monitor as two `i64` values.
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let resolution = monitor::primary_resolution();
/// print(resolution); // Output: [width, height]
/// ```
pub fn primary_resolution() -> [i64; 2] {
let (w, h) = get_primary_monitor_resolution();
[w, h]
}
/// Get the resolution of the primary monitor as a string.
///
/// # Returns
///
/// Returns the resolution of the primary monitor as a string in the format "width x height".
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let resolution_str = monitor::primary_resolution_str();
/// print(resolution_str); // Output: "1920x1080"
/// ```
pub fn primary_resolution_str() -> String {
let (w, h) = get_primary_monitor_resolution();
format!("{w}x{h}")
}
/// Get the resolutions of all connected monitors.
///
/// # Returns
///
/// Returns an array of arrays, where each inner array contains the width and height of a monitor.
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let resolutions = monitor::all_resolutions();
/// print(resolutions); // Output: [[width1, height1], [width2, height2], ...]
/// ```
pub fn all_resolutions() -> Vec<[i64; 2]> {
get_all_monitor_resolutions().into_iter().map(|(w, h)| [w, h]).collect()
}
/// Get the resolutions of all connected monitors as a string.
///
/// # Returns
///
/// Returns a string where each monitor's resolution is formatted as "width x height", separated by commas.
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let resolutions_str = monitor::all_resolutions_str();
/// print(resolutions_str); // Output: "1920x1080, 1280x720"
/// ```
pub fn all_resolutions_str() -> String {
get_all_monitor_resolutions()
.into_iter()
.map(|(w, h)| format!("{w}x{h}"))
.collect::<Vec<_>>()
.join(", ")
}
/// Get the dimensions (x, y, width, height) of a specific monitor.
///
/// # Arguments
///
/// * `index` - The index of the monitor (0-based).
///
/// # Returns
///
/// Returns an array with the monitor's position (x, y) and size (width, height).
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let dimensions = monitor::dimensions(0);
/// print(dimensions); // Output: [x, y, width, height]
/// ```
pub fn dimensions(index: i64) -> [i64; 4] {
let (x, y, w, h) = get_monitor_dimensions(index as usize);
[x, y, w, h]
}
/// Get the dimensions of a specific monitor as a string.
///
/// # Arguments
///
/// * `index` - The index of the monitor (0-based).
///
/// # Returns
///
/// Returns the monitor's dimensions as a string in the format "x,y - width x height".
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let dimensions_str = monitor::dimensions_str(0);
/// print(dimensions_str); // Output: "0,0 - 1920x1080"
/// ```
pub fn dimensions_str(index: i64) -> String {
let (x, y, w, h) = get_monitor_dimensions(index as usize);
format!("{x},{y} - {w}x{h}")
}
/// Get the DPI (dots per inch) of a specific monitor.
///
/// # Arguments
///
/// * `index` - The index of the monitor (0-based).
///
/// # Returns
///
/// Returns the DPI (scale factor * base DPI) of the monitor as a `f64`.
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let dpi = monitor::dpi(0);
/// print(dpi); // Output: DPI of the monitor
/// ```
pub fn dpi(index: i64) -> f64 {
get_monitor_dpi(index as usize)
}
/// Get the DPI of a specific monitor as a string.
///
/// # Arguments
///
/// * `index` - The index of the monitor (0-based).
///
/// # Returns
///
/// Returns the DPI of the monitor as a string formatted to 1 decimal place.
///
/// # Example
///
/// ```js
/// import "std::monitor" as monitor;
///
/// let dpi_str = monitor::dpi_str(0);
/// print(dpi_str); // Output: "96.0"
/// ```
pub fn dpi_str(index: i64) -> String {
format!("{:.1}", get_monitor_dpi(index as usize))
}
}
fn ensure_gdk_init() {
if gtk::is_initialized_main_thread() {
return;
}
gtk::init().expect("Failed to initialize GTK");
}
fn get_monitor_count() -> i64 {
ensure_gdk_init();
let display = gdk::Display::default().expect("No display found");
display.n_monitors() as i64
}
fn get_primary_monitor_resolution() -> (i64, i64) {
ensure_gdk_init();
let display = gdk::Display::default().expect("No display found");
if let Some(primary) = display.primary_monitor() {
let rect = primary.geometry();
(rect.width() as i64, rect.height() as i64)
} else {
(0, 0)
}
}
fn get_all_monitor_resolutions() -> Vec<(i64, i64)> {
ensure_gdk_init();
let display = gdk::Display::default().expect("No display found");
(0..display.n_monitors())
.filter_map(|i| display.monitor(i))
.map(|m| {
let rect = m.geometry();
(rect.width() as i64, rect.height() as i64)
})
.collect()
}
fn get_monitor_dimensions(index: usize) -> (i64, i64, i64, i64) {
ensure_gdk_init();
let display = gdk::Display::default().expect("No display found");
if let Some(m) = display.monitor(index as i32) {
let geom = m.geometry();
(geom.x() as i64, geom.y() as i64, geom.width() as i64, geom.height() as i64)
} else {
(0, 0, 0, 0)
}
}
fn get_monitor_dpi(index: usize) -> f64 {
ensure_gdk_init();
let display = gdk::Display::default().expect("No display found");
if let Some(m) = display.monitor(index as i32) {
m.scale_factor() as f64 * 96.0 // base DPI * scale factor
} else {
0.0
}
}

View File

@@ -0,0 +1,120 @@
use regex::Regex;
use rhai::plugin::*;
use rhai::{Array, Dynamic};
/// A module providing regular expression support.
#[export_module]
pub mod regex_lib {
/// Checks if a regex pattern matches the given text.
///
/// # Arguments
///
/// * `text` - A string to be matched with the pattern.
/// * `pattern` - The pattern to match on the string.
///
/// # Returns
///
/// Returns a boolean (true/false) based on if the pattern is matched on the text provided.
///
/// # Example
///
/// ```javascript
/// import "std::regex" as regex;
///
/// let result = regex::is_match("This is an example!", "example");
/// if result == true {
/// print("The pattern is matched!");
/// }
/// ```
#[rhai_fn(return_raw)]
pub fn is_match(text: &str, pattern: &str) -> Result<bool, Box<EvalAltResult>> {
let re = Regex::new(pattern).map_err(|e| format!("Failed to read regex pattern: {}", e))?;
Ok(re.is_match(text))
}
/// Returns the first match of a regex pattern in the text.
///
/// # Arguments
///
/// * `text` - A string to be matched with the pattern.
/// * `pattern` - The pattern to match on the string.
///
/// # Returns
///
/// Returns a string which is the first match of a regex pattern.
///
/// # Example
///
/// ```javascript
/// import "std::regex" as regex;
///
/// let result = regex::find("This is an example!", `\be\w*\b`);
/// print(result); // output: "example"
/// ```
#[rhai_fn(return_raw)]
pub fn find(text: &str, pattern: &str) -> Result<String, Box<EvalAltResult>> {
let re = Regex::new(pattern).map_err(|e| format!("Failed to read regex pattern: {}", e))?;
match re.find(text).map(|m| m.as_str().to_string()) {
Some(s) => Ok(s),
None => Ok(String::new()),
}
}
/// Returns all matches of a regex pattern in the text.
///
/// # Arguments
///
/// * `text` - A string to be matched with the pattern.
/// * `pattern` - The pattern to match on the string.
///
/// # Returns
///
/// Returns aan array of strings containing the all the things that match the regex pattern in the provided text.
///
/// # Example
///
/// ```javascript
/// import "std::regex" as regex;
///
/// let result = regex::find("This is an example!", `\be\w*\b`);
/// print(result); // output: ["example"]
/// ```
#[rhai_fn(return_raw)]
pub fn find_all(text: &str, pattern: &str) -> Result<Array, Box<EvalAltResult>> {
let re = Regex::new(pattern).map_err(|e| format!("Failed to read regex pattern: {}", e))?;
let results: Array =
re.find_iter(text).map(|m| Dynamic::from(m.as_str().to_string())).collect();
Ok(results)
}
/// Replaces all matches of a regex pattern with a replacement string.
///
/// # Arguments
///
/// * `text` - A string to be matched with the pattern.
/// * `pattern` - The pattern to match on the string.
/// * `replacement` - A string that the matched pattern will get replaced with.
///
/// # Returns
///
/// Returns the provided text with the matches of the regex pattern replaced with the provided replacement argument.
///
/// # Example
///
/// ```javascript
/// import "std::regex" as regex;
///
/// let result = regex::replace("This is an example!", "an example", "a test");
/// print(result); // output: "This is a test!"
/// ```
#[rhai_fn(return_raw)]
pub fn replace(
text: &str,
pattern: &str,
replacement: &str,
) -> Result<String, Box<EvalAltResult>> {
let re = Regex::new(pattern).map_err(|e| format!("Failed to read regex pattern: {}", e))?;
Ok(re.replace_all(text, replacement).to_string())
}
}

View File

@@ -16,7 +16,7 @@ pub mod text {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::text" as text;
///
/// let result = text::to_slug("Hello World!");
@@ -48,7 +48,7 @@ pub mod text {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::text" as text;
///
/// let result = text::to_camel_case("hello world example");
@@ -93,7 +93,7 @@ pub mod text {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::text" as text;
///
/// let result = text::truncate_chars("Hello World!", 5);
@@ -118,7 +118,7 @@ pub mod text {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::text" as text;
///
/// let result = text::to_upper("hello");
@@ -140,7 +140,7 @@ pub mod text {
///
/// # Example
///
/// ```js
/// ```javascript
/// import "std::text" as text;
///
/// let result = text::to_lower("HELLO");

View File

@@ -10,8 +10,5 @@ homepage = "https://github.com/elkowar/eww"
[dependencies]
serde.workspace = true
derive_more.workspace = true
ref-cast.workspace = true
chrono = { workspace = true, features = ["unstable-locales"] }
rhai = { version = "1.22.2" }
rhai.workspace = true
anyhow.workspace = true

View File

@@ -63,6 +63,12 @@ pub fn get_i32_prop(props: &Map, key: &str, default: Option<i32>) -> Result<i32>
if let Some(value) = props.get(key) {
if let Some(v) = value.clone().try_cast::<i32>() {
Ok(v)
} else if let Some(v) = value.clone().try_cast::<i64>() {
if v >= i32::MIN as i64 && v <= i32::MAX as i64 {
Ok(v as i32)
} else {
Err(anyhow!("Value for `{}` is out of range for i32", key))
}
} else if let Some(s) = value.clone().try_cast::<String>() {
s.parse::<i32>()
.map_err(|_| anyhow!("Expected property `{}` to be an i32 or numeric string", key))
@@ -113,12 +119,18 @@ pub fn get_duration_prop(props: &Map, key: &str, default: Option<Duration>) -> R
let mins =
num.parse::<u64>().map_err(|_| anyhow!("Invalid min value: '{}'", key_str))?;
Ok(Duration::from_secs(mins * 60))
} else if key_str.ends_with("m") {
let num = &key_str[..key_str.len() - 1];
let mins = num.parse::<u64>().map_err(|_| anyhow!("Invalid m value: '{}'", key_str))?;
Ok(Duration::from_secs(mins * 60))
} else if key_str.ends_with("h") {
let num = &key_str[..key_str.len() - 1];
let hrs = num.parse::<u64>().map_err(|_| anyhow!("Invalid h value: '{}'", key_str))?;
Ok(Duration::from_secs(hrs * 3600))
} else {
Err(anyhow!("Unsupported duration format: '{}'", key_str))
default.ok_or_else(|| {
anyhow!("Unsupported duration format: '{}', and no default provided", key_str)
})
}
} else {
default.ok_or_else(|| anyhow!("No value for duration and no default provided"))

View File

@@ -1,8 +1,4 @@
pub mod extract_props;
pub mod locale;
pub mod span;
pub mod wrappers;
pub use locale::*;
pub use span::*;
pub use wrappers::*;

View File

@@ -1,11 +0,0 @@
use chrono::Locale;
use std::env::var;
/// Returns the `Locale` enum based on the `LC_ALL`, `LC_TIME`, and `LANG` environment variables in
/// that order, which is the precedence order prescribed by Section 8.2 of POSIX.1-2017.
/// If the environment variable is not defined or is malformed use the POSIX locale.
pub fn get_locale() -> Locale {
var("LC_ALL").or_else(|_| var("LC_TIME")).or_else(|_| var("LANG")).map_or(Locale::POSIX, |v| {
v.split('.').next().and_then(|x| x.try_into().ok()).unwrap_or_default()
})
}

View File

@@ -1,89 +0,0 @@
use derive_more::{Debug, *};
use ref_cast::RefCast;
use serde::{Deserialize, Serialize};
/// The name of a variable
#[repr(transparent)]
#[derive(
Clone,
Hash,
PartialEq,
Eq,
Serialize,
Deserialize,
AsRef,
From,
FromStr,
Display,
Debug,
RefCast,
)]
#[debug("VarName({})", _0)]
pub struct VarName(pub String);
impl std::borrow::Borrow<str> for VarName {
fn borrow(&self) -> &str {
&self.0
}
}
impl AttrName {
pub fn to_attr_name_ref(&self) -> &AttrName {
AttrName::ref_cast(&self.0)
}
}
impl From<&str> for VarName {
fn from(s: &str) -> Self {
VarName(s.to_owned())
}
}
impl From<AttrName> for VarName {
fn from(x: AttrName) -> Self {
VarName(x.0)
}
}
/// The name of an attribute
#[repr(transparent)]
#[derive(
Clone,
Hash,
PartialEq,
Eq,
Serialize,
Deserialize,
AsRef,
From,
FromStr,
Display,
Debug,
RefCast,
)]
#[debug("AttrName({})", _0)]
pub struct AttrName(pub String);
impl AttrName {
pub fn to_var_name_ref(&self) -> &VarName {
VarName::ref_cast(&self.0)
}
}
impl std::borrow::Borrow<str> for AttrName {
fn borrow(&self) -> &str {
&self.0
}
}
impl From<&str> for AttrName {
fn from(s: &str) -> Self {
AttrName(s.to_owned())
}
}
impl From<VarName> for AttrName {
fn from(x: VarName) -> Self {
AttrName(x.0)
}
}

1
docs/.gitignore vendored
View File

@@ -1 +0,0 @@
book/

View File

@@ -1,3 +0,0 @@
# Ewwii docs
Ewwii documentation page.

View File

@@ -1,14 +0,0 @@
[book]
authors = ["byson94"]
language = "en"
multilingual = false
src = "src"
title = "Ewwii documentation"
[output.html]
default-theme = "latte"
preferred-dark-theme = "ewwii"
site-url = "/ewwii/"
git-repository-url = "https://github.com/Ewwii-sh/ewwii"
additional-js = ["./js/home_button.js", "./theme/rhai-autodocs/tabs.js"]
additional-css = ["./theme/catppuccin.css", "./theme/ewwii.css", "./theme/rhai-autodocs/default.css"]

View File

@@ -1,31 +0,0 @@
document.addEventListener("DOMContentLoaded", function () {
const homeBtn = document.createElement("a");
homeBtn.href = "https://ewwii-sh.github.io/";
homeBtn.innerText = "🏠︎";
homeBtn.className = "home-button";
homeBtn.style.padding = "6px";
homeBtn.style.backgroundColor = "transparent";
homeBtn.style.color = "grey";
homeBtn.style.borderRadius = "4px";
homeBtn.style.textDecoration = "none";
homeBtn.style.display = "inline-flex";
homeBtn.style.alignItems = "center";
homeBtn.style.justifyContent = "center";
homeBtn.style.transition = "all 0.2s ease";
// Hover effect
homeBtn.addEventListener("mouseover", () => {
homeBtn.style.color = "#bbbbbb";
homeBtn.style.transform = "scale(1.01)";
});
homeBtn.addEventListener("mouseout", () => {
homeBtn.style.backgroundColor = "transparent";
homeBtn.style.color = "grey";
homeBtn.style.transform = "scale(1)";
});
const header = document.querySelector(".right-buttons");
if (header) header.appendChild(homeBtn);
});

View File

@@ -1,44 +0,0 @@
# Summary
[Introduction](introduction.md)
- [Getting Started](getting_started.md)
- [Installation](installation.md)
- [Configuration & Syntax](config/config_and_syntax.md)
- [Configuration](config/configuration.md)
- [Fundamentals](config/config_fundamentals.md)
- [Variables](config/variables.md)
- [Expression Language](config/expression_language.md)
- [Rendering and Best Practices](config/rendering_and_best_practices.md)
- [Widgets](widgets/widgets.md)
- [Widgets & Parameters](widgets/widgets_and_params.md)
- [Widget Properties](widgets/props.md)
- [Theming & UI](theming/theming_and_ui.md)
- [Working With GTK](theming/working_with_gtk.md)
- [Styling Widgets](theming/styling_widgets.md)
- [Modules](modules/modules.md)
- [User Defined Modules](modules/user_defined.md)
- [Global Builtin Rhai Functions](modules/global.md)
- [Std Library](modules/stdlib.md)
- [API Library](modules/apilib.md)
- [Examples](examples/examples.md)
- [Starter Bar](examples/starter_bar.md)
- [Wifi Manager Template](examples/wifi_manager.md)
- [Advanced Commands](commands/advanced_commands_intro.md)
- [Update](commands/update.md)
- [Call Functions](commands/call_fns.md)
- [Troubleshooting](troubleshooting.md)

View File

@@ -1,9 +0,0 @@
# Advanced Commands
Now that you all are familiar with ewwii and may be making awesome widgets, lets get to know about some advanced commands in ewwii, that makes it even more flexible and powerful.
In this section, we will cover:
- How to use advanced commands
- Limitations of these advanced commands
- And finally, solutions to these limitations

View File

@@ -1,44 +0,0 @@
# `ewwii call-fns`
The `call-fns` command allows you to call **Rhai functions** directly from the command line. This can be useful for triggering specific functionality in your widget configuration without updating or interacting with the GUI.
> **Note:** All variables created by `poll` or `listen` handlers will default to their initial values when calling functions. They **cannot be preserved**.
**Example:**
```bash
# Call a single Rhai function
ewwii call-fns "my_function(32, 21)"
# Call multiple functions
ewwii call-fns "first_function('string')" "second_function()"
```
This will execute the specified functions in the context of your current configuration.
## Limitation: Main configuration
However, there is one limitation in `call-fns`. It can only see and call functions defined within your main configuration (i.e `ewwii.rhai` file).
## Solution: Creating wrappers
But, there is one solution though! You can call external functions from functions defined in main.
**Example:**
```js
// in external.rhai
fn awesome_fn() {
print("Awesome fn triggered!");
}
```
```js
// in ewwii.rhai
fn call_awesome_fn() {
import "external" as external;
external::awesome_fn();
}
```
Now you can run `ewwii call-fns "call-awesome_fn()"` and get "Awesome fn triggered!".

View File

@@ -1,37 +0,0 @@
# `ewwii update`
The `update` command refreshes the widgets rendered in a specified window. It allows you to immediately reflect changes in your widget configuration.
**Example:**
```bash
# Update a single window
ewwii update --window "my_awesome_widget"
# Short form
ewwii update -w "my_awesome_widget"
```
## Limitation: `poll` and `listen` handlers
A known limitation of `ewwii update` is that it does **not** preserve variables created by `poll` or `listen` handlers. When you run `ewwii update`, these variables are reset to their initial values.
## Solution: Injecting variables with `--inject-vars`
To prevent certain variables from being reset, you can manually inject values into the configuration using the `--inject-vars` argument. This allows you to explicitly set variable values during an update.
```bash
# Long form
ewwii update --window "my_awesome_widget" --inject-vars "VAR1=bar,VAR2=foo2"
# Short form
ewwii update -w "my_awesome_widget" --inject-vars "VAR1=ewwii,VAR2=baz1"
```
> Note: `--inject-vars` does **not** automatically capture the current state of `poll` or `listen` variables. You must explicitly provide the values you want.
## Best Practices
- Consider using `--inject-vars` when your widgets rely on `poll` or `listen` to avoid default resets.
- Update multiple widgets by running `ewwii update` for each window separately.
- Be explicit and consistent with variable values to avoid unexpected behavior.

View File

@@ -1,14 +0,0 @@
# Configuration & Syntax
This section introduces the foundational systems that define how you configure your UI, express logic, and work with dynamic data in Rahi (Ewwii's configuration language).
The configuration model is imparative by nature but will be used in a declarative format that is made to make configuring ewwii easy as well as to provide a logical way of configuring. You'll also work with special built in functions and modules that expose live system state and other information.
We'll cover:
- The structure of configuration files
- Embedding expressions within properties and attributes
- Accessing and using built-in variables
- Interpolation, scoping, and reactivity rules
> If you're coming from EWW's Yuck, expect similarities in structure but with much more flexibility and logical programming.

View File

@@ -1,119 +0,0 @@
# Fundamentals
Ewwii uses Rhai as its configuration language. But instead of just pure Rhai, ewwii has its own layout that users should follow to create widgets using Rhai. And you may be wondering why ewwii has a "custom" layout instead of allowing users to just use pure Rhai. It's good question and the reason why ewwii has a custom layout is because it tries to remove unnecessary complexity.
The full reasons for this layout wont be explained much more because it goes way deeper than just "decreasing complexity".
For more information about Rhai, you can read [their documentation](https://rhai.rs/book/).
## Widgets and their parameters
Each widget in ewwii is a function (e.g: `button(#{...})` is a function call to create a button). So each one requires its own parameters.
For example, `defwindow` expects a **String**, **Properties**, and a function call that **returns a widget.**
**Example:**
```js
enter([
// the string here (the text in "") is the name of the window
// the content in #{} is the properties
// and the 3rd `root_widget()` call is the function that returns a child.
// defwindow cant have children in [] directly, but it expects a function returning it for it.
defwindow("example", #{
monitor: 0,
windowtype: "dock",
stacking: "fg",
wm_ignore: false,
geometry: #{
x: "0%",
y: "2px",
width: "90%",
height: "30px",
anchor: "top center"
},
reserve: #{ distance: "40px" side: "top" }
}, root_widget())
])
```
This is not that complex once you know the parameters of defwindow as most of the other widgets only take in properties or optinally children. **Poll/Listen** are the only things that is similar to `defwindow` and you will learn about it later in the [variables chapter](./variables.md).
## The root
It is an important concept that users must know to go forward with this documentaiton. Ewwii's Rhai layout is made to be **logical and powerful**, so the user is given access the root of the entire widget system.
The root is defined as `enter()` and it is where you should write `defwindow`.
Here is an example:
```js
enter([
defwindow("example", #{
monitor: 0,
windowtype: "dock",
stacking: "fg",
wm_ignore: false,
geometry: #{
x: "0%",
y: "2px",
width: "90%",
height: "30px",
anchor: "top center"
},
reserve: #{ distance: "40px" side: "top" }
}, root_widget())
])
```
Now that you saw this example, you may be wondering why we are doing `enter([])` instead of `enter()`. That is due to another fundamental concept in ewwii which is very important. You will learn about it in the [properties and child definition section](#properties-and-child-definition).
## Semi-colons
Semi-colon is an important character in Rhai. Just like programming languages like JavaScript, Java, Rust etc.
You can use the following link to read about semi-colons in the Rhai book as they have an awesome documentation.
[https://rhai.rs/book/ref/statements.html#statements](https://rhai.rs/book/ref/statements.html#statements)
## Properties and child definition
The part where most people get confused is the use of `[]` and `#{}`. Let's get into what those are and how you can use them.
The `[]` is used for adding **children** to a widget.
**Example:**
```js
fn greeter(foo) {
return box(#{
orientation: "horizontal",
halign: "center"
}, [
// the `[]` holds a button which is the child widget of the box widget
// each element in a `[]` should end in a comma (,) instead of a semi-colon (;).
button(#{ onclick: `notify-send '${foo}'`, label: "baz" }),
label(#{ text: "example" }),
]);
};
```
The `#{}` works similar to the `[]` but, it is used to add properties into the widget.
**Example:**
```js
fn greeter(foo) {
// the `#{}` holds the properties of the box widget
// each element in a `#{}` should end in a comma (,) instead of a semi-colon (;).
return box(#{
orientation: "horizontal",
halign: "center"
}, [
// properties are assigned to both button and label using the #{}.
button(#{ onclick: `notify-send '${foo}'`, label: "baz" }),
label(#{ text: "example" }),
]);
};
```

View File

@@ -1,145 +0,0 @@
# Writing your ewwii configuration
(For a list of all built-in widgets (i.e. `box`, `label`, `button`), see [Widget Documentation](../widgets/widgets.md).)
Ewwii is configured using a language called `Rhai`.
Using rhai, you declare the structure and content of your widgets, the geometry, position, and behavior of any windows,
as well as any state and data that will be used in your widgets.
Rhai is based around imparative syntax, which you may know from programming languages like C, Rust etc.
If you're using vim, you can make use of [vim-rhai](https://github.com/rhaiscript/vim-rhai) for editor support.
If you're using VSCode, you can get syntax highlighting and formatting from [vscode-rhai](https://marketplace.visualstudio.com/items?itemName=rhaiscript.vscode-rhai).
Additionally, any styles are defined in CSS or SCSS (which is mostly just slightly improved CSS syntax).
While ewwii supports a significant portion of the CSS you know from the web,
not everything is supported, as ewwii relies on GTK's own CSS engine.
Notably, some animation features are unsupported,
as well as most layout-related CSS properties such as flexbox, `float`, absolute position or `width`/`height`.
To get started, you'll need to create two files: `ewwii.rhai` and `ewwii.scss` (or `ewwii.css`, if you prefer).
These files must be placed under `$XDG_CONFIG_HOME/ewwii` (this is most likely `~/.config/ewwii`).
Now that those files are created, you can start writing your first widget!
## Creating your first window
Firstly, you will need to create a top-level window. Here, you configure things such as the name, position, geometry, and content of your window.
Let's look at an example window definition:
```js
enter([ // Add all defwindow inside enter. Enter is the root of the config.
defwindow("example", #{
monitor: 0,
windowtype: "dock",
stacking: "fg",
wm_ignore: false,
geometry: #{
x: "0%",
y: "2px",
width: "90%",
height: "30px",
anchor: "top center"
},
reserve: #{ distance: "40px" side: "top" }
}, label(#{ text: "example content" }))
])
```
Here, we are defining a window named `example`, which we then define a set of properties for. Additionally, we set the content of the window to be the text `"example content"`.
You can now open your first window by running `ewwii open example`! Glorious!
### `defwindow`-properties
| Property | Description |
| ---------: | ------------------------------------------------------------------------ |
| `monitor` | Which monitor this window should be displayed on. See below for details. |
| `geometry` | Geometry of the window. |
**`monitor`-property**
This field can be:
- the string `<primary>`, in which case ewwii tries to identify the primary display (which may fail, especially on wayland)
- an integer, declaring the monitor index
- the name of the monitor
- a string containing a JSON-array of monitor matchers, such as: `'["<primary>", "HDMI-A-1", "PHL 345B1C", 0]'`. Ewwii will try to find a match in order, allowing you to specify fallbacks.
**`geometry`-properties**
| Property | Description |
| ----------------: | ----------------------------------------------------------------------------------------------------------------------- |
| `x`, `y` | Position of the window. Values may be provided in `px` or `%`. Will be relative to `anchor`. |
| `width`, `height` | Width and height of the window. Values may be provided in `px` or `%`. |
| `anchor` | Anchor-point of the window. Either `center` or combinations of `top`, `center`, `bottom` and `left`, `center`, `right`. |
| `resizable` | Whether to allow resizing the window or not. Eiither `true` or `false`. |
<br/>
Depending on if you are using X11 or Wayland, some additional properties exist:
#### X11
| Property | Description |
| -----------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `stacking` | Where the window should appear in the stack. Possible values: `fg`, `bg`. |
| `wm_ignore` | Whether the window manager should ignore this window. This is useful for dashboard-style widgets that don't need to interact with other windows at all. Note that this makes some of the other properties not have any effect. Either `true` or `false`. |
| `reserve` | Specify how the window manager should make space for your window. This is useful for bars, which should not overlap any other windows. |
| `windowtype` | Specify what type of window this is. This will be used by your window manager to determine how it should handle your window. Possible values: `normal`, `dock`, `toolbar`, `dialog`, `desktop`. Default: `dock` if `reserve` is specified, `normal` otherwise. |
#### Wayland
| Property | Description |
| ----------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `stacking` | Where the window should appear in the stack. Possible values: `fg`, `bg`, `overlay`, `bottom`. |
| `exclusive` | Whether the compositor should reserve space for the window automatically. Either `true` or `false`. If `true` `:anchor` has to include `center`. |
| `focusable` | Whether the window should be able to be focused. This is necessary for any widgets that use the keyboard to work. Possible values: `none`, `exclusive` and `ondemand`. |
| `namespace` | Set the wayland layersurface namespace ewwii uses. Accepts a `string` value. |
## Your first widget
While our bar is already looking great, it's a bit boring. Thus, let's add some actual content!
```js
fn greeter(name) {
return box(#{
orientation: "horizontal",
halign: "center"
}, [
button(#{ onclick: `notify-send 'Hello' 'Hello, ${name}'`, label: "Greet" })
]);
};
```
To show this, let's replace the text in our window definition with a call to this new widget:
```js
enter([
defwindow(
"example",
#{
// ... properties omitted
},
greeter("Bob")
),
]);
```
There is a lot going on here, so let's step through this.
We are creating a function named `greeter` and a function is equal to a component that returns a child (widget). So function has two uses: one to return a component, and the other to do a set of functions.
And this function takes one parameters, called `name`. The `name` parameter _must_ be provided or else, you should emit it. Rhai does allow adding optional parameters, but we will talk about it later for the sake of beginners who are in-experienced with imprative programming languages.
Now inside the function, we declare the body of our widget that we are returning. We make use of a `box`, which we set a couple properties of.
We need this `box`, as a function can only ever contain a single widget - otherwise,
ewwii would not know if it should align them vertically or horizontally, how it should space them, and so on.
Thus, we wrap multiple children in a `box`.
This box then contains a button.
In that button's `onclick` property, we refer to the provided `name` using string-interpolation syntax: `` `${name}` ``. It is not possible to use a variable within a `""` or `''` just like javascript. You can learn more about it [here](https://rhai.rs/book/ref/strings-chars.html?interpolation#string-interpolation).
<!-- TODO -->
<!-- In fact, there is a lot more you can do within `${...}` - more on that in the chapter about the [expression language](expression_language.md). -->
To then use our widget, we call the function that provides the widget with the necessary parameters passed.
As you may have noticed, we are using a couple predefined widgets here. These are all listed and explained in the [widgets chapter](widgets.md).

View File

@@ -1,87 +0,0 @@
# The Rhai Expression Engine
Ewwii uses [Rhai](https://rhai.rs/) as its core expression and scripting engine. This means your configuration is more than just static values or simple substitutions—its **real code**, and you can use it anywhere dynamic behavior is needed.
Rhai expressions can:
- Perform logic and branching (`if`, `match`, `? :`)
- Handle mathematical calculations and string operations
- Access nested data from arrays, maps, or JSON
- Run custom functions
- Be used directly in layout definitions, widget attributes, and style rules
Unlike Yuck, where expressions were embedded in `{ ... }` or `${ ... }`, Rhai treats expressions as **native**. They dont need to be wrapped in special delimiters. If you can write it in Rhai, it just works.
## Example
```js
let value = 12 + foo * 10;
box(#{
class: "baz"
orientation: "h",
}, [
button(#{
class: button_active ? "active" : "inactive",
on_click: "toggle_thing",
label: `Some math: ${value}`,
}),
]);
```
## Core Features
Rhai supports a wide range of expression capabilities:
- **Mathematics**: `+`, `-`, `*`, `/`, `%`
- **Comparisons**: `==`, `!=`, `<`, `>`, `<=`, `>=`
- **Boolean logic**: `&&`, `||`, `!`
- **Conditionals**: `if/else`, ternary (`cond ? a : b`)
- **Regex matching**: `=~` operator (Rust-style regex)
- **Optional access**: `?.` and `?.[index]`
- **Data structures**: maps/arrays (`obj.field`, `arr[3]`, `map["key"]`)
- **Function calls**: standard and Ewwii-specific built-ins (see below)
- **String interpolation**: `` `Value is ${value}` `` (standard Rhai feature)
> Note
>
> ---
>
> Rhai only allows string interpolation only for the strings that are quoted in `` similar to JavaScript.
>
> > Learn more about it [here](https://rhai.rs/book/ref/strings-chars.html?interpolation#string-interpolation).
## Common Built-in Functions
💡 _You may recognize some of these from the old expression system—but now they're just Rhai functions._
Examples include:
- `round()`, `floor()`, `ceil()`, `powi()`, `powf()`
- `min()`, `max()`, `sin()`, `cos()`, etc.
- `replace()`, `matches()`, `captures()`
- `strlength()`, `arraylength()`, `objectlength()`
- `jq()` run jaq-compatible filters on JSON data
- `get_env()` read environment variables
- `formattime()` format UNIX timestamps
- `formatbytes()` format file sizes (IEC or SI)
## Dynamic Usage
Because expressions are just Rhai, you can now write real logic inline or break it into reusable functions:
```js
fn status_text(active) {
return active ? "enabled" : "disabled";
}
label({
text: `Status: ${status_text(system_active)}`
});
```
---
### TL;DR
> If youve used scripting languages like JavaScript or Lua, youll feel at home. Rhai gives you real control—not just interpolation tricks.

View File

@@ -1,133 +0,0 @@
# Rendering and Best Practices
## Rendering children in your widgets
As your configuration grows, you might want to improve its structure by factoring out pieces into reusable functions.
In Ewwiis Rhai-based configuration system, you can define wrapper functions that return widgets and accept a `children` parameter (or any parameter that you prefer), just like built-in widgets such as `box()` or `button()`.
Here's an example of a custom container that adds a label before its children:
```js
fn labeled_container(name, children = []) {
return box(#{ class: "container" }, [label(#{text: name})] + children)
}
```
You can call it like this:
```js
labeled_container("foo", [
button(#{ onclick: "notify-send hey ho", label: "Click me" }),
]);
```
Because children are just a list of widgets, you can also write functions that structure them however you'd like. For example, here's a layout that places the first two children side by side:
```js
fn two_boxes(children = []) {
return box(#{}, [
box(#{ class: "first" }, [children[0]]),
box(#{ class: "second" }, [children[1]])
]);
}
```
And call it like this:
```js
two_boxes([label(#{ text: "First" }), label(#{ text: "Second" })]);
```
If a child is missing (e.g., children[1] doesn't exist), make sure to handle that gracefully or document the expected number of children.
<!-- TODO: add it once literal is implemented -->
<!-- ## Dynamically generated widgets with `literal`
In some cases, you want to not only change the text,
value, or color of a widget dynamically, but instead want to generate an entire widget structure dynamically.
This is necessary if you want to display lists of things (for example notifications)
where the amount is not necessarily known,
or if you want to change the widget structure in some other, more complex way.
For this, you can make use of one of ewwii's most powerful features: the `literal` widget.
```js
let variable_containing_rhai = "(box (button 'foo') (button 'bar'))";
// Then, inside your widget, use:
literal(#{ content: variable_containing_rhai })
```
Here, you specify the content of your literal by providing it a string (most likely stored in a variable) which contains a single yuck widget tree.
Ewwii then reads the provided value and renders the resulting widget. Whenever it changes, the widget will be rerendered.
Note that this is not all that efficient. Make sure to only use `literal` when necessary! -->
## Window ID
In some cases you may want to use the same window configuration for multiple widgets, e.g. for multiple windows. This is where arguments and ids come in.
Firstly let us start off with ids. An id can be specified in the `open` command
with `--id`, by default the id will be set to the name of the window
configuration. These ids allow you to spawn multiple of the same windows. So
for example you can do:
```bash
ewwii open my_bar --screen 0 --id primary
ewwii open my_bar --screen 1 --id secondary
```
## Generating a list of widgets from array using `for`
If you want to display a list of values, you can use the `for`-Element to fill a container with a list of elements generated from a JSON-array.
```js
let my_array = [1, 2, 3];
// Then, inside your widget, you can use
box(#{}, [
for entry in my_array {
button(#{ onclick: `notify-send 'click' 'button ${entry}'`, label: entry.to_string() })
}
])
```
This can be useful in many situations, for example when generating a workspace list from an array representation of your workspaces.
In many cases, this can be used instead of `literal`, and should most likely be preferred in those cases.
<!-- To see how to declare and use more advanced data structures, check out the [data structures example](/examples/data-structures/ewwii.rhai). -->
## Splitting up your configuration
As time passes, your configuration might grow larger and larger. Luckily, you can easily split up your configuration into multiple files!
There are two options to achieve this:
### Using `import/export`
```js
// in ./foo/baz.rhai
/// Note: all functions are automatically exported.
fn greet() { return "Greetings!" }
let PI = 3.14159
export PI; // we need to export variables manually
// in ./ewwii.rhai
import "foo/baz" as example;
print(example::greet()); // Greetings!
print(example::PI); // 3.14159
```
A rhai file may import the contents of any other rhai file that they export. For this, make use of the `import` directive. If you are exporting a variable/function, make use the `export` directive.
### Using a separate ewwii configuration directory
If you want to separate different widgets even further, you can create a new ewwii config folder anywhere else.
Then, you can tell ewwii to use that configuration directory by passing _every_ command the `--config /path/to/your/config/dir` flag.
Make sure to actually include this in all your `ewwii` calls, including `ewwii kill`, `eww logs`, etc.
This launches a separate instance of the ewwii daemon that has separate logs and state from your main ewwii configuration.
```bash
ewwii --config "/path/to/your/config/dir"
```

View File

@@ -1,122 +0,0 @@
# Variables
Now that you feel sufficiently greeted by your bar, you may realize that showing data like the time and date might be even more useful than having a button that greets you.
To implement dynamic content in your widgets, you make use of _variables_.
All variables are only locally available so you would need to pass it around using function parameters. And whenever the variable changes, the value in the widget will update!
## Static variables
In Rhai, all variables are dynamically typed bindings to values. You can define variables using let, pass them as function parameters.
**Basic variables (`let`)**
```js
let foo = "value";
```
This is the simplest type of variable.
Basic variables don't ever change automatically, if you need a dynamic variable, you can use built in functions like `poll()` and `listen()` to register dynamic values which we will talk about in the following section.
## Dynamic variables
Just having static variables that wont update is pretty limiting. So, ewwii has two built in functions to register dynamic variables that can change according to the command.
**Polling variables (`poll`)**
```js
enter([
poll("var_name", #{
// It is recommended to have initial property passed.
// If not provided, it will default to no value which may cause problems when used.
// You can pass something like "" if you want no initial value.
initial: "inital value",
interval: "2s",
cmd: "date +%H:%M:%S", // command to execute
});
])
```
A polling variable is a variable which runs a provided shell-script repeatedly, in a given interval.
This may be the most commonly used type of variable.
They are useful to access any quickly retrieved value repeatedly,
and thus are the perfect choice for showing your time, date, as well as other bits of information such as pending package updates, weather, and battery level.
But it is important to note that these variables are locally available only in enter (a.k.a the root) and you need to pass it to other functions with something like `some_fn(foo)` when you want to use a polled variable.
<!-- You can also specify an initial-value. This should prevent ewwii from waiting for the result of a given command during startup, thus
making the startup time faster. -->
To externally update a polling variable, `ewwii update` can be used like with basic variables to assign a value. [Learn more about ewwii update](../commands/update.md).
**Listening variables (`listen`)**
```js
enter([
listen("foo", #{
initial: "whatever",
cmd: "tail -F /tmp/some_file",
});
])
```
Listening variables might be the most confusing of the bunch.
A listening variable runs a script once, and reads its output continously.
Whenever the script outputs a new line, the value will be updated to that new line.
In the example given above, the value of `foo` will start out as `"whatever"`, and will change whenever a new line is appended to `/tmp/some_file`.
These are particularly useful when you want to apply changes instantaneously when an operation happens if you have a script
that can monitor some value on its own. Volume, brightness, workspaces that get added/removed at runtime,
monitoring currently focused desktop/tag, etc. are the most common usecases of this type of variable.
These are particularly efficient and should be preffered if possible.
For example, the command `xprop -spy -root _NET_CURRENT_DESKTOP` writes the currently focused desktop whenever it changes.
Another example usecase is monitoring the currently playing song with playerctl: `playerctl --follow metadata --format {{title}}`.
<!--
**Built-in "magic" variables**
In addition to defining your own variables, ewwii provides some values for you to use out of the box.
These include values such as your CPU and RAM usage.
These mostly contain their data as JSON, which you can then get using the [json access syntax](expression_language.md).
All available magic variables are listed [here](magic-vars.md). -->
<div class="warning">
<strong>Warning:</strong> Dynamic variables created by `poll` or `listen` handlers
should always be defined inside an <code>enter([])</code> block.
If `poll` or `listen` is defined outside the <code>enter([])</code> block, then they simply will be ignored.
</div>
## Passing variables
As we discussed earlier, all variables are only available locally. So, you would need to pass it around from the current scope.
Here is an example of how it is done:
```js
let foo = "example";
enter([
poll("time", #{
initial: "inital value",
interval: "2s",
cmd: "date +%H:%M:%S",
}),
defwindow("1", #{}, wont_work()), // wont work
defwindow("2", #{}, will_work(time, foo)) // will work
])
// Here we have 2 variables named "time" (registered dynamically by poll) and foo (a static variable)
// here is an example of something that wont
fn wont_work() {
return box(#{}, [ label(#{ text: time }), label(#{ text: foo }) ]);
}
// here is an example of something that will work
fn will_work(time, foo) { // time and foo is passed from `enter([])`
return box(#{}, [ label(#{ text: time }), label(#{ text: foo }) ]);
}
```

View File

@@ -1,13 +0,0 @@
# Examples
This section provides hands-on, practical demonstrations of everything covered so far. Real layouts, interactive components, and theming techniques will be used in these examples.
Each example is minimal but complete, focusing on a particular design pattern or technique. You can copy-paste them into your own config to experiment.
Included:
- Common layout patterns (e.g., bars, panels, dashboards)
- Interactive elements like buttons, sliders, toggles
- Theming techniques and tricks to override or enhance GTK styles
If you're stuck or just looking for inspiration, this is your go-to reference.

View File

@@ -1,15 +0,0 @@
# Starter Bar
![Example 1](https://raw.githubusercontent.com/ewwii-sh/ewwii/main/examples/ewwii-bar/ewwii-bar.png)
A basic starter bar which will be very helpful to beginners, see [examples/ewwii-bar](https://github.com/Ewwii-sh/ewwii/tree/main/examples/ewwii-bar).
## Installing
This template is regestered in the [eii-manifests](https://github.com/Ewwii-sh/eii-manifests), so you can install it via [eiipm](https://ewwii-sh.github.io/docs/package-manager/overview/): ewwii's package manager.
Just run the following command and have the template ready in the current working directory in an instant!
```bash
eiipm i starter_template
```

View File

@@ -1,15 +0,0 @@
# Wifi Manager Template
![Wifi Manager Template Screenshot](../images/wifi_manager_template.png)
An advanced ewwii template showcasing `api::wifi` module, manual `nm-cli` parsing, and advacned ewwii CLI commands. See the template at [Ewwii-sh/ewifi_gui_template](https://github.com/Ewwii-sh/ewifi_gui_template).
## Installing
This template is regestered in the [eii-manifests](https://github.com/Ewwii-sh/eii-manifests), so you can install it via [eiipm](https://ewwii-sh.github.io/docs/package-manager/overview/): ewwii's package manager.
Just run the following command and have the template ready in the current working directory!
```bash
eiipm i ewifi_gui_template
```

View File

@@ -1,3 +0,0 @@
# Getting Started
Getting starting with Ewwii. This section will cover how you can install and use ewwii.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

View File

@@ -1,90 +0,0 @@
# Installation
The first step of using Ewwii is installing it. You would need to have the following prerequesties installed on your system to build/install ewwii.
**Prerequesties:**
- rustc
- cargo
Rather than with your system package manager,
I **strongly** recommend installing it using [rustup](https://rustup.rs/).
Additionally, eww requires some dynamic libraries to be available on your system.
The exact names of the packages that provide these may differ depending on your distribution.
The following list of package names should work for arch linux:
<details>
<summary><strong>Packages (click here)</strong></summary>
- gtk3 (libgdk-3, libgtk-3)
- gtk-layer-shell (only on Wayland)
- pango (libpango)
- gdk-pixbuf2 (libgdk_pixbuf-2)
- libdbusmenu-gtk3
- cairo (libcairo, libcairo-gobject)
- glib2 (libgio, libglib-2, libgobject-2)
- gcc-libs (libgcc)
- glibc
</details>
> **Note** that you will most likely need the -devel variants of your distro's packages to be able to compile ewwii.
## Building
Once you have the prerequisites ready, you're ready to install and build ewwii.
First clone the repo:
```bash
git clone https://github.com/Ewwii-sh/ewwii
```
```bash
cd ewwii
```
Then build:
```bash
cargo build --release --no-default-features --features x11
```
**NOTE:**
When you're on Wayland, build with:
```bash
cargo build --release --no-default-features --features=wayland
```
## Running ewwii
Once you've built it you can now run it by entering:
```bash
cd target/release
```
Then make the Eww binary executable:
```bash
chmod +x ./ewwii
```
Then to run it, enter:
```bash
./ewwii daemon
./ewwii open <window_name>
```
## Installing via package managers
If you don't want to go through the _very_ tedious task of cloning and building ewwii, you can install it using Cargo (Rust crate manager).
You can run the following command to install ewwii from cargo:
```bash
cargo install --git https://github.com/Ewwii-sh/ewwii
```

View File

@@ -1,26 +0,0 @@
# Ewwii - Widgets for everyone made better!
Ewwii (ElKowar's Wacky Widgets improved interface) is a foork of
Eww (ElKowar's Wacky Widgets) which is a
widget system made in [Rust](https://www.rust-lang.org/),
which lets you create your own widgets similarly to how you can in AwesomeWM.
**Strength of Ewwii over Eww:**
- Full-fledged scripting & expressions
- User-defined widget trees & composition
- Built-in configuration libraries
- Builtin tooling for better developer experience
- Full control over reactive updates (user defines if widget should update dynamically)
Ewwii is configured in [Rhai](https://rhai.rs/)
and themed using [CSS](https://en.wikipedia.org/wiki/CSS)
or [SCSS](<https://en.wikipedia.org/wiki/Sass_(style_sheet_language)>),
it is easy to customize and is powerful and dynamic.
The main goal of Ewwii is to make configuration easy
and to give the user all the power that they need.
Rhai is not just a basic markup language. It is a full embeddable scripting language!
This makes ewwii's configuration even more flexible and powerful.
Whether you're building a tiling-friendly status bar, a floating dashboard, or a themed control panel, Ewwii gives you the tools to design it, script it, and make it your own.

View File

@@ -1,6 +0,0 @@
# Magic variables
These are variables that are always there, without you having to import them.
The delay between all the updating variables except `EWW_TIME` is 2s, for `EWW_TIME` it is 1s.

View File

@@ -1 +0,0 @@
# API Library

View File

@@ -1 +0,0 @@
# Global Builtin Rhai Functions

View File

@@ -1,12 +0,0 @@
# Modules
Modules undoubtedly are one of the most powerful features in Rhai. They provide infinite extensibility to ewwii.
Every module follows the syntax:
```js
import "std::env" as env;
let home = env::get_home_dir(); // returns `$HOME` env var value
```
This allows you to write expressive, modular Rhai code with functions grouped logically under `std` or custom namespaces.

View File

@@ -1 +0,0 @@
# Std Library

View File

@@ -1,55 +0,0 @@
# User-Defined Modules
User-defined modules allow you to **organize your code** by splitting it into separate, reusable files. This makes large projects easier to maintain and understand.
## Exporting Items from a Module
In Rhai modules:
- **Functions are automatically exported** by default. You do **not** need to use `export` for functions.
- **Variables, constants, and objects must be exported manually** using the `export` keyword.
```js
// File: ./foo/baz.rhai
/// A function that is automatically exported
fn greet() {
return "Greetings!"
}
/// A private function, NOT exported automatically
private fn foo() {
return "This function is hidden and not exported"
}
/// A variable
let PI = 3.14159;
// Export the variable explicitly
export PI;
```
**Tip:** Only variables, constants, and objects require the `export` keyword. Functions are always available unless marked `private`. [More info](https://rhai.rs/book/language/modules/export.html#export-functions)
## Importing a Module
You can import a module using the `import` keyword:
```js
// File: ./ewwii.rhai
import "foo/baz" // just runs the script without importing it.
import "foo/baz" as example; // runs the script and imports it into example.
// Access exported items
print(example::greet()); // Greetings!
print(example::PI); // 3.14159
```
**Tip:** Always use the `as` keyword to import a script as a module with the name you desire.
## Notes
- Functions are automatically exported unless explicitly marked `private`.
- Variables, constants, and objects must be exported using the `export` keyword.
- `as` keyword is important in an `import` statement if you want to import the variables and functions in a Rhai file.

View File

@@ -1,15 +0,0 @@
# Styling Widgets
Ewwii also allows writing inline styles to widgets using the `style` property. These styles are then applied at runtime using GTK's CSS system.
**Example:**
```js
fn foo() {
return box(#{
style: "color: black; background-color: #fff;",
}, [ label(#{ text: "baz" }) ]);
}
```
> This example makes the text color of all child widgets of box to black and sets the background color of the box to white (`#fff` is the hexadecimal for white).

View File

@@ -1,11 +0,0 @@
# Theming & UI
This section focuses on visual styling and user interface customization. The core visual layer is built atop GTK, allowing deep integration with system themes while also enabling custom overrides through SCSS-style syntax.
We'll explore:
- How GTK theming works under the hood
- Styling your widgets using theme classes and custom CSS
- Layout implications of theme decisions (e.g., spacing, margins, z-order)
Whether you're trying to match your system's look or building a highly customized UI, this section gives you the tools to style confidently.

View File

@@ -1,27 +0,0 @@
# Working with GTK
## Gtk Theming
Ewwii is styled in GTK CSS.
You can use `Vanilla CSS` or `SCSS` to make theming even easier. The latter is compiled into CSS for you.
If you don't know any way to style something check out the [GTK CSS Overview wiki](https://docs.gtk.org/gtk3/css-overview.html),
the [GTK CSS Properties Overview wiki ](https://docs.gtk.org/gtk3/css-properties.html),
or use the [GTK-Debugger](#gtk-debugger).
If you have **NO** clue about how to do CSS, check out some online guides or tutorials.
SCSS is _very_ close to CSS, so if you know CSS you'll have no problem learning SCSS.
## GTK Debugger
The debugger can be used for **a lot** of things, especially if something doesn't work or isn't styled right.
To open the GTK debugger, simply run
```bash
ewwii inspector
```
If a style or something similar doesn't work, you can click on the icon in the top left to select the thing that isn't being styled correctly.
Then you can click on the drop down menu in the top right corner and select CSS Nodes. Here you will see everything about styling it, CSS Properties, and how it's structured.

View File

@@ -1,35 +0,0 @@
# Troubleshooting
Here you will find help if something doesn't work. If the issue isn't listed here, please [open an issue on the GitHub repo.](https://github.com/Ewwii-sh/ewwii/issues)
## Ewwii does not compile
1. Make sure that you are compiling ewwii using a recent version of rust (run `rustup update` to be sure you have the latest version available)
2. Make sure you have all the necessary dependencies. If there are compile-errors, the compiler will tell you what you're missing.
## Ewwii does not work on Wayland
1. Make sure you compiled ewwii with the `--no-default-features --features=wayland` flags.
2. Make sure that you're not trying to use X11-specific features (these are (hopefully) explicitly specified as such in the documentation).
## My configuration is not loaded correctly
1. Make sure the `ewwii.rhai` and `ewwii.(s)css` files are in the correct places.
2. Sometimes, ewwii might fail to load your configuration as a result of a configuration error. Make sure your configuration is valid.
## Something isn't styled correctly!
Check the [GTK-Debugger](working_with_gtk.md#gtk-debugger) to get more insight into what styles GTK is applying to which elements.
## General issues
You should try the following things before opening an issue or doing more specialized troubleshooting:
- Kill the ewwii daemon by running `ewwii kill` and re-open your window with the `--debug`-flag to get additional log output.
- Now you can take a look at the logs by running `ewwii logs`.
- Use `ewwii state` to see the state of all variables.
- Use `ewwii debug` to see the structure of your widget and other information.
- Update to the latest ewwii version.
- Sometimes hot reloading doesn't work. In that case, you can make use of `ewwii reload` manually.
Remember, if your issue isn't listed here, [open an issue on the GitHub repo](https://github.com/Ewwii-sh/ewwii/issues).

View File

@@ -1,254 +0,0 @@
# Widget Properties
## widget
These properties apply to all widgets, and can be used anywhere!
**Properties**
- `class`: `string` css class name
- `valign`: `string` how to align this vertically. possible values: "fill", "baseline", "center", "start", "end"
- `halign`: `string` how to align this horizontally. possible values: "fill", "baseline", "center", "start", "end"
- `vexpand`: `bool` should this container expand vertically. Default: false
- `hexpand`: `bool` should this widget expand horizontally. Default: false
- `width`: `int` width of this element
- `height`: `int` height of this element
- `active`: `bool` If this widget can be interacted with
- `tooltip`: `string` tooltip text (on hover)
- `visible`: `bool` visibility of the widget
- `style`: `string` inline scss style applied to the widget
- `css`: `string` scss code applied to the widget
## combo-box-text
**Properties**
- `items`: `vec` Items displayed in the combo box
- `timeout`: `duration` timeout of the command. Default: "200ms"
- `onchange`: `string` runs when an item is selected, replacing `{}` with the item
## expander
**Properties**
- `name`: `string` name of the expander
- `expanded`: `bool` sets whether it's expanded
## revealer
**Properties**
- `transition`: `string` animation name ("slideright", "slideleft", etc.)
- `reveal`: `bool` whether the child is revealed
- `duration`: `duration` how long the transition lasts. Default: "500ms"
## checkbox
**Properties**
- `checked`: `bool` initial checked state
- `timeout`: `duration` command timeout. Default: "200ms"
- `onchecked`: `string` command when checked
- `onunchecked`: `string` command when unchecked
## color-button
**Properties**
- `use_alpha`: `bool` use alpha channel
- `onchange`: `string` command on color select
- `timeout`: `duration` Default: "200ms"
## color-chooser
**Properties**
- `use_alpha`: `bool` use alpha channel
- `onchange`: `string` command on color select
- `timeout`: `duration` Default: "200ms"
## slider
**Properties**
- `flipped`: `bool` reverse direction
- `marks`: `string` draw marks
- `draw_value`: `bool` show value
- `value_pos`: `string` where to show value ("left", "right", etc.)
- `round_digits`: `int` number of decimal places
- `value`: `float` current value
- `min`: `float` minimum value
- `max`: `float` maximum value
- `timeout`: `duration` Default: "200ms"
- `onchange`: `string` command on change (use `{}` for value)
- `orientation`: `string` layout direction
## progress
**Properties**
- `flipped`: `bool` reverse direction
- `value`: `float` progress (0100)
- `orientation`: `string` layout direction
## input
**NOTE:** This widget exposes a special environment variable `INPUT_VAL` to the commands specified in `onchange` and `onaccept`.
**Properties**
- `value`: `string` current text
- `onchange`: `string` command on change; `INPUT_VAL` contains the new value
- `timeout`: `duration` Default: "200ms"
- `onaccept`: `string` command on Enter; `INPUT_VAL` contains the new value
- `password`: `bool` obscure input
## button
**Properties**
- `timeout`: `duration` Default: "200ms"
- `onclick`: `string` command on activation
- `onmiddleclick`: `string` command on middle click
- `onrightclick`: `string` command on right click
## image
**Properties**
- `path`: `string` image file path
- `image_width`: `int` image width
- `image_height`: `int` image height
- `preserve_aspect_ratio`: `bool` keep aspect ratio
- `fill_svg`: `string` fill color for SVGs
- `icon`: `string` theme icon name
- `icon_size`: `string` size of the icon
## box
**Properties**
- `spacing`: `int` spacing between children
- `orientation`: `string` direction of children
- `space_evenly`: `bool` distribute children evenly
## overlay
**Properties**
_None_
## tooltip
**Properties**
_None listed_
## centerbox
**Properties**
- `orientation`: `string` direction of layout
## scroll
**Properties**
- `hscroll`: `bool` allow horizontal scrolling
- `vscroll`: `bool` allow vertical scrolling
- `propagate_natural_height`: `bool` use the natural height if true
## eventbox
**Properties**
- `timeout`: `duration` Default: "200ms"
- `onscroll`: `string` command on scroll (`{}` becomes direction)
- `onhover`: `string` command on hover
- `onhoverlost`: `string` command on hover exit
- `cursor`: `string` cursor type
- `ondropped`: `string` command on drop (`{}` is URI)
- `dragvalue`: `string` URI to drag from this widget
- `dragtype`: `string` type to drag ("file", "text")
- `onclick`: `string` command on click
- `onmiddleclick`: `string` command on middle click
- `onrightclick`: `string` command on right click
## label
**Properties**
- `text`: `string` text to display
- `truncate`: `bool` truncate text
- `limit_width`: `int` max characters to show
- `truncate_left`: `bool` truncate beginning
- `show_truncated`: `bool` show truncation
- `unindent`: `bool` strip leading spaces
- `markup`: `string` Pango markup
- `wrap`: `bool` wrap text
- `angle`: `float` rotation angle
- `gravity`: `string` text gravity
- `xalign`: `float` horizontal alignment
- `yalign`: `float` vertical alignment
- `justify`: `string` text justification
- `wrap_mode`: `string` wrap mode ("word", "char", etc.)
- `lines`: `int` max lines (1 = unlimited)
## literal
**Properties**
- `content`: `string` raw yuck
## calendar
**Properties**
- `day`: `float` selected day
- `month`: `float` selected month
- `year`: `float` selected year
- `show_details`: `bool` show details
- `show_heading`: `bool` show heading
- `show_day_names`: `bool` show day names
- `show_week_numbers`: `bool` show week numbers
- `onclick`: `string` command with `{0}`, `{1}`, `{2}` for day/month/year
- `timeout`: `duration` Default: "200ms"
## stack
**Properties**
- `selected`: `int` child index
- `transition`: `string` animation name
- `same_size`: `bool` equal child size
## transform
**Properties**
- `rotate`: `float` rotation angle
- `transform_origin_x`: `string` transform origin x
- `transform_origin_y`: `string` transform origin y
- `translate_x`: `string` shift x
- `translate_y`: `string` shift y
- `scale-x`: `string` scale x
- `scale-y`: `string` scale y
## circular-progress
**Properties**
- `value`: `float` 0100 progress
- `start_at`: `float` start percentage
- `thickness`: `float` line thickness
- `clockwise`: `bool` direction
## graph
**Properties**
- `value`: `float` current value
- `thickness`: `float` line thickness
- `time_range`: `duration` duration to track
- `min`: `float` minimum value
- `max`: `float` maximum value

View File

@@ -1,12 +0,0 @@
# Widgets
Widgets are the building blocks of your interface. Each widget represents a visual element—text, images, containers, interactive components—that can be composed, styled, and updated dynamically.
This section introduces:
- The basic anatomy of a widget definition
- How widgets are laid out within windows
- The attributes and properties available to each widget type
- Patterns for building reusable or dynamic widget trees
Youll also learn how widget properties interact with the expression language and how reactivity is handled across updates.

View File

@@ -1,49 +0,0 @@
# Widgets & Parameters
Below is a list of available widgets and the parameters each accepts.
## Widget Functions
These functions correspond to actual GTK widgets and render visible UI elements.
- **box**: `props`, `children`
- **centerbox**: `props`, `children`
- **eventbox**: `props`, `children`
- **tooltip**: `props`, `children`
- **circular_progress**: `props`
- **graph**: `props`
- **transform**: `props`
- **slider**: `props`
- **progress**: `props`
- **image**: `props`
- **button**: `props`
- **label**: `props`
- **input**: `props`
- **calendar**: `props`
- **color_button**: `props`
- **expander**: `props`, `children`
- **color_chooser**: `props`
- **combo_box_text**: `props`
- **checkbox**: `props`
- **revealer**: `props`, `children`
- **scroll**: `props`, `children`
- **overlay**: `props`, `children`
- **stack**: `props`, `children`
## Utility Functions
These are not visible UI widgets but are essential for layout, data binding, or dynamic behavior.
- **defwindow**: `string`, `props`, `children`
- **poll**: `props`
- **listen**: `props`
> **Let's recall**
>
> ---
>
> `props` param: Defined in `#{}`
>
> `children` param: Defined in `[]`
>
> > Both of these are discussed in [chapter 2.2](../config/config_fundamentals.md)

View File

@@ -1,844 +0,0 @@
/* https://highlightjs.readthedocs.io/en/latest/css-classes-reference.html */
.latte.hljs {
color: #4c4f69;
background: #eff1f5;
}
.latte .hljs-keyword {
color: #8839ef;
}
.latte .hljs-built_in {
color: #d20f39;
}
.latte .hljs-type {
color: #df8e1d;
}
.latte .hljs-literal {
color: #fe640b;
}
.latte .hljs-number {
color: #fe640b;
}
.latte .hljs-operator {
color: #04a5e5;
}
.latte .hljs-punctuation {
color: #5c5f77;
}
.latte .hljs-property {
color: #179299;
}
.latte .hljs-regexp {
color: #ea76cb;
}
.latte .hljs-string {
color: #40a02b;
}
.latte .hljs-char.escape_ {
color: #40a02b;
}
.latte .hljs-subst {
color: #6c6f85;
}
.latte .hljs-symbol {
color: #dd7878;
}
.latte .hljs-variable {
color: #8839ef;
}
.latte .hljs-variable.language_ {
color: #8839ef;
}
.latte .hljs-variable.constant_ {
color: #fe640b;
}
.latte .hljs-title {
color: #1e66f5;
}
.latte .hljs-title.class_ {
color: #df8e1d;
}
.latte .hljs-title.function_ {
color: #1e66f5;
}
.latte .hljs-params {
color: #4c4f69;
}
.latte .hljs-comment {
color: #7c7f93;
}
.latte .hljs-doctag {
color: #d20f39;
}
.latte .hljs-meta {
color: #fe640b;
}
.latte .hljs-section {
color: #1e66f5;
}
.latte .hljs-tag {
color: #179299;
}
.latte .hljs-name {
color: #8839ef;
}
.latte .hljs-attr {
color: #1e66f5;
}
.latte .hljs-attribute {
color: #40a02b;
}
.latte .hljs-bullet {
color: #179299;
}
.latte .hljs-code {
color: #40a02b;
}
.latte .hljs-emphasis {
color: #d20f39;
font-style: italic;
}
.latte .hljs-strong {
color: #d20f39;
font-weight: bold;
}
.latte .hljs-formula {
color: #179299;
}
.latte .hljs-link {
color: #209fb5;
font-style: italic;
}
.latte .hljs-quote {
color: #40a02b;
font-style: italic;
}
.latte .hljs-selector-tag {
color: #df8e1d;
}
.latte .hljs-selector-id {
color: #1e66f5;
}
.latte .hljs-selector-class {
color: #179299;
}
.latte .hljs-selector-attr {
color: #8839ef;
}
.latte .hljs-selector-pseudo {
color: #179299;
}
.latte .hljs-template-tag {
color: #dd7878;
}
.latte .hljs-template-variable {
color: #dd7878;
}
.latte .hljs-addition {
color: #40a02b;
background: rgba(64, 160, 43, 0.15);
}
.latte .hljs-deletion {
color: #d20f39;
background: rgba(210, 15, 57, 0.15);
}
.latte :is(h1, h2, h3, h4, h5, h6) a code {
color: #4c4f69;
}
.latte a code {
color: #1e66f5;
}
.latte code {
color: #4c4f69;
background: #e6e9ef;
}
.latte blockquote blockquote {
border-top: 0.1em solid #acb0be;
border-bottom: 0.1em solid #acb0be;
}
.latte hr {
border-color: #acb0be;
border-style: solid;
}
.latte del {
color: #7c7f93;
}
.latte .ace_gutter {
color: #8c8fa1;
background: #e6e9ef;
}
.latte .ace_gutter-active-line.ace_gutter-cell {
color: #ea76cb;
background: #e6e9ef;
}
.latte .tooltiptext {
background: #e6e9ef;
color: #4c4f69;
}
.frappe.hljs {
color: #c6d0f5;
background: #303446;
}
.frappe .hljs-keyword {
color: #ca9ee6;
}
.frappe .hljs-built_in {
color: #e78284;
}
.frappe .hljs-type {
color: #e5c890;
}
.frappe .hljs-literal {
color: #ef9f76;
}
.frappe .hljs-number {
color: #ef9f76;
}
.frappe .hljs-operator {
color: #99d1db;
}
.frappe .hljs-punctuation {
color: #b5bfe2;
}
.frappe .hljs-property {
color: #81c8be;
}
.frappe .hljs-regexp {
color: #f4b8e4;
}
.frappe .hljs-string {
color: #a6d189;
}
.frappe .hljs-char.escape_ {
color: #a6d189;
}
.frappe .hljs-subst {
color: #a5adce;
}
.frappe .hljs-symbol {
color: #eebebe;
}
.frappe .hljs-variable {
color: #ca9ee6;
}
.frappe .hljs-variable.language_ {
color: #ca9ee6;
}
.frappe .hljs-variable.constant_ {
color: #ef9f76;
}
.frappe .hljs-title {
color: #8caaee;
}
.frappe .hljs-title.class_ {
color: #e5c890;
}
.frappe .hljs-title.function_ {
color: #8caaee;
}
.frappe .hljs-params {
color: #c6d0f5;
}
.frappe .hljs-comment {
color: #949cbb;
}
.frappe .hljs-doctag {
color: #e78284;
}
.frappe .hljs-meta {
color: #ef9f76;
}
.frappe .hljs-section {
color: #8caaee;
}
.frappe .hljs-tag {
color: #81c8be;
}
.frappe .hljs-name {
color: #ca9ee6;
}
.frappe .hljs-attr {
color: #8caaee;
}
.frappe .hljs-attribute {
color: #a6d189;
}
.frappe .hljs-bullet {
color: #81c8be;
}
.frappe .hljs-code {
color: #a6d189;
}
.frappe .hljs-emphasis {
color: #e78284;
font-style: italic;
}
.frappe .hljs-strong {
color: #e78284;
font-weight: bold;
}
.frappe .hljs-formula {
color: #81c8be;
}
.frappe .hljs-link {
color: #85c1dc;
font-style: italic;
}
.frappe .hljs-quote {
color: #a6d189;
font-style: italic;
}
.frappe .hljs-selector-tag {
color: #e5c890;
}
.frappe .hljs-selector-id {
color: #8caaee;
}
.frappe .hljs-selector-class {
color: #81c8be;
}
.frappe .hljs-selector-attr {
color: #ca9ee6;
}
.frappe .hljs-selector-pseudo {
color: #81c8be;
}
.frappe .hljs-template-tag {
color: #eebebe;
}
.frappe .hljs-template-variable {
color: #eebebe;
}
.frappe .hljs-addition {
color: #a6d189;
background: rgba(166, 209, 137, 0.15);
}
.frappe .hljs-deletion {
color: #e78284;
background: rgba(231, 130, 132, 0.15);
}
.frappe :is(h1, h2, h3, h4, h5, h6) a code {
color: #c6d0f5;
}
.frappe a code {
color: #8caaee;
}
.frappe code {
color: #c6d0f5;
background: #292c3c;
}
.frappe blockquote blockquote {
border-top: 0.1em solid #626880;
border-bottom: 0.1em solid #626880;
}
.frappe hr {
border-color: #626880;
border-style: solid;
}
.frappe del {
color: #949cbb;
}
.frappe .ace_gutter {
color: #838ba7;
background: #292c3c;
}
.frappe .ace_gutter-active-line.ace_gutter-cell {
color: #f4b8e4;
background: #292c3c;
}
.frappe .tooltiptext {
background: #292c3c;
color: #c6d0f5;
}
.macchiato.hljs {
color: #cad3f5;
background: #24273a;
}
.macchiato .hljs-keyword {
color: #c6a0f6;
}
.macchiato .hljs-built_in {
color: #ed8796;
}
.macchiato .hljs-type {
color: #eed49f;
}
.macchiato .hljs-literal {
color: #f5a97f;
}
.macchiato .hljs-number {
color: #f5a97f;
}
.macchiato .hljs-operator {
color: #91d7e3;
}
.macchiato .hljs-punctuation {
color: #b8c0e0;
}
.macchiato .hljs-property {
color: #8bd5ca;
}
.macchiato .hljs-regexp {
color: #f5bde6;
}
.macchiato .hljs-string {
color: #a6da95;
}
.macchiato .hljs-char.escape_ {
color: #a6da95;
}
.macchiato .hljs-subst {
color: #a5adcb;
}
.macchiato .hljs-symbol {
color: #f0c6c6;
}
.macchiato .hljs-variable {
color: #c6a0f6;
}
.macchiato .hljs-variable.language_ {
color: #c6a0f6;
}
.macchiato .hljs-variable.constant_ {
color: #f5a97f;
}
.macchiato .hljs-title {
color: #8aadf4;
}
.macchiato .hljs-title.class_ {
color: #eed49f;
}
.macchiato .hljs-title.function_ {
color: #8aadf4;
}
.macchiato .hljs-params {
color: #cad3f5;
}
.macchiato .hljs-comment {
color: #939ab7;
}
.macchiato .hljs-doctag {
color: #ed8796;
}
.macchiato .hljs-meta {
color: #f5a97f;
}
.macchiato .hljs-section {
color: #8aadf4;
}
.macchiato .hljs-tag {
color: #8bd5ca;
}
.macchiato .hljs-name {
color: #c6a0f6;
}
.macchiato .hljs-attr {
color: #8aadf4;
}
.macchiato .hljs-attribute {
color: #a6da95;
}
.macchiato .hljs-bullet {
color: #8bd5ca;
}
.macchiato .hljs-code {
color: #a6da95;
}
.macchiato .hljs-emphasis {
color: #ed8796;
font-style: italic;
}
.macchiato .hljs-strong {
color: #ed8796;
font-weight: bold;
}
.macchiato .hljs-formula {
color: #8bd5ca;
}
.macchiato .hljs-link {
color: #7dc4e4;
font-style: italic;
}
.macchiato .hljs-quote {
color: #a6da95;
font-style: italic;
}
.macchiato .hljs-selector-tag {
color: #eed49f;
}
.macchiato .hljs-selector-id {
color: #8aadf4;
}
.macchiato .hljs-selector-class {
color: #8bd5ca;
}
.macchiato .hljs-selector-attr {
color: #c6a0f6;
}
.macchiato .hljs-selector-pseudo {
color: #8bd5ca;
}
.macchiato .hljs-template-tag {
color: #f0c6c6;
}
.macchiato .hljs-template-variable {
color: #f0c6c6;
}
.macchiato .hljs-addition {
color: #a6da95;
background: rgba(166, 218, 149, 0.15);
}
.macchiato .hljs-deletion {
color: #ed8796;
background: rgba(237, 135, 150, 0.15);
}
.macchiato :is(h1, h2, h3, h4, h5, h6) a code {
color: #cad3f5;
}
.macchiato a code {
color: #8aadf4;
}
.macchiato code {
color: #cad3f5;
background: #1e2030;
}
.macchiato blockquote blockquote {
border-top: 0.1em solid #5b6078;
border-bottom: 0.1em solid #5b6078;
}
.macchiato hr {
border-color: #5b6078;
border-style: solid;
}
.macchiato del {
color: #939ab7;
}
.macchiato .ace_gutter {
color: #8087a2;
background: #1e2030;
}
.macchiato .ace_gutter-active-line.ace_gutter-cell {
color: #f5bde6;
background: #1e2030;
}
.macchiato .tooltiptext {
background: #1e2030;
color: #cad3f5;
}
.mocha.hljs {
color: #cdd6f4;
background: #1e1e2e;
}
.mocha .hljs-keyword {
color: #cba6f7;
}
.mocha .hljs-built_in {
color: #f38ba8;
}
.mocha .hljs-type {
color: #f9e2af;
}
.mocha .hljs-literal {
color: #fab387;
}
.mocha .hljs-number {
color: #fab387;
}
.mocha .hljs-operator {
color: #89dceb;
}
.mocha .hljs-punctuation {
color: #bac2de;
}
.mocha .hljs-property {
color: #94e2d5;
}
.mocha .hljs-regexp {
color: #f5c2e7;
}
.mocha .hljs-string {
color: #a6e3a1;
}
.mocha .hljs-char.escape_ {
color: #a6e3a1;
}
.mocha .hljs-subst {
color: #a6adc8;
}
.mocha .hljs-symbol {
color: #f2cdcd;
}
.mocha .hljs-variable {
color: #cba6f7;
}
.mocha .hljs-variable.language_ {
color: #cba6f7;
}
.mocha .hljs-variable.constant_ {
color: #fab387;
}
.mocha .hljs-title {
color: #89b4fa;
}
.mocha .hljs-title.class_ {
color: #f9e2af;
}
.mocha .hljs-title.function_ {
color: #89b4fa;
}
.mocha .hljs-params {
color: #cdd6f4;
}
.mocha .hljs-comment {
color: #9399b2;
}
.mocha .hljs-doctag {
color: #f38ba8;
}
.mocha .hljs-meta {
color: #fab387;
}
.mocha .hljs-section {
color: #89b4fa;
}
.mocha .hljs-tag {
color: #94e2d5;
}
.mocha .hljs-name {
color: #cba6f7;
}
.mocha .hljs-attr {
color: #89b4fa;
}
.mocha .hljs-attribute {
color: #a6e3a1;
}
.mocha .hljs-bullet {
color: #94e2d5;
}
.mocha .hljs-code {
color: #a6e3a1;
}
.mocha .hljs-emphasis {
color: #f38ba8;
font-style: italic;
}
.mocha .hljs-strong {
color: #f38ba8;
font-weight: bold;
}
.mocha .hljs-formula {
color: #94e2d5;
}
.mocha .hljs-link {
color: #74c7ec;
font-style: italic;
}
.mocha .hljs-quote {
color: #a6e3a1;
font-style: italic;
}
.mocha .hljs-selector-tag {
color: #f9e2af;
}
.mocha .hljs-selector-id {
color: #89b4fa;
}
.mocha .hljs-selector-class {
color: #94e2d5;
}
.mocha .hljs-selector-attr {
color: #cba6f7;
}
.mocha .hljs-selector-pseudo {
color: #94e2d5;
}
.mocha .hljs-template-tag {
color: #f2cdcd;
}
.mocha .hljs-template-variable {
color: #f2cdcd;
}
.mocha .hljs-addition {
color: #a6e3a1;
background: rgba(166, 227, 161, 0.15);
}
.mocha .hljs-deletion {
color: #f38ba8;
background: rgba(243, 139, 168, 0.15);
}
.mocha :is(h1, h2, h3, h4, h5, h6) a code {
color: #cdd6f4;
}
.mocha a code {
color: #89b4fa;
}
.mocha code {
color: #cdd6f4;
background: #181825;
}
.mocha blockquote blockquote {
border-top: 0.1em solid #585b70;
border-bottom: 0.1em solid #585b70;
}
.mocha hr {
border-color: #585b70;
border-style: solid;
}
.mocha del {
color: #9399b2;
}
.mocha .ace_gutter {
color: #7f849c;
background: #181825;
}
.mocha .ace_gutter-active-line.ace_gutter-cell {
color: #f5c2e7;
background: #181825;
}
.mocha .tooltiptext {
background: #181825;
color: #cdd6f4;
}
.latte {
--bg: #eff1f5;
--fg: #4c4f69;
--sidebar-bg: #e6e9ef;
--sidebar-fg: #4c4f69;
--sidebar-non-existant: #9ca0b0;
--sidebar-active: #1e66f5;
--sidebar-spacer: #9ca0b0;
--scrollbar: #9ca0b0;
--icons: #9ca0b0;
--icons-hover: #7c7f93;
--links: #1e66f5;
--inline-code-color: #4c4f69;
--theme-popup-bg: #e6e9ef;
--theme-popup-border: #9ca0b0;
--theme-hover: #ccd0da;
--quote-bg: #e6e9ef;
--quote-border: #dce0e8;
--table-border-color: #ccd0da;
--table-header-bg: #e6e9ef;
--table-alternate-bg: #e6e9ef;
--searchbar-border-color: #ccd0da;
--searchbar-bg: #e6e9ef;
--searchbar-fg: #4c4f69;
--searchbar-shadow-color: #dce0e8;
--searchresults-header-fg: #4c4f69;
--searchresults-border-color: #ccd0da;
--searchresults-li-bg: #eff1f5;
--search-mark-bg: #fe640b;
--warning-border: #fe640b;
--color-scheme: light;
--copy-button-filter: brightness(0) saturate(100%) invert(47%) sepia(6%) saturate(1263%) hue-rotate(195deg) brightness(90%) contrast(81%);
--copy-button-filter-hover: brightness(0) saturate(100%) invert(30%) sepia(80%) saturate(1850%) hue-rotate(209deg) brightness(94%) contrast(105%);
}
.frappe {
--bg: #303446;
--fg: #c6d0f5;
--sidebar-bg: #292c3c;
--sidebar-fg: #c6d0f5;
--sidebar-non-existant: #737994;
--sidebar-active: #8caaee;
--sidebar-spacer: #737994;
--scrollbar: #737994;
--icons: #737994;
--icons-hover: #949cbb;
--links: #8caaee;
--inline-code-color: #c6d0f5;
--theme-popup-bg: #292c3c;
--theme-popup-border: #737994;
--theme-hover: #414559;
--quote-bg: #292c3c;
--quote-border: #232634;
--table-border-color: #414559;
--table-header-bg: #292c3c;
--table-alternate-bg: #292c3c;
--searchbar-border-color: #414559;
--searchbar-bg: #292c3c;
--searchbar-fg: #c6d0f5;
--searchbar-shadow-color: #232634;
--searchresults-header-fg: #c6d0f5;
--searchresults-border-color: #414559;
--searchresults-li-bg: #303446;
--search-mark-bg: #ef9f76;
--warning-border: #ef9f76;
--color-scheme: dark;
--copy-button-filter: brightness(0) saturate(100%) invert(82%) sepia(6%) saturate(1287%) hue-rotate(192deg) brightness(86%) contrast(85%);
--copy-button-filter-hover: brightness(0) saturate(100%) invert(68%) sepia(16%) saturate(1070%) hue-rotate(185deg) brightness(96%) contrast(95%);
}
.macchiato {
--bg: #24273a;
--fg: #cad3f5;
--sidebar-bg: #1e2030;
--sidebar-fg: #cad3f5;
--sidebar-non-existant: #6e738d;
--sidebar-active: #8aadf4;
--sidebar-spacer: #6e738d;
--scrollbar: #6e738d;
--icons: #6e738d;
--icons-hover: #939ab7;
--links: #8aadf4;
--inline-code-color: #cad3f5;
--theme-popup-bg: #1e2030;
--theme-popup-border: #6e738d;
--theme-hover: #363a4f;
--quote-bg: #1e2030;
--quote-border: #181926;
--table-border-color: #363a4f;
--table-header-bg: #1e2030;
--table-alternate-bg: #1e2030;
--searchbar-border-color: #363a4f;
--searchbar-bg: #1e2030;
--searchbar-fg: #cad3f5;
--searchbar-shadow-color: #181926;
--searchresults-header-fg: #cad3f5;
--searchresults-border-color: #363a4f;
--searchresults-li-bg: #24273a;
--search-mark-bg: #f5a97f;
--warning-border: #f5a97f;
--color-scheme: dark;
--copy-button-filter: brightness(0) saturate(100%) invert(75%) sepia(18%) saturate(361%) hue-rotate(190deg) brightness(91%) contrast(86%);
--copy-button-filter-hover: brightness(0) saturate(100%) invert(67%) sepia(17%) saturate(1007%) hue-rotate(183deg) brightness(99%) contrast(94%);
}
.mocha {
--bg: #1e1e2e;
--fg: #cdd6f4;
--sidebar-bg: #181825;
--sidebar-fg: #cdd6f4;
--sidebar-non-existant: #6c7086;
--sidebar-active: #89b4fa;
--sidebar-spacer: #6c7086;
--scrollbar: #6c7086;
--icons: #6c7086;
--icons-hover: #9399b2;
--links: #89b4fa;
--inline-code-color: #cdd6f4;
--theme-popup-bg: #181825;
--theme-popup-border: #6c7086;
--theme-hover: #313244;
--quote-bg: #181825;
--quote-border: #11111b;
--table-border-color: #313244;
--table-header-bg: #181825;
--table-alternate-bg: #181825;
--searchbar-border-color: #313244;
--searchbar-bg: #181825;
--searchbar-fg: #cdd6f4;
--searchbar-shadow-color: #11111b;
--searchresults-header-fg: #cdd6f4;
--searchresults-border-color: #313244;
--searchresults-li-bg: #1e1e2e;
--search-mark-bg: #fab387;
--warning-border: #fab387;
--color-scheme: dark;
--copy-button-filter: brightness(0) saturate(100%) invert(84%) sepia(9%) saturate(767%) hue-rotate(192deg) brightness(84%) contrast(84%);
--copy-button-filter-hover: brightness(0) saturate(100%) invert(68%) sepia(18%) saturate(951%) hue-rotate(180deg) brightness(98%) contrast(100%);
}

150
docs/theme/ewwii.css vendored
View File

@@ -1,150 +0,0 @@
.ewwii.hljs {
color: #abb2bf; /* base text */
background: #2c2f36; /* One Dark Pro background */
}
.ewwii .hljs-comment,
.ewwii .hljs-quote {
color: #5c6370; /* gray */
font-style: italic;
}
.ewwii .hljs-keyword,
.ewwii .hljs-selector-tag,
.ewwii .hljs-subst,
.ewwii .hljs-title,
.ewwii .hljs-section,
.ewwii .hljs-type {
color: #c678dd; /* purple */
}
.ewwii .hljs-literal,
.ewwii .hljs-number,
.ewwii .hljs-variable,
.ewwii .hljs-template-variable,
.ewwii .hljs-tag .hljs-attr {
color: #d19a66; /* orange/brown */
}
.ewwii .hljs-string,
.ewwii .hljs-doctag,
.ewwii .hljs-title.class_,
.ewwii .hljs-name,
.ewwii .hljs-selector-id,
.ewwii .hljs-selector-class,
.ewwii .hljs-attribute,
.ewwii .hljs-built_in {
color: #98c379; /* green */
}
.ewwii .hljs-title.function_,
.ewwii .hljs-function .hljs-title {
color: #61afef; /* blue */
}
.ewwii .hljs-keyword.operator,
.ewwii .hljs-operator {
color: #56b6c2; /* cyan */
}
.ewwii .hljs-regexp,
.ewwii .hljs-symbol,
.ewwii .hljs-link {
color: #e06c75; /* red/pink */
}
.ewwii .hljs-meta,
.ewwii .hljs-deletion {
color: #e06c75; /* red */
}
.ewwii .hljs-addition {
color: #98c379; /* green */
background: rgba(152, 193, 142, 0.15);
}
.ewwii .hljs-selector-attr,
.ewwii .hljs-selector-pseudo,
.ewwii .hljs-bullet,
.ewwii .hljs-code,
.ewwii .hljs-emphasis {
color: #abb2bf; /* default text */
}
.ewwii :is(h1, h2, h3, h4, h5, h6) a code {
color: #c1c3c8;
}
.ewwii a code {
color: #ff914c;
}
.ewwii code {
color: #c1c3c8;
background: #181819;
}
.ewwii pre {
border-top: 2px solid #7c7f93;
padding-top: 0.2em;
}
.ewwii blockquote blockquote {
border-top: 0.1em solid #1c1d1e;
border-bottom: 0.1em solid #1c1d1e;
}
.ewwii hr {
border-color: #1c1d1e;
border-style: solid;
}
.ewwii del {
color: #7c7f93;
}
.ewwii .tooltiptext {
background: #1c1d1e;
color: #c1c3c8;
}
.ewwii .ace_gutter {
color: #7c7f93;
background: #1c1d1e;
}
.ewwii .ace_gutter-active-line.ace_gutter-cell {
color: #ea76cb;
background: #1c1d1e;
}
.ewwii {
--bg: #212223; /* book background */
--fg: #c1c3c8; /* default text color */
--sidebar-bg: #1c1d1e;
--sidebar-fg: #c1c3c8;
--sidebar-non-existant: #7c7f93;
--sidebar-active: #ff914c;
--sidebar-spacer: #7c7f93;
--scrollbar: #7c7f93;
--icons: #7c7f93;
--icons-hover: #c1c3c8;
--links: #ff914c;
--inline-code-color: #c1c3c8;
--theme-popup-bg: #1c1d1e;
--theme-popup-border: #7c7f93;
--theme-hover: #2c2f3b;
--quote-bg: #1c1d1e;
--quote-border: #2c2f3b;
--table-border-color: #2c2f3b;
--table-header-bg: #1c1d1e;
--table-alternate-bg: #1c1d21;
--searchbar-border-color: #2c2f3b;
--searchbar-bg: #1c1d1e;
--searchbar-fg: #c1c3c8;
--searchbar-shadow-color: #1c1d21;
--searchresults-header-fg: #c1c3c8;
--searchresults-border-color: #2c2f3b;
--searchresults-li-bg: #212223;
--search-mark-bg: #fe640b;
--warning-border: #fe640b;
--color-scheme: dark;
--copy-button-filter: brightness(0) saturate(100%) invert(47%) sepia(6%)
saturate(1263%) hue-rotate(195deg) brightness(90%) contrast(81%);
--copy-button-filter-hover: brightness(0) saturate(100%) invert(30%)
sepia(80%) saturate(1850%) hue-rotate(209deg) brightness(94%)
contrast(105%);
}

372
docs/theme/index.hbs vendored
View File

@@ -1,372 +0,0 @@
<!DOCTYPE HTML>
<html lang="{{ language }}" class="{{ default_theme }} sidebar-visible" dir="{{ text_direction }}">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>{{ title }}</title>
{{#if is_print }}
<meta name="robots" content="noindex">
{{/if}}
{{#if base_url}}
<base href="{{ base_url }}">
{{/if}}
<!-- Custom HTML head -->
{{> head}}
<meta name="description" content="{{ description }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
{{#if favicon_svg}}
<link rel="icon" href="{{ resource "favicon.svg" }}">
{{/if}}
{{#if favicon_png}}
<link rel="shortcut icon" href="{{ resource "favicon.png" }}">
{{/if}}
<link rel="stylesheet" href="{{ resource "css/variables.css" }}">
<link rel="stylesheet" href="{{ resource "css/general.css" }}">
<link rel="stylesheet" href="{{ resource "css/chrome.css" }}">
{{#if print_enable}}
<link rel="stylesheet" href="{{ resource "css/print.css" }}" media="print">
{{/if}}
<!-- Fonts -->
<link rel="stylesheet" href="{{ resource "FontAwesome/css/font-awesome.css" }}">
{{#if copy_fonts}}
<link rel="stylesheet" href="{{ resource "fonts/fonts.css" }}">
{{/if}}
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" id="highlight-css" href="{{ resource "highlight.css" }}">
<link rel="stylesheet" id="tomorrow-night-css" href="{{ resource "tomorrow-night.css" }}">
<link rel="stylesheet" id="ayu-highlight-css" href="{{ resource "ayu-highlight.css" }}">
<!-- Custom theme stylesheets -->
{{#each additional_css}}
<link rel="stylesheet" href="{{ resource this }}">
{{/each}}
{{#if mathjax_support}}
<!-- MathJax -->
<script async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
{{/if}}
<!-- Provide site root and default themes to javascript -->
<script>
const path_to_root = "{{ path_to_root }}";
const default_light_theme = "{{ default_theme }}";
const default_dark_theme = "{{ preferred_dark_theme }}";
{{#if search_js}}
window.path_to_searchindex_js = "{{ resource "searchindex.js" }}";
{{/if}}
</script>
<!-- Start loading toc.js asap -->
<script src="{{ resource "toc.js" }}"></script>
</head>
<body>
<div id="mdbook-help-container">
<div id="mdbook-help-popup">
<h2 class="mdbook-help-title">Keyboard shortcuts</h2>
<div>
<p>Press <kbd>←</kbd> or <kbd>→</kbd> to navigate between chapters</p>
{{#if search_enabled}}
<p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p>
{{/if}}
<p>Press <kbd>?</kbd> to show this help</p>
<p>Press <kbd>Esc</kbd> to hide this help</p>
</div>
</div>
</div>
<div id="body-container">
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
let theme = localStorage.getItem('mdbook-theme');
let sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
let theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
const html = document.documentElement;
html.classList.remove('{{ default_theme }}')
html.classList.add(theme);
html.classList.add("js");
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
let sidebar = null;
const sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
sidebar_toggle.checked = false;
}
if (sidebar === 'visible') {
sidebar_toggle.checked = true;
} else {
html.classList.remove('sidebar-visible');
}
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<!-- populated by js -->
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
<noscript>
<iframe class="sidebar-iframe-outer" src="{{ path_to_root }}toc.html"></iframe>
</noscript>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
{{> header}}
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="default_theme">Auto</button></li>
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
<li role="none"><button role="menuitem" class="theme" id="latte">Latte</button></li>
<li role="none"><button role="menuitem" class="theme" id="frappe">Frappé</button></li>
<li role="none"><button role="menuitem" class="theme" id="macchiato">Macchiato</button></li>
<li role="none"><button role="menuitem" class="theme" id="mocha">Mocha</button></li>
<li role="none"><button role="menuitem" class="theme" id="ewwii">Ewwii</button></li>
</ul>
{{#if search_enabled}}
<button id="search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
{{/if}}
</div>
<h1 class="menu-title">{{ book_title }}</h1>
<div class="right-buttons">
{{#if print_enable}}
<a href="{{ path_to_root }}print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
{{/if}}
{{#if git_repository_url}}
<a href="{{git_repository_url}}" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa {{git_repository_icon}}"></i>
</a>
{{/if}}
{{#if git_repository_edit_url}}
<a href="{{git_repository_edit_url}}" title="Suggest an edit" aria-label="Suggest an edit" rel="edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
{{/if}}
</div>
</div>
{{#if search_enabled}}
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<div class="search-wrapper">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
<div class="spinner-wrapper">
<i class="fa fa-spinner fa-spin"></i>
</div>
</div>
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
{{/if}}
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
{{{ content }}}
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
{{#previous}}
<a rel="prev" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
{{/previous}}
{{#next}}
<a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
{{/next}}
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
{{#previous}}
<a rel="prev" href="{{ path_to_root }}{{link}}" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
{{/previous}}
{{#next}}
<a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
{{/next}}
</nav>
</div>
{{#if live_reload_endpoint}}
<!-- Livereload script (if served using the cli tool) -->
<script>
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsAddress = wsProtocol + "//" + location.host + "/" + "{{{live_reload_endpoint}}}";
const socket = new WebSocket(wsAddress);
socket.onmessage = function (event) {
if (event.data === "reload") {
socket.close();
location.reload();
}
};
window.onbeforeunload = function() {
socket.close();
}
</script>
{{/if}}
{{#if google_analytics}}
<!-- Google Analytics Tag -->
<script>
const localAddrs = ["localhost", "127.0.0.1", ""];
// make sure we don't activate google analytics if the developer is
// inspecting the book locally...
if (localAddrs.indexOf(document.location.hostname) === -1) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '{{google_analytics}}', 'auto');
ga('send', 'pageview');
}
</script>
{{/if}}
{{#if playground_line_numbers}}
<script>
window.playground_line_numbers = true;
</script>
{{/if}}
{{#if playground_copyable}}
<script>
window.playground_copyable = true;
</script>
{{/if}}
{{#if playground_js}}
<script src="{{ resource "ace.js" }}"></script>
<script src="{{ resource "mode-rust.js" }}"></script>
<script src="{{ resource "editor.js" }}"></script>
<script src="{{ resource "theme-dawn.js" }}"></script>
<script src="{{ resource "theme-tomorrow_night.js" }}"></script>
{{/if}}
{{#if search_js}}
<script src="{{ resource "elasticlunr.min.js" }}"></script>
<script src="{{ resource "mark.min.js" }}"></script>
<script src="{{ resource "searcher.js" }}"></script>
{{/if}}
<script src="{{ resource "clipboard.min.js" }}"></script>
<script src="{{ resource "highlight.js" }}"></script>
<script src="{{ resource "book.js" }}"></script>
<!-- Custom JS scripts -->
{{#each additional_js}}
<script src="{{ resource this}}"></script>
{{/each}}
{{#if is_print}}
{{#if mathjax_support}}
<script>
window.addEventListener('load', function() {
MathJax.Hub.Register.StartupHook('End', function() {
window.setTimeout(window.print, 100);
});
});
</script>
{{else}}
<script>
window.addEventListener('load', function() {
window.setTimeout(window.print, 100);
});
</script>
{{/if}}
{{/if}}
{{#if fragment_map}}
<script>
document.addEventListener('DOMContentLoaded', function() {
const fragmentMap =
{{{fragment_map}}}
;
const target = fragmentMap[window.location.hash];
if (target) {
let url = new URL(target, window.location.href);
window.location.replace(url.href);
}
});
</script>
{{/if}}
</div>
</body>
</html>

View File

@@ -1,54 +0,0 @@
pre {
display: block;
font-family: monospace;
white-space: pre;
margin: 0px;
}
.func-name {
/* override mdbook default margin for h2/h3 */
margin-top: 0em;
}
/* Annotations for a diagram or a snippet */
.ann {
text-align: center;
font-size: 0.8em;
font-style: italic;
}
/* custom css for the rust SectionFormat::Tabs option */
/* NOTE: variables used here are from mdbook's css */
.tab {
overflow: hidden;
border-left: 1px solid var(--theme-hover);
border-right: 1px solid var(--theme-hover);
}
.tab button {
color: var(--icons);
background-color: var(--theme-hover);
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
}
.tab button:hover {
color: var(--icons-hover);
background-color: var(--theme-hover);
}
.tab button.active {
background-color: var(--theme-bg);
}
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid var(--theme-hover);
border-top: none;
}

View File

@@ -1,23 +0,0 @@
function openTab(evt, group, tab) {
const tabcontent = document.getElementsByClassName("tabcontent");
for (let i = 0; i < tabcontent.length; i++) {
if (tabcontent[i].getAttribute("group") === group) {
tabcontent[i].style.display = "none";
}
}
const tablinks = document.getElementsByClassName("tablinks");
for (let i = 0; i < tablinks.length; i++) {
if (tabcontent[i].getAttribute("group") === group) {
tablinks[i].className = tablinks[i].className.replace(
" active",
""
);
}
}
document.getElementById(`${group}-${tab}`).style.display = "block";
evt.currentTarget.className += " active";
}

View File

@@ -1 +1,2 @@
/target
/auto_gen

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
use rhai::{Engine, module_resolvers::StaticModuleResolver};
use rhai_autodocs::{export::options, generate::mdbook};
use rhai_autodocs::{export::options, generate::docusaurus};
use rhai_impl::providers;
use std::{env, fs, path::Path};
@@ -15,8 +15,7 @@ fn generate_docs(
.export(engine)
.expect("failed to generate documentation");
// Generate markdown documentation content
let docs_content = mdbook().generate(&docs).unwrap();
let docs_content = docusaurus().generate(&docs).unwrap();
if docs_content.is_empty() {
eprintln!("No documentation generated for {}.", filename);
@@ -27,10 +26,55 @@ fn generate_docs(
let full_docs =
docs_content.into_iter().map(|(_, doc)| doc).collect::<Vec<String>>().join("\n");
// combination of all docs and pre description
let final_docs = format!("{}\n\n{}", pre_description, full_docs);
let mut lines = full_docs.lines();
// Write documentation to markdown file
let mut filtered_lines = Vec::new();
let mut in_frontmatter = false;
let mut frontmatter_title: Option<String> = None;
for line in &mut lines {
let trimmed = line.trim();
if trimmed == "---" {
in_frontmatter = !in_frontmatter;
if !in_frontmatter {
if let Some(title) = &frontmatter_title {
// The following will be generated:
//
// :::note Module
// # title
// :::
filtered_lines.push(format!(":::note Module\n# {}\n:::", title));
}
frontmatter_title = None;
}
continue;
}
if in_frontmatter {
if let Some(title) = trimmed.strip_prefix("title: ") {
frontmatter_title = Some(title.to_string());
}
continue;
}
if trimmed == "import Tabs from '@theme/Tabs';"
|| trimmed == "import TabItem from '@theme/TabItem';"
{
continue;
}
filtered_lines.push(line.to_string());
}
// combine
let all_imports = "import Tabs from '@theme/Tabs';\nimport TabItem from '@theme/TabItem';";
let final_docs =
format!("{}\n\n{}\n\n{}", all_imports, pre_description, filtered_lines.join("\n"));
// Write to file
let file_path = Path::new(path).join(format!("{}.md", filename));
fs::write(&file_path, final_docs).expect("failed to write documentation");
println!("Documentation generated at: {}", file_path.display());
@@ -38,7 +82,7 @@ fn generate_docs(
fn main() {
let args: Vec<String> = env::args().collect();
let path = if args.len() > 1 { &args[1] } else { "./docs/src/modules" };
let path = if args.len() > 1 { &args[1] } else { "./tools/generate-rhai-docs/auto_gen" };
// engine/resolver
let engine = Engine::new();
@@ -57,7 +101,7 @@ These functions are built-in and available globally, meaning they can be used di
For example, to get the value of PI, you can simply write:
```js
```javascript
let x = PI();
```