Fixed build workflow

This commit is contained in:
Alexandr Bogomiakov
2025-07-23 23:53:46 +03:00
parent 201d008d81
commit 977d67cbf0
15 changed files with 1467 additions and 880 deletions

View File

@@ -20,13 +20,20 @@ jobs:
include:
- os: ubuntu-latest
build_target: x86_64-unknown-linux-musl
platform_name: linux-amd64-musl
build_type: musl
- os: ubuntu-latest
build_target: x86_64-unknown-linux-gnu
platform_name: linux-amd64
build_type: dynamic
- os: windows-latest
build_target: x86_64-pc-windows-msvc
platform_name: windows-amd64
build_type: default
- os: macos-latest
build_target: aarch64-apple-darwin
platform_name: macos-arm64
build_type: default
permissions:
contents: write
steps:
@@ -61,21 +68,28 @@ jobs:
- name: Install rust targets
run: rustup target add ${{ matrix.build_target }}
- name: Build Linux MUSL
if: matrix.os == 'ubuntu-latest'
- name: Install Linux dependencies
if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'dynamic'
run: |
sudo apt-get update
sudo apt-get install -y libssl-dev pkg-config libgtk-3-dev libglib2.0-dev libcairo2-dev libpango1.0-dev libatk1.0-dev libgdk-pixbuf2.0-dev libxdo-dev
- name: Build Linux Dynamic
if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'dynamic'
run: cargo build --target ${{ matrix.build_target }} --release
- name: Build Linux MUSL (no GUI)
if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'musl'
uses: gmiam/rust-musl-action@master
with:
args: |
sed -i 's/deb.debian.org/archive.debian.org/g' /etc/apt/sources.list
sed -i 's/security.debian.org/archive.debian.org/g' /etc/apt/sources.list
sed -i '/updates/d' /etc/apt/sources.list
apt-get update && apt-get install -y pkg-config libglib2.0-dev libatk1.0-dev libpango1.0-dev libgdk-pixbuf2.0-dev libgtk-3-dev libxdo-dev libcairo2-dev libgio2.0-cil libxml2-dev libfontconfig1-dev libfreetype6-dev libharfbuzz-dev libfribidi-dev libdatrie-dev libthai-dev libpixman-1-dev libxcb1-dev libxcb-render0-dev libxcb-shm0-dev libx11-dev libxext-dev libxrender-dev libgobject-2.0-dev gcc g++ musl-dev
apt-get update && apt-get install -y pkg-config libssl-dev musl-dev
export PKG_CONFIG_ALLOW_CROSS=1
export PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/share/pkgconfig
export PKG_CONFIG_SYSROOT_DIR=/
export PKG_CONFIG_ALL_STATIC=1
export RUSTFLAGS="-C target-feature=+crt-static"
cargo build --target ${{ matrix.build_target }} --release
cargo build --target ${{ matrix.build_target }} --release --no-default-features --features server
- name: Build MacOS
if: matrix.os == 'macos-latest'
@@ -93,6 +107,7 @@ jobs:
release:
name: Create Release Page
if: always() # Always run even if some builds fail
needs: build
runs-on: ubuntu-latest
outputs:
@@ -114,13 +129,15 @@ jobs:
upload:
name: Upload Release Assets
if: always() # Always run even if some builds fail
needs: release
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
include:
- os: ubuntu-latest
platform_name: linux-amd64-musl
- os: ubuntu-latest
platform_name: linux-amd64
- os: windows-latest
@@ -135,8 +152,19 @@ jobs:
with:
name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
path: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
continue-on-error: true # Continue if artifact doesn't exist
- name: Check if artifact exists
id: check_artifact
run: |
if [ -f "${{ env.BINARY_NAME }}_${{ matrix.platform_name }}/${{ env.BINARY_NAME }}${{ matrix.platform_name == 'windows-amd64' && '.exe' || '' }}" ]; then
echo "artifact_exists=true" >> $GITHUB_OUTPUT
else
echo "artifact_exists=false" >> $GITHUB_OUTPUT
fi
- name: Upload Release Asset
if: steps.check_artifact.outputs.artifact_exists == 'true'
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -154,9 +182,9 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
name: Download Linux artifact
name: Download Linux MUSL artifact
with:
name: ${{ env.BINARY_NAME }}_linux-amd64
name: ${{ env.BINARY_NAME }}_linux-amd64-musl
path: .
- name: ls

View File

