Compare commits

...

46 Commits

Author SHA1 Message Date
1f55e19924 adapted to the new API 2025-10-27 21:53:52 +01:00
e239c1a3dd Update Cargo.toml 2025-07-05 15:05:36 +02:00
0f7fa5ba0d can now specify steam client path with BT_STEAM_CLIENT_PATH 2025-05-04 18:07:59 +02:00
594f871fab forgot this file in the last commit, my bad 2025-04-29 20:14:24 +02:00
0fbed904c6 can now pass environment variable but not use them 2025-04-28 20:22:33 +02:00
7d2529588d add some error cli message for debug 2025-04-28 18:45:28 +02:00
b4358afcec can now pass --debug to enable debug messages 2025-04-28 18:40:16 +02:00
ce7a89eeb2 fix launcher was not compiling 2025-04-27 18:24:20 +02:00
8804bec06c catch the error if proton is not initialized correctly 2025-04-27 16:45:58 +02:00
6e1b7ac461 fix sdk was not compiling 2025-04-11 08:38:09 +02:00
9a643b4866 removing the flutter code 2025-04-07 18:42:26 +02:00
ALEZ
908d4b8aec
Merge pull request #29 from ALEZ-DEV/gtk
Transition from Flutter to GTK
2025-04-07 18:41:11 +02:00
9059ce0cf1 some refactor 2025-04-07 18:40:10 +02:00
2d9fac062a some correction 2025-04-07 18:25:31 +02:00
cde2c99e2d now able to change the launch option 2025-04-07 17:58:50 +02:00
c70feada75 fix: game state was not updated 2025-03-17 20:37:05 +01:00
80836f32ec can now download the game 2025-03-14 22:43:31 +01:00
1a6bb86cb5 added the base for the settings page 2025-03-14 19:49:13 +01:00
ce50bf00e4 edited the about page 2025-03-14 19:38:31 +01:00
c84520212c added game page and about page 2025-03-13 21:29:51 +01:00
f793b18b2c some refactor and cleaning 2025-03-13 18:48:48 +01:00
0a60f79daa added a dialog for errors 2025-03-12 21:31:30 +01:00
23acb09ef3 can now download dxvk, fonts and the denpendecies correctly
the fonts installation seems to fail, idk why because it work in
ulterior version but not on this one and I have litteraly changed
nothing, do idk what's going on, but I need to implement error handling
and fix this little issue before continuing
2025-03-11 21:14:55 +01:00
ALEZ-DEV
fa242c1cca can now download proton from the new gtk launcher 2025-02-26 21:46:56 +01:00
ALEZ-DEV
846b4291c6 the project now use workspaces 2025-02-20 18:39:34 +01:00
ALEZ-DEV
baf66a4e13 can now choose release 2025-01-27 20:47:13 +01:00
ALEZ-DEV
72fd11a2ac added some steps 2025-01-17 21:34:53 +01:00
ALEZ-DEV
9246d3a36f improve the menu 2025-01-16 21:07:19 +01:00
ALEZ-DEV
d2e8f5f818 better menu 2025-01-16 20:45:14 +01:00
ALEZ-DEV
c93454358f add menu 2025-01-16 19:24:51 +01:00
ALEZ-DEV
08364f8624 better menu 2024-12-21 00:51:59 +01:00
ALEZ-DEV
1b34ad7642 added libadwaita and added app icon 2024-12-19 19:12:30 +01:00
ALEZ-DEV
a2e0b6315f game process now run on a separate thread 2024-12-18 21:29:11 +01:00
ALEZ-DEV
85bb1e2c59 can now run the game 2024-12-16 21:11:15 +01:00
ALEZ-DEV
f6247cee5a added the foundation to transition from Flutter to GTK 2024-12-14 18:08:55 +01:00
ALEZ-DEV
b1248fdb05 update CHANGELOG.md 2024-11-06 20:01:01 +01:00
ALEZ
dfba16f675
Merge pull request #24 from ALEZ-DEV/show-download-speed
Show download speed
2024-11-06 19:58:50 +01:00
ALEZ-DEV
f66922d813 big edit 2024-11-06 19:55:18 +01:00
ALEZ-DEV
80ea7ec2cf more cleaning 2024-11-06 19:54:10 +01:00
ALEZ-DEV
6ea0d7ac12 some cleaning 2024-11-06 19:51:18 +01:00
ALEZ-DEV
f0c9e4707a can now see the download speed 2024-11-06 19:50:21 +01:00
ALEZ
323ebaaf63
Create FUNDING.yml 2024-11-01 10:26:14 +01:00
ALEZ
adc97cf5bc
Merge pull request #18 from My1/patch-1
Update game_steps_widget.dart
2024-10-31 21:31:11 +01:00
My1
617b21f3ab
Update CHANGELOG.md 2024-10-31 21:04:51 +01:00
My1
0db2c88f83
Update game_steps_widget.dart
Fix data Unit, simplify GiB calculation.
2024-10-31 16:47:35 +01:00
ALEZ
fb4e47eac7
Update CHANGELOG.md 2024-10-28 22:54:03 +01:00
104 changed files with 7493 additions and 11940 deletions

1
.envrc Normal file
View File

@ -0,0 +1 @@
use flake

1
.github/FUNDING.yml vendored Normal file
View File

@ -0,0 +1 @@
github: ALEZ-DEV

2
.gitignore vendored
View File

@ -1,5 +1,5 @@
set_github_env.sh
babylonia-terminal-cli/TDData-data.db
babylonia-terminal-cli/backtrace.txt
target

4470
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

11
Cargo.toml Normal file
View File

@ -0,0 +1,11 @@
[workspace]
resolver = "2"
members = [
"babylonia-terminal",
"babylonia-terminal-cli",
"babylonia-terminal-gui",
"babylonia-terminal-sdk",
]
[workspace.dependencies]
downloader = { git = "https://github.com/ALEZ-DEV/downloader" } # version = "0.2.7",

File diff suppressed because it is too large Load Diff

View File

@ -8,9 +8,6 @@ repository = "https://github.com/ALEZ-DEV/Babylonia-terminal"
license = "LGPL-3.0-or-later"
keywords = ["launcher", "game"]
[[bin]]
name = "babylonia-terminal-cli"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
@ -19,7 +16,7 @@ babylonia-terminal-sdk = { path = "./../babylonia-terminal-sdk" }
clap = { version = "4.5.7", features = ["derive"] }
derive = "1.0.0"
dialoguer = "0.11.0"
downloader = { git = "https://github.com/ALEZ-DEV/downloader" } # version = "0.2.7",
downloader = { workspace = true }
indicatif = "0.17.8"
log = "0.4.21"
simple_logger = "4.3.3"

View File

@ -13,7 +13,19 @@ pub struct Args {
#[arg(long)]
pub set_options: Option<String>,
/// Pass environment variables to tinker the behavior of the game
#[arg(long, value_name = "VALUE", action = clap::ArgAction::Append)]
pub add_env_var: Vec<String>,
/// Show the logs direcly to the stdout of your terminal
#[arg(long, default_value = "false")]
pub logs: bool,
/// Launch the GUI version
#[arg(long, default_value = "false")]
pub gui: bool,
/// Enable debug messages
#[arg(long, default_value = "false")]
pub debug: bool,
}

View File

@ -6,7 +6,7 @@ use babylonia_terminal_sdk::{
proton_component::{ProtonComponent, PROTON_DEV, PROTON_REPO},
},
game_config::GameConfig,
game_manager::GameManager,
game_manager::{EnvironmentVariable, GameManager},
game_state::GameState,
};
@ -16,7 +16,11 @@ use wincompatlib::prelude::*;
use crate::{reporter::DownloadReporter, utils};
pub async fn run(launch_options: Option<String>, show_logs: bool) {
pub async fn run(
launch_options: Option<String>,
env_vars: Vec<EnvironmentVariable>,
show_logs: bool,
) {
let mut proton_component: Option<ProtonComponent> = None;
let mut proton: Option<Proton> = None;
@ -170,6 +174,7 @@ pub async fn run(launch_options: Option<String>, show_logs: bool) {
.await
.expect("Failed to start game, the game directory was not found"),
launch_options,
env_vars,
show_logs,
)
.await;

View File

@ -0,0 +1,35 @@
use arguments::Args;
use babylonia_terminal_sdk::{game_config::GameConfig, game_manager::EnvironmentVariable};
use clap::Parser;
use log::debug;
pub mod arguments;
pub mod game;
pub mod reporter;
pub mod utils;
pub fn run() {
let args = Args::parse();
debug!("Launch option -> {:?}", args.options);
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
if let Some(command) = args.set_options {
GameConfig::set_launch_options(Some(command))
.await
.expect("Failed to save launch options into the config file");
}
let vars = args
.add_env_var
.iter()
.map(|v| EnvironmentVariable::parse(v))
.collect();
game::run(args.options, vars, args.logs).await;
});
}

View File

@ -0,0 +1,19 @@
[package]
name = "babylonia-terminal-gui"
version = "0.1.0"
edition = "2021"
[dependencies]
babylonia-terminal-sdk = { path = "./../babylonia-terminal-sdk" }
anyhow = "1.0.94"
log = "0.4.22"
relm4-components = "0.9.1"
wincompatlib = "0.7.5"
relm4 = { version = "0.9.1", features = ["libadwaita"] }
libadwaita = { version = "0.7.1", features = ["v1_4"] }
downloader = { workspace = true }
rfd = "0.15.2"
arboard = { version = "3.4.1", features = ["wayland-data-control"] }
[build-dependencies]
glib-build-tools = "0.20.0"

View File

Before

Width:  |  Height:  |  Size: 239 KiB

After

Width:  |  Height:  |  Size: 239 KiB

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
<gresource prefix="/moe/celica/babylonia-terminal/icons/hicolor/scalable/apps">
<file alias="icon.png">icon.png</file>
</gresource>
</gresources>

View File

@ -0,0 +1,5 @@
use glib_build_tools::compile_resources;
fn main() {
compile_resources(&["assets"], "assets/resources.xml", "resources.gresource");
}

View File

@ -0,0 +1,54 @@
use log::debug;
use relm4::{
gtk::{self, gdk, gio},
RelmApp,
};
mod manager;
mod ui;
pub const APP_RESOURCE_PATH: &str = "/moe/celica/babylonia-terminal";
pub const IS_DEVEL: bool = cfg!(debug_assertions);
pub fn run() {
debug!("Start GUI!");
let app = RelmApp::new("moe.celica.BabyloniaTerminal").with_args(vec![]);
gio::resources_register_include!("resources.gresource").unwrap();
let display = gdk::Display::default().unwrap();
let theme = gtk::IconTheme::for_display(&display);
theme.add_resource_path(&format!("{APP_RESOURCE_PATH}/icons"));
relm4::set_global_css(&format!(
"
progressbar > text {{
margin-bottom: 4px;
}}
window.classic-style {{
background-repeat: no-repeat;
background-size: cover;
}}
window.classic-style progressbar {{
background-color: #00000020;
border-radius: 16px;
padding: 8px 16px;
}}
window.classic-style progressbar:hover {{
background-color: #00000060;
color: #ffffff;
transition-duration: 0.5s;
transition-timing-function: linear;
}}
.round-bin {{
border-radius: 24px;
}}
"
));
ui::run(app);
}

View File

@ -0,0 +1,330 @@
use std::{ops::Deref, sync::Arc};
use babylonia_terminal_sdk::{
components::proton_component::ProtonComponent, game_config::GameConfig,
game_manager::GameManager, utils::github_requester::GithubRelease,
};
use downloader::download;
use log::{debug, error};
use relm4::{
tokio::{self, sync::OnceCell},
Worker,
};
use wincompatlib::prelude::Proton;
use crate::ui::{
self,
pages::{
self,
steps::{
self,
download_components::{self, DownloadComponentsPageWidgets},
},
},
};
static PROTON: OnceCell<Proton> = OnceCell::const_new();
pub async fn get_proton() -> anyhow::Result<Proton> {
if !PROTON.initialized() {
let proton_component = ProtonComponent::new(GameConfig::get_config().await.config_dir);
let proton = proton_component.init_proton();
if let Err(ref e) = proton {
error!("Failed to initialize proton : {}", e);
anyhow::bail!("Failed to initialize proton : {}", e);
}
Ok(PROTON
.get_or_init(|| async { proton.unwrap() })
.await
.clone())
} else {
Ok(PROTON.get().unwrap().clone())
}
}
pub async fn run_game() -> anyhow::Result<()> {
let proton = get_proton().await?;
let game_dir = GameConfig::get_config().await.game_dir;
if game_dir.is_none() {
error!("Failed to start game, the game directory was not found");
anyhow::bail!("Failed to start game, the game directory was not found");
}
GameManager::start_game(&proton, game_dir.unwrap(), None, vec![], false).await?;
Ok(())
}
#[derive(Debug)]
pub enum HandleGameProcessMsg {
RunGame,
}
#[derive(Debug)]
pub struct HandleGameProcess;
impl Worker for HandleGameProcess {
type Init = ();
type Input = HandleGameProcessMsg;
type Output = ui::pages::game::GamePageMsg;
fn init(_init: Self::Init, _sender: relm4::ComponentSender<Self>) -> Self {
Self
}
fn update(&mut self, message: Self::Input, sender: relm4::ComponentSender<Self>) {
match message {
HandleGameProcessMsg::RunGame => {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
sender.output(ui::pages::game::GamePageMsg::SetIsGameRunning(true));
if let Err(error) = run_game().await {
sender.output(pages::game::GamePageMsg::ShowError(format!(
"Unable to start game : {}",
error
)));
};
sender.output(ui::pages::game::GamePageMsg::SetIsGameRunning(false));
});
}
}
}
}
#[derive(Debug)]
pub enum HandleGameInstallationMsg {
StartInstallation(Arc<pages::game::ProgressBarGameInstallationReporter>),
StartPatch,
StartUpdate(Arc<pages::game::ProgressBarGameInstallationReporter>),
}
#[derive(Debug)]
pub struct HandleGameInstallation;
impl Worker for HandleGameInstallation {
type Init = ();
type Input = HandleGameInstallationMsg;
type Output = pages::game::GamePageMsg;
fn init(init: Self::Init, sender: relm4::ComponentSender<Self>) -> Self {
Self
}
fn update(&mut self, message: Self::Input, sender: relm4::ComponentSender<Self>) {
match message {
HandleGameInstallationMsg::StartInstallation(progress_bar) => {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
sender.output(pages::game::GamePageMsg::SetIsDownloading(true));
let game_dir = if let Some(dir) = GameConfig::get_config().await.game_dir {
dir
} else {
GameConfig::get_config_directory().await
};
if let Err(error) = GameManager::install_game(game_dir, progress_bar).await
{
sender.output(pages::game::GamePageMsg::ShowError(format!(
"Error while downloading the game : {}",
error
)));
};
sender.output(pages::game::GamePageMsg::SetIsDownloading(false));
sender.output(pages::game::GamePageMsg::UpdateGameState);
});
}
HandleGameInstallationMsg::StartPatch => {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
sender.output(pages::game::GamePageMsg::SetIsPatching(true));
let game_dir = if let Some(dir) = GameConfig::get_config().await.game_dir {
dir
} else {
GameConfig::get_config_directory().await
};
if let Err(error) = GameManager::patch_game(game_dir).await {
sender.output(pages::game::GamePageMsg::ShowError(format!(
"Error while patching the game : {}",
error
)));
};
sender.output(pages::game::GamePageMsg::SetIsPatching(false));
sender.output(pages::game::GamePageMsg::UpdateGameState);
});
}
HandleGameInstallationMsg::StartUpdate(progress_bar) => {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
sender.output(pages::game::GamePageMsg::SetIsDownloading(true));
if let Err(error) = GameManager::update_game().await {
sender.output(pages::game::GamePageMsg::ShowError(format!(
"Error while updating the game : {}",
error
)));
};
let game_dir = if let Some(dir) = GameConfig::get_config().await.game_dir {
dir
} else {
GameConfig::get_config_directory().await
};
if let Err(error) = GameManager::install_game(game_dir, progress_bar).await
{
sender.output(pages::game::GamePageMsg::ShowError(format!(
"Error while updating the game : {}",
error
)));
};
sender.output(pages::game::GamePageMsg::SetIsDownloading(true));
sender.output(pages::game::GamePageMsg::UpdateGameState);
});
}
}
}
}
#[derive(Debug)]
pub enum HandleComponentInstallationMsg {
StartInstallation(
(
usize,
usize,
Arc<download_components::DownloadComponentProgressBarReporter>,
),
), // proton release and dxvk release
}
#[derive(Debug)]
pub struct HandleComponentInstallation;
impl Worker for HandleComponentInstallation {
type Init = ();
type Input = HandleComponentInstallationMsg;
type Output = download_components::DownloadComponentsMsg;
fn init(_init: Self::Init, _sender: relm4::ComponentSender<Self>) -> Self {
Self
}
fn update(&mut self, message: Self::Input, sender: relm4::ComponentSender<Self>) {
match message {
HandleComponentInstallationMsg::StartInstallation((
proton_release,
dxvk_release,
progress_bar,
)) => {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
let _ = sender.output(
download_components::DownloadComponentsMsg::UpdateProgressBarMsg(
String::from("Starting download for proton"),
Some(String::from("Unpacking and initializing proton")),
),
);
let _ = sender.output(
download_components::DownloadComponentsMsg::UpdateCurrentlyInstalling(
download_components::CurrentlyInstalling::Proton,
),
);
let _ = sender.output(
download_components::DownloadComponentsMsg::UpdateDownloadedComponentName(
String::from("proton"),
),
);
let game_dir = if let Some(dir) = GameConfig::get_config().await.game_dir {
dir
} else {
GameConfig::get_config_directory().await
};
if let Err(error) = GameManager::install_wine(game_dir.clone(), proton_release, Some(progress_bar.clone())).await {
sender.output(download_components::DownloadComponentsMsg::ShowError(format!("Failed to install proton : {}", error))).unwrap();
return;
}
let _ = sender
.output(download_components::DownloadComponentsMsg::UpdateProgressBarMsg(String::from("Starting download for DXVK"), Some(String::from("Installing DXVK"))));
let _ = sender.output(download_components::DownloadComponentsMsg::UpdateCurrentlyInstalling(download_components::CurrentlyInstalling::DXVK));
let _ = sender.output(download_components::DownloadComponentsMsg::UpdateDownloadedComponentName(String::from("DXVK")));
let proton = match get_proton().await {
Ok(p) => p,
Err(e) => {
sender.output(download_components::DownloadComponentsMsg::ShowError(format!("Failed to initialize proton : {:?}", e))).unwrap();
return;
}
};
if let Err(error) = GameManager::install_dxvk(&proton, game_dir, dxvk_release, Some(progress_bar.clone())).await {
sender.output(download_components::DownloadComponentsMsg::ShowError(format!("Failed to install DXVK : {}", error))).unwrap();
return;
}
let _ = sender
.output(download_components::DownloadComponentsMsg::UpdateProgressBarMsg(String::from("Downloading and installing fonts"), Some(String::from("Fonts installed"))));
let _ = sender.output(download_components::DownloadComponentsMsg::UpdateCurrentlyInstalling(download_components::CurrentlyInstalling::Fonts));
let _ = sender.output(download_components::DownloadComponentsMsg::UpdateDownloadedComponentName(String::from("fonts")));
if let Err(error) = GameManager::install_font(&proton, Some(progress_bar.clone())).await {
sender.output(download_components::DownloadComponentsMsg::ShowError(format!("Failed to install fonts : {}", error))).unwrap();
return;
}
let _ = sender
.output(download_components::DownloadComponentsMsg::UpdateProgressBarMsg(String::from("Download and installing denpendecies"), None));
let _ = sender.output(download_components::DownloadComponentsMsg::UpdateCurrentlyInstalling(download_components::CurrentlyInstalling::Denpendecies));
let _ = sender.output(download_components::DownloadComponentsMsg::UpdateDownloadedComponentName(String::from("denpendecies")));
if let Err(error) = GameManager::install_dependencies(&proton).await {
sender.output(download_components::DownloadComponentsMsg::ShowError(format!("Failed to install dependencies : {}", error))).unwrap();
return;
}
debug!("Finished to installing the components!");
let _ = sender.output(download_components::DownloadComponentsMsg::Finish);
});
}
}
}
}

