Skip to content

Commit

Permalink
Updates (#7)
Browse files Browse the repository at this point in the history
* update

* Update Cargo.toml

* fixes

* anyhow::result

* update

* Bump egui

* Bump versions

* fix lints

* Bump versions

* add lints and fix the issues

* update

* update crates

* fix fmt

* fix clippy

* add scripts

* bump versions
  • Loading branch information
bircni authored Sep 14, 2024
1 parent 2112104 commit ddf6ca0
Show file tree
Hide file tree
Showing 11 changed files with 215 additions and 65 deletions.
140 changes: 135 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,148 @@ short_description = "A GUI for the awtrix clock."

[dependencies]
# Error handling
anyhow = "1.0.86"
anyhow = "1.0.88"
# Networking
reqwest = { version = "0.12.5", features = ["blocking"] }
reqwest = { version = "0.12.7", features = ["blocking"] }
# Parsing
serde = { version = "1.0.204", features = ["derive"] }
serde_json = "1.0.120"
serde = { version = "1.0.210", features = ["derive"] }
serde_json = "1.0.128"
semver = "1.0.23"
# GUI
eframe = "0.28.1"
egui = "0.28.1"
egui-notify = "0.15.0"
egui_extras = { version = "0.28.1", features = ["syntect", "image"] }
image = "0.25.1"
image = "0.25.2"
open = "5.3.0"
parking_lot = "0.12.3"

[lints.rust]
unsafe_code = "forbid"

[lints.clippy]
as_ptr_cast_mut = "warn"
await_holding_lock = "warn"
bool_to_int_with_if = "warn"
char_lit_as_u8 = "warn"
checked_conversions = "warn"
clear_with_drain = "warn"
cloned_instead_of_copied = "warn"
dbg_macro = "warn"
debug_assert_with_mut_call = "warn"
derive_partial_eq_without_eq = "warn"
doc_link_with_quotes = "warn"
doc_markdown = "warn"
empty_enum = "warn"
enum_glob_use = "warn"
equatable_if_let = "warn"
exit = "warn"
expl_impl_clone_on_copy = "warn"
explicit_deref_methods = "warn"
explicit_into_iter_loop = "warn"
explicit_iter_loop = "warn"
fallible_impl_from = "warn"
filter_map_next = "warn"
flat_map_option = "warn"
float_cmp_const = "warn"
fn_params_excessive_bools = "warn"
fn_to_numeric_cast_any = "warn"
from_iter_instead_of_collect = "warn"
get_unwrap = "warn"
if_let_mutex = "warn"
implicit_clone = "warn"
implied_bounds_in_impls = "warn"
imprecise_flops = "warn"
index_refutable_slice = "warn"
inefficient_to_string = "warn"
infinite_loop = "warn"
into_iter_without_iter = "warn"
invalid_upcast_comparisons = "warn"
iter_not_returning_iterator = "warn"
iter_on_empty_collections = "warn"
iter_on_single_items = "warn"
iter_without_into_iter = "warn"
large_digit_groups = "warn"
large_include_file = "warn"
large_stack_arrays = "warn"
large_stack_frames = "warn"
large_types_passed_by_value = "warn"
let_unit_value = "warn"
linkedlist = "warn"
lossy_float_literal = "warn"
macro_use_imports = "warn"
manual_assert = "warn"
manual_clamp = "warn"
manual_instant_elapsed = "warn"
manual_let_else = "warn"
manual_ok_or = "warn"
manual_string_new = "warn"
map_err_ignore = "warn"
map_flatten = "warn"
map_unwrap_or = "warn"
match_bool = "warn"
match_on_vec_items = "warn"
match_same_arms = "warn"
match_wild_err_arm = "warn"
match_wildcard_for_single_variants = "warn"
mem_forget = "warn"
mismatched_target_os = "warn"
mismatching_type_param_order = "warn"
missing_enforced_import_renames = "warn"
missing_errors_doc = "warn"
missing_safety_doc = "warn"
mut_mut = "warn"
mutex_integer = "warn"
needless_borrow = "warn"
needless_continue = "warn"
needless_for_each = "warn"
needless_pass_by_ref_mut = "warn"
needless_pass_by_value = "warn"
negative_feature_names = "warn"
nonstandard_macro_braces = "warn"
option_option = "warn"
path_buf_push_overwrite = "warn"
ptr_as_ptr = "warn"
ptr_cast_constness = "warn"
pub_without_shorthand = "warn"
rc_mutex = "warn"
readonly_write_lock = "warn"
redundant_type_annotations = "warn"
ref_option_ref = "warn"
ref_patterns = "warn"
rest_pat_in_fully_bound_structs = "warn"
same_functions_in_if_condition = "warn"
semicolon_if_nothing_returned = "warn"
single_match_else = "warn"
str_to_string = "warn"
string_add = "warn"
string_add_assign = "warn"
string_lit_as_bytes = "warn"
string_lit_chars_any = "warn"
string_to_string = "warn"
suspicious_command_arg_space = "warn"
suspicious_xor_used_as_pow = "warn"
todo = "warn"
trailing_empty_array = "warn"
trait_duplication_in_bounds = "warn"
tuple_array_conversions = "warn"
unchecked_duration_subtraction = "warn"
undocumented_unsafe_blocks = "warn"
unimplemented = "warn"
uninhabited_references = "warn"
uninlined_format_args = "warn"
unnecessary_box_returns = "warn"
unnecessary_safety_doc = "warn"
unnecessary_struct_initialization = "warn"
unnecessary_wraps = "warn"
unnested_or_patterns = "warn"
unused_peekable = "warn"
unused_rounding = "warn"
unused_self = "warn"
use_self = "warn"
useless_transmute = "warn"
verbose_file_reads = "warn"
wildcard_dependencies = "warn"
zero_sized_map_values = "warn"

nursery = { level = "deny", priority = -1 }
20 changes: 20 additions & 0 deletions scripts/check.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
@echo on
REM This script runs various CI-like checks in a convenient way.

setlocal enabledelayedexpansion
set script_path=%~dp0
cd /d "%script_path%\.."
set RUSTDOCFLAGS=-D warnings

REM Installing typos-cli if not already installed
cargo install typos-cli --quiet

REM Running various Rust checks
typos
cargo fmt --all -- --check
cargo clippy --quiet --all-features -- -D warnings
cargo check --quiet --all-targets
cargo test --quiet --all-targets
cargo test --quiet --doc

echo All checks passed.
20 changes: 20 additions & 0 deletions scripts/check.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# This scripts runs various CI-like checks in a convenient way.

set -eu
script_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$script_path/.."
set -x

cargo install --quiet typos-cli

export RUSTDOCFLAGS="-D warnings"

typos
cargo fmt --all -- --check
cargo clippy --quiet --all-features -- -D warnings
cargo check --quiet --all-targets
cargo test --quiet --all-targets
cargo test --quiet --doc

echo "All checks passed."
11 changes: 4 additions & 7 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,10 @@ pub struct Config {

impl Config {
pub fn new() -> Self {
match Self::read() {
Ok(config) => config,
Err(_) => Self {
ip: String::new(),
last_state: false,
},
}
Self::read().unwrap_or_else(|_| Self {
ip: String::new(),
last_state: false,
})
}

fn read() -> anyhow::Result<Self> {
Expand Down
9 changes: 0 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
#![warn(clippy::pedantic)]
#![warn(clippy::perf)]
#![warn(clippy::style)]
#![deny(clippy::all)]
#![warn(clippy::unwrap_used)]
#![deny(clippy::expect_used)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
use anyhow::Context;
use egui::ViewportBuilder;

Expand Down
32 changes: 14 additions & 18 deletions src/ui/device.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::Context;
use egui::{Button, DragValue, Label, ScrollArea, SidePanel, Ui};
use egui::{Button, DragValue, ScrollArea, SidePanel, Ui};
use reqwest::blocking::Client;
use semver::Version;
use serde_json::{from_str, Value};
Expand All @@ -12,7 +12,7 @@ pub struct Device {
}

impl Device {
pub fn new() -> Self {
pub const fn new() -> Self {
Self {
time: 0,
update_available: false,
Expand Down Expand Up @@ -122,8 +122,14 @@ impl Device {
stats: &Option<Stat>,
enabled: bool,
) -> anyhow::Result<()> {
let mut ret = ui
.horizontal(|ui| {
if self.update_available {
ui.add(Button::new("Update now"))
.on_hover_text("Update device")
.clicked()
.then(|| Self::set_update(ip))
.unwrap_or(Ok(()))
} else {
ui.horizontal(|ui| {
let ret = ui
.add_enabled(enabled, Button::new("Update"))
.clicked()
Expand All @@ -134,24 +140,14 @@ impl Device {
ret
})
.inner
.unwrap_or(Ok(()));

if self.update_available {
ui.add(Label::new("An Update is available!"));
ret = ui
.add(Button::new("Update now"))
.on_hover_text("Update device")
.clicked()
.then(|| Self::set_update(ip))
.unwrap_or(Ok(()));
.unwrap_or(Ok(()))
}
ret
}

fn check_update(&mut self, ip: &str) -> anyhow::Result<()> {
let stats = status::get_stats(ip).context("Failed to get stats")?;
let current = Device::parse_to_version(&stats.version);
let latest = Device::parse_to_version(&Device::get_latest_tag().unwrap_or_default());
let current = Self::parse_to_version(&stats.version);
let latest = Self::parse_to_version(&Self::get_latest_tag().unwrap_or_default());
if current < latest {
self.update_available = true;
Ok(())
Expand Down Expand Up @@ -179,7 +175,7 @@ impl Device {
.context("")?
.as_str()
.context("")?
.to_string()
.to_owned()
.replace('"', "");

Ok(text)
Expand Down
9 changes: 5 additions & 4 deletions src/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ enum Tab {
}

impl Tab {
fn as_str(&self) -> &str {
const fn as_str(&self) -> &str {
match self {
Tab::Screen => "Screen",
Tab::Status => "Status",
Tab::Settings => "Settings",
Self::Screen => "Screen",
Self::Status => "Status",
Self::Settings => "Settings",
}
}
}
Expand Down Expand Up @@ -83,6 +83,7 @@ impl App {

/// Main application loop (called every frame)
impl eframe::App for App {
#[allow(clippy::significant_drop_in_scrutinee)]
fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
let mut current_tab = self.current_tab.write();
CentralPanel::default().show(ctx, |ui| {
Expand Down
8 changes: 3 additions & 5 deletions src/ui/screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const SIZE: [usize; 2] = [320, 80];

pub fn show(ui: &mut Ui, ip: &str, texture: Arc<RwLock<TextureHandle>>) -> anyhow::Result<()> {
if ui.button("Refresh").clicked() {
return threaded_screen(ip.to_string(), texture);
return threaded_screen(ip.to_owned(), texture);
}

ui.image(&texture.read().clone());
Expand All @@ -33,10 +33,8 @@ fn threaded_screen(ip: String, texture: Arc<RwLock<TextureHandle>>) -> anyhow::R
});

// Wait for the result from the thread
match rx.recv() {
Ok(result) => result,
Err(_) => Err(anyhow::anyhow!("Failed to receive result from thread")),
}
rx.recv()
.unwrap_or_else(|_| Err(anyhow::anyhow!("Failed to receive result from thread")))
}

fn get_screen(ip: &str) -> anyhow::Result<ColorImage> {
Expand Down
6 changes: 3 additions & 3 deletions src/ui/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub struct Settings {
impl Settings {
pub fn new() -> Self {
Self {
language: "json".to_string(),
language: "json".to_owned(),
code: String::new(),
}
}
Expand Down Expand Up @@ -73,7 +73,7 @@ impl Settings {

fn get_settings(ip: &str) -> anyhow::Result<String> {
let response = get(format!("http://{ip}/api/settings"))
.map_err(|_| anyhow::anyhow!("Failed to get settings"))?;
.map_err(|_e| anyhow::anyhow!("Failed to get settings"))?;

Ok(response
.text()?
Expand All @@ -82,7 +82,7 @@ impl Settings {
.replace('}', "\n}"))
}

pub fn set_settings(&mut self, ip: &str) -> anyhow::Result<()> {
pub fn set_settings(&self, ip: &str) -> anyhow::Result<()> {
Client::new()
.post(format!("http://{ip}/api/settings"))
.body(self.code.clone())
Expand Down
Loading

0 comments on commit ddf6ca0

Please sign in to comment.