@@ -493,7 +493,9 @@ impl DbClient {
info!(
"Bulk deprecated {} key(s) for {} servers in flow '{}'",
affected, server_names.len(), flow_name
affected,
server_names.len(),
flow_name
);
Ok(affected)
@@ -526,7 +528,9 @@ impl DbClient {
info!(
"Bulk restored {} key(s) for {} servers in flow '{}'",
affected, server_names.len(), flow_name
affected,
server_names.len(),
flow_name
);
Ok(affected)

View File

@@ -1,9 +1,9 @@
use crate::gui::api::{fetch_keys, SshKey};
use crate::gui::common::KhmSettings;
use eframe::egui;
use log::{error, info};
use std::collections::HashMap;
use std::sync::mpsc;
use crate::gui::api::{SshKey, fetch_keys};
use crate::gui::common::KhmSettings;
#[derive(Debug, Clone)]
pub enum AdminOperation {
@@ -57,8 +57,8 @@ impl AdminState {
if !self.search_term.is_empty() {
let search_term = self.search_term.to_lowercase();
filtered.retain(|key| {
key.server.to_lowercase().contains(&search_term) ||
key.public_key.to_lowercase().contains(&search_term)
key.server.to_lowercase().contains(&search_term)
|| key.public_key.to_lowercase().contains(&search_term)
});
}
@@ -66,7 +66,11 @@ impl AdminState {
}
/// Load keys from server
pub fn load_keys(&mut self, settings: &KhmSettings, ctx: &egui::Context) -> Option<mpsc::Receiver<Result<Vec<SshKey>, String>>> {
pub fn load_keys(
&mut self,
settings: &KhmSettings,
ctx: &egui::Context,
) -> Option<mpsc::Receiver<Result<Vec<SshKey>, String>>> {
if settings.host.is_empty() || settings.flow.is_empty() {
return None;
}
@@ -82,9 +86,7 @@ impl AdminState {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
fetch_keys(host, flow, basic_auth).await
});
let result = rt.block_on(async { fetch_keys(host, flow, basic_auth).await });
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -128,7 +130,12 @@ impl AdminState {
let total_keys = self.keys.len();
let active_keys = self.keys.iter().filter(|k| !k.deprecated).count();
let deprecated_keys = total_keys - active_keys;
let unique_servers = self.keys.iter().map(|k| &k.server).collect::<std::collections::HashSet<_>>().len();
let unique_servers = self
.keys
.iter()
.map(|k| &k.server)
.collect::<std::collections::HashSet<_>>()
.len();
AdminStatistics {
total_keys,

View File

@@ -1,7 +1,7 @@
use super::state::{get_key_preview, get_key_type, AdminState};
use crate::gui::api::SshKey;
use eframe::egui;
use std::collections::BTreeMap;
use super::state::{AdminState, get_key_type, get_key_preview};
use crate::gui::api::SshKey;
/// Render statistics cards
pub fn render_statistics(ui: &mut egui::Ui, admin_state: &AdminState) {
@@ -18,29 +18,64 @@ pub fn render_statistics(ui: &mut egui::Ui, admin_state: &AdminState) {
// Total keys
cols[0].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("📊").size(20.0));
ui.label(egui::RichText::new(stats.total_keys.to_string()).size(24.0).strong());
ui.label(egui::RichText::new("Total Keys").size(11.0).color(egui::Color32::GRAY));
ui.label(
egui::RichText::new(stats.total_keys.to_string())
.size(24.0)
.strong(),
);
ui.label(
egui::RichText::new("Total Keys")
.size(11.0)
.color(egui::Color32::GRAY),
);
});
// Active keys
cols[1].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("").size(20.0));
ui.label(egui::RichText::new(stats.active_keys.to_string()).size(24.0).strong().color(egui::Color32::LIGHT_GREEN));
ui.label(egui::RichText::new("Active").size(11.0).color(egui::Color32::GRAY));
ui.label(
egui::RichText::new(stats.active_keys.to_string())
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_GREEN),
);
ui.label(
egui::RichText::new("Active")
.size(11.0)
.color(egui::Color32::GRAY),
);
});
// Deprecated keys
cols[2].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("").size(20.0));
ui.label(egui::RichText::new(stats.deprecated_keys.to_string()).size(24.0).strong().color(egui::Color32::LIGHT_RED));
ui.label(egui::RichText::new("Deprecated").size(11.0).color(egui::Color32::GRAY));
ui.label(
egui::RichText::new(stats.deprecated_keys.to_string())
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_RED),
);
ui.label(
egui::RichText::new("Deprecated")
.size(11.0)
.color(egui::Color32::GRAY),
);
});
// Servers
cols[3].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("💻").size(20.0));
ui.label(egui::RichText::new(stats.unique_servers.to_string()).size(24.0).strong().color(egui::Color32::LIGHT_BLUE));
ui.label(egui::RichText::new("Servers").size(11.0).color(egui::Color32::GRAY));
ui.label(
egui::RichText::new(stats.unique_servers.to_string())
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_BLUE),
);
ui.label(
egui::RichText::new("Servers")
.size(11.0)
.color(egui::Color32::GRAY),
);
});
});
});
@@ -64,19 +99,33 @@ pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -
let search_response = ui.add_sized(
[ui.available_width() * 0.6, 20.0],
egui::TextEdit::singleline(&mut admin_state.search_term)
.hint_text("Search servers or keys...")
.hint_text("Search servers or keys..."),
);
if admin_state.search_term.is_empty() {
ui.label(egui::RichText::new("Type to search").size(11.0).color(egui::Color32::GRAY));
ui.label(
egui::RichText::new("Type to search")
.size(11.0)
.color(egui::Color32::GRAY),
);
} else {
ui.label(egui::RichText::new(format!("{} results", admin_state.filtered_keys.len())).size(11.0));
if ui.add(egui::Button::new(egui::RichText::new("").color(egui::Color32::WHITE))
ui.label(
egui::RichText::new(format!("{} results", admin_state.filtered_keys.len()))
.size(11.0),
);
if ui
.add(
egui::Button::new(
egui::RichText::new("").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(170, 170, 170))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(89, 89, 89)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(18.0, 18.0))
).on_hover_text("Clear search").clicked() {
.min_size(egui::vec2(18.0, 18.0)),
)
.on_hover_text("Clear search")
.clicked()
{
admin_state.search_term.clear();
changed = true;
}
@@ -98,7 +147,10 @@ pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -
admin_state.show_deprecated_only = false;
changed = true;
}
if ui.selectable_label(show_deprecated, "❗ Deprecated").clicked() {
if ui
.selectable_label(show_deprecated, "❗ Deprecated")
.clicked()
{
admin_state.show_deprecated_only = true;
changed = true;
}
@@ -115,7 +167,11 @@ pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -
/// Render bulk actions controls
pub fn render_bulk_actions(ui: &mut egui::Ui, admin_state: &mut AdminState) -> BulkAction {
let selected_count = admin_state.selected_servers.values().filter(|&&v| v).count();
let selected_count = admin_state
.selected_servers
.values()
.filter(|&&v| v)
.count();
if selected_count == 0 {
return BulkAction::None;
@@ -128,39 +184,60 @@ pub fn render_bulk_actions(ui: &mut egui::Ui, admin_state: &mut AdminState) -> B
ui.vertical(|ui| {
ui.horizontal(|ui| {
ui.label(egui::RichText::new("📋").size(14.0));
ui.label(egui::RichText::new(format!("Selected {} servers", selected_count))
ui.label(
egui::RichText::new(format!("Selected {} servers", selected_count))
.size(14.0)
.strong()
.color(egui::Color32::LIGHT_BLUE));
.color(egui::Color32::LIGHT_BLUE),
);
});
ui.add_space(5.0);
ui.horizontal(|ui| {
if ui.add(egui::Button::new(egui::RichText::new("❗ Deprecate Selected").color(egui::Color32::BLACK))
if ui
.add(
egui::Button::new(
egui::RichText::new("❗ Deprecate Selected")
.color(egui::Color32::BLACK),
)
.fill(egui::Color32::from_rgb(255, 200, 0))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(102, 94, 72)))
.rounding(egui::Rounding::same(6.0))
.min_size(egui::vec2(130.0, 28.0))
).clicked() {
.min_size(egui::vec2(130.0, 28.0)),
)
.clicked()
{
action = BulkAction::DeprecateSelected;
}
if ui.add(egui::Button::new(egui::RichText::new("✅ Restore Selected").color(egui::Color32::WHITE))
if ui
.add(
egui::Button::new(
egui::RichText::new("✅ Restore Selected").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(101, 199, 40))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(94, 105, 25)))
.rounding(egui::Rounding::same(6.0))
.min_size(egui::vec2(120.0, 28.0))
).clicked() {
.min_size(egui::vec2(120.0, 28.0)),
)
.clicked()
{
action = BulkAction::RestoreSelected;
}
if ui.add(egui::Button::new(egui::RichText::new("X Clear Selection").color(egui::Color32::WHITE))
if ui
.add(
egui::Button::new(
egui::RichText::new("X Clear Selection").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(170, 170, 170))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(89, 89, 89)))
.rounding(egui::Rounding::same(6.0))
.min_size(egui::vec2(110.0, 28.0))
).clicked() {
.min_size(egui::vec2(110.0, 28.0)),
)
.clicked()
{
admin_state.clear_selection();
action = BulkAction::ClearSelection;
}
@@ -183,12 +260,19 @@ pub fn render_keys_table(ui: &mut egui::Ui, admin_state: &mut AdminState) -> Key
// Group keys by server
let mut servers: BTreeMap<String, Vec<SshKey>> = BTreeMap::new();
for key in &admin_state.filtered_keys {
servers.entry(key.server.clone()).or_insert_with(Vec::new).push(key.clone());
servers
.entry(key.server.clone())
.or_insert_with(Vec::new)
.push(key.clone());
}
// Render each server group
for (server_name, server_keys) in servers {
let is_expanded = admin_state.expanded_servers.get(&server_name).copied().unwrap_or(false);
let is_expanded = admin_state
.expanded_servers
.get(&server_name)
.copied()
.unwrap_or(false);
let active_count = server_keys.iter().filter(|k| !k.deprecated).count();
let deprecated_count = server_keys.len() - active_count;
@@ -196,60 +280,103 @@ pub fn render_keys_table(ui: &mut egui::Ui, admin_state: &mut AdminState) -> Key
ui.group(|ui| {
ui.horizontal(|ui| {
// Server selection checkbox
let mut selected = admin_state.selected_servers.get(&server_name).copied().unwrap_or(false);
if ui.add(egui::Checkbox::new(&mut selected, "")
.indeterminate(false)
).changed() {
admin_state.selected_servers.insert(server_name.clone(), selected);
let mut selected = admin_state
.selected_servers
.get(&server_name)
.copied()
.unwrap_or(false);
if ui
.add(egui::Checkbox::new(&mut selected, "").indeterminate(false))
.changed()
{
admin_state
.selected_servers
.insert(server_name.clone(), selected);
}
// Expand/collapse button
let expand_icon = if is_expanded { "" } else { "" };
if ui.add(egui::Button::new(expand_icon)
let expand_icon = if is_expanded { "-" } else { "+" };
if ui
.add(
egui::Button::new(expand_icon)
.fill(egui::Color32::TRANSPARENT)
.stroke(egui::Stroke::NONE)
.min_size(egui::vec2(20.0, 20.0))
).clicked() {
admin_state.expanded_servers.insert(server_name.clone(), !is_expanded);
.min_size(egui::vec2(20.0, 20.0)),
)
.clicked()
{
admin_state
.expanded_servers
.insert(server_name.clone(), !is_expanded);
}
// Server icon and name
ui.label(egui::RichText::new("💻").size(16.0));
ui.label(egui::RichText::new(&server_name)
ui.label(
egui::RichText::new(&server_name)
.size(15.0)
.strong()
.color(egui::Color32::WHITE));
.color(egui::Color32::WHITE),
);
// Keys count badge
render_badge(ui, &format!("{} keys", server_keys.len()), egui::Color32::from_rgb(52, 152, 219), egui::Color32::WHITE);
render_badge(
ui,
&format!("{} keys", server_keys.len()),
egui::Color32::from_rgb(52, 152, 219),
egui::Color32::WHITE,
);
ui.add_space(5.0);
// Deprecated count badge
if deprecated_count > 0 {
render_badge(ui, &format!("{} depr", deprecated_count), egui::Color32::from_rgb(231, 76, 60), egui::Color32::WHITE);
render_badge(
ui,
&format!("{} depr", deprecated_count),
egui::Color32::from_rgb(231, 76, 60),
egui::Color32::WHITE,
);
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Server action buttons
if deprecated_count > 0 {
if ui.add(egui::Button::new(egui::RichText::new("✅ Restore").color(egui::Color32::WHITE))
if ui
.add(
egui::Button::new(
egui::RichText::new("✅ Restore").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(101, 199, 40))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(94, 105, 25)))
.stroke(egui::Stroke::new(
1.0,
egui::Color32::from_rgb(94, 105, 25),
))
.rounding(egui::Rounding::same(4.0))
.min_size(egui::vec2(70.0, 24.0))
).clicked() {
.min_size(egui::vec2(70.0, 24.0)),
)
.clicked()
{
action = KeyAction::RestoreServer(server_name.clone());
}
}
if active_count > 0 {
if ui.add(egui::Button::new(egui::RichText::new("❗ Deprecate").color(egui::Color32::BLACK))
if ui
.add(
egui::Button::new(
egui::RichText::new("❗ Deprecate").color(egui::Color32::BLACK),
)
.fill(egui::Color32::from_rgb(255, 200, 0))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(102, 94, 72)))
.stroke(egui::Stroke::new(
1.0,
egui::Color32::from_rgb(102, 94, 72),
))
.rounding(egui::Rounding::same(4.0))
.min_size(egui::vec2(85.0, 24.0))
).clicked() {
.min_size(egui::vec2(85.0, 24.0)),
)
.clicked()
{
action = KeyAction::DeprecateServer(server_name.clone());
}
}
@@ -279,29 +406,56 @@ fn render_empty_state(ui: &mut egui::Ui, admin_state: &AdminState) {
ui.vertical_centered(|ui| {
ui.add_space(60.0);
if admin_state.keys.is_empty() {
ui.label(egui::RichText::new("🔑").size(48.0).color(egui::Color32::GRAY));
ui.label(egui::RichText::new("No SSH keys available")
ui.label(
egui::RichText::new("🔑")
.size(48.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("No SSH keys available")
.size(18.0)
.color(egui::Color32::GRAY));
ui.label(egui::RichText::new("Keys will appear here once loaded from the server")
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("Keys will appear here once loaded from the server")
.size(14.0)
.color(egui::Color32::DARK_GRAY));
.color(egui::Color32::DARK_GRAY),
);
} else if !admin_state.search_term.is_empty() {
ui.label(egui::RichText::new("🔍").size(48.0).color(egui::Color32::GRAY));
ui.label(egui::RichText::new("No results found")
ui.label(
egui::RichText::new("🔍")
.size(48.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("No results found")
.size(18.0)
.color(egui::Color32::GRAY));
ui.label(egui::RichText::new(format!("Try adjusting your search: '{}'", admin_state.search_term))
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new(format!(
"Try adjusting your search: '{}'",
admin_state.search_term
))
.size(14.0)
.color(egui::Color32::DARK_GRAY));
.color(egui::Color32::DARK_GRAY),
);
} else {
ui.label(egui::RichText::new("").size(48.0).color(egui::Color32::GRAY));
ui.label(egui::RichText::new("No keys match current filters")
ui.label(
egui::RichText::new("")
.size(48.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("No keys match current filters")
.size(18.0)
.color(egui::Color32::GRAY));
ui.label(egui::RichText::new("Try adjusting your search or filter settings")
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("Try adjusting your search or filter settings")
.size(14.0)
.color(egui::Color32::DARK_GRAY));
.color(egui::Color32::DARK_GRAY),
);
}
});
}
@@ -327,60 +481,92 @@ fn render_key_item(ui: &mut egui::Ui, key: &SshKey, server_name: &str) -> Option
// Status badge
if key.deprecated {
ui.label(egui::RichText::new("❗ DEPR")
ui.label(
egui::RichText::new("❗ DEPR")
.size(10.0)
.color(egui::Color32::from_rgb(231, 76, 60))
.strong());
.strong(),
);
} else {
ui.label(egui::RichText::new("[OK] ACTIVE")
ui.label(
egui::RichText::new("")
.size(10.0)
.color(egui::Color32::from_rgb(46, 204, 113))
.strong());
.strong(),
);
}
ui.add_space(5.0);
// Key preview
ui.label(egui::RichText::new(get_key_preview(&key.public_key))
ui.label(
egui::RichText::new(get_key_preview(&key.public_key))
.font(egui::FontId::monospace(10.0))
.color(egui::Color32::LIGHT_GRAY));
.color(egui::Color32::LIGHT_GRAY),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Key action buttons
if key.deprecated {
if ui.add(egui::Button::new(egui::RichText::new("[R]").color(egui::Color32::WHITE))
if ui
.add(
egui::Button::new(
egui::RichText::new("[R]").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(101, 199, 40))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(94, 105, 25)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(22.0, 18.0))
).on_hover_text("Restore key").clicked() {
.min_size(egui::vec2(22.0, 18.0)),
)
.on_hover_text("Restore key")
.clicked()
{
action = Some(KeyAction::RestoreKey(server_name.to_string()));
}
if ui.add(egui::Button::new(egui::RichText::new("Del").color(egui::Color32::WHITE))
if ui
.add(
egui::Button::new(
egui::RichText::new("Del").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(246, 36, 71))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(129, 18, 17)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(26.0, 18.0))
).on_hover_text("Delete key").clicked() {
.min_size(egui::vec2(26.0, 18.0)),
)
.on_hover_text("Delete key")
.clicked()
{
action = Some(KeyAction::DeleteKey(server_name.to_string()));
}
} else {
if ui.add(egui::Button::new(egui::RichText::new("").color(egui::Color32::BLACK))
if ui
.add(
egui::Button::new(
egui::RichText::new("").color(egui::Color32::BLACK),
)
.fill(egui::Color32::from_rgb(255, 200, 0))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(102, 94, 72)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(22.0, 18.0))
).on_hover_text("Deprecate key").clicked() {
.min_size(egui::vec2(22.0, 18.0)),
)
.on_hover_text("Deprecate key")
.clicked()
{
action = Some(KeyAction::DeprecateKey(server_name.to_string()));
}
}
if ui.add(egui::Button::new(egui::RichText::new("Copy").color(egui::Color32::WHITE))
if ui
.add(
egui::Button::new(egui::RichText::new("Copy").color(egui::Color32::WHITE))
.fill(egui::Color32::from_rgb(0, 111, 230))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(35, 84, 97)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(30.0, 18.0))
).on_hover_text("Copy to clipboard").clicked() {
.min_size(egui::vec2(30.0, 18.0)),
)
.on_hover_text("Copy to clipboard")
.clicked()
{
ui.output_mut(|o| o.copied_text = key.public_key.clone());
}
});
@@ -392,15 +578,9 @@ fn render_key_item(ui: &mut egui::Ui, key: &SshKey, server_name: &str) -> Option
/// Render a badge with text
fn render_badge(ui: &mut egui::Ui, text: &str, bg_color: egui::Color32, text_color: egui::Color32) {
let (rect, _) = ui.allocate_exact_size(
egui::vec2(50.0, 18.0),
egui::Sense::hover()
);
ui.painter().rect_filled(
rect,
egui::Rounding::same(8.0),
bg_color
);
let (rect, _) = ui.allocate_exact_size(egui::vec2(50.0, 18.0), egui::Sense::hover());
ui.painter()
.rect_filled(rect, egui::Rounding::same(8.0), bg_color);
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
@@ -411,16 +591,15 @@ fn render_badge(ui: &mut egui::Ui, text: &str, bg_color: egui::Color32, text_col
}
/// Render a small badge with text
fn render_small_badge(ui: &mut egui::Ui, text: &str, bg_color: egui::Color32, text_color: egui::Color32) {
let (rect, _) = ui.allocate_exact_size(
egui::vec2(40.0, 16.0),
egui::Sense::hover()
);
ui.painter().rect_filled(
rect,
egui::Rounding::same(3.0),
bg_color
);
fn render_small_badge(
ui: &mut egui::Ui,
text: &str,
bg_color: egui::Color32,
text_color: egui::Color32,
) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(40.0, 16.0), egui::Sense::hover());
ui.painter()
.rect_filled(rect, egui::Rounding::same(3.0), bg_color);
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,

View File

@@ -1,7 +1,7 @@
use reqwest::Client;
use crate::gui::common::{perform_sync, KhmSettings};
use log::info;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::gui::common::{KhmSettings, perform_sync};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SshKey {
@@ -12,7 +12,11 @@ pub struct SshKey {
}
/// Test connection to KHM server
pub async fn test_connection(host: String, flow: String, basic_auth: String) -> Result<String, String> {
pub async fn test_connection(
host: String,
flow: String,
basic_auth: String,
) -> Result<String, String> {
if host.is_empty() || flow.is_empty() {
return Err("Host and flow must be specified".to_string());
}
@@ -25,18 +29,22 @@ pub async fn test_connection(host: String, flow: String, basic_auth: String) ->
request = add_auth_if_needed(request, &basic_auth)?;
let response = request.send().await
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response.text().await
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
check_html_response(&body)?;
let keys: Vec<SshKey> = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse response: {}", e))?;
let keys: Vec<SshKey> =
serde_json::from_str(&body).map_err(|e| format!("Failed to parse response: {}", e))?;
let message = format!("Found {} SSH keys from flow '{}'", keys.len(), flow);
info!("Connection test successful: {}", message);
@@ -44,12 +52,20 @@ pub async fn test_connection(host: String, flow: String, basic_auth: String) ->
}
/// Fetch all SSH keys including deprecated ones
pub async fn fetch_keys(host: String, flow: String, basic_auth: String) -> Result<Vec<SshKey>, String> {
pub async fn fetch_keys(
host: String,
flow: String,
basic_auth: String,
) -> Result<Vec<SshKey>, String> {
if host.is_empty() || flow.is_empty() {
return Err("Host and flow must be specified".to_string());
}
let url = format!("{}/{}/keys?include_deprecated=true", host.trim_end_matches('/'), flow);
let url = format!(
"{}/{}/keys?include_deprecated=true",
host.trim_end_matches('/'),
flow
);
info!("Fetching keys from: {}", url);
let client = create_http_client()?;
@@ -57,26 +73,40 @@ pub async fn fetch_keys(host: String, flow: String, basic_auth: String) -> Resul
request = add_auth_if_needed(request, &basic_auth)?;
let response = request.send().await
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response.text().await
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
check_html_response(&body)?;
let keys: Vec<SshKey> = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse response: {}", e))?;
let keys: Vec<SshKey> =
serde_json::from_str(&body).map_err(|e| format!("Failed to parse response: {}", e))?;
info!("Fetched {} SSH keys", keys.len());
Ok(keys)
}
/// Deprecate a key for a specific server
pub async fn deprecate_key(host: String, flow: String, basic_auth: String, server: String) -> Result<String, String> {
let url = format!("{}/{}/keys/{}", host.trim_end_matches('/'), flow, urlencoding::encode(&server));
pub async fn deprecate_key(
host: String,
flow: String,
basic_auth: String,
server: String,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
info!("Deprecating key for server '{}' at: {}", server, url);
let client = create_http_client()?;
@@ -84,20 +114,37 @@ pub async fn deprecate_key(host: String, flow: String, basic_auth: String, serve
request = add_auth_if_needed(request, &basic_auth)?;
let response = request.send().await
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response.text().await
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, &format!("Successfully deprecated key for server '{}'", server))
parse_api_response(
&body,
&format!("Successfully deprecated key for server '{}'", server),
)
}
/// Restore a key for a specific server
pub async fn restore_key(host: String, flow: String, basic_auth: String, server: String) -> Result<String, String> {
let url = format!("{}/{}/keys/{}/restore", host.trim_end_matches('/'), flow, urlencoding::encode(&server));
pub async fn restore_key(
host: String,
flow: String,
basic_auth: String,
server: String,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}/restore",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
info!("Restoring key for server '{}' at: {}", server, url);
let client = create_http_client()?;
@@ -105,81 +152,124 @@ pub async fn restore_key(host: String, flow: String, basic_auth: String, server:
request = add_auth_if_needed(request, &basic_auth)?;
let response = request.send().await
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response.text().await
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, &format!("Successfully restored key for server '{}'", server))
parse_api_response(
&body,
&format!("Successfully restored key for server '{}'", server),
)
}
/// Delete a key permanently for a specific server
pub async fn delete_key(host: String, flow: String, basic_auth: String, server: String) -> Result<String, String> {
let url = format!("{}/{}/keys/{}/delete", host.trim_end_matches('/'), flow, urlencoding::encode(&server));
info!("Permanently deleting key for server '{}' at: {}", server, url);
pub async fn delete_key(
host: String,
flow: String,
basic_auth: String,
server: String,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}/delete",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
info!(
"Permanently deleting key for server '{}' at: {}",
server, url
);
let client = create_http_client()?;
let mut request = client.delete(&url);
request = add_auth_if_needed(request, &basic_auth)?;
let response = request.send().await
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response.text().await
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, &format!("Successfully deleted key for server '{}'", server))
parse_api_response(
&body,
&format!("Successfully deleted key for server '{}'", server),
)
}
/// Bulk deprecate multiple servers
pub async fn bulk_deprecate_servers(host: String, flow: String, basic_auth: String, servers: Vec<String>) -> Result<String, String> {
pub async fn bulk_deprecate_servers(
host: String,
flow: String,
basic_auth: String,
servers: Vec<String>,
) -> Result<String, String> {
let url = format!("{}/{}/bulk-deprecate", host.trim_end_matches('/'), flow);
info!("Bulk deprecating {} servers at: {}", servers.len(), url);
let client = create_http_client()?;
let mut request = client.post(&url)
.json(&serde_json::json!({
let mut request = client.post(&url).json(&serde_json::json!({
"servers": servers
}));
request = add_auth_if_needed(request, &basic_auth)?;
let response = request.send().await
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response.text().await
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, "Successfully deprecated servers")
}
/// Bulk restore multiple servers
pub async fn bulk_restore_servers(host: String, flow: String, basic_auth: String, servers: Vec<String>) -> Result<String, String> {
pub async fn bulk_restore_servers(
host: String,
flow: String,
basic_auth: String,
servers: Vec<String>,
) -> Result<String, String> {
let url = format!("{}/{}/bulk-restore", host.trim_end_matches('/'), flow);
info!("Bulk restoring {} servers at: {}", servers.len(), url);
let client = create_http_client()?;
let mut request = client.post(&url)
.json(&serde_json::json!({
let mut request = client.post(&url).json(&serde_json::json!({
"servers": servers
}));
request = add_auth_if_needed(request, &basic_auth)?;
let response = request.send().await
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response.text().await
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, "Successfully restored servers")
@@ -188,7 +278,10 @@ pub async fn bulk_restore_servers(host: String, flow: String, basic_auth: String
/// Perform manual sync operation
pub async fn perform_manual_sync(settings: KhmSettings) -> Result<String, String> {
match perform_sync(&settings).await {
Ok(keys_count) => Ok(format!("Sync completed successfully with {} keys", keys_count)),
Ok(keys_count) => Ok(format!(
"Sync completed successfully with {} keys",
keys_count
)),
Err(e) => Err(e.to_string()),
}
}
@@ -203,7 +296,10 @@ fn create_http_client() -> Result<Client, String> {
.map_err(|e| format!("Failed to create HTTP client: {}", e))
}
fn add_auth_if_needed(request: reqwest::RequestBuilder, basic_auth: &str) -> Result<reqwest::RequestBuilder, String> {
fn add_auth_if_needed(
request: reqwest::RequestBuilder,
basic_auth: &str,
) -> Result<reqwest::RequestBuilder, String> {
if basic_auth.is_empty() {
return Ok(request);
}
@@ -220,7 +316,9 @@ fn check_response_status(response: &reqwest::Response) -> Result<(), String> {
let status = response.status().as_u16();
if status == 401 {
return Err("Authentication required. Please provide valid basic auth credentials.".to_string());
return Err(
"Authentication required. Please provide valid basic auth credentials.".to_string(),
);
}
if status >= 300 && status < 400 {
@@ -228,7 +326,11 @@ fn check_response_status(response: &reqwest::Response) -> Result<(), String> {
}
if !response.status().is_success() {
return Err(format!("Server returned error: {} {}", status, response.status().canonical_reason().unwrap_or("Unknown")));
return Err(format!(
"Server returned error: {} {}",
status,
response.status().canonical_reason().unwrap_or("Unknown")
));
}
Ok(())

View File

@@ -29,19 +29,14 @@ impl Default for KhmSettings {
/// Get default known_hosts file path based on OS
fn get_default_known_hosts_path() -> String {
#[cfg(target_os = "windows")]
{
if let Ok(user_profile) = std::env::var("USERPROFILE") {
format!("{}/.ssh/known_hosts", user_profile)
if let Some(home) = home_dir() {
let ssh_dir = home.join(".ssh");
let known_hosts_file = ssh_dir.join("known_hosts");
known_hosts_file.to_string_lossy().to_string()
} else {
"~/.ssh/known_hosts".to_string()
}
}
#[cfg(not(target_os = "windows"))]
{
"~/.ssh/known_hosts".to_string()
}
}
/// Get configuration file path
pub fn get_config_path() -> PathBuf {
@@ -99,8 +94,10 @@ pub fn expand_path(path: &str) -> String {
pub async fn perform_sync(settings: &KhmSettings) -> Result<usize, std::io::Error> {
use crate::Args;
info!("Starting sync with settings: host={}, flow={}, known_hosts={}, in_place={}",
settings.host, settings.flow, settings.known_hosts, settings.in_place);
info!(
"Starting sync with settings: host={}, flow={}, known_hosts={}, in_place={}",
settings.host, settings.flow, settings.known_hosts, settings.in_place
);
// Convert KhmSettings to Args for client module
let args = Args {
@@ -138,6 +135,9 @@ pub async fn perform_sync(settings: &KhmSettings) -> Result<usize, std::io::Erro
keys_before
};
info!("Sync completed: {} keys before, {} keys after", keys_before, keys_after);
info!(
"Sync completed: {} keys before, {} keys after",
keys_before, keys_after
);
Ok(keys_after)
}

View File

@@ -1,8 +1,8 @@
use log::info;
// Modules
mod api;
mod admin;
mod api;
mod common;
#[cfg(feature = "gui")]
@@ -38,6 +38,6 @@ pub async fn run_gui() -> std::io::Result<()> {
pub async fn run_gui() -> std::io::Result<()> {
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"GUI features not compiled. Install system dependencies and rebuild with --features gui"
"GUI features not compiled. Install system dependencies and rebuild with --features gui",
));
}

View File

@@ -1,8 +1,8 @@
use crate::gui::api::{perform_manual_sync, test_connection};
use crate::gui::common::{save_settings, KhmSettings};
use eframe::egui;
use log::{error, info};
use std::sync::mpsc;
use crate::gui::api::{test_connection, perform_manual_sync};
use crate::gui::common::{KhmSettings, save_settings};
#[derive(Debug, Clone)]
pub enum ConnectionStatus {
@@ -31,6 +31,7 @@ pub struct ConnectionTab {
pub is_syncing: bool,
pub sync_result_receiver: Option<mpsc::Receiver<Result<String, String>>>,
pub sync_status: SyncStatus,
pub should_auto_test: bool,
}
impl Default for ConnectionTab {
@@ -42,6 +43,7 @@ impl Default for ConnectionTab {
is_syncing: false,
sync_result_receiver: None,
sync_status: SyncStatus::Unknown,
should_auto_test: false,
}
}
}
@@ -66,9 +68,7 @@ impl ConnectionTab {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
test_connection(host, flow, basic_auth).await
});
let result = rt.block_on(async { test_connection(host, flow, basic_auth).await });
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -92,17 +92,25 @@ impl ConnectionTab {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
perform_manual_sync(settings).await
});
let result = rt.block_on(async { perform_manual_sync(settings).await });
let _ = tx.send(result);
ctx_clone.request_repaint();
});
}
/// Check for test/sync results
pub fn check_results(&mut self, ctx: &egui::Context, settings: &KhmSettings, operation_log: &mut Vec<String>) {
/// Check for test/sync results and handle auto-test
pub fn check_results(
&mut self,
ctx: &egui::Context,
settings: &KhmSettings,
operation_log: &mut Vec<String>,
) {
// Handle auto-test on first frame if needed
if self.should_auto_test && !self.is_testing_connection {
self.should_auto_test = false;
self.start_test(settings, ctx);
}
// Check for test connection result
if let Some(receiver) = &self.test_result_receiver {
if let Ok(result) = receiver.try_recv() {
@@ -112,25 +120,37 @@ impl ConnectionTab {
// Parse keys count from message
let keys_count = if let Some(start) = message.find("Found ") {
if let Some(end) = message[start + 6..].find(" SSH keys") {
message[start + 6..start + 6 + end].parse::<usize>().unwrap_or(0)
} else { 0 }
} else { 0 };
message[start + 6..start + 6 + end]
.parse::<usize>()
.unwrap_or(0)
} else {
0
}
} else {
0
};
self.connection_status = ConnectionStatus::Connected {
keys_count,
flow: settings.flow.clone()
flow: settings.flow.clone(),
};
info!("Connection test successful: {}", message);
// Add to UI log
super::ui::add_log_entry(operation_log, format!("✅ Connection test successful: {}", message));
super::ui::add_log_entry(
operation_log,
format!("✅ Connection test successful: {}", message),
);
}
Err(error) => {
self.connection_status = ConnectionStatus::Error(error.clone());
error!("Connection test failed");
// Add to UI log
super::ui::add_log_entry(operation_log, format!("❌ Connection test failed: {}", error));
super::ui::add_log_entry(
operation_log,
format!("❌ Connection test failed: {}", error),
);
}
}
self.test_result_receiver = None;
@@ -150,14 +170,20 @@ impl ConnectionTab {
info!("Sync successful: {}", message);
// Add to UI log
super::ui::add_log_entry(operation_log, format!("✅ Sync completed: {}", message));
super::ui::add_log_entry(
operation_log,
format!("✅ Sync completed: {}", message),
);
}
Err(error) => {
self.sync_status = SyncStatus::Error(error.clone());
error!("Sync failed");
// Add to UI log
super::ui::add_log_entry(operation_log, format!("❌ Sync failed: {}", error));
super::ui::add_log_entry(
operation_log,
format!("❌ Sync failed: {}", error),
);
}
}
self.sync_result_receiver = None;

View File

@@ -1,6 +1,6 @@
use super::connection::{save_settings_validated, ConnectionStatus, ConnectionTab, SyncStatus};
use crate::gui::common::{get_config_path, KhmSettings};
use eframe::egui;
use crate::gui::common::{KhmSettings, get_config_path};
use super::connection::{ConnectionTab, ConnectionStatus, SyncStatus, save_settings_validated};
/// Render connection settings tab with modern horizontal UI design
pub fn render_connection_tab(
@@ -9,7 +9,7 @@ pub fn render_connection_tab(
settings: &mut KhmSettings,
auto_sync_interval_str: &mut String,
connection_tab: &mut ConnectionTab,
operation_log: &mut Vec<String>
operation_log: &mut Vec<String>,
) {
// Check for connection test and sync results
connection_tab.check_results(ctx, settings, operation_log);
@@ -41,7 +41,7 @@ pub fn render_connection_tab(
// Local Configuration Card
render_local_config_card(ui, settings);
}
},
);
ui.add_space(8.0);
@@ -56,7 +56,7 @@ pub fn render_connection_tab(
// System Information Card
render_system_info_card(ui);
}
},
);
});
@@ -71,7 +71,10 @@ pub fn render_connection_tab(
fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionTab) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
@@ -85,11 +88,13 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
} else {
format!("Connected to '{}' • {} keys", flow, keys_count)
};
("🟢", text, egui::Color32::GREEN)
}
ConnectionStatus::Error(error_msg) => {
("🔴", format!("Connection Error: {}", error_msg), egui::Color32::RED)
("", text, egui::Color32::GREEN)
}
ConnectionStatus::Error(error_msg) => (
"",
format!("Connection Error: {}", error_msg),
egui::Color32::RED,
),
ConnectionStatus::Unknown => {
("", "Not Connected".to_string(), ui.visuals().text_color())
}
@@ -101,9 +106,17 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if connection_tab.is_testing_connection {
ui.spinner();
ui.label(egui::RichText::new("Testing...").italics().color(ui.visuals().weak_text_color()));
ui.label(
egui::RichText::new("Testing...")
.italics()
.color(ui.visuals().weak_text_color()),
);
} else {
ui.label(egui::RichText::new(&status_text).size(13.0).color(status_color));
ui.label(
egui::RichText::new(&status_text)
.size(13.0)
.color(status_color),
);
}
});
});
@@ -119,17 +132,26 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
match &connection_tab.sync_status {
SyncStatus::Success { keys_count } => {
ui.label(egui::RichText::new(format!("{} keys synced", keys_count))
.size(13.0).color(egui::Color32::GREEN));
ui.label(
egui::RichText::new(format!("{} keys synced", keys_count))
.size(13.0)
.color(egui::Color32::GREEN),
);
}
SyncStatus::Error(error_msg) => {
ui.label(egui::RichText::new("❌ Failed")
.size(13.0).color(egui::Color32::RED))
ui.label(
egui::RichText::new("❌ Failed")
.size(13.0)
.color(egui::Color32::RED),
)
.on_hover_text(error_msg);
}
SyncStatus::Unknown => {
ui.label(egui::RichText::new("No sync performed yet")
.size(13.0).color(ui.visuals().weak_text_color()));
ui.label(
egui::RichText::new("No sync performed yet")
.size(13.0)
.color(ui.visuals().weak_text_color()),
);
}
}
});
@@ -142,7 +164,10 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
@@ -150,7 +175,11 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
// Header
ui.horizontal(|ui| {
ui.label("🌐");
ui.label(egui::RichText::new("Server Configuration").size(14.0).strong());
ui.label(
egui::RichText::new("Server Configuration")
.size(14.0)
.strong(),
);
});
ui.add_space(8.0);
@@ -168,7 +197,7 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
egui::TextEdit::singleline(&mut settings.host)
.hint_text("https://your-khm-server.com")
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 6.0)) // Better vertical centering
.margin(egui::Margin::symmetric(8.0, 6.0)), // Better vertical centering
);
});
@@ -181,15 +210,24 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
egui::TextEdit::singleline(&mut settings.flow)
.hint_text("production, staging, development")
.font(egui::FontId::new(14.0, egui::FontFamily::Proportional))
.margin(egui::Margin::symmetric(8.0, 6.0))
.margin(egui::Margin::symmetric(8.0, 6.0)),
);
});
// Basic Auth (optional)
ui.vertical(|ui| {
ui.horizontal(|ui| {
ui.label(egui::RichText::new("Basic Authentication").size(13.0).strong());
ui.label(egui::RichText::new("(optional)").size(12.0).weak().italics());
ui.label(
egui::RichText::new("Basic Authentication")
.size(13.0)
.strong(),
);
ui.label(
egui::RichText::new("(optional)")
.size(12.0)
.weak()
.italics(),
);
});
ui.add_space(3.0);
ui.add_sized(
@@ -198,7 +236,7 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
.hint_text("username:password")
.password(true)
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 6.0))
.margin(egui::Margin::symmetric(8.0, 6.0)),
);
});
});
@@ -211,7 +249,10 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
@@ -219,21 +260,29 @@ fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
// Header
ui.horizontal(|ui| {
ui.label("📁");
ui.label(egui::RichText::new("Local Configuration").size(14.0).strong());
ui.label(
egui::RichText::new("Local Configuration")
.size(14.0)
.strong(),
);
});
ui.add_space(8.0);
// Known hosts file
ui.vertical(|ui| {
ui.label(egui::RichText::new("Known Hosts File Path").size(13.0).strong());
ui.label(
egui::RichText::new("Known Hosts File Path")
.size(13.0)
.strong(),
);
ui.add_space(3.0);
ui.add_sized(
[ui.available_width(), 28.0],
egui::TextEdit::singleline(&mut settings.known_hosts)
.hint_text("~/.ssh/known_hosts")
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 6.0))
.margin(egui::Margin::symmetric(8.0, 6.0)),
);
ui.add_space(8.0);
@@ -242,8 +291,19 @@ fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
ui.horizontal(|ui| {
ui.checkbox(&mut settings.in_place, "");
ui.vertical(|ui| {
ui.label(egui::RichText::new("Update file in-place after sync").size(13.0).strong());
ui.label(egui::RichText::new("Automatically modify the known_hosts file when synchronizing").size(12.0).weak().italics());
ui.label(
egui::RichText::new("Update file in-place after sync")
.size(13.0)
.strong(),
);
ui.label(
egui::RichText::new(
"Automatically modify the known_hosts file when synchronizing",
)
.size(12.0)
.weak()
.italics(),
);
});
});
});
@@ -253,17 +313,23 @@ fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
}
/// Auto-sync configuration card
fn render_auto_sync_card(ui: &mut egui::Ui, settings: &mut KhmSettings, auto_sync_interval_str: &mut String) {
fn render_auto_sync_card(
ui: &mut egui::Ui,
settings: &mut KhmSettings,
auto_sync_interval_str: &mut String,
) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| {
let is_auto_sync_enabled = !settings.host.is_empty()
&& !settings.flow.is_empty()
&& settings.in_place;
let is_auto_sync_enabled =
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
// Header with status
ui.horizontal(|ui| {
@@ -272,12 +338,16 @@ fn render_auto_sync_card(ui: &mut egui::Ui, settings: &mut KhmSettings, auto_syn
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let (status_text, status_color) = if is_auto_sync_enabled {
(" Active", egui::Color32::GREEN)
(" Active", egui::Color32::GREEN)
} else {
(" Inactive", egui::Color32::from_gray(128))
(" Inactive", egui::Color32::from_gray(128))
};
ui.label(egui::RichText::new(status_text).size(12.0).color(status_color));
ui.label(
egui::RichText::new(status_text)
.size(12.0)
.color(status_color),
);
});
});
@@ -291,7 +361,7 @@ fn render_auto_sync_card(ui: &mut egui::Ui, settings: &mut KhmSettings, auto_syn
[80.0, 26.0], // Smaller height
egui::TextEdit::singleline(auto_sync_interval_str)
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(6.0, 5.0))
.margin(egui::Margin::symmetric(6.0, 5.0)),
);
ui.label("min");
@@ -317,19 +387,31 @@ fn render_auto_sync_card(ui: &mut egui::Ui, settings: &mut KhmSettings, auto_syn
let in_place_ok = settings.in_place;
ui.horizontal(|ui| {
let (icon, color) = if host_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
let (icon, color) = if host_ok {
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("Host URL").size(11.0));
});
ui.horizontal(|ui| {
let (icon, color) = if flow_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
let (icon, color) = if flow_ok {
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("Flow name").size(11.0));
});
ui.horizontal(|ui| {
let (icon, color) = if in_place_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
let (icon, color) = if in_place_ok {
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("In-place update").size(11.0));
});
@@ -343,14 +425,17 @@ fn render_auto_sync_card(ui: &mut egui::Ui, settings: &mut KhmSettings, auto_syn
fn render_system_info_card(ui: &mut egui::Ui) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().extreme_bg_color)
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| {
// Header
ui.horizontal(|ui| {
ui.label("⚙️");
ui.label("🔧");
ui.label(egui::RichText::new("System Info").size(14.0).strong());
});
@@ -370,7 +455,7 @@ fn render_system_info_card(ui: &mut egui::Ui) {
egui::TextEdit::singleline(&mut path_str.clone())
.interactive(false)
.font(egui::FontId::new(12.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 5.0))
.margin(egui::Margin::symmetric(8.0, 5.0)),
);
ui.add_space(4.0);
@@ -391,25 +476,22 @@ fn render_action_section(
ctx: &egui::Context,
settings: &KhmSettings,
connection_tab: &mut ConnectionTab,
operation_log: &mut Vec<String>
operation_log: &mut Vec<String>,
) {
ui.add_space(8.0);
ui.add_space(2.0);
// Validation message
// Validation for save button
let save_enabled = !settings.host.is_empty() && !settings.flow.is_empty();
if !save_enabled {
ui.horizontal(|ui| {
ui.label("⚠️");
ui.label(egui::RichText::new("Complete server configuration to enable saving")
.size(12.0)
.color(egui::Color32::LIGHT_YELLOW)
.italics());
});
ui.add_space(8.0);
}
// Action buttons with modern styling
render_modern_action_buttons(ui, ctx, settings, connection_tab, save_enabled, operation_log);
render_modern_action_buttons(
ui,
ctx,
settings,
connection_tab,
save_enabled,
operation_log,
);
}
/// Modern action buttons with improved styling and layout
@@ -419,13 +501,13 @@ fn render_modern_action_buttons(
settings: &KhmSettings,
connection_tab: &mut ConnectionTab,
save_enabled: bool,
operation_log: &mut Vec<String>
operation_log: &mut Vec<String>,
) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
// Primary actions (left side)
if ui.add_enabled(
let mut save_button = ui.add_enabled(
save_enabled,
egui::Button::new(
egui::RichText::new("💾 Save & Close")
@@ -439,7 +521,14 @@ fn render_modern_action_buttons(
})
.min_size(egui::vec2(120.0, 32.0))
.rounding(6.0)
).clicked() {
);
// Add tooltip when button is disabled
if !save_enabled {
save_button = save_button.on_hover_text("Complete server configuration to enable saving:\n• Host URL is required\n• Flow name is required");
}
if save_button.clicked() {
match save_settings_validated(settings) {
Ok(()) => {
add_log_entry(operation_log, "✅ Settings saved successfully".to_string());

View File

@@ -1,14 +1,17 @@
use crate::gui::admin::{
render_bulk_actions, render_keys_table, render_search_controls, render_statistics,
AdminOperation, AdminState, BulkAction, KeyAction,
};
use crate::gui::api::{
bulk_deprecate_servers, bulk_restore_servers, delete_key, deprecate_key, restore_key, SshKey,
};
use crate::gui::common::{load_settings, KhmSettings};
use eframe::egui;
use log::info;
use std::sync::mpsc;
use crate::gui::common::{load_settings, KhmSettings};
use crate::gui::admin::{AdminState, AdminOperation, render_statistics, render_search_controls,
render_bulk_actions, render_keys_table, KeyAction, BulkAction};
use crate::gui::api::{SshKey, bulk_deprecate_servers, bulk_restore_servers,
deprecate_key, restore_key, delete_key};
use super::connection::{ConnectionTab, SettingsTab};
use super::ui::{render_connection_tab, add_log_entry};
use super::ui::{add_log_entry, render_connection_tab};
pub struct SettingsWindow {
settings: KhmSettings,
@@ -26,7 +29,7 @@ impl SettingsWindow {
let settings = load_settings();
let auto_sync_interval_str = settings.auto_sync_interval_minutes.to_string();
Self {
let mut instance = Self {
settings,
auto_sync_interval_str,
current_tab: SettingsTab::Connection,
@@ -35,7 +38,20 @@ impl SettingsWindow {
admin_receiver: None,
operation_receiver: None,
operation_log: Vec::new(),
};
// Auto-test connection if configuration is found and valid
if !instance.settings.host.is_empty() && !instance.settings.flow.is_empty() {
add_log_entry(
&mut instance.operation_log,
"🔍 Auto-testing connection with saved configuration...".to_string(),
);
// We can't call start_test here because we don't have egui::Context yet
// So we set a flag to trigger test on first frame
instance.connection_tab.should_auto_test = true;
}
instance
}
}
@@ -52,18 +68,20 @@ impl eframe::App for SettingsWindow {
.resizable(false)
.min_height(140.0)
.max_height(140.0)
.frame(egui::Frame::none()
.frame(
egui::Frame::none()
.fill(egui::Color32::from_gray(12))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_gray(60)))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_gray(60))),
)
.show(ctx, |ui| {
render_bottom_activity_log(ui, &mut self.operation_log);
});
egui::CentralPanel::default()
.frame(egui::Frame::none()
.frame(
egui::Frame::none()
.fill(egui::Color32::from_gray(18))
.inner_margin(egui::Margin::same(20.0))
.inner_margin(egui::Margin::same(20.0)),
)
.show(ctx, |ui| {
// Modern header with gradient-like styling
@@ -71,21 +89,30 @@ impl eframe::App for SettingsWindow {
.fill(ui.visuals().panel_fill)
.rounding(egui::Rounding::same(8.0))
.inner_margin(egui::Margin::same(12.0))
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color));
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
));
header_frame.show(ui, |ui| {
ui.horizontal(|ui| {
ui.add_space(4.0);
ui.label("🔑");
ui.heading(egui::RichText::new("KHM Settings").size(20.0).strong());
ui.label(egui::RichText::new(
"(Known Hosts Manager for SSH key management and synchronization)"
).size(11.0).weak().italics());
ui.label(
egui::RichText::new(
"(Known Hosts Manager for SSH key management and synchronization)",
)
.size(11.0)
.weak()
.italics(),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Version from Cargo.toml
let version = env!("CARGO_PKG_VERSION");
if ui.small_button(format!("v{}", version))
if ui
.small_button(format!("v{}", version))
.on_hover_text(format!(
"{}\n{}\nRepository: {}\nLicense: {}",
env!("CARGO_PKG_DESCRIPTION"),
@@ -118,9 +145,8 @@ impl eframe::App for SettingsWindow {
// Connection/Settings Tab
let connection_selected = matches!(self.current_tab, SettingsTab::Connection);
let connection_button = egui::Button::new(
egui::RichText::new("🌐 Connection").size(13.0)
)
let connection_button =
egui::Button::new(egui::RichText::new("🌐 Connection").size(13.0))
.fill(if connection_selected {
egui::Color32::from_rgb(0, 120, 212)
} else {
@@ -129,7 +155,10 @@ impl eframe::App for SettingsWindow {
.stroke(if connection_selected {
egui::Stroke::new(1.0, egui::Color32::from_rgb(0, 120, 212))
} else {
egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color)
egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
)
})
.rounding(6.0)
.min_size(egui::vec2(110.0, 32.0));
@@ -140,9 +169,8 @@ impl eframe::App for SettingsWindow {
// Admin Tab
let admin_selected = matches!(self.current_tab, SettingsTab::Admin);
let admin_button = egui::Button::new(
egui::RichText::new("🔧 Admin Panel").size(13.0)
)
let admin_button =
egui::Button::new(egui::RichText::new("🔧 Admin Panel").size(13.0))
.fill(if admin_selected {
egui::Color32::from_rgb(120, 80, 0)
} else {
@@ -151,7 +179,10 @@ impl eframe::App for SettingsWindow {
.stroke(if admin_selected {
egui::Stroke::new(1.0, egui::Color32::from_rgb(120, 80, 0))
} else {
egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color)
egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
)
})
.rounding(6.0)
.min_size(egui::vec2(110.0, 32.0));
@@ -172,7 +203,7 @@ impl eframe::App for SettingsWindow {
&mut self.settings,
&mut self.auto_sync_interval_str,
&mut self.connection_tab,
&mut self.operation_log
&mut self.operation_log,
);
}
SettingsTab::Admin => {
@@ -205,7 +236,10 @@ impl SettingsWindow {
self.load_admin_keys(ctx);
}
Err(error) => {
add_log_entry(&mut self.operation_log, format!("❌ Operation failed: {}", error));
add_log_entry(
&mut self.operation_log,
format!("❌ Operation failed: {}", error),
);
}
}
self.admin_state.current_operation = AdminOperation::None;
@@ -238,9 +272,11 @@ impl SettingsWindow {
// Check if connection is configured
if self.settings.host.is_empty() || self.settings.flow.is_empty() {
ui.vertical_centered(|ui| {
ui.label(egui::RichText::new("❗ Please configure connection settings first")
ui.label(
egui::RichText::new("❗ Please configure connection settings first")
.size(16.0)
.color(egui::Color32::YELLOW));
.color(egui::Color32::YELLOW),
);
ui.add_space(10.0);
if ui.button("Go to Connection Settings").clicked() {
self.current_tab = SettingsTab::Connection;
@@ -250,12 +286,20 @@ impl SettingsWindow {
}
// Load keys automatically on first view
if self.admin_state.keys.is_empty() && !matches!(self.admin_state.current_operation, AdminOperation::LoadingKeys) {
if self.admin_state.keys.is_empty()
&& !matches!(
self.admin_state.current_operation,
AdminOperation::LoadingKeys
)
{
self.load_admin_keys(ctx);
}
// Show loading state
if matches!(self.admin_state.current_operation, AdminOperation::LoadingKeys) {
if matches!(
self.admin_state.current_operation,
AdminOperation::LoadingKeys
) {
ui.vertical_centered(|ui| {
ui.spinner();
ui.label("Loading keys...");
@@ -333,7 +377,10 @@ impl SettingsWindow {
fn start_bulk_deprecate(&mut self, servers: Vec<String>, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::BulkDeprecating;
add_log_entry(&mut self.operation_log, format!("Deprecating {} servers...", servers.len()));
add_log_entry(
&mut self.operation_log,
format!("Deprecating {} servers...", servers.len()),
);
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -345,9 +392,8 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
bulk_deprecate_servers(host, flow, basic_auth, servers).await
});
let result = rt
.block_on(async { bulk_deprecate_servers(host, flow, basic_auth, servers).await });
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -356,7 +402,10 @@ impl SettingsWindow {
fn start_bulk_restore(&mut self, servers: Vec<String>, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::BulkRestoring;
add_log_entry(&mut self.operation_log, format!("Restoring {} servers...", servers.len()));
add_log_entry(
&mut self.operation_log,
format!("Restoring {} servers...", servers.len()),
);
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -368,9 +417,8 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
bulk_restore_servers(host, flow, basic_auth, servers).await
});
let result =
rt.block_on(async { bulk_restore_servers(host, flow, basic_auth, servers).await });
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -379,7 +427,10 @@ impl SettingsWindow {
fn start_deprecate_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::DeprecatingKey;
add_log_entry(&mut self.operation_log, format!("Deprecating key for server: {}", server));
add_log_entry(
&mut self.operation_log,
format!("Deprecating key for server: {}", server),
);
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -392,9 +443,8 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
deprecate_key(host, flow, basic_auth, server_name).await
});
let result =
rt.block_on(async { deprecate_key(host, flow, basic_auth, server_name).await });
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -403,7 +453,10 @@ impl SettingsWindow {
fn start_restore_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::RestoringKey;
add_log_entry(&mut self.operation_log, format!("Restoring key for server: {}", server));
add_log_entry(
&mut self.operation_log,
format!("Restoring key for server: {}", server),
);
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -416,9 +469,8 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
restore_key(host, flow, basic_auth, server_name).await
});
let result =
rt.block_on(async { restore_key(host, flow, basic_auth, server_name).await });
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -427,7 +479,10 @@ impl SettingsWindow {
fn start_delete_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::DeletingKey;
add_log_entry(&mut self.operation_log, format!("Deleting key for server: {}", server));
add_log_entry(
&mut self.operation_log,
format!("Deleting key for server: {}", server),
);
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -440,9 +495,8 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
delete_key(host, flow, basic_auth, server_name).await
});
let result =
rt.block_on(async { delete_key(host, flow, basic_auth, server_name).await });
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -530,7 +584,7 @@ fn render_bottom_activity_log(ui: &mut egui::Ui, operation_log: &mut Vec<String>
[ui.available_width() - 8.0, 80.0], // Account for right margin
egui::TextEdit::multiline(&mut log_text.clone())
.font(egui::FontId::new(11.0, egui::FontFamily::Monospace))
.interactive(false)
.interactive(false),
);
ui.add_space(8.0); // Right margin

View File

@@ -6,10 +6,7 @@ use notify::RecursiveMode;
use notify_debouncer_mini::{new_debouncer, DebounceEventResult};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tray_icon::{
menu::MenuEvent,
TrayIcon,
};
use tray_icon::{menu::MenuEvent, TrayIcon};
use winit::{
application::ApplicationHandler,
event_loop::{EventLoop, EventLoopProxy},
@@ -18,9 +15,11 @@ use winit::{
#[cfg(target_os = "macos")]
use winit::platform::macos::EventLoopBuilderExtMacOS;
use super::{SyncStatus, TrayMenuIds, create_tray_icon, update_tray_menu,
create_tooltip, start_auto_sync_task, update_sync_status};
use crate::gui::common::{load_settings, get_config_path, perform_sync, KhmSettings};
use super::{
create_tooltip, create_tray_icon, start_auto_sync_task, update_sync_status, update_tray_menu,
SyncStatus, TrayMenuIds,
};
use crate::gui::common::{get_config_path, load_settings, perform_sync, KhmSettings};
pub struct TrayApplication {
tray_icon: Option<TrayIcon>,
@@ -56,7 +55,10 @@ impl TrayApplication {
std::thread::spawn(move || {
while let Ok(result) = rx.recv() {
if let Ok(events) = result {
if events.iter().any(|e| e.path.to_string_lossy().contains("khm_config.json")) {
if events
.iter()
.any(|e| e.path.to_string_lossy().contains("khm_config.json"))
{
let _ = proxy.send_event(crate::gui::UserEvent::ConfigFileChanged);
}
}
@@ -65,7 +67,11 @@ impl TrayApplication {
if let Ok(mut debouncer) = new_debouncer(Duration::from_millis(500), tx) {
if let Some(config_dir) = config_path.parent() {
if debouncer.watcher().watch(config_dir, RecursiveMode::NonRecursive).is_ok() {
if debouncer
.watcher()
.watch(config_dir, RecursiveMode::NonRecursive)
.is_ok()
{
info!("File watcher started");
self._debouncer = Some(debouncer);
} else {
@@ -95,7 +101,10 @@ impl TrayApplication {
// Restart auto sync if interval changed
if old_interval != new_interval {
info!("Auto sync interval changed from {} to {} minutes, restarting auto sync", old_interval, new_interval);
info!(
"Auto sync interval changed from {} to {} minutes, restarting auto sync",
old_interval, new_interval
);
self.start_auto_sync();
}
}
@@ -109,7 +118,7 @@ impl TrayApplication {
self.auto_sync_handle = start_auto_sync_task(
Arc::clone(&self.settings),
Arc::clone(&self.sync_status),
self.proxy.clone()
self.proxy.clone(),
);
}
@@ -122,7 +131,11 @@ impl TrayApplication {
}
}
fn handle_menu_event(&mut self, event: MenuEvent, event_loop: &winit::event_loop::ActiveEventLoop) {
fn handle_menu_event(
&mut self,
event: MenuEvent,
event_loop: &winit::event_loop::ActiveEventLoop,
) {
if let Some(menu_ids) = &self.menu_ids {
if event.id == menu_ids.settings_id {
info!("Settings menu clicked");
@@ -162,7 +175,10 @@ impl TrayApplication {
return;
}
info!("Syncing with host: {}, flow: {}", settings.host, settings.flow);
info!(
"Syncing with host: {}, flow: {}",
settings.host, settings.flow
);
// Run sync in separate thread with its own tokio runtime
std::thread::spawn(move || {
@@ -202,7 +218,8 @@ impl ApplicationHandler<crate::gui::UserEvent> for TrayApplication {
_event_loop: &winit::event_loop::ActiveEventLoop,
_window_id: winit::window::WindowId,
_event: winit::event::WindowEvent,
) {}
) {
}
fn resumed(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop) {
if self.tray_icon.is_none() {
@@ -222,7 +239,11 @@ impl ApplicationHandler<crate::gui::UserEvent> for TrayApplication {
}
}
fn user_event(&mut self, event_loop: &winit::event_loop::ActiveEventLoop, event: crate::gui::UserEvent) {
fn user_event(
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
event: crate::gui::UserEvent,
) {
match event {
crate::gui::UserEvent::TrayIconEvent => {}
crate::gui::UserEvent::UpdateMenu => {
@@ -246,12 +267,23 @@ pub async fn run_tray_app() -> std::io::Result<()> {
EventLoop::<crate::gui::UserEvent>::with_user_event()
.with_activation_policy(ActivationPolicy::Accessory)
.build()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("Failed to create event loop: {}", e)))?
.map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to create event loop: {}", e),
)
})?
};
#[cfg(not(target_os = "macos"))]
let event_loop = EventLoop::<crate::gui::UserEvent>::with_user_event().build()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("Failed to create event loop: {}", e)))?;
let event_loop = EventLoop::<crate::gui::UserEvent>::with_user_event()
.build()
.map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to create event loop: {}", e),
)
})?;
let proxy = event_loop.create_proxy();
@@ -268,8 +300,12 @@ pub async fn run_tray_app() -> std::io::Result<()> {
let mut app = TrayApplication::new(proxy);
event_loop.run_app(&mut app)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("Event loop error: {:?}", e)))?;
event_loop.run_app(&mut app).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Event loop error: {:?}", e),
)
})?;
Ok(())
}

View File

@@ -1,10 +1,10 @@
use crate::gui::common::{perform_sync, KhmSettings};
use log::{error, info};
use std::sync::{Arc, Mutex};
use tray_icon::{
menu::{Menu, MenuItem, MenuId},
menu::{Menu, MenuId, MenuItem},
TrayIcon, TrayIconBuilder,
};
use crate::gui::common::{KhmSettings, perform_sync};
#[derive(Debug, Clone)]
pub struct SyncStatus {
@@ -30,9 +30,13 @@ pub struct TrayMenuIds {
}
/// Create tray icon with menu
pub fn create_tray_icon(settings: &KhmSettings, sync_status: &SyncStatus) -> (TrayIcon, TrayMenuIds) {
pub fn create_tray_icon(
settings: &KhmSettings,
sync_status: &SyncStatus,
) -> (TrayIcon, TrayMenuIds) {
// Create simple blue icon
let icon_data: Vec<u8> = (0..32*32).flat_map(|i| {
let icon_data: Vec<u8> = (0..32 * 32)
.flat_map(|i| {
let y = i / 32;
let x = i % 32;
if x < 2 || x >= 30 || y < 2 || y >= 30 {
@@ -40,7 +44,8 @@ pub fn create_tray_icon(settings: &KhmSettings, sync_status: &SyncStatus) -> (Tr
} else {
[64, 128, 255, 255] // Blue center
}
}).collect();
})
.collect();
let icon = tray_icon::Icon::from_rgba(icon_data, 32, 32).unwrap();
let menu = Menu::new();
@@ -60,27 +65,38 @@ pub fn create_tray_icon(settings: &KhmSettings, sync_status: &SyncStatus) -> (Tr
};
menu.append(&MenuItem::new(flow_text, false, None)).unwrap();
let is_auto_sync_enabled = !settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let sync_text = format!("Auto sync: {} ({}min)",
let is_auto_sync_enabled =
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let sync_text = format!(
"Auto sync: {} ({}min)",
if is_auto_sync_enabled { "On" } else { "Off" },
settings.auto_sync_interval_minutes);
menu.append(&MenuItem::new(&sync_text, false, None)).unwrap();
settings.auto_sync_interval_minutes
);
menu.append(&MenuItem::new(&sync_text, false, None))
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
// Sync Now menu item
let sync_item = MenuItem::new("Sync Now", !settings.host.is_empty() && !settings.flow.is_empty(), None);
let sync_item = MenuItem::new(
"Sync Now",
!settings.host.is_empty() && !settings.flow.is_empty(),
None,
);
let sync_id = sync_item.id().clone();
menu.append(&sync_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
// Settings menu item
let settings_item = MenuItem::new("Settings", true, None);
let settings_id = settings_item.id().clone();
menu.append(&settings_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
// Quit menu item
let quit_item = MenuItem::new("Quit", true, None);
@@ -125,27 +141,38 @@ pub fn update_tray_menu(tray_icon: &TrayIcon, settings: &KhmSettings) -> TrayMen
};
menu.append(&MenuItem::new(flow_text, false, None)).unwrap();
let is_auto_sync_enabled = !settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let sync_text = format!("Auto sync: {} ({}min)",
let is_auto_sync_enabled =
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let sync_text = format!(
"Auto sync: {} ({}min)",
if is_auto_sync_enabled { "On" } else { "Off" },
settings.auto_sync_interval_minutes);
menu.append(&MenuItem::new(&sync_text, false, None)).unwrap();
settings.auto_sync_interval_minutes
);
menu.append(&MenuItem::new(&sync_text, false, None))
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
// Sync Now menu item
let sync_item = MenuItem::new("Sync Now", !settings.host.is_empty() && !settings.flow.is_empty(), None);
let sync_item = MenuItem::new(
"Sync Now",
!settings.host.is_empty() && !settings.flow.is_empty(),
None,
);
let sync_id = sync_item.id().clone();
menu.append(&sync_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
// Settings menu item
let settings_item = MenuItem::new("Settings", true, None);
let settings_id = settings_item.id().clone();
menu.append(&settings_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
// Quit menu item
let quit_item = MenuItem::new("Quit", true, None);
@@ -163,7 +190,10 @@ pub fn update_tray_menu(tray_icon: &TrayIcon, settings: &KhmSettings) -> TrayMen
/// Create tooltip text for tray icon
pub fn create_tooltip(settings: &KhmSettings, sync_status: &SyncStatus) -> String {
let mut tooltip = format!("KHM - SSH Key Manager\nHost: {}\nFlow: {}", settings.host, settings.flow);
let mut tooltip = format!(
"KHM - SSH Key Manager\nHost: {}\nFlow: {}",
settings.host, settings.flow
);
if let Some(keys_count) = sync_status.last_sync_keys {
tooltip.push_str(&format!("\nLast sync: {} keys", keys_count));
@@ -186,17 +216,23 @@ pub fn create_tooltip(settings: &KhmSettings, sync_status: &SyncStatus) -> Strin
pub fn start_auto_sync_task(
settings: Arc<Mutex<KhmSettings>>,
sync_status: Arc<Mutex<SyncStatus>>,
event_sender: winit::event_loop::EventLoopProxy<crate::gui::UserEvent>
event_sender: winit::event_loop::EventLoopProxy<crate::gui::UserEvent>,
) -> Option<std::thread::JoinHandle<()>> {
let initial_settings = settings.lock().unwrap().clone();
// Only start auto sync if settings are valid and in_place is enabled
if initial_settings.host.is_empty() || initial_settings.flow.is_empty() || !initial_settings.in_place {
if initial_settings.host.is_empty()
|| initial_settings.flow.is_empty()
|| !initial_settings.in_place
{
info!("Auto sync disabled or settings invalid");
return None;
}
info!("Starting auto sync with interval {} minutes", initial_settings.auto_sync_interval_minutes);
info!(
"Starting auto sync with interval {} minutes",
initial_settings.auto_sync_interval_minutes
);
let handle = std::thread::spawn(move || {
// Initial sync on startup
@@ -207,7 +243,10 @@ pub fn start_auto_sync_task(
rt.block_on(async {
match perform_sync(&current_settings).await {
Ok(keys_count) => {
info!("Initial sync completed successfully with {} keys", keys_count);
info!(
"Initial sync completed successfully with {} keys",
keys_count
);
let mut status = sync_status.lock().unwrap();
status.last_sync_time = Some(std::time::Instant::now());
status.last_sync_keys = Some(keys_count);
@@ -222,11 +261,9 @@ pub fn start_auto_sync_task(
// Start menu update timer
let timer_sender = event_sender.clone();
std::thread::spawn(move || {
loop {
std::thread::spawn(move || loop {
std::thread::sleep(std::time::Duration::from_secs(1));
let _ = timer_sender.send_event(crate::gui::UserEvent::UpdateMenu);
}
});
// Periodic sync
@@ -235,7 +272,10 @@ pub fn start_auto_sync_task(
std::thread::sleep(std::time::Duration::from_secs(interval_minutes as u64 * 60));
let current_settings = settings.lock().unwrap().clone();
if current_settings.host.is_empty() || current_settings.flow.is_empty() || !current_settings.in_place {
if current_settings.host.is_empty()
|| current_settings.flow.is_empty()
|| !current_settings.in_place
{
info!("Auto sync stopped due to invalid settings or disabled in_place");
break;
}

View File

@@ -2,5 +2,7 @@ mod app;
mod icon;
pub use app::*;
pub use icon::{SyncStatus, TrayMenuIds, create_tray_icon, update_tray_menu,
create_tooltip, start_auto_sync_task, update_sync_status};
pub use icon::{
create_tooltip, create_tray_icon, start_auto_sync_task, update_sync_status, update_tray_menu,
SyncStatus, TrayMenuIds,
};

View File

@@ -1,8 +1,8 @@
mod client;
mod db;
mod gui;
mod server;
mod web;
mod gui;
use clap::Parser;
use env_logger;
@@ -165,7 +165,7 @@ async fn main() -> std::io::Result<()> {
error!("GUI features not compiled. Install system dependencies and rebuild with --features gui");
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"GUI features not compiled"
"GUI features not compiled",
));
}
}
@@ -193,10 +193,7 @@ async fn main() -> std::io::Result<()> {
" Client mode: {} --host https://khm.example.com --flow work",
env!("CARGO_PKG_NAME")
);
eprintln!(
" GUI mode: {} --gui",
env!("CARGO_PKG_NAME")
);
eprintln!(" GUI mode: {} --gui", env!("CARGO_PKG_NAME"));
eprintln!(
" Settings window: {} --gui --settings-ui",
env!("CARGO_PKG_NAME")

View File

@@ -1,14 +1,14 @@
use actix_web::{web, HttpResponse, Result};
use futures::future;
use log::info;
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::sync::Arc;
use trust_dns_resolver::TokioAsyncResolver;
use trust_dns_resolver::config::*;
use serde::{Deserialize, Serialize};
use futures::future;
use tokio::sync::Semaphore;
use tokio::time::{timeout, Duration};
use trust_dns_resolver::config::*;
use trust_dns_resolver::TokioAsyncResolver;
use crate::db::ReconnectingDbClient;
use crate::server::Flows;
@@ -41,10 +41,7 @@ async fn check_dns_resolution(hostname: String, semaphore: Arc<Semaphore>) -> Dn
}
};
let resolver = TokioAsyncResolver::tokio(
ResolverConfig::default(),
ResolverOpts::default(),
);
let resolver = TokioAsyncResolver::tokio(ResolverConfig::default(), ResolverOpts::default());
let lookup_result = timeout(Duration::from_secs(5), resolver.lookup_ip(&hostname)).await;
@@ -88,7 +85,10 @@ pub async fn scan_dns_resolution(
) -> Result<HttpResponse> {
let flow_id_str = path.into_inner();
info!("API request to scan DNS resolution for flow '{}'" , flow_id_str);
info!(
"API request to scan DNS resolution for flow '{}'",
flow_id_str
);
if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({
@@ -114,7 +114,10 @@ pub async fn scan_dns_resolution(
drop(flows_guard);
info!("Scanning DNS resolution for {} unique hosts", hostnames.len());
info!(
"Scanning DNS resolution for {} unique hosts",
hostnames.len()
);
// Limit concurrent DNS requests to prevent "too many open files" error
let semaphore = Arc::new(Semaphore::new(20));
@@ -128,7 +131,11 @@ pub async fn scan_dns_resolution(
let results = future::join_all(scan_futures).await;
let unresolved_count = results.iter().filter(|r| !r.resolved).count();
info!("DNS scan complete: {} unresolved out of {} hosts", unresolved_count, results.len());
info!(
"DNS scan complete: {} unresolved out of {} hosts",
unresolved_count,
results.len()
);
Ok(HttpResponse::Ok().json(json!({
"results": results,
@@ -147,7 +154,11 @@ pub async fn bulk_deprecate_servers(
) -> Result<HttpResponse> {
let flow_id_str = path.into_inner();
info!("API request to bulk deprecate {} servers in flow '{}'", request.servers.len(), flow_id_str);
info!(
"API request to bulk deprecate {} servers in flow '{}'",
request.servers.len(),
flow_id_str
);
if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({
@@ -161,7 +172,11 @@ pub async fn bulk_deprecate_servers(
.await
{
Ok(count) => {
info!("Bulk deprecated {} key(s) for {} servers", count, request.servers.len());
info!(
"Bulk deprecated {} key(s) for {} servers",
count,
request.servers.len()
);
count
}
Err(e) => {
@@ -203,7 +218,11 @@ pub async fn bulk_restore_servers(
) -> Result<HttpResponse> {
let flow_id_str = path.into_inner();
info!("API request to bulk restore {} servers in flow '{}'", request.servers.len(), flow_id_str);
info!(
"API request to bulk restore {} servers in flow '{}'",
request.servers.len(),
flow_id_str
);
if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({
@@ -217,7 +236,11 @@ pub async fn bulk_restore_servers(
.await
{
Ok(count) => {
info!("Bulk restored {} key(s) for {} servers", count, request.servers.len());
info!(
"Bulk restored {} key(s) for {} servers",
count,
request.servers.len()
);
count
}
Err(e) => {