View File

View File

@ -0,0 +1,281 @@
use std::convert::identity;
use crate::{manager, IS_DEVEL};
use babylonia_terminal_sdk::game_state::GameState;
use log::debug;
use pages::game::GamePageMsg;
use relm4::{
self,
component::AsyncConnector,
gtk::{self, prelude::*, Widget},
loading_widgets::LoadingWidgets,
once_cell::sync::OnceCell,
prelude::*,
*,
};
use adw::prelude::*;
use libadwaita as adw;
use crate::APP_RESOURCE_PATH;
pub mod pages;
pub static mut MAIN_WINDOW: Option<adw::ApplicationWindow> = None;
pub fn run(app: RelmApp<MainWindowMsg>) {
app.run_async::<MainWindow>(None);
}
#[derive(Debug)]
pub enum MainWindowMsg {
ToggleMenuVisibility,
SelectPage(Pages),
UpdateGameState,
}
struct MainWindow {
game_state: GameState,
setup_page: AsyncController<pages::steps::SetupPage>,
game_page: AsyncController<pages::game::GamePage>,
settings_page: AsyncConnector<pages::settings::SettingsPage>,
about_page: AsyncConnector<pages::about::AboutPage>,
current_page: Pages,
is_menu_visible: bool,
}
impl MainWindow {
fn new(game_state: GameState, sender: &relm4::AsyncComponentSender<Self>) -> Self {
let setup_page = pages::steps::SetupPage::builder()
.launch(game_state.clone())
.forward(sender.input_sender(), identity);
let game_page = pages::game::GamePage::builder()
.launch(game_state.clone())
.forward(sender.input_sender(), identity);
let about_page = pages::about::AboutPage::builder().launch(());
let settings_page = pages::settings::SettingsPage::builder().launch(());
MainWindow {
game_state,
setup_page,
game_page,
settings_page,
about_page,
current_page: Pages::GamePage,
is_menu_visible: false,
}
}
}
#[derive(Debug, PartialEq, Eq)]
enum Pages {
GamePage,
SettingsPage,
AboutPage,
}
#[relm4::component(async)]
impl SimpleAsyncComponent for MainWindow {
type Input = MainWindowMsg;
type Output = ();
type Init = Option<GameState>;
view! {
#[root]
main_window = adw::ApplicationWindow {
set_default_size: (700, 560),
add_css_class?: IS_DEVEL.then_some("devel"),
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
adw::OverlaySplitView {
#[watch]
set_show_sidebar: model.is_menu_visible,
set_collapsed: true,
#[wrap(Some)]
set_content = &gtk::Box {
set_orientation: gtk::Orientation::Vertical,
adw::HeaderBar {
pack_start = &gtk::Button {
set_icon_name: "open-menu-symbolic",
#[watch]
set_visible: model.game_state.is_environment_ready(),
connect_clicked => MainWindowMsg::ToggleMenuVisibility,
},
},
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_vexpand: true,
set_margin_horizontal: 50,
set_valign: gtk::Align::Center,
#[watch]
set_visible: model.game_state.is_environment_ready(),
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_vexpand: true,
#[watch]
set_visible: model.current_page == Pages::GamePage,
model.game_page.widget(),
},
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_vexpand: true,
#[watch]
set_visible: model.current_page == Pages::SettingsPage,
model.settings_page.widget(),
},
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_vexpand: true,
#[watch]
set_visible: model.current_page == Pages::AboutPage,
model.about_page.widget(),
},
},
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
#[watch]
set_visible: !model.game_state.is_environment_ready(),
model.setup_page.widget(),
}
},
#[wrap(Some)]
set_sidebar = &gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_width_request: 250,
set_margin_all: 10,
gtk::Picture {
set_resource: Some(&format!("{APP_RESOURCE_PATH}/icons/hicolor/scalable/apps/icon.png")),
set_hexpand: true,
set_margin_horizontal: 30,
set_margin_top: 30,
set_margin_bottom: 10,
},
gtk::Label {
set_label: "Babylonia Terminal",
set_margin_top: 12,
add_css_class: "title-1",
set_margin_horizontal: 30,
set_margin_bottom: 10,
},
gtk::Button {
set_margin_vertical: 5,
set_label: "Game",
connect_clicked => MainWindowMsg::SelectPage(Pages::GamePage),
},
gtk::Button {
set_margin_vertical: 5,
set_label: "Settings",
connect_clicked => MainWindowMsg::SelectPage(Pages::SettingsPage),
},
gtk::Button {
set_margin_vertical: 5,
set_label: "About",
connect_clicked => MainWindowMsg::SelectPage(Pages::AboutPage),
},
},
},
}
}
}
async fn init(
game_state: Self::Init,
root: Self::Root,
sender: relm4::AsyncComponentSender<Self>,
) -> AsyncComponentParts<Self> {
let model;
if game_state.is_none() {
model = MainWindow::new(
babylonia_terminal_sdk::game_state::GameState::get_current_state()
.await
.unwrap(),
&sender,
);
} else {
model = MainWindow::new(game_state.unwrap(), &sender);
}
let widgets = view_output!();
unsafe {
MAIN_WINDOW = Some(widgets.main_window.clone());
}
debug!("current GameState : {:?}", model.game_state);
AsyncComponentParts { model, widgets }
}
fn init_loading_widgets(root: Self::Root) -> Option<LoadingWidgets> {
view! {
#[local]
root {
set_title: Some("Babylonia Terminal"),
set_default_width: 700,
set_default_height: 300,
#[name(spinner)]
gtk::Spinner {
start: (),
set_halign: gtk::Align::Center,
}
}
}
Some(LoadingWidgets::new(root, spinner))
}
async fn update(&mut self, message: Self::Input, _sender: relm4::AsyncComponentSender<Self>) {
match message {
MainWindowMsg::ToggleMenuVisibility => self.is_menu_visible = !self.is_menu_visible,
MainWindowMsg::SelectPage(page) => {
self.current_page = page;
self.is_menu_visible = false;
}
MainWindowMsg::UpdateGameState => {
self.game_state = GameState::get_current_state().await.unwrap();
self.game_page.sender().send(GamePageMsg::UpdateGameState);
debug!(
"is_environment_ready : {}",
self.game_state.is_environment_ready()
);
}
}
}
}

View File

@ -0,0 +1,736 @@
use libadwaita::prelude::{PreferencesPageExt, PreferencesRowExt};
use relm4::{
gtk::prelude::{OrientableExt, WidgetExt},
prelude::{adw, gtk, AsyncComponentParts, SimpleAsyncComponent},
RelmWidgetExt,
};
use crate::APP_RESOURCE_PATH;
pub struct AboutPage;
#[relm4::component(pub, async)]
impl SimpleAsyncComponent for AboutPage {
type Input = ();
type Output = ();
type Init = ();
view! {
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
adw::PreferencesPage {
add = &adw::PreferencesGroup {
gtk::Label {
set_label: "Babylonia Terminal",
set_margin_top: 24,
add_css_class: "title-1",
},
gtk::Label {
set_label: "Made by ALEZ-DEV and the anime game community on Github",
set_margin_top: 24,
add_css_class: "title-3",
},
gtk::Label {
set_label: "This software was made under the GPL-3.0 license",
set_margin_vertical: 24,
add_css_class: "title-4",
},
gtk::Label {
set_justify: gtk::Justification::Fill,
set_label: r#"Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>."#,
set_margin_top: 24,
set_css_classes: &["body", "monospace"],
},
},
},
}
}
async fn init(
_: Self::Init,
root: Self::Root,
sender: relm4::AsyncComponentSender<Self>,
) -> relm4::prelude::AsyncComponentParts<Self> {
let model = AboutPage {};
let widgets = view_output!();
AsyncComponentParts { model, widgets }
}
}

View File

@ -0,0 +1,339 @@
use std::{convert::identity, fmt::format};
use arboard::Clipboard;
use babylonia_terminal_sdk::game_state::GameState;
use libadwaita::prelude::{MessageDialogExt, PreferencesPageExt};
use log::error;
use relm4::{
adw,
gtk::{
self,
prelude::{ButtonExt, GtkWindowExt, OrientableExt, WidgetExt},
},
prelude::{AsyncComponentParts, SimpleAsyncComponent},
Component, RelmWidgetExt, WorkerController,
};
use crate::{
manager,
ui::{MainWindowMsg, MAIN_WINDOW},
APP_RESOURCE_PATH,
};
#[derive(Debug)]
pub struct GamePage {
game_state: GameState,
game_handler: WorkerController<manager::HandleGameProcess>,
installation_handler: WorkerController<manager::HandleGameInstallation>,
is_game_running: bool,
is_downloading: bool,
is_patching: bool,
progress_bar_reporter: std::sync::Arc<ProgressBarGameInstallationReporter>,
progress_bar_message: String,
fraction: f64,
}
#[derive(Debug)]
pub enum GamePageMsg {
SetIsGameRunning(bool),
SetIsDownloading(bool),
SetIsPatching(bool),
UpdateGameState,
UpdateProgressBar(u64, u64),
ShowError(String),
}
#[relm4::component(pub, async)]
impl SimpleAsyncComponent for GamePage {
type Input = GamePageMsg;
type Output = MainWindowMsg;
type Init = GameState;
view! {
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
adw::PreferencesPage {
add = &adw::PreferencesGroup {
gtk::Picture {
set_resource: Some(&format!("{APP_RESOURCE_PATH}/icons/hicolor/scalable/apps/icon.png")),
set_vexpand: true,
set_width_request: 350,
},
gtk::Label {
set_label: "Babylonia Terminal",
set_margin_top: 24,
add_css_class: "title-1",
},
},
add = &adw::PreferencesGroup {
set_margin_vertical: 48,
gtk::Button {
set_css_classes: &["suggested-action", "pill"],
set_label: "Install",
set_hexpand: false,
set_width_request: 200,
#[watch]
set_visible: model.game_state == GameState::GameNotInstalled,
#[watch]
set_sensitive: !model.is_downloading,
connect_clicked[sender = model.installation_handler.sender().clone(), progress_bar = model.progress_bar_reporter.clone()] => move |_| {
sender.send(manager::HandleGameInstallationMsg::StartInstallation(progress_bar.clone())).unwrap();
},
},
gtk::Button {
set_css_classes: &["suggested-action", "pill"],
set_label: "Apply patch",
set_hexpand: false,
set_width_request: 200,
#[watch]
set_visible: model.game_state == GameState::GameNotPatched,
#[watch]
set_sensitive: !model.is_patching,
connect_clicked[sender = model.installation_handler.sender().clone()] => move |_| {
sender.send(manager::HandleGameInstallationMsg::StartPatch).unwrap();
},
},
gtk::Button {
set_css_classes: &["suggested-action", "pill"],
set_label: "Start game",
set_hexpand: false,
set_width_request: 200,
#[watch]
set_visible: model.game_state == GameState::GameInstalled,
#[watch]
set_sensitive: !model.is_game_running,
connect_clicked[sender = model.game_handler.sender().clone()] => move |_| {
sender.send(manager::HandleGameProcessMsg::RunGame).unwrap();
},
},
gtk::Button {
set_css_classes: &["suggested-action", "pill"],
set_label: "Update",
set_hexpand: false,
set_width_request: 200,
#[watch]
set_visible: model.game_state == GameState::GameNeedUpdate,
#[watch]
set_sensitive: !model.is_downloading,
connect_clicked[sender = model.installation_handler.sender().clone(), progress_bar = model.progress_bar_reporter.clone()] => move |_| {
sender.send(manager::HandleGameInstallationMsg::StartUpdate(progress_bar.clone())).unwrap();
},
},
},
},
gtk::ProgressBar {
#[watch]
set_fraction: model.fraction,
#[watch]
set_visible: (model.game_state == GameState::GameNotInstalled || model.game_state == GameState::GameNeedUpdate) && model.is_downloading && model.fraction != 0.0,
#[watch]
set_text: Some(&model.progress_bar_message),
set_show_text: true,
},
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
#[watch]
set_visible: (model.game_state == GameState::GameNotInstalled || model.game_state == GameState::GameNeedUpdate) && model.is_downloading && model.fraction == 0.0,
gtk::Box {
set_orientation: gtk::Orientation::Horizontal,
set_halign: gtk::Align::Center,
set_margin_bottom: 24,
gtk::Label {
set_label: "Checking game files",
add_css_class: "title-2",
},
gtk::Spinner {
set_spinning: true,
set_margin_start: 24,
}
},
gtk::Label {
set_label: "This can take some time, please wait...",
add_css_class: "title-4",
},
},
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
#[watch]
set_visible: model.game_state == GameState::GameNotPatched && model.is_patching,
gtk::Box {
set_orientation: gtk::Orientation::Horizontal,
set_halign: gtk::Align::Center,
gtk::Label {
set_label: "Patching game",
add_css_class: "title-2",
},
gtk::Spinner {
set_spinning: true,
}
},
gtk::Label {
set_label: "This can take some time, please wait...",
add_css_class: "title-4",
},
}
}
}
async fn init(
game_state: Self::Init,
root: Self::Root,
sender: relm4::AsyncComponentSender<Self>,
) -> relm4::prelude::AsyncComponentParts<Self> {
let model = GamePage {
progress_bar_reporter: ProgressBarGameInstallationReporter::create(sender.clone()),
game_state,
game_handler: manager::HandleGameProcess::builder()
.detach_worker(())
.forward(sender.input_sender(), identity),
installation_handler: manager::HandleGameInstallation::builder()
.detach_worker(())
.forward(sender.input_sender(), identity),
is_game_running: false,
is_downloading: false,
is_patching: false,
fraction: 0.0,
progress_bar_message: String::new(),
};
let widgets = view_output!();
AsyncComponentParts { model, widgets }
}
async fn update(&mut self, message: Self::Input, _: relm4::AsyncComponentSender<Self>) -> () {
match message {
GamePageMsg::SetIsGameRunning(value) => self.is_game_running = value,
GamePageMsg::SetIsDownloading(value) => self.is_downloading = value,
GamePageMsg::SetIsPatching(value) => self.is_patching = value,
GamePageMsg::UpdateGameState => {
self.game_state = GameState::get_current_state().await.unwrap()
} //TODO: remove unwrap()
GamePageMsg::UpdateProgressBar(current, max_progress) => {
self.fraction = if current == 0 {
0.0
} else {
current as f64 / max_progress as f64
};
//1024^3 = 1073741824
let current_gb = current as f64 / 1073741824 as f64;
let max_gb = max_progress as f64 / 1073741824 as f64;
self.progress_bar_message = format!(
"Downloading : {:.2}% ({:.2} / {:.2}GiB)",
self.fraction * 100 as f64,
current_gb,
max_gb,
);
}
GamePageMsg::ShowError(message) => {
let dialog = unsafe {
adw::MessageDialog::new(
MAIN_WINDOW.as_ref(),
Some("Something went wrong"),
Some(&message),
)
};
dialog.add_response("close", "Close");
dialog.add_response("copy", "Copy");
dialog.set_response_appearance("copy", adw::ResponseAppearance::Suggested);
dialog.connect_response(Some("copy"), move |_, _| {
if let Err(err) = Clipboard::new().unwrap().set_text(&message.clone()) {
error!("Failed to copy the error to the clipboard : {}", err);
}
});
dialog.present();
}
}
}
}
#[derive(Debug)]
struct ProgressBarGameInstallationReporterPrivate {
max_progress: Option<u64>,
}
#[derive(Debug)]
pub struct ProgressBarGameInstallationReporter {
private: std::sync::Mutex<Option<ProgressBarGameInstallationReporterPrivate>>,
sender: relm4::AsyncComponentSender<GamePage>,
}
impl ProgressBarGameInstallationReporter {
fn create(page: relm4::AsyncComponentSender<GamePage>) -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
private: std::sync::Mutex::new(None),
sender: page,
})
}
}
impl downloader::progress::Reporter for ProgressBarGameInstallationReporter {
fn setup(&self, max_progress: Option<u64>, message: &str) {
let private = ProgressBarGameInstallationReporterPrivate { max_progress };
let mut guard = self.private.lock().unwrap();
*guard = Some(private);
}
fn progress(&self, current: u64) {
if let Some(p) = self.private.lock().unwrap().as_mut() {
self.sender.input(GamePageMsg::UpdateProgressBar(
current,
p.max_progress.unwrap(),
));
}
}
fn set_message(&self, _: &str) {}
fn done(&self) {
let mut guard = self.private.lock().unwrap();
*guard = None;
}
}

View File

@ -0,0 +1,4 @@
pub mod about;
pub mod game;
pub mod settings;
pub mod steps;

View File

