Skip to content

Commit

Permalink
Work in progress move to async-channel
Browse files Browse the repository at this point in the history
  • Loading branch information
aknarts committed Apr 20, 2024
1 parent c62a162 commit 4592661
Show file tree
Hide file tree
Showing 23 changed files with 411 additions and 324 deletions.
4 changes: 3 additions & 1 deletion .idea/runConfigurations/Run.xml

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ serde_json = "1"
sha-1 = "0.10"
threadpool = "1.8"
tokio = { version = "1", features = ["rt-multi-thread"] }
version-compare = "0.1"
version-compare = "0.2"
zip = "0.6"

[target.'cfg(target_os = "windows")'.build-dependencies]
Expand Down
9 changes: 0 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,6 @@ lazy_static::lazy_static! {
static ref RUNNING: Arc<std::sync::RwLock<bool>> = Arc::new(std::sync::RwLock::new(true));
}

fn runtime() -> &'static tokio::runtime::Runtime {
static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("Setting up tokio runtime needs to succeed.")
})
}
fn main() {
env_logger::Builder::from_env(Env::default().default_filter_or("epic_asset_manager:info"))
.format(|buf, record| {
Expand Down
2 changes: 2 additions & 0 deletions src/models/engine_data.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use glib::ObjectExt;
use gtk4::{glib, prelude::*, subclass::prelude::*};
use log::debug;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::io::Read;
Expand Down Expand Up @@ -261,6 +262,7 @@ impl EngineData {
let engine = self.clone();
glib::spawn_future_local(async move {
while let Ok(response) = receiver.recv().await {
debug!("engine_data: {:?}", &response);
engine.update(response);
}
});
Expand Down
14 changes: 8 additions & 6 deletions src/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub mod project_data;
use crate::config::APP_ID;
use egs_api::EpicGames;
use gtk4::gio;
use gtk4::glib::{MainContext, Priority, Receiver, Sender, UserDirectory};
use gtk4::glib::UserDirectory;
use gtk4::prelude::*;
use log::{debug, error, info, warn};
use std::cell::RefCell;
Expand All @@ -23,8 +23,8 @@ pub struct Model {
pub epic_games: RefCell<EpicGames>,
#[cfg(target_os = "linux")]
pub secret_service: Option<SecretService<'static>>,
pub sender: Sender<crate::ui::messages::Msg>,
pub receiver: RefCell<Option<Receiver<crate::ui::messages::Msg>>>,
pub sender: async_channel::Sender<crate::ui::messages::Msg>,
pub receiver: RefCell<Option<async_channel::Receiver<crate::ui::messages::Msg>>>,
pub settings: gio::Settings,
#[cfg(target_os = "linux")]
pub dclient: RefCell<Option<ghregistry::Client>>,
Expand All @@ -38,7 +38,7 @@ impl Default for Model {

impl Model {
pub fn new() -> Self {
let (sender, receiver) = MainContext::channel(Priority::default());
let (sender, receiver) = async_channel::bounded(1);
let mut obj = Self {
epic_games: RefCell::new(EpicGames::new()),
#[cfg(target_os = "linux")]
Expand Down Expand Up @@ -145,7 +145,9 @@ impl Model {
Ok(auth) => {
if auth {
sender
.send(crate::ui::messages::Msg::DockerClient(docker_client))
.send_blocking(crate::ui::messages::Msg::DockerClient(
docker_client,
))
.unwrap();
info!("Docker Authenticated");
}
Expand All @@ -157,7 +159,7 @@ impl Model {
Err(e) => {
error!("Failed authentication {:?}", e);
sender
.send(crate::ui::messages::Msg::GithubAuthFailed)
.send_blocking(crate::ui::messages::Msg::GithubAuthFailed)
.unwrap();
}
};
Expand Down
1 change: 1 addition & 0 deletions src/models/plugin_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ impl PluginData {
let project = self.clone();
glib::spawn_future_local(async move {
while let Ok(response) = receiver.recv().await {
debug!("plugin_data: {:?}", &response);
project.update(response);
}
});
Expand Down
67 changes: 33 additions & 34 deletions src/models/project_data.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use glib::ObjectExt;
use gtk4::gdk::Texture;
use gtk4::glib::clone;
use gtk4::{self, glib, subclass::prelude::*};
use log::{error, info};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Read;
use std::path::PathBuf;
use std::thread;

use glib::ObjectExt;
use gtk4::gdk::Texture;
use gtk4::{self, glib, subclass::prelude::*};
use log::{debug, error, info};
use serde::{Deserialize, Serialize};

#[derive(Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Uproject {
Expand All @@ -34,16 +34,18 @@ pub struct Uproject {

#[derive(Debug, Clone)]
pub enum Msg {
Thumbnail(gtk4::gdk::Texture),
Thumbnail(Texture),
}

// Implementation sub-module of the GObject
mod imp {
use super::*;
use std::cell::RefCell;

use glib::ToValue;
use gtk4::gdk::Texture;
use gtk4::glib::{ParamSpec, ParamSpecObject, ParamSpecString, Priority};
use std::cell::RefCell;
use gtk4::glib::{ParamSpec, ParamSpecObject, ParamSpecString};

use super::*;

// The actual data structure that stores our values. This is not accessible
// directly from the outside.
Expand All @@ -52,10 +54,10 @@ mod imp {
guid: RefCell<Option<String>>,
path: RefCell<Option<String>>,
name: RefCell<Option<String>>,
pub uproject: RefCell<Option<super::Uproject>>,
pub uproject: RefCell<Option<Uproject>>,
thumbnail: RefCell<Option<Texture>>,
pub sender: gtk4::glib::Sender<super::Msg>,
pub receiver: RefCell<Option<gtk4::glib::Receiver<super::Msg>>>,
pub sender: async_channel::Sender<Msg>,
pub receiver: RefCell<Option<async_channel::Receiver<Msg>>>,
}

// Basic declaration of our type for the GObject type system
Expand All @@ -66,7 +68,7 @@ mod imp {
type ParentType = glib::Object;

fn new() -> Self {
let (sender, receiver) = gtk4::glib::MainContext::channel(Priority::default());
let (sender, receiver) = async_channel::bounded(1);
Self {
guid: RefCell::new(None),
path: RefCell::new(None),
Expand All @@ -91,10 +93,10 @@ mod imp {
self.obj().setup_messaging();
}

fn signals() -> &'static [gtk4::glib::subclass::Signal] {
static SIGNALS: once_cell::sync::Lazy<Vec<gtk4::glib::subclass::Signal>> =
fn signals() -> &'static [glib::subclass::Signal] {
static SIGNALS: once_cell::sync::Lazy<Vec<glib::subclass::Signal>> =
once_cell::sync::Lazy::new(|| {
vec![gtk4::glib::subclass::Signal::builder("finished")
vec![glib::subclass::Signal::builder("finished")
.flags(glib::SignalFlags::ACTION)
.build()]
});
Expand Down Expand Up @@ -201,13 +203,10 @@ impl ProjectData {
if let Ok(mut file) = std::fs::File::open(p) {
let mut contents = String::new();
if file.read_to_string(&mut contents).is_ok() {
return match serde_json::from_str::<Uproject>(&contents) {
Ok(uproject) => uproject,
Err(e) => {
error!("Unable to parse uproject {path}: {e}");
Uproject::default()
}
};
return serde_json::from_str::<Uproject>(&contents).unwrap_or_else(|e| {
error!("Unable to parse uproject {path}: {e}");
Uproject::default()
});
}
}
Uproject::default()
Expand All @@ -221,13 +220,13 @@ impl ProjectData {
pub fn setup_messaging(&self) {
let self_ = self.imp();
let receiver = self_.receiver.borrow_mut().take().unwrap();
receiver.attach(
None,
clone!(@weak self as project => @default-panic, move |msg| {
project.update(msg);
glib::ControlFlow::Continue
}),
);
let project = self.clone();
glib::spawn_future_local(async move {
while let Ok(response) = receiver.recv().await {
debug!("project_data: {:?}", &response);
project.update(response);
}
});
}

pub fn update(&self, msg: Msg) {
Expand All @@ -239,16 +238,16 @@ impl ProjectData {
self.emit_by_name::<()>("finished", &[]);
}

pub fn load_thumbnail(path: &str, sender: &gtk4::glib::Sender<Msg>) {
pub fn load_thumbnail(path: &str, sender: &async_channel::Sender<Msg>) {
let mut pathbuf = match PathBuf::from(&path).parent() {
None => return,
Some(p) => p.to_path_buf(),
};
pathbuf.push("Saved");
pathbuf.push("AutoScreenshot.png");
if pathbuf.exists() {
match gtk4::gdk::Texture::from_file(&gtk4::gio::File::for_path(pathbuf.as_path())) {
Ok(t) => sender.send(Msg::Thumbnail(t)).unwrap(),
match Texture::from_file(&gtk4::gio::File::for_path(pathbuf.as_path())) {
Ok(t) => sender.send_blocking(Msg::Thumbnail(t)).unwrap(),
Err(e) => {
error!("Unable to load file to texture: {}", e);
}
Expand Down
12 changes: 7 additions & 5 deletions src/ui/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ impl EpicAssetManagerWindow {
.block_on(eg.auth_code(None, Some(s)))
{
sender
.send(crate::ui::messages::Msg::LoginOk(eg.user_details()))
.send_blocking(crate::ui::messages::Msg::LoginOk(eg.user_details()))
.unwrap();
} else {
sender
.send(crate::ui::messages::Msg::LoginFailed(
.send_blocking(crate::ui::messages::Msg::LoginFailed(
"Unable to authenticate with auth code".to_string(),
))
.unwrap();
Expand Down Expand Up @@ -97,11 +97,11 @@ impl EpicAssetManagerWindow {
.block_on(eg.login())
{
sender
.send(crate::ui::messages::Msg::LoginOk(eg.user_details()))
.send_blocking(crate::ui::messages::Msg::LoginOk(eg.user_details()))
.unwrap();
} else {
sender
.send(crate::ui::messages::Msg::LoginFailed(
.send_blocking(crate::ui::messages::Msg::LoginFailed(
"Relogin request failed".to_string(),
))
.unwrap();
Expand All @@ -125,7 +125,9 @@ impl EpicAssetManagerWindow {
.build()
.unwrap()
.block_on(eg.logout());
sender.send(crate::ui::messages::Msg::Logout).unwrap();
sender
.send_blocking(crate::ui::messages::Msg::Logout)
.unwrap();
});
}
}
Loading

0 comments on commit 4592661

Please sign in to comment.