feat(game): game uninstalling & partial compat

This commit is contained in:
DecDuck
2024-12-26 11:59:26 +11:00
parent 9ea2aa4997
commit dd7f5675d8
26 changed files with 469 additions and 96 deletions

View File

@ -1,39 +1,65 @@
<template>
<button
type="button"
@click="() => buttonActions[props.status.type]()"
:class="[
<div class="inline-flex">
<button type="button" @click="() => buttonActions[props.status.type]()" :class="[
styles[props.status.type],
'inline-flex uppercase font-display items-center gap-x-2 rounded-md px-4 py-3 text-md font-semibold shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
]"
>
<component
:is="buttonIcons[props.status.type]"
class="-mr-0.5 size-5"
aria-hidden="true"
/>
{{ buttonNames[props.status.type] }}
</button>
showDropdown ? 'rounded-l-md' : 'rounded-md',
'inline-flex uppercase font-display items-center gap-x-2 px-4 py-3 text-md font-semibold shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
]">
<component :is="buttonIcons[props.status.type]" class="-mr-0.5 size-5" aria-hidden="true" />
{{ buttonNames[props.status.type] }}
</button>
<Menu v-if="showDropdown" as="div" class="relative inline-block text-left grow">
<div class="h-full">
<MenuButton
class="inline-flex w-full h-full justify-center items-center rounded-r-md bg-zinc-800 px-1 py-2 text-sm font-semibold text-zinc-100 shadow-sm ring-1 ring-inset ring-zinc-600 hover:bg-zinc-800">
<ChevronDownIcon class="size-5 text-gray-400" aria-hidden="true" />
</MenuButton>
</div>
<transition enter-active-class="transition ease-out duration-100" enter-from-class="transform opacity-0 scale-95"
enter-to-class="transform opacity-100 scale-100" leave-active-class="transition ease-in duration-75"
leave-from-class="transform opacity-100 scale-100" leave-to-class="transform opacity-0 scale-95">
<MenuItems
class="absolute right-0 z-50 mt-2 w-32 origin-top-right rounded-md bg-zinc-900 shadow-lg ring-1 ring-zinc-100/5 focus:outline-none">
<div class="py-1">
<MenuItem v-slot="{ active }">
<button @click="() => emit('uninstall')"
:class="[active ? 'bg-zinc-800 text-zinc-100 outline-none' : 'text-zinc-400', 'w-full block px-4 py-2 text-sm inline-flex justify-between']">Uninstall
<TrashIcon class="size-5" />
</button>
</MenuItem>
</div>
</MenuItems>
</transition>
</Menu>
</div>
</template>
<script setup lang="ts">
import {
ArrowDownTrayIcon,
ChevronDownIcon,
PlayIcon,
QueueListIcon,
TrashIcon,
WrenchIcon,
} from "@heroicons/vue/20/solid";
import type { Component } from "vue";
import { GameStatusEnum, type GameStatus } from "~/types.js";
import { Menu, MenuButton, MenuItem, MenuItems } from '@headlessui/vue'
const props = defineProps<{ status: GameStatus }>();
const emit = defineEmits<{
(e: "install"): void;
(e: "play"): void;
(e: "queue"): void;
(e: "uninstall"): void;
}>();
const showDropdown = computed(() => props.status.type === GameStatusEnum.Installed);
const styles: { [key in GameStatusEnum]: string } = {
[GameStatusEnum.Remote]:
"bg-blue-600 text-white hover:bg-blue-500 focus-visible:outline-blue-600",
@ -73,9 +99,9 @@ const buttonActions: { [key in GameStatusEnum]: () => void } = {
[GameStatusEnum.Remote]: () => emit("install"),
[GameStatusEnum.Queued]: () => emit("queue"),
[GameStatusEnum.Downloading]: () => emit("queue"),
[GameStatusEnum.SetupRequired]: () => {},
[GameStatusEnum.SetupRequired]: () => { },
[GameStatusEnum.Installed]: () => emit("play"),
[GameStatusEnum.Updating]: () => emit("queue"),
[GameStatusEnum.Uninstalling]: () => {},
[GameStatusEnum.Uninstalling]: () => { },
};
</script>

View File

@ -1,11 +1,12 @@
import { listen } from "@tauri-apps/api/event";
export type QueueState = {
queue: Array<{ id: string; status: string, progress: number | null }>;
queue: Array<{ id: string; status: string; progress: number | null }>;
status: string;
};
export const useQueueState = () =>
useState<QueueState>("queue", () => ({ queue: [] }));
useState<QueueState>("queue", () => ({ queue: [], status: "Unknown" }));
listen("update_queue", (event) => {
const queue = useQueueState();

View File

@ -18,6 +18,7 @@
"@tauri-apps/api": ">=2.0.0",
"@tauri-apps/plugin-deep-link": "~2",
"@tauri-apps/plugin-dialog": "^2.0.1",
"@tauri-apps/plugin-os": "~2",
"@tauri-apps/plugin-shell": ">=2.0.0",
"markdown-it": "^14.1.0",
"moment": "^2.30.1",

View File

@ -22,6 +22,7 @@
@install="() => installFlow()"
@play="() => play()"
@queue="() => queue()"
@uninstall="() => uninstall()"
:status="status"
/>
<a
@ -409,4 +410,8 @@ async function play() {
async function queue() {
router.push("/queue");
}
async function uninstall() {
await invoke("uninstall_game", {gameId: game.value.id});
}
</script>

View File

@ -9,25 +9,18 @@
<nav class="flex flex-col" aria-label="Sidebar">
<ul role="list" class="-mx-2 space-y-1">
<li v-for="(item, itemIdx) in navigation" :key="item.prefix">
<NuxtLink
:href="item.route"
:class="[
<NuxtLink :href="item.route" :class="[
itemIdx === currentPageIndex
? 'bg-zinc-800/50 text-zinc-100'
: 'text-zinc-400 hover:bg-zinc-800/30 hover:text-zinc-200',
'transition group flex gap-x-3 rounded-md p-2 pr-12 text-sm font-semibold leading-6',
]">
<component :is="item.icon" :class="[
itemIdx === currentPageIndex
? 'bg-zinc-800/50 text-zinc-100'
: 'text-zinc-400 hover:bg-zinc-800/30 hover:text-zinc-200',
'transition group flex gap-x-3 rounded-md p-2 pr-12 text-sm font-semibold leading-6',
]"
>
<component
:is="item.icon"
:class="[
itemIdx === currentPageIndex
? 'text-zinc-100'
: 'text-zinc-400 group-hover:text-zinc-200',
'transition h-6 w-6 shrink-0',
]"
aria-hidden="true"
/>
? 'text-zinc-100'
: 'text-zinc-400 group-hover:text-zinc-200',
'transition h-6 w-6 shrink-0',
]" aria-hidden="true" />
{{ item.label }}
</NuxtLink>
</li>
@ -43,11 +36,13 @@
<script setup lang="ts">
import {
ArrowDownTrayIcon,
CubeIcon,
HomeIcon,
RectangleGroupIcon,
} from "@heroicons/vue/16/solid";
import type { Component } from "vue";
import type { NavigationItem } from "~/types";
import { platform } from '@tauri-apps/plugin-os';
const navigation: Array<NavigationItem & { icon: Component }> = [
{
@ -70,5 +65,12 @@ const navigation: Array<NavigationItem & { icon: Component }> = [
},
];
const currentPlatform = platform();
switch (currentPlatform) {
case "linux":
navigation.splice(2, 0, { label: "Compatibility", route: "/settings/compatibility", prefix: "/settings/compatibility", icon: CubeIcon });
break;
}
const currentPageIndex = useCurrentNavigationIndex(navigation);
</script>

View File

@ -0,0 +1,3 @@
<template>
</template>

49
src-tauri/Cargo.lock generated
View File

@ -984,6 +984,7 @@ dependencies = [
"tauri-build",
"tauri-plugin-deep-link",
"tauri-plugin-dialog",
"tauri-plugin-os",
"tauri-plugin-shell",
"tauri-plugin-single-instance",
"tokio",
@ -1435,6 +1436,16 @@ dependencies = [
"version_check",
]
[[package]]
name = "gethostname"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc3655aa6818d65bc620d6911f05aa7b6aeb596291e1e9f79e52df85583d1e30"
dependencies = [
"rustix",
"windows-targets 0.52.6",
]
[[package]]
name = "getrandom"
version = "0.1.16"
@ -2853,6 +2864,17 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "os_info"
version = "3.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb6651f4be5e39563c4fe5cc8326349eb99a25d805a3493f791d5bfd0269e430"
dependencies = [
"log",
"serde",
"windows-sys 0.52.0",
]
[[package]]
name = "os_pipe"
version = "1.2.1"
@ -4107,6 +4129,15 @@ dependencies = [
"syn 2.0.91",
]
[[package]]
name = "sys-locale"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
dependencies = [
"libc",
]
[[package]]
name = "system-configuration"
version = "0.6.1"
@ -4388,6 +4419,24 @@ dependencies = [
"uuid",
]
[[package]]
name = "tauri-plugin-os"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dda2d571a9baf0664c1f2088db227e3072f9028602fafa885deade7547c3b738"
dependencies = [
"gethostname",
"log",
"os_info",
"serde",
"serde_json",
"serialize-to-javascript",
"sys-locale",
"tauri",
"tauri-plugin",
"thiserror 2.0.9",
]
[[package]]
name = "tauri-plugin-shell"
version = "2.2.0"

View File

@ -41,6 +41,7 @@ http = "1.1.0"
urlencoding = "2.1.3"
md5 = "0.7.0"
chrono = "0.4.38"
tauri-plugin-os = "2"
[dependencies.tauri]
version = "2.1.1"

View File

@ -13,6 +13,7 @@
"core:window:allow-maximize",
"core:window:allow-close",
"deep-link:default",
"dialog:default"
"dialog:default",
"os:default"
]
}