@ -0,0 +1,122 @@
use arboard::Clipboard;
use babylonia_terminal_sdk::game_config::GameConfig;
use log::error;
use relm4::{
gtk::{
prelude::{EditableExt, GtkWindowExt, OrientableExt, WidgetExt},
InputHints,
},
prelude::{gtk, AsyncComponentParts, SimpleAsyncComponent},
};
use libadwaita::{
self as adw,
prelude::{
EntryRowExt, MessageDialogExt, PreferencesGroupExt, PreferencesPageExt, PreferencesRowExt,
},
};
use crate::ui::MAIN_WINDOW;
#[derive(Debug)]
pub enum SettingsPageMsg {
UpdateLaunchOption(Option<String>),
ShowError(String),
}
pub struct SettingsPage {
launch_option: String,
}
#[relm4::component(pub, async)]
impl SimpleAsyncComponent for SettingsPage {
type Input = SettingsPageMsg;
type Output = ();
type Init = ();
view! {
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
adw::PreferencesPage {
set_title: "General settings",
add = &adw::PreferencesGroup {
set_width_request: 500,
set_title: "Launch option",
set_description: Some("Pass launch options to tinker the behavior of the game"),
adw::EntryRow {
set_title: "%command%",
set_text: &model.launch_option,
connect_changed[sender] => move |entry| {
let command = entry.text().trim().to_string();
if command.is_empty() {
sender.input(SettingsPageMsg::UpdateLaunchOption(None))
} else {
sender.input(SettingsPageMsg::UpdateLaunchOption(Some(command)))
}
}
}
}
}
}
}
async fn init(
_: Self::Init,
root: Self::Root,
sender: relm4::AsyncComponentSender<Self>,
) -> relm4::prelude::AsyncComponentParts<Self> {
let launch_option = match GameConfig::get_launch_options().await {
Err(e) => String::new(),
Ok(v) => match v {
None => String::new(),
Some(launch) => launch,
},
};
let model = SettingsPage { launch_option };
let widgets = view_output!();
AsyncComponentParts { model, widgets }
}
async fn update(&mut self, message: Self::Input, sender: relm4::AsyncComponentSender<Self>) {
match message {
SettingsPageMsg::UpdateLaunchOption(new_launch_option) => {
if let Err(e) = GameConfig::set_launch_options(new_launch_option).await {
sender.input(SettingsPageMsg::ShowError(format!(
"Something went wrong when updated the launch options : {}",
e
)));
}
}
SettingsPageMsg::ShowError(message) => {
let dialog = unsafe {
adw::MessageDialog::new(
MAIN_WINDOW.as_ref(),
Some("Something went wrong"),
Some(&message),
)
};
dialog.add_response("close", "Close");
dialog.add_response("copy", "Copy");
dialog.set_response_appearance("copy", adw::ResponseAppearance::Suggested);
dialog.connect_response(Some("copy"), move |_, _| {
if let Err(err) = Clipboard::new().unwrap().set_text(&message.clone()) {
error!("Failed to copy the error to the clipboard : {}", err);
}
});
dialog.present();
}
}
}
}

View File

@ -0,0 +1,123 @@
use std::{path::PathBuf, str::FromStr};
use babylonia_terminal_sdk::{game_config::GameConfig, game_manager::GameManager};
use log::info;
use relm4::{
gtk,
prelude::{AsyncComponentParts, SimpleAsyncComponent},
view, RelmWidgetExt,
};
use libadwaita::{self as adw, prelude::*};
use super::SetupPageMsg;
#[derive(Debug)]
pub enum ChooseGameDirectoryMsg {
ChoosePath,
Next,
}
pub struct ChooseGameDirectoryPage {
path: PathBuf,
}
#[relm4::component(async, pub)]
impl SimpleAsyncComponent for ChooseGameDirectoryPage {
type Input = ChooseGameDirectoryMsg;
type Output = SetupPageMsg;
type Init = ();
view! {
#[root]
gtk::Box {
adw::PreferencesPage {
set_hexpand: true,
add = &adw::PreferencesGroup {
set_valign: gtk::Align::Center,
set_vexpand: true,
gtk::Label {
set_label: "Game directory",
add_css_class: "title-1"
},
},
add = &adw::PreferencesGroup {
set_width_request: 500,
set_valign: gtk::Align::Center,
set_vexpand: true,
adw::ActionRow {
set_title: "Game directory",
set_icon_name: Some("folder-symbolic"),
set_activatable: true,
#[watch]
set_subtitle: model.path.to_str().unwrap(),
connect_activated => ChooseGameDirectoryMsg::ChoosePath,
},
},
add = &adw::PreferencesGroup {
set_margin_vertical: 48,
gtk::Button {
set_css_classes: &["suggested-action", "pill"],
set_label: "Next",
set_hexpand: false,
set_width_request: 200,
connect_clicked => ChooseGameDirectoryMsg::Next,
},
},
},
}
}
async fn init(
init: Self::Init,
root: Self::Root,
sender: relm4::AsyncComponentSender<Self>,
) -> relm4::prelude::AsyncComponentParts<Self> {
let path = if let Some(dir) = GameConfig::get_config().await.game_dir {
dir
} else {
GameConfig::get_config_directory().await
};
let model = ChooseGameDirectoryPage { path };
let widgets = view_output!();
AsyncComponentParts { widgets, model }
}
async fn update(&mut self, message: Self::Input, sender: relm4::AsyncComponentSender<Self>) {
match message {
ChooseGameDirectoryMsg::ChoosePath => {
info!("choose path");
let result = rfd::AsyncFileDialog::new()
.set_directory(self.path.clone())
.pick_folder()
.await;
if let Some(result) = result {
self.path = result.path().to_path_buf();
}
GameConfig::set_game_dir(Some(self.path.clone()))
.await
.unwrap(); // TODO: remove unwrap
}
ChooseGameDirectoryMsg::Next => {
let _ = sender.output(SetupPageMsg::GoToDownloadComponentPage);
}
}
}
}

View File

@ -0,0 +1,465 @@
use std::{convert::identity, usize};
use arboard::Clipboard;
use babylonia_terminal_sdk::{
components::{
dxvk_component::{self, DXVKComponent},
proton_component::{self, ProtonComponent},
},
game_config::GameConfig,
game_state::GameState,
utils::{
github_requester::{GithubRelease, GithubRequester},
kuro_prod_api::CurrentGameInfo,
},
};
use log::{debug, error, info};
use relm4::{
self,
gtk::{self, prelude::*},
prelude::*,
*,
};
use adw::prelude::*;
use libadwaita as adw;
use crate::{manager, ui::MAIN_WINDOW};
use super::SetupPageMsg;
#[derive(Debug)]
pub enum DownloadComponentsMsg {
UpdateProgressBar((u64, u64)), // current and max_progress
UpdateProgressBarMsg(String, Option<String>), // current msg and when done msg
ShowDoneMsg,
UpdateDownloadedComponentName(String),
UpdateCurrentlyInstalling(CurrentlyInstalling),
ShowError(String), // error message
Finish,
Quit,
}
#[derive(Debug, PartialEq, Eq)]
pub enum CurrentlyInstalling {
None,
Proton,
DXVK,
Fonts,
Denpendecies,
}
#[derive(Debug)]
pub struct DownloadComponentsPage {
// widgets
proton_combo: adw::ComboRow,
dxvk_combo: adw::ComboRow,
//error_dialog: Controller<CopyDialog>,
// values
proton_versions: Vec<GithubRelease>,
dxvk_versions: Vec<GithubRelease>,
selected_proton_version: Option<GithubRelease>,
selected_dxvk_version: Option<GithubRelease>,
game_config: GameConfig,
//progress_bar
progress_bar_reporter: std::sync::Arc<DownloadComponentProgressBarReporter>,
progress_bar_message: String,
fraction: f64,
show_progress_bar: bool,
// download part
installation_handler: WorkerController<manager::HandleComponentInstallation>,
downloaded_component_name: String,
currently_installing: CurrentlyInstalling,
msg_when_done: Option<String>,
}
#[relm4::component(async, pub)]
impl SimpleAsyncComponent for DownloadComponentsPage {
type Input = DownloadComponentsMsg;
type Output = SetupPageMsg;
type Init = ();
view! {
#[root]
gtk::Box {
adw::PreferencesPage {
set_hexpand: true,
#[watch]
set_visible: model.currently_installing == CurrentlyInstalling::None,
add = &adw::PreferencesGroup {
set_valign: gtk::Align::Center,
set_vexpand: true,
gtk::Label {
set_label: "Install components",
add_css_class: "title-1"
},
},
add = &adw::PreferencesGroup {
set_width_request: 500,
set_valign: gtk::Align::Center,
set_vexpand: true,
#[local_ref]
proton_combo -> adw::ComboRow {
set_title: "proton version",
set_model: Some(&gtk::StringList::new(model
.proton_versions
.iter()
.map(|r| r.tag_name.as_str())
.collect::<Vec<&str>>()
.as_slice())),
},
#[local_ref]
dxvk_combo -> adw::ComboRow {
set_title: "dxvk version",
set_model: Some(&gtk::StringList::new(model
.dxvk_versions
.iter()
.map(|r| r.tag_name.as_str())
.collect::<Vec<&str>>()
.as_slice())),
},
},
add = &adw::PreferencesGroup {
set_margin_vertical: 48,
gtk::Button {
set_css_classes: &["suggested-action", "pill"],
set_label: "Next",
set_hexpand: false,
set_width_request: 200,
connect_clicked => DownloadComponentsMsg::UpdateCurrentlyInstalling(CurrentlyInstalling::Proton),
},
},
},
adw::PreferencesPage {
set_hexpand: true,
#[watch]
set_visible: model.currently_installing != CurrentlyInstalling::None,
add = &adw::PreferencesGroup {
set_width_request: 500,
set_valign: gtk::Align::Center,
set_vexpand: true,
gtk::Label {
set_label: "Downloading and installing components",
add_css_class: "title-1"
},
},
add = &adw::PreferencesGroup {
set_valign: gtk::Align::Center,
set_vexpand: true,
adw::ActionRow {
set_title: "Proton",
#[watch]
set_subtitle: match &model.selected_proton_version {
Some(release) => &release.tag_name,
None => "WTF??!! there's no proton version found ????",
},
#[watch]
set_icon_name: if model.currently_installing != CurrentlyInstalling::Proton && model.game_config.is_wine_installed { Some("emblem-ok-symbolic") } else { None },
add_prefix = &gtk::Spinner {
set_spinning: true,
#[watch]
set_visible: model.currently_installing == CurrentlyInstalling::Proton,
}
},
adw::ActionRow {
set_title: "DXVK",
#[watch]
set_subtitle: match &model.selected_dxvk_version {
Some(release) => &release.tag_name,
None => "WTF??!! there's no proton version found ????",
},
#[watch]
set_icon_name: if model.currently_installing != CurrentlyInstalling::DXVK && model.game_config.is_dxvk_installed { Some("emblem-ok-symbolic") } else { None },
add_prefix = &gtk::Spinner {
set_spinning: true,
#[watch]
set_visible: model.currently_installing == CurrentlyInstalling::DXVK,
}
},
adw::ActionRow {
#[watch]
set_title: "Fonts",
set_subtitle: "Arial",
#[watch]
set_icon_name: if model.currently_installing != CurrentlyInstalling::Fonts && model.game_config.is_font_installed { Some("emblem-ok-symbolic") } else { None },
add_prefix = &gtk::Spinner {
set_spinning: true,
#[watch]
set_visible: model.currently_installing == CurrentlyInstalling::Fonts,
}
},
adw::ActionRow {
#[watch]
set_title: "Denpendecies",
set_subtitle: "vcrun2022",
#[watch]
set_icon_name: if model.currently_installing != CurrentlyInstalling::Denpendecies && model.game_config.is_dependecies_installed { Some("emblem-ok-symbolic") } else { None },
add_prefix = &gtk::Spinner {
set_spinning: true,
#[watch]
set_visible: model.currently_installing == CurrentlyInstalling::Denpendecies,
}
}
},
add = &adw::PreferencesGroup {
set_valign: gtk::Align::Center,
set_vexpand: true,
gtk::ProgressBar {
#[watch]
set_fraction: model.fraction,
#[watch]
set_visible: model.currently_installing != CurrentlyInstalling::Fonts && model.currently_installing != CurrentlyInstalling::Denpendecies,
#[watch]
set_text: Some(&model.progress_bar_message),
set_show_text: true,
},
gtk::Box {
set_halign: gtk::Align::Center,
set_orientation: gtk::Orientation::Horizontal,
gtk::Label {
#[watch]
set_visible: model.currently_installing == CurrentlyInstalling::Fonts || model.currently_installing == CurrentlyInstalling::Denpendecies,
#[watch]
set_label: &model.progress_bar_message,
add_css_class: "title-3",
},
gtk::Spinner {
set_spinning: true,
set_margin_start: 24,
#[watch]
set_visible: model.currently_installing == CurrentlyInstalling::Fonts || model.currently_installing == CurrentlyInstalling::Denpendecies,
}
}
}
},
}
}
async fn init(
_: Self::Init,
root: Self::Root,
sender: AsyncComponentSender<Self>,
) -> AsyncComponentParts<Self> {
let proton_releases = ProtonComponent::get_github_releases(
proton_component::PROTON_DEV,
proton_component::PROTON_REPO,
)
.await
.unwrap(); //TODO: remove unwrap()
let dxvk_releases =
DXVKComponent::get_github_releases(dxvk_component::DXVK_DEV, dxvk_component::DXVK_REPO)
.await
.unwrap(); //TODO: remove unwrap()
let model = DownloadComponentsPage {
proton_combo: adw::ComboRow::new(),
dxvk_combo: adw::ComboRow::new(),
proton_versions: proton_releases,
dxvk_versions: dxvk_releases,
selected_proton_version: None,
selected_dxvk_version: None,
game_config: GameConfig::get_config().await,
progress_bar_reporter: DownloadComponentProgressBarReporter::create(sender.clone()),
progress_bar_message: String::new(),
fraction: 0.0,
show_progress_bar: false,
installation_handler: manager::HandleComponentInstallation::builder()
.detach_worker(())
.forward(sender.input_sender(), identity),
downloaded_component_name: String::new(),
currently_installing: CurrentlyInstalling::None,
msg_when_done: None,
};
let proton_combo = &model.proton_combo;
let dxvk_combo = &model.dxvk_combo;
let widgets = view_output!();
AsyncComponentParts { widgets, model }
}
async fn update(&mut self, message: Self::Input, sender: AsyncComponentSender<Self>) -> () {
match message {
DownloadComponentsMsg::UpdateDownloadedComponentName(name) => {
self.downloaded_component_name = name;
}
DownloadComponentsMsg::UpdateProgressBar((current, max_progress)) => {
if self.currently_installing != CurrentlyInstalling::Fonts
&& self.currently_installing != CurrentlyInstalling::Denpendecies
{
self.fraction = if current == 0 {
0.0
} else {
current as f64 / max_progress as f64
};
self.progress_bar_message = format!(
"Downloading {} : {:.2}%",
self.downloaded_component_name,
self.fraction * 100.0
);
} else {
self.progress_bar_message =
format!("Downloading {}", self.downloaded_component_name);
}
}
DownloadComponentsMsg::UpdateProgressBarMsg(message, message_when_done) => {
self.progress_bar_message = message;
self.msg_when_done = message_when_done;
}
DownloadComponentsMsg::ShowDoneMsg => {
if let Some(msg) = self.msg_when_done.clone() {
self.progress_bar_message = msg;
}
}
DownloadComponentsMsg::UpdateCurrentlyInstalling(currently_installing) => {
self.game_config = GameConfig::get_config().await;
self.currently_installing = currently_installing;
}
DownloadComponentsMsg::ShowError(message) => {
let dialog = unsafe {
adw::MessageDialog::new(
MAIN_WINDOW.as_ref(),
Some("Error while downloading components"),
Some(&message),
)
};
dialog.add_response("close", "Close");
dialog.add_response("copy", "Copy");
dialog.set_response_appearance("copy", adw::ResponseAppearance::Suggested);
dialog.connect_response(Some("copy"), move |_, _| {
if let Err(err) = Clipboard::new().unwrap().set_text(&message.clone()) {
error!("Failed to copy the error to the clipboard : {}", err);
}
});
dialog.present();
}
DownloadComponentsMsg::Finish => {
let _ = sender.output(SetupPageMsg::Finish);
}
DownloadComponentsMsg::Quit => relm4::main_application().quit(),
}
if self.selected_proton_version.is_none()
&& self.selected_dxvk_version.is_none()
&& self.currently_installing != CurrentlyInstalling::None
{
let proton_index = self.proton_combo.selected() as usize;
let dxvk_index = self.dxvk_combo.selected() as usize;
let proton_release = self.proton_versions[proton_index].clone();
let dxvk_release = self.dxvk_versions[dxvk_index].clone();
self.selected_proton_version = Some(proton_release);
self.selected_dxvk_version = Some(dxvk_release);
let _ = self.installation_handler.sender().send(
manager::HandleComponentInstallationMsg::StartInstallation((
proton_index,
dxvk_index,
self.progress_bar_reporter.clone(),
)),
);
}
}
}
#[derive(Debug)]
struct ProgressBarReporterPrivate {
max_progress: Option<u64>,
}
#[derive(Debug)]
pub struct DownloadComponentProgressBarReporter {
private: std::sync::Mutex<Option<ProgressBarReporterPrivate>>,
sender: relm4::AsyncComponentSender<DownloadComponentsPage>,
}
impl DownloadComponentProgressBarReporter {
fn create(page: relm4::AsyncComponentSender<DownloadComponentsPage>) -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
private: std::sync::Mutex::new(None),
sender: page,
})
}
}
impl downloader::progress::Reporter for DownloadComponentProgressBarReporter {
fn setup(&self, max_progress: Option<u64>, message: &str) {
let private = ProgressBarReporterPrivate { max_progress };
let mut guard = self.private.lock().unwrap();
*guard = Some(private);
}
fn progress(&self, current: u64) {
if let Some(p) = self.private.lock().unwrap().as_mut() {
self.sender.input(DownloadComponentsMsg::UpdateProgressBar((
current,
p.max_progress.unwrap(),
)));
}
}
fn set_message(&self, message: &str) {}
fn done(&self) {
self.sender.input(DownloadComponentsMsg::ShowDoneMsg);
let mut guard = self.private.lock().unwrap();
*guard = None;
}
}

View File

@ -0,0 +1,119 @@
use std::convert::identity;
use babylonia_terminal_sdk::{game_config::GameConfig, game_state::GameState};
use choose_game_directory::ChooseGameDirectoryPage;
use download_components::DownloadComponentsPage;
use libadwaita::prelude::{OrientableExt, WidgetExt};
use relm4::{
prelude::{
adw, gtk, AsyncComponent, AsyncComponentController, AsyncComponentParts, AsyncController,
SimpleAsyncComponent,
},
AsyncComponentSender, Component, ComponentController, Controller,
};
use welcome::WelcomePage;
use crate::ui::MainWindowMsg;
mod choose_game_directory;
pub mod download_components;
mod welcome;
#[derive(Debug)]
pub enum SetupPageMsg {
GoToChooseGameDirectoryPage,
GoToDownloadComponentPage,
Finish,
}
pub struct SetupPage {
game_state: GameState,
welcome_page: Controller<welcome::WelcomePage>,
choose_game_directory_page: AsyncController<choose_game_directory::ChooseGameDirectoryPage>,
download_components_page: AsyncController<download_components::DownloadComponentsPage>,
carousel: adw::Carousel,
}
#[relm4::component(async, pub)]
impl SimpleAsyncComponent for SetupPage {
type Input = SetupPageMsg;
type Output = MainWindowMsg;
type Init = GameState;
view! {
#[root]
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_hexpand: true,
set_vexpand: true,
#[local_ref]
carousel -> adw::Carousel {
set_allow_mouse_drag: false,
set_allow_long_swipes: false,
set_allow_scroll_wheel: false,
append = model.welcome_page.widget(),
append = model.choose_game_directory_page.widget(),
append = model.download_components_page.widget(),
},
adw::CarouselIndicatorDots {
set_carousel: Some(&carousel),
set_height_request: 32,
},
},
}
async fn init(
game_state: GameState,
root: Self::Root,
sender: AsyncComponentSender<Self>,
) -> AsyncComponentParts<Self> {
let welcome_page = WelcomePage::builder()
.launch(())
.forward(sender.input_sender(), identity);
let choose_game_directory_page = ChooseGameDirectoryPage::builder()
.launch(())
.forward(sender.input_sender(), identity);
let download_components_page = DownloadComponentsPage::builder()
.launch(())
.forward(sender.input_sender(), identity);
let carousel = adw::Carousel::new();
carousel.scroll_to(welcome_page.widget(), true);
let model = SetupPage {
welcome_page,
choose_game_directory_page,
download_components_page,
game_state,
carousel: carousel.clone(),
};
let widgets = view_output!();
AsyncComponentParts { widgets, model }
}
async fn update(&mut self, message: Self::Input, sender: AsyncComponentSender<Self>) {
self.game_state = GameState::get_current_state().await.unwrap(); // TODO: delete this unwrap()
match message {
SetupPageMsg::GoToChooseGameDirectoryPage => {
self.carousel
.scroll_to(self.choose_game_directory_page.widget(), true);
}
SetupPageMsg::GoToDownloadComponentPage => {
self.carousel
.scroll_to(self.download_components_page.widget(), true);
}
SetupPageMsg::Finish => {
sender.output(MainWindowMsg::UpdateGameState);
}
}
}
}

