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

feat(ui): progress screen on the application setup #19

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@ rand = "0.8.5"
custom-protocol = ["tauri/custom-protocol"]

[package.metadata.cargo-machete]
ignored = ["log4rs", "xz2"]
ignored = ["log4rs", "xz2", "libsqlite3-sys", "minotari_wallet_grpc_client"]
6 changes: 1 addition & 5 deletions src-tauri/src/cpu_miner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,7 @@ impl CpuMiner {
// Refresh CPUs again.
s.refresh_cpu_all();

let mut cpu_brand = "Unknown";
for cpu in s.cpus() {
cpu_brand = cpu.brand();
break;
}
let cpu_brand = s.cpus().get(0).map(|cpu| cpu.brand()).unwrap_or("Unknown");

let cpu_usage = s.global_cpu_usage() as u32;

Expand Down
42 changes: 35 additions & 7 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,25 +25,43 @@ use crate::mm_proxy_manager::MmProxyManager;
use crate::node_manager::NodeManager;
use crate::wallet_adapter::WalletBalance;
use crate::wallet_manager::WalletManager;
use dirs_next::data_dir;
use futures_util::{FutureExt, TryFutureExt};
use futures_util::TryFutureExt;
use log::{debug, error, info, warn};
use serde::Serialize;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::thread::sleep;
use std::{panic, process};
use tari_common_types::tari_address::TariAddress;
use tari_core::transactions::tari_amount::MicroMinotari;
use tari_shutdown::Shutdown;
use tauri::{api, RunEvent, UpdaterEvent};
use tauri::{RunEvent, UpdaterEvent};
use tokio::sync::RwLock;
use tokio::{join, try_join};
use tokio::try_join;

use std::thread;
use std::time::Duration;

#[derive(Debug, Serialize, Deserialize, Clone)]
struct SetupStatusEvent {
event_type: String,
title: String,
progress: f64,
}

#[tauri::command]
async fn init<'r>(
async fn setup_application<'r>(
window: tauri::Window,
state: tauri::State<'r, UniverseAppState>,
app: tauri::AppHandle,
) -> Result<(), String> {
let _ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "Downloading Applications".to_string(),
progress: 0.5,
},
);
let data_dir = app.path_resolver().app_local_data_dir().unwrap();
let task1 = state
.node_manager
Expand All @@ -62,6 +80,16 @@ async fn init<'r>(
});

try_join!(task1, task2)?;
_ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "Syncing Blockchain".to_string(),
progress: 1.0,
},
);
// TODO: Sync blockchain when p2p mining finished
thread::sleep(Duration::from_secs(5));
Ok(())
}

