Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(ui): implement listening to outside app activity #30

10 changes: 0 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^5.2.1",
"react-idle-timer": "^5.7.2",
"zustand": "^4.5.4"
},
"devDependencies": {
Expand Down
38 changes: 38 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ libsqlite3-sys = { version = "0.25.1", features = ["bundled"] }

log = "0.4.22"
rand = "0.8.5"
device_query = "2.1.0"

[features]
# This feature is used for production builds or when a dev server is not specified, DO NOT REMOVE!!
Expand Down
17 changes: 16 additions & 1 deletion src-tauri/src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const LOG_TARGET: &str = "tari::universe::app_config";
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AppConfigFromFile {
pub mode: String,
pub auto_mining: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
Expand Down Expand Up @@ -38,14 +39,15 @@ impl MiningMode {
pub struct AppConfig {
config_file: Option<PathBuf>,
pub mode: MiningMode,
// auto-mining in future etc.
pub auto_mining: bool,
}

impl AppConfig {
pub fn new() -> Self {
Self {
config_file: None,
mode: MiningMode::Eco,
auto_mining: false,
}
}

Expand All @@ -59,6 +61,7 @@ impl AppConfig {
match serde_json::from_str::<AppConfigFromFile>(&config) {
Ok(config) => {
self.mode = MiningMode::from_str(&config.mode).unwrap_or(MiningMode::Eco);
self.auto_mining = config.auto_mining;
}
Err(e) => {
warn!(target: LOG_TARGET, "Failed to parse app config: {}", e.to_string());
Expand All @@ -68,6 +71,7 @@ impl AppConfig {
info!(target: LOG_TARGET, "App config does not exist or is corrupt. Creating new one");
let config = &AppConfigFromFile {
mode: MiningMode::to_str(self.mode.clone()),
auto_mining: self.auto_mining.clone(),
};
let config = serde_json::to_string(&config)?;
fs::write(file, config).await?;
Expand All @@ -89,10 +93,21 @@ impl AppConfig {
self.mode.clone()
}

pub async fn set_auto_mining(&mut self, auto_mining: bool) -> Result<(), anyhow::Error> {
self.auto_mining = auto_mining;
self.update_config_file().await?;
Ok(())
}

pub fn get_auto_mining(&self) -> bool {
self.auto_mining.clone()
}

pub async fn update_config_file(&mut self) -> Result<(), anyhow::Error> {
let file = self.config_file.clone().unwrap();
let config = &AppConfigFromFile {
mode: MiningMode::to_str(self.mode.clone()),
auto_mining: self.auto_mining,
};
let config = serde_json::to_string(config)?;
info!(target: LOG_TARGET, "Updating config file: {:?} {:?}", file, self.clone());
Expand Down
66 changes: 60 additions & 6 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
mod cpu_miner;
mod mm_proxy_manager;
mod process_watcher;
mod user_listener;
mod xmrig;
mod xmrig_adapter;

Expand All @@ -25,6 +26,7 @@ use crate::cpu_miner::CpuMiner;
use crate::internal_wallet::InternalWallet;
use crate::mm_proxy_manager::MmProxyManager;
use crate::node_manager::NodeManager;
use crate::user_listener::UserListener;
use crate::wallet_adapter::WalletBalance;
use crate::wallet_manager::WalletManager;
use app_config::{AppConfig, MiningMode};
Expand All @@ -37,14 +39,12 @@ use std::{panic, process};
use tari_common_types::tari_address::TariAddress;
use tari_core::transactions::tari_amount::MicroMinotari;
use tari_shutdown::Shutdown;
use tauri::{RunEvent, UpdaterEvent};
use tauri::{Manager, RunEvent, UpdaterEvent};
use tokio::sync::RwLock;
use tokio::try_join;

use crate::xmrig_adapter::XmrigAdapter;
use dirs_next::cache_dir;
use std::thread;
use std::time::Duration;

#[derive(Debug, Serialize, Deserialize, Clone)]
struct SetupStatusEvent {
Expand Down Expand Up @@ -122,6 +122,29 @@ async fn setup_application<'r>(
Ok(())
}

#[tauri::command]
async fn set_auto_mining<'r>(
auto_mining: bool,
window: tauri::Window,
state: tauri::State<'r, UniverseAppState>,
) -> Result<(), String> {
let _ = state
.config
.write()
.await
.set_auto_mining(auto_mining)
.await;
let mut user_listener = state.user_listener.write().await;

if auto_mining {
user_listener.start_listening_to_mouse_poisition_change(window);
} else {
user_listener.stop_listening_to_mouse_poisition_change();
}

Ok(())
}

#[tauri::command]
async fn start_mining<'r>(
window: tauri::Window,
Expand Down Expand Up @@ -233,6 +256,7 @@ async fn status(state: tauri::State<'_, UniverseAppState>) -> Result<AppStatus,
},
wallet_balance,
mode: config_guard.mode.clone(),
auto_mining: config_guard.auto_mining.clone(),
})
}

Expand All @@ -243,6 +267,7 @@ pub struct AppStatus {
base_node: BaseNodeStatus,
wallet_balance: WalletBalance,
mode: MiningMode,
auto_mining: bool,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -282,6 +307,7 @@ struct UniverseAppState {
shutdown: Shutdown,
cpu_miner: RwLock<CpuMiner>,
cpu_miner_config: Arc<RwLock<CpuMinerConfig>>,
user_listener: Arc<RwLock<UserListener>>,
mm_proxy_manager: Arc<RwLock<MmProxyManager>>,
node_manager: NodeManager,
wallet_manager: WalletManager,
Expand Down Expand Up @@ -312,11 +338,14 @@ fn main() {
shutdown: shutdown.clone(),
cpu_miner: CpuMiner::new().into(),
cpu_miner_config: cpu_config.clone(),
user_listener: Arc::new(RwLock::new(UserListener::new())),
mm_proxy_manager: mm_proxy_manager.clone(),
node_manager,
wallet_manager,
};

let user_listener = app_state.user_listener.clone();

let app = tauri::Builder::default()
.manage(app_state)
.setup(|app| {
Expand All @@ -330,17 +359,41 @@ fn main() {
)
.expect("Could not set up logging");

let app_config_clone = app_config.clone();

let config_path = app.path_resolver().app_config_dir().unwrap();
let thread_config = tauri::async_runtime::spawn(async move {
app_config.write().await.load_or_create(config_path).await
});

match tauri::async_runtime::block_on(thread_config).unwrap() {
Ok(_) => {}
Err(e) => {
error!(target: LOG_TARGET, "Error setting up app state: {:?}", e);
}
};

// let auto_mining = app_config.read().auto_mining;
// let user_listener = app_state.user_listener.write();

// let user_listener = app_state.user_listener.clone();
let app_window = app.get_window("main").unwrap().clone();
let auto_miner_thread = tauri::async_runtime::spawn(async move {
let auto_mining = app_config_clone.read().await.auto_mining;
let mut user_listener = user_listener.write().await;

if auto_mining {
user_listener.start_listening_to_mouse_poisition_change(app_window);
}
});

match tauri::async_runtime::block_on(auto_miner_thread) {
Ok(_) => {}
Err(e) => {
error!(target: LOG_TARGET, "Error setting up auto mining: {:?}", e);
}
}

let config_path = app.path_resolver().app_config_dir().unwrap();
let thread = tauri::async_runtime::spawn(async move {
match InternalWallet::load_or_create(config_path).await {
Expand All @@ -360,7 +413,7 @@ fn main() {

return Err(e);
}
};
}
Ok(())
});
match tauri::async_runtime::block_on(thread).unwrap() {
Expand All @@ -376,7 +429,8 @@ fn main() {
status,
start_mining,
stop_mining,
set_mode
set_auto_mining,
set_mode,
])
.build(tauri::generate_context!())
.expect("error while running tauri application");
Expand Down Expand Up @@ -406,7 +460,7 @@ fn main() {
info!(target: LOG_TARGET, "App shutdown caught");
shutdown.trigger();
// TODO: Find a better way of knowing that all miners have stopped
sleep(std::time::Duration::from_secs(3));
sleep(std::time::Duration::from_secs(5));
info!(target: LOG_TARGET, "App shutdown complete");
}
RunEvent::MainEventsCleared => {
Expand Down
Loading