View File

@ -0,0 +1,86 @@
use libadwaita::prelude::{ButtonExt, PreferencesPageExt, WidgetExt};
use relm4::{adw, gtk, ComponentParts, ComponentSender, RelmWidgetExt, SimpleComponent};
use super::SetupPageMsg;
use crate::APP_RESOURCE_PATH;
#[derive(Debug)]
pub enum WelcomePageMsg {
Next,
}
pub struct WelcomePage;
#[relm4::component(pub)]
impl SimpleComponent for WelcomePage {
type Input = WelcomePageMsg;
type Output = SetupPageMsg;
type Init = ();
view! {
#[root]
adw::PreferencesPage {
set_hexpand: true,
add = &adw::PreferencesGroup {
set_valign: gtk::Align::Center,
set_vexpand: true,
gtk::Picture {
set_resource: Some(&format!("{APP_RESOURCE_PATH}/icons/hicolor/scalable/apps/icon.png")),
set_vexpand: true,
},
gtk::Label {
set_label: "Babylonia Terminal",
set_margin_top: 24,
add_css_class: "title-1",
},
gtk::Label {
set_label: "We need to do some setup before to be able to play",
set_justify: gtk::Justification::Center,
set_wrap: true,
set_margin_top: 32
},
},
add = &adw::PreferencesGroup {
set_margin_vertical: 48,
gtk::Button {
set_css_classes: &["suggested-action", "pill"],
set_label: "Next",
set_hexpand: false,
set_width_request: 200,
connect_clicked => WelcomePageMsg::Next,
},
},
},
}
fn init(
init: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let model = WelcomePage {};
let widgets = view_output!();
ComponentParts { widgets, model }
}
fn update(&mut self, message: Self::Input, sender: ComponentSender<Self>) {
match message {
WelcomePageMsg::Next => sender
.output(SetupPageMsg::GoToChooseGameDirectoryPage)
.unwrap(),
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -15,7 +15,7 @@ anyhow = "1.0.81"
chksum-md5 = { version = "0.0.0", features = ["reader"] }
dirs = "5.0.1"
dotenv = "0.15.0"
downloader = { git = "https://github.com/ALEZ-DEV/downloader" } # version = "0.2.7",
downloader = { workspace = true }
flate2 = "1.0.28"
fs_extra = "1.3.0"
futures = "0.3.30"

View File

@ -54,8 +54,7 @@ impl GameComponent {
let _permit = semaphore.acquire().await;
for resource_to_check in cloned_resources {
let file_path =
game_dir.join(resource_to_check.dest.clone().strip_prefix("/").unwrap());
let file_path = game_dir.join(resource_to_check.dest.clone());
if file_path.try_exists().unwrap() {
let blocking_file_path = file_path.clone();
@ -145,7 +144,7 @@ impl ComponentDownloader for GameComponent {
.iter()
.map(|r| {
output_dir
.join(r.dest.strip_prefix("/").unwrap())
.join(r.dest.clone())
.parent()
.unwrap()
.to_path_buf()

View File

@ -110,6 +110,9 @@ impl ProtonComponent {
let mut proton =
wincompatlib::prelude::Proton::new(self.path.clone(), Some(prefix.clone()));
let steam_location = Self::get_steam_location()?;
debug!("Steam location used -> {:?}", steam_location);
proton.steam_client_path = Some(steam_location);
proton.init_prefix(Some(prefix)).unwrap();
@ -117,11 +120,16 @@ impl ProtonComponent {
}
fn get_steam_location() -> Result<PathBuf, String> {
let specified_steam_location = std::env::var("BT_STEAM_CLIENT_PATH");
if let Ok(location) = specified_steam_location {
return Ok(PathBuf::from(location));
}
let location_to_check = [
dirs::home_dir().unwrap().join(".steam/steam"),
dirs::home_dir()
.unwrap()
.join("/.var/app/com.valvesoftware.Steam/steam"), // for the flatpak version of steam
.join(".var/app/com.valvesoftware.Steam/steam"), // for the flatpak version of steam
];
for location in location_to_check {

View File

@ -23,6 +23,22 @@ use crate::{
utils::{get_game_name, get_game_name_with_executable, github_requester::GithubRequester},
};
pub struct EnvironmentVariable {
name: String,
value: String,
}
impl EnvironmentVariable {
pub fn parse(variable: &str) -> Self {
let split: Vec<&str> = variable.split('=').collect();
Self {
name: split[0].to_string(),
value: split[1].to_string(),
}
}
}
pub struct GameManager;
impl GameManager {
@ -152,9 +168,10 @@ impl GameManager {
proton: &Proton,
game_dir: PathBuf,
options: Option<String>,
env_variables: Vec<EnvironmentVariable>,
show_logs: bool,
) {
let proton_version = proton.wine().version().unwrap();
) -> anyhow::Result<()> {
let proton_version = proton.wine().version()?;
let binary_path = game_dir
.join(get_game_name())
.join(get_game_name_with_executable());
@ -162,18 +179,14 @@ impl GameManager {
debug!("Wine version : {:?}", proton_version);
let mut child = if let Some(custom_command) = options {
Self::run(proton, binary_path, Some(custom_command))
.await
.unwrap()
Self::run(proton, binary_path, Some(custom_command), env_variables).await?
} else {
if let Some(custom_command) = GameConfig::get_launch_options().await.unwrap() {
Self::run(proton, binary_path, Some(custom_command))
.await
.unwrap()
Self::run(proton, binary_path, Some(custom_command), env_variables).await?
} else {
Self::run(proton, binary_path, None).await.unwrap()
Self::run(proton, binary_path, None, env_variables).await?
}
};
}?;
let log_stdout = Arc::new(Mutex::new(None));
let log_stderr = Arc::new(Mutex::new(None));
@ -274,13 +287,16 @@ impl GameManager {
.write_all(to_write)
.await
.expect("Failed to write the output to the log file");
Ok(())
}
async fn run(
proton: &Proton,
binary_path: PathBuf,
custom_command: Option<String>,
) -> Result<Child, std::io::Error> {
env_variables: Vec<EnvironmentVariable>,
) -> anyhow::Result<Result<Child, std::io::Error>> {
let mut command: Vec<&str> = vec![];
let proton_path = GameConfig::get_config_directory()
@ -300,10 +316,11 @@ impl GameManager {
let tokens: Vec<&str> = launch_option.split_whitespace().collect();
// position of the %command%
let index = tokens
.iter()
.position(|&s| s == "%command%")
.expect("You forget to put %command% in your custom launch command");
let index = if let Some(v) = tokens.iter().position(|&s| s == "%command%") {
v
} else {
anyhow::bail!("You forget to put %command% in your custom launch command");
};
let start_command = tokens[0..index].to_vec();
let mut end_command = tokens[(index + 1)..tokens.len()].to_vec();
@ -318,14 +335,14 @@ impl GameManager {
debug!("Command preview -> {}", command.join(" "));
Command::new(command[0])
Ok(Command::new(command[0])
.args(&command[1..command.len()])
.envs(proton.get_envs())
.env("PROTON_LOG", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.spawn())
}
}

View File

@ -1,6 +1,6 @@
use crate::{game_config::GameConfig, utils::kuro_prod_api::GameInfo};
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum GameState {
ProtonNotInstalled,
DXVKNotInstalled,
@ -46,4 +46,11 @@ impl GameState {
Ok(GameState::GameInstalled)
}
pub fn is_environment_ready(&self) -> bool {
self == &GameState::GameNotInstalled
|| self == &GameState::GameNeedUpdate
|| self == &GameState::GameNotPatched
|| self == &GameState::GameInstalled
}
}

View File

@ -2,6 +2,7 @@ use std::path::PathBuf;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use tokio::fs::read_to_string;
use tokio::io::AsyncWriteExt;
@ -12,22 +13,36 @@ use crate::game_config::GameConfig;
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GameInfo {
pub chunk_download_switch: i64,
pub key_file_check_switch: i64,
pub default: Default,
#[serde(rename = "RHIOptionSwitch")]
pub rhioption_switch: i64,
pub resources_login: ResourcesLogin,
pub predownload_switch: i64,
#[serde(rename = "RHIOptionList")]
pub rhioption_list: Vec<Value>,
pub experiment: Experiment,
pub check_exe_is_running: i64,
pub hash_cache_check_acc_switch: i64,
pub key_file_check_list: Vec<String>,
pub fingerprints: Vec<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Default {
pub sample_hash_switch: i64,
pub cdn_list: Vec<CdnList>,
pub resources_base_path: String,
pub changelog: Changelog,
pub resources: String,
pub resources_base_path: String,
pub resources_exclude_path_need_update: Vec<String>,
pub config: Config,
pub resources_diff: ResourcesDiff,
pub resources_exclude_path: Vec<String>,
pub resources_exclude_path_need_update: Vec<String>,
pub sample_hash_switch: i64,
pub version: String,
pub changelog_visible: i64,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
@ -44,10 +59,58 @@ pub struct CdnList {
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Changelog {
#[serde(rename = "zh-Hans")]
pub zh_hans: String,
pub en: String,
pub struct Changelog {}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Config {
pub index_file_md5: String,
pub un_compress_size: i64,
pub base_url: String,
pub size: i64,
pub patch_type: String,
pub zip_config: ZipConfig,
pub index_file: String,
pub resources_exclude_path_need_update: Vec<String>,
pub version: String,
pub resources_exclude_path: Vec<String>,
pub patch_config: Vec<PatchConfig>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZipConfig {
pub index_file_md5: String,
pub un_compress_size: i64,
pub ext: Ext,
pub base_url: String,
pub size: i64,
pub index_file: String,
pub version: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Ext {
pub max_file_size: i64,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PatchConfig {
pub index_file_md5: String,
pub un_compress_size: i64,
pub ext: Ext2,
pub base_url: String,
pub size: i64,
pub index_file: String,
pub version: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Ext2 {
pub max_file_size: i64,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
@ -61,16 +124,47 @@ pub struct ResourcesDiff {
#[serde(rename_all = "camelCase")]
pub struct CurrentGameInfo {
pub file_name: String,
pub md5: String,
pub version: String,
pub md5: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PreviousGameInfo {
pub file_name: String,
pub md5: String,
pub version: String,
pub md5: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourcesLogin {
pub host: String,
pub login_switch: i64,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Experiment {
pub download: Download,
#[serde(rename = "res_check")]
pub res_check: ResCheck,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Download {
pub download_cdn_select_test_duration: String,
pub download_read_block_timeout: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResCheck {
pub file_chunk_check_switch: String,
pub file_size_check_switch: String,
pub res_valid_check_time_out: String,
pub file_check_white_list_config: String,
}
// Resources ---------------------------------------------------------------------
@ -79,7 +173,6 @@ pub struct PreviousGameInfo {
#[serde(rename_all = "camelCase")]
pub struct Resources {
pub resource: Vec<Resource>,
pub sample_hash_info: SampleHashInfo,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
@ -99,12 +192,11 @@ pub struct SampleHashInfo {
}
// end data ---------------------------------------------------------------------
static URL: &str = concat!(
"https://prod-alicdn-gamestarter.k",
"uro",
"gam",
"e.com/pcstarter/prod/game/G143/4/index.json"
"e.com/launcher/game/G143/50015_LWdk9D2Ep9mpJmqBZZkcPBU2YNraEWBQ/index.json"
);
impl GameInfo {
@ -137,7 +229,9 @@ impl GameInfo {
}
pub fn get_resource_base_path(&self) -> String {
self.default.resources_base_path.clone()
let mut result = self.default.resources_base_path.clone();
result.push('/');
result
}
pub async fn fetch_resources(&self) -> anyhow::Result<Resources> {

View File

@ -0,0 +1,12 @@
[package]
name = "babylonia-terminal"
version = "0.1.0"
edition = "2021"
[dependencies]
babylonia-terminal-gui = { path = "./../babylonia-terminal-gui" }
babylonia-terminal-cli = { path = "./../babylonia-terminal-cli" }
log = "0.4.22"
simple_logger = "5.0.0"
tokio = { version = "1.37.0", features = ["full"] }
clap = "4.5.23"

View File

@ -1,17 +1,10 @@
use babylonia_terminal_sdk::game_config::GameConfig;
use clap::Parser;
use log::{debug, LevelFilter};
use log::{debug, info, LevelFilter};
use simple_logger::SimpleLogger;
mod arguments;
pub mod game;
pub mod reporter;
pub mod utils;
fn main() {
let args = babylonia_terminal_cli::arguments::Args::parse();
use crate::arguments::Args;
#[tokio::main]
async fn main() {
let simple_logger = SimpleLogger::new()
.with_module_level("hyper", LevelFilter::Off)
.with_module_level("hyper_util", LevelFilter::Off)
@ -20,20 +13,16 @@ async fn main() {
.with_module_level("minreq", LevelFilter::Off)
.with_module_level("tokio_utils", LevelFilter::Off);
if cfg!(debug_assertions) {
if args.debug || cfg!(debug_assertions) {
simple_logger.init().unwrap();
info!("Debug messages enabled");
} else {
simple_logger.with_level(LevelFilter::Info).init().unwrap();
}
let args = Args::parse();
debug!("Launch option -> {:?}", args.options);
if let Some(command) = args.set_options {
GameConfig::set_launch_options(Some(command))
.await
.expect("Failed to save launch options into the config file");
if args.gui {
babylonia_terminal_gui::run();
} else {
babylonia_terminal_cli::run();
}
game::run(args.options, args.logs).await;
}

View File

@ -1,57 +0,0 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
# Ignore platforms
/linux/*
!/linux/my_application.cc
# Misc
/test
# Rust related
.cargo/
target/
# Generated messages
*/**/messages/

View File

@ -1,30 +0,0 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "54e66469a933b60ddf175f858f82eaeb97e48c8d"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 54e66469a933b60ddf175f858f82eaeb97e48c8d
base_revision: 54e66469a933b60ddf175f858f82eaeb97e48c8d
- platform: linux
create_revision: 54e66469a933b60ddf175f858f82eaeb97e48c8d
base_revision: 54e66469a933b60ddf175f858f82eaeb97e48c8d
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'

View File

@ -1,27 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.1.2] - 2024-10-28
### Changed
- Only install Arial font from now on instead of the whole corefonts library
### Added
- Added gamescope path library to the flatpak version of the launcher
## [0.1.1] - 2024-10-23
### Added
- Notice for new release
[unreleased]: https://github.com/ALEZ-DEV/Babylonia-terminal/compare/0.1.1...HEAD
[0.1.1]: https://github.com/ALEZ-DEV/Babylonia-terminal/compare/0.1.1

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +0,0 @@
# This file is used for telling Rust-related tools
# where various Rust crates are.
# This also unifies `./target` output folder and
# various Rust configurations.
[workspace]
members = ["./native/*"]
resolver = "2"

View File

@ -1,39 +0,0 @@
# How to compile the GUI version
!! **Disclaimer :** this might not work on your steam deck, a Flatpak version is distributed, [see instruction on how to install it!](https://github.com/ALEZ-DEV/Babylonia-terminal/wiki/Installation#installing-via-flatpak)
## Requirement
You need the [base](https://github.com/ALEZ-DEV/Babylonia-terminal/wiki/Compilation-requirement) requirement
You will need [Flutter](https://flutter.dev/) in order to compile the GUI version
Install [Rinf](https://github.com/cunarist/rinf) with **Cargo** :
```bash
cargo install rinf
```
And check if all the requirement are installed successfully :
```bash
rustc --version
flutter doctor
```
## Compile
First generate all the necessary messages :
```bash
rinf message
```
Generate all the necessary linux file for compilation :
```bash
flutter create --platform=linux .
```
Then compile the project :
```bash
flutter run
```

View File

@ -1,28 +0,0 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

View File

@ -1,207 +0,0 @@
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:yaru/yaru.dart';
import './screens/screens.dart';
import './screens/setup_screen.dart';
import './providers/providers.dart';
import './models/error_reporter.dart';
import './models/game.dart';
import './models/release_notice.dart';
import './widgets/release_notice_widget.dart';
class BabyloniaLauncher extends StatelessWidget {
BabyloniaLauncher(
{super.key,
required this.settingsProvider,
required this.gameStateProvider});
final SettingsProvider settingsProvider;
final GameStateProvider gameStateProvider;
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
@override
Widget build(BuildContext context) {
ErrorReporter.listenAllRustError(navigatorKey);
gameStateProvider.updateSetup();
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => settingsProvider,
),
ChangeNotifierProvider(
create: (context) => gameStateProvider,
),
],
child: YaruTheme(
builder: (context, yaru, child) => MaterialApp(
navigatorKey: navigatorKey,
title: "Babylonia Terminal",
debugShowCheckedModeBanner: false,
theme: yaru.theme,
darkTheme: yaru.darkTheme,
themeMode: ThemeMode.system,
highContrastTheme: yaruHighContrastLight,
highContrastDarkTheme: yaruHighContrastDark,
home: Provider.of<GameStateProvider>(context).haveToSetup
? const SetupScreen()
: const Menu(),
),
),
);
}
}
class Menu extends StatefulWidget {
const Menu({super.key});
@override
State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> {
int _selectedIndex = 0;
@override
void didChangeDependencies() async {
final provider = Provider.of<SettingsProvider>(context, listen: false);
final pkgsInfo = await PackageInfo.fromPlatform();
final currentVersion = pkgsInfo.version;
if (provider.lastVersion != currentVersion) {
final releaseInfo = await ReleaseNoticeInfo.getInfo(currentVersion);
showDialog<void>(
context: context,
builder: (context) =>
ReleaseNotice(currentVersion: currentVersion, info: releaseInfo),
);
provider.lastVersion = currentVersion;
}
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
List<Widget> items = Screens.drawerItem(
selectedIndex: _selectedIndex,
onSelected: (index) {
setState(() => _selectedIndex = index);
Navigator.of(context).pop();
},
);
items.insert(
0,
Center(
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
border: Border(
bottom: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
),
),
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 50.0,
),
child: Image.asset(
'assets/images/Lee6.png',
),
),
const Text(
"Babylonia Terminal",
style: TextStyle(fontSize: 24),
),
],
),
),
),
),
),
);
final window = YaruWindow.of(context);
return ChangeNotifierProvider(
create: (context) => Game(),
child: Stack(
children: [
Scaffold(
drawer: Drawer(
child: ListView(
children: items,
),
),
appBar: AppBar(
title: const Text("Babylonia Terminal"),
centerTitle: true,
actions: [
Padding(
padding: const EdgeInsets.only(right: 14.0),
child: YaruWindowControl(
type: YaruWindowControlType.minimize,
platform: YaruWindowControlPlatform.yaru,
onTap: () async {
final state = await window.state();
if (state.isMinimizable ?? false) window.minimize();
},
),
),
StreamBuilder<YaruWindowState>(
stream: window.states(),
builder: (context, snapshot) {
final state = snapshot.data;
return Padding(
padding: const EdgeInsets.only(right: 14.0),
child: YaruWindowControl(
type: (state?.isMinimizable ?? false)
? YaruWindowControlType.maximize
: YaruWindowControlType.restore,
platform: YaruWindowControlPlatform.yaru,
onTap: () async {
(state?.isMinimizable ?? false)
? window.maximize()
: window.restore();
},
),
);
},
),
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: YaruWindowControl(
type: YaruWindowControlType.close,
platform: YaruWindowControlPlatform.yaru,
onTap: () async {
final state = await window.state();
if (state.isClosable ?? false) window.close();
},
),
),
],
),
body: Screens.getCurrent(_selectedIndex),
),
Padding(
padding: const EdgeInsets.only(right: 115.0, left: 60.0),
child: GestureDetector(
onPanStart: (_) => window.drag(),
child: const SizedBox(
height: 60,
),
),
),
],
),
);
}
}

View File

@ -1,27 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:media_kit/media_kit.dart';
import 'package:rinf/rinf.dart';
import 'package:yaru_window/yaru_window.dart';
import './app.dart';
import './messages/generated.dart';
import './providers/providers.dart';
void main() async {
await initializeRust(assignRustSignal);
await YaruWindow.ensureInitialized();
WidgetsFlutterBinding.ensureInitialized();
MediaKit.ensureInitialized();
final SettingsProvider settings = SettingsProvider();
await settings.init();
final GameStateProvider gameState = GameStateProvider();
await gameState.updateGameState();
runApp(BabyloniaLauncher(
settingsProvider: settings,
gameStateProvider: gameState,
));
}

View File

@ -1,54 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'package:babylonia_terminal_launcher/models/config.dart';
import 'package:http/http.dart' as http;
import './../providers/providers.dart';
class Background {
String path;
Background._({required this.path});
static Future<Background> get(SettingsProvider provider) async {
final json = await _fetchMainMenu();
final info = json['pcTopPicture'];
final backgroundId = info['topPictureId'];
final videoLink = info['backgroundVideo'];
final path = "${Config.instance.path}/background.mp4";
if (provider.backgroundId == null ||
provider.backgroundId != backgroundId) {
provider.backgroundId = backgroundId;
await _updateVideo(videoLink, path);
}
return Background._(path: path);
}
static Future<Map<String, dynamic>> _fetchMainMenu() async {
// ignore: prefer_interpolation_to_compose_strings, prefer_adjacent_string_concatenation
final response = await http.get(
Uri.parse('https://media-cdn-zspms.' +
'k' +
'u' +
'r' +
'o' +
'game.net/pnswebsite/website2.0/json/G167/MainMenu.json'),
);
return jsonDecode(response.body);
}
static _updateVideo(String link, String path) async {
final response = await http.get(Uri.parse(link));
final file = File(path);
if (await file.exists()) {
// just to be sure to overwrite the file
await file.delete();
await file.create();
}
await file.writeAsBytes(response.bodyBytes);
}
}

View File

@ -1,46 +0,0 @@
import 'package:babylonia_terminal_launcher/messages/config.pb.dart';
class Config {
String path;
static late Config instance;
Config._({required this.path});
static bool _isLoadingConfig = false;
static Future update() async {
if (!_isLoadingConfig) {
_isLoadingConfig = true;
ConfigInput().sendSignalToRust();
final stream = ConfigOutput.rustSignalStream;
await for (final rustSignal in stream) {
instance = Config._(
path: rustSignal.message.configPath,
);
break;
}
_isLoadingConfig = false;
}
}
static bool _isLoadingGetLaunchOptions = false;
static Future<String?> getLaunchOptions() async {
if (!_isLoadingGetLaunchOptions) {
_isLoadingGetLaunchOptions = true;
GetLaunchOptionsInput().sendSignalToRust();
final stream = GetLaunchOptionsOutput.rustSignalStream;
await for (final rustSignal in stream) {
_isLoadingGetLaunchOptions = false;
return rustSignal.message.launchOptions;
}
}
return null;
}
static void setLaunchOptions(String? newLaunchOptions) {
SetLaunchOptionsInput(launchOptions: newLaunchOptions).sendSignalToRust();
}
}

View File

@ -1,23 +0,0 @@
import 'package:flutter/material.dart';
import './../messages/steps/dependencies.pb.dart';
import './../providers/providers.dart';
enum DependenciesInstallationState {
idle,
installing,
}
class Dependencies with ChangeNotifier {
DependenciesInstallationState dependeciesState =
DependenciesInstallationState.idle;
Future startInstallation(GameStateProvider gameState) async {
StartDependenciesInstallation().sendSignalToRust();
final stream = NotifyDependenciesSuccessfullyInstalled.rustSignalStream;
await for (final _ in stream) {
gameState.updateGameState();
break;
}
}
}

View File

@ -1,53 +0,0 @@
import 'package:fixnum/fixnum.dart';
import 'package:flutter/material.dart';
import './../messages/steps/dxvk.pb.dart';
import './../providers/providers.dart';
enum DXVKInstallationState {
idle,
downloading,
decompressing,
}
class DXVK with ChangeNotifier {
DXVKInstallationState dxvkState = DXVKInstallationState.idle;
Int64 currentProgress = Int64(0);
Int64 maxProgress = Int64(0);
Future startInstallation(
GameStateProvider gameStateProvider, String protonVersion) async {
StartDXVKInstallation(protonVersion: protonVersion).sendSignalToRust();
final progressStream = DXVKDownloadProgress.rustSignalStream;
await for (final rustSignal in progressStream) {
currentProgress = rustSignal.message.current;
maxProgress = rustSignal.message.max;
if (dxvkState == DXVKInstallationState.idle) {
dxvkState = DXVKInstallationState.downloading;
}
notifyListeners();
if (currentProgress >= maxProgress) {
break;
}
}
final notificationDecompressingStream =
NotifyDXVKStartDecompressing.rustSignalStream;
await for (final _ in notificationDecompressingStream) {
dxvkState = DXVKInstallationState.decompressing;
notifyListeners();
break;
}
final notificationInstalledStream =
NotifyDXVKSuccessfullyInstalled.rustSignalStream;
await for (final _ in notificationInstalledStream) {
gameStateProvider.updateGameState();
break;
}
}
}

View File

@ -1,56 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_highlight/flutter_highlight.dart';
import 'package:flutter_highlight/themes/vs.dart';
import 'package:flutter_highlight/themes/vs2015.dart';
import 'package:yaru/icons.dart';
import 'package:yaru/widgets.dart';
import './../messages/error.pb.dart';
class ErrorReporter {
static Future listenAllRustError(
GlobalKey<NavigatorState> navigatorState) async {
final stream = ReportError.rustSignalStream;
await for (final rustSignal in stream) {
final context = navigatorState.currentState!.overlay!.context;
await showDialog<void>(
context: context,
builder: (context) => AlertDialog(
titlePadding: EdgeInsets.zero,
title: YaruDialogTitleBar(
title: const Text('Error'),
isClosable: true,
leading: Center(
child: YaruIconButton(
icon: const Icon(YaruIcons.copy),
tooltip: 'Copy',
onPressed: () async {
Clipboard.setData(
ClipboardData(text: rustSignal.message.errorMessage),
);
},
),
),
),
contentPadding: EdgeInsets.zero,
content: SizedBox(
height: 400,
width: 700,
child: HighlightView(
rustSignal.message.errorMessage,
language: '',
theme: Theme.of(context).brightness == Brightness.dark
? vs2015Theme
: vsTheme,
padding: const EdgeInsets.all(12),
textStyle: const TextStyle(
fontSize: 16,
),
),
),
),
);
}
}
}

View File

@ -1,38 +0,0 @@
import 'package:fixnum/fixnum.dart';
import 'package:flutter/material.dart';
import './../messages/steps/fonts.pb.dart';
import './../providers/providers.dart';
enum FontsInstallationState {
idle,
installing,
}
class Fonts with ChangeNotifier {
FontsInstallationState fontsState = FontsInstallationState.idle;
Int64 currentProgress = Int64(0);
Int64 maxProgress = Int64(0);
Future startInstallation(GameStateProvider gameState) async {
StartFontsInstallation().sendSignalToRust();
final stream = FontsInstallationProgress.rustSignalStream;
await for (final rustSignal in stream) {
maxProgress = rustSignal.message.max;
currentProgress = rustSignal.message.current;
if (fontsState == FontsInstallationState.idle) {
fontsState = FontsInstallationState.installing;
}
notifyListeners();
if (currentProgress >= maxProgress) {
break;
}
}
gameState.updateGameState();
}
}

View File

@ -1,77 +0,0 @@
import 'package:babylonia_terminal_launcher/messages/steps/game.pb.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flutter/material.dart';
import './../providers/providers.dart';
enum GameInstallationState {
idle,
checkingFile,
downloading,
patching,
}
enum GameRunState {
idle,
running,
}
class Game with ChangeNotifier {
GameInstallationState gameInstallationState = GameInstallationState.idle;
GameRunState gameRunState = GameRunState.idle;
Int64 currentProgress = Int64(0);
Int64 maxProgress = Int64(0);
Future startInstallation(GameStateProvider gameState, bool isUpdating) async {
StartGameInstallation(isUpdating: isUpdating).sendSignalToRust();
gameInstallationState = GameInstallationState.checkingFile;
notifyListeners();
//final downloadStream = NotifyGameStartDownloading.rustSignalStream;
//await for (final _ in downloadStream) {
// gameInstallationState = GameInstallationState.downloading;
// notifyListeners();
// break;
//}
final downloadProgresStream = GameInstallationProgress.rustSignalStream;
await for (final rustSignal in downloadProgresStream) {
if (gameInstallationState == GameInstallationState.checkingFile) {
gameInstallationState = GameInstallationState.downloading;
}
currentProgress = rustSignal.message.current;
maxProgress = rustSignal.message.max;
print("progress current : $currentProgress / $maxProgress");
notifyListeners();
if (currentProgress >= maxProgress) {
break;
}
}
print("patching game...");
gameInstallationState = GameInstallationState.patching;
notifyListeners();
final successStream = NotifyGameSuccessfullyInstalled.rustSignalStream;
await for (final _ in successStream) {
gameState.updateGameState();
break;
}
}
Future startGame() async {
RunGame().sendSignalToRust();
gameRunState = GameRunState.running;
notifyListeners();
final stream = GameStopped.rustSignalStream;
await for (final _ in stream) {
gameRunState = GameRunState.idle;
notifyListeners();
break;
}
}
}

View File

@ -1,34 +0,0 @@
import 'package:babylonia_terminal_launcher/messages/github.pb.dart';
class Github {
static bool _isFetchingProtonVersions = false;
static bool _isFetchingDXVKVersions = false;
static Future<List<String>> getProtonVersions() async {
if (!_isFetchingProtonVersions) {
_isFetchingProtonVersions = true;
AskProtonVersions().sendSignalToRust();
final stream = ProtonVersions.rustSignalStream;
await for (final rustSignal in stream) {
_isFetchingProtonVersions = false;
return rustSignal.message.versions;
}
}
return [];
}
static Future<List<String>> getDXVKVersions() async {
if (!_isFetchingDXVKVersions) {
_isFetchingDXVKVersions = true;
AskDXVKVersions().sendSignalToRust();
final stream = DXVKVersions.rustSignalStream;
await for (final rustSignal in stream) {
_isFetchingDXVKVersions = false;
return rustSignal.message.versions;
}
}
return [];
}
}

View File

@ -1,53 +0,0 @@
import 'package:fixnum/fixnum.dart';
import 'package:flutter/material.dart';
import './../messages/steps/proton.pb.dart';
import './../providers/providers.dart';
enum ProtonInstallationState {
idle,
downloading,
decompressing,
}
class Proton with ChangeNotifier {
ProtonInstallationState protonState = ProtonInstallationState.idle;
Int64 currentProgress = Int64(0);
Int64 maxProgress = Int64(0);
Future startInstallation(
GameStateProvider gameStateProvider, String protonVersion) async {
StartProtonInstallation(protonVersion: protonVersion).sendSignalToRust();
final progressStream = ProtonDownloadProgress.rustSignalStream;
await for (final rustSignal in progressStream) {
currentProgress = rustSignal.message.current;
maxProgress = rustSignal.message.max;
if (protonState == ProtonInstallationState.idle) {
protonState = ProtonInstallationState.downloading;
}
notifyListeners();
if (currentProgress >= maxProgress) {
break;
}
}
final notificationDecompressingStream =
NotifyProtonStartDecompressing.rustSignalStream;
await for (final _ in notificationDecompressingStream) {
protonState = ProtonInstallationState.decompressing;
notifyListeners();
break;
}
final notificationInstalledStream =
NotifyProtonSuccessfullyInstalled.rustSignalStream;
await for (final _ in notificationInstalledStream) {
gameStateProvider.updateGameState();
break;
}
}
}

View File

@ -1,29 +0,0 @@
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:xml/xml.dart';
import 'package:xml/xpath.dart';
class ReleaseNoticeInfo {
static const _releaseInfoUrl =
"https://raw.githubusercontent.com/ALEZ-DEV/Babylonia-terminal-flatpak-builds/refs/heads/main/moe.celica.BabyloniaTerminal.metainfo.xml";
static Future<String> getInfo(String currentVersion) async {
final content = await rootBundle.loadString("CHANGELOG.md");
return parseChangelog(content, currentVersion);
}
static String parseChangelog(String content, String currentVersion) {
final regex = RegExp(r'(## \[' +
currentVersion +
'].+)(?<content>(.|\n)*)(?=(\[unreleased\]|(## \[\d\.\d\.\d\])))');
final match = regex.firstMatch(content);
if (match != null) {
final changelogContent = match.namedGroup("content");
if (changelogContent != null) {
return changelogContent;
}
}
return "### Failed to parse info";
}
}

View File

@ -1,162 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import './config.dart';
enum BackgroundType {
contain,
fill,
cover,
fitHeight,
fitWidth,
disable,
}
class Settings {
final SharedPreferences prefs;
String? _launchOptions;
Settings({required this.prefs, required String? launchOptions})
: _launchOptions = launchOptions;
static Future<Settings> create() async {
final prefs = await SharedPreferences.getInstance();
final launchOptions = await Config.getLaunchOptions();
return Settings(
prefs: prefs,
launchOptions: launchOptions,
);
}
final String _firstTimeKey = 'first_time';
bool? get firstTime {
return prefs.getBool(_firstTimeKey);
}
set firstTime(bool? value) {
prefs.setBool(_firstTimeKey, value!);
}
final String _lastVersionKey = 'last_version';
String? get lastVersion {
return prefs.getString(_lastVersionKey);
}
set lastVersion(String? value) {
prefs.setString(_lastVersionKey, value!);
}
String? get launchOptions {
return _launchOptions;
}
set launchOptions(String? value) {
Config.setLaunchOptions(value);
_launchOptions = value;
}
BackgroundType? _backgroundType;
final String _backgroundTypeKey = 'background_type';
BackgroundType get selectedBackgroundType {
final bt = prefs.getString(_backgroundTypeKey);
if (bt == null) {
_backgroundType = BackgroundType.disable;
prefs.setString(
_backgroundTypeKey,
getStringNameOfBackgroundType(_backgroundType!),
);
} else {
_backgroundType ??= getBackgroundTypeFromString(bt);
}
return _backgroundType!;
}
set selectedBackgroundType(BackgroundType selectedBackground) {
_backgroundType = selectedBackground;
prefs.setString(
_backgroundTypeKey,
getStringNameOfBackgroundType(selectedBackground),
);
}
int? _backgroundId;
String backgroundIdKey = 'background_id';
int? get backgroundId {
_backgroundId ??= prefs.getInt(backgroundIdKey);
return _backgroundId;
}
set backgroundId(int? value) {
_backgroundId = value;
prefs.setInt(backgroundIdKey, value!);
}
static final List<BackgroundType> backgoundList = [
BackgroundType.contain,
BackgroundType.fill,
BackgroundType.cover,
BackgroundType.fitHeight,
BackgroundType.fitWidth,
BackgroundType.disable,
];
static String getStringNameOfBackgroundType(BackgroundType backgroundType) {
switch (backgroundType) {
case BackgroundType.contain:
return 'contain';
case BackgroundType.fill:
return 'fill';
case BackgroundType.cover:
return 'cover';
case BackgroundType.fitHeight:
return 'fitHeight';
case BackgroundType.fitWidth:
return 'fitWidth';
case BackgroundType.disable:
return 'disable';
}
}
static BackgroundType getBackgroundTypeFromString(String background) {
switch (background) {
case 'contain':
return BackgroundType.contain;
case 'fill':
return BackgroundType.fill;
case 'cover':
return BackgroundType.cover;
case 'fitHeight':
return BackgroundType.fitHeight;
case 'fitWidth':
return BackgroundType.fitWidth;
case 'disable':
return BackgroundType.disable;
default:
throw FormatException('Can\'t convert String to Enum BackgroundType!');
}
}
static BoxFit getBoxFitFromBackgroundType(BackgroundType backgroundType) {
switch (backgroundType) {
case BackgroundType.contain:
return BoxFit.contain;
case BackgroundType.fill:
return BoxFit.fill;
case BackgroundType.cover:
return BoxFit.cover;
case BackgroundType.fitHeight:
return BoxFit.fitHeight;
case BackgroundType.fitWidth:
return BoxFit.fitWidth;
case BackgroundType.disable:
throw FormatException(
'Can\'t convert BackgroundType to widget BoxFit!');
}
}
}

View File

@ -1,43 +0,0 @@
import 'package:babylonia_terminal_launcher/messages/game_state.pb.dart';
import 'package:flutter/material.dart';
class GameStateProvider with ChangeNotifier {
States? _gameState;
bool isUpdating = false;
bool haveToSetup = false;
get gameState {
return _gameState;
}
Future updateGameState() async {
if (!isUpdating) {
isUpdating = true;
AskGameState().sendSignalToRust();
final stream = GameState.rustSignalStream;
await for (final rustSignal in stream) {
_gameState = rustSignal.message.state;
break;
}
isUpdating = false;
notifyListeners();
}
}
void updateSetup() {
haveToSetup = needToSetup();
notifyListeners();
}
bool needToSetup() {
return _gameState == States.ProtonNotInstalled ||
_gameState == States.DXVKNotInstalled ||
_gameState == States.FontNotInstalled ||
_gameState == States.DependecieNotInstalled;
}
bool isGameUpdating() {
return _gameState == States.GameNeedUpdate;
}
}

View File

@ -1,2 +0,0 @@
export './settings_provider.dart';
export './game_state_provider.dart';

View File

@ -1,67 +0,0 @@
import 'package:flutter/foundation.dart';
import './../models/settings.dart';
import './../models/config.dart';
class SettingsProvider with ChangeNotifier {
late final Settings _settings;
Future init() async {
_settings = await Settings.create();
if (kDebugMode) {
_settings.firstTime = true;
_settings.prefs.clear();
}
await Config.update();
}
bool get firstTime {
final result = _settings.firstTime;
if (result == null) {
_settings.firstTime = true;
}
return _settings.firstTime!;
}
set firstTime(bool value) {
_settings.firstTime = value;
notifyListeners();
}
String get lastVersion {
final result = _settings.lastVersion;
if (result == null) {
return '';
}
return result;
}
set lastVersion(String value) {
_settings.lastVersion = value;
}
set setSelectedBackgroundType(BackgroundType selectedBackground) {
_settings.selectedBackgroundType = selectedBackground;
notifyListeners();
}
get getSelectedBackgroundType {
return _settings.selectedBackgroundType;
}
int? get backgroundId {
return _settings.backgroundId;
}
set backgroundId(int? value) {
_settings.backgroundId = value;
}
String? get launchOptions {
return _settings.launchOptions;
}
set launchOptions(String? value) {
_settings.launchOptions = value;
}
}

View File

@ -1,79 +0,0 @@
import 'package:babylonia_terminal_launcher/messages/game_state.pb.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/background_widget.dart';
import '../widgets/serious_lee_widget.dart';
import '../widgets/play_button.dart';
import '../widgets/steps/game_steps_widget.dart';
import './../providers/providers.dart';
import './../models/settings.dart';
import './../models/background.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final gameStateProvider = Provider.of<GameStateProvider>(context);
return Stack(
children: [
const ShowBackground(),
gameStateProvider.gameState != States.GameInstalled
? const GameSteps()
: const PlayButton(),
],
);
}
}
class ShowBackground extends StatefulWidget {
const ShowBackground({super.key});
@override
State<ShowBackground> createState() => _ShowBackgroundState();
}
class _ShowBackgroundState extends State<ShowBackground> {
bool isLoading = false;
bool hadLoaded = false;
late final Background _background;
@override
void didChangeDependencies() async {
if (!hadLoaded) {
isLoading = true;
_background =
await Background.get(Provider.of<SettingsProvider>(context));
setState(() {
isLoading = false;
hadLoaded = true;
});
}
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
if (Provider.of<SettingsProvider>(context).getSelectedBackgroundType !=
BackgroundType.disable) {
if (isLoading) {
return const SeriousLeeWidget(
title: 'Babylonia Terminal',
);
} else {
return BackgroundWidget(
background: _background,
);
}
} else {
return const SeriousLeeWidget(
title: 'Babylonia Terminal',
);
}
}
}

View File

@ -1,36 +0,0 @@
import 'package:babylonia_terminal_launcher/screens/settings_screen.dart';
import 'package:flutter/material.dart';
import 'package:yaru/icons.dart';
import 'package:babylonia_terminal_launcher/screens/home_screen.dart';
class Screens {
static final _screens = <Widget, (Widget, Widget, String)>{
const HomeScreen(): (
const Icon(YaruIcons.home_filled),
const Icon(YaruIcons.home),
'Home',
),
const SettingsScreen(): (
const Icon(YaruIcons.settings_filled),
const Icon(YaruIcons.settings),
'Settings',
),
};
static List<Widget> drawerItem(
{required Function(int) onSelected, required int selectedIndex}) =>
[
for (int i = 0; i < Screens._screens.values.length; i++)
ListTile(
selected: i == selectedIndex,
leading: i == selectedIndex
? Screens._screens.values.elementAt(i).$1
: Screens._screens.values.elementAt(i).$2,
title: Text(Screens._screens.values.elementAt(i).$3),
onTap: () => onSelected(i),
),
];
static Widget getCurrent(int index) => Screens._screens.keys.toList()[index];
}

View File

@ -1,12 +0,0 @@
import 'package:flutter/material.dart';
class GameSettingsPage extends StatelessWidget {
const GameSettingsPage({super.key});
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Game settings'),
);
}
}

View File

@ -1,69 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:yaru/yaru.dart';
import './../../providers/settings_provider.dart';
class GeneralSettingsPage extends StatefulWidget {
const GeneralSettingsPage({super.key});
@override
State<GeneralSettingsPage> createState() => _GeneralSettingsPageState();
}
class _GeneralSettingsPageState extends State<GeneralSettingsPage> {
final textFieldController = TextEditingController();
String? _launchOptionsError;
bool isLaunchOptionsValid(String launchOptions) {
return RegExp(r'^.*%command%.*$').hasMatch(launchOptions);
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<SettingsProvider>(context, listen: false);
final launchOptions = provider.launchOptions;
return Center(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(15.0),
child: SizedBox(
child: YaruSection(
headline: const Text('Launch options'),
child: TextFormField(
initialValue: launchOptions,
decoration: InputDecoration(
labelText:
'Your custom launch options, E.G. : mangohud %command%',
errorText: _launchOptionsError,
),
validator: (value) => _launchOptionsError,
onChanged: (String text) {
if (text.isEmpty) {
setState(() {
_launchOptionsError = null;
});
provider.launchOptions = null;
} else if (!isLaunchOptionsValid(text)) {
setState(() {
_launchOptionsError =
'You need to put \'%command%\' in your command';
});
} else {
setState(() {
_launchOptionsError = null;
});
provider.launchOptions = text;
}
},
),
),
),
),
],
),
);
}
}

View File

@ -1,33 +0,0 @@
import 'package:flutter/material.dart';
import 'package:yaru/yaru.dart';
import './general_settings_page.dart';
import './game_settings_page.dart';
import './style_settings_page.dart';
class SettingsPage {
static final _pages = <Widget, (Widget, String)>{
const GeneralSettingsPage(): (
const Icon(YaruIcons.gears),
'General',
),
const GameSettingsPage(): (
const Icon(YaruIcons.game_controller_filled),
'Game',
),
const StyleSettingsPage(): (
const Icon(YaruIcons.desktop_appearance_filled),
'Style',
),
};
static List<Widget> tabItems() => [
for (int i = 0; i < SettingsPage._pages.values.length; i++)
YaruTab(
icon: SettingsPage._pages.values.elementAt(i).$1,
label: SettingsPage._pages.values.elementAt(i).$2,
),
];
static List<Widget> getPages() => SettingsPage._pages.keys.toList();
}

View File

@ -1,69 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:yaru/yaru.dart';
import './../../providers/settings_provider.dart';
import './../../models/settings.dart';
class StyleSettingsPage extends StatefulWidget {
const StyleSettingsPage({super.key});
@override
State<StyleSettingsPage> createState() => _StyleSettingsPageState();
}
class _StyleSettingsPageState extends State<StyleSettingsPage> {
late BackgroundType _radioValue;
void setBackgroundValue(
BuildContext context,
SettingsProvider provider,
BackgroundType? value,
) {
if (value != null) {
provider.setSelectedBackgroundType = value;
setState(() {
_radioValue = value;
});
}
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<SettingsProvider>(context, listen: false);
_radioValue = provider.getSelectedBackgroundType;
return Center(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(15.0),
child: SizedBox(
child: YaruSection(
headline: const Text('Background video'),
child: Column(
children: Settings.backgoundList
.map(
(b) => YaruRadioListTile(
value: b,
groupValue: _radioValue,
onChanged: (v) =>
setBackgroundValue(context, provider, v),
toggleable: true,
title: Text(
Settings.getStringNameOfBackgroundType(
b,
),
),
),
)
.toList(),
),
),
),
),
],
),
);
}
}

View File

@ -1,52 +0,0 @@
import 'package:flutter/material.dart';
import 'package:yaru/yaru.dart';
import './settings/settings_pages.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen>
with TickerProviderStateMixin {
late TabController tabController;
@override
void initState() {
super.initState();
tabController =
TabController(length: SettingsPage.getPages().length, vsync: this);
}
@override
void dispose() {
super.dispose();
tabController.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: YaruTabBar(
tabController: tabController,
tabs: SettingsPage.tabItems(),
),
),
Expanded(
child: TabBarView(
controller: tabController,
children: SettingsPage.getPages(),
),
),
],
),
);
}
}

View File

@ -1,23 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './../providers/settings_provider.dart';
import './setups/welcome_screen.dart';
import 'setups/steps_screen.dart';
class SetupScreen extends StatelessWidget {
const SetupScreen({super.key});
@override
Widget build(BuildContext context) {
final settingsProvider = Provider.of<SettingsProvider>(context);
return Scaffold(
appBar: AppBar(
title: const Text("Babylonia Terminal"),
centerTitle: true,
),
body: settingsProvider.firstTime ? const WelcomeScreen() : StepsScreen(),
);
}
}

View File

@ -1,81 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'package:yaru/yaru.dart';
import './../../messages/game_state.pb.dart';
import './../../providers/providers.dart';
import './../../widgets/selectable_yaru_expansion_panel.dart';
import './../../widgets/simple_button.dart';
import './../../widgets/steps/proton_steps_widget.dart';
import './../../widgets/steps/dxvk_steps_widget.dart';
import './../../widgets/steps/fonts_steps_widget.dart';
import './../../widgets/steps/dependencies_steps_widget.dart';
class StepsScreen extends StatelessWidget {
StepsScreen({super.key});
final SectionController controller = SectionController(selectedItem: 0);
@override
Widget build(BuildContext context) {
final gameStateProvider = Provider.of<GameStateProvider>(context);
switch (gameStateProvider.gameState) {
case States.ProtonNotInstalled:
controller.updateSection(0);
break;
case States.DXVKNotInstalled:
controller.updateSection(1);
break;
case States.FontNotInstalled:
controller.updateSection(2);
break;
case States.DependecieNotInstalled:
controller.updateSection(3);
break;
default:
controller.updateSection(null);
break;
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: 600,
maxWidth: 750,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: SelectableYaruExpansionPanel(
controller: controller,
headers: const [
Text("Proton"),
Text("DXVK"),
Text("Fonts"),
Text("Dependencies"),
],
children: const [
ProtonSteps(),
DXVKSteps(),
FontsSteps(),
DependenciesSteps(),
],
),
),
),
Padding(
padding: const EdgeInsets.only(top: 12.0),
child: SimpleButton(
onPressed: !gameStateProvider.needToSetup()
? () => gameStateProvider.updateSetup()
: null,
child: const Text('next'),
),
),
],
),
);
}
}

View File

@ -1,40 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './../../providers/settings_provider.dart';
import './../../widgets/serious_lee_widget.dart';
import './../../widgets/simple_button.dart';
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SeriousLeeWidget(title: 'Welcome to Babylonia Terminal!'),
const Text(
'We have to setup some things first',
style: TextStyle(
fontSize: 20,
),
),
Padding(
padding: const EdgeInsets.only(top: 15.0),
child: SizedBox(
width: 200,
child: SimpleButton(
onPressed: () =>
Provider.of<SettingsProvider>(context, listen: false)
.firstTime = false,
child: const Text('Start'),
),
),
)
],
),
);
}
}

View File

@ -1,56 +0,0 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:provider/provider.dart';
import './../providers/settings_provider.dart';
import './../models/settings.dart';
import './../models/background.dart';
class BackgroundWidget extends StatefulWidget {
const BackgroundWidget({super.key, required this.background});
final Background background;
@override
State<BackgroundWidget> createState() => _BackgroundWidgetState();
}
class _BackgroundWidgetState extends State<BackgroundWidget> {
late final player = Player(
configuration: const PlayerConfiguration(),
);
late final controller = VideoController(player);
@override
void initState() {
super.initState();
player.open(
Media(
widget.background.path,
),
);
player.setPlaylistMode(PlaylistMode.loop);
}
@override
void dispose() {
player.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<SettingsProvider>(context);
player.play();
return Video(
controller: controller,
controls: NoVideoControls,
wakelock: false,
fit: Settings.getBoxFitFromBackgroundType(
provider.getSelectedBackgroundType,
),
);
}
}

View File

@ -1,112 +0,0 @@
import 'dart:math';
import 'package:flutter/material.dart';
class GtkSpinner extends StatefulWidget {
const GtkSpinner({
super.key,
this.size = 15.0,
this.strokeSize = 5.0,
this.color = Colors.grey,
});
final double size;
final double strokeSize;
final Color color;
@override
State<GtkSpinner> createState() => _GtkSpinnerState();
}
class _GtkSpinnerState extends State<GtkSpinner>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1, milliseconds: 500),
)..repeat();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return CustomPaint(
painter: _GtkSpinnerPainter(
_controller.value * 2 * pi,
widget.strokeSize,
widget.color,
),
size: Size(widget.size, widget.size),
);
},
),
);
}
}
class _GtkSpinnerPainter extends CustomPainter {
_GtkSpinnerPainter(this.angle, this.strokeSize, this.color);
final double angle;
final double strokeSize;
final Color color;
@override
void paint(Canvas canvas, Size size) {
final double radius = size.width / 2;
final Rect rect =
Rect.fromCircle(center: Offset(radius, radius), radius: radius);
// Define the gradient for the arc
final Paint gradientPaint = Paint()
..shader = SweepGradient(
startAngle: 0.0,
endAngle: 2 * pi,
colors: [
color,
color.withOpacity(0.0),
],
stops: const [0.0, 0.90],
transform: GradientRotation(angle),
).createShader(rect)
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeWidth = strokeSize;
// Draw the gradient arc
canvas.drawArc(
rect,
angle,
7 * pi / 4, // Draw an arc of 300 degrees
false,
gradientPaint,
);
// Add two circles at the start and end to create the rounded caps effect
final Paint capPaint = Paint()
..color = color
..style = PaintingStyle.fill;
canvas.drawCircle(
Offset(radius + radius * cos(angle), radius + radius * sin(angle)),
strokeSize / 2,
capPaint,
);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}

View File

@ -1,54 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './simple_button.dart';
import './../models/game.dart';
class PlayButton extends StatelessWidget {
const PlayButton({super.key});
@override
Widget build(BuildContext context) {
final game = Provider.of<Game>(context);
return Padding(
padding: const EdgeInsets.all(50.0),
child: Row(
children: [
const Expanded(
child: SizedBox(),
),
const Expanded(
child: SizedBox(),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: 600,
maxHeight: 50,
),
child: SimpleButton(
onPressed: game.gameRunState == GameRunState.idle
? () {
Provider.of<Game>(context, listen: false)
.startGame();
}
: null,
child: Center(
child: game.gameRunState == GameRunState.idle
? const Text("Play")
: const Text("Running..."),
),
),
),
],
),
),
],
),
);
}
}