Expand Down Expand Up @@ -293,7 +321,7 @@ fn main() {
}
})
.invoke_handler(tauri::generate_handler![
init,
setup_application,
status,
start_mining,
stop_mining
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/minotari_node_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ impl MinotariNodeStatusMonitor {
})
.await?;
let mut res = res.into_inner();
while let Some(difficulty) = res.message().await? {
if let Some(difficulty) = res.message().await? {
return Ok((
difficulty.sha3x_estimated_hash_rate,
difficulty.randomx_estimated_hash_rate,
Expand Down
103 changes: 56 additions & 47 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,57 +14,66 @@ import useAppStateStore from './store/appStateStore';
import ErrorSnackbar from './containers/Error/ErrorSnackbar';

function App() {
const {
view, background, setHashRate, setCpuUsage, setAppState, setError,
setCpuBrand, setEstimatedEarnings,
setBlockHeight, setBlockTime, setIsSynced, setWallet
} =
useAppStateStore((state) => ({
view: state.view,
background: state.background,
setHashRate: state.setHashRate,
setCpuUsage: state.setCpuUsage,
setAppState: state.setAppState,
setError: state.setError,
setCpuBrand: state.setCpuBrand,
setEstimatedEarnings: state.setEstimatedEarnings,
setBlockHeight: state.setBlockHeight,
setBlockTime: state.setBlockTime,
setIsSynced: state.setIsSynced,
setWallet: state.setWallet
}));
const { view, background, setHashRate, setCpuUsage, setAppState, setError,
setCpuBrand, setEstimatedEarnings, setBlockHeight, setBlockTime, setIsSynced,
settingUpFinished, setSetupDetails, setWallet
} =
useAppStateStore((state) => ({
view: state.view,
background: state.background,
isSettingUp: state.isSettingUp,
setHashRate: state.setHashRate,
setCpuUsage: state.setCpuUsage,
setAppState: state.setAppState,
setError: state.setError,
setCpuBrand: state.setCpuBrand,
setEstimatedEarnings: state.setEstimatedEarnings,
settingUpFinished: state.settingUpFinished,
setSetupDetails: state.setSetupDetails,
setBlockHeight: state.setBlockHeight,
setBlockTime: state.setBlockTime,
setIsSynced: state.setIsSynced,
setWallet: state.setWallet,
}));

useEffect(() => {
invoke("init", {}).catch((e) => {
console.error('Could not init', e);
setError(e.toString());
});
const unlistenPromise = listen('message', (event) => {
console.log('some kind of event', event.event, event.payload);
});
useEffect(() => {
const unlistenPromise = listen('message', ({ event, payload }: TauriEvent) => {
console.log('some kind of event', event, payload);

switch (payload.event_type) {
case "setup_status":
setSetupDetails(payload.title, payload.progress);
break;
default:
console.log("Unknown tauri event: ", { event, payload });
break;
}
});

const intervalId = setInterval(() => {
invoke('status', {})
.then((status: any) => {
console.log('Status', status);
setAppState(status);
setCpuUsage(status.cpu?.cpu_usage);
setHashRate(status.cpu?.hash_rate);
setCpuBrand(status.cpu?.cpu_brand);
setEstimatedEarnings(status.cpu?.estimated_earnings);
setBlockHeight(status.base_node?.block_height);
setBlockTime(status.base_node?.block_time);
setIsSynced(status.base_node?.is_synced);
setWallet({balance: status.wallet_balance?.available_balance + status.wallet_balance?.timelocked_balance + status.wallet_balance?.pending_incoming_balance});
})
.catch((e) => {
console.error('Could not get status', e);
setError(e.toString());
});
invoke('setup_application').then(() => settingUpFinished());

const intervalId = setInterval(() => {
invoke('status', {})
.then((status: any) => {
console.log('Status', status);
setAppState(status);
setCpuUsage(status.cpu?.cpu_usage);
setHashRate(status.cpu?.hash_rate);
setCpuBrand(status.cpu?.cpu_brand);
setEstimatedEarnings(status.cpu?.estimated_earnings);
setBlockHeight(status.base_node?.block_height);
setBlockTime(status.base_node?.block_time);
setIsSynced(status.base_node?.is_synced);
setWallet({balance: status.wallet_balance?.available_balance + status.wallet_balance?.timelocked_balance + status.wallet_balance?.pending_incoming_balance});
})
.catch((e) => {
console.error('Could not get status', e);
setError(e.toString());
});
}, 1000);
return () => {
unlistenPromise.then((unlisten) => unlisten());
clearInterval(intervalId);
unlistenPromise.then((unlisten) => unlisten());
clearInterval(intervalId);
};
}, []);

Expand Down
4 changes: 2 additions & 2 deletions src/containers/Dashboard/Dashboard.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { DashboardContainer } from './styles';
import MiningView from './MiningView/MiningView';
import SetupView from './SetupView/SetupView';
import TribesView from './TribesView/TribesView';
import { viewType } from '../../store/types';
import SetupViewContainer from './SetupView/SetupViewContainer';

function Dashboard({ status }: { status: viewType }) {
let view = <MiningView />;

switch (status) {
case 'setup':
view = <SetupView />;
view = <SetupViewContainer />;
break;
case 'tribes':
view = <TribesView />;
Expand Down
9 changes: 4 additions & 5 deletions src/containers/Dashboard/SetupView/SetupView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,23 @@ import { Stack, Typography } from '@mui/material';
import { StyledLinearProgress, ProgressBox } from '../styles';
import VisualMode from '../components/VisualMode';

function SetupView() {
const progress = 30;
function SetupView({ title, progressPercentage }: { title: string, progressPercentage: number }) {
return (
<Stack spacing={8} alignItems="center">
<img src={setup} alt="Setup" />
<Stack spacing={2} alignItems="center">
<Typography variant="h4">
Setting up the Tari truth machine...
Setting up the Tari truth machine...
</Typography>
<Typography variant="body1" align="center">
This might take a few minutes.
<br />
Don’t worry you’ll only need to do this once.
</Typography>
<ProgressBox>
<StyledLinearProgress variant="determinate" value={progress} />
<StyledLinearProgress variant="determinate" value={progressPercentage} />
</ProgressBox>
<Typography variant="body1">{progress}%</Typography>
<Typography variant="body1">{`${progressPercentage}% - ${title}`}</Typography>
</Stack>
<VisualMode />
</Stack>
Expand Down
32 changes: 32 additions & 0 deletions src/containers/Dashboard/SetupView/SetupViewContainer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useEffect, useMemo } from "react";
import useAppStateStore from "../../../store/appStateStore";
import SetupView from "./SetupView";

let latestSetupProgress = 0;

function SetupViewContainer() {
const { setupTitle, setupProgress } = useAppStateStore((state) => ({
setupTitle: state.setupTitle,
setupProgress: state.setupProgress,
}));
const progressPercentage = useMemo(
() => Math.floor(latestSetupProgress * 100),
[latestSetupProgress]
);

useEffect(() => {
const progressInterval = setInterval(() => {
latestSetupProgress += (setupProgress - latestSetupProgress) * 0.25;
}, 500);

return () => {
clearInterval(progressInterval);
};
}, [setupProgress]);

return (
<SetupView title={setupTitle} progressPercentage={progressPercentage} />
);
}

export default SetupViewContainer;
Loading