View File

@ -199,8 +199,10 @@ pub fn retry_connect(state: tauri::State<'_, Mutex<AppState>>) -> Result<(), ()>
pub fn setup() -> Result<(AppStatus, Option<User>), ()> {
let data = DB.borrow_data().unwrap();
let auth = data.auth.clone();
drop(data);
if data.auth.is_some() {
if auth.is_some() {
let user_result = fetch_user();
if user_result.is_err() {
let error = user_result.err().unwrap();
@ -215,7 +217,5 @@ pub fn setup() -> Result<(AppStatus, Option<User>), ()> {
return Ok((AppStatus::SignedIn, Some(user_result.unwrap())));
}
drop(data);
Ok((AppStatus::SignedOut, None))
}

View File

@ -10,8 +10,7 @@ pub fn quit(app: tauri::AppHandle) {
cleanup_and_exit(&app);
}
pub fn cleanup_and_exit(app: &AppHandle, ) {
pub fn cleanup_and_exit(app: &AppHandle) {
info!("exiting drop application...");
app.exit(0);

View File

@ -21,6 +21,11 @@ pub struct DatabaseAuth {
pub client_id: String,
}
pub struct GameStatusData {
version_name: String,
install_dir: String,
}
// Strings are version names for a particular game
#[derive(Serialize, Clone, Deserialize)]
#[serde(tag = "type")]

View File

@ -39,17 +39,17 @@ pub struct GameDownloadAgent {
pub stored_manifest: StoredManifest,
}
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum GameDownloadError {
Communication(RemoteAccessError),
Checksum,
Setup(SetupError),
Lock,
IoError(io::Error),
IoError(io::ErrorKind),
DownloadError,
}
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum SetupError {
Context,
}
@ -297,7 +297,6 @@ impl GameDownloadAgent {
}
}
Err(e) => {
error!("GameDownloadError: {}", e);
self.sender.send(DownloadManagerSignal::Error(e)).unwrap();
}
}

View File

@ -186,7 +186,9 @@ pub fn download_game_chunk(
content_length.unwrap().try_into().unwrap(),
);
let completed = pipeline.copy().map_err(GameDownloadError::IoError)?;
let completed = pipeline
.copy()
.map_err(|e| GameDownloadError::IoError(e.kind()))?;
if !completed {
return Ok(false);
};

View File

@ -2,6 +2,7 @@ use std::{
any::Any,
collections::VecDeque,
fmt::Debug,
io,
sync::{
mpsc::{SendError, Sender},
Arc, Mutex, MutexGuard,
@ -41,8 +42,12 @@ pub enum DownloadManagerSignal {
Error(GameDownloadError),
/// Pushes UI update
Update,
/// Uninstall game
/// Takes game ID
Uninstall(String),
}
#[derive(Debug, Clone)]
pub enum DownloadManagerStatus {
Downloading,
Paused,
@ -51,6 +56,15 @@ pub enum DownloadManagerStatus {
Finished,
}
impl Serialize for DownloadManagerStatus {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&format!["{:?}", self])
}
}
#[derive(Serialize, Clone)]
pub enum GameDownloadStatus {
Queued,
@ -191,6 +205,11 @@ impl DownloadManager {
.unwrap();
self.terminator.join()
}
pub fn uninstall_game(&self, game_id: String) {
self.command_sender
.send(DownloadManagerSignal::Uninstall(game_id))
.unwrap();
}
}
/// Takes in the locked value from .edit() and attempts to

View File

@ -1,5 +1,6 @@
use std::{
collections::HashMap,
fs::remove_dir_all,
sync::{
mpsc::{channel, Receiver, Sender},
Arc, Mutex, RwLockWriteGuard,
@ -7,13 +8,17 @@ use std::{
thread::{spawn, JoinHandle},
};
use http::version;
use log::{error, info};
use tauri::{AppHandle, Emitter};
use crate::{
db::{Database, GameStatus, GameTransientStatus},
library::{on_game_complete, GameUpdateEvent, QueueUpdateEvent, QueueUpdateEventQueueData},
state::GameStatusManager,
library::{
on_game_complete, push_game_update, GameUpdateEvent, QueueUpdateEvent,
QueueUpdateEventQueueData,
},
state::{GameStatusManager, GameStatusWithTransient},
DB,
};
@ -120,15 +125,7 @@ impl DownloadManagerBuilder {
let status = GameStatusManager::fetch_state(&id);
self.app_handle
.emit(
&format!("update_game/{}", id),
GameUpdateEvent {
game_id: id,
status,
},
)
.unwrap();
push_game_update(&self.app_handle, id, status);
}
fn push_manager_update(&self) {
@ -142,7 +139,14 @@ impl DownloadManagerBuilder {
})
.collect();
let event_data = QueueUpdateEvent { queue: queue_objs };
let status_handle = self.status.lock().unwrap();
let status = status_handle.clone();
drop(status_handle);
let event_data = QueueUpdateEvent {
queue: queue_objs,
status,
};
self.app_handle.emit("update_queue", event_data).unwrap();
}
@ -159,9 +163,7 @@ impl DownloadManagerBuilder {
drop(download_thread_lock);
}
fn sync_download_agent(&self) {}
fn remove_and_cleanup_game(&mut self, game_id: &String) -> Arc<Mutex<GameDownloadAgent>> {
fn remove_and_cleanup_front_game(&mut self, game_id: &String) -> Arc<Mutex<GameDownloadAgent>> {
self.download_queue.pop_front();
let download_agent = self.download_agent_registry.remove(game_id).unwrap();
self.cleanup_current_download();
@ -214,26 +216,100 @@ impl DownloadManagerBuilder {
return Ok(());
}
DownloadManagerSignal::Remove(game_id) => {
self.manage_remove_game(game_id);
self.manage_remove_game_queue(game_id);
}
DownloadManagerSignal::Uninstall(game_id) => {
self.uninstall_game(game_id);
}
};
}
}
fn manage_remove_game(&mut self, game_id: String) {
fn uninstall_game(&mut self, game_id: String) {
// Removes the game if it's in the queue
self.manage_remove_game_queue(game_id.clone());
let mut db_handle = DB.borrow_data_mut().unwrap();
db_handle
.games
.transient_statuses
.entry(game_id.clone())
.and_modify(|v| *v = GameTransientStatus::Uninstalling {});
push_game_update(
&self.app_handle,
game_id.clone(),
(None, Some(GameTransientStatus::Uninstalling {})),
);
let previous_state = db_handle.games.statuses.get(&game_id).cloned();
if previous_state.is_none() {
info!("uninstall job doesn't have previous state, failing silently");
return;
}
let previous_state = previous_state.unwrap();
if let Some((version_name, install_dir)) = match previous_state {
GameStatus::Installed {
version_name,
install_dir,
} => Some((version_name, install_dir)),
GameStatus::SetupRequired {
version_name,
install_dir,
} => Some((version_name, install_dir)),
_ => None,
} {
db_handle
.games
.transient_statuses
.entry(game_id.clone())
.and_modify(|v| *v = GameTransientStatus::Uninstalling {});
drop(db_handle);
let sender = self.sender.clone();
let app_handle = self.app_handle.clone();
spawn(move || match remove_dir_all(install_dir) {
Err(e) => {
sender
.send(DownloadManagerSignal::Error(GameDownloadError::IoError(
e.kind(),
)))
.unwrap();
}
Ok(_) => {
let mut db_handle = DB.borrow_data_mut().unwrap();
db_handle.games.transient_statuses.remove(&game_id);
db_handle
.games
.statuses
.entry(game_id.clone())
.and_modify(|e| *e = GameStatus::Remote {});
drop(db_handle);
DB.save().unwrap();
info!("uninstalled {}", game_id);
push_game_update(&app_handle, game_id, (Some(GameStatus::Remote {}), None));
}
});
}
}
fn manage_remove_game_queue(&mut self, game_id: String) {
if let Some(current_download) = &self.current_download_agent {
if current_download.id == game_id {
self.manage_cancel_signal();
}
}
let index = self.download_queue.get_by_id(game_id.clone()).unwrap();
let mut queue_handle = self.download_queue.edit();
queue_handle.remove(index);
self.set_game_status(game_id, |db_handle, id| {
db_handle.games.transient_statuses.remove(id);
});
drop(queue_handle);
let index = self.download_queue.get_by_id(game_id.clone());
if let Some(index) = index {
let mut queue_handle = self.download_queue.edit();
queue_handle.remove(index);
self.set_game_status(game_id, |db_handle, id| {
db_handle.games.transient_statuses.remove(id);
});
drop(queue_handle);
}
if self.current_download_agent.is_none() {
self.manage_go_signal();
@ -256,11 +332,16 @@ impl DownloadManagerBuilder {
// When if let chains are stabilised, combine these two statements
if interface.id == game_id {
info!("Popping consumed data");
let download_agent = self.remove_and_cleanup_game(&game_id);
let download_agent = self.remove_and_cleanup_front_game(&game_id);
let download_agent_lock = download_agent.lock().unwrap();
let version = download_agent_lock.version.clone();
let install_dir = download_agent_lock.stored_manifest.base_path.clone().to_string_lossy().to_string();
let install_dir = download_agent_lock
.stored_manifest
.base_path
.clone()
.to_string_lossy()
.to_string();
drop(download_agent_lock);
@ -281,6 +362,22 @@ impl DownloadManagerBuilder {
fn manage_queue_signal(&mut self, id: String, version: String, target_download_dir: usize) {
info!("Got signal Queue");
if let Some(index) = self.download_queue.get_by_id(id.clone()) {
// Should always give us a value
if let Some(download_agent) = self.download_agent_registry.get(&id) {
let download_agent_handle = download_agent.lock().unwrap();
if download_agent_handle.version == version {
info!("game with same version already queued, skipping");
return;
}
// If it's not the same, we want to cancel the current one, and then add the new one
drop(download_agent_handle);
self.manage_remove_game_queue(id.clone());
}
}
let download_agent = Arc::new(Mutex::new(GameDownloadAgent::new(
id.clone(),
version,
@ -391,7 +488,8 @@ impl DownloadManagerBuilder {
fn manage_error_signal(&mut self, error: GameDownloadError) {
let current_status = self.current_download_agent.clone().unwrap();
self.remove_and_cleanup_game(&current_status.id); // Remove all the locks and shit
self.stop_and_wait_current_download();
self.remove_and_cleanup_front_game(&current_status.id); // Remove all the locks and shit, and remove from queue
let mut lock = current_status.status.lock().unwrap();
*lock = GameDownloadStatus::Error;

View File

@ -7,4 +7,4 @@ mod download_thread_control_flag;
mod manifest;
mod progress_object;
pub mod queue;
mod stored_manifest;
mod stored_manifest;

View File

@ -14,25 +14,28 @@ use crate::db::DatabaseImpls;
use auth::{auth_initiate, generate_authorization_header, recieve_handshake, retry_connect};
use cleanup::{cleanup_and_exit, quit};
use db::{
add_download_dir, delete_download_dir, fetch_download_dir_stats, DatabaseInterface,
add_download_dir, delete_download_dir, fetch_download_dir_stats, DatabaseInterface, GameStatus,
DATA_ROOT_DIR,
};
use downloads::download_commands::*;
use downloads::download_manager::DownloadManager;
use downloads::download_manager_builder::DownloadManagerBuilder;
use http::Response;
use http::{header::*, response::Builder as ResponseBuilder};
use library::{fetch_game, fetch_game_status, fetch_game_verion_options, fetch_library, Game};
use log::{debug, info, LevelFilter};
use library::{fetch_game, fetch_game_status, fetch_game_verion_options, fetch_library, uninstall_game, Game};
use log::{debug, info, warn, LevelFilter};
use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender;
use log4rs::append::rolling_file::RollingFileAppender;
use log4rs::config::{Appender, Root};
use log4rs::encode::pattern::PatternEncoder;
use log4rs::Config;
use process::compat::CompatibilityManager;
use process::process_commands::launch_game;
use process::process_manager::ProcessManager;
use remote::{gen_drop_url, use_remote};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::sync::Arc;
use std::{
collections::HashMap,
@ -74,6 +77,8 @@ pub struct AppState<'a> {
download_manager: Arc<DownloadManager>,
#[serde(skip_serializing)]
process_manager: Arc<Mutex<ProcessManager<'a>>>,
#[serde(skip_serializing)]
compat_manager: Arc<Mutex<CompatibilityManager>>,
}
#[tauri::command]
@ -112,6 +117,7 @@ fn setup(handle: AppHandle) -> AppState<'static> {
let games = HashMap::new();
let download_manager = Arc::new(DownloadManagerBuilder::build(handle));
let process_manager = Arc::new(Mutex::new(ProcessManager::new()));
let compat_manager = Arc::new(Mutex::new(CompatibilityManager::new()));
debug!("Checking if database is set up");
let is_set_up = DB.database_is_set_up();
@ -122,18 +128,62 @@ fn setup(handle: AppHandle) -> AppState<'static> {
games,
download_manager,
process_manager,
compat_manager,
};
}
debug!("Database is set up");
let (app_status, user) = auth::setup().unwrap();
let db_handle = DB.borrow_data().unwrap();
let mut missing_games = Vec::new();
let statuses = db_handle.games.statuses.clone();
drop(db_handle);
for (game_id, status) in statuses.into_iter() {
match status {
db::GameStatus::Remote {} => {}
db::GameStatus::SetupRequired {
version_name: _,
install_dir,
} => {
let install_dir_path = Path::new(&install_dir);
if !install_dir_path.exists() {
missing_games.push(game_id);
}
}
db::GameStatus::Installed {
version_name: _,
install_dir,
} => {
let install_dir_path = Path::new(&install_dir);
if !install_dir_path.exists() {
missing_games.push(game_id);
}
}
}
}
info!("detected games missing: {:?}", missing_games);
let mut db_handle = DB.borrow_data_mut().unwrap();
for game_id in missing_games {
db_handle
.games
.statuses
.entry(game_id.to_string())
.and_modify(|v| *v = GameStatus::Remote {});
}
drop(db_handle);
info!("finished setup!");
AppState {
status: app_status,
user,
games,
download_manager,
process_manager,
compat_manager,
}
}
@ -141,7 +191,9 @@ pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::se
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let mut builder = tauri::Builder::default().plugin(tauri_plugin_dialog::init());
let mut builder = tauri::Builder::default()
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_dialog::init());
#[cfg(desktop)]
#[allow(unused_variables)]
@ -177,6 +229,7 @@ pub fn run() {
pause_game_downloads,
resume_game_downloads,
cancel_game,
uninstall_game,
// Processes
launch_game,
])
@ -271,8 +324,16 @@ pub fn run() {
let response = client
.get(object_url.to_string())
.header("Authorization", header)
.send()
.unwrap();
.send();
if response.is_err() {
warn!(
"failed to fetch object with error: {}",
response.err().unwrap()
);
responder.respond(Response::builder().status(500).body(Vec::new()).unwrap());
return;
}
let response = response.unwrap();
let resp_builder = ResponseBuilder::new().header(
CONTENT_TYPE,

View File

@ -8,7 +8,7 @@ use urlencoding::encode;
use crate::db::DatabaseImpls;
use crate::db::GameVersion;
use crate::db::{GameStatus, GameTransientStatus};
use crate::downloads::download_manager::GameDownloadStatus;
use crate::downloads::download_manager::{DownloadManagerStatus, GameDownloadStatus};
use crate::process::process_manager::Platform;
use crate::remote::RemoteAccessError;
use crate::state::{GameStatusManager, GameStatusWithTransient};
@ -37,7 +37,7 @@ pub struct Game {
#[derive(serde::Serialize, Clone)]
pub struct GameUpdateEvent {
pub game_id: String,
pub status: (Option<GameStatus>, Option<GameTransientStatus>),
pub status: GameStatusWithTransient,
}
#[derive(Serialize, Clone)]
@ -50,6 +50,7 @@ pub struct QueueUpdateEventQueueData {
#[derive(serde::Serialize, Clone)]
pub struct QueueUpdateEvent {
pub queue: Vec<QueueUpdateEventQueueData>,
pub status: DownloadManagerStatus,
}
// Game version with some fields missing and size information
@ -232,6 +233,30 @@ pub fn fetch_game_verion_options<'a>(
fetch_game_verion_options_logic(game_id, state).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn uninstall_game(
game_id: String,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<(), String> {
let state_lock = state.lock().unwrap();
state_lock.download_manager.uninstall_game(game_id);
drop(state_lock);
Ok(())
}
pub fn push_game_update(app_handle: &AppHandle, id: String, status: GameStatusWithTransient) {
app_handle
.emit(
&format!("update_game/{}", id),
GameUpdateEvent {
game_id: id,
status,
},
)
.unwrap();
}
pub fn on_game_complete(
game_id: String,
version_name: String,

View File

@ -0,0 +1,51 @@
use std::{
fs::create_dir_all,
path::PathBuf,
sync::atomic::{AtomicBool, Ordering},
};
use crate::db::DATA_ROOT_DIR;
pub struct CompatibilityManager {
compat_tools_path: PathBuf,
prefixes_path: PathBuf,
created_paths: AtomicBool,
}
/*
This gets built into both the Windows & Linux client, but
we only need it in the Linux client. Therefore, it should
do nothing but take a little bit of memory if we're on
Windows.
*/
impl CompatibilityManager {
pub fn new() -> Self {
let root_dir_lock = DATA_ROOT_DIR.lock().unwrap();
let compat_tools_path = root_dir_lock.join("compatibility_tools");
let prefixes_path = root_dir_lock.join("prefixes");
drop(root_dir_lock);
Self {
compat_tools_path,
prefixes_path,
created_paths: AtomicBool::new(false),
}
}
fn ensure_paths_exist(&self) -> Result<(), String> {
if self.created_paths.fetch_and(true, Ordering::Relaxed) {
return Ok(());
}
if !self.compat_tools_path.exists() {
create_dir_all(self.compat_tools_path.clone()).map_err(|e| e.to_string())?;
}
if !self.prefixes_path.exists() {
create_dir_all(self.prefixes_path.clone()).map_err(|e| e.to_string())?;
}
self.created_paths.store(true, Ordering::Relaxed);
Ok(())
}
}

View File

@ -1,2 +1,3 @@
pub mod compat;
pub mod process_commands;
pub mod process_manager;
pub mod process_commands;

View File

@ -3,7 +3,10 @@ use std::sync::Mutex;
use crate::AppState;
#[tauri::command]
pub fn launch_game(game_id: String, state: tauri::State<'_, Mutex<AppState>>) -> Result<(), String> {
pub fn launch_game(
game_id: String,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<(), String> {
let state_lock = state.lock().unwrap();
let mut process_manager_lock = state_lock.process_manager.lock().unwrap();

View File

@ -46,6 +46,12 @@ impl ProcessManager<'_> {
(Platform::Linux, Platform::Linux),
&NativeGameLauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
),
/*
(
(Platform::Linux, Platform::Windows),
&UMULauncher {} as &(dyn ProcessHandler + Sync + Send + 'static)
)
*/
]),
}
}
@ -66,12 +72,6 @@ impl ProcessManager<'_> {
pub fn valid_platform(&self, platform: &Platform) -> Result<bool, String> {
let current = &self.current_platform;
info!("{:?}", self.game_launchers.keys());
info!(
"{:?} {}",
(current.clone(), platform.clone()),
(Platform::Linux, Platform::Linux) == (Platform::Linux, Platform::Linux)
);
Ok(self
.game_launchers
.contains_key(&(current.clone(), platform.clone())))
@ -201,3 +201,19 @@ impl ProcessHandler for NativeGameLauncher {
.map_err(|v| v.to_string())
}
}
struct UMULauncher;
impl ProcessHandler for UMULauncher {
fn launch_game(
&self,
game_id: &String,
version_name: &String,
command: String,
args: Vec<String>,
install_dir: &String,
log_file: File,
error_file: File,
) -> Result<Child, String> {
todo!()
}
}

View File

@ -5,10 +5,7 @@ use crate::{
DB,
};
pub type GameStatusWithTransient = (
Option<GameStatus>,
Option<GameTransientStatus>,
);
pub type GameStatusWithTransient = (Option<GameStatus>, Option<GameTransientStatus>);
pub struct GameStatusManager {}
impl GameStatusManager {

View File

@ -40,6 +40,7 @@
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
],
"externalBin": []
}
}

View File

@ -1392,6 +1392,13 @@
dependencies:
"@tauri-apps/api" "^2.0.0"
"@tauri-apps/plugin-os@~2":
version "2.2.0"
resolved "https://registry.yarnpkg.com/@tauri-apps/plugin-os/-/plugin-os-2.2.0.tgz#ef5511269f59c0ccc580a9d09600034cfaa9743b"
integrity sha512-HszbCdbisMlu5QhCNAN8YIWyz2v33abAWha6+uvV2CKX8P5VSct/y+kEe22JeyqrxCnWlQ3DRx7s49Byg7/0EA==
dependencies:
"@tauri-apps/api" "^2.0.0"
"@tauri-apps/plugin-shell@>=2.0.0":
version "2.0.0"
resolved "https://registry.yarnpkg.com/@tauri-apps/plugin-shell/-/plugin-shell-2.0.0.tgz#b6fc88ab070fd5f620e46405715779aa44eb8428"