View File

@ -1,59 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:yaru/yaru.dart';
class ReleaseNotice extends StatelessWidget {
const ReleaseNotice(
{super.key, required this.currentVersion, required this.info});
final String currentVersion;
final String info;
@override
Widget build(BuildContext context) {
return AlertDialog(
titlePadding: EdgeInsets.zero,
title: const YaruDialogTitleBar(
title: Text('Release notice'),
isClosable: true,
),
contentPadding: EdgeInsets.zero,
content: SizedBox(
height: 400,
width: 700,
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
"Version $currentVersion just dropped!",
style: const TextStyle(
fontSize: 32,
),
),
),
const Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.only(left: 25.0),
child: Text(
"What's new :",
style: TextStyle(
fontSize: 16,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30.0),
child: SizedBox(
height: 300,
child: Markdown(data: info),
),
),
],
),
),
);
}
}

View File

@ -1,237 +0,0 @@
// This file has been literally copied from https://github.com/ubuntu/yaru.dart/blob/main/lib/src/widgets/yaru_expansion_panel.dart
// and https://github.com/ubuntu/yaru.dart/blob/main/lib/src/widgets/yaru_expandable.dart
// Just want to make some change to it for specific needs instead of contributing to it, because I'm too lazy for that and I think they don't want these change
import 'package:flutter/material.dart';
import 'package:yaru/constants.dart';
import 'package:yaru/widgets.dart';
class SectionController extends ChangeNotifier {
int? selectedItem;
Function()? onChange;
SectionController({required this.selectedItem});
void updateSection(int? newSelectedItem) {
selectedItem = newSelectedItem;
notifyListeners();
if (onChange != null) {
onChange!();
}
}
}
class SelectableYaruExpansionPanel extends StatefulWidget {
const SelectableYaruExpansionPanel({
super.key,
required this.controller,
required this.children,
this.borderRadius =
const BorderRadius.all(Radius.circular(kYaruContainerRadius)),
this.border,
required this.headers,
this.width,
this.height,
this.padding,
this.margin,
this.expandIconPadding = const EdgeInsets.all(10),
this.headerPadding = const EdgeInsets.only(left: 20),
this.color,
this.placeDividers = true,
this.expandIcon,
this.shrinkWrap = true,
this.scrollPhysics = const ClampingScrollPhysics(),
this.collapseOnExpand = true,
}) : assert(headers.length == children.length);
final SectionController controller;
final List<Widget> children;
final List<Widget> headers;
final BorderRadius borderRadius;
final BoxBorder? border;
final double? width;
final double? height;
final EdgeInsetsGeometry? padding;
final EdgeInsetsGeometry? margin;
final EdgeInsetsGeometry expandIconPadding;
final EdgeInsetsGeometry headerPadding;
final Color? color;
final bool placeDividers;
final Widget? expandIcon;
final bool shrinkWrap;
final ScrollPhysics scrollPhysics;
final bool collapseOnExpand;
@override
State<SelectableYaruExpansionPanel> createState() =>
_SelectableYaruExpansionPanelState();
}
class _SelectableYaruExpansionPanelState
extends State<SelectableYaruExpansionPanel> {
late List<bool> _expandedStore;
@override
void initState() {
super.initState();
widget.controller.onChange = widget.collapseOnExpand
? () {
if (widget.controller.selectedItem != null) {
_expandedStore[widget.controller.selectedItem!];
for (var n = 0; n < _expandedStore.length; n++) {
if (_expandedStore[n]) {
setState(() => _expandedStore[n] = false);
}
}
} else {
for (var n = 0; n < _expandedStore.length; n++) {
setState(() => _expandedStore[n] = false);
}
}
}
: null;
_expandedStore =
List<bool>.generate(widget.children.length, (index) => false);
}
@override
Widget build(BuildContext context) {
assert(widget.children.length == widget.headers.length);
if (widget.controller.selectedItem != null) {
_expandedStore[widget.controller.selectedItem!] = true;
}
return YaruBorderContainer(
border: widget.border,
borderRadius: widget.borderRadius,
color: widget.color,
width: widget.width,
height: widget.height,
padding: widget.padding,
margin: widget.margin,
child: widget.placeDividers
? ListView.separated(
shrinkWrap: widget.shrinkWrap,
physics: widget.scrollPhysics,
itemCount: widget.children.length,
itemBuilder: _itemBuilder,
separatorBuilder: (context, index) {
if (index != widget.children.length - 1) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 1),
child: Divider(),
);
} else {
return const SizedBox.shrink();
}
},
)
: ListView.builder(
shrinkWrap: widget.shrinkWrap,
physics: widget.scrollPhysics,
itemCount: widget.children.length,
itemBuilder: _itemBuilder,
),
);
}
Widget? _itemBuilder(context, index) {
return YaruExpandable(
expandIconPadding: widget.expandIconPadding,
isExpanded: _expandedStore[index],
header: Padding(
padding: widget.headerPadding,
child: widget.headers[index],
),
child: widget.children[index],
);
}
}
const _kAnimationDuration = Duration(milliseconds: 250);
const _kAnimationCurve = Curves.easeInOutCubic;
class YaruExpandable extends StatefulWidget {
const YaruExpandable({
super.key,
required this.header,
this.expandIconPadding = EdgeInsets.zero,
required this.child,
this.collapsedChild,
this.gapHeight = 4.0,
this.isExpanded = false,
this.onChange,
});
final Widget header;
final EdgeInsetsGeometry expandIconPadding;
final Widget child;
final Widget? collapsedChild;
final double gapHeight;
final bool isExpanded;
final ValueChanged<bool>? onChange;
@override
State<YaruExpandable> createState() => _YaruExpandableState();
}
class _YaruExpandableState extends State<YaruExpandable> {
late bool _isExpanded;
@override
void initState() {
_isExpanded = widget.isExpanded;
super.initState();
}
@override
void didUpdateWidget(YaruExpandable oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.isExpanded != widget.isExpanded) {
_isExpanded = widget.isExpanded;
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
widget.header,
Padding(
padding: widget.expandIconPadding,
child: const SizedBox(
height: 36,
width: 36,
),
),
],
),
AnimatedCrossFade(
firstChild: _buildChild(widget.child),
secondChild: widget.collapsedChild != null
? _buildChild(widget.collapsedChild!)
: Container(),
crossFadeState: _isExpanded
? CrossFadeState.showFirst
: CrossFadeState.showSecond,
sizeCurve: _kAnimationCurve,
duration: _kAnimationDuration,
),
],
);
}
Widget _buildChild(Widget child) {
return Column(
children: [
SizedBox(height: widget.gapHeight),
child,
],
);
}
}

