Compare commits

...

2 Commits

Author SHA1 Message Date
e90cf242bd feat: Add VS Code configuration and icon assets for Tauri application 2026-01-26 21:58:34 +01:00
efbbccb36f feat: Enhance application with logging, configuration management, and system tray support
first working gui windows with configs
2026-01-18 21:36:59 +01:00
71 changed files with 538 additions and 239 deletions

5
.gitignore vendored
View File

@@ -7,10 +7,11 @@
.DS_Store .DS_Store
Thumbs.db Thumbs.db
# VS Code # VS Code - Ignore everything but project-specific config
.vscode/ .vscode/*
!.vscode/launch.json !.vscode/launch.json
!.vscode/tasks.json !.vscode/tasks.json
!.vscode/extensions.json
# Node / Frontend (om det läggs till senare) # Node / Frontend (om det läggs till senare)
node_modules/ node_modules/

7
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
"recommendations": [
"vadimcn.vscode-lldb",
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}

19
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,19 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Tauri App",
"type": "lldb",
"request": "launch",
"program": "${workspaceFolder}/src-tauri/target/debug/ai-translater-client",
"args": [],
"cwd": "${workspaceFolder}/src-tauri",
"preLaunchTask": "build",
"env": {
"WEBKIT_DISABLE_COMPOSITING_MODE": "1",
// "GDK_BACKEND": "x11" // Uncomment if the above doesn't fix the initialization error
},
"sourceLanguages": ["rust"]
}
]
}

69
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,69 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "cargo",
"args": [
"build",
"--manifest-path=./src-tauri/Cargo.toml",
"--no-default-features"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": [
"$rustc"
]
},
{
"label": "Build Release (Linux)",
"type": "shell",
"command": "cargo",
"args": [
"tauri",
"build"
],
"options": {
"cwd": "${workspaceFolder}/src-tauri"
},
"group": "build",
"problemMatcher": []
},
{
"label": "Build Release (Windows)",
"type": "shell",
"command": "cargo",
"args": [
"tauri",
"build",
"--target",
"x86_64-pc-windows-msvc"
],
"options": {
"cwd": "${workspaceFolder}/src-tauri"
},
"group": "build",
"problemMatcher": []
},
{
"label": "tauri dev",
"type": "shell",
"command": "cargo",
"args": [
"tauri",
"dev"
],
"options": {
"cwd": "${workspaceFolder}/src-tauri",
"env": {
"WEBKIT_DISABLE_COMPOSITING_MODE": "1"
}
},
"group": "build",
"problemMatcher": []
}
]
}

265
README.md
View File

@@ -1,191 +1,110 @@
# AI Typist Client # AI Typist Client
En cross-platform skrivbordsapplikation utvecklad i Rust och Tauri v2 för Windows 11 och Linux (med Wayland-stöd). Applikationen fungerar som en smart AI-assistent som integrerar sömlöst med ditt arbetsflöde via system-tray, globala genvägar och urklippshantering. En smart skrivbordsassistent utvecklad i Rust och Tauri v2. Applikationen hjälper dig att översätta, rättstava och förbättra text i realtid genom att integrera lokala AI-modeller (Ollama) eller molntjänster (OpenAI) direkt i ditt arbetsflöde.
## Projektbeskrivning ## 🚀 Komma Igång
Målet med detta projekt är att skapa ett verktyg som kan förbättra, rättstava eller översätta text i alla applikationer genom att utnyttja lokala LLM:er (via Ollama) eller molnbaserade API:er (OpenAI). ### Förutsättningar
### Kärnfunktionalitet För att utveckla och bygga applikationen behöver du följande installerat:
1. **System Tray Integration**: 1. **Rust & Cargo**:
* Applikationen körs i bakgrunden med en ikon i statusfältet/systemfältet. ```bash
* Högerklick ger en meny för att komma åt inställningar eller avsluta appen. curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
2. **System-beroenden (Linux/Debian/Ubuntu)**:
```bash
sudo apt update
sudo apt install libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libssl-dev \
libgtk-3-dev \
libayatana-appindicator3-dev \
librsvg2-dev
```
3. **Cross-compilation (Windows från Linux)**:
Om du vill bygga för Windows från Linux behöver du `nsis` samt Rust-målet för Windows:
```bash
rustup target add x86_64-pc-windows-msvc
# Observera att cross-compilation med MSVC kan kräva ytterligare konfiguration (libs).
# Alternativt använd x86_64-pc-windows-gnu om du har Mingw installerat.
```
2. **AI-Workflow**: ---
* **Input**: Appen hämtar text direkt från systemets urklipp (clipboard).
* **Bearbetning**: Texten bakas in i en prompt och skickas till en LLM (Ollama/OpenAI) för översättning eller rättstavning.
* **Output**: Det bearbetade svaret kan antingen:
* Kopieras tillbaka till urklipp.
* Skrivas ut direkt i det aktiva fönstret genom att imitera tangentbordstryckningar (Keyboard Mimicry).
3. **Teknisk Stack**: ## 💻 Utveckling i VS Code
* **Språk**: Rust
* **GUI/Ramverk**: Tauri v2
* **Tangentbord/Input**: `enigo` (mimic) & `global-hotkey` (lyssna)
* **Urklipp**: `arboard`
* **AI-Kommunikation**: `reqwest` & `ollama-rs`
## Förutsättningar Det här projektet är konfigurerat för en smidig upplevelse i VS Code.
Du behöver Rust installerat (rekommenderat via `rustup`). ### Rekommenderade Tillägg
VS Code kommer automatiskt rekommendera dessa, men se till att du har:
* **rust-analyzer** (Rust språkstöd)
* **Tauri** (Tauri verktyg)
* **CodeLLDB** (För debugging)
**Installera Rust (Linux/macOS):** ### Debugging (Felsökning)
Du kan köra och debugga appen direkt inifrån redigeraren:
1. Gå till **Run and Debug** fliken (Ctrl+Shift+D).
2. Välj **"Debug Tauri App"** i menyn.
3. Tryck **F5** (Play).
* *Detta bygger appen och startar debuggern automatiskt. Du kan sätta breakpoints i din Rust-kod.*
### Bygga för Release 📦
För att skapa färdiga körbara filer (binärer) utan debug-info:
1. Öppna **Command Palette** (Ctrl+Shift+P).
2. Skriv och välj **"Tasks: Run Task"**.
3. Välj en av följande:
* **Build Release (Linux)**: Skapar en optimerad build för Linux.
* *Resultat:* `src-tauri/target/release/bundle/deb/` (eller AppImage)
* **Build Release (Windows)**: Skapar en `.exe` för Windows.
* *Resultat:* `src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/` (eller nsis)
---
## 📂 Projektstruktur
Så här hittar du i koden:
* **`src-tauri/`**: Backend-koden (Rust) och Tauri-konfigurationen.
* `Cargo.toml`: Beroenden för Rust.
* `tauri.conf.json`: Inställningar för fönster, ikoner, behörigheter och bundles.
* `build.rs`: Byggscript.
* **`src/`**: Källkoden för backend.
* `main.rs`: Entry point.
* `controllers/`: Logik för applikationens tillstånd och kommandon.
* `viewers/`: Hantering av fönster och System Tray.
* `utilities/`: Hjälpfunktioner (loggning, config).
* **`dist/`**: (Frontend) Om du har en frontend (HTML/JS/CSS) ligger de kompilerade filerna här som Tauri laddar.
* **`.vscode/`**: Inställningar för debugging och tasks i VS Code.
---
## 🛠 Felsökning
### Error 71 (Protocol Error) på Linux (Wayland)
Om appen kraschar eller inte startar på Wayland:
Debuggern är konfigurerad att automatiskt sätta `WEBKIT_DISABLE_COMPOSITING_MODE=1`.
Om du kör manuellt från terminalen:
```bash ```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh WEBKIT_DISABLE_COMPOSITING_MODE=1 cargo tauri dev
# Följ instruktionerna på skärmen (standardinstallation är oftast bäst)
source $HOME/.cargo/env
``` ```
**Felsökning: "cannot install while Rust is installed"** ### Debuggern startar inte
Om du får detta felmeddelande har du redan Rust installerat via systemets pakethanterare (vilket sällan stöder cross-compilation smidigt). * Kontrollera att du installerat **CodeLLDB** tillägget.
* Om du får fel vid länkning, kontrollera att du har alla system-beroenden installerade (se "Förutsättningar").
*Lösning:* Avinstallera system-versionen och kör scriptet igen. ---
* **Arch Linux:** `sudo pacman -Rs rust` (Kolla även om du har `cargo` installerat separat) ## 🧠 Teknisk Stack
* **Ubuntu/Debian:** `sudo apt remove rustc cargo`
**Verifiera installationen:** * **Core**: Rust
```bash * **Framework**: Tauri v2
rustc --version * **Input Monitoring**: `enigo` (tangentbords-simulering), `global-hotkey` (genvägar)
cargo --version * **Clipboard**: `arboard`
``` * **AI**: `ollama-rs` (lokal) & `reqwest` (API)
### Linux-beroenden (Ubuntu/Debian)
För att kompilera Tauri på Linux krävs följande bibliotek:
```bash
sudo apt update
sudo apt install libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libssl-dev \
libgtk-3-dev \
libayatana-appindicator3-dev \
librsvg2-dev
```
### Linux-beroenden (Arch Linux / Manjaro)
```bash
sudo pacman -Syu
sudo pacman -S webkit2gtk-4.1 \
base-devel \
curl \
wget \
file \
openssl \
gtk3 \
libayatana-appindicator \
librsvg
```
*Obs: För Wayland-stöd hanterar GTK3/4 detta oftast automatiskt, men säkerställ att du kör en modern distribution.*
## Utveckling
### Installera Tauri CLI
```bash
cargo install tauri-cli --version "^2.0.0"
```
### Kör i utvecklingsläge
Gå in i `src-tauri` mappen eller kör från roten om konfigurerat korrekt, men standard är:
```bash
cd src-tauri
cargo tauri dev
```
Detta kommer starta applikationen. Eftersom vi inte har en frontend (HTML/JS) ännu, kommer fönstret vara tomt eller vitt, men System Tray-ikonen ska synas.
## Debugging med VS Code (CodeLLDB)
För att debugga Rust-koden effektivt i VS Code, skapa filen `.vscode/launch.json` i roten av projektet med följande innehåll. Detta binder CodeLLDB till Tauri-processen.
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Tauri App",
"type": "lldb",
"request": "launch",
"program": "${workspaceFolder}/src-tauri/target/debug/ai-translater-client",
"args": [],
"cwd": "${workspaceFolder}/src-tauri",
"preLaunchTask": "build",
"sourceLanguages": ["rust"]
}
]
}
```
## Cross-Compilation: Windows 11 från Linux
Att bygga Windows `.exe` från Linux är fullt möjligt med `cargo-xwin`.
1. **Installera cross-kompileringsverktyg:**
**Ubuntu/Debian:**
```bash
sudo apt install mingw-w64
```
**Arch Linux:**
```bash
sudo pacman -S mingw-w64 clang lld
# Välj "alla" (tryck Enter) om du tillfrågas om medlemmar i gruppen
```
**Alla:**
```bash
cargo install cargo-xwin
```
2. **Lägg till Windows target:**
```bash
rustup target add x86_64-pc-windows-msvc
```
3. **Bygg för Windows:**
Stå i `src-tauri` mappen och kör:
```bash
cargo tauri build --target x86_64-pc-windows-msvc --runner cargo-xwin
```
Resultatet (exe & msi) hamnar i `src-tauri/target/x86_64-pc-windows-msvc/release/bundle/`.
## Windows-testning på Linux (Wine/Proton)
För att snabbt verifiera att Windows-bygget startar utan att byta OS:
1. **Installera Wine:**
```bash
sudo apt install wine64
```
2. **Kör applikationen:**
Navigera till output-mappen från steget ovan och kör:
```bash
wine "ai-translater-client.exe"
```
*Notera: System Tray kan bete sig annorlunda i Wine än i äkta Windows.*
## Packaging & Distribution
Tauri hanterar paketering automatiskt baserat på ditt OS.
### Linux (.deb & .AppImage)
```bash
cargo tauri build
```
Filerna genereras i `src-tauri/target/release/bundle/deb/` och `appimage/`.
### Windows (.msi & .exe)
När du bygger via `cargo-xwin` (se ovan) eller på en Windows-maskin, genereras en `.msi` via WiX Toolset (om installerat) eller en `.exe` setup-fil via NSIS (standard i v2).
## Projektstruktur
* `src-tauri/Cargo.toml`: Alla beroenden (tauri, enigo, ollama-rs, etc).
* `src-tauri/src/main.rs`: Entry point. Innehåller logik för System Tray.
* `src-tauri/tauri.conf.json`: Konfiguration för fönster och byggprocess.

15
src-tauri/.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Tauri App",
"type": "lldb",
"request": "launch",
"program": "${workspaceFolder}/src-tauri/target/debug/ai-translater-client",
"args": [],
"cwd": "${workspaceFolder}/src-tauri",
"preLaunchTask": "build",
"sourceLanguages": ["rust"]
}
]
}

13
src-tauri/Cargo.lock generated
View File

@@ -22,8 +22,10 @@ name = "ai-translater-client"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"arboard", "arboard",
"chrono",
"enigo", "enigo",
"env_logger", "env_logger",
"fern",
"global-hotkey", "global-hotkey",
"log", "log",
"ollama-rs", "ollama-rs",
@@ -417,8 +419,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118"
dependencies = [ dependencies = [
"iana-time-zone", "iana-time-zone",
"js-sys",
"num-traits", "num-traits",
"serde", "serde",
"wasm-bindgen",
"windows-link 0.2.1", "windows-link 0.2.1",
] ]
@@ -913,6 +917,15 @@ dependencies = [
"simd-adler32", "simd-adler32",
] ]
[[package]]
name = "fern"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9f0c14694cbd524c8720dd69b0e3179344f04ebb5f90f2e4a440c6ea3b2f1ee"
dependencies = [
"log",
]
[[package]] [[package]]
name = "field-offset" name = "field-offset"
version = "0.3.6" version = "0.3.6"

View File

@@ -30,3 +30,5 @@ global-hotkey = "0.6" # Systemomfattande genvägar
# Logging (Strongly recommended for debugging) # Logging (Strongly recommended for debugging)
log = "0.4" log = "0.4"
env_logger = "0.11" env_logger = "0.11"
fern = "0.6"
chrono = { version = "0.4", features = ["serde"] }

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

BIN
src-tauri/icons/64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
</resources>

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -0,0 +1,19 @@
use std::sync::Mutex;
use tauri::{App, Manager, Runtime};
pub struct AppState {
#[allow(dead_code)]
pub ollama_ready: Mutex<bool>,
}
impl AppState {
pub fn new() -> Self {
Self {
ollama_ready: Mutex::new(false),
}
}
}
pub fn init_state<R: Runtime>(app: &mut App<R>) {
app.manage(AppState::new());
}

View File

@@ -0,0 +1,6 @@
use tauri::command;
#[command]
pub fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}

View File

@@ -0,0 +1,3 @@
pub mod app_state;
pub mod settings;
pub mod greet;

View File

@@ -0,0 +1,16 @@
use tauri::command;
use crate::utilities::config::{AppConfig, load_config, save_config};
#[command]
pub fn get_settings() -> Result<AppConfig, String> {
load_config().map_err(|e| e.to_string())
}
#[command]
pub fn save_settings(config: AppConfig) -> Result<(), String> {
save_config(&config).map_err(|e| e.to_string())?;
// Note: Re-initializing logging at runtime is complex with fern alone as it sets a global logger.
// Ideally we would have a reloadable logger or just ask user to restart.
// For now we just save.
Ok(())
}

View File

@@ -1,81 +1,60 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!! // Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri::{ mod utilities;
menu::{Menu, MenuItem}, mod controllers;
tray::{MouseButton, TrayIconBuilder, TrayIconEvent}, mod viewers;
Manager,
};
use std::sync::Mutex;
// Placeholder for application state use log::info;
struct AppState { use utilities::config::load_config;
// Exempel: Spara status för ollama connection här use utilities::logging::setup_logging;
ollama_ready: Mutex<bool>, use controllers::app_state::init_state;
} use controllers::settings::{get_settings, save_settings};
use controllers::greet::greet;
use viewers::tray::setup_tray;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
// Initiera loggning // 1. Load configuration
env_logger::init(); let config = match load_config() {
Ok(c) => c,
Err(e) => {
eprintln!("Failed to load config: {}", e);
// Default config fallback logic is inside load_config, but if file IO fails we might get here.
// We can try to proceed with default logging if possible, but for now just print to stderr.
return;
}
};
// 2. Init logging
if let Err(e) = setup_logging(&config) {
eprintln!("Failed to setup logging: {}", e);
}
info!("Application started");
tauri::Builder::default() tauri::Builder::default()
.invoke_handler(tauri::generate_handler![get_settings, save_settings, greet])
.setup(|app| { .setup(|app| {
// Setup Application State info!("Setting up application...");
app.manage(AppState {
ollama_ready: Mutex::new(false),
});
// --- System Tray Setup --- // 3. Init State
init_state(app);
// Skapa menyalternativ // 4. Setup Tray
let quit_i = MenuItem::with_id(app, "quit", "Avsluta", true, None::<&str>)?; setup_tray(app)?;
let settings_i = MenuItem::with_id(app, "settings", "Inställningar", true, None::<&str>)?;
// Skapa menyn
let menu = Menu::with_items(app, &[&settings_i, &quit_i])?;
// Bygg Tray-ikonen
let _tray = TrayIconBuilder::new()
.icon(app.default_window_icon().unwrap().clone())
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(|app, event| {
match event.id.as_ref() {
"quit" => {
println!("Avslutar applikationen...");
app.exit(0);
}
"settings" => {
println!("Öppnar inställningar (Placeholder)...");
// Här kan du öppna ditt inställningsfönster:
// if let Some(window) = app.get_webview_window("main") {
// window.show().unwrap();
// window.set_focus().unwrap();
// }
}
_ => {}
}
})
.on_tray_icon_event(|tray, event| {
match event {
TrayIconEvent::Click {
button: MouseButton::Left,
..
} => {
let app = tray.app_handle();
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.set_focus();
}
}
_ => {}
}
})
.build(app)?;
Ok(()) Ok(())
}) })
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
// Prevent the window from closing (destroying)
// Instead, hide it. This keeps the app running in the tray.
window.hide().unwrap();
api.prevent_close();
}
})
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }

View File

@@ -0,0 +1,75 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub struct LogConfig {
pub path: String,
pub level: String,
pub enabled: bool,
}
impl Default for LogConfig {
fn default() -> Self {
Self {
path: "loggs".to_string(),
level: "debug".to_string(),
enabled: true,
}
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct GeneralConfig {
pub theme: String,
}
impl Default for GeneralConfig {
fn default() -> Self {
Self {
theme: "dark".to_string(),
}
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct AppConfig {
#[serde(default)]
pub logging: LogConfig,
#[serde(default)]
pub general: GeneralConfig,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
logging: LogConfig::default(),
general: GeneralConfig::default(),
}
}
}
pub fn load_config() -> Result<AppConfig, Box<dyn std::error::Error>> {
let exe_path = std::env::current_exe()?;
let exe_dir = exe_path.parent().ok_or("Could not find exe directory")?;
let config_path = exe_dir.join("config.json");
if config_path.exists() {
let content = std::fs::read_to_string(&config_path)?;
Ok(serde_json::from_str(&content).unwrap_or_else(|_| AppConfig::default()))
} else {
let config = AppConfig::default();
if let Ok(content) = serde_json::to_string_pretty(&config) {
let _ = std::fs::write(&config_path, content);
}
Ok(config)
}
}
pub fn save_config(config: &AppConfig) -> Result<(), Box<dyn std::error::Error>> {
let exe_path = std::env::current_exe()?;
let exe_dir = exe_path.parent().ok_or("Could not find exe directory")?;
let config_path = exe_dir.join("config.json");
let content = serde_json::to_string_pretty(config)?;
std::fs::write(config_path, content)?;
Ok(())
}

View File

@@ -0,0 +1,45 @@
use log::LevelFilter;
use std::str::FromStr;
use super::config::AppConfig;
pub fn setup_logging(config: &AppConfig) -> Result<(), Box<dyn std::error::Error>> {
if !config.logging.enabled {
return Ok(());
}
let exe_path = std::env::current_exe()?;
let exe_dir = exe_path.parent().ok_or("Could not find exe directory")?;
let log_path_config = std::path::Path::new(&config.logging.path);
let log_dir = if log_path_config.is_absolute() {
log_path_config.to_path_buf()
} else {
exe_dir.join(log_path_config)
};
if !log_dir.exists() {
std::fs::create_dir_all(&log_dir)?;
}
let file_name = chrono::Local::now().format("%Y-%m-%d.log").to_string();
let log_path = log_dir.join(file_name);
let level_filter = LevelFilter::from_str(&config.logging.level).unwrap_or(LevelFilter::Debug);
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"[{}][{}][{}] {}",
chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
record.level(),
record.target(),
message
))
})
.level(level_filter)
.chain(std::io::stdout())
.chain(fern::log_file(log_path)?)
.apply()?;
Ok(())
}

View File

@@ -0,0 +1,2 @@
pub mod config;
pub mod logging;

View File

@@ -0,0 +1 @@
pub mod tray;

View File

@@ -0,0 +1,96 @@
use tauri::{
menu::{Menu, MenuItem},
tray::{MouseButton, TrayIconBuilder, TrayIconEvent},
App, Manager, Runtime, WebviewWindowBuilder, WebviewUrl,
};
use log::{info, error};
fn toggle_settings_window<R: Runtime>(app: &tauri::AppHandle<R>) {
match app.get_webview_window("settings") {
Some(window) => {
info!("Settings window found");
if let Ok(true) = window.is_visible() {
info!("Window is visible, hiding...");
let _ = window.hide();
} else {
info!("Window is hidden, showing...");
// On checking docs/issues: Some Wayland compositors dislike set_focus or show on hidden windows
// Creating the window 'visible' from start is safer.
let _ = window.show();
// window.set_focus(); - Removed to prevent Wayland protocol error 71
}
}
None => {
info!("Creating new settings window...");
let build_result = WebviewWindowBuilder::new(
app,
"settings",
WebviewUrl::App("index.html".into())
)
.title("AI Typist Inställningar")
.inner_size(800.0, 600.0)
.visible(false) // Create hidden first to avoid Wayland focus issues on creation
.build();
match build_result {
Ok(window) => {
info!("Settings window created successfully");
// Now show it explicitly
if let Err(e) = window.show() {
error!("Failed to show window: {}", e);
}
},
Err(e) => error!("Failed to create settings window: {}", e),
}
}
}
}
pub fn setup_tray<R: Runtime>(app: &mut App<R>) -> Result<(), Box<dyn std::error::Error>> {
// Settings window is now created via tauri.conf.json to ensure correct init context on Wayland
// Skapa menyalternativ
let quit_i = MenuItem::with_id(app, "quit", "Avsluta", true, None::<&str>)?;
let settings_i = MenuItem::with_id(app, "settings", "Inställningar", true, None::<&str>)?;
// Skapa menyn
let menu = Menu::with_items(app, &[&settings_i, &quit_i])?;
info!("Tray menu created");
// Bygg Tray-ikonen
let _tray = TrayIconBuilder::new()
.icon(app.default_window_icon().unwrap().clone())
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(|app, event| {
match event.id.as_ref() {
"quit" => {
info!("User clicked quit from tray");
println!("Avslutar applikationen...");
app.exit(0);
}
"settings" => {
info!("User clicked settings from tray");
toggle_settings_window(app);
}
_ => {}
}
})
.on_tray_icon_event(|tray, event| {
match event {
TrayIconEvent::Click {
button: MouseButton::Left,
..
} => {
let app = tray.app_handle();
toggle_settings_window(app);
}
_ => {}
}
})
.build(app)?;
info!("Tray system initialized successfully");
Ok(())
}

View File

@@ -8,12 +8,15 @@
"frontendDist": "../dist" "frontendDist": "../dist"
}, },
"app": { "app": {
"withGlobalTauri": true,
"windows": [ "windows": [
{ {
"label": "settings",
"title": "AI Typist Inställningar", "title": "AI Typist Inställningar",
"url": "index.html",
"width": 800, "width": 800,
"height": 600, "height": 600,
"visible": false "visible": true
} }
], ],
"security": { "security": {