View File

@ -1,32 +0,0 @@
import 'package:flutter/material.dart';
class SeriousLeeWidget extends StatelessWidget {
const SeriousLeeWidget({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 300,
child: Image.asset('assets/images/Lee6.png'),
),
Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
title,
style: const TextStyle(
fontSize: 34,
),
),
),
)
],
),
);
}
}

View File

@ -1,30 +0,0 @@
import 'package:flutter/material.dart';
class SimpleButton extends StatelessWidget {
const SimpleButton({super.key, required this.child, required this.onPressed});
final Function()? onPressed;
final Widget? child;
@override
Widget build(BuildContext context) {
return ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.disabled)) {
return Colors.grey;
}
return Colors.blue[500];
}),
side: MaterialStateProperty.all(BorderSide.none),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100.0),
side: const BorderSide(color: Colors.red),
),
),
),
onPressed: onPressed,
child: child,
);
}
}

View File

@ -1,85 +0,0 @@
import 'package:babylonia_terminal_launcher/widgets/gtk_spinner_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './../../models/dependencies.dart';
import './../../providers/providers.dart';
import './../../widgets/simple_button.dart';
class DependenciesSteps extends StatelessWidget {
const DependenciesSteps({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: ChangeNotifierProvider(
create: (context) => Dependencies(),
child: Builder(
builder: (context) {
switch (Provider.of<Dependencies>(context).dependeciesState) {
case DependenciesInstallationState.idle:
return const InstallDependecies();
case DependenciesInstallationState.installing:
return const DependeciesInstallationProgress();
}
},
),
),
);
}
}
class InstallDependecies extends StatefulWidget {
const InstallDependecies({super.key});
@override
State<InstallDependecies> createState() => _InstallDependeciesState();
}
class _InstallDependeciesState extends State<InstallDependecies> {
bool canInstall = true;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SimpleButton(
onPressed: canInstall
? () {
Provider.of<Dependencies>(context, listen: false)
.startInstallation(
Provider.of<GameStateProvider>(context, listen: false),
);
setState(() {
canInstall = false;
});
}
: null,
child: const Text("Install"),
),
if (!canInstall) const GtkSpinner(),
],
),
);
}
}
class DependeciesInstallationProgress extends StatelessWidget {
const DependeciesInstallationProgress({super.key});
@override
Widget build(BuildContext context) {
return const Row(
children: [
GtkSpinner(),
Text(
'Installing dependecies (this can take a while, so go grab a coffee)',
),
],
);
}
}

View File

@ -1,159 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:yaru/widgets.dart';
import './../../models/github.dart';
import './../../models/dxvk.dart';
import './../../widgets/simple_button.dart';
import './../../widgets/gtk_spinner_widget.dart';
import './../../providers/providers.dart';
class DXVKSteps extends StatefulWidget {
const DXVKSteps({super.key});
@override
State<DXVKSteps> createState() => _DXVKStepsState();
}
class _DXVKStepsState extends State<DXVKSteps> {
final DXVK proton = DXVK();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: ChangeNotifierProvider(
create: (_) => proton,
child: Builder(
builder: (context) {
switch (Provider.of<DXVK>(context).dxvkState) {
case DXVKInstallationState.idle:
return const InstallDXVK();
case DXVKInstallationState.downloading:
return const DXVKDownloadProgress();
case DXVKInstallationState.decompressing:
return const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.all(8.0),
child: GtkSpinner(),
),
Text('Installing...'),
],
);
}
},
),
),
);
}
}
class InstallDXVK extends StatefulWidget {
const InstallDXVK({super.key});
@override
State<InstallDXVK> createState() => _InstallDXVKState();
}
class _InstallDXVKState extends State<InstallDXVK> {
bool hasLoaded = false;
bool isLoading = false;
late List<String> protonVersions;
String? selectedValue;
bool canInstall = true;
@override
void didChangeDependencies() async {
if (!hasLoaded) {
isLoading = true;
protonVersions = await Github.getDXVKVersions();
setState(() {
isLoading = false;
hasLoaded = true;
});
}
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
if (hasLoaded && selectedValue == null) {
selectedValue = protonVersions.first;
}
return isLoading
? const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.all(8.0),
child: GtkSpinner(),
),
Text('Fetching versions...'),
],
)
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
YaruPopupMenuButton(
enabled: canInstall,
initialValue: selectedValue,
itemBuilder: (_) => protonVersions
.map(
(e) => PopupMenuItem(
value: e,
child: Text(e),
),
)
.toList(),
onSelected: (v) => setState(() {
selectedValue = v;
}),
child: Text(selectedValue!),
),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: SimpleButton(
onPressed: canInstall
? () {
Provider.of<DXVK>(context, listen: false)
.startInstallation(
Provider.of<GameStateProvider>(context,
listen: false),
selectedValue!);
setState(() {
canInstall = false;
});
}
: null,
child: const Text("Install"),
),
),
if (!canInstall) const GtkSpinner(),
],
);
}
}
class DXVKDownloadProgress extends StatelessWidget {
const DXVKDownloadProgress({super.key});
@override
Widget build(BuildContext context) {
final provider = Provider.of<DXVK>(context);
final pourcent =
(provider.currentProgress.toInt() / provider.maxProgress.toInt()) * 100;
return Column(
children: [
Text("Downloaded: ${pourcent.toStringAsFixed(2)}%"),
YaruLinearProgressIndicator(
value: pourcent / 100,
),
],
);
}
}

View File

@ -1,100 +0,0 @@
import 'package:babylonia_terminal_launcher/widgets/gtk_spinner_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:yaru/yaru.dart';
import './../../models/fonts.dart';
import './../../providers/providers.dart';
import './../../widgets/simple_button.dart';
class FontsSteps extends StatelessWidget {
const FontsSteps({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: ChangeNotifierProvider(
create: (context) => Fonts(),
child: Builder(
builder: (context) {
switch (Provider.of<Fonts>(context).fontsState) {
case FontsInstallationState.idle:
return const InstallFonts();
case FontsInstallationState.installing:
return const FontsInstallationProgress();
}
},
),
),
);
}
}
class InstallFonts extends StatefulWidget {
const InstallFonts({super.key});
@override
State<InstallFonts> createState() => _InstallFontsState();
}
class _InstallFontsState extends State<InstallFonts> {
bool canInstall = true;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SimpleButton(
onPressed: canInstall
? () {
Provider.of<Fonts>(context, listen: false)
.startInstallation(
Provider.of<GameStateProvider>(context, listen: false),
);
setState(() {
canInstall = false;
});
}
: null,
child: const Text("Install"),
),
if (!canInstall) const GtkSpinner(),
],
),
);
}
}
class FontsInstallationProgress extends StatelessWidget {
const FontsInstallationProgress({super.key});
@override
Widget build(BuildContext context) {
final provider = Provider.of<Fonts>(context);
final pourcent =
(provider.currentProgress.toInt() / provider.maxProgress.toInt()) * 100;
return Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const GtkSpinner(),
Text(
"${provider.currentProgress} / ${provider.maxProgress} fonts installed"),
],
),
),
YaruLinearProgressIndicator(
value: pourcent / 100,
),
],
);
}
}

View File

@ -1,152 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:yaru/yaru.dart';
import './../../models/game.dart';
import './../simple_button.dart';
import './../gtk_spinner_widget.dart';
import './../../providers/providers.dart';
class GameSteps extends StatelessWidget {
const GameSteps({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(50.0),
child: Builder(builder: (context) {
switch (Provider.of<Game>(context).gameInstallationState) {
case GameInstallationState.idle:
return const _InstallGame();
case GameInstallationState.checkingFile:
return const _CheckingFileGame();
case GameInstallationState.downloading:
return const _DownloadingGame();
case GameInstallationState.patching:
return const _PatchingGame();
}
}),
);
}
}
class _InstallGame extends StatelessWidget {
const _InstallGame({super.key});
@override
Widget build(BuildContext context) {
final gameStateProvider = Provider.of<GameStateProvider>(context);
return Row(
children: [
const Expanded(
child: SizedBox(),
),
const Expanded(
child: SizedBox(),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: 600,
maxHeight: 50,
),
child: SimpleButton(
onPressed: () async {
Provider.of<Game>(context, listen: false).startInstallation(
Provider.of<GameStateProvider>(context, listen: false),
gameStateProvider.isGameUpdating(),
);
},
child: gameStateProvider.isGameUpdating()
? const Center(
child: Text("Update"),
)
: const Center(
child: Text("Download"),
),
),
),
],
),
),
],
);
}
}
class _CheckingFileGame extends StatelessWidget {
const _CheckingFileGame({super.key});
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.only(bottom: 40.0),
child: Align(
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GtkSpinner(),
Text("Checking files... (This can take a while)"),
],
),
),
);
}
}
class _DownloadingGame extends StatelessWidget {
const _DownloadingGame({super.key});
@override
Widget build(BuildContext context) {
final provider = Provider.of<Game>(context);
final pourcent =
(provider.currentProgress.toInt() / provider.maxProgress.toInt()) * 100;
final currentGb = provider.currentProgress.toInt() / 1024 / 1024 / 1024;
final maxGb = provider.maxProgress.toInt() / 1024 / 1024 / 1024;
return Padding(
padding: const EdgeInsets.only(bottom: 40.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
"${currentGb.toStringAsFixed(2)} / ${maxGb.toStringAsFixed(2)} Gb (${pourcent.toStringAsFixed(2)}%)",
),
),
YaruLinearProgressIndicator(
value: pourcent / 100,
),
],
),
);
}
}
class _PatchingGame extends StatelessWidget {
const _PatchingGame({super.key});
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.only(bottom: 40.0),
child: Align(
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GtkSpinner(),
Text("Patching game"),
],
),
),
);
}
}

View File

@ -1,157 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:yaru/widgets.dart';
import './../../models/github.dart';
import './../../models/proton.dart';
import './../../widgets/simple_button.dart';
import './../../widgets/gtk_spinner_widget.dart';
import './../../providers/providers.dart';
class ProtonSteps extends StatefulWidget {
const ProtonSteps({super.key});
@override
State<ProtonSteps> createState() => _ProtonStepsState();
}
class _ProtonStepsState extends State<ProtonSteps> {
final Proton proton = Proton();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: ChangeNotifierProvider(
create: (_) => proton,
child: Builder(
builder: (context) {
switch (Provider.of<Proton>(context).protonState) {
case ProtonInstallationState.idle:
return const InstallProton();
case ProtonInstallationState.downloading:
return const ProtonDownloadProgress();
case ProtonInstallationState.decompressing:
return const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.all(8.0),
child: GtkSpinner(),
),
Text('decompressing...'),
],
);
}
},
),
),
);
}
}
class InstallProton extends StatefulWidget {
const InstallProton({super.key});
@override
State<InstallProton> createState() => _InstallProtonState();
}
class _InstallProtonState extends State<InstallProton> {
bool hasLoaded = false;
bool isLoading = false;
late List<String> protonVersions;
String? selectedValue;
bool canInstall = true;
@override
void didChangeDependencies() async {
if (!hasLoaded) {
isLoading = true;
protonVersions = await Github.getProtonVersions();
setState(() {
isLoading = false;
hasLoaded = true;
});
}
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
if (hasLoaded && selectedValue == null) {
selectedValue = protonVersions.first;
}
return isLoading
? const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.all(8.0),
child: GtkSpinner(),
),
Text('Fetching versions...'),
],
)
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
YaruPopupMenuButton(
initialValue: selectedValue,
itemBuilder: (_) => protonVersions
.map(
(e) => PopupMenuItem(
value: e,
child: Text(e),
),
)
.toList(),
onSelected: (v) => setState(() {
selectedValue = v;
}),
child: Text(selectedValue!),
),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: SimpleButton(
onPressed: canInstall
? () {
Provider.of<Proton>(context, listen: false)
.startInstallation(
Provider.of<GameStateProvider>(context,
listen: false),
selectedValue!);
setState(() {
canInstall = false;
});
}
: null,
child: const Text("Install"),
),
),
],
);
}
}
class ProtonDownloadProgress extends StatelessWidget {
const ProtonDownloadProgress({super.key});
@override
Widget build(BuildContext context) {
final provider = Provider.of<Proton>(context);
final pourcent =
(provider.currentProgress.toInt() / provider.maxProgress.toInt()) * 100;
return Column(
children: [
Text("Downloaded: ${pourcent.toStringAsFixed(2)}%"),
YaruLinearProgressIndicator(
value: pourcent / 100,
),
],
);
}
}

View File

@ -1,124 +0,0 @@
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = FALSE;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "babylonia_terminal_launcher");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "babylonia_terminal_launcher");
}
gtk_window_set_default_size(window, 1280, 720);
gtk_widget_show(GTK_WIDGET(window));
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
//MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
//MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID,
"flags", G_APPLICATION_NON_UNIQUE,
nullptr));
}

View File

@ -1,23 +0,0 @@
syntax = "proto3";
package config;
// [RINF:DART-SIGNAL]
message ConfigInput {}
// [RINF:RUST-SIGNAL]
message ConfigOutput {
string configPath = 1;
}
// [RINF:DART-SIGNAL]
message GetLaunchOptionsInput {}
// [RINF:RUST-SIGNAL]
message GetLaunchOptionsOutput {
optional string launchOptions = 1;
}
// [RINF:DART-SIGNAL]
message SetLaunchOptionsInput {
optional string launchOptions = 1;
}

View File

@ -1,7 +0,0 @@
syntax = "proto3";
package error;
// [RINF:RUST-SIGNAL]
message ReportError {
string errorMessage = 1;
}

View File

@ -1,21 +0,0 @@
syntax = "proto3";
package game_state;
enum States {
ProtonNotInstalled = 0;
DXVKNotInstalled = 1;
FontNotInstalled = 2;
DependecieNotInstalled = 3;
GameNotInstalled = 4;
GameNeedUpdate = 5;
GameNotPatched = 6;
GameInstalled = 7;
}
// [RINF:RUST-SIGNAL]
message GameState {
States state = 1;
}
// [RINF:DART-SIGNAL]
message AskGameState {}

View File

@ -1,18 +0,0 @@
syntax = "proto3";
package github;
// [RINF:DART-SIGNAL]
message AskProtonVersions {}
// [RINF:RUST-SIGNAL]
message ProtonVersions {
repeated string versions = 1;
}
// [RINF:DART-SIGNAL]
message AskDXVKVersions {}
// [RINF:RUST-SIGNAL]
message DXVKVersions {
repeated string versions = 1;
}

View File

@ -1,8 +0,0 @@
syntax = "proto3";
package dependencies;
// [RINF:DART-SIGNAL]
message StartDependenciesInstallation {}
// [RINF:RUST-SIGNAL]
message NotifyDependenciesSuccessfullyInstalled {}

View File

@ -1,19 +0,0 @@
syntax = "proto3";
package dxvk;
// [RINF:RUST-SIGNAL]
message DXVKDownloadProgress {
uint64 current = 1;
uint64 max = 2;
}
// [RINF:DART-SIGNAL]
message StartDXVKInstallation {
string protonVersion = 1;
};
// [RINF:RUST-SIGNAL]
message NotifyDXVKStartDecompressing {}
// [RINF:RUST-SIGNAL]
message NotifyDXVKSuccessfullyInstalled {}

View File

@ -1,14 +0,0 @@
syntax = "proto3";
package fonts;
// [RINF:RUST-SIGNAL]
message FontsInstallationProgress {
uint64 current = 1;
uint64 max = 2;
}
// [RINF:DART-SIGNAL]
message StartFontsInstallation {};
// [RINF:RUST-SIGNAL]
message NotifyFontsSuccessfullyInstalled {}

View File

@ -1,28 +0,0 @@
syntax = "proto3";
package game;
// [RINF:RUST-SIGNAL]
message GameInstallationProgress {
uint64 current = 1;
uint64 max = 2;
}
// [RINF:DART-SIGNAL]
message StartGameInstallation {
bool isUpdating = 1;
}
// [RINF:RUST-SIGNAL]
message NotifyGameStartDownloading {}
// [RINF:RUST-SIGNAL]
message NotifyGameStartPatching {}
// [RINF:RUST-SIGNAL]
message NotifyGameSuccessfullyInstalled {}
// [RINF:DART-SIGNAL]
message RunGame {}
// [RINF:RUST-SIGNAL]
message GameStopped {}

View File

@ -1,19 +0,0 @@
syntax = "proto3";
package proton;
// [RINF:RUST-SIGNAL]
message ProtonDownloadProgress {
uint64 current = 1;
uint64 max = 2;
}
// [RINF:DART-SIGNAL]
message StartProtonInstallation {
string protonVersion = 1;
};
// [RINF:RUST-SIGNAL]
message NotifyProtonStartDecompressing {}
// [RINF:RUST-SIGNAL]
message NotifyProtonSuccessfullyInstalled {}

View File

@ -1,28 +0,0 @@
[package]
# Do not change the name of this crate.
name = "hub"
version = "0.1.0"
edition = "2021"
[lib]
# `lib` is required for non-library targets,
# such as tests and benchmarks.
# `cdylib` is for Linux, Android, Windows, and web.
# `staticlib` is for iOS and macOS.
crate-type = ["lib", "cdylib", "staticlib"]
[dependencies]
rinf = "6.9.0"
prost = "0.12.3"
wasm-bindgen = "0.2.91"
tokio_with_wasm = "0.4.3"
babylonia-terminal-sdk = { path = "./../../../babylonia-terminal-sdk" }
downloader = { git = "https://github.com/ALEZ-DEV/downloader" } # version = "0.2.7",
once_cell = "1.19.0"
wincompatlib = { version = "0.7.4", features = [
"dxvk",
"wine-bundles",
"wine-proton",
"wine-fonts",
"winetricks",
] }

View File

@ -1,52 +0,0 @@
use babylonia_terminal_sdk::game_config::GameConfig;
use crate::messages::{
config::{
ConfigInput, ConfigOutput, GetLaunchOptionsInput, GetLaunchOptionsOutput,
SetLaunchOptionsInput,
},
error::ReportError,
};
pub async fn listen_config() {
let mut receiver = ConfigInput::get_dart_signal_receiver().unwrap();
while let Some(_) = receiver.recv().await {
let config = GameConfig::get_config().await;
ConfigOutput {
config_path: config.config_dir.to_str().unwrap().to_string(),
}
.send_signal_to_dart();
}
}
pub async fn listen_get_launch_options() {
let mut receiver = GetLaunchOptionsInput::get_dart_signal_receiver().unwrap();
while let Some(_) = receiver.recv().await {
let launch_options_result = GameConfig::get_launch_options().await;
if let Err(err) = launch_options_result {
ReportError {
error_message: format!("Failed to get launch options :\n{:?}", err),
}
.send_signal_to_dart();
continue;
}
GetLaunchOptionsOutput {
launch_options: launch_options_result.unwrap(),
}
.send_signal_to_dart();
}
}
pub async fn listen_set_launch_options() {
let mut receiver = SetLaunchOptionsInput::get_dart_signal_receiver().unwrap();
while let Some(dart_signal) = receiver.recv().await {
let result = GameConfig::set_launch_options(dart_signal.message.launch_options).await;
if let Err(err) = result {
ReportError {
error_message: format!("Failed to set launch options :\n{:?}", err),
}
.send_signal_to_dart();
}
}
}

View File

@ -1,37 +0,0 @@
use std::thread;
use babylonia_terminal_sdk::game_manager::GameManager;
use tokio_with_wasm::tokio;
use crate::{
messages::{
error::ReportError,
steps::dependencies::{
NotifyDependenciesSuccessfullyInstalled, StartDependenciesInstallation,
},
},
proton::get_proton,
};
pub async fn listen_dependecies_installation() {
let mut receiver = StartDependenciesInstallation::get_dart_signal_receiver().unwrap();
while let Some(_) = receiver.recv().await {
let proton = get_proton().await;
thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
match GameManager::install_dependencies(&proton).await {
Err(e) => ReportError {
error_message: format!("Failed to install dependencies : {}", e),
}
.send_signal_to_dart(),
Ok(_) => NotifyDependenciesSuccessfullyInstalled {}.send_signal_to_dart(),
}
});
});
}
}

View File

@ -1,117 +0,0 @@
use std::thread;
use babylonia_terminal_sdk::{
components::dxvk_component::{DXVK_DEV, DXVK_REPO},
game_config::GameConfig,
game_manager::GameManager,
utils::github_requester::{GithubRelease, GithubRequester},
};
use tokio_with_wasm::tokio;
use crate::{
github::GithubInfo,
messages::{
error::ReportError,
steps::dxvk::{
DxvkDownloadProgress, NotifyDxvkStartDecompressing, NotifyDxvkSuccessfullyInstalled,
StartDxvkInstallation,
},
},
proton::get_proton,
};
pub async fn listen_dxvk_installation() {
let mut receiver = StartDxvkInstallation::get_dart_signal_receiver().unwrap();
while let Some(info) = receiver.recv().await {
let releases: Result<Vec<GithubRelease>, _> =
GithubInfo::get_github_releases(DXVK_DEV, DXVK_REPO).await;
if releases.is_err() {
ReportError {
error_message: format!("When fetching DXVK versions : {}", releases.unwrap_err()),
}
.send_signal_to_dart();
continue;
}
let checked_releases = releases.unwrap();
let release_index = checked_releases
.iter()
.position(|v| v.tag_name == info.message.proton_version);
if release_index.is_none() {
ReportError {
error_message: "Failed to find DXVK version".to_string(),
}
.send_signal_to_dart();
continue;
}
let proton = get_proton().await;
thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
match GameManager::install_dxvk(
&proton,
GameConfig::get_config().await.config_dir,
release_index.unwrap(),
Some(DownloadReporter::create()),
)
.await
{
Err(e) => ReportError {
error_message: format!("Failed to install DXVK : {}", e),
}
.send_signal_to_dart(),
Ok(_) => NotifyDxvkSuccessfullyInstalled {}.send_signal_to_dart(),
}
});
});
}
}
struct DownloadReporterPrivate {
max_progress: Option<u64>,
}
struct DownloadReporter {
private: std::sync::Mutex<Option<DownloadReporterPrivate>>,
}
impl DownloadReporter {
pub fn create() -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
private: std::sync::Mutex::new(None),
})
}
}
impl downloader::progress::Reporter for DownloadReporter {
fn setup(&self, max_progress: Option<u64>, _: &str) {
let private = DownloadReporterPrivate { max_progress };
let mut guard = self.private.lock().unwrap();
*guard = Some(private);
}
fn progress(&self, current: u64) {
if let Some(p) = self.private.lock().unwrap().as_mut() {
DxvkDownloadProgress {
current,
max: p.max_progress.unwrap(),
}
.send_signal_to_dart();
}
}
fn set_message(&self, _: &str) {}
fn done(&self) {
NotifyDxvkStartDecompressing {}.send_signal_to_dart();
let mut guard = self.private.lock().unwrap();
*guard = None;
}
}

View File

@ -1,81 +0,0 @@
use std::thread;
use babylonia_terminal_sdk::game_manager::GameManager;
use tokio_with_wasm::tokio;
use crate::{
messages::{
error::ReportError,
steps::fonts::{
FontsInstallationProgress, NotifyFontsSuccessfullyInstalled, StartFontsInstallation,
},
},
proton::get_proton,
};
pub async fn listen_fonts_installation() {
let mut receiver = StartFontsInstallation::get_dart_signal_receiver().unwrap();
while let Some(_) = receiver.recv().await {
let proton = get_proton().await;
thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
match GameManager::install_font(&proton, Some(InstallationReporter::create()))
.await
{
Err(e) => ReportError {
error_message: format!("Failed to install fonts : {}", e),
}
.send_signal_to_dart(),
Ok(_) => NotifyFontsSuccessfullyInstalled {}.send_signal_to_dart(),
}
});
});
}
}
struct DownloadReporterPrivate {
max_progress: Option<u64>,
}
struct InstallationReporter {
private: std::sync::Mutex<Option<DownloadReporterPrivate>>,
}
impl InstallationReporter {
pub fn create() -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
private: std::sync::Mutex::new(None),
})
}
}
impl downloader::progress::Reporter for InstallationReporter {
fn setup(&self, max_progress: Option<u64>, _: &str) {
let private = DownloadReporterPrivate { max_progress };
let mut guard = self.private.lock().unwrap();
*guard = Some(private);
}
fn progress(&self, current: u64) {
if let Some(p) = self.private.lock().unwrap().as_mut() {
FontsInstallationProgress {
current,
max: p.max_progress.unwrap(),
}
.send_signal_to_dart();
}
}
fn set_message(&self, _: &str) {}
fn done(&self) {
let mut guard = self.private.lock().unwrap();
*guard = None;
}
}

View File

@ -1,160 +0,0 @@
use std::thread;
use babylonia_terminal_sdk::{game_config::GameConfig, game_manager::GameManager};
use rinf::debug_print;
use tokio_with_wasm::tokio;
use crate::{
messages::{
error::ReportError,
steps::game::{
GameInstallationProgress, GameStopped, NotifyGameStartPatching,
NotifyGameSuccessfullyInstalled, RunGame, StartGameInstallation,
},
},
proton::get_proton,
};
pub async fn listen_game_running() {
let mut receiver = RunGame::get_dart_signal_receiver().unwrap();
thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
while let Some(_) = receiver.recv().await {
let proton = get_proton().await;
let game_dir = GameConfig::get_game_dir().await;
if game_dir.is_none() {
ReportError {
error_message: "Failed to start game, the game directory was not found"
.to_string(),
}
.send_signal_to_dart();
GameStopped {}.send_signal_to_dart();
continue;
}
GameManager::start_game(&proton, game_dir.unwrap(), None, false).await;
GameStopped {}.send_signal_to_dart();
}
})
});
}
pub async fn listen_game_installation() {
let mut receiver = StartGameInstallation::get_dart_signal_receiver().unwrap();
while let Some(info) = receiver.recv().await {
thread::spawn(move || {
debug_print!("start downloading game...");
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
if GameConfig::get_game_dir().await.is_none() {
if let Err(e) =
GameConfig::set_game_dir(Some(GameConfig::get_config_directory().await))
.await
{
ReportError {
error_message: format!("Failed to set new path : {}", e),
}
.send_signal_to_dart();
}
}
if info.message.is_updating {
if let Err(e) = GameManager::update_game().await {
ReportError {
error_message: format!("Failed to start updating the game : {}", e),
}
.send_signal_to_dart();
}
}
let game_dir = GameConfig::get_game_dir().await;
if game_dir.is_none() {
ReportError {
error_message: "Failed to get the game directory".to_string(),
}
.send_signal_to_dart();
}
match GameManager::install_game(
game_dir.clone().unwrap(),
InstallationReporter::create(),
)
.await
{
Err(e) => ReportError {
error_message: format!("Failed to install game : {}", e),
}
.send_signal_to_dart(),
Ok(_) => {
NotifyGameStartPatching {}.send_signal_to_dart();
debug_print!("start patching game...");
match GameManager::patch_game(game_dir.unwrap()).await {
Err(e) => ReportError {
error_message: format!("Failed to install game : {}", e),
}
.send_signal_to_dart(),
Ok(_) => NotifyGameSuccessfullyInstalled {}.send_signal_to_dart(),
}
}
}
})
});
}
}
struct DownloadReporterPrivate {
max_progress: Option<u64>,
}
struct InstallationReporter {
private: std::sync::Mutex<Option<DownloadReporterPrivate>>,
}
impl InstallationReporter {
pub fn create() -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
private: std::sync::Mutex::new(None),
})
}
}
impl downloader::progress::Reporter for InstallationReporter {
fn setup(&self, max_progress: Option<u64>, _: &str) {
let private = DownloadReporterPrivate { max_progress };
let mut guard = self.private.lock().unwrap();
*guard = Some(private);
}
fn progress(&self, current: u64) {
if let Some(p) = self.private.lock().unwrap().as_mut() {
GameInstallationProgress {
current,
max: p.max_progress.unwrap(),
}
.send_signal_to_dart();
}
}
fn set_message(&self, _: &str) {}
fn done(&self) {
if let Some(p) = self.private.lock().unwrap().as_mut() {
GameInstallationProgress {
current: p.max_progress.unwrap(),
max: p.max_progress.unwrap(),
}
.send_signal_to_dart();
}
let mut guard = self.private.lock().unwrap();
*guard = None;
}
}

View File

@ -1,38 +0,0 @@
use babylonia_terminal_sdk::game_state::GameState;
use crate::messages::{
error::ReportError,
game_state::{AskGameState, GameState as GameStateMessage, States},
};
impl GameStateMessage {
fn from_sdk_state_to_msg_state(state: GameState) -> Self {
let game_state = match state {
GameState::ProtonNotInstalled => States::ProtonNotInstalled,
GameState::DXVKNotInstalled => States::DxvkNotInstalled,
GameState::FontNotInstalled => States::FontNotInstalled,
GameState::DependecieNotInstalled => States::DependecieNotInstalled,
GameState::GameNotInstalled => States::GameNotInstalled,
GameState::GameNeedUpdate => States::GameNeedUpdate,
GameState::GameNotPatched => States::GameNotPatched,
GameState::GameInstalled => States::GameInstalled,
};
GameStateMessage {
state: game_state.into(),
}
}
}
pub async fn listen_game_state() {
let mut receiver = AskGameState::get_dart_signal_receiver().unwrap();
while let Some(_) = receiver.recv().await {
let result_state = GameState::get_current_state().await;
match result_state {
Ok(state) => GameStateMessage::from_sdk_state_to_msg_state(state).send_signal_to_dart(),
Err(e) => ReportError {
error_message: format!("When updating the game state : {}", e),
}
.send_signal_to_dart(),
}
}
}

View File

@ -1,57 +0,0 @@
use babylonia_terminal_sdk::{
components::{
dxvk_component::{DXVK_DEV, DXVK_REPO},
proton_component::{PROTON_DEV, PROTON_REPO},
},
utils::github_requester::{GithubRelease, GithubRequester},
};
use crate::messages::{
error::ReportError,
github::{AskDxvkVersions, AskProtonVersions, DxvkVersions, ProtonVersions},
};
#[warn(dead_code)]
pub struct GithubInfo;
impl GithubRequester for GithubInfo {
fn set_github_release_index(&mut self, _: usize) {
todo!()
}
}
pub async fn listen_proton_version() {
let mut receiver = AskProtonVersions::get_dart_signal_receiver().unwrap();
while let Some(_) = receiver.recv().await {
let releases: Result<Vec<GithubRelease>, _> =
GithubInfo::get_github_releases(PROTON_DEV, PROTON_REPO).await;
match releases {
Ok(r) => ProtonVersions {
versions: r.iter().map(|v| v.tag_name.to_owned()).collect(),
}
.send_signal_to_dart(),
Err(e) => ReportError {
error_message: format!("When fetching proton versions : {}", e),
}
.send_signal_to_dart(),
}
}
}
pub async fn listen_dxvk_version() {
let mut receiver = AskDxvkVersions::get_dart_signal_receiver().unwrap();
while let Some(_) = receiver.recv().await {
let releases: Result<Vec<GithubRelease>, _> =
GithubInfo::get_github_releases(DXVK_DEV, DXVK_REPO).await;
match releases {
Ok(r) => DxvkVersions {
versions: r.iter().map(|v| v.tag_name.to_owned()).collect(),
}
.send_signal_to_dart(),
Err(e) => ReportError {
error_message: format!("When fetching dxvk versions : {}", e),
}
.send_signal_to_dart(),
}
}
}

View File

@ -1,35 +0,0 @@
use tokio_with_wasm::tokio;
mod config;
mod dependencies;
mod dxvk;
mod fonts;
mod game;
mod game_state;
mod github;
mod messages;
mod proton;
rinf::write_interface!();
async fn main() {
//config
tokio::spawn(game_state::listen_game_state());
tokio::spawn(config::listen_config());
tokio::spawn(config::listen_get_launch_options());
tokio::spawn(config::listen_set_launch_options());
//github
tokio::spawn(github::listen_proton_version());
tokio::spawn(github::listen_dxvk_version());
//installation
tokio::spawn(proton::listen_proton_installation());
tokio::spawn(dxvk::listen_dxvk_installation());
tokio::spawn(fonts::listen_fonts_installation());
tokio::spawn(dependencies::listen_dependecies_installation());
tokio::spawn(game::listen_game_installation());
//game
tokio::spawn(game::listen_game_running());
}

View File

@ -1,133 +0,0 @@
use std::thread;
use babylonia_terminal_sdk::{
components::proton_component::{ProtonComponent, PROTON_DEV, PROTON_REPO},
game_config::GameConfig,
game_manager::GameManager,
utils::github_requester::{GithubRelease, GithubRequester},
};
use tokio_with_wasm::tokio::{self, sync::OnceCell};
use wincompatlib::wine::bundle::proton::Proton;
use crate::{
github::GithubInfo,
messages::{
error::ReportError,
steps::proton::{
NotifyProtonStartDecompressing, NotifyProtonSuccessfullyInstalled,
ProtonDownloadProgress, StartProtonInstallation,
},
},
};
static PROTON: OnceCell<Proton> = OnceCell::const_new();
pub async fn get_proton() -> Proton {
PROTON
.get_or_init(|| async {
let proton_component = ProtonComponent::new(GameConfig::get_config().await.config_dir);
let proton = proton_component.init_proton();
if let Err(ref e) = proton {
ReportError {
error_message: format!("Failed to initialize proton : {}", e),
}
.send_signal_to_dart();
}
proton.unwrap()
})
.await
.clone()
}
pub async fn listen_proton_installation() {
let mut receiver = StartProtonInstallation::get_dart_signal_receiver().unwrap();
while let Some(info) = receiver.recv().await {
let releases: Result<Vec<GithubRelease>, _> =
GithubInfo::get_github_releases(PROTON_DEV, PROTON_REPO).await;
if releases.is_err() {
ReportError {
error_message: format!("When fetching proton versions : {}", releases.unwrap_err()),
}
.send_signal_to_dart();
continue;
}
let checked_releases = releases.unwrap();
let release_index = checked_releases
.iter()
.position(|v| v.tag_name == info.message.proton_version);
if release_index.is_none() {
ReportError {
error_message: "Failed to find Proton version".to_string(),
}
.send_signal_to_dart();
continue;
}
thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
match GameManager::install_wine(
GameConfig::get_config().await.config_dir,
release_index.unwrap(),
Some(DownloadReporter::create()),
)
.await
{
Err(e) => ReportError {
error_message: format!("Failed to install Proton : {}", e),
}
.send_signal_to_dart(),
Ok(_) => NotifyProtonSuccessfullyInstalled {}.send_signal_to_dart(),
}
});
});
}
}
struct DownloadReporterPrivate {
max_progress: Option<u64>,
}
struct DownloadReporter {
private: std::sync::Mutex<Option<DownloadReporterPrivate>>,
}
impl DownloadReporter {
pub fn create() -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
private: std::sync::Mutex::new(None),
})
}
}
impl downloader::progress::Reporter for DownloadReporter {
fn setup(&self, max_progress: Option<u64>, _: &str) {
let private = DownloadReporterPrivate { max_progress };
let mut guard = self.private.lock().unwrap();
*guard = Some(private);
}
fn progress(&self, current: u64) {
if let Some(p) = self.private.lock().unwrap().as_mut() {
ProtonDownloadProgress {
current,
max: p.max_progress.unwrap(),
}
.send_signal_to_dart();
}
}
fn set_message(&self, _: &str) {}
fn done(&self) {
NotifyProtonStartDecompressing {}.send_signal_to_dart();
let mut guard = self.private.lock().unwrap();
*guard = None;
}
}

Some files were not shown because too many files have changed in